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
69096792
################################################## # pygame - 마우스 이벤트(MOUSEMOTION) 이해 # # 참고 사이트 # https://pg.org # https://pg.org/docs/ ################################################## import pygame as pg import sys import time # 초기화 작업 # 반드시 주어진 함수이름과 순서를 지켜야 함. pg.init() screen = pg.display.set_mode((400, 300...
null
1006.py
1006.py
py
885
python
en
code
null
code-starcoder2
51
89133984
#чоловіки жінки ієрархічна import pandas as pd import matplotlib.pyplot as plt import scipy.cluster.hierarchy as sch from sklearn.cluster import AgglomerativeClustering data = pd.read_csv('1.csv', sep=';') print(data.head()) X = data.iloc[:, [0, 5, 6]].values #дендограма dendogram = sch.dendrogram(sch.linkage(X[:,...
null
2.py
2.py
py
1,307
python
en
code
null
code-starcoder2
51
220999683
import psutil as ps import time import netifaces class NetMonitor: def __init__(self): self._last_stat = None self._last_time = None def _get_net_io_counters(self): counters = ps.net_io_counters(pernic=True) ret = dict() for k, v in counters.items(): ret[...
null
statbrowser/monitor/network.py
network.py
py
1,655
python
en
code
null
code-starcoder2
51
328569008
# -*- coding: utf-8 -*- """ Created on Sat Apr 18 16:59:20 2020 @author: Jieyun Hu """ # This file includes preparing the data, encoding and modeling # To predict two type of activity. Click = 0 , Swipe = 1. # put this file outside the filtered_traces folder import os import json from matplotlib import py...
null
encoding_modeling.py
encoding_modeling.py
py
6,613
python
en
code
null
code-starcoder2
51
574894510
from xai.brain.wordbase.verbs._participate import _PARTICIPATE #calss header class _PARTICIPATED(_PARTICIPATE, ): def __init__(self,): _PARTICIPATE.__init__(self) self.name = "PARTICIPATED" self.specie = 'verbs' self.basic = "participate" self.jsondata = {}
null
xai/brain/wordbase/verbs/_participated.py
_participated.py
py
273
python
en
code
null
code-starcoder2
51
22089702
import sys import time import copy from selenium import webdriver from selenium.common.exceptions import NoSuchElementException def scroll_bottom(browser, cycle): # scroll to bottom to get more URLs script = "var q=document.documentElement.scrollTop={}" scroll = 10000 for i in range(cycle): js = script.format(sc...
null
scrapy.py
scrapy.py
py
1,817
python
en
code
null
code-starcoder2
51
28042027
from flask_app.config.mysqlconnection import connectToMySQL from flask import flash import re EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') class Recipe: def __init__( self , data ): self.id = data['id'] self.name = data['name'] self.description = data['descr...
null
flask_mysql/validation/recipes/flask_app/models/recipe.py
recipe.py
py
3,191
python
en
code
null
code-starcoder2
50
359088689
import json def run(data, parameters): listDictionaries = json.loads(data) minVehicleCount = int(parameters['minVehicleCount']) maxVehicleCount = int(parameters['maxVehicleCount']) print('minVehicleCount is: ' + str(minVehicleCount)) print('maxVehicleCount is: ' + str(maxVehicleCount)) # Filte...
null
vehicleCountFilterScript.py
vehicleCountFilterScript.py
py
1,639
python
en
code
null
code-starcoder2
50
302851296
"""Ecolink 4655BC0-R device.""" from zigpy.profiles import zha from zigpy.quirks import CustomDevice from zigpy.zcl.clusters.general import Basic, Identify, Ota, PollControl from zigpy.zcl.clusters.homeautomation import Diagnostic from zigpy.zcl.clusters.measurement import TemperatureMeasurement from zigpy.zcl.cluster...
null
zhaquirks/ecolink/contact.py
contact.py
py
2,215
python
en
code
null
code-starcoder2
50
504414090
import networkx as nx # Imports networkx package for implementation of graphs import matplotlib.pyplot as plt # Imports matplotlib package for plotting and displaying the graphs node=[] edge=[] # Return a list of nodes of each cycle def cycles(G): l = list(nx.simple_cycles(G)) if len(l) != 0: print...
null
Standalone EXE program/graph.py
graph.py
py
5,266
python
en
code
null
code-starcoder2
50
69774422
def search(amount, values, maxValues, maxValueItems): for i in range(amount + 1): maxValue = 0 maxValueItem = None for d in [value for value in values if value[1] <= i]: if d[2] + maxValues[i - d[1]] > maxValue: maxValue = d[2] + maxValues[i - d[1]] maxValueItem = d maxValues[i] ...
null
base/steal_bag.py
steal_bag.py
py
798
python
en
code
null
code-starcoder2
50
649364548
#!/usr/bin/python # Deploys the master branch to the hutmap.com dreamhost account # # Specifically, merges master into dreamhost, builds css and js files with new # uuid suffixes, pulls this all into dreamhost, and restarts the server. # # Assumptions: # - git on the PATH (i.e. you can use git from a terminal) # - the...
null
scripts/utils/deploy-dreamhost.py
deploy-dreamhost.py
py
2,397
python
en
code
null
code-starcoder2
51
538532492
# coding=utf-8 from random import Random # json数据((filename,data),(filename,time)) ZeroJsonData = { 'data':{}, 'time':{} } # 计算字符串长度 def strLen(str): try: row_l=len(str) utf8_l=len(str.encode('utf-8')) return (utf8_l-row_l)/2+row_l except: return None return N...
null
app/glb.py
glb.py
py
760
python
en
code
null
code-starcoder2
51
510353263
from .attention_weight import AttentionWeight from .weight_sum import WeightSum class Attention: def __init__(self): self.params, self.grads = [], [] self.attention_weight = AttentionWeight() self.weight_sum = WeightSum() self.weight = None def forward(self, hs, h): ...
null
model/layer/attention.py
attention.py
py
652
python
en
code
null
code-starcoder2
51
13869570
### # Script for plotting and animating both PurpleAir and AQY data from a controlled experiment # across multiple rounds. If a similar experiment is performed in the future, the filenames # and round times can be subsituted into the global variables at the top of the script to # produce new plots ### import pandas as...
null
AQY_Analysis/exp.py
exp.py
py
12,989
python
en
code
null
code-starcoder2
51
248293684
from flask import Blueprint, render_template, redirect, url_for, request import traceback from fantom_util import mturk from controllers import training_controller training_app = Blueprint("training", __name__) CONTACT_EMAIL = "<INSERT_EMAIL@EXAMPLE.COM>" @training_app.route("/set_trainer") def set_trainer() -> str:...
null
crowd_sourcing/pages/training.py
training.py
py
3,018
python
en
code
null
code-starcoder2
51
456678305
from readMetrics import readMetrics import numpy as np from matplotlib import pyplot as plt from matplotlib.pyplot import cm from scipy.interpolate import splrep, splev, interp1d from math import log10, floor MAXRAD = ['90', '92', '94', '96'] MAXRAD = ['90', '99'] #MAXRAD = ['80','82','84','86','88','90', '92', '94', ...
null
C++/draft01/ALT/highCa/postproc/metrics/master/metrics.py
metrics.py
py
2,928
python
en
code
null
code-starcoder2
51
286640403
""" Author: oliver """ import numpy as np import pandas as pd import scipy as sp import datetime import time import subprocess import matplotlib # matplotlib.use("Agg") # This suppresses the annoying Python Rocket GUI indicator in the dock. matplotlib.use('TkAgg') import pylab import matplotlib.pyplot as plt f...
null
Python/other_rates.py
other_rates.py
py
3,441
python
en
code
null
code-starcoder2
51
485497608
""" 输入两个正整数计算它们的最大公约数和最小公倍数 Version: 0.1 Author: rebecca Date: 2018-03-01 """ a, b= input("please input two positive integer: ").split() a = int(a) b = int(b) for i in range(min(a,b),0,-1): if a%i==0 and b%i==0: print("%d is the highest common factor of %d and %d" %(i,a,b)) print("%d is the least c...
null
day1-3 2021-06-10/py_day4_2.py
py_day4_2.py
py
424
python
en
code
null
code-starcoder2
51
277624187
""" Sentiment Classification Model """ from data import IMDB_Data_Loader import tensorflow as tf import tensorflow_hub as hub from tensorflow.contrib import predictor import pandas as pd import os class Sentiment_Classifier: def __init__(self): self.dl = IMDB_Data_Loader() self.train_df, self.test_...
null
ml_model.py
ml_model.py
py
3,869
python
en
code
null
code-starcoder2
51
52024111
import os import json import base64 from typing import (Dict, Optional, Any, List) from collections import OrderedDict from gtmcore.labbook.labbook import LabBook from gtmcore.activity import ActivityStore, ActivityType, ActivityRecord, ActivityDetailType, ActivityDetailRecord, \ ActivityAction from gtmcore.activ...
null
packages/gtmcore/gtmcore/environment/bundledapp.py
bundledapp.py
py
6,800
python
en
code
null
code-starcoder2
51
253550646
from panther_base_helpers import box_parse_additional_details def rule(event): if event.get('event_type') != 'SHIELD_ALERT': return False alert_details = box_parse_additional_details(event).get('shield_alert', {}) if alert_details.get('rule_category', '') == 'Anomalous Download': if alert_...
null
box_rules/box_anomalous_download.py
box_anomalous_download.py
py
819
python
en
code
null
code-starcoder2
51
300483046
import time import argparse import pynvml class Device(object): class Status: INIT = "INIT" DETECTING = "DETECTING" STOP = "STOP" start_detecting_mem_threshold = 32 * 1024 * 1024 def __init__(self, handle): self.handle = handle self.status = self.Status.INIT ...
null
LanguageModeling/gpt-2/tools/gpu_memory_usage.py
gpu_memory_usage.py
py
1,861
python
en
code
null
code-starcoder2
51
397983169
#!/usr/bin/env python # coding:utf-8 """ Author: LiTeng 1471356861@qq.com Implement TextRNN, contains LSTM,GRU,RNN Reference: "Effective LSTMs for Target-Dependent Sentiment Classification" "Bidirectional LSTM-CRF Models for Sequence Tagging" "Generative and discriminative text classi...
null
model/classification/textrnn.py
textrnn.py
py
3,277
python
en
code
null
code-starcoder2
50
522554903
"""Common features for bignum in test generation framework.""" # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # 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 # # ...
null
scripts/mbedtls_dev/bignum_common.py
bignum_common.py
py
4,802
python
en
code
null
code-starcoder2
50
307158340
#Jose Luis Mata Lomelí #Crear dibujos tipo espirografo import pygame import math import random #Dimensiones Ancho = 800 Alto = 800 #Colores BLANCO = (255, 255, 255) def dibujar(r, R, l): # Inicializa el motor de pygame pygame.init() # Crea una ventana de Ancho * Alto ventana = pyga...
null
misionImposible-mision6.py
misionImposible-mision6.py
py
3,559
python
en
code
null
code-starcoder2
50
195964046
#import ui #used for pythonista #import console #used for pythonista import get_time import get_data import calc import matplotlib.pyplot as plt import pylab import matplotlib.dates as mdates import pylab from io import BytesIO from pprint import pprint #Last week: sunday (0) + Monday (2) #week before: Sunday (1) + M...
null
Winter_10.py
Winter_10.py
py
5,363
python
en
code
null
code-starcoder2
51
340674584
from influxdb import InfluxDBClient from numpy.random import default_rng import numpy as np import pandas as pd import datetime import random import csv import os from optimal_downsampling_manager.resource_predictor.estimate_table import Degraded_IATable, get_context, DownTimeTable, DownRatioTable, Degraded_Q_IATable,...
null
query_generator.py
query_generator.py
py
7,452
python
en
code
null
code-starcoder2
51
263821164
import json import logging from typing import List, Callable, Any, Optional from cryptoxlib.WebsocketMgr import Subscription, WebsocketMgr, WebsocketMessage, Websocket, CallbacksType from cryptoxlib.Pair import Pair from cryptoxlib.clients.binance.functions import map_ws_pair from cryptoxlib.clients.binance.enums impo...
null
cryptoxlib/clients/binance/BinanceWebsocket.py
BinanceWebsocket.py
py
5,553
python
en
code
null
code-starcoder2
51
551508955
from flask_twisted import Twisted from wordStore.app import create_app app = create_app() twisted = Twisted(app) if __name__ == '__main__': twisted.run( host=app.config['host'], port=app.config['port'], debug=app.config['debug'])
null
manage.py
manage.py
py
247
python
en
code
null
code-starcoder2
51
566139547
import datetime import os import matplotlib.pyplot as plt import networkx as nx class Representation: def __init__(self): self.iterations =[] self.values_fc = [] def reset_chart(self): self.iterations= [] self.values_fc= [] def add_point_to_chart(self,iteration, value): ...
null
src/representation.py
representation.py
py
5,446
python
en
code
null
code-starcoder2
50
179960298
from bs4 import BeautifulSoup from datetime import datetime,date import requests import os import sys import re import time from subprocess import call,Popen,check_output,PIPE sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'includes')) from customSettings import repoDir,djangoDir,djangoSettings,startFin...
null
django/n.libtech.info/src/custom/crawlScripts/crawlMain.py
crawlMain.py
py
7,211
python
en
code
null
code-starcoder2
50
523380136
import numpy as np import operator # k-近邻算法执行排序操作 import argparse import matplotlib import matplotlib.pyplot as plt import os def createDataSet(): group = np.array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])# 测量点 labels = ['A', 'A', 'B', 'B'] # 数据点的标签信息,元素个数等于group矩阵行数 return group, labels # 参数:inX:用于分类的...
null
MLzhoupengwu/kNN.py
kNN.py
py
7,339
python
en
code
null
code-starcoder2
50
3765698
from django.urls import path from .views import CategoryView, ProductListView, OrderCreateView from rest_framework import routers app_name = 'products' router = routers.DefaultRouter() router.register('products', ProductListView, basename='product') urlpatterns = [ path('categories/', CategoryView.as_view()), ...
null
products/urls.py
urls.py
py
384
python
en
code
null
code-starcoder2
50
215224187
import time import torch import torch.nn.functional as F from torch.utils.data.dataloader import DataLoader from torch.utils.tensorboard import SummaryWriter from audio import Audio from dataset import new_audio_datasets from losses import MaskedL1 from model.io import ModelPackage from utils.common import Averager f...
null
trainer.py
trainer.py
py
7,709
python
en
code
null
code-starcoder2
50
477060780
from echopype.echodata import EchoData import xarray as xr import numpy as np def test_harmonize_env_param_time(): # Scalar p = 10.05 assert EchoData._harmonize_env_param_time(p=p) == 10.05 # time1 length=1, should return length=1 numpy array p = xr.DataArray( data=[1], coords={ ...
null
echopype/tests/echodata/test_echodata_misc.py
test_echodata_misc.py
py
1,519
python
en
code
null
code-starcoder2
50
255206708
""" HandleCollisionsAction module Contains HandleCollisionsAction class and associated utilities. Used in controlling the gameplay and managing collisions in-game. Authors: - Shad Christopherson - Peter Griffin - Christian Soldevilla """ import random from game import constants from game.action import Action from...
null
cse210-tc06/batter/game/handle_collisions_action.py
handle_collisions_action.py
py
3,574
python
en
code
null
code-starcoder2
50
9420601
import pdfkit def html_to_pdf(html, to_file): # 将wkhtmltopdf.exe程序绝对路径传入config对象 path_wkthmltopdf = r'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf) # 生成pdf文件,to_file为文件路径 pdfkit.from_file(html, to_file, configuration=config) p...
null
docs/html/htmltopdf.py
htmltopdf.py
py
413
python
en
code
null
code-starcoder2
50
453182898
#! /usr/bin/env python # Public domain; MZMcBride, 2011; Legoktm, 2014 from flask import Flask, request import cgi import urllib import re import oursql import operator import json import os app = Flask(__name__) my_cnf = os.path.expanduser('~/replica.my.cnf') def database_list(): conn = oursql.connect(host='e...
null
checker/checker.py
checker.py
py
9,445
python
en
code
null
code-starcoder2
51
575911156
from django.contrib import messages from django.shortcuts import render, redirect from .forms import MicrotasksForm from .models import Microtasks,MAL_Requirements # Create your views here. def microtask(request): if request.method == 'POST': form = MicrotasksForm(request.POST, request.FILES) if fo...
null
jobs/views.py
views.py
py
3,217
python
en
code
null
code-starcoder2
51
262511262
import pandas as pd import numpy as np import re import os import matplotlib.pyplot as plt from nltk.corpus import stopwords from six.moves import cPickle as pickle from nltk.corpus import stopwords from sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_score import itertools no_alignment_file ...
null
run_model.py
run_model.py
py
15,676
python
en
code
null
code-starcoder2
51
161296733
''' Gestion principale d'un jeu de Yams, module principal. @author: Rouyan Thi ''' from random import sample, randint def jet_init(nb_des, mode): '''Lance tous les dés une première fois. :param nb_des: nombre de dés à lancer :type nb_des: int :param mode: jeu avec ou sans dés cassés :type ...
null
modules/main.py
main.py
py
2,912
python
en
code
null
code-starcoder2
51
445572431
""" mapsAPI.py Source Code for Google Maps API or interaction between genetic algorithm and google maps Author(s): Niklaas Cotta CIS422 FA21 Team NASAK Creation Date: 10/9/21 Sources: List of APIs: https://developers.google.com/maps/documentation Distance Matrix Documentation: https://developers.google.com/maps/doc...
null
webapp/api/mapsAPI.py
mapsAPI.py
py
4,441
python
en
code
null
code-starcoder2
51
194272122
def line_splitter(filename): num1 = [] with open(filename, encoding="utf8") as text: text = text.read() text.strip("\n") line = text.splitlines() return line def search_cap_letter(line): speech_box = [] speech_box1 = [] DASH = "—" cap_inp = input("Найти...
null
Preparation1.py
Preparation1.py
py
1,089
python
en
code
null
code-starcoder2
51
457832215
from PIL import Image, ImageDraw import math import random SIZE=(500, 700) START=(250, SIZE[1]-100) def radians(degrees): return degrees/180*math.pi def sortAngleHelper(angle): return getAngleDistance(angle, radians(-90)) def getAngleDistance(angleA, angleB): distance = angleA - angleB if dis...
null
generate/objects/trees/evergreen.py
evergreen.py
py
6,806
python
en
code
null
code-starcoder2
51
341016782
from Stacks import FirstStack def is_valid(expr): st = FirstStack.Stack() # Use the Class.method notation to access the Stack() class in FirstStack for ch in expr: if ch in '({[': st.push(ch) if ch in ')}]': if st.is_empty(): print("Right parentheses a...
null
Python_Programming/PythonDataStructures/Stacks/ValidateParentheses.py
ValidateParentheses.py
py
1,284
python
en
code
null
code-starcoder2
51
332385312
import pandas as pd import matplotlib.pyplot as plt import numpy as np clicksData = pd.read_csv('./clicksInfo.csv', '\t', header=0).ix[:,:].as_matrix() conversionsData = pd.read_csv('./conversionsInfo.csv', '\t', header=0).ix[:,:].as_matrix() objForCpc = {} for row in clicksData: if(row[0] in objForCpc): objForCp...
null
plots/basicBarForAvgCpc.py
basicBarForAvgCpc.py
py
1,123
python
en
code
null
code-starcoder2
51
641614323
# coding: utf-8 from __future__ import unicode_literals import os.path import re from collections import Sequence from operator import itemgetter from .common import InfoExtractor from ..compat import ( compat_urllib_parse_urlparse, compat_urlparse, compat_str, ) from ..utils import parse_iso8601, Extract...
null
youtube_dl/extractor/youmaker.py
youmaker.py
py
15,038
python
en
code
null
code-starcoder2
51
278790596
import os from os import listdir from openvino.inference_engine import IECore import cv2 import numpy as np from scipy.spatial.distance import cosine import imutils import dlib from numpy import savez_compressed det_model=r"C:\Users\LENOVO\Desktop\FaceReid\detection_model\face-detection-0202.xml" det_w...
null
Evaluating the Oneshot model/modelEval-Straightface.py
modelEval-Straightface.py
py
7,910
python
en
code
null
code-starcoder2
51
649318733
import unittest class TestMnvram(unittest.TestCase): def test_rename(self): nvram = {} from mnvram import MozaiqRouter router = MozaiqRouter(nvram) router.renameRouter("newname") nvram = router.nvram self.assertTrue(nvram['wan_hostname'] == 'mozaiqnewname') self.assertTrue(nvram['router_...
null
test_mnvram.py
test_mnvram.py
py
457
python
en
code
null
code-starcoder2
51
641535635
# popQuiz - Nov 30, 2018 # Michael Reilly # I pledge my honor that I have abided by the Stevens Honor System from cs115 import * ''' These exercises give you practice writing code with loops and practice reading code. Read the instructions and the code carefully. ''' ''' Here is a variation on the Car class. ''' ...
null
popQuiz.py
popQuiz.py
py
5,796
python
en
code
null
code-starcoder2
51
606580312
import gc import uasyncio as asyncio gc.collect() from base_node import BaseDriver import lvgl as lv async def set_valve(i2c, i2c_address, pin, state): ''' Parameters ---------- i2c : machine.I2C I2C driver handle. i2c_address : int I2C address. pin : int ...
null
valve.py
valve.py
py
721
python
en
code
null
code-starcoder2
51
55454051
# Copyright (C) 2019 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """A mixin for objects that can be filtered in Query API""" class Filterable(object): """Mixin for identification of filterable attributes of model in Query API""" _filterable_attrs = [] @classmetho...
null
src/ggrc/models/mixins/filterable.py
filterable.py
py
996
python
en
code
null
code-starcoder2
51
114287718
import pgl import paddle.fluid as F import paddle.fluid.layers as L from models.base import BaseNet, BaseGNNModel from models.ernie_model.ernie import ErnieModel from models.ernie_model.ernie import ErnieGraphModel from models.ernie_model.ernie import ErnieConfig class ErnieSageV2(BaseNet): def build_inputs(self...
null
examples/erniesage/models/erniesage_v2.py
erniesage_v2.py
py
4,208
python
en
code
null
code-starcoder2
50
643000706
#Time complexity: O(n) #Space complexity: O(1) #Works on leetcode: yes #Approach: The idea here is to find the middle of the linked list and then reverse the second half of the linked list. #After that, start traversing and comparing the first half and second half of the linked list. If any value is unequal, #the link...
null
Problem2.py
Problem2.py
py
1,147
python
en
code
null
code-starcoder2
50
216516250
from typing import List class Solution: def coinChange(self, coins: List[int], amount: int) -> int: if amount == 0: return 0 if coins is None or len(coins) == 0: return -1 coins = sorted(coins) if amount < coins[0]: return -1 result = [10...
null
coin_change.py
coin_change.py
py
712
python
en
code
null
code-starcoder2
50
422560165
from __future__ import print_function import contextlib import functools import os import sys import shutil import subprocess import time from astropy.io import fits from .backend import CoadditionBackend from .backend import ProjectionBackend from .backend import BackendError @contextlib.contextmanager def timer(...
null
worker/backend/swarp.py
swarp.py
py
8,652
python
en
code
null
code-starcoder2
50
439059818
import pandas as pd import requests import settings import pygame.mixer import os import time aitalk_url = "https://webapi.aitalk.jp/webapi/v2/ttsget.php" csv_path = "./audio/dialogue.csv" audio_folder = "./audio/" df = pd.read_csv(csv_path, index_col=0) pygame.mixer.init() def get_dialogue(status): print(df['di...
null
dialogue.py
dialogue.py
py
2,754
python
en
code
null
code-starcoder2
50
558180748
#!/usr/bin/env python3 # coding=utf-8 # Author: Junjie Wang # Mail: dreamboy.gns@sjtu.edu.cn # Website:http://120.79.231.160 # Blog:http://120.79.231.160/wordpress # Created Time: 2018-12-01 21:03:11 # -------------- For more details, refer to https://wiseodd.github.io/techblog/2015/10/17/metropolis-hastings/ ----...
null
M_H_Sampling.py
M_H_Sampling.py
py
1,693
python
en
code
null
code-starcoder2
50
162549020
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns class StockCollection(object): def __init__(self): self.__stocks = [] def add_stock(self, stock): self.__stocks.append(stock) def get_stock(self, index): return self.__stocks[index] def get_stocks(self...
null
project/StockCollection.py
StockCollection.py
py
1,674
python
en
code
null
code-starcoder2
50
231728584
# -*- coding: utf-8 -*- # Scrapy settings for kindle project # # For simplicity, this file contains only the most important settings by # default. All the other settings are documented here: # # http://doc.scrapy.org/en/latest/topics/settings.html # BOT_NAME = 'kindle' SPIDER_MODULES = ['kindle.spiders'] NEWSPID...
null
scrapy/kindle/settings.py
settings.py
py
1,223
python
en
code
null
code-starcoder2
50
119745185
import hashlib,json from collections import OrderedDict class My_MerkTree: def __init__(self,listoftransaction=None): self.listoftransaction = listoftransaction self.past_transaction = [] def create_tree(self): listoftransaction = self.listoftransaction past_transaction = self.past_transaction temp_trans...
null
merkle.2.py
merkle.2.py
py
3,848
python
en
code
null
code-starcoder2
51
434005392
import pandas as pd from sklearn import svm, metrics or_input = [ [1,0,1], [0,1,1], [0,0,0], [1,1,1], [1,0,1], [0,1,1], [0,0,0], [1,1,1], [0,0,0], [1,1,0], ] or_df = pd.DataFrame(or_input) or_data = or_df.ix[:, 0:1] or_label = or_df.ix[:, 2] clf = svm.SVC() clf.fit(or_data, or...
null
04_AI/1_Machine_Learning/150_or_train.py
150_or_train.py
py
504
python
en
code
null
code-starcoder2
51
281551642
'''DAILY TICKETS SENDING TO A WHATSAPP GROUP''' import requests from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.ui import WebDriverWait from selenium.web...
null
whatsapp.py
whatsapp.py
py
3,890
python
en
code
null
code-starcoder2
51
137754772
''' Created on Oct 17, 2019 @author: kerrylu ''' import math def distance(a,b): """ Parameters a and b are both 2-tuples calculate and return distance between points a and b """ return math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2) def minDistance(points): """ points (list of tuple...
null
Lab07/minDistance.py
minDistance.py
py
1,063
python
en
code
null
code-starcoder2
51
79959994
from __future__ import print_function import tensorflow as tf import numpy as np from argparse import ArgumentParser import os import cv2 import sys from yolo_model import YOLOModel from rotation_invariance_model import RotationalInvarianceModel def main(): parser = ArgumentParser() parser.add_argument('--input...
null
rotational-invariance/yolo_inference.py
yolo_inference.py
py
3,614
python
en
code
null
code-starcoder2
51
452260426
# 导入socket这个库 import socket # 创建一个socket对象 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 开始建立TCP连接 s.connect(("127.0.0.1",8888)) # 接收数据 buffer = [] d = s.recv(1024) buffer.append(d) # 把字节连接起来 data = b''.join(buffer) print(data) # 关闭连接 s.close()
null
程序/3.py
3.py
py
321
python
en
code
null
code-starcoder2
51
232442902
#! /usr/bin/env python3 import vcf import httplib2 import json __author__ = 'Gerhard Bilek' ## ## ## Aim of this assignment is to annotate the variants with various attributes ## We will use the API provided by "myvariant.info" - more information here: https://docs.myvariant.info ## NOTE NOTE! - check here for hg38 ...
null
assignment3.py
assignment3.py
py
5,772
python
en
code
null
code-starcoder2
51
653446250
import subprocess import numpy as np import os def SplitType(csv_flag): if(csv_flag): return "," else: return " " def OpenTUMPose(pose_path,csv_flag): Pose = list() with open(pose_path,encoding="utf-8") as f: for line in f.readlines(): line=line.strip('\n') ...
null
EUROC/evaluation.py
evaluation.py
py
3,942
python
en
code
null
code-starcoder2
51
187513857
import sublime import sublime_plugin import os import golangconfig from .gotools_util import Buffers from .gotools_util import GoBuffers from .gotools_util import Logger from .gotools_util import ToolRunner class GotoolsGuruCommand(sublime_plugin.TextCommand): def is_enabled(self): return GoBuffers.is_go_source...
null
gotools_guru.py
gotools_guru.py
py
2,927
python
en
code
null
code-starcoder2
51
606287825
import RPi.GPIO as GPIO import threading import time RELEASE_REVOLUTIONS = 2 class Motor(threading.Thread): def __init__(self, write_pin, read_pin): threading.Thread.__init__(self) self.motor_write_pin = write_pin self.motor_read_pin = read_pin self.gpio_setup() self.revolu...
null
Code/Backend/helpers/Motor.py
Motor.py
py
1,310
python
en
code
null
code-starcoder2
51
428445231
def solution(array, commands): answer = [] arr = [] for i in range(len(commands)): arr = array arr = arr[commands[i][0]-1:commands[i][1]] arr.sort() #print(arr) answer.append(arr[commands[i][2]-1]) return answer
null
프로그래머스/정렬_K번째수/K번째 수.py
K번째 수.py
py
277
python
en
code
null
code-starcoder2
51
77599074
import sys import csv import math import os def ReadFile (filename = "C:/Users/VictorKiraydt/Documents/git/filmopoisk/server/resources/ratings.csv"): #filename = os.path.dirname(os.path.abspath("../resources/ratings.csv")) + "\\ratings.csv" f = open (filename) r = csv.reader (f) mentions = dict() i...
null
server/python/collaborativeFiltering.py
collaborativeFiltering.py
py
2,171
python
en
code
null
code-starcoder2
51
427506636
import numpy as np import cv2 from matplotlib import pyplot as plt """ ORB是一种想要代替SIFT和SURF的算法,它更快。 1 FAST features from accelerated segment test,绘制16像素的圆 2 BRIEF Binary Robust Independt Elementary Features 3 暴力匹配 """ img1 = cv2.imread('4.jpeg', 0) img2 = cv2.imread('5.jpeg', 0) orb = cv2.ORB_create() kp1, des1 = ...
null
读书笔记《opencv3 计算机视觉 python语言实现》/第6章图像检索/6.1.4_orb.py
6.1.4_orb.py
py
694
python
en
code
null
code-starcoder2
51
439284625
# A function named unique_common that accepts two lists both of which # contain integers as parameters and returns a sorted list (ascending # order) which contains unique common elements from both the lists. If # there are no common elements between the two lists, then your function # should return the keyword None...
null
09 - Midterm Exam/08 Midterm Exam, Part 8 (Unique Common Elements).py
08 Midterm Exam, Part 8 (Unique Common Elements).py
py
1,606
python
en
code
null
code-starcoder2
50
645699035
## Tickets File def insertTickets(filetype, json, cursor, conn, uid): if (filetype == 'tickets'): featureAttrs = {'tickets', 'timestamp', 'uid'} cnt = 0 tblName = 'tickets' cntattr = 0 keytypevals = {} values = [] for tis in featureAttrs: keytypevals,values = appendJsonKey(json, tis, keytypevals, valu...
null
scripts/betterX_attributes_interactive.py
betterX_attributes_interactive.py
py
25,968
python
en
code
null
code-starcoder2
50
73411396
# Day 5: Poisson Distribution 2 - 포아송 분포 # 특정 사건에 대한 기대값을 람다 l로 정의할때, 특정 사건이 k번 발생할 확률 분포 a, b = map(float, input().split()) result1 = 160 + 40*(a + a**2) result2 = 128 + 40*(b + b**2) print(round(result1, 3)) print(round(result2, 3))
null
hackerrank/statistics/5. poisson_distribution_2.py
5. poisson_distribution_2.py
py
310
python
en
code
null
code-starcoder2
50
634859315
distancias = [ ("Alabaster", "Birmingham", 24), ("Alabaster", "Montgomery", 71), ("Birmingham", "Huntsville", 103), ("Birmingham","Tuscaloosa", 59), ("Demopolis","Mobile", 141), ("Demopolis","Montgomery", 101), ("Demopolis","Tuscaloosa", 65), ("Mobile","Montgomery", 169), ("Montgomery","Tuscaloosa", 134) ] ...
null
python_stuff/ex5.py
ex5.py
py
2,812
python
en
code
null
code-starcoder2
50
69304178
import itertools import numpy as np from sklearn.neighbors import NearestNeighbors from sklearn.externals.joblib import delayed, Parallel from sklearn.utils import gen_even_slices from ..base import BaseDetector from ..utils import timeit, OneDimArray, TwoDimArray __all__ = ['FastABOD'] def approximate_abof( X...
null
kenchi/outlier_detection/angle_based.py
angle_based.py
py
4,091
python
en
code
null
code-starcoder2
50
162301565
''' Handlers for AJAX (Javascript) functions used in the web interface to start experiments and train BMI decoders ''' import json, datetime import logging import io, traceback import numpy as np from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.db.models import Prote...
null
db/tracker/ajax.py
ajax.py
py
24,165
python
en
code
null
code-starcoder2
50
501437840
# -*- coding: utf-8 -*- from django import forms from django.utils.translation import ugettext_lazy as _ from .models import( Column, DJANGOCMS_GRID_LG_CHOICES, DJANGOCMS_GRID_MD_CHOICES, DJANGOCMS_GRID_SM_CHOICES, DJANGOCMS_GRID_XS_CHO...
null
djangocms_bootstrap3/forms.py
forms.py
py
2,012
python
en
code
null
code-starcoder2
50
123570584
# A function which accepts an input string consisting of alphabetic characters # and spaces and returns the string with all the spaces removed. Do NOT use any # string methods for this problem. # method 1 def Remove_All_Spaces(input_str): new_str = "" for chara in input_str: if ord(chara) == ord(" ")...
null
10 - Week 6/02 String Methods/10 Strings Functions Exercise 4 (Remove All Spaces).py
10 Strings Functions Exercise 4 (Remove All Spaces).py
py
719
python
en
code
null
code-starcoder2
50
588713837
from __future__ import division from bokeh.plotting import cursession, figure, output_server, output_notebook, show from copy import copy from keras.callbacks import Callback from numpy import inf, nan from os import _exit from Print import printflush # The following defines a Class object that monitors and records #...
null
Programming Scripts/zzz Utility Code/Python/KerasTrainingMonitor.py
KerasTrainingMonitor.py
py
5,998
python
en
code
null
code-starcoder2
51
44860443
from __future__ import print_function import errno import os import numpy as np from PIL import Image import torch import torch.nn as nn EPS = 1e-7 def assert_eq(real, expected): assert real == expected, '%s (true) vs %s (expected)' % (real, expected) def assert_array_eq(real, expected): assert (np.abs(r...
null
utils.py
utils.py
py
4,690
python
en
code
null
code-starcoder2
51
28841343
from typing import Dict import numpy from overrides import overrides from allennlp.data.fields.field import Field class ArrayField(Field[numpy.ndarray]): """ A class representing an array, which could have arbitrary dimensions. A batch of these arrays are padded to the max dimension length in the batch ...
null
src/allennlp/data/fields/array_field.py
array_field.py
py
1,616
python
en
code
null
code-starcoder2
51
223646032
import annoy import numpy as np import logging import glob import re logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class RecommenderVectorIndex(object): """Database index for finding nearest neighbors. The rows are float vectors, such as Word2Vec vectors or some other embedding...
null
django/mapdrive/utils/putin_face_recognition/index.py
index.py
py
4,923
python
en
code
null
code-starcoder2
51
216731355
import pymysql class SQL : def __init__(self, host='192.168.137.172', user='ssu', password='', db='ssudb', charset='utf8'): self.connection = pymysql.connect(host=host, user=user, password=password, ...
null
ServerSit/odr.py
odr.py
py
2,282
python
en
code
null
code-starcoder2
51
238164153
''' Requirments: python & > pip install pillow > pip install matplotlib > pip install numpy Run: > python task1.py path/to/image ''' import PIL from PIL import Image import numpy as np import itertools import sys import os import matplotlib.pyplot as plt import mylib from mylib import BOX # open image imag...
null
DIP/LABS/lab08/solution/task2.py
task2.py
py
1,522
python
en
code
null
code-starcoder2
51
145270068
import os from telebot import types import flask from app.bot_handlers import bot from app.config import settings server = flask.Flask(__name__) @server.route('/' + settings.TOKEN, methods=['POST']) def get_message(): bot.process_new_updates( [types.Update.de_json(flask.request.stream.read().decode('ut...
null
run_server.py
run_server.py
py
754
python
en
code
null
code-starcoder2
51
214577347
#Find and show the sum of all multiples of 3 or 5 less than 1000 (this number is 233168) sum=int(0) n=0 while n<1000: if n%3==0 or n%5==0: sum=sum+n n=n+1 print(sum)
null
Lezione1/Ex5.py
Ex5.py
py
200
python
en
code
null
code-starcoder2
51
370998504
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 15 14:39:29 2019 @author: em812 """ import pdb import numpy as np import pandas as pd from sklearn.decomposition import PCA def univariate_tests( X, y, control='N2', test='ANOVA', comparison_type='multiclass', multitest_corr...
null
tierpsytools/analysis/statistical_tests.py
statistical_tests.py
py
12,041
python
en
code
null
code-starcoder2
51
630205264
import pickle import numpy as np with open('./bangalore/bangalore.pickle','rb') as f: model = pickle.load(f) with open('./bangalore/locations.txt','r') as file: locs = file.read() l = locs.split(',') X = np.array(l) def predict_price(location,sqft,bath,balcony,bhk): loc_ind = np.where(X == location)[0][...
null
bangalore/usethis.py
usethis.py
py
503
python
en
code
null
code-starcoder2
51
244013969
import torch from torch.nn import Linear from torch_geometric.nn import TransformerConv class GraphAttentionEmbedding(torch.nn.Module): def __init__(self, in_channels, out_channels, msg_dim, time_enc): super(GraphAttentionEmbedding, self).__init__() self.time_enc = time_enc edge_dim = msg_...
null
src/layers/gnn.py
gnn.py
py
1,188
python
en
code
null
code-starcoder2
51
397421462
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # 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 copyright notice, this ...
null
src/primaires/communication/commandes/messages/lire.py
lire.py
py
3,878
python
en
code
null
code-starcoder2
51
449859332
# -*- coding: utf-8 -*- import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches import matplotlib.lines as mlines from pandas import ExcelWriter from numpy import interp import math def Load_results1(instance,i,n,type_generator): ''' This function loads the...
null
Results.py
Results.py
py
75,742
python
en
code
null
code-starcoder2
51
50512460
import socket import re def service_client(client_socket,recv_data): request_lines=recv_data.splitlines() # 第一行格式为 GET /index.html HTTP/1.1 # GET可能换为POST,PUT,DEL等 # print(recv_data.decode('utf-8')) # 发送headers ret=re.match(r'[^/]+(/[^ ]*)',request_lines[0]) if ret: file_name=ret.gro...
null
python-learn/http/http_server6_noblocking.py
http_server6_noblocking.py
py
2,568
python
en
code
null
code-starcoder2
51
338464965
import unittest from array_splitter import split class TestArraySplitter(unittest.TestCase): def test_split_should_return_empty_set_if_there_is_no_valid_splitting(self): # given array = ['a', 'b', 'c'] GROUP_COUNT_TOO_MANY = len(array) + 1 expected = {} # when act...
null
basics/recursion/src/test_array_splitter.py
test_array_splitter.py
py
718
python
en
code
null
code-starcoder2
51
445510582
import tensorflow as tf from functools import partial from sys import stdout from sklearn.model_selection import KFold import time from tensorflow.python.client import timeline from noise_models_and_integration import * def fidelity_cost_fn(network,y_, learning_rate, params, n_ts, evo_time,dim, noise_name): tmp_...
null
architecture.py
architecture.py
py
6,851
python
en
code
null
code-starcoder2
51
331807531
# import numpy as np # from keras.models import Sequential # from keras.layers import Dense, Dropout, Flatten # from keras.layers import Convolution2D, MaxPooling2D # np.random.seed(42) # set deterministic reproducibility import image from log import debug from keras.models import model_from_json from multiclasshel...
null
src/python/wswtm.py
wswtm.py
py
2,215
python
en
code
null
code-starcoder2
51
399666237
import pygame import board from pygame.locals import * width = 700 height = 600 def start(): pygame.init() screen = pygame.display.set_mode((width, height)) game_loop(screen) pygame.quit() def game_loop(screen): game_board = board.Board() colors = {0: (255, 255, 255), 1: (200, 0, 0), 2: (25...
null
UI.py
UI.py
py
1,500
python
en
code
null
code-starcoder2
51