max_stars_repo_path stringlengths 3 269 | max_stars_repo_name stringlengths 4 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.05M | score float64 0.23 5.13 | int_score int64 0 5 |
|---|---|---|---|---|---|---|
inn/inn_hotels/report/room_discrepancy/room_discrepancy.py | vinhnguyent090/front-desk | 4 | 12797251 | <gh_stars>1-10
# Copyright (c) 2013, Core Initiative and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from datetime import datetime
def execute(filters=None):
columns = [
{
'fieldname': 'date',
'label': 'Date',
... | 2.359375 | 2 |
examples/recipes/prax_shake_head.py | pi-top/pi-top-Python-SDK | 28 | 12797252 | from time import sleep
from pitop import TiltRollHeadController
# Create a head controller object
head = TiltRollHeadController()
# Initialize the servo angles
head.roll.target_angle = 0
head.tilt.target_angle = 50
sleep(1)
# Nod 6 times at max speed 5 degrees either side of current angle. Blocks program execution... | 3.296875 | 3 |
python/unit_test/get_data_test.py | aaronlam88/cmpe295 | 5 | 12797253 | import sys
sys.path.insert(0, '../models')
from get_data import GetData
# from python.ultilities.get_data import GetData
import unittest
import csv
class TestGetData(unittest.TestCase):
def test_getAllFeatures1(self):
getData = GetData()
features = getData.getAllFeatures()
self.assertIsNotN... | 2.75 | 3 |
tests/test_cli.py | wizardsoftheweb/gitflow-easyrelease | 0 | 12797254 | # pylint: disable=missing-docstring
from __future__ import print_function
from mock import patch
from gitflow_easyrelease import cli
@patch('gitflow_easyrelease.cli_file.ColorOutput')
@patch('gitflow_easyrelease.cli_file.Subcommand')
@patch('gitflow_easyrelease.cli_file.Application')
def test_execution(mock_app, ... | 2.109375 | 2 |
lib/command.py | GrimHacker/hashcatter | 2 | 12797255 | <reponame>GrimHacker/hashcatter
'''
.1111... | Title: command
.10000000000011. .. | Author: <NAME>
.00 000... | Email: <EMAIL>
1 01.. | Description:
.. | executes a command as a subprocess
.. |
GrimHacker .. ... | 2.5 | 2 |
kontaktmap.py | muellermartin/kontaktmap | 0 | 12797256 | import os
from flask import Flask, render_template, request, json
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/save', methods=['POST'])
def save():
with open('data.json', 'w+') as f:
f.write(json.dumps(request.get_json()))
return ''
@app.route('/load')
... | 2.796875 | 3 |
relaax/common/metrics.py | j0k/relaax | 4 | 12797257 | from __future__ import print_function
class Metrics(object):
def scalar(self, name, y, x=None):
raise NotImplementedError
| 1.90625 | 2 |
server/insctructions/aggregator.py | Ashkan-Agc/web-time-tracker | 5 | 12797258 | <reponame>Ashkan-Agc/web-time-tracker<gh_stars>1-10
from django.db.models import Sum, Avg, Max, Min
from TimeTracker.models import Sites
from datetime import datetime
from .dataFunc import DataInstruct
class Aggregators():
def __init__(self, user_id):
self.now = datetime.now()
self.date = self.no... | 2.34375 | 2 |
qvi/misc/plot.py | amirdib/quantized-variational-inference | 0 | 12797259 | <gh_stars>0
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib import colors
from scipy.spatial import Voronoi, voronoi_plot_2d
from scipy.signal import savgol_filter
from qvi.core.experiments import compute_traces_from_multiple_trainning
class _TFCol... | 2.296875 | 2 |
keychain/keychain_urls.py | osgee/keychainserver | 2 | 12797260 | <reponame>osgee/keychainserver
from django.conf.urls import url, include
from keychain import keychain_client_urls
from keychain import keychain_web_urls
from keychain.views import appview
app_name = 'keychain'
urlpatterns = [
url(r'^web/', include(keychain_web_urls)),
url(r'^client/', include(keychain_client... | 1.960938 | 2 |
tools/fake_server.py | uActor/uActor | 1 | 12797261 | <filename>tools/fake_server.py
import socket
import argparse
import struct
import msgpack
parser = argparse.ArgumentParser()
parser.add_argument("host")
parser.add_argument("port", type=int)
parser.add_argument("node_id")
arguments = parser.parse_args()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
... | 2.328125 | 2 |
tests/schema/test_visitor.py | mabrains/ALIGN-public | 119 | 12797262 | import pytest
from align.schema.types import BaseModel, Optional, List, Dict
from align.schema.visitor import Visitor, Transformer, cache
@pytest.fixture
def dummy():
class DummyModel(BaseModel):
arg1: str
arg2: Optional[str]
arg3: List[str]
arg4: List[Optional[str]]
arg5: ... | 2.234375 | 2 |
code/02_modeling/02_model_creation/DataReader.py | suryappal/MachineLearningSamples-BiomedicalEntityExtraction | 40 | 12797263 | <gh_stars>10-100
from keras.preprocessing import sequence
import numpy as np
import nltk
from nltk.tokenize import sent_tokenize
import _pickle as cPickle
class DataReader:
def __init__ (self, input_resources_pickle_file =None):
# Some constants
self.num_classes = 0
self.num_e... | 2.65625 | 3 |
elasticlog/customlogger.py | gustavohenrique/elasticlog | 1 | 12797264 | # coding: utf-8
import sys
import logging
import settings
logFormatter = logging.Formatter('%(asctime)s [%(levelname)-5.5s] %(message)s')
logger = logging.getLogger()
fileHandler = logging.FileHandler('{0}'.format(settings.LOG_FILE_PATH))
fileHandler.setFormatter(logFormatter)
logger.addHandler(fileHandler)
conso... | 2.328125 | 2 |
phr/ciudadano/migrations/0006_auto_20170131_1114.py | richardqa/django-ex | 0 | 12797265 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-01-31 11:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ciudadano', '0005_auto_20170127_1841'),
]
operations = [
migrations.RemoveFi... | 1.484375 | 1 |
src/train/kuka_reach/with_image/train_with_rllib.py | borninfreedom/deep-rl-with-robots | 0 | 12797266 | <filename>src/train/kuka_reach/with_image/train_with_rllib.py
import time
import ray
import ray.rllib.agents.ppo as ppo
from ray.tune.logger import pretty_print
from env import CustomSkipFrame, KukaCamReachEnv
from ray import tune
from ray.tune import grid_search
from ray.rllib.env.env_context import EnvContext
from ra... | 1.992188 | 2 |
tests/test_graphs.py | jodahoney/pyinterview | 2 | 12797267 | <reponame>jodahoney/pyinterview
import pytest
from collections import deque
from pyinterview.graphs import (
undirected_adj_list,
directed_adj_list,
inbound_degrees,
find_sources,
)
@pytest.mark.parametrize(
("edges", "expected"),
[
([("A", "B"), ("A", "C")], {"A": ["B", "C"], "B": ["A... | 2.515625 | 3 |
web/premises/views.py | beratdogan/arguman.org | 0 | 12797268 | # -*- coding:utf-8 -*-
import json
from datetime import timedelta
from markdown2 import markdown
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.utils import timezone
from django.db.models import Max
from django.utils.timezone import now
from django.http import HttpRespons... | 1.929688 | 2 |
tensorbank/tf/points.py | pshved/tensorbank | 1 | 12797269 | <reponame>pshved/tensorbank
"""Point operations
===================
Batch operations on points in D-dimensional Eucledian space R^D.
"""
import tensorflow as tf
def pairwise_l2_distance(a, b, sqrt=True):
"""Compute pairwise L2 distance between all points in A and B.
L2 norm is ``sqrt(sum(|x_i - y_i| ^ 2))`... | 3.015625 | 3 |
odd_collector/adapters/kafka/mappers/parser/types.py | opendatadiscovery/odd-collector | 0 | 12797270 | from typing import Dict, Any
RawSchema = Dict[str, Any]
Field = Dict[str, Any]
| 2.03125 | 2 |
backend_sqlalchemy/backend_app/common/contents.py | jiz148/medical_app | 0 | 12797271 | FORGET_MY_PASSWORD_SUBJECT = """Password Change Confirmation"""
FORGET_MY_PASSWORD_CONTENT = """hello {user},\n
Please click the following link to change your password:\n
http://jinchispace.com:5001/newpass?token={token}\n
T... | 1.601563 | 2 |
blaze/command/replay.py | henry1jin/alohamora | 5 | 12797272 | """ Implements the commands for viewing and manipulating the training manifest """
import json
import time
import os
from blaze.action import Policy
from blaze.logger import logger as log
from blaze.mahimahi.server import start_server
from . import command
@command.argument("replay_dir", help="The directory contain... | 2.421875 | 2 |
examples/example_publisher_subscriber/consumer.py | vladcalin/pymicroservice | 2 | 12797273 | <gh_stars>1-10
import gemstone
from gemstone.event.transport import RabbitMqEventTransport
class ConsumerService(gemstone.MicroService):
name = "consumer"
port = 8000
event_transports = [
RabbitMqEventTransport("192.168.1.71", 5672, username="admin", password="<PASSWORD>")
]
@gemstone.e... | 2.40625 | 2 |
amocrm_asterisk_ng/crm/amocrm/kernel/calls/call_records/file_converters/impl/PydubFileConverter.py | iqtek/amocrn_asterisk_ng | 0 | 12797274 | import os
import aiofiles
from pydub import AudioSegment
from amocrm_asterisk_ng.domain import File
from amocrm_asterisk_ng.domain import Filetype
from ..core import IFileConverter
from ...CallRecordsConfig import CallRecordsConfig
__all__ = [
"PydubFileConverter",
]
class PydubFileConverter(IFileConverter):... | 2.484375 | 2 |
tpapi/client.py | ash30/tpapi | 0 | 12797275 | <reponame>ash30/tpapi<filename>tpapi/client.py
import os
import json
import itertools
import urllib
import requests
import entities
import collections
"""
Future Todo:
- Pass entity objects into edits
- TP client caching
"""
# Utils #
def is_sequence(elem):
"Returns true for iterables other than strings"
if... | 2.5 | 2 |
ex-mundo2/ex065.py | PedroPegado/ex-cursoemvideo | 0 | 12797276 | parar = False
soma = 0
cont = 0
while parar == False:
num = int(input('''\033[1;36mDigite um numero inteiro:\033[m '''))
soma += num
cont += 1
print('''Deseja continuar?
[ 1 ] SIM
[ 2 ] NÃO''')
opcao = int(input('Escolha sua opção: '))
if opcao == 2:
parar = True
e... | 3.734375 | 4 |
xavier/builder/model.py | fabriciotorquato/pyxavier | 5 | 12797277 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import time
import numpy as np
import torch
import torch.optim as optim
from sklearn.model_selection import train_test_split
from torch import nn
import xavier.constants.config as config
from xavier.constants.type import Type
from xavier.core.dataLoader import ... | 2.640625 | 3 |
test/schema/stream_gain_strategy_test.py | hq9000/py-headless-daw | 22 | 12797278 | import unittest
from typing import List
import numpy as np
from py_headless_daw.processing.stream.stream_gain import StreamGain
from py_headless_daw.schema.dto.time_interval import TimeInterval
from py_headless_daw.schema.events.event import Event
from py_headless_daw.schema.events.parameter_value_event import Parame... | 2.296875 | 2 |
home/views.py | sa-y-an/Qriosity2.0 | 0 | 12797279 | <reponame>sa-y-an/Qriosity2.0<gh_stars>0
from django.shortcuts import render
from django.contrib.auth.decorators import user_passes_test
# Create your views here.
def not_logged_in(user):
return not user.is_authenticated
def base(request):
return render(request, 'home/base.html')
def home(request):
r... | 1.992188 | 2 |
backend/src/models/Warehouse.py | ahmedsalahacc/Inventory-Management-System | 0 | 12797280 | <filename>backend/src/models/Warehouse.py
from models import BaseModel, gen_id
class WarehouseModel(BaseModel):
'''
ORM for Warehouse table with the following structure
warehouse(
id CHARACTER(10) NOT NULL PRIMARY KEY,
name TEXT NOT NULL,
location TEXT NOT NULL
);
'''
... | 3.0625 | 3 |
ansibleroler/utils/__init__.py | xoxys/ansible-role | 3 | 12797281 | import six
import os
import yaml
import logging
import logging.config
from appdirs import AppDirs
from pkg_resources import resource_filename
def setup_logging(log_level):
log_config_file = os.path.join(resource_filename('ansibleroler', 'static'), 'config', 'logging.yml')
level = logging.getLevelName(log_leve... | 2.171875 | 2 |
kora/install/rust.py | wannaphong/kora | 91 | 12797282 | import os
os.system('apt install rustc')
os.environ['PATH'] += ':/root/.cargo/bin'
os.environ['USER'] = 'user'
| 1.367188 | 1 |
viusitemapparser/sitemap_file.py | VIU-one/VIU-Sitemap-Parser | 1 | 12797283 | <gh_stars>1-10
class SitemapFile:
sitemap_file_name = None
sitemap_contents = None
sitemap_headers = None
sitemap_source_type = None # remote or local
sitemap_file_error = None
sitemap_received = False
sitemap_lxml = None
sitemap_plain_text = None
sitemap_type = None ... | 2.3125 | 2 |
habiticaapi/habitica_object.py | nasfarley88/pyhabitica | 0 | 12797284 | # User provided config file
import config
import requests
import attrdict
import logging
def attrdict_or_list(thing):
if type(thing) == dict:
return attrdict.AttrMap(thing)
elif type(thing) == list:
return thing
else:
assert False, "DON'T PANIC. Something that wasn't a list or dic... | 2.765625 | 3 |
udemy/python-video-workbook/my_progress/033.py | djrgit/coursework | 0 | 12797285 | # Exercise 33 - Local Variables
c = 1
def foo():
c = 2
return c
c = 3
print(foo()) | 2.859375 | 3 |
bom_tools/part_finder.py | snhobbs/BOMTools | 0 | 12797286 | """
part_finder.py
Look through two files and search for an internal part number that looks like `match_pattern`
"""
#!/usr/bin/env python3
import sys, regex, click
#first arg is a digikey csv cart
#second is a newline deliminated list of eoi partnumbers
match_pattern = "\w{3}-\w{4}-\w{2}"
@click.argument("--first",... | 3.3125 | 3 |
src/10fastfingers-auto-type.py | gordonnguyen/10fastfingers-auto-type | 0 | 12797287 | <reponame>gordonnguyen/10fastfingers-auto-type
import os,sys,inspect
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
# Init working folder
currentdir = os.path... | 2.6875 | 3 |
xps_convert/read/xmp_parser.py | InternetUnexplorer/XPSConvert | 0 | 12797288 | import re
from typing import Iterator
from xps_convert.read.errors import ParseError
from xps_convert.read.xmp import Xmp
FIELD_RE = re.compile(r"([\w\s]+):\s(.*)")
def parse_xmp(filename: str, lines: Iterator[str]) -> Xmp:
xmp = Xmp()
# First line is always a comment, skip it
next(lines)
# Match ea... | 2.9375 | 3 |
initializer.py | obs145628/py-neural-nets | 0 | 12797289 | <reponame>obs145628/py-neural-nets
import numpy as np
'''
Initializer
params(shape):
Create initalized tensor
@param shape tuple of dimensions of the expected tensor
@return initialized tensor
'''
class GaussInitializer:
def params(self, shape):
return np.random.sta... | 3.0625 | 3 |
text_extensions_for_pandas/array/tensor.py | lresende/text-extensions-for-pandas | 0 | 12797290 | <filename>text_extensions_for_pandas/array/tensor.py
#
# Copyright (c) 2020 IBM Corp.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Un... | 2.421875 | 2 |
subprojects/laser/data/setup.py | sirca/bdkd_datastore | 3 | 12797291 | # Copyright 2015 Nicta
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... | 1.515625 | 2 |
fact-bounty-flask/api/models/story.py | ganeshpatro321/fact-Bounty | 0 | 12797292 | from datetime import datetime
from ... import db
class Story(db.Model):
""" This model holds information about Story """
__tablename__ = 'story'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.Text, nullable=False)
content = db.Column(db.Text, nullable=False)
featured_img_u... | 3.359375 | 3 |
cpdb/officers/serializers/response_mobile_serializers.py | invinst/CPDBv2_backend | 25 | 12797293 | <filename>cpdb/officers/serializers/response_mobile_serializers.py
from rest_framework import serializers
from shared.serializer import NoNullSerializer, OfficerPercentileSerializer, OfficerYearlyPercentileSerializer
class PoliceUnitMobileSerializer(NoNullSerializer):
unit_id = serializers.IntegerField(source='i... | 2 | 2 |
osmcsclassify/Config.py | jremillard/osm-changeset-classification | 16 | 12797294 | <filename>osmcsclassify/Config.py
historyDbTempDirName = "/home/jason/nn/osm-changeset-classification/osm-planet"
historyDbFileName = "osm-planet/history.sqlite"
#historyPBF = "../osm-data/vermont.osh.pbf"
#historyPBF = 'osm-planet/history-180319.osm.pbf'
historyPBF = "/media/jason/E46AC1AC6AC17BB4/Remillard/maps/os... | 0.984375 | 1 |
hilearn/mcmc/mcmc_sampler.py | houruiyan/hilearn | 4 | 12797295 | <reponame>houruiyan/hilearn<gh_stars>1-10
import numpy as np
def Geweke_Z(X, first=0.1, last=0.5):
N = X.shape[0]
A = X[:int(first*N)]
B = X[int(last*N):]
if np.sqrt(np.var(A) + np.var(B)) == 0:
Z = None
else:
Z = abs(A.mean() - B.mean()) / np.sqrt(np.var(A) + np.var(B))
return ... | 2.515625 | 3 |
model/user_in_group.py | Belyanova/Python_-training | 0 | 12797296 | class UserGroup:
def __init__(self, id=None, group_id=None,):
self.group_id = group_id
self.id = id | 2.078125 | 2 |
landing/migrations/0001_initial.py | XeryusTC/projman | 0 | 12797297 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
def setup_site(apps, schema_editor):
"""Populate the sites model"""
Site = apps.get_model('sites', 'Site')
Site.objects.all().delete()
# Register SITE_ID = 1
t... | 2.09375 | 2 |
gmaps/process/gmaps_process.py | cfespinoza/google_maps_exractor | 0 | 12797298 | import multiprocessing
class GmapsProcess(multiprocessing.Process):
# make 'daemon' attribute always return False
def _get_daemon(self):
return False
def _set_daemon(self, value):
pass
daemon = property(_get_daemon, _set_daemon)
# We sub-class multiprocessing.pool.Pool instead of m... | 2.71875 | 3 |
listful/types.py | d1618033/listful | 2 | 12797299 | <gh_stars>1-10
import typing
ITEM = typing.TypeVar('ITEM')
FIELD = str
VALUE = typing.TypeVar('VALUE')
GETTER = typing.Callable[[ITEM, FIELD], VALUE]
| 2.359375 | 2 |
amicropyserver.py | IhorNehrutsa/micropyserver | 0 | 12797300 | <gh_stars>0
"""
MicroPyServer is a simple HTTP server for MicroPython projects.
@see https://github.com/troublegum/micropyserver
The MIT License
Copyright (c) 2019 troublegum. https://github.com/troublegum/micropyserver
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software an... | 2.25 | 2 |
ole.py | nursultanramazanov/123 | 2 | 12797301 | <reponame>nursultanramazanov/123
# -*- coding:utf-8 -*-
# Author: <NAME>(<EMAIL>)
import os
import sys
import struct
import types
import kernel
import kavutil
# -------------------------------------------------------------------------
# 메시지 출력 함수
# -------------------------------------------------------------------... | 1.984375 | 2 |
segmentation.py | chngchinboon/necklysis | 0 | 12797302 | import matplotlib.pyplot as plt
# import pydicom
import os
from pydicom.filereader import dcmread, read_dicomdir
from glob import glob
import cv2
import numpy as np
cv2.destroyAllWindows()
# window prop
screensize = ((-1440,0),(0,900))
screenwidth = screensize[0][1]-screensize[0][0]
screenheight = screensize[1][1]-scr... | 2.53125 | 3 |
week_10/extra_problems/server.py | vlasenckov/MIPT_py_3_term | 5 | 12797303 | import socket
import threading
import multiprocessing
import os
def worker(sock):
while True:
conn, addr = sock.accept()
print("PID:", os.getpid())
thread = threading.Thread(target=process_request, args=(conn, addr))
thread.start()
def process_request(conn, addr):
print("add... | 3.046875 | 3 |
plot_bathymetry.py | sustain-lab/multibeam-em712 | 0 | 12797304 | import glob
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import xarray as xr
from mpl_toolkits.basemap import Basemap
import gc
import matplotlib
matplotlib.rc('font', size=12)
data_path = 'processed_netcdf'
multibeam_files = glob.glob(data_path + '/*.nc')
multibeam_files.sort()
lon... | 2.21875 | 2 |
ego/decomposition/relabel.py | fabriziocosta/EGO | 0 | 12797305 | <gh_stars>0
#!/usr/bin/env python
"""Provides scikit interface."""
from ego.component import GraphComponent
from collections import Counter
def decompose_relabel_node_size(graph_component):
new_subgraphs_list = []
new_signatures_list = []
for subgraph, signature in zip(graph_component.subgraphs, graph_co... | 2.203125 | 2 |
source/Mlos.Python/mlos/OptimizerEvaluationTools/SyntheticFunctions/sample_functions.py | GindaChen/MLOS | 81 | 12797306 | #
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
#
import math
import numpy as np
def quadratic(**kwargs) -> float:
return sum(x_i ** 2 for _, x_i in kwargs.items())
def ackley(x_1=None, x_2=None, a=20, b=0.2, c=2*math.pi):
d = 2
return -a * np.exp(-b * np.sqrt((x_1... | 2.96875 | 3 |
main.py | adezoguns/flask_server_ml_display | 0 | 12797307 | from flask import Flask, url_for, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from werkzeug.utils import secure_filename
from werkzeug.serving import run_simple
from id_class_locator import id_class_detector
import os
import time
from cv2 import cv2
app=Flas... | 2.28125 | 2 |
zapr/utils/reader.py | zapr-oss/zapr-athena-client | 1 | 12797308 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | 1.828125 | 2 |
xcount/events/query.py | Havenir/xcount | 0 | 12797309 | import frappe
import datetime
@frappe.whitelist()
def get_batch_nos(doctype, txt, searchfield, start, page_len, filters):
return frappe.db.sql("""select batch_id, expiry_date
from `tabBatch`
where
item = {item_code} and disabled = 0 and (expiry_date is null or expiry_date > '{cur_date}')"""
.format(item_code... | 2.1875 | 2 |
djangobmf/contrib/accounting/bmf_module.py | caputomarcos/django-bmf | 0 | 12797310 | #!/usr/bin/python
# ex:set fileencoding=utf-8:
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from djangobmf.dashboards import Accounting
from djangobmf.sites import Module
from djangobmf.sites import ViewMixin
from djangobmf.sites import regi... | 1.984375 | 2 |
api/log.py | StonebreakerDesigns/project-boilerplate | 0 | 12797311 | # coding: utf-8
'''Centralized logger factory.'''
import logging
from .config import config
# The level options supported in configuration.
LEVEL_OPTIONS = list((
'notset', 'debug', 'info', 'warning', 'error', 'critical'
))
def _setup_logger_supply():
'''Create and return a logger generator.'''
configured_level =... | 2.515625 | 3 |
tests/test_utilities.py | mhostetter/quaternionic | 40 | 12797312 | import sys
import numpy as np
import quaternionic
import pytest
def test_self_return():
def f1(a, b, c):
d = np.asarray(a).copy()
assert isinstance(a, np.ndarray) and isinstance(a, quaternionic.array)
assert isinstance(b, np.ndarray) and isinstance(b, quaternionic.array)
assert isi... | 2.484375 | 2 |
docs/02.AI_ML/code-1805/Day05all/map.py | mheanng/PythonNote | 2 | 12797313 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
def f1(x):
return x + 3
a = 1
b = f1(a)
print(b)
A = [1, 2, 3]
'''
B = []
for x in A:
B.append(f1(x))
'''
B = list(map(f1, A))
print(B)
C = list(map(lambda x: x + 3, A))
print(C)
| 3.796875 | 4 |
001_TwoSum/two_sum.py | fangqian/LeetCodes | 0 | 12797314 | class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for i in range(len(nums)):
find = target - nums[i]
if d.get(find, None) is None:
d[nums[i]... | 3.3125 | 3 |
day02/day02.py | andreaskaempf/adventofcode2021 | 0 | 12797315 | <gh_stars>0
# Advent of Code, Day 2
# State variables for problems 1 & 2
horiz1 = depth1 = 0
horiz2 = depth2 = aim2 = 0
# Process each line of text
for l in open('input.txt'):
# Get instruction and value
instruction, n = l.split()
n = int(n)
# Process instructions for both problems
if instructio... | 3.78125 | 4 |
runner.py | inXS212/Saltie | 0 | 12797316 | <gh_stars>0
import configparser
import ctypes
import io
import mmap
import msvcrt
import multiprocessing as mp
import os
import sys
import random
import time
import bot_input_struct as bi
import bot_manager
import game_data_struct as gd
import rlbot_exception
from bot_code.conversions.server_converter import ServerCo... | 2.0625 | 2 |
src/features/FER.py | pandov/myitacademy | 1 | 12797317 | import torchvision
from ..paths import PATH_DATA_PROCESSED
class FER(torchvision.datasets.ImageFolder):
def __init__(self, num_classes: int, **kwargs):
kwargs['root'] = PATH_DATA_PROCESSED.joinpath(f'FER{num_classes}').as_posix()
super().__init__(**kwargs)
| 2.203125 | 2 |
Difficulty/Medium/16.3-sum-closest.py | ryderfang/LeetCode | 1 | 12797318 | #
# @lc app=leetcode id=16 lang=python3
#
# [16] 3Sum Closest
#
# @lc code=start
from typing import List
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
ans = 0x7fffffff
sz = len(nums)
nums.sort()
for i in range(sz-2):
if i > 0 and nums[i]... | 3.109375 | 3 |
yetl/metaconf/__init__.py | semanticinsight/yetl-framework | 0 | 12797319 | from ._dataset import DataSet
from ._datastore import DataStore
from ._environment import Environment
from ._project import Project
from ._secret_store import SecretStore
from ._spark import _Spark, Spark
from ._type_mapping import TypeMapping
from ._exceptions import *
__all__ = [
"DataSet",
"DataStore",
"... | 1.296875 | 1 |
cogs/onload.py | paulranshaw/Discord-Bot | 0 | 12797320 | <filename>cogs/onload.py<gh_stars>0
import discord
import os
from discord.errors import ClientException
import dotenv
import logging
import asyncio
from discord.ext import commands, tasks
from dotenv import load_dotenv
from itertools import cycle
client = discord.Client()
class Onload(commands.Cog):
... | 2.484375 | 2 |
tests/impls/gen_detector_prop_sal/test_drise_scoring.py | vbhavank/xaitk-saliency | 0 | 12797321 | from unittest import TestCase
import numpy as np
import os
from xaitk_saliency.impls.gen_detector_prop_sal.drise_scoring import DetectorRISE
from xaitk_saliency import GenerateDetectorProposalSaliency
from smqtk_core.configuration import configuration_test_helper
from tests import DATA_DIR, EXPECTED_MASKS_4x6
clas... | 2.28125 | 2 |
AA_FOOTBALL/GuessLeverage.py | fattail/- | 0 | 12797322 | <filename>AA_FOOTBALL/GuessLeverage.py
import pandas as pd
import numpy as np
import os as os
def GetLverage(v_win,v_tie,v_los,bet_amt,keep_side):
AllocateList = pd.read_csv(r'./data/cmb_list.csv',index_col=None)
AllocateList['胜'] = (AllocateList['胜']*bet_amt)/100
AllocateList['平'] = (AllocateList['平']*b... | 2.59375 | 3 |
高频120_Lint/Regular Expression Matching.py | lixiaoruiusa/Rui7272 | 0 | 12797323 | class Solution:
"""
@param s: A string
@param p: A string includes "." and "*"
@return: A boolean
@ '.'匹配任意一个字母。'*'匹配零个或者多个前面的元素。
@ conner case ??
@ Time | Space
"""
def isMatch(self, s, p):
# 长为S+1 高为p+1 的二维矩阵
dp = [[False] * (len(s) + 1) for _ in range(len(p) + 1)]... | 3.703125 | 4 |
src/vis.py | atreyasha/lfw-faces-rgan | 0 | 12797324 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import re
import os
import glob
import imageio
import argparse
import subprocess
import numpy as np
from tqdm import tqdm
from PIL import Image
from pygifsicle import optimize
from obj.arg_formatter import arg_metav_formatter
def sorted_alphanumeric(data):
... | 2.46875 | 2 |
djangoerp/registration/forms.py | xarala221/django-erp | 345 | 12797325 | <filename>djangoerp/registration/forms.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""This file is part of the django ERP project.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL... | 1.921875 | 2 |
DailyCodingProblem/147_Others_Sort_List_Using_Given_Reverse_Method.py | RafayAK/CodingPrep | 5 | 12797326 | """
Given a list, sort it using this method: reverse(lst, i, j), which reverses lst from i to j.
"""
def reverse(lst, i, j):
lst[i: j] = lst[i: j][::-1]
def sort_with_reverse(lst:list):
iterator = 0
while iterator < len(lst)-1:
smallest_value = min(lst[iterator:])
index_smallest = lst.i... | 4.1875 | 4 |
pyflsk.py | swathiprabhu3/SwakshaGadgetShop | 0 | 12797327 | <reponame>swathiprabhu3/SwakshaGadgetShop
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import pymysql
pymysql.install_as_MySQLdb()
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql://root:@localhost/shoppingwebapp"
db... | 2.28125 | 2 |
service/models.py | YuraPogorelov/auto-blog-pyhon | 0 | 12797328 | <gh_stars>0
from django.db import models
from django.urls import reverse
# Create your models here.
class Category(models.Model):
"""Кактегория услуг"""
name = models.CharField('Название категории', max_length=120)
slug = models.SlugField('URL', max_length=120)
text = models.TextField('Текст категор... | 2.296875 | 2 |
winning_ticket.py | GYosifov88/Python-Fundamentals | 0 | 12797329 | <reponame>GYosifov88/Python-Fundamentals<filename>winning_ticket.py
def additional_func(partition):
current_max_num = 0
special_char = ''
for ch in partition:
if ch != special_char:
if current_max_num >= 6:
break
current_max_num = 1
special_char =... | 3.546875 | 4 |
migrations/versions/2021_102612_bbedc353f90c_.py | fareszr/app | 0 | 12797330 | <gh_stars>0
"""empty message
Revision ID: bbedc353f90c
Revises: d67eab226ecd
Create Date: 2021-10-26 12:05:38.840492
"""
import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'bbedc353f90c'
down_revision = 'd67eab226ecd'
branch_labels = None
depen... | 1.359375 | 1 |
neuralprocesses/util.py | tom-andersson/neuralprocesses | 0 | 12797331 | <reponame>tom-andersson/neuralprocesses
from functools import wraps
import lab as B
import numpy as np
from lab.util import resolve_axis
from . import _dispatch
__all__ = [
"is_framework_module",
"modules",
"register_module",
"models",
"register_model",
"composite_coders",
"register_compo... | 2.28125 | 2 |
word2vec/wordvectors.py | fangyw/word2vec | 1 | 12797332 | <filename>word2vec/wordvectors.py<gh_stars>1-10
# coding: utf-8
import numpy as np
from word2vec.utils import unitvec
class WordVectors(object):
def __init__(self, vocab=None, vectors=None, saveMemory=True):
self.vocab = vocab
if not saveMemory:
self.vectors = vectors
self.l2n... | 3.046875 | 3 |
tests/features/test_evaluate_constant_expression.py | TomPretty/calculator | 0 | 12797333 | <reponame>TomPretty/calculator
from calculator import evaluate
def test_evaluating_a_constant_expression():
source = "3"
assert evaluate(source) == 3
| 2.8125 | 3 |
bot/short.py | dvdrm/gd | 14 | 12797334 | <reponame>dvdrm/gd
from telethon import events, Button
from .utils import split_list, press_event, cmd
from asyncio import exceptions
from .. import jdbot, chat_id, SHORTCUT_FILE, logger, BOT_SET, ch_name
@jdbot.on(events.NewMessage(from_users=chat_id, pattern=r'^/a$'))
async def my_a(event):
markup = []
SEND... | 2.09375 | 2 |
checks/check_nicusage.py | graphingit/droko-agent | 0 | 12797335 | <gh_stars>0
#!/usr/bin/env __PYTHONVER__
import psutil
import time
import sys
if __name__ == "__main__":
while True:
try:
# Get the current unix epoch time
now = str(int(time.time() / 1))
# Output needs to be in comma format, eg:
# epoch,checkname,value... | 2.421875 | 2 |
.projectsAg/model/mail.py | Hraesvel/portfolioSite_flutter | 0 | 12797336 | <reponame>Hraesvel/portfolioSite_flutter
import json
import os
import boto3
from botocore.exceptions import ClientError
# from email.mime.multipart import MIMEMultipart
# from email.mime.text import MIMEText
# from email.mime.application import MIMEApplication
region = os.environ['Region']
def send_mail(msg):
... | 2.203125 | 2 |
model.py | liuying350169/fl | 0 | 12797337 | import torch
import time
import torch.nn as nn
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(in_channels=1, out_channels=16, kernel_size=5, stride=1, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(k... | 3.1875 | 3 |
pybabel_acorn/__init__.py | qbane/pybabel-acorn | 0 | 12797338 | import sys
from contextlib import contextmanager
from os import path
import importlib
# https://stackoverflow.com/a/41904558/2281355
@contextmanager
def add_to_path(p):
import sys
old_path = sys.path
old_modules = sys.modules
sys.modules = old_modules.copy()
sys.path = sys.path[:]
sys.path.inse... | 2.375 | 2 |
datastore/db.py | cs0x65/soil-classifier | 0 | 12797339 | import psycopg2
from psycopg2 import Error
try:
# Connect to an existing database
connection = psycopg2.connect(user="sa",
password="<PASSWORD>",
host="127.0.0.1",
port="5432",
... | 3.5625 | 4 |
database/compiled_templates/webapps/galaxy/admin/tool_sheds.mako.py | psnehal/MethylSig | 0 | 12797340 | # -*- encoding:ascii -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 6
_modified_time = 1433361565.2110319
_template_filename='templates/webapps/galaxy/admin/tool_sheds.mako'
_template_uri='/webapps/galaxy/admin/tool_sheds.ma... | 1.773438 | 2 |
tests/xtest_laser_power2.py | dapperfu/python_GCode | 0 | 12797341 | import time
import grbl
import pytest
import gcode
@pytest.fixture(scope="session")
def cnc(request):
grbl_cfg = {
"port": request.config.getoption("--port"),
"baudrate": request.config.getoption("--baudrate"),
}
cnc = grbl.Grbl(**grbl_cfg)
time.sleep(2)
cnc.reset()
# Metric
... | 1.84375 | 2 |
tests/test_raw_lightcurve.py | konkolyseismolab/autoeap | 3 | 12797342 | import numpy as np
import autoeap
from numpy.testing import assert_array_almost_equal
import os
PACKAGEDIR = os.path.abspath(os.path.dirname(__file__))
def test_raw_lightcurve():
time,flux,flux_err = autoeap.createlightcurve('EPIC220198696',campaign=8)
lc = np.genfromtxt(os.path.join(PACKAGEDIR,"EPIC22019869... | 2.09375 | 2 |
common/services/unchained.py | shapeshift-legacy/watchtower | 0 | 12797343 | import logging
import os
import urllib3
import ast
from common.utils.requests import http
from common.utils.networks import ETH
from common.services import cointainer_web3 as web3
from common.utils.ethereum import ERC20_ABI
logger = logging.getLogger('watchtower.common.services.unchained')
class UnchainedClient(ob... | 2.234375 | 2 |
PythonAndOop/N39_method_overloading_3.py | jiauy/before_work | 0 | 12797344 | class MyList(list):
def __getitem__(self, index):
if index == 0:
raise IndexError
if index > 0:
index -= 1
return list.__getitem__(self, index)
def __setitem__(self, index, value):
if index == 0:
raise IndexError
if index > 0:
... | 3.859375 | 4 |
build/lib/drf_advanced_token/management/commands/revoke_all_tokens.py | amp89/drf_advanced_token | 2 | 12797345 | from django.core.management.base import BaseCommand
from rest_framework.authtoken.models import Token
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'--force',
action='store_true',
help='WARNING - Understand that this logs out and *PER... | 2.046875 | 2 |
Tests/test_main_pytest.py | miki4920/ChessAI | 0 | 12797346 | from config import Config
from main import determine_colour, return_tile_colour, coordinates_to_notation
def test_determine_colour():
assert determine_colour(0, 0)
assert not determine_colour(0, 7)
assert not determine_colour(7, 0)
assert determine_colour(7, 7)
def test_return_tile_colour():
ass... | 3.109375 | 3 |
tools/mqtt_listener.py | SaibboRiginal/Python_remote_PLC | 0 | 12797347 | # Essential modules import
import json
from paho.mqtt.client import *
# Variables modules import
from tools import *
# Importing custom Utility modules
from utility.logger import MyLogger
log = MyLogger("mqtt") # Logger
class Marker(Client):
'''
Client Marker : Broker client to send and/or receive MQTT pub... | 2.765625 | 3 |
vmfw.py | whs/OvzCP | 1 | 12797348 | import os, sys, ConfigParser
sys.path.insert(0, os.path.join(os.getcwd(), "Jinja2-2.3-py2.5.egg"))
sys.path.append(os.path.join(os.getcwd(), "netifaces-0.5-py2.5-linux-i686.egg"))
import jinja2, netifaces
_config = ConfigParser.SafeConfigParser()
_config.read("config.ini")
# iptables forwarding configuration ... | 2.28125 | 2 |
back/test.py | sresoft/thengrow | 0 | 12797349 | <filename>back/test.py
from minitwit import *
couch = Couch('sre.cloudant.com') | 1.335938 | 1 |
LeetCode/905 Sort Array By Parity.py | gesuwen/Algorithms | 0 | 12797350 | <reponame>gesuwen/Algorithms<filename>LeetCode/905 Sort Array By Parity.py
# Array
# Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.
#
# You may return any answer array that satisfies this condition.
#
#
#
# Example 1:
#
# Inpu... | 3.96875 | 4 |