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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
71622317224 | from gnocchi import gnocchi_api
def create_NN_file(instance_id) :
data = gnocchi_api("admin" , "hamed" , "admin")
instance_resource_id = instance_id
network_instance_resource_id = data.get_resource_id("instance_network_interface" , instance_id)
disk_instance_resource_id = data.get_resource_id("instance... | universcom/Cloud-AI-AutoScale | get_data/data_gathering.py | data_gathering.py | py | 1,768 | python | en | code | 0 | github-code | 36 |
43566759366 | # Connect to an "eval()" service over BLE UART.
import os
import sys
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService
ble = BLERadio()
ble.stop_scan()
uart_connection = None
while True:
if not uart_con... | jappavoo/flashy | ble.py | ble.py | py | 1,214 | python | en | code | 0 | github-code | 36 |
29389754682 | class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
rows = [set() for _ in range(9)]
cols = [set() for _ in range(9)]
boxes = [set() for _ in range(9)]
for i in range(9):
for j in range(9):
cell = board[i][j]
i... | AnotherPianist/LeetCode | 0036-valid-sudoku/0036-valid-sudoku.py | 0036-valid-sudoku.py | py | 629 | python | en | code | 1 | github-code | 36 |
14365200747 | #Import dependencies
import json
import pandas as pd
import numpy as np
import re
from sqlalchemy import create_engine
import psycopg2
from config import db_password
import time
#Set file directory
file_dir = '/Users/mariacarter/Desktop/Berkeley-Bootcamp/Analysis-Projects/Movies-ETL/Resources/'
def process_ETL(wiki_m... | mcarter-00/Movies-ETL | challenge.py | challenge.py | py | 15,363 | python | en | code | 0 | github-code | 36 |
7704128693 | # -*- coding:utf-8 -*-
"""
Evluate the performance of embedding via different methods.
"""
import math
import numpy as np
from sklearn import metrics
from sklearn import utils as sktools
from sklearn.cluster import AgglomerativeClustering
from sklearn.cluster import SpectralClustering
from sklearn.linear_model impor... | Sngunfei/HSD | tools/evaluate.py | evaluate.py | py | 5,117 | python | en | code | 3 | github-code | 36 |
14049615322 | from django.shortcuts import render
from admin_dashboard.models import Review, Package
from django.contrib import messages
def home(request):
reviews = Review.objects.all()
packages = Package.objects.all()
return render(request, 'index.html', {
'title': 'Home',
'reviews': reviews,
... | aniatki/pro-dad | homepage/views.py | views.py | py | 709 | python | en | code | 0 | github-code | 36 |
40568030755 | from __future__ import annotations
import random
from datetime import timedelta
from typing import Type
from game.theater import FrontLine
from game.utils import Distance, Speed, feet
from .capbuilder import CapBuilder
from .invalidobjectivelocation import InvalidObjectiveLocation
from .patrolling import PatrollingFl... | dcs-liberation/dcs_liberation | game/ato/flightplans/barcap.py | barcap.py | py | 2,444 | python | en | code | 647 | github-code | 36 |
33865589189 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import datetime
class Migration(migrations.Migration):
dependencies = [
('bot', '0007_bot_logo'),
]
operations = [
migrations.CreateModel(
name='Chat',
fields... | DenerRodrigues/Chatterbot | bot/migrations/0008_chat.py | 0008_chat.py | py | 681 | python | en | code | 0 | github-code | 36 |
4255077844 | """
Introduction
Given the weights and profits of 'N' items, we are asked to put these items in a knapsack that has a capacity 'C'. The goal is to get the maximum profit from the items in the knapsack. The only difference between the "0/1 Knapsack" problem and this problem is that we are allowed to use an unlimited qua... | blhwong/algos_py | grokking_dp/unbounded_knapsack/unbounded_knapsack/main.py | main.py | py | 2,617 | python | en | code | 0 | github-code | 36 |
21393775413 | """
5 element API Client
"""
from typing import Optional, Tuple
from bgd.constants import FIFTHELEMENT
from bgd.responses import GameSearchResult, Price
from bgd.services.abc import GameSearchResultFactory
from bgd.services.api_clients import GameSearcher, JsonHttpApiClient
from bgd.services.base import CurrencyExchan... | ar0ne/bg_deal | bgd/services/apis/fifth_element.py | fifth_element.py | py | 3,213 | python | en | code | 0 | github-code | 36 |
15827248022 | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import unittest
import importlib
import os
from emission.core.wrapper.trip_ol... | e-mission/e-mission-server | emission/individual_tests/TestNominatim.py | TestNominatim.py | py | 6,717 | python | en | code | 22 | github-code | 36 |
28297076587 | #!/bin/python3
"""
Creates new training data for all language directions (META_LANGS) according to META_RECIPES.
This may take some time, but is written in a functional way, so the files are not loaded into memory
in larger pieces.
"""
import file_utils
from recipes import META_RECIPES
import os
import argparse
par... | zouharvi/reference-mt-distill | src/create_data.py | create_data.py | py | 1,805 | python | en | code | 0 | github-code | 36 |
42218937553 | import os
import pandas as pd
import time
from pathlib import Path
import shutil
from bs4 import BeautifulSoup
#loading all the files in the memory and parsing it using beautiful soap to get key financials
#problem in reading coal india.
#due to unrecognized encoding, it throws error
#we add encoding="utf8"
d... | santoshjsh/invest | nse_7.py | nse_7.py | py | 2,312 | python | en | code | 0 | github-code | 36 |
5543843400 | N = int(input())
b = 0
a = -1
for i in range(1, N+1):
x = int(input())
if x <= 437:
a = i
break
if a != -1:
print(f'crash {a}')
else:
print('No crash')
| Grigorij-Kuzmin/Python | Автобусная экскурсия.py | Автобусная экскурсия.py | py | 184 | python | en | code | 0 | github-code | 36 |
35206645553 | from django.contrib import admin
from .models import *
class CostInline(admin.TabularInline):
model = Cost
extra = 0
class CoordinatesAdmin(admin.ModelAdmin):
list_display = ('latitude', 'longitude')
class LanguageAdmin(admin.ModelAdmin):
list_display = ('name', 'population')
class CountryAdmin(admin.... | borisovodov/np | app/admin.py | admin.py | py | 4,586 | python | en | code | 0 | github-code | 36 |
262396930 | from bs4 import BeautifulSoup
import requests
import requests # request img from web
import shutil # save img locally
URL1 = 'http://localhost'
page = requests.get(URL1)
soup = BeautifulSoup(page.content, 'html.parser')
print(soup.prettify())
image_tags = soup.find_all('img')
for image_tag in image_tags:
url = im... | FukudaYoshiro/singo | saudi/import image.py | import image.py | py | 555 | python | en | code | 4 | github-code | 36 |
15098306537 | #
#
#
import pandas as pd
import geopandas as gpd
from zipfile import ZipFile
from pathlib import Path
import sys,time
def Read_Glob_Bldg( country_geojson ):
CACHE = './PICKLE'
DIR = Path( '/home/phisan/GeoData/GlobML_BldgFP' )
GEOJSON = DIR.joinpath( country_geojson )
STEM = GEOJSON.stem
PICKLE ... | phisan-chula/Thai_Bldg_Model | BreakProv_Bldg.py | BreakProv_Bldg.py | py | 2,944 | python | en | code | 0 | github-code | 36 |
28780066181 | """
HackerRank Python Numpy Polynomials
author: Manny egalli64@gmail.com
info: http://thisthread.blogspot.com/
https://www.hackerrank.com/challenges/np-polynomials/problem
given the coefficients of a polynomial, find its value at x
"""
import numpy as np
values = tuple(map(float, input().split()))
x = float(in... | egalli64/pythonesque | hr/numpy/polynomials.py | polynomials.py | py | 357 | python | en | code | 17 | github-code | 36 |
35809219103 | #! python2
# -*- coding: utf-8 -*-
import scrapy
import csv
import time
from sys import exit
import os
import logging
from scrapy import signals
from . import wikimallbottodbmy
import re
#from scrapy.utils.log import configure_logging
class WikimallbotSpider(scrapy.Spider):
name = 'wikimallbot'
allowed_do... | rizanurhadi/webscraping1 | spiders/wikimallbot.py | wikimallbot.py | py | 7,971 | python | en | code | 0 | github-code | 36 |
41057893138 | lista_compras = ['leite em pó', 'mamão', 'queijo']
id_clientes_2 = (100, 125, 478, 547, 565)
cod_uf = {'mg':31, 'sp':35}
pessoa = 'Marcelo'
num_pessoas = 274
dist_km = 25.23
custo_carro = '500,00'
capitais_sul_br = ['Porto Alegre', 'Curitiba', 'Florianópolis'] | marcusvco/Simple-Side-Projects | IGTI/Python/trabalho_pratico.py | trabalho_pratico.py | py | 270 | python | pt | code | 0 | github-code | 36 |
16858290153 | # Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import deque
deq = deque()
for i in range(int(input())):
command = input().split()
if command[0] == 'append':
deq.append(command[1])
elif command[0] == 'appendleft':
deq.appendleft(command[1])
elif c... | polemeest/daily_practice | hackerrank_deque.py | hackerrank_deque.py | py | 490 | python | en | code | 0 | github-code | 36 |
198052217 | from django.views import generic
from digifarming.models import User, Staff, Rating, \
RequestType, Commodity, Supply, \
Order, OrderItem, UserTrackingMovements, HarvestDispatch,FacilityType, Facility, \
JobTitle, JobShift, ArrivalView, DepartureView, CancellationView, \
TransportCategory, TransportTyp... | gatirobi/digifarming | digifarming/digifarming/views.py | views.py | py | 53,254 | python | en | code | 0 | github-code | 36 |
4567187720 | from app.models.roles_enums import Werewolves, Alignment
from app.services import game_info as gi
from app.utils.ability_utils import add_death, remove_death
from app.utils.info_utils import find_alignment
def werewolf(player: int, target: int) -> str:
gi.night_info["ww_kill"] = target
add_death(target)
... | wenyangzhang42/werewolf-backend | app/services/abilities.py | abilities.py | py | 5,438 | python | en | code | 0 | github-code | 36 |
11043626340 | from RiceClassifier.config.configuration import (ConfigurationManager,YAMLConfigReader,FilesystemDirectoryCreator)
from RiceClassifier.components.data_ingestion import (DataIngestion,FileDownloader,ZipExtractor)
from RiceClassifier.logger import logger
STAGE_NAME = "Data Ingestion stage"
class DataIngestionTrainingP... | nasserml/End-To-End_Rice-Classification-Project | src/RiceClassifier/pipeline/stage_01_data_ingestion.py | stage_01_data_ingestion.py | py | 1,172 | python | en | code | 0 | github-code | 36 |
34558226431 | #Stephen Duncanson
#Standard deviation
import math
total = 0
dataList = []
total_num = 0
def get_input():
how_many = 0
how_many = int(input("How many pieces of data: "))
for i in range(how_many):
data = float(input("Enter data point:"))
dataList.append(data)
def sd():
total = 0
to... | kellyfitmore/random-python | sd.py | sd.py | py | 609 | python | en | code | 0 | github-code | 36 |
18375485118 | #!/bin/python3
# Complete the extraLongFactorials function below.
def extraLongFactorials(n):
factorial = 1
# check if the number is negative, positive or zero
if n < 0:
print("Sorry, factorial does not exist for negative numbers")
elif n == 0:
print(1)
else:
for i in range(... | sauravsapkota/HackerRank | Practice/Algorithms/Implementation/Extra Long Factorials.py | Extra Long Factorials.py | py | 489 | python | en | code | 0 | github-code | 36 |
44675601513 | import pysubs2
import pysrt
archivo = 'subtitle.ass'
subs = pysubs2.load(archivo, encoding='utf-8')
for line in subs:
print(line.text)
textoplano = line.text
texto = open('textoplano.txt', 'a')
texto.write(textoplano)
texto.close()
| FukurOwl/subtitles_translate | load_files.py | load_files.py | py | 260 | python | es | code | 0 | github-code | 36 |
1529107170 | #Time complexity = O(n^2) | Space complexity = O(n)s
def threeNumberSum(array, targetSum):
resultArray = list()
for i in range(len(array) - 2):
left = i+1
right = len(array)-1
while (left < right):
currentSum = array[left] + array[right] + array[i]
if(currentSum =... | puneeth1999/InterviewPreparation | AlgoExpert/arrays/2. threeNumberSum/two_pointer_method.py | two_pointer_method.py | py | 705 | python | en | code | 2 | github-code | 36 |
12390972181 | class seating:
def __init__(self , filename):
self.seat = self.read_file(filename)
self.index = 0
@staticmethod
def read_file(filename):
try :
with open(filename , 'r') as f:
seat = [i.rstrip('\n').split(' ') for i in f]
... | homework2005/hw01 | hw01.py | hw01.py | py | 1,857 | python | en | code | 0 | github-code | 36 |
72908308584 | """
Чтобы решить данную задачу, можно воспользоваться алгоритмом поиска в ширину (BFS),
так как он позволяет находить кратчайшие пути в графе с невзвешенными ребрами.
В нашем случае города и дороги между ними образуют граф без весов на ребрах.
"""
from collections import deque
# Функция для вычисления расстояния ме... | TatsianaPoto/yandex | ML & Programming/6_find_shortest_path.py | 6_find_shortest_path.py | py | 4,858 | python | ru | code | 0 | github-code | 36 |
3733422218 | from argparse import Namespace
from pandas.core.frame import DataFrame
from app.command.sub_command import SubCommand
from app.error.column_already_exists_error import ColumnAlreadyExistsError
from app.error.column_not_found_error import ColumnNotFoundError
class Add(SubCommand):
def __init__(self, args: Namesp... | takenoco82/alter_csv | src/app/command/add.py | add.py | py | 1,355 | python | en | code | 0 | github-code | 36 |
71551407784 | import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
from textClustringAnalysis.feature.common import dict2Array, myTFIDF
from textClustringAnalysis.feature.main import TC, TC_PCA, PCA
from textClustringAnalysis.preprocessor.dataInfo import getWordCount
if __name__ == '__main__':
"""
当我们想要对高维数据进行... | bearbro/TextClusteringAnalysis | textClustringAnalysis/showdatafirst.py | showdatafirst.py | py | 2,127 | python | en | code | 3 | github-code | 36 |
30134924939 | import numpy as np
import datetime as dt
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func, and_
from flask import Flask, jsonify
engine = create_engine("sqlite:///hawaii.sqlite")
base = automap_base()
base.prepare(engine,... | Emziicles/sqlalchemy-challenge | app.py | app.py | py | 2,364 | python | en | code | 0 | github-code | 36 |
33743344827 | # import from module
from random import seed
from lab4 import rand_search
# random seed
seed(123)
some_string = "this is some string that will be used in the code"
search_string = "strings"
# test for strings
input_data = list(some_string.split())
# print status
rand_search(input_data, search_string) | KarloHasnek/Algoritmi-i-Strukture-podataka | Labovi/Lab4/lab4nastavak.py | lab4nastavak.py | py | 306 | python | en | code | 0 | github-code | 36 |
1355556431 | import pygame
import os
import time
import random
x = 100
y = 50
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x,y)
width = 1640
height = 980
pygame.init()
screen = pygame.display.set_mode((width, height))
white = (255, 255, 255)
black = (0, 0, 0)
random_color = (random.randint(0, 255), random.ra... | MagicLuxa/Python-Projects | sorting algorithms visualized.py | sorting algorithms visualized.py | py | 4,028 | python | en | code | 0 | github-code | 36 |
6435166822 | from collections import Counter
def maketemp(l,h):
templist = []
for i in range(l,h+1):
templist.append(i)
return templist
def themode(lst):
n = len(lst)
data = Counter(lst)
get_mode = dict(data)
mode = [k for k, v in get_mode.items() if v == max(list(data.values()))]
if len(mo... | DongjiY/Kattis | src/airconditioned.py | airconditioned.py | py | 1,012 | python | en | code | 1 | github-code | 36 |
37412585435 | import numpy as np
from ..functions import B_nu, dB_nu_dT
from ..integrate import integrate_loglog
from ..constants import sigma, k, c
def test_b_nu():
nu = np.logspace(-20, 20., 10000)
for T in [10, 100, 1000, 10000]:
# Compute planck function
b = B_nu(nu, T)
# Check that the int... | hyperion-rt/hyperion | hyperion/util/tests/test_functions.py | test_functions.py | py | 1,107 | python | en | code | 51 | github-code | 36 |
18518889020 | import os
def get_profits(folder):
all_profits = []
subfolders = os.listdir(folder)
subfolders.sort(key=int)
# go through all folders in the folder
for subfolder in subfolders:
# read profit from total_profit.txt
with open(os.path.join(folder, subfolder, 'total_profit.txt'),
... | BenPVandenberg/blackjack-ai | analysis.py | analysis.py | py | 584 | python | en | code | 1 | github-code | 36 |
4115122521 | import os
def transfer(fileName):
matrix = []
f = open(fileName, 'r')
for line in f.readlines():
matrix.append(line.split(','))
f.close()
f = open(fileName, 'w')
rows = len(matrix[1])
for i in range(rows - 1):
newLine = ''
for j in [1,4]:
newLine += (mat... | LaputaRobot/STK_MATLAB | PMetis/reservCSV.py | reservCSV.py | py | 590 | python | en | code | 0 | github-code | 36 |
69845996905 | #!/usr/bin/env python
import pika
from pika.adapters import BlockingConnection
from pika import BasicProperties
#connection = BlockingConnection('172.20.14.192')
connection = pika.BlockingConnection(pika.ConnectionParameters('172.20.14.192'))
channel = connection.channel()
client_params = {"x-ha-policy": "all"}
exch... | appop/simple-test | createmessage/createqueue.py | createqueue.py | py | 654 | python | en | code | 2 | github-code | 36 |
25353856217 | import http.server
import socketserver
import cgi
import pymongo
import json
import bcrypt
import secrets
import hashlib
import base64
from datetime import datetime, timedelta
import helperFunction as helper
SOCKET_GUID = b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
TEXT_FRAME = 1
OPCODE_MASK = 0b00001111
PAYLOAD_LEN_MASK ... | jackyzhu209/312-Project | website/httpserver.py | httpserver.py | py | 27,742 | python | en | code | 0 | github-code | 36 |
2503764043 | #!/usr/bin/env python
# *********************
# webcam video stream
# *********************
import time
import cv2
# 0 - Dell Webcam
# cap = cv2.VideoCapture('filename.avi')
cap = cv2.VideoCapture(0)
pTime = 0
while (cap.isOpened()):
cTime = time.time()
ret, frame = cap.read()
if ret == True:
fp... | ammarajmal/cam_pose_pkg | script/webcam.py | webcam.py | py | 640 | python | en | code | 0 | github-code | 36 |
16567280409 | import tensorflow as tf
import keras
import numpy as np
import matplotlib.pyplot as plt
from keras.layers import Input, Dense, Lambda, InputLayer, concatenate, Dropout
from keras.models import Model, Sequential
from keras import backend as K
from keras import metrics
from keras.datasets import mnist
from keras.utils i... | tirthasheshpatel/Generative-Models | vae.py | vae.py | py | 3,413 | python | en | code | 0 | github-code | 36 |
7410224509 | from bs4 import BeautifulSoup
import requests
from selenium import webdriver
import re
import timeit
url = "https://www.investing.com/equities/trending-stocks"
driver = webdriver.Chrome(r"C:\Program Files\chromedriver.exe")
driver.get(url)
# x, stockPopularityData
page = driver.page_source
soup = BeautifulSoup(page, ... | SRI-VISHVA/WebScrapping | scrapping_73.py | scrapping_73.py | py | 1,915 | python | en | code | 0 | github-code | 36 |
23413820054 | # -*- coding: utf-8 -*-
"""
Create doc tree if you follows
:ref:`Sanhe Sphinx standard <en_sphinx_doc_style_guide>`.
"""
from __future__ import print_function
import json
from pathlib_mate import PathCls as Path
from .template import TC
from .pkg import textfile
class ArticleFolder(object):
"""
Represent... | MacHu-GWU/docfly-project | docfly/doctree.py | doctree.py | py | 5,328 | python | en | code | 0 | github-code | 36 |
4877559988 |
import os
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
import pandas
data = pandas.read_csv('C:\\Users\\aruny\\Downloads\\ezyzip\\MusicApp\\songs.csv')
data = data.to_dict('records')
song_names = [i['name'] for i in data]
dir = 'C:\playlist songs\Malayalam_sad_songs'
files = os.listdir(dir)
for song in ... | chmson/MusicApp_website | MusicApp/give_id.py | give_id.py | py | 1,094 | python | en | code | 0 | github-code | 36 |
34922299042 | """
shared dataloader for multiple issues
must gurantee that a batch only has data from same issue
but the batches can be shuffled
"""
import collections
from more_itertools import more
from numpy.core import overrides
import torch
from torch import tensor
import torch.nn as nn
import numpy as np
from torch.utils.data... | xymou/Frame_Detection | myprompt/myprompt/data/share_dataloader.py | share_dataloader.py | py | 7,930 | python | en | code | 1 | github-code | 36 |
3327955898 | import argparse
import re
_re_pattern_value_unit = r"^\s*(-?\d+(?:.\d+)?)\s*([a-zA-Z]*?[\/a-zA-Z]*)$"
# this regex captures the following example normal(3s,1ms) with/without spaces between parenthesis and comma(s)
# it's also able to capture the sample duration specified after the distribution e.g., normal(3s,1ms) H 2... | connets/tod-carla | src/args_parse/parser_utils.py | parser_utils.py | py | 7,994 | python | en | code | 3 | github-code | 36 |
37914230085 | from pathlib import Path
import json
import plotly.express as px
import numpy as np
# Read data as a string and convert to a Python object.
path = Path("eq_data/eq_data.geojson")
contents = path.read_text(encoding="utf-8")
all_eq_data = json.loads(contents)
# Examine all the earthquakes in dataset
all_eq_dicts = all... | hharpreetk/python-earthquake-data-viz | eq_explore_data.py | eq_explore_data.py | py | 1,615 | python | en | code | 0 | github-code | 36 |
10603730701 | import argparse
import time , datetime
from pythonosc import udp_client
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--ip", default="127.0.0.1",
help="The ip of the OSC server")
parser.add_argument("--port", type=int, default=9000,
help="The port the OSC server... | kakuchrome/OSCscript | timer.py | timer.py | py | 968 | python | en | code | 0 | github-code | 36 |
17079421444 | from glob import glob
from itertools import chain
import logging
from lib.language import canonicalize_tokens, clean_text, clean_tokens, tokenize_text
from lib.language.types import TokenStream
from lib.util import chain as chain_calls, extract_text
logger = logging.getLogger(__name__)
def tokenize_corpus(globby_p... | amy-langley/tracking-trans-hate-bills | lib/tasks/tokenize_corpus.py | tokenize_corpus.py | py | 752 | python | en | code | 2 | github-code | 36 |
476391810 | from jwcrypto import jwk
import json
from .key_base import KeyBase
class Jwks(KeyBase):
def handle(self, input_output):
public_keys = self.fetch_and_check_keys(self.configuration("path_to_public_keys"))
keys = [
{
"kid": key["kid"],
"use": key["use"],
... | cmancone/clearskies-auth-server | src/clearskies_auth_server/handlers/jwks.py | jwks.py | py | 597 | python | en | code | 0 | github-code | 36 |
73520719463 | from Functions import Functions
from log import Log
from webdriver import WebDriver
import PySimpleGUI as sg
import json
class Main:
def __init__(self):
self.ind = 0 # Indice utilizado para acessar o json.
self.log = Log() # Log de registro.
self.url = Functions().Json('Collector', 'ur... | LucasAmorimDC/SeleniumCollector | Selenium_Collector/Main.py | Main.py | py | 4,318 | python | en | code | 0 | github-code | 36 |
14128327348 | #!/usr/local/bin/ python3
# -*- coding:utf-8 -*-
# __author__ = "zenmeder"
class Solution(object):
def searchInsert(self, nums, target):
low = 0
high = len(nums)-1
while low<=high:
mid = int((low+high)/2)
if nums[mid] == target:
return mid
elif nums[mid]<target:
low = mid+1
else:
high = m... | zenmeder/leetcode | 35.py | 35.py | py | 408 | python | en | code | 0 | github-code | 36 |
35198885002 | # -*- coding: utf-8 -*-
"""
Test to check api calls in in varonis assignment
"""
import json
import pytest
import requests
URL = "http://localhost:8000"
data = {
"data": [{"key": "key1", "val": "val1", "valType": "str"}]
}
credentials_data = {
"username": "test",
"password": "1234"
}
wron... | eldar101/EldarRep | Python/Varonis/api_assignment/test_api.py | test_api.py | py | 2,627 | python | en | code | 0 | github-code | 36 |
2769961219 | from weixin_api_two.api.contact.get_wework_token import WeworkToken
from weixin_api_two.uitls.get_data import GetData
import loguru
class Tag(WeworkToken):
def __init__(self):
self.baseurl=GetData()
self.log= loguru.logger
self.tagurl=self.baseurl.get_UrlData('url','tag')
self.add... | liwanli123/HogwartProjectPractice | weixin_api_two/api/externalcontact/tag_api.py | tag_api.py | py | 2,429 | python | en | code | 0 | github-code | 36 |
2922317279 | import os
DATA_DIR = '/home/sdemyanov/synapse/UniversalGAN/data/mnist'
RESULTS_DIR = '/home/sdemyanov/synapse/UniversalGAN/results/mnist'
#DATA_DIR = '/home/ge/Project/ICCV2017/lib/UniversalGAN/data/mnist'
#RESULTS_DIR = '/home/ge/Project/ICCV2017/lib/UniversalGAN/results/mnist'
TRAIN_FOLD = 'train'
VALID_FOLD = 'va... | sdemyanov/tensorflow-worklab | paths.py | paths.py | py | 450 | python | en | code | 24 | github-code | 36 |
23268554610 | import os
import asyncio
from user import User
class MessageError(Exception):
pass
class Message:
@classmethod
async def create(cls, **args):
self = Message()
self.channel = args.get("channel")
self.text = args.get("text")
self.user = args.get("user", (await User.create()))
if (self.channel is None or s... | Liyara/Tracker | message.py | message.py | py | 1,771 | python | en | code | 0 | github-code | 36 |
41675250827 | # Daily Coding Problem: Problem #4 [Hard]
# Given an array of integers, find the first missing positive integer in linear time and constant space.
# In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
#
# For example, the inp... | mglacayo07/DailyCodingProblem4 | main.py | main.py | py | 898 | python | en | code | 0 | github-code | 36 |
38440361902 | import requests
from decouple import config
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
@login_required(login_url='/accounts/login/')
def home(request):
disk = requests.get(config("API") + 'disk_space._')
load = requests.get(config("API") + 'system.load')
... | carlos-moreno/dashboard | dashboard/core/views.py | views.py | py | 950 | python | en | code | 0 | github-code | 36 |
3855378751 | # Applying the algorithms
n_simulation = 100000
# From module 6
predcorr_forward = np.ones([n_simulation, N]) \
* (model_prices[:-1]-model_prices[1:]) \
/ (delta_t*model_prices[1:])
predcorr_capfac = np.ones([n_simulation, N+1])
delta = np.ones([n_simulation, N])*delta_t
# calculate the forward rate f... | haininhhoang94/wqu | MScFE630/gwa_computational_finance/GWA3_1_simulation.py | GWA3_1_simulation.py | py | 1,813 | python | en | code | 21 | github-code | 36 |
17613252101 | import plotly.plotly as py
import plotly.graph_objs as go
from pymongo import MongoClient
import sys
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib
from networkx.algorithms import approximation as approx
from nxpd import draw
from networkx.drawing.nx_agraph import graphviz_layout
client = Mongo... | diaaahmed850/snaproject | diaa.py | diaa.py | py | 5,831 | python | en | code | 0 | github-code | 36 |
73450401385 | # !/usr/bin/python
# -*-coding=utf-8-*-
# Example site:@http://www.apostilando.com/pagina.php?cod=1
# 将要扫描的网站写入当前目录文件中。python xxx.py xxx.txt
import urllib
import os
import sys
if os.name == "nt":
os.system("cls")
else:
os.system("clear")
def usage():
print
"""
=================SQL INJECTION====... | Guaijs/Sql_injection_detection | crawler/Test2.py | Test2.py | py | 2,176 | python | en | code | 0 | github-code | 36 |
28984839741 | #! /usr/bin/env python
import argparse
import re
import numpy as np
def to_binary_string(value):
"""
Converts F or L to zeros, and B or R to 1 and interprets the string as a binary value
>>> to_binary_string("FBFBBFF")
('0101100', 44)
>>> to_binary_string("RLR")
('101', 5)
:param value:... | SocialFinanceDigitalLabs/AdventOfCode | solutions/2020/kws/day_05.py | day_05.py | py | 1,856 | python | en | code | 2 | github-code | 36 |
43301216014 | import py
from rpython.flowspace.model import Constant
from rpython.rtyper.lltypesystem import lltype
from rpython.jit.codewriter.flatten import SSARepr, Label, TLabel, Register
from rpython.jit.codewriter.flatten import ListOfKind, IndirectCallTargets
from rpython.jit.codewriter.jitcode import SwitchDictDescr
from rpy... | mozillazg/pypy | rpython/jit/codewriter/format.py | format.py | py | 6,680 | python | en | code | 430 | github-code | 36 |
26763674457 | import pandas as pd
from mega_analysis.crosstab.gif_sheet_names import gif_sheet_names
from mega_analysis.crosstab.file_paths import file_paths
def gif_lobes_from_excel_sheets():
"""
sort the gif parcellations as per excel gif sheet lobes.
e.g. GIF FL = GIF Frontal Lobe - has a list of gif parcellations
... | thenineteen/Semiology-Visualisation-Tool | mega_analysis/crosstab/gif_lobes_from_excel_sheets.py | gif_lobes_from_excel_sheets.py | py | 980 | python | en | code | 9 | github-code | 36 |
12514324819 | import torch
from torchtext.datasets import AG_NEWS
from torchtext.data.utils import get_tokenizer
from torchtext.vocab import build_vocab_from_iterator
from torch.utils.data import DataLoader
UNK = '<unk>'
tok = get_tokenizer('basic_english')
train_iter = AG_NEWS(split='train')
def yield_tokens(data_iter, tokenizer... | moon0331/TorchTutorial | seq2seq.py | seq2seq.py | py | 1,590 | python | en | code | 0 | github-code | 36 |
10844238227 | import shutil
executables = [
"flex",
"yacc",
]
def is_available(exe: str) -> bool:
return shutil.which(exe) is not None
def test_executables() -> None:
missing = [exe
for exe in executables
if not is_available(exe)]
assert not missing, f"Missing executables: {', '... | GravityDrowned/teaching-notebook | test_executables.py | test_executables.py | py | 337 | python | en | code | 0 | github-code | 36 |
30055768931 | import argparse
import numpy as np
from Data import Data
from Experiment import Experiment
from FrameStackExperiment import FrameStackExperiment
if __name__=='__main__':
parser = argparse.ArgumentParser(description='Evaluate termination classifier performance')
parser.add_argument('filepath', type=str, help=... | jwnicholas99/option-term-classifier | run.py | run.py | py | 5,905 | python | en | code | 0 | github-code | 36 |
15771336312 | import ctypes
import typing as t
from . import sdk
from .enum import Result
from .event import bind_events
from .exception import get_exception
from .model import UserAchievement
class AchievementManager:
_internal: sdk.IDiscordAchievementManager = None
_garbage: t.List[t.Any]
_events: sdk.IDiscordAchiev... | Maselkov/GW2RPC | gw2rpc/lib/discordsdk/achievement.py | achievement.py | py | 3,610 | python | en | code | 47 | github-code | 36 |
73456512104 | # -*- coding: utf-8 -*-
# Time : 2023/10/5 22:53
# Author : QIN2DIM
# GitHub : https://github.com/QIN2DIM
# Description:
import csv
from dataclasses import dataclass, field
from pathlib import Path
from typing import List
class Level:
first = 1
second = 2
third = 3
fourth = 4
fifth =... | QIN2DIM/hysterical_ticket | hysterical_ticket/component/bingo_ssq.py | bingo_ssq.py | py | 3,044 | python | en | code | 3 | github-code | 36 |
3579460229 | import sys
import os
import string
def int_input():
string = input()
if not string:
return (-10)
elif (len(string) == 1) and (string[0] == '0'):
return (0)
else:
try:
numb = int(string)
return (numb)
except ValueError:
return (-10)
ps... | gquence/term_db | python/main.py | main.py | py | 6,548 | python | en | code | 0 | github-code | 36 |
3465936756 | import json, requests, subprocess, sys, yaml
from pip._vendor.distlib.compat import raw_input
class JiraClient():
board_status_to_env = {"Ready to Deploy": "QAX",
"QAX Done": "STGX",
"StgX Done": "PROD-EU",
"Prod EU Done": "PROD-US"... | mulesoft-labs/popeye | JiraClient.py | JiraClient.py | py | 9,957 | python | en | code | 1 | github-code | 36 |
2346859029 | import numpy as np
from PIL import Image
# Goal: convert an image file from normal pixels to ANSI art made of dots "."
# of same color with canvas-like color background
# ANSI foreground color (n, 0-255) based on 256-bit -> \033[38;5;nm
# ANSI background color (n, 0-255) based on 256-bit -> \033[48;5;nm
# end with \0... | jakecharris/pointillism | source.py | source.py | py | 2,172 | python | en | code | 0 | github-code | 36 |
36749002781 | import cv2
thres = 0.45 # Threshold to detect object
# hog = cv2.HOGDescriptor()
# hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
#
# cv2.startWindowThread()
cap = cv2.VideoCapture(0)
### for IP CAM
# cap = cv2.VideoCapture('rtsp://admin:admin@192.168.1.108/',apiPreference=cv2.CAP_FFMPEG)
cap.set(... | Quant1766/detectObjects | main.py | main.py | py | 1,420 | python | en | code | 0 | github-code | 36 |
2722455823 | class Solution(object):
def sortSentence(self, s):
"""
:type s: str
:rtype: str
"""
tmp = []
for sub in s.split(" "):
tmp.append([sub[-1], sub[:-1]])
tmp.sort()
return ' '.join([x[1] for x in tmp])
| ZhengLiangliang1996/Leetcode_ML_Daily | contest/biweekcontest52/sortsentence.py | sortsentence.py | py | 296 | python | en | code | 1 | github-code | 36 |
18665738715 | import os, requests
index_file_path = input("Enter Index file path with extension m3u8 : ")
index_file = open(index_file_path,'r')
indexes = index_file.read()
index_file.close()
output_file_path = input("Enter output file path : ")
output_file = open(output_file_path,'wb')
folder_path = input("Enter folder path ... | nkpro2000sr/m3u8ToVideo | m3u8tovideo.py | m3u8tovideo.py | py | 952 | python | en | code | 1 | github-code | 36 |
74172105702 | import math
import centrosome.outline
import numpy
import numpy.testing
import pytest
import skimage.measure
import skimage.segmentation
import cellprofiler_core.image
import cellprofiler_core.measurement
from cellprofiler_core.constants.measurement import (
EXPERIMENT,
COLTYPE_FLOAT,
C_LOCATION,
)
impo... | BodenmillerGroup/ImcPluginsCP | tests/test_measureobjectintensitymultichannel.py | test_measureobjectintensitymultichannel.py | py | 20,306 | python | en | code | 10 | github-code | 36 |
16211931413 | # 두 요소의 위치를 바꿔주는 helper function
def swap_elements(my_list, index1, index2):
tmpValue = my_list[index2]
my_list[index2] = my_list[index1]
my_list[index1] = tmpValue
return my_list
# 퀵 정렬에서 사용되는 partition 함수
def partition(my_list, start, end):
p = end # pivot 인덱스
b = start # big 그룹 이동 인덱스
i = start # 체크 이... | hwiVeloper/zzamzzam2 | codeit-algorithm-python/15-partition/main.py | main.py | py | 914 | python | ko | code | 0 | github-code | 36 |
17795055591 | from typing import List
class Solution:
def highFive(self, items: List[List[int]]) -> List[List[int]]:
items.sort(key=lambda x: (x[0], x[1]))
ans = list()
for i in range(len(items)):
if i == len(items) - 1 or items[i][0] != items[i + 1][0]:
temp = list()
... | fastso/learning-python | leetcode_cn/solved/pg_1086.py | pg_1086.py | py | 569 | python | en | code | 0 | github-code | 36 |
24486912101 | """ Clean up of hail endpoint column in three steps:
- remove unused staging column
- remove now obsolete testing column
- make hail_endpoint_production non null
Revision ID: aa6d3d875f28
Revises: 8bd62cba881a
Create Date: 2020-11-17 09:28:10.910999
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.d... | openmaraude/APITaxi | APITaxi_models2/migrations/versions/20201117_09:28:10_aa6d3d875f28_clean_hail_endpoints.py | 20201117_09:28:10_aa6d3d875f28_clean_hail_endpoints.py | py | 1,214 | python | en | code | 24 | github-code | 36 |
32058791507 | from datetime import datetime
from binance_functions.client_functions.binance_client import CreateClient
from decouple import config
from settings.bot_settings import *
from multiprocessing import Pool
import timeit
import json
class HistoricalData:
def __init__(self):
if config('API_KEY') != None and con... | turancan-p/binance-trade-bot | collecting_functions/historical_data.py | historical_data.py | py | 2,183 | python | en | code | 25 | github-code | 36 |
44649010863 | #!/usr/bin/env python
# coding: utf-8
import warnings
warnings.filterwarnings("ignore")
import numpy as np
import os
import pandas as pd
from divexplorer_generalized.FP_Divergence import FP_Divergence
DATASET_DIRECTORY = os.path.join(os.path.curdir, "datasets")
# # Import data
def abbreviateValue(value, abbrevia... | elianap/h-divexplorer | run_experiments_pruning.py | run_experiments_pruning.py | py | 11,632 | python | en | code | 2 | github-code | 36 |
34116401936 | '''
Detects a grid.
'''
import ujson
import cv2
from math import floor
from operator import itemgetter
from argparse import ArgumentParser
from pytesseract import image_to_string
parser = ArgumentParser(description = 'Detect grid.')
parser.add_argument(
"-f",
"--filename",
dest = "filename",
help = "filename prefi... | pumpncode/mimoai | read-game.py | read-game.py | py | 12,747 | python | en | code | 0 | github-code | 36 |
34647682320 | from pathlib import Path
from uuid import uuid4
from django.core.validators import FileExtensionValidator
from django.db.models import (
CASCADE,
CharField,
DateField,
FileField,
ForeignKey,
IntegerChoices,
IntegerField,
Model,
TextField,
URLField,
)
from django.utils.translatio... | cuducos/fio-de-ariadne | web/core/models.py | models.py | py | 2,873 | python | en | code | 78 | github-code | 36 |
23682193376 |
file_object = open("advent.of.code.03.txt", "r")
lines = file_object.readlines()
lines[-1] = lines[-1] + '\n'
treesmap = list(map(lambda s: s[:-1], lines))
class Position:
x = 0
y = 0
currentpos = Position()
treescount = 0
def getnextposfunc(rightmov, downmov, length):
def getnextpos(position):
... | jfornasin/Advent-of-code-2020 | 03/01.py | 01.py | py | 774 | python | en | code | 0 | github-code | 36 |
15795277469 | #!/usr/bin/env python2
from __future__ import print_function
import struct
import sys
import killerbee
class RZVictim(object):
def __init__(self, channel=26):
self.kb = killerbee.KillerBee()
self.kb.set_channel(channel)
self.kb.sniffer_on()
print("RZVictim: listening on '%s', li... | mwil/wifire | src/tools/killerbee_monitor.py | killerbee_monitor.py | py | 5,542 | python | en | code | 5 | github-code | 36 |
74332806822 | from time import sleep
import traceback
from django.forms import model_to_dict
from django.shortcuts import redirect, render
from .models import Transaction
from .form.CreateTransactionForm import CreateTransactionForm
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from F... | edwinlowxh/CZ3002---Advanced-Software-Engineering | FinApp/Transaction/views.py | views.py | py | 12,542 | python | en | code | 0 | github-code | 36 |
6318280878 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 15 12:38:24 2019
@author: MHozayen
Simple Linear Regression
Weighted Linear Regression is commented out
"""
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
def predict(x, y, pred):
#degree is u... | mohamedhozayen/Diabetes-Analytics-Engine | Joe_Deliverable/LR.py | LR.py | py | 772 | python | en | code | 0 | github-code | 36 |
6637403650 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse
# Create your views here.
def home_view(request):
if request.user.is_authenticated():
context = {
'isim': 'Emine'
}
else:
context = {
'isim': 'Gues... | emineksknc/veterinerim | home/views.py | views.py | py | 382 | python | en | code | 0 | github-code | 36 |
36402183870 | from datetime import datetime, timedelta
date_format = "%d.%m.%Y"
print("Laenukalkulaator")
amount = None
while amount is None:
try:
amount = int(input("laenusumma (täisarv): "))
if amount <= 0:
print("Sisestatud väärtus peab olema suurem kui 0")
amount = None
except ... | marianntoots/Programmeerimine_2021 | laenukalkulaator.py | laenukalkulaator.py | py | 3,000 | python | en | code | 0 | github-code | 36 |
70606642025 | import os
import sys
# 在linux会识别不了包 所以要加临时搜索目录
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)
import pandas as pd
import pymysql
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from clickhouse_sqlalchemy import make_sessio... | cgyPension/pythonstudy_space | 05_quantitative_trading_hive/util/DBUtils.py | DBUtils.py | py | 6,392 | python | en | code | 7 | github-code | 36 |
25043548577 | # coding:utf-8
import os
DEBUG = True
basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'myweb.db')
SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')
SQLALCHEMY_TRACK_MODIFICATIONS = True
SQLALCHEMY_COMMIT_TEARDOWN = True
WTF_CSRF_ENABLE... | Thecoldrain/vuejs_flask | flask_web/config/config.py | config.py | py | 598 | python | en | code | 0 | github-code | 36 |
22808427576 | #!/usr/bin/env python
#
# Looks through the run directory for "*.enzotest" and makes a csv spreadsheet of all answer test scripts and their properties.
#
# Author: David Collins (dcollins4096@gmail.com), 2011-06-14 11:19 AM. It's a bright sunny day here in Los Alamos.
#
import fnmatch
import os
#Hunt for enzotest... | enzo-project/enzo-dev | run/test_makespreadsheet.py | test_makespreadsheet.py | py | 1,609 | python | en | code | 72 | github-code | 36 |
11761396412 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the solve function below.
def solve(s):
shift = True
another = list()
char = None
for i in range(len(s)):
char = s[i]
if s[i] is " " or i == 0:
shift = True
if s[i] i... | g2des/taco4ways | hackerrank/python/capitalize_exc.py | capitalize_exc.py | py | 718 | python | en | code | 0 | github-code | 36 |
2909760362 | import streamlit as st
import leafmap.kepler as leafmap
import geopandas as gpd
def app():
st.title("Kaavoitetut rakennukset tyypeittäin")
st.markdown(
"""
Väritä, visualisoi ja filtteröi aineistoa kartan vasemmasta yläkulmasta avautuvan työkalupakin avulla.
"""
)
m = leafmap.Map(ce... | SanttuVP/SpatialPlanning_vizualization_streamlit | apps/rakennustyypit.py | rakennustyypit.py | py | 1,216 | python | fi | code | 0 | github-code | 36 |
30222648461 | import torch.nn as nn
class RPN(nn.Module):
def __init__(self, input_channels, anchor_count):
super(RPN, self).__init__()
self.ContainsObjectClassifier = nn.Conv2d(
in_channels = input_channels,
out_channels = 2*anchor_count,
kernel_size = 1,
stride = 1,
padding = 0)
self.RegionRegressor = n... | jday96314/Kuzushiji | ImageProcessing/DualNetworkApproach/RegionProposal/RPN.py | RPN.py | py | 1,450 | python | en | code | 0 | github-code | 36 |
41217273106 | # coding=utf-8
from tkinter import Button
__author__ = 'zjutK'
'''__call__使用'''
class Call(object):
def __call__(self, *args, **kwargs):
print('Called:', args, kwargs)
class ColorBack(object):
def __init__(self, color):
self.color = color
def __call__(self, *args, **kwargs):
pr... | kzrs55/learnpython | oop/call.py | call.py | py | 623 | python | en | code | 0 | github-code | 36 |
17364039643 | # Imports from Third Party Modules
from bs4 import BeautifulSoup
from urllib2 import urlopen
BASE_URL = "http://www.portlandhikersfieldguide.org"
REGIONS = ['Gorge', 'Mount Hood', 'Central OR', 'OR Coast', 'East OR',
'South OR', 'Portland', 'SW WA', 'WA Coast']
REGION_INDEXS = [
'http://www.portlandhike... | RAINSoftwareTech/hiketheplanet | backend/datascrape.py | datascrape.py | py | 5,124 | python | en | code | 1 | github-code | 36 |
20736597554 | import random
import datetime
st = datetime.datetime.now()
tai_moji = 10 # 対象文字数
ke_moji = 2 # 欠損文字数
chance = 2 # 試行回数
def shutudai(alh):
moji = random.sample(alh, tai_moji)
print("対象文字", end = " ")
for i in moji:
print(i, end = " ")
print()
nai_moji = random.sample(moji, ke_moji)
p... | c0b2108596/ProjExD | ex01/alphabet.py | alphabet.py | py | 1,363 | python | ja | code | 0 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.