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 |
|---|---|---|---|---|---|---|
download/Cost-Function-Of-ML/costFunctionExam.py | chenjian158978/chenjian.github.io | 3 | 52700 | <reponame>chenjian158978/chenjian.github.io
# -*- coding:utf8 -*-
"""
@author: <EMAIL>
@date: Tue, May 23 2017
@time: 19:05:20 GMT+8
"""
import matplotlib.pyplot as plt
import numpy as np
# 都转换成列向量
X = np.array([[0, 1, 2, 4]]).T
Y = np.array([[0, 1, 2, 4]]).T
# 三个不同的theta_1值
theta1 = np.array([[0, 0]]).T
theta2 = ... | 3.09375 | 3 |
request-by-coordinate.py | fossgis-routing-server/request-by-coordinate | 2 | 52701 | import cherrypy
import urllib.parse, urllib.request
import math
from polyline import decodePolyline
"""
Dispatches OSRM routing requests to backend servers
depending on the requested start and end coordinates
This is a workaround because OSRM needs large amounts of
memory for preprocessing and running. This allows to... | 3 | 3 |
scrapli/transport/plugins/asyncssh/transport.py | verbosemode/scrapli | 0 | 52702 | """scrapli.transport.plugins.asyncssh.transport"""
import asyncio
from dataclasses import dataclass
from typing import Optional
from asyncssh import connect
from asyncssh.connection import SSHClientConnection
from asyncssh.misc import ConnectionLost, PermissionDenied
from asyncssh.stream import SSHReader, SSHWriter
f... | 1.984375 | 2 |
kagura/utils.py | nishio/kagura | 1 | 52703 | <filename>kagura/utils.py
"""
utilities
=========
"""
def stratified_split(xs, ys, nfold=10):
"""
USAGE:
train_xs, test_xs, train_ys, test_ys = stratified_split(xs, ys)
"""
from sklearn.cross_validation import StratifiedKFold
train, test = StratifiedKFold(ys, nfold).__iter__().next()
retur... | 2.953125 | 3 |
artificial_intelligence/agents/tryTeam.py | startupjing/machine_learning | 1 | 52704 | <filename>artificial_intelligence/agents/tryTeam.py
# baselineTeam.py
# ---------------
# Licensing Information: Please do not distribute or publish solutions to this
# project. You are free to use and extend these projects for educational
# purposes. The Pacman AI projects were developed at UC Berkeley, primarily by
#... | 3.125 | 3 |
download_bert.py | tcnguyen/bert | 0 | 52705 | <gh_stars>0
# download BERT multi-lingual
from utils import maybe_download
import os
BERT_MODELS_DIR = 'bert_models'
BERT_BASE_DIR = 'bert_models/multilingual_L-12_H-768_A-12'
BERT_MODEL_URL = 'https://storage.googleapis.com/bert_models/2018_11_03/'
BERT_BASE_MULTI_FILE = 'multilingual_L-12_H-768_A-12.zip'
if __nam... | 1.882813 | 2 |
utils/subtitution.py | Samoray-l337/CryptoGuesser | 0 | 52706 | import utils.config as config
from utils.words import prensetage_of_real_words_in_list
from utils.random import random_subtitution_string
from utils.search import is_known_part_in_text
from string import ascii_lowercase
from tqdm import tqdm
def get_array_key_from_string(string):
return { ascii_lowercase[i]: stri... | 2.6875 | 3 |
pastetape/db/base.py | EXLER/Pastetape | 1 | 52707 | from sqlalchemy.ext.declarative import as_declarative, declared_attr
from pastetape.db.session import engine
@as_declarative()
class Base:
__name__: str
@declared_attr
def __tablename__(cls) -> str:
return cls.__name__.lower()
def initialize_db() -> None:
"""
Initializes the database t... | 2.421875 | 2 |
day23/solution.py | namanwahi/advent-of-code | 0 | 52708 | <reponame>namanwahi/advent-of-code
from collections import deque
if __name__ == "__main__":
cups = [2, 1, 5, 6, 9, 4, 7, 8, 3]
cups = cups + list(range(max(cups) + 1, 1_000_001))
min_label = min(cups)
max_label = max(cups)
# build mapping from current to next
circle = {}
for i, cup in... | 3.71875 | 4 |
courseparticipation/api/permissions.py | TBrockmeyer/courses-participation-api | 0 | 52709 | from rest_framework import permissions
class IsAdminOrReadOnly(permissions.BasePermission):
"""
Custom permission to only allow admins to edit an object, and all others to view it.
"""
def has_permission(self, request, view):
# Read permissions are allowed to any authenticated request,
... | 3.0625 | 3 |
kao_decorators/lazy_property.py | cloew/KaoDecorators | 0 | 52710 |
def lazy_property(fn):
""" Convert function into a property where the function is
only called the first time the property is accessed """
varName = "__{0}".format(fn.__name__)
def lazyLoad(self):
if not hasattr(self, varName):
setattr(self, varName, fn(self))
re... | 3.546875 | 4 |
doc/format-for-listings.py | dominique-unruh/qrhl-tool | 10 | 52711 | <filename>doc/format-for-listings.py
#!/usr/bin/python3
import sys, re
sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf8', buffering=1)
# sys.stdout.reconfigure(encoding='utf-8') # Works only with Python 3.7+
substitutes = {
'lambda': '\\lambda',
'Rightarrow': '\\Rightarrow',
'bar': '\\vert... | 2.90625 | 3 |
lesson10/qiangshihong/users/urls.py | herrywen-nanj/51reboot | 0 | 52712 | #!/usr/bin/python
# author: qsh
from django.urls import path, re_path
from . import views_old,views1,views
from . import views,user,roles
app_name = 'users'
urlpatterns = [
# http://ip:8000/
path("", views.IndexView.as_view(), name='index'),
# http://ip:8000/login/
path("login/", views.LoginView.as_vi... | 1.882813 | 2 |
examples/color/rgbcolor.py | Granitosaurus/generativepy | 0 | 52713 | from generativepy.drawing import makeImage
from generativepy.color import Color
def draw(ctx, width, height, frame_no, frame_count):
ctx.set_source_rgba(*Color(1).get_rgba())
ctx.paint()
for i in range(200):
for j in range(200):
ctx.set_source_rgba(*Color(i/200, j/200, 0).get_rgba())
... | 3.015625 | 3 |
lab2/p4b.py | sarahmid/programming-bootcamp | 1 | 52714 | dnaSeq = raw_input("Enter a DNA sequence: ")
motif = raw_input("Enter a motif to search for: ")
if len(motif) > len(dnaSeq):
print "Error: motif sequence is longer than DNA sequence."
else:
if motif in dnaSeq:
print "Found the motif in the sequence."
else:
print "Did not find the motif in the sequence." | 3.984375 | 4 |
toontown/toonbase/BitmaskGlobals.py | CrankySupertoon01/Toontown-2 | 1 | 52715 | <gh_stars>1-10
from pandac.PandaModules import BitMask32
WallBitmask = BitMask32(1)
FloorBitmask = BitMask32(2)
CameraBitmask = BitMask32(4)
CameraTransparentBitmask = BitMask32(8)
SafetyNetBitmask = BitMask32(512)
SafetyGateBitmask = BitMask32(1024)
GhostBitmask = BitMask32(2048)
PathFindingBitmask = BitMask32.bit(29... | 1.40625 | 1 |
util/test/tests/D3D11/D3D11_Untyped_Backbuffer_Descriptor.py | hbina/renderdoc | 6,181 | 52716 | <filename>util/test/tests/D3D11/D3D11_Untyped_Backbuffer_Descriptor.py
import renderdoc as rd
import rdtest
class D3D11_Untyped_Backbuffer_Descriptor(rdtest.TestCase):
demos_test_name = 'D3D11_Untyped_Backbuffer_Descriptor'
def check_capture(self):
# find the first action
action = self.find_a... | 1.953125 | 2 |
verba/apps/github/api.py | nhsuk/verba | 0 | 52717 | <gh_stars>0
import json
import requests
import base64
import logging
from django.utils.dateparse import parse_datetime
from verba_settings import config
from .exceptions import InvalidResponseException, NotFoundException
logger = logging.getLogger('github.api')
class Request(object):
base_url = None
defa... | 2.296875 | 2 |
app/planeks_news/admin.py | smak0v/planeks_news | 0 | 52718 | <reponame>smak0v/planeks_news
from django.contrib.admin import AdminSite
class PlaneksNewsAdminSite(AdminSite):
site_header = 'PLANEKS News Administration'
admin_site = PlaneksNewsAdminSite(name='planeks_news_admin')
| 1.484375 | 1 |
src/pyrobot/tm700/camera.py | liu115/pyrobot | 1 | 52719 | <reponame>liu115/pyrobot
import os
import threading
from copy import deepcopy
import numpy as np
import rospy
import message_filters
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import CameraInfo
from sensor_msgs.msg import Image
from sensor_msgs.msg import JointState
from pyrobot.core import Ca... | 2.0625 | 2 |
sync_gtasks_grocy.py | BlueBlueBlob/appdaemon_scripts | 2 | 52720 | import appdaemon.plugins.hass.hassapi as hass
import datetime
import pytz
import requests
import json
class SyncGTasksAndGrocy(hass.Hass):
tl_name = 'Corvées'
tl_id = None
tl_main = None
debug = False
gr_cl = None
service = None
tl_lastup = None
google_oauth_tasks = None
grocyapi = ... | 2.1875 | 2 |
Filter.py | eejwa/Data-Preprocessing | 0 | 52721 | #!/usr/bin/env python
usage = """Code to filter traces in the directory given a frequency band and file wildcard.
[-fl][-fh][-f][-t] where:
-fl = miniumum frequency value (e.g. 0.05)
-fh = maxiumum frequency value (e.g. 1.0)
-f = filename wildcard (e.g. '*SAC')
-t = type of filtering (e.g. bandpass)
"""
import obsp... | 3.03125 | 3 |
nrm_analysis/InstrumentData.py | vandalt/ImPlaneIA | 0 | 52722 | #! /usr/bin/env python
"""
InstrumentData Class -- defines data format, wavelength info, mask geometry
Instruments/masks supported:
NIRISS AMI
GPI, VISIR, NIRC2 removed - too much changed for the JWST NIRISS class
"""
# Standard Imports
import numpy as np
from astropy.io import fits
import os, sys, time
import copy
... | 2.21875 | 2 |
scripts/measure.py | TomMelt/PhysFilmMakers | 0 | 52723 | from time import sleep
from ina219 import INA219
ina = INA219(shunt_ohms=0.1,
max_expected_amps = 0.2,
address=0x40)
ina.configure(voltage_range=ina.RANGE_32V,
gain=ina.GAIN_AUTO,
bus_adc=ina.ADC_128SAMP,
shunt_adc=ina.ADC_128SAMP)
def get_readings... | 2.78125 | 3 |
tests/test_discovery_integration.py | lejmr/prometheus-ecs-discoverer | 12 | 52724 | <reponame>lejmr/prometheus-ecs-discoverer
import os
import boto3
from botocore.stub import Stubber
from prometheus_ecs_discoverer import discovery, fetching, toolbox
from tests import test_discovery_integration_data as data
def test_discovery_full():
os.environ["AWS_DEFAULT_REGION"] = "eu-central-1"
os.envi... | 1.921875 | 2 |
arithmetic_arranger.py | riannselegar/SCwP-arithmetic-formatter | 0 | 52725 | <filename>arithmetic_arranger.py
def arithmetic_arranger(problems, sum=False):
firstLine = ''
secondLine = ''
thirdLine = ''
fourthLine = ''
if len(problems) > 5:
return "Error: Too many problems."
for exp in problems:
splited = exp.split()
if max(len(splited[0]), len(s... | 3.359375 | 3 |
deploy/deploy_main.py | mikeshultz/solidbyte-test-project | 0 | 52726 | STD_GAS_PRICE = int(3e9) # 3gwei
def autofund_account(web3, address, value):
""" Automatically fund an account """
assert isinstance(value, int)
net_id = int(web3.net.version)
balance = web3.eth.getBalance(address)
if net_id > 100:
# If this is the test network, make sure our deployment... | 2.203125 | 2 |
gra.py | golawskaj/Plumber | 0 | 52727 | import pygame, math
pygame.init()
win = pygame.display.set_mode((1000, 600))
pygame.display.set_caption("Plumber")
angle = [pygame.image.load('angl1.png'), pygame.image.load('angl2.png'), pygame.image.load('angl3.png'),
pygame.image.load('angl4.png')]
straight = [pygame.image.load('str1.png'), pyga... | 2.578125 | 3 |
test/ibmq/test_serialization.py | chahatagarwal/qiskit-ibmq-provider | 1 | 52728 | # -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modif... | 2.0625 | 2 |
sources/controller/main_window/button_main_window.py | Groomsha/lan-map | 0 | 52729 | #
# 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.796875 | 2 |
standard_lib/file_matching_regex.py | DahlitzFlorian/python-snippets | 29 | 52730 | <reponame>DahlitzFlorian/python-snippets
import fnmatch
import os
import re
reg = "({})|({})".format(fnmatch.translate("*.md"), fnmatch.translate("*.git*"))
markdown_files = [f for f in os.listdir() if re.match(reg, f)]
print(markdown_files)
| 2.84375 | 3 |
ovirtlib4/networks.py | MosheSheena/ovirtlib4 | 0 | 52731 | <gh_stars>0
# -*- coding: utf-8 -*-
import ovirtsdk4.types as types
from .system_service import CollectionService, CollectionEntity
class Networks(CollectionService):
"""
Gives access to all oVirt Networks
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
se... | 2.546875 | 3 |
Lib/sunos5/SOCKET.py | AtjonTV/Python-1.4 | 0 | 52732 | <filename>Lib/sunos5/SOCKET.py
# Generated by h2py from /usr/include/sys/socket.h
NC_TPI_CLTS = 1
NC_TPI_COTS = 2
NC_TPI_COTS_ORD = 3
NC_TPI_RAW = 4
SOCK_STREAM = NC_TPI_COTS
SOCK_DGRAM = NC_TPI_CLTS
SOCK_RAW = NC_TPI_RAW
SOCK_RDM = 5
SOCK_SEQPACKET = 6
SO_DEBUG = 0x0001
SO_ACCEPTCONN = 0x0002
SO_REUSEADDR = 0x0004
SO_... | 1.53125 | 2 |
services/backend/src/schemas/notes.py | gideonmandu/note_taking_app | 0 | 52733 | from pydantic import BaseModel
from tortoise.contrib.pydantic import pydantic_model_creator
from typing import Optional
from src.database.models import Notes
# Creating new notes
NoteInSchema = pydantic_model_creator(
Notes, name="NoteIn", exclude=["author_id"], exclude_readonly=True
)
# retrieving Notes
NoteOu... | 2.40625 | 2 |
data/config.py | Iwillsky/ProteinFoldingCloud | 1 | 52734 | import os
settings = {
'host': os.environ.get('ACCOUNT_HOST', 'https://hacktest.documents.azure.com:443/'),
'master_key': os.environ.get('ACCOUNT_KEY', '<KEY>'),
'database_id': os.environ.get('COSMOS_DATABASE', 'hackjoblist'),
'container_id': os.environ.get('COSMOS_CONTAINER', 'joblist'),
} | 1.15625 | 1 |
src/tngsdksm/generate.py | tsoenen/tng-sdk-sm | 1 | 52735 | <gh_stars>1-10
# Copyright (c) 2015 SONATA-NFV, 2017 5GTANGO
# ALL RIGHTS RESERVED.
#
# 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
#
# Unle... | 1.6875 | 2 |
pcdet/models/roi_heads/roi_head_template.py | Kemo-Huang/OpenPCDet | 0 | 52736 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from .target_assigner.proposal_target_layer import ProposalTargetLayer
from ..model_utils.model_nms_utils import class_agnostic_nms
from ...utils import box_coder_utils, common_utils, loss_utils
class RoIHeadTemplate(nn.Module):
... | 1.835938 | 2 |
200-299/200-209/202.py | dcragusa/LeetCode | 0 | 52737 | """
Write an algorithm to determine if a number n is happy.
A happy number is a number defined by the following process:
- Starting with any positive integer, replace the number by the sum of the squares of its digits.
- Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycl... | 4.0625 | 4 |
tests/conftest.py | routeco/routor | 2 | 52738 | <filename>tests/conftest.py
from pathlib import Path
import osmnx
import pytest
from networkx import DiGraph
from routor.engine import Engine
@pytest.fixture(autouse=True, scope="session")
def vcr_cassette_dir() -> str:
"""
Use one single cassettes dir.
"""
tests_dir = Path(__file__).parent
retu... | 2.140625 | 2 |
2019/day3.py | dethi/adventofcode | 0 | 52739 | #!/usr/bin/env python3
import sys
import operator
from functools import reduce
from typing import List, Tuple, Iterator
Vector = Tuple[int, int] # x, y
def decode_move(move: str) -> Vector:
d, n = move[0], int(move[1:])
if d == 'U':
return (0, n)
elif d == 'D':
return (0, -n)
elif ... | 3.265625 | 3 |
noicesoup/noicesoup.py | richeyphu/noicesoup | 0 | 52740 | """
A simple python package for scraping and downloading images from Google
Usage:
$ noicesoup.py [-h] -k KEYWORD [-cd CHROMEDRIVER]
NOTE: Default webdriver is Chrome in relative path "chromedriver"
Images will be saved in "downloads/<keyword>"
This package is currently under development...
"""
import threading... | 3.5625 | 4 |
Bonsucesso/Semana 03/Exemplos de Sala de Aula/Exemplo012/main.py | profoswaldo/Unisuam_2022-1 | 2 | 52741 | <gh_stars>1-10
# Desenvolva um algoritmo em Python que receba a matricula, nome, e 3 notas de um aluno e que calcule e exiba a matricula, nome, média e conceito do mesmo, conforme definido abaixo:
# Conceito A - Média maior ou igual a 7
# Conceito B - Média Menor do que 7 e maior ou igual a 5
# Conceito C - Mé... | 4.21875 | 4 |
twitoff/app.py | GermanParra/Mytwitoff | 0 | 52742 | from os import getenv
from flask import Flask, render_template, request
from twitoff.twitter import add_or_update_user
from .models import DB, User, Tweet
from .twitter import add_or_update_user, get_all_usernames
from .predict import predict_user
# Create a 'factory' for serving up the app when is launched
def creat... | 2.84375 | 3 |
ReversingNumbers/reversing_numbers.py | Yoshiyuki-Su/python_samples | 0 | 52743 | def reverseNumber(number):
result = ''
while number:
result += str(number % 10)
number = number // 10
return result
def reverseNumberForSlice(number):
return str(number[::-1])
if __name__ == '__main__':
input_num = input("数値を入力してください。>>> ")
# 数値チェックをいれる
if input_num.isdigit... | 4.03125 | 4 |
0306_more_guest.py | arunkumarang/python | 0 | 52744 | <filename>0306_more_guest.py<gh_stars>0
#!/usr/bin/python
import sys
def main():
guest_lists = ['senthil', 'raj', 'ameen']
print("Hi Everyone! I found a bigger dinner table. I would like to invite more people for Dinner.")
guest_lists.insert(0, 'naveen')
guest_lists.insert(2, 'prabhu')... | 3.25 | 3 |
main/xev/template.py | RoastVeg/cports | 0 | 52745 | <filename>main/xev/template.py
pkgname = "xev"
pkgver = "1.2.4"
pkgrel = 0
build_style = "gnu_configure"
hostmakedepends = ["pkgconf"]
makedepends = ["libxrandr-devel"]
pkgdesc = "Display X events"
maintainer = "q66 <<EMAIL>>"
license = "MIT"
url = "https://xorg.freedesktop.org"
source = f"$(XORG_SITE)/app/{pkgname}-{p... | 1.570313 | 2 |
harris_county_bookings/settings_example.py | open-austin/harris-county-bookings | 4 | 52746 | <gh_stars>1-10
"""
These settings are only needed if you are planning to push to S3, GitHub or data.world.
If you only are only saving to local files, then these are not needed.
"""
S3_BUCKETS = {
# 'bucket': name of the bucket
# 'key': syntax: a_folder/another_folder
#
# For the 'scrub' bucket, one su... | 1.539063 | 2 |
myexperiment_new/Tic_Tac_Toe_file/version5.py | abodi050/kjkjkjkjkj | 0 | 52747 | from random import randint
gnum = randint(0, 2)
print(gnum)
print("welcome to the game\n\n")
print(
"you will guess a number \nbetween 1 to 100 \nwe have selected for you\n\n"
)
print("hint: WARM! mean yor are close by 10 ")
print("\nlet's start\n")
z = 0
count_num = 0
out = 0
warm = 0
cold = 0
list1 = []
while z =... | 3.84375 | 4 |
pbs_util/prime_example.py | Clyde-fare/pbs_util | 1 | 52748 | import pbs_util.pbs_map as ppm
class PrimeWorker(ppm.Worker):
def __call__(self, n):
is_prime = True
for m in xrange(2,n):
if n % m == 0:
is_prime = False
break
return (n, is_prime)
if __name__ == "__main__":
for (n, is_prime) ... | 3.03125 | 3 |
model/section.py | yiyangyi/cc98-tornado | 0 | 52749 | <filename>model/section.py
class SectionModel(Query):
def __init__(self, db):
self.db = db
self.table_name = "section"
super(SectionModel, self).__init__() | 2.390625 | 2 |
bmi_tester/bmipytest.py | csdms/bmi-tester | 0 | 52750 | <filename>bmi_tester/bmipytest.py<gh_stars>0
#! /usr/bin/env python
import importlib
import os
import pathlib
import re
import sys
import tempfile
from functools import partial
import click
import pkg_resources
from model_metadata import MetadataNotFoundError
from model_metadata.api import query, stage
from pytest imp... | 2.171875 | 2 |
src/podrum/network/protocol/AdventureSettingsPacket.py | genisyspromcpe/Podrum | 1 | 52751 | """
* ____ _
* | _ \ ___ __| |_ __ _ _ _ __ ___
* | |_) / _ \ / _` | '__| | | | '_ ` _ \
* | __/ (_) | (_| | | | |_| | | | | | |
* |_| \___/ \__,_|_| \__,_|_| |_| |_|
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the Licens... | 1.898438 | 2 |
excut/embedding/ampligraph_extend/__init__.py | mhmgad/ExCut | 5 | 52752 | from .models.TransE import TransE
from .models.ComplEx import ComplEx
from .models.DistMult import DistMult
from .models.ConvKB import ConvKB
__all__=['TransE', 'ComplEx','DistMult', 'ConvKB'] | 1.070313 | 1 |
t72pkl.py | kopetri/LayoutNetv2 | 166 | 52753 | # load .t7 file and save as .pkl data
import torchfile
import cv2
import numpy as np
import scipy.io as sio
import pickle
import time
data_path = './data/test_PC/'
# panoContext
#img_tr = torchfile.load('./data/panoContext_img_train.t7')
#print(img_tr.shape)
#lne_tr = torchfile.load('./data/panoContext_line_train.t7... | 2.296875 | 2 |
zerorobot/storage/base.py | threefoldtech/0-robot | 0 | 52754 | <reponame>threefoldtech/0-robot
from abc import ABC, abstractmethod
from zerorobot.task.task import TASK_STATE_RUNNING
class ServiceStorageBase(ABC):
@abstractmethod
def save(self, service):
"""
save a service object
:param service: service
:type service: zerorobot.template.... | 2.875 | 3 |
model.py | awesome-archive/TranSummar | 0 | 52755 | # -*- coding: utf-8 -*-
#pylint: skip-file
import sys
import numpy as np
import torch
import torch as T
import torch.nn as nn
from torch.autograd import Variable
import copy
from utils_pg import *
from encoder import *
from decoder import *
from transformer.layers import Embeddings, PositionEmbeddings
class Model(nn... | 2.28125 | 2 |
geco/__init__.py | FreestyleBuild/GeCO | 8 | 52756 | from geco.mips import *
| 0.699219 | 1 |
dzo/__init__.py | moriaki3193/dzo | 8 | 52757 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""dzo -- Python implemented portable and easy-to-use search engine.
"""
from .const import _VERSION
__author__: str = '<NAME>'
__version__: str = _VERSION
| 1.078125 | 1 |
src/huntsman/pocs/core.py | danjampro/huntsman-pocs | 0 | 52758 | <reponame>danjampro/huntsman-pocs
from panoptes.pocs.core import POCS
class HuntsmanPOCS(POCS):
""" Minimal overrides to the POCS class """
def __init__(self, *args, **kwargs):
self._dome_open_states = []
super().__init__(*args, **kwargs)
def run(self, initial_next_state='starting', *arg... | 2.5625 | 3 |
gnuradio-3.7.13.4/gr-analog/python/analog/qa_dpll.py | v1259397/cosmic-gnuradio | 1 | 52759 | <reponame>v1259397/cosmic-gnuradio<filename>gnuradio-3.7.13.4/gr-analog/python/analog/qa_dpll.py<gh_stars>1-10
#!/usr/bin/env python
#
# Copyright 2012,2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the... | 2.109375 | 2 |
ProbePage.py | linuxnico/bCNC | 0 | 52760 | <filename>ProbePage.py<gh_stars>0
# $Id$
#
# Author: <EMAIL>
# Date: 18-Jun-2015
__author__ = "<NAME>"
__email__ = "<EMAIL>"
import sys
# import time
import math
try:
from Tkinter import *
import tkMessageBox
except ImportError:
from tkinter import *
import tkinter.messagebox as tkMessageBox
from CNC import CN... | 2.0625 | 2 |
src/backend/app/drivers/sqlalchemy/models/role.py | douglasdaly/web-app-skeleton | 1 | 52761 | <reponame>douglasdaly/web-app-skeleton
# -*- coding: utf-8 -*-
"""
Role storage schema for SQLAlchemy.
"""
import typing as tp
import sqlalchemy as sa
from app.crud.models.role import RoleBase
from app.drivers.sqlalchemy.models.base import Base
class Role(RoleBase, Base):
"""
Storage table for Role objects ... | 2.375 | 2 |
chapter_4_modeling/train_audioregression.py | fancyerii/voicebook | 1 | 52762 | <gh_stars>1-10
'''
================================================
## VOICEBOOK REPOSITORY ##
================================================
repository name: voicebook
repository version: 1.0
repository link: https://github.com/jim-schwoebel/voicebook
author: <NAME>
author contact:... | 1.796875 | 2 |
statinf/data/__init__.py | matthieubulte/statinf | 0 | 52763 | <filename>statinf/data/__init__.py<gh_stars>0
from .GenerateData import generate_dataset | 1.117188 | 1 |
coalaip_bigchaindb/utils.py | bigchaindb/bigchaindb-coalaip | 12 | 52764 | <reponame>bigchaindb/bigchaindb-coalaip
from functools import wraps
from coalaip.exceptions import PersistenceError
def make_transfer_tx(bdb_driver, *, input_tx, recipients, metadata=None):
if input_tx['operation'] == 'CREATE':
input_asset_id = input_tx['id']
else:
input_asset_id = input_tx['a... | 2.515625 | 3 |
tests/test_config.py | lukelu0520/boxdetect | 43 | 52765 | import pytest
import sys
sys.path.append(".")
sys.path.append("../.")
from boxdetect import config
from boxdetect import pipelines
def test_save_load_config(capsys):
cfg = config.PipelinesConfig()
cfg.morph_kernels_thickness = 10
cfg.save_yaml('test_cfg.yaml')
cfg2 = config.PipelinesConfig('test_cfg.y... | 2.03125 | 2 |
nodes/2.x/python/ElevationMarker.Views.py | andydandy74/ClockworkForDynamo | 147 | 52766 | <gh_stars>100-1000
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
def GetElevationMarkerView(item):
val = []
if hasattr(item, "HasElevations"):
if item.HasElevations():
for i in range(item.MaximumViewCount... | 2.265625 | 2 |
audacitorch/core.py | hugofloresgarcia/audacitorch | 32 | 52767 | <gh_stars>10-100
from typing import Tuple
import torch
from torch import nn
def _waveform_check(x: torch.Tensor):
assert x.ndim == 2, "input must have two dimensions (channels, samples)"
assert x.shape[-1] > x.shape[0], f"The number of channels {x.shape[-2]} exceeds the number of samples {x.shape[-1]} in your INPU... | 2.796875 | 3 |
ops-tests/feature/test_ft_lag_statistics.py | ashutoshshanker/ops-lacpd | 0 | 52768 | <reponame>ashutoshshanker/ops-lacpd<filename>ops-tests/feature/test_ft_lag_statistics.py
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You ... | 1.507813 | 2 |
tests/__init__.py | vpv11110000/pyss | 0 | 52769 | <reponame>vpv11110000/pyss<gh_stars>0
# -*- coding: utf-8 -*-
import sys
import os
import random
import unittest
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
DIRNAME_MODULE = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(sys.argv[0])))) + os.sep
sys.path.append(D... | 2.171875 | 2 |
tests/saq/modules/test_o365.py | ace-ecosystem/ACE | 24 | 52770 | <reponame>ace-ecosystem/ACE<gh_stars>10-100
import pytest
import saq
from saq.database import Alert, Observable, ObservableMapping
from saq.analysis import RootAnalysis
from saq.constants import *
from saq.modules.o365 import O365FileConversationAnalyzer
@pytest.mark.parametrize('conversation, has_detection_points... | 1.984375 | 2 |
www/tests/test_print.py | raspberrypieman/brython | 5,926 | 52771 | <gh_stars>1000+
funcs = [
"abs", "all", "any", "ascii", "bin", "callable", "chr", "compile",
"delattr", "dir", "divmod", "eval", "exec", "exit", "format", "getattr",
"globals", "hasattr", "hash", "help", "hex", "id", "input", "isinstance",
"issubclass", "iter", "len", "locals", "max", "min", "next", "oc... | 2.21875 | 2 |
tmp/disable_call_recording.py | dtolb/docstring-extractor | 0 | 52772 | # Example: Disable Call Recording
api.disable_call_recording('c-callId')
| 1.320313 | 1 |
backtesting/backtesting.py | CryptoRichy/OctoBot | 1 | 52773 | import logging
import os
import time
from backtesting import get_bot
from config.cst import *
class Backtesting:
def __init__(self, config, exchange_simulator, exit_at_end=True):
self.config = config
self.begin_time = time.time()
self.time_delta = 0
self.force_exit_at_end = exit_a... | 2.609375 | 3 |
examples/codes/cross_check_file_exists.py | rhoposit/self-attention-tacotron | 0 | 52774 | import sys, os, glob
infile = sys.argv[1]
outfile = infile+".revised"
existsfile = "vctk_files.txt"
input = open(infile, "r")
tacodata = input.read().split("\n")
input.close()
input = open(existsfile, "r")
existsdata = input.read().split("\n")
input.close()
existsdata = [item.split(".")[0] for item in existsdata]
... | 2.640625 | 3 |
things/attrs.py | jmoswalt/django-things | 2 | 52775 | <gh_stars>1-10
from .types import *
AUTHOR = {
"name": "Author",
"key": "author",
"description": "The Author of the {{ model }}.",
"datatype": TYPE_TEXT
}
CONTENT = {
"name": "Content",
"key": "content",
"description": "The main content of the {{ model }}.",
"required": True,
"data... | 2.578125 | 3 |
beginner/eyes-detection-from-web-cam-opencv-python/main.py | CrispenGari/opencv-python | 1 | 52776 |
try:
import cv2
import numpy as np
except ImportError as e:
from pip._internal import main as install
packages = ["numpy", "opencv-python"]
for package in packages:
install(["install", package])
finally:
pass
def detectEyeGlasses():
capture = cv2.VideoCapture(0)
eyesCasecade = c... | 2.859375 | 3 |
bot.py | suntorvic/tobman | 0 | 52777 | <reponame>suntorvic/tobman
#!/usr/bin/python3
# coding: utf-8
from __future__ import annotations
import discord
from discord.ext import commands
from enum import Enum
import yaml
import re
import sys
import json
import os.path
import urllib, urllib.parse
import datetime
import ics
import io
import asyncio
class Transl... | 2.09375 | 2 |
interpolation/methods/linear_system.py | JNagasava/Polynomial-Interpolation | 0 | 52778 | <reponame>JNagasava/Polynomial-Interpolation
"""
Linear System (Polynomial Interpolation)
"""
import numpy as np
def swap_rows(Z, a, b):
"""
Swap two rows (a, b) from Z matrix (np.array)
Parameters
----------
Z : np.array
matrix
a : int
index row from Z
... | 3.46875 | 3 |
workspace/src/path_planning/path_planning/path_planning.py | uwsbel/autonomy-research-testbed | 0 | 52779 | #
# BSD 3-Clause License
#
# Copyright (c) 2022 University of Wisconsin - Madison
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyrig... | 1.171875 | 1 |
chomsky/exceptions.py | colinta/chomsky | 3 | 52780 |
class ParseException(Exception):
pass
class RollbackException(Exception):
pass
| 1.320313 | 1 |
bench/plot_bench.py | JoelKatz/NuDB | 7 | 52781 | #/usr/bin/env python
# Script to read the result of the benchmark program and plot the results.
# Options:
# `-i arg` : input file (benchmark result)
# `-o arg` : html output for the plot
# Notes: After the script runs the plot will automatically be shown in a browser.
# Tested with python 3 only.
import a... | 2.953125 | 3 |
flows/squeeze.py | UdonDa/normalizing-flows-pytorch | 39 | 52782 | import torch
import torch.nn as nn
def channel_split(z, dim=1, odd=False):
C = z.size(dim)
z0, z1 = torch.split(z, C // 2, dim=dim)
if odd:
z0, z1 = z1, z0
return z0, z1
def channel_merge(z0, z1, dim=1, odd=False):
if odd:
z0, z1 = z1, z0
z = torch.cat([z0, z1], dim=dim)
... | 2.3125 | 2 |
hooks/pre_gen_project.py | aubricus/cookiecutter-python-package | 0 | 52783 | """Cookiecutter pre_gen_project hook.
See: https://cookiecutter.readthedocs.io/en/1.7.2/advanced/hooks.html
"""
import os
import shutil
import fileinput
from pathlib import Path
def run():
"""Run pre gen hook functions."""
# NOTE: Do not delete this or the hook will not run.
run()
| 1.445313 | 1 |
taller control repetitivas/ejercicio_10.py | cristianm24/algoritmos-y-programacion- | 0 | 52784 | <reponame>cristianm24/algoritmos-y-programacion-<gh_stars>0
lista=[]
datos=int(input("Ingrese numero de datos: "))
for i in range(0,datos):
alt=float(input("Ingrese las alturas: "))
lista.append(alt)
print("La altura maxima es: ", max(lista)) | 3.84375 | 4 |
tests/test2.py | gaoce/timevis | 1 | 52785 | <filename>tests/test2.py
import os
import os.path
import json
# The folder holding the test data
data_path = os.path.dirname('.')
# Set the temporal config for testing
os.environ['TIMEVIS_CONFIG'] = os.path.join(data_path, 'config.py')
import timevis
app = timevis.app.test_client()
url = '/api/v2/experiment'
resp ... | 1.914063 | 2 |
ops.py | Lornatang/zero2MBGD | 4 | 52786 | """Implement some basic operations of SGD.
"""
####################################################
# Author: <<NAME>><EMAIL>
# License: MIT
####################################################
from activation import *
def random_mini_batches(data, label, batch_size):
""" creates a list of random mini batches fr... | 3.140625 | 3 |
setup.py | rusek/bgjobs | 0 | 52787 | <gh_stars>0
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='bgjobs',
version='0.1',
author='<NAME>',
author_email='<EMAIL>',
description='Run and monitor background jobs',
url='https://github.com/rusek/bgjobs',
license='The MIT License (MIT)',
keywords='b... | 0.9375 | 1 |
tests/test_check_des_points.py | Megscammell/METOD-Algorithm | 0 | 52788 | <reponame>Megscammell/METOD-Algorithm<gh_stars>0
import numpy as np
from hypothesis import given, settings, strategies as st
from metod_alg import objective_functions as mt_obj
from metod_alg import metod_algorithm_functions as mt_alg
from metod_alg import check_metod_class as prev_mt_alg
def calc_minimizer_sev_quad... | 2.6875 | 3 |
camerartc/camerartc.gyp | Teaonly/yacamera | 20 | 52789 | <gh_stars>10-100
#
# Building script for ipcamera application
#
{
'includes': ['build/common.gypi'],
'targets' : [
{
'target_name': 'camerartc',
'type': 'executable',
'include_dirs': [
'../third_party/webrtc/modules/interface',
],
'dependencies': [
... | 1.34375 | 1 |
ejemplos/DHT11/DHT11_Alarma.py | etolocka/pyTrainerBASIC | 0 | 52790 | <reponame>etolocka/pyTrainerBASIC
#Lectura del sensor de temperatura y humedad
#<NAME> 2021
#www.profetolocka.com.ar/pytrainer
#Alarma de temperatura
#Se activa si la temperatura sube "delta" grados
#Toma como valor "Normal" el primer valor leido.
from PyTrainer import *
from time import sleep
temperatur... | 3.125 | 3 |
2021/Day17/probe.py | dh256/adventofcode | 0 | 52791 | <reponame>dh256/adventofcode
# Assumption, target lies to bottom left of start point i.e. x range is +ve and y range is -ve
import re
class Probe:
def __init__(self, filename):
with open(filename,'r') as input_file:
nums = [int(num) for num in re.findall(r'-?\d+', input_file.readline().strip('\... | 3.515625 | 4 |
lib/main.py | Donskov7/toxic_comments | 30 | 52792 | from __future__ import absolute_import
import os.path
import argparse
import logging
import json
from six import iteritems
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.externals import joblib
from keras.models import load_model
from tensorflow.python.client import device_lib
f... | 1.960938 | 2 |
tradingdb/restapi/urls.py | vaporyorg/pm-trading-db | 11 | 52793 | from django.conf.urls import url
from . import views
app_name = "restapi"
timestamp_regex = '\\d{4}[-]?\\d{1,2}[-]?\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}'
urlpatterns = [
url(r'^about/$', views.AboutView.as_view(), name='about'),
url(r'^centralized-oracles/$', views.CentralizedOracleListView.as_view(), name='c... | 1.953125 | 2 |
libscampi/contrib/cms/newsengine/views/helpers.py | azpm/django-scampi-cms | 2 | 52794 | import logging
from django.core.cache import cache
from django.db.models import Q
from libscampi.contrib.cms.communism.models import Javascript, StyleSheet
from libscampi.contrib.cms.communism.views.mixins import html_link_refs
logger = logging.getLogger("libscampi.contrib.cms.newsengine.views")
def story_stylesheet... | 2.015625 | 2 |
yuzu/utils/utils.py | andymitch/yuzu | 0 | 52795 | from inspect import signature
from questionary import Style
from pytz import reference
import math, os, datetime
from typing import Callable
from pandas import DataFrame
############################## CONSTANTS
ROOT_PATH = os.path.expanduser('~') + os.sep + '.yuzu'
STRATS_PATH = ROOT_PATH + os.sep + 'strategies'
ENV_... | 2.15625 | 2 |
brain_flair_segmentation/models/fpn.py | rahul1-bot/Semantic-Segmentation-of-Brain-MRI-Images | 5 | 52796 | from __future__ import annotations
import torch
import torch.nn as nn
from typing import Optional
import warnings
warnings.simplefilter("ignore")
class ConvNormRelu(nn.Module):
def __init__(self, in_channels: int, out_channels: int, upsample: Optional[bool] = False) -> None:
super(ConvNormRe... | 2.515625 | 3 |
pyjs/runners/giwebkit.py | chopin/pyjs | 0 | 52797 | # Copyright (C) 2012 C <NAME> <<EMAIL>>
#
# LICENSE: Apache 2.0 <http://www.apache.org/licenses/LICENSE-2.0.txt>
import os
import sys
import logging
logging.basicConfig(level=logging.INFO)
logging.getLogger(__name__).setLevel(logging.DEBUG)
logger = logging.getLogger(__name__)
import re
from urllib import urlopen
fro... | 2.15625 | 2 |
test/test_kmeans.py | seba2550/project5 | 0 | 52798 | # Write your k-means unit tests here
from cluster import (KMeans, make_clusters)
import pytest
import numpy as np
def test_kmeans_zero():
"""
Start out with a basic test: Model should not run if k = 0
"""
with pytest.raises(ValueError) as error_message:
km = KMeans(k = 0)
assert "K must be greater than 0!" in ... | 3.3125 | 3 |
src/test-capture-hot-point/main.py | kalemena/docker-opencv | 0 | 52799 | import cv2
import time
# Open Camera
camera = cv2.VideoCapture(0)
# Set definition
camera.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 1024)
time.sleep(2)
# camera.set(15, -8.0)
def get_image():
retval, im = camera.read()
return im
def get_warm_up_image():
# Warmup
for i in range(10... | 3.03125 | 3 |