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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
27365994887 | import codecs
import json
import uuid
import re
from scrapy.utils.markup import remove_tags
from scrapy.utils.serialize import ScrapyJSONEncoder
from typing import Union
from scrapper.crowler.data.object import Variant, Step
class JsonWithEncodingPipeline(object):
def __init__(self):
self.... | Paleontolog/summarizer_service | crowler/pipelines/pipel.py | pipel.py | py | 1,896 | python | en | code | 0 | github-code | 36 |
5011304095 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from testcase.BasicTestCase import BasicTestCase
from HelperPage.Helper_Login import Helper_login
from HelperPage.Helper_Logout import Helper_Logout
from HelperPage.Helper_Pulish import Helper_Publish
from HelperPage.Helper_Reply import Helper_Reply
import time
class testLogi... | renhuigit/discuz_python | Webauto_Discuz_TestPython/testcase/testLogin.py | testLogin.py | py | 1,352 | python | en | code | 0 | github-code | 36 |
29739632222 | import os
def read_file(file_path: str) -> str:
"""Read content of file provided."""
with open(file_path, "r", encoding="utf-8") as reader:
return reader.read()
def write_file(to_write: str, file_path: str) -> None:
"""Write input string to file."""
folder_path = os.path.dirname(file_path)
... | Syndallic/py-to-ts-interfaces | py_to_ts_interfaces/file_io.py | file_io.py | py | 498 | python | en | code | 7 | github-code | 36 |
41633545139 | # Contest Page: https://www.codechef.com/NOV21C/
def hillSequence(arr_size, arr):
if arr_size == 1:
return arr
arr.sort(reverse=True)
count = 1
if arr[0] == arr[1]: # The max value cannot be repeated
return -1
if arr_size == 2:
return arr
for i in range(2, arr_si... | hamaldonado/CodeChef-Python | Python/NOV21C/HillSequence.py | HillSequence.py | py | 1,056 | python | en | code | 0 | github-code | 36 |
34140146726 | from __future__ import print_function, division
import we
import json
import numpy as np
import sys
if sys.version_info[0] < 3:
import io
open = io.open
"""
Hard-debias embedding
Man is to Computer Programmer as Woman is to Homemaker? Debiasing Word Embeddings
Tolga Bolukbasi, Kai-Wei Chang, James Zou, Venkates... | JasmineZhangxyz/nlp-optimization-objective | bolukbais2016 + bias metrics/debias.py | debias.py | py | 2,466 | python | en | code | 0 | github-code | 36 |
20422284442 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 5 00:48:35 2019
@author: Vamshi Krishna
"""
import matplotlib.pyplot as plt
emp_names=['vamshi','preethi','santhosh','deexita']
emp_salary=[80000,75000,60000,80000]
plt.pie(emp_salary,labels=emp_names,radius=2,autopct='%0.0f%%',shadow=True,explode=[0.2,0,0,0])... | RevanthR/AI_Assignments | Assignment4piegraph.py | Assignment4piegraph.py | py | 334 | python | en | code | 0 | github-code | 36 |
3489772775 | #Create a function and ask the user for two inputs and ask what is the operators
def func():
x=int(input("Enter the num 1 : "))
y=int(input("Enter the num 2 : "))
z=input("Choose '+', '-', '*', '/', '%': ")
if(z=='+'):
print("Addition :",x+y)
elif(z=='-'):
print("Substraction :",x-y)
elif(z=='*'):
... | anujpaunikar/TNAssignments | simpleCalculator.py | simpleCalculator.py | py | 450 | python | en | code | 0 | github-code | 36 |
30672279272 | import jingo
from devmo import (SECTION_USAGE, SECTION_ADDONS, SECTION_APPS, SECTION_MOBILE,
SECTION_WEB)
from feeder.models import Bundle, Feed
def home(request):
"""Home page."""
tweets = []
for section in SECTION_USAGE:
tweets += Bundle.objects.recent_entries(section.twitter... | ozten/mdn | apps/landing/views.py | views.py | py | 1,924 | python | en | code | 1 | github-code | 36 |
4221751433 | #!/usr/bin/env python3
"""
Extensive database of location and timezone data for nearly every airport and landing strip in the world.
"""
from __future__ import annotations
import csv
from pathlib import Path
from typing import Dict, Literal, TypedDict
__project_name__ = __package__
# Release numbering follows the r... | legoironman1234/IATAGuesser | IATAGuesser/airportsdata/__init__.py | __init__.py | py | 3,193 | python | en | code | 0 | github-code | 36 |
1789536758 | import math
# The direction of wolf3d objects in the order their sprites appwear
wolf3d_sprite_directions = [
"s", # towards you
"sw",
"w", # facing left
"nw",
"n", # facing away from you
"ne",
"e", # facing right
"se"
]
# the order in which 0-360 degrees maps to quadra... | jammers-ach/pywolf3d | pywolf3d/util.py | util.py | py | 1,050 | python | en | code | 0 | github-code | 36 |
9766145404 | """
This script is used to compute neural network embeddings.
"""
import torch
import numpy as np
import sklearn
import pickle
import os
import json
import argparse
from pathlib import Path
from tqdm import tqdm
import librosa
from utils import extract_spectrogram
from models import AudioEncoder
de... | andrebola/contrastive-mir-learning | encode.py | encode.py | py | 3,368 | python | en | code | 13 | github-code | 36 |
74311600743 | import numpy as np
import glob
import os
from blimpy import Waterfall
import blimpy as bl
import gc
import time
import matplotlib
import matplotlib.pyplot as plt
start=time.time()
def get_elapsed_time(start=0):
end = time.time() - start
time_label = 'seconds'
if end > 3600:
end = end/3600
... | Tusay/589_ML | get_images.py | get_images.py | py | 4,546 | python | en | code | 0 | github-code | 36 |
41715969518 | import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
def hidden_init(layer):
fan_in = layer.weight.data.size()[0]
lim = 1. / np.sqrt(fan_in)
return (-lim, lim)
class Actor(nn.Module):
"""Initialize parameters and build model.
Args:
... | zachterrell57/stock-trading | DDPG Example Implementation/network.py | network.py | py | 2,616 | python | en | code | 0 | github-code | 36 |
34438943697 | import gaia.recognition as recognition
import gaia.draw as draw
import gaia.resize as resize
import gaia.utils as cfg
import gaia.people as model
recognizer = recognition.face_recognizer()
recognizer.read('data/trainer.yml')
people = model.all()
def predict(frame):
global recognizer
print("Predicting...")
... | thiagozampieri/gaia-loginface | gaia/predict.py | predict.py | py | 721 | python | en | code | 0 | github-code | 36 |
7207753656 | # geospatial help functions
import geopandas as gpd
import matplotlib.pyplot as plt
def show_overlaps(data_temp, id_col):
# checks and plots which areas overlap
overlaps = []
for index, row in data_temp.iterrows():
data_temp1 = data_temp.loc[data_temp[id_col] != row[id_col]] # grab all ro... | PeterFriedrich/bridge_the_gap | helper_functions.py | helper_functions.py | py | 1,286 | python | en | code | 0 | github-code | 36 |
8670554139 | import logging
from cterasdk import CTERAException
def unsuspend_filer_sync(self=None, device_name=None, tenant_name=None):
"""Unsuspend sync on a device"""
logging.info("Starting unsuspend sync task.")
try:
device = self.devices.device(device_name, tenant_name)
device.sync.unsuspend()
... | ctera/ctools | unsuspend_sync.py | unsuspend_sync.py | py | 480 | python | en | code | 4 | github-code | 36 |
38053442903 | def special_typing():
# your code here ^_^
def func(substring, location):
Length = len(substring)
if targetLen <= location:
return Length
nextList = []
for i in range(0, Length, 2):
if substring[i] == target[location]:
nextList.append(i)
... | RussellXX/2023-Spring-SEI | stream_readcsv_specialtyping/24-specialtyping/src/special_typing.py | special_typing.py | py | 1,091 | python | en | code | 0 | github-code | 36 |
40244178963 | import sys
#we want to divide children in groups due to their ages in such way that the
#largest difference in age of any two children in one gorup will be at most 1#
#and we also want to minimize the number of groups
#The task is equal to cover points on the axe with segments of length 1
def MinGroupsNaive(C):
R ... | NastyaMelnik57/Coursera | Algorithms/PointsCoverSorted.py | PointsCoverSorted.py | py | 648 | python | en | code | 0 | github-code | 36 |
2168304898 | import wave
import numpy as np
import scipy
from scipy.io.wavfile import read
from scipy.signal import hann
from scipy.fftpack import rfft
import matplotlib.pyplot as plt
def plotFreqSpec(filename,graphpath=None):
# read audio samples
framerate,data = read(filename)
file = wave.open(filename, 'rb')
n... | Mheeh/Audio | spectrum.py | spectrum.py | py | 1,348 | python | en | code | 0 | github-code | 36 |
70291499304 | import webapp2
import random
def rand_fortune():
fortunes = ["To avoid criticism, do nothing, say nothing, be nothing", "Error 404: Fortune not found", "Optimist believe we live in the best of worlds and pessimists fear this is true.", "Of all our human resources, the most precious is the desire to improve"]
i... | freddyworldpeace/fortune-cookie | main.py | main.py | py | 1,023 | python | en | code | 0 | github-code | 36 |
42360805462 | from django.shortcuts import render, redirect, reverse
# Create your views here.
from django.views.decorators.http import require_GET
from django.contrib.auth.decorators import login_required
from goods.models import Goods
from . import models
@require_GET
@login_required
def add(req, count, goods_id):
goods = ... | hwzHw/python37 | dayWeb/myshopping/shopcart/views.py | views.py | py | 1,215 | python | en | code | 0 | github-code | 36 |
462199369 | # the dupe bot needs a lot of special logic so it can't really use the same code as the other bots sadly
import discord
import logging
import time
import asyncio
from enum import Enum
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import ... | Sadtrxsh/Mathboi | dupe.py | dupe.py | py | 14,259 | python | en | code | 0 | github-code | 36 |
17436666953 | import functools
import torch.nn as nn
import os
import sys
import time
import random
import argparse
import torch
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(i... | xmed-lab/EPL_SemiDG | network/resnet.py | resnet.py | py | 9,203 | python | en | code | 33 | github-code | 36 |
21332967957 | from sostrades_core.execution_engine.sos_wrapp import SoSWrapp
from climateeconomics.core.core_land_use.land_use_v1 import LandUseV1
from sostrades_core.tools.post_processing.charts.chart_filter import ChartFilter
from sostrades_core.tools.post_processing.charts.two_axes_instanciated_chart import InstanciatedSeries,\
... | os-climate/witness-core | climateeconomics/sos_wrapping/sos_wrapping_land_use/land_use/land_use_v1_disc.py | land_use_v1_disc.py | py | 15,085 | python | en | code | 7 | github-code | 36 |
38219558633 | from news_api import get_top_headlines, filter_articles
from send_email import send_email
if __name__ == "__main__":
page_size = 20 # Change this to the desired page size
page_number = 1 # Start from the first page
articles = get_top_headlines(page_size=page_size, page=page_number)
if articles:
... | VarshaDas/PyDailyNews | main.py | main.py | py | 408 | python | en | code | 0 | github-code | 36 |
22288759928 | import os, sys, shutil
def build_sets(positive,reportfile, num):
report = open("generalization"+os.sep+reportfile,"a")
report.write("Generalization \n")
log = open(positive,"r")
dim = len(log.readlines())//num
log.close()
log = open(positive,"r")
y = 0
c = 0
for i in range(num):
os.mkdir("generalizatio... | bpm-diag/DECMOL | scripts/GeneralizationMDL.py | GeneralizationMDL.py | py | 1,321 | python | en | code | 2 | github-code | 36 |
17353771853 | # Cam definition
from collections import namedtuple
_Cam = namedtuple("_Cam", field_names = ["xpos", "ypos", "steps", "offset", "signal_name", "horizontal", "reverse_direction", "bump_height", "follower"])
class Cam(_Cam):
def __new__(_cls, xpos, ypos, steps, offset, signal_name, horizontal=False, reverse_direct... | jmacarthur/box2d-ssem | cams.py | cams.py | py | 3,563 | python | en | code | 0 | github-code | 36 |
69933322346 | #!/usr/bin/python
import cv2, time, argparse
from ptpython.repl import embed
parser = argparse.ArgumentParser(description='OpenCV Face Recognition')
parser.add_argument('-interactive', action='store_true', help='Open a console terminal for evaluation')
parser.add_argument('input', help='Input video file to pro... | jaysridhar/learn-opencv | face-detection/face-detect.py | face-detect.py | py | 1,773 | python | en | code | 0 | github-code | 36 |
6117512730 | from __future__ import annotations
import logging
import math
import pickle
import lpips
import omegaconf
import pytorch3d
import pytorch3d.io
import torch
from pytorch3d import transforms
from pytorch3d.ops.points_alignment import SimilarityTransform
from pytorch3d.renderer.cameras import CamerasBase
from pytorch3d.... | shubham-goel/ds | src/eval/evaluate_base.py | evaluate_base.py | py | 11,007 | python | en | code | 68 | github-code | 36 |
21009796740 | # -*- coding: utf-8 -*-
__author__ = "Julien Dubois"
__version__ = "0.1.0"
class App:
ID = 0
SERVER_ADDRESS = "10.3.141.1"
SERVER_PORT = 41520
CONNECTION_TIMEOUT = 10
class Res:
SOUND_PATH = "data/sounds/"
SOUNDS = (
"connected.wav",
"connecting.wav",
"connection_error.wav"
)
IMAGE_PATH = ... | RedbeanGit/Robot | robot_core/constants.py | constants.py | py | 453 | python | en | code | 0 | github-code | 36 |
18176395440 | import compropago.config as config
class PlaceOrderInfo:
order_id = None
order_name = None
order_price = None
customer_name = None
customer_email = None
payment_type = None
currency = None
expiration_time = None
image_url = None
app_client_name = None
app_client_version = N... | compropago/sdk-python | compropago/factory/models/placeorderinfo.py | placeorderinfo.py | py | 1,124 | python | en | code | 1 | github-code | 36 |
70005734826 | from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot
class TInteractObj(QObject):
SigReceivedMessFromJS = pyqtSignal(dict)
SigSendMessageToJS = pyqtSignal(str)
def __init__(self, parent = None):
super().__init__(parent)
@pyqtSlot(str,result=str)
def JSSendMessage(self, strPara... | cjt24703/pyqt5- | TInteractObject.py | TInteractObject.py | py | 631 | python | en | code | 1 | github-code | 36 |
41988108653 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def rangeSumBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
... | kuangwanjing/leetcode | 938.RangeSumOfBST/main.py | main.py | py | 665 | python | en | code | 0 | github-code | 36 |
31591011107 | width = int(input())
length = int(input())
height = int(input())
volume = width * length * height
sum = 0
command = input()
while command != "Done":
sum += int(command)
if sum > volume:
print(f"No more free space! You need {sum - volume} Cubic meters more.")
break
command = input()
if co... | TeodorChakalov/Python | Python_Basics/While_Loop_Exercise/Moving.py | Moving.py | py | 384 | python | en | code | 0 | github-code | 36 |
69886479786 | import os
import unittest
import ansible
from ansiblelint import Runner, RulesCollection
from pkg_resources import parse_version
class TestTaskIncludes(unittest.TestCase):
def setUp(self):
rulesdir = os.path.join('lib', 'ansiblelint', 'rules')
self.rules = RulesCollection.create_from_directory(r... | dholdaway/Best-Practices_And_Examples | Ansible/test/TestTaskIncludes.py | TestTaskIncludes.py | py | 1,901 | python | en | code | 4 | github-code | 36 |
7130018134 | from TrackingTools.TransientTrack.TransientTrackBuilder_cfi import *
from TrackingTools.GeomPropagators.SmartPropagator_cff import *
from TrackingTools.MaterialEffects.MaterialPropagator_cfi import *
from TrackingTools.MaterialEffects.OppositeMaterialPropagator_cfi import *
from PhysicsTools.PatAlgos.patSequences_cff i... | cms-tamu/MuJetAnalysis | DataFormats/python/miniAODtoPAT_cff.py | miniAODtoPAT_cff.py | py | 5,523 | python | en | code | 1 | github-code | 36 |
20752748311 | import requests
import googletrans
from pycatapi import Client
def load_random_cat():
c = Client()
cat_url = c.get_cat()
return cat_url
def load_random_joke():
url = "https://official-joke-api.appspot.com/random_joke"
response = requests.get(url).json()
joke = f'- {response["setup"]}\n- {re... | zarex1111/WEB_Project | base_config.py | base_config.py | py | 697 | python | en | code | 0 | github-code | 36 |
23633159967 | #!/usr/bin/python
import sys
def fibo(n):
if n < 3:
return 1
return fibo(n-1)+fibo(n-2)
def memoize(f):
cache = {}
def memf(*x):
if x not in cache:
cache[x] = f(*x)
return cache[x]
return memf
@memoize
def fibo_memoized(n):
if n < 3:
return 1
return... | trauzti/blog.trauzti.com | fibonacci/fibonacci.py | fibonacci.py | py | 935 | python | en | code | 0 | github-code | 36 |
73484234343 | import time
import nlp_pre_processing
nlp = nlp_pre_processing.NLPPreprocessor()
# Multiprocessing
from multiprocessing import Pool
start_time = time.time()
num_partitions = 20
num_cores = 15
print(f'Partition Number: {num_partitions} - Number of Cores: {num_cores}...')
def main_process_pipeline(df, func):
df_... | fclesio/learning-space | Python/multiprocessing_function.py | multiprocessing_function.py | py | 932 | python | en | code | 10 | github-code | 36 |
36122181612 | import os, sys
import argparse
libpath = os.path.join(os.path.dirname(__file__), '../')
sys.path.append(libpath)
import src
from src.compiler.gen_relay_ir import gen_relay_ir
from src.compiler.visualize import visualize
from src.compiler.compiler import Compiler
from src.compiler.utils import dump_params
def fronten... | LianjunW/QuantizationTools | examples/test_complier.py | test_complier.py | py | 3,582 | python | en | code | 0 | github-code | 36 |
16412395588 | class Geese:
'''大雁类'''
def __init__(self, beak, wing, claw):
print("窝是大雁类!窝还有一下特征:")
print(beak)
print(wing)
print(claw)
beak_1 = '喙较高'
wing_1 = "翅膀长而尖"
claw_1 = "爪子是有的"
wildGoose = Geese(beak_1, wing_1, claw_1)
| zhangxinzhou/PythonLearn | helloworld/chapter07/demo01.03.py | demo01.03.py | py | 311 | python | en | code | 0 | github-code | 36 |
289073657 | import pathlib
#path to the desktop
desktop = pathlib.Path("/home/symon_kipkemei")
#create a new folder folder
new_path = pathlib.Path("/home/symon_kipkemei/screenshots")
new_path.mkdir(exist_ok=True)
# list items in desktop
for filepath in desktop.iterdir():
#filter screenshots only
if filepath.suffix == "... | symonkipkemei/cnd-labs | python-101/labs/13_modules-and-automation.py | 13_modules-and-automation.py | py | 501 | python | en | code | 0 | github-code | 36 |
3269639480 | #
# cfg - all configuration settings. no intradepenencies,
# so depends on os,sys for bootstrapping
#
import os
import sys
SETTINGS = {
"default-snapshot-policy": "0-1dy: all, 1dy-1wk: 4hr, 1wk-12wk: 1wk, 12wk-1yr: 4wk, 1yr+: none",
"snapshot-pattern": r"^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d[-+]\d\d\d\d$"... | toppk/saveme | lib/saveme/cfg.py | cfg.py | py | 1,117 | python | en | code | 2 | github-code | 36 |
70152353705 | import numpy as np
from PIL import Image
IMAGE_SIZE = 1000
if __name__ == '__main__':
# Два изображения одинаковой яркости, но полностью разного цвета
img_1_1_data = np.zeros((IMAGE_SIZE, IMAGE_SIZE, 3), dtype=np.uint8)
img_1_1_data[..., 0] = 255
img_1_1 = Image.fromarray(img_1_1_data)
img_1_1.sav... | borgishmorg/abchihba_back_end | image_generator.py | image_generator.py | py | 3,272 | python | ru | code | 0 | github-code | 36 |
28612344516 | from PySide import QtGui
class DemoScene(QtGui.QGraphicsScene):
def drawItems(self, painter, items, options, widget):
for item, option in zip(items, options):
painter.save()
painter.setMatrix(item.sceneMatrix(), True)
item.paint(painter, option, widget)
pain... | pyside/Examples | examples/demos/qtdemo/demoscene.py | demoscene.py | py | 334 | python | en | code | 357 | github-code | 36 |
21411610014 | from __future__ import absolute_import, division
import scipy.ndimage as ndimage
from matplotlib import widgets
import glob
import datetime
import scipy.interpolate as interpolate
import numpy as np
import matplotlib.pyplot as plt
__all__ = ['Slit']
#===================================================================... | CyclingNinja/sunkit-sst | sunkitsst/visualisation/slit.py | slit.py | py | 5,853 | python | en | code | 0 | github-code | 36 |
31557609448 | import sys
import os
def read_void_func(header_file):
f = open('derivations/output/' + header_file, 'r')
lines = f.readlines()
f.close()
void_funcs = [item for item in lines if "void" in item]
return void_funcs
if __name__ == "__main__":
all_headers = [ item for item in os.listdir('derivations/... | sskhan67/GPGPU-Programming- | QODE/qode/many_body/hierarchical_fluctuations/fast_operator/baker_campbell_hausdorff/autoQode/c_caller_generator.py | c_caller_generator.py | py | 1,792 | python | en | code | 0 | github-code | 36 |
19412985681 | from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
name = "This time"
urlpatterns = patterns('articles.views',
# home page
url(r'^$', 'collections', kwargs={"template_name": "home.html"}),
# inserting collections
... | jlong29/AY250 | Homework7/bibtex/urls.py | urls.py | py | 746 | python | en | code | 0 | github-code | 36 |
7750318589 | import os
import codecs
from decimal import Decimal
from cnab240.bancos import santander, itau
from cnab240.tipos import Lote, Evento, Arquivo
itau_data = dict()
dict_arquivo = {
'cedente_inscricao_tipo': 2,
'cedente_inscricao_numero': 15594050000111,
'cedente_agencia': 4459,
'cedente_cont... | rafadeveloper1982/CPRJ | testesUtils/testeremessa.py | testeremessa.py | py | 1,993 | python | pt | code | 0 | github-code | 36 |
18617730217 | # python 3.6
# author: qcw
from requests import get, exceptions
import re
class SentiveFile(object):
"""
从可能泄露的敏感文件中发现子域名,如crossdomain.xml、robots.txt等等
"""
def __init__(self, url):
"""
:param url: 外部输入的url
:param domians:返回主程序的结果
"""
self.url = url
sel... | b1ackc4t/getdomain | module/active/SensitiveFile.py | SensitiveFile.py | py | 2,248 | python | en | code | 3 | github-code | 36 |
28513906657 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington
# See opus_core/LICENSE
import os, sys
from opus_core.database_management.configurations.database_server_configuration import DatabaseServerConfiguration
from opus_core.data... | psrc/urbansim | opus_gui/data_manager/run/tools/synthesizer_import_pums_id_to_bg_id_to_db.py | synthesizer_import_pums_id_to_bg_id_to_db.py | py | 3,397 | python | en | code | 4 | github-code | 36 |
27578227980 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import time,configparser
try:
from tkinter import *
except ImportError: # Python 2.x
PythonVersion = 2
from Tkinter import *
from tkFont import Font
from ttk import *
# Usage:showinfo/warning/error,askquestion/okcancel/yesno/retrycancel
from tkM... | ilaer/mteam_checkin | ui.py | ui.py | py | 6,048 | python | en | code | 20 | github-code | 36 |
17864613680 | import traceback
import copy
from compare_reports import Comparison
import sources
import warnings
import asyncio
import inspect
import arrow
import ast
import sys
import time
import pandas as pd
from pprint import pprint
from string import ascii_lowercase
import gspread
import gspread_formatting
from oauth2client.ser... | CodeBlackwell/Incomparable | DataValidation/sources/semaphore_methods.py | semaphore_methods.py | py | 26,468 | python | en | code | 0 | github-code | 36 |
4185172909 | from django.db import models
from django.utils import timezone
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=... | jetbrains-academy/pycharm-courses | DjangoTutorial_v3.5/lesson1/task1/blog/models.py | models.py | py | 476 | python | en | code | 232 | github-code | 36 |
73082338983 | import numpy as np
from sklearn import metrics
from sklearn.metrics import roc_curve
from sklearn.metrics import roc_auc_score
import matplotlib.pyplot as plt
def calculate_AUC(model_results):
'''
:param model_results: model_results=[TP, FP, TN, FN, pred, pred_prob, test_data, test_flag]
:return: auc
'... | lauraqing/test_metric_evaluation_s3 | calculate_AUC.py | calculate_AUC.py | py | 1,292 | python | en | code | 0 | github-code | 36 |
22353244515 | import hashlib
from pyspark.sql.functions import udf
from pyspark.sql.types import StringType
def _hash_list(*list_to_hash):
list_to_hash = [str(element) for element in list_to_hash]
str_concatted = "".join(list_to_hash)
sha1 = hashlib.sha1()
sha1.update(str_concatted.encode("utf8"))
return sha1.... | mlrun/mlrun | mlrun/datastore/spark_udf.py | spark_udf.py | py | 929 | python | en | code | 1,129 | github-code | 36 |
285229649 | import tensorflow as tf
from tensorflow.python.ops.init_ops import _compute_fans
import numpy as np
class HeNormalExpertInitializer(tf.keras.initializers.Initializer):
def __init__(self, numexp, mode="fan_in"):
self.numexp = numexp
self.scale = 2.0
self.mode = mode
def __call__(self... | hhihn/HVCL | initializer.py | initializer.py | py | 2,144 | python | en | code | 5 | github-code | 36 |
14428087568 | from pico2d import load_image
import game_world
class Sword2:
image = None
def __init__(self, x = 400, y = 300, velocity = 1):
if Sword2.image == None:
Sword2.image = load_image('sSword2.png')
self.x, self.y, self.velocity = x, y, velocity
self.face_dir = 1
def draw(se... | Hbyien/2DPG_Project_2020180050 | sword2.py | sword2.py | py | 808 | python | en | code | 0 | github-code | 36 |
31065215705 |
from ..utils import Object
class UpdateNewPreCheckoutQuery(Object):
"""
A new incoming pre-checkout query; for bots only. Contains full information about a checkout
Attributes:
ID (:obj:`str`): ``UpdateNewPreCheckoutQuery``
Args:
id (:obj:`int`):
Unique query identifie... | iTeam-co/pytglib | pytglib/api/types/update_new_pre_checkout_query.py | update_new_pre_checkout_query.py | py | 2,045 | python | en | code | 20 | github-code | 36 |
33904308892 | import os
import argparse
# from icecream import ic
from misc_functions import read_name_funct
# from misc_functions import *
####################################################
def find_movie_files(movie_folders, iniID, finID, movie_path, imov_min=1, imov_max=9):
exist_movies = {}
rt_infofiles = False
#... | MartinAlvarezSergio/ramses2hdf5_movies | combine_movies_functions.py | combine_movies_functions.py | py | 4,453 | python | en | code | 0 | github-code | 36 |
18854609090 | import cv2 # import the OpenCV module
import numpy as np # import the numpy module using the name 'np'.
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
#HOMEWORK 2
# Utility functions
def show_wait(original, transformed, filename):
double = np.hstack((original,transformed)) #stac... | matitaweb/mumet2017_computer_vision_homework | HOMEWORK_03/bounding_box.py | bounding_box.py | py | 983 | python | en | code | 0 | github-code | 36 |
42591855037 | from pyrailbaron.map.datamodel import Coordinate
from pyrailbaron.map.states import download_zip, extract_kml, simplify_coords
from typing import List
from pathlib import Path
from math import log, atan, cos, pi, tan, sqrt
FALSE_EASTING = 6200000
FALSE_NORTHING = 3000000
CENTRAL_MERIDIAN = -91.866667 * (pi/180)
STD_P... | bmboucher/rail_baron | python/src/pyrailbaron/map/canada.py | canada.py | py | 2,330 | python | en | code | 0 | github-code | 36 |
16404277171 | # REGRAS:
#
# se o número é par, então (número / 2)
# se o número é ímpar, então (3 * número + 1)
number = int(input('Choose your number: '))
while number != 1:
if number % 2 == 0:
number //= 2
print(number, end=' ')
else:
number = 3 * number + 1
print(number, end=' ... | Pimegonho/Python-Udemy | Exercicios/EX11_exercicio.py | EX11_exercicio.py | py | 332 | python | pt | code | 0 | github-code | 36 |
7044110193 | import imgaug as ia
import argparse
import imgaug.augmenters as iaa
from shapely.geometry import Polygon
from cvat import CvatDataset
import shapely
import numpy as np
from urllib.request import urlopen
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
from PIL import Image, ImageDraw
import random
... | cds-mipt/cds-dtld-utils | data_augmentation.py | data_augmentation.py | py | 6,262 | python | en | code | 0 | github-code | 36 |
22508968712 | import socket
from flask import Flask
from redis import Redis
app = Flask(__name__)
redis = Redis(host='redis', port=6379)
hostname = socket.gethostname()
@app.route('/')
def hello():
redis.incr('hits')
return 'This is %s! There have been %s total hits.' % (
hostname,
redis.get('hits'),
... | GoodWriteHQ/datacenter-demo | service/app.py | app.py | py | 393 | python | en | code | 8 | github-code | 36 |
74100918822 | # Authors: Chao Li, Handing Wang, Jun Zhang, Wen Yao, Tingsong Jiang
# Xidian University, China
# Defense Innovation Institute, Chinese Academy of Military Science, China
# EMAIL: lichaoedu@126.com, hdwang@xidian.edu.cn
# DATE: February 2022
# ------------------------------------------... | HandingWangXDGroup/AGSM-DE | LSS_DE.py | LSS_DE.py | py | 6,576 | python | en | code | 9 | github-code | 36 |
36337524182 | import pygame
from pygame.sprite import Sprite
class Fish(Sprite):
def __init__(self, oa_game):
super().__init__()
self.screen = oa_game.screen
self.settings = oa_game.settings
self.image = pygame.image.load('gameproject_final/images/fish.png')
self.image = pygame.transfor... | sortzis/CIT228 | gameproject_final/fish.py | fish.py | py | 826 | python | en | code | 0 | github-code | 36 |
72748557223 | from asyncio.windows_events import NULL
from cmath import nan
from itertools import count
import os
from pathlib import Path
from importlib.resources import path
from tokenize import String
from weakref import ref
import pandas as pd
import numpy as np
import datetime
# cols_to_be_replaced = ['Kund: Namn', 'Kund: C/o... | Farazzaidi22/TeodorProject | Main/Source Code/script.py | script.py | py | 13,948 | python | en | code | 0 | github-code | 36 |
22589698303 | def square(nums):
return nums**2
num_list = [1,2,3,4]
square_list = list(map(square,num_list))
print(f'Square Values : {square_list}')
def check_string(string):
if(len(string)%2==0):
return 'Even'
else:
return string[0]
string_list = ['hrishab','jha','amar']
new_list = l... | Hrishabkumr/Python | pythonFunction/mapFunction.py | mapFunction.py | py | 390 | python | en | code | 0 | github-code | 36 |
17633338331 | # script part2c
# Sammy, Nikolai, Aron
# integral nummer (1), time_to_destination
import numpy as np
import roadster
import matplotlib.pyplot as plt
route_dist, route_speed = roadster.load_route('speed_elsa.npz')
delintervall = 25
l = [2**i for i in range(0,delintervall)]
trapets_list = []
for num in ... | Nikkobrajj/roadster | script_part2c.py | script_part2c.py | py | 1,019 | python | en | code | 0 | github-code | 36 |
40243498393 | from api.serializers import RecipeSmallSerializer
from rest_framework import serializers
from users.models import Subscription, User
class UserShowSerializer(serializers.ModelSerializer):
"""Serializer to output user/user list."""
email = serializers.EmailField(required=True)
username = serializers.CharF... | nastyatonkova/foodgram-project-react | backend/users/serializers.py | serializers.py | py | 5,079 | python | en | code | 0 | github-code | 36 |
8368523559 | # 풀이 방법
# target : 만들 수 있는지 체크
# 화폐가 작은 단위부터 하나씩 확인해 target을 업데이트
N = int(input())
coins = map(int, input().split())
coins = sorted(coins)
target = 1
for c in coins:
if c > target:
break
target += c
print(target)
| hyelimchoi1223/Algorithm-Study | 이것이코딩테스트다/그리디_알고리즘/만들 수 없는 금액2.py | 만들 수 없는 금액2.py | py | 297 | python | ko | code | 1 | github-code | 36 |
25412118768 | from typing import Iterable, Tuple
from ..shared.more_itertools import flat_map, count
from ..shared.solver import Solver
"""[summary]
2 thoughts on performance:
1. This *enumerates* paths, which isn't necessary.
All we need to do is count them, so just increment
a number when you get to 16,16, and... | bathcat/pyOiler | src/pyoiler/problems/euler015.py | euler015.py | py | 2,357 | python | en | code | 1 | github-code | 36 |
71765839143 | import matplotlib.pyplot as plt
import random
def roll_dice(number_of_dice: int, sides: int = 6) -> int:
"""Simulates dice throws."""
result = 0
for _ in range(number_of_dice):
result += random.randint(1, sides)
return result
def simulate_die_throws(number_of_rolls: int, amount_of_dice: int, ... | Joey-JJ/dice_simulations | dice_simulation.py | dice_simulation.py | py | 1,664 | python | en | code | 0 | github-code | 36 |
28481602613 | # Importing flask module in the project is mandatory
# An object of Flask class is our WSGI application.
from flask import Flask, render_template,request, redirect, url_for,session
from pymongo import MongoClient
app = Flask(__name__)
client = MongoClient("mongodb+srv://arsal0344:03444800061@cluster0.u6h8hwf.mongodb... | SHnice/MentoriaPakistan | index.py | index.py | py | 2,889 | python | en | code | 0 | github-code | 36 |
70644132904 | from . import database, user
CHAT_MSG_MAX_LEN = 100
def get_chats(game_id):
"""Retrieves the chat messages for a specified game."""
query = 'SELECT * FROM chats WHERE game_id = ? ORDER BY timestamp ASC'
query_args = [game_id]
chats = database.sql_exec(database.DATABASE_FILE, query, query_args)
... | kurtjd/chesscorpy | chesscorpy/chat.py | chat.py | py | 878 | python | en | code | 2 | github-code | 36 |
21911933808 | #!/usr/bin/env python3
import re
import os
from os.path import join, isfile
import sys
import argparse
import requests
ENCLAVE_ENDPOINT = ""
class S3FileReader(object):
"""
Reads P3A measurements (as they are stored in the S3 bucket) from disk and
replays them to our live Nitro enclave. This object mus... | brave-experiments/p3a-shuffler | scripts/replay-p3a-data.py | replay-p3a-data.py | py | 2,065 | python | en | code | 1 | github-code | 36 |
22525078962 | from . import user
from ..models.user import User, Contact
from flask import render_template, flash, redirect, request, url_for
from flask_login import login_required, current_user
from ..forms.profile import PhotoForm, EditProfileForm
from ..forms.activity import ContactForm
import os
from ..extentions import a... | Honglin-Li/TravelPlatform | app/user/view_profile.py | view_profile.py | py | 7,125 | python | en | code | 0 | github-code | 36 |
72776407783 | #!/usr/bin/env python3
import rospy
from std_msgs.msg import Float32MultiArray, Int32MultiArray, Int32
import numpy as np
from cameraService.cameraClient import CameraClient
from affordanceService.client import AffordanceClient
from orientation_service.srv import runOrientationSrv, runOrientationSrvResponse
from orient... | HuchieWuchie/handover_system | handoverOrientation/scripts/orientationService/client.py | client.py | py | 2,840 | python | en | code | 0 | github-code | 36 |
15599967327 | from django.shortcuts import render
from inicio.models import Paciente
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
def mi_vista(request):
return... | MatrixUHzp/web-doctor | inicio/views.py | views.py | py | 1,189 | python | en | code | 0 | github-code | 36 |
32000840841 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
arr = self.get_list_node(head)
# list(map()) 방식을 사용해서 이진수를 만들어도된다.
dig... | plan-bug/LeetCode-Challenge | landwhale2/easy/1290. Convert Binary Number in a Linked List to Integer.py | 1290. Convert Binary Number in a Linked List to Integer.py | py | 709 | python | en | code | 2 | github-code | 36 |
44140383131 | import logging as log
from os import getenv, listdir
import discord
from discord.ext import commands
from discord import ExtensionAlreadyLoaded
from dotenv import load_dotenv
# -------------------------> Globals
load_dotenv()
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=getenv('PREFIX'), intents... | juliavdkris/dotobot | src/main.py | main.py | py | 1,451 | python | en | code | 0 | github-code | 36 |
31090757185 | nama_barang=input("nama barang =",)
print("ketik 1 untuk mencari harga jual")
print("ketik 2 untuk mencari harga beli")
print("ketik 3 untuk mencari banyak barang")
print("ketik 4 untuk mencari keuntungan")
x=int(input())
if x == 1:
keuntungan=input("keuntungan yang ingin diperoleh = ",)
keuntungan=int(... | kafa123/My-work | final_project/tes.py | tes.py | py | 3,230 | python | id | code | 1 | github-code | 36 |
72555949543 | """django_sandbox URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Cl... | tedlano/django-sandbox | django_sandbox/urls.py | urls.py | py | 1,394 | python | en | code | 1 | github-code | 36 |
36567731753 | from __future__ import unicode_literals
from django.db import migrations
from django.db import models
class Migration(migrations.Migration):
dependencies = [
('django_mfa', '0002_auto_20160706_1421'),
]
operations = [
migrations.AlterField(
model_name='UserRecoveryCodes',
... | MicroPyramid/django-mfa | django_mfa/migrations/0003_change_secret_code_max_length.py | 0003_change_secret_code_max_length.py | py | 418 | python | en | code | 176 | github-code | 36 |
15108076525 | # -*- coding: utf-8 -*-
__author__ = 'lily'
import sys
import unittest
import time, datetime
from TestCase.webCase.case_web_all import ParametrizedTestCase,SearchTest,HomeTest,UserinfoTest
from common import report
from common import util
import xlsxwriter
from common import readYaml
import os
sys.path.append("..")
P... | hi-noikiy/apiTest | testRunner/webRunner.py | webRunner.py | py | 2,977 | python | en | code | 0 | github-code | 36 |
32220783153 | from itertools import chain
def matches_gen(data):
yield {
'team-slug' : data['event']['homeTeam']['slug'],
'eventid': data['event']['id'],
}
yield {
'team-slug' : data['event']['awayTeam']['slug'],
'eventid': data['event']['id'],
}
def goals_gen(data):
team_dict... | repositoriolegal/JokerDoMilhao | Sofa/analysis/filters.py | filters.py | py | 803 | python | en | code | 2 | github-code | 36 |
26117861949 | from datetime import datetime, timezone
from unittest import TestCase
from zoneinfo import ZoneInfo
from app import chasecenter, ical
from app.tests.test_chasecenter import EXAMPLE_RAW_EVENT
EXAMPLE_EVENT = chasecenter.initialize_chase_event(EXAMPLE_RAW_EVENT)
class TestGenerateCalendar(TestCase):
def test_gen... | albertyw/chase-center-calendar | app/tests/test_ical.py | test_ical.py | py | 1,388 | python | en | code | 2 | github-code | 36 |
39100789183 | # -*- encode: utf-8 -*-
def color(string:str, fore="紫", back="黑", disp="默认"):
"""Coloring text.
Parameters
==========
string: String, text to be colored.
fore: String, foreground color.
back: String, background color.
disp: String, display effect.
Return
=====... | AllenYZB/homework | MA333/Project2/Code/color.py | color.py | py | 1,057 | python | en | code | 1 | github-code | 36 |
74035927782 | from __future__ import print_function, division
import torch
from torchvision import datasets, transforms
import os
import math
data_transforms = {
'train': transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transfor... | xuchaoxi/pytorch-classification | data_provider.py | data_provider.py | py | 1,588 | python | en | code | 24 | github-code | 36 |
847509581 | #Python Image Library (PIL)
#Installation:
#Open terminal
#pip install pillow
from PIL import Image
#Open an image
mem_img = Image.open('d:/images/kids.jpg')
#fetch its attributes
#print(mem_img.size) # size of the image as a (w,h) tuple
#print(mem_img.format) #format: JPEG, PNG, ...
#print(mem_img.mode) #Color mod... | dheeraj120501/Lets-Code | 02-Languages/Python/11-PIL/handson_pil_1.py | handson_pil_1.py | py | 1,087 | python | en | code | 3 | github-code | 36 |
13087308271 | import sql_connection as sq
import logging
def is_new_recipe(cursor, title):
"""
This function checks if the recipe title already exists in the database or not. If the recipe title does not
exist yet in the database, function returns True. If the title already exists in the database, or this an error,
... | DarShabi/Web-Scraping-allrecipes | dump_data.py | dump_data.py | py | 7,380 | python | en | code | 0 | github-code | 36 |
11440299116 | # _*_ coding:utf-8 _*_
"""
主界面逻辑函数
"""
import os
import exifread
import requests
from PyQt5.QtCore import QSize, Qt
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QWidget, QFileDialog
from ui.main_window import Ui_Form
class MainWindow(Ui_Form, QWidget):
def __init__(self):
super(MainWi... | a-ltj/pyqt_image | view/main.py | main.py | py | 4,659 | python | en | code | 4 | github-code | 36 |
73894836904 | # -*- coding: utf-8
"""
File containing ConfigObject.
"""
from __future__ import division, print_function, unicode_literals
### Logging ###
import logging
_logger = logging.getLogger("ConfigUtils")
###############
import os
import sys
from ast import literal_eval
try:
import configparser
except ImportError:
... | thnguyn2/ECE_527_MP | mp4/SD_card/partition1/usr/share/pyshared/Onboard/ConfigUtils.py | ConfigUtils.py | py | 20,458 | python | en | code | 0 | github-code | 36 |
2223003364 | import collections
def longest_nonrep(s):
# len longest substr with nonrepeating characters
if s == "": return 0
d = {}
l = 0
last = 0
# use last i window to be the substring
for i in range(len(s)):
if d.get(s[i], -1) != -1: # if repeating character
last = max(last, d[s[... | arrws/leetcode | array/repeat_chars_substr.py | repeat_chars_substr.py | py | 1,530 | python | en | code | 0 | github-code | 36 |
239999918 | def tipoTriangulo(x, y, z):
if not ((x>0) and (y>0) and (z>0))and ((x+y)!=z):
return "No es un triangulo"
elif ((x==y)and(y==z)):
return "Equilatero"
elif ((x!=y)and(x!=z)and(y!=z)):
return "Escaleno"
elif((x+y)!=z) or ((y+z)!=x) or ((x+z)!=y):
return "Isosceles"
pri... | bentosmariano33/Mis-pruebas- | pruebas_09_04_2022.py | pruebas_09_04_2022.py | py | 344 | python | en | code | 0 | github-code | 36 |
3747122457 | # Standard Library
import logging
import subprocess
logging.basicConfig(level=logging.INFO)
def create_namespace_if_not_exists(namespace_name: str) -> bool:
"""
Create a namespace if not exists
:param namespace_name:
name of the namespace you want to create
:return: bool
Returns t... | abnamro/repository-scanner | deployment/resc-helm-wizard/src/resc_helm_wizard/kubernetes_utilities.py | kubernetes_utilities.py | py | 1,223 | python | en | code | 137 | github-code | 36 |
3289497062 | from pyomo.contrib.trustregion.param import *
class FilterElement:
def __init__(self, objective, infeasible):
self.objective = objective
self.infeasible = infeasible
def compare(self, x):
if (x.objective >= self.objective and x.infeasible >= self.infeasible):
return -1
... | igorsowa9/vpp | venv/lib/python3.6/site-packages/pyomo/contrib/trustregion/filterMethod.py | filterMethod.py | py | 948 | python | en | code | 3 | github-code | 36 |
1749907675 | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, print_function,
unicode_literals, division)
from itertools import chain
from namedlist import namedtuple, NO_DEFAULT
from six import iteritems, iterkeys
from .api import kv_format_pairs
def _validate_filters(fields, filters):
... | eisensheng/kaviar | kaviar/functools.py | functools.py | py | 1,432 | python | en | code | 1 | github-code | 36 |
73483496103 | #!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
#
# haus.py
# @Author : Gustavo F (gustavo@gmf-tech.com)
# @Link : https://github.com/sharkguto
# @Date : 17/02/2019 12:32:47
from ims24.contrators.requester import RequesterCrawler
import html5lib
import re
class ExtractorHaus(RequesterCrawler):
"""
imple... | fclesio/learning-space | Python/ims24/ims24/services/haus.py | haus.py | py | 1,442 | python | en | code | 10 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.