id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
1663002
<filename>src/server/wsgi/shopster/commodity/serializer.py from rest_framework import serializers from rest_framework import serializers from .models import Product, Order, Order_Item, Category class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product # fields = ('id', 'ti...
StarcoderdataPython
41893
<filename>ib/ext/cfg/EWrapperMsgGenerator.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ ib.ext.cfg.EWrapperMsgGenerator -> config module for EWrapperMsgGenerator.java. """ modulePreamble = [ 'from ib.ext.AnyWrapperMsgGenerator import AnyWrapperMsgGenerator', 'from ib.ext.Util import Util', ]
StarcoderdataPython
106571
"""Implementation of a CNN for classfication with VGG Encoder.""" import torch import torchvision.models as models from torch.nn import CrossEntropyLoss, Linear, Module from src.utils.mapper import configmapper STR_MODEL_MAPPING = { "11": models.vgg11, "13": models.vgg13, "16": models.vgg16, "19": m...
StarcoderdataPython
92438
from decimal import Decimal from typing import Any, Optional from freshbooks.api.accounting import AccountingResource from freshbooks.api.resource import HttpVerbs from freshbooks.errors import FreshBooksError from freshbooks.models import Result class EventsResource(AccountingResource): """Handles resources und...
StarcoderdataPython
1763551
<filename>twitter_app/twitter_bot/views.py from django.shortcuts import render import tweepy, requests import sys, requests, json, time, os from django.contrib.messages.views import messages from .forms import InputForm from django.conf import settings CONSUMER_KEY = settings.CONSUMER_KEY CONSUMER_SECRET = settings.C...
StarcoderdataPython
14391
<filename>ssd_project/functions/multiboxloss.py import torch import torch.nn as nn import torch.nn.functional as F from math import sqrt as sqrt import collections import numpy as np import itertools from ssd_project.utils.utils import * from ssd_project.utils.global_variables import * device = DEVICE class MultiBoxLo...
StarcoderdataPython
81142
<reponame>tobby2002/python-sandbox import matplotlib.pyplot as plt import pandas as pd # http://queirozf.com/entries/pandas-dataframe-plot-examples-with-matplotlib-pyplot df = pd.DataFrame({ 'name': ['john','mary','peter','jeff','bill','lisa','jose'], 'age': [23,78,22,19,45,33,20], 'gender': ['M','F','M','...
StarcoderdataPython
3299397
<reponame>jiaju-yang/leetcode # # @lc app=leetcode id=139 lang=python3 # # [139] Word Break # from typing import List # @lc code=start class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: dp = [False] * (len(s) + 1) dp[0] = True max_word_len = len(max(wordDict, key=len...
StarcoderdataPython
106716
<reponame>DeepLearnI/atlas def load_parameters(log_parameters=True): try: parameters = _parsed_json(_raw_json_from_parameters_file()) if log_parameters: log_params(parameters) return parameters except FileNotFoundError: return {} def flatten_parameter_dictionary(...
StarcoderdataPython
3210766
<reponame>Penchekrak/Distilling-Object-Detectors from .VOC import VOC
StarcoderdataPython
1654325
<reponame>Khufos/10FastFingersBot "Version Python 3.8.7 64bits" "Você precisa de duas bibliotecas Selenium e pyautogui" "10 fast fingers" "TRADUÇÃO , DEDOS RAPIDOS." '''WebDriver é uma ferramenta de código aberto para teste automatizado de aplicativos da web em vários navegadores. Ele fornece recursos para navegar par...
StarcoderdataPython
1779281
<reponame>PacktPublishing/Boosting-Machine-Learning-Models-in-Python """ Voting classifier example, by default it's set up for majority/hard voting mode. """ from section1_video5_data import get_data from sklearn import model_selection from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier from skle...
StarcoderdataPython
4813752
import mpmath __all__ = ['yeo_johnson', 'inv_yeo_johnson'] def yeo_johnson(x, lmbda): r""" Yeo-Johnson transformation of x. See https://en.wikipedia.org/wiki/Power_transform#Yeo%E2%80%93Johnson_transformation """ with mpmath.extradps(5): x = mpmath.mpf(x) lmbda = mpmath.mpf(lmb...
StarcoderdataPython
19348
<reponame>littlepea/django-auction<filename>auction/models/bidbasket.py<gh_stars>1-10 import importlib from django.conf import settings from auction.utils.loader import load_class AUCTION_BIDBASKET_MODEL = getattr(settings, 'AUCTION_BIDBASKET_MODEL', 'auction.models.defaults.BidBasket') BidBasket = load_class(AUC...
StarcoderdataPython
66279
### The point of this module is that, ### when you import it, you get the "vendor" directory ### on your python's sys.path. import sys import os.path import site already_vendorified = False def vendorify(): global already_vendorified if already_vendorified: return ROOT = os.path.dirname(os.path.a...
StarcoderdataPython
56149
from django import template from core.models import Order from django.contrib.auth.decorators import login_required register = template.Library() @login_required @register.simple_tag def product_cart_item_count(user,slug): obj = Order.objects.filter(user__username=user,ordered=False) if obj.exists(): ...
StarcoderdataPython
109130
#!/home/nitin/Learn/Repositories/Github/WebApps/SimpleIsBetterThanComplex.com/myproject/.env/bin/python3 from django.core import management if __name__ == "__main__": management.execute_from_command_line()
StarcoderdataPython
1691320
<filename>src/final/config.py # + from sqlalchemy import create_engine import psycopg2 def dbconfig(): db = {"host": "affordablehousing.a2hosted.com", "port": 5432, "database": "afford31_housing", "user": "afford31_siads", "pass": "<PASSWORD>"} pg_string = f...
StarcoderdataPython
10361
# -*- coding: utf-8 -*- ''' Copyright 2012 <NAME> <<EMAIL>> 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 agree...
StarcoderdataPython
185044
i=0 while 1: a = int(input()) if a == 0 : break i+=1 print "Case %d: %d" % (i, a)
StarcoderdataPython
1732384
<reponame>Jemie-Wang/ECE5725_Project-Reptile_Monitoring_System #!/usr/bin/env python # Capture data from a DHT11 sensor and save it on a database import time import sqlite3 import board import adafruit_dht import RPi.GPIO as GPIO import os dbname='../sensorData.db' sampleFreq = 10 # time in seconds dhtDevice = adafr...
StarcoderdataPython
1778931
#!/usr/bin/python import sys import xml.etree.ElementTree as ET import re import os import datetime import shutil import time import glob import cgi import cgitb import sqlite3 import subprocess import random from ast import literal_eval as make_tuple import math MAX_RESPONCE_ITEMS = int(10000) MODE = "fast" #fast /...
StarcoderdataPython
4810160
<reponame>alexanderlopoukhov/CDMSouffleur import os import pandas as pd from pathlib import Path from pyspark.sql.utils import AnalysisException from cdm_souffleur.utils.utils import spark from cdm_souffleur.utils.constants import VOCABULARY_DESCRIPTION_PATH from cdm_souffleur.utils.utils import Database def load_voc...
StarcoderdataPython
4823082
<gh_stars>1-10 """Adds repositories/archives.""" ######################################################################## # DO NOT EDIT THIS FILE unless you are inside the # https://github.com/3rdparty/eventuals-grpc-examples repository. If you # encounter it anywhere else it is because it has been copied there in # o...
StarcoderdataPython
1746602
<filename>wce_triage/setup/install_boot.py #!/usr/bin/python3 # # import os, sys, subprocess if os.getuid() != 0: print("***** install_boot would only work as root *****") sys.exit(1) # subprocess.run(['update-grub']) # subprocess.run(['update-initramfs', '-u']) # subprocess.run(['mkdir', '/ro']) subprocess....
StarcoderdataPython
3289931
import sqlite3 with sqlite3.connect("test.db") as conn: all_food = conn.execute("SELECT * FROM food") for food in all_food: print(food) conn.execute("INSERT INTO food (name, price) VALUES ('salad', 7.77)") conn.commit() all_food_again = conn.execute("SELECT * FROM food") for food...
StarcoderdataPython
110200
<gh_stars>0 from django.urls import include, path from rapidsms.backends.kannel import views urlpatterns = ( path('account/', include('rapidsms.urls.login_logout')), path('delivery-report/', views.DeliveryReportView.as_view(), name='kannel-delivery-report'), path('backend/kannel/', ...
StarcoderdataPython
4838142
# 1089 - Loop Musical # https://www.urionlinejudge.com.br/judge/pt/problems/view/1089 def peaks(sample): # add the last in the beginning and the first in the end magnitudes = sample[-1:] + sample + sample[:1] # loop through a magn, its previous magn, and the next one for prev, magn, nxt in zip(magnitu...
StarcoderdataPython
1758557
""" --------------------------------------------------------------------------------- The main shine server running as backend and waiting for incoming Game connections to be served - using the twisted library by <NAME> (c) 2017 ducandu GmbH ----------------------------------------------------------------------...
StarcoderdataPython
4811557
""" Testing the exponential map """ import sys import spin import numpy as np import unittest import csb.numeric as csb import matplotlib.pylab as plt from params import ExponentialMap from scipy.linalg import logm from spin.rotation import skew_matrix from littlehelpers import make_title class TestExpMap(unittest....
StarcoderdataPython
73323
<reponame>Preen1/Antipetros_Discord_Bot<filename>antipetros_discordbot/utility/enums.py # region [Imports] # * Standard Library Imports --> from enum import Enum, Flag, auto # endregion[Imports] class RequestStatus(Enum): Ok = 200 NotFound = 404 NotAuthorized = 401 class WatermarkPosition(Flag): T...
StarcoderdataPython
4813941
<gh_stars>1-10 # Copyright 2020 TWO SIGMA OPEN SOURCE, LLC # # 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 applica...
StarcoderdataPython
3339497
import logging import sys import time from botocore.exceptions import ClientError logger = logging.getLogger(__name__) class MaxRetriesExceededError(Exception): pass def wait(seconds, tick=12): """ Waits for a specified number of seconds, while also displaying an animated spinner. :param secon...
StarcoderdataPython
1601660
fist_name = "ada" last_name = "lovelace" full_name = f'{fist_name} {last_name}' message = f'Olá, {full_name.title()}!' print(message)
StarcoderdataPython
145889
from vk_api.longpoll import VkLongPoll, VkEventType import vk_api import dialogflow_v2 as dialogflow import random import os import logging import logging.config from dotenv import load_dotenv load_dotenv() VK_TOKEN = os.getenv('VK_TOKEN') PROJECT_ID = os.getenv('PROJECT_ID') GOOGLE_APPLICATION_CREDENTIALS = os.geten...
StarcoderdataPython
1651039
import pickle as pkl import numpy as np import time t1 = time.time() gsan_keep_data_list, gsan_right_data_list,gsan_left_data_list = [], [], [] for i in range(60): with open(f"new_data/new_data_{i}.pkl","rb") as f: _ = pkl.load(f) data = _['data'] label = _['label'] gsan_left_number = gsan_right...
StarcoderdataPython
1656430
from .testcases import * from .utils import *
StarcoderdataPython
98664
<filename>server/ec2-coordinator-app/src/initial_server/wait_for_sync_completion.py import time from loguru import logger from library import ssh, geth_status def wait(instance_dns, instance_type, datadir_mount, data_dir, debug_run, interrupt_avail_pct, status_interval_secs): logger.info(f"Monitoring get...
StarcoderdataPython
3341987
<gh_stars>0 from Statistics.SampleMean import sampleMean from Statistics.Proportion import proportion from Calculators.Subtraction import subtraction from Calculators.Division import division from Calculators.Multiplication import multiplication def var_sample_proportion(data): sample_data = data[0:999] samp_...
StarcoderdataPython
4832278
<reponame>motrom/kittitracking-pdfmht # -*- coding: utf-8 -*- """ taken from https://github.com/utiasSTARS/pykitti/blob/master/pykitti/odometry.py """ """Provides helper methods for loading and parsing KITTI data.""" from collections import namedtuple import numpy as np #from PIL import Image __author__ ...
StarcoderdataPython
3282032
<reponame>sethah/allencv from allencv.common.testing import AllenCvTestCase, ModelTestCase from allencv.data.dataset_readers import PairedImageReader from allencv.models import SemanticSegmentationModel from allencv.modules.image_encoders import ResnetEncoder, FPN from allencv.modules.image_decoders import BasicDecoder...
StarcoderdataPython
1708450
import os import googleapiclient.discovery import requests import json from private import private class RouteData: """ General catch all for all the functions and data for the main.py """ selection_danger = "Please submit a selection to view the other pages." wiki_err = """Currently, either t...
StarcoderdataPython
3344544
<gh_stars>0 # Generated by Django 2.1.2 on 2018-12-09 13:42 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('coupons', '0010_auto_20181209_2135'), ] operations = [ migrations.AlterField( model_name='coupon', ...
StarcoderdataPython
1725138
<reponame>jannschu/mkdocs-section-index import collections import logging import mkdocs.utils from jinja2 import Environment from mkdocs.plugins import BasePlugin from mkdocs.structure.nav import Navigation, Section from mkdocs.structure.pages import Page from . import SectionPage, rewrites __all__ = ["SectionIndexP...
StarcoderdataPython
1661163
<reponame>urushiyama/DeUI from .element import Element from ..attribute.composite import Common from ..attribute import ( AttributeRenderer, Disabled, Label, Selected, Value ) class Option(Element): """ Represents option for select box. """ attribute_renderer = AttributeRenderer( *Co...
StarcoderdataPython
3236624
<reponame>tpvt99/rl-course<filename>hw1/behavior_cloning.py import os import tensorflow as tf import numpy as np import gym import mujoco_py import pickle import time from tensorflow.keras import Model from tensorflow.keras.layers import Dense from load_policy_v2 import ExpertPolicy NUM_ROLLOUTS = 20 ENV_NAME = "Huma...
StarcoderdataPython
1637951
<reponame>nhsuk/nhsuk-content-store import imghdr from django.db import models from django.utils.crypto import get_random_string from django.utils.text import slugify from wagtail.wagtailimages.models import Image as WagtailImage class Image(WagtailImage): caption = models.CharField( max_length=255, blan...
StarcoderdataPython
4836526
<gh_stars>1-10 import os import re import fnmatch import string import bpy p = os.path def plugin_root(): return p.dirname(__file__) def gen_root(): return p.join(plugin_root(), "gen") proot = None def project_root(): root = p.join(bpy.path.abspath('//'), p.pardir) if not proot: return p.ab...
StarcoderdataPython
1614886
///Under dev...ML language convertor with python
StarcoderdataPython
86734
<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
3301783
<reponame>RaminMammadzada/security-webcam<filename>security webcam.py #if opencv was installed through home-brew on mac #sys.path.append('/usr/local/lib/python2.7/site-packages') import cv2 import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg from PIL import Image import time import datet...
StarcoderdataPython
62254
import tornado.gen from .base import BaseApiHandler from ..tasks import cel class TaskHandler(BaseApiHandler): @tornado.gen.coroutine def get(self, task_id): data = yield self.get_task_meta(task_id) result_data = {'result': data['result'], 'status': data['status']} self.finish(result...
StarcoderdataPython
3283173
from flask import Flask, render_template, request import sys import requests from PIL import Image import numpy as np app = Flask(__name__) def get_img_array(request, img_key): img = request.files[img_key] img = Image.open(img).convert('RGB') img_arr = np.array(img.getdata()) img_arr = img_arr.reshape...
StarcoderdataPython
3263513
from onelang_core import * import OneLang.One.Ast.Types as types import OneLang.One.ITransformer as iTrans class CollectInheritanceInfo: def __init__(self): self.name = "CollectInheritanceInfo" # C# fix self.name = "CollectInheritanceInfo" def visit_class(self, cls_): all_b...
StarcoderdataPython
3393746
# should be able to remove this try block when we drop OpenMM < 7.6 try: import openmm as mm from openmm import unit except ImportError: try: from simtk import openmm as mm from simtk import unit # -no-cov- except ImportError: HAS_OPENMM = False mm = None unit = ...
StarcoderdataPython
1626002
<gh_stars>0 import numpy as np import math extraNumber = 4 * math.pi * pow(10,-7) def rodSpeed(): mass = input("Input mass (g): ") resistance = input("Input the resistance (Ω): ") distance = input("Input distance apart (cm): ") magField = input("Input the magnetic Field (T): ") emf = inp...
StarcoderdataPython
3237594
from output.models.sun_data.elem_decl.nillable.nillable00101m.nillable00101m1_xsd.nillable00101m1 import Root __all__ = [ "Root", ]
StarcoderdataPython
1785152
from .part import Part from .primitives import Long, Int class Stat(Part): """ Znode stat structure Contains attributes: - **created_zxid** The zxid of the change that created this znode. - **last_modified_zxid** The zxid of the change that last modified this znode. - **created** The t...
StarcoderdataPython
3320268
from exercise344 import * def validso3(S, e): # S is the potential 3x3 skew-symmetric matrix in so(3) # e is the allowable error to still be a skew-symmetric matrix # returns true if S is within e of being an element of so(3); false otherwise # matrix should be of form: # 0 -x3 x2 # x3 0 ...
StarcoderdataPython
1708750
<filename>LeetCodeSolutions/python/22_Generate_Parentheses.py class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ def recur(result, string, left, right): if left == 0 and right == 0: result.append(string...
StarcoderdataPython
1764294
bl_info = { "name": "OSVR_Analog", "category": "Object", } import bpy from bpy.types import Operator # from ClientKit import ClientKit class OSVR_Analog(Operator): """OSVR_Analog""" # blender tooltip for menu items and buttons bl_idname = "object.osvr_analog" # uniqu...
StarcoderdataPython
43354
<filename>src/data/common.py from typing import Optional, List, TypeVar, Iterable import re PREM_KEY = 'premise' HYPO_KEY = 'hypothesis' LABEL_KEY = 'label' SENT_KEY = 'sentence' ANTI_KEY = 'neg_sentence' MASKED_SENT_KEY = 'masked_sentence' MASKED_ANTI_KEY = 'masked_neg_sentence' PATTERNS = [ "{pal} {prem} {par}...
StarcoderdataPython
1761074
<filename>classification/classification_test.py<gh_stars>1-10 import os import os.path as osp import random import sys import numpy as np import torch import torch.nn.functional as F import torch.utils.data as data from tqdm import tqdm def seed_worker(worker_id): worker_seed = torch.initial_seed() % 2 ** 32 ...
StarcoderdataPython
3383207
<reponame>Fogapod/information_security_pract_8<gh_stars>0 import sys import string from PIL import Image SUPPORTED_CHARS = string.printable BITS_PER_LETTER = 8 def main(): if len(sys.argv) < 3: print("Not enough arguments provided") sys.exit(1) src_image_path = sys.argv[1] text = " ".j...
StarcoderdataPython
37323
import os import tests from tests import at_most, compile, savefile import subprocess node_present = True erlang_present = True if os.system("node -v >/dev/null 2>/dev/null") != 0: print " [!] ignoring nodejs tests" node_present = False if (os.system("erl -version >/dev/null 2>/dev/null") != 0 or os.sys...
StarcoderdataPython
1717739
<gh_stars>0 #!/usr/bin/env python # coding:utf-8 import sys, os, re import distutils.core, py2exe import optparse import shutil import zipfile manifest_template = ''' <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity ...
StarcoderdataPython
77575
<filename>data_collection/gazette/spiders/pi_teresina.py import datetime from urllib.parse import urlencode import scrapy from gazette.items import Gazette from gazette.spiders.base import BaseGazetteSpider class PiTeresina(BaseGazetteSpider): TERRITORY_ID = "2211001" name = "pi_teresina" allowed_domain...
StarcoderdataPython
1701680
from pathlib import Path import unittest import numpy as np from bgen.reader import BgenFile from tests.utils import load_gen_data class TestBgenFile(unittest.TestCase): ''' class to make sure BgenFile works correctly ''' @classmethod def setUpClass(cls): cls.gen_data = load_gen_data()...
StarcoderdataPython
139263
def reverse(x: int) -> int: neg = x < 0 if neg: x *= -1 result = 0 while x: result = result * 10 + x % 10 x //= 10 return result if not neg else -1 * result assert reverse(123) == 321 assert reverse(-123) == -321
StarcoderdataPython
1727240
#! /usr/bin/python # -*- coding: utf-8 -*- #M3 -- Meka Robotics Robot Components #Copyright (C) 2010 Meka Robotics #Author: <EMAIL> (<NAME>) #M3 is free software: you can redistribute it and/or modify #it under the terms of the GNU Lesser General Public License as published by #the Free Software Foundation, either v...
StarcoderdataPython
3349732
from simbatch.core import core as batch import pytest @pytest.fixture(scope="module") def sib(): # TODO pytest-datadir pytest-datafiles vs ( path.dirname( path.realpath(sys.argv[0]) ) sib = batch.SimBatch(5, ini_file="config_tests.ini") return sib def test_prepare_data_directory_by_delete_a...
StarcoderdataPython
172309
#Neural net analysis of phyllosphere data #Code adapted from https://machinelearningmastery.com/regression-tutorial-keras-deep-learning-library-python/ #Contents of code: #Loading and examining data #Feature selection #Feature engineering: dummy variable creation, NA imputation, scaling/centering #Model definition and...
StarcoderdataPython
3265099
<reponame>HaoTy/qore """ The pseudoflow algorithm for open-pit mining problems. See https://hochbaum.ieor.berkeley.edu/html/pub/Hochbaum-OR.pdf """ from networkx import DiGraph from numpy import MAXDIMS from pseudoflow import hpf class Pseudoflow: def __init__(self, MAX_FLOW: int = 1000000) -> None: sel...
StarcoderdataPython
3313568
<reponame>dalvarezperez/umse #!/usr/bin/env python # -*- coding: UTF-8 -*- """ * UMSE Antivirus Agent Example * Author: <NAME> <<EMAIL>[at]gmail[dot]com> * Module: Main * Description: This module launch the "UMSE Antivirus Agent Example" System Try Icon. * * Copyright (c) 2019-2020. The UMSE Authors. All...
StarcoderdataPython
1695574
#!/usr/bin/python3 from sorters.sort_base import sort_base from sort_util.data_tools import data_store class bubble_sort(sort_base): def __init__(self) -> None: super().__init__() def name(self) -> str: return 'Bubble' def _do_sort(self, data: data_store) -> None: sorted = False...
StarcoderdataPython
6797
<filename>keystoneclient/auth/identity/v3/federated.py # 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 ...
StarcoderdataPython
1700474
<filename>util_scripts/pysystestxml_upgrader.py # PySys System Test Framework, Copyright (C) 2006-2021 <NAME> # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the ...
StarcoderdataPython
1784197
from django.db.models.signals import post_save from django.dispatch import receiver from researchhub_case.constants.case_constants import APPROVED, INITIATED from researchhub_case.models import AuthorClaimCase from researchhub_case.utils.author_claim_case_utils import ( get_new_validation_token, reward_author_clai...
StarcoderdataPython
162750
<gh_stars>1-10 # 序列化是将一个数据结构或者对象转换为连续的比特位的操作, # 进而可以将转换后的数据存储在一个文件或者内存中, # 同时也可以通过网络传输到另一个计算机环境, # 采取相反方式重构得到原数据。 # 请设计一个算法来实现二叉树的序列化与反序列化。 # 这里不限定你的序列 / 反序列化算法执行逻辑, # 你只需要保证一个二叉树可以被序列化为一个字符串, # 并且将这个字符串反序列化为原始的树结构。 # 示例:  # 你可以将以下二叉树: # 1 # / \ # 2 3 # / \ # 4 5 # 序列化为 "[1,2,3,null,null,4,5]" ...
StarcoderdataPython
3263605
<filename>s13_debug_unittest/bug.py<gh_stars>10-100 numbers = [1, 2, 3, 4, 10, -4, -7, 0] def all_even(num_list): even_numbers = [] for number in num_list: if number%2 == 0: even_numbers.append(number) return even_numbers print(all_even(numbers))
StarcoderdataPython
68405
# Copyright 2018 The Oppia Authors. All Rights Reserved. # # 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 ...
StarcoderdataPython
1635932
from Core.IFactory import IFactory from Regs.Block_D import RD140 class RD140Factory(IFactory): def create_block_object(self, line): self.rd140 = _rd140 = RD140() _rd140.reg_list = line return _rd140
StarcoderdataPython
1689835
# -*- coding: utf-8 -*- # License: Apache License 2.0 import os import platform import sys from setuptools import setup, find_packages, Extension from setuptools.command.build_ext import build_ext def list_cpp_files(package_dir='wikipedia2vec'): if sys.platform.startswith("win"): compile_args = [] ...
StarcoderdataPython
1677811
<reponame>AccelByte/accelbyte-python-sdk # Copyright (c) 2021 AccelByte Inc. All Rights Reserved. # This is licensed software from AccelByte Inc, for limitations # and restrictions contact your company contract manager. # # Code generated. DO NOT EDIT! # template file: justice_py_sdk_codegen/__main__.py # pylint: di...
StarcoderdataPython
4812911
# wikimedia functions .wikimedia.py """ collection of existing Python tools and Wikimedia/Data endpoints """ import os import pandas as pd import xml.etree.ElementTree as ET from amidict import Resources # SPARQL keywords WIKIDATA_QUERY_URL = 'https://query.wikidata.org/sparql' RESULTS_NS = "http://www.w3.org/2005/spa...
StarcoderdataPython
3382664
<filename>examples/seedpython/scripts/sorting/quick_sort.py # [[ Data ]] a = [8, 1, 0, 5, 6, 3, 2, 4, 7, 1] # [[ Index(start, end) ]] def partition(start, end, a): # [[ Index ]] pivot_index = start # [[ Save ]] pivot = a[pivot_index] while start < end: while start < len(a) and a[start] <= p...
StarcoderdataPython
85828
<reponame>dolong2110/Algorithm-By-Problems-Python from typing import Optional # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def isCousins(self, root: Optional[TreeNode], x: int, y: ...
StarcoderdataPython
69155
from joblib import delayed, Parallel import os import sys import glob from tqdm import tqdm import cv2 import argparse import matplotlib.pyplot as plt plt.switch_backend('agg') def str2bool(s): """Convert string to bool (in argparse context).""" if s.lower() not in ['true', 'false']: raise ValueE...
StarcoderdataPython
1681813
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: <NAME> <vargash1> # @Date: Sunday, April 10th 2016, 11:25:34 pm # @Email: <EMAIL> # @Last modified by: vargash1 # @Last modified time: Sunday, April 10th 2016, 11:28:31 pm import os from setuptools import setup # Utility function to read the README file. d...
StarcoderdataPython
1742550
<filename>noise/dh/keypair.py<gh_stars>1-10 class KeyPair(object): def __init__(self, public_key, private_key): """ :param public_key: :type public_key: noise.dh.public.PublicKey :param private_key: :type private_key: noise.dh.private.PrivateKey """ self._publ...
StarcoderdataPython
3378546
from ntlm import HTTPNtlmAuthHandler
StarcoderdataPython
3203988
import numpy as np import part1 if __name__ == "__main__": board, claims = part1.create_board("input.txt") unique_id = None # store the result for id, x0, y0, width, height in claims: unique = True for y in np.arange(y0, y0 + height): for x in np.arange(x0, x0 + width): ...
StarcoderdataPython
1618310
import suspect import numpy def test_null_transform(): fid = numpy.ones(128, 'complex') data = suspect.MRSData(fid, 1.0 / 128, 123) transformed_data = suspect.processing.frequency_correction.transform_fid(data, 0, 0) assert type(transformed_data) == suspect.MRSData def test_water_peak_alignment_mis...
StarcoderdataPython
40273
import pandas as pd import matplotlib.pyplot as plt from data import games plays = games[games['type']=='play'] plays.columns= ['type','inning','team', 'player', 'count','pitches','event', 'game_id', 'year'] #print (plays) hits = plays.loc[plays['event'].str.contains('^(?:S(?!B)|D|T|HR)'), ['inning','event']] #print...
StarcoderdataPython
1674257
import pytest pytest.importorskip("requests") pytest.importorskip("requests.exceptions") def test_load_module(): __import__("modules.contrib.getcrypto")
StarcoderdataPython
1634871
<filename>Python3/OTUS/lesson04/lesson04-1.py class MyIterable: def __init__(self, start, stop): if not stop > start: raise ValueError('Start has to be < than stop') self.start = start self.stop = stop # self.current = start self.reset() def __iter__(self): ...
StarcoderdataPython
1727370
# Generated by Django 3.2.8 on 2021-12-06 05:39 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import uuid class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(...
StarcoderdataPython
13486
<gh_stars>10-100 """ Module to take a water_level reading.""" # Raspi-sump, a sump pump monitoring system. # <NAME> # http://www.linuxnorth.org/raspi-sump/ # # All configuration changes should be done in raspisump.conf # MIT License -- http://www.linuxnorth.org/raspi-sump/license.html try: import ConfigParser as ...
StarcoderdataPython
188713
<filename>dbsetup.py # -*- coding: utf-8 -*- # swtstore->dbsetup.py # Create and setup databases for the first time run of the application import sys import os # Get the path to the base directory of the app BASE_DIR = os.path.join(os.path.dirname(__file__)) # append the path to the WSGI env path sys.path.insert(0,...
StarcoderdataPython
1753351
<reponame>spkuehl/circuitpython import sys import json # Map start block to current allocation info. current_heap = {} allocation_history = [] root = {} def change_root(trace, size): level = root for frame in reversed(trace): file_location = frame[1] if file_location not in level: ...
StarcoderdataPython