id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
1612889
def url(): import urllib.request try: site = urllib.request.urlopen('http://pudim.com.br/') except: print('\33[1:31mFalha!\33[m\nImpossível de acessar o site no momento!') else: print('\33[1:32mSucesso!\33[m\nSite funcionando normalmente!')
StarcoderdataPython
3210732
def persistence(n): nums = [int(x) for x in str(n)] count = 0 while len(nums) != 1: n = 1 for i in nums: n*= i nums = [int(x) for x in str(n)] count+=1 return count
StarcoderdataPython
126045
<gh_stars>0 """ ----------------------------------------------------- # TECHNOGIX # ------------------------------------------------------- # Copyright (c) [2022] Technogix SARL # All rights reserved # ------------------------------------------------------- # Keywords to manage dynamodb tasks # -----------------...
StarcoderdataPython
76906
import importlib module = importlib.import_module("07_the_sum_of_its_parts") find_steps_order = module.find_steps_order parse_instructions = module.parse_instructions instructions = [ "Step C must be finished before step A can begin.", "Step C must be finished before step F can begin.", "Step A must be fi...
StarcoderdataPython
1737516
""" Copyright 2021 Nirlep_5252_ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software d...
StarcoderdataPython
27919
from rest_framework import serializers from . import models class ShelterSerializer(serializers.ModelSerializer): class Meta: model = models.Shelter fields = ('name', 'location') class DogSerializer(serializers.ModelSerializer): class Meta: model = models.Dog ...
StarcoderdataPython
4810617
<reponame>jstraub/tdp import numpy as np import matplotlib.pyplot as plt def GetEmptyFig(): fig=plt.figure(frameon=False) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) return fig #I = np.resize(np.arange(9),(100,100)) #fig = GetEmptyFig() #plt.imshow(I, # interpolation="nearest"...
StarcoderdataPython
16366
<reponame>vragonx/DiscordStatusChanger from colorama import Fore, init, Style import requests import random import ctypes import time import os ctypes.windll.kernel32.SetConsoleTitleW('Discord Status Changer') init(convert=True, autoreset=True) SuccessCounter = 0 ErrorCounter = 0 os.system('cls') print(F...
StarcoderdataPython
4829321
""" This module provides common classes to document APIs. The purpose of these classes is to provide an abstraction layer on top of a specific set of rules to document APIs. For example, it should be possible to generate both OpenAPI Documentation v2 and v3 (currently only v3 is supported) from these types, and potent...
StarcoderdataPython
4831241
<gh_stars>1-10 class ScriptPlatformScriptGen: def __init__(self): pass def GenerateScriptStart(self): Script = "var filePath = activeDocument.fullName.path;\r\n" #Script += "var newDoc = app.activeDocument.duplicate();\r\n" #Script += "app.activeDocument...
StarcoderdataPython
1691604
<filename>board.py """Board module""" import copy import math import random import string def create_solution_board(width=6, height=6): """Randomly generates a new board with width by height size """ if type(width) != int or type(height) != int: raise TypeError('Arguments must be int type') ...
StarcoderdataPython
3359210
<filename>migrations/211-recategorize-canned-responses.py """ All the forum canned responses are stored in KB articles. There is a category for them now. Luckily they follow a simple pattern of slugs, so they are easy to find. """ from django.conf import settings from django.db.models import Q from kitsune.wiki.model...
StarcoderdataPython
1776966
<filename>speechrec_test.py #!/usr/bin/env python import speech_recognition as sr rec = sr.Recognizer() mic = sr.Microphone() while True: with mic as source: #ノイズ対策 rec.adjust_for_ambient_noise(source) audio = rec.listen(source) try: print(rec.recognize_google(audio, language='ja-JP')) exce...
StarcoderdataPython
3320768
import numpy as np class SGD: def __init__(self, learning_rate, exponential_weight): self.learning_rate = learning_rate self.exponential_weight = 1. if exponential_weight != None: self.moving_average = None self.exponential_weight = exponential_weight def __call...
StarcoderdataPython
1667085
<reponame>treilly94/mango-exercise from numpy import random class DistributionGenerator: """ Generate random data within a given distribution """ def __init__(self, num_samples, mean=0, sd=1, interval=1, n=1, p=0.5): """ :param num_samples: Int The number of samples to be returned ...
StarcoderdataPython
65350
<gh_stars>0 app_name = "users" urlpatterns = [ ]
StarcoderdataPython
1724453
<reponame>ThBlitz/Self-Driving-car<filename>tfBlitz.py import tensorflow as tf import os import glob import numpy as np from random import shuffle import datetime import time from contextlib import redirect_stdout from tensorflow import keras # use single folder directory for a single data type # only one tfinfo.txt f...
StarcoderdataPython
56525
import torch import numpy as np from torch import nn from torch import optim from torch.utils.data import TensorDataset, DataLoader from forPython.datasets.uci import load_mhealth from forPython.models.torch.cnn import SimpleCNN from forPython.utility.trainer import TorchSimpleTrainer np.random.seed(0) torch.random.m...
StarcoderdataPython
3330513
<filename>3rd_party_libs/transnetv1/post_process.py import os import gc import sys from sys import getsizeof import math import time seed_int = 5 from numpy.random import seed as np_seed np_seed(seed_int) from tensorflow import set_random_seed as tf_set_random_seed tf_set_random_seed(seed_int) import num...
StarcoderdataPython
3234053
import pandas as pd from leaderboard.constants import scoreWeights from leaderboard.constants import contribTypes def get_final_score_table( intermediate_score_df: pd.DataFrame, user_list: list ) -> pd.DataFrame: """ Returns final score table dataframe Args: df: pandas DataFrame - Intermediate S...
StarcoderdataPython
45619
<filename>apps/scraper/bing_api.py #script to scraper bing api #include libs import sys sys.path.insert(0, '..') from include import * def generate_scraping_job(query, scraper): query_string = query[1] query_id = query[4] study_id = query[0] search_engine = scraper result_pages = 20 number_m...
StarcoderdataPython
43283
''' ExperimentClient tests. ''' import os import unittest import pandas as pd import time from mljar.client.project import ProjectClient from mljar.client.dataset import DatasetClient from mljar.client.experiment import ExperimentClient from .project_based_test import ProjectBasedTest, get_postfix class ExperimentCl...
StarcoderdataPython
51401
<reponame>UW-OCP/Collocation-Solver-CUDA import numpy as np import scipy.linalg class collocation_node: """ Node class for collocation solver, save the required DAE variables at each time node """ ''' Input: size_y - size of the ODE variables size_z - size of the DA...
StarcoderdataPython
3206639
#On the name of ALLAH and may the blessing and peace of Allah #be upon the Messenger of <NAME> <NAME>. #Author : <NAME> #Date : 15/06/10 #version :2.6 from string import * from itertools import * """ My program uses special functions to test, count, and extract vowels and consonants. However,the string_check functio...
StarcoderdataPython
3258556
<filename>tests/test_quickumls-service.py ''' Example of json TCP communication, make sure you have app/quickumls-service.py running on port 9999 ''' import json import socket def recvall(sock): BUFF_SIZE = 2048 data = b'' while True: part = sock.recv(BUFF_SIZE) data += part i...
StarcoderdataPython
3212414
<filename>brincadeiras/func.py import config.janela as cjane def como_jogar(titulo, conteudo): """Cria a tela de "como jogar" para um jogo, recebendo o título e as instruções daquele jogo.""" janela = cjane.Janela() janela.muda_linha(1, titulo.upper()) janela.muda_linha(3, ' - INSTRUÇÕES:', alin='lj...
StarcoderdataPython
1796468
<reponame>NathanKr/docker-compose-python-mysql-playground from datetime import datetime import mysql.connector import time import os now = datetime.now() print(f' ########### hello python start -{now}-') mydb = None while True: try: mydb = mysql.connector.connect( # host is db container name !!! ...
StarcoderdataPython
121989
import sqlite3 conn = sqlite3.connect('rpg_db.sqlite3') curs = conn.cursor() count_characters = 'SELECT COUNT(*) FROM charactercreator_character;' print(curs.execute(count_characters).fetchall() [0][0]) query = '''SELECT character_id, COUNT(distinct item_id) FROM charactercreator_character_inventory ...
StarcoderdataPython
4804476
from braces.views import LoginRequiredMixin from django.conf import settings from model_controller.utils import EXCLUDE_MODEL_CONTROLLER_FIELDS class ExtendedLoginRequiredMixin(LoginRequiredMixin): login_url = settings.LOGIN_URL class ModelControllerAdminMixin(object): exclude = EXCLUDE_MODEL_CONTROLLER_FI...
StarcoderdataPython
146045
<reponame>NovaSBE-DSKC/retention-evaluation def calc_percentage_at_k(test, pred, k): # sort scores, ascending pred, test = zip(*sorted(zip(pred, test))) pred, test = list(pred), list(test) pred.reverse() test.reverse() # calculates number of values to consider n_percentage = round(len(pr...
StarcoderdataPython
1799662
<filename>models/loss/__init__.py from .loss_functions import listMLE, pointwise_ranking_loss, listwise_ranking_loss
StarcoderdataPython
1781245
<reponame>interactiveinstitute/watthappened<gh_stars>0 from ektime import * class Value(object): def __init__(self, *args): self.set(*args) def set(self): raise NotImplementedError def current(self): return self.predicted_at(Time.from_s(time.time())) def predicted_at(self, time): raise NotIm...
StarcoderdataPython
3293995
# Maze in a 60x60 grid # Nodes: 620 # Edges: 654 adjList = [ [23, 1], [45, 2, 0], [27, 1], [28, 4], [31, 3], [6], [14, 5], [17, 8], [7], [19], [60, 11], [41, 12, 10], [29, 11], [22], [54, 6, 15], [14], [34, 17], [35, 7, 16], [38, 19], [39...
StarcoderdataPython
169947
<reponame>peter88213/PyWriter """Provide a generic class for csv file import. Other csv file representations inherit from this class. Copyright (c) 2021 <NAME> For further information see https://github.com/peter88213/PyWriter Published under the MIT License (https://opensource.org/licenses/mit-license.php) ""...
StarcoderdataPython
198153
<reponame>pauloubuntu/ocr-processing-service __author__ = 'paulo.rodenas' from datetime import datetime class Date(object): BRAZILIAN_FORMAT = '%d/%m/%Y' @staticmethod def parse(date_str, date_format=BRAZILIAN_FORMAT): try: return datetime.strptime(date_str, date_format) exc...
StarcoderdataPython
3292417
<gh_stars>0 # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/topics/item-pipeline.html from scrapy.exceptions import DropItem from structuredDataCrawler.items import PipeSeedItem from structuredDataCrawler.items import SeedItem from colle...
StarcoderdataPython
1664770
<reponame>adolphus-c/AI_LAB<gh_stars>0 import re def getAttributes(string): expr = '\([^)]+\)' matches = re.findall(expr, string) return [m for m in str(matches) if m.isalpha()] def getPredicates(string): expr = '[a-z~]+\([A-Za-z,]+\)' return re.findall(expr, string) def DeMorgan(sentence): s...
StarcoderdataPython
4811884
<gh_stars>0 # -*- coding: utf-8 -*- '''Test cases for Sequenceops module.''' from __future__ import (absolute_import, division, print_function, unicode_literals) import unittest from functools import reduce from future.builtins import (ascii, filter, hex, map, oct, zip, range) from intro_py import util from intro...
StarcoderdataPython
1799756
<gh_stars>1000+ # coding=utf-8 from .test_default_mirror import TestDefaultMirror from .test_httpbin import TestHttpbin from .test_verification import TestVerification, TestVerificationSingleAnswer from .test_cache_system import TestCacheSystem from .test_cdn import TestCDN from .test_redirection import TestRedirection...
StarcoderdataPython
3213957
import logging import snowflake import snowflake.connector.errors from ubiops_connector import InputConnector, ConnectorError, RecoverableConnectorError, get_variable, retry logger = logging.getLogger('Snowflake Connector') class Deployment(InputConnector): """ Snowflake connector """ def __init__...
StarcoderdataPython
162396
#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # <NAME> # California Institute of Technology # (C) 1998-2005 All Rights Reserved # # <LicenseText> # # ~~~~~~~~~~~~~~~~~~~~~~~~~...
StarcoderdataPython
3365550
import os import time from collections import defaultdict from itertools import combinations, permutations from lib.report.report_tools import global_track_dt from lib.filters.structural_QC import identify_intronic_transcripts from lib.parsing.gtf_object_tools import create_gtf_object, write_gtf from lib.tools.other_t...
StarcoderdataPython
138358
<reponame>kmarcini/Project-Euler-Python ########################### # # #718 Unreachable Numbers - Project Euler # https://projecteuler.net/problem=718 # # Code by <NAME> # ###########################
StarcoderdataPython
97205
<filename>apps/shop/migrations/0001_initial.py # -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-11 11:07 from __future__ import unicode_literals import apps.shop.utils import autoslug.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration)...
StarcoderdataPython
3280010
<gh_stars>10-100 ################################################### # header_troops.py # This file contains declarations for troops # DO NOT EDIT THIS FILE! ################################################### from header_common import * # Troop flags tf_male = 0 tf_female = 1 tf_undead ...
StarcoderdataPython
3294289
# coding=utf-8 # author: al0ne # https://github.com/al0ne import re import base64 import urllib3 import glob import itertools import concurrent.futures import logging import ssl import chardet import socket import OpenSSL import requests import random from urllib import parse from bs4 import BeautifulSoup from lib.ver...
StarcoderdataPython
3314010
import sys from draw import * import random import json # GAME RULES # 1)Any live cell with fewer than two live neighbours dies, as if by underpopulation. # Default is UNDER_THRESH = 2 # 2)Any live cells that does not die due to underpopulation or overpopulation remains alive. # 3)Any live cell with more than three...
StarcoderdataPython
3367586
#!/usr/bin/env python # Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Re-runs the ChromeDriver's client-side commands, given a log file. Takes a ChromeDriver log file that was created with the --replay...
StarcoderdataPython
1700867
# -*- coding: utf-8 -*- import sys import random from collections import Counter import numpy as np import cmath from qlazy.error import * from qlazy.config import * from qlazy.util import * from qulacs import QuantumState from qulacs import QuantumCircuit from qulacs.gate import Identity, X, Y, Z from qulacs.gate im...
StarcoderdataPython
3202277
<reponame>anilpai/leetcode # w = [1, 2, 4, 2, 5] # v = [5, 3, 5, 3, 2] # C = 10 ''' 'w' is the weights of items. 'v' is the values of items. ''' w = [1, 3, 4, 5] v = [1, 4, 5, 7] # Naive version. print("### Naive solution. ###") def KS(n, C): if n==0 or C==0: res = 0 elif w[n] > C: res = K...
StarcoderdataPython
1720154
<reponame>nervmaster/djangoproj from django.db import models from decimal import Decimal # Create your models here. class Ingredient(models.Model): MEASURE_CHOICES = ( ('L', 'Liter'), ('G', 'Gram') ) CURRENCY_CHOICES = ( ('USD', 'US Dollars'), ('EUR', 'EURO'), ('BRL'...
StarcoderdataPython
1611497
from functools import wraps from .checker import ( satisfies_independent_axiom, satisfies_dependent_axiom, satisfies_bases_axiom, satisfies_circuits_axiom, satisfies_rank_function_axiom, satisfies_nulity_function_axiom, satisfies_closure_axiom, satisfies_open_sets_axiom, satisfies_h...
StarcoderdataPython
4806175
<reponame>Siddharthgolecha/UDMIS from inspect import CO_VARKEYWORDS import sys import pennylane as qml from pennylane import numpy as np def hamiltonian_coeffs_and_obs(graph): """Creates an ordered list of coefficients and observables used to construct the UDMIS Hamiltonian. Args: - graph (list((...
StarcoderdataPython
1761329
import numpy from chainer import distributions from chainer import testing from chainer import utils @testing.parameterize(*testing.product({ 'shape': [(2, 3), ()], 'is_variable': [True, False], 'sample_shape': [(3, 2), ()], })) @testing.fix_random() @testing.with_requires('scipy') class TestLogNormal(te...
StarcoderdataPython
100803
<gh_stars>1-10 import endpoints from api_user import UserAPI from api_posts import PostsAPI from api_comments import ReactionAPI from api_image import ImageAPI APPLICATION = endpoints.api_server([PostsAPI, ReactionAPI, UserAPI, ImageAPI])
StarcoderdataPython
1702397
<gh_stars>1-10 import torch import numpy as np import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.distributions as dist import matplotlib.pyplot as plt from src.params_to_flat import params_to_flat p = 2 n = 10 od = 1 dist_w = dist.Laplace(0, 0.1) dist_o = dist.Exponential(...
StarcoderdataPython
3332306
# write a program that adds the digits in a 2 digit number. # the user inputs a two digit number number = input("Type a two digit number: \n") # assign a variable to each number string_first_number = number[0] string_second_number = number[1] # convert from string to integer first_number = int(string_first_number) s...
StarcoderdataPython
3313517
""" Creating cover file for configuring registration image pairs The paths and all other constants are set to run on CMP grid for ANHIR dataset Copyright (C) 2016-2018 <NAME> <<EMAIL>> """ import os import glob import logging from functools import partial import pandas as pd DATASET_IMAGES = '/datagrid/Medical/data...
StarcoderdataPython
4810871
<reponame>NHSDigital/list-reconciliation from validate_and_forward.lambda_handler import ValidateAndForward app = ValidateAndForward() def lambda_handler(event, context): return app.main(event, context)
StarcoderdataPython
1776879
import os import time def log(filename, text): """ Writes text to file in logs/mainnet/filename and adds a timestamp :param filename: filename :param text: text :return: None """ path = "logs/" if not os.path.isdir("logs/"): os.makedirs("logs/") if not os.path.isdir("logs/...
StarcoderdataPython
1666129
"""Kata url: https://www.codewars.com/kata/570a6a46455d08ff8d001002.""" def no_boring_zeros(n: int) -> int: if n == 0: return 0 while not n % 10: n //= 10 return n
StarcoderdataPython
1738964
<gh_stars>0 # -*- coding: utf-8 -*- import grok import z3c.flashmessage.interfaces from grokui.base.layout import GrokUIView from grokui.admin.interfaces import ISecurityNotifier from grokui.admin.utilities import getVersion from grokui.admin.security import SecurityNotifier from ZODB.interfaces import IDatabase fro...
StarcoderdataPython
171091
# -*- coding: utf-8 -*- # script.module.python.koding.aio # Python Koding AIO (c) by whufclee (<EMAIL>) # Python Koding AIO is licensed under a # Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. # You should have received a copy of the license along with this # work. If not, see h...
StarcoderdataPython
3314203
<reponame>Lewkow/astro-outlier<gh_stars>0 class IOHandler: def __init__(self): self.data_fid_npy = "../data/KeplerSampleWErr.npy" self.data_fid_csv = "../data/kepDenselcvs.csv" def import_numpy_fid(self, numpy_fid): data_array = np.load(self.data_fid, allow_pickle=True) retur...
StarcoderdataPython
3373040
<gh_stars>0 import math class Position(object): def __init__(self, position=None, xpos=None, ypos=None): self.__x = 0 self.__y = 0 if position is not None: self.__x = position.x self.__y = position.y else: if xpos is not None: sel...
StarcoderdataPython
93709
__author__ = '<NAME> <<EMAIL>>' __date__ = ' 16 December 2017' __copyright__ = 'Copyright (c) 2017 <NAME>' import dg import pandas as pd from copy import deepcopy from dg.utils import bar from dg import persistence from dg.config import Config from dg.enums import Mode, Dataset def train_model(model, train_set, eva...
StarcoderdataPython
3223629
# Databricks notebook source # MAGIC %md # MAGIC # What's in this exercise? # MAGIC # MAGIC 1) Read raw data, augment with derived attributes, augment with reference data & persist<BR> # MAGIC 2) Create external unmanaged Hive tables<BR> # MAGIC 3) Create statistics for tables # COMMAND ---...
StarcoderdataPython
198469
import numpy as np import torch import torch.nn.functional as F from torch.autograd import Variable def cross_entropy_2d(predict, target): """ Args: predict:(n, c, h, w) target:(n, h, w) """ assert not target.requires_grad assert predict.dim() == 4 assert target.dim() == 3 ...
StarcoderdataPython
49315
<gh_stars>10-100 #!/usr/bin/python ## @package catalog-manager # Provides general functions to parse SQ3 files # and generate SQL code. # # Can manage both 3D and MATERIALS (with TEXTURES). import csv import fnmatch import getopt import logging import os import platform import random import re import shutil import...
StarcoderdataPython
1649453
<reponame>dblueai/dblue-stats class Constants: # Data types DATA_TYPE_INTEGER = "integer" DATA_TYPE_NUMBER = "number" DATA_TYPE_STRING = "string" DATA_TYPE_BOOLEAN = "boolean" # Field types FIELD_TYPE_CATEGORICAL = "categorical" FIELD_TYPE_NUMERICAL = "numerical"
StarcoderdataPython
3312926
<reponame>rwiuff/QuantumTransport from matplotlib import pyplot as plt # Pyplot for nice graphs # from matplotlib.gridspec import GridSpec from progress.bar import Bar import numpy as np # NumPy from Functions import Import, NPGElectrode from Functions import EnergyRecursion, Transmission, Peri...
StarcoderdataPython
1625884
M, H = [int(n) for n in input().split()] print('No' if H%M else 'Yes')
StarcoderdataPython
3397283
import logging import random from typing import Any, Dict, List, Optional, Union from pydantic import create_model, BaseModel from .base import BaseSchema, ProviderNotSetException logger = logging.getLogger() class PropertyNames(BaseModel): pattern: Optional[str] = None PropertyDependency = Dict[str, List[st...
StarcoderdataPython
1789960
<reponame>fyumoto/RBMs import json import os # load the configuration file with the backend specification filedir = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(filedir,"config.json"), "r") as infile: config = json.load(infile) # read the processor type PROCESSOR = config['processor'] BACKEND...
StarcoderdataPython
48860
<filename>bloodbank_rl/tianshou_utils/policies.py from tianshou.policy import A2CPolicy, PPOPolicy from typing import Any, Dict, List, Optional, Type from tianshou.data import Batch # Normal key structure for output doesn't work with MLFlow logging nicely # loss used as a key and also parent class A2CPolicyforMLFlow...
StarcoderdataPython
1687548
import json from datetime import datetime, timezone from typing import Dict, Any, NamedTuple, Optional from uuid import UUID import bach from bach import DataFrame from sql_models.constants import DBDialect from sql_models.util import is_postgres, is_bigquery from sqlalchemy import create_engine from sqlalchemy.engine...
StarcoderdataPython
4823195
# # Project SmartDjango REST # Copyright (c) <NAME> 2021 # This software is licensed under MIT license # import logging from rest_framework import viewsets, permissions from rest_framework.decorators import action from rest_framework.response import Response from smartdjangorest.dao import get_book_by_author from ...
StarcoderdataPython
71823
from easydict import EasyDict from typing import Optional, List import copy final_eval_reward_wrapper = EasyDict(type='final_eval_reward') def get_default_wrappers(env_wrapper_name: str, env_id: Optional[str] = None) -> List[dict]: if env_wrapper_name == 'mujoco_default': return [ EasyDict(ty...
StarcoderdataPython
4830702
<reponame>slomrafgrav/MMdnn from mmdnn.conversion.pytorch.pytorch_parser import PytorchParser parser = PytorchParser('/media/slomkarafa/HDD0/Projects/android/py_to_tf/model.pth',[3,224,224]) # parser = PytorchParser(dens,(3,224,224)) parser.run('out/sen')
StarcoderdataPython
3372818
__source__ = 'https://leetcode.com/problems/construct-quad-tree/' # Time: O() # Space: O() # # Description: Leetcode # 427. Construct Quad Tree # # We want to use quad trees to store an N x N boolean grid. # Each cell in the grid can only be true or false. # The root node represents the whole grid. # For each node, it...
StarcoderdataPython
123701
<gh_stars>0 import threading import time from datetime import datetime from sensor.sensor import Sensor, SensorException from logger.logger import SensorDataLogger class DataCollector(threading.Thread): def __init__(self): super().__init__() self.sensors = {} self.loggers = [] s...
StarcoderdataPython
1653005
<filename>backend/coreapp/migrations/0001_initial.py # Generated by Django 3.2.4 on 2021-08-26 10:41 import django.db.models.deletion from django.db import migrations, models from ..models.scratch import gen_scratch_id class Migration(migrations.Migration): initial = True dependencies = [] # type: ignore...
StarcoderdataPython
1741125
<reponame>crf1111/Bio-Informatics-Learning<filename>Bioinformatics-Armory/src/Protein_Translation.py from Bio.Seq import translate # List of all possible NCBI table codes NCBI_LIST = [1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15] def translate_dna(dna, ncbi): return translate(dna, stop_symbol = "", table = ncbi) ...
StarcoderdataPython
150767
<gh_stars>1000+ def test_eval_mode(wdriver): assert wdriver.execute_script("return window.rp.pyEval('1+1')") == 2 def test_exec_mode(wdriver): assert wdriver.execute_script("return window.rp.pyExec('1+1')") is None def test_exec_single_mode(wdriver): assert wdriver.execute_script("return window.rp.pyExe...
StarcoderdataPython
12967
<reponame>PhillSimonds/capirca """Google Cloud Hierarchical Firewall Generator. Hierarchical Firewalls (HF) are represented in a SecurityPolicy GCP resouce. """ import copy import re from typing import Dict, Any from absl import logging from capirca.lib import gcp from capirca.lib import nacaddr class ExceededCos...
StarcoderdataPython
3351162
<filename>src/pymordemos/elliptic_oned.py #!/usr/bin/env python # This file is part of the pyMOR project (http://www.pymor.org). # Copyright 2013-2020 pyMOR developers and contributors. All rights reserved. # License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) from typer import Argument, Option...
StarcoderdataPython
1688499
from numpy import fabs, arange class Integration: EPS = 1e-6 area_domain = list() area_codomain = list() @staticmethod def rectangles(func, a, b, iterations=180): delta_x = (b - a) / iterations x = [a + 0.5 * delta_x] y = [func(x[0])] current_area = 0.0 fo...
StarcoderdataPython
98758
import numpy as np from scipy import signal def random_spikes(size): """ Generate zeros and ones in an array of size=size. probabilities = [probability 0 will appear, probability 1 will appear] """ spikes = np.random.choice(2, size, p=[0.99, 0.01]) # Get rid of spikes that are on top of each ...
StarcoderdataPython
1794016
''' import Monsoon.HVPM as HVPM import Monsoon.sampleEngine as sampleEngine import Monsoon.Operations as op import pyqtgraph as pg getted_num = 0 usb_data = [] Mon = HVPM.Monsoon() Mon.setup_usb() Mon.setVout(4.0) engine = sampleEngine.SampleEngine(Mon) engine.enableChannel(sampleEngine.channels.USBCurrent) Mon.s...
StarcoderdataPython
1665729
<filename>sphinxcontrib/varlinks.py # -*- coding: utf-8 -*- """ Variable hyperlinks ~~~~~~~~~~~~~~~~~~~ Extension that adds support for substitutions in hyperlinks. Substitutions are supported in both the link's label and target. Eg. `Download |subproject| <http://example.com/|subproject|/>`_....
StarcoderdataPython
1688088
<gh_stars>1-10 from qgis.PyQt.QtCore import QCoreApplication from qgis.core import (QgsProcessing, QgsFeatureSink, QgsProcessingException, QgsProcessingAlgorithm, QgsProcessingParameterNumber, QgsProcessin...
StarcoderdataPython
68942
<reponame>yay4ya/catflap<gh_stars>0 from catflap.data import Message from catflap.proxies.proxy import Proxy @Proxy.register("stdout") class StdoutProxy(Proxy): def post(self, message: Message) -> None: output = f"{message.datetime} [{message.author.name}] - {message.message}" print(output) d...
StarcoderdataPython
1759622
<filename>modoboa/transport/factories.py """Transport factories.""" import factory from . import models class TransportFactory(factory.django.DjangoModelFactory): """Factory for Transport.""" class Meta: model = models.Transport django_get_or_create = ("pattern", ) pattern = factory.Se...
StarcoderdataPython
3252358
import hashlib import uuid def get_uuid(): """ 生成UUID :return: UUID """ uuid_str = str(uuid.uuid4()) md5 = hashlib.md5() md5.update(uuid_str.encode('utf-8')) return md5.hexdigest()
StarcoderdataPython
3285035
import lyricsgenius from discord.ext import commands import discord import traceback from EZPaginator import Paginator genius = lyricsgenius.Genius('') class Lyric(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(aliases=["가사", "ly", "ㅣㅛ"]) async def lyric(self,...
StarcoderdataPython
1665219
<gh_stars>0 #!/usr/bin/env python # class Parent(object): # # def __call__(self, name): # print("hello world, ", name) # # # class Person(Parent): # # def __call__(self, someinfo): # super(Person, self).__call__(someinfo) # znaczy ze bierze pochodna od Parent czyli tutaj Person # # p = Person()...
StarcoderdataPython
1693218
# %% from copy import deepcopy import enum from re import T from numpy.core.defchararray import mod from numpy.core.function_base import linspace from scipy.ndimage.measurements import label from scipy.sparse import data from qutip.visualization import plot_fock_distribution from qutip.states import coherent import hba...
StarcoderdataPython
3349416
from nltk.corpus import wordnet from nltk.tokenize import word_tokenize from random import randint import nltk.data class Replacer(object): def __init__(self, text): self.text = text self.output = "" def tokenize(self): # Load the pretrained neural net tokenizer = nltk.data.l...
StarcoderdataPython
3387510
<gh_stars>1-10 # pyjam build file. See https://github.com/kaspar030/pyjam for info. default.CFLAGS = "-O3 -DUHCP_SYSTEM_LINUX -DUHCP_SERVER" Main("uhcpd")
StarcoderdataPython
1762600
from django.contrib.auth import login, authenticate, logout from django.shortcuts import render from django.views import View from carts.utils import merge_cart_cookie_to_redis from goods.models import SKU from meiduo_mall.utils.views import LoginRequiredMixin from .models import User, Address from django.http import ...
StarcoderdataPython