id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3236928
<filename>algo/applications/coin_change_2.py """ https://leetcode.com/problems/coin-change-2/ """ def solve(coins, amount: int) -> int: """ Unbounded knapsack DP. Note the base case is: For 0 amount we pick 0 coins, so we have only one way to pick, dp[0] = 1. """ dp = [0] * (amount + 1) dp[0] ...
StarcoderdataPython
50950
import os from unittest import TestCase from inbm_vision_lib.xml_handler import XmlHandler, XmlException from inbm_vision_lib.ota_parser import ParseException, get_children, parse_pota MISSING_HEADER_XML = '<?xml version="1.0" encoding="utf-8"?> <manifest><type>ota</type>' \ '<ota><type><fota name="sample"><target...
StarcoderdataPython
3339571
import unittest from Peer import PeerSet, Pod, IpBlock from K8sNamespace import K8sNamespace class TestPeerSetMethods(unittest.TestCase): def test_eq(self): default_namespace = K8sNamespace('default') pod_a = Pod('A', default_namespace) ip1 = IpBlock("1.2.3.0/24") ip2 = IpBlock("...
StarcoderdataPython
4826773
<gh_stars>0 def new_client_welcome(client, server) : with open("new_client_message.txt", "rb") as f : server.send_message(client,f.read()) def send_messages(client, server, message) : if message == "" : pass elif message == "--help" : with open("options.txt", "rb") as f : ...
StarcoderdataPython
1752824
<gh_stars>1-10 """ Utilities related to MP3 (MPEG vers 1 layer III) audio headers. This file is based on information found at: http://www.datavoyage.com/mpgscript/mpeghdr.htm """ import struct # Channel codes STEREO = 0 JOINT_STEREO = 1 DUAL_MONO = 2 MONO = 3 # Convert a channel code to a string _CHANNELS_TO_ST...
StarcoderdataPython
159479
# Copyright 2020 The Pigweed Authors # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
StarcoderdataPython
1784399
<reponame>shobhit009/Machine_Learning_Projects import pandas as pd # TASK 1 TASK_1_OUTPUT = pd.read_csv('data/TASK_1_OUTPUT.csv') # TASK 2 TASK_2_PART_1_OUTPUT = pd.read_csv('data/TASK_2_PART_1_OUTPUT.csv', parse_dates=[9]) TASK_2_PART_2_T10_OUTPUT = pd.read_csv('data/TASK_2_PART_2_T10_OUTPUT.csv', index_col=0, heade...
StarcoderdataPython
3329896
<gh_stars>10-100 # -*- coding: utf-8 -*- import itertools import copy import pickle import inspect import numpy as np from datetime import datetime from collections import OrderedDict class HyperParamsBase(object): def __init__(self): # default params pass def get(self, attr, default=None): ...
StarcoderdataPython
1678151
<filename>metrics/local_evaluation.py import codecs import json import os import numpy as np from pathlib import Path from .evaluate import evaluate_with_gin from disentanglement_lib.config.unsupervised_study_v1 import sweep as unsupervised_study_v1 def compute_metrics(exp_path, dataset, ...
StarcoderdataPython
1630436
"""Script to clean the criminal code qualifiers data.""" import sys from cleaning_helpers import extract_code_number def process(infile, outfile): """Read the raw data from [infile] and write cleaned data to [outfile].""" rows = open(infile).read().splitlines() print('Dropping the first row: %s' % rows[...
StarcoderdataPython
1791890
from .delete import Delete from .get_many import GetMany from .get_single import GetSingle from .post import Post from .patch import Patch from .defs import HttpMethods __all__ = ['HttpMethods', 'Delete', 'GetMany', 'GetSingle', 'Post', 'Patch']
StarcoderdataPython
3364976
from enum import Enum import ipaddress from typing import List class ROLES(Enum): COSTUMER = -1 PEER = 0 PROVIDER = 1 class MESSAGE_TYPE(Enum): ADVERTISE = 1 WITHDRAW = -1 PATH_CONST = "path" RANGE_IP_CONST = "range_ip" MESSAGE_TYPE_CONST = "message_type" class LinkedAS: def __init__(sel...
StarcoderdataPython
4819504
import json import uuid import boto3 import settings def download_file(s3_client, bucket, key): tmp_path = settings.TMP_PATH if not tmp_path.endswith('/'): tmp_path += '/' filename = tmp_path + 'waylon_' + str(uuid.uuid4()) s3_client.download_file(bucket, key, filename) return filename ...
StarcoderdataPython
123151
<reponame>min9288/Multicampus<filename>Python/python_programming_stu/mycode/lab/function_test.py ''' function : default value ''' def my_func(a=20, b=10): return a - b print(my_func()) print(my_func(30)) print(my_func(40, 5)) def my_func2(a, b=10): return a + b # default parameter value가 non-default para...
StarcoderdataPython
3379133
# import pytest # from base.client_request import ApiReq # from common.common_type import * # from common.common_func import * # # prefix = "prefix_" # # # class TestPartitionLoad(ApiReq): # """ Test case of partition load interface """ # # @pytest.mark.tags(CaseLabel.L1) # @pytest.mark.parametrize("fields"...
StarcoderdataPython
3225199
<gh_stars>0 import sys import pygame import traceback import img import var import start import title import field import battle var.clock = pygame.time.Clock() def init(): var.screen = pygame.display.set_mode((1280, 800)) pygame.display.set_caption('Dessert Card RPG') img.image_load() start.start_...
StarcoderdataPython
110408
<filename>azdocli/strategies/pipelineruns_get_strategy.py from azdocli.strategies.strategy_context import Strategy from azdocli.lib.pipelines import PipelinesAPI class PipelinerunsGetStrategy(Strategy): def run_strategy(self): pipelinesapi = PipelinesAPI(self.org_name, self.org_pat) return pipelin...
StarcoderdataPython
1790152
import os import time import cv2 import numpy as np time_start = time.time() rootdir = "../cpi_data/training_datasets/hand_labeled_resized_multcampaigns_clean/" savedir = "../cpi_data/training_datasets/hand_labeled_resized_multcampaigns_masked/" if not os.path.exists(savedir): os.makedirs(savedir, exist_ok=True)...
StarcoderdataPython
140583
<reponame>reinout/z3c.dependencychecker<filename>z3c/dependencychecker/tests/test_modules_django_settings.py # -*- coding: utf-8 -*- from z3c.dependencychecker.modules import DjangoSettings from z3c.dependencychecker.tests.utils import write_source_file_at import os import tempfile RANDOM_CODE = 'from zope.component ...
StarcoderdataPython
1606012
x = int(input()) max_val = x cnt = 1 while x != 0: x = int(input()) if x > max_val: max_val = x cnt = 1 elif x == max_val: cnt += 1 print(cnt)
StarcoderdataPython
3240020
from __future__ import absolute_import, division, print_function import argparse import logging import os import random import sys from io import open import numpy as np import torch from torch.utils.data import (DataLoader, RandomSampler, TensorDataset) from tqdm import tqdm, trange from models.modeling_bert import...
StarcoderdataPython
1679105
<gh_stars>10-100 import dash import dash_core_components as dcc import dash_html_components as html app = dash.Dash(__name__) app.layout = html.Div( [ dcc.Link("/test", href="/test"), # ➊ html.Br(), dcc.Link("/test2", href="/test2"), html.Br(), dcc.Link("/test3", href="/te...
StarcoderdataPython
3290337
<reponame>AlexiYIMU/INFO6105-Projects # -*- coding: utf-8 -*- """ Created on Fri Feb 8 16:09:17 2019 @author: 96984 """ import csv import re import os def file_name(file_dir): for root, dirs, files in os.walk(file_dir): for file in files: yield file ...
StarcoderdataPython
136576
class NodeCalculator: @staticmethod def calculate_node_size(node, relationships): linked_tables = list() size = 0 for table_key, table_value in relationships.items(): if table_key == node: for table in relationships[table_key]: linked_ta...
StarcoderdataPython
1646638
<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/10/23 21:03 # @Author : ganliang # @File : test_tf_activation.py # @Desc : 激活函数测试类 import unittest from mtensorflow import tf_activation class TestTensorflowActivation(unittest.TestCase): def test_activation_threhold(self): ...
StarcoderdataPython
5720
import json import logging from redash.query_runner import * from redash.utils import JSONEncoder logger = logging.getLogger(__name__) try: from influxdb import InfluxDBClusterClient enabled = True except ImportError: enabled = False def _transform_result(results): result_columns = [] result_r...
StarcoderdataPython
4800965
lis = [] w = open('data.txt','r') lis.append(w.read()) lis = lis[0].split("\n") a,b = [],[] for i in lis: first, second = i.split(":") a.append(first) b.append(second) final = 0 for i in range(len(a)): x,y = a[i][:-2].split("-") xbool = a[i][-1] == b[i][int(x)] ybool = a[i][-1] == b[i][int(y)]...
StarcoderdataPython
3376448
<reponame>tristanbrown/fintrist """ The engine that applies analyses to studies. """ import time from .dask import client from fintrist import (get_study, BaseStudy, Study, create_study, spawn_study) from fintrist_lib import get_recipe from .backtest import backtest from .settings import Config __all__ = ['build_dag...
StarcoderdataPython
3344698
import pandas as pd import pytest from numba.typed import List from ranx import Run def test_init(): run_dict = { "q1": { "d1": 1, "d2": 2, "d3": 3, }, "q2": { "d1": 1, "d2": 2, }, } run = Run(run_dict, name="bm2...
StarcoderdataPython
195601
# -*- coding: utf-8 -*- # Copyright 2013 Google 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/LICENSE-2.0 # # Unless require...
StarcoderdataPython
177302
import pickle from os.path import join import numpy as np import sys; sys.path.insert(0, '..'); sys.path.insert(0, '.') from util import print_stats file_path = '/data2/mengtial/Exp/ArgoVerse1.1/output/rt_htc_dconv2_ms_nm_s1.0/val/time_info.pkl' time_info = pickle.load(open(file_path, 'rb')) runtime_all_np = np.arr...
StarcoderdataPython
3277373
<gh_stars>10-100 # # BSD 3-Clause License # # Copyright (c) 2019, Analog Devices, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above c...
StarcoderdataPython
32765
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: <NAME>, ph4r05, 2018 import operator import sys # Useful for very coarse version differentiation. PY3 = sys.version_info[0] == 3 if PY3: indexbytes = operator.getitem intlist2bytes = bytes int2byte = operator.methodcaller("to_bytes", 1, "big") else...
StarcoderdataPython
1776752
from collections import namedtuple RobotPacket = namedtuple('RobotPacket', 'robot_id command kick_type kick_force dribbler_state charge_kick') RobotState = namedtuple('RobotState', 'timestamp is_team_yellow packet')
StarcoderdataPython
3321393
<filename>portal/management/commands/import_artist_image.py<gh_stars>0 # -*- coding: utf-8 -*- try: from lxml import etree print("running with lxml.etree") except ImportError: try: # Python 2.5 import xml.etree.cElementTree as etree print("running with cElementTree on Python 2.5+")...
StarcoderdataPython
3368889
from pygame import * from Game.const import * class Sound(object): """ Play sound effects """ def __init__(self): # All sound effects if not mac: self.themes = { "mainWorldFight" : "resources/sound/mainWorldFight.ogg", "mainWorldTheme" : "resources/sound/travel1.ogg", "waterWorldTheme" : "r...
StarcoderdataPython
3278190
<filename>doc/mpl_toolkits/axes_grid/figures/demo_colorbar_of_inset_axes.py import matplotlib.pyplot as plt from mpl_toolkits.axes_grid.inset_locator import inset_axes, zoomed_inset_axes from mpl_toolkits.axes_grid.colorbar import colorbar def get_demo_image(): from matplotlib.cbook import get_sample_data imp...
StarcoderdataPython
3240792
"{b}".format(**{"a": 1, **{"b":2}}) "{c}".format(**{**{"b":2}, "a": 1, **{"c":2}}) <warning descr="Key 'd' has no corresponding argument">"{d}"</warning>.format(**{**{"b":2}, "a": 1, **{"c":2}})
StarcoderdataPython
126137
<reponame>ArticulatedControl17/path_planning<filename>scripts/recalculatePath.py from error_calc import errorCalc from math import * from Point import Point from vehicleState import VehicleState import rospy from custom_msgs.msg import Path, Position from helper_functions import * class recalculatePath: def __ini...
StarcoderdataPython
3352440
<reponame>LittleEndu/Codeforces amount = int(input()) for i in range(amount): ss = input() if len(ss)>10: print("{}{}{}".format(ss[0],len(ss)-2,ss[-1])) else: print(ss)
StarcoderdataPython
34226
<reponame>mshen63/DevUp import os from flask import Flask from dotenv import load_dotenv from flask_cors import CORS from flask_mail import Mail # Database and endpoints from flask_migrate import Migrate from models.models import db from endpoints.exportEndpoints import exportEndpoints load_dotenv() app = Flask(__nam...
StarcoderdataPython
3347201
#! /usr/bin/env python """ Implementation of Elliptic-Curve Digital Signatures. Classes and methods for elliptic-curve signatures: private keys, public keys, signatures, NIST prime-modulus curves with modulus lengths of 192, 224, 256, 384, and 521 bits. Example: # (In real-life applications, you would probably wan...
StarcoderdataPython
3390947
# -*- coding: utf-8 -*- """ Created on Tue Aug 6 17:33:06 2019 @author: Mhowa """ import db_manager as dbm import file_reader as fr import record_handler import visualisation_manager import time def main(): """ @summary - the application controller. @description - will controll what ...
StarcoderdataPython
1607056
<gh_stars>1-10 """Lightweight Python module to discover and control WiLight devices.""" from .discovery import ( device_from_host, device_from_description, discover_devices, wilight_from_discovery ) # noqa F401 from .subscribe import SubscriptionRegistry # noqa F401 from .wilight_device.support import...
StarcoderdataPython
193805
""" Demo script modified Generates forward and backward flow for cityscapes sequence. T0 = 19 T1 = 19+[1..10] Uses two GPUs, one for fwd and the other for bwd """ import sys sys.path.append('core') import argparse import os import cv2 import glob import numpy as np import torch from PIL import Image fr...
StarcoderdataPython
3329650
#!/usr/bin/python2 # -*- coding: utf-8 -*- # mongo_data # # use mongodb pyalgotrade and sz50 # # vim:fileencoding=utf-8:sw=4:et -*- coding: utf-8 -*- import tushare as ts import json import pandas as pd import _index from energy.db.emongo import emongo class UN800(): def run(self): df500 = ts.get_zz500s...
StarcoderdataPython
146709
# Copyright (c) IBM Corp. 2018. All Rights Reserved. # Project name: Constrained Exploration and Recovery from Experience Shaping # This project is licensed under the MIT License, see LICENSE import numpy as np from .resetter_env import ResetterEnv class ResetterEnvCeres(ResetterEnv): ''' Resetter base enviro...
StarcoderdataPython
77259
#!/usr/bin/env python ''' Script to generate ntrials number of background only test statistics and save information about each trial to outfile @options: --i index: alert event index --ntrials: number of trials to perform ''' import time, pickle, argparse, os import numpy as np import pandas as pd from fr...
StarcoderdataPython
87713
<gh_stars>0 # -*- coding: utf-8 -*- """ Created on Wed Jun 26 18:29:41 2019 @author: <NAME> """ import cv2 from PIL import Image import matplotlib.pyplot as plt import tools import numpy as np from scipy import ndimage #from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img #%%...
StarcoderdataPython
1712274
import matplotlib matplotlib.use('Agg') import os, sys import yaml from argparse import ArgumentParser from tqdm import tqdm import copy import imageio import numpy as np from skimage.transform import resize from skimage import img_as_ubyte import torch import torch.nn.functional as F from modules.generator import Oc...
StarcoderdataPython
1679678
import click from src import configurations as config_module from src.lyrics import exceptions from src.lyrics.application_service import RunTimeTopWordsService from src.lyrics.searchers import AlbumsSearcher, TrackSearcher, LyricsSearcher, ArtistSearcher from src.lyrics.statitics import create_statistic @click.grou...
StarcoderdataPython
3277178
print(f'Loading {__file__}') from bluesky.suspenders import SuspendCeil,SuspendFloor quad_em_sus = SuspendCeil(quad_em, 0, resume_thresh=0) RE.install_suspender(quad_em_sus) ring_current_sus = SuspendFloor(ring_current, 360, resume_thresh=395, sleep=60*15) RE.install_suspender(ring_current_sus) ##RE.clear_suspen...
StarcoderdataPython
1768501
from django.urls import path from rest_framework.routers import DefaultRouter from radical_translations.events.views import EventViewSet, event_grid router = DefaultRouter() router.register("api", basename="event-api", viewset=EventViewSet) urlpatterns = [ path("", event_grid, name="timeline"), ] + router.urls
StarcoderdataPython
1655640
<filename>mcp9808.py """ Temperature readout using the I2CDriver Mini (https://i2cdriver.com/mini.html) and an MCP9808 digital temperature sensor (https://www.adafruit.com/product/1782) """ import time import i2cdriver class MCP9808: """ Simple support for the MCP9808 sensor """ MCP_CONFIG_REG = 0x0...
StarcoderdataPython
112244
from jarbas_hive_mind.slave.terminal import HiveMindTerminal, \ HiveMindTerminalProtocol from jarbas_hive_mind.message import HiveMessageType, HiveMessage from jarbas_hive_mind.nodes import HiveMindNodeType from ovos_utils.log import LOG from ovos_utils.messagebus import Message, get_mycroft_bus import json class...
StarcoderdataPython
3325134
from typing import Union, List, Optional from pyspark.sql.types import StructType, StructField, StringType, ArrayType, DataType # This file is auto-generated by generate_schema so do not edit it manually # noinspection PyPep8Naming class Observation_ReferenceRangeSchema: """ Measurements and simple assertion...
StarcoderdataPython
187163
<gh_stars>0 from flytekit.sdk.tasks import ( python_task, inputs, outputs, ) from flytekit.sdk.types import Types from flytekit.sdk.sagemaker.task import custom_training_job_task from flytekit.sdk.workflow import workflow_class, Input, Output from flytekit.models.sagemaker import training_job as training_jo...
StarcoderdataPython
3311322
<reponame>AMNeumann/gtd_helper #!/usr/bin/env python3 import os import argparse from jinja2 import Environment, FileSystemLoader if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('input', metavar='FILE', type=str) args = parser.parse_args() env = Environment( l...
StarcoderdataPython
3304901
def check_ascii(string): if not string.isascii(): raise NameError(f"{string} must be ascii instead.")
StarcoderdataPython
1745613
<filename>open_alchemy/helpers/__init__.py """Helper functions.""" from .define_all import define_all from .get_ext_prop import get_ext_prop from .merge_all_of import merge_all_of from .peek_type import peek_type from .prepare_schema import prepare_schema from .resolve_ref import resolve_ref from .testing_guard import...
StarcoderdataPython
167850
<gh_stars>1-10 from __future__ import annotations from contextlib import suppress from dataclasses import asdict from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Any, Callable, Iterable class Resolvable: """Placeholder for component which can be resolved to the actual object at a later ...
StarcoderdataPython
3221681
<gh_stars>0 import attr from openapi_core.schema.exceptions import OpenAPIMappingError class OpenAPIContentError(OpenAPIMappingError): pass @attr.s(hash=True) class MimeTypeNotFound(OpenAPIContentError): mimetype = attr.ib() availableMimetypes = attr.ib() def __str__(self): return "Mimetyp...
StarcoderdataPython
93459
<gh_stars>1-10 #!/usr/bin/env python2 import heapq from aoc18 import util TEST = False SAMPLE_INPUT = 18 INPUT = 9306 _coords_cache = {} def PowerLevel(coords, serial): global _coords_cache c = _coords_cache.get(coords, None) if c is None: x, y = coords power = (x + 10) * (x * y + 10 * ...
StarcoderdataPython
3360923
<gh_stars>1-10 """Vehicle class to model wheeled motion in two dimensions. Author: <NAME> Jan 2018 """ import numpy as np from ssd_robotics import rk4, mpi_to_pi, wrap class Vehicle: def __init__( self, wheelbase=0.7, center_of_mass=0.35, initial_state=np.zeros(3), # [x, y, the...
StarcoderdataPython
1661941
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from authentication.models import User # Register your models here. class MyUserAdmin(UserAdmin): model = User #print(UserAdmin.fieldsets) #print(type(UserAdmin.fieldsets)) fieldsets = UserAdmin.fieldsets + ( ...
StarcoderdataPython
4814016
<gh_stars>1-10 #!/usr/bin/env python3 """ This daemon repeatedly pings the google server to get the most up-to-date calendar info, and stores the info in MongDB. """ import time from helpers import get_service from main import get_events from config import CAL_NAMES, EVENT_DAEMON_REFRESH_RATE import db def get_events...
StarcoderdataPython
3310962
<reponame>nikmagini/pilot __author__ = "<NAME>" __copyright__ = "Copyright 2012-2013, The SAGA Project" __license__ = "MIT" import saga.adaptors.cpi.decorators as cpi_dec import saga.adaptors.cpi.base as cpi_base SYNC = cpi_dec.CPI_SYNC_CALL ASYNC = cpi_dec.CPI_ASYNC_CALL class Context (cpi_base.CPIBas...
StarcoderdataPython
17420
import sys from setuptools import setup required_packages = ["boombox", "Pillow", "PyYAML", "rich"] win_packages = ["keyboard"] unix_packages = ["pynput"] WIN = "win32" LINUX = "linux" MACOS = "darwin" if sys.platform == WIN: required_packages += win_packages elif sys.platform in (LINUX, MACOS): required_pa...
StarcoderdataPython
3369147
#!/usr/bin/env python3 ''' Given a word, write a function that returns the first index and the last index of a character. ''' def char_index(word, char): return None if char not in word else [word.index(char), word.rindex(char)]
StarcoderdataPython
1728281
from will.plugin import WillPlugin from will.decorators import respond_to, periodic, hear, randomly, route, rendered_template, require_settings class ThanksPlugin(WillPlugin): @respond_to("^(?:thanks|thank you|tx|thx|ty|tyvm)") def respond_to_thanks(self, message): self.reply(message, "You're welcome...
StarcoderdataPython
1771073
<reponame>tdiprima/code<filename>recipes/Python/200638_Generate_PythSymbol_Lists_Programmers_Editor/recipe-200638.py<gh_stars>1000+ # GenEditorSymbolLists.py """Make lists of Python symbols for a programmer's editor syntax coloring file Redirect this program's stdout to a text file. Cut and paste some or all of the l...
StarcoderdataPython
1687683
<filename>FL/main.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ @author:mjx """ from torchvision import transforms from datasets import InitDataSet from models import MLP, CNN, UNet from train import Train, GlobalTrain from utils.args import args from utils.utils import utils if __name__ == "__main__": # a...
StarcoderdataPython
167316
<reponame>Xetera/IreneBot class TooLarge(Exception): """The input was too long.""" def __init__(self): super(TooLarge, self).__init__("That number was too large.") class ImproperFormat(Exception): """Invalid Format was given.""" def __init__(self): super(ImproperFormat, self).__init__(...
StarcoderdataPython
1794086
<filename>kubernetes_typed/client/models/v1_limit_range_item.py<gh_stars>10-100 # Code generated by `typeddictgen`. DO NOT EDIT. """V1LimitRangeItemDict generated type.""" from typing import TypedDict, Dict V1LimitRangeItemDict = TypedDict( "V1LimitRangeItemDict", { "default": Dict[str, str], "...
StarcoderdataPython
1676334
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='nabla', packages=find_packages(), version='0.1.0', author='<...
StarcoderdataPython
61624
<filename>tests/tvl_adapters/test_tvl_adapter_vault_v2.py from operator import itemgetter import brownie import pytest from brownie import ZERO_ADDRESS, interface from ..addresses import * def test_generator_info(v2VaultsTvlAdapter): adapterInfo = v2VaultsTvlAdapter.adapterInfo() assert adapterInfo[0] == v2...
StarcoderdataPython
1676338
# coding=utf-8 from __future__ import absolute_import from wecubek8s.apps.model import controller def add_routes(api): ''' model route required: query: POST /kubernetes/entities/cluster/query {"additionalFilters": []} GET /kubernetes/entities/cluster return {'data': ...
StarcoderdataPython
179176
<reponame>zhengpingzhou/pymoka from setuptools import setup, find_packages setup( name='moka', version='1.0', description='A useful module', author='<NAME>', author_email='<EMAIL>', packages=find_packages(), install_requires=['numpy', 'opencv-python', 'matplotlib', 'torch', 'visdom', 'scipy', 'sc...
StarcoderdataPython
1687648
################################### # Utilities that are not exported # ################################### import logging from collections import deque __all__ = ['AutoContextType', 'AutoDecoratorType', 'AutoIterType', 'combine_types'] log = logging.getLogger(__name__) types = {} class AutoDecoratorType(type): ...
StarcoderdataPython
1634921
<reponame>testing-farm/artemis # Copyright Contributors to the Testing Farm project. # SPDX-License-Identifier: Apache-2.0 from typing import Optional, Pattern import pytest from gluetool.result import Error, Ok, Result import tft.artemis from tft.artemis.drivers import vm_info_to_ip @pytest.mark.parametrize( ...
StarcoderdataPython
1711557
import random from ledger.util import has_nth_bit_set def test_nth_bit_set(): """ Check if bits of randomly chosen integers are set or unset and compare with the binary representation. """ for _ in range(0, 10000): number = random.randint(0, 100000000) bits = bin(number)[2:] ...
StarcoderdataPython
1787243
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # 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 ...
StarcoderdataPython
170890
<filename>FuzzyACO.py # -*- coding: utf-8 -*- """ UNIVERSIDAD DE CONCEPCION Departamento de Ingenieria Informatica y Ciencias de la Computacion Memoria de Titulo Ingenieria Civil Informatica DETECCION DE BORDES EN IMAGENES DGGE USANDO UN SISTEMA HIBRIDO ACO CON LOGICA DIFUSA Autor: <NAME> Patrocinante: <NA...
StarcoderdataPython
70168
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime, time import pytz from dateutil import rrule from dateutil.relativedelta import relativedelta from odoo import api, fields, models, _ from odoo.exceptions import UserError from odoo.addon...
StarcoderdataPython
3316416
<reponame>Dogeek/Reusables #!/usr/bin/env python # -*- coding: UTF-8 -*- import random import reusables from reusables.cli import * from .common_test_data import * class TestWeb(BaseTestClass): def test_server_and_download(self): try: os.unlink("example_file") except OSError: ...
StarcoderdataPython
3286204
<filename>tests/integration/conftest.py import json import os import sys import warnings import pytest from vistir.compat import ResourceWarning, fs_str from vistir.path import mkdir_p from pipenv._compat import Path, TemporaryDirectory from pipenv.exceptions import VirtualenvActivationException from pipenv.utils im...
StarcoderdataPython
1791148
import urllib.request import tensorflow as tf import itertools URL = 'http://download.tensorflow.org/data/fsns-20160927/testdata/fsns-00000-of-00001' DST_ORIG = 'fsns-00000-of-00001.orig' DST = 'fsns-00000-of-00001' KEEP_NUM_RECORDS = 5 print('Downloading %s ...' % URL) urllib.request.urlretrieve(URL, DST_O...
StarcoderdataPython
199542
from random import choice from string import ascii_uppercase, digits try: from django.utils.encoding import force_unicode as force_text except (NameError, ImportError): from django.utils.encoding import force_str as force_text from django.db import transaction from django.contrib.gis.db.models import PointFie...
StarcoderdataPython
3227961
#!/usr/bin/env python2.5 # # Copyright 2009 the Melange authors. # # 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 applicab...
StarcoderdataPython
103747
<reponame>greydongilmore/tactics #!/usr/bin/env python import math import sys import vtk import toolcursor from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # The images are img1 and img2, or the same if only 1 image img1 = 0 img2 = 0 filenames = [] if len(sys.argv) > 1: filenames.exten...
StarcoderdataPython
3330529
<filename>report.py #Report.py #Report the current state a wandering pillar to a restfull web database. #todo: #- add debugging option (verbose... -v ?) import argparse, json, requests, datetime, logging, sys #setup logging logging.basicConfig(filename="wapi.log", level=logging.DEBUG) now = datetime.datetime.now().s...
StarcoderdataPython
4813889
from __future__ import absolute_import from __future__ import division from __future__ import print_function # Imports import numpy as np import tensorflow as tf #what does the same code look like with Tensor Board import time sess = tf.Session() log_dir = "./tesnorBoardFiles/NSC211_BKlecture_code" #from currdir of n...
StarcoderdataPython
50202
#!/usr/bin/env python 3.6 # -*- coding: utf-8 -*- """ Created on Saturdau Sep 16 16:58:58 2017 @author: Hans - Clément - Ali """ #----------Import_module----------- import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.decomposition import PCA from sklearn.model_selection impo...
StarcoderdataPython
3282970
import urllib.request import pandas as pd # load all URLs excel file #replace image urls excel file name with your file name data = pd.read_excel(r'image_urls.xlsx') # check size of data print(data.shape) # get all URLs from loaded data # 'image' is the name of column which contains my url link in e...
StarcoderdataPython
69664
<gh_stars>1-10 import numpy as np params = { 'svm_cat': { 'C': 10000.0, 'gamma': 0.1, 'tol': 1e-3, 'probability': True, 'shrinking': True, 'class_weight': 'balanced' }, 'svm_mat': { 'C': 10000.0, 'gamma': 0.1, 'tol': 1e-3, 'pro...
StarcoderdataPython
198398
<reponame>berez23/anchore import sys import os import re import json import getpass import click import yaml import time import shutil from anchore.cli.common import anchore_print, anchore_print_err from anchore.util import contexts from anchore import anchore_utils, anchore_auth, anchore_feeds config = {} @click.gr...
StarcoderdataPython
162681
<reponame>baradist/multiagent-particle-envs import os import numpy as np import tensorflow as tf from tensorflow.initializers import random_uniform class Critic(object): def __init__(self, lr, n_actions, name, input_dims, sess, fc1_dims, fc2_dims, batch_size=64, chkpt_dir='tmp/ddpg'): self.lr = lr ...
StarcoderdataPython
3363054
from re import fullmatch def count(data, bag): result = 1 if bag in data: for n, child_bag in data[bag]: result += n * count(data, child_bag) return result data = {} with open("input.txt", 'r', encoding="utf-8") as file: for line in file: cur_bag, inner_bags = fullmatc...
StarcoderdataPython
1798742
# File : helper.py # Created by gabys # Date : 30/03/2020 # License : Apache 2.0 import os import re import zipfile from typing import Optional def is_zip(file_type) -> bool: """ Check if the given file is a ZIP Returns: bool: Whether it's a ZIP file or not """ mimes = { 'applicati...
StarcoderdataPython
1757368
<reponame>OxfordBot/raspi-camera2 # Import modules import os import sys import cv2 from tkinter import * # Clear CMD # Commands from sys.argv count = 0 commands = {} getType = "" for argv in sys.argv: if ".py" not in argv.lower(): if count == 0: getType = argv.replace("-",...
StarcoderdataPython