id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3308056
import os import logging from sdmdl.sdmdl.config import Config from sdmdl.sdmdl.occurrences import Occurrences from sdmdl.sdmdl.gis import GIS from sdmdl.sdmdl.data_prep.presence_map import PresenceMap from sdmdl.sdmdl.data_prep.raster_stack import RasterStack from sdmdl.sdmdl.data_prep.presence_pseudo_absence import...
StarcoderdataPython
4841079
# -*- coding: utf-8 -*- ''' bootstrap.unittesting ~~~~~~~~~~~~~~~~~~~~~ Unit testing related classes, helpers. :codeauthor: :email:`<NAME> (<EMAIL>)` :copyright: © 2013 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. ''' # Import python...
StarcoderdataPython
4819666
<gh_stars>1-10 import random import datetime import flask import flask_login import werkzeug.security import jk_logging from thaniya_server_archive import AppRuntimeArchiveHttpd from thaniya_server.utils import SVGDiskSpaceGraphGenerator from thaniya_common.utils import APIPassword def init_blueprint(app:fl...
StarcoderdataPython
3278829
<filename>holoai_api/Preset.py from json import loads from os import listdir from os.path import join, abspath, dirname, exists from copy import deepcopy from random import choice from holoai_api.types import Model from typing import Dict, List, Any, Union, Optional, NoReturn class Preset: _TYPE_MAPPING = { ...
StarcoderdataPython
78426
#!/usr/bin/env python from iris_sdk.models.base_resource import BaseData, BaseResourceSimpleList from iris_sdk.models.maps.import_tn_checker_list import TnListMap class TelephoneNumbers(TnListMap, BaseData): @property def items(self): return self.telephone_number.items def __init__(self): ...
StarcoderdataPython
1659388
from flask import render_template_string class TestRenderFormRow: def test_render_form_row(self, app, client, hello_form): @app.route('/form') def test(): form = hello_form() return render_template_string(''' {% from 'bootstrap/form.html' import render_f...
StarcoderdataPython
52801
#!/usr/bin/env python #import standard libraries import obspy.imaging.beachball import datetime import os import csv import pandas as pd import numpy as np import fnmatch from geopy.distance import geodesic from math import * #from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt from matplotlib imp...
StarcoderdataPython
3354035
<filename>employeemanager/staff/serializers.py from rest_framework import serializers from staff.models import Department, Employee # COMMON_FIELDS contains fields which may exist on all serializers. COMMON_FIELDS = ('id', 'created_at', 'updated_at') class DepartmentSerializer(serializers.HyperlinkedModelSerializer...
StarcoderdataPython
79020
# Generated by Django 3.1 on 2020-08-13 02:38 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ("core", "0011_auto_20200214_1939"), ] operations = [ migrations.AlterField( model_name="note", ...
StarcoderdataPython
4811727
<reponame>kosuke1701/AnimeCV import sys import os EFFDET_PATH = os.path.join( os.path.abspath(os.path.dirname(__file__)), "..", "effdet" ) sys.path = [EFFDET_PATH, *sys.path] from backbone import EfficientDetBackbone from efficientdet.utils import BBoxTransform, ClipBoxes from utils.utils import preproce...
StarcoderdataPython
1739698
"""Map plugin for Home Assistant CLI (hass-cli).""" import sys import webbrowser import click import homeassistant_cli.autocompletion as autocompletion from homeassistant_cli.cli import pass_context from homeassistant_cli.config import Configuration import homeassistant_cli.remote as api OSM_URL = "https://www.opens...
StarcoderdataPython
3233382
<reponame>WIPACrepo/prometheus-reconfig import os import json import asyncio import pytest import requests import tornado.web from tornado.httpclient import HTTPRequest import tornado.testing from rest_tools.client import RestClient import prometheus_reconfig CONFIG = { 'AUTH_ISSUER': None, 'AUTH_SECRET': '...
StarcoderdataPython
80725
<reponame>nkukadiya89/learn-python #Handling Exceptions try: age = int(input("Enter your age:")) except ValueError as ex: print(ex) print(type(ex)) print("Please enter valid age!") else: print("else part executed")
StarcoderdataPython
45672
# Importing modules import pygame import numpy as np import random # Initializing the Pygame module pygame.init() def console_screen(): """This function is meant for the user to enter specifications for the game as the player plays. """ print('Note: Enter nicknames to name the players in the game'...
StarcoderdataPython
61605
# read README.md file on my GitHub. It walks you through the instalation of necessary # libraries, helps you solve common errors and provides useful references ;) # https://github.com/scraptechguy/SpeechCheck # import library to report time in debug printing import datetime # import elements from libraries for Mi...
StarcoderdataPython
3261490
<gh_stars>0 import logging def get_logger(): logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) logge...
StarcoderdataPython
3277181
# 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
3388939
<reponame>rnag/wystia import examples from argparse import ArgumentParser from wystia import WistiaApi parser = ArgumentParser(description='Script to list videos in a Wistia project') parser.add_argument( 'project_id', help='The hashed ID for a project on Wistia (ex. abc1234567)' ) parser.add_argument( '...
StarcoderdataPython
171336
from starcluster.clustersetup import ClusterSetup from starcluster.logger import log class SnpEffInstaller(ClusterSetup): def run(self, nodes, master, user, user_shell, volumes): for node in nodes: log.info("Installing SnpEff and SnpSift 4.0 on %s" % (node.alias)) node.ssh.execute('mkdir -p /opt/software/snpe...
StarcoderdataPython
177473
########################################################################### ########################################################################### # SPyH ########################################################################### #########################################################...
StarcoderdataPython
181829
from ray.rllib.offline.estimators.off_policy_estimator import OffPolicyEstimate from ray.rllib.offline.estimators.direct_method import DirectMethod, k_fold_cv from ray.rllib.utils.annotations import DeveloperAPI, override from ray.rllib.utils.typing import SampleBatchType from ray.rllib.policy.sample_batch import Sampl...
StarcoderdataPython
5265
<reponame>ArcherLuo233/election-s-prediction from sqlalchemy import Column, ForeignKey, Integer, String, Text from model.base import Base class SWTZ_TY(Base): __tablename__ = 'swtz_ty' class_name = '商务团组-团员' foreign_key = 'swtz_id' export_docx = False export_handle_file = ['identity'] field ...
StarcoderdataPython
3253203
from generate_text import train_tensorflow, generate_tensorflow import os import tensorflow as tf DIR = os.path.dirname(os.path.abspath(__file__)) # train_tensorflow(mode='length', file='story', # len_min=10, len_max=200, # maxlen=200, num_words=20000, # num_units=12...
StarcoderdataPython
170402
# Class defining an intersection of two line segments # Inherits Event type from .Event import Event class Intersection(Event): def __init__(self, x, y, seg1, seg2): super().__init__(x, y) self.seg1 = seg1 self.seg2 = seg2 def __eq__(self, o): if isinstance(o, type(self)): ...
StarcoderdataPython
42466
from os import getenv from dataclasses import dataclass from collections import ChainMap from dotenv import load_dotenv from bot.structs import CaseInsensitiveDict load_dotenv() MY_NAME = "LPUBeltbot" MY_REDDIT_PW = getenv("BELTBOT_REDDIT_PW") MY_REDDIT_CLIENT_ID = getenv("BELTBOT_REDDIT_CID") MY_REDDIT_SECRET...
StarcoderdataPython
3200804
# USAGE # python classify_standart.py --image images/office.png --model vgg16 # thanks for Dr. adryan at http://www.pyimagesearch.com my best teacher. # import the necessary packages from keras.applications import ResNet50 from keras.applications import VGG16 from keras.applications import VGG19 from keras.applicati...
StarcoderdataPython
100356
<reponame>mv20100/phd_code from PyDAQmx import * import numpy as np import ctypes, time from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph as pg from collections import deque class SyncAIAO(object): compatibility_mode = 0 # Set this to 1 on some PC (Mouss) trigName = "ai/StartTrigger" ...
StarcoderdataPython
3224075
<filename>TALOS/TrainingStats.py<gh_stars>1-10 # ===================================================================================================================== # # Tensor Abstraction Layer Objects 0.0.8-ALPHA # NEURAL NETWORK TRAINING STATISTICS # # Framework design by <NAME> #...
StarcoderdataPython
3274468
<reponame>RoW171/trayPy #!/usr/bin/python # -*- coding: utf-8 -*- __author__ = "Robin 'r0w' Weiland" __date__ = "2020-03-02" __version__ = "0.1.2" """Library for creating system tray applications based on Moses Palmér's 'pystray' library See README for insntructions""" __all__ = ('SubMenu',) from pystray import Men...
StarcoderdataPython
3282341
<gh_stars>1-10 from collections import defaultdict from circus import zmq import json from itertools import chain import os import errno import socket from zmq.eventloop import ioloop, zmqstream from circus.commands import get_commands from circus.client import CircusClient from circus.stats.collector import WatcherS...
StarcoderdataPython
1698007
<filename>Lez10/files/fractal.py import turtle def koch(order, size): if order == 0: turtle.forward(size) else: for angle in [60, -120, 60, 0]: koch(order-1, size/3) turtle.left(angle)
StarcoderdataPython
116827
<filename>models/harosc.py import numpy as np import sympy as sp import math from kaa.model import Model class HarOsc(Model): def __init__(self, init_box=[[-5,-4],[0,1]]): x,y = sp.Symbol('x'), sp.Symbol('y') dx = 0.707107*x + 0.707107*y dy = -0.707107*x + 0.707107*y dyns = [d...
StarcoderdataPython
79
<reponame>constantinius/eoxserver_combined<filename>eoxserver/services/ows/wps/v10/encoders/parameters.py #------------------------------------------------------------------------------- # # WPS 1.0 parameters' XML encoders # # Project: EOxServer <http://eoxserver.org> # Authors: <NAME> <<EMAIL>> # <NAME> <<EM...
StarcoderdataPython
3261309
from dataclasses import dataclass, field from typing import Callable, Dict, List, Optional, Union from django.utils.http import urlencode from rest_framework.request import Request from rest_framework.reverse import reverse @dataclass class ItemPermission: permissions: List[str] = field(default_factory=list) ...
StarcoderdataPython
69598
<reponame>awesome-archive/Dragon # ------------------------------------------------------------ # Copyright (c) 2017-present, SeetaTech, Co.,Ltd. # # Licensed under the BSD 2-Clause License. # You should have received a copy of the BSD 2-Clause License # along with the software. If not, See, # # <https://opensourc...
StarcoderdataPython
28970
<reponame>onaio/airbyte # # Copyright (c) 2022 Airbyte, Inc., all rights reserved. # import json import os from pytest import fixture def load_file(fn): return open(os.path.join("unit_tests", "responses", fn)).read() @fixture def test_config_v1(): return {"site": "airbyte-test", "site_api_key": "site_api_...
StarcoderdataPython
8599
<gh_stars>10-100 { "includes": [ "../common.gypi" ], "targets": [ { "target_name": "libgdal_ogr_mem_frmt", "type": "static_library", "sources": [ "../gdal/ogr/ogrsf_frmts/mem/ogrmemdatasource.cpp", "../gdal/ogr/ogrsf_frmts/mem/ogrmemlayer.cpp", "../gdal/ogr/ogrsf_frmts/mem/ogrmemdriver.cpp" ...
StarcoderdataPython
158198
from sys import stdin stdin = open("input.txt", "r") def parse(line): lr, rr = 0, 127 lc, rc = 0, 7 for ch in line: if ch == 'F': rr = (lr + rr) // 2 elif ch == 'B': lr = (lr + rr) // 2 + 1 elif ch == 'L': rc = (lc + rc) // 2 elif ch == 'R...
StarcoderdataPython
137898
<filename>tests/test_settings.py import os from cms.utils.compat import DJANGO_3_1 INSTALLED_APPS = [ "django.contrib.contenttypes", "django.contrib.auth", "django.contrib.sites", "django.contrib.sessions", "django.contrib.admin", "django.contrib.messages", "easy_thumbnails", "filer", ...
StarcoderdataPython
3296382
import logging import boto3 import daiquiri daiquiri.setup(level=logging.INFO) logger = daiquiri.getLogger(__name__) def _parse_s3_file(original_file): """ Convert `s3://bucketname/path/to/file.txt` to ('bucketname', 'path/to/file.txt') """ bits = original_file.replace('s3://', '').split("/") buc...
StarcoderdataPython
3317896
from .AbcRepository import AbcRepository class AbcQuizSuggestionAnswerRepository(AbcRepository): pass
StarcoderdataPython
93272
<filename>tests/sort_depends.py #!/usr/bin/env python3 import os.path import sys def main(): target = None depends = dict() for line in sys.stdin: # We don't interpret the backslash continuation. line = line.replace("\\", "").strip() colon = line.find(":") if colon != -1...
StarcoderdataPython
1776923
<gh_stars>10-100 ''' Jabber Protocol. ''' from common import pref, netcall from digsby.loadbalance import DigsbyLoadBalanceManager from hashlib import sha256 from jabber.JabberProtocol import JabberProtocol from jabber.threadstream import ThreadStream from logging import getLogger from peak.util.imports import lazyMod...
StarcoderdataPython
3397372
# Generated by Django 2.0.5 on 2018-06-18 07:23 from django.contrib.auth.management import create_permissions from django.db import migrations def migrate_permissions(apps, schema_editor): for app_config in apps.get_app_configs(): app_config.models_module = True create_permissions(app_config, app...
StarcoderdataPython
1770776
# -*- coding: UTF-8 -*- from nltk.tokenize import word_tokenize from nltk.stem import RSLPStemmer from utils import filehelper as fh from config import DISCR_TERMS_FILE stemmer = RSLPStemmer() def load_discriminative_terms_set(): term_set = set() for term in fh.read(DISCR_TERMS_FILE): if (not term): ...
StarcoderdataPython
1730579
<reponame>hejianc/meeting # -*- coding: utf-8 -*- from django.conf.urls import patterns urlpatterns = patterns( 'iwork.views', (r'^$', 'home'), )
StarcoderdataPython
1608992
#!/usr/bin/python3 # -*- coding:utf-8 -*- # __author__ = '__Jack__' from django.test import RequestFactory from test_plus.test import TestCase from wenhu.users.views import UserUpdateView class BaseUserTestCase(TestCase): def setUp(self): self.factory = RequestFactory() self.user = self.make_us...
StarcoderdataPython
3215460
#!/home/dsiervo/sc3-autotuner/env/bin/python # -*- coding: utf-8 -*- """ Created on Jun 24 2021 @author: <NAME>, <EMAIL> """ import os import sys import MySQLdb from picker_tuner import picker_tuner from icecream import ic ic.configureOutput(prefix='debug| ') def main(): """Read parmas, choose in wich modules wi...
StarcoderdataPython
198974
<reponame>ariwells2001/Python-Programming-Blueprints<filename>Chapter06/tests/test_dependencies/test_users.py from mock import Mock, patch import pytest from temp_messenger.dependencies.users import ( CreateUserError, AuthenticationError, UserNotFound, UserStore, UserWrapper, ) class TestUserSto...
StarcoderdataPython
4821618
from output.models.nist_data.list_pkg.byte.schema_instance.nistschema_sv_iv_list_byte_max_length_2_xsd.nistschema_sv_iv_list_byte_max_length_2 import NistschemaSvIvListByteMaxLength2 __all__ = [ "NistschemaSvIvListByteMaxLength2", ]
StarcoderdataPython
3353480
<filename>tests/attributes/test_datetime.py<gh_stars>1-10 import datetime import libfaketime import pytest import pytz import sheraf import tests def test_datetime_timestamp(sheraf_connection): class Model(tests.UUIDAutoModel): date = sheraf.DateTimeAttribute() m = Model.create() assert m.date i...
StarcoderdataPython
61146
<reponame>kids-first/kf-api-study-creator import pytest import requests.exceptions from django.core.exceptions import ValidationError from creator.releases.validators import validate_endpoint def test_validate_endpoint_invalid_url(): with pytest.raises(ValidationError): validate_endpoint("not a url") de...
StarcoderdataPython
4819827
<gh_stars>0 import json import time import requests base_url = 'https://api.kivaws.org/v1/loans/' file = open('leaked_file_list1.txt', 'r', encoding='utf8'); for line in file: temp = line.split(',') for idx, value in enumerate(temp): temp[idx] = value.strip(); for idx, value in enumerate(temp): file_na...
StarcoderdataPython
4818977
from marketlearn.orderbook.zero_intelligence_models import LimitOrderBook __all__ = [ "LimitOrderBook", ]
StarcoderdataPython
1713616
<filename>controllers/pioneerController/pioneerController.py from controller import * import roverHelper import cv2 import numpy import csv params = dict() with open("../params.csv", "r") as f: lines = csv.reader(f) for line in lines: params[line[2]] = line[3] TIME_STEP = int(params["ROVER_TIME_STEP"]) robot = Ro...
StarcoderdataPython
69454
from uuid import uuid4 from record_keeper import BOT @BOT.database.update def update( server: str, pokemon_number: str, pokemon_name: str, user: str, notes: str = "", board: str = "TRADE_BOARD", ) -> str: """Updates the database for trade commands. Args: server (str): the ser...
StarcoderdataPython
1647227
#Implemente um programa que faça a leitura de uma string e a leitura de um carater e #depois apresente o número de ocorrências desse caracter na string inicial. def contSTR(): sring=str(input('Escreva uma frase/palavra:\n')) print('-'*80) let=str(input('Indique uma letra: ')) while let not in 'a...
StarcoderdataPython
3389618
<filename>legistar/config.py class Config (dict): def defaults(self, defs): """ Update from the keys in defs where this dictionary has no corresponding key. """ for key in defs: if key not in self: self[key] = defs[key] return self DEFAULT_CONFIG = Config( date_format='%m/%d/...
StarcoderdataPython
3238197
<filename>checklistindex.py import datetime print(datetime.datetime.now().strftime("%a")) x=datetime.datetime.now() print(datetime.datetime.now().strftime("%a")) print(time.date().now())
StarcoderdataPython
3249812
class Solution: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: # Time complexity O(n) # Since unique numbers are limited [0-100] in the array # we create a lenght of the array 102. count = [0] * 102 for num in nums: count[num+1] += 1 f...
StarcoderdataPython
4802061
<gh_stars>0 # Este projeto está sendo implementado
StarcoderdataPython
1659086
import os import time import shutil from .fileinformation import FileInformation from .folderfunctions import MakeFolder class FileClusterManager: def __init__(self, date, path, maxOnDiskFiles=5, maxOnDiskSizeGB=3): self.Size = 0 # List of FileInformation Classes self.Files = [] s...
StarcoderdataPython
9938
<reponame>dhruvdcoder/allennlp-wandb from setuptools import setup, find_packages install_requires = [ "allennlp>=0.9.0", "wandb==0.8.15", ] setup( name='allennlp_wandb', version='0.0.1', description='Utilities to use allennlp with wandb', packages=find_packages( exclude=["*.tests", "*....
StarcoderdataPython
3282241
<gh_stars>0 ''' Desc: Download icons from web site https://brandspace.xxx.com. Details please see also variable EntryURL defined in this program Requirements: 1.It needs chromedriver as web driver which can be downloaded from site: https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver 2.Module selenium is also requ...
StarcoderdataPython
149419
import os.path import time import typing import numpy # type: ignore from d3m import container, exceptions, utils from d3m.metadata import base as metadata_base, hyperparams from d3m.primitive_interfaces import base, transformer from . import __author__, __version__, null __all__ = ('PrimitiveSumPrimitive',) Inpu...
StarcoderdataPython
3355114
<reponame>ZhukovGreen/aiohttp-json-rpc #!/usr/bin/env python # -*- coding: utf-8 -*- # Author: <NAME> <<EMAIL>> from aiohttp.web import Application from aiohttp_json_rpc import JsonRpc import asyncio @asyncio.coroutine def ping(request): return 'pong' if __name__ == '__main__': loop = asyncio.get_event_loo...
StarcoderdataPython
3368947
# AUTOGENERATED! DO NOT EDIT! File to edit: 01_model_functions.ipynb (unless otherwise specified). __all__ = ['XOR', 'boolxor', 'smoothxor', 'MPX', 'MUX', 'boolmux', 'smoothmux', 'NOT', 'boolnot', 'smoothnot', 'COPY', 'boolcopy', 'smoothcopy', 'AND', 'booland', 'smoothand', 'OR', 'boolor', 'smoothor', 'NOR'...
StarcoderdataPython
3312177
from wtforms.fields import html5 from wtforms.fields import StringField as _StringField from ..widgets import ( DateInput, DateTimeInput, DateTimeLocalInput, EmailInput, NumberInput, RangeInput, SearchInput, TextInput ) class EmailField(_StringField): widget = EmailInput() class...
StarcoderdataPython
3255044
import numpy as np import pandas as pd # non-migrating population = base population - out migration # in migrating population = in migrating rates applied to base population # dead population = death rates applied to non-migrating population # non-migrating survived population = non-migrating population - deaths # n...
StarcoderdataPython
77621
<filename>cle/backends/macho/section.py # -*-coding:utf8 -*- # This file is part of Mach-O Loader for CLE. # Contributed December 2016 by Fraunhofer SIT (https://www.sit.fraunhofer.de/en/). from typing import Optional from .segment import MachOSegment from .. import Section TYPE_MASK = 0x000000ff ATTRIBUTES_MASK = 0x...
StarcoderdataPython
4828319
import sys import os import string import time from stat import * if len(sys.argv) < 5: print "<generated_scene_folder> <output_folder> <start frame> <end frame> <ray-tracing binary>" sys.exit() for i in range(string.atoi(sys.argv[3]), string.atoi(sys.argv[4])): checkfile = sys.argv[2] + "render.%(#)05d....
StarcoderdataPython
128265
<filename>mnist_forward.py import tensorflow as tf INPUT_NODE = 784 OUTPUT_NODE = 10 LAYER_NODE = 500 def get_weight(shape,regularizer): #beijieduande biaozhuncha buhuichaoguo liangge biaozhuncha w = tf.Variable(tf.truncated_normal(shape,stddev=0.1)) if regularizer != None: tf.add_to_collection("...
StarcoderdataPython
1727216
<gh_stars>0 # Adapted from https://github.com/bermanmaxim/LovaszSoftmax import torch import torch.nn.functional as F from torch.autograd import Variable def flatten(scores, labels): """ Flattens predictions in the batch (binary case) """ return scores.view(-1), labels.view(-1) def lovasz_grad(gt_s...
StarcoderdataPython
3326749
<filename>slack/tests/test_io.py import json import time import asyncio import datetime import asks import trio import curio import pytest import aiohttp import requests import asynctest import slack from slack import methods, exceptions from slack.io.trio import SlackAPI as SlackAPITrio from slack.io.curio import Sla...
StarcoderdataPython
104407
#!/usr/bin/env python3 # MIT License # # Copyright (c) 2020 <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, co...
StarcoderdataPython
1710441
<gh_stars>100-1000 from django.urls import reverse from orchestra.tests.helpers import OrchestraAuthenticatedTestCase from orchestra.tests.helpers.fixtures import StaffingResponseFactory from orchestra.tests.helpers.fixtures import WorkerFactory class StaffRequestBase(OrchestraAuthenticatedTestCase): template = ...
StarcoderdataPython
51133
<reponame>Searchlight2/Searchlight2 def out_parsing(out_path_parameter, global_variables): # default inputs out_path = None # gets the sub-parameters sub_params_list = out_path_parameter.split(",") for sub_param in sub_params_list: if sub_param.upper().startswith("path=".upper()): ...
StarcoderdataPython
3261856
""" Given an integer n, return the length of the longest consecutive run of 1s in its binary representation. For example, given 156, you should return 3. """ def longest_consecutive_run(n: int) -> int: max_count = 0 count = 0 while n > 0: if n & 1: count += 1 if count > ma...
StarcoderdataPython
4810032
def fib(n): a = 1 b = 1 for i in range(n-2): a, b = b, a + b return b
StarcoderdataPython
4828886
<filename>setup.py #!/usr/bin/env python from setuptools import setup setup(name='redshell', version='1.0', description='A RedTeam shell', author='<NAME>', author_email='<EMAIL>', url='https://github.com/dominee/redshell', packages=['redshell', 'redshell.builtins'], entry_poi...
StarcoderdataPython
127487
<filename>server/app/models/Course.py #!/usr/bin/env python # coding=utf-8 import datetime from app.database import DB class Course(object): def __init__(self, name, instructor, _id): self._id = _id self.name= name self.instructor = instructor self.students = [] #add attr...
StarcoderdataPython
1693754
# ------------------------------------------------------------------------------ # Copyright (c) 2019 Parallax Inc. - # - # Permission is hereby granted, free of charge, to any person obtaining ...
StarcoderdataPython
1702861
<filename>profiles_api/views.py from rest_framework.views import APIview from rest_framework.response import Response # standard response object and import APIview class class HelloApiView(APIview): """ Test API View""" def get(self, request, format = None): """ Returns a list of APIviews features...
StarcoderdataPython
1632889
<reponame>elix-tech/infrag """ Copyright (c) 2021 Elix, Inc. """ from .ge_operations.crossover import crossover from .ge_operations.fragment_crossover import fragment_crossover from .ge_operations.mutate import mutate from .ge_operations.selfies_crossover import selfies_crossover from .ge_operations.selfies_mutate imp...
StarcoderdataPython
156852
<reponame>WEHI-ResearchComputing/wehi-globus from helper import WehiGlobusApiHelper import drmaa from multiprocessing.pool import Pool from config import * """ This is a template for building a system that will list files in a globus endpoint and submit jobs to the batch system. You need to 1. Edit config.py 2. Login ...
StarcoderdataPython
3280916
<reponame>rwuilbercq/Hive #!/usr/bin/env python # ---- MODULE DOCSTRING __doc__ = """ (C) Hive, <NAME>, 2017 _ /_/_ .'''. =O(_)))) ...' `. \_\ `. .'''X `..' .---. .---..-./`) ,---. ,---. .-''-. | | |_ _|\ .-.')| / | | .'_ _ \ | | ( ' )/ `...
StarcoderdataPython
4822456
# 문자열 내 p와 y의 개수 ```python def solution(s): len_p = 0 len_y = 0 for i in range(len(s)): if s[i] in ['P','p']: len_p += 1 elif s[i] in ['Y','y']: len_y += 1 if len_p == len_y: return True elif len_p != len_y: return False ```
StarcoderdataPython
198058
# Generated by Django 3.1.2 on 2020-12-01 23:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Hydroxychloroquine', '0009_auto_20201201_1805'), ] operations = [ migrations.AddField( model_name='report', name='us...
StarcoderdataPython
3208366
<reponame>rodrigovilar/medieval-bank-python from sqlalchemy import Column, Integer, String, create_engine, DateTime from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy import Column, Integer, String, create_engine, DateTime, ForeignKey from sqlal...
StarcoderdataPython
3319033
<gh_stars>1-10 from transformers import GPT2Tokenizer, GPT2LMHeadModel, AutoTokenizer, AutoModelWithLMHead, BertTokenizer, LongformerTokenizer, LongformerModel import torch, json, random import numpy as np parser = argparse.ArgumentParser(description='') parser.add_argument('--percentage', type=str, default='None', he...
StarcoderdataPython
1632938
<filename>scripts/project.py #!/usr/bin/env python3 """ Author: <NAME> Copyright 2018 ChainSecurity AG 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...
StarcoderdataPython
112492
<gh_stars>100-1000 # # Copyright (C) [2020] Futurewei Technologies, Inc. # # FORCE-RISCV is licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # ...
StarcoderdataPython
70389
<reponame>GTJuniorDesign0100-2020/anti-malarial-MCMC-bayesian-algorithm from collections import OrderedDict from typing import List import datetime import math import os import time from flask import Flask, request from flask_restful import Resource, Api from flask_limiter import Limiter from flask_limiter.util import...
StarcoderdataPython
4824356
import re import os import json import argparse from string import punctuation import torch import yaml import numpy as np import librosa import pyworld as pw import audio as Audio from torch.utils.data import DataLoader from g2p_en import G2p from pypinyin import pinyin, Style from utils.model impo...
StarcoderdataPython
1724166
<reponame>slowy07/natural-instructions-expansion import json from os import listdir from os.path import isfile, join import random # read all the tasks and make sure that they're following the right pattern tasks_path = 'tasks/' expected_keys = [ "Definition", "Positive Examples", "Negative Examples", ...
StarcoderdataPython
3216926
# Copyright (c) <NAME> # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from io import BytesIO import logging import os import re from concurrent.futures.thread import ThreadPoolExecutor from subprocess import PIPE, run from typing import Any...
StarcoderdataPython
3327235
<filename>wagtail_svgmap/tests/test_admin.py import pytest from django.core.urlresolvers import reverse from django.utils.crypto import get_random_string from bs4 import BeautifulSoup from wagtail_svgmap.models import ImageMap from wagtail_svgmap.tests.utils import IDS_IN_EXAMPLE_SVG from wsm_test.models import TestPa...
StarcoderdataPython
180342
<reponame>GianmarcoMidena/LIP-predictor<gh_stars>0 import pandas as pd class StackingClassifier: """A 'Stacking Cross-Validation' classifier. Parameters ---------- base_classifiers : array-like, shape = [n_classifiers] A list of classifiers to use for the first layer of the ensemble. meta...
StarcoderdataPython
110959
# -*- coding: utf-8 -*- """ triangulate =========== Script : triangulate.py Author : <EMAIL> Modified : 2018-08-24 Purpose: triangulate poly* features Useage : References ---------- `<http://pro.arcgis.com/en/pro-app/arcpy/data-access/numpyarraytotable.htm>`_. `<http://pro.arcgis.com/en/pro...
StarcoderdataPython
3320246
<filename>biserici_inlemnite/app/migrations/0055_auto_20210929_0104.py<gh_stars>0 # Generated by Django 3.1.13 on 2021-09-28 22:04 from django.db import migrations import wagtail.core.fields class Migration(migrations.Migration): dependencies = [ ('app', '0054_auto_20210928_1422'), ] operations...
StarcoderdataPython