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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
11699765759 | import sys
c_del = 2
c_ins = 2
def lire_mots(filename):
""" Prend en entrée le nom d'un fichier de type adn
et renvoie les 2 mots associés à ce fichier sous
forme de tableau numpy """
with open(filename, 'r') as f:
#Supression des deux premières lignes
f.readline()
f.re... | RamiELB/projet_align | A.py | A.py | py | 2,264 | python | fr | code | 0 | github-code | 36 |
35553806288 | import tweepy
import configparser
from datetime import datetime
from dateutil import tz
from threading import Thread
config = configparser.ConfigParser(interpolation=None)
config.read('twitterkeys.ini')
api_key = config["twitter"]["APIKey"]
api_key_secret = config["twitter"]["APIKeySecret"]
bearer_token = config["twi... | gatordevin/TradingBot | twitterbot.py | twitterbot.py | py | 2,403 | python | en | code | 1 | github-code | 36 |
18916909399 | import re;
import sys;
i = 1;
for line in sys.stdin:
arr = re.split("[ \t]+", line.strip());
j = 1;
for v in arr:
print("%d %d\t%s" % (i, j, v));
j += 1;
i += 1;
| lukaszog/HadoopProjects | Matrix/prepare.py | prepare.py | py | 195 | python | en | code | 0 | github-code | 36 |
3355703340 | from modules.base_classes import *
import modules.comp_map as cmp
def main():
n = int(input())
rectangles = [Rectangle(*(map(int, input().split()))) for _ in range(n)]
m = int(input())
points = [Point2D(*map(int, input().split())) for _ in range(m)]
x_values, y_values = cmp.fill_zipped_coord(rec... | B-S-B-Rabbit/algorithm_lab2 | compression_map.py | compression_map.py | py | 521 | python | en | code | 0 | github-code | 36 |
7284886713 | #!/usr/bin/env python
# coding: utf-8
# # Integración con Python
#
# Esta sección pretende ser un compendio (esperemos que claro y ordenado) de todo el `Python`
# que hemos ido usando en el Capítulo 4.
#
# Esta sección también puede servir como repaso de los conceptos más aplicados que hemos introducido en dicho c... | GCED-CM/JB-Calculo2-UDC | _build/jupyter_execute/capitulos/05/07.Integracion.py | 07.Integracion.py | py | 5,684 | python | es | code | 2 | github-code | 36 |
25299883898 | import pandas as pd
import numpy as np
from sqlalchemy import create_engine
from typing import List
engine = create_engine('sqlite:///../data/data.db', echo=False)
con = engine.connect()
df = pd.read_sql('select * from patient', con=con)
con.close()
def detect_duplicates(df:pd.DataFrame) -> pd.DataFrame:
# remove... | monkeyusage/duplicates | scripts/detect_duplicates.py | detect_duplicates.py | py | 1,699 | python | en | code | 0 | github-code | 36 |
41215973749 | import unittest
from dolt import app, db
from dolt.models import Customer, Partner, Food
class DoltTestCaseCourier(unittest.TestCase):
def setUp(self):
app.config.update(
TESTING=True,
SQLALCHEMY_DATABASE_URI="sqlite:///:memory:"
)
db.create_all()
custome... | JonasBerx/foodorderingapp | tests/test_customer.py | test_customer.py | py | 3,472 | python | en | code | 2 | github-code | 36 |
12279662576 | # third party
import torch
import torch.nn as nn
class IMDBDataset:
def __init__(self, reviews, targets):
"""
Argument:
reviews: a numpy array
targets: a vector array
"""
self.reviews = reviews
self.target = targets
def __len__(self):
# return l... | seedatnabeel/Data-IQ | src/models/nlp_models.py | nlp_models.py | py | 1,958 | python | en | code | 9 | github-code | 36 |
1259534191 | from CRABClient.UserUtilities import config, getUsernameFromSiteDB
config = config()
config.General.requestName = 'THEREQUESTNAME'
config.General.workArea = 'crab_skims'
config.JobType.pluginName = 'Analysis'
config.JobType.psetName = '/nfs/dust/cms/user/swieland/ttH_legacy/skimming/RELEASE/src/BoostedTTH/BoostedAnal... | cms-ttH/BoostedTTH | crab/common/template_cfg.py | template_cfg.py | py | 994 | python | en | code | 4 | github-code | 36 |
13988428678 | class Solution:
def countLetters(self, S: str) -> int:
ans = 0
prev = None
start = 0
for end, c in chain(enumerate(S), [(len(S), None)]):
if c != prev:
size = end - start
ans += size * (size + 1) // 2
prev = c
... | dariomx/topcoder-srm | leetcode/trd-pass/easy/count-substrings-with-only-one-distinct-letter/count-substrings-with-only-one-distinct-letter.py | count-substrings-with-only-one-distinct-letter.py | py | 353 | python | en | code | 0 | github-code | 36 |
59318069 | import numpy as np
def mean(data,name):
sh = data.shape
nx = sh[1]
ny = sh[0]
new_data = np.zeros(sh)
if(name in ["ex","jx","hy"]):
for i in range(1,nx):
for j in range(0,ny):
new_data[i,j] = 0.5*(data[i,j]+data[i-1,j])
elif(name in ["ey","jy","hx"])... | takagi-junya/pyprogs | meaning.py | meaning.py | py | 702 | python | en | code | 0 | github-code | 36 |
41902703943 | import cv2
import numpy as np
img = cv2.imread('water_coins.jpg')
gr_img = cv2.cvtColor(img , cv2.COLOR_BGR2GRAY)
_ , thresh = cv2.threshold(gr_img , 0 , 255 , cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
#noise removal
kernel = np.ones((3 , 3) , np.uint8)
opening = cv2.morphologyEx(thresh , cv2.MORPH_OPEN , ker... | kumar6rishabh/counting_objects | counting_objects.py | counting_objects.py | py | 1,148 | python | en | code | 0 | github-code | 36 |
15500224657 | import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
"""使用scikit-learn提供的数值归一化"""
if __name__ == "__main__":
iris = datasets.load_iris()
X = iris.data
y = iri... | ediltwwj/MachinelLearning | ModelTest/scalerTest.py | scalerTest.py | py | 975 | python | en | code | 0 | github-code | 36 |
8511486303 | import math
from .ProductionSystem import ProductionSystem
class Gas(ProductionSystem):
def __init__(self, pressure=1500, temperature=50, sg=0.7):
"""
Generic class to define PVT properties for
a single-phase gas in the production system
Attributes:
- sg (float) : ga... | olaadapo/wellpvt | wellpvt/Gas.py | Gas.py | py | 5,005 | python | en | code | 5 | github-code | 36 |
7640727921 | #Before all this run the command pip install --user PyPDF2==1.26.0
#Shift + right click will bring up the powershell/cmd for the folder
#Ensure file is in the same folder and has the extension .pdf
import PyPDF2
import sys
import time
from tqdm import tqdm
pdfname = input("Enter the name of your file (example: Hello.pd... | anjannair/Automating-With-Python | PDFs/extracttext.py | extracttext.py | py | 1,524 | python | en | code | 1 | github-code | 36 |
13835335301 | import tensorflow as tf
class NConvDocConvNFC(object):
"""
CNN for text classification.
Uses an embedding layer, followed by a convolutional, max-pooling layers.
Lacks an output layer.
"""
def __init__(
self, document_length, sequence_length, embedding_size, filter_size_lists, num... | aeryen/AA_CNN | networks/middle_components/parallel_conv_DocLevel.py | parallel_conv_DocLevel.py | py | 7,392 | python | en | code | 2 | github-code | 36 |
35319730396 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: mcxiaoke
# @Date: 2016-01-04 11:18:06
import codecs
import os
import sys
import requests
import shutil
import time
HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.1234.0 Safari/537.36',
'Refe... | mcxiaoke/python-labs | instagram/utils.py | utils.py | py | 2,838 | python | en | code | 7 | github-code | 36 |
16147202007 | # import sys
# input = sys.stdin.readline
# while True:
# A,B = map(int, input().split())
# if 0<A<10 and 0<B<10:
# print(A+B)
# else:
# break
# 이렇게 풀었다가
# 런타임에러 = 해결못함 만 4번인가 5번ㅋㅋㅋ
# break도 해보고 무한loop도 돌려봤는데 왜 통과를 못하는지 이해 못하다가
# 1시간 넘어서 걍 구글링했따....정답은 try except 사용.........
# 혹은 입력 받고 안받... | kkeolmusae/BAEKJOON_Python | 4-while문/10951 A+B-4.py | 10951 A+B-4.py | py | 885 | python | ko | code | 0 | github-code | 36 |
1864913317 | '''
#! /usr/bin/python3
# Measurement System Input
def metric_imperial():
system = input('Type i for Imperial system, type any other key for Metric System: ')
return system
# Data Input
def get_data():
if system != 'i':
weight = float(input("weight(kg): "))
height = float(input("height(cm): ")... | yongtanggit/health | BMICalculator.py | BMICalculator.py | py | 2,491 | python | en | code | 0 | github-code | 36 |
26296087809 |
from PIL import Image
import numpy as np
import cv2
import pdb
import os
import time
import signal
import argparse
import json
import shutil
def split_data(path_, set_):
path_ = path_ + "/"
file_array = [file for file in os.listdir(path_) if file.endswith('.txt')]
file_array = sorted(file_array)
... | IIT-PAVIS/ReId_without_Id | data/split_train_test.py | split_train_test.py | py | 1,418 | python | en | code | 16 | github-code | 36 |
16743970431 | # -*-python-*-
VECTORS = ['Index',
'int',
'double',
'std::string']
SETS = { 'less': ['Index',
'int',
'double',
'std::string'],
'none': ['Index']}
HEADER = """\
#ifndef STATISKIT_STL_H
#define STATISKIT_STL_... | Global19-atlassian-net/STL-1 | src/cpp/SConscript | SConscript | 5,930 | python | en | code | null | github-code | 36 | |
75273634025 | total = 0
all_int = []
lowest = None
highest = None
while True:
try:
line = input('Zadajte číslo alebo Enter pre ukončenie: ')
if not line:
break
number = int(line)
total += number
all_int.append(number)
if lowest is None or lowest > number:
... | branislavblazek/notes | Python/1.lesson/average2.py | average2.py | py | 1,675 | python | en | code | 0 | github-code | 36 |
10538619256 | from collections import deque
노드개수, 간선개수 = map(int, input().split())
result = 0
# 빈 그래프 그리기
graph = [ [] for i in range(노드개수+1) ]
for i in range(간선개수):
a, b = map(int, input().split())
graph[a].append(b)
graph[b].append(a)
visited = [False] * (노드개수 + 1)
def 너비우선탐색(graph, start, visited):
queue = deq... | 5pponent/opponent | dfs&bfs/연결 요소의 개수.py | 연결 요소의 개수.py | py | 768 | python | en | code | 0 | github-code | 36 |
6753837772 | import numpy as np
from scipy import signal
# input:
# data(type:numpy array)(shape:time * 2)
# model(sklearn model or pytorch model)
# flatten(type: bool)(whether to flatten the input as 200 or use 100*2 as the model input)
# output:
# probanility_map(number of split, 12)
def stroke_probability_map(data, model, fl... | yzhao07/MLMA_EOG | Continuous CNN/stroke probability map/stroke_probability_map.py | stroke_probability_map.py | py | 881 | python | en | code | 0 | github-code | 36 |
36892858608 | from lxml import html
import requests
import csv
from os.path import exists
import time
import sys
# function printing additional info about request
def my_http_get(url):
print('')
print('REQUEST ' + url)
time.sleep(3) # added to avoid being blocked by fbref server
start = time.time()
result = req... | kornasm/GIS | scrapers/SeasonSquadScraper.py | SeasonSquadScraper.py | py | 3,520 | python | en | code | 0 | github-code | 36 |
5747062131 | from setuptools import setup
with open('README.md', 'r', encoding='utf-8') as f:
readme = f.read()
setup(
name='gearbest_api',
version='0.0.4',
description='Retrieve info from gearbest api.',
long_description=readme,
long_description_content_type='text/markdown',
url='https://github.com/ma... | matteobaldelli/python-gearbest-api | setup.py | setup.py | py | 716 | python | en | code | 1 | github-code | 36 |
3383149311 | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
first = float('inf') # Initialize first to positive infinity
second = float('inf') # Initialize second to positive infinity
for num in nums:
if num <= first:
first = num # Update fir... | neetcode-gh/leetcode | python/0334-increasing-triplet-subsequence.py | 0334-increasing-triplet-subsequence.py | py | 596 | python | en | code | 4,208 | github-code | 36 |
27298381738 | # Exercise 9
# Write a function that recognizes palindromes. (Hint: use your reverse function to make this easy!).
def mirror_back(text):
"""Returns a string backward."""
mirror_text = text
for i in range(len(text) - 1, - 1, - 1):
mirror_text = mirror_text + text[i]
len_mirrored = l... | Wilscos/thinkcspy-exercises | Chapter 9/Ex. 9.py | Ex. 9.py | py | 1,106 | python | en | code | 2 | github-code | 36 |
74752031784 | import os
import requests
from requests.exceptions import ReadTimeout
from requests_oauthlib import OAuth1
from helpers.configHelpers import decryptEnvVar
from helpers.logHelpers import createLog
from helpers.errorHelpers import URLFetchError
logger = createLog('hathiCover')
class HathiCover():
"""Manager class ... | NYPL/sfr-ingest-pipeline | lambda/sfr-hathi-reader/lib/hathiCover.py | hathiCover.py | py | 5,653 | python | en | code | 1 | github-code | 36 |
32352030938 | import logging
import glob
import collections
import os
import clang.cindex
from clang.cindex import CursorKind
from . import helpers
from . import enum_decl
from . import class_struct_decl
from . import function_decl
_LOGGER = logging.getLogger(__name__)
def _detect_library_file():
version = os.getenv("PYCODE... | blejdfist/pycodegen | pycodegen/frontend/frontend_cpp/parser_libclang.py | parser_libclang.py | py | 3,854 | python | en | code | 4 | github-code | 36 |
36947653909 | from __future__ import print_function
__revision__ = "src/engine/SCons/Tool/MSCommon/common.py bee7caf9defd6e108fc2998a2520ddb36a967691 2019-12-17 02:07:09 bdeegan"
import copy
import json
import os
import re
import subprocess
import sys
import SCons.Util
# SCONS_MSCOMMON_DEBUG is internal-use so undocumented:
# se... | mongodb/mongo | src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/MSCommon/common.py | common.py | py | 9,322 | python | en | code | 24,670 | github-code | 36 |
25240483381 | import datetime
import json
import time
import numpy as np
from common.args import Runtime
from data.premetheus import DataManger
cpu_data_range = {}
def cpu_data_pretreatment():
y = datetime.datetime.now().year
m = datetime.datetime.now().month
d = datetime.datetime.now().day
dt = str(y) + '-' + st... | falcomlife/klog-ai | src/core/data/pretreatment.py | pretreatment.py | py | 2,476 | python | en | code | 0 | github-code | 36 |
40451981469 | """seed event types
Revision ID: 0311eb0fc2e6
Revises: 61043123657a
Create Date: 2021-02-04 14:27:03.847005
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import table, column
from sqlalchemy import String, Integer, Boolean
# revision identifiers, used by Alembic.
revision = '0311eb0fc2e6'
do... | jcsumlin/secret-santa-discord-bot | alembic/versions/0311eb0fc2e6_seed_event_types.py | 0311eb0fc2e6_seed_event_types.py | py | 1,160 | python | en | code | 0 | github-code | 36 |
19421956825 | # import the libraries
from datetime import timedelta
# The DAG object; we'll need this to instantiate a DAG
from airflow import DAG
# Operators; we need this to write tasks!
from airflow.operators.bash_operator import BashOperator
# This makes scheduling easy
from airflow.utils.dates import days_ago
#defining DAG argu... | Amarigh/Apache_Airflow_DAG | ETL_Server_Access_Log_Processing.py | ETL_Server_Access_Log_Processing.py | py | 1,513 | python | en | code | 0 | github-code | 36 |
19354601917 | from __future__ import (absolute_import, print_function,
unicode_literals, division)
import time
import numpy as np
import pandas as pd
import requests
from bokeh import plotting
from bokeh.objects import ColumnDataSource
class QlogPlot:
def __init__(self, base, name, limit, ds):
self.nam... | jordens/qlog | qlog/plot.py | plot.py | py | 2,229 | python | en | code | 0 | github-code | 36 |
18431593043 | # -*- coding: utf-8 -*-
from my_collectors.abstract_scraper import AbstractScraper
import re
import traceback
class TechcrunchScraper(AbstractScraper):
base_url = "https://techcrunch.com/page/1/"
def __init__(self, target_url, save_dir):
super(TechcrunchScraper, self).__init__(
target_u... | shunk031/MyCollectors | my_collectors/techcrunch_collector/scraper.py | scraper.py | py | 2,613 | python | en | code | 0 | github-code | 36 |
1488036241 | import os
import re
import json
import glob
import tempfile
import argparse
import ast
import pandas as pd
import sys
import shipyard_utils as shipyard
from google.cloud import bigquery
from google.oauth2 import service_account
from google.api_core.exceptions import NotFound
EXIT_CODE_UNKNOWN_ERROR = 3
EXIT_CODE_INVA... | shipyardapp/googlebigquery-blueprints | googlebigquery_blueprints/upload_file.py | upload_file.py | py | 9,540 | python | en | code | 0 | github-code | 36 |
73495508264 | from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseNotFound
from django.views import View
from django.conf import settings
import json
import itertools
import random
from datetime import datetime
JSON_DATA = settings.NEWS_JSON_PATH
def get_json_data():
with open(JSON_... | Vladpetr/NewsPortal | HyperNews Portal/task/news/views.py | views.py | py | 2,754 | python | en | code | 0 | github-code | 36 |
9815611814 | # author:Nicolo
# time:2017/7/23
# function:生成汉字字库并转换为图片
import codecs
import os
import pygame
start,end = (0x4E00, 0x9FA5)
with codecs.open("chinese.txt", "wb", encoding="utf-8") as f:
for codepoint in range(int(start),int(end)):
f.write(chr(codepoint))
chinese_dir = 'chinese'
if not os.path.... | X-Nicolo/ChineseToImg | wordToImg.py | wordToImg.py | py | 824 | python | en | code | 4 | github-code | 36 |
17457985140 | """
Tests for specific issues and pull requests
"""
import os
import tempfile
import difflib
from textwrap import dedent
import gffutils
from gffutils import feature
from gffutils import merge_criteria as mc
from nose.tools import assert_raises
def test_issue_79():
gtf = gffutils.example_filename("keep-order-te... | hpatterton/gffutils | gffutils/test/test_issues.py | test_issues.py | py | 13,843 | python | en | code | null | github-code | 36 |
8445132228 | import numpy as _numpy
import cupy as _cupy
from cupy_backends.cuda.libs import cublas as _cublas
from cupy.cuda import device as _device
def gesv(a, b):
"""Solve a linear matrix equation using cusolverDn<t>getr[fs]().
Computes the solution to a system of linear equation ``ax = b``.
Args:
a (cu... | cupy/cupy | cupyx/lapack.py | lapack.py | py | 12,437 | python | en | code | 7,341 | github-code | 36 |
74032441703 | import os
import json
import time
import numpy as np
from .FCNN_FA import FCNN_FA
class FCNN_KP(FCNN_FA):
'''
Description: Class to define a Fully Connected Neural Network (FCNN)
with the Kolen-Pollack (KP) algorithm as learning algorithm
'''
def __init__(self, sizes... | makrout/Deep-Learning-without-Weight-Transport | fcnn/FCNN_KP.py | FCNN_KP.py | py | 4,665 | python | en | code | 31 | github-code | 36 |
73156319784 | from flask import Flask,render_template,request,make_response
app=Flask(__name__)
@app.route('/')
def input():
return render_template('page2.html')
@app.route('/page3',methods=['POST','GET'])
def page3():
a=request.form.get('nos1',type=int)
b=request.form.get('nos2',type=int)
result=a+b
resp=make_... | adityatyagi1998/Flask-Calci | calculator.py | calculator.py | py | 722 | python | en | code | 0 | github-code | 36 |
25066192842 | import torch
import torch.nn
import os,csv,datetime
import numpy as np
from cnn_structure import CNN
from torch.autograd import Variable
from sklearn.metrics import confusion_matrix
# MODEL_FOLDER = './model/'
MODEL_FOLDER = './'
DATA_FOLDER = './k1000_vec200/'
EMOTION = {'ne':0, 'ha':1, 'sa':2, 'an':3, 'di':4, 'su':5... | 1021546/test_pytorch | 學長 pytorch/2dCNNpredict/model_predict.py | model_predict.py | py | 2,030 | python | en | code | 0 | github-code | 36 |
39287803357 | # Library imports
import numpy as np
import pandas as pd
# Reading orginal dataset into excel file
original_df = pd.read_excel('Original-River-Data.xlsx', usecols='A:I', skiprows=1)
river_data = original_df.copy()
# Renaming Headers
new_columns = {'Unnamed: 0': 'Date'}
new_columns.update({col: f"{col} MDF (Cumecs)" f... | bheki-maenetja/small-projects-ai | lboro/cob107/cw2/data-processing.py | data-processing.py | py | 7,779 | python | en | code | 0 | github-code | 36 |
11504595660 | import numpy as np
import theano
import theano.tensor as T
from collections import OrderedDict
def simulate_dynamics(initial_pos, initial_vel, stepsize, n_steps, energy_fn):
"""
Return final (position, velocity) obtained after an `n_steps` leapfrog
updates, using Hamiltonian dynamics.
Parameters
-... | rueberger/MJHMC | mjhmc/fast/hmc.py | hmc.py | py | 14,473 | python | en | code | 24 | github-code | 36 |
29346768383 | #Aplikacja klienta
import threading
import socket
import sys
from socket import SHUT_RDWR
import time
def nadawanie():
wejscie = 'nic'
while wejscie != '\q':
wejscie = input()
if wejscie == '\q':
sock.sendall('quit'.encode(encoding='U16'))
try:
sock.shu... | LewalskiSebastian/SimpleTCPCommunicator | client_old.py | client_old.py | py | 1,797 | python | pl | code | 0 | github-code | 36 |
73260920425 | import pymongo
cliente = pymongo.MongoClient("mongodb://localhost:27017/")
database = cliente["bancoDados"]
pessoas = database["pessoas"]
pessoa1 = {"nome":"Gustavo","peso": 58}
insert = pessoas.insert_one(pessoa1)
print(insert.inserted_id)
listaDBs = cliente.list_database_names()
print(listaDBs)
listaCollections = ... | Gustavo-Baumann/AprendendoSintaxePython | phyton/mongoDB/test.py | test.py | py | 376 | python | pt | code | 0 | github-code | 36 |
6405350957 | """This module contains necessary function needed"""
# Import necessary modules
from imblearn.over_sampling import SMOTE, ADASYN
from imblearn.under_sampling import RandomUnderSampler, NearMiss
import numpy as np
import pandas as pd
import streamlit as st
import math
from sklearn.model_selection import cross_validate... | tobintobin16/Streamlit_CS498 | Parkinsons-Detector/web_functions.py | web_functions.py | py | 3,070 | python | en | code | 0 | github-code | 36 |
24629581794 | from Crypto.PublicKey import RSA
from django.contrib.auth.models import User
from rest_framework import serializers
from app.models import *
import uuid
class UserRelationField(serializers.RelatedField):
def to_representation(self, value):
return '{}'.format(value.user.username)
class AllOthersRelationFi... | bobbykemp/cryptoapp | cryptoapp/serializers.py | serializers.py | py | 4,528 | python | en | code | 0 | github-code | 36 |
24800813642 | import socket
import time
IP = 'localhost'
PORT = 12344
for x in range(10):
#initialize the socket with default settings
client_socket = socket.socket()
#connect to the server
client_socket.connect((IP, PORT))
print('connected successfuly')
mess = 'message is send'
client_socket.send(mess... | SandaCotovici/SI | lab#1/sent_after5sec/client.py | client.py | py | 400 | python | en | code | 0 | github-code | 36 |
17250742320 | scale = '0.002,0.002'
int_scale = [0.002, 0.002]
current_mode = ''
center = (300, 225)
list_to_delete = []
w, h = 600, 450
offset_for_coords = 3 * int_scale[0]
count = 0
current_map_file = None
coords_in_map_list = [0, 0]
coords_in_map = '0'
address_lox = ''
all_map_mods = ('map', 'sat', 'sat,skl')
apikey = "40d1649f-0... | Gamer3600/mars_task_lol | consts.py | consts.py | py | 348 | python | en | code | 0 | github-code | 36 |
4023788958 | import os
import sys
import json
import struct
import logging
from capstone.arm import *
from collections import Counter
from argxtract.common import paths as common_paths
from argxtract.core import utils
from argxtract.core import consts
from argxtract.common import objects as common_objs
from argxtract.core.disasse... | projectbtle/argXtract | argxtract/resources/vendor/nordic_ant/chipset_analyser.py | chipset_analyser.py | py | 8,728 | python | en | code | 25 | github-code | 36 |
74050641704 | from typing import Any, Dict, List, Optional, Union
from parlai.agents.rag.retrieve_api import (
SearchEngineRetriever,
SearchEngineRetrieverMock,
)
from parlai.agents.rag.retrievers import Document
from parlai.core.agents import Agent
from parlai.core.opt import Opt
from parlai.core.params import ParlaiParser... | facebookresearch/ParlAI | projects/bb3/agents/search_agent.py | search_agent.py | py | 3,676 | python | en | code | 10,365 | github-code | 36 |
2421253674 | days31=["January", "March", "May", "July", "August", "October", "December"]
days30=["April", "June", "September", "November"]
days28=["February"]
months={
"January":1,
"February":2,
"March":3,
"April":4,
"May":5,
"June":6,
"July":7,
"August":8,
"September":9,
"October":10,
"... | Time2Mire/PersonalPythonLearning | dayOfDate.py | dayOfDate.py | py | 2,169 | python | en | code | 0 | github-code | 36 |
37749884465 | from elegy.module import Module
import typing as tp
import haiku as hk
import jax.numpy as jnp
import numpy as np
from elegy import types
def _infer_shape(output_shape, dimensions):
"""
Replaces the -1 wildcard in the output shape vector.
This function infers the correct output shape given the input d... | anvelezec/elegy | elegy/nn/flatten.py | flatten.py | py | 4,093 | python | en | code | null | github-code | 36 |
22778778238 | #!/usr/bin/python
# encoding: utf-8
import random
import six
import numpy as np
from skimage.transform import resize as imresize
import chainer
import os
import skimage.io as skio
class resizeNormalize(object):
def __init__(self, size):
self.size = size
def __call__(self, img):
# image shap... | Swall0w/chainer-crnn | dataset.py | dataset.py | py | 2,600 | python | en | code | 4 | github-code | 36 |
74060339624 | import os
from .keys import KEYS
BASE_CONFIG = {
"LOG_LEVEL": "DEBUG",
"API_LOG_FILE": "api.log",
"DEMO_DYNAMO_TABLE": "cfde-dev-actions1",
"GLOBUS_NATIVE_APP": "417301b1-5101-456a-8a27-423e71a2ae26",
"GLOBUS_CC_APP": "9424983e-7bd6-4cea-b589-e93e88b038d9",
"GLOBUS_SCOPE": "",
"GLOBUS_AUD"... | fair-research/deriva-action-provider | cfde_ap/dev_config.py | dev_config.py | py | 835 | python | en | code | 0 | github-code | 36 |
26834249137 | """
.. module:: Wairakei/Tauhara MT inversion and Temp. extrapolation
:synopsis: Forward and inversion ot MT using MCMC 1D constrain inversion.
Extrapolation from temperature profiles in wells.
Estimate Temperature distribution.
.. moduleauthor:: Alberto Ardid
University of Auckland
.. con... | aardid/mt_meb_inv_code | 00_main_inversion.py | 00_main_inversion.py | py | 77,169 | python | en | code | 0 | github-code | 36 |
40716389632 | while True:
try:
a,b,c=input().split()
a=int(a)
b=int(b)
c=int(c)
break
except:
print("Invalid input")
break
d=b+c
if(a%d==0):
print("YES")
else:
print("NO")
| vaseem14/GUVI | b.py | b.py | py | 177 | python | en | code | 0 | github-code | 36 |
13183244334 | from math import sqrt
from itertools import product
import pandas as pd
import torch
from torch.autograd import Function
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
def make_vgg():
layers = []
in_channels = 3
cfg = [64, 64, 'M', 128, 128, 'M', 256, 256,
... | jsw6872/DataScience_ML-DL | DL/lecture/detection_segmentation/SSD/model.py | model.py | py | 17,905 | python | ko | code | 0 | github-code | 36 |
27054113665 | from tkinter import *
win1 = Tk()
win1.title('Schedule') #title
win1.geometry('800x800') #size
win1.resizable(False,False) #win1 -> not resizable
#win2 = Tk()
#win2.title('test')
#win2.geometry('400x400')
#win2.resizable(True, False) #win2 -> resizable
t1 = Text(win1, height = 10)
t1.insert(CURRENT, 'Arrange your sch... | sojin2019/myscheduler | input_schedule.py | input_schedule.py | py | 1,513 | python | en | code | 0 | github-code | 36 |
7731571907 | # Pickhacks 2023
# Safer Caver
# This is inspired by https://github.com/UP-RS-ESP/PointCloudWorkshop-May2022/blob/main/2_Alignment/ICP_Registration_ALS_UAV.ipynb
import copy
from pathlib import Path
import numpy as np
import open3d as o3d
import laspy
import distinctipy as colorpy
from scipy.spatial import cKDTree... | cubrink/pickhacks-2023 | safercaver/src/aligner.py | aligner.py | py | 8,767 | python | en | code | 0 | github-code | 36 |
32171583210 | import random
birthdays = set()
def newrun():
global birthdays
random.seed()
birthdays = set()
print("\n\n")
def BirthdayDate(bd):
if (bd <= 31): return ("%02d.01" % bd)
bd -= 31
if (bd <= 28): return ("%02d.02" % bd)
bd -= 28
if (bd <= 31): return ("%02d.03" % bd)
... | freyfakse/Skole | DAT235/Downloads/BirthdayParadox.py | BirthdayParadox.py | py | 1,330 | python | en | code | 0 | github-code | 36 |
70050076903 | """
Simple runner that can parse template and run all Sources to write in the Sinks
"""
import sys
from typing import Optional
from pipereport.base.templateregistry import BaseTemplateRegistry
from pipereport.template.template import Template
from pipereport.template.registry import GitFSTemplateRegistry
class Pip... | enchantner/pipereport | pipereport/runner/runner.py | runner.py | py | 2,078 | python | en | code | 0 | github-code | 36 |
4204565119 | import argparse
import itertools
import random
import sys
import gym
import numpy as np
from gym.wrappers import TimeLimit
from tqdm import trange
import sen.envs
from sen.agents import LimitActionsRandomAgent, RandomAgent
from sen.envs.block_pushing import render_cubes, rot90_action
from sen.utils import save_h5
d... | jypark0/sen | sen/data/gen_cubes.py | gen_cubes.py | py | 3,917 | python | en | code | 4 | github-code | 36 |
12485964052 | from pathlib import Path
import numpy as np
import pandas as pd
ROOT_DIRECTORY = Path("/code_execution")
DATA_DIRECTORY = Path("/data")
OUTPUT_FILE = ROOT_DIRECTORY / "submission" / "subset_matches.csv"
def generate_matches(query_video_ids) -> pd.DataFrame:
raise NotImplementedError(
"This script is jus... | drivendataorg/meta-vsc-matching-runtime | submission_src/main.py | main.py | py | 786 | python | en | code | 3 | github-code | 36 |
9958405181 | class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
values = []
arr = self.inorder(root,values)
return arr[k-1]
def inorder(self,root,a):
if(root):
self.inorder(root.left... | Hamzenium/Neet-Code | k_smallest.py | k_smallest.py | py | 475 | python | en | code | 0 | github-code | 36 |
75311890665 | import json
import os
import shutil
import torch
from efficientnet_pytorch import EfficientNet
from tensorboardX import SummaryWriter
from torch.nn import CrossEntropyLoss
from torch.optim.lr_scheduler import ExponentialLR, CosineAnnealingLR
from torch.utils.data import DataLoader
from torchsummary import summary
from... | Danil328/ID_RND_V2 | src/shuffleMetrics.py | shuffleMetrics.py | py | 3,370 | python | en | code | 2 | github-code | 36 |
14559612423 | #!/usr/bin/env python3
from time import time
from datetime import timedelta
import json
import decimal
import os
import sys
import traceback
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import logging
logging.getLogger("tensorflow").setLevel(logging.WARNING)
import tensorflow as tf
from recipes.baskt_rs_recipes import Ba... | Stepka/baskt-recommendation-system | prediction_flask_server.py | prediction_flask_server.py | py | 10,049 | python | en | code | 0 | github-code | 36 |
75134171944 | from flask_bcrypt import Bcrypt
from flask_sqlalchemy import SQLAlchemy
bcrypt = Bcrypt()
db = SQLAlchemy()
class Like (db.Model):
__tablename__='likes'
user_liking_id = db.Column(
db.Integer,
db.ForeignKey('users.id', ondelete='CASCADE'),
primary_key=True,
)
... | ibdao/cyas-friender | friender-backend/models.py | models.py | py | 4,829 | python | en | code | 1 | github-code | 36 |
8880207451 | import math
from typing import Callable
import numpy as np
from nm.typing import NDArrayOrFloat
def relative_error(
curr_approx: NDArrayOrFloat, prev_approx: NDArrayOrFloat
) -> NDArrayOrFloat:
"""Given current and previous iteration/approximation value returns the
relative error (does not return percen... | abzrg/nmpy | nm/error.py | error.py | py | 2,102 | python | en | code | 0 | github-code | 36 |
71513904425 | from flask import request, jsonify
from os.path import isfile
from sklearn import svm
import pickle
MODEL_FILE = 'model.p'
class Model(object):
__model_loaded = False
def __init__(self):
self.__model = svm.SVC()
if isfile(MODEL_FILE):
self.__load_model()
def __load... | ColinShaw/python-sklearn-flask-deployment-example | src/model.py | model.py | py | 1,593 | python | en | code | 0 | github-code | 36 |
38190199809 | #!/usr/bin/python
import sys
import logging
from rdsConfig import getDbConfig
import json
import config
from responseIO import returnResponse, errString
from keyCheck import verifyPublisher, verifyUsers
import datetime
from modules.post import post
from dbCommons import createModuleIssue
## Creating a lamb... | misternaks/allmoduleissues | allModuleIssues.py | allModuleIssues.py | py | 2,027 | python | en | code | 0 | github-code | 36 |
37360585045 | # 工具类函数
import colorsys
import functools
import glob
import json
import re
from loguru import logger
def parse_range(page_range: str, page_count: int, is_multi_range: bool = False, is_reverse: bool = False, is_unique: bool = True):
# e.g.: "1-3,5-6,7-10", "1,4-5", "3-N", "even", "odd"
page_range = page_range... | kevin2li/PDF-Guru | thirdparty/utils.py | utils.py | py | 7,425 | python | en | code | 941 | github-code | 36 |
1102639884 | # -*- coding: utf-8 -*-
' a test module '
__author__ = 'wuqiang'
import sys
def test():
args = sys.argv
print("args:", args)
#args[0]为本脚本文件的全路径
if len(args)==1:
print('Hello, world!')
elif len(args)==2:
print('Hello, %s!' % args[1])
else:
print('Too many arguments... | code4love/dev | Python/demos/python-course/模块/hello.py | hello.py | py | 556 | python | zh | code | 0 | github-code | 36 |
5213207430 | from unittest import TestCase
from typing import List, Set, Tuple
"""
You are given a m x n 2D grid initialized with these three possible values.
-1 - A wall or an obstacle.
0 - A gate.
INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the
distance to a... | tugloo1/leetcode | problem_286.py | problem_286.py | py | 3,246 | python | en | code | 0 | github-code | 36 |
12979955656 | import sys
from reward_abc import RewardFunctionAbc
# from skimage.measure import approximate_polygon, find_contours
# from skimage.draw import polygon_perimeter, line
from skimage.transform import hough_line, probabilistic_hough_line
# from skimage.transform import hough_line_peaks
import torch
from skimage.draw impor... | kreshuklab/rewardchecking | lines_reward.py | lines_reward.py | py | 9,442 | python | en | code | 0 | github-code | 36 |
1941680628 | # SHOW CARD LIST
#
import os
import re
import json
import sublime
import sublime_plugin
import subprocess
class UmbertoGetRecipCardLinkCommand(sublime_plugin.TextCommand, sublime_plugin.WindowCommand):
def run(self, edit):
settings = sublime.load_settings('Umberto.sublime-settings'... | tgparton/Umberto | get_recip_card_link.py | get_recip_card_link.py | py | 4,350 | python | en | code | 0 | github-code | 36 |
70631838504 | import pandas as pd
import numpy as np
import string, re
import nltk
import time,random
import operator
#from tabulate import tabulate
from nltk.stem.snowball import SnowballStemmer
import os.path
stop_list = nltk.corpus.stopwords.words('english')
lemmatizer = nltk.stem.WordNetLemmatizer()
punctuation = list(string.p... | zaksoliman/twitter-sentiment-analysis | tweet_analysis/classifiers/process_chars.py | process_chars.py | py | 2,719 | python | en | code | 0 | github-code | 36 |
13076725712 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import os
# directory where the FWHM file is located
directory = '//fs03/LTH_Neutimag/hkromer/02_Simulations/06_COMSOL/\
03_BeamOptics/01_OldTarget/IGUN_geometry/2018-09-18_comsolGeometry/\
02.define_release_time/particle... | kromerh/phd_python | 03_COMSOL/03_BeamOptics/01_particlePosition/2018-09-28_compareFWHMs_oldTarget.py | 2018-09-28_compareFWHMs_oldTarget.py | py | 1,802 | python | en | code | 0 | github-code | 36 |
25625656419 | import logging
import random
import json
import string
import threading
import urllib.request
import spacy
from datetime import datetime
from tinydb import TinyDB, Query
from tinydb.operations import add
from urllib.parse import quote
from urllib.error import HTTPError
import pymorphy2
from operator import... | alkurmtl/playnamegame | run.py | run.py | py | 29,693 | python | ru | code | 0 | github-code | 36 |
14836136357 | import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel as DDP
from utils.Manager import Manager
from models.XFormer import XFormer
def main(rank, manager):
""" train/dev/test/tune the model (in distributed)
Args:
rank: current process id
world_size: total gpu... | tyh666/News-Recommendation-MIND | xformer.py | xformer.py | py | 1,123 | python | en | code | 1 | github-code | 36 |
38985345142 | from functools import partial
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.datasets import fetch_openml
from sklearn.metrics import mean_tweedie_deviance
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
def load_mtpl2(n_samples=100... | christopher-parrish/sas_viya | python/tweedie_regressor_python/pure_premium_python_example.py | pure_premium_python_example.py | py | 10,361 | python | en | code | 1 | github-code | 36 |
27089925634 | class Solution:
def longestPalindrome(self, s: str) -> int:
occured = {}
res = 0
uneven=False
for c in s:
if c in occured:
occured[c]+=1
else:
occured[c]=1
for k,v in occured.items():
res+=floor(v/2)*2
... | JuliaGrajek/LeetCode | LeetCode 75/LongestPalindrome.py | LongestPalindrome.py | py | 428 | python | en | code | 0 | github-code | 36 |
34358986297 | import SECRETS
import os
import openai
openai.organization = "org-0iQE6DR7AuGXyEw1kD4poyIg"
openai.api_key = SECRETS.open_ai_api_key
from sms.logger import json_logger
def send_init_roast_bot_primer_prompt():
completion = openai.Completion.create(
model = "text-davinci-003",
# prompt="Tell me a joke abo... | Brandon-Valley/tik_live_host | src/open_ai_api_handler.py | open_ai_api_handler.py | py | 1,813 | python | en | code | 0 | github-code | 36 |
10076939934 | from langchain.document_loaders import PyPDFLoader
from langchain.document_loaders.csv_loader import CSVLoader
from langchain.text_splitter import MarkdownHeaderTextSplitter,RecursiveCharacterTextSplitter
from langchain.vectorstores import Chroma
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.l... | Utsav-ace/LLMGpt | src/mylib/upload.py | upload.py | py | 3,755 | python | en | code | 0 | github-code | 36 |
8806412517 | import threading, queue, time
# The worker thread gets jobs off the queue. When the queue is empty, it
# assumes there will be no more work and exits.
# (Realistically workers will run until terminated.)
def worker():
print('Running worker')
time.sleep(0.1)
while True:
try:
arg = q.get... | juewuer/learnpython | test_queue.py | test_queue.py | py | 929 | python | en | code | 0 | github-code | 36 |
33553726731 | '''
单个模型的pipeline
比如多层意图 只能对某一层意图进行infer
'''
from pre_data_deal import Pre_Data_Deal
from NameEntityRec import NameEntityRec
import random
from IntentConfig import Config
from collections import OrderedDict
from model.dl_model.model_lstm_mask.lstm_mask import LstmMask
from model.dl_model.model_lstm_mask.pipeline_lstm_m... | markWJJ/Intent_Detection | pipeline_tool.py | pipeline_tool.py | py | 10,671 | python | en | code | 4 | github-code | 36 |
889446688 | from numpy.lib import average
import pandas as pd
import numpy as np
import re
import nltk
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split,learning_curve,GridSearchCV
from nltk.stem.snowball import SnowballStemmer
from nltk.corpus import stopwords
from sklearn.feature_extraction.tex... | saarthakbabuta1/loan-agreement | machine_learning.py | machine_learning.py | py | 10,438 | python | en | code | 0 | github-code | 36 |
71806898343 |
import pandas as pd
from splinter import Browser
from bs4 import BeautifulSoup as bs
from webdriver_manager.chrome import ChromeDriverManager
import time
def scrape():
# Latest Mars News
# Set up Splinter
executable_path = {'executable_path': ChromeDriverManager().install()}
browser = Browser('c... | NZeinali/Web_Scraping_Challenge | scrape_mars.py | scrape_mars.py | py | 2,652 | python | en | code | 0 | github-code | 36 |
571034080 | ## BMO CHATBOT CLASS DEFINITION
# Author: Milk + Github Copilot (WOW!)
# Last modified: 2022-10-05
import random
from pathlib import Path
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
class BMO():
def __init__(self,debug=False):
#set debug mode
self.DEBUG = debug
... | MasterMilkX/BMO_chatbot_prototype | Python/bmo.py | bmo.py | py | 10,867 | python | en | code | 1 | github-code | 36 |
274283973 | import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def boxplot(df, output_folder):
#simple version, only makes the 4 boxplots every dataset has in common
fig, (ax1, ax2, ax3, ax4) = plt.subplots(1, 4)
#fig.suptitle('Air Beam', fontsize=20)
dat = [df['Temperature'].dropna(... | bglowniak/Air-Quality-Analysis | src/main/python/vis_utils.py | vis_utils.py | py | 4,065 | python | en | code | 1 | github-code | 36 |
74698899304 | from fastapi import APIRouter
from db import db
from models import Wct
router = APIRouter()
@router.patch("/{syncId}/wct")
async def update_wct(syncId: int, wct: Wct):
await db.update_user_wct(syncId, wct)
return {
'status': 'OK'
}
| NIDILLIN/Kathrin | Microservices/Users(1406)/routers/patch.py | patch.py | py | 258 | python | en | code | 0 | github-code | 36 |
12814321526 | # 카드 정렬하기 / p363 / 정렬
import heapq
N = int(input())
data = []
for i in range(N):
heapq.heappush(data,int(input()))
min = []
result = 0
for i in range(N-1):
a = heapq.heappop(data)
b = heapq.heappop(data)
result += a+b
heapq.heappush(data,a+b)
print(result) | Girin7716/PythonCoding | pythonBook/Problem Solving/Q26.py | Q26.py | py | 295 | python | en | code | 1 | github-code | 36 |
11412632632 | import logging
import time
from typing import List
from spaceone.inventory.connector.aws_kinesis_data_stream_connector.schema.data import (
StreamDescription,
Consumers,
)
from spaceone.inventory.connector.aws_kinesis_data_stream_connector.schema.resource import (
StreamResource,
KDSResponse,
)
from sp... | 100sun/plugin-aws-cloud-services | src/spaceone/inventory/connector/aws_kinesis_data_stream_connector/connector.py | connector.py | py | 6,632 | python | en | code | null | github-code | 36 |
7905545130 | # Problem 6
# Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
# https://projecteuler.net/problem=6
# create a list of number from 900 to 1000
start = 1
numlist = []
for i in range(0, 100):
numlist.append(start)
start += 1
squareList = []
... | BenThienngern/WebbComscience | problem6.py | problem6.py | py | 490 | python | en | code | 0 | github-code | 36 |
41978532192 | from ja.common.job import Job, JobSchedulingConstraints, JobPriority
from ja.common.docker_context import DockerContext, MountPoint, DockerConstraints
from test.serializable.base import AbstractSerializableTest
class JobTest(AbstractSerializableTest):
"""
Class for testing Job.
"""
def setUp(self) -> ... | DistributedTaskScheduling/JobAdder | src/test/serializable/job/test_job.py | test_job.py | py | 1,996 | python | en | code | 2 | github-code | 36 |
24026596766 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.6
from tqdm import tqdm
import matplotlib.pyplot as plt
import os
import datetime
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from utils import get_dataset
from options import args_parser
from update ... | LiruichenSpace/FedFusion | src/baseline_main.py | baseline_main.py | py | 4,708 | python | en | code | 6 | github-code | 36 |
20460415252 | import time
import matplotlib.pyplot as plt
import numpy as np
import numpy.random as rnd
import sorting.merge_sort as merge
import sorting.quick_sort as quick
MAX_SIZE = 1000
STEP = 1
NUM_ITERATIONS = 10
def timer(task):
start = time.clock()
task()
end = time.clock()
return end - start
def test_... | Apophany/coding-exercises | python/performance/perf_test.py | perf_test.py | py | 1,160 | python | en | 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.