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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
38348533917 | #!/usr/bin/python3
import sys, getopt, os
import pandas as pd
import numpy as np
from analytical_settings import HAP1_control_1, HAP1_control_2, HAP1_control_3, HAP1_control_4
from analytical_settings import grouping
from analytical_settings import cauchy_compatibility
from global_functions import read_csv, write_csv... | BrummelkampResearch/HAP1_Synthetic_Lethality_pipeline | sub/normalize.py | normalize.py | py | 9,869 | python | en | code | 1 | github-code | 6 |
34905834189 | import shutil
import tempfile
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import Client, TestCase, override_settings
from django.urls import reverse
from ..forms import PostForm
from ..models import Post... | DianaKab/hw05_final_new | yatube/posts/tests/test_forms.py | test_forms.py | py | 4,715 | python | ru | code | 0 | github-code | 6 |
11428296984 | """Tool pack for email.
emails.py in: 2021-12-11.
This module exports the following functions:
-> is_valid - Check if the string is a valid email.
-> is_same - Check if the two emails are the same.
"""
import doctest
from re import match
# File with the configuration of the loguru logger
from logs.loguru_con... | cicerohr/python_template | tools/emails.py | emails.py | py | 3,063 | python | en | code | 0 | github-code | 6 |
1907238463 | #Haz un programa que lea un numero y te duvukeva la suma de sus cifras, tratando el numero como un numero natural.
#Ejemplo:
#Si leemos 123 la suma de sus cifras es 6.
#Si leemos 5 la suma de sus cifras es 5.
numero = int(input("Ingrese un número: "))
suma_cifras = 0
while numero > 0:
cifra = numero % 10
sum... | ANDRESTOBAJAS/Carpeta-de-Python | sumador de cifras.py | sumador de cifras.py | py | 406 | python | es | code | 0 | github-code | 6 |
23525022654 | from matplotlib import pyplot as plt
import numpy as np
import collections
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
# Get cpu or gpu device for training.
device = "cuda" if torch.cuda.is_a... | lewiis252/machine_learning | cifar10_nn.py | cifar10_nn.py | py | 7,791 | python | en | code | 0 | github-code | 6 |
8909155137 | """
Command line tool to search image sources.
"""
import sys
sys.path.insert(0, '../..')
from searcher import database, image
if __name__ == "__main__":
if len(sys.argv) != 4:
print("Invalid number of arguments.")
exit()
db = database.Database(sys.argv[1])
reference_url = sys.argv[2]
... | SebastianBach/searcher | apps/search/search.py | search.py | py | 640 | python | en | code | 0 | github-code | 6 |
73952557948 | import os
today = '02-06-19_'
import numpy as np
import treecorr
def parse_args():
import argparse
parser = argparse.ArgumentParser(description='Produce Tau correlations, i.e correlation among galaxies and reserved stars')
parser.add_argument('--metacal_cat',
#default='/home2/d... | des-science/Y3_shearcat_tests | alpha-beta-eta-test/code/essentials/taus.py | taus.py | py | 7,792 | python | en | code | 1 | github-code | 6 |
15362206849 | from generator import Generator
from discriminator import Discriminator
from speaker_encoder import SPEncoder
import torch
import torch.nn.functional as F
import os
from os.path import join, basename, exists
import time
import datetime
import numpy as np
from tqdm import tqdm
import numpy as np
import copy
class Solve... | Mortyzhou-Shef-BIT/DYGANVC | solver.py | solver.py | py | 12,824 | python | en | code | null | github-code | 6 |
24150027900 | from fastapi import FastAPI, APIRouter,status, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
from services.connectionHobolink import Connection
from routers import login
app=FastAPI(title="WeatherStation")
#routers
app.inc... | AlvaroCoder/WeatherStation | main.py | main.py | py | 1,214 | python | en | code | 0 | github-code | 6 |
29644942121 | from openerp import models, fields, api, _
class QcInspection(models.Model):
_inherit = "qc.inspection"
@api.multi
def _prepare_inspection_line(self, test, line, fill=None):
res = super(QcInspection, self)._prepare_inspection_line(
test, line, fill=fill)
res['min_value_below']... | odoomrp/odoomrp-wip | quality_control_tolerance/models/qc_inspection.py | qc_inspection.py | py | 2,979 | python | en | code | 119 | github-code | 6 |
15152787587 | # -*- coding: utf-8 -*
#该程序用于模型测试
import os
import torch
import numpy as np
import torch.nn as nn
from evaluation import HKOEvaluation
from ium_data.bj_iterator import BJIterator
if __name__ == "__main__":
#最佳的模型
test_model = torch.load('./checkpoints/trained_model_12000.pkl' )
test_model.eval()
... | LiangHe77/UNet_v1 | test.py | test.py | py | 1,817 | python | en | code | 0 | github-code | 6 |
17324365412 | from motor import motor_asyncio
from .model import Guild
import os
class Database:
def __init__(self, *, letty):
self.letty = letty
self.connection = motor_asyncio.AsyncIOMotorClient(os.environ['DB_URL'])
self.db = db = self.connection[os.environ['DB_NAME']]
self.guild = db.guilds
... | WhyNoLetty/Letty | database/base.py | base.py | py | 890 | python | en | code | 7 | github-code | 6 |
17732707406 | #!/usr/bin/env python
import subprocess
import time
import socket
import re
from threading import Thread
import tkinter as tk
class TCPClient(Thread):
def __init__(self, host, port, device):
Thread.__init__(self)
self.host = host
self.port = port
self.device = device
self.... | Drake81/spyduino | spyduino_simulator/spyduino-simulator.py | spyduino-simulator.py | py | 6,994 | python | en | code | 0 | github-code | 6 |
13020029275 | import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import ensemble
def data_accuracy(predictions, real):
"""
Check the accuracy of the estimated prices
"""
# This will be a list, the ith element of this list will be abs(prediction[i] - real[i])/rea... | V1K1NGbg/House-Price-Prediction-Project | testing.py | testing.py | py | 2,216 | python | en | code | 0 | github-code | 6 |
10425091071 | #-*- coding: utf-8 -*-
u"""
.. moduleauthor:: Martí Congost <marti.congost@whads.com>
"""
from cocktail import schema
from .block import Block
class CustomBlock(Block):
instantiable = True
type_group = "blocks.custom"
view_class = schema.String(
required = True,
shadows_attribute = True... | marticongost/woost | woost/models/customblock.py | customblock.py | py | 402 | python | en | code | 0 | github-code | 6 |
27949370562 | # String formatting/Templeting
# 1
name = "Mohib"
greeting = f"Hello, {name}"
print(f"Hello, {name}")
# 2
greeting = "Hi, {}"
with_name = greeting.format(name)
print(with_name)
# 3
longer_phrase = "Hello, {}. Today is {}."
formated = longer_phrase.format("Rahman", "Monday")
print(formated)
| newmohib/python-fundamental-2 | string_formatting.py | string_formatting.py | py | 297 | python | en | code | 0 | github-code | 6 |
12858137004 | """
We are given a directed graph. We are given also a set of pairs of vertices.
Find the shortest distance between each pair of vertices or -1 if there is no path connecting them.
On the first line, you will get N, the number of vertices in the graph.
On the second line, you will get P, the number of pairs between whi... | dandr94/Algorithms-with-Python | 04. Minimum-spanning-tree-and-Shortest-path-in-Graph/02. Exercise/01. distance_between_vertices.py | 01. distance_between_vertices.py | py | 2,005 | python | en | code | 0 | github-code | 6 |
44870137636 | #!/usr/bin/python3
def main():
d = { "one": 1, "two": 2, "three": 3, "four": 4, "five": 5 }
print("Dictionaries: ", d)
for k in d:
print(k, d[k])
print("Sorted by Keys: ")
for k in sorted(d.keys()):
print(k, d[k])
print("Dictionaries are mutable objects")
dd = dict(
... | sandeepgholve/Python_Programming | Python 3 Essential Training/05 Variables/variables-dictionaries.py | variables-dictionaries.py | py | 539 | python | en | code | 0 | github-code | 6 |
31412656744 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""
Life's pathetic, have fun ("▔□▔)/hi~♡ Nasy.
Excited without bugs::
| * *
| . .
| .
| * ,
| .
|
| *
... | nasyxx/nacf | tests/test_nacf.py | test_nacf.py | py | 5,224 | python | en | code | 9 | github-code | 6 |
28153506484 | import json
import numpy as np
def load_json(file_path : str) -> dict:
"""
Loads .json file types.
Use json python library to load a .json file.
Parameters
----------
file_path : string
Path to file.
Returns
-------
json file : dictionary
.json dictionary file.
... | jm1261/PeakFinder | src/fileIO.py | fileIO.py | py | 4,274 | python | en | code | 0 | github-code | 6 |
25070502975 | import pydoc
import logging
from typing import Generic, Type, Optional, Union, TypeVar, Any, NamedTuple
from django.db import models
from django.conf import settings
from django.forms.models import model_to_dict
from rest_framework import serializers
logger = logging.getLogger(__name__)
T = TypeVar("T")
class Abstra... | danh91/purplship | server/modules/core/purplship/server/serializers/abstract.py | abstract.py | py | 8,956 | python | en | code | null | github-code | 6 |
71968698427 | import torch.nn as nn
from collections import OrderedDict
from graph_ter_seg.tools import utils
class EdgeConvolution(nn.Module):
def __init__(self, k, in_features, out_features):
super(EdgeConvolution, self).__init__()
self.k = k
self.conv = nn.Conv2d(
in_features * 2, out_f... | gyshgx868/graph-ter | graph_ter_seg/models/layers.py | layers.py | py | 2,158 | python | en | code | 56 | github-code | 6 |
6496477997 | import os
from util import build_utils
def FilterProguardOutput(output):
'''ProGuard outputs boring stuff to stdout (proguard version, jar path, etc)
as well as interesting stuff (notes, warnings, etc). If stdout is entirely
boring, this method suppresses the output.
'''
ignore_patterns = [
'ProGuard, ve... | danrwhitcomb/Monarch | build/android/gyp/util/proguard_util.py | proguard_util.py | py | 3,140 | python | en | code | 5 | github-code | 6 |
30241855772 | import os
from autoPyTorch.core.api import AutoNet
from autoPyTorch.pipeline.base.pipeline import Pipeline
from autoPyTorch.pipeline.nodes.one_hot_encoding import OneHotEncoding
from autoPyTorch.pipeline.nodes.metric_selector import MetricSelector
from autoPyTorch.pipeline.nodes.ensemble import EnableComputePredictions... | RitchieAlpha/Auto-PyTorch | autoPyTorch/core/ensemble.py | ensemble.py | py | 5,843 | python | en | code | null | github-code | 6 |
12805757281 | import os
import cv2
import matplotlib.pyplot as plt
import numpy as np
import random
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
Datadirectory = "train\\"
Classes = ["0", "1", "2", "3", "4", "5", "6"]
img_size = 224
training_data = []
counter = 0
def createtrainingset()... | Mudaferkaymak/Detecting-Faces-and-Analyzing-Them-with-Computer-Vision | Detecting-Faces-and-Analyzing-Them-with-Computer-Vision/training_themodel.py | training_themodel.py | py | 1,867 | python | en | code | 1 | github-code | 6 |
17536523132 | import pystan
import stan_utility
import matplotlib
import matplotlib.pyplot as plot
##################################################
##### Simulate data and write to file
##################################################
model = stan_utility.compile_model('gen_data.stan')
fit = model.sampling(seed=194838, algorit... | MiyainNYC/Rose | stan/wimlds/1/lin_regr.py | lin_regr.py | py | 3,574 | python | en | code | 0 | github-code | 6 |
23048935694 | from sqlalchemy.orm import Session
from .. import models, schemas
from fastapi.encoders import jsonable_encoder
def get_score(db: Session):
score = db.query(models.Score).first()
if not score:
new_score = create_score()
db.add(new_score)
db.commit()
db.refresh(new_score)
... | hooglander/fastapi-get-and-post | app/repository/score.py | score.py | py | 873 | python | en | code | 0 | github-code | 6 |
70939280508 | import os
import argparse
import pickle
import scipy
import trajnetplusplustools
class TrajnetEvaluator:
def __init__(self, reader_gt, scenes_gt, scenes_id_gt, scenes_sub, indexes, sub_indexes, args):
self.reader_gt = reader_gt
##Ground Truth
self.scenes_gt = scenes_gt
self.scen... | lzz970818/Trajectory-Prediction | Trajectory-Prediction-master/evaluator.py | evaluator.py | py | 13,202 | python | en | code | 12 | github-code | 6 |
17284176875 | # Calculates the number of trees that are visibile from outside the grid
def part1():
ROW, COLUMN = [99, 99] # Dimensions for the forest map
forest_grid = [[] for _ in range(COLUMN)] # Forest map represented by a 2D Array (99x99)
trees_visible = 0 # Number o... | kianlak/Advent-Of-Code-2022 | Day8/Day8Part1.py | Day8Part1.py | py | 3,196 | python | en | code | 0 | github-code | 6 |
25528262922 | #!/usr/bin/python3
# 3-infinite_add.py
# Simon Tagbor <simontagbor360@gmail.com>
if __name__ == "__main__":
import sys
result = 0
for i in range(len(sys.argv) - 1):
result += int(sys.argv[i+1])
print("{:d}".format(result))
| Simontagbor/alx-higher_level_programming | 0x02-python-import_modules/3-infinite_add.py | 3-infinite_add.py | py | 248 | python | en | code | 2 | github-code | 6 |
21840251334 | """Order views module"""
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from rest_framework import status as st
from rest_framework import generics
from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer
from rest_framework.parsers import JSONParser
from... | GunGalla/order-flow-test | orders/views.py | views.py | py | 2,855 | python | en | code | 0 | github-code | 6 |
18246562040 | class nomatch(Exception):
'''Thrown when parsing fails. Almost always caught and almost never fatal'''
def parse(string):
'''Parse a full string and return a lego piece. Fail if the whole string wasn't parsed'''
p, i = pattern.match(string, 0)
if i != len(string):
raise Exception("Could not parse '" + string + "... | Honghe/greenery | lego.py | lego.py | py | 95,333 | python | en | code | null | github-code | 6 |
2156579897 | from crsql_correctness import connect, close, min_db_v
from pprint import pprint
# exploratory tests to debug changes
def sync_left_to_right(l, r, since):
changes = l.execute(
"SELECT * FROM crsql_changes WHERE db_version > ? ORDER BY db_version, seq ASC", (since,))
ret = 0
for change in changes... | vlcn-io/cr-sqlite | py/correctness/tests/test_sandbox.py | test_sandbox.py | py | 1,707 | python | en | code | 2,036 | github-code | 6 |
75188719226 | # 초기 거리를 1로 지정
# 가까운 곳부터 수행하는 bfs이기에 이미 최단거리가 기록된 경우에는 거리가 갱신되지 않도록 설정
from collections import deque
def bfs(x, y):
# 큐 구현을 위해 deque 라이브러리 사용
queue = deque()
# 초기 좌표 설정
queue.append((x, y))
# 큐가 빌 때까지 반복
while queue:
x, y = queue.popleft()
# 현재 위치에서 4가지 방향으로 위치 확인
... | zacinthepark/Problem-Solving-Notes | na/02/DFS-BFS/미로탈출.py | 미로탈출.py | py | 1,348 | python | ko | code | 0 | github-code | 6 |
16351053586 | from bs4 import BeautifulSoup as bs
import requests
from cardBeta import CardBeta
from cardWitj import CardWitj
urls = {
'beta':
'https://beta.gouv.fr/recrutement/developpement?',
'witj':
'https://www.welcometothejungle.com/fr/companies/communaute-beta-gouv/jobs'
}
divs = {'beta': 'fr-card__body', 'wi... | apimobi/witj-beta-replit | crawler.py | crawler.py | py | 1,963 | python | en | code | 0 | github-code | 6 |
14956977226 | import argparse
import os
from scipy.interpolate import griddata
import numpy as np
from tqdm import tqdm
import cv2
import scipy.ndimage as sp
import matplotlib.pyplot as plt
from matplotlib import cm, patches
# Argument Parser
parser = argparse.ArgumentParser(description="Time-series Heatmap Generator")
parser.add_a... | raghavauppuluri13/robot-palpation | rpal/scripts/visualize_heatmap.py | visualize_heatmap.py | py | 2,568 | python | en | code | 0 | github-code | 6 |
10958770997 | import os
import csv
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from torch.utils.data import Dataset, DataLoader
from torchvision.io import read_image
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torchvision.io import rea... | K-kiron/animal-detect | Helpers/AWA2_Dataloader.py | AWA2_Dataloader.py | py | 7,864 | python | en | code | 1 | github-code | 6 |
26113397145 | __authors__ = ["T. Vincent"]
__license__ = "MIT"
__date__ = "08/09/2017"
import weakref
from silx.gui import qt
from silx.gui.icons import getQIcon
from .. import actions
class ViewpointToolButton(qt.QToolButton):
"""A toolbutton with a drop-down list of ways to reset the viewpoint.
:param parent: See :cl... | silx-kit/silx | src/silx/gui/plot3d/tools/ViewpointTools.py | ViewpointTools.py | py | 1,903 | python | en | code | 106 | github-code | 6 |
27002025081 | from work1_wangb import DataSampling_wangb
from work2_wangb import foo_wangb
from work3_wangb import weather_wangb
def show():
print(u"请输入数字abc来选择查看作业1~3,输入字母d退出程序")
while True:
try:
x = str(input())
if x == 'a':
DataSampling_wangb.show()
e... | wanghan79/2023_Python | python_wangb/theLastwork_wangb.py | theLastwork_wangb.py | py | 717 | python | en | code | 8 | github-code | 6 |
14431348416 | from concurrent import futures
import threading
words = ['hello', 'world']
result = []
def letter_by_letter(my_word):
for letter in my_word:
# proof that we are using 2 threads
print(threading.current_thread().getName())
result.append(letter)
# thanks to `with`, script will wait until a... | cuZzior/python-multithreading-helloworld | hello_world.py | hello_world.py | py | 498 | python | en | code | 0 | github-code | 6 |
42156059489 | import pytest
import responses
from repositories.app import APP
@pytest.fixture
def client():
with APP.test_client() as client:
APP.extensions["cache"].clear()
yield client
@responses.activate
def test_get_repo(client):
url = f"https://api.github.com/repos/owner/repo"
response = {
... | lukaszmenc/get-repository-data | tests/test_app.py | test_app.py | py | 1,667 | python | en | code | 0 | github-code | 6 |
23850509915 | from datasets import load_dataset,load_metric
from transformers import AutoTokenizer,AutoModelForSeq2SeqLM,Seq2SeqTrainingArguments,DataCollatorForSeq2Seq,Seq2SeqTrainer
import numpy as np
metric=load_metric("BLEU.py")
max_input_length = 64
max_target_length = 64
src_lang = "zh"
tag_lang = "en"
model_path = "... | Scpjoker/NLP-Course-Homework-2022 | translate.py | translate.py | py | 2,866 | python | en | code | 1 | github-code | 6 |
3709328599 | import os
from cloudservice import add_file, add_dir, get_dir_subs, get_root_dir_id
from pathlib import Path
import pandas as pd
def test():
uploadfile(os.path.join('我文件夹', 'test1.docx'), dirid=39, projid=36)
print()
def create_dir_test():
add_dir('addsub', 39, 36)
def uploadfile(fpath, dirid, projid)... | pengyang486868/PY-read-Document | batch_upload.py | batch_upload.py | py | 3,549 | python | en | code | 0 | github-code | 6 |
31108358568 | import tushare as ts
import pandas as pd
#当列太多时,显示不换行
pd.set_option('expand_frame_repr',False)
#显示所有的列
pd.set_option('display.max_columns', None)
'''
Created on 2020年12月24日
@author: My
'''
ts.set_token('b869861b624139897d87db589b6782ca0313e0e9378b2dd73a4baff5')
pro=ts.pro_api()
#data = pro.stock_basic(exchange=''... | geekzhp/zhpLiangHua | tmp/tushareStudy.py | tushareStudy.py | py | 1,356 | python | en | code | 0 | github-code | 6 |
41969655941 | import cv2 as cv
src = cv.imread("./img_input/266679.png") #读取图片
# 新建一个窗口并展示
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
cv.waitKey(0)
cv.destroyAllWindows()
print("hello") | RMVision/study-opencv | chapter01/test.py | test.py | py | 237 | python | zh | code | 1 | github-code | 6 |
75226774588 | import logging
from kiteconnect import KiteConnect
import datetime
import pymongo
instrument_token = "738561"
from_date = "2021-04-01"
to_date = "2021-06-30"
interval = '5minute'
logging.basicConfig(level=logging.DEBUG)
api_key = "kpgos7e4vbsaam5x"
api_secret = "t9092opsldr1huxk1bgopmitovurftto"
reque... | prashanth470/trading | source/sample.py | sample.py | py | 1,284 | python | en | code | 0 | github-code | 6 |
34572128931 | import random,server,time,istatistik,settings
import sqlite3 as sql
server_list=server.Server()
patlayan_power=6.5;kartopu_power=7;oyuk_power=2
_35power=10;_25power=9;_15power=5
def randomplayer():
global first,two
while True:
first=random.choice(server_list)
two=random.choice(server_li... | zeminkat/Game | savas.py | savas.py | py | 11,157 | python | en | code | 0 | github-code | 6 |
71174596349 | from __future__ import unicode_literals
import re
import os
import io
import sys
PY3 = sys.version_info.major > 2
try:
from urllib.parse import quote # py3
from urllib.request import urlopen
from urllib.error import HTTPError, URLError
except ImportError: # py2
from urllib import quote
from urllib2... | jwdj/EasyABC | tune_elements.py | tune_elements.py | py | 58,593 | python | en | code | 67 | github-code | 6 |
23748260373 | import os
import sys
from functools import partial
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from toolBar import ToolBar
from Canvas.canvas import Canvas
import cv2
import numpy as np
from grab_cut import Grab_cut
from choiceDiaGen import ChoiceDiaGen
from choiceDiaStyle imp... | kisstherain8677/Image_generate | app.py | app.py | py | 19,181 | python | en | code | 3 | github-code | 6 |
20463208050 | from collections import defaultdict
d = defaultdict(int)
n = int(input())
for _ in range(n):
d[input()] += 1
allwords = list(d)
allwords_str = d.values()
listofx = []
for x in allwords_str:
listofx.append(str(x))
print(len(allwords))
print(" ".join(listofx))
# This line is the same as the above block > print(... | Ronen-EDH/Code-exercises | Python/Hackerrank/Hackrank_wordorder.py | Hackrank_wordorder.py | py | 361 | python | en | code | 0 | github-code | 6 |
16098965612 | from django.urls import path
from card import views
urlpatterns = [
path('create/', views.CreateFlashCardView.as_view(), name="create-flash-card"),
path('update/<id>/', views.UpdateFlashCardView.as_view(), name="update-flash-card"),
path('dalete/<id>/', views.DeleteFlashCardView.as_view(), name="delete-fl... | leonardo0231/flash-card | card/urls.py | urls.py | py | 428 | python | en | code | 0 | github-code | 6 |
70398650747 | """utilities for generation of CTRMs
Author: Keisuke Okumura
Affiliation: TokyoTech & OSX
"""
from __future__ import annotations
import numpy as np
from numba import f8, jit
from ..environment import Instance
from ..roadmap import TimedNode, TimedRoadmap
from ..roadmap.utils import valid_move
@jit(f8[:](f8[:, :], ... | omron-sinicx/ctrm | src/ctrm/roadmap_learned/utils.py | utils.py | py | 5,210 | python | en | code | 21 | github-code | 6 |
29821357591 | import docker
class MicroDockerClient:
def __init__(self, micro_configuration):
self.client = docker.from_env()
self.config = micro_configuration
def pull(self):
self.client.images.pull(self.config.image_name)
def run(self):
self.client.containers.run(
self.confi... | alichamouda/micro-cd | micro_docker_client.py | micro_docker_client.py | py | 713 | python | en | code | 0 | github-code | 6 |
72474543549 | import Accelerometer
import ButtonControl
import RollPitch
import ParserSettings
# a parser for just one wii data
class oneWii :
def __init__(self):
self.accelerometer = Accelerometer.Accelerometer()
self.buttons = ButtonControl.ButtonControl()
self.rollPitch = RollPitch.RollPitch()
def __call__(self,ts,wid,... | cloew/WiiCanDoIt-Framework | src/ProtocolGame/wiis/onewii.py | onewii.py | py | 535 | python | en | code | 2 | github-code | 6 |
28663549378 | # Please develop your ingestion service in Python. You may select the delivery format (e.g., Jupyter
# Notebook, containerized microservice). For this exercise, you may assume that a scheduling service
# to regularly invoke your ingestion is provided.
# Where and how you process the data is at your discretion.
import ... | madelinepet/take_home_assignment | assignment.py | assignment.py | py | 7,586 | python | en | code | 0 | github-code | 6 |
2988023971 | import spoonacular as sp
api = sp.API("eaf1205e8c26404a8cda30c46c86f1cd")
def find_from_ingredients(ingredient_list):
#ranking = 2 means minimizing missing ingredients
recipe_list = api.search_recipes_by_ingredients(ingredients=ingredient_list, number=1, ranking=2)
return recipe_list
def get_recipe_nutrition(ingred... | emilyhua/hintofyum | nutrition.py | nutrition.py | py | 626 | python | en | code | 0 | github-code | 6 |
41798087631 | # Task 1 For a given integer n calculate the value which is equal to a:
# squared number, if its value is strictly positive;
# modulus of a number, if its value is strictly negative;
# zero, if the integer n is zero.
# Example: n=4 result= 16; n=-5 result= 5; n=0 result=0
n = float(input("Please, enter n for calculat... | natshabat/Nataliya_Shabat | epam_hw2_ShabatN.py | epam_hw2_ShabatN.py | py | 2,221 | python | en | code | 0 | github-code | 6 |
12483812629 | import numpy as np
import matplotlib.pyplot as plt
from scipy.constants import degree
from FallingCat import FallingCat
JI = 0.25
alpha = 30*degree
plt.figure(figsize=(5,7))
c = FallingCat(JI, alpha)
t = c.theta/degree
psi = c.lean()/degree
gamma = c.bend()/degree
phi = c.twist()/degree
print(phi[-1])
print((c.alpha... | tt-nakamura/cat | fig2.py | fig2.py | py | 660 | python | en | code | 0 | github-code | 6 |
73652393469 | # 给你一个字符串 s ,仅反转字符串中的所有元音字母,并返回结果字符串。
# 元音字母包括 'a'、'e'、'i'、'o'、'u',且可能以大小写两种形式出现。
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
Vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
s = list(s)
i = 0
j = l... | xxxxlc/leetcode | array/reverseVowels.py | reverseVowels.py | py | 834 | python | zh | code | 0 | github-code | 6 |
26664284885 | import json
import logging
import os
from http.client import HTTPConnection
from pathlib import Path
from typing import Dict, Any
from mmcc_framework import DictCallback, Framework
from mmcc_framework.nlu_adapters import NluAdapter
from tuning.mmcc_config.callbacks import my_callbacks
from tuning.types import Pipelin... | DEIB-GECO/DSBot | DSBot/tuning/mmcc_integration.py | mmcc_integration.py | py | 4,842 | python | en | code | 0 | github-code | 6 |
8918699138 | import sys
if __name__ == '__main__':
if len(sys.argv) == 1:
print("Usage: python {} [rom.ch8] >> [output.csv]".format(sys.argv[0]))
exit()
rom = sys.argv[-1]
bytes = bytearray()
with open(rom, 'rb') as r:
byte = r.read(1)
while byte != "":
bytes.ap... | FrancescoTerrosi/chip8emu | CHIP8/disassembler/disassemble.py | disassemble.py | py | 5,468 | python | en | code | 0 | github-code | 6 |
41675665840 | # 영역 구하기
import sys
sys.setrecursionlimit(100000000)
input = sys.stdin.readline
m, n, k = map(int, input().split())
# 종이
paper = [[0 for _ in range(n)] for _ in range(m)]
# 방문 처리
visited = [[False for _ in range(n)] for _ in range(m)]
res = []
# 종이에 색칠하기
for _ in range(k):
x1, y1, x2, y2 = map(int, input().s... | jisupark123/Python-Coding-Test | 알쓰/week1/2583.py | 2583.py | py | 1,313 | python | en | code | 1 | github-code | 6 |
34248836732 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
plt.style.use("bmh")
def exact(r1, r2, w):
return 2 * np.sqrt(w/np.pi) * np.exp(- w * (r1 * r1 + r2 * r2))
def fmt(x, pos):
a, b = '{:.1e}'.format(x).split('e')
b = int(b)
return r'${} \times 10^{{{}}}$'.format(... | evenmn/Master-thesis | scripts/plot_exact_tb.py | plot_exact_tb.py | py | 1,391 | python | en | code | 4 | github-code | 6 |
1904177195 | from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
import json, os
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=['*'],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get('/contents/{page_id}/{content_id}')
a... | tetla/knowledge-reader | backend/offdemy-api.py | offdemy-api.py | py | 1,203 | python | en | code | 0 | github-code | 6 |
33381013184 | from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.urls import path, include
from django.contrib.auth import views as auth_views
from polls.views import (
RegistrationView,
CreateBoardView,
BoardDetailView,
BoardDeleteView,
CreateList... | destinymalone/projectmanagement-capstone | mysite/urls.py | urls.py | py | 1,486 | python | en | code | 0 | github-code | 6 |
2665829226 | from heatSink import HeatSink
from waterPipes import WaterPipes
from solarPanel import SolarPanel
from system import System
import matplotlib.pyplot as plt
flow_rates = [0.00025, 0.0005, 0.001, 0.002, 0.003, 0.005]
panel_temp = []
no_pipes = []
inlet_temp = 30
for f in flow_rates:
temps = []
pipes = []
f... | southwelljake/HeatSinkModelling | src/comparePipes.py | comparePipes.py | py | 1,260 | python | en | code | 0 | github-code | 6 |
73400221629 | # Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/... | PolarisXQ/Polaris-NoteBook | source/conf.py | conf.py | py | 1,924 | python | en | code | 0 | github-code | 6 |
40070373372 | import boto3
import json
from tqdm import tqdm
dynamodb = boto3.resource('dynamodb',region_name='us-east-2')
table = dynamodb.Table('FSBP_tree')
print(table.creation_date_time)
'''
with open('/hdd/c3s/data/aws_data/breach_compilation-pw_tree_1000000.json') as f:
data = json.load(f)
with table.batch_writer() as bat... | lucy7li/compromised-credential-checking | perfomance_simulations/fsbp/save_amazon.py | save_amazon.py | py | 793 | python | en | code | 6 | github-code | 6 |
25814131906 | import errno
from flask import current_app, request, render_template
from flask.views import MethodView
from werkzeug.exceptions import Forbidden, NotFound
from ..constants import COMPLETE, FILENAME, LOCKED, TYPE
from ..utils.date_funcs import delete_if_lifetime_over
from ..utils.http import redirect_next_referrer
fr... | bepasty/bepasty-server | src/bepasty/views/modify.py | modify.py | py | 1,929 | python | en | code | 162 | github-code | 6 |
8778305417 | from flask_restful import Resource, reqparse
from flask_jwt import jwt_required, current_identity
from models.player import PlayerModel
from models.team import TeamModel
class Player(Resource):
parser = reqparse.RequestParser()
parser.add_argument(
'back_number',
type=int,
required=True... | baehs1989/flask-RESTful-project | resources/player.py | player.py | py | 3,467 | python | en | code | 0 | github-code | 6 |
29186498876 | import numpy
import multiprocessing as mp
import scipy.fftpack as fft
import scipy.signal as signal
import h5py
from .utilities import working_dir
from .stationbandpass import lofar_station_subband_bandpass
def fir_filter_coefficients(num_chan, num_taps, cal_factor=1./50.0):
'''
Compute FIR filter coefficient... | brentjens/software-correlator | softwarecorrelator/stationprocessing.py | stationprocessing.py | py | 11,844 | python | en | code | 4 | github-code | 6 |
25816673887 | # Write a program to convert decimal number to equivalent binary, octal, and hexadecimal numbers.
def binary(num):
b=''
while num:
r=num%2
b+=str(r)
num=num// 2
return b[::-1]
def octal(num):
x=''
while num:
r=num%8
x=x+str(r)
num=num//8
return ... | asteekgoswami/5th-sem-python | assignment-4/Q4.py | Q4.py | py | 723 | python | en | code | 0 | github-code | 6 |
24168209609 | #!/usr/bin/env python
'''
summarise slurm job details
Usage: summarise.py --files slurm-*.log > summary.tsv
Time is in hours.
Memory is in GB.
'''
#(venv_somatic_2) spartan-login1 18:48:20 msi-evaluation$ sacct -j 18860471 --format="JobName,CPUTime,MaxRSS,Elapsed,MaxVMSize,Timelimit"
# JobName CPUTime ... | supernifty/slurm_util | summarise.py | summarise.py | py | 2,901 | python | en | code | 0 | github-code | 6 |
22682272557 | # -*- coding: utf-8 -*-
"""
Created on Wed May 12 04:34:12 2021
@author: Zakaria
"""
import pandas as pd
data = pd.read_csv('prediction_de_fraud_2.csv')
caracteristiques = data.drop('isFraud', axis=1).values
cible = data['isFraud'].values
from sklearn.preprocessing import LabelEncoder
LabEncdr_X... | Baxx95/6-10-Programmes-Data-Science-SL-Random_Forest_Classifier | Random_Forest_Classifier.py | Random_Forest_Classifier.py | py | 961 | python | en | code | 0 | github-code | 6 |
42549531170 | ### This file has been adopted from
### https://github.com/openlawlibrary/pygls/blob/master/examples/json-extension/server/server.py
import asyncio
from bisect import bisect
from cromwell_tools import api as cromwell_api
from cromwell_tools.cromwell_auth import CromwellAuth
from cromwell_tools.utilities import downlo... | broadinstitute/wdl-ide | server/wdl_lsp/server.py | server.py | py | 17,170 | python | en | code | 38 | github-code | 6 |
7796988085 | import xml.dom.minidom
import string;
import logging;
def LoadSession(system, FileName):
Logger = logging.getLogger("PPLT");
Logger.debug("Try to load Session from %s"%FileName);
doc = xml.dom.minidom.parse(FileName);
dev_tag = doc.getElementsByTagName("Devices")[0];
sym_tag = doc.getElementsByTag... | BackupTheBerlios/pplt-svn | PPLT/PPLT/LoadSession.py | LoadSession.py | py | 2,939 | python | en | code | 0 | github-code | 6 |
34038204278 | from aio_proxy.response.formatters.elus import format_elus
from aio_proxy.response.unite_legale_model import CollectiviteTerritoriale
def format_collectivite_territoriale(
colter_code=None,
colter_code_insee=None,
colter_elus=None,
colter_niveau=None,
):
if colter_code is None:
return None... | etalab/annuaire-entreprises-search-api | aio/aio-proxy/aio_proxy/response/formatters/collectivite_territoriale.py | collectivite_territoriale.py | py | 565 | python | it | code | 13 | github-code | 6 |
20927340765 | import tensorflow as tf
from architecture import eda_net
MOVING_AVERAGE_DECAY = 0.995
IGNORE_LABEL = 255
def model_fn(features, labels, mode, params):
"""
This is a function for creating a computational tensorflow graph.
The function is in format required by tf.estimator.
"""
is_training = mode... | TropComplique/EDANet | model.py | model.py | py | 6,023 | python | en | code | 2 | github-code | 6 |
3019297917 |
def getBestCand(candidates,visited):
bestIndex = -1
cost = 0x3f3f3f
for i in range(len(visited)):
if not visited[i] and candidates[i] < cost:
cost = candidates[i]
bestIndex = i
return bestIndex,cost
def bfs(g):
n = len(g)
visited = [False] * n
candidates ... | medranoGG/AlgorithmsPython | test01/bisbal.py | bisbal.py | py | 1,252 | python | en | code | 0 | github-code | 6 |
19511071794 | import random
def magic_ball() -> str:
"""
Ask this crabby Magic 8 Ball a question out loud
and run to see the answer.
:return: `str`, a random answer.
"""
# Possible responses that the Magic 8 Ball can give
responses = ["Don't ask me!", "Next question, loser.",
"Go away... | CrochetGamer/small-projects | magic_8_ball.py | magic_8_ball.py | py | 1,440 | python | en | code | 0 | github-code | 6 |
40310342893 | import time
import random
import pandas as pd
import multiprocessing as mp
import numpy as np
import os
import torch
import torch.nn.functional as F
import copy
from .utils import strToListF
from .models import makeDataSet_Vec
from .utils import strToListF, colorizar, getSTime
# models
from .drlearning import Agent... | mjason98/haha21 | code/protos.py | protos.py | py | 20,732 | python | en | code | 0 | github-code | 6 |
13610828545 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import taggit.managers
class Migration(migrations.Migration):
dependencies = [
('taggit', '0001_initial'),
('learn', '0003_project_photo'),
]
operations = [
migrations.Create... | klebercode/sofia | sofia/apps/learn/migrations/0004_auto_20141215_1723.py | 0004_auto_20141215_1723.py | py | 1,769 | python | en | code | 0 | github-code | 6 |
1922022592 | from sklearn import preprocessing
import pandas as pd
import numpy as np
import pickle
data_path = './data/STT.csv'
window = 15
def normalize(df):
min_max_scaler = preprocessing.MinMaxScaler()
df['open'] = min_max_scaler.fit_transform(df.open.values.reshape(-1, 1))
df['close'] = min_max_scaler.fit_transf... | sinlin0908/ML_course | hw4/prepro.py | prepro.py | py | 1,925 | python | en | code | 0 | github-code | 6 |
8677677831 | import xarray as xr
import xesmf as xe
import pandas as pd
import datetime
import os
first_date = '2021-01-01'
last_date = '2022-12-31'
lonmin,lonmax = 360-90,360-69
latmin,latmax = -40,-15
variables = [
'surf_el',
'water_temp',
'salinity',
'water_u',
'water_v']
renamedict = {'surf_el':'zos',
... | lucasglasner/DOWNLOADSCRIPTS | HYCOM/download_hycom_hindcast.py | download_hycom_hindcast.py | py | 2,754 | python | en | code | 0 | github-code | 6 |
29099471877 | from openpyxl import load_workbook, Workbook
from openpyxl.formatting.rule import ColorScaleRule
from openpyxl.styles import PatternFill, Font
def _cal_writer_final_report(barcode, ws_report, all_data, init_row, init_col, report_output):
row_counter = init_row
ws_report.cell(column=-1 + init_col, row=row_co... | ZexiDilling/structure_search | report_setup.py | report_setup.py | py | 12,580 | python | en | code | 0 | github-code | 6 |
1526323654 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 3 11:13:08 2020
@author: jiaxinli
"""
import re
def readlines(filepath):
fd = open(filepath, 'r')
lines = []
for line in fd:
### Uncomment if needed to fileter things other that alphanum and $%
# line = re.sub(r"[... | jiaxinli980115/getting-job-description | find_time.py | find_time.py | py | 1,179 | python | en | code | 0 | github-code | 6 |
21645750883 | #Tutorial de Umbral OpenCV
import cv2
import numpy as np
img = cv2.imread('Pagina.jpg')
#Imagen a escala de grises
grayscaled = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#Umbral de 10
retval, threshold = cv2.threshold(img, 12, 255, cv2.THRESH_BINARY)
#Umbral en escala de grises
retval, threshold2 = cv2.threshold(grayscale... | Deniry/Practicas_OpenCV | Practica5.py | Practica5.py | py | 666 | python | en | code | 0 | github-code | 6 |
38785952057 | import cv2 as cv
import sys
img = cv.imread("Photos/cat_large.jpg")
print(img.shape)
cv.imshow("Cat", img)
def rescale(frame, scale=0.75):
width = frame.shape[1] * scale
height = frame.shape[0] * scale
dimensions = (int(width), int(height))
new_frame = cv.resize(frame, dimensions, interpolation=cv.... | adamferencz/opencv-course-ghb | rescale.py | rescale.py | py | 446 | python | en | code | 0 | github-code | 6 |
41584679238 | # 윈도우에서는 한글 인코딩 오류가 발생할 수 있습니다.
# 한글 인코딩 오류가 발생한다면
# Message.log(message_type="info", msg="데이터를 저장했습니다.")
# 위의 코드 부분의 msg를 영어로 수정해서 사용해주세요.
import json
import sys
from eliot import Message, start_action, to_file, write_traceback
import requests
# 로그 출력을 표준 출력으로 설정(터미널에 출력하기)
to_file(sys.stdout)
# 크롤링 대상... | JSJeong-me/2021-K-Digital-Training | Web_Crawling/python-crawler/chapter_5/sample_eliot.py | sample_eliot.py | py | 1,833 | python | ko | code | 7 | github-code | 6 |
24916898593 | import time
from datetime import datetime
from bluepy.btle import BTLEDisconnectError
from miband import miband
from ibmcloudant.cloudant_v1 import CloudantV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibmcloudant.cloudant_v1 import CloudantV1, Document
import os
from dotenv import load_dotenv
... | Rushour0/MSIT-The-New-Normal-Submission | WebVersions/web_v1/cloudant-module.py | cloudant-module.py | py | 2,911 | python | en | code | 1 | github-code | 6 |
6905801846 | """
Write a function count_letters(word_list) that takes as input a list of words that
are composed entirely of lower case letters . This function should return the lower
case letter that appears most frequently (total number of occurrences) in the words
in word_list. (In the case of ties, return the earliest letter in... | hqpiotr/learning-python | 2. Python - Rice/c3-dataAnalysis/week1/c3_w1_ex.py | c3_w1_ex.py | py | 1,251 | python | en | code | 0 | github-code | 6 |
74543338748 | '''Q5.
Write a Python program to sort (ascending and descending) a dictionary by value.
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
Dictionary in ascending order by value : [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}'''
d = {1: 2, 3: 4, ... | Jija-sarak/python_dictionary | q5.py | q5.py | py | 493 | python | en | code | 0 | github-code | 6 |
71082529787 | from classes.rayon import *
from classes.point import *
from classes.mur import *
from classes.base import *
from resources.const import *
from processing.diffraction import get_direction
from processing.transmission import get_theta_i, get_theta_t, get_s, get_reflexion_perpendiculaire
from math import pi as PI
from ma... | bjoukovs/PHYSRayTracing2017 | processing/reflexion.py | reflexion.py | py | 5,192 | python | en | code | 0 | github-code | 6 |
19218028573 | from rest_framework import serializers
from api.v1.auth.schemas import LanguageChoiceField, TimeZoneNameChoiceField
from users.models import User
class CurrentUserOutputSchema(serializers.ModelSerializer):
language_code = LanguageChoiceField()
time_zone = TimeZoneNameChoiceField()
class Meta:
mo... | plathanus-tech/django_boilerplate | src/api/v1/users/schemas.py | schemas.py | py | 591 | python | en | code | 2 | github-code | 6 |
40309032747 | from initdata import db
'''
Simple way to persist record. KEY==>VALUE in each line. EndRec. on a line for end of Record
and EndDb. for end of database.
'''
ENDREC='EndRec.'
ENDDB='EndDb.'
RECSEP='==>'
#file_name='people-file.txt'
file_name='people-file.txt'
print('2'+ __name__)
def writeDb(db, dbfname=file_name):
... | mathewjoy/testpython | programmingpython/make_db_file.py | make_db_file.py | py | 678 | python | en | code | 0 | github-code | 6 |
14321604555 | #calculate n^2 jaccard values and create companion of every file
import sys
import glob
import os
import shutil
if os.path.exists("modified_files"):
shutil.rmtree("modified_files")
os.mkdir("modified_files")
def extract(directory):
#looks at the sync folder , creates our own folder of exercises
files =... | AbhinavDutta/mini-moss | extract.py | extract.py | py | 2,490 | python | en | code | 0 | github-code | 6 |
26023690910 | import matplotlib.pyplot as plt
import numpy as np
x=np.arange(-10,10,0.01)
y=1/(np.sin(x)+2)
z=1/(np.cos(x)+2)
plt.plot(x,y,x,z) #生成在一张图像上
fig2,(axs1,axs2)=plt.subplots(2,1) #分配两个坐标轴并且按照(2,1)的形状
axs1.plot(x,y)
axs2.plot(x,z) #在两个轴上单独生成一次
plt.show(... | suanhaitech/pythonstudy2023 | Wangwenbin/Matplotlib1.py | Matplotlib1.py | py | 388 | python | en | code | 2 | github-code | 6 |
45017345126 | #!/usr/bin/env python3
#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
# DESCRIPTION:
#
# CALL SAMPLE:
# ~/data/solarity/sit-raspi/modbus/direct_marketing_interface.py --host_ip '192.168.0.34' --host_mac '00:90:E8:7B:76:9C' -v -t
#
# REQUIRE
#
#... | phgachoud/sty-pub-raspi-modbus-drivers | sma/direct_marketing_interface.py | direct_marketing_interface.py | py | 8,844 | python | en | code | 0 | github-code | 6 |
42597128032 | import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sklearn
df=pd.read_csv("insurance.csv")
tem=pd.get_dummies(df["region"])
df.drop("region",axis=1,inplace=True)
df=pd.concat([df,tem],axis=1)
print(df.head(10))
map={"yes":1,"no":0}
df["smoker"]=df["smo... | manav88/Medical-cost-prediction | med_cost.py | med_cost.py | py | 1,956 | python | en | code | 0 | github-code | 6 |
8670869554 | import numpy as np
from neuroglancer_interface.utils.rotation_utils import (
rotate_matrix)
def test_rotate_matrix():
rng = np.random.default_rng(665234)
base_arr = rng.random((5, 6, 7))
actual = rotate_matrix(
data=base_arr,
rotation_matrix = [[0, 0, 1],
[... | AllenInstitute/neuroglancer_formatting_scripts | tests/utils/test_rotation_utils.py | test_rotation_utils.py | py | 1,318 | python | en | code | 2 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.