id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
4838239
<filename>aes/aes.py DOCS_PDF = 'http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf' sbox = ( # Substitution Box 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC...
StarcoderdataPython
3311612
import contextlib import numpy as np # https://stackoverflow.com/questions/2891790/how-to-pretty-printing-a-numpy-array-without-scientific-notation-and-with-given#2891805 @contextlib.contextmanager def np_printoptions(*args, **kwargs): original = np.get_printoptions() np.set_printoptions(*args, **kwargs) t...
StarcoderdataPython
4807299
#!/usr/bin/python class A: def f(self): return self.g() def g(self): return 'A' class B(A): def g(self): return 'B' a = A() b = B() print ('a.f(), b.f()') print ('a.g(), b.g()')
StarcoderdataPython
3372846
<filename>edX/MIT6001x/wk1/wk_1_for1.py x = 2 for i in range(2, 12, 2): print(x) x += 2 print('Goodbye!')
StarcoderdataPython
120294
import datetime import json import sys from caresjpsutil import PythonLogger from pyproj import Proj, transform import admsTest from admsAplWriterShip import admsAplWriter from admsInputDataRetrieverChimney import admsInputDataRetriever from config import Constants from adms_apl_builder import * pythonLogger = PythonL...
StarcoderdataPython
1667699
<filename>seamless/graphs/multi_module/mytestpackage/sub/mod1.py from .. import testvalue from mytestpackage.mod3 import testfunc from ..mod4 import blah def func(): return testvalue
StarcoderdataPython
1761238
""" Copyright 2013 Twitter, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distr...
StarcoderdataPython
3289332
"""The messiest test file in the world. Runs 'smoke test' to make sure everything runs. """ import numpy as np import tasks import representations import matplotlib.pyplot as plt import plotting import util import seaborn as sns def test_everything_runs(): """Check everything runs.""" discount = .9 sigma ...
StarcoderdataPython
195241
<filename>calamari_ocr/test/test_model_zoo.py import os import tempfile import unittest from glob import glob from subprocess import check_call import pytest from tensorflow.python.keras.backend import clear_session from tfaip.data.databaseparams import DataPipelineParams from calamari_ocr.ocr.predict.params import P...
StarcoderdataPython
140025
config = { 'population_size' : 100, 'mutation_probability' : .1, 'crossover_rate' : .9, # maximum simulation runs before finishing 'max_runs' : 100, # maximum timesteps per simulation 'max_timesteps' : 150, # smoothness value of the line in [0, 1] 'line_smoothness' : .4, # Bound ...
StarcoderdataPython
15186
<filename>Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/video_pipeline/forms.py """ Defines a form to provide validations for course-specific configuration. """ from django import forms from openedx.core.djangoapps.video_config.forms import CourseSpecificFlagAdminBa...
StarcoderdataPython
3204463
import os import numpy as np import tensorflow as tf import gpflow from GPcounts import branchingKernel from GPcounts import NegativeBinomialLikelihood from sklearn.cluster import KMeans import scipy.stats as ss from pathlib import Path import pandas as pd from gpflow.utilities import set_trainable from tqdm import tq...
StarcoderdataPython
1764336
# -*- coding: utf-8 -*- """ Created on Mon Jul 30 12:29:06 2018 @author: <NAME> """ import numpy as np import cv2 import glob import matplotlib.pyplot as plt #%matplotlib qt ## Calculates calibration coefficients def calib_cam(): # prepare object points nx = 9#TODO: enter the number of inside corners in x ...
StarcoderdataPython
3339853
from abc import ABCMeta, abstractmethod from base64 import b64decode, b64encode from dataclasses import dataclass, field from datetime import datetime, timedelta from typing import Any, Callable, Dict, FrozenSet, Iterable, Iterator, List, Optional, Set, Type from uuid import UUID, uuid4 from .policies import CoalesceP...
StarcoderdataPython
1720247
#!/usr/bin/env python # -*- coding: utf-8 -*- """Add random data to dummy speakers.csv data""" from random import random import lorem import pandas as pd # institutions def get_random_institution(row): insts = [['KCL', 0.3], ['UCL', 0.5], ['Imperial', 0.6], ['Oxford', 0.7], ['Cambridge', 0.8], ['Manc...
StarcoderdataPython
54246
<gh_stars>0 from sqlalchemy import Column, Integer, String, DateTime from mps_database.models import Base import datetime class InputHistory(Base): """ InputHistory class (input_history table) Input data collected from the central node All derived data is from the mps_configuration database. Properties:...
StarcoderdataPython
4813574
<gh_stars>0 example = 3 data = 314 def func1(data): buf = [0] current_pos = 0 for i in range(2017): current_pos = (current_pos + data) % len(buf) buf.insert(current_pos+1, i+1) current_pos += 1 return buf[(current_pos + 1) % len(buf)] print(func1(example)) print(func1(data)) ...
StarcoderdataPython
3230814
<reponame>IMULMUL/PythonForWindows import sys import os.path sys.path.append(os.path.abspath(__file__ + "\..\..")) import windows system = windows.system print("Basic system infos:") print(" version = {0}".format(system.version)) print(" bitness = {0}".format(system.bitness)) print(" computer_name = {0}".for...
StarcoderdataPython
1603124
<reponame>Signbank/signbank """Create small videos for GlossVideos that have no small version.""" import os from django.core.management.base import BaseCommand from django.core.exceptions import ObjectDoesNotExist from signbank.settings.base import WRITABLE_FOLDER from signbank.dictionary.models import Dataset from si...
StarcoderdataPython
3374764
<gh_stars>0 from django.urls import path from . import views app_name = 'produto' urlpatterns = [ path('', views.ListaProdutos.as_view(), name='lista'), path('<slug>', views.DetalheProduto.as_view(), name='detalhe'), path('addtocart/', views.AddToCart.as_view(), name='addtocart'), path('removetocart/'...
StarcoderdataPython
3393114
from datetime import datetime from django.utils.timezone import make_aware from django.db import IntegrityError from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.permissions import AllowAny from treeckle.common.exceptions impor...
StarcoderdataPython
3359324
<gh_stars>0 # This file is part of the Indico plugins. # Copyright (C) 2002 - 2019 CERN # # The Indico plugins are free software; you can redistribute # them and/or modify them under the terms of the MIT License; # see the LICENSE file for more details. from flask import session from flask_pluginengine import depends ...
StarcoderdataPython
171167
<gh_stars>0 # Início do programa print("\n"*100) print("Neste jogo você deve convencer Deus a não destruir Sodoma e Gomorra.") print("No prompt 'Eu' Digite:") print("--> Senhor, e se houver xyz justos na cidade?") print("(Onde 'xyz' corresponde a um número entre 0 e 999)") print("BOA SORTE!!!") input("Tecle <ENTER> ")...
StarcoderdataPython
3234982
from fastapi import FastAPI from datetime import datetime from typing import Optional from fastapi.encoders import jsonable_encoder from model.model import Task, TaskList import model.taskman as taskman app = FastAPI() @app.get("/api/tasks") async def get_tasks(): """TODO Fetch the list of all tasks """...
StarcoderdataPython
168056
<reponame>dt/SublimeScalaAddImport<filename>foursquare/source_code_analysis/scala/scala_import_parser.py # coding=utf-8 # Copyright 2013 Foursquare Labs Inc. All Rights Reserved. from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicod...
StarcoderdataPython
3267816
<gh_stars>0 from django.contrib import admin # Register your models here. from .models import Product, Country, Town, StockCard class StockCardAdmin(admin.ModelAdmin): pass admin.site.register(StockCard, StockCardAdmin) admin.site.register(Country) admin.site.register(Town) admin.site.register(Product)
StarcoderdataPython
3336596
<reponame>ChucklesZeClown/learn-python # create a string variable consisting of some text plus a formatted value x = "There are %d types of people." % 10 # create a string binary = "binary" # create another string do_not = "don't" # create a third string, which includes the previous 2 strings using formatted values y =...
StarcoderdataPython
1789230
PERIOD_TYPE_MONTH = "MONTH" PERIOD_TYPE_QUARTER = "QUARTER" PERIOD_TYPE_SIX_MONTH = "SIX_MONTH" PERIOD_TYPE_YEAR = "YEAR" def detect(dhis2_period): if len(dhis2_period) == 4: return PERIOD_TYPE_YEAR if "Q" in dhis2_period: return PERIOD_TYPE_QUARTER if "S" in dhis2_period: return...
StarcoderdataPython
158101
import base64 from collections import namedtuple from datetime import datetime import hashlib import os import secrets import struct import sys import time from fido2.client import Fido2Client from fido2.ctap2 import CTAP2 from fido2.ctap2 import CredentialManagement from fido2.hid import CtapHidDevice from fido2.util...
StarcoderdataPython
1777537
from django import forms from .models import Blog from django.contrib.auth.models import User class SignUpForm(forms.ModelForm): class Meta: password = forms.CharField(widget=forms.PasswordInput) model = User widgets = { 'password': forms.PasswordInput(), } fiel...
StarcoderdataPython
1626631
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import ...
StarcoderdataPython
3371894
import pathlib import os import logging from timeit import default_timer as timer from decimal import Decimal from rich import print as rprint from rich.text import Text from rich.console import Console import subprocess log_format = '%(asctime)s %(filename)s: %(message)s' logging.basicConfig(filename='../app.log', le...
StarcoderdataPython
1737256
import os import subprocess import sys from django.test import TestCase from django.core.exceptions import ImproperlyConfigured from unittest.mock import patch from configurations.importer import ConfigurationImporter ROOT_DIR = os.path.dirname(os.path.dirname(__file__)) TEST_PROJECT_DIR = os.path.join(ROOT_DIR, 't...
StarcoderdataPython
1741242
<gh_stars>1-10 from typing import Dict, Any, Optional from mmic_translator.models import ToolkitModel from mmelemental.models.forcefield import ForceField import parmed from mmic_parmed.components.ff_component import FFToParmedComponent from mmic_parmed.components.ff_component import ParmedToFFComponent __a...
StarcoderdataPython
1657287
import pygame WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) FPS = 60 WIDTH, HEIGHT = 600, 700 ROWS = COLS = 40 TOOLBAR_HEIGHT = HEIGHT - WIDTH PIXEL_SIZE = WIDTH // COLS BG_COLOR = WHITE INVERTED_BG_COLOR = BLACK DRAW_GRID_LINES = True def get_font(size):...
StarcoderdataPython
1736947
# -*- coding: utf-8 -*- # Data Preprocessing # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Data.csv') ## [:, :-1] 1st : -> take all the lines | 2nd :-1 -> take all coluqms exvcept last column X = dataset.iloc[:, :-1]....
StarcoderdataPython
119366
import os import sys from openslide_reader import OpenslideReader import subprocess __all__ = ("PreprocessReader", ) import logging logger = logging.getLogger('slideatlas') from lockfile import LockFile class PreprocessReader(OpenslideReader): def __init__(self): logger.info('PreprocessReader init') ...
StarcoderdataPython
3326098
<filename>diffdirs/cli.py #!/usr/bin/env python # -*- coding: utf-8 -*- """Command Line Interface for diffdirs""" import argparse from pprint import pprint from .diffdirs import diff_dirs def parse_args(): """Parse arguments""" parser = argparse.ArgumentParser(prog="diffdirs") parser.add_argument( ...
StarcoderdataPython
1678785
""" Unit tests for the `HasTraits.class_traits` class function. """ from __future__ import absolute_import import six from traits import _py2to3 from traits.testing.unittest_tools import unittest from traits.api import HasTraits, Int, List, Str class A(HasTraits): x = Int name = Str(marked=True) cla...
StarcoderdataPython
3355633
<reponame>bmintz/python-snippets<filename>list_compare.py #!/usr/bin/env python3 # encoding: utf-8 import operator def list_compare(a, b, op): if len(a) != len(b) and op is operator.eq or op is operator.ne: return op is operator.ne # search for the first index where items are different for i in range(len(a)): ...
StarcoderdataPython
102027
async def setupAddSelfrole(plugin, ctx, name, role, roles): role_id = role.id name = name.lower() if role_id in [roles[x] for x in roles] or name in roles: return await ctx.send(plugin.t(ctx.guild, "already_selfrole", _emote="WARN")) if role.position >= ctx.guild.me.top_role.position: ...
StarcoderdataPython
197515
""" Copyright 2018 <NAME> [This program is licensed under the "MIT License"] Please see the file LICENSE in the source distribution of this software for license terms. """ #======================Imports======================== from flask import Flask, render_template, request, redirect, url_for, jsonify from...
StarcoderdataPython
19684
import json import os import shutil import urllib.request import traceback import logging import psutil from collections import defaultdict from typing import List, Dict, Tuple from multiprocessing import Semaphore, Pool from subprocess import Popen, PIPE from datetime import datetime, timedelta from lxml import etree...
StarcoderdataPython
3227099
<reponame>ysilvy/ocean_toe_2020 ''' Compute, in zonal means, how much of the ocean (per basin) has emerged from 1861 to 2100 ''' import os import glob from netCDF4 import Dataset as open_ncfile import matplotlib.pyplot as plt import numpy as np import datetime import pickle # -- Read result emerge = pickle.load( open...
StarcoderdataPython
1657598
<reponame>Gizmondd/longmbart #!/usr/bin/env python # -*- coding: utf-8 -*- import argparse from pathlib import Path from filter_foreign import filter_foreign_characters def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument( "--filter-files", ...
StarcoderdataPython
1705
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
StarcoderdataPython
1651319
from opyapi.schema.types.type import Type def is_optional(type_definition) -> bool: if isinstance(type_definition, Type): return type_definition.nullable origin_type = getattr(type_definition, "__origin__", None) if origin_type and type(None) in type_definition.__args__: return True ...
StarcoderdataPython
3363250
import discord import os import time import re import datetime from PIL import Image, ImageFont, ImageDraw from finnhub import client as Finnhub # api docs: https://finnhub.io/docs/api import requests import matplotlib import mplfinance import stocks import pandas as pd FINNHUB_CHART_API_TOKEN_2 = os.environ.get('FINN...
StarcoderdataPython
1798990
<reponame>pytexas/PyTexas<filename>conference/profiles/admin.py import traceback from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.template.response import TemplateResponse from django.conf import settings...
StarcoderdataPython
1655576
# Generated by Django 3.2.7 on 2021-09-16 15:42 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('django_world', '0002_auto_20210913_1528'), ] operations = [ migrations.CreateModel( name='Succe...
StarcoderdataPython
1620891
# Copyright (c) Microsoft Corporation. # Licensed under the Apache License 2.0. import random import os from base64 import b64decode import azext_aro.vendored_sdks.azure.mgmt.redhatopenshift.v2022_04_01.models as openshiftcluster from azure.cli.command_modules.role import GraphError from azure.cli.core.commands.clie...
StarcoderdataPython
3382215
from typing import Tuple, List, Dict from matplotlib import pyplot from tqdm import tqdm from utils.argument_parser import parse_arguments from utils.file_utils import get_files_to_be_processed, get_absolute_path, \ extract_judgements_from_given_year_from_file, extract_from_judgement, OUTPUT_DIRECTORY_PATH, save_...
StarcoderdataPython
1689142
# -*- coding: utf-8 -*- ############################################################################### # Copyright (c), Forschungszentrum Jülich GmbH, IAS-1/PGI-1, Germany. # # All rights reserved. # # This file is part of the AiiDA-FLEUR package. ...
StarcoderdataPython
1753803
<reponame>waverDeep/WaveBYOL<filename>src/utils/make_dataset.py<gh_stars>1-10 import pandas as pd import src.utils.interface_file_io as file_io from tqdm import tqdm from sklearn.model_selection import train_test_split def main(metadata_path): file_list = [] label = [] dataset = pd.read_csv(metadata_path) ...
StarcoderdataPython
3217809
import torch import math import torch.distributed as dist from torch.utils.data.sampler import Sampler from torch.utils.data.dataset import Dataset from typing import Optional, Iterator, Callable from collections import OrderedDict __all__ = ["LoadBalancingDistributedSampler", "LoadBalancingDistributedBatchSampler"] ...
StarcoderdataPython
3265857
<reponame>abretaud/biomaj2galaxy from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import click from future import standard_library from .config import read_global_config standard_library.install_aliases() __version__ = '2.1.0' CONT...
StarcoderdataPython
34482
<reponame>horacexd/clist # Generated by Django 2.2.10 on 2020-04-03 19:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('events', '0039_event_limits'), ] operations = [ migrations.AddField( model_name='event', n...
StarcoderdataPython
60829
<filename>test/test_parameters.py<gh_stars>1000+ # Copyright 2020 Tensorforce Team. 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...
StarcoderdataPython
3231124
# -*- coding: utf8 -*- CONNECT_MAX_TRY = 5
StarcoderdataPython
3394559
import os import sys sys.path.append("../../../monk/"); import psutil from keras_prototype import prototype ################################################### Foldered - Train Dataset ################################################################# ktf = prototype(verbose=1); ktf.Prototype("sample-project-1...
StarcoderdataPython
123041
# Copyright 2016 <NAME> (<EMAIL>) # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
StarcoderdataPython
190627
<reponame>ar90n/yolact from . import backbone, data, layers, utils, web, yolact, eval
StarcoderdataPython
1654320
def name_func(func, _, params): return f'{func.__name__}_{"_".join(str(arg) for arg in params.args)}' def get_enc_params(dtype): if dtype == "float32": return "PCM_F", 32 if dtype == "int32": return "PCM_S", 32 if dtype == "int16": return "PCM_S", 16 if dtype == "uint8": ...
StarcoderdataPython
29642
import ConfigParser from datetime import datetime import os import sys import numpy as np import pandas as pd import utils.counts import utils.counts_deviation __author__ = '<NAME>' # This script finds the days with the greatest deviation from some reference value (such as hourly means or medians) if __name__ == '_...
StarcoderdataPython
3332558
<filename>module2/Bot/bot_user_session.py<gh_stars>0 import cherrypy import aiml class Response(object): def __init__(self): self.kernel = aiml.Kernel() self.kernel.learn("startup.xml") self.kernel.respond("load aiml") self.question = Question() def _cp_dispatch(self,...
StarcoderdataPython
1769375
<gh_stars>100-1000 # pylint: disable=missing-function-docstring, missing-module-docstring, pointless-statement def sum_two_numbers(x : 'int', y : 'int'): x + y
StarcoderdataPython
3371131
import pytest from harvey.heap import InMemoryHeap def test_in_memory_heap_push_and_pop(monkeypatch): h = InMemoryHeap() h.push(1, 'cat') h.push(10, 'dog') assert h.pop() == 'cat' assert h.pop() == 'dog' def test_in_memory_heap_upsert_element(monkeypatch): h1 = InMemoryHeap() h1.push(1,...
StarcoderdataPython
99156
<filename>sequana_pipelines/bioconvert/main.py # # This file is part of Sequana software # # Copyright (c) 2016-2021 - Sequana Development Team # # Distributed under the terms of the 3-clause BSD license. # The full license is in the LICENSE file, distributed with this software. # # website: https://github.com/seq...
StarcoderdataPython
3242705
# Código Original # x = float(input('Digite a nota 1: ')) # y = float(input('Digite a nota 2: ')) # print (f'a media entre a nota {x} e a nota {y} é {(x+y)/2}') # Desafio da aula 11 x = float(input('\033[33mDigite a nota 1: ')) y = float(input('\033[33mDigite a nota 2: ')) print(f'a media entre a nota {x} e a nota {...
StarcoderdataPython
1699367
class Solution: def isValidSerialization(self, preorder: str) -> bool:
StarcoderdataPython
34033
import pandas as pd import click import collections def kmer_suffix(kmer): return kmer[1:] def kmer_prefix(kmer): return kmer[:-1] def chunks(l, n): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i:i + n] def build_graph(kmers): graph = collection...
StarcoderdataPython
1791502
<reponame>MelkiyHondavod/computations # Дано натуральное число N>1. Проверьте, является ли оно простым. # Программа должна вывести слово YES, если число простое и NO, если число составное. def is_prime(N): return "YES"
StarcoderdataPython
18284
<gh_stars>0 #!/usr/bin/env python import asyncio from abc import abstractmethod, ABC from enum import Enum import logging from typing import ( Optional, List, Deque ) from hummingbot.logger import HummingbotLogger from hummingbot.core.data_type.kline_stream_tracker_data_source import \ KlineStreamTrack...
StarcoderdataPython
4808803
import commands import datetime import json import logging import math import os import shutil import sys import time import traceback import threading import pickle import signal from os.path import abspath as _abspath, join as _join # logging.basicConfig(filename='Yoda.log', level=logging.DEBUG) import Interaction,...
StarcoderdataPython
1685289
import gym import matplotlib import torch import numpy as np from sac.model import GaussianPolicy, QNetwork, DeterministicPolicy # from core.notebook_utils import animate # from core.notebook_utils import gen_video seed = 123456 hidden_size = 256 device = 'cpu' # env_name = 'Hopper-v2' env_name = 'Walker2d-v2' # e...
StarcoderdataPython
3390861
<filename>08_multi_processing/mapPool.py<gh_stars>10-100 from multiprocessing import Pool import time def myTask(n): time.sleep(n+2) return n+2 def main(): with Pool(4) as p: for iter in p.imap_unordered(myTask, [1,3,2,1]): print(iter) if __name__ == '__main__': main()
StarcoderdataPython
1682802
<reponame>binti59/LV<filename>tests/test_transformers.py # tests to apply to all transformers import pytest import tubular.base as base import tubular.capping as capping import tubular.dates as dates import tubular.imputers as imputers import tubular.mapping as mapping import tubular.misc as misc import tubular.nominal...
StarcoderdataPython
36507
from m5stack import * from m5stack_ui import * from uiflow import * from ble import ble_uart import face screen = M5Screen() screen.clean_screen() screen.set_screen_bg_color(0x000000) mb_click = None rb_click = None lb_click = None snd_val = None st_mode = None stval = None prval = None faces_encode = face.get(face...
StarcoderdataPython
3255268
# Copyright 2020 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
StarcoderdataPython
3288151
__author__ = '<NAME> <<EMAIL>>' import unittest from bitcodin import Subscription from bitcodin import list_events from bitcodin import create_subscription from bitcodin import delete_subscription from bitcodin.test.bitcodin_test_case import BitcodinTestCase class DeleteSubscriptionTestCase(BitcodinTestCase): ...
StarcoderdataPython
1654072
"""This module provides decorator/context manager solutions that prevent wrapped operations from finishing before a given number of seconds has elapsed. Useful if you're fairly confident that your function should finish in a certain amount of time, but you want to make the return time constant (e.g. to prevent constan...
StarcoderdataPython
4828021
<reponame>eyalzek/gcpdiag<filename>gcpdiag/config.py # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
StarcoderdataPython
1754778
import csv from typing import List from app.data_readers.trip_data import TripData from app.data_readers.trip_data import Date class FileReader: def __init__(self, filename) -> None: self.filename = filename self.unprocessed_count = 0 def read(self) -> List[TripData]: rows = [] ...
StarcoderdataPython
67711
# -*- coding: utf-8 -*- import unittest from openeo_udf.server.data_model.metadata_schema import MetadataModel from openeo_udf.server.data_model.data_collection_schema import DataCollectionModel, ObjectCollectionModel, TimeStampsModel from openeo_udf.server.data_model.model_example_creator import create_simple_feature_...
StarcoderdataPython
137770
from .conv_head import ConvHead from .latent_head import LatentHead __all__ = [ 'ConvHead', 'LatentHead', ]
StarcoderdataPython
4823366
<reponame>zkan/pysomtum-pythonic-code # 1. Avoid comparing directly to `True`, `False`, or `None` a = True if a == False: # do something if a: # do something if a is None: # do something # 2. Avoid repeating variable name in compound if statement if name == 'Kan' or name == 'Man' or name == 'Natty': ...
StarcoderdataPython
3344807
import sys import numpy as np import torch from layers.encoding import * from layers.attention import * import torch.nn as nn class MMBiDAF(nn.Module): """ The combination of the Bidirectional Attention Flow model and the Multimodal Attention Layer model. Follows a high-level structure inspired from the B...
StarcoderdataPython
3242454
<gh_stars>1-10 # Simple Generator Function def simpleGenerator(): yield 1 yield 2 yield 3 x = simpleGenerator() print(x.__next__()); print(x.__next__()); print(x.__next__());
StarcoderdataPython
4817615
<filename>api/app/api/api_v1/endpoints/sources.py<gh_stars>10-100 from typing import Any, Dict, List from asyncpg.exceptions import UniqueViolationError from fastapi import APIRouter, HTTPException from orm.exceptions import NoMatch from starlette.status import ( HTTP_200_OK, HTTP_201_CREATED, HTTP_400_BAD...
StarcoderdataPython
3322624
<filename>azurefestorage.py import os, uuid from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient import json ##python blob storage test with open('credentials.json', 'r') as f: creds = json.load(f) connect_str = creds["azure_storage"]["connectionstring"] # print (connect_str)...
StarcoderdataPython
1608108
from graphene_django import DjangoObjectType from pnp_graphql.constants import MODEL_TYPE_ATTR from pnp_graphql.utils.class_factory import class_factory from pnp_graphql.utils.managers import get_enabled_app_models class GraphQlTypeGenerator(object): @classmethod def get_models_for_typing(cls, *args, **kwarg...
StarcoderdataPython
3348591
from django.contrib import admin from .models import post admin.site.register(post)
StarcoderdataPython
153426
# Copyright (c) 2020 Idiap Research Institute, http://www.idiap.ch/ # Written by <NAME> <<EMAIL>> # # This file is part of CBI Toolbox. # # CBI Toolbox is free software: you can redistribute it and/or modify # it under the terms of the 3-Clause BSD License. # # CBI Toolbox is distributed in the hope that it will be use...
StarcoderdataPython
77982
# Copyright 2021 Foundries.io # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
StarcoderdataPython
1764592
from __future__ import absolute_import from __future__ import division from __future__ import print_function """An example of customizing PPO to leverage a centralized critic with an imitation loss""" import argparse from ray.rllib.policy.sample_batch import SampleBatch from ray.rllib.utils import try_import_tf from ...
StarcoderdataPython
1674215
from odoo import models, fields, api from odoo import exceptions import logging _logger = logging.getLogger(__name__) class TodoWizard(models.TransientModel): _name = 'todo.wizard' _description = 'To-do Mass Assignment' task_ids = fields.Many2many('todo.task', string='Tasks') new_deadline = fields.Da...
StarcoderdataPython
17690
""" Driver class for Hagisonic Stargazer, with no ROS dependencies. """ from serial import Serial from collections import deque import re import yaml import time import logging import rospy import numpy as np from threading import Thread, Event from tf import transformations # STX: char that represents the start of a ...
StarcoderdataPython
1731337
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Written by <NAME>. MIT Licensed. Contact at www.sinclair.bio """ # Built-in modules # import os, glob # Internal modules # import autopaths # Constants # if os.name == "posix": sep = "/" if os.name == "nt": sep = "\\" ###########################################...
StarcoderdataPython
3266488
<gh_stars>0 from pathlib import Path from appdirs import user_data_dir user_data_directory = Path(user_data_dir(appname='ml4a', appauthor='golmschenk'))
StarcoderdataPython
4835084
# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors # This software is distributed under the terms and conditions of the 'Apache-2.0' # license which can be found in the file 'LICENSE' in this package distribution # or at 'http://www.apache.org/licenses/LICENSE-2.0'. import logging from cliff.li...
StarcoderdataPython