id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
124227
<gh_stars>1-10 from functools import partial import arcade from ..config import CONFIG from .menu_view import MenuView, MenuField from ..constants import * class SettingsView(MenuView): def __init__(self, views): super().__init__(views) self.width, self.height = self.window.get_size() # u...
StarcoderdataPython
11350783
import configparser def return_credentials(): config = configparser.ConfigParser() config.read('credentials.ini') return config if __name__ == '__main__': return_credentials()
StarcoderdataPython
5198556
"""A module defining dependencies of the `rules_rust` tests""" load("//test/load_arbitrary_tool:load_arbitrary_tool_test.bzl", "load_arbitrary_tool_test") def io_bazel_rules_rust_test_deps(): """Load dependencies for rules_rust tests""" load_arbitrary_tool_test()
StarcoderdataPython
8075080
<gh_stars>1-10 layout = None
StarcoderdataPython
3205680
# Copyright 2019, Oath Inc. # Licensed under the terms of the Apache 2.0 license. See the LICENSE file in the project root for terms import configparser import copy import os import sys from tempfile import TemporaryDirectory import unittest from screwdrivercd.version import cli from screwdrivercd.version.version_type...
StarcoderdataPython
12812224
from pbxproj import PBXGenericObject class XCConfigurationList(PBXGenericObject): def _get_comment(self): info = self._get_section() return f'Build configuration list for {info[0]} "{info[1]}"' def _get_section(self): objects = self.get_parent() target_id = self.get_id() ...
StarcoderdataPython
6701802
<reponame>pyensemble/wildwood """ In this module we use wildwood on a binary classification problem with 2 features but with a very large sample size (to check that parallization works, and to track the evolution of computing times """ from time import time import logging import numpy as np import matplotlib.pyplot as...
StarcoderdataPython
12823198
<gh_stars>0 # Copyright (C) 2020 GreenWaves Technologies, SAS # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. ...
StarcoderdataPython
4948006
import abstract_interface import logging from game_code import interactions from game_code.core import exceptions log = logging.getLogger('interface.python') class PythonDecision(abstract_interface.Decision): def __init__(self, interface, prompt_id, prompt, choices, **kwargs): assert isinstance(interface...
StarcoderdataPython
11214007
def eval_numerical_gradient(f, x): """ a naive implementation of numerical gradient of f at x - f should be a function that takes a single argument - x is the point (numpy array) to evaluate the gradient at """ import numpy as np fx = f(x) # evaluate function value at original point grad = np.zeros(x.s...
StarcoderdataPython
9754623
import numpy as np import pandas as pd from scipy.spatial.distance import cdist from .base import Sampler class VoxelgridSampler(Sampler): def __init__(self, *, pyntcloud, voxelgrid_id): super().__init__(pyntcloud=pyntcloud) self.voxelgrid_id = voxelgrid_id def extract_info(self): s...
StarcoderdataPython
1710477
from tb_profil import Tb_profil from tb_login import Tb_Login from termcolor import colored from Validation import Validations from os import system class Main: Valid = Validations() TbProfil = Tb_profil() Tblogin = Tb_Login() def __init__(self): self.User = "" #...
StarcoderdataPython
1911860
<gh_stars>0 """ After pressed enter, the program retrieve the position of the mouse.""" from gui import PyGuiAutomation def main(): print('Press Ctrl+C to quit.') input() auto = PyGuiAutomation() try: while True: x, y = auto.position() print(f"X:{x} Y:{y}") except ...
StarcoderdataPython
11283705
<filename>upy/contrib/tree/views.py<gh_stars>1-10 from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from upy.contrib.tree.utility import UPYRobotTXT, UPYSitemap def upy_render(request, upy_context, vars_dictionary): ...
StarcoderdataPython
6617954
from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import Group from django.conf import settings from .forms import StudentUserCreationForm, StudentUserChangeForm from .models import StudentUser import os cla...
StarcoderdataPython
6472033
<reponame>0xflotus/voctomix<gh_stars>100-1000 from mock import ANY from lib.response import NotifyResponse from tests.commands.commands_test_base import CommandsTestBase class SetVideoTest(CommandsTestBase): def test_set_video_a(self): response = self.commands.set_video_a("cam2") self.pipeline_mo...
StarcoderdataPython
87489
<reponame>ashishdhngr/baserow from unittest.mock import patch, call, ANY import pytest from django.db import transaction from baserow.contrib.database.api.constants import PUBLIC_PLACEHOLDER_ENTITY_ID from baserow.contrib.database.rows.handler import RowHandler from baserow.contrib.database.views.handler import ViewH...
StarcoderdataPython
6561437
<reponame>Kipngetich33/Potrait-HAll from django.test import TestCase from .models import Category, Image , Location class ImageTestClass(TestCase): # Set up method def setUp(self): self.image= Image(image = 'imageurl', name ='test_image', image_description ='image test description') # Testing...
StarcoderdataPython
4997728
<reponame>hammad26/MedViLL """ MedViLL, pre-training model main run.py """ import os import argparse from datetime import datetime from data.dataset_origin import CXRDataset from torch.utils.data import DataLoader from utils.utils import * from models.train_origin import CXRBERT_Trainer # CXR-BERT from transformers...
StarcoderdataPython
6651156
#!/usr/bin/python ''' # TrueRNG Read - Simple Example # <NAME> # 8/21/2016 # # Requires Python 2.7, pyserial # On Linux - may need to be root or set /dev/tty port permissions to 666 # # Python 2.7.xx is available here: https://www.python.org/ # Install Pyserial package with: python -m pip install pyserial ''' import...
StarcoderdataPython
4804845
# -*- coding: utf-8 -*- """ A script that selects random users and add them as approved submitters Written by /u/SmBe19 """ import praw import random import time import OAuth2Util # ### USER CONFIGURATION ### # # The bot's useragent. It should contain a short description of what it does and your username. e.g. "RSS...
StarcoderdataPython
1625486
from django.contrib import admin from django.urls import path, include from . import views # /student/.. urlpatterns = [ path('', views.studentDashboard, name="student_dashboard"), path('postad/<str:pk>/', views.postAd, name="post_ad"), path('ads/', views.Ads, name="ads"), path('wishlist/', views.w...
StarcoderdataPython
11304642
<filename>mscience_cachetclient/cachet.py # Copyright Red Hat, Inc. 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/LICEN...
StarcoderdataPython
4836470
<gh_stars>1-10 import numpy as np class MeanIonization: """ Compute the mean ionization state (<Z> or Zbar) for a given system. Parameters ---------- Am : float or arrary_like Atomic mass of element (or isotope) in units of grams [g]. mass_density : float or array_like ...
StarcoderdataPython
1696051
import re from django.conf import settings from html import unescape from urllib import parse as urlparse from .constants import deprecated_page_redirects, FrontEndSection from common.helpers.dictionaries import keys_omit def args_dict_to_query_string(args_dict, urlencode=False): ''' Takes argument dictionary...
StarcoderdataPython
9698519
from exp_base import * # THIS FILE IS FOR STORING STANDARD EXPERIMENTS/BASELINES FOR CARLA_STA MODE ############## choose an experiment ############## # current = 'builder' # current = 'trainer_sb' # current = 'builder' current = 'res_trainer' # current = 'vis_trainer' # current = 'occvis_trainer' # current = 'emb_t...
StarcoderdataPython
5137423
#!/usr/bin/env python import sys#!/usr/bin/env python import sys import traceback import os import imp import json from multiprocessing import Process, Queue import prometheus_client as prom import boto3 mod_name = os.getenv('MOD_NAME') func_handler = os.getenv('FUNC_HANDLER') queue_name = os.getenv('QUEUE_NAME') t...
StarcoderdataPython
246883
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware import inferModel.infer as Infer app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["GET"], allow_headers=["*"], ) @app.get("/") async def root(url: str = None): if url == None: ...
StarcoderdataPython
3403889
<gh_stars>1-10 import os def getFilesList(folder): if folder=='.': #if folder name was dot, get current folder dir filesList=os.listdir() else: #if a folder name was passed, get folder dir of that parameter filesList=os.listdir(folder) #return the resultant list return ...
StarcoderdataPython
3535327
import sys import os import numpy as np import acl import cv2 import glob path = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(path, "..")) sys.path.append(os.path.join(path, "../../../../common/")) sys.path.append(os.path.join(path, "../../../../common/acllite")) from acllite_resource impo...
StarcoderdataPython
3547512
<filename>CS1/0310_maze_navigator/working_code/main10.py import pygame, random, time pygame.init() #Initialize variables: clock = pygame.time.Clock() size = 50 #size in pixels of each tile maze_file = '../maze_navigator_starter_code/mazes/trial00.txt' fps = 3 #Frames per second green = 0,255,0 red = 255,0,0 yellow = ...
StarcoderdataPython
3520356
#!/usr/bin/env python3 import sys import argparse import rclpy from rclpy.node import Node from rmf_traffic_msgs.msg import ItineraryClear def main(argv = sys.argv): ''' Example : - participant_name: 0 - itinerary_version: 0 - topic_name: rmf_traffic/itinerary_clear ''' default_partici...
StarcoderdataPython
8144515
import re DURATION_REGEX = re.compile(r'PT(?P<minutes>\d+)M(?P<seconds>\d+)') def minutes_and_seconds_from_duration(duration): """ Returns a tuple of integers minutes, seconds from the YouTube duration format which is PT3M20S :param duration: string YouTube duration :return: tuple of integers ...
StarcoderdataPython
3472829
""" N <NAME> Monte 1 / 2 / 3 marche """ 10 3 = 3 * 1 + 2 * 1 + 1 * 1 3 = 1 + 1 + 1 10 / 3 3 = 1 / 2 4 1 1 1 1 1 1 2 1 2 1 1 3 2 1 1 2 2 3 1 4 1 1 1 1 1 1 1 1 2 1 1 2 1 1 1 3 1 2 1 1 1 2 2 1 3 1 2 1 1 1 2 1 2 2 2 1 2 3 3 1 1 3 2 p = nombre de possibilité 5 = p(4) + p(3) + p(2...
StarcoderdataPython
4948819
<reponame>nishaarya/LondonCrimes<filename>build_week_2_london_crimes_nisha_arya.py # -*- coding: utf-8 -*- """Build Week 2 - London Crimes - <NAME> Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1z6aphy51MJe2yn47nWOL-SIv3Ou4O00V """ url = https://www....
StarcoderdataPython
6680274
<gh_stars>0 import dns.resolver SUPPORTED_RECORDS = ['A', 'MX', 'NS', 'CERT', 'TXT'] class DNSRecord(object): def __init__(self): # Model variables self._a = None self._mx = None self._ns = None self._cert = None self._txt = None self._registered_at = No...
StarcoderdataPython
6670486
from .propagators import Conditional, Cascade, PointMutation, MateUniform, SelectBest, SelectUniform, InitUniform, IntervalMutationNormal def get_default_propagator(pop_size, limits, mate_prob, mut_prob, random_prob, sigma_factor=0.05): propagator = Cascade( [ SelectBest(pop_size), ...
StarcoderdataPython
296595
# ======================== Imports ======================== # import argparse import os import warnings from typing import Any, Callable, Dict, List import higher import torch import torch.nn as nn from numpy import number from tqdm import tqdm import wandb from dataloader import ECGDataSetWrapper from engine.helper...
StarcoderdataPython
3575878
<gh_stars>0 """Holds custom exceptions.""" class CommandCancel(Exception): pass
StarcoderdataPython
295715
import typing import flask import werkzeug.datastructures from nasse import config, exceptions, models, utils _overwritten = {"nasse", "app", "nasse_endpoint", "client_ip", "method", "headers", "values", "args", "form", "params", "cookies"} class Request(object): def __init__(self, app, endpoi...
StarcoderdataPython
3239471
import os.path as p def parse_username_and_password_file(path): with open(p.abspath(p.expanduser(path)), 'rb') as f: up = f.readlines() return tuple([l.strip() for l in up][:2])
StarcoderdataPython
9671557
from kivy.vector import Vector from .decorator import CallResult class Movement: def __init__(self, grid): self.grid = grid self.size = Vector(len(self.grid), len(self.grid[0])) @CallResult def down(self, pos: Vector): x = pos.x + 1 while x < self.size.x: tile...
StarcoderdataPython
4984631
<filename>src/django_grainy/migrations/0001_initial.py # -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-11-30 14:40 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django_grainy.fields class Migratio...
StarcoderdataPython
318879
<reponame>frikol3000/Amazon_Headset_Scraper<gh_stars>0 BOT_NAME = 'AmazonHeadSetScraping' SPIDER_MODULES = ['AmazonHeadSetScraping.spiders'] NEWSPIDER_MODULE = 'AmazonHeadSetScraping.spiders' USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0' DOWNLOAD_DELAY = 3 DOWNLOAD_TIM...
StarcoderdataPython
366484
"""Allow for easily adding segments to lines.""" from functools import singledispatch from typing import Optional from cairo import ANTIALIAS_NONE from gi.repository import Gtk from gaphas.aspect import MoveType from gaphas.aspect.handlemove import HandleMove, ItemHandleMove, item_at_point from gaphas.connector impor...
StarcoderdataPython
9797408
<filename>ovl/partials/keyword_partial.py import functools import warnings from .reverse_partial import ReversePartial def keyword_partial(target_function): """ A Decorator used to load other parameters to a function before applying it on a given input data This decorator is used to load parameters to th...
StarcoderdataPython
1823644
import re BREAK_PATTERN = re.compile(r'\n') EMOJI_PATTERN = re.compile(r'\\uf\w+') SPACES_PATTERN = re.compile(r' +') WEB_PATTERN = re.compile('[\w\-_\d]*.(com|net)', re.I) NUM_PATTERN = re.compile(r'\d+')
StarcoderdataPython
3566549
import os import random from PIL import Image import numpy as np from torch.utils.data import Dataset from torch.utils.data import DataLoader from torch.utils.data.sampler import SubsetRandomSampler import torchvision.transforms as transforms from data_aug.gaussian_blur import GaussianBlur from data_aug.cutout import ...
StarcoderdataPython
287147
# Compute the sum of perfect sqaures up to h import math h = int(input("Enter number:")) q = 0 perfectSquares = [] for i in range(1, h+1): perfectSquares.append(i) q += int(math.pow(i, 2)) print(perfectSquares) print(f"Sum: {q}")
StarcoderdataPython
11305838
import sys if sys.argv[0].endswith("__main__.py"): sys.argv[0] = "python -m tktable" from . import _test as main main()
StarcoderdataPython
4999363
<filename>cliapp/main_cli.py #!/usr/bin/python # -*- coding: utf-8 -*- import sys import os import click from .core.mymodule import MyClass HERE = os.path.abspath(os.path.dirname(__file__)) CMD_LINE_EXAMPLES = """SOME EXAMPLES HERE: $ cliapp => returns some nice text """ @click.command() @click.argument('args'...
StarcoderdataPython
9784298
<gh_stars>0 # # @lc app=leetcode.cn id=51 lang=python3 # # [51] N 皇后 # # https://leetcode-cn.com/problems/n-queens/description/ # # algorithms # Hard (73.36%) # Likes: 676 # Dislikes: 0 # Total Accepted: 89.5K # Total Submissions: 122K # Testcase Example: '4' # # n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。 ...
StarcoderdataPython
3489469
from models.models import Historial
StarcoderdataPython
199776
<gh_stars>1-10 from datetime import datetime, timedelta import pytest from releasy.miner.vcs.miner import Miner from tests.miner.vcs.mock import DifferentReleaseNameVcsMock miner = Miner(vcs=DifferentReleaseNameVcsMock(), release_prefixes=["v",""], ignored_suffixes=["Final"]) project = miner.mine_releases() print(pr...
StarcoderdataPython
9714996
<filename>shortner/views.py<gh_stars>0 from django.shortcuts import render import pyshorteners # Create your views here. def index(request): return render(request, 'shortner/index.html') def create(request): if request.method == 'POST': link = request.POST['link'] s = pyshorteners.Shortener()...
StarcoderdataPython
1762225
import numpy as np import theano import theano.tensor as T import theano.tensor.nnet.bn as bn eps = np.float32(1e-6) zero = np.float32(0.) one = np.float32(1.) def bn_shared(params, outFilters, index): ''' Setup BN shared variables. ''' normParam = {} template = np.ones((outFilters,)...
StarcoderdataPython
6438286
<filename>thespian/system/transport/MultiprocessQueueTransport.py """Uses the python multiprocess.Queue as the transport mechanism. Queues are multi-producer/multi-consumer objects. In this usage, there will be only one consumer (the current Actor) although there may be multiple producers (any other actor sending to ...
StarcoderdataPython
212049
#!/usr/bin/env python """ Styled just like an apt-get installation. """ import time import quo from quo.progress import formatters style = quo.styles.Style.add( { "label": "bg:#ffff00 #000000", "percentage": "bg:#ffff00 #000000", "current": "#448844", "bar": "", } ) def main(...
StarcoderdataPython
5138745
<reponame>anschwa/savetheyak<filename>savetheyak/views.py # -*- coding: utf-8 -*- import datetime as dt try: # PY3 from urllib.parse import urljoin except ImportError: # PY2 from urlparse import urljoin from collections import Counter from flask import render_template, request from werkzeug.contrib.atom impo...
StarcoderdataPython
3318438
<reponame>alliance-genome/ontobio #!/usr/bin/env python """ Command line wrapper to ontobio.golr library. Type: qbiogolr -h For instructions """ import argparse from ontobio.golr.golr_associations import search_associations from ontobio.ontol_factory import OntologyFactory from ontobio.io.ontol_renderers impo...
StarcoderdataPython
3414891
""" Functions for two particles """ import numpy as np from .phys import pt class TwoParticles(): def __init__(self, data, is_signal=1): self.var_labels = ["px1", "py1", "pz1", "e1", "px2", "py2", "pz2", "e2"] self.data = self.get_data(data, is_signal) def get_...
StarcoderdataPython
5108940
<gh_stars>0 from django.apps import AppConfig class PilotsConfig(AppConfig): name = 'pilots'
StarcoderdataPython
8078477
<gh_stars>1-10 # Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.errors import AnsibleFilterError from ansible.module_utils.six.moves.u...
StarcoderdataPython
11348693
INF = float('inf') NEG_INF = float('-inf') PASSIVE = "PASSIVE" __all__ = ["INF", "NEG_INF", "PASSIVE"]
StarcoderdataPython
8053410
<filename>parsing/tracking_logs/generate_course_tracking_logs.py ''' This module will extract tracking logs for a given course and date range between when course enrollment start and when the course ended. For each log, the parent_data and meta_data from the course_structure collection will be appended to the log bas...
StarcoderdataPython
6586757
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
StarcoderdataPython
3571062
<filename>text_recognizer/data/__init__.py<gh_stars>0 from .base_data_module import BaseDataModule # Hide lines below until Lab 2 from .emnist import EMNIST from .emnist_lines import EMNISTLines from .mnist import MNIST from .util import BaseDataset # Hide lines above until Lab 2
StarcoderdataPython
3210684
import logging import time import datetime import random import weaved # BEGIN Configuration # Weaved related configuration PLUG_IP = '192.168.1.201' # Assumes the Smart Plug is configured for SSH and IR blaster PLUG_USER = 'root' # Assumes password-less (key based) SSH authentication is set up # ...
StarcoderdataPython
3326394
import json import boto3 from util import DecimalEncoder dynamodb = boto3.resource('dynamodb', region_name='us-east-1') structures_table = dynamodb.Table('corp-fittings-doctrines') def handle(event, context): doctrine_response = structures_table.scan() doctrines = doctrine_response['Items'] return { ...
StarcoderdataPython
9616090
<filename>myProject/myApp/migrations/0001_initial.py<gh_stars>0 # Generated by Django 2.0.6 on 2019-02-21 17:38 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ ...
StarcoderdataPython
8131833
<filename>ableton/v2/control_surface/components/scene.py #Embedded file name: /Users/versonator/Jenkins/live/output/Live/mac_64_static/Release/python-bundle/MIDI Remote Scripts/ableton/v2/control_surface/components/scene.py from __future__ import absolute_import, print_function, unicode_literals import Live from builti...
StarcoderdataPython
247391
""" This is the Contacts Walker Process caveats: * email address is assumed to be case-insensitive in SalesForce * some email addresses are duplicates within a single CSV file. """ import pprint import os, sys import textwrap import time import datetime import re import logging import cSt...
StarcoderdataPython
5044947
class Solution(object): def getSum(self, a, b): """ :type a: int :type b: int :rtype: int """ # 32 bits integer max MAX = 0x7FFFFFFF # 32 bits interger min MIN = 0x80000000 # mask to get last 32 bits mask = 0xFFFFFFFF w...
StarcoderdataPython
37948
import matplotlib.pyplot as plt from sdaudio.callables import Circular from sdaudio.callables import Constant from sdaudio import draw from sdaudio import wavio from sdaudio.wt_oscillators import Choruses def main(): #------------------------------------------------------------------------- # sawtooth dem...
StarcoderdataPython
6471014
<filename>main/migrations/0021_auto_20161208_1214.py # -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-12-08 11:14 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0020_tournament_profiles'), ...
StarcoderdataPython
5135488
<reponame>justinforbes/munin #!/usr/bin/python import json import sys import colorama from colorama import Fore,Style with open(sys.argv[1], "r") as f: data = json.load(f) print ("----------------------------------------------------") print ( "Total Hash Count : %s" % len(data)) print ( "Showing Suspicious and Mali...
StarcoderdataPython
3295558
<reponame>JesusManuelPuentesG/ML_Python_Metricas … # Librería necesaria para utilizar la matriz de confusión from sklearn.metrics import confusion_matrix … matrix = confusion_matrix(y_test, yhat_classes) print() print('Matriz de Confusión: ') print() print(matrix) …
StarcoderdataPython
11205619
#!/usr/bin/env python import typing class AttributeValue(typing.TypedDict, total=False): """ AttributeValue https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_AttributeValue.html Attributes: ---------- B: str BS: typing.List[str] BOOL: bool L: typing.List ...
StarcoderdataPython
11288933
from targets.pipes.base import ( InputPipeProcessWrapper, IOPipeline, OutputPipeProcessWrapper, ) class Bzip2Pipeline(IOPipeline): input = "bytes" output = "bytes" def pipe_reader(self, input_pipe): return InputPipeProcessWrapper(["bzcat"], input_pipe) def pipe_writer(self, outp...
StarcoderdataPython
358639
<filename>leetcode/116_填充每个节点的下一个右侧节点指针.py # -*- coding:utf-8 -*- # author: hpf # create time: 2020/12/15 11:07 # file: 116_填充每个节点的下一个右侧节点指针.py # IDE: PyCharm # 题目描述: ''' 给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下: struct Node { int val; Node *left; Node *right; Node *next; } 填充它的每个 next 指针,让这个指针指向其下一个右侧节点...
StarcoderdataPython
211659
<reponame>mrslow/cbr-client import pytest from cbr_client import Task from conftest import base_url, correct_headers, tasks_json @pytest.mark.asyncio async def test_tasks(httpx_mock, client): httpx_mock.add_response(status_code=200, json=tasks_json, headers...
StarcoderdataPython
8051694
<reponame>DominicOram/ophyd<filename>ophyd/log.py<gh_stars>10-100 # The LogFormatter is adapted light from tornado, which is licensed under # Apache 2.0. See other_licenses/ in the repository directory. import logging import sys try: import colorama colorama.init() except ImportError: colorama = None try...
StarcoderdataPython
8001622
<reponame>LeonidPavlov/home_budget from genericpath import isdir import os from src.storage.storage import Storage storage = Storage('test_db_dir', 'test_db.db') def test_create_directory_when_directory_absent() -> None: assert(storage.create_directory() == True) def test_create_directory_when_directory_exist()...
StarcoderdataPython
5099169
# Stand-alone example test file: # - define equivalent old- and new-style flows # - parameterize a test to run each flow and verify its data artifacts from metaflow import FlowSpec, Parameter import metaflow.api as ma from metaflow.api import foreach, join, step from metaflow.tests.utils import parametrize, run clas...
StarcoderdataPython
1613994
import time import json import os import datetime import dateutil.parser from dateutil.tz import tzutc import pytest from waiting import wait from replicate.heartbeat import Heartbeat def test_heartbeat_running(tmpdir): tmpdir = str(tmpdir) path = "foo/heartbeat.json" heartbeat = Heartbeat( "expe...
StarcoderdataPython
11231755
<filename>tests/test_opttools.py import io import os import sys import math import unittest import unittest.mock from libcli import default, command, error, run import libcli.opttools as opttools class TestException(Exception): pass class TestException32(Exception): pass class TestExceptionUnexpected(Excepti...
StarcoderdataPython
291607
''' 四数之和 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。 注意: 答案中不可以包含重复的四元组。 ''' from typing import List ''' 解题思路:双指针法 设置4个指针,逐步向内搜索可能的解 时间复杂度:O(n^3) 空间复杂度:O(1) ''' class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]...
StarcoderdataPython
3540998
<filename>scripts/create_c_api_projections.py #!/usr/bin/env python ############################################################################### # $Id$ # # Project: PROJ # Purpose: Parse XML output of Doxygen on coordinateoperation.hpp to creat # C API for projections. # Author: <NAME> <even.rouaul...
StarcoderdataPython
5030912
<filename>src/lava/lib/dl/slayer/io.py # Copyright (C) 2021 Intel Corporation # SPDX-License-Identifier: BSD-3-Clause """Spike/event Input Output and visualization module.""" import numpy as np from matplotlib import pyplot as plt from matplotlib import animation class Event(): """This class provides a way to ...
StarcoderdataPython
3430179
<filename>evilmc/__init__.py from .core import * from .example import *
StarcoderdataPython
6673060
import udees.datasets.mitdb as mitdb from udees.datasets.mitdb import Record from udees.datasets.mitdb import interleave_record import unittest from unittest.mock import Mock from unittest.mock import patch @patch("udees.datasets.mitdb.np") @patch("udees.datasets.mitdb.pd") @patch("udees.datasets.mitdb.Path") @patch(...
StarcoderdataPython
1978729
<gh_stars>0 import paho.mqtt.client as mqtt import time from gpiozero import CamJamKitRobot MQTT_SERVER = "localhost" MQTT_PATH = "CommandChannel" robot = CamJamKitRobot() # The test callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Conne...
StarcoderdataPython
6651471
<reponame>Gawesomer/specs2016 # Some inputs that we will use multiple times ls_out = \ """ -rw-r--r-- 1 synp staff 1462 Mar 9 10:45 Makefile -rw-r--r-- 1 synp staff 4530 Mar 4 19:36 Makefile.cached_depends -rw-r--r-- 1 synp staff 4576 Mar 4 19:36 Makefile.cached_depends_vs -rw-r--r-- 1 synp sta...
StarcoderdataPython
6435173
<reponame>denizcangi/stereoscope #!/usr/bin/env python3 import sys from os import mkdir, getcwd import os.path as osp import argparse as arp import torch as t from torch.cuda import is_available from torch.utils.data import Dataset import numpy as np import pandas as pd import stsc.fit as fit import stsc.datasets...
StarcoderdataPython
5108699
import torch from .training import get_predictions, get_num_correct_predictions def get_score_fusion_accuracy(data_loaders, models, device): """ Receives two lists of data loaders and models (synchronized), gets predictions and fuses the data of all the models based on a max, product and sum rule. Returns...
StarcoderdataPython
8188028
import pandas as pd import csv from collections import defaultdict def analysis(): disease_list = [] def return_list(disease): disease_list = [] match = disease.replace('^','_').split('_') ctr = 1 for group in match: if ctr%2==...
StarcoderdataPython
4970760
#!/usr/bin/env python # rebatch.py # # Copyright (C) 2011 <NAME>, <NAME> # # This code is distributed under the BSD license, a copy of which is # included in the root directory of this package. # # Replacement for CCP4 program rebatch, using cctbx Python. # from __future__ import absolute_import, division impor...
StarcoderdataPython
9736523
from typing import List import sys import gym import numpy as np from baselines.common.vec_env.subproc_vec_env import SubprocVecEnv from prettytable import PrettyTable import neat.hyperneat as hn from neat.phenotypes import Phenotype, FeedforwardCUDA from neat.mapElites import MapElitesConfiguration, MapElitesUpdat...
StarcoderdataPython
1658572
# Standard imports import datetime import io import json import os # Django imports from django import http from rest_framework import viewsets # Third-party imports import piexif from PIL import Image # Local imports from . import filters, models, serializers, utils from .membership import permissions # Provide A...
StarcoderdataPython
216248
""" Download and render afferent mesoscale projection data using the AllenBrainAtlas (ABA) and Scene classes """ import brainrender from brainrender import Scene, Animation from vedo import settings as vsettings from brainrender.video import VideoMaker # // DEFAULT SETTINGS // # You can see all the default setti...
StarcoderdataPython