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
71075554025
class Solution: def findShortestSubArray(self, nums: List[int]) -> int: count = Counter(nums) degree = max(count.values()) candidates = {} for n in count: if count[n] == degree: candidates[n] = [-1, -1] res = float('inf')...
nango94213/Leetcode-solution
697-degree-of-an-array/697-degree-of-an-array.py
697-degree-of-an-array.py
py
817
python
en
code
2
github-code
36
14992228919
from flask import Flask from flask import request from urllib.parse import urlencode import requests import json server = Flask(__name__) api_key = "AIzaSyAWtsz4ALYdHQJKRSeGv-invChqgL7tAFs" @server.route('/location') def location(): city_name = request.values.get('city-name') data_type = "json" endpoint = f"https:...
KJS89/Wuduplz
Web mining/final/locationList.py
locationList.py
py
1,190
python
en
code
2
github-code
36
22007463848
#!/usr/bin/env python3 import os import subprocess import sys def get_souffle_version(): lines = subprocess.check_output(['souffle', '--version']).decode().split('\n') line = ([l for l in lines if 'Version' in l] + lines)[0] version = line.split(': ')[1].replace('-', '.').replace('(64bit Domains)', '').split('.') ...
typro-type-propagation/TyPro-CFI
llvm-typro/lib/Typegraph/patch_souffle_datastructures.py
patch_souffle_datastructures.py
py
1,497
python
en
code
3
github-code
36
37636175480
# 861. Score After Flipping Matrix # Medium # 333 # 88 # Favorite # Share # We have a two dimensional matrix A where each value is 0 or 1. # A move consists of choosing any row or column, and toggling each value in that row or column: changing all 0s to 1s, and all 1s to 0s. # After making any number of moves, ev...
sunnyyeti/Leetcode-solutions
861_Score_After_Flipping_Matrix.py
861_Score_After_Flipping_Matrix.py
py
1,317
python
en
code
0
github-code
36
43303443334
#! /usr/bin/env python import colorsys def hsv2ansi(h, s, v): # h: 0..1, s/v: 0..1 if s < 0.1: return int(v * 23) + 232 r, g, b = map(lambda x: int(x * 5), colorsys.hsv_to_rgb(h, s, v)) return 16 + (r * 36) + (g * 6) + b def ramp_idx(i, num): assert num > 0 i0 = float(i) / num h = ...
mozillazg/pypy
rpython/tool/ansiramp.py
ansiramp.py
py
742
python
en
code
430
github-code
36
19655830809
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on 03/03/2021 @author: phongdk """ import os from datetime import datetime import icecream DATA_DIR = os.getenv('DATA_DIR', '/shared_storage/bi_mlearn_training/coccoc_shopping') DATA_FILENAME = f'{DATA_DIR}/data/shopee_sample.pkl' DOC2VEC_FILENAME = f"{DATA_D...
phongdk92/shopping_retrieval
src/config.py
config.py
py
1,703
python
en
code
0
github-code
36
953778032
pkgname = "libxxf86misc" pkgver = "1.0.4" pkgrel = 0 build_style = "gnu_configure" configure_args = ["--enable-malloc0returnsnull"] hostmakedepends = ["pkgconf"] makedepends = ["xorgproto", "libxext-devel", "libx11-devel"] pkgdesc = "XFree86-Misc X extension library" maintainer = "q66 <q66@chimera-linux.org>" license =...
chimera-linux/cports
main/libxxf86misc/template.py
template.py
py
668
python
en
code
119
github-code
36
36121027603
import logging import sys import torch import yaml from tagging_trainer import TaggingTrainer from forte.common.configuration import Config logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) if __name__ == "__main__": task = sys.argv[1] assert task in ["ner", "pos"], "Not supported...
asyml/forte
examples/tagging/main_train_tagging.py
main_train_tagging.py
py
1,785
python
en
code
230
github-code
36
2412656493
from karp5.server import searching from karp5.tests.util import get_json def test_autocomplete_with_q(client_w_panacea): result = get_json(client_w_panacea, "autocomplete?q=sig") assert result["hits"]["total"] == 0 # https://ws.spraakbanken.gu.se/ws/karp/v5/autocomplete?multi=kasta,docka&resource=saldom&...
spraakbanken/karp-backend-v5
karp5/tests/integration_tests/server/test_searching_integration.py
test_searching_integration.py
py
9,519
python
en
code
4
github-code
36
30838795713
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 11 18:11:32 2021 @author: mathisagathe """ from pymongo import MongoClient import matplotlib.pyplot as plt client = MongoClient("10.35.7.4", username = "mathis", password = "MathisM21", authsource = "mathisdb") db=client.mathisdb collection = d...
romanelollier/School_Project_BigData
requetes_mod.py
requetes_mod.py
py
1,536
python
fr
code
0
github-code
36
33406629366
""" Main Neural Network Pipeline. """ #-------------------------- set gpu using tf ---------------------------# import tensorflow as tf config = tf.ConfigProto() config.gpu_options.allow_growth = True session = tf.Session(config=config) #------------------- start importing keras module ---------------------# from ke...
ghunkins/Binaural-Source-Localization-CNN
Neural_Net/v3/neuralnet.py
neuralnet.py
py
2,940
python
en
code
9
github-code
36
42831133132
#!/usr/bin/env python3 import struct import json import sys def write_tileset(filename, spec): with open(spec['base'], 'rb') as src: base_data = src.read() with open(spec['overlay'], 'rb') as src: overlay_data = src.read() if 'cc2' in spec: with open(spec['cc2'], 'rb') as src: ...
zrax/cctools
res/gen_tilesets.py
gen_tilesets.py
py
1,323
python
en
code
18
github-code
36
21885184448
""" Device discovery """ import enum import re from dataclasses import asdict, dataclass from queue import Empty, Queue from socket import inet_ntoa from typing import Dict, Generator, List, Optional import click import requests import usb from zeroconf import ServiceBrowser, ServiceInfo, ServiceStateChange, Zeroconf...
BrewBlox/brewblox-ctl
brewblox_ctl/discovery.py
discovery.py
py
7,942
python
en
code
3
github-code
36
74508033382
#!/bin/python3 import sys n = int(input().strip()) for i in range(n): line = "" for j in range(n): if j < (n - i - 1): line = line + " " else: line = line + "#" print(line)
costincaraivan/hackerrank
algorithms/warmup/python3/staircase.py
staircase.py
py
237
python
en
code
1
github-code
36
75009815143
import asyncio import logging from random import randint from src.streaming import Consumer, Producer, Topic LOGGER = logging.getLogger(__name__) GROUP_ID = "WEBSITE_NER" async def amain(): """Consume website changes, produce NER results.""" consumer = await Consumer.create(Topic.CHANGE.value, group_id=G...
SebastianRemander/eda-demo
src/producers/website_ner.py
website_ner.py
py
1,060
python
en
code
1
github-code
36
23297663163
import pathlib import pandas as pd from model import dez datadir = pathlib.Path(__file__).parents[0].joinpath('data') def test_populate_solution_land_distribution(): expected = pd.read_csv(datadir.joinpath('lbt_ocean_dist.csv'), index_col=0) de = dez.DEZ('Limiting bottom trawling') # We freeze applicabl...
ProjectDrawdown/solutions
model/tests/test_dez.py
test_dez.py
py
634
python
en
code
203
github-code
36
39433044372
from html.parser import HTMLParser from urllib.error import HTTPError import urllib.request from urllib.request import urlopen from urllib import parse import sys import pandas as pd url = 'https://www.yapo.cl/chile/autos?ca=5_s&l=0&st=s&br=68&mo=36' url_2 = 'https://www.chileautos.cl/autos/busqueda?s={:d}&q=(C.Marc...
simontorres/experimentos
depreciacion_autos/webcrawl.py
webcrawl.py
py
6,480
python
en
code
0
github-code
36
9817120997
import itertools import os import pandas as pd import pickle import random import torch from torchvision import datasets from tqdm import tqdm from scipy import rand import data_handler from models import AlexNet, Vgg16 def generate_model_testset_results(model, testset_path): """ Evaluate whole 'imagenetv2-m...
tlabarta/helpfulnessofxai
experiment_creator.py
experiment_creator.py
py
7,853
python
en
code
0
github-code
36
37452044980
import os, sys, subprocess, time def CAPTURE(cmd): return subprocess.run(f'{cmd}', shell=True, capture_output=True).stdout.decode('utf-8').strip(' \n') # capture & format terminal output def SBATCH(job_id, partition, nodes, ntasks, memory, walltime, out_err, task=None, email=None, conda_env=None): labels = ['job...
mattheatley/sra_download
core.py
core.py
py
4,087
python
en
code
0
github-code
36
22996305248
class Solution: def findTilt(self, root): if root is None: return 0 result = 0 queue = [root] while len(queue): node = queue.pop() if node.left is None: a = 0 else: a = self.bfs_sum(node.left) ...
xmu-ggx/leetcode
563.py
563.py
py
923
python
en
code
0
github-code
36
26672929841
#!/usr/bin/env python import argparse import itertools import pandas as pd def getCmdArgs(): p = argparse.ArgumentParser(description="Add scenes in neighboring rows of scenes in a given scene ID list.") p.add_argument("-l", "--list", dest="scn_list", required=True, default=None, metavar="CSV_OF_SCENE_LIST",...
zhanlilz/landsat-tools
landsat-albedo-pipeline/buffer_scene_list.py
buffer_scene_list.py
py
3,074
python
en
code
3
github-code
36
32453645847
from tkinter import * import re import ast class ResizingCanvas(Canvas): """ Class for making dynamic resizing for the text window we are using. Example usage: root = Tk() txt_panel = Text(root) txt_panel.pack(fill=BOTH, expand=YES) ResizingCanvas(txt_panel, width=850, hei...
BrickText/BrickTextExperimental
autocomplete.py
autocomplete.py
py
4,453
python
en
code
0
github-code
36
73368915303
from __future__ import print_function import numpy as np np.random.seed(1337) from itertools import product from sklearn import cluster from sklearn.externals import joblib from keras.datasets import mnist from sklearn.neighbors import KNeighborsClassifier from scipy.misc import imresize from keras.utils import np_util...
jmendozais/lung-nodule-detection
bovw.py
bovw.py
py
12,019
python
en
code
11
github-code
36
75127774184
import sys from cravat import BaseAnnotator from cravat import InvalidData import sqlite3 import os class CravatAnnotator(BaseAnnotator): def setup(self): self.cursor.execute('select distinct chr from omim where chr not null;') if hasattr(self, 'supported_chroms'): self.supp...
KarchinLab/open-cravat-modules-karchinlab
annotators/omim/omim.py
omim.py
py
1,137
python
en
code
1
github-code
36
1904857127
from scipy import linalg import numpy as np import scipy.optimize as sopt import matplotlib.pyplot as plt from scipy.optimize import fsolve from scipy.optimize import LinearConstraint from matplotlib import cm import tabulate import math START_POINT = [2,2] # fun - main muction def fun(x: np.ndarray) -> np.float64: ...
BON4/FuncOptimization
constarint_optimization.py
constarint_optimization.py
py
6,464
python
en
code
0
github-code
36
23006702098
import torch import numpy as np from torch._C import dtype from torch import nn from torch.nn import functional as F from torchvision import transforms from torchvision.transforms import functional as TF class ImageAugmentation(): def __init__(self): super().__init__() """ PepperSaltNoise ...
xmu-xiaoma666/SDATR
models/augmentation.py
augmentation.py
py
6,969
python
en
code
18
github-code
36
15744632677
import multiprocessing import optparse import os import re from error import InvalidProjectGroupsError from error import NoSuchProjectError from error import RepoExitError from event_log import EventLog import progress # Are we generating man-pages? GENERATE_MANPAGES = os.environ.get("_REPO_GENERATE_MANPAGES_") == "...
GerritCodeReview/git-repo
command.py
command.py
py
17,769
python
en
code
267
github-code
36
74953743465
"""Unit tests for the config module.""" import os import pytest from wmtmetadata.config import Config, ConfigFromFile, ConfigFromHost from wmtmetadata.host import HostInfo from . import data_dir tmp_dir = '/tmp' sample_config_file = os.path.join(data_dir, 'wmt-config-siwenna.yaml') host = 'siwenna.colorado.edu' name...
csdms/wmt-metadata
wmtmetadata/tests/test_config.py
test_config.py
py
1,593
python
en
code
0
github-code
36
17541630757
import glob import os import random import shutil import numpy as np import torch import torch.nn as nn import torchvision.transforms.v2 as T def set_seed(seed: int = 42): """Sets the seed for reproducibility.""" random.seed(seed) np.random.seed(seed) os.environ["PYTHONHASHSEED"] = str(seed) torc...
xkurozaru/fewshot-finetune-domain-adaptation
common/utils.py
utils.py
py
1,761
python
en
code
0
github-code
36
27414823832
import logging import os from copy import deepcopy from harmony.util import shortened_id from harmony.repository_state import RepositoryState logger = logging.getLogger(__name__) def commit(local_location_id, working_directory, location_states, repository_state): """ Scan the given working directory for cha...
Droggelbecher/harmony
harmony/file_state_logic.py
file_state_logic.py
py
9,182
python
en
code
0
github-code
36
74273514024
import numpy as np import jax from jax import lax, random, numpy as jnp import flax from flax.core import freeze, unfreeze from flax import linen as nn from flax import optim from typing import Any, Callable, Sequence, Optional import pickle from tensorflow import keras file_prefix = "struct" activation = nn.relu...
mselezniova/ntk_beyond_limit
ntk_train_dynamics.py
ntk_train_dynamics.py
py
5,198
python
en
code
0
github-code
36
36955110589
import wttest from wiredtiger import stat from wtscenario import make_scenarios # Test compact behaviour with overflow values. class test_compact03(wttest.WiredTigerTestCase): uri='table:test_compact03' fileConfig = [ ('1KB', dict(fileConfig='allocation_size=1KB,leaf_page_max=1KB')), ('4KB', ...
mongodb/mongo
src/third_party/wiredtiger/test/suite/test_compact03.py
test_compact03.py
py
7,278
python
en
code
24,670
github-code
36
34385049617
""" Code for computing SW distances between PDs [1]_ of point cloud summaries of activations Notes ----- Relevant section : Experiments with PH Relevant library : `Persim` [2]_ References ---------- .. [1] Carrière, M.; Cuturi, M.; and Oudot, S. 2017. Sliced Wasserstein Kernel for Persistence Diagrams. In Precup...
pnnl/DeepDataProfiler
papers_with_code/ExperimentalObservations/AAAI-code-PH/SW_distances.py
SW_distances.py
py
4,209
python
en
code
20
github-code
36
19483517480
''' 函数说明: Author: hongqing Date: 2021-08-04 14:23:54 LastEditTime: 2021-08-04 15:23:25 ''' import torch import torch.nn as nn import torch.nn.functional as F import numpy as np numoffinger=21 class Net(nn.Module): def __init__(self,type=1): super(Net, self).__init__() self.fc1 = nn.Linear(numoffing...
KouseiHongqing/KouseiPose
mymodel.py
mymodel.py
py
1,095
python
en
code
0
github-code
36
42157253168
"""empty message Revision ID: c4665b8d682b Revises: 10dbb0e0a903 Create Date: 2019-12-26 14:38:11.609539 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'c4665b8d682b' down_revision = '10dbb0e0a903' branch_labels = None depends_on = None def upgrade(): # ...
FeelingsLw/flask_demo2
migrations/versions/c4665b8d682b_.py
c4665b8d682b_.py
py
646
python
en
code
0
github-code
36
16879280056
import requests import json import urllib3 from settings import settings as settings from sdwan_operations import monitor as sdwanmn import time import sys, getopt urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) def main(argv): # To run the program use the syntax: # python __main__.py -d <...
stantiku/sdwan_monitor
__main__.py
__main__.py
py
2,117
python
en
code
0
github-code
36
43114992788
""" The codes are heavily borrowed from NeuS """ import os import cv2 as cv import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import logging import mcubes from icecream import ic from models.render_utils import sample_pdf from models.projector import Projector from tsparse.torchspa...
One-2-3-45/One-2-3-45
reconstruction/models/sparse_neus_renderer.py
sparse_neus_renderer.py
py
44,709
python
en
code
1,164
github-code
36
5058919782
from django.db import models # Create your models here. class Meal(models.Model): menu = models.TextField(blank=True) def __str__(self): return self.menu class MealList(models.Model): date = models.DateField(blank=True) breakfast = models.ForeignKey( Meal, blank=True, ...
KaceTH/django_api-0.00.90
MealTable/models.py
models.py
py
1,139
python
en
code
0
github-code
36
74486754983
def is_prime(num): if(num>1): for i in range(2,num): if((num % i) != 0): #number is prime return 1 else: return 0 #driver code num= int(input("\n Enter the positive number: ")) print(is_prime(num)) if(num==1): prin...
Charut24/Programming-Paradigms-
Lab Assignment 4_3.py
Lab Assignment 4_3.py
py
490
python
en
code
0
github-code
36
16098373063
#!/usr/bin/env python """Notepad-- : A very simple text editor.""" import sys if sys.version_info < (3,): import Tkinter as tk import tkFileDialog as filedialog else: import tkinter as tk from tkinter import filedialog def create_gui(root): """Set up the GUI and functionality.""" root.title("N...
jgat/notepad--
notepad--.py
notepad--.py
py
1,143
python
en
code
1
github-code
36
35090835676
#!/usr/bin/python ###################################################################################### ## Find disk usage under a root directory, examples: ## 1. python du_rootdir.py -d rootDir ## Find disk usage under the root directory "rootDir" ## 2. python du_rootdir.py -d rootDir -r true ## Find di...
zhichang-guo/Scripts
du_rootdir.py
du_rootdir.py
py
2,785
python
en
code
0
github-code
36
7595057258
from os import path from subprocess import check_output, check_call from pathlib import Path def _filename(fname): import yapl yapl_root = Path(yapl.__file__).parent filename = fname + ".sh" full_filename = yapl_root / filename return str(full_filename) def func(fname, *args): shell_script = _...
padresmurfa/yapl
python_library/yapl/internal/shell_call.py
shell_call.py
py
613
python
en
code
0
github-code
36
4758110469
import os, random import numpy as np import torch import argparse from train import train def init_seeds(seed=0): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) def parsing_args(c): parser = argparse.ArgumentParser(...
cool-xuan/msflow
main.py
main.py
py
2,580
python
en
code
15
github-code
36
73202366184
import os, sys from langchain.llms import OpenAI from langchain.chains.question_answering import load_qa_chain from langchain.embeddings.openai import OpenAIEmbeddings from langchain.vectorstores import FAISS prefix, query = sys.argv[1:3] api_key = os.environ.get('OPENAI_API_KEY') if api_key is None: sys.exit("O...
d2jvkpn/x-ai
pkg/langchain/langchain_query.py
langchain_query.py
py
833
python
en
code
0
github-code
36
9008219006
print('Задача 1. Результаты') import os import random # Одному программисту дали задачу для обработки неких результатов тестирования # двух групп людей. Файл первой группы (group_1.txt) находится в папке task, # файл второй группы (group_2.txt) — в папке Additional_info. # На экран нужно было вывести сумму очков пер...
SertFly/Python_Basic_Training
Module_22 (Module_9)/Task_9_3_1.py
Task_9_3_1.py
py
1,562
python
ru
code
0
github-code
36
34620661332
from turtle import Turtle import random COLORS = ["red", "orange", "yellow", "green", "blue", "purple"] BORDER = "black" STARTING_MOVE_DISTANCE = 5 MOVE_INCREMENT = 5 class CarManager: def __init__(self): self.all_cars = [] self.initial_speed = STARTING_MOVE_DISTANCE def createCar(self): ...
bose-aritra2003/Turtle-Crossing
car_manager.py
car_manager.py
py
1,226
python
en
code
1
github-code
36
26546120550
# Пример кода 1. Файл test_add_house #Асбстрактный сервис по созданию сущности дома и квартир в нем (для ТСЖ) from model.new_house import New_house from model.rooms import Rooms import time def test_add_house(app): app.new_house.fill_info(New_house(district="Железнодорожный", street="Тестовая", house_number=...
NickVolzh/tasks2
task_review_service.py
task_review_service.py
py
1,415
python
ru
code
0
github-code
36
74731484265
import torch from torch.optim.optimizer import Optimizer class COCOB(Optimizer): r"""Implements COCOB algorithm. It has been proposed in `Training Deep Networks without Learning Rates Through Coin Betting`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining ...
bremen79/parameterfree
parameterfree/cocob.py
cocob.py
py
4,274
python
en
code
73
github-code
36
26246312144
import serial from sense_hat import SenseHat from socket import gethostname from xbee import XBee from statistics import median def clear_matrix(): sense.clear() def show_hostname(): hostname = gethostname() sense.show_message("Hostname: " + hostname) def receive_data(data): print("received data: ", ...
tristndev/UzL_DSN
Tutorial 4/ex04_01_RSSI_to_distance.py
ex04_01_RSSI_to_distance.py
py
4,390
python
en
code
1
github-code
36
11624227934
import re import sys from napalm import get_network_driver from getpass import getpass def pretty_print(d, indent=0): for key, value in d.items(): print('\t' * indent + str(key)) if isinstance(value, dict): pretty_print(value, indent+1) elif isinstance(value, list): ...
pkomissarov/cisco-parsers
parsecfg.py
parsecfg.py
py
3,480
python
en
code
0
github-code
36
73157619305
from distutils.core import setup from os.path import isdir from itertools import product all_packages = ['airborne_car_simulator'] packages = list(filter(isdir, all_packages)) setup( name='ese615', packages=packages, version='0.1', install_requires=[ 'pyyaml', 'opencv-python', ...
ngurnard/f1tenth_pitch_control
simulator/airborne_car_simulator/setup.py
setup.py
py
398
python
en
code
0
github-code
36
16015771292
import heapq from sys import stdin n = int(stdin.readline()) # print(f'n: {n}') arr = list(map(int,stdin.readline().split())) # print(f'arr: {arr}') heap, answer = [], 0 for _ in range(n): num = arr[_] # print(f'num: {num}') heapq.heappush(heap, num) # print(f'heap: {heap}') # print(len(heap)) # if len(hea...
HiImConan/algorithm-study
백준/Silver/14241. 슬라임 합치기/슬라임 합치기.py
슬라임 합치기.py
py
518
python
en
code
0
github-code
36
26825630541
#!/usr/bin/python import numpy as np import matplotlib.pyplot as plt import argparse, os, sys, glob, time from tqdm import tqdm from skimage.transform import resize import cPickle from keras.layers import average from keras.models import load_model, Model from training_utils import scale_data, compute_time_series im...
DominicL3/hey-aliens
simulateFRBclassification/predict.py
predict.py
py
13,210
python
en
code
6
github-code
36
1313517117
from __future__ import print_function import argparse import keras from data_utils import load_data from sklearn.model_selection import train_test_split from model import vgg16 from hyperspace import hyperdrive num_classes = 10 batch_size = 32 epochs = 5 # The data, shuffled and split between train and test sets: ...
yngtodd/vgg_hyper
vgg_hyper/main.py
main.py
py
2,878
python
en
code
0
github-code
36
43102871488
import playment client = playment.Client("your-x-api-key-here") frames = [ "https://example.com/image_url_1", "https://example.com/image_url_2", "https://example.com/image_url_3" ] """ Create sensor_data variable """ sensor_data = playment.SensorData() """ Defining Sensor: Contain details of sensor :p...
crowdflux/playment-sdk-python
examples/video_job_creation.py
video_job_creation.py
py
2,037
python
en
code
0
github-code
36
31310132227
"""Extract KML data into DataFrame.""" from typing import Dict, Sequence, Union import numpy as np import pandas as pd from pykml import parser from pykml.factory import KML_ElementMaker as KML NS = {"t": "http://www.opengis.net/kml/2.2"} def read_kml(filepath: str) -> KML.kml: """Read a KML file. Param...
dankkom/kmldata
kmldata/parser.py
parser.py
py
6,224
python
en
code
0
github-code
36
40279875263
import math import random # random.seed(0.24975077935850032) # random.seed(0.0329938859085428) # print('Current seed - robustness', random.random()) """ position 19,30 could be avoided with areaSize parameter and fitness function Seed: 0.24975077935850032 This seed does a good job of exaggerating the difference between...
472mbah/path-finding
algorithms/automate/robustness.py
robustness.py
py
1,581
python
en
code
0
github-code
36
22660738512
# data_processing.py from shapely import wkb from shapely.geometry import shape import binascii import psycopg2 ewkb_data = None def get_variable_ewkb(): global ewkb_data print("variable ewkb") print(ewkb_data) return ewkb_data def process_for_view(data): global ewkb_data # Declare ewkb_da...
Fakhrynm/serverdatatrainingsitepython
Processdataview.py
Processdataview.py
py
1,054
python
en
code
0
github-code
36
7078437282
import os import base64 import argparse from cliff.command import Command from cliff.show import ShowOne from cliff.lister import Lister from meteoroid_cli.meteoroid.v1.client.function_client import FunctionClient from meteoroid_cli.meteoroid.v1.errors import CommandError from meteoroid_cli.meteoroid.v1.libs.decorator...
OkinawaOpenLaboratory/fiware-meteoroid-cli
meteoroid_cli/meteoroid/v1/function.py
function.py
py
7,858
python
en
code
5
github-code
36
1419102307
#!/usr/bin/env python # coding=utf-8 ''' Author: Yuxiang Yang Date: 2021-08-21 16:29:41 LastEditors: Yuxiang Yang LastEditTime: 2021-08-21 17:02:54 FilePath: /leetcode/剑指 Offer 60. n个骰子的点数.py Description: 把n个骰子扔在地上,所有骰子朝上一面的点数之和为s。输入n,打印出s的所有可能的值出现的概率。 假设n=1,和一共有6种,6=5*1+1 n=2, 和一共有11种(最小是2,最大是12),11=5*2+1 n=3, 和一共有16...
yangyuxiang1996/leetcode
剑指 Offer 60. n个骰子的点数.py
剑指 Offer 60. n个骰子的点数.py
py
1,226
python
zh
code
0
github-code
36
24503302432
#%% Ejercicio 1 # Crear un programa que pida al usuario una letra, y si es vocal, muestre el mensaje # "Es vocal". Sino, decirle al usuario que no es vocal Letra = input('Porfavor ingrese una letra: ') if Letra == 'a' or Letra == 'e' or Letra == 'i' or Letra == 'o' or Letra == 'u': print('La letra {}, Es vocal'...
CriSarC/PythonExercises
3.Condicionales/3.3.0Ejercicios.py
3.3.0Ejercicios.py
py
1,246
python
es
code
0
github-code
36
27551610430
import argparse import logging import os import shutil import sys import tarfile import tempfile import traceback from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile import rdiffweb from rdiffweb.core.librdiff import LANG, STDOUT_ENCODING, find_rdiff_backup, popen logger = logging.getLogger(__name__) # Increase th...
ikus060/rdiffweb
rdiffweb/core/restore.py
restore.py
py
9,753
python
en
code
114
github-code
36
28111130337
from django.db.models import Avg from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from dinnerevent.models import Review from .forms import UserRegisterForm, ProfileForm def register(r...
taheeraahmed/Dinnersharing
middagproj/users/views.py
views.py
py
1,640
python
en
code
0
github-code
36
22654441124
from matplotlib.colors import ListedColormap from sklearn import neighbors, datasets import numpy as np from matplotlib import pyplot as plt from sklearn.neural_network import MLPClassifier from sklearn.model_selection import train_test_split # same process as svm np.random.seed(0) iris = datasets.load_iris() X = iris...
fh-Zh/Classification.old
bpnn.py
bpnn.py
py
1,918
python
en
code
0
github-code
36
2884786469
# coding:utf-8 # @Time : 2020/4/21 19:18 # @Author: Xiawang # Description: import datetime import time import requests import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header ''' 用于主流程监控定期执行并发送报警信息 ''' def get_fix_time(): now_time = dat...
Ariaxie-1985/aria
task/send_auto_test_report.py
send_auto_test_report.py
py
7,283
python
en
code
0
github-code
36
23420270770
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('stock', '0088_auto_20160620_1304'), ] operations = [ migrations.Create...
pmmrpy/SIGB
stock/migrations/0089_auto_20160622_1414.py
0089_auto_20160622_1414.py
py
2,301
python
es
code
0
github-code
36
21592351209
def get_all_measurements(): f = open("input_day_1.txt", "r") list_of_measurements = f.read().split('\n') return list_of_measurements def get_count_of_increased_sequent(measurements) -> int: """ Count how many sequent increases are in a list of measurements Args: measurement...
PavcaHyx/advent-of-code-2021
day_1/day_1.py
day_1.py
py
2,180
python
en
code
0
github-code
36
27875338483
import json import requests from openerp.tests.common import HttpCase from openerp import api, exceptions, tools, models HOST = '127.0.0.1' PORT = tools.config['xmlrpc_port'] class Webhook(models.Model): _inherit = 'webhook' @api.one def run_wehook_test_get_foo(self): """ This method i...
Blancorama/blancorama_tools
webhook/tests/test_webhook_post.py
test_webhook_post.py
py
3,596
python
en
code
0
github-code
36
6688406212
from langchain.chat_models import ChatOpenAI from langchain.output_parsers import PydanticOutputParser from langchain.prompts import ChatPromptTemplate from pydantic import BaseModel, Field from dotenv import load_dotenv from typing import List import pandas as pd import os # loading api key and defining vars load_d...
oresttokovenko/gpt-anki
src/generate_flashcards.py
generate_flashcards.py
py
2,043
python
en
code
9
github-code
36
8695937067
#from compiler import to_program #from reader import read, Literal, Expr from rpython.config.translationoption import get_combined_translation_config from util import STDIN, STDOUT, STDERR, read_file, write import api import base import evaluator.loader import space import sys, os config = get_combined_translation_conf...
cheery/pyllisp
main.py
main.py
py
3,246
python
en
code
7
github-code
36
35217198422
import requests from urllib.request import urlopen import urllib from selenium import webdriver from bs4 import BeautifulSoup import http.client from openpyxl import Workbook from openpyxl import load_workbook from openpyxl.writer.excel import ExcelWriter from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE import json...
Just-Doing/python-caiji
src/work/20210719/tydexoptics.py
tydexoptics.py
py
5,791
python
en
code
1
github-code
36
34622506671
import os import zipfile from pathlib import Path import warnings from shutil import rmtree import time import pandas as pd import numpy as np import SimpleITK as sitk from tqdm import tqdm from segmentation_metrics import compute_segmentation_scores from survival_metrics import concordance_index class AIcrowdEvalu...
voreille/hecktor
src/aicrowd_evaluator/evaluator.py
evaluator.py
py
11,240
python
en
code
65
github-code
36
33083611476
# ISO-8859-1 import csv from urllib import request # -> Abre um url def read(url): with request.urlopen(url) as arquivo: print('Baixando o CSV...') dados = arquivo.read().decode('latin1') print('Download completo!') for linha in csv.reader(dados.splitlines()): print('{}...
sarandrade/Python-Courses
Python 3 - Curso Completo do Básico ao Avançado/Seção 09 - Manipulação de Arquivos/106. Desafio CSV do IBGE (resp).py
106. Desafio CSV do IBGE (resp).py
py
453
python
pt
code
0
github-code
36
33279344042
import requests, json BaseURL = 'https://paper-api.alpaca.markets' OrdersURL = '{}/v2/orders'.format(BaseURL) Headers = {"APCA-API-KEY-ID": "PKU31JDVN0AYRLMI1MEQ", "APCA-API-SECRET-KEY": "LVgw3y2RuffyDAMsjDR2EfscgsokGNTsuSEn3LUb"} def create_order(symbol, qty, side, type, time_in_force): data = { 'symbol'...
Jacob-Kenney/JagBot
4.Buy stocks/Buystocks.py
Buystocks.py
py
534
python
en
code
1
github-code
36
16185478017
from .channel import MessageChannel class MessageBroker(): _wss = {} def __init__(self, config: dict, channel: MessageChannel): self.config = config self.channel = channel self.channel.add_handler(self._handle_message) async def _handle_message(self, user_id, message): i...
jaggerwang/sanic-in-practice
weiguan/adapter/message/broker.py
broker.py
py
897
python
en
code
42
github-code
36
2317503124
import torch import torch.nn as nn import torch.nn.functional as F from core.loss.multi_task import MultiTaskProxy from core.loss.segment import SemanticSegmentation from core.loss.matting import ImageMatting from core.loss.grad import MattingGrad, ImageGradient class JointMattingParsingLoss(nn.Module): def __i...
xinyunmian/matting
core/loss/joint.py
joint.py
py
1,456
python
en
code
0
github-code
36
20157623405
from collections import namedtuple import sys class Accumulator: def __init__(self, input): self.accumulator = 0 self.executed_instructions = [] self.next_instruction = 1 self.instructions = input self.stopping_instruction = max(self.instructions.keys()) + 1 sel...
davidcolton/adventofcode
2020/day_08/accumulator.py
accumulator.py
py
2,828
python
en
code
0
github-code
36
6129429499
import argparse from src.gt_merger import constants def get_parser(): parser = argparse.ArgumentParser() parser.add_argument('--obaFile', type=str, required=True, help='Path to CSV file exported from OBA Firebase ' 'Export App') parser.a...
CUTR-at-USF/onebusaway-travel-behavior-analysis
src/gt_merger/args.py
args.py
py
2,668
python
en
code
0
github-code
36
71789567783
# Binary search algorithm built with python from random import randint from insertion_sort import * # Returns position in array if found otherwise returns -1 def binary_search(arr, target): bottom = 0 top = len(arr) - 1 while bottom <= top: mid = (top + bottom) // 2 if arr[mid] == target: return mid eli...
alex-hunter3/standard-algorithms
py/binary_search.py
binary_search.py
py
649
python
en
code
0
github-code
36
74477036264
from flask import Flask from flask import render_template, request, jsonify from engine.inv_ind import get_inv_ind from engine.retrieval import get_retrieved_docs app = Flask(__name__) @app.route('/') def hello(): return render_template("default.html") @app.route('/index', methods=["GET", "POST"]) de...
ashishu007/IR-Engine
main.py
main.py
py
1,441
python
en
code
0
github-code
36
31748860310
import numpy as np from timeit import default_timer as timer from numba import vectorize @vectorize(['float32(float32, float32)'], target='cuda') def gpu_pow(a, b): return a ** b @vectorize(['float32(float32, float32)'], target='parallel') def cpu_para_pow(a, b): return a ** b def cpu_pow(a, b, c): fo...
Purdue-Academic-Projects/AI_Final_Project
heart_rate_ai/cuda_test/cuda_tutorial.py
cuda_tutorial.py
py
1,237
python
en
code
0
github-code
36
20077173649
from django.urls import resolve from rest_framework import status from rest_framework.reverse import reverse from rest_framework.test import APITestCase, APIRequestFactory from cars.models import Car, Manufacturer from cars.serializers import CarGetSerializer from cars.views import CarListCreateView factory = APIRequ...
tomasz-rzesikowski/cars_API
cars/tests/tests_views/tests_car_list_view.py
tests_car_list_view.py
py
1,620
python
en
code
0
github-code
36
71002340904
""" 40. O custo ao consumidor de um carro novo é a soma do custo de fábrica, da comissão do distribuidor, e dos impostos. A comissão e os impostos são calculados sobre o custo de fábrica, de acordo com a tabela abaixo. Leia o custo de fábrica e escreva o custo ao consumidor. ----------------------------------------...
Kaiquenakao/Python
Estruturas Logicas e Condicionais/Exercicio40.py
Exercicio40.py
py
1,463
python
pt
code
5
github-code
36
23215865575
class TimeBlock2: """ Creates an object that represents the available block of time in which a court is available to play in """ def __init__(self, club_id, initial_time, final_time, court_name, match_duration, court_value, court_size): self.club_id = club_id self.initial_time = initial_time.strftime("%Y-%m...
rbilbeny/PadelOk
mysite/time_block.py
time_block.py
py
539
python
en
code
0
github-code
36
75273737705
import tkinter import pyperclip sirka = 500 vyska = 450 data = [] size = [] c = tkinter.Canvas(width=sirka, height=vyska) c.pack() def copy(): cptxt = '(' for i in range(size[1]): cptxt += '0b' + ''.join(str(e) for e in data[i]) + ',' if i == size[1] - 1: cptxt = c...
branislavblazek/notes
Python/projekty/char_creator.py
char_creator.py
py
1,990
python
en
code
0
github-code
36
40461953299
import os import gspread from oauth2client.service_account import ServiceAccountCredentials as SAC from linebot import LineBotApi, WebhookParser from linebot.models import MessageEvent, TextMessage, ImageSendMessage, URITemplateAction, TextSendMessage, TemplateSendMessage, ButtonsTemplate, MessageTemplateAction, Carous...
JasperLin0118/linebot
utils.py
utils.py
py
15,459
python
en
code
0
github-code
36
28779713791
""" Exercism Python track Source: https://exercism.org/tracks/python My solutions: https://github.com/egalli64/pythonesque/exercism Card Games https://exercism.org/tracks/python/exercises/card-games Functions for tracking poker hands and assorted card tasks. """ import unittest from lists import * class TestCardGa...
egalli64/pythonesque
exercism/lists_test.py
lists_test.py
py
2,302
python
en
code
17
github-code
36
16644155233
c = 100 w = [12, 9, 56, 78, 55, 23] # 按重量从小到大排序 w.sort() # 贪心选择策略:每次选择最轻的集装箱装上船 count = 0 for i in range(len(w)): if c >= w[i]: c -= w[i] count += 1 else: break print(count)
AanKn/School_work
算法设计/最优装载问题.py
最优装载问题.py
py
281
python
en
code
0
github-code
36
15293966281
# -*- coding:utf-8 -*- import os import sys import time import math import threading import json import random import logging from apscheduler.schedulers.background import BackgroundScheduler sys.path.append('./lib') import mylog mylog.setLog('KD48Monitor', logging.WARNING) loggerInfo = logging.getLogger('mylogger') l...
momo-xii/KD48
KDMonitor.py
KDMonitor.py
py
26,545
python
en
code
1
github-code
36
73381842664
import matplotlib.pyplot as plt import numpy as np #IMAGEN 1 Imagen='33.jpg' I=plt.imread(Imagen) plt.title('Imagen original') plt.imshow(I) plt.show() rgb = [0.2989, 0.5870, 0.1140] ig = np.dot(I[...,:3], rgb) plt.imshow(ig,cmap='gray') plt.axis('off') plt.savefig('b&w.png',bbox_inches='tight',pad_inches=0,dpi=1200...
BrianCobianS/Capitulo4-Python
rgb.py
rgb.py
py
1,806
python
es
code
0
github-code
36
26735300247
def pali(st): n = len(st) if n==1: return True for i in range(n//2): if st[i] != st[-i-1]: return False return True st = input() def ans(st): for a in range(1,len(st)-2): if pali(st[:a]): for b in range(a+1,len(st)): if pali(st[a:b]) an...
arpitkushwaha/Codevita-2020-Solutions
pallindrome_2.py
pallindrome_2.py
py
500
python
en
code
0
github-code
36
16079144937
from calendar_lib.constants import TEMPLATE_FILE from calendar_lib.calendar import three_calendars from html.html_gen import HTMLPage from os import remove from os.path import exists OUTPUT_DIR="tests/pages" def delete_file(year) -> None: """ Remove file for given year if it exists, bubble exceptions to tople...
minishrink/calendargen
tests/html_test.py
html_test.py
py
1,534
python
en
code
2
github-code
36
3093791396
# You will be given a sequence of strings, each on a new line. # Every odd line on the console is representing a resource (e.g. Gold, Silver, Copper, and so on) # and every even – quantity. Your task is to collect the resources and print them each on a new line. # Print the resources and their quantities in the followi...
ivn-svn/SoftUniPythonPath
Programming Fundamentals with Python/7_dictionaries/exercise/2_miner_task.py
2_miner_task.py
py
829
python
en
code
1
github-code
36
38869163941
from pathlib import Path import pandas as pd from sklearn.metrics import make_scorer, accuracy_score, f1_score, roc_auc_score from imblearn.metrics import geometric_mean_score, sensitivity_score, specificity_score def get_slovak_data(business_area, year, postfix): print("Loading Slovak data...") path_bankrupt ...
kanasz/TabNet
src/base_functions.py
base_functions.py
py
1,548
python
en
code
0
github-code
36
22604017166
def perform_operation(operand1, operator, operand2): if operator == "+": return operand1 + operand2 elif operator == "-": return operand1 - operand2 elif operator == "*": return operand1 * operand2 elif operator == "/": if operand2 != 0: return operan...
Chiro2002/SEM_5_SE
python_and_bash/calculator.py
calculator.py
py
1,354
python
en
code
1
github-code
36
6540041788
# Задача №17. Решение в группах # Дан список чисел. Определите, сколько в нем # встречается различных чисел. # Input: [1, 1, 2, 0, -1, 3, 4, 4] # Output: 6 import random length = int(input("Введите длину списка: ")) list = [] temp = 0 for i in range(length): list.append(random.randint(0,10)) print(list) # input...
ALGUL1987/Python
3Семинар. Списки и словари/31task.py
31task.py
py
731
python
ru
code
0
github-code
36
25698014660
import string # YAML -> XML f = open('Расписание.json',"r",encoding='utf-8') f = f.readlines() tab_count = 0 alph = list(string.ascii_letters) tab_count = 1 last = '' firstWord = '' count = 0 tab_count = 0 a = [] print('<?xml version="1.0" encoding="utf-8"?>') for i in f: word = '' firstWord = 'Body' f...
Sinchi1/-Computer-Science
4 лаба/Parser1.py
Parser1.py
py
1,705
python
en
code
0
github-code
36
33148392054
import turtle import random screen = turtle.Screen() bob = turtle.Turtle() screen.bgcolor("black") bob.pencolor("cyan") bob.speed(10000) def crazy(var1): for i in range(360): bob.forward(i) bob.left(var1) crazy(555) # Range = 360 # Crazy = 34 # Crazy = 50 #speed = 100 #crazy = 34 ...
Sush4fc/Turtle-Module
Universal Pattern Creator.py
Universal Pattern Creator.py
py
362
python
en
code
1
github-code
36
10441407969
import xlwt import csv import requests import pprint class GitClient(object): def __init__(self): self.base_url = 'https://api.github.com/' self.userName = '' self.password = '' self.autorization = False self.notAut = '' self.exporter = [] self.toWrite = {} ...
Delight116/003-004-be-addo-Cmd_and_Html_GitClient
GitClient.py
GitClient.py
py
6,608
python
en
code
0
github-code
36
13549248356
import random import Crypto from Crypto.PublicKey import RSA from Crypto import Random import ast import pyDes from Crypto.Cipher import DES from config import max_input_bit_length import time def OT_transfer(m0,m1,bit): m0=int(m0) m1=int(m1) x0=random.randint(0, 2**1024-1) x1=random.randint(0, 2**1024-1) #loadi...
makeapp007/cryptography
mpc/code/nbit-comparator/ot.py
ot.py
py
2,974
python
en
code
0
github-code
36