id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3350004
import time from bottle import install, response @install def execution_time(func): def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() response.headers['X-Exec-Time'] = str(end - start) return result return wrapper
StarcoderdataPython
3216197
from math import pi, sin from geojson import Feature, LineString RADIUS = 6378137 def geom_reduce(geojson, initial_value_param): initial_value = initial_value_param previous_value = initial_value_param def callback_geom_each( current_geometry, feature_index, feature_properties, ...
StarcoderdataPython
156526
<reponame>Anmol-Singh-Jaggi/interview-notes """ One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as #. _9_ / \ 3 2 / \ / \ 4 1 # 6 / \ / \ / \ # # # #...
StarcoderdataPython
3338221
<gh_stars>1-10 # Owner(s): ["oncall: distributed"] import sys from typing import Optional import torch import torch.distributed as dist import torch.nn from torch.testing._internal.common_utils import TestCase from torch.distributed._shard.checkpoint.resharding import ( _prepare_sharded_tensor_write, _create...
StarcoderdataPython
3245917
<reponame>eno-lang/enolib<filename>python/tests/generated/api/field/test_string_value.py<gh_stars>10-100 import enolib def test_querying_an_existing_required_string_value_from_a_field_produces_the_expected_result(): input = ("field: value") output = enolib.parse(input).field('field').required_string_value() ...
StarcoderdataPython
1620591
import collections q=collections.deque([10,20,30,40]) q.pop() print(q) #deque([10,20,30])
StarcoderdataPython
4812521
<reponame>shaysw/anyway import logging from anyway.request_params import RequestParams from anyway.widgets.widget import Widget class UrbanWidget(Widget): def __init__(self, request_params: RequestParams, name: str): if not UrbanWidget.is_urban(request_params): logging.error(f"UrbanWid...
StarcoderdataPython
1632115
<reponame>Neklaustares-tPtwP/torchflare<gh_stars>1-10 # flake8: noqa import os import torch from torchflare.callbacks.load_checkpoint import LoadCheckpoint from torchflare.callbacks.model_checkpoint import ModelCheckpoint from torchflare.experiments.core import State class Experiment: def __init__(self, model,...
StarcoderdataPython
1604577
<reponame>saman-codes/dldojo<gh_stars>0 # Standard Python import os import copy import pickle import logging from collections import OrderedDict # Local from layers import Layer from losses import BinaryCrossEntropy # Thirdparty import numpy as np from tqdm import tqdm import matplotlib.pyplot as plt logging.basicCo...
StarcoderdataPython
101234
import pathlib import pytest import parser import code TEMPLATE_DIR = pathlib.Path(__file__).resolve().parent.parent def test_parse_testsuite_0000_sample(): sample = f"{TEMPLATE_DIR}/sample/test-suite-00000-jsonplaceholder.yaml" ret = parser.yaml2dict(sample) print(ret) def test_test_suite_parse_init_one...
StarcoderdataPython
78179
# -*- coding: utf-8 -*- import warnings from contextlib import redirect_stderr, redirect_stdout, suppress from copy import deepcopy from logging import Logger, LogRecord from os import devnull from typing import Optional, Sequence, Sized, Tuple, TypeVar import numpy as np import pandas as pd import sklearn.datasets fr...
StarcoderdataPython
155134
<gh_stars>0 #Crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz quadrada. n = int(input('Informe um número')) print(f'O número informado é {n}\nSeu dobro é {n*2}\nSeu triplo é {n*3}\nSua raiz quadrada é {n**(1/2):.2f}')
StarcoderdataPython
169828
import os from pyscf.pbc.gto import Cell from pyscf.pbc.scf import KRHF from pyscf.pbc.tdscf import KTDHF from pyscf.pbc.tdscf import krhf_slow_gamma as ktd import unittest from numpy import testing import numpy from test_common import retrieve_m, retrieve_m_hf, assert_vectors_close, tdhf_frozen_mask class DiamondT...
StarcoderdataPython
3261063
""" This module contains methods for analysing extensions. """ import string from collections import defaultdict import nltk import pandas as pd import extensionstores chromecast_extension_ids = ["pkedcjkdefgpdelpbcmbmeomcjbeemfm", "enhhojjnijigcajfphajepfemndkmdlo"] def analyse_extensions_by_request_count_clean(r...
StarcoderdataPython
3261852
# # Package: MediaComp # Module: jes.pictures # Author: <NAME>, <EMAIL> # # Derived from source code, power point slides, and media (pictures, movies, # sounds) from http://mediacomputation.org created by <NAME> and others # licensed under the Creative Commons Attribution 3.0 United States License, # See: http://creati...
StarcoderdataPython
4826325
# -*- coding: utf-8 -*- # # Copyright (C) 2019 Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG), # acting on behalf of its Max Planck Institute for Intelligent Systems and the # Max Planck Institute for Biological Cybernetics. All rights reserved. # # Max-Planck-Gesellschaft zur Förderung der Wissens...
StarcoderdataPython
1695472
from script.model.sklearn_like_model.NetModule.InceptionSructure.BaseInceptionNetModule import \ BaseInceptionNetModule from script.util.Stacker import Stacker from script.util.tensor_ops import * class InceptionV4NetModule(BaseInceptionNetModule): def stem(self, stacker, name='stem'): with tf...
StarcoderdataPython
1677565
from __future__ import print_function __authors__ = "<NAME>, <NAME>" __copyright__ = "Copyright 2010-2012, Universite de Montreal" __credits__ = ["<NAME>", "<NAME>"] __license__ = "3-clause BSD" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" from pylearn2.testing.skip import skip_if_no_gpu skip_if_no_gpu() import n...
StarcoderdataPython
1616848
<reponame>Bhargavasomu/py-trie<gh_stars>0 import logging from hypothesis import ( given, settings, strategies, example, ) from hypothesis.types import RandomWithSeed from trie import HexaryTrie from trie.sync import HexaryTrieSync from .utils import make_random_trie logger = logging.getLogger() # ...
StarcoderdataPython
3250035
import sys sys.path.append('../') from uuid import uuid4 from typing import List from datetime import datetime from fastapi.encoders import jsonable_encoder from models.bbox import BboxModel async def create_user_bbox(coords, area): bbox = BboxOut( id=uuid4(), created_on=datetime.utcnow(), ...
StarcoderdataPython
40961
<reponame>ramarketing/signalwire-python<gh_stars>10-100 from .base_fax import BaseFax from ..constants import Method class FaxSend(BaseFax): def __init__(self, call, document, identity=None, header=None): super().__init__(call) self._document = document self._identity = identity self._header = heade...
StarcoderdataPython
1722457
<reponame>JaydenYL/Projects<filename>INFO1112/week8/writebin.py f = open('ttt.bin', 'wb') f.write(b'""UU') f.close()
StarcoderdataPython
3292793
import json import traceback from datetime import datetime from sqlalchemy import func from apps.auth.models.users import User from apps.jobs.models.jobs import JobsRecord from apps.project.business.assets import PhoneBorrowBusiness, PhoneBusiness from apps.project.business.credit import CreditBusiness from apps.proj...
StarcoderdataPython
6909
import tensorflow as tf from tensorflow.python.training.session_run_hook import SessionRunArgs # Define data loaders ##################################### # See https://gist.github.com/peterroelants/9956ec93a07ca4e9ba5bc415b014bcca class IteratorInitializerHook(tf.train.SessionRunHook): """Hook to initialise data...
StarcoderdataPython
1672062
<gh_stars>0 # Scanning tests # Copyright (c) 2013-2015, <NAME> <<EMAIL>> # # This software may be distributed under the terms of the BSD license. # See README for more details. import time import logging logger = logging.getLogger() import os import subprocess import hostapd from wpasupplicant import WpaSupplicant fr...
StarcoderdataPython
160614
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This script saves bid and ask data for specified ETFs to files for each day during market open hours. It assumes the computer is at US East Coast Time. @author: mark """ import os import pandas as pd import numpy as np from itertools import product import streaml...
StarcoderdataPython
1643881
from setuptools import setup, find_packages with open('README.md') as fp: long_description = fp.read() setup( name='typeform', version='1.1.0', description='Python Client wrapper for Typeform API', long_description=long_description, long_description_content_type='text/markdown', keywords=[...
StarcoderdataPython
3213724
import numpy as np import pandas as pd import matplotlib.pyplot as plt country_code = {'US': '082', # United States 'AU': '127', # Australia 'CA': '101', # Canada 'GE': '910', # Germany 'UK': '110', # United Kingdom 'JP': '105', # Ja...
StarcoderdataPython
1637573
<gh_stars>0 from .thermostat import Thermostat, CommonThermostat, CT30v175, CT30v192, CT50v109, CT50v188, CT50v194, CT80RevB2v103 from . import discover from . import fields THERMOSTATS = (CT30v175, CT30v192, CT50v109, CT50v188, CT50v194, CT80RevB2v103,) def get_thermostat_class(model): """ :param model: st...
StarcoderdataPython
1686616
""" Scripts specific to dealing with motion, in particular motion retargeting of mixamo data. Relies on Blender 2.79 API. """ import bpy import logging import re LOG = logging.getLogger(__name__) def detect_bone_prefix(bones): """ Mixamo data tends to prefix bone names with character names or other prefixes....
StarcoderdataPython
3306191
<filename>phidl/geometry.py<gh_stars>0 # -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import import numpy as np import itertools from numpy import sqrt, pi, cos, sin, log, exp, sinh # from scipy.interpolate import interp1d import gdspy from gdspy import clipper from phidl.device_layo...
StarcoderdataPython
146898
from setuptools import setup, find_packages setup( name='pypolycontain', author='<NAME>', description='A python package for polytopic objects, operations, and containment encodings', author_email='<EMAIL>', version='1.3', packages=['pypolycontain'], #fix long_description='A python package ...
StarcoderdataPython
171607
<reponame>qk-i/candidate-test-5d69fbf4 from __future__ import annotations from unittest import mock from django.http import HttpRequest from visitors import context_processors from visitors.models import Visitor class TestVisitorContextProcessor: def test_visitor(self): request = HttpRequest() ...
StarcoderdataPython
3368020
from enum import Enum import random import pygame class WorldState (Enum): WORLD_SPAWN = 0, WORLD_PLAY = 1, WORLD_OVER = 2 class SpaceInvaders: def __init__(self): # init all pygame systems... pygame.init() pygame.mixer.init() # display data s...
StarcoderdataPython
66526
# -- Setup Django -- from os import environ as env from os.path import dirname, join from sys import path path.insert(0, dirname(dirname(__file__))) path.insert(1, join(dirname(__file__), '_ext')) env['DJANGO_SETTINGS_MODULE'] = 'MangAdventure.tests.settings' __import__('django').setup() # -- Project information --...
StarcoderdataPython
178781
<reponame>AnnaSvalova/anytask import os # from anytask.settings_common import INSTALLED_APPS DEBUG = os.environ.setdefault('DJANGO_DEBUG', 'False') TEMPLATE_DEBUG = DEBUG INSTALLED_APPS = list(INSTALLED_APPS) + ['jupyter'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', ...
StarcoderdataPython
3397647
"""Main interface for evolving applications.""" from __future__ import unicode_literals import itertools import logging from collections import OrderedDict from contextlib import contextmanager from django.db import connections from django.db.utils import DEFAULT_DB_ALIAS from django.utils.translation import ugettex...
StarcoderdataPython
1635965
<filename>Shadow/__init__.py # # import to the main level the main objects first defined in C (ShadowLib) # then extended in ShadowLibExtensions # #from Shadow import ShadowLib from __future__ import print_function from Shadow.ShadowLibExtensions import OE, Source, Beam, CompoundOE, IdealLensOE # Defined in C, not u...
StarcoderdataPython
3373739
def check_sudoku(true_vars): """ Check sudoku. :param true_vars: List of variables that your system assigned as true. Each var should be in the form of integers. :return: """ import math as m s = [] row = [] for i in range(len(true_vars)): row.append(str(int(true_vars[i]) % 1...
StarcoderdataPython
1665703
# coding=utf-8 from OTLMOW.OTLModel.BaseClasses.OTLAttribuut import OTLAttribuut from OTLMOW.OTLModel.Classes.LaagDikte import LaagDikte from OTLMOW.OTLModel.Classes.Laag import Laag from OTLMOW.OTLModel.Datatypes.BooleanField import BooleanField from OTLMOW.OTLModel.Datatypes.DtcKrimpvoeg import DtcKrimpvoeg from OTLM...
StarcoderdataPython
136320
<gh_stars>0 from typing import Any, Tuple from neuraxle.base import BaseTransformer from neuraxle.base import ExecutionContext as CX from neuraxle.data_container import DataContainer as DACT from neuraxle.hyperparams.space import (HyperparameterSamples, HyperparameterSpace) from...
StarcoderdataPython
1764045
import requests class Image(object): def __init__(self, client_id="", api_key=""): self.client_id = client_id self.api_key = api_key self.name = None self.id = None self.distribution = None def __call_api(self, path, params=dict()): payload = {'client_id': self...
StarcoderdataPython
1662211
<reponame>michaelhaaf/PolyglotDB class Track(object): """ Track class to contain, select, and manage :class:`~polyglotdb.acoustics.classes.TimePoint` objects Attributes ---------- points : iterable of :class:`~polyglotdb.acoustics.classes.TimePoint` Time points with values of the acoustic t...
StarcoderdataPython
3327905
<filename>instagram_api/response/broadcast_like_count.py from .mapper import ApiResponse, ApiResponseInterface from .model import User __all__ = ['BroadcastLikeCountResponse'] class BroadcastLikeCountResponseInterface(ApiResponseInterface): like_ts: int likes: int burst_likes: int likers: [User] c...
StarcoderdataPython
3246991
from .expectation_maximization import ExpectationMaximization
StarcoderdataPython
107512
<reponame>apetesh/firefly import math import os import os.path import subprocess import tornado.web import xml.etree.cElementTree as ET import firefly.data_source class GangliaRRD(firefly.data_source.DataSource): """Stats from Ganglia""" DESC = "Ganglia Stats" path_splitter = "" def __init__(self,...
StarcoderdataPython
1738619
<reponame>tomi77/slumber-extra<filename>setup.py from setuptools import setup setup( name='slumber-serializers', version='0.1.0', author='<NAME>', author_email='<EMAIL>', url='https://github.com/tomi77/slumber-serializers', description='A set of Slumber serializers', long_description=open('...
StarcoderdataPython
85262
""" Line Chart with datum --------------------------------- An example of using ``datum`` to highlight certain values, including a ``DateTime`` value. This is adapted from two corresponding Vega-Lite Examples: `Highlight a Specific Value <https://vega.github.io/vega-lite/docs/datum.html#highlight-a-specific-data-value>...
StarcoderdataPython
196779
<reponame>SourceCode-AI/fassert<filename>tests/test_primitives.py import re import unittest from fassert import fassert class MatchingPrimitivesTest(unittest.TestCase): def test_matching_primitives(self): test_data = ( ("", ""), ("test_string", "test_string"), (b"test_...
StarcoderdataPython
3203233
<gh_stars>0 from datetime import date, datetime import jsonpickle from bson import ObjectId from cryptodataaccess.Transactions.TransactionRepository import TransactionRepository from cryptodataaccess.Transactions.TransactionMongoStore import TransactionMongoStore from cryptodataaccess.Users.UsersMongoStore import User...
StarcoderdataPython
1641212
import argparse import re """ --- Day 9: Explosives in Cyberspace --- Wandering around a secure area, you come across a datalink port to a new part of the network. After briefly scanning it for interesting files, you find one file in particular that catches your attention. It's compressed with an experimental format,...
StarcoderdataPython
3383701
import keras.layers as layer class Conv(layer.Layer): def __init__(self, channel, kernel_size, name, padding='same', activation = 'relu', strides=(1, 1), **kwargs): self.channel = channel self.kernel_size = kernel_size self.padding = padding self.activation = activa...
StarcoderdataPython
4817468
<reponame>codewithrakib/first-django-blog from django.db import models from django.contrib.auth.models import User from django.utils.text import slugify from django.shortcuts import redirect STATUS_CHOICES = ( ('draft', 'Draft'), ('publish', 'Publish'), ) class Post(models.Model): user = models.ForeignKey(...
StarcoderdataPython
4814151
# -*- coding: utf-8 -*- """hstest.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1r6_GKKju6U80i3VUIwdozBgjyIyiFgtl """ from google.colab import drive drive.mount('/content/drive') ''' Testing Script ''' import json import pickle import numpy as...
StarcoderdataPython
99638
# Importing Necessary projects import cv2 import numpy as np # Creating the video capture object cap = cv2.VideoCapture(0) # Defining upper and lower ranges for yellow color # If you don't have a yellow marker feel free to change the RGB values Lower = np.array([20, 100, 100]) Upper = np.array([30, 255, 255]) # Defi...
StarcoderdataPython
1695637
''' Cartesian product of a vector of vectors The coding challenge was print all combinations you can create from a vector of a vector of strings, find all valid strings you can create from a list of letters you have. Input: [ [ a, b ], [ c, d, e ], [ f, g ] ] Questions ? Max scale of Input...
StarcoderdataPython
3363284
{ "variables": { "gypkg_deps": [ "../libuv => uv.gyp:libuv", ], }, "targets": [{ "target_name": "uv_link_t", "type": "<!(gypkg type)", "direct_dependent_settings": { "include_dirs": [ "include" ], }, "dependencies": [ "<!@(gypkg deps <(gypkg_deps))" ], "in...
StarcoderdataPython
109859
<gh_stars>0 # coding=utf-8 """ A translator runner by itself """ from typing import TypeVar, List from fluentogram.src.impl import AttribTracer, FluentTranslator TTranslatorRunner = TypeVar("TTranslatorRunner", bound="TranslatorRunner") class TranslatorRunner(AttribTracer): """This is one-shot per Telegram even...
StarcoderdataPython
4805119
<reponame>sarvex/DjangoUnchained # Register your models here. from django.contrib import admin from stories.models import Story admin.site.register(Story)
StarcoderdataPython
4824663
import tensorflow as tf from model import create_model import utils model = create_model(True) ckpt = tf.train.Checkpoint(model=model) ckpt_manager = tf.train.CheckpointManager(ckpt, utils.ckpt_path, 5) if ckpt_manager.latest_checkpoint: ckpt.restore(ckpt_manager.latest_checkpoint).assert_consumed() print("La...
StarcoderdataPython
3302023
import os import shutil import sys GLOBAL_PATH = '' # Folders to create folders = ['archive', 'audio', 'documents', 'images', 'video', 'other'] # Extentions of known files archive_ext = ['.7z', '.ace', '.arj', 'bz2', '.cab', '.cbr', '.d8t', '.deb', '.gz', '.gzip', '.gztar', '.jar', '.pak', ...
StarcoderdataPython
3242572
<filename>dao/replyDao.py from domain.database import DBSession from domain.reply import Reply import datetime # 从x位置获取n个跟帖 def selectReplyFromXGetN(topicId, x, n): try: session = DBSession() offset = x num = x + n reply = session.query(Reply).filter(Reply.topicId == topic...
StarcoderdataPython
1618944
<gh_stars>1-10 from .operation import Operation from ..util._collections import _escape_column, _escape_mapper_args class Insert(Operation): def insert(self, table): """ examples: insert('table1') """ if not table: raise ValueError('table cannot be empty') ...
StarcoderdataPython
116538
<reponame>fizista/Mturk-Tracker # -*- coding: utf-8 -*- import time import logging from optparse import make_option from django.db.models import F from django.core.management import call_command from django.conf import settings from utils.management.commands.base.crawl_updater import CrawlUpdaterCommand from utils.s...
StarcoderdataPython
1632091
#!/usr/bin/env python3 from dataloaders import MsdBbLoader def main(): loader = MsdBbLoader( hits_file_path= './storage/msd_bb_matches.csv', non_hits_file_path= './storage/msd_bb_non_matches.csv', features_path='./tools', non_hits_per_hit=1, features=['hl']...
StarcoderdataPython
3209364
class Coalition: neutral = 0 Allies = 1 Axis = 2 class Country: neutral = 0 USSR = 101 Germany = 201
StarcoderdataPython
3270514
#!/usr/bin/env python3 # Copyright 2021 The Kubernetes 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 appl...
StarcoderdataPython
65158
# Copyright 2021 solo-learn development team. # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to use, # copy, modify, merge, publ...
StarcoderdataPython
178582
import torch from torch import nn import numpy as np from collections import OrderedDict from torch.utils.data import DataLoader from torch.utils.data import Sampler from contextlib import nullcontext import yaml from yaml import SafeLoader as yaml_Loader, SafeDumper as yaml_Dumper import os,sys from tqdm import tqdm...
StarcoderdataPython
65170
<reponame>vaynelau/ZS3-voc12 import os import numpy as np import torch from torch import nn from tqdm import tqdm from zs3.dataloaders import make_data_loader from zs3.modeling.deeplab import DeepLab from zs3.modeling.gmmn import GMMNnetwork from zs3.modeling.sync_batchnorm.replicate import patch_replicatio...
StarcoderdataPython
185913
# Version of the specification for MDF MODECI_MDF_VERSION = "0.1" # Version of the python module. Use MDF version here and just change minor version __version__ = "%s.3" % MODECI_MDF_VERSION
StarcoderdataPython
4805726
<filename>tintg/prod_settings/__init__.py import dj_database_url from tintg.settings import * DEBUG = False TEMPLATE_DEBUG = False DATABASES['default'] = dj_database_url.parse(get_env_variable('TINTG_DB_URL')) SECRET_KEY = get_env_variable('TINTG_SECRET_KEY') ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', ...
StarcoderdataPython
178460
<reponame>Informasjonsforvaltning/fdk-model-publisher """Model Element mapper.""" from copy import deepcopy from typing import Dict, List, Optional, Union from datacatalogtordf import URI from modelldcatnotordf.modelldcatno import ( Attribute, Choice, CodeElement, CodeList, Composition, ModelE...
StarcoderdataPython
1772253
class Cajero: def __init__(self, estado, id, tiempo_utilizacion, acum_t_utilizacion, cliente): self.id = id self.estado = estado self.cliente = cliente self.tiempo_utilizacion = tiempo_utilizacion self.acum_t_utilizacion = acum_t_utilizacion def __eq__(self, otro): ...
StarcoderdataPython
3249459
from SimpleCV.base import * from SimpleCV.Features.Features import Feature, FeatureSet from SimpleCV.Color import Color from SimpleCV.ImageClass import Image from SimpleCV.Features.Detection import ShapeContextDescriptor import math import scipy.stats as sps try: from sklearn import neighbors except: print "Nee...
StarcoderdataPython
51630
nome = str(input('Digite o seu nome completo:\n')) lista = nome.split() print('Seu primeiro nome é:\n {}'.format(lista[0])) print('Seu último nome é:\n {}'.format(lista[-1]))
StarcoderdataPython
3280780
print("this is a test for git") print('hello github') print("git test")
StarcoderdataPython
1655935
<reponame>cfernandesFEUP/GEARpie '''MIT License Copyright (c) 2022 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy...
StarcoderdataPython
40286
from network import Listener, Handler, poll handlers = {} # map client handler to user name class MyHandler(Handler): def on_open(self): pass def on_close(self): pass def on_msg(self, msg): print msg port = 8888 server = Listener(port, MyHandler) while...
StarcoderdataPython
4804473
from .balance_sheet_item import BalanceSheetItem class BalanceSheetItemTuple: def __init__( self, balance_sheet_item: BalanceSheetItem, debit: float, credit: float, ) -> None: self.balance_sheet_item = balance_sheet_item self.debit = debit self.credi...
StarcoderdataPython
4839922
from typing import Mapping, Optional, Union import numpy as np from collections import OrderedDict from scipy.sparse import issparse if False: from .base import AnnData, Index # noqa class AnnDataLayers: def __init__( self, adata: 'AnnData', layers: Optional[Mapping[str, np.ndarray]...
StarcoderdataPython
1657775
<reponame>dvpc/rgb-autoenc-tf ''' import tensorflow as tf sess = tf.Session() sess.run(init) a = tf.Variable( [ [[1,0,0],[2,0,0]], [[0,1,0],[0,2,0]], [[0,0,1],[0,0,2]] ] ) flat = tf.reshape(a,[3*2,3]) init = tf.initialize_all_variables() sess.run( init ) sess.run( flat ) sess.run( a ) sess.run( tf.transpose(flat,[1,0]...
StarcoderdataPython
3243062
import datetime import random import shutil import string import time from lab2 import write_image import fs from fs.memoryfs import MemoryFS import imutils from importlib import import_module import cv2 import cv2 as cv import os from google.cloud import storage if os.environ.get('CAMERA'): Camera = import_mo...
StarcoderdataPython
27283
#TODO: use only one (RGB) channel import numpy as np import pandas as pd import os from torch.utils import data from torch.utils.data.dataloader import DataLoader as DataLoader import torch from torchvision import transforms from natsort import natsorted, ns import cv2 from PIL import Image import matplotlib.pyplot as ...
StarcoderdataPython
1642575
<gh_stars>1-10 from ..xmlUtil import * from ..ActionEffect import ActionEffect from ..LangText import LangText class ChangeNodeEffect(ActionEffect): def __init__(self, nodeID = None, printNode = True, xml = None): self.nodeID = nodeID self.printNode = printNode if xml != None: validateNoChildren(xml) v...
StarcoderdataPython
1785975
""" Good morning! Here's your coding interview problem for today. This problem was asked by Twitter. A network consists of nodes labeled 0 to N. You are given a list of edges (a, b, t), describing the time t it takes for a message to be sent from node a to node b. Whenever a node receives a message, it immediately ...
StarcoderdataPython
3377146
import difflib import argparse import sys def main(argv): parser = argparse.ArgumentParser(description='Compare two text files and report differences') parser.add_argument('file1', help='file 1') parser.add_argument('file2', help='file 2') args = parser.parse_args() l1 = open(args.file1, 'r').rea...
StarcoderdataPython
1600501
<gh_stars>0 import bpy class OBJECT_OT_ResizeChart(bpy.types.Operator): '''Resizes selected chart to new specified dimensions''' bl_idname = 'object.resize_chart' bl_label = 'Resize Chart' bl_options = {'REGISTER'} source: bpy.props.EnumProperty( items=( ('default', 'Default C...
StarcoderdataPython
1621452
""" .. harn_master.py """ ## Framework import drv.core import drv.game.base ## Tools import functools as fn ## Sugar dk = drv.game.base.dk def _harn_master_operator(r, t): success = 1 if r < t else -1 critical = 1 if r % 5 else 2 return success * critical def test(skill): """ Return a random vari...
StarcoderdataPython
129186
<reponame>kiranrraj/100Days_Of_Coding<filename>Day_58/lambda_exp.py<gh_stars>0 # Title : Lambda example # Author : <NAME>. # Date : 31:10:2020 def higher_o_func(x, func): return x + func(x) result1 = higher_o_func(2, lambda x: x * x) # result1 x = 2, (2*2) + 2, x = 6 result2 = higher_o_func(2, lambda x: x + 3) ...
StarcoderdataPython
3368166
import socket UDP_IP = "192.168.10.1" UDP_PORT = 8889 print("Tello UDP target IP:", UDP_IP) print("UDP target port:", UDP_PORT) class Tello(object): def __init__(self, interface=2, timeout=2): self.sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM, socket.IPPROTO_UDP) # UDP...
StarcoderdataPython
3371835
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Mar 17 23:14:28 2018 @author: <NAME> """ import numpy as np def centroid (power_spectrum:list, fft_size:int, sampling_rate:int) -> float: """ Spectral centroid :param power_spectrum: power spectrum in list :param fft_size: size of fft...
StarcoderdataPython
4817303
from django.urls import reverse from rest_framework import status from rest_framework.authtoken.models import Token from rest_framework.test import APITestCase from core.models import Ingredient from users.factories import UserFactory, IngredientFactory from recipe.serializers import IngredientSerializer class Publ...
StarcoderdataPython
17057
#!/usr/bin/env python # # Copyright 2013 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
StarcoderdataPython
3331997
<reponame>huster-wgm/SRCGAN import math import torch import numpy as np import torch.nn as nn import torch.nn.functional as F def get_deconv_params(upscale_factor): """ args: ratio:(str) upsample level H_out =(H_in−1)×stride[0]−2×pad[0]+ksize[0]+output_padding[0] """ if upscale_factor...
StarcoderdataPython
1720844
<reponame>NCBI-Hackathons/Tumor_sim<gh_stars>1-10 from Bio import SeqIO import numpy as np from mutation_creator import Mutation_Creator from mutation_tracker import Mutation_Tracker import logging from probabilities_config import structural_variations_probabilities, snv_probabilities class Mutation_Orchestrator: ...
StarcoderdataPython
3364535
<filename>nip24/invoicedata.py<gh_stars>0 # # -*- coding: utf-8 -*- # # Copyright 2015-2020 NETCAT (www.netcat.pl) # # 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/li...
StarcoderdataPython
3273067
<filename>fem/config_file.py from __future__ import print_function, absolute_import import os config_file = os.path.join(os.path.dirname(__file__), 'configuration.fem.0.0.0.json') del os
StarcoderdataPython
3381017
<filename>utilities/transport/convert_rail_station_journey_fares.py """Read from transport data to output smif scenario """ import os import sys import pandas as pd def main(input_filename, output_filename): """Run script """ # Could use glob to find similarly-named engineTypeFraction*.csv df_in = pd...
StarcoderdataPython
195026
from typing import Tuple, List, Dict from numpy.typing import NDArray import numpy as np import pandas as pd from ..ray_tracer.obj_reader import ObjToTriangles from ...utils import VecNorm, VecDistance, VecAngle, PosBetweenXZ, SortPointsFromPlaneY from ...utils.constants import EPSILON, MIN_ROOF_EDGE_DISTANCE, ROOF_M...
StarcoderdataPython