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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
15849092722 | import json
from typing import List, Any
import os
import sys
from copy import deepcopy
def get_data_folder() -> str:
root_folder = os.path.dirname(sys.modules['__main__'].__file__)
data_folder = f'{root_folder}/data'
os.makedirs(data_folder, exist_ok=True)
return data_folder
def load_json_list(file... | hungntit/python-jwt-example-api | utils/load_json_file.py | load_json_file.py | py | 2,697 | python | en | code | 0 | github-code | 1 |
7116978905 | def tandem(redShirtSpeeds, blueShirtSpeeds, fastest):
redShirtSpeeds.sort()
blueShirtSpeeds.sort()
if not fastest:
reverseTeamSpeed(redShirtSpeeds)
total_speed = 0
for idx in range(len(redShirtSpeeds)):
redShirtSpeed = redShirtSpeeds[idx]
blueShirtSpeed = blueShirtSpeeds[l... | Theeyecode/python_alg | Easy/tandem_bicycle.py | tandem_bicycle.py | py | 787 | python | en | code | 0 | github-code | 1 |
70643890275 | import sys
import os
import json
from candidate_dictionary import candidates
from handle_file_dict import handle_dict
from twitter_client import get_twitter_client
root = 'timelines/'
def get_retweets(tweet):
retweets = tweet.get('retweet_count', [])
#print("The number of retweets is: {}".format(retweets))
return... | azaidi06/twitter_analysis | tweet_stats.py | tweet_stats.py | py | 1,071 | python | en | code | 0 | github-code | 1 |
9491554968 | import os
import logging
import datetime as dt
class SingletonType(type):
_instances = {}
def __call__(cls, *args, **kwargs):
# Only create a new instance if one does not exist
if cls not in cls._instances:
cls._instances[cls] = super(SingletonType, cls).__call__(*args, **kwargs)
... | rahulmsys/automation | lib/logger.py | logger.py | py | 2,328 | python | en | code | 0 | github-code | 1 |
14797687487 | import torch
import torch.nn as nn
from torch.nn import init
from torch.optim import lr_scheduler
from typing import Dict, Any
from copy import deepcopy
from i2iTranslation.constant import NORM_CFG
###############################################################################
# Helper Functions
#####################... | AI4SCR/VirtualMultiplexer | i2iTranslation/models/networks.py | networks.py | py | 21,560 | python | en | code | 0 | github-code | 1 |
21482840418 | import torch.nn as nn
import torch.nn.functional as F
import torch
class nn_resampler(nn.Module):
def __init__(self, n_input, n_output):
super(nn_resampler, self).__init__()
# encoder
self.enc1 = nn.Linear(n_input,75)
self.enc2 = nn.Linear(75,50)
self.enc3 = nn... | ajrheng/smc-nn-resampler | nn_resampler.py | nn_resampler.py | py | 1,316 | python | en | code | 0 | github-code | 1 |
72404397793 | from bs4 import BeautifulSoup
import requests
import json
from unicodedata import normalize
import os
from datetime import datetime
import re
remove_diacritics = lambda string : normalize("NFKD", string).encode('ASCII','ignore').decode('ASCII')
def update_clearing_file_names():
clearing_files = {}
html_pag... | holondo/B3_collector | utils/clearing_files_scraper.py | clearing_files_scraper.py | py | 2,223 | python | en | code | 0 | github-code | 1 |
43419247130 | import time
import sys
import yaml
import numpy as np
import torch as t
import torch.nn.functional as F
sys.path.insert(0, './gnet')
from g_init import set_optimizer_g
opts = yaml.safe_load(open('./tracking/options.yaml','r'))
def g_pretrain(model, model_g, criterion_g, pos_data):
# Evaluate mask
n = pos_da... | abnerwang/py-Vital | gnet/g_pretrain.py | g_pretrain.py | py | 2,470 | python | en | code | 35 | github-code | 1 |
9416815920 | """
Heizungsregelung Exporter
Started: 5.4.2023
see: https://trstringer.com/quick-and-easy-prometheus-exporter/
Possible parameters:
Environment variables:
- POLLING_INTERVAL_SECONDS -> default value: 5
- APP_PORT -> default value: 42424
- EXPORTER_PORT ... | mneuroth/heizungsregelung-public | heizung_exporter.py | heizung_exporter.py | py | 7,589 | python | en | code | 0 | github-code | 1 |
26205162416 | class Solution:
def isValid(self, s):
pairs = self.init_pairs()
stack = list()
for ch in s:
if len(stack) == 0:
stack.append(ch)
else:
if pairs.get(stack[-1], '') == ch:
stack.pop()
else:
... | anushkumarv/leetcode | stack/valid_parenthesis.py | valid_parenthesis.py | py | 685 | python | en | code | 1 | github-code | 1 |
40894969872 | import time
import gpiozero
import gpiozero.pins.rpigpio
import click
from loguru import logger
from rich.console import Console
from rich.table import Table
# zone = bcm pin
zones = dict()
zones[1] = 17 # 11 gpio0
zones[2] = 18 # 12 gpio1
zones[3] = 27 # 13 gpio2
zones[4] = 22 # 15 gpio3
zones[5] = 23 # ... | why-pengo/sprinkler | scripts/zone_tool.py | zone_tool.py | py | 3,351 | python | en | code | 0 | github-code | 1 |
26553103154 | from flask_app.config.mysqlconnection import connectToMySQL
from flask import flash
from flask_app.controllers.users import User
class Show:
def __init__(self, data):
self.id = data['id']
self.title = data['title']
self.network = data['network']
self.release_date = data['release_dat... | OhJackie21/Python-Practice | practice/tvshow/flask_app/models/show.py | show.py | py | 3,261 | python | en | code | 0 | github-code | 1 |
44638395566 | #
# Script intended to ease malicious JS deobfuscation.
#
# Deobfuscates Locky Javascript transformations to a human readable JS
# (most likely it will work with other malware obfuscation transformations as well)
#
# Try this out with:
# $ python translate.py -f locky.js -s deobfuscate.py Deobfuscate
#
# https://... | kalkehcoisa/deobscuripy | resources/deobfuscate.py | deobfuscate.py | py | 2,156 | python | en | code | 0 | github-code | 1 |
264300740 | from turtle import Turtle, Screen, forward
import random
is_race_on = False
"""Screen set up - width, height"""
screen = Screen()
screen.setup(width = 500, height = 400)
user_bet = screen.textinput(title = "Make your bet", prompt="Który żółw Ninja jest najszybszy? Podaj imię: ")
print(user_bet)
Leonardo = Turtle()
Le... | hollymartiniosos/100dayspython | 19. Instances, state and higher order/wojownicze_żółwie_Ninja.py | wojownicze_żółwie_Ninja.py | py | 1,393 | python | en | code | 0 | github-code | 1 |
25037508638 | from fastapi import FastAPI, APIRouter, Depends, HTTPException
from ..db import users_crud, auth_crud, matches_crud, profile_crud,anime_crud
from ..schemas.matches_schema import Matches
from pydantic import BaseModel
import random
#from .. import files
router = APIRouter(
prefix="/user",
tags=["user"],
re... | konn1ehuang/Backend | app/routers/users.py | users.py | py | 4,851 | python | en | code | null | github-code | 1 |
37245446965 | """
Read file into texts and calls.
It's ok if you don't understand how to read files
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 2: Which telephone number spent the ... | apsommer/unscramble_problems | Task2.py | Task2.py | py | 1,462 | python | en | code | 0 | github-code | 1 |
18992750458 | # -*- coding: utf-8 -*-
"""
Created by: Rishabh Gupta
Description: To update corn, soybean, and potato cultivars in *.CUL file
"""
from typing import Optional, Union
def update_corn_cultivar(param: Union[str,dict],
cul_srcdir: str, cul_dstdir: str) -> None:
'param can be dictionary of parameters ... | AgroClimaticTools/dssat-pylib | dssatpylib/util_cultivar.py | util_cultivar.py | py | 7,334 | python | en | code | 0 | github-code | 1 |
70077763554 | class Node(object):
def __init__(self,data=None,next_node=None):
self.data=data
self.next=next_node
class Linked_list:
def __init__(self):
self.head=None
def inserNth(self,data,position):
if position==0:
if self.head is None:
self.head=Node(data... | dhimanmonika/DataStructures | Linked_list/MergeTwoSortedLinkedLists.py | MergeTwoSortedLinkedLists.py | py | 1,686 | python | en | code | 0 | github-code | 1 |
33479963348 | from PIL import Image
from lib.prediction_processing import denormalize_bbox
from lib.logging_config import logger
def get_crop(image, bbox, extension_factor=None, angle=0, resize_w=None, patchwork=False):
"Takes a pil image"
w = image.size[0]
h = image.size[1]
if bbox is not None:
# for tag/... | Deepomatic/workflows-sa-lib | deepomatic/workflows/sa/image_processing.py | image_processing.py | py | 1,991 | python | en | code | 0 | github-code | 1 |
31669461633 | import time
import base64
import hmac
def generator(user_key, expire=2 * 60 * 60):
token_header = 'dsf132cqwdsfsdafrewdcsveqrasc3reqsdvsdcdrdsvdx'
ts_str = str(time.time() + expire)
ts_byte = ts_str.encode("utf-8")
hmac_token_header = hmac.new(token_header.encode('utf-8'), ts_byte, 'sha1').he... | yaolixin-creater/UI | code-v1/autoTestPlatform/apps/user/auth_token.py | auth_token.py | py | 2,366 | python | en | code | 0 | github-code | 1 |
38137246425 | ##########################################################
######## USER SETTING BOX OF FUN ######
##########################################################
host = 1 # local:1, client:0, server:1 ##
net = 0 # local:0, client:1, server:1 ##
username = 'Gawd' # you'd better pick a cool name ##
ip = 'home.ch... | Gomer3261/fps-project | gamedata/newProg/engine/__init__.py | __init__.py | py | 4,632 | python | en | code | 0 | github-code | 1 |
72040607393 | """
This entire file is deprecated and will be deleted when MVC is working
"""
# import something for getting error codes
import validators
import re
import logging
logger = logging.getLogger(__name__) # now we use logger.debug, etc.
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(style="{", fmt="{asc... | fromCharCode/YouTube-Downloader | url_validator.py | url_validator.py | py | 1,000 | python | en | code | 0 | github-code | 1 |
33508627985 | # Napisz program wypisujący na konsolę zawartość wskazanego pliku
# wraz z numerami linii. Obsłuż sytuację, gdy użytkownik nie poda
# nazwy pliku lub poda błędną nazwę.
# Przykład użycia:
# $ python test.txt
# 1: pierwsza linia pliku
# 2: druga linia pliku
# with open("plik.txt") as plik:
# tresc = plik.read()
# f... | kadamekALX/python_20220326 | files_ka/zad_1.py | zad_1.py | py | 638 | python | pl | code | 0 | github-code | 1 |
22826503664 |
for i in range(1042000,702648205):
order = len(str(i))
sum = 0
temp = i
while temp > 0:
digit = temp % 10
sum += digit ** order
# print(sum)
temp //= 10
if i == sum:
print(i,"is the First Armstrong Number")
break
| samyank7/letsupgrade | letsupgradeASSIGN_3.py | letsupgradeASSIGN_3.py | py | 305 | python | en | code | 0 | github-code | 1 |
43858548346 | import requests
# your code here
response=requests.get("https://assets.breatheco.de/apis/fake/sample/project_list.php")
proyects = response.json()
proyect1 = proyects[1]
print(proyect1["name"])
proyects_names=[]
for proyect in proyects:
proyects_names.append(proyect["name"])
print(proyects_names)
| SilMontes/python-http-requests-api-tutorial-exercises | exercises/06-project-list/app.py | app.py | py | 303 | python | es | code | 0 | github-code | 1 |
43182715341 | import zipfile,rarfile
from zipfile import ZipFile
def unzip(zip_file_path,pwd,target_path):
zip_file = support_gbk(zipfile.ZipFile(zip_file_path))
zip_list = zip_file.namelist()
for f in zip_list:
if pwd != None:
zip_file.extract(f,target_path,pwd.encode("utf-8"))
else:
... | MapleNe/SaltZip-For-Android | sfa/library/Core/Zip/zip.py | zip.py | py | 861 | python | en | code | 0 | github-code | 1 |
29587463507 | import os
import json
import torch
import pandas as pd
from wilds.datasets.wilds_dataset import WILDSDataset
from wilds.common.utils import map_to_id_array
from wilds.common.metrics.all_metrics import F1, multiclass_logits_to_pred
from wilds.common.grouper import CombinatorialGrouper
REGIONS = {'Beijing': 0, 'Liaoning... | coastalcph/fairlex | dataloaders/cail_dataset.py | cail_dataset.py | py | 6,203 | python | en | code | 10 | github-code | 1 |
12047436942 | from dataclasses import dataclass, field
import transformers
import datasets
import tqdm.auto as tqdm
import os
import math
@dataclass
class TokenizeArguments:
dataset_path: str = field()
save_fol: str = field()
rank: int = field()
world_size: int = field()
tokenizer_path: str = field(default="met... | zphang/minimal-llama | minimal_llama/hyper/tokenize_flan.py | tokenize_flan.py | py | 1,667 | python | en | code | 447 | github-code | 1 |
5376519317 | from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime
default_args = {
'owner': 'airflow',
'start_date': datetime(2015, 6, 1)
}
dag = DAG(
'hello',
default_args = default_args
)
hello = BashOperator(
task_id='hello',
bash_command='echo ... | komparo/rosetta-pipeline | tasks/one-job/airflow/workflow.py | workflow.py | py | 366 | python | en | code | 6 | github-code | 1 |
40151074581 | from typing import List, Any, Optional
from fastapi import APIRouter, Depends, Response
from sqlalchemy.orm import Session
import crud
import schemas
from api import deps
from services import DBTableService
router = APIRouter()
@router.get('/', response_model=List[schemas.DBTableInDB])
def read_db_tables(
resp... | mifercre/auto-dq | backend/api/endpoints/db_tables.py | db_tables.py | py | 1,574 | python | en | code | 0 | github-code | 1 |
1218322774 | from model.bo.Niveau import Niveau
from model.dao.db.db_interaction import DBInteraction
class Niveau_dao:
def ajouter(niveau):
req = """INSERT INTO niveaux (nom)
values (?)"""
db = DBInteraction()
db.maj(req, niveau.nom)
req = """SELECT *
FROM niveaux
... | Amiri-saifelislam/newproj | model/dao/niveau_dao.py | niveau_dao.py | py | 1,066 | python | en | code | 0 | github-code | 1 |
13487722126 | """
解题思路
一种是新分配内存来做,一种是原地转换。
因为在python中字符串是不变的常量,所以需转换成数组来做(模拟C++字符串原地)
原地转换的思路是:
因为空格转%20,每一次转换需多占用2个长度的内存。
所以在保证原字符串后有可分配的连续内存时,可以通过扩展字符串长度后再替换空格达到原地转换的效果,目的是节约内存
在原地转换基础上,当我们转换一次空格时,%替换空格位置,20需一次替换空格后两个字符,所以需将后面的字符依次后移,但这样的时间复杂度在最坏情况下需要O(n*n)
所以我们可以先确定替换后的字符串总长度,从后往前替换,这样能保证每次替换不影响未替换的字符。用双指针一个指向原字符串末尾,另外一个指向扩充后的字符... | TravelSir/leetcode_solutions | 剑指offer/05.py | 05.py | py | 1,802 | python | zh | code | 2 | github-code | 1 |
41480965027 | # Nested Loops
## When you have more advanced problems involving repetition within repetition you may need to use loops within loops or nested loops.
# Motivating example
## For example, a supermarket regional manager may need to check on stocks for each of the supermarket he/she supervises. For that, he/she will look... | Folzi99/ItP_Trinket_Exercises-main | ItP_Trinket_Exercises-main/Self Learning Materials/Iterations/Iterations_Nested-loops.py | Iterations_Nested-loops.py | py | 1,688 | python | en | code | 0 | github-code | 1 |
11721013436 | from setuptools import find_packages, setup
def get_lines(relative_path):
with open(relative_path) as f:
return f.readlines()
INSTALL_REQUIRES = get_lines("requirements.txt")
setup(
name="ecci",
version="2.0.2",
author="Data Science - DSI APHP",
author_email="thomas.petitjean-ext@aphp.f... | aphp-datascience/study-collaborative-workflow-nlp | ecci/setup.py | setup.py | py | 494 | python | en | code | 0 | github-code | 1 |
71112216994 | import os
import re
import argparse
import configparser
from AIPUBuilder.Optimizer.logger import opt_workflow_register, OPT_ERROR, OPT_INFO, OPT_WARN
from AIPUBuilder.Optimizer.framework import ALL_OPT_OP_DICT, ALL_OPT_QUANT_OP_DICT
from . cfg_fields import ALL_FIELDS, DEFAULT_FIELDS
class CfgParser(object):
def ... | Arm-China/Compass_Optimizer | AIPUBuilder/Optimizer/config/parser.py | parser.py | py | 11,634 | python | en | code | 18 | github-code | 1 |
44047520749 | import preprocess_images
from constants import *
#tf and tf keras
import tensorflow as tf
import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import json
#imports needed to build model
from keras.models import Sequential,Input,Model... | KhazanahAmericasInc/waste-classifier | cnn_trainer.py | cnn_trainer.py | py | 10,205 | python | en | code | 4 | github-code | 1 |
27523318809 | import random
import operator
def ksa(key):
key_length = len(key)
# membuat array "S"
S = list(range(256))
random.seed(key_length % 256)
random.shuffle(S)
return S
def prga(S, text: bytes):
# S array dari KSA
# n panjang plaintext
i = 0
j = 0
C = []
arr = []
f... | graciellavl/stream-cipher | myowncipher.py | myowncipher.py | py | 1,011 | python | en | code | 1 | github-code | 1 |
3561355814 | #!/usr/bin/python3.6
# -*- coding: utf-8 -*-
# @Time : 2020/08/17 13:32
# @Author : panrhenry
# @Email : panrhenry@163.com
import numpy
from pandas import Series, DataFrame
import pandas as pd
# Series 类似于一维数组的对象,由一组数据及一组与之相关的标签组成
# --------------------------------------------------------------------------------... | panrhenry/py_pro_1 | dataAnalise/part_2/pandas_series.py | pandas_series.py | py | 1,150 | python | en | code | 0 | github-code | 1 |
17610873425 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 11 14:19:15 2018
@author: Arunodhaya
"""
import torch
import pandas as pd
from torch.utils.data import dataset
def crt_emb(df):
df['thal']=df['thal'].replace({3:0,6:1,7:2})
df['slope']=df['slope'].replace({1:0,2:1,3:2})
df['exercise_induced_angin... | rajagurunath/CategoricalEmbedding | pred_inference.py | pred_inference.py | py | 1,644 | python | en | code | 1 | github-code | 1 |
43698934586 | #Nana Abekah
#Merge Files - File Reading
file1 = [];
file2 = [];
file3 = [];
with open('file1.txt', 'r') as file:
for line in file:
file1.append(line);
with open('file2.txt', 'r') as file:
for line in file:
file2.append(line);
for element in file1:
file1 = element.split(' ');
for... | Nanared1/Python-Codes | Python programs/fileIOex5.py | fileIOex5.py | py | 588 | python | en | code | 0 | github-code | 1 |
2190214220 |
from sklearn.model_selection import StratifiedKFold
import numpy as np
from dsp.utils import Timer
class CrossValidator:
debug = False
def __init__(self, Examples, Labels, model, model_train_eval,
n_folds=10, batch_size=100, epochs=100):
"""CrossValidator(Exa... | vyshakbellur/Recurrent-Neural-Network-Architectures | classifier/crossvalidator.py | crossvalidator.py | py | 3,546 | python | en | code | 0 | github-code | 1 |
23021450479 | import sys
prefix = sys.argv[1]
fi = open(prefix + "/" + "test_results.tsv", "r")
fo = open(prefix + "/" + "preds.txt", "w")
fo.write("pairID,gold_label\n")
counter = 0
labels = ["contradiction", "entailment", "neutral"]
for line in fi:
parts = [float(x) for x in line.strip().split("\t")]
max_ind = 0
max_val = ... | tommccoy1/hans | berts_of_a_feather/files_for_replication/process_test_results.py | process_test_results.py | py | 501 | python | en | code | 122 | github-code | 1 |
26100104371 | from flask import Flask, render_template, request, jsonify
from config.default import SECRET_KEY, UPLOAD_DIR, HOST, PORT
from utils import validate
from utils.custom_log import log_msg
from werkzeug.utils import secure_filename
from utils.data_constructor import build_data_to_insert
from utils.db_helper import select_r... | praveencali2017/file_uploader_fr | uploader_back_end/controller.py | controller.py | py | 1,997 | python | en | code | 0 | github-code | 1 |
36379153893 | #Assume you have a method isSubstring which checks if one word is a substring of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring (i.e., “waterbottle” is a rotation of “erbottlewat”).
def isSubstring(big,small):
if big.find(small)>=0:
re... | ebegeti/LeetCode-problems | question1_8.py | question1_8.py | py | 777 | python | en | code | 0 | github-code | 1 |
19471234306 | """
@file
@brief Timeseries metrics.
"""
import numpy
def ts_mape(expected_y, predicted_y, sample_weight=None):
"""
Computes :math:`\\frac{\\sum_i | \\hat{Y_t} - Y_t |}
{\\sum_i | Y_t - Y_{t-1} |}`.
It compares the prediction to what a dummy
predictor would do by using the previous day
as a pr... | sdpython/mlinsights | mlinsights/timeseries/metrics.py | metrics.py | py | 1,476 | python | en | code | 65 | github-code | 1 |
45798614001 | #!/usr/bin/env python3
import argparse
import json
import os.path
from collections import OrderedDict
import numpy as np
import pandas as pd
import xarray as xr
from dateutil.parser import parse
from pkg_resources import resource_filename
from aodntools import __version__
from aodntools.timeseries_products import ag... | aodn/python-aodntools | aodntools/timeseries_products/hourly_timeseries.py | hourly_timeseries.py | py | 25,463 | python | en | code | 8 | github-code | 1 |
40761688444 | # n=[3,4,5,6]
# # m=n.index(5)
# # print(m)
# n1=int(input("enter the number:"))
# i=0
# while i<len(n):
# if n1==n[i]:
# print(i)
# break
# i=i+1
# n=["s_shailu","lu_kky"]
# i=0
# s=[]
# while i<len(n):
# j=0
# string=""
# while j<len(n[i]):
# if n[i][j]=="_":
# ... | shailajaBegari/interview | indexing of numbers.py | indexing of numbers.py | py | 1,437 | python | en | code | 0 | github-code | 1 |
29032478752 | # ***************
# File: hw4_3_SinghM.py
# Program Description: Program that displays a histogram of the sum value of a given amount of dice rolls
# Input: Number of times the dice is rolled, given by user through keyboard
# Output: Asterisks of the values acheived from the sum of the 2 rolls in a histogram format
# M... | MSingh29xl/CSC15 | Assignments/Assignment 4/hw4_3_SinghM.py | hw4_3_SinghM.py | py | 983 | python | en | code | 0 | github-code | 1 |
27509355015 | import datetime
import braintree
from django.db.models.query import QuerySet
from django.http import HttpRequest
from django.test import RequestFactory, TestCase, Client
from django.urls import reverse
import json
from unittest.mock import Mock, patch
from wagtail.models import Site
from accounts.factories import User... | WesternFriend/WF-website | subscription/tests.py | tests.py | py | 24,841 | python | en | code | 46 | github-code | 1 |
28549650826 | """
Created by plough on 2019/1/21.
"""
import re
import sys
from app.utils.callback.WXBizMsgCrypt import WXBizMsgCrypt
from app.utils.wx_manager import WxManager
from config import WxConf, WxBotConf
class WxBotHelper:
wx_crypt = WXBizMsgCrypt(WxConf.APP_TOKEN, WxConf.APP_ENCODING_AES_KEY, WxConf.CORP_ID)
c... | plough/wxbot | app/utils/wxbot_helper.py | wxbot_helper.py | py | 5,431 | python | en | code | 1 | github-code | 1 |
35153041227 | for t in range(int(input())):
n = int(input())-1
a = [int(i) for i in input().split()]
min = a[n]
max = a[n]
p = 0
for i in reversed(a):
if i < max:
p += max-i
min = i
else:
max = i
print(f'#{t} {p}')
| ihaeeun/Algorithms | Python/SWExpertAcademy/level2/1859.py | 1859.py | py | 281 | python | en | code | 0 | github-code | 1 |
24929327776 | def permutation(nums):
res=[]
visited=set()
def backtrack(subset=[]):
if len(subset) == len(nums):
res.append(subset)
else:
for i, num in enumerate(nums):
if i not in visited:
visited.add(i)
backtrack(subset+[nu... | cha1690/Data-Structures-and-Algoritms | backtracking/permutations.py | permutations.py | py | 397 | python | en | code | 2 | github-code | 1 |
25129635764 | import pandas as pd
import numpy as np
import datetime
import time
import os
class FindNearestPoint(object):
'''
选取离站点最近的格点
'''
def __init__(self, sPLat, sPLon, mRLat, mRLon):
'''
获取模式基本属性参数,包括分辨率和起始格点经纬度
:param sPLat:模式起始纬度
:param sPLon:模式起始经度
:param mRLat:模式纬... | xianyu94wo/Correct | ClassTest.py | ClassTest.py | py | 4,357 | python | en | code | 1 | github-code | 1 |
41974870547 | import random
inputPath = input("Enter the path of file u want to open")
f1 = open(inputPath, 'r')
print(f1.read())
outputPath = input("Enter the path of file u want to create ")
f2 = open(outputPath, 'w')
text = input("Enter text you want to add")
f2.write(text)
f1.close()
f2.close()
fromPath = input("Enter the path ... | actively-lazy/programming-language-3- | Lab/lab5.py | lab5.py | py | 1,803 | python | en | code | 0 | github-code | 1 |
13043454998 | """A list of changes to an emulated device for verification purposes."""
import sys
import threading
from collections import namedtuple
import csv
from time import monotonic
StateChange = namedtuple("StateChange", ['time', 'tile', 'property', 'value', 'string_value'])
class EmulationStateLog(object):
"""A threa... | iotile/coretools | iotileemulate/iotile/emulate/virtual/state_log.py | state_log.py | py | 3,752 | python | en | code | 14 | github-code | 1 |
17227588596 | from menu import *
import pandas as pd
def init():
perso = ['Age',
'Gender',
'Education',
'Country',
'Ethnicity']
personality = [
'Neuroticism',
'Extraversion',
'Openness to experience',
'Agreeableness',
... | MatthiasPicard/Drug-consumption-analysis | Streamlit/init.py | init.py | py | 6,444 | python | en | code | 0 | github-code | 1 |
3656334256 | def load():
global client_info
with open("client_info.json", "r", encoding="utf-8") as json_file:
client_info = json.load(json_file)
def save(info: dict):
with open("client_info.json", "w", encoding=" utf-8") as json_file:
json.dump(info, json_file)
def show_info():
load()
... | dmitriylityagin/tictoe | FinanceApp/client.py | client.py | py | 1,704 | python | en | code | 0 | github-code | 1 |
38573736688 | import json
from django.http import HttpResponse
from django.views.generic import View
from .models import ClientRecord
class CreateView(View):
def post(self, request):
message = request.body.decode('utf-8')
user_agent = request.META['HTTP_USER_AGENT']
username = str(request.user)
... | wfmexpert/verme-logs | applogs/views.py | views.py | py | 586 | python | en | code | 1 | github-code | 1 |
16722909802 | """
The main script that controls the deployment towards Azure.
It is executed inside the container 'live-deploy'
"""
import os
import time
import json
def getEnvDataAsDict(path: str) -> dict:
with open(path, 'r') as f:
return dict(tuple(line.replace('\n', '').split('=')) for line
in f.readl... | martinkarlssonio/azure-dataplatform | main.py | main.py | py | 6,847 | python | en | code | 2 | github-code | 1 |
13487584936 | """
解题思路:仅仅执行一次交换,那么只要找出a字符串与b字符串不同的字符进行比较即可
因为交换可以同一字符交换(即不交换),这里可以先判断字符串是否相等,相等则直接返回True
当不同的字符大于两个时,则直接返回False。
"""
class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if s1 == s2:
return True
dif = []
for i in range(len(s1)):
if s1[i] != s2[i]:
... | TravelSir/leetcode_solutions | 1701-1800/1790. Check if One String Swap Can Make Strings Equal.py | 1790. Check if One String Swap Can Make Strings Equal.py | py | 730 | python | zh | code | 2 | github-code | 1 |
70536214433 | unsortedList = [4,3,2,4,4,4,1,2]
tabElementAmount = len(unsortedList)
bucketList = {}
maximal = max(unsortedList) + 1
for item in unsortedList:
if item not in bucketList:
bucketList[item] = [ item ]
else:
bucketList[item].append(item)
finalArr = []
for i in range(0, maximal):
if i in bucketL... | zbigniewzolnierowicz/school-notes | Klasa 4/informatyka/20200218/main.py | main.py | py | 385 | python | en | code | 0 | github-code | 1 |
22401760559 | # -*- coding: utf-8 -*-
import sys
import subprocess
def help():
print("Help information")
def wrapper(content, additional_packages=None, resize_box = None):
lines = [r"\documentclass[crop,tikz]{standalone}",r"\usepackage{tikz,pgfplots}",r"\usepackage{amsmath, amsfonts}",r"\usepgfplotslibrary{fillbetween}",r"... | udicr/tikz_command | tikz.py | tikz.py | py | 1,933 | python | en | code | 0 | github-code | 1 |
19323588275 | import psycopg2
import sqlalchemy
import sqlalchemy_utils
import pytest
from intergov.conf import env_postgres_config
from intergov.repos.api_outbox.postgres_objects import Base, Message
from tests.unit.domain.wire_protocols import test_generic_message as test_messages
def pg_is_responsive(ip, docker_setup):
try:... | bizcubed/intergov | tests/integration/repos/api_outbox/postgres/conftest.py | conftest.py | py | 2,226 | python | en | code | 0 | github-code | 1 |
23601928367 | import psycopg2
from psycopg2.extras import Range
import json
from db_config import db_config
def main():
# Connect to PostgreSQL
conn = psycopg2.connect(**db_config)
# Create a cursor object
cur = conn.cursor()
# Load state from genesis
with open('genesis.json') as f:
data = json.loa... | gitopia/gitopia-subgraph-scripts | main.py | main.py | py | 3,236 | python | en | code | 0 | github-code | 1 |
15279331981 | def maxHarvest(arr, k):
n = len(arr)
maxProfit = float('-inf')
# Evaluate all n/2 harvesting options (6 slices->3 options, 4 slices->2 options, and so on)
for i in range(n//2):
sm = 0
for j in range(k):
currIndex = i+j
# adding n//2 gets us the opposite slice's i... | onyxolu/DSA | Goldman/EfficientHarvest.py | EfficientHarvest.py | py | 1,736 | python | en | code | 0 | github-code | 1 |
7455908050 | import sys
try:
metaID = sys.argv[1]
except Exception:
metaID = None
import json
import uuid
taskParamMap = {}
taskParamMap["taskName"] = str(uuid.uuid4())
taskParamMap["userName"] = "pandasrv1"
taskParamMap["vo"] = "atlas"
taskParamMap["taskPriority"] = 100
taskParamMap["architecture"] = "i686-slc5-gcc43-opt... | PanDAWMS/panda-jedi | pandajedi/jeditest/addTestTaskParamToDEFT.py | addTestTaskParamToDEFT.py | py | 2,257 | python | en | code | 3 | github-code | 1 |
8691495169 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head:
return None
dummy = ListNode(next=head)
prev, curr... | songkuixi/LeetCode | Python/Remove Duplicates from Sorted List II.py | Remove Duplicates from Sorted List II.py | py | 655 | python | en | code | 1 | github-code | 1 |
38785958758 | import cv2
import numpy as np
import os
import tensorflow as tf
import file_io
import save_func as sf
import utility_func as uf
import mnist_data_input
import mnist_data_ph
class NetFlow(object):
def __init__(self, model_params, load_train, load_test):
load_dapt = model_params['adapt']
self.load... | hanzhaoml/MDAN | mnist/net_flow.py | net_flow.py | py | 8,128 | python | en | code | 102 | github-code | 1 |
30024284612 | import Helper as helper
class Users:
def insert(self, val, conn_obj):
mycursor = conn_obj.cursor()
sql = "INSERT INTO users (user_name, email,activation_key,repository) VALUES (%s, %s, %s, %s)"
mycursor.execute(sql, val)
conn_obj.commit()
return mycursor.lastrowid
def ... | jainmohit1/Automated-Project-Analyser | docroot/api/Users.py | Users.py | py | 645 | python | en | code | 0 | github-code | 1 |
14194317798 | import numba
import numpy as np
import pytest
try:
import cupy # type: ignore
except ImportError:
cupy = None
import tdgl
from tdgl.geometry import box, circle
from tdgl.solver.options import SolverOptionsError
@pytest.mark.parametrize("current", [5.0, lambda t: 10])
@pytest.mark.parametrize("field", [0, 1... | loganbvh/py-tdgl | tdgl/test/test_solve.py | test_solve.py | py | 5,348 | python | en | code | 24 | github-code | 1 |
20520651806 | import os.path
import warnings
from django_docker_helpers.config import ConfigLoader
from . import __version__
# --------------- PATHS ---------------
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_NAME = os.path.basename(BASE_DIR)
PROJECT_PATH = os.path.abspath(os.path.dirname(__fil... | atten/dictionary-trainer-bot | dictrainer/settings.py | settings.py | py | 7,040 | python | en | code | 0 | github-code | 1 |
23770881786 | import openai
import time
import requests
import re
import json
import logging
# Set up your API keys here or load them from environment variables
# Define a class for managing the dialog context
class DialogContext:
def __init__(self, maxlen=5):
self.maxlen = maxlen
self.history = []
def add... | nky001/LLM | chatbot_utils.py | chatbot_utils.py | py | 3,266 | python | en | code | 2 | github-code | 1 |
37759871886 | # coding: utf-8
import tkinter as tk
from tkinter import messagebox
from tkinter import filedialog
import time
from fukumenzan_dialog import FukumenzanDialog
from fukumenzan_solver import FukumenzanSolver
class Fukumenzan():
def __init__(self, root):
self.root = root
self.probrem_ = []
self.probrem_number = 0... | umeya/puzzle_alogorithm_python | ch02/fukumenzan.py | fukumenzan.py | py | 6,383 | python | en | code | 0 | github-code | 1 |
31153559984 | #!/usr/bin/python3.5
# D402
# Setup variables
db = {}
# Set database items
dbitems = int(input())
for i in range(dbitems):
item = input()
item = item.split(' ')
db[item[0]] = float(item[1])
# Get database and scan stuff
iceagebaby = int(input())
moni = 0
for i in range(iceagebaby):
item2 = input()
... | kcomain-wasteland/hkoi_submissions | Python/Finished/D402.py | D402.py | py | 372 | python | en | code | 1 | github-code | 1 |
72536618273 | #ben isenberg 10/1/2016
#recursive method
# find all subsets of a set
def powerSets(my_set):
#base case
if (len(my_set) == 0):
return
print(my_set)
for x in my_set:
powerSets(my_set.difference(set([x])))
return
def main():
powerSets(set([1,2,3,4]))
main() | bji6/Practice_Problems | Cracking_Coding_Interview/Recursion/powerSets.py | powerSets.py | py | 272 | python | en | code | 0 | github-code | 1 |
9977912268 | import time
import cv2
import os,random
import subprocess
import numpy as np
from keras.models import model_from_json
from keras.preprocessing import image
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
#load model
model = model_from_json(open("fer.json", "r").read())
#load weights
model.load_weights('fer.h5')
size = 4
# We... | adarshsingh2001/Music-Recommender-through-emotion-detection | music_player_webcam.py | music_player_webcam.py | py | 6,490 | python | en | code | 3 | github-code | 1 |
70071534753 | from core import services
from django.http import HttpResponse
from openpyxl.writer.excel import save_virtual_workbook
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
class DetailedListViewSetMixin(viewsets.ModelViewSet):
serializer_act... | berkaymizrak/Immfly-Media-Platform-Project | core/mixins.py | mixins.py | py | 3,096 | python | en | code | 0 | github-code | 1 |
25431418879 | from collections import Counter
import sys
input = sys.stdin.readline
def is_row_high(arr: list[list]) -> bool:
return len(arr) >= len(arr[0])
def correct(arr: list[list], r: int, c: int, k: int) -> bool:
if len(arr) >= r and len(arr[0]) >= c:
return arr[r-1][c-1] == k
return False
de... | reddevilmidzy/baekjoonsolve | 백준/Gold/17140. 이차원 배열과 연산/이차원 배열과 연산.py | 이차원 배열과 연산.py | py | 2,210 | python | en | code | 3 | github-code | 1 |
39948100628 | """
Module for defining the database models for representing items.
"""
from typing import Optional, List, Any
from pydantic import BaseModel, Field, ConfigDict, field_validator, AwareDatetime
from inventory_management_system_api.models.catalogue_item import Property
from inventory_management_system_api.models.custom... | ral-facilities/inventory-management-system-api | inventory_management_system_api/models/item.py | item.py | py | 1,868 | python | en | code | 0 | github-code | 1 |
19415984300 | def change(amount, coins):
ways = [0] * (amount + 1)
ways[0] = 1
for each in coins:
for i in range(1, len(ways)):
if each <= i:
ways[i] += ways[i - each]
else:
continue
return ways[amount]
print(change(5, [1, 2, 5])) | shashilsravan/Programming | Programs/Number of ways to make change.py | Number of ways to make change.py | py | 299 | python | en | code | 0 | github-code | 1 |
15842308542 | def askint():
while True:
try:
val = int(input("Please enter an integer : "))
except:
print("Looks like you didn't enter an integer")
continue
else:
print("Correct, that is an integer!")
finally:
print("Finally blo... | desamsetti/Python | ExceptionHandling.py | ExceptionHandling.py | py | 366 | python | en | code | 1 | github-code | 1 |
17880564669 | import logging
import sys
import json
import IOUtil
import numpy as np
import re
from nltk.tokenize import word_tokenize
DATAPATH = "/Users/zxj/Google 云端硬盘/models_and_sample/"
BRACKETS = re.compile("[\[\]]")
def read_file(file_path, preprocess):
content_list = []
try:
with open(file_path, encoding="u... | contemn1/sentence_evaluation | word_dict_test.py | word_dict_test.py | py | 3,623 | python | en | code | 1 | github-code | 1 |
31216842139 | import json
from flask import request
from pymongo.errors import DuplicateKeyError
from werkzeug.urls import url_encode
from biocontainers.biomongo.helpers import InsertContainers
from biocontainers.common.models import MongoTool, _CONSTANT_TOOL_CLASSES, MongoToolVersion, MongoWorkflow, SimilarTool
from biocontainer... | BioContainers/biocontainers-backend | biocontainers_flask/server/controllers/ga4_gh_controller.py | ga4_gh_controller.py | py | 25,340 | python | en | code | 3 | github-code | 1 |
31225027984 | with open("weather2018.csv", "r", encoding="utf-8") as w:
aTotal = []
maxCold = 15.1;
maxColdDay = "31.08.2018";
maxHat = 15.1;
maxHatDay = "31.08.2018";
aDay = [];
day = 31;
aDays = [];
rainDays = 1;
totalDay = 0;
for string in w:
if(string[0] == "#"):
continue
else:
string1 = string.split(';'... | MitraXak/weather2018 | weather.py | weather.py | py | 998 | python | en | code | 0 | github-code | 1 |
25460129335 | import logging
import os
import shutil
import tempfile
import unittest
from telemetry.core import util
from telemetry.core import exceptions
from telemetry import decorators
from telemetry.internal.browser import browser as browser_module
from telemetry.internal.browser import browser_finder
from telemetry.internal.pl... | hanpfei/chromium-net | third_party/catapult/telemetry/telemetry/internal/browser/browser_unittest.py | browser_unittest.py | py | 10,334 | python | en | code | 289 | github-code | 1 |
27286953893 | import pytest
from cleanlab.datalab.internal.data import Data
from cleanlab.datalab.internal.data_issues import DataIssues
class TestDataIssues:
labels = ["B", "A", "B"]
label_name = "labels"
@pytest.fixture
def data_issues(self):
data = Data(data={self.label_name: self.labels}, label_name=se... | cleanlab/cleanlab | tests/datalab/test_data_issues.py | test_data_issues.py | py | 1,965 | python | en | code | 7,004 | github-code | 1 |
24156552472 | import sys
import os
import time
from multiprocessing import Pool, cpu_count
import numpy as np
import matplotlib.pyplot as plt
from torch import nn
sys.path.insert(0, 'graph_enc_dec')
from graph_enc_dec import data_sets
from graph_enc_dec import graph_clustering as gc
from graph_enc_dec import architecture
from graph... | vmtenorio/GIGOArchitecture | graph_enc_dec_basic_test.py | graph_enc_dec_basic_test.py | py | 5,144 | python | en | code | 0 | github-code | 1 |
9788791815 | import argparse
import matplotlib.pyplot as plt
from model_sir import Simulation
from model_animation import Animation, LineAnimation
from model_plot import plot_simulation
from model_animation import get_ylim
def main(*args):
"""Command line entry point.
$ python runsim_model.py ... | norman-cheen/Covid19-Epidemic-Modelling | modified_model/model_runsim.py | model_runsim.py | py | 4,091 | python | en | code | 0 | github-code | 1 |
32099910050 | n = int(input())
welfare = input().split(' ')
welfare = list(map(int, welfare ))
max_value = max(welfare)
min_burles = 0
for i in range(n):
temp = max_value - welfare[i]
min_burles += temp
print(min_burles)
| lilianacandrea/Codeforces_Problems_Solutions | 758A.Holiday_of_Equality.py | 758A.Holiday_of_Equality.py | py | 214 | python | en | code | 1 | github-code | 1 |
40757405958 | import time
def getYesterday():
day = int(time.strftime("%d"))
month = time.strftime("%b")
year = int(time.strftime("%Y"))
if day!=1:
return day-1, month, year
#El dia uno no va hacia atrás
else:
list_month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
... | ManuRS/SSH-Alert | getDates.py | getDates.py | py | 963 | python | en | code | 1 | github-code | 1 |
15999910432 | import os
import sys
import requests
from bs4 import BeautifulSoup
import colorama
tabs = []
tags = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'a', 'ul', 'li', 'head', 'title', "div"]
# write your code here
while True:
text = input()
dots = [pos for pos, char in enumerate(text) if char == '.']
if len(dots) ... | Arpita2005/Programming | Python/Python/Browser/Browser.py | Browser.py | py | 1,579 | python | en | code | 3 | github-code | 1 |
5905755203 | import contextlib
import enum
import functools
import hashlib
import math
import re
from datetime import datetime
from functools import cache, lru_cache, wraps
from typing import Tuple
import redis
from django.conf import settings
from django.contrib.auth.decorators import user_passes_test
from django.db.models import... | teammatehunt/tph-site | server/puzzles/utils.py | utils.py | py | 9,749 | python | en | code | 4 | github-code | 1 |
22493893152 | import streamlit as st
import sklearn
import joblib
model = joblib.load('Coursera Review Sentiment')
st.title('Coursera Sentiment')
ip = st.text_input('Enter your review')
op = model.predict([ip])
if st.button('Predict'):
temp = op[0]
if temp==5:
st.title("Loved It! (Rating: 5)")
elif temp==4:
st.title("I... | AmreshSinha/Sentiment-Analysis-Major-Project-ML | app.py | app.py | py | 539 | python | en | code | 0 | github-code | 1 |
43749345101 | import csv
import sys
import json
import os
cwd = os.getcwd()
def minsToDegrees (minsString, isLongitude):
parts = minsString.split("-")
parts[0] = float(parts[0])
parts[1] = float(parts[1])
parts[2] = float(parts[2][:parts[2].find(" ")])
degrees = parts[0] + (parts[1] / 60) + (parts[2] / 3600... | tristan-morrison/airspace-fixes | toCSV.py | toCSV.py | py | 1,801 | python | en | code | 0 | github-code | 1 |
16557810975 | # 16 다이나믹 프로그래밍 - 못생긴 수
# Solved Date: 22.06.23.
import sys
read = sys.stdin.readline
def solve(n):
dp = [0 for _ in range(n)]
dp[0] = 1
index_2, index_3, index_5 = 0, 0, 0
next_2, next_3, next_5 = 2, 3, 5
for index in range(1, n):
dp[index] = min(next_2, next_3, next_5)
if next_2... | imn00133/algorithm | ItIsCodingTest/chap16/35.ugly_number.py | 35.ugly_number.py | py | 708 | python | en | code | 0 | github-code | 1 |
31653910747 | import codecs
import os
import re
import json
from collections import defaultdict
from nlplingo.annotation.ace import AceAnnotation
from nlplingo.annotation.serif import to_lingo_doc
from nlplingo.text.text_theory import Document
from nlplingo.annotation.idt import process_idt_file
from nlplingo.annotation.enote impor... | BBN-E/nlplingo | nlplingo/annotation/ingestion.py | ingestion.py | py | 13,495 | python | en | code | 4 | github-code | 1 |
6085412327 | __author__ = 'Xing'
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if n==1:return '1'
pre=self.countAndSay(n-1)
result,index,count,length='',0,0,len(pre)
while index<length:
count+=1
if index+... | jinxin0924/LeetCode | Count and Say.py | Count and Say.py | py | 605 | python | en | code | 1 | github-code | 1 |
42066464961 | """
Изменить реализацию функции рекурсивного поиска элемента в словаре (из предыдущего задания)
следующим образом:
- функция должна находить ПЕРВОЕ соответствие имени и возвращать результат в виде словаря:
{'val': found_value, 'parent': found_value_parent, 'deep': found_value_deep}
"""
def recursive_search(sourc... | Dakiin/TMS_origin | lesson_5/homework_task_4.py | homework_task_4.py | py | 2,490 | python | ru | code | 0 | github-code | 1 |
27848174064 | # LEnet 网络
################################
# linear input
# linear 16
# linear 64
# linear 100
###################################
import torch.nn as nn
# 定义网络结构
class Net(nn.Module):
def __init__(self, input, output):
super(Net, self).__init__()
self.l1 = nn.Sequential(
nn.Linear(... | BobbyBBY/machine-learning-course | Net.py | Net.py | py | 675 | python | en | code | 0 | github-code | 1 |
19945551153 | """
Michael Miller and Kurt Tuohy
CS 598 Deep Learning for Healthcare - University of Illinois
Final project - Paper Results Verification
4/4/2022
Reproduce the k-Nearest Neighbors models in the paper below.
Do both classification and regression.
Paper: "Natural language processing for cognitive therapy: Extracting... | mich1eal/cs598_dl4hc | src/knn.py | knn.py | py | 12,293 | python | en | code | 0 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.