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
28345998993
from typing import List import gymnasium as gym import numpy as np from urdfenvs.robots.generic_urdf import GenericUrdfReacher from urdfenvs.scene_examples.goal import dynamicGoal from urdfenvs.scene_examples.obstacles import dynamicSphereObst2 from urdfenvs.urdf_common.urdf_env import UrdfEnv def run_panda_capsules(n...
maxspahn/gym_envs_urdf
examples/panda_capsules.py
panda_capsules.py
py
2,589
python
en
code
33
github-code
1
2073191328
import paho.mqtt.client as mqtt import phone_auth_token as auth from time import sleep import paho.mqtt.client as mqtt from tinder_bot_sms import TinderBotSms import subprocess import random phone_number = '' def on_connect(client, userdata,flags,rc): print("connected with result code "+ str(rc)) cl...
Freyja21/LB-242
subscriber.py
subscriber.py
py
1,812
python
en
code
0
github-code
1
41519811232
def binary_search(array, left, right, target): #while Loop 내에서 찾으면 존재 while left <= right: middle_idx = (left + right) // 2 middle = array[middle_idx] if target == middle: return True elif target < middle: right = middle_idx - 1 else: l...
Raemerrr/AlgorithmProblems
Algorithm/BinarySearch.py
BinarySearch.py
py
639
python
en
code
0
github-code
1
43044444049
from fenics_concrete.experimental_setups.experiment import Experiment from fenics_concrete.helpers import Parameters import dolfin as df class MinimalCubeExperiment(Experiment): def __init__(self, parameters=None): # initialize a set of "basic paramters" (for now...) p = Parameters() # boun...
BAMresearch/FenicsConcrete
fenics_concrete/experimental_setups/minimal_cube.py
minimal_cube.py
py
1,542
python
en
code
0
github-code
1
1993760833
"""Test for TaskContextConnection""" from unittest.mock import Mock import pytest from pynocular.aiopg_transaction import LockedConnection, TaskContextConnection @pytest.fixture() def locked_connection(): """Return a locked connection""" return LockedConnection(Mock()) @pytest.mark.asyncio() async def tes...
NarrativeScience-old/pynocular
tests/unit/test_task_context_connection.py
test_task_context_connection.py
py
1,463
python
en
code
13
github-code
1
21841299155
import sys input = sys.stdin.readline N, K, B = map(int, input().split()) arr = [1] * (N + 1) for _ in range(B): n = int(input()) arr[n] = 0 cnt = sum(arr[1:1 + K]) ans = min(float('inf'), K - cnt) for i in range(1, N - K + 1): cnt = cnt - arr[i] + arr[K + i] ans = min(ans, K - cnt) print(...
pearl313/BOJ
백준/Silver/14465. 소가 길을 건너간 이유 5/소가 길을 건너간 이유 5.py
소가 길을 건너간 이유 5.py
py
324
python
en
code
0
github-code
1
28377662905
import numpy as np from matplotlib.axes import Axes from matplotlib.collections import PathCollection from matplotlib.lines import Line2D from matplotlib.projections import register_projection class PickableAxes(Axes): """ A subclass of matplotlib.axes._axes.Axes which support selection and action on data se...
clark3493/pygui
pygui/widget/plot/_pickable_plot.py
_pickable_plot.py
py
21,770
python
en
code
0
github-code
1
24997941524
import numpy as np from scipy.stats import norm from stock import Stock # source: https://github.com/jeromeku/Python-Financial-Tools/blob/master/capm.py class CAPM(object): def __init__(self, risk_free, market, alpha=.05): self.risk_free = Stock(risk_free["ticker"], risk_free["date_range"]) if type(risk_...
LongntLe/Tradingsystem
src/statistics/CAPM.py
CAPM.py
py
576
python
en
code
2
github-code
1
10389756553
import time from random import randint import matplotlib.pyplot as plt import algorythms import threading threading.stack_size(2 ** 27) q = 1 n = 10000 r = 1000000 T_fb = [] M_fb = [] T_d = [] M_d = [] def task(m_min, m_step, m_max): # creating data for m in range(m_min, m_max, m_step): arr_edges ...
Mihinator3000/Group-Projects
Ilia/main.py
main.py
py
1,459
python
en
code
0
github-code
1
70737271074
## 10816. 숫자 카드 2 (01.04) from collections import Counter n = int(input()) card = list(map(int, input().split())) card_count = Counter(card).most_common() card_count.sort() m = int(input()) find = list(map(int, input().split())) answer = [] for f in find: flag = 0 for c in card_count: if f == c[0]: ...
ChanWhanPark/Algorithm
BaekJoon/Searching/10816_number_card_2.py
10816_number_card_2.py
py
463
python
en
code
0
github-code
1
40676657630
import sys sys.stdin = open("수의 새로운 연산_input.txt") t = int(input()) for case in range(1): a, b = map(int, input().split()) print(a, b) n = 0 if a >= b: n = int(a**(1/2))+1 else: n = int(b**(1/2))+1 print(n) arr = [[0 for _ in range(n+1)]for _ in range(n+1)] for i in ra...
manuck/Algorithm
연습/D3-수의 새로운 연산.py
D3-수의 새로운 연산.py
py
491
python
en
code
0
github-code
1
3501285342
#!/usr/local/bin/python import sys current_id = None answers_length = [] question_length = 0 #input: id\t\isquestion\tlength def get_average(l): if len(l) == 0: return 0 else: return sum(l) / len(l) for line in sys.stdin: data_mapped = line.strip().split("\t") if (len(data_mapped) ...
scepas/forum-mr
ReducerPostLength.py
ReducerPostLength.py
py
926
python
en
code
0
github-code
1
36949810486
__module_name__ = "pyXAOP" __module_version__ = "beta 1.0 revision 5" __module_description__ = "Xchat Auto-op Script by psi, type /xaop help" import xchat import re import pickle import os import hexchat from pickle import * CHANNEL_PREFIXES = ['#','&','!'] CHANNEL_ALL_MASK = "ALL" NETWORK_ALL_MASK = "ALL" OPERA...
Dummy101/Hexchat
HexChat_Scripts/pyxaop.py
pyxaop.py
py
7,625
python
en
code
1
github-code
1
30579043142
from datetime import datetime, timedelta from requests.exceptions import HTTPError from utils.signing import sign from blockchain.models import Policy from utils import headers from utils.urls import BANK_URL, BC_URL, SELLER_URL from utils.ids import BANK_ID, SELLER_ID import utils.auth from utils.auth import create_a...
momvart/dns_project
client/__main__.py
__main__.py
py
3,494
python
en
code
0
github-code
1
34195148442
import tweepy import feedparser import re import requests import os import datetime # pip3 install tweepy feedparser feed_url = "https://lambdan.se/blog/rss.xml" database_file = "./tweeted_by_twitter_bot.txt" # txt with urls that have been tweeted (one url per line) twitter_consumer_api_key = "" twitter_api_secret_ke...
lambdan/lambblog
twitter_bot/twitter_bot.py
twitter_bot.py
py
2,532
python
en
code
1
github-code
1
20358272470
import torch import pickle import random import os import numpy as np import matplotlib.pyplot as plt from torchvision import transforms from captum.attr import Saliency from PIL import Image from convnet import * from ResNets import * from utils.dynamiccentrecrop import DynamicCenterCrop # Load model to test model = ...
ripervail/weapon-detection-CNN
saliency_plot.py
saliency_plot.py
py
2,142
python
en
code
0
github-code
1
71098568994
# 给定一个整数数组,判断是否存在重复元素。 # 如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。 def Solution1(nums): # 超出时间限制 if len(nums)==1: return False for i in range(len(nums)): for j in range(len(nums)-i-1): if nums[i]==nums[-j-1]: return True return False a1=[1,2,3,1] a2=[1,2,3,4] a3=[3,1] print(Solution(a3))
Da-Yuan/LeetCode-Python
LeetCode-217.py
LeetCode-217.py
py
445
python
zh
code
0
github-code
1
43788847753
from django.urls import path, include from rest_framework_simplejwt.views import ( TokenObtainPairView ) from .views import SignUpUser urlpatterns = [ path('signup/', SignUpUser.as_view(), name='signup_user'), path('jwt/', include([ path('', TokenObtainPairView.as_view(), name='token_obtain_pair')...
Farnaz-1999/CloudProject
identity_service/users/urls.py
urls.py
py
333
python
en
code
0
github-code
1
4454139738
from django.conf import settings from django.test import SimpleTestCase, override_settings import responses from ...records.api import get_records_client from ...records.models import Record from ..exceptions import ClientAPIError, DoesNotExist, MultipleObjectsReturned from .factories import create_record, create_sea...
nationalarchives/ds-wagtail
etna/ciim/tests/test_models.py
test_models.py
py
3,087
python
en
code
8
github-code
1
39628727692
# EvalArgParser.py # Implements EvalArgParser, which handles evaluation-specific command line arguments. import argparse from .CommonArgParser import CommonArgParser class EvalArgParser(CommonArgParser): def __init__(self, description="Evaluation script argument parser class", fromfile_prefix_chars='@', conflict_han...
DylanAuty/MDE-biological-vision-systems
ArgParseWrappers/EvalArgParser.py
EvalArgParser.py
py
1,170
python
en
code
6
github-code
1
6310460415
import tool.excel import db import pymysql from tool.update import category as book_cate data = tool.excel.import_data() def deal(): conn = db.database_conn() cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # book列表 books = book_cate() books_name = [] for u in books: ...
wantaname/flask_huayiyiyu
huayiyiyu/tool/analysis.py
analysis.py
py
1,551
python
en
code
0
github-code
1
5124372066
# Compute approximate grade level needed to read text from cs50 import get_string # Get text input from user text = get_string("Text: ") # Initialize variables, assume one word if text is not empty letters = words = sentences = 0 if len(text) > 0: words = 1 # Iterate through text for c in text: if c.lower(...
joonnoh/CS50x
cs50/pset6/readability/readability.py
readability.py
py
741
python
en
code
0
github-code
1
11478214116
## Remembre to adjust this import numpy as np ID_file= "ind_assignments.txt" pops= [] sample_id_to_population = {} with open(ID_file,'r') as sample_id_lines: for line in sample_id_lines: line= str.encode(line) sample_id, population = line.split()[:2] sample_id_to_population[sample_id] = po...
SantosJGND/fine-scale-mutation-spectrum-master
sim_compare/mutation_counter/count/labels.py
labels.py
py
674
python
en
code
0
github-code
1
73511514913
import json import math import tvregdiff as tvrd import dataFuncs import numpy as np class Point: def __init__(self, x, y, label = ''): if(isinstance(x, int) or isinstance(x, float)): self.x = x else: self.x = float(x) if(isinstance(y,int) or isinstance(y, float)): ...
danmartelly/sketch
studentInterface/graphUtil.py
graphUtil.py
py
8,105
python
en
code
0
github-code
1
9439503388
from django.test import TestCase, Client from .models import Museum from .forms import CreateGroupForm import secrets from django.contrib.auth.models import User from user.models import UserProfile class CreateDeleteGroupTestCase(TestCase): def setUp(self): _basic_setup(self) def test_create_one_user...
nicholastaylor0000/CPS410-F20-Team04
museum/tests.py
tests.py
py
2,529
python
en
code
0
github-code
1
11822031002
import pandas as pd import numpy as np import re from joblib import dump from sklearn.base import BaseEstimator, TransformerMixin from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.preprocessing import OneHotEncoder, StandardScaler from sklearn.model_selection import GridSe...
willzh0/titanic
train.py
train.py
py
8,975
python
en
code
0
github-code
1
25431166019
import sys input = sys.stdin.readline def dfs(word:str, cur: dict, depth: int) -> None: print("--"*depth,word,sep='') for nxt in sorted(cur[word]): dfs(nxt, cur[word], depth+1) trie = dict() n = int(input()) for _ in range(n): words = list(map(str,input().rstrip().split()))[1:] c...
reddevilmidzy/baekjoonsolve
백준/Gold/14725. 개미굴/개미굴.py
개미굴.py
py
489
python
en
code
3
github-code
1
38762343427
""" 给定一种 pattern(模式) 和一个字符串 str ,判断 str 是否遵循相同的模式。 这里的遵循指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应模式。 """ class Solution(object): def wordPattern(self, pattern, str): """ :type pattern: str :type str: str :rtype: bool """ words = str.split(" ") if ...
love525150/leetcode-answer
a290.py
a290.py
py
905
python
zh
code
0
github-code
1
20974871673
#-----MENSAJES---- PREGUNTA_EDAD = "Ingrese su edad porfavor \n" PREGUNTA_INGRESOS = "Ingrese el valor de sus ingresos mensuales \n" MENSAJE_TRIBUTAR = "Tienes la obligacion de tributar" MENSAJE_NO_TRIBUTAR = "Aun no es necesario que pagues impuestos" #-----ENTRADAS---- _edadUsuario = 0 _ingresosUsuario = 0 #-----CODIG...
elenaposadac27/Programaci-n1
EjerciciosDePractica/ejercicio1.5.py
ejercicio1.5.py
py
603
python
es
code
0
github-code
1
4508130902
# 5 kyu Simple fraction to mixed number converter # https://www.codewars.com/kata/556b85b433fb5e899200003f/train/python from gmpy2 import bit_scan1 as ctz def mixed_fraction(s): # special cases if s.endswith('/0'): raise ZeroDivisionError if s.startswith('0'): return '0' sign = '-'*(s...
mateuszmacheta/codewars-python
simple-fraction-mixed-number-converter.py
simple-fraction-mixed-number-converter.py
py
1,334
python
en
code
2
github-code
1
73034204833
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Jayesh Kariya <jayeshk@saltstack.com>` ''' # Import Python libs from __future__ import absolute_import # Import Salt Testing Libs from salttesting import skipIf, TestCase from salttesting.mock import ( NO_MOCK, NO_MOCK_REASON, MagicMock, patch) from...
shineforever/ops
salt/tests/unit/states/ntp_test.py
ntp_test.py
py
1,869
python
en
code
9
github-code
1
74923992992
import discord import emailer as emailer from discord.ext import commands client = commands.Bot(command_prefix = ",") @client.event async def on_ready(): print("le bot est pret") @client.command() async def email(ctx,*,name): data = name.split(sep = " ") print(data) num = emailer.getcommandline() ...
adamsirri1231/emailer
bot.py
bot.py
py
745
python
en
code
0
github-code
1
12413857901
#!/usr/bin/env python # coding: utf-8 ####################################################### # Code used for creating these smaller CSV files. ####################################################### ####################################################### ## Import required libraries. ###############################...
rs2pydev/datasets
okcupid_profiles_dataset/Splitter_Combiner.py
Splitter_Combiner.py
py
2,068
python
en
code
0
github-code
1
20192676246
import os from tkinter.tix import INTEGER from conf import SAMPLE_INPUTS, SAMPLE_OUTPUTS from moviepy.editor import * from PIL import Image source_path = os.path.join(SAMPLE_INPUTS, 'sample.mp4') thumbnail_dir = os.path.join(SAMPLE_OUTPUTS, 'thumbnails') thumbnail_per_frame_dir = os.path.join(SAMPLE_OUTPUTS, 'thumbn...
eavf/30-days
Day15/1_thumbs.py
1_thumbs.py
py
2,246
python
en
code
0
github-code
1
30050528076
# S6.1: Design the View Data page of the multipage app. # Import necessary modules import streamlit as st import pandas as pd import numpy as np # Define a function 'app()' which accepts 'car_df' as an input. def app(car_df): st.markdown("<body><h1 style='color:black;font-size:40px'> <center> <b> VIEW DATA</b>...
SomyaJhamb/web_app
data.py
data.py
py
1,418
python
en
code
0
github-code
1
20113329318
import asyncio import json from typing import Any, AsyncGenerator, Coroutine, Generator, Optional import requests from fastapi import HTTPException from pydantic import BaseModel, Field from llmstudio.engine.providers.provider import ChatRequest, Provider, provider class OllamaParameters(BaseModel): temperature...
TensorOpsAI/LLMstudio
llmstudio/engine/providers/ollama.py
ollama.py
py
1,970
python
en
code
60
github-code
1
17002177456
import subprocess def into_routingtable(addr, prefix, next_hop): addrprefix = addr + '/' + prefix args = ['ip', 'route', 'add', addrprefix, 'via', next_hop] print("\033[33m", "ip route add ", addrprefix, "via", next_hop, "\033[0m", 'proto', 'bgp') try: res = subprocess.check_output(args) ex...
izumin-baal/bgp_explorer
bgp-2process/routing.py
routing.py
py
1,171
python
en
code
3
github-code
1
20501404858
from dataclasses import dataclass from networkx import DiGraph, contracted_edge, weakly_connected_components, subgraph, draw_networkx, nx_agraph, relabel_nodes, tree import matplotlib.pyplot as plt from random import randint from networkx.drawing.nx_pydot import graphviz_layout from matplotlib.backend_bases import Mous...
webmiche/edge-choice
main.py
main.py
py
4,579
python
en
code
0
github-code
1
43475059159
from DiffusionFreeGuidence.TrainCondition import train, eval def main(model_config=None): modelConfig = { "state": "eval", # or eval or train "epoch": 1000, "batch_size": 12, "T": 1000, "channel": 32, "channel_mult": [1, 2, 2, 4], "num_res_blocks": 1, ...
luoxinggyyy/MCDDPM
MainCondition_new.py
MainCondition_new.py
py
1,035
python
en
code
1
github-code
1
32163240806
import pandas as pd from utils import * import regex import traceback from sentence_transformers import SentenceTransformer, util import argparse import os os.environ["TOKENIZERS_PARALLELISM"] = "false" def topic_pairs(topic_sent, all_pairs, threshold=0.5, num_pair=2): """ Return the most similar topic pairs...
chtmp223/topicGPT
script/refinement.py
refinement.py
py
12,346
python
en
code
104
github-code
1
74945137313
Import('env') extfn_env = env.Clone() if extfn_env.get('WITH_PYTHON'): extfn_env.Append(CPPDEFINES=['-DWITH_PYTHON']) srcs = Split(""" extpy.c """) extfn_env.AppendUnique( LIBPATH=['#',env.get('PYTHON_LIBPATH')] ,LIBS=['ascend',env.get('PYTHON_LIB')] ,CPPPATH=[env.get('PYTHON_CPPPATH')] ) lib = extfn_env.Shar...
georgyberdyshev/ascend
models/johnpye/extpy/SConscript
SConscript
555
python
en
code
5
github-code
1
12449616071
with open('day_7.in') as f: datastream = f.read() n_packet = 0 n_message = 0 for i in range(len(datastream)): if len(set(datastream[i:i+4])) == 4 and n_packet == 0: n_packet = i+4 if len(set(datastream[i:i+14])) == 14: n_message = i+14 ...
timkalan/advent-of-code
2022/06/day_6.py
day_6.py
py
440
python
en
code
0
github-code
1
73045493795
import csv import sys def get_csv_diff(file1, file2): # read the contents of the two files into two lists of rows with open(file1, 'r') as f1, open(file2, 'r') as f2: reader1 = csv.reader(f1) reader2 = csv.reader(f2) rows1 = [row for row in reader1] rows2 = [row for row in reade...
professorharsh402/harshj402
csv-diff.py
csv-diff.py
py
1,058
python
en
code
0
github-code
1
35329696123
import cv2 import time import os import numpy as np import pandas as pd import matplotlib.pyplot as plt from skimage.morphology import medial_axis, skeletonize cv2.destroyAllWindows() def plot_color_image(image,title,colorscheme,file_ext,colorbar,path): # sizes=np.shape(image) my_dpi=96 pix=700 ...
mjm7919/ground-truth-velocity
ground_truth3.py
ground_truth3.py
py
5,186
python
en
code
0
github-code
1
25759539784
import pathlib # import classification import os # PACKAGE_ROOT = pathlib.Path(classification.__file__).resolve().parent PACKAGE_ROOT = pathlib.Path(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) DATASET_DIR = PACKAGE_ROOT / 'dataset' TRAINED_MODEL_DIR = PACKAGE_ROOT/'trained_model' TESTING_DATA_...
mikosa01/smoking-status
package/classification/classification/config/config.py
config.py
py
1,795
python
en
code
0
github-code
1
70722569634
def d(n): ret = n str_n = str(n) for i in str_n: ret += int(i) return ret not_self = [] for i in range(1, 10000): n = i while n < 10000: n = d(n) # print(n) if n in not_self: break else: not_self.append(n) for i in range(1, 1000...
inticoy/study-algorithm
boj/python/4673.py
4673.py
py
367
python
en
code
0
github-code
1
4058443527
# Given an array of integers arr, replace each element with its rank. # # The rank represents how large the element is. The rank has the following rules: # # # Rank is an integer starting from 1. # The larger the element, the larger the rank. If two elements are equal, their rank must be the same. # Rank should ...
HEroKuma/leetcode
1256-rank-transform-of-an-array/rank-transform-of-an-array.py
rank-transform-of-an-array.py
py
1,184
python
en
code
0
github-code
1
39661526958
import numpy as np from numpy.linalg import eig, inv from fitEllipse import * arc = .5 R = np.arange(0,arc*np.pi, 0.01) x = 1.5*np.cos(R) + 10 + 0.1*np.random.rand(len(R)) y = np.sin(R) + 5 + 0.1*np.random.rand(len(R)) a = fitEllipse(x,y) center = ellipse_center(a) #phi = ellipse_angle_of_rotation(a) phi = ellipse_a...
mvoellmy/stove-state
sandbox/PanTrack/src/tests/fitEllipseTest.py
fitEllipseTest.py
py
720
python
en
code
0
github-code
1
2665416173
# Includes MicroPython SSD1306 OLED driver, I2C and SPI interfaces from machine import Pin, I2C from micropython import const import framebuf import utime class State: def __init__(self): pass def update(self): pass class Application: __instance = None @staticmethod def ...
AceKiron/artifact-2023
src/picosquared.py
picosquared.py
py
5,854
python
en
code
1
github-code
1
1306431034
import tensorflow as tf """ Data input pipeline """ # Shape of embedding layers layers_shape = {'pool1': [None, 48, 32, 64], 'pool2': [None, 24, 16, 128], 'pool3': [None, 12, 8, 256], 'pool4': [None, 6, 4, 512], 'fc1_1': [None, 4096], 'fc...
polimi-ispl/speech_reconstruction_embeddings
data_provider.py
data_provider.py
py
5,949
python
en
code
1
github-code
1
14386534431
class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: """ 문제 접근 1) 교집합이라는 건 포함되는 요소를 찾는 것 2) 만약에 배열이 정렬이 되어있다면 이진탐색을 할 수도 있을 것임 3) 교집합을 구하는 것이므로 set으로 변형을 시켜야함 (set으로 변형이 되면 자동으로 정렬이 안됨) """ set1 = sorted(list(set(num...
hyo-eun-kim/algorithm-study
ch18/yujin/ch18_3_yujin.py
ch18_3_yujin.py
py
1,100
python
ko
code
0
github-code
1
14927412816
print("Starting") import board from kmk.kmk_keyboard import KMKKeyboard from kmk.keys import KC from kmk.matrix import DiodeOrientation from kmk.modules.layers import Layers from kmk.keys import KC, make_key envkb = KMKKeyboard() envkb.col_pins = (board.GP10, board.GP9, board.GP8, board.GP7, board.GP6, board.GP5, boa...
Envious-Data/Env-KB60F
_Firmware/KMK_Keymap.py
KMK_Keymap.py
py
2,820
python
es
code
7
github-code
1
5118365393
from django.urls import re_path as url from . import views from django.conf import settings from django.conf.urls.static import static app_name = 'pictures' urlpatterns = [ url(r'^login/', views.loginPage, name='login'), url(r'^logout/', views.logoutPage, name='logout'), url(r'^$', views.index, name='ind...
HusainSuksar/photo_library
pictures/urls.py
urls.py
py
616
python
en
code
0
github-code
1
35211737106
from girl.common import * from girl.typehelpers import * from math import sqrt class Vertice(TypedList): def __new__(cls, initializer, n_columns=2): self = super().__new__(cls, initializer) self.n_columns = n_columns return self _dtype = float n_columns = 2 @property def n_rows(self): ...
ismaelharunid/girl
pyimp/girl/geometry/vertice.py
vertice.py
py
1,370
python
en
code
1
github-code
1
10053022525
import requests import json import time import re URL = 'https://5ka.ru/api/v2/special_offers/' headers = {'User-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'} CAT_URL = 'https://5ka.ru/api/v2/categories/' def x5ka(url, params): resul...
alexzhdankin34/Geekbrains_Data_Mining
Lesson1/Task_1.py
Task_1.py
py
1,159
python
en
code
0
github-code
1
72642332195
# # @Function:This script is designed to trnasform sentences to a # 100 dimensional vector # # @Input: Input a filename which indicates the place for your # text files that you would like to deploy transformation # # @Output: The text will be transformed and stored in to some # certain pl...
XiaohanLiang/data_classification
sentence_to_vec_new.py
sentence_to_vec_new.py
py
1,855
python
en
code
0
github-code
1
36038984563
def partitionLabels(S): """ :type S: str :rtype: List[int] """ last = {c:i for i, c in enumerate(S)} start,j = 0,0 ans = [] for i, c in enumerate(S): j = max(j, last[c]) if i==j: ans.append(j-start+1) start = i+1 j = 0 return ans ...
zhaoxy92/leetcode
763_partition_labels.py
763_partition_labels.py
py
375
python
en
code
0
github-code
1
74748567073
import argparse import glob from multiprocessing.pool import ThreadPool import numpy as np import os import random import shutil import subprocess import tarfile import threading import sys sys.path.append('./') from network import network def parse_args(): argv = sys.argv[1:] if '--' in argv: remaining_args =...
aravic/6.829-pset-3
scripts/leaderboard.py
leaderboard.py
py
4,608
python
en
code
2
github-code
1
75149849952
'''Task You are given the coefficients of a polynomial P. Your task is to find the value of P at point x.''' import numpy as np A = np.array(list(map(float,input().split()))) num =int(input()) print(np.polyval(A,num))
karinabk/Python
NumPy/Polynomials.py
Polynomials.py
py
225
python
en
code
1
github-code
1
1167739842
from django.shortcuts import render, get_object_or_404, redirect from .models import Project from django.contrib.auth.decorators import login_required def home(request): projects = Project.objects return render(request, 'projects/home.html', {'projects':projects}) def detail(request, project_id): project ...
m2442/projecthunt-project
projects/views.py
views.py
py
1,279
python
en
code
0
github-code
1
36629170558
"""Доработаем задачи 3 и 4. Создайте класс Project, содержащий атрибуты – список пользователей проекта и админ проекта. Класс имеет следующие методы: Классовый метод загрузки данных из JSON файла (из второй задачи 8 семинара) Метод входа в систему – требует указать имя и id пользователя. Далее метод создает пользовател...
Pisarev82/Immersion_in_Python
sem_13/task_13_5.py
task_13_5.py
py
4,043
python
ru
code
0
github-code
1
5972547899
#Uses python3 import sys def dfs(adj, used, order, v): #write your code here explore(v, used) pass def toposort(adj): used = [0]*n order = [] #write your code here for v in range(n): if not used[v]: dfs(adj, used, order, v) #print(used) order = [x for (y,x) in sorted(zip(post,range(n)), reverse=True)] ...
vpodshiv/alg_uc
crs3_wk2/09_graph_decomposition_starter_files_2/toposort/toposort.py
toposort.py
py
1,369
python
en
code
0
github-code
1
40156597239
import matplotlib.pyplot as plt from calculator import HUCalculator mu = lambda x: 1 beta = lambda x: 50 * pow(x, 2) sigma = lambda x: 40 * pow(x, 2) f = lambda x: 40 * pow(x - 0.3, 5) N = 5 a = -1 b = 1 calc = HUCalculator(N, a, b, mu, beta, sigma, f) calc = calc.calc_until(5, 50) print("N\t| Норма оцінювача\t\t|...
helgi98/num_mod
main.py
main.py
py
589
python
en
code
0
github-code
1
30322430680
import numpy as np import os from PIL import Image # root_dir="C:/Users/sh/Desktop/data" root_dir = "C:/Users/huili/Desktop/fruitdatas" image_folders = os.listdir(root_dir) floders_num = 0 for i in image_folders: image_list = os.listdir(root_dir + '/' + i) for j in image_list: # if os.path.splitext(j)[...
huilizhou/Deeplearning_Python_DEMO
read_image.py
read_image.py
py
864
python
en
code
0
github-code
1
25913875765
def solution(n, s, a, b, fares): answer = 0 INF=100000*n graph=[[INF]*n for _ in range(n)] for i in range(n): graph[i][i]=0 for load in fares: graph[load[0]-1][load[1]-1]=load[2] graph[load[1]-1][load[0]-1]=load[2] #인접행렬 세팅 #플로이드워셜로 모든 정점 최단거리 계산 for k i...
Ojin0104/MyCode
프로그래머스/lv3/72413. 합승 택시 요금/합승 택시 요금.py
합승 택시 요금.py
py
691
python
en
code
0
github-code
1
26411905134
''' Variable definitions defining and opening the file containing information on trees. Then, defining lists for each of the different tree characteristics. Creating a matrix for all tree data in the same order as the tree data file. ''' common_Name = [] symbol = [] scientific_Name = [] family_Symbol = [] family_Comm...
DragonOfBrooklyn/Tree-Database
Tree Database/Tree_Database.py
Tree_Database.py
py
2,852
python
en
code
0
github-code
1
40930652896
# -*- coding: utf-8 -*- from django.contrib import messages from uuid import uuid4 from Contract.models import Stage, Attache from Contract.forms import FormStage ###################################################################################################################### def change_stage(request, contract...
joinc/SupportCenter
Contract/tools.py
tools.py
py
1,013
python
en
code
0
github-code
1
15279356191
# https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/ # def compute(s): # dic = {'A':[], 'B':[], 'C':[]} # result = 0 # length = len(s) # # added in reverse order to allow pop() to be O(1) # for i in range(len(s)-1,-1,-1): # if (s[i] in dic.keys()): # dic[s[i]].app...
onyxolu/DSA
Goldman/Sharees_Purchase.py
Sharees_Purchase.py
py
1,365
python
en
code
0
github-code
1
9748710718
#!/usr/bin/python3 import urllib.request, json, mysql.connector import os from datetime import datetime,date import collections class DatetimeEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime): return obj.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(obj, da...
Gain-Profit/Tools
python/PostingProduct.py
PostingProduct.py
py
1,710
python
en
code
0
github-code
1
72134356513
#problem link - https://leetcode.com/problems/rotate-array/ # 283. Move Zeroes # Easy # Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. # Note that you must do this in-place without making a copy of the array. # Example 1: # Input: nums = [0,...
AlHasanSony/problem_solving
leetcode/python/283.move_zeroes_leetcode.py
283.move_zeroes_leetcode.py
py
1,296
python
en
code
0
github-code
1
11776543102
#from tgpirobot.tgpirobot import TgPiRobot, print_help from tgpirobot import TgPiRobot, print_help, instally import sys import os from rich.console import Console from rich.progress import track, Progress import subprocess from pyrogram.errors.exceptions.unauthorized_401 import AuthKeyUnregistered try: def update()...
hk4crprasad/tgpirobot
tgpirobot/main.py
main.py
py
4,220
python
en
code
0
github-code
1
14545580592
from re import I from uuid import uuid4 def renderPlaceholder(placeholder: str, value: str,filename: str): with open(filename, 'r') as f: content = f.read() return content.replace(placeholder, value) xsrf_token = str(uuid4()) addedTokenPage = renderPlaceholder("{{token}}", xsrf_tok...
a2677331/CSE312-Web-Applications
HW2/Obejct_3-5/text.py
text.py
py
394
python
en
code
0
github-code
1
19029218792
import numpy as np import nolds def mle(x: np.ndarray) -> float: """ Maximum Lyapunov Exponent :param x: 1-d numeric vector :return: numeric scalar """ k = int(np.sqrt(len(x))) try: out = nolds.lyap_r(data=x, emb_dim=k, trajectory_...
vcerqueira/vest-python
vest/aggregations/lyapunov.py
lyapunov.py
py
477
python
en
code
19
github-code
1
19084643641
n = int (input()) s = str (input()) p = '' e = [0] w = [0] for i in range (1, n): if s[i - 1] == 'W': e.append (e[-1] + 1) else: e.append (e[-1]) s_mir = s[::-1] for j in range (1, n): if s_mir[j - 1] == 'E': w.append (w[-1] + 1) else: w.append (w[-1]) w = w[::-1] total ...
RocketMirror/AtCoder_Practice
atten.py
atten.py
py
396
python
en
code
0
github-code
1
27401833030
import pytest from cognite.client import data_modeling as dm from cognite.pygen._core.generators import SDKGenerator from cognite.pygen._generator import CodeFormatter from tests.constants import APM_SDK, EXAMPLES_DIR @pytest.fixture def sdk_generator(apm_data_model: dm.DataModel[dm.View]) -> SDKGenerator: retur...
cognitedata/pygen
tests/test_unit/test_generator/test_sdk_generator_apm_sdk.py
test_sdk_generator_apm_sdk.py
py
859
python
en
code
2
github-code
1
23033248915
"""Pull data from geth and parse it into mongo.""" import subprocess import sys sys.path.append("./../Preprocessing") sys.path.append("./../Analysis") import os os.environ['ETH_BLOCKCHAIN_ANALYSIS_DIR'] = './../Preprocessing/' from Crawler import Crawler from ContractMap import ContractMap import subprocess import tim...
alex-miller-0/Ethereum_Blockchain_Parser
Scripts/preprocess.py
preprocess.py
py
994
python
en
code
149
github-code
1
10412059340
import pandas as pd import numpy as np import glob all_data = pd.DataFrame() data = pd.ExcelFile("부산 시가수준.xlsx") names = ["해운대구", "수영구", "남구", "부산진구", "동구", "서구", "중구", "연제구", "양산시"] #names = ["해운대구"] for name in names: df = pd.read_excel(data, sheet_name=name) prev = "" my_list = [] ...
soicem/work_automation
publicPriceCharacteristicMatching.py
publicPriceCharacteristicMatching.py
py
922
python
en
code
0
github-code
1
17958819468
# 함수로 세 정수 중 중간 값 리턴하기 # return mid value of three integers through function # int형 정수 세 개를 입력 받아 중간 값을 출력하시오. # method 1 n, m, x = map(int, input().split()) def mid(a, b, c): if b <= a and a <= c or b >= a and a >= c: return a elif c <= b and b <= a or c >= b and b >= a: return b else: ...
junes7/python_algorithm
CodeUp/Function/1563.py
1563.py
py
426
python
ko
code
1
github-code
1
8702569815
import streamlit as st from snowflake.snowpark import Session def icon(emoji: str): """Shows an emoji as a Notion-style page icon.""" st.write( f'<span style="font-size: 78px; line-height: 1">{emoji}</span>', unsafe_allow_html=True, ) st.set_page_config("Snowpark & PySpark support", "🏂"...
streamlit/release-demos
1.16.0/snowpark-support/streamlit_app.py
streamlit_app.py
py
2,133
python
en
code
78
github-code
1
18419126879
from sys import stdin as kb def count(u, v): global nNode,n if u==v: return 0 c=1 for o in G[u]: if o==v: continue tmp=count(o,u) nNode[u].append(tmp) c+=tmp nNode[u].append(n-c) return c def choke(u): global nNode co = sum(nNode[u]) for i in range(l...
tirogen/Algorithm-Design
Graph/Choke Point/a58_q3_p4a_chokepoint.py
a58_q3_p4a_chokepoint.py
py
665
python
en
code
0
github-code
1
25538779474
from flask import session, flash, redirect, current_app from flask import Blueprint, session, redirect, url_for, render_template #request, , , jsonify auth_routes = Blueprint("auth_routes", __name__) @auth_routes.route("/login") def login(): print("LOGIN...") return render_template("login.html") @auth_route...
ryanrs93/uncommon_grounds_sheet_2023
web_app/routes/auth_routes.py
auth_routes.py
py
2,293
python
en
code
2
github-code
1
7294540326
""" In colors.py we will store some hexadecimal values of colors as variables. We will use these colors in our project.""" DARK_GRAY = '#65696B' LIGHT_GRAY = '#C4C5BF' BLUE = '#0CA8F6' DARK_BLUE = '#4204CC' WHITE = '#FFFFFF' BLACK = '#000000' RED = '#F22810' YELLOW = '#F7E806' PINK = '#F50BED' LIGHT_GREEN = '#05F50E' ...
noviicee/Sorting-Visualizer
colors.py
colors.py
py
339
python
en
code
0
github-code
1
43067855203
import numpy as np import matplotlib.pylab as plt from pathlib import Path import csv from functions import sigmoid, softmax, sigmoid_derivative """ Multilayered neural network class. Note: only the sigmoid and softmax activation functions have been implemented. """ class MLN: def __init__(self, layers_s...
ArchambaultP/COMP473-Project
MultiLayerNetwork.py
MultiLayerNetwork.py
py
4,380
python
en
code
0
github-code
1
30171104636
from functools import partial, wraps from databases import Database def init_db(func=None, *, db: Database = None): if func is None: if db is None: raise ValueError('init db must not be None') return partial(init_db, db=db) @wraps(func) async def wrapper(*args, **kwargs): ...
ruicore/python
02-usecase/decorator/database.py
database.py
py
628
python
en
code
10
github-code
1
40771332183
revenue = int(input('Выручка')) costs = int(input('Издержки')) if revenue > costs: print('Profit') profit = revenue - costs profitability = profit / revenue print(f'Рентабельность комании равна:{profitability}') employees = int(input('Введите количество сотрудников')) profit_employ = profit // e...
Geek101-prog/Python
Задача 5.py
Задача 5.py
py
506
python
ru
code
0
github-code
1
18776786672
import os class FileExtensionIs(object): """ Tests if a given file has one of the defined extensions. """ config_name = 'file-extension-is' def __init__(self, match_value, case_sensitive=False): """ :param match_value: A string containing one or more file extensions separated by s...
jashort/SmartFileSorter
smartfilesorter/matchplugins/fileextensionis.py
fileextensionis.py
py
934
python
en
code
2
github-code
1
35417777576
# if not auth.has_membership("admin"): # redirect(URL('initial', 'home')) @auth.requires_login() def category(): form = SQLFORM(db.category, formstyle='divs', submit_button='Enviar', _class='admform', _id='formblog') if form.process().accepted: response.flash = "Sucesso" elif form.errors: response.flash = ...
fndiaz/web2py_curso
applications/projeto/controllers/manager.py
manager.py
py
1,007
python
en
code
0
github-code
1
27344363959
from PIL import Image class Country(object): def __init__(self,name,geographical_location,flag_image,capital_city="Shinshigonshima",population_size=2000,total_area = "900,000"): self.name = name self.total_area = total_area self.capital_city = capital_city self.population_size = ...
eneadodi/Country_Mastery
utils/Geographical_Information.py
Geographical_Information.py
py
864
python
en
code
0
github-code
1
3243198675
#!/usr/bin/env python # -*- coding: utf-8 -*- # !@Time : 2021/4/30 下午4:49 # !@Author : miracleyin @email: miracleyin@live.com # !@File : main.py import spacy import urllib import urllib.request import zipfile import os from lxml import etree # 读取XML文件 from utils import * debug_mode = True def model_build(mo...
MIracleyin/spacy_ud
main.py
main.py
py
9,794
python
en
code
0
github-code
1
73034109793
# -*- coding: utf-8 -*- from __future__ import print_function # Import Salt Testing libs from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs import integration class PublishModuleTest(integration.ModuleCase, integration.SaltReturnAssertsMixIn): ...
shineforever/ops
salt/tests/integration/modules/publish.py
publish.py
py
4,149
python
en
code
9
github-code
1
15824210218
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2017 You Yufeng <649602192@qq.com> """ :module: firstapp.myAES :synopsis: 对部门上传的数据进行安全处理 :author: 649602192@qq.com (You Yufeng) """ import os, tempfile, time from cryptokit import AESCrypto class AES_ed(): # def _encrypt(self, joinRN): ...
guoquanming/Digital-virtual-asset-protection-platform_demo
progect/firstapp/myAES.py
myAES.py
py
3,101
python
en
code
0
github-code
1
43621771755
""" Question:You are given an array arr[] of N integers including 0. The task is to find the smallest positive number missing from the array. Example 1: Input: N = 5 arr[] = {1,2,3,4,5} Output: 6 Explanation: Smallest positive missing number is 6. Example 2: Input: N = ...
RatnadeepYSVS/Algorithms
Smallest Positive missing number .py
Smallest Positive missing number .py
py
1,578
python
en
code
0
github-code
1
41884370702
import logging from pymongo.errors import DuplicateKeyError from api.caching.caching_shared import getDatabase logger = logging.getLogger(__name__) def getInstanceLifetimeCollection(): return getDatabase().instance_lifetime def addInstance(instanceKey, oauthToken, oauthSecret, instanceGeographicalSetupString, ke...
michael-pryor/GeoTweetSearch
api/caching/instance_lifetime.py
instance_lifetime.py
py
2,291
python
en
code
1
github-code
1
14151866900
import re, math from typing import NamedTuple, List, Tuple from collections import defaultdict class Reaction(NamedTuple): left: List[Tuple[int, str]] right: Tuple[int, str] def create_reaction(unparsed_reaction: List[str]) -> Reaction: parse_element = lambda x: (int(x.split(' ')[0]), x.split(' ')[1]) ...
cernat-catalin/advent_of_code_2019
day14/main.py
main.py
py
2,245
python
en
code
1
github-code
1
20113391010
''' Author: ronlee Date: 2022-01-07 11:09:16 LastEditors: ronlee LastEditTime: 2022-01-19 09:33:14 Description: 自动生成导航栏和侧边栏 FilePath: \_1_learn\gitronlee.github.io\autoNavbarFiles.py ''' import os import sys import re import shutil new_line = " * [首页](README)" # 全局变量 readmetext = "# 本站目录\n\n" def write2file(fname, ...
Gitronlee/gitronlee.github.io
autoNavbarFiles.py
autoNavbarFiles.py
py
3,685
python
en
code
0
github-code
1
41059786168
from setuptools import setup, find_packages import re import os import sys import subprocess ROOT = os.path.dirname(__file__) def get_long_description(): with open(os.path.join(ROOT, 'README.md'), encoding='utf-8') as f: return f.read() def get_version(): VERSION_RE = re.compile(r'''VERSION\s+=\s+['"...
mjpost/bibsearch
setup.py
setup.py
py
3,249
python
en
code
59
github-code
1
72307937635
import requests # Get URL data from bs4 import BeautifulSoup # Manipulate URL data from pymongo import MongoClient from datetime import timedelta, date import os # ad_decline takes a row of data from the JSE Market Activity list and converts it # into a list of dictionaries formatted like: # {ticker symbol, stock nam...
Foliolensja/scrape_data_scripts
scrape_market_activities.py
scrape_market_activities.py
py
4,680
python
en
code
0
github-code
1
22473793552
class Solution(object): def maxArea(self, height): """ :type height: List[int] :rtype: int """ head, tail, max_area = 0, len(height) - 1, 0 while head < tail: min_height = height[head] if height[head] <= height[tail] else height[tail] area = (t...
Brady31027/leetcode
11_Container_With_Most_Water/container_with_most_water.py
container_with_most_water.py
py
526
python
en
code
1
github-code
1
26382411896
#!/usr/bin/env python # coding=utf-8 from wtforms import form, validators, StringField, TextField, BooleanField,\ IntegerField from tornado.web import HTTPError class BaseForm(form.Form): @classmethod def from_json_with_validate(cls, json): form = cls.from_json(json) if not form.validat...
ghostry/tvee
tvee/forms/__init__.py
__init__.py
py
1,259
python
en
code
0
github-code
1
45015791803
from qwak_proto import wire_dependencies from qwak.alerting.alerting_registry_client import AlertingRegistryClient from qwak.alerting.channel import SlackChannel, Channel wire_dependencies() def set_session(env_name: str): """ Sets the working environment for this session """ from qwak_proto.di_confi...
qwak-ai/sdk-examples
model-monitoring/add_alert_channels.py
add_alert_channels.py
py
1,233
python
en
code
0
github-code
1