id
stringlengths
2
8
text
stringlengths
16
264k
dataset_id
stringclasses
1 value
3577846
<gh_stars>0 # Generated by Django 3.1.2 on 2020-10-13 16:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("core", "0002_auto_20201012_1804")] operations = [ migrations.AlterField( model_name="activity", name="description", ...
StarcoderdataPython
8014728
from abc import abstractmethod, ABCMeta from uuid import UUID from opyoid import Injector, Module from erica.infrastructure.InfrastructureModule import InfrastructureModule from erica.infrastructure.rq.RqModule import RqModule from erica.infrastructure.sqlalchemy.repositories.EricaAuftragRepository import EricaAuftra...
StarcoderdataPython
9700040
#!/usr/bin/env python import psycopg2 DBNAME = "news" query1 = """ SELECT '"' || articles.title || '"' , COUNT(log.id) AS views FROM articles CROSS JOIN log WHERE log.path = '/article/' || articles.slug AND log.status = '200 OK' GROUP BY articles.id ORD...
StarcoderdataPython
3300717
import requests class Pnr(object): def __init__(self): self.ids = {} #json = requests.get("https://api.coinmarketcap.com/v1/ticker/").json() #for cr in json: #self.ids[cr["symbol"]] = cr["id"] def get_pnr(self, pnrno): try: json = requests.get("https://api.railwayapi.com/v2/pnr-status/pnr/"+pnrno+"/ap...
StarcoderdataPython
4929108
<reponame>alexfikl/python-doi import re import logging __version__ = '0.1.1' logger = logging.getLogger("doi") def pdf_to_doi(filepath, maxlines=float('inf')): """Try to get doi from a filepath, it looks for a regex in the binary data and returns the first doi found, in the hopes that this doi is the ...
StarcoderdataPython
3387447
import warnings from contextlib import contextmanager from decimal import Decimal import webcolors from . import BaseRenderer, renders from ..operations import (BaseList, Bold, BulletList, CodeBlock, Footnote, Format, Group, Heading, HyperLink, Image, InlineCode, It...
StarcoderdataPython
11302953
# -*- coding: utf-8; -*- # # @file actioncontroller.py # @brief collgate # @author <NAME> (INRA UMR1095) # @date 2018-01-05 # @copyright Copyright (c) 2018 INRA/CIRAD # @license MIT (see LICENSE file) # @details from django.contrib.contenttypes.models import ContentType from django.db import transaction, IntegrityErr...
StarcoderdataPython
5164911
from rest_framework.permissions import BasePermission, SAFE_METHODS class IsSuperUser(BasePermission): """ Allow access only to superusers. """ message = 'Allow access only to superusers.' def has_permission(self, request, view): return bool( request.method in SAFE_METHODS or ...
StarcoderdataPython
6705380
<filename>models/team.py import logging import re from google.appengine.ext import ndb from helpers.champ_split_helper import ChampSplitHelper from models.location import Location class Team(ndb.Model): """ Teams represent FIRST Robotics Competition teams. key_name is like 'frc177' """ team_numbe...
StarcoderdataPython
9746537
from pypair.association import continuous_continuous from pypair.continuous import Continuous x = [x for x in range(10)] y = [y for y in range(10)] for m in Continuous.measures(): r = continuous_continuous(x, y, m) print(f'{r}: {m}') print('-' * 15) con = Continuous(x, y) for m in con.measures(): r = co...
StarcoderdataPython
1876012
import pprint import re import requests import upnpclient from philips_hue.models import Bridge def discover_hue(**kwargs): cloud = kwargs.get("cloud", False) upnp = kwargs.get("upnp", True) bridges = Bridge.select() bridge_addresses = [] for bridge in bridges: bridge_addresses.append(...
StarcoderdataPython
6528238
<gh_stars>1-10 import os, gzip, math import numpy as np import scipy.misc import imageio import matplotlib.pyplot as plt from matplotlib import cm import torch import torch.optim as optim import torchvision import torchvision.transforms as transforms import torch.nn as nn def load_dataset(dataset, batch_size = 64, for...
StarcoderdataPython
5069993
import requests from pyprintplus import Log class Flaschentaschen(): def __init__(self, show_log=True): self.logs = ['self.__init__'] self.show_log = show_log self.url = 'http://pegasus.noise:4444/api' self.help = 'https://www.noisebridge.net/Flaschen_Taschen' def log(self, te...
StarcoderdataPython
5094227
"""Version tests.""" from sphinxcontrib.towncrier import __version__ def test_version(): """Test that version has at least 3 parts.""" assert __version__.count('.') >= 2
StarcoderdataPython
8146523
import os, stat, hashlib, collections from filekeep import logger, xml def sha1_file(path, logger=None): sha1 = hashlib.sha1() with open(path, "rb", buffering=0) as f: while True: data = f.read(65536) if data: sha1.update(data) if logger: ...
StarcoderdataPython
5127891
<filename>tests/ssl_api.py from tests.test import WebTest from models import Test from database import db_session from datetime import datetime import requests import time class SSLAPITest(WebTest): API_ENDPOINT = "https://api.ssllabs.com/api/v2/" def __init__(self, scan): self.scan = scan se...
StarcoderdataPython
1785792
from pathlib import Path from ombpdf.semdom import to_dom from .snapshot import assert_snapshot_matches MY_DIR = Path(__file__).parent def assert_dom_xml_snapshot_matches(doc, force_overwrite=False): dom = to_dom(doc) xml = dom.toprettyxml(indent=' ') name = Path(doc.filename).stem expected_xml_pa...
StarcoderdataPython
5077908
from command.public import SourceCommand from remote_execution.public import RemoteHostExecutor class DeviceModifyingCommand(SourceCommand): """ a command supplying utility methods for command which iterate over the devices of the source and target """ def _execute_on_every_device(self, executable_fo...
StarcoderdataPython
11222916
import json import logging import copy from lib.rdcl_graph import RdclGraph from lib.nemo.nemo_external_parser import Nemo_Intent, Nemo_Nodemodel logging.basicConfig(level=logging.DEBUG) log = logging.getLogger('NemoRdclGraph') class NemoRdclGraph(RdclGraph): """Operates on the graph representation used for the G...
StarcoderdataPython
8119016
#!/usr/bin/env python3 # # Copyright 2018 <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 ag...
StarcoderdataPython
8091825
<filename>cogs/commands/admin.py import discord from discord.ext import commands class Admin(commands.Cog): def __init__(self, bot): self.bot = bot async def cog_check(self, ctx): guild = self.bot.get_guild(700880842309894175) if ctx.author in guild.members: user = guild.g...
StarcoderdataPython
9779347
from functools import reduce import numpy as np def parse_data(): with open('2019/03/input.txt') as f: data = f.read() return [wire.split(",") for wire in data.splitlines()] def wire_circuit(data): directions = { "U": np.array([0, 1]), "D": np.array([0, -1]), "L": np.arr...
StarcoderdataPython
8124981
<gh_stars>1000+ #!/usr/bin/env python import asyncio import logging import time import aiohttp from hummingbot.connector.exchange.wazirx import wazirx_constants as CONSTANTS from typing import Optional, List, Dict, AsyncIterable, Any from hummingbot.core.data_type.order_book import OrderBook from hummingbot.c...
StarcoderdataPython
5156645
<reponame>LSSTDESC/firecrown import numpy as np from scipy.interpolate import Akima1DInterpolator import sacc import pyccl as ccl from ..cluster_count import ClusterCountStatistic class DummySource(object): pass def test_cluster_count_sacc(tmpdir): sacc_data = sacc.Sacc() params = dict( Omega...
StarcoderdataPython
1806962
<filename>wagtail/admin/tests/test_account_management.py import unittest import pytz from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth import views as auth_views from django.contrib.auth.models import Group, Permission from django.contrib.auth.tokens import Passw...
StarcoderdataPython
11245329
# -*- coding: UTF-8 -*- from django import forms from apps.registro.models import AnexoAutoridad class AnexoAutoridadFormFilters(forms.Form): anexo_id = None def __init__(self, *args, **kwargs): try: self.anexo_id = kwargs.pop('anexo_id') except KeyError: pass ...
StarcoderdataPython
8091572
<reponame>Mirantis/ceph-monitoring<filename>ceph_report/service.py<gh_stars>1-10 import sys import site import time import argparse import subprocess from typing import List, Any, cast import configparser from dataclasses import dataclass from pathlib import Path from typing import Optional, Dict import logging.config ...
StarcoderdataPython
3296665
<filename>tests/unit/sqlite3_to_mysql_test.py import logging import re from random import choice import mysql.connector import pytest from mysql.connector import errorcode from sqlalchemy import create_engine, inspect from sqlalchemy.dialects.sqlite import __all__ as sqlite_column_types from sqlite3_to_mysql import S...
StarcoderdataPython
8118666
import torch from torch import nn class HexaConv2d(nn.Conv2d): def __init__(self, *args, **kargs): super(HexaConv2d, self).__init__(*args, **kargs) self.mask = nn.Parameter(self.get_mask(), requires_grad=False) copy_w = self.weight.clone().detach() self.weight = nn.Parameter(copy...
StarcoderdataPython
396560
# Sequence Reconstruction # Check whether the original sequence org can be uniquely reconstructed from the sequences in seqs. # The orginal sequence is a permutation of the integers from 1 to n, with 1 ≤ n ≤ 104. # Reconstruction means building a shortest common supersequence of the sequences in seqs # (i.e., a shortes...
StarcoderdataPython
6678138
#!/usr/bin/env python # # Creates a csv file relating voltage shifts to amino acid index # from __future__ import print_function import base import numpy as np def tasks(): """ Returns a list of the tasks in this file. """ return [ VoltageShiftIndices(), ] class VoltageShiftIndices(base....
StarcoderdataPython
5060716
<reponame>pecimuth/synthia<filename>backend/web/__init__.py<gh_stars>0 from flask import Flask from flasgger import Swagger from flask_cors import CORS from . import service from . import controller import os def create_app(**kwargs) -> Flask: """Create, configure and return a Flask app. Keyword arguments m...
StarcoderdataPython
334578
<reponame>dozymoe/django-carbondesign<filename>carbondesign/tags/inline_loading.py """ Inline Loading ============== See: https://www.carbondesignsystem.com/components/inline-loading/usage/ The inline loading component provides visual feedback that data is being processed. Overview -------- Inline loading spinners ...
StarcoderdataPython
1885062
from typing import List, Iterable, Dict from keras_preprocessing.text import Tokenizer as KTokenizer from headliner.preprocessing.tokenizer import Tokenizer class KerasTokenizer(Tokenizer): def __init__(self, **kwargs): self._keras_tokenizer = KTokenizer(**kwargs) def encode(self, text: str) -> Li...
StarcoderdataPython
11395411
import abc from typing import List from signalflowgrapher.common.observable import ValueObservable from collections import defaultdict import logging logger = logging.getLogger(__name__) class Command(abc.ABC): """Command for undo and redo operation.""" @abc.abstractmethod def redo(self): pass ...
StarcoderdataPython
3208309
<reponame>ytoyama/yans_chainer_hackathon import math import numpy from chainer import cuda from chainer import function from chainer.utils import type_check def _as_mat(x): if x.ndim == 2: return x return x.reshape(len(x), -1) class Linear(function.Function): """Linear function (a.k.a. fully-...
StarcoderdataPython
1782787
########################################################################## # NSAp - Copyright (C) CEA, 2013 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html # for details. ##########...
StarcoderdataPython
297818
<reponame>AliYoussef96/dinuq from Bio import SeqIO from Bio.Seq import Seq ########################################################### ################### RDA ################### ########################################################### #non-informative dinucleotide positions that w...
StarcoderdataPython
8049614
#!/bin/bash # ------------------------- # Filename: Address_Initialization.py # Revision: 1.0 # Data: long ago # Author: <NAME> # Description: Generate codes that print out variables' name and their addresses, so we can bind dynamic address to its IR form. # Process: # 1. Based on initialization of global varia...
StarcoderdataPython
1946150
# Consensus and Profile # rosalind.info/problems/cons/ import sys class cons: def main(self, dna_file): if not dna_file: raise Exception('ERROR: File is empty.') data = [line.strip() for line in dna_file] matrix = [] for line in data: if str(line[0]...
StarcoderdataPython
365334
""" .. module:: location.text :synopsis: Django location application text module. Django location application text module. """ from django.utils.translation import ugettext_lazy as _ # flake8: noqa # required because of pep8 regression in ignoring disable of E123 address_labels = { "country": _("Country"),...
StarcoderdataPython
6469037
#!/usr/bin/env python2 # -*- coding: UTF-8 -*- # File: html.py # Date: Tue May 20 18:01:39 2014 +0800 # Author: <NAME> <<EMAIL>> from . import api_method, request from ukdbconn import get_mongo # api: /html?pid=2&page=0,1,3,5 # 0 is the html framework @api_method('/html') def html(): """ return a dict of {pagenum...
StarcoderdataPython
1840381
import gws.tools.net import gws.tools.xml2 from . import error _ows_error_strings = '<ServiceException', '<ServerException', '<ows:ExceptionReport' def raw_get(url, **kwargs): # the reason to use lax is that we want an exception text from the server # even if the status != 200 kwargs['lax'] = True ...
StarcoderdataPython
5033906
<gh_stars>0 import argparse import numpy from db.sqlite import get_sqlite_twint parser = argparse.ArgumentParser( description="Fetches data from a number of sources and compiles a training set" ) parser.add_argument( "--sqlite_twint", action="store", type=str, help="Where the bird site is stored" ) args = par...
StarcoderdataPython
3566282
def ignore_msg(msg): return 'fuzzy' in msg.flags or \ msg.obsolete or \ msg.msgstr == msg.msgid or \ not msg.msgstr
StarcoderdataPython
8050222
<filename>model_compiler/src/model_compiler/compilers/saved_model_file_to_openvino_model.py # Copyright 2019 ZTE corporation. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 from tempfile import TemporaryDirectory from . import repository from ..models.sources.saved_model_file import SavedModelFile from .....
StarcoderdataPython
3567972
from substance.monads import * from substance.logs import * from substance import (Command, Engine) from tabulate import tabulate class Recreate(Command): def getShellOptions(self, optparser): optparser.add_option("-t", "--time", dest="time", help="Seconds to wait before sendi...
StarcoderdataPython
3421073
class A: __class__ = 15 a = A() print(a.__class__) # <ref>
StarcoderdataPython
4922552
<filename>com_detection.py ''' This file includes the implementation of community detection module. ''' import networkx as nx import numpy as np import community from basic_test import compute_p, GAW from scipy.stats import norm from utils import to_undirected_graph, augmentation, percentile def get_partition(graph):...
StarcoderdataPython
9716390
<reponame>pulumi/pulumi-f5bigip<filename>sdk/python/pulumi_f5bigip/big_iq_as3.py # 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 fr...
StarcoderdataPython
8012341
<filename>lab01/redis-chat/client.py import redis # create the redis connection r = redis.Redis() # class representative of the system's users class Person(): def __init__(self, username, name): self.username = username self.name = name def __str__(self): return self.username def m...
StarcoderdataPython
9661929
from tornado.web import RequestHandler import json class MainHandler(RequestHandler): """ Render the frontend of the system """ async def get(self): self.render("index.html")
StarcoderdataPython
6578979
from typing import Any, Dict, Optional from broadcaster import Event as BroadcasterEvent class Event(BroadcasterEvent): def __init__( self, channel: str, message: Any, context: Optional[Dict[str, Any]] = None, ): super().__init__(channel, message) if context i...
StarcoderdataPython
1797257
""" WSGI config for pbs project. It exposes the WSGI callable as a module-level variable named ``application`` """ import confy import os from pathlib2 import Path d = Path(__file__).resolve().parents[1] dot_env = os.path.join(str(d), '.env') if os.path.exists(dot_env): confy.read_environment_file(dot_env) os.env...
StarcoderdataPython
1873330
import socket import threading import argparse def serveClient(clientToServeSocket, clientIPAddress, portNumber): clientRequest = clientToServeSocket.recv(4096) print('[!] Received dara from the client (%s:%d) : %s' % clientIPAddress, portNumber, clientRequest) # Reply back to client clientToServeSock...
StarcoderdataPython
11311997
<filename>pitch-predictor/answers/components/collectStats/collect_stats_dataflow.py<gh_stars>1-10 # libraries from __future__ import print_function from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.options.pipeline_options import SetupOptions import apache_beam as beam import argparse im...
StarcoderdataPython
9633207
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import misc.utils as utils from torch.nn.utils.rnn import PackedSequence, pack_padded_sequence, pad_packed_sequence class C...
StarcoderdataPython
9684288
import os import numpy as np import gzip import pickle from pathlib import Path from proseco.core import StarsTable import pytest from proseco import get_aca_catalog from proseco.characteristics import aca_t_ccd_penalty_limit, MonFunc, MonCoord import agasc from Quaternion import Quat import Ska.Sun from proseco.test...
StarcoderdataPython
11241675
<gh_stars>0 from django.test import TestCase from django.core.management import call_command from surveys18.models import Survey, NoSalaryHire, Month class ModelTestCase(TestCase): """ models: Survey, NoSalaryHire reference models : WorkType, Month data: nosalaryhire.yaml, survey.yaml, month.yaml m...
StarcoderdataPython
3471530
<filename>wellcad/com/_page.py<gh_stars>1-10 from ._dispatch_wrapper import DispatchWrapper class Page(DispatchWrapper): """ The Page class manages properties for the document print out. Example ------- >>> import wellcad.com >>> app = wellcad.com.Application() >>> app.new_borehole() <wel...
StarcoderdataPython
369592
<filename>o3/operators/row_count_operator.py # -*- coding: utf-8 -*- """Custom operator for counting rows in a file.""" from airflow.exceptions import AirflowException from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults from ..hooks.hdfs_hook import HDFSHook class RowCountOpe...
StarcoderdataPython
1628714
# -*- coding: utf-8 -*- from typing import List, Tuple import collections.abc as abc import random import string import click FAKE_OPT_NAME_LEN = 30 def get_callback_and_params(func) -> Tuple[abc.Callable, List[click.Option]]: """Returns callback function and its parameters list :param func: decorated f...
StarcoderdataPython
312219
# -*- coding: utf-8 -*- # Created by apple on 2017/1/30. import os import logging from subprocess import Popen class BaseConfig: # server config host = '10.0.1.90' # 服务器访问地址 bing = '0.0.0.0' # 绑定地址 port = 8000 # 绑定端口 debug = False # 是否为测试模式 url = None # static 静态uri static_main =...
StarcoderdataPython
26045
<filename>main.py import pygame import random import math import numpy as np from pygame import mixer x = np.array(([723, 123.4000000000003], [121, 133.40000000000038], [586, 125.40000000000032]), dtype=float ) y = np.array(([99], [86], [89]), dtype=float ) # Scaled Units x = x / np.amax ( x, axis=0 ) y = ...
StarcoderdataPython
6681439
import argparse parser = argparse.ArgumentParser('Multimodal arbitrary style transfer') parser.add_argument('input_path', type=str, help='path to a folder of input images') parser.add_argument('style_path', type=str, help='path to a folder of style images') parser.add_argument('weight_file', type=str, help='path to a t...
StarcoderdataPython
3372499
<gh_stars>10-100 """Set up application's fonts""" import dearpygui.dearpygui as dpg import os import pkg_resources from ..items_ids import * with dpg.font_registry() as font_registry: dpg.add_font(pkg_resources.resource_filename('raviewer', '/fonts/OpenSans-Bold.tt...
StarcoderdataPython
9673948
<gh_stars>100-1000 """ Logic to write ELF files. """ import io import logging from collections import defaultdict from ...arch.arch_info import Endianness from ... import ir from .headers import ElfMachine from .headers import SectionHeaderType, SectionHeaderFlag from .headers import SymbolTableBinding, SymbolTableTyp...
StarcoderdataPython
6531595
from django.urls import path from .views import MyObtainTokenPairView, RegisterView, UserView from rest_framework_simplejwt.views import TokenRefreshView urlpatterns = [ path('login/', MyObtainTokenPairView.as_view(), name='token_obtain_pair'), # path('login/refresh/', TokenRefreshView.as_view(), name='token_...
StarcoderdataPython
4952708
# 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
6625008
<filename>TkiWrapper/logger.py from TkiWrapper.Settings import Settings from Namespace.Namespace import Namespace from datetime import datetime class LogIssuer: def setIssuerData(self): self.__logIssuerData__ = Namespace(scope = 'tki', name = self.__class__.__name__, id = hex(id(self))[2:].upper()) ret...
StarcoderdataPython
9754856
<gh_stars>1-10 """"" Old BRL UTIL code. Temporary Trash codes. """"" import sys sys.path.insert(0,'/usr/local/lib/python2.7/site-packages') import matplotlib.pyplot as plt #from mpl_toolkits.mplot3d import Axes3D import numpy as np from scipy.stats import norm import pdb from matplotlib import cm from operator impor...
StarcoderdataPython
176324
import pytest from datetime import datetime, timedelta from lt_booking_scraper.utils import extract_number, validate_date, generate_headers def test_generate_headers_accept(): header = generate_headers() assert 'Accept' in header def test_generate_headers_user_agent(): header = generate_headers() a...
StarcoderdataPython
9666831
<gh_stars>10-100 import copy from ..fstrips import AddEffect, DelEffect, FunctionalEffect, UniversalEffect from ..evaluators.simple import evaluate from ..fstrips.representation import substitute_expression from ..syntax.transform.substitutions import enumerate_substitutions def is_applicable(model, operator): "...
StarcoderdataPython
89333
<gh_stars>1-10 # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RSpatialpack(RPackage): """Tools to assess the association between two spat...
StarcoderdataPython
4993069
import zipfile from urllib.request import urlretrieve from tqdm import tqdm class DLProgress(tqdm): """ Report download progress to the terminal. :param tqdm: Information fed to the tqdm library to estimate progress. """ last_block = 0 def hook(self, block_num=1, block_size=1, total_size=None): """ Store n...
StarcoderdataPython
3420209
<reponame>cbonilla20/great_expectations """ Helper utilities for creating and testing benchmarks using NYC Taxi data (yellow_trip_data_sample_2019-01.csv) found in the tests/test_sets/taxi_yellow_trip_data_samples directory, and used extensively in unittest and integration tests for Great Expectations. """ impo...
StarcoderdataPython
11241479
<reponame>rainprob/GibsonEnv #from realenv.client.client_actions import client_actions as actions #from realenv.client.vnc_client import VNCClient as VNCClient from gym.envs.registration import registry, register, make, spec #===================== Full Environments =====================# ## Eventually we will packag...
StarcoderdataPython
1772927
import numpy as np import random as rd import torch from log import Logger import torch.nn as nn from c4Grid import c4Grid IN_LEN=43 OUT_LEN=7 NUM_IMG=1 DEVICE=torch.device("cpu") if torch.cuda.is_available() else torch.device("cpu") DTYPE=torch.float LR=1e-3 NUM_ITERATIONS=401 INF = 1000000 RED = 2 YELLOW = 1 DRAW ...
StarcoderdataPython
11251772
from typing import List # from dataclasses import dataclass, field # @dataclass # class Identifier: # label: str # allowed_values: List[str] # @dataclass # class Product: # id: str # name: str=None # description: str=None # image: str=None # unit_of_measure: str=None # unit_of_meas...
StarcoderdataPython
5153333
# Import Standard Libraries import logging import scipy as np # Import Local Libraries from Utilities import * #=========================================================================== # EC2 Equations - Material properties #=========================================================================== def elastic...
StarcoderdataPython
9636819
<reponame>ariadne-pereira/cev-python from datetime import date anoNasc = int(input('Digite o ano de nascimento do atleta: ')) idade = date.today().year - anoNasc print('O atleta tem {} anos e sua categoria é: '.format(idade)) if idade <= 9: print('Mirim') elif idade <= 14: print('Infantil') elif idade <= 19: ...
StarcoderdataPython
4975759
from tester import * from PIL import Image from PIL import ImagePalette ImagePalette = ImagePalette.ImagePalette def test_sanity(): assert_no_exception(lambda: ImagePalette("RGB", list(range(256))*3)) assert_exception(ValueError, lambda: ImagePalette("RGB", list(range(256))*2)) def test_getcolor(): pa...
StarcoderdataPython
5136175
from django.apps import AppConfig class BotReminderConfig(AppConfig): name = "bot.remind" label = "bot_reminder"
StarcoderdataPython
6491032
<filename>smdebug/rules/rule_invoker.py # First Party from smdebug.core.logger import get_logger from smdebug.exceptions import ( NoMoreProfilerData, RuleEvaluationConditionMet, StepUnavailable, TensorUnavailable, TensorUnavailableForStep, ) logger = get_logger() def invoke_rule(rule_obj, start_s...
StarcoderdataPython
5134458
from .photos import photos from .sets import sets __all__ = ['photos', 'sets']
StarcoderdataPython
1915290
# Copyright 2020-2021 Axis Communications AB. # # For a full list of individual contributors, please see the commit history. # # 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...
StarcoderdataPython
3464802
from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from posts.models import Post class TestPostModel(TestCase): def setUp(self): self.user = get_user_model().objects.create_user( username="testuser", email="<EMAIL>", ...
StarcoderdataPython
5062392
from datetime import datetime class Cooldown: users_cld = {} @classmethod def check_user(cls, cmd: str, author_id: int, cooldown: int) -> tuple: now = datetime.now() user_cld = cls.users_cld.get(author_id) if user_cld is None: cls.users_cld[author_id] = {} ...
StarcoderdataPython
9712115
from datetime import datetime from typing import Any, Dict from bluepy.btle import DefaultDelegate, Peripheral from miblepy import ATTRS from miblepy.deviceplugin import MibleDevicePlugin class LYWSD03MMC(MibleDevicePlugin, DefaultDelegate): plugin_id = "lywsd03mmc" plugin_name = "LYWSD03MMC" plugin_des...
StarcoderdataPython
1631724
# Еще одна задача без подвоха :) # # Вам необходимо написать программу, которая считает вещественные числа A и B и выведет результат деления A на B. # # Напомним, что вещественное деление делается с помощью операции / (в отличие от деления нацело, которое делается # с помощью операции //). a = float(input()) b = float...
StarcoderdataPython
3350181
#!/usr/bin/python # # File: DockSim.py # Author: <NAME> # Email: <EMAIL> # Date: Dec 20, 2015 #---------------------------------------------------------------------------- from __future__ import print_function, division from collections import namedtuple from math import sqrt, trunc StateVec = namedtuple('State...
StarcoderdataPython
220110
<reponame>BluecellChen/Python-Challenge<filename>pyPoll/main.py #!/usr/bin/env python # coding: utf-8 # In[4]: # Import Modules / Dependencies import os import csv # Create file path csv_path = os.path.join("..", "PyPoll", "Resources", "election_data.csv") csv_path #Voter ID,County,Candidate # In[13]: # Read in...
StarcoderdataPython
1993421
import datetime from datetime import date import pytest from regolith.dates import (month_to_str_int, day_to_str_int, find_gaps_overlaps, get_dates, last_day, is_current, get_due_date, ...
StarcoderdataPython
146
<reponame>yavook/kiwi-scp from typing import Tuple import click from .cmd import KiwiCommandType, KiwiCommand from .decorators import kiwi_command from ..executable import COMPOSE_EXE from ..instance import Instance from ..project import Project @click.argument( "compose_args", metavar="[ARG]...", nargs...
StarcoderdataPython
1762726
<gh_stars>1-10 # -*- coding: utf-8 -*- # Zinc dumping and parsing module # (C) 2016 VRT Systems # # vim: set ts=4 sts=4 et tw=78 sw=4 si: import base64 import binascii import datetime import random import string import sys import traceback import six import hszinc from hszinc import VER_3_0, Grid, MODE_ZINC, MODE_JSO...
StarcoderdataPython
213793
# -*- coding: utf-8 -*- # This file is part of pygal # # A python svg graph plotting library # Copyright © 2012-2015 Kozea # # This library is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version...
StarcoderdataPython
4843233
<gh_stars>0 import wikipedia import folders from pydub import AudioSegment from pydub import effects import sys sys.path.append('/path/to/ffmpeg') def write_file(file,data): # f = open(file, "w") # f.write(data) # f.close() with open(file, 'w') as f: f.write(data) def getwiki(path_wiki,title): wikipedia.set_l...
StarcoderdataPython
75717
""" Python Interchangeable Virtual Instrument Library Copyright (c) 2012-2016 <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 ...
StarcoderdataPython
3221205
# # @lc app=leetcode id=118 lang=python # # [118] Pascal's Triangle # # https://leetcode.com/problems/pascals-triangle/description/ # # algorithms # Easy (44.14%) # Total Accepted: 225.9K # Total Submissions: 509K # Testcase Example: '5' # # Given a non-negative integer numRows, generate the first numRows of Pascal...
StarcoderdataPython
5196863
# IMPORTS ############################################ from rest_framework.generics import ( CreateAPIView, ListAPIView, RetrieveAPIView, RetrieveDestroyAPIView, ) from vsitapp.models import Post from .serializers import ( PeopleSerializer, PeopleDetailSerializer, PeopleCreate...
StarcoderdataPython