id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
66643 | # -*- coding: utf-8 -*-
"""
bxemu - bitmex xbt emulator.
"""
from setuptools import setup, find_packages
import codecs
import os
def read_install_requires():
with codecs.open('requirements.txt', 'r', encoding='utf-8') as f:
res = f.readlines()
res = list(map(lambda s: s.replace('\n', '... | StarcoderdataPython |
3274516 | """This file implements RPN and baselines for the Kitchen3D environment."""
import torch
import torch.nn as nn
from rpn.utils.torch_wrapper import MLP, time_distributed
import rpn.utils.torch_utils as tu
from rpn.utils.eval_utils import classification_accuracy, masked_binary_accuracy
from rpn.net import Net, masked_s... | StarcoderdataPython |
15527 | import glob, os
import subprocess
from difflib import context_diff
class TestRunner(object):
def __init__(self, context):
self.context = context
self.error_count = 0
self.test_count = 0
self.success_count = 0
def run(self):
os.getcwd()
os.chdir(self.context.repo... | StarcoderdataPython |
1611953 | def lone_sum(a, b, c):
original = [a, b, c]
loneSet = list(set([a, b, c]))
retSum = 0
for i in loneSet:
if original.count(i) == 1:
retSum += i
return retSum
| StarcoderdataPython |
3371669 | import pytest
from pytest import param
from fastapi.testclient import TestClient
from forest_lite.server import main
from forest_lite.server.routers import atlas
client = TestClient(main.app)
@pytest.mark.parametrize("name,category,scale,expect", [
param("physical", "coastline", "110m",
137, id="coast... | StarcoderdataPython |
3222424 | # -*- coding: utf-8 -*-
# imports
import numpy as np
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
device = "cpu"
print(device)
from google.colab import drive
drive.mount('/content/drive')
import torch, torchvision, torchvision.transforms as transforms
from torchvision.datasets import Fashi... | StarcoderdataPython |
116171 | from fastapi import Depends, FastAPI
#from .image.image.uncolorization import users
app = FastAPI()
import importlib
import pkgutil
def import_submodules(package, recursive=True):
""" Import all submodules of a module, recursively, including subpackages
:param package: package (name or actual module)
... | StarcoderdataPython |
1676887 | <gh_stars>1-10
#!usr/bin/env python3
# when I create a context manager, I don't have to worry about closing the file
# when I'm done with it; the context manager will simply do it for me.
# for creating a context manager we simple use "with" before "open"
# open a file for writing data
# "w" means write, "r" means re... | StarcoderdataPython |
3461 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#__Author__ = 烽火戏诸侯
#_PlugName_ = Shop7z /admin/lipinadd.asp越权访问
import re
def assign(service, arg):
if service == "shop7z":
return True, arg
def audit(arg):
payload = 'admin/lipinadd.asp'
target = arg + payload
code, head,res, errcode... | StarcoderdataPython |
1641059 | ## reading different inputs
from py3plex.core import multinet
multilayer_network = multinet.multi_layer_network().load_network("../datasets/multiedgelist2.txt",directed=False, input_type="multiedgelist")
multilayer_network.basic_stats()
## Let's count node properties.
node_layer_tuples = set()
unique_nodes = set()... | StarcoderdataPython |
88435 | import random
import os
import numpy as np
from scipy.ndimage.filters import median_filter
import os
import random
import numpy as np
from scipy.ndimage.filters import median_filter
def gaussian_noise(img, mean=0, sigma=0.03):
img = img.copy()
noise = np.random.normal(mean, sigma, img.shape)
mask_overflo... | StarcoderdataPython |
1689549 | """updated support_texts field
Revision ID: 7bf20ada100b
Revises: cbaba<PASSWORD>
Create Date: 2021-01-26 16:06:44.264345
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "7bf20ada100b"
down_revision = "cbaba765195a"
branch_labels = None
depends_on = None
def ... | StarcoderdataPython |
3222397 | <gh_stars>1-10
import os
import random
from .. import Problem, ProblemInstance, instance_path
from ...util import mkfile, curr_dir_relative
from ...system import *
NUM_TRIALS = 20
def partition(xs, rate=50):
k = int((len(xs) / 100)*rate)
return xs[:k], xs[k:]
class Hexose(Problem):
def __init__(self,... | StarcoderdataPython |
1614120 | <gh_stars>1-10
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload... | StarcoderdataPython |
106857 | <reponame>cnakhl/quimb<gh_stars>0
import functools
from numbers import Integral
from itertools import product, starmap
from collections import defaultdict
from autoray import do
from ..gen.rand import randn, seed_rand
from . import array_ops as ops
from .tensor_core import (
Tensor,
TensorNetwork,
oset,
... | StarcoderdataPython |
199553 | <gh_stars>0
from django.core.management import BaseCommand
from faker import Faker
from random import randrange
from core.models import Order, OrderItem
class Command(BaseCommand):
def handle(self, *args, **options):
faker = Faker()
for _ in range(3):
order = Order.objects.create(
... | StarcoderdataPython |
3226158 | <gh_stars>1-10
#!/usr/bin/env python
"""Tests the HTTP remote data store abstraction."""
import os
import platform
import shutil
import socket
import tempfile
import threading
import unittest
import ipaddr
import portpicker
import logging
from grr.lib import data_store
from grr.lib import data_store_test
from grr... | StarcoderdataPython |
3243119 | <gh_stars>1-10
""" Forum serializers. """
from django.core.exceptions import ObjectDoesNotExist
from django.db import IntegrityError
from rest_framework import serializers
from forum.models import Forum, Branch, Thread, Post, PostLike, ThreadLike, ForumMembership, \
BranchMembership, PostViewer, ThreadViewer
from ... | StarcoderdataPython |
4838771 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2019-08-13 09:25
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('commercialoperator', '0006_merge_20190809_1412'),
]
operations = [
migratio... | StarcoderdataPython |
1721216 | import cv2
import qr_code_decoder
capture = cv2.VideoCapture(1, cv2.CAP_DSHOW) ## remove the cv2.CAP_DSHOW if any errors occour
while True:
_, frame = capture.read()
cv2.imshow('frame', frame)
k = cv2.waitKey(1)
if k == 27:
break
try:
print(qr_code_decoder.decode_qr_codes... | StarcoderdataPython |
21607 | <filename>utils/tracker.py
import os
import numpy as np
class Tracker:
def __init__(self, seed, model_name):
self.save_tag = model_name + '_seed_' + str(seed)
self.model_save = "models/"
if not os.path.exists(self.model_save): os.makedirs(self.model_save)
def save_model(self, model):
... | StarcoderdataPython |
3216099 | <filename>arclet/edoves/mah/server_docker.py
import asyncio
import json
from asyncio import Event
from typing import Optional, Union, Dict, Any, Tuple, TYPE_CHECKING
from aiohttp import FormData, WSMsgType, WebSocketError
from arclet.edoves.main.server_docker import BaseServerDocker, DockerBehavior, BaseDockerMetaCompo... | StarcoderdataPython |
4840473 | from django.contrib import admin
from .models import RelatorioIdade, RelatorioCidade, RelatorioCracha, RelatorioHospedagem, RelatorioStatusPagamento
@admin.register(RelatorioCidade)
class RelatorioCidadeAdmin(admin.ModelAdmin):
change_list_template = "relatorios/relatorio_cidade.html"
def changelist_view(se... | StarcoderdataPython |
3343689 | import graphene
import graphql_jwt
import apps.accounts.schema
import apps.hn.schema
class Query(
apps.accounts.schema.Query, apps.hn.schema.Query, graphene.ObjectType,
):
pass
class Mutation(
apps.accounts.schema.Mutation,
apps.hn.schema.Mutation,
graphene.ObjectType,
):
token_auth = graph... | StarcoderdataPython |
3348196 | <reponame>hemanthkini/prometheus-es-exporter<filename>prometheus_es_exporter/utils.py
import functools
import logging
import signal
import sys
from collections import OrderedDict
log = logging.getLogger(__name__)
def merge_dicts_ordered(*dict_args, **extra_entries):
"""
Given an arbitrary number of dictiona... | StarcoderdataPython |
28655 | <gh_stars>0
b = "r n b q k b n r p p p p p p p p".split(" ") + ['.']*32 + "p p p p p p p p r n b q k b n r".upper().split(" ")
def newBoard():
b = "r n b q k b n r p p p p p p p p".split(" ") + ['.']*32 + "p p p p p p p p r n b q k b n r".upper().split(" ")
def display(): #white side view
... | StarcoderdataPython |
1699378 | <filename>top10_errorplot.py
from datetime import datetime
from functools import partial
import numpy as np
import utils
from pagerank import PageRank, MCPageRank
from hits import HITS, MCHITS
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(context='poster', style='whitegrid')
if __name__ == '__main__':
... | StarcoderdataPython |
150114 | <gh_stars>0
'''
Created on Nov 12, 2018
@author: yangzh
'''
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import OS_Script | StarcoderdataPython |
3306657 | # Ignoring some linting rules in tests
# pylint: disable=redefined-outer-name
# pylint: disable=missing-docstring
import pytest
from bingo.symbolic_regression.benchmarking.benchmark_test import BenchmarkTest
from bingo.symbolic_regression.agraph.agraph import AGraph
def dummy_train_function(training_data):
dumm... | StarcoderdataPython |
94291 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import datetime as dt
from pandas_datareader import data
import statsmodels.api as sm
from statsmodels.tsa.seasonal import STL
import pandas_datareader.data as DataReader
def get_stock(stock,start,end):
df = data.DataReader(stock, 'stooq',star... | StarcoderdataPython |
1791706 | import sys
PY2 = sys.version_info[0] == 2
if PY2:
def iteritems(d):
return d.iteritems()
def itervalues(d):
return d.itervalues()
xrange = xrange
string_types = (unicode, bytes)
def to_str(x, charset="utf8", errors="strict"):
if x is None or isinstance(x, str):
... | StarcoderdataPython |
3206146 | <filename>site/mysite/settings/local.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
SECRET_KEY = <KEY>"
DEBUG = False
ALLOWED_HOSTS = ['*']
# COMPRESS_ENABLED = True
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.co... | StarcoderdataPython |
3202206 | <reponame>vonguyenleduy/parametric_lasso_selective_inference
import numpy as np
from mpmath import mp
mp.dps = 500
def construct_s(bh):
s = []
for bhj in bh:
if bhj != 0:
s.append(np.sign(bhj))
s = np.array(s)
s = s.reshape((len(s), 1))
return s
def construct_A_XA_Ac_XAc_b... | StarcoderdataPython |
4814424 | <reponame>o-netzer/operations1<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 27 21:05:02 2016
@author: netzer
This .py file is a module for the operations1 project and only contains
XML-templates used in various scripts of that project. For security reasons the
contents of the templates was left b... | StarcoderdataPython |
89264 | # Copyright The PyTorch Lightning team.
#
# 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 i... | StarcoderdataPython |
3224364 | <filename>wsgi.py
import os
from dotenv import load_dotenv
flaskenv_path = os.path.join(os.path.dirname(__file__), '.flaskenv')
env_path = os.path.join(os.path.dirname(__file__), '.env')
if os.path.exists(flaskenv_path):
load_dotenv(flaskenv_path)
if os.path.exists(env_path):
load_dotenv(env_path)
from bluel... | StarcoderdataPython |
4814351 | <reponame>Samakwa/PyDS
def fibo(n) :
if n<2 :
return 1
else :
return fibo(n-2) + fibo(n-1)
succ = lambda x : x+1
fibo1 = lambda x : 1 if x<2 else fibo1 (x-1) + fibo1(x-2)
def fibo2(n) :
i = 1
j = 1
k=0
while(k<n) :
ij=i+j
i=j
j=ij
k+=1
return i
def fibos(n) :
def f... | StarcoderdataPython |
3243913 | # coding: utf-8
from ptrlib.asm.assembler import *
| StarcoderdataPython |
1796020 | <reponame>ckamtsikis/cmssw<filename>DQMOffline/CalibTracker/test/CRAFTCalib/SiStripDQMBadStripsValidation_cfg.py
import FWCore.ParameterSet.Config as cms
process = cms.Process( "SiStripDQMBadStripsValidation" )
### Miscellanous ###
## Logging ##
process.options = cms.untracked.PSet(
wantSummary = cms.untracked.b... | StarcoderdataPython |
1668385 | <filename>main.py
import pygame
import os
import time
# map
_map = """
00000000000000
00111100000011
10000001110000
11111111110000
11111111100011
11111111111111
"""
# global
ids = 0
# load images into game
BASE_SIZE = [80,80]
IMAGES = {}
# entities and blocks list
entities = {}
blocks = []
block_hitbox = []
# lin... | StarcoderdataPython |
106903 | """
Copyright (c) 2017, <NAME>.
Distributed under the terms of the MIT License.
The full license is in the file LICENSE, distributed with this software.
Created on May 20, 2017
@author: jrm
"""
from atom.api import Typed, ForwardTyped, Bool, observe
from enaml.core.declarative import d_
from enaml.core.conditional ... | StarcoderdataPython |
1708025 | <filename>school/migrations/0023_auto_20210519_1149.py
# Generated by Django 3.0.5 on 2021-05-19 06:19
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('school', '0022_auto_20210519_1100'),
]
operations = [
migrations.Crea... | StarcoderdataPython |
137378 | from flask import Response, request
from io import BytesIO
import xml.etree.ElementTree
from fHDHR.tools import sub_el
class RMG_Devices_DeviceKey_Scanners():
endpoints = ["/devices/<devicekey>/scanners", "/rmg/devices/<devicekey>/scanners"]
endpoint_name = "rmg_devices_devicekey_scanners"
endpoint_metho... | StarcoderdataPython |
1600721 | <reponame>MisakaMikoto0502/zeroday
import discord
from discord.ext import commands
from app.ext.music.filter import safe
from app.controller.logger import Logger
def ytdl_format_options_a():
options = {
"format": "bestaudio/best",
"outtmpl": "downloads/%(extractor)s-%(id)s-%(title)s.%(ext... | StarcoderdataPython |
4840662 | <filename>py/examples/spinbox.py<gh_stars>1-10
# Form / Spinbox
# Use a spinbox to allow users to incrementally adjust a value in small steps.
# ---
from h2o_wave import main, app, Q, ui
@app('/demo')
async def serve(q: Q):
if q.args.show_inputs:
q.page['example'].items = [
ui.text(f'spinbox={... | StarcoderdataPython |
1688348 | from datetime import datetime
from app import DATETIME_FORMAT
from tests.app.db import (
create_api_key,
create_service,
create_notification,
create_template
)
from app.models import (
KEY_TYPE_NORMAL,
)
def test_get_api_key_stats_with_sends(admin_request, notify_db, notify_db_session):
ser... | StarcoderdataPython |
1735502 | <filename>openedx/tasks_test.py
"""Courseware tasks"""
import pytest
from openedx import tasks
from users.factories import UserFactory
@pytest.mark.django_db
def test_create_edx_user_from_id(mocker):
"""Test that create_edx_user_from_id loads a user and calls the API method to create an edX user"""
patch_cre... | StarcoderdataPython |
4837359 | #!/usr/bin/env python3
# Copyright (c) 2019 FRC Team 1678: Citrus Circuits
"""Export data from local MongoDB database to CSV file for picklist editor spreadsheet.
Timestamps files. Data exports also used for analysts in stands at competition.
"""
import argparse
import csv
from datetime import datetime
from data_tran... | StarcoderdataPython |
1668190 | <reponame>ZHider/bitrate-viewer
import json
import xml.etree.ElementTree as ET
class FileParser:
def __calculate_bitrate_per_sec(self, bitrates):
seconds = []
bitrates_per_sec = []
current_second = 0
current_bitrate = 0
frame_count = 0
for bitrate in bi... | StarcoderdataPython |
27159 | from datetime import timedelta
from dotenv import load_dotenv
from azure.identity import DefaultAzureCredential
from azure.mgmt.media import AzureMediaServices
from azure.storage.blob import BlobServiceClient
from azure.mgmt.media.models import (
Asset,
Transform,
TransformOutput,
StandardEncoderPreset,
AacAu... | StarcoderdataPython |
3381934 | <reponame>enermaps/heatlearn
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 22 12:11:55 2021
@author: giuseppeperonato, rboghetti
Original template from https://www.pyimagesearch.com/2019/01/28/keras-regression-and-cnns/
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as pl... | StarcoderdataPython |
3395561 | # Generated by Django 3.1.1 on 2020-09-19 11:41
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='File',
fields=[
('id', models.AutoField(aut... | StarcoderdataPython |
3293278 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
class DNN_cart_search(nn.Module):
def __init__(self, cont_field, cate_field, comb_field, cate_cont_feature,
comb_feature, criterion, selected_pairs, orig_embedding_dim=32,
... | StarcoderdataPython |
120804 | <reponame>OSHI7/Learning1<filename>LM/fit.py<gh_stars>0
"""
Curve Fit example
@luis.fernandes
#Nov 20 2019
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def lorentzian(x, amplitude, x0, sigma, background):
# A lorentzian peak with:
# Constant... | StarcoderdataPython |
192426 | <reponame>laowantong/paroxython
"""Pick uniformly a random floating point number in [a..b[.
Pick a random number greater than or equals to _a, strictly inferior to _b. Precondition : _a < _b.
Source: programming-idioms.org
"""
# Implementation author: vinodv
# Created on 2019-09-28T08:37:42.776686Z
# Last modified o... | StarcoderdataPython |
3311621 | from base.base_train import BaseTrain
from tqdm import tqdm
import numpy as np
class TemplateTrainer(BaseTrain):
def __init__(self, sess, model, config):
super(TemplateTrainer, self).__init__(sess, model, config)
def train_step(self):
"""
implement the logic of the train step
... | StarcoderdataPython |
3240564 | from bs4 import BeautifulSoup
import Model.MainModel
from Crawler import Crawl as crawl
from Crawler import CrawlThread as thread
import sys
model = Model.MainModel.MainModel.GetInstance()
def oddTo10(u, d):
return (u + d) / d
def ruleBy500(soup):
obj = {}
# obj['odd'] = soup.find_all("tbody", attrs={"... | StarcoderdataPython |
1675844 | <reponame>priyanka-choubey/kolibri
from django.conf.urls import include
from django.conf.urls import url
from rest_framework import routers
from .api import ChannelMetadataViewSet
from .api import ContentNodeGranularViewset
from .api import ContentNodeProgressViewset
from .api import ContentNodeSearchViewset
from .api... | StarcoderdataPython |
92774 | <filename>broken/new/samuel.py
import re
from tqdm import tqdm
import string
import random
from _table import lookup_subbyte, reverse_subbyte_lookup, character_lookup
def fill_list(list, characters: int):
list.append("&")
for i in range(characters):
list.append(hex(ord(random.choice(string.ascii_letter... | StarcoderdataPython |
1604388 | <reponame>camvogel/dagster<filename>python_modules/dagster/dagster/core/asset_defs/asset.py
from typing import Mapping
from dagster.core.definitions import OpDefinition
from dagster.core.definitions.events import AssetKey
class AssetsDefinition:
def __init__(
self,
input_names_by_asset_key: Mappi... | StarcoderdataPython |
1646503 | import datetime
import json
from carball.generated.api.metadata import player_loadout_pb2
from sqlalchemy import func, desc, literal
from backend.blueprints.spa_api.service_layers.utils import with_session
from backend.database.objects import Loadout, Game
from backend.database.startup import lazy_get_redis
from back... | StarcoderdataPython |
3306355 | <filename>user.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# User Module.
# Including User class and reading/writing implementations
#
import re, os, json, time
import config
import database
from hashlib import md5
cursor = database.conn.cursor()
class User:
def __init__(self, dbRow=None):
'''
... | StarcoderdataPython |
3249752 | # Copyright 2017-2021 <NAME>
#
# 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 writ... | StarcoderdataPython |
191462 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
ROOT="../"
FILE=ROOT + "packs/actions.db"
import json
# read file
with open(FILE, 'r') as f:
content = f.readlines()
for line in content:
obj = json.loads(line)
with open(ROOT + 'data/actions/' + obj['_id'] + ".htm", 'w') as df:
df.write('Name: ' + obj['name'... | StarcoderdataPython |
3349111 | <gh_stars>1-10
#c_input-pool readout
# h------------------>td ------->
# c-p us
# h-------------->td --------->
# c-p us
# h---------->td ----------->
# c-p us
# h------>td ------------->
# c-p us
# h ------------------>
import... | StarcoderdataPython |
3262797 | <reponame>prasoonbatham11/cfcli<filename>cf/__main__.py
import sys
import argparse
import requests
import json
from cf.user_info import *
from cf.user_rating import *
from cf.contest_list import *
from cf.problems import *
from cf.blog import *
from cf.ratingchange import *
from cf.bloguser import *
from cf.userstatus ... | StarcoderdataPython |
3535 | <reponame>wesokes/django-query-builder<filename>querybuilder/tests/window_tests.py<gh_stars>100-1000
from querybuilder.fields import (
RankField, RowNumberField, DenseRankField, PercentRankField, CumeDistField, NTileField, LagField,
LeadField, FirstValueField, LastValueField, NthValueField, NumStdDevField
)
fro... | StarcoderdataPython |
12167 | import time
import board
import busio
from digitalio import DigitalInOut
from adafruit_esp32spi import adafruit_esp32spi
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
import neopixel
# Import Philips Hue Bridge
from adafruit_hue import Bridge
# Get wifi details and more from a secrets.py file
... | StarcoderdataPython |
3265874 | """Drive Types."""
from typing import List, Type
from .drive_type import DriveType
from .metadata import MetadataDriveType
from .no_action import NoActionDriveType
from .usercode import UserCodeDriveType
# List of drive types, in priority order.
# The first one that matches will be selected.
DRIVE_TYPES: List[Type[D... | StarcoderdataPython |
118410 | from .pressure import Pressure
__author__ = '<NAME>'
__maintainer__ = '<NAME>' | StarcoderdataPython |
169599 | <reponame>Phate334/taiwan-movie-time
# -*- coding: utf-8 -*-
""" parser for Yahoo movie website.
"""
import re
import requests
from bs4 import BeautifulSoup
HOST = 'https://tw.movies.yahoo.com'
def get_theaters():
""" yield theater's meta data.
Yield:
{
'id': theater id,
'... | StarcoderdataPython |
3316602 | __author__ = '<NAME>'
__email__ = '<EMAIL>'
__date__ = '12/25/2020 12:07 PM'
class Solution:
def preorder(self, root: 'Node') -> List[int]:
if not root:
return []
result = []
stack = [root]
while stack:
node = stack.pop()
result.append(node.val)... | StarcoderdataPython |
98963 | <reponame>SmithSamuelM/keripy-wot
# -*- encoding: utf-8 -*-
"""
KERI
keri.app.apping module
"""
import os
from hio.base import doing
from hio.core import wiring
from hio.core.serial import serialing
from .. import kering
from .. import help
from ..db import basing
from . import keeping, habbing, directing, configing... | StarcoderdataPython |
4830941 | """Validate data in private_modules.json.
Keys are a list of all public/documented modules. The values are the lists of
private/non-public modules that the public module relies on.
"""
import json
import pathlib
import sys
with open("module_names.json", "r", encoding="utf-8") as file:
module_names = frozenset(js... | StarcoderdataPython |
1641344 | import numpy as np
from tqdm import tqdm
def generate_sample_data(filename, item_count=1000, basket_count=100000, seed=123):
print("Creating data set of {} baskets with {} unique items".format(basket_count, item_count))
np.random.seed(seed)
# Create item indices and probability of being selected in the ... | StarcoderdataPython |
36377 | <reponame>jolynch/service-capacity-modeling
import math
from decimal import Decimal
from typing import Any
from typing import Dict
from typing import Optional
from typing import Sequence
from typing import Tuple
from service_capacity_modeling.interface import AccessConsistency
from service_capacity_modeling.interface ... | StarcoderdataPython |
3215635 | <filename>events/contrib/plugins/form_elements/security/honeypot/fobi_form_elements.py
from __future__ import absolute_import
from fobi.base import form_element_plugin_registry
from .base import HoneypotInputPlugin
__title__ = 'fobi.contrib.plugins.form_elements.security.' \
'honeypot.fobi_form_elements'... | StarcoderdataPython |
21986 | <reponame>NECOTIS/CRITICAL
# Copyright (c) 2012-2018, NECOTIS
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# - Redistributions of source code must retain the above copyright notice,
# thi... | StarcoderdataPython |
141460 | #!python
from __future__ import print_function
import sys
import ctypes
from ctypes import byref, sizeof
from ctypes.wintypes import BOOL, DWORD
import select
import socket
import struct
try:
import servicemanager
import win32api
import win32con
import win32security
import win32service
import ... | StarcoderdataPython |
4815716 | <gh_stars>1000+
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-18 16:54
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0040_u2fdevice'),
]
... | StarcoderdataPython |
1749276 | <gh_stars>1-10
from pyjavaproperties.pyjavaproperties import Properties
name = "pyjavaproperties"
| StarcoderdataPython |
3364814 | <gh_stars>1-10
"""
Generate StyledLayerDescriptor objecs for django querysets.
This generator uses the python-sld and pysal libraries to generate classes
for map classification, and returns a StyledLayerDescriptor class object. This
class object may be serialized to an SLD XML file, which is useful for many
GIS and ma... | StarcoderdataPython |
4824154 | <gh_stars>1-10
"""
Module to load outages data from ENTSO-E.
"""
from .load import * | StarcoderdataPython |
1666420 | <gh_stars>0
import csv
from dataclasses import dataclass
from lib.graphe import Graphe
from lib.page import Page
from lib.utilisateur import Utilisateur
@dataclass(frozen=True)
class BadDataFormatException(Exception):
error: str = ""
class DataLoader:
@staticmethod
def load(path : str):
"""
... | StarcoderdataPython |
25411 | <gh_stars>1-10
import numpy as np
import matplotlib.pyplot as plt
from plot_data import plot_data
def visualize_boundary(X, y, clf):
"""
Plots a linear decision boundary learned by the SVM.
Parameters
----------
X : ndarray, shape (n_samples, n_features)
Samples, where n_samples is the n... | StarcoderdataPython |
1648982 | <reponame>spennymac/pysecretary
import re
from typing import Tuple
from pysecretary import InvalidPrefixError
PREFIX_PATTERN = re.compile(r"(^(\w+):\/\/)")
VALID_PREFIX = re.compile(r"^\w+")
def parse(v: str) -> Tuple[str, str]:
elements = re.split(PREFIX_PATTERN, v, maxsplit=1)
if len(elements) == 4:
... | StarcoderdataPython |
1690285 | # Python packages
from _socket import SHUT_RDWR
import socket
import struct
import time
import timer
try: # Python 3
import socketserver
except ImportError: # Python 2
import SocketServer as socketserver
import threading
# Third-party packages
# Modules from this project
import globals as G
from savingsyste... | StarcoderdataPython |
3332548 | #Analysis # distribution for the 3-D Rods
#Author: <NAME>
#Date: 2015 July 28
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import math
from matplotlib import rc
rc('font',**{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)
def his():
N1 = [] # Ver
N2 = [] # Hor
N... | StarcoderdataPython |
3318586 | <filename>baseq/snv/vcf/annovar.py
import os
import pandas as pd
def filter_annovar_result(inPath, outPath):
df = pd.read_csv(inPath)
csv_filter = df[df["1000G2015aug_ALL"]<0.5]
return csv_filter
class GATKVCF:
def __init__(self, path):
pass
class Annovar_Filter:
def __init__(self, path):... | StarcoderdataPython |
1633178 | # Dedicated to the public domain under CC0: https://creativecommons.org/publicdomain/zero/1.0/.
'''
`craft-py-ext` is an experimental tool for generating the boilerplate to build simple CPython extensions.
It should be considered a work in progress.
To use it, you write a `.pyi` type declaration file, and then genera... | StarcoderdataPython |
4338 | import pprint
from FactorioCalcBase.data.binary import sorted_recipe_list, production_machine_category_list_dict
from FactorioCalcBase.recipe import Recipe
from FactorioCalcBase.calculator_base import CalculatorBase
from FactorioCalcBase.dependency_dict_common_function import dict_add_number
import time
def test_chan... | StarcoderdataPython |
173255 | <reponame>pyy1988/pyy_test1
# encoding: utf-8
# module termios
# from /usr/lib/python3.5/lib-dynload/termios.cpython-35m-x86_64-linux-gnu.so
# by generator 1.145
"""
This module provides an interface to the Posix calls for tty I/O control.
For a complete description of these calls, see the Posix or Unix manual
pages. I... | StarcoderdataPython |
3289831 | <reponame>Nimor111/pazaak-python<filename>core/player.py
from dataclasses import dataclass, field
@dataclass
class Player:
player: int = field(default=0)
def toggle_player(self):
raise NotImplementedError
def toggle_player_new(self, player: 'Player'):
raise NotImplementedError
| StarcoderdataPython |
3347013 | #
# Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates
#
# 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 ap... | StarcoderdataPython |
4831019 | <filename>tests/components/test_nuheat.py
"""NuHeat component tests."""
import unittest
from unittest.mock import patch
from tests.common import get_test_home_assistant, MockDependency
from homeassistant.components import nuheat
VALID_CONFIG = {
"nuheat": {
"username": "warm",
"password": "<PASSW... | StarcoderdataPython |
153418 | <reponame>userFour/MECH491-postprocessor
# ------------------------------------------------------------------------------
# 5-Axis Postprocessor Python Implementation
#
#
# Authors: Phillip, Markos Date: 2021-10-15T10:33:10
#
# ------------------------------------------------------------------------------
#
# This sc... | StarcoderdataPython |
1673070 | # <NAME> 2017
#
# screenlamp is a Python toolkit
# for hypothesis-driven virtual screening.
#
# Copyright (C) 2017 Michigan State University
# License: Apache v2
#
# Software author: <NAME> <http://sebastianraschka.com>
# Software author email: <EMAIL>
#
# Software source repository: https://github.com/rasbt/screenlamp... | StarcoderdataPython |
153352 | <filename>orttraining/orttraining/test/python/checkpoint/_test_helpers.py
import os
import pickle
from itertools import islice
import torch
import torch.distributed as dist
from onnxruntime import set_seed
from onnxruntime.training import amp, checkpoint, optim, orttrainer
from orttraining_test_orttrainer_frontend im... | StarcoderdataPython |
3238709 | import json
import os
import pathlib
import urllib.parse
from typing import Any, Dict, Union, cast
from unittest.mock import Mock
import pytest
import yaml
from globus_automate_client import flows_client
VALID_FLOW_DEFINITION = {
"StartAt": "perfect",
"States": {
"perfect": {
"Type": "Pas... | StarcoderdataPython |
1792952 | from flask import Blueprint, request
import config
from blueprints.private.settings import setting
from modules.registration import Registration
from modules.validations import Validation
PublicForm_bp = Blueprint("PublicForm_bp", __name__)
register = Registration()
validate = Validation()
def responseData(data):
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.