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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
36347951264 | import random
import numpy as np
from scipy.optimize import fsolve
# velocity upper bound from Wu et al (https://flow-project.github.io/papers/wu17a.pdf )
# This is an approximation
def v_eq_max_function(v, *args):
"""Return the error between the desired and actual equivalent gap."""
num_vehicles, length = a... | poudel-bibek/Beyond-Simulated-Drivers | flow/density_aware_util.py | density_aware_util.py | py | 7,049 | python | en | code | 0 | github-code | 6 |
19886880930 | from guardata.client.client_events import ClientEvent
import pytest
from unittest.mock import ANY
from pendulum import datetime
from guardata.api.data import UserManifest, WorkspaceEntry
from guardata.client.types import WorkspaceRole, LocalUserManifest, EntryID
from guardata.client.fs import (
FSError,
FSWork... | bitlogik/guardata | tests/client/fs/userfs/test_sharing.py | test_sharing.py | py | 21,167 | python | en | code | 9 | github-code | 6 |
9264192052 | import mne
import numpy as np
import pandas as pd
from mne.beamformer import make_lcmv, apply_lcmv, apply_lcmv_cov
from scipy.stats import pearsonr
import config
from config import fname, lcmv_settings
from time_series import simulate_raw, create_epochs
# Don't be verbose
mne.set_log_level(False)
fn_stc_signal = fna... | wmvanvliet/beamformer_simulation | lcmv.py | lcmv.py | py | 6,703 | python | en | code | 4 | github-code | 6 |
7911525547 | import nltk
from collections import Counter
nltk.download('vader_lexicon')
from nltk.sentiment import SentimentIntensityAnalyzer
#Зчитуємо файл який дали в завданні
filename = "data.csv"
with open(filename, 'r') as f:
reviews = f.readlines()
# ініціалізуємо SentimentIntensityAnalyzer (бібліотека для визначення... | Stepanxan/home_task-2 | app.py | app.py | py | 3,167 | python | uk | code | 0 | github-code | 6 |
44426849776 | from test_framework import mininode
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
import time
from test_framework.blocktools import create_block, create_coinbase
class BsvProtoconfViolationTest(BitcoinTestFramework):
def add_options(self, parser):
parser.... | bitcoin-sv/bitcoin-sv | test/functional/bsv-protoconf-violation.py | bsv-protoconf-violation.py | py | 2,254 | python | en | code | 597 | github-code | 6 |
42891510827 | #PYTHON CAMERA MODEL
import cv2
import numpy as np
i=0
def capturing(event,x,y,flags,param):
global i
if event==cv2.EVENT_LBUTTONUP:
name="photo_"+str(i)+".png"
wname="CAPTURED IMAGE"
cv2.imwrite(name,frame)
h=cv2.imread(name)
cv2.namedWindow(wname)
cv2.imshow(wn... | NamrithaGirish/LiveCam | cam.py | cam.py | py | 1,003 | python | en | code | 0 | github-code | 6 |
31366310671 | from api.models import EventTypes
# temp models
class GithubBodyModel(object):
def __init__(self):
self.type = ''
self.preferred_labels = {}
self.alternative_labels = []
self.broader_labels = []
self.narrower_labels = []
self.related_labels = []
... | NatLibFi/Finto-suggestions | api/scripts/github_models.py | github_models.py | py | 1,467 | python | en | code | 7 | github-code | 6 |
32467362643 | """
ID: jasonhu5
LANG: PYTHON3
TASK: transform
"""
def reflect(ar):
n = len(ar)
res = ar.copy()
for row in range(n):
res[row] = res[row][::-1]
return res
def solve(ar1, ar2):
def rot_cw_90(A, B):
for row in range(n):
for col in range(n):
if A[row][col] !... | jasonhuh/UASCO-Solutions | transform/transform.py | transform.py | py | 2,822 | python | en | code | 0 | github-code | 6 |
35968448866 | from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import ui
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import... | surbhikhandelwal/Python-Projects | CWTV/cwtv.py | cwtv.py | py | 3,267 | python | en | code | 0 | github-code | 6 |
40483436324 | import tkinter
import os
from PIL import Image, ImageTk
class OngletsPersonnage():
def __init__(self, main_onglets):
self.onglets_personnage = tkinter.ttk.Frame(main_onglets)
self.onglets_personnage.pack()
main_onglets.add(self.onglets_personnage, text='character')
self.cre... | Azzary/LeafMITM | interface/onglets/onglets_personnage.py | onglets_personnage.py | py | 4,255 | python | en | code | 3 | github-code | 6 |
34928362935 | import mysql.connector
from mysql.connector import pooling
class Database:
def __init__(self, config):
self.config = config
self.cnxpool = self.create_cnxpool()
def create_cnxpool(self):
try:
cnxpool = pooling.MySQLConnectionPool(
pool_name = "cnxpool",
... | alice1315/wehelp-third | app/models/database.py | database.py | py | 1,070 | python | en | code | 0 | github-code | 6 |
7998902064 | import os
from bson.json_util import dumps
from dotenv import load_dotenv
# from flask import jsonify
import pymongo
load_dotenv() # use dotenv to hide sensitive credential as environment variables
DATABASE_URL = f'mongodb+srv://{os.environ.get("user")}:{os.environ.get("passwort")}' \
'@flask-mongodb-a... | rosemaxio/flauraBackend | plants/db.py | db.py | py | 1,326 | python | en | code | 0 | github-code | 6 |
811133362 | import pygame
from pygame.locals import *
from entities import User, Enemy
from fonctions import *
from stage import *
from hud import *
import random
import time
import zmq
import threading
from stage import *
from tkinter import *
from playsound import playsound
def choix1():
global perso
perso=1
b... | ZeProf10T/projet-isn | server.py | server.py | py | 8,030 | python | en | code | 0 | github-code | 6 |
6193427862 | """
Main script: Autonomous Driving on Udacity Simulator
@author : nelsoonc
Undergraduate Thesis
Nelson Changgraini - Bandung Institute of Technology, Indonesia
"""
# Throttle 0 - 1 will produce speed 0 - 30 mph
# Steering -1 - 1 will produce angle -25 - 25 degrees
import os
import numpy as np
import so... | zhouzheny1/Conditional_Imitation_Learning | simulation/main.py | main.py | py | 2,123 | python | en | code | 0 | github-code | 6 |
37182795454 | import os
import re
from typing import Tuple
from transformers import pipeline # type: ignore
MODEL_PATH = os.environ.get("MODEL_PATH", "./distilbert-base-cased-distilled-squad")
class CardSourceGeneratorMock:
def __call__(self, text: str, question: str) -> Tuple[int, int]:
return 0, len(text) // 2
c... | MoShrank/card-generation-service | text/CardSourceGenerator.py | CardSourceGenerator.py | py | 1,408 | python | en | code | 0 | github-code | 6 |
5203502596 | # -*- coding: utf-8 -*-
"""
Spyderエディタ
これは一時的なスクリプトファイルです
"""
#WEBクローリング
import time
import re
import requests
import lxml.html
from pymongo import MongoClient
def main():
client = MongoClient('localhost', 27017)
#scrapingデータベースのebooksコレクションを作成
collection = client.scraping.eb... | inamasa12/cr-sc | python_crowler_4.py | python_crowler_4.py | py | 2,855 | python | ja | code | 0 | github-code | 6 |
25993011459 | import urllib
from flask import Blueprint, request, render_template, flash, redirect, url_for
from orders_tracker.blueprints.clients.service import add_client, update_client, remove_client, search_clients, \
get_form_fields, get_path_args, \
get_clients_count, render_empty, get_pagination_metadata, paginate_c... | 1Lorde/orders-tracker | orders_tracker/blueprints/clients/routes.py | routes.py | py | 4,565 | python | en | code | 0 | github-code | 6 |
8267132836 | import logging
import os
import pytest
import yaml
from cekit.config import Config
from cekit.descriptor import Image, Overrides
from cekit.descriptor.resource import create_resource
from cekit.errors import CekitError
try:
from unittest.mock import call
except ImportError:
from mock import call
config = Co... | cekit/cekit | tests/test_unit_resource.py | test_unit_resource.py | py | 11,760 | python | en | code | 70 | github-code | 6 |
6343086075 | from .db import add_prefix_for_prod, db, environment, SCHEMA
from sqlalchemy.sql import func
community_users = db.Table(
"community_users",
db.Model.metadata,
db.Column("user_id", db.ForeignKey(
add_prefix_for_prod("users.id")), primary_key=True),
db.Column("business_id", db.ForeignKey(
... | marcsmithr/Reddit-Clone | app/models/join_tables.py | join_tables.py | py | 450 | python | en | code | 0 | github-code | 6 |
7538481658 | # You are given a list of integers. Write a Python function that finds and returns the largest element in the list.
# The integers in the list may not be sorted.
# You can assume that the list will not be empty.
def find_largest_element(input_list):
positional_var = 0
num = input_list[0]
while True:
... | Shaunc99/Python | arrays/LargestElement.py | LargestElement.py | py | 908 | python | en | code | 2 | github-code | 6 |
7965704838 | from pathlib import Path
from promtail_ops_manager import PromtailOpsManager
# The promtail release file.
resource = "./promtail.zip"
manager = PromtailOpsManager()
# manager.install(resource)
# Setup for local tests such that installation of binaries etc.
# will not mess up your local client.
manager.promtail_home ... | erik78se/promtail-vm-operator | tests/testlib.py | testlib.py | py | 839 | python | en | code | 0 | github-code | 6 |
4203368667 |
# Method to find all the legitimate words
def get_legimate_words(letters, sowpods):
legitimate_words = []
# Iterate on each word of the dictionary
for word in sowpods:
# Set the flag as True
is_word_legitimate = True
# Iterate on each character of word
for character in word:... | Adnation/sowpods | yoptima.py | yoptima.py | py | 841 | python | en | code | 0 | github-code | 6 |
24037873801 | import os.path
homedir = os.path.expanduser("~")
class Config:
bindsym_dict = {}
set_dict = {}
exec_list = []
exec_always_list = []
def get_i3_config():
i3_config_file = open(homedir + "/.config/i3/config", "r")
config = Config()
for line in i3_config_file:
line = line.strip()
... | flyingcakes85/i3wm-config-gui | config_parser.py | config_parser.py | py | 1,139 | python | en | code | 1 | github-code | 6 |
18155298342 | import customtkinter as ctk
from PIL import Image
root = ctk.CTk()
root.title("IRIS")
root.geometry("1080x720")
root._set_appearance_mode("dark")
frame = ctk.CTkFrame(master=root)
frame.pack(pady=20)
logo = ctk.CTkImage(Image.open(
"/home/nabendu/Documents/MCA/projects/python-speechRecongition-desktop-AI-project/... | Nandy1002/python-speechRecongition-desktop-AI-project | main/gui.py | gui.py | py | 906 | python | en | code | 0 | github-code | 6 |
71040814269 | import pandas as pd
n = 6
res = [[] for _ in range(0, 105, 5)]
def checkLine(boardline, cons):
realCons = []
cnt = 0
for i in boardline:
if i==0:
if cnt!=0:
realCons.append(cnt)
cnt = 0
else:
cnt += 1
if cnt!=0:
realCons.appen... | ilesejin/ECSR_Nonogram | NonogramGrapher.py | NonogramGrapher.py | py | 2,231 | python | en | code | 0 | github-code | 6 |
3777146121 | from django.shortcuts import render
from cowsay_app.models import Input
from cowsay_app.forms import InputForm
import subprocess
# I mainly used this source to figure out subprocess:
# https://linuxhint.com/execute_shell_python_subprocess_run_method/
# I also used Stackoverflow and Python docs
# Also found some usefu... | pokeyjess/cowsay | cowsay_app/views.py | views.py | py | 1,247 | python | en | code | 0 | github-code | 6 |
6191154878 | #! /usr/bin/env python
"""
Compute the transmission and reflection probabilities of a
particle with a given mass and energy encountering a potential step.
Leon Hostetler, Feb. 14, 2017
USAGE: python quantum_step.py
"""
from __future__ import division, print_function
# Constants
m = 9.11e-31 # Mass of particl... | leonhostetler/undergrad-projects | computational-physics/01_basic_calculations/quantum_step.py | quantum_step.py | py | 960 | python | en | code | 0 | github-code | 6 |
16675031691 |
import os
import syslog
import time
import traceback
import support.cmd_exe
from vmlib import fwprint
gips_connects = {}
gips_state = {}
def pause_vm(uuid):
cmd = '/usr/bin/python /usr/vmd/glusterfs/connect_serial0.py /var/run/%s/monit.sock stop' % (uuid)
fwprint( cmd)
os.system(cmd)
def cont_vm(uuid)... | sun7shines/GlusterFS | glusterfs/vm_route.py | vm_route.py | py | 2,215 | python | en | code | 0 | github-code | 6 |
73644652346 | import structure.concrete.类型 as type
'''
部分系数
'''
def 外形系数(t: type.钢筋种类) -> float:
s = type.钢筋种类
switch = {
s.带勾光面钢筋 : 0.16,
s.带肋钢筋 : 0.14,
s.螺旋肋钢丝 : 0.13,
s.三股钢绞线 : 0.16,
s.七股钢绞线 : 0.17
}
return switch[t] | TheVeryDarkness/structure | concrete/附录.py | 附录.py | py | 359 | python | zh | code | 0 | github-code | 6 |
38899572282 | import pygame
import time
import random
pygame.init()
pygame.font.init()
myfont = pygame.font.SysFont('Comic Sans MS', 30)
screen = pygame.display.set_mode((1280,720))
done = False
p1_x=30
p1_y= screen.get_height()-60
#make player
class Player:
def __init__(self,x,y):
self.x=x
self.y=y
def move... | mahi-pas/Egg-Catcher | catcher.py | catcher.py | py | 1,381 | python | en | code | 0 | github-code | 6 |
21397154599 | import os
import backoff
import pytest
from racetrack_commons.dir import project_root
from racetrack_client.client.deploy import send_deploy_request
from racetrack_client.client_config.auth import set_user_auth
from racetrack_client.client_config.client_config import ClientConfig
from racetrack_client.utils.request i... | TheRacetrack/racetrack | tests/e2e/test_auth.py | test_auth.py | py | 6,570 | python | en | code | 27 | github-code | 6 |
40323903072 | # LOOP WHILE
# Estrutura de repetição que permite executar um bloco de códico, enquanto a condição for verdadeira
# Sintaxe;
# while (condição):
# bloco de códico.
#
# ex:
#controle = ""
#while (controle != "s"):
# print("a.Pagar")
# print("b.Receber")
# print("c.Transferir")
# print("s.Sair")
# ... | Herley25/algoritmo_python | While.py | While.py | py | 887 | python | pt | code | 0 | github-code | 6 |
15864287326 | import pandas as pd
import matplotlib.pyplot as plt
# Set up the output screen
plt.style.use(style='ggplot')
plt.rcParams['figure.figsize'] = [20, 12]
# Read dataset
trainData = pd.read_csv('./train.csv')
# With outliers
plt.scatter(trainData.GarageArea, trainData.SalePrice, color='red')
plt.xlabel('Garage Area')
pl... | nikolozdz/Linear-Regression-Models-ICP5 | Task 1.py | Task 1.py | py | 690 | python | en | code | 0 | github-code | 6 |
42479620713 | """Collection of common layers."""
import tensorflow as tf
class Layers(object):
"""Collection of computational NN layers."""
@staticmethod
def linear(prev_layer, out_dim, name="linear"):
"""Create a linear fully-connected layer.
Parameters
----------
prev_layer : tf.Te... | gabrieleangeletti/Deep-Learning-TensorFlow | yadlt/core/layers.py | layers.py | py | 2,874 | python | en | code | 965 | github-code | 6 |
6106005547 | """
Usage:
python parser.py <filename>
example:
python parser.py 2012_12_15.txt
"""
class FileReader(object):
def __init__(self):
self.count = 0
def process(self, filename):
"""
This a filereader
Arguments:
filename: Name of the file that we are reading
... | justincely/miami-python | day_2/fp.py | fp.py | py | 1,227 | python | en | code | 0 | github-code | 6 |
14241805756 | from sys import exit
from time import sleep, time
from random import randint
import pygame
from pygame.constants import RESIZABLE
# Tetramino definitions on a 4x4 grid. 1 means the tile exists.
TETRAMINO_I = (((0, 0, 0, 0), (0, 0, 0, 0), (1, 1, 1, 1), (0, 0, 0, 0)),
((0, 1, 0, 0), (0, 1, 0, 0), (0, 1, 0... | dmcdo/Pygame-Games | tetris.pyw | tetris.pyw | pyw | 22,293 | python | en | code | 0 | github-code | 6 |
14334373987 | # dictionary inside list
a = [{'Name':'Ram','Age':34,'Add':'Kathmandu'},
{'Name':'Shyam','Age':56,'Add':'Bhaktapur'},
{'Name':'Hari','Age':89,'Add':'Lalitpur'}]
print(a[0])
b = {'Name':'Hari','Age':89,'Add':'Lalitpur'}
a.append(b)
print(a)
info = []
n = int(input("Enter n = "))
for i in range(n):
name = ... | Roshan2059/learning-python-with-django | day15-c.py | day15-c.py | py | 1,733 | python | en | code | 0 | github-code | 6 |
7804756691 | from jinja2 import Environment, FileSystemLoader
import yaml
import os.path
ENV = Environment(loader=FileSystemLoader('./'))
script_path = 'SCRIPTS/'
script = os.path.join(script_path, 'script.txt')
with open("config.yaml") as _:
yaml_dict = yaml.load(_)
template = ENV.get_template("template.text")
with open... | dancwilliams/Prefix_List_Script | EXTRA_SCRIPTS/MANUAL_CREATE/generate_config.py | generate_config.py | py | 416 | python | en | code | 0 | github-code | 6 |
26239584931 | from sets import Set
def prod_exists(x):
x = str(x)
for i in range(1,5):
for j in range(1, 8 - i):
if (int(x[:i]) * int(x[i:i + j]) == int(x[i+j:])):
return int(x[i+j:])
return 0
facs = {}
def fac(x):
try: return facs[x]
except:
if(x ==... | schroeji/Projekt-Euler | prob32.py | prob32.py | py | 1,063 | python | en | code | 0 | github-code | 6 |
16106099445 | #import logging
class stopwatch:
"""usage:
swgen = stopwatch.template("[INTEGRATION]")
...
with swgen("Running xxx") as _:
run_stuff()
with swgen("Finalizing xxx") as _:
finish_stuff()
"""
def __init__(self, message, logger):
self.logger ... | KellisLab/benj | benj/timer.py | timer.py | py | 1,382 | python | en | code | 2 | github-code | 6 |
29707449656 | #!/usr/bin/env python
import pybullet as p
import random
import numpy as np
from mamad_util import JointInfo
def check_collision(active_joints_info,num_active_joints):
collision_set=[]
index_of_active_joints = [active_joints_info[i]["jointIndex"] for i in range(num_active_joints)]
for i in index_of_active_joints:
... | ccylance/theis-code | gym_test/gym_test/envs/shadow_hand_vijay/gym_test.py | gym_test.py | py | 4,379 | python | en | code | 0 | github-code | 6 |
9756222638 | import theano
from theano import tensor as T
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from theano.tensor.signal import pool
from theano.tensor.nnet import conv3d2d
import numpy as np
from collections import OrderedDict
from .. import config
from .numpy_backend import get_random_magic_seed,... | trungnt13/odin_old | odin/tensor/theano_backend.py | theano_backend.py | py | 43,646 | python | en | code | 2 | github-code | 6 |
73061190269 | import os
import threading
high_value_extensions = [
".csv", ".json", ".xls", ".xlsx", ".doc", ".docx", ".pdf", ".ppt", ".pptx",
".html", ".htaccess", ".properties", ".env", ".yml", ".yaml", ".py", ".php",
".asp", ".aspx", ".jsp", ".war", ".jar", ".gz", ".tar.gz", ".zip", ".rar",
".dbf", ".ini", ".rc",... | tp9222/python-for-hackers | tools/High_Value_Files_Finder/High_Value_Files_Finder(HVFF).py | High_Value_Files_Finder(HVFF).py | py | 1,356 | python | en | code | 0 | github-code | 6 |
16010093346 | import toga
from colosseum import CSS
def build(app):
def on_load(widget):
print('Finished loading!')
print(widget.dom)
def on_key(event, flag):
print('Key down: ', event, ' Flag: ', flag)
webview = toga.WebView(on_key_down=on_key, on_webview_load=on_load, style=CSS(flex=1))
... | Ocupe/toga_test_app_collection | webview/webview/app.py | app.py | py | 1,488 | python | en | code | 0 | github-code | 6 |
5125409200 | from heatmappy import Heatmapper
from PIL import Image
import database_func as db
import img_lib
def percent_to_diameter(percent):
default = 150
if percent == 0:
return 0
elif percent <= 10:
return default
elif percent <= 20:
return default + 50
elif percent <... | jinho17/eye_tracking_project | eye_tracking/database/heatmap.py | heatmap.py | py | 2,434 | python | en | code | 0 | github-code | 6 |
20594474782 | import torch
import torch.nn.functional as F
def global_align_loss(
visual_embed,
textual_embed,
labels,
mixture=False,
alpha=0.6,
beta=0.4,
scale_pos=10,
scale_neg=40,
):
batch_size = labels.size(0)
visual_norm = F.normalize(visual_embed, p=2, d... | CCNU-DigitalLibrary/CCNU-DigitalLibrary | MCM-HC/lib/models/losses/align_loss.py | align_loss.py | py | 6,662 | python | en | code | 0 | github-code | 6 |
2107589551 | import pygame
import sys
from space_objects import *
from tools import *
pygame.init()
infoObject = pygame.display.Info()
W_SIZE = WIDTH, HEIGHT = (infoObject.current_w, infoObject.current_h)
H_SIZE = H_WIDTH, H_HEIGHT = WIDTH // 2, HEIGHT // 2
screen = pygame.display.set_mode(W_SIZE, pygame.FULLSCREEN)
clock = py... | Programmer-Anchous/Solar-system-model | main.py | main.py | py | 8,409 | python | en | code | 0 | github-code | 6 |
12836912861 | import sys
from typing import Optional
import PySide6
from PySide6 import QtWidgets
from qt_material import QtStyleTools, list_themes
from safebox.gui.widgets import cycle_generator, CreatorWidget
class MainWindow(QtWidgets.QMainWindow, QtStyleTools):
def __init__(self, parent: Optional[PySide6.QtWidgets.QWidget]... | pouralijan/SafeBox | safebox/gui/safebox_creator_main_window.py | safebox_creator_main_window.py | py | 829 | python | en | code | 2 | github-code | 6 |
36388156115 | from typing import Union
import psutil
def get_cpu_temp() -> Union[float, None]:
temperature_file_path = "/sys/class/thermal/thermal_zone0/temp"
try:
raw_temp = None
with open(temperature_file_path) as f:
raw_temp = f.readline().strip("\n")
return float(raw_temp) / 1000
... | noahtigner/homelab | api/diagnostics/retrieval.py | retrieval.py | py | 1,365 | python | en | code | 0 | github-code | 6 |
911107140 | from collections import Counter
import re
from xml.etree import ElementTree
from trapdoor import TrapdoorProgram, Message, run_command
exclusion_rules = [
re.compile(r'^[\s]*raise NotImplementedError')
]
def excluded_from_coverage(source_line):
"""Determine of the given line should be excluded from the cov... | theochem/horton | tools/qa/trapdoor_coverage.py | trapdoor_coverage.py | py | 5,168 | python | en | code | 83 | github-code | 6 |
16293536002 | import os
from time import sleep
import boto3
from botocore.exceptions import ClientError
IAM_R = boto3.resource('iam')
IAM_C = boto3.client('iam')
LAMBDA_C = boto3.client('lambda')
EVENTS_C = boto3.client('events')
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
def setup_iam_role():
"""
Setup the A... | zulily/aws_monitor | deployscripts/setup_lambda.py | setup_lambda.py | py | 4,849 | python | en | code | 3 | github-code | 6 |
44757415813 | from telegram.ext import *
from telegram import *
import openai
openai.api_key = "YOUR OPENAI API KEY" # Enter your OpenAI Secret Key.
telegram_token = "YOUR TELEGRAM BOT TOKEN" # Enter your Telegram Bot Token.
conversation=[{"role": "system", "content": "You are a helpful assistant."}] # Define... | muhammetharundemir/Telegram-ChatGPT | telegramChatGPT.py | telegramChatGPT.py | py | 3,703 | python | en | code | 1 | github-code | 6 |
42488414261 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 23 12:34:08 2018
@author: michal
"""
import networkx as nx
from networkx.algorithms.isomorphism import GraphMatcher
from networkx.readwrite.json_graph import node_link_data
from os.path import isdir, join, isfile
from os import mkdir
import json
fr... | chemiczny/PDB_supramolecular_search | anionTemplateCreator.py | anionTemplateCreator.py | py | 10,065 | python | en | code | 1 | github-code | 6 |
17514206848 | from unittest import TestCase
from unittest.mock import MagicMock, patch
from src.utils.callgrind import extract_function_calls, extract_hotspots
class TestExtractHotspots(TestCase):
def test(self):
callgrind = MagicMock()
count = 2
# Fake CallgrindParser internals
event1 = Magic... | haggj/bachelors-thesis | container/src/test/test_callgrind.py | test_callgrind.py | py | 2,772 | python | en | code | 0 | github-code | 6 |
75319095866 | import random
from pypinyin import lazy_pinyin
from nonebot import require, on_command, on_message, on_keyword, on_shell_command, on_request
from nonebot.rule import command
from nonebot.permission import SUPERUSER
from nonebot.typing import T_State,T_Handler
from nonebot.adapters.cqhttp.bot import Bot
from nonebot.ad... | Joenothing-lst/qbot | src/plugins/admin/__init__.py | __init__.py | py | 9,965 | python | en | code | 0 | github-code | 6 |
26109711840 | """
The customers resource is a representation of the customer accounts.
All the REST API calls to the Customer or the Address Database are housed here.
Customers Service with Swagger and Flask RESTX
Paths:
------
GET / - Displays a UI for Selenium testing
GET /customers - Lists a list all of Customers
GET /customers/... | CSCI-GA-2820-SP23-003/customers | service/routes.py | routes.py | py | 21,967 | python | en | code | 3 | github-code | 6 |
33963223285 | from http import HTTPStatus
from django.test import TestCase, Client
class AboutTests(TestCase):
def setUp(self):
self.guest_client = Client()
def test_about_urls_uses_correct_templates(self):
templates_url_names_quest = {
'/about/author/': 'about/author.html',
'/abou... | Mashabor/hw05_final | yatube/about/tests.py | tests.py | py | 660 | python | en | code | 0 | github-code | 6 |
73675897789 | import math
import numpy as np
from numpy.linalg import norm
from random import randint
import os
from select import select
os.environ["PYTHONDONTWRITEBYTECODE"]="True"
from servThread import servThread
BUFFER_SIZE = 32
alfa = 1
mi = 0.001
nfeatures = 4
#funkcija koja pokusava predvidjeti y
def h(theta,x):
retur... | termistotel/microbitML | server/learn.py | learn.py | py | 4,883 | python | hr | code | 0 | github-code | 6 |
25495485263 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 27 17:39:39 2020
@author: satya
"""
import pandas as pd
import scipy.cluster.hierarchy as sch
from sklearn.cluster import DBSCAN
data=pd.read_csv('cars_clus.csv')
featureset = data[['engine_s', 'horsepow', 'wheelbas', 'width', 'length', 'curb_wgt', 'fuel_... | Satyake/Deep-Learning | DBSCAN and HC.py | DBSCAN and HC.py | py | 928 | python | en | code | 1 | github-code | 6 |
2736213027 | from keras.optimizers import Nadam, Optimizer
from keras import backend as K
class Nadam_entropy(Nadam):
def __init__(self, temperature=0.1, **kwargs):
self.temperature = temperature
super(Nadam_entropy, self).__init__(**kwargs)
def get_gradients(self, loss, params):
grads = K.gradients(loss, params)... | twoev/APEMEN | utils/optimisers.py | optimisers.py | py | 1,081 | python | en | code | 0 | github-code | 6 |
38456424440 | import re
import os
import torch
import base64
import uvicorn
import numpy as np
from io import BytesIO
from PIL import Image
from typing import Union
from fastapi import FastAPI, File, Form
from pydantic import BaseModel
from maskrcnn_benchmark.config import cfg
from maskrcnn_benchmark.engine.predictor_glip import G... | bensonbs/GLIP | main.py | main.py | py | 2,914 | python | en | code | 5 | github-code | 6 |
29401120526 | import json
import os
from googleapiclient.discovery import build
class Channel:
"""Класс для ютуб-канала"""
def __init__(self, channel_id: str) -> None:
"""Экземпляр инициализируется id канала. Дальше все данные будут подтягиваться по API."""
self.__channel_id = channel_id
api_key: ... | AnastasiaLykova/youtube-analytics-project | src/channel.py | channel.py | py | 4,052 | python | ru | code | null | github-code | 6 |
41912482635 | from array import array
import datetime
from datetime import datetime, timezone
import requests
import math
from app.core.common import cf
# import json
from app.core.wcommon import wcf
from app.db.database import couch
class WSearch():
def __init__(self) -> None:
self.SEARCH_TAGS = [
... | metno/weamyl-metcap | app/app/core/wsearch.py | wsearch.py | py | 19,290 | python | en | code | 0 | github-code | 6 |
16120458600 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Dr Ekaterina Abramova, 2017
STRUCTURED TYPES.
Sequence type: lists
"""
# -----------------------------------------------------------------------------
# ----------------------------- create a list ---------------------------------
L = []
# List Comprehensio... | EkaterinaAbramova/python_exercises | Structured Types/lists.py | lists.py | py | 3,389 | python | en | code | 0 | github-code | 6 |
17351623183 | import vertexai
from vertexai.language_models import ChatModel, InputOutputTextPair
vertexai.init(project="samwin", location="us-central1")
chat_model = ChatModel.from_pretrained("chat-bison@001")
parameters = {
"max_output_tokens": 256,
"temperature": 0.2,
"top_p": 0.8,
"top_k": 40
}
chat = chat_model... | samwinp/rock-paper-sisor | future.py | future.py | py | 1,288 | python | en | code | 0 | github-code | 6 |
36690654635 | #!.venv/bin/python
# File: bracket.py
# Author: Jonathan Belden
# Description: A small utility to check for the correct
# amount of brackets (and possibly other
# formatting irregularities)
import os
def is_valid(input_file):
return os.path.isfile(input_file)
def analyze(input_file... | rckt-cmdr/bracket | bracket/bracket.py | bracket.py | py | 4,556 | python | en | code | 0 | github-code | 6 |
6960045652 | import numpy as np
import matplotlib.pyplot as plt
x = np.arange(10, 90, 10.)
y = np.array([25, 70, 380, 550, 610, 1220, 830, 1450])
plt.figure(1)
plt.plot(x, y, 'ro-')
plt.grid()
xsum=np.sum(x)
ysum=np.sum(y)
xysum=sum(x*y)
n=np.size(x)
xavg=xsum/n
yavg=ysum/n
a1=(n*xysum-xsum*ysum)/(n*sum(x**2)-xsum**2)
a0= yavg... | SCKIMOSU/Numerical-Analysis | polyfit_implement.py | polyfit_implement.py | py | 566 | python | en | code | 17 | github-code | 6 |
33362804571 | import os
class Student:
def __init__(self,name,path):
'''
name : Name of the student should correspond to records in moodle
path : path to the folder with name "name"
'''
self.name = name
self.path = path+"/"+name
self.solved_problems = dict()
for p ... | VitalyRomanov/p2p_hw_grading | student.py | student.py | py | 1,575 | python | en | code | 0 | github-code | 6 |
37708709276 | from django.urls import path
from . import views
app_name = "shop"
urlpatterns = [
path("", views.all_products, name="all_products"),
path("<slug:c_slug>/", views.all_products, name="category_products"),
path("product/new/", views.add_product, name="add_product"),
path("product/remove/<slug:p_slug>", ... | aleksandr-hilko/alex_online_shop | homeshop/shop/urls.py | urls.py | py | 532 | python | en | code | 0 | github-code | 6 |
6815148797 | import pygame
import numpy as np
import pickle
import datetime
import os
from snake import Snake
from map import Map
from agent import Agent
# Version 1.1
MODEL_DIR = "models"
MODEL_NAME = "model_1v7" # Name of the pickle file in which we store our model.
MODEL_PATH = os.path.join(MODEL_DIR, MODEL_NAME)
# MODEL_NAME ... | Dawir7/Reinforcement-Learing-Bot-to-play-Snake-game | Reinforcement_learninig/main_learning.py | main_learning.py | py | 6,247 | python | en | code | 0 | github-code | 6 |
7973610749 | import logging
from dataclasses import asdict
from typing import List
from game_service.routers.templates import BasicResponse
from game_service.services.game_manager import CodingConundrumManager
logging.basicConfig(format='%(name)s-%(levelname)s|%(lineno)d: %(message)s', level=logging.INFO)
log = logging.getLogger... | zhuweiji/CPP-FYP-Proj | game_service/game_service/routers/game_handlers.py | game_handlers.py | py | 1,858 | python | en | code | 0 | github-code | 6 |
27986005563 | # Author: Vivian Long
# Assignment: Lab 7
# Completed:
import sys
# Problem 1
# Step 1
x = 1
data = list()
while x > 0:
x = float(input("Enter a score (0 to quit): "))
if x > 0:
data.append(x)
print("Initial list:", data)
print("Size of list:", len(data))
# Step 2
high = data[0]
for i in data[1:]:
... | vwlong/CS299 | lab7.py | lab7.py | py | 2,738 | python | en | code | 0 | github-code | 6 |
7782101624 | import cv2
import random
import numpy as np
frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture(0)
cap.set(3, frameWidth)
cap.set(4, frameHeight)
save = False
colors = [[51, 153, 255],
[255, 0, 255],
[0, 255, 0],
[255, 0, 0],
[0, 0, 255]]
color = random.choice(colors)
poin... | tarekbrahmi/Open-cv-project | learining/projects and apps/other/webcam-drawing.py | webcam-drawing.py | py | 1,934 | python | en | code | 0 | github-code | 6 |
4341271396 | from __future__ import annotations
import logging
import os
from time import sleep
from typing import List, Optional, Union, ClassVar, Dict, Type, Optional, Iterable
from queue import Queue, Empty
from easyflow.common.logger import setupLogger
from easyflow.common.utils import Timer
import threading
logger = setupLo... | catwang01/easyflow | easyflow/obj.py | obj.py | py | 8,548 | python | en | code | 0 | github-code | 6 |
10663274434 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 16 11:25:30 2020
@author: Rijk
Extracts the resistance from the IV curves measured
"""
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 22 17:10:35 2019
@author: LocalAdmin
Curve fitting script
"""
import os
import math as m
import numpy as np
import matplotlib.pyplot... | rehogenbirk/MEP_control_software | fit_IVcurve_single.py | fit_IVcurve_single.py | py | 3,578 | python | en | code | 0 | github-code | 6 |
74916425146 | import util
import cv2
import torch
import os
def compareTensors(refs, target, targetName):
sum_ = 0
if len(refs) == 0:
print("no reference images")
return
for i in range(len(refs)):
ref = refs[i]
dotself = torch.tensordot(ref , ref, dims=2)
sum_ =... | EunbinSeo/Pytorch-vgg-memoji | compare.py | compare.py | py | 1,363 | python | en | code | 1 | github-code | 6 |
42090679043 | from events import OnEvents
from environment import Environment
from util import Util
class Component(OnEvents):
""" Base Class for individual processes.
"""
def __init__(self):
super(Component, self).__init__()
self.exec_times = []
self.Util = Util()
def run(self, **kwargs):
... | tom-kerr/bookmaker | components/component.py | component.py | py | 2,107 | python | en | code | 6 | github-code | 6 |
73706334586 | from django.shortcuts import render
from django.http import HttpResponse
from app1.models import Topic, Webpage, AccessRecord
from app1.forms import App1Form
# Create your views here.
def home(request):
#return HttpResponse("Hello Hao!")
my_dict = {'insert_me':"Goodbye now from view.py!!"}
return render(request,... | haozer/project1 | app1/views.py | views.py | py | 1,277 | python | en | code | 0 | github-code | 6 |
38814850733 | import matplotlib.pyplot as plt
import pandas as pd
import argparse
import seaborn as sns
sns.set_context("notebook", font_scale=1.8)
plt.style.use('fivethirtyeight')
parser = argparse.ArgumentParser()
parser.add_argument('--classifier', default="svm", type=str, nargs='?', help='classifier')
args = parser.parse_args()... | nphdang/CCRAL | visualize.py | visualize.py | py | 1,524 | python | en | code | 3 | github-code | 6 |
19581520317 | import os
import time
from collections import defaultdict
from os.path import join as osjoin
import csv
from pyspark.sql import SparkSession
import pyspark.sql.types as T
from util.file_manager import file_manager
from util.cosine_similarity import calculate_cosine_similarity
from core.directory import (
src_embe... | oldguard69/lvtn | server/core/4_make_data_for_training_classifier.py | 4_make_data_for_training_classifier.py | py | 4,560 | python | en | code | 0 | github-code | 6 |
18932875190 | # === Úloha 22===
# Napíšte program, ktorý zo súboru zoznam.txt vypíše pod seba meno a vek všetkých žiakov, ktorí majú aspoň 17 rokov. Údaje v súbore zoznam.txt sú zoradené tak, že v každom riadku je postupne vek a meno jedného žiaka.
subor = open("ziaci.txt", "r")
ziaci = list(map(lambda x: x.split(" "), subor.read()... | Plasmoxy/MaturitaInformatika2019 | ulohyPL/u22.py | u22.py | py | 472 | python | sk | code | 2 | github-code | 6 |
18091330209 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('account', '0060_auto_20150130_1750'),
]
operations = [
migrations.AlterField(
model_name='basicmemberinformation... | hongdangodori/slehome | slehome/account/migrations/0061_auto_20150201_1909.py | 0061_auto_20150201_1909.py | py | 531 | python | en | code | 0 | github-code | 6 |
35727586260 | #!/usr/bin/python
import pygame, sys, game
from pygame.locals import *
WIDTH = 640
HEIGHT = 480
DRAWSTEP = 3
TICK = 30
VOLATILITY = 0.8
TIMESTEP = float(TICK)/1000
if len(sys.argv) < 2:
ORDER = 2
else:
ORDER = int(sys.argv[1])
BLACK = pygame.Color(0,0,0)
WHITE = pygame.Color(255,255,255)
pygame.init()
fpsCl... | TheBB/deriv | deriv.py | deriv.py | py | 1,999 | python | en | code | 0 | github-code | 6 |
25847899408 | from pyautocad import Autocad
class Channel(object):
instance = None
def __init__(self):
self._session = None
@property
def session(self):
if not self._session:
try:
self._session = session = Autocad(create_if_not_exists=False)
session.prom... | akila122/pycad | autocad_session/__init__.py | __init__.py | py | 679 | python | en | code | 0 | github-code | 6 |
12211334459 | '''Some helper functions for PyTorch, including:
- get_mean_and_std: calculate the mean and std value of dataset.
- msr_init: net parameter initialization.
- progress_bar: progress bar mimic xlua.progress.
'''
import os
import sys
import time
import math
import torch
import torchvision
import torch.nn as n... | zarekxu/QuadraLib | image_classification/utils.py | utils.py | py | 7,113 | python | en | code | 6 | github-code | 6 |
35260443444 | import logging
from typing import List, Optional
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from debunkbot.models import (
Claim,
GoogleSheetCredentials,
MessageTemplate,
MessageTemplateSource,
)
logger = logging.getLogger(__name__)
class GoogleSheetHelper(obj... | CodeForAfrica/DebunkBot | debunkbot/utils/gsheet/helper.py | helper.py | py | 3,569 | python | en | code | 8 | github-code | 6 |
42926779466 | '''
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增
的顺序排序,每一列都按照从上到下递增的顺序排
序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数
'''
class Solution:
# array二维列表
def find(self, target, array):
xend = len(array) - 1
yend = len(array[0]) - 1
x = 0
while x <= xend and yend >= 0:
if array[x][yend] ... | ppalantir/axjingWorks | algorithm_note/getOffer/offer_find_two_array.py | offer_find_two_array.py | py | 878 | python | zh | code | 1 | github-code | 6 |
72532378429 | from collections.abc import Sequence
from datetime import datetime, timedelta
from typing import Final
import arrow
import pytest
from pydantic import NonNegativeFloat
from simcore_service_dynamic_sidecar.modules.prometheus_metrics import (
_MAX_DEFAULT_METRICS_SCRAPE_INTERVAL,
_MAX_PROMETHEUS_SAMPLES,
_ge... | ITISFoundation/osparc-simcore | services/dynamic-sidecar/tests/unit/test_modules_prometheus_metrics.py | test_modules_prometheus_metrics.py | py | 1,426 | python | en | code | 35 | github-code | 6 |
10260578739 | import json
import heapq
import math
#get texts
with open('10k_tokenized_texts.json', 'r') as file:
tokenized_texts = json.load(file)
#count word frequency and create vocabulary
wordfreq = {}
for text in tokenized_texts:
for token in text:
if token not in wordfreq.keys():
wordfreq[token] =... | iwillemse/pre-uni | code/bow-tfidf.py | bow-tfidf.py | py | 1,368 | python | en | code | 0 | github-code | 6 |
21402553475 | from pyTasks.tasks import Task, Parameter
from pyTasks.utils import containerHash
from .graph_tasks import GraphPruningTask
from .mongo_tasks import MongoResourceTarget
from sklearn.model_selection import KFold
import numpy as np
from bson.code import Code
def non_filter(label):
return False
def identity(obj):
... | cedricrupb/pySVRanker | frequent_pattern_tasks.py | frequent_pattern_tasks.py | py | 2,344 | python | en | code | 2 | github-code | 6 |
74959952508 | from django.db import models
from django.core.validators import RegexValidator
from django.contrib.auth.models import AbstractUser
from django.db import models
from libgravatar import Gravatar
# Create your models here.
class User(AbstractUser):
"""User model used for authentication."""
class Experience(mode... | amir-rahim/ChessClubManagementSystem | clubs/models/users.py | users.py | py | 1,456 | python | en | code | 1 | github-code | 6 |
13522158009 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 7 10:37:20 2019
@author: paul
"""
# import relevant packages
from TwitterAPI import TwitterAPI
import pandas as pd
import json
i = 0 # counter
requestlist = [] # list for storing each call from the api (500 tweets at a time)
# search Crit... | prgeddes/TwitterDataExtraction | Search_Save_Tweets.py | Search_Save_Tweets.py | py | 1,563 | python | en | code | 0 | github-code | 6 |
72940318588 | #
# @lc app=leetcode id=9 lang=python3
#
# [9] Palindrome Number
#
# https://leetcode.com/problems/palindrome-number/description/
#
# algorithms
# Easy (47.22%)
# Likes: 2092
# Dislikes: 1505
# Total Accepted: 860.8K
# Total Submissions: 1.8M
# Testcase Example: '121'
#
# Determine whether an integer is a palind... | LeanderLXZ/leetcode-solutions | problems/9.palindrome-number/9.palindrome-number.py | 9.palindrome-number.py | py | 1,419 | python | en | code | 0 | github-code | 6 |
5404980794 | # the array consist of interger,where every integer is repeated thrice except one integer ,we need to return that.
def single_number(Arr):
n = len(Arr)
ones = 0
twos = 0
for i in range(0,n):
ones = (ones ^ Arr[i] ) & (~twos)
twos = (twos ^ Arr[i]) & (~ ones)
return ones
... | Ranjit007ai/InterviewBit-BitManipulation | bit_manipulation/single_number_II/solution.py | solution.py | py | 418 | python | en | code | 0 | github-code | 6 |
35473677115 | import numpy as np
class PriorBoxes:
def __init__(self, strides, scales, ratios):
self.strides = strides
self.scales = scales # [10, 25, 40]
self.ratios = ratios
self.config = {
"strides": self.strides,
"scales": self.scales,
"ratios": self.rati... | taila0/single-shot-multibox-detector | src/old_codes/prior.py | prior.py | py | 2,726 | python | en | code | 0 | github-code | 6 |
71839285309 | """This module is responsible for reading the tables and processing them in order to use their data.
The use of pandas or any other parsing of the particular data table should be done here.
"""
__author__ = "carlosmperilla"
__copyright__ = "Copyright 2022 Carlos M. Perilla"
__credits__ = "Carlos M. Perilla"
_... | carlosmperilla/budget-system | budget_system/purchase/__init__.py | __init__.py | py | 510 | python | en | code | 2 | github-code | 6 |
34892241691 | from logging import raiseExceptions
from flask import Flask, request, make_response, jsonify
from flask_cors import CORS, cross_origin
import hashlib
from controller import *
app = Flask(__name__)
CORS(app)
Controller = Controller()
@app.route("/ong", methods=["GET", "POST", "PUT"])
@cross_origin()
def ong():
"""... | BrunoTaufner/RPII | server/app.py | app.py | py | 4,960 | python | en | code | 0 | github-code | 6 |
18216869821 | #Fall2019W9B
#Broken Keyboard | CodeForces 1251A
if __name__ == "__main__":
nqueries = int(input())
outputs = []
for q in range(nqueries):
testStr = input()
strLen = len(testStr)
res = ""
ind = 0
while ind < strLen:
currChar = testStr[ind]
if ... | andrew-qu2000/Programming-Club | Poly Programming Club/Fall2019W9B.py | Fall2019W9B.py | py | 814 | python | en | code | 0 | github-code | 6 |
14703280517 | from datetime import datetime
from os.path import dirname, join
import pytest
from city_scrapers_core.constants import COMMISSION
from city_scrapers_core.utils import file_response
from freezegun import freeze_time
from city_scrapers.spiders.sf_planning import SfPlanningSpider
test_response = file_response(
join... | washabstract/city-scrapers-ca | tests/test_sf_planning.py | test_sf_planning.py | py | 2,234 | python | en | code | 1 | github-code | 6 |
21959415638 | from fastapi import APIRouter, HTTPException
from init_system import system
from schemas.customer_shcema import SignIn, SignUp, SetCart, Email
from models.Cart import CartItem
router = APIRouter(prefix="/customer")
@router.post("/sign_in")
async def customer_login(body: SignIn):
try:
return {
... | Dope21/python-oop | controllers/customer_ctrl.py | customer_ctrl.py | py | 2,486 | python | en | code | 0 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.