seq_id
stringlengths
4
11
text
stringlengths
113
2.92M
repo_name
stringlengths
4
125
sub_path
stringlengths
3
214
file_name
stringlengths
3
160
file_ext
stringclasses
18 values
file_size_in_byte
int64
113
2.92M
program_lang
stringclasses
1 value
lang
stringclasses
93 values
doc_type
stringclasses
1 value
stars
int64
0
179k
dataset
stringclasses
3 values
pt
stringclasses
78 values
37325991579
import numpy as np from zipline.pipeline import CustomFactor from zipline.pipeline.data import USEquityPricing class CCI(CustomFactor): """ Commodity Channel Index Momentum indicator **Default Inputs:** USEquityPricing.close, USEquityPricing.high, USEquityPricing.low **Default Wi...
ahmad-emanuel/quant_trading_system
Indicators/CCI_self.py
CCI_self.py
py
1,542
python
en
code
1
github-code
36
24019764012
import numpy as np import random from matplotlib import pyplot as plt from matplotlib.patches import Circle from matplotlib.patches import Rectangle # ========================== CONSTANTS ============================ L = 7 SHAPES = ['CUBE', 'SPHERE', 'EMPTY'] COLORS = ['R', 'G', 'B'] def get_shape_pattern(i_start, i_...
evanthebouncy/program_synthesis_pragmatics
version_space/grid.py
grid.py
py
3,191
python
en
code
7
github-code
36
3119120370
''' 参考资料:https://blog.csdn.net/weixin_45971950/article/details/122331273 ''' import cv2 def is_inside(o, i): ox, oy, ow, oh = o ix, iy, iw, ih = i return ox > ix and oy > iy and ox+ow < ix+iw and oy+oh < iy+ih def draw_person(image, person): x, y, w, h = person cv2.rectangle(image, (x, y), (x+w, ...
ryan6liu/demo
facedetect/demo/demo_movedetect_hog_svm.py
demo_movedetect_hog_svm.py
py
1,477
python
en
code
0
github-code
36
1122067056
# Sweet home Alabama class Node: def __init__(self, input_info): self.__info = input_info self.__children = [] # End of Node class class Tree: def __init__(self): self.root = Node( {"id": 1, "Name": "Root", "Family Name": "Root", "Birthday": "Eternal"} ) s...
xgiberish/foundations-cs-python
assignment_05_Dina_Fallah.py
assignment_05_Dina_Fallah.py
py
4,706
python
en
code
0
github-code
36
36956278049
from suite_subprocess import suite_subprocess from contextlib import contextmanager from wtscenario import make_scenarios import json, re, wiredtiger, wttest # Shared base class used by verbose tests. class test_verbose_base(wttest.WiredTigerTestCase, suite_subprocess): # The maximum number of lines we will read f...
mongodb/mongo
src/third_party/wiredtiger/test/suite/test_verbose01.py
test_verbose01.py
py
10,688
python
en
code
24,670
github-code
36
2997295714
# Import the socket module from socket import * # Specify the server's port and IP address port = 53 ip = '127.0.0.1' # Create a UDP socket object clientSocket = socket(AF_INET, SOCK_DGRAM) # Enter an infinite loop to allow the user to enter multiple DNS queries while True: # Get a DNS query from the...
mananmehtaa/DNS
dns_client.py
dns_client.py
py
766
python
en
code
0
github-code
36
44007123128
""" Django default settings for medfinder project. Crate a local.py in this same folder to set your local settings. """ import requests from os import path from django.utils.translation import ugettext_lazy as _ import environ import datetime import django_heroku root = environ.Path(__file__) - 3 e...
ninjadevtrack/medifiner-api
medfinder/settings/default.py
default.py
py
11,988
python
en
code
1
github-code
36
10350771272
import pandas as pd from astroquery.simbad import Simbad import astropy.units as u from astropy.coordinates import SkyCoord from astroquery.gaia import Gaia import numpy as np import argparse import sys from time import sleep parser = argparse.ArgumentParser(description='SIXTH: get information from Simbad and GAIA TAP...
HajimeKawahara/LookAtThis
database/python/siwiyn_parallax.py
siwiyn_parallax.py
py
3,494
python
en
code
0
github-code
36
21883804476
# coding: utf-8 # In[2]: CUDA_VISIBLE_DEVICES = 1 # In[3]: import cv2 import numpy as np import matplotlib.pyplot as plt # In[4]: trainA = [] trainB = [] for i in range(1,701): img = cv2.imread('rain/{}clean.jpg'.format(i)) img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) img = cv2.resize(img,(256,256)) tr...
programmer-770/Image_Deraining_GANs
multi_res_unet-Copy1.py
multi_res_unet-Copy1.py
py
13,838
python
en
code
1
github-code
36
35699327063
import os, json, sys import scrapy def get_report(select): anaul_reports = select.xpath('//*[@id="nav-main-backgroundItem"]/div[@tyc-event-ch="CompangyDetail.nianbao"]/div[2]/div/table/tbody/tr') Ltemp = [] for t in anaul_reports: temp = {} temp['企业年报'] = t.xpath('./td[2]/text()').extract_fi...
elysium-amami/tianyancha_spyder
get_anaul_report.py
get_anaul_report.py
py
451
python
en
code
3
github-code
36
18499875935
def sumar(num1, num2): sum = num1+num2 return sum def multiplicar(num1, num2): return num1*num2 def dividir(num1, num2): try: div = num1/num2 return div except Exception as e: print("Error trying to operate: ", e) return 0 def power(num1, num2): return num1**num2 def salida...
laramruma/Cisco
05_calculator.py
05_calculator.py
py
1,208
python
es
code
0
github-code
36
12782770518
from estimate_explosion_time.shared import get_custom_logger, main_logger_name, pickle_dir import logging logger = get_custom_logger(main_logger_name) logger.setLevel(logging.INFO) logger.debug('logging level is DEBUG') from estimate_explosion_time.analyses.rappid_simulations import rappidDH from estimate_explosion_t...
JannisNe/ztf_SN-LCs-explosion_time_estimation
estimate_explosion_time/analyses/rappid_simulations/complete_analyses.py
complete_analyses.py
py
2,150
python
en
code
0
github-code
36
3020252175
class Solution: def permute(self, nums: List[int]) -> List[List[int]]: if not nums: return [] elif len(nums) == 1: return [nums] else: res = [] for i in range(len(nums)): copy = list(nums) x = copy.pop(i) ...
cdluminate/MyNotes
algo/lc.46.py
lc.46.py
py
462
python
en
code
0
github-code
36
34588733658
import os import atexit import secrets import unittest from functools import wraps import augpathlib as aug from sxpyr import sxpyr from pyontutils.utils import Async, deferred # TODO -> asyncd in future from pyontutils.utils_fast import isoformat from sparcur import exceptions as exc from sparcur.utils import GetTime...
SciCrunch/sparc-curation
test/test_delete.py
test_delete.py
py
32,914
python
en
code
11
github-code
36
34005697680
from socket import socket from squaring_server.server import ADDRESS, PORT, DISCONNECT, decode, encode client = socket() client.connect((ADDRESS, PORT)) while True: msg = input('Your msg: ') client.send(encode(msg)) if msg == DISCONNECT: break print(f'Server: {decode(client.recv(1024))}') cl...
siriusdevs/rpm_chat_2023
squaring_server/client.py
client.py
py
333
python
en
code
1
github-code
36
42600269199
# Script to mess around with User authenticated spotify API # For some reason, cannot authenticate with Google Chrome, so instead use Firefox # http://spotipy.readthedocs.io/en/latest/ from pathlib import Path from spotipy.oauth2 import SpotifyClientCredentials import json import spotipy import time import sys import ...
tkajikawa/spotify_api
spotify_test.py
spotify_test.py
py
2,133
python
en
code
0
github-code
36
16191137869
import datetime from django.utils import timezone from django.core.paginator import Paginator from django.db import transaction from django.db.models import Q from the_mechanic_backend.apps.accounts.models import Store from the_mechanic_backend.apps.stock.models import Brand, BrandModel, Spare, SpareCustomer, SpareOr...
muthukumar4999/the-mechanic-backend
the_mechanic_backend/v0/stock/views.py
views.py
py
23,745
python
en
code
0
github-code
36
8975839640
import cv2 from keras.models import load_model import numpy as np video_capture = cv2.VideoCapture(0) font = cv2.FONT_HERSHEY_SIMPLEX # 读取人脸haar模型 face_detection = cv2.CascadeClassifier('model/face_detection/haarcascade_frontalface_default.xml') # 读取性别判断模型 gender_classifier = load_model('model/gender/simp...
HadXu/machine-learning
face_detection_and_emotion/video_test.py
video_test.py
py
2,250
python
en
code
287
github-code
36
40892450132
import io from pathlib import Path import magic from django.conf import settings from smb.smb_structs import OperationFailure from smb.SMBConnection import SMBConnection def factory(): config = settings.SAMBA connection = SMBConnection( config["user"], config["password"], "abcd", ...
pierrotlemekcho/exaged
sifapi/planning/samba.py
samba.py
py
1,707
python
en
code
0
github-code
36
74205781223
from typing import Iterable, Iterator from PIL import Image # type: ignore def resize_image_to_height(image: Image.Image, height: int) -> Image.Image: return image.resize(size=(int(image.width * (height / image.height)), height)) def concat_paired_images( left_image: Image.Image, right_image: Image.Image,...
yskuniv/python-simple-web-counter
simple_web_counter/utils/image/image.py
image.py
py
1,340
python
en
code
0
github-code
36
34998622413
import sys for line in sys.stdin: # print(line) # break arr=[int(x) for x in line.strip().split()] # print(arr) if arr[0]==0: for c in range(arr[4]): print("%s\t%s" % ((arr[1], c, arr[2] ), arr[3])) if arr[0]==1: for a in range(arr[4]): print("%s\t%s" % (...
keshavbnsl102/DS-assign2
2019101019_ass2/2019101019_1/mapper/mapper.py
mapper.py
py
378
python
en
code
0
github-code
36
72079445545
# 17124번 # 정수 배열 A와 B가 있다. A는 총 n개의 서로 다른 양의 정수를 포함하고 B는 총 m개의 서로 다른 양의 정수를 포함한다. A,B를 이용해서 길이가 n인 새로운 배열 C를 만들어보자. # 1 : C[i]는 배열 B에 있는 값중 A[i에 가장 가까운 값(절대값 차이가 가장 작은값)으로 정의된다. # 2 : 만약 이 조건을 만족하는 값들이 여럿 있는 경우, 그 중 가장 크기가 작은 값으로 정의된다. # 예를 들어, ,A=[20,5,14,9] 그리고 B=[16,8,12]라고 해보자 # C[1] = 16이다 - 왜냐하면 B[1] = 16이 A[1]=2...
kkhhkk/Study-Algorithms
backjoon/17124.py
17124.py
py
2,335
python
ko
code
0
github-code
36
646138808
#Lista de Exercício 1 - Questão 5 #Dupla: 2020314273 - Cauã Alexandre Torres de Holanda e 2021327294 - Kallyne Ferro Veiga #Disciplina: Programação Web #Professor: Ítalo Arruda #5.Faça um Programa que converta metros para centímetros. class ConversorMedidas: def __init__(self, valor): self.valor = valor ...
caalexandre/Revisao-Python-IFAL-2023-Caua-e-Kallyne
Lista1/l1q5KC-523.py
l1q5KC-523.py
py
901
python
pt
code
0
github-code
36
16173542417
# pylint: disable=missing-docstring """This is a script to test the RecurrentEncoder module.""" import pickle import pytest import torch import torch.nn as nn from metarl.torch.embeddings import RecurrentEncoder class TestRecurrentEncoder: """Test for RecurrentEncoder.""" # yapf: disable @pytest.mark.p...
icml2020submission6857/metarl
tests/metarl/torch/embeddings/test_recurrent_encoder.py
test_recurrent_encoder.py
py
2,849
python
en
code
2
github-code
36
42119246092
import pygame from settings import Settings from pygame.sprite import Sprite class Ship(Sprite): def __init__(self, ai_game): """initialize the ship and set its starting position""" super().__init__() self.screen = ai_game.screen self.settings = ai_game.settings self.screen_rect = ai_game.screen.get_rect()...
SylvainAroma/Alien-Invasion
ship.py
ship.py
py
1,202
python
en
code
0
github-code
36
33537990133
from tree import Tree #Tree tests complete t = Tree(3) print(t) a = t.addNode(0,4) b = t.addNode(0,5) c = t.addNode(a,6) d = t.addNode(a,7) e = t.addNode(d,8) print(t) print("Path to e:") p = t.pathToNode(e) for i in p: print("\t",t.getData(i)) print("Path to c") p = t.pathToNode(c) for i in p: print("\t",t.g...
zanda8893/Student-Robotics
code/tree-test.py
tree-test.py
py
400
python
en
code
0
github-code
36
73335007463
from datetime import datetime from .setup import config, logger def bibcodes(): try: with open(config.get('CLASSIC_CANONICAL_FILE'), "r") as f: bibcodes = [line.strip() for line in f] except: logger.exception("Unable to retreive bibcodes from classic") return [] else: ...
adsabs/ADSStatsCollector
statscollector/classic.py
classic.py
py
2,065
python
en
code
0
github-code
36
34076302112
from sklearn.base import BaseEstimator, TransformerMixin import numpy as np import sys ''' The key concept in CSP is to find a set of spatial filters (components) that optimally discriminate between the two classes. These filters are represented by the eigenvectors obtained in the 'fit' method. When you apply the CS...
artainmo/total_perspective_vortex
processing_EEGs_lib/dimensionality_reduction_algorithm.py
dimensionality_reduction_algorithm.py
py
4,957
python
en
code
0
github-code
36
33571337998
#!/usr/bin/env python3 from subprocess import Popen, PIPE, STDOUT from threading import Thread from time import sleep import logging import os import sys # Very simple tee logic implementation. You can specify shell command, output # logfile and env variables. After TeePopen is created you can only wait until # it f...
ByConity/ByConity
tests/ci/tee_popen.py
tee_popen.py
py
2,012
python
en
code
1,352
github-code
36
28890197379
"""PDB dataset loader.""" import tree import numpy as np import torch import pandas as pd import logging import random import functools as fn from torch.utils import data from data import utils as du from openfold.data import data_transforms from openfold.np import residue_constants from openfold.utils import rigid_ut...
blt2114/twisted_diffusion_sampler
protein_exp/data/pdb_data_loader.py
pdb_data_loader.py
py
10,693
python
en
code
11
github-code
36
40435532047
import unittest from src.entities.event import Event from src.repos.in_memory.data_store import DataStore from src.repos.in_memory.in_memory_event_repo import InMemoryEventRepo class TestInMemoryEventRepo(unittest.TestCase): def setUp(self): data_store = DataStore() self.event_repo = InMemoryEven...
mchlzhao/discord-bingo-bot
tests/unit/repos/in_memory/test_in_memory_event_repo.py
test_in_memory_event_repo.py
py
1,392
python
en
code
0
github-code
36
42998147166
from __future__ import annotations import time from datetime import date, datetime, timedelta from logging import getLogger from time import struct_time from typing import Any, Callable import pytz from .compat import IS_WINDOWS from .constants import is_date_type_name, is_timestamp_type_name from .converter import ...
snowflakedb/snowflake-connector-python
src/snowflake/connector/converter_snowsql.py
converter_snowsql.py
py
7,534
python
en
code
511
github-code
36
24369028230
import os import time import argparse from datetime import datetime from utils.CpuMonitor import CpuMonitor from utils.GpuMonitor import GpuMonitor from utils.Recoder import Recoder from utils.Printer import print_info, print_err, print_warn def get_args(): parser = argparse.ArgumentParser() parser.add_argume...
Huang-Junchen/hardware-tester
no_gui.py
no_gui.py
py
2,093
python
en
code
0
github-code
36
73694828905
# This program is a print queue simulator. # The program reads instructions off of a web page # pertaining to addition, removal, and printing of documents # as well as showing contents of the print queue # Assignment 2 for CISC 121, Summer 2017 # Author: Andy Wang import urllib.request ''' Reads instructions from a ...
AndyHFW/CISC-121-Assignments
W3 - Print Queue Simulator.py
W3 - Print Queue Simulator.py
py
6,842
python
en
code
0
github-code
36
14913237067
from __future__ import annotations import datetime from dataclasses import dataclass, field import random from typing import List, Dict, Any from chess_manager.M import turn_model MAX_STR_LEN = 122 def check_valid_int(user_int_input: Any) -> bool: """ Vérifie si l'input de l'utilisateur est un int valide. """ ...
AntoineArchy/Chessmanager
chess_manager/M/tournament_model.py
tournament_model.py
py
4,751
python
en
code
null
github-code
36
15491681290
# App Libraries import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State import dash_bootstrap_components as dbc import plotly.graph_objs as go import base64 # Replication strategy library from Asian_Option_CRR import * # Input of rep strat ...
MichelVanderhulst/web-app-asian-option-crr
app.py
app.py
py
33,229
python
en
code
0
github-code
36
70970695463
# -*- coding: utf-8 -*- """ Created on Fri Dec 4 11:20:09 2020 @author: KANNAN """ from flask import Flask, render_template, request import emoji #import sklearn import pickle model = pickle.load(open("diabetes_logreg.pkl", "rb")) app = Flask(__name__) @app.route('/') def home(): return ...
GuruYohesh/ML
Diabetes Prediction/Diabetes_app.py
Diabetes_app.py
py
3,799
python
en
code
0
github-code
36
41587212510
import os import numpy as np import warnings from equilib import equi2cube import cv2 import torch from PIL import Image def main(): image_path = "./data/images/000001.jpg" equi_img = Image.open(image_path) img_mode = equi_img.mode equi_img = np.asarray(equi_img) print("equi_img: ", equi_img.s...
motoki/nsworks
src/sphere2cube.py
sphere2cube.py
py
1,211
python
en
code
0
github-code
36
29402978628
from users import User from userfile import UserFile from places import Places from get_poi import TripAdvisorApi from poi_data import PoiData # Initialise user object and conduct API_key_check # If no API key, user given instructions to subscribe. # API_key saved as a persistent environment variable in src/.env and #...
ashley190/travelapp
src/main.py
main.py
py
1,541
python
en
code
0
github-code
36
35099642670
from django.contrib.auth.models import Group from mf.crud.models import Dolar, HistoryOperations, Permisology from mf.user.models import User from django.utils import timezone from datetime import date, datetime, timedelta def convertToDecimalFormat(n): return n.replace('.', '').replace(',', '.') def get_dollar()...
isela1998/facebook
app/mf/crud/functions.py
functions.py
py
2,923
python
en
code
0
github-code
36
71335908263
from os import * from sys import * from collections import * from math import * ''' Following is the Binary Tree node structure: class TreeNode: def __init__(self, data=0, left=None, right=None): self.data = data self.left = left self.right = right ''' def getInOrd...
architjee/solutions
CodingNinjas/inorder traversal without recursion.py
inorder traversal without recursion.py
py
680
python
en
code
0
github-code
36
74160075943
''' l = [i for i in range(len_string - len_sub + 1) if string[i:i + len_sub] == sub_string] 1.If you want to find the first index of the substring in the original string l[0] is your destination 2.If you want to find every index of the snstring in the original l[::] is what you want 3.If you want the number of times ...
CodingProgrammer/HackerRank_Python
(All)Find_a_string.py
(All)Find_a_string.py
py
1,362
python
en
code
0
github-code
36
31700687852
from __future__ import unicode_literals import os import shutil import unittest from doctpl.core import TemplateInfo class TemplateInfoTest(unittest.TestCase): @classmethod def setUpClass(cls): # setup TemplateInfo. TemplateInfo.CONFIG_DIR = os.path.join(os.getcwd(), '.doctpl') Templa...
huntzhan/DocTemplate
test.py
test.py
py
1,848
python
en
code
0
github-code
36
36278744993
import re from pprint import pprint import csv from decorator import to_log if __name__ == '__main__': # читаем адресную книгу в формате CSV в список contacts_list with open("phonebook_raw.csv", encoding='utf-8') as f: rows = csv.reader(f, delimiter=",") contacts_list = list(rows) # rewrit...
OysterLover/regex_decorated
main.py
main.py
py
1,633
python
en
code
0
github-code
36
40451279379
import random def gtn(): sec_num = random.randint(1, 1000) no_of_tries = 0 print("Welcome to Guess The Number Game!") print("I'm thinking of a number between 1 and 1000. Can you guess it?") while True: user_guess = int(input("Enter your guess: ")) no_of_tries += 1 if us...
Jayasri2021/Guess_the_number_game
function.py
function.py
py
577
python
en
code
1
github-code
36
3761949834
import cv2 import numpy as np img2 = cv2.imread("images.jpg") img1 = cv2.imread("new quantum.PNG") rows, cols, channels = img2.shape # Reading image details roi = img1[0:rows, 0:cols] img2g = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) # converting to grayscale # defining mask , makes our logo black and background wh...
AirbotsBetaProject/Day-6
D6-04Dheeraj/Source Code/adding_logo_with_no_background.py
adding_logo_with_no_background.py
py
929
python
en
code
0
github-code
36
40252587840
while(1) : data = list(map(int, input().split())) data.sort() if (data[0]==0) and (data[1]==0) and (data[2]==0) : break else : if data[2]**2 == data[0]**2 + data[1]**2 : print('right') else : print('wrong')
parksjsj9368/TIL
ALGORITHM/BAEKJOON/SOURCE/15. PrimeNumber(소수 판별)/4. 직각삼각형.py
4. 직각삼각형.py
py
283
python
zh
code
0
github-code
36
34108283515
A = [int(i) for i in open('26.txt') if ' ' not in i] A.sort() s = k = 0 while s < 8200 and k < 970: s += A[k] k += 1 s -= A[k-1] + A[k-2] maxi = 0 for i in range(k-2, len(A)): if s + A[i] > 8200: break if maxi < A[i]: maxi = A[i] print(k-1, maxi)
alex3287/ege
2021/demo_26.py
demo_26.py
py
278
python
en
code
0
github-code
36
37634246750
# A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words such that: # The first word in the sequence is beginWord. # The last word in the sequence is endWord. # Only one letter is different between each adjacent pair of words in the sequence. # Every word in th...
sunnyyeti/Leetcode-solutions
127 Word Ladder.py
127 Word Ladder.py
py
2,240
python
en
code
0
github-code
36
39803390183
from homepageapp.models import ModelsNewSQL02Model from django.conf import settings from django.http import JsonResponse from django.core.files.storage import FileSystemStorage import os from django.shortcuts import get_object_or_404, render from django.core.paginator import Paginator # repairOrder model was added on 1...
zjgcainiao/new_place_at_76
appointments/views.py
views.py
py
12,477
python
en
code
0
github-code
36
27047741058
""" @author Joe This file contains some pretty functions """ def get_top_k_indexes_of_list(target_list, k, is_max=True, min_value=None): """ get the top k indexes of elements in list Example: Problem: I have a list say a = [5,3,1,4,10], and I need to get a index of top two values of the ...
JoeZJH/JoePyLibs
general/list_utils.py
list_utils.py
py
1,495
python
en
code
0
github-code
36
2214688634
import argparse from alarm import __version__ from alarm.constants import ALLOWED_EXTENSIONS, ON_WINDOWS def parse_args(args): """Passing in args makes this easier to test: https://stackoverflow.com/a/18161115 """ parser = argparse.ArgumentParser( description="Play an alarm after N minutes", ...
hobojoe1848/pybites-alarm
alarm/cli.py
cli.py
py
2,095
python
en
code
null
github-code
36
31619170189
import pandas as pd import xml.etree.ElementTree as ET # Load the XML data tree = ET.parse('statement_short.xml') root = tree.getroot() # Define a function to extract data from the XML elements def extract_data(elem): data = {} for child in elem: if len(child) == 0: data[child.tag] = chil...
dochaauch/Tools_for_buh
xml_pank/xml1.py
xml1.py
py
627
python
en
code
0
github-code
36
70973655465
import torch import torch.nn as nn class ChannelAttention(nn.Module): def __init__(self, in_planes, ratio=16): super(ChannelAttention, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.max_pool = nn.AdaptiveMaxPool2d(1) self.fc = nn.Sequential(nn.Conv2d(in_planes, in_p...
AAleka/Cycle-CBAM-and-CBAM-UNet
UNet/model.py
model.py
py
3,806
python
en
code
7
github-code
36
4738737155
import torch import torch.nn as nn import numpy as np from torch.autograd import Variable import math import time import multiprocessing from torch.nn.parameter import Parameter from torch.nn.modules.module import Module import torch.nn.functional as F import copy class conGraphConvolutionlayer(Module): def __i...
luoyuanlab/stdgcn
STdGCN/GCN.py
GCN.py
py
9,989
python
en
code
2
github-code
36
10387196560
from setuptools import setup, find_packages from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='pysnippets', version='0.1.0', descriptio...
gongzhitaao/snippets
pysnippets/setup.py
setup.py
py
1,010
python
en
code
0
github-code
36
71251001
import torch import torch.nn as nn import torch.utils.data as Data from torch.autograd import Variable import torch.nn.functional as F import time import numpy as np assert F import csv,random from imblearn.over_sampling import SMOTE class Datamanager(): def __init__(self): self.dataset = {}...
b04901056/dsa2017
qualcomm/nn.py
nn.py
py
17,265
python
en
code
0
github-code
36
3169544582
# ported from uniborg thanks to @s_n_a_p_s , @r4v4n4 , @spechide and @PhycoNinja13b #:::::Credit Time:::::: # 1) Coded By: @s_n_a_p_s # 2) Ported By: @r4v4n4 (Noodz Lober) # 3) End Game Help By: @spechide # 4) Better Colour Profile Pic By @PhycoNinja13b import asyncio import base64 import os import random import shut...
rockzy77/catusertbot77
userbot/plugins/autoprofile.py
autoprofile.py
py
14,466
python
en
code
2
github-code
36
20271187203
''' This module provides management methods for the pygame screen ''' import sys import pygame class MetaGame(type): ''' the metaclass for the game class - this implements classproperties on Game ''' @property def clock(cls): ''' produce the game clock ''' return c...
oaken-source/pyablo
pyablo/game.py
game.py
py
2,780
python
en
code
2
github-code
36
34005743410
from torch.utils.data import * from imutils import paths import numpy as np import random import cv2 import os CHARS = ['京', '沪', '津', '渝', '冀', '晋', '蒙', '辽', '吉', '黑', '苏', '浙', '皖', '闽', '赣', '鲁', '豫', '鄂', '湘', '粤', '桂', '琼', '川', '贵', '云', '藏', '陕', '甘', '青', '宁', '新', '0', '1'...
sirius-ai/LPRNet_Pytorch
data/load_data.py
load_data.py
py
2,544
python
en
code
759
github-code
36
138761933
import json def json_read(path): ''' Parses file of json type. ''' with open(path, 'r', encoding='utf-8') as f: text = json.load(f) return text def conti_with_count(): names = json_read('names.json') continents = json_read('continent.json') result = {} for country in con...
AndriiTurko/homeworks_programming
json_make_dict.py
json_make_dict.py
py
534
python
en
code
0
github-code
36
8827426863
from __future__ import absolute_import, division, print_function import os from setuptools import setup HERE = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(HERE, 'README.rst')) as f: README = f.read() setup(name='marv', version='3.2.0', description='MARV framework', long_de...
ternaris/marv
setup.py
setup.py
py
2,262
python
en
code
3
github-code
36
11604655493
import ipaddress import json import os import uuid import encryption_helper import phantom.app as phantom import phantom.rules as ph_rules import phantom.utils as ph_utils import requests import xmltodict from phantom.action_result import ActionResult from phantom.base_connector import BaseConnector from requests.auth...
splunk-soar-connectors/office365
ewsonprem_connector.py
ewsonprem_connector.py
py
129,772
python
en
code
3
github-code
36
4440001992
import re import six import time import inspect import importlib from .dataType import * import spannerorm.base_model from datetime import date from .relation import Relation from google.api_core.datetime_helpers import DatetimeWithNanoseconds class Helper(object): @classmethod def is_property(cls, v): ...
sijanonly/spanner-orm
spannerorm/helper.py
helper.py
py
19,932
python
en
code
0
github-code
36
2939710815
#!/usr/bin/env python # """ Utilitities used by our app. We want to separate them from main.app so we can use them in other modules without running the code in app. """ # system imports # from hashlib import sha256 #################################################################### # def short_hash_email(email: dict...
scanner/postmark_webhooks
app/utils.py
utils.py
py
937
python
en
code
0
github-code
36
14991911664
from os import environ import uuid import logging import json # file_name = environ('log_file_name') file_name = 'app.log' class ModelLog: def __init__(self): ModelLog.load_create() @staticmethod def request_uid(use_case): """ Generate a unique unicode id for the object. The def...
ahmadaneeque/my-code
kubectl_docker/model-update-framework/re-train/mlog.py
mlog.py
py
1,357
python
en
code
0
github-code
36
12626651053
# 2. Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя: имя, фамилия, год рождения, # город проживания, email, телефон. Функция должна принимать параметры как именованные аргументы. # Реализовать вывод данных о пользователе одной строкой. def user_data_input(): user_data_dict =...
AlexProsku/HW_Python
Lesson_3/task_2.py
task_2.py
py
1,702
python
ru
code
0
github-code
36
20025415289
#Develop a menu-based python program #menu items: 1. Addition 2. Subtraction 3. Multiplication 4. Division 5. Average 6. Find maximum 7. Find minimum import sys def PrintMenu(): print("Menu") print("1. Addition") print("2. Subtraction") print("3. Multiplication") print("4. Division") pr...
sohelbaba/Python
Practical 3/p1.py
p1.py
py
1,808
python
en
code
0
github-code
36
43288963064
from ctypes import * import sys import pytest @pytest.fixture def dll(sofile): return CDLL(str(sofile), use_errno=True) def test_char_result(dll): f = dll._testfunc_i_bhilfd f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double] f.restype = c_char result = f(0, 0, 0, 0, 0, 0) assert...
mozillazg/pypy
extra_tests/ctypes_tests/test_functions.py
test_functions.py
py
7,258
python
en
code
430
github-code
36
21025390512
from db import db from db.db import AuthorEntity def save(author: AuthorEntity): with db.tiktok_db: db.tiktok_db.connect(reuse_if_open=True) author.save() def add_authors(authors: list[str], category: int): with db.tiktok_db: db.tiktok_db.connect(reuse_if_open=True) authors_...
MAG135/robot
repositories/author_repository.py
author_repository.py
py
2,671
python
en
code
0
github-code
36
6753606270
from flask import Flask # create Flask app object and init all modules def create_app(config_object): from .main import create_module as main_create_module from app.api.v1 import create_module as api_v1_create_module # Init APP app = Flask(__name__) app.config.from_object(config_object) # In...
artem-shestakov/PIN_and_Hash
app/__init__.py
__init__.py
py
545
python
en
code
0
github-code
36
27770460762
import os, sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../fastapi_basic'))) from fastapi.testclient import TestClient from app import app from controllers.models.test import Calculate_Data from services.auth import service_auth client = TestClient(app) access_token = service_auth....
jinybear/fastapi_basic
tests/test_controllers.py
test_controllers.py
py
1,030
python
en
code
0
github-code
36
43156875927
# 성적 계산 # minso.jeong@daum.net ''' 문제링크 : https://www.codeup.kr/problem.php?id=1127 ''' score = 0 for _ in range(3): p, n = input().split() score += float(p) * int(n) print('%.1f' %score)
minssoj/Learning_Algorithm_Up
code/1127.py
1127.py
py
211
python
en
code
0
github-code
36
18567314308
# scrape British Columbia acupuncturists number_of_rows = 2090 # set this before running delim = "\t" from urllib.request import urlopen import time def SetHomeDirectory(): import os os.chdir("C:\\Users\\Matt Scandale\\OneDrive - Council of Better Business Bureaus, Inc\\Desktop") SetHomeDire...
mscandale-iabbb/research_public
sample_iabbb_bots/scrape_bc_acupuncturists_shared.py
scrape_bc_acupuncturists_shared.py
py
4,974
python
en
code
0
github-code
36
1985519466
#imports libary needed to access photo from PIL import Image #Opens and loads the image that it processes you have to change this to what your picture is called. money = Image.open("money.png") money = money.convert("RGBA") pixels = money.load() #Sets two vairables for the loops that go through each pixel ...
koanarec/recolorimagepython
recolor.py
recolor.py
py
730
python
en
code
0
github-code
36
23618566810
""" Makes it easier to create pretty representations """ def uirepr(object, name=None, defaults=None, exclude=None): """ Returns string of representation. """ if not hasattr(object, '__ui_repr__'): return repr(object) imports = {} collected = object.__ui_repr__(imports, name, defaults, exclude) result = '' ...
mdavezac/LaDa
tools/uirepr.py
uirepr.py
py
3,584
python
en
code
5
github-code
36
37466207832
from concurrent import futures import sys import grpc import summary_api_pb2 import summary_api_pb2_grpc import pandas as pd from summary_statistics import calculate_frequency class DocumentSummarizer(summary_api_pb2_grpc.DocumentSummarizerServicer): def SummarizeDocument(self, request, context): ...
doralaura24/visma
summary-statistics-service/summary/server.py
server.py
py
1,856
python
en
code
0
github-code
36
72640523303
#! /usr/bin/env python3 """ --- besspin.py is the main BESSPIN-Tool-Suite program. All documentation and features are based on solely executing this file. Please do not execute any other file. --- usage: besspin.py [-h] [-c CONFIGFILE | -cjson CONFIGFILESERIALIZED] [-w WORKINGDIRECTORY] [-l LOGFILE...
GaloisInc/BESSPIN-Tool-Suite
besspin.py
besspin.py
py
8,521
python
en
code
5
github-code
36
21720674809
''' you are given a string made up of parenthesis only.Your task is to check whether parenthesis are balanced or not.If they are balanced print 1 else print 0 Input Description: You are given a string ‘s’ Output Description: Print 1 for balanced and 0 for imbalanced Sample Input : {({})} Sample Output : 1 ''' n...
Aishwarya0206/Codekata
Strings/13.py
13.py
py
775
python
en
code
0
github-code
36
34821763042
sample_input = [[1, 5], [1, 2, 1], [1, 3, 2], [1, 4, 3], [3, 5, 5], [4, 3, 4], [4, 5, 1]] final_input = [[2, 4], [1, 6, 8], [1, 31, 2], [1, 2, 16], [31, 33, 2], ...
Bodziowy/Party-Parrot-Puzzles
Task06.py
Task06.py
py
2,285
python
en
code
0
github-code
36
36720262828
import time import uuid class stagedfiles: """ This type, when filled out as staged_files(n) or mod_n for some integer n, will watch the project that is in its input for consumed (staged) files and deliver them on each iteration """ def __init__(self, cs, samhandle, dbhandle): ...
fermitools/poms
webservice/split_types/stagedfiles.py
stagedfiles.py
py
2,089
python
en
code
0
github-code
36
28982674293
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: if len(s) < 10: return [] tenLengthSet = set() ans = set() for i in range(len(s)-9): cur = s[i:i+10] if( cur in tenLengthSet ): ...
Kirroneku/leetcode_practice
Done Randomly/Bit Manipulation/find_repeated_dna_fast.py
find_repeated_dna_fast.py
py
451
python
en
code
0
github-code
36
36395259809
import os import os.path as osp import random def load_class_idx_to_label(txt_path='./resource/imagenet1000_clsidx_to_labels.txt'): txt_str = '' with open(txt_path, 'r') as fio: for line in fio.readlines(): txt_str += line.strip('\n\r') return eval(txt_str) def load_folder_idx_to_lab...
hyk1996/Rank-Diminishing-in-Deep-Neural-Networks
core/utils/imagenet.py
imagenet.py
py
1,242
python
en
code
4
github-code
36
8298790752
# from https://github.com/iskandr/fancyimpute import numpy as np from sklearn.utils.extmath import randomized_svd from sklearn.utils import check_array import warnings F32PREC = np.finfo(np.float32).eps from joblib import Memory memory = Memory('cache_dir', verbose=0) def soft_impute_rank(X_obs, n_folds = 5, max...
TwsThomas/miss-vae
softimpute.py
softimpute.py
py
16,429
python
en
code
2
github-code
36
43639564307
#!/usr/bin/env python # coding=utf-8 class Item(): def __init__(self, key = None): self.key = key self.nextItem = None class Stack(): def __init__(self): self.head = None def push(self, item): if self.head is None: item.nextItem = None self.head ...
blry/CLRS
C10-Elementary-Data-Structures/10_2_2_stack_using_linked_list.py
10_2_2_stack_using_linked_list.py
py
843
python
en
code
0
github-code
36
70031496105
from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import pickle import store_database d = store_database.d class TodayStores(QWidget): def __init__(self): super().__init__() self.set_ui() def set_ui(self): self.setWindowTitle("Today's Store...
cammy-mun/Canteen-Food-Menu
DSAI1_Lee_Luo_Mun/TodayStores.py
TodayStores.py
py
12,873
python
en
code
0
github-code
36
73520890983
palavra = str(input('Digite a frase: ')) palavra = palavra.strip().upper() analise = palavra.split() analise = ''.join(analise) inverso = '' for letra in range(len(analise)-1, -1, -1): inverso += analise[letra] print(analise) print(inverso) if (analise == inverso): print('\nTEMOS UM PALINDROMO') else: p...
luks-rossato/curso-Python3
Exercicios propostos/Ex 053 - Palíndromo].py
Ex 053 - Palíndromo].py
py
355
python
pt
code
0
github-code
36
17964305010
from sklearn.model_selection import train_test_split from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import f_classif from sklearn.feature_selection import chi2 import numpy as np import argparse import sys import os from sklearn.svm import SVC from sklearn.metrics import confusion_matr...
Yangnnnn/Identifying-political-persuasion-on-Reddit
code/a1_classify.py
a1_classify.py
py
15,122
python
en
code
0
github-code
36
30382531462
import os import random import numpy as np import pandas as pd from sklearn.model_selection import train_test_split import torch from torch.utils.data import TensorDataset import torch.nn as nn import torch.nn.functional as F import os from transformers import logging import warnings import yaml from pathlib impor...
XiaoyanAmy/HLT_Coursework
src/util.py
util.py
py
2,186
python
en
code
0
github-code
36
14859359219
''' Created on 2017��3��23�� @author: gb ''' import sys import os import jieba import gensim,logging import sys def savefile(savepath,content): fp=open(savepath,"w") fp.write(content) fp.close() def readfile(path): fp=open(path,"r") content=fp.read() fp.close() return content ...
guob1l/gensimW2V
jieba.py
jieba.py
py
966
python
en
code
4
github-code
36
72002642984
import os.path from django.http import HttpResponse from cmis_storage.storage import CMISStorage def get_file(request, path): """ Returns a file stored in the CMIS-compatible content management system :param path: The full path of the file within the CMS """ _, filename = os.path.split(path) ...
JoseTomasTocino/cmis_storage
cmis_storage/views.py
views.py
py
547
python
en
code
1
github-code
36
6044301694
import socket, threading HEADER = 64 #Constante para número de bytes por mensagem FORMAT = 'utf-8' #Constante para decodificar mensagens DISCONNECT_MESSAGE = '!disconnect' #Constante para desconectar o cliente print("## SETUP DO SERVIDOR ##") ip = input("INSIRA UM ENDEREÇO DE IP OU 'localhost'\n") port = 80 server = ...
vnvz/App-Cliente-Servidor
serverTCP.py
serverTCP.py
py
2,720
python
pt
code
0
github-code
36
72516589224
# settings.py import os from os.path import join, dirname from dotenv import load_dotenv dotenv_path = join(dirname(__file__), '.env') load_dotenv(dotenv_path) # Accessing variables. NUM_REQUESTS = os.getenv('NUM_REQUESTS') URL = os.getenv('URL') SECRET = os.getenv('SECRET') SLEEP_SECONDS = os.getenv('SLEEP_SECONDS')...
blainemincey/generateApiRequests
settings.py
settings.py
py
470
python
en
code
0
github-code
36
38790064496
""" This script shows how pedestrian detections and robot data can be converted to a spatio-temporal grid The output data of this script can then be used to train a CoPA-Map model """ import pandas as pd from copa_map.model.Gridifier import Gridifier, GridParams from copa_map.model.InitInducing import InducingInitial...
MarvinStuede/copa-map
src/copa_map/examples/01_atc_gridify_data.py
01_atc_gridify_data.py
py
4,685
python
en
code
0
github-code
36
6722106434
from PyQt4 import QtGui as qg, QtCore as qc try: _fromUtf8 = qc.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s class ListWidgetController: def __init__(self, widget): self.widget = widget def show_in_gadgets_list(self, gadgets): self.widget.clear() ...
Tanesh1701/ropa
ropa/gui/controller/list_widget_controller.py
list_widget_controller.py
py
710
python
en
code
null
github-code
36
16874206716
from utils.rabbit_controller import RabbitMqController from utils.tools import Tools from utils.verifier import Verifier from utils.watcher import Watcher if __name__ == "__main__": """ This is the SAAS Client! Results will be under the server http://3.73.75.114:5000/ 1. Get all md5 of...
Oreldm/RuntimeDefender
saas/client.py
client.py
py
1,910
python
en
code
0
github-code
36
25810655781
from datetime import datetime import unittest from mongoengine import Document, StringField, IntField from eve.exceptions import SchemaException from eve.utils import str_to_date, config from eve_mongoengine import EveMongoengine from tests import BaseTest, Eve, SimpleDoc, ComplexDoc, LimitedDoc, WrongDoc, SETTINGS...
MongoEngine/eve-mongoengine
tests/test_mongoengine_fix.py
test_mongoengine_fix.py
py
3,618
python
en
code
39
github-code
36
29834508518
from apps.maps.dto.map import MapDto from apps.maps.factory.choice import ChoiceFactory from apps.maps.models.map import Map class MapFactory: def __init__(self): self.dto = MapDto self.choice_factory = ChoiceFactory() def dto_from_model(self, item: Map) -> MapDto: return self.dto( ...
yellowpearl/realtor
src/apps/maps/factory/map.py
map.py
py
535
python
en
code
0
github-code
36
9328318313
import pandas as pd import matplotlib.pyplot as plt def gerar_grafico_tempos(caminho_entrada): df = pd.read_csv(caminho_entrada, delimiter=';') labels = ['Média', 'Mediana'] values = [df['Média'].iloc[0], df['Mediana'].iloc[0]] plt.bar(labels, values, color=['blue', 'green']) plt.title('Média e ...
ClaudioJansen/GitHub-Script
Tis 06/correction_time/graphic_generator.py
graphic_generator.py
py
645
python
pt
code
0
github-code
36
72240477223
from LinkedList import LinkedList from LinkedList import build_ll_from_lst from Node import Node """ Return data in Nth node from the end head could be None as well for empty list # Approaches 1) Use a queue to keek track of last pos_from_tail values, then dequeue at end 2) Use list, then return list[len(list)-pos_fr...
bfortuner/problems
lists/python/nth_node_from_tail.py
nth_node_from_tail.py
py
938
python
en
code
37
github-code
36