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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
1293373601 | import random
import itertools
from fp.fp import FreeProxy
import requests
from itemloaders.processors import TakeFirst, MapCompose
proxies_list = FreeProxy().get_proxy_list()
print(type(proxies_list))
proxy = itertools.cycle(proxies_list)
# pr = random.choice(proxies)
def set_proxy(proxy):
_proxy = next(proxy)
... | navneet37/BusinessScrapy | testproxy.py | testproxy.py | py | 589 | python | en | code | 0 | github-code | 1 |
24645452076 | """
This module should contain your main project pipeline(s).
Whilst the pipeline may change during the analysis phases, any more stable pipeline should be implemented here so
that it can be reused and easily reproduced.
"""
# This must be set in the beggining because in model_util, we import it
logger_name = "FCRN-BI... | aleksei-mashlakov/fcrn-bidding | src/fcrn_bidding/pipeline.py | pipeline.py | py | 3,112 | python | en | code | 0 | github-code | 1 |
28941505818 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from tex import Tex
from PIL import Image
if __name__ == '__main__':
for root, dirs, files in os.walk('PackedContent'):
for f in files:
if os.path.splitext(f)[1].lower() == '.tex':
name = os.path.join(root, f)
... | noword/EXAPUNKS-Localize | images/import_imgs.py | import_imgs.py | py | 1,256 | python | en | code | 32 | github-code | 1 |
35219965731 | from ast import main
import collections
from statistics import mean
import numpy as np
import random
from collections import defaultdict
import matplotlib.pyplot as plt
class MonteCarlo():
def __init__(self, gamma):
self.actions = [(-1,0), (0,1), (1,0), (0,-1)] # up, right, down, left
self.arrows ... | saurabhbajaj123/Reinforcement-Learning-Algorithms-1 | HW4/submission/HW4.py | HW4.py | py | 20,952 | python | en | code | 0 | github-code | 1 |
24889391856 | with open("2015\input_day1.txt", "rt") as f:
input = f.readline().rstrip("\r\n")
### PART 1
# count = 0
# for char in input:
# count = count + 1 if char == "(" else count - 1
# print(count)
### PART 2
floor = 0
for i in range(len(input)): # need the position
floor = floor + 1 if input[i] == "(" else flo... | jacobcrigby/Advent-of-Code-Python | 2015/day1.py | day1.py | py | 382 | python | en | code | 0 | github-code | 1 |
71918011555 | from urllib.parse import urljoin, urlparse
def is_safe_url(request, target):
"""Check if the URL has no tricks
Args:
request (Request): The Request object from requests library
target (string): The URL to redirect to
Returns:
bool: True if the URL is safe, False otherwise
"""... | GrindLabs/lsmakeupstudio | lsmakeupstudio/utils/url.py | url.py | py | 507 | python | en | code | 0 | github-code | 1 |
25497213504 | import abc
import logging
import random
import numpy as np
import pandas as pd
EVALUATION_CRITERIA = 'Accuracy'
def _new_func(optimization, t, theta=1.0, record=None, gamma=1):
third_term = np.sqrt(2 * np.log(t) / optimization.count)
forth_term = np.sqrt(1 / theta * third_term)
second_term = np.sqrt(1 /... | pineconebean/automl_lab | bandit/model_selection.py | model_selection.py | py | 11,212 | python | en | code | 0 | github-code | 1 |
26781812415 | import re
import nltk
import pandas as pd
from textblob import TextBlob
def lemmatize_with_postag(sentence):
'''
https://www.machinelearningplus.com/nlp/lemmatization-examples-python/
'''
sent = TextBlob(sentence)
tag_dict = {"J": 'a',
"N": 'n',
"V": 'v',
... | SamEdwardes/sentiment-cdn-election | src/twitter_analysis.py | twitter_analysis.py | py | 6,996 | python | en | code | 0 | github-code | 1 |
71349302755 | """
"""
import datetime as dt
import requests
import time
import pandas as pd
import streamlit as st
def app():
asset_contract_address = st.sidebar.text_input("Contract Address")
start_dt_input = st.sidebar.date_input(label='Start Date')
end_dt_input = st.sidebar.date_input(label='End Date')
def get... | alhedlund/al_nft_data_app | pages/collections.py | collections.py | py | 2,310 | python | en | code | 0 | github-code | 1 |
16190520974 | # coding: utf-8
"""
Производственный календарь.
"""
import json
import os
import datetime
import requests
WORKING_TYPE_WORK = 0
WORKING_TYPE_HOLIDAY = 2
WORKING_TYPE_SHORT = 3
DEFAULT_CACHE_PATH = '/tmp/basicdata_calend.json'
def is_working_time(date_time, use_cache=False, cache_path=DEFAULT_CACHE_PATH):
except... | telminov/sw-python-utils | swutils/prod_calendar.py | prod_calendar.py | py | 2,802 | python | en | code | 0 | github-code | 1 |
33776237261 | # # Notation: Draw Supported Notations of Explicit Converter
import mechkit
import networkx as nx
import matplotlib.pyplot as plt
plot_options = dict(
node_color="yellow",
node_size=2000,
width=2,
arrows=True,
font_size=10,
font_color="black",
)
converter = mechkit.notation.ExplicitConverter(... | JulianKarlBauer/mechkit | docs/source/notebooks/06.py | 06.py | py | 551 | python | en | code | 14 | github-code | 1 |
5237933206 | import numpy as np
import matplotlib.pyplot as plt
class Agent:
def __init__(self, bandit, exploration_rate):
self.bandit = bandit
self.exploration_rate = exploration_rate
self.cur_estimates = self.first_estimates()
self.all_estimates = [[self.cur_estimates[i]] for i in range(len(se... | Oppac/RL | simple_bandit.py | simple_bandit.py | py | 1,735 | python | en | code | 0 | github-code | 1 |
10874556516 | # code library
# https://practice.geeksforgeeks.org/problems/binary-tree-to-dll/1
class Test:
def __init__(self):
self.flag = 0
self.prev = self.head = None
def inorder(self,root):
if root == None:
return
self.inorder(root.left)
if self.flag == 0:
... | sunny-khatik/Love-Babbar-Sheet-Codes | BinaryTreeToDLL.py | BinaryTreeToDLL.py | py | 691 | python | en | code | 2 | github-code | 1 |
4490266612 | # My_Picture Predict
import numpy as np
import matplotlib.pyplot as plt
import cv2
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import load_model
model = load_model('../data/h5/k67_img.h5')
pred_datagen = ImageDataGenerator(rescale=1./255)
pred_data = pred_datagen... | Taerimmm/ML | keras2/keras67_4_my_result.py | keras67_4_my_result.py | py | 1,145 | python | en | code | 3 | github-code | 1 |
70449561955 | from builtins import ConnectionError
import warnings
import logging
import time
import serial
from radios.MotorolaRSSRepeater.interface import MotorolaRSSRepeater
class MotorolaQuantar(MotorolaRSSRepeater):
def __init__(self, serialPort, baud=9600):
super().__init__(serialPort, baud)
self.firmwareV... | jelimoore/OpenAutoBench | radios/MotorolaQuantar/interface.py | interface.py | py | 3,558 | python | en | code | 3 | github-code | 1 |
70755527714 | __all__ = [
"Mapper",
]
import top
from top.utils.log import log
# Primary Elect does not support the concept of a Barcode. To satisfy
# the system, we copy over the first 15 characters of the Conn Note.
FIELDS = {'Conn Note': {'offset': 0,
'length': 20},
'Identifier': {'offset':... | loum/top | top/mapper.py | mapper.py | py | 4,629 | python | en | code | 0 | github-code | 1 |
4496867704 | import requests
import argparse
from datetime import datetime
PXLA_ENDPOINT = "https://pixe.la/v1/users"
USERNAME = "stamnoob"
PWD = "m0n0mlkiaple0n"
HEADER = {"X-USER-TOKEN": PWD}
def arg_parser() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Post a coding hours pixel in the pixela \"code-... | stzanos95/python-projects | Habit-Tracker/main.py | main.py | py | 2,221 | python | en | code | 0 | github-code | 1 |
916735937 | # RAKE
import RAKE
import operator
import re
# Reka setup with stopword directory
stop_dir = "SmartStoplist.txt"
rake_object = RAKE.Rake(stop_dir)
# Sample text to test RAKE
with open("test1.txt", "rb") as f:
text = str(f.readlines())
text = text.replace(" xc ", "")
text = text.replace(" xa ", "")
text = text.re... | fazil2003/virtual-library-assistant | python_files/extract/files/rake.py | rake.py | py | 1,312 | python | en | code | 1 | github-code | 1 |
2558854509 | import sqlite3
connection=sqlite3.connect("RUGIPP_REGISTRI.db")
crsr=connection.cursor()
class Registar_Geodeta:
def __init__(self,JMBG,ime,prezime,strucna_sprema,broj_strucnog,red_licence):
self.JMBG=JMBG
self.ime=ime
self.prezime=prezime
self.sprema=strucna_sprema
self.st... | SarajlicS/Zavrsni_Rad | Registar_Geodeta.py | Registar_Geodeta.py | py | 4,781 | python | en | code | 0 | github-code | 1 |
2524008345 | import matplotlib.pyplot as plt
import cv2
import os, glob
import numpy as np
import matplotlib._png as png
from moviepy.editor import VideoFileClip
#%matplotlib inline
#%config InlineBackend.figure_format = 'retina'
def show_images(images, cmap=None):
cols = 2
rows = (len(images) + 1) // cols
plt.figur... | ghazalsaf/mobNavigation | road_detect_hls.py | road_detect_hls.py | py | 10,716 | python | en | code | 0 | github-code | 1 |
19294404545 | from statsmodels.tsa.holtwinters import ExponentialSmoothing
from dateutil.relativedelta import relativedelta
import pandas as pd
def predict_next_12_months(data):
pred = pd.DataFrame()
start_and_finish = [max(pd.to_datetime(data.columns, format = "%Y-%m")) + relativedelta(months=(x*11)+1) for x in range(2)]
... | nizarcan/CapacityPlanningDSS-SD | backend/predictor.py | predictor.py | py | 1,444 | python | en | code | 0 | github-code | 1 |
71730627235 | from gui.visual.player import Player
from gui.visual.entity import Entity
import glm
import OpenGL.GL as gl
from gui.visual.camera import Camera
from gui.visual.staticShader import StaticShader
from gui.visual.entityRenderer import EntityRenderer
from gui.visual.skyboxRenderer import SkyboxRenderer
from gui.visual.worl... | Mimikkk/2023-amib | src/libs/framspy/gui/visual/masterRenderer.py | masterRenderer.py | py | 3,138 | python | en | code | 0 | github-code | 1 |
74152867874 | import gym
import time
env = gym.make('CartPole-v0')
env.reset()
for step in range(1000):
env.render() # rendering the environment at each step
env.step(env.action_space.sample()) # feed the env with random actions that exist in all possible actions
time.sleep(0.1)
| Aslanfmh65/open_ai_project | practice.py | practice.py | py | 281 | python | en | code | 0 | github-code | 1 |
36916798983 | # Módulos
from datetime import date
# Declaração de variáveis
pessoa = dict()
# Entrada de dados da pessoa
pessoa['nome'] = str(input('Nome: '))
nasc = int(input('Ano de nascimento: '))
pessoa['idade'] = date.today().year - nasc
ctps = int(input('Carteira de Trabalho (0 se não possui): '))
if ctps !=... | Henrique-Botelho/ExerciciosDePython-Curso-em-Video | Exercícios Aula 19/Ex. 092.py | Ex. 092.py | py | 636 | python | pt | code | 0 | github-code | 1 |
22119528446 | import numpy as np
import cv2
def load_image(path_img):
return cv2.imread(path_img)
def bgr2hsv(img):
return cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
def setRangeColor(hsv, lower_color, upper_color):
return cv2.inRange(hsv, lower_color, upper_color)
def contours_img(mask):
contours,_ = cv2.... | opsun1/code | color_detection.py | color_detection.py | py | 3,063 | python | en | code | 0 | github-code | 1 |
15166107096 | import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import os
all_models = pd.read_csv('model_results.csv')
all_models['Accuracy'] = all_models['target_response']
folder = 'accuracy_plots'
mymax = all_models.query('Task == "Different"').groupby(
['c', 'Representation', 'Category', 'Subcateg... | crasanders/vision | plot_model_accuracy.py | plot_model_accuracy.py | py | 3,031 | python | en | code | 0 | github-code | 1 |
25029382246 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 19 11:53:10 2022
@author: albertomengual
"""
def f1():
print('My name is')
for i in range(5):
print('Jimmy Five Times ' + str(i))
# The code in the for loop is run five times. The first time it is run, the
# variable ... | aldamepi/Udemy-AutomatePython | for_example.py | for_example.py | py | 895 | python | en | code | 0 | github-code | 1 |
34459058884 | import os, sys
from typing import Union, List
import numpy as np
import pandas as pd
from sklearn.preprocessing import scale
import torch
import torch.nn as nn
from torch.utils.data import Dataset
def load_data(data_path):
name = ["train", "test"]
columns = [f"V{i}" for i in range(1, 31)]
val_columns = ... | doyooni303/UnsupervisedAnomalyDetection_VAE | src/build_datset.py | build_datset.py | py | 1,789 | python | en | code | 0 | github-code | 1 |
36783915591 | import numpy as np
import matplotlib.pyplot as plt
import higra as hg
import torch
from tqdm import tqdm
#=========================================
#= Helper Functions =
#=========================================
def get_centroids(X, high_dim_clusters,K,device="cpu",dim=2):
index_sets = [np.a... | hci-unihd/DTAE | loss.py | loss.py | py | 3,853 | python | en | code | 6 | github-code | 1 |
26074240113 | import json
from flask import Flask, redirect, request, render_template
from oauth2client.client import flow_from_clientsecrets
from config import GOOGLE_CLIENT_SECRETS_JSON, REGISTERED_CREDENTIALS_JSON
server_uri = 'http://localhost:5000'
app = Flask(__name__)
flow = flow_from_clientsecrets(
GOOGLE_CLIENT_SECR... | sk364/inbox-cleaner | server.py | server.py | py | 1,740 | python | en | code | 0 | github-code | 1 |
27286970033 | import numpy as np
import pandas as pd
import pytest
from cleanlab.datalab.internal.issue_manager import IssueManager
from cleanlab.datalab.internal.issue_manager_factory import REGISTRY, register
class TestCustomIssueManager:
@pytest.mark.parametrize(
"score",
[0, 0.5, 1],
ids=["zero", "... | cleanlab/cleanlab | tests/datalab/test_issue_manager.py | test_issue_manager.py | py | 1,931 | python | en | code | 7,004 | github-code | 1 |
70561841635 |
import tensorflow.keras.backend as K
import matplotlib.pyplot as plt
from tensorflow.keras.callbacks import Callback
class LRFinder(Callback):
#adjuted callback from Lucas Anders at: https://github.com/LucasAnders1/LearningRateFinder/blob/master/lr_finder_callback.py
#adjusted to geometrically increase by ste... | valentinocc/Keras_cifar10 | custom_callbacks.py | custom_callbacks.py | py | 5,315 | python | en | code | 0 | github-code | 1 |
8803458348 | from typing import Union
import requests as r
from requests_toolbelt.multipart.encoder import MultipartEncoder
class PetFriends:
def __init__(self):
self.base_url = 'https://petfriends1.herokuapp.com/'
def get_api_key(self, email: str, password: str):
"""Метод получения ключа API"... | 313109116/Unit_19.7 | api.py | api.py | py | 2,661 | python | ru | code | 0 | github-code | 1 |
2775509897 | """
https://leetcode.com/problems/ugly-number-ii/
"""
class Solution:
def nthUglyNumber(self, n: int) -> int:
nums = [1]
k = 3
factors = (2, 3, 5)
powers = [0] * k
for i in range(n - 1):
candidate_nums = [factors[i] * nums[powers[i]] for i in range(k)]
... | alexparunov/leetcode_solutions | src/200-300/_264_ugly-number-ii.py | _264_ugly-number-ii.py | py | 500 | python | en | code | 1 | github-code | 1 |
39101218782 | # type: ignore
import json
fin = open("secrets.json")
raw_data = fin.read()
#print(raw_data)
environ_data = json.loads(raw_data)
def load(os, db):
for i in environ_data:
os.environ[i] = environ_data[i]
| py660/PyChat-Self-Deploy | shh.py | shh.py | py | 216 | python | en | code | 0 | github-code | 1 |
30632192338 | import argparse
import json
import os
import platform
import PySide6 as RefMod
import PyInstaller.__main__
from mapclient.core.provenance import reproducibility_info
from mapclient.settings.definitions import APPLICATION_NAME, FROZEN_PROVENANCE_INFO_FILE
# Set Python optimisations on.
os.environ['PYTHONOPTIMIZE'] ... | MusculoskeletalAtlasProject/mapclient | res/pyinstaller/create_application.py | create_application.py | py | 3,596 | python | en | code | 19 | github-code | 1 |
73111750755 | # -*- coding: utf-8 -*-
# __author__ = 'XingHuan'
# 6/17/2018
import os
import sys
from sins.module.sqt import *
from sins.utils.res import resource
from sins.ui.widgets.file_dialog import FileDialog
from sins.test.test_res import TestPic
IMAGE_WIDTH = 400
IMAGE_HEIGHT = 300
class ImageUploadEdit(QWidget):
app... | ZackBinHill/Sins | sins/ui/widgets/image_upload_edit.py | image_upload_edit.py | py | 2,333 | python | en | code | 0 | github-code | 1 |
538148120 | import streamlit as st
import datetime
import requests
import json
import pandas as pd
import time
page = st.sidebar.selectbox('chose your page', ['users', 'checkin', 'checkout'])
if page == 'users':
st.title('ユーザー登録画面')
with st.form(key='user'):
username: str = st.text_input('ユーザー名', max_chars=12)
... | terotero57/tes | app.py | app.py | py | 7,125 | python | en | code | 0 | github-code | 1 |
239044330 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def print_list(self):
temp = s... | Melkor7354/Linked-list-practice | linked_list.py | linked_list.py | py | 1,121 | python | en | code | 0 | github-code | 1 |
25608601191 | import json
with open( "Task2.json","r+")as f:
data=json.load(f)
def group_of_decade(movies):
dic={}
list1=[]
for i in movies:
m=int(i)%10
decade=int(i)-m
if decade not in list1:
list1.append(decade)
list1.sort()
for i in list1:
dic[i]=[]
for i in ... | Subhkirti/PYTHON | WEB SCRAPPING/TASK3.py | TASK3.py | py | 666 | python | en | code | 0 | github-code | 1 |
10867449440 | import pyproptest.basicGenerators as bg
import pyproptest.testing as pytest
class sortingTests:
@staticmethod
@bg.test([bg.intListArb(10,-100,100)])
def prop_equalLength(i):
return len(i) == len(sorted(i))
@staticmethod
@bg.test([bg.intListArb(10,-100,100)])
def prop_sortedResult(i... | test1932/pyproptest | tests/runTests.py | runTests.py | py | 717 | python | en | code | 0 | github-code | 1 |
21532212683 | # -*- coding: utf-8 -*-
import scrapy
from protectoras_scrap.models.Pet import Pet
class ProtectoraLugoSpider(scrapy.Spider):
name = 'protectora_lugo_spider'
allowed_domains = ['www.protectoralugo.org']
base_url = 'http://www.protectoralugo.org/'
start_urls = ['http://www.protectoralugo.org/templates/j... | SaulEiros/protectoras-scraper | protectoras_scrap/spiders/protectora_lugo_spider.py | protectora_lugo_spider.py | py | 1,447 | python | en | code | 0 | github-code | 1 |
74329843233 | import numpy as np
from sympy import Matrix
import string
import random
dim = 2 #n차원 행렬
cipher = string.ascii_uppercase
def main():
mode = input("Select Encrypt or Decrypt:")
if mode == 'Encrypt':
encrypt()
elif mode == 'Decrypt':
decrypt()
def encrypt():
key = np.matrix([[1, 2], [2, 5]... | jeongyoonlee2015/Ciphers | Theoretical/hillCipher.py | hillCipher.py | py | 1,602 | python | en | code | 1 | github-code | 1 |
9907501422 | #!/usr/bin/env python3
import sys
import re
import sqlite3
import codecs
season_length = 14
def __grab(term, lines):
for line in lines:
if term in line:
return line
def __get_line(term, lines):
num = 0
for line in lines:
num = num+1
if term in line:
retur... | phantom-voltage/mortician | scripts/cdda.py | cdda.py | py | 5,313 | python | en | code | 0 | github-code | 1 |
264166147 | """django_obj URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-ba... | zhouf1234/django_obj | django_obj/urls.py | urls.py | py | 1,554 | python | en | code | 0 | github-code | 1 |
73426657635 | from time import sleep
import requests
def parsing_data(token_key, repos_list):
url = "https://api.github.com/repos/{}/{}"
headers = {
"Accept": "application/vnd.github.v3+json",
"Authorization": "token {}".format(token_key), # 此处的XXX代表上面的token
"X-OAuth-Scopes": "repo"
}
urls =... | freedanfan/delete_gitlab_repositories | delete_gitlab_repositories.py | delete_gitlab_repositories.py | py | 1,191 | python | en | code | 1 | github-code | 1 |
41440456232 | from collections import deque
from time import sleep
def append_one(num):
return int(str(num) + '1')
def solution(num, target):
queue = deque()
queue.append([num, 0])
while(queue):
cur_num, cur_cnt = queue.popleft()
if cur_num == target:
return cur_cnt + 1
... | aszxvcb/TIL | BOJ/boj16953.py | boj16953.py | py | 738 | python | en | code | 0 | github-code | 1 |
23080189321 | from parsing import parse_polynomial
from ft_math import ft_sqrt, ft_abs, pgcd
class Polynomial:
def __init__(self, polynomial) -> None:
if isinstance(polynomial, str) is False:
raise TypeError("Only str is accepted")
try:
self.values = parse_polynomial(polynomial)
... | adbenoit-9/42_computorv1 | polynomial.py | polynomial.py | py | 6,588 | python | en | code | 0 | github-code | 1 |
2396932646 | import pathlib
# directories
DATA_DIR = pathlib.Path(__file__).resolve().parent.parent / "data"
RESOURCE_DIR = pathlib.Path(__file__).resolve().parent.parent / "resources"
MODEL_DIR = RESOURCE_DIR / "checkpoints"
WSD_DIR = DATA_DIR / "wsd_corpora"
TRAIN_DIR = DATA_DIR / "train"
DEV_DIR = DATA_DIR / "dev"
MAPPING_DIR =... | Riccorl/elmo-wsd | elmo-wsd/constants.py | constants.py | py | 1,683 | python | en | code | 2 | github-code | 1 |
15279633261 | #using bucket sort
def assignBikes(self, workers, bikes):
m, n = len(workers), len(bikes)
def manhattan(a, b):
(x1, y1), (x2, y2) = a, b
return abs(x1-x2) + abs(y1-y2)
buckets = [[] for _ in range(2001)]
for i, worker in enumerate(workers):
... | onyxolu/DSA | Tunmise/google/climbing_bikes.py | climbing_bikes.py | py | 2,053 | python | en | code | 0 | github-code | 1 |
73268716835 | import json
test_list =\
[{"Title":"Harry Potter", "DVD":"T", "Form":"C", "Genre":"Fantasy", "Date":"2003", "Alt Title 1":"", "Alt Title 2":"", "Count":1, \
"Director":"Jon","Writer":"Rowling", "Language":"English", "Date Watched":"2019", "Spec":""}, \
{"Title":"Transformers", "DVD":"F", "Form":"B", "Genre... | Leeoku/MovieDatabase | main.py | main.py | py | 789 | python | en | code | 0 | github-code | 1 |
70508257953 | import itertools
#taking input
k=int(input())
a=list(map(int,input().split()))
#generating prime numbers
soe=[True]*(100000)
for i in range(2,100000):
if soe[i]==True:
j=i+i
while j<100000:
soe[j]=False
j+=i
#storing prime numbers whith in given input
p=[i for i in range(2,le... | jay8299/practice_cp | python_prac/smarttraining_infytq.py | smarttraining_infytq.py | py | 572 | python | en | code | 0 | github-code | 1 |
8243965245 | import numpy as np
import random
import matplotlib.pyplot as plt
import pickle
class Dataset:
def __init__(self):
self.index = 0
self.obs = []
self.classes = []
self.num_obs = 0
self.num_classes = 0
self.indices = []
def __iter__(self):
return self
... | moritzlangenberg/SCaML6 | network.py | network.py | py | 13,504 | python | en | code | 0 | github-code | 1 |
4347841797 | # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see
# that the 6th prime is 13.
# What is the 10 001st prime number?
import time
t=time.time()
def project_7(n):
l=[]
num=2
l.append(2)
while len(l)-1<n:
if all(num%i!=0 for i in range(2,int((num)**0.5)+1)):
l.appen... | pedramsalimi/Euler-Projects-with-Python | Project_7.py | Project_7.py | py | 397 | python | en | code | 2 | github-code | 1 |
12079240635 | # Maximum of Odd and Even Digit Count
# An integer N is passed as input. The program must print the odd digit count if odd digit count is greater than even digit count. Else the program must print the even digit count.
# Boundary Condition(s):
# 1 <= N <= 999999999
# Input Format:
# The first line contains N.
# Outp... | Logesh08/Programming-Daily-Tests | Maximum of Odd and Even Digit Count.py | Maximum of Odd and Even Digit Count.py | py | 595 | python | en | code | 0 | github-code | 1 |
16778853734 | """
Salidas esperadas (lo que quiero obtener):
El apellido del mayor deudor es: Massingham
El total de deuda acumulada de los riocuartenses es de $624606
Los nombres de pila de los clientes cuyos DNI comiencen con 2 son:
Elmore
Wheeler
"""
datos = [
'37572991#Shauna Romanov#137345#Villa María',
'4366... | pablokan/23prog1 | parciales/B/acotto_primerParcial.py | acotto_primerParcial.py | py | 2,096 | python | es | code | 0 | github-code | 1 |
17715925911 | """The medical image object.
This module defines :class:`MedicalVolume`, which is a wrapper for nD volumes.
"""
import warnings
from copy import deepcopy
from mmap import mmap
from numbers import Number
from typing import Sequence, Tuple, Union
import nibabel as nib
import numpy as np
import pydicom
from nibabel.spat... | ad12/DOSMA | dosma/core/med_volume.py | med_volume.py | py | 54,208 | python | en | code | 49 | github-code | 1 |
36170270181 | from abc import ABCMeta, abstractmethod
from bisect import bisect_right
from typing import Any, Dict, Iterable, List, Optional, Tuple
from volatility3.framework import exceptions, interfaces
from volatility3.framework.configuration import requirements
from volatility3.framework.layers import linear
class NonLinearly... | volatilityfoundation/volatility3 | volatility3/framework/layers/segmented.py | segmented.py | py | 6,939 | python | en | code | 1,879 | github-code | 1 |
4733428989 | # Name: BoPclip.py
# Created on: 2017-03-06
# Author: Jessica Nephin
# Description:
# Clips NCC bottom patches to correct boundary
# Converts factor attributes
# Removes fields
# Import modules
import os
import arcpy
# move up one directory
os.chdir('..')
# allow overwriting
arcpy.env.overwriteOutput = True
... | jnephin/align-predictors | BoPclip.py | BoPclip.py | py | 2,757 | python | en | code | 0 | github-code | 1 |
74112978272 | from commands.Command import Command
import discord
import asyncio
class Cat(Command):
def __init__(self):
super().__init__(
{
'name': 'cat',
'description': 'extracts the text content of your file',
'argc': 1
}
)
async de... | luccanunes/code-runner-bot | commands/Cat.py | Cat.py | py | 1,045 | python | en | code | 0 | github-code | 1 |
36039000703 | import random
secret = "anqomr"
def numOfMatch(w1, w2):
ans = 0
for i in range(len(w1)):
if w1[i] == w2[i]:
ans += 1
return ans
def guess(w):
return numOfMatch(w, secret)
def findSecretWord(wordlist, guess):
"""
:type wordlist: List[Str]
:type master: Master
:rt... | zhaoxy92/leetcode | 843_guess_word.py | 843_guess_word.py | py | 1,956 | python | en | code | 0 | github-code | 1 |
11807763247 |
import os
import glob
import shutil
import traceback
from .context import KFJobContext
class DataPathCleaner(object):
def __init__(self, base_path=None):
self.base_path = (base_path or '').strip() or (KFJobContext.get_context().get_user_path() or '').strip()
if self.base_path and not os.path.isab... | tencentmusic/cube-studio | job-template/job/pkgs/datapath_cleaner.py | datapath_cleaner.py | py | 1,972 | python | en | code | 1,577 | github-code | 1 |
1443567060 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 9 12:39:55 2022
@author: pkinn
"""
def cvTrain(model, features, targets, nSplits, nEpochs, batchSz, initWts):
from sklearn.model_selection import KFold
import numpy as np
kf = KFold(n_splits = nSplits, shuffle = True)
fn = 1
# Define per-fold score co... | Tessier-Lab-UMich/Emi_Pareto_Opt_ML | cvTrain.py | cvTrain.py | py | 1,305 | python | en | code | 14 | github-code | 1 |
10108533189 | """计算结果"""
from solve import solve
def quiz(show_style, is_int=True):
"""测验"""
print("注意!")
print("若结果为分数不需转换为小数。")
if is_int:
path = "problem_int.txt"
else:
path = "problem_fraction.txt"
file = open(path, "r", encoding="utf8")
problems = file.readlines()
total = len(pr... | HavEWinTao/BIT-CS | 软件工程基础/quiz.py | quiz.py | py | 1,004 | python | en | code | 1 | github-code | 1 |
34529095803 | import copy
import re
from knack.log import get_logger
from azdev.utilities import get_name_index
logger = get_logger(__name__)
_LOADER_CLS_RE = re.compile('.*azure/cli/command_modules/(?P<module>[^/]*)/__init__.*')
def filter_modules(command_loader, help_file_entries, modules=None, include_whl_extensions=False... | Azure/azure-cli-dev-tools | azdev/operations/linter/util.py | util.py | py | 4,677 | python | en | code | 71 | github-code | 1 |
72184037154 | import tqdm
import torch
import csv
import os
import os.path as osp
import random
import json
import h5py
import time
from collections import defaultdict
if __name__ == '__main__':
from MiniImageNet import MiniImageNetDataset, TransformedImageLoader, h5load
from base import MultiProcessImageLoader
else:
f... | alecwangcq/Prototypical-network | dataloader/MiniImageNetMAML.py | MiniImageNetMAML.py | py | 7,428 | python | en | code | 0 | github-code | 1 |
25922177105 | from swift.common.swob import wsgify, HTTPInternalServerError, HTTPException
from swift.common.utils import get_logger
from zion.handlers import ProxyHandler
from zion.handlers import ComputeHandler
from zion.handlers import ObjectHandler
from zion.handlers.base import NotFunctionRequest
from distutils.util import strt... | JosepSampe/storage-functions | Engine/swift/middleware/zion/function_handler.py | function_handler.py | py | 4,342 | python | en | code | 11 | github-code | 1 |
23605228901 | import numpy
screen = [[0]*120]*40
screen = numpy.array(screen)
objbrick = []
#component = [[]*120]*40
paddle = "^^^^^^"
brick1 = "▭"
ball = "◦"
exppaddle = "@"
shrpaddle = "*"
fastball = "&"
thruball = "%"
paddlegrab = "$"
ballmultiply = "#"
bullet = "."
shoot1 = "!"
bomb= "+"
ufo ="(__)"
objballmultiply = []
objpaddl... | raipro/Brick-Breaker | global1.py | global1.py | py | 698 | python | en | code | 0 | github-code | 1 |
2724354165 | from graphviz import Digraph
import pandas as pd
import numpy as np
import glob
import os
#Associa cada cor na planilha a um par (cor de fundo,cor da fonte) do Graphviz
colors = {'Amarelo':('yellow','black'),'Azul':('blue','white'),'Branco':('white','black'),
'Cinza':('grey','black'),'Marrom':('brown'... | lcoandrade/relationshipdiagram | diagrama_relacoes.py | diagrama_relacoes.py | py | 7,035 | python | pt | code | 0 | github-code | 1 |
8954539420 | import random
def game_rules():
print("Winning Rules of the Rock paper scissor game as follows: \n"
+"Rock vs paper->paper wins \n"
+ "Rock vs scissor->Rock wins \n"
+"paper vs scissor->scissor wins \n")
game_rules()
de... | solexy79/rock-paper-scissor-python | main.py | main.py | py | 2,346 | python | en | code | 0 | github-code | 1 |
31904502980 | from Tkinter import *
import tkMessageBox
import Tkinter
import random
import ttk
list=[0,0,0,0,0,0]
right1=0
right2=0
right3=0
wrong1=0
wrong2=0
wrong3=0
def msg(event=None):
val()
setwrong()
setval()
def helpp(event=None):
tkMessageBox.showinfo("Info","Select all ask... | Agoli01/Image-Captcha | ImageCaptcha/framecapcha.py | framecapcha.py | py | 6,083 | python | en | code | 0 | github-code | 1 |
30685906080 | """
验证码识别
1.简单的图像文字可以用tesseract或CNN神经网络训练数据集预测,再不行就云打码平台
2.极验(滑动)验证码要先计算窗口偏移量大小然后selenium模拟拖动按钮
tesseract是一个将图像翻译成文字的OCR库(optical character recognition) --> 识别验证码效果一般,还是用云打码平台吧
windows安装tesseract-ocr并配置环境变量
from PIL import Image
import pytesseract
img = Image.open("./test.jpg")
# 此处可能需要做降噪和二值化处理,去除干扰线等
print(pytesserac... | okccc/python | crawl/09_验证码识别.py | 09_验证码识别.py | py | 3,682 | python | en | code | 0 | github-code | 1 |
21080209384 | import message
class State:
def __init__(self, number):
self.number = number
def start_message(self):
message.Message.data()
def database_init():
table = Table("stat")
table.create(["id", "text", "callback"], ["int(5) PRIMARY KEY AUTO_INCREMENT", "VARCHAR(128)", "VARCHAR(128)"])... | 6a16ec/bot_7483934 | main/state.py | state.py | py | 1,789 | python | en | code | 0 | github-code | 1 |
73033768993 | # -*- coding: utf-8 -*-
'''
The AWS Cloud Module
====================
The AWS cloud module is used to interact with the Amazon Web Services system.
This module has been replaced by the EC2 cloud module, and is no longer
supported. The documentation shown here is for reference only; it is highly
recommended to change ... | shineforever/ops | salt/salt/cloud/clouds/botocore_aws.py | botocore_aws.py | py | 7,499 | python | en | code | 9 | github-code | 1 |
21358312248 | __author__ = ["fkiraly"]
from sktime.tests import test_all_estimators
def pytest_addoption(parser):
"""Pytest command line parser options adder."""
parser.addoption(
"--matrixdesign",
default=False,
help="sub-sample estimators in tests by os/version matrix partition design",
)
d... | orgTestCodacy11KRepos110MB/repo-5089-sktime | conftest.py | conftest.py | py | 499 | python | en | code | 0 | github-code | 1 |
11337631853 |
import pandas as pd
import numpy as np
import scipy.signal as sig
import matplotlib.pyplot as plt
import control as con
import scipy.fftpack
def FFT(x, fs):
N = len(x)
X_fft = scipy.fftpack.fft(x)
X_fft_shifted = scipy.fftpack.fftshift(X_fft)
freq = np.arange(-N/2, N/2) * fs/N
X_... | Shujaea/ECE351_CODE | Lab12 Project.py | Lab12 Project.py | py | 3,866 | python | en | code | 0 | github-code | 1 |
4348600276 | from pyspark.sql import SparkSession
from pyspark.ml.feature import MinMaxScaler
from pyspark.ml.linalg import Vectors
spark = SparkSession.builder.appName('normalization').getOrCreate()
spark.sparkContext.setLogLevel("WARN")
print("### spark starting ###")
records = [
(1, Vectors.dense([10.0, 10000.00, 1.0]),),... | yuyatinnefeld/spark | python/pyspark/ml_transformation/normalization.py | normalization.py | py | 793 | python | en | code | 0 | github-code | 1 |
8701827459 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 16 10:52:20 2018
@author: admin
"""
import re
p=re.compile('(c=)|(c-)|(dz=)|(d-)|(lj)|(nj)|(s=)|(z=)')
in_str=input()
l=len(in_str)
c_c=0
for c_w in re.finditer(p,in_str):
l-=len(c_w.group())
c_c+=1
print(l+c_c) | songkwangho/algorithm | 크로아티아 알파벳.py | 크로아티아 알파벳.py | py | 283 | python | en | code | 0 | github-code | 1 |
11026928784 | from bs4 import BeautifulSoup
import requests
import numpy as np
import pandas as pd
import re
import warnings
warnings.simplefilter(action='ignore')
titles = list()
locations = list()
pap = list()
dau = list()
serv = list()
desc = list()
bbt = list()
info = list()
title_text = list()
location_text = list()
pap_tex... | Williamz4lyf/My_Projects | lagos_listings/scrape_propertypro.py | scrape_propertypro.py | py | 2,743 | python | en | code | 0 | github-code | 1 |
38946099835 | import logging
from json import load
from os.path import isdir
from time import time
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.tree import DecisionTreeRegressor
def get_setting(arg_setting_name, arg_settings):
if arg_setting_name in arg_settings.keys():
... | mikedelong/animated-kaggle | code/predict.py | predict.py | py | 4,735 | python | en | code | 0 | github-code | 1 |
43438440366 | # Find prime numbers among permutations of given integers
#
# Sieve of Eratosthenes: why only calculate upto sqrt(n)?
# - https://math.stackexchange.com/questions/58799/why-in-sieve-of-erastothenes-of-n-number-you-need-to-check-and-cross-out-numbe
#1. regular permutation creation + regular trial division
#- 25.20s us... | jocho-here/coding-problems | python/prime_in_permutation.py | prime_in_permutation.py | py | 4,867 | python | en | code | 0 | github-code | 1 |
6380421844 | from machine import Pin
from utime import sleep
# GPIO pin designations
pin20 = Pin(20)
pin21 = Pin(21)
i2c = machine.I2C(0, sda=pin20, scl=pin21, freq=400000)
from ssd1306 import SSD1306_I2C
oled = SSD1306_I2C(128, 32, i2c)
oled.fill(0)
sleep(1)
oled.show()
oled.text('Hello Caroline', 0, 0)
oled.show()
sleep(2)
o... | willnotwish/pi-pico-experiments | getting-started/main.py | main.py | py | 491 | python | en | code | 1 | github-code | 1 |
71534665953 | import json
def get_utterance_indices(utterance):
utterance += " "
index = 0
for i in range(len(utterance)):
if utterance[i] == ' ':
print(utterance[index:i]+" "+str(index))
index = i+1
print("Last index : {}".format(len(utterance)-1))
with open('final_result.json') as js... | guptaSneha31/Bot-Assignment- | json_repair.py | json_repair.py | py | 903 | python | en | code | 0 | github-code | 1 |
29752726253 | import sys
sys.path.append('../')
import cnvfc
import numpy as np
import pandas as pd
import pathlib as pal
root_p = pal.Path('../data/')
pheno_p = root_p / 'pheno/Pheno.csv'
connectome_p = root_p / 'preprocessed/connectome/sample_connectome/python/'
connectome_t = 'connectome_s{}_mist64.npy'
label_p = root_p / 'parce... | surchs/Neuropsychiatric_CNV_code_supplement | Scripts/FC_case_control_contrast.py | FC_case_control_contrast.py | py | 1,540 | python | en | code | 4 | github-code | 1 |
37213121317 | import numpy as np
import pandas as pd
import os
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
import mlflow
from ydata_profiling import ProfileReport
from trail import Trail
import inspect
def dataloader():
for dirname, _, filenames in os.walk('./input... | NikolausPinger/titanic | baseline.py | baseline.py | py | 2,499 | python | en | code | 0 | github-code | 1 |
72153311074 | """Model serialization/deserialization schema."""
import inspect
from typing import Type
from pydent.marshaller.descriptors import DataAccessor
from pydent.marshaller.exceptions import CallbackValidationError
from pydent.marshaller.exceptions import MultipleValidationError
from pydent.marshaller.exceptions import Sche... | aquariumbio/pydent | pydent/marshaller/schema.py | schema.py | py | 8,155 | python | en | code | 6 | github-code | 1 |
20623982774 | from sympy import symbols, sin, tan, cos, limit, pi, oo, latex
def main():
def limnote(expr, n):
r"""Expr and n must be a pure expr"""
lat = r"\lim_{x \rightarrow " + str(latex(n)) + r"} " + latex(expr)
return str(lat)
x = symbols('x')
# expr = ((x * sin(5*x))/(tan(2*... | David-Sirait01/SCnLM-Informatika-23-24 | Limit & Integral/Limit/Short/main.py | main.py | py | 1,372 | python | en | code | 0 | github-code | 1 |
27666830311 | '''
Input: a List of integers
Returns: a List of integers
'''
def moving_zeroes(arr):
# Your code here
# See if the array has any zeros
# FIRST PASS SOLUTION
if 0 not in arr:
return arr
# What is the length of the current array
length = len(arr)
# Make a new array with no zeros
... | raythurman2386/cs-algorithms | moving_zeroes/moving_zeroes.py | moving_zeroes.py | py | 731 | python | en | code | 0 | github-code | 1 |
42272214993 | """
Module for building and manipulating astronomical catalogues.
@author: A.Ruiz
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six.moves import zip, range
from io import open
import os
import warnings
import tempfile
import subprocess
from copy ... | ruizca/astromatch | astromatch/catalogues.py | catalogues.py | py | 37,736 | python | en | code | 5 | github-code | 1 |
20994301540 | from __future__ import absolute_import, division, print_function, unicode_literals
from typing import List, Dict, Tuple, Iterable, Type, Any
import fidia
# Python Standard Library Imports
# from collections import OrderedDict, Mapping
from copy import deepcopy
# Other Library Imports
# import pandas as pd
import sq... | astrogreen/fidia | fidia/archive/archive.py | archive.py | py | 24,238 | python | en | code | 0 | github-code | 1 |
12307570528 |
import math
import numpy as np
from scipy.special import erf
from scipy import stats
norm = stats.norm
class BSOPM_Class:
def disc_function(self, FV, r, T):
PV = FV * np.exp(-r*T)
return PV
def bs_d1_d2(self,St,r,t,K,call,sig):
d1 = np.log(St/K)
d1 += ( sig*sig/2 + r)*t
with np.errstate(di... | aclime/vix | bsopm.py | bsopm.py | py | 2,041 | python | en | code | 0 | github-code | 1 |
44569908079 |
import heapq
import config
import logbot
log = logbot.getlogger("ASTAR")
class PathNode(object):
def __init__(self, coords, cost=1):
self.coords = coords
self.cost = cost
self.g = 0
self.h = 0
self.f = 0
self.step = 0
self._parent = None
self.has... | FrederickGeek8/TwistedBot | twistedbot/pathfinding.py | pathfinding.py | py | 4,625 | python | en | code | null | github-code | 1 |
4667314344 | from threading import Thread
from . import tm_tc_internal_handler
import time
class TMTCRedeployHandler(Thread):
"""
This thread is started by external tm-tc subscriber to handle re-deploying of
TMTC service (by creating internal kicker and setting/resetting internal oper-data).
"""
def __init__... | lucianonunes/vtal-yangs | vtal/cisco-tm-tc-fp/python/cisco_tm_tc_fp/tm_tc_redeploy_handler.py | tm_tc_redeploy_handler.py | py | 1,435 | python | en | code | 0 | github-code | 1 |
35157210724 | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression, RidgeClassifier
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from s... | ManishSinghh/Major_project | train_model.py | train_model.py | py | 1,517 | python | en | code | 0 | github-code | 1 |
16190921784 | import torch
import torch.nn as nn
import torch.nn.functional as F
from itertools import chain
class GaussianActorCriticNet(nn.Module):
def __init__(self, state_size, action_size, shared_layers, actor_layers, critic_layers, std_init=0):
super(GaussianActorCriticNet, self).__init__()
self.shared... | telmo-correa/DRLND-project-2 | model.py | model.py | py | 2,913 | python | en | code | 2 | github-code | 1 |
25058294272 | import torch, vtk
import numpy as np
import h5py
from vtk_utils import *
import os
from scipy.stats import zscore
path = 'Twin_Transformers'
folder_name = '/media/shawey/SSD8T/GyraSulci_Motor/'+path+'/figs'
weis = os.listdir(folder_name)
filename = "/media/shawey/SSD8T/GyraSulci_Motor/H5_vtk/100408.h5"
f1 = h5py.File... | Shawey94/Gyral_Sulci_Project | Code/pkl2vtkV2.py | pkl2vtkV2.py | py | 1,535 | python | en | code | 0 | github-code | 1 |
16845484949 | import errno
import os
import re
import threading
import unittest
try:
from unittest import mock
except ImportError:
import mock
import ptracer
eperm_mock = mock.Mock(
side_effect=OSError(errno.EPERM, 'Operation not permitted'))
class TestPtracer(unittest.TestCase):
@mock.patch('ptracer.ptrace.att... | pinterest/ptracer | tests/test_ptracer.py | test_ptracer.py | py | 4,300 | python | en | code | 150 | github-code | 1 |
8479598404 | import sqlalchemy
from fastapi import Depends
from sqlalchemy.orm import Session
from src.data_layer.bot_io import OrderInput
from src.data_layer.db_connector import get_db
from src.models.order import OrderModel
from fastapi import APIRouter
router = APIRouter()
@router.post("/order")
def get_order_by_hospital_id(ho... | AshikaInnovate/LocAid_Project | src/endpoints/order.py | order.py | py | 2,646 | python | en | code | 0 | github-code | 1 |
13428488153 | import torch
from torch.utils.data import Dataset, DataLoader, SequentialSampler, RandomSampler
from utils_MTL import (str2bool,
init_seed,
load_json_data,
get_pretrained_tokenizer,
get_pretrained_model,
g... | woog2ee/KGEC-MTL | MTL/test_MTL.py | test_MTL.py | py | 3,502 | python | en | code | 0 | github-code | 1 |
9640228574 | from openpyxl.styles import NamedStyle, Font, Border, Side, Alignment, PatternFill
from openpyxl.formatting.rule import ColorScaleRule
# 薄緑(主にheader用)
style_00 = NamedStyle(name="style_00",
font=Font(bold=True, size=10.5),
fill=PatternFill(patternType='solid', start_color='... | copipe/nclick | nclick/excel/cell_styles.py | cell_styles.py | py | 4,958 | python | en | code | 0 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.