id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
381905
<gh_stars>1-10 from EvaMap.Dimensions.Dimension import Dimension from EvaMap.Metrics.sameAs import sameAs from EvaMap.Metrics.externalURIs import externalURIs from EvaMap.Metrics.externalLink import externalLink from EvaMap.Metrics.localLinks import localLinks class Connectability(Dimension) : def __init__(self,...
StarcoderdataPython
1986965
# 1. import dependancies from flask import Flask from flask import jsonify import datetime as dt import numpy as np import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func, inspect, distinct #-------------------------------------...
StarcoderdataPython
8165415
<reponame>dirodriguezm/APF from apf.core.step import {{step_class}} as Step import logging class {{step_name}}(Step): """{{step_name}} Description Parameters ---------- config : dict Configuration for the step and its components **step_args : type Other args passed to step (DB con...
StarcoderdataPython
8187417
<gh_stars>1-10 from Logic.Data.DataManager import Writer from Logic.Data.DataManager import Reader class StreamEntry: def encode(self: Writer, info): self.writeLogicLong(info['StreamID'][0], info['StreamID'][1]) # StreamEntryID self.writeLogicLong(info['PlayerID'][0], info['PlayerID'][1]) # Target...
StarcoderdataPython
5056103
# %% fold_number = 3 tta = 20 batch_size = { "tpu": 8, # x8 "gpu": 16, # 10 without AMP "cpu": 4, } arch = "efficientnet-b5" resolution = 456 # orignal res for B5 input_res = 512 lr = 1e-5 # * batch_size weight_decay = 2e-5 pos_weight = 3.2 label_smoothing = 0.03 max_epochs = 4 # %% #!pip instal...
StarcoderdataPython
291541
<reponame>luiszeni/sigrapi18_gender_detection import cv2 import numpy as np from core.BoundBox import BoundBox from math import sqrt def convert_detections_to_my_imp(out_boxes, out_scores, out_classes, class_names,shape): detections = [] for i, c in enumerate(out_classes): predicted_class = class_names...
StarcoderdataPython
3527581
<reponame>amplifylitco/asiaq """ This module contains logic that processes a VPC's peering connections """ import logging from itertools import product from sets import ImmutableSet from boto.exception import EC2ResponseError import boto3 # FIXME: Disabling complaint about relative-import. This seems to be the only...
StarcoderdataPython
5189778
<gh_stars>1-10 """Views for doc serving.""" import logging import mimetypes import os from functools import wraps from urllib.parse import urlparse from django.conf import settings from django.core.files.storage import get_storage_class from django.http import Http404, HttpResponse, HttpResponseRedirect from django.s...
StarcoderdataPython
1915709
#!/usr/bin/python3 import os, sys import logging, argparse import re import networkx as nx import matplotlib.pyplot as plt import multiprocessing from multiprocessing.managers import BaseManager from queue import LifoQueue from tqdm import tqdm from nltk.tokenize import word_tokenize from datasketch import MinHash ...
StarcoderdataPython
1752719
<filename>benchmark/rclpy/service/client-stress-test.py<gh_stars>100-1000 #!/usr/bin/env python3 # Copyright (c) 2018 Intel Corporation. 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 ...
StarcoderdataPython
5132064
#!/usr/bin/python # # Copyright (c) SAS Institute 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...
StarcoderdataPython
8199492
def say_hi(): print('我是mymodule模块的say_hi函数') __version__= '0.2'
StarcoderdataPython
1649321
<filename>tests/flake8_integration/test_formatter.py<gh_stars>0 # -*- coding: utf-8 -*- import os from typing import List import pytest from flake8_nb.flake8_integration.formatter import IpynbFormatter from flake8_nb.parsers.notebook_parsers import NotebookParser TEST_NOTEBOOK_PATH = os.path.join( "tests", "dat...
StarcoderdataPython
9649920
<reponame>zmxdream/Paddle<filename>python/paddle/fluid/tests/unittests/npu/test_bce_loss_npu.py # Copyright (c) 2021 PaddlePaddle Authors. 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 o...
StarcoderdataPython
1737857
<gh_stars>0 # Autogenerated file. ANY CHANGES WILL BE OVERWRITTEN from to_python.core.types import FunctionType, \ FunctionArgument, \ FunctionArgumentValues, \ FunctionReturnTypes, \ FunctionSignature, \ FunctionDoc, \ FunctionData, \ CompoundFunctionData DUMP_PARTIAL = [ CompoundFunct...
StarcoderdataPython
257856
<filename>scripts/tf_cnn_benchmarks/test_util.py<gh_stars>1-10 # Copyright 2017 The TensorFlow Authors. 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...
StarcoderdataPython
3393935
# Hack 1: InfoDB lists. Build your own/personalized InfoDb with a list length > 3, create list within a list as illustrated with Owns_Cars InfoDb = [] # List with dictionary records placed in a list InfoDb.append({ "FirstName": "Ben", "LastName": "Holland", "Residence": "San Diego", "Owns_Shoes":["...
StarcoderdataPython
366653
from src.interface import Coord from src.sons import Sons from src.jeu import Jeu def listeJoueursTri(listeJoueurs): """Retourne la liste des joueurs du plus avancé en km au moins avancé.""" listeTri = [] for joueur in listeJoueurs[::-1]: i = 0 while len(listeTri) > i and listeTri[i].km >=...
StarcoderdataPython
8138918
def load_file_lines (file): """ Loads a file as a list of lines. Args: file (str): The path of the file. Returns: list of str: A list of lines in the file. """ data = [] with open(file, mode='r') as target: for line in target: data.append(line.rstrip('\n')) ...
StarcoderdataPython
246735
__author__ = "<NAME>, <NAME>" __copyright__ = None __credits__ = ["<NAME>", "Rosettacommons"] __license__ = "MIT" __version__ = "0.1.0" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Prototype" # Python standard library import argparse, binascii, bz2, collections, json, os, sys from typing import * # TO...
StarcoderdataPython
5127235
<reponame>abhishekagarwalnpl/QHAL-copy from typing import Dict, Tuple import numpy as np from . import command_unpacker, string_to_opcode from ..quantum_simulators import IQuantumSimulator class HALMetadata: """Class for storing HAL metadata items in pre-defined form. """ def __init__( self, ...
StarcoderdataPython
4801249
<filename>apps/netsuite/helpers.py from datetime import datetime, timezone import logging from django.utils.module_loading import import_string from rest_framework.exceptions import AuthenticationFailed from apps.workspaces.models import Configuration, Workspace, NetSuiteCredentials from .tasks import schedule_vend...
StarcoderdataPython
56327
from subprocess import Popen, PIPE import sys import os def osascript(scpt): p = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate(scpt.encode('utf-8')) return stdout, stderr def openTab(): script = f""" tell application "System Events" ...
StarcoderdataPython
3245630
import json from adapters.base_adapter import Adapter from devices.switch.on_off_switch import OnOffSwitch class TS0012(Adapter): def __init__(self): super().__init__() self.devices.append(OnOffSwitch('left', 'state_left')) self.devices.append(OnOffSwitch('right', 'state_right')) def...
StarcoderdataPython
3280755
from flask import Flask, jsonify, render_template, request app = Flask(__name__) # ---------------------------------------------------------------------------------------------------------------------- @app.route('/') def index(): return render_template('base.html') # --------------------------------------------...
StarcoderdataPython
5085656
import asyncio from asgiref import sync from . import pool def gentask(corofunc): def wrapper(*args, **kwargs): coro = corofunc(*args, **kwargs) return asyncio.create_task(coro) return wrapper def to_async(callback, as_task=True): corofunc = sync.sync_to_async(callback) if as_task ...
StarcoderdataPython
9793468
<filename>commercialoperator/migrations/0033_auto_20200402_1732.py # -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2020-04-02 09:32 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('commercialoperator', '003...
StarcoderdataPython
185045
import unittest import sympy from means.approximation.mea.eq_central_moments import eq_central_moments from means.core import Moment from means.util.sympyhelpers import to_sympy_matrix, assert_sympy_expressions_equal class CentralMomentsTestCase(unittest.TestCase): def test_centralmoments_using_p53model(self): ...
StarcoderdataPython
1623175
""" Lawful, the simple test framework. """ import traceback import textwrap import sys import argparse def report(message=''): """Reports a message.""" print(message) def report_exc(message, exc): """Reports an unexpected Error.""" report(message) report(textwrap.indent(exc, ' > ')) def chec...
StarcoderdataPython
3581547
<reponame>garthur/cds-util import argparse import xarray as xr import pandas as pd NCEP_REMOTE_RESOURCES = { 'temperature':'https://psl.noaa.gov/thredds/dodsC/Datasets/ncep.reanalysis/surface/air.sig995.{}.nc' } def slice_gridded_data( dates=None, area=[90, -180, -90, 180], round_area_to_g...
StarcoderdataPython
3310259
#E<NAME> student = dict(firstname = "Joe", lastname = "Bloggs") print(student)
StarcoderdataPython
1913083
#-*- coding:utf-8 -*- from typing import Iterable from winsound import Beep from .musicLaw import AbsoluteFreqMap, RelativeFreqMap import time class InvalidNotationError(Exception): def __init__(self, *args: object) -> None: super().__init__(*args) class FreqOutRangeError(Exception): def __init__(se...
StarcoderdataPython
9647754
<gh_stars>1-10 import unittest import unittest.mock as mock from unittest.mock import patch import os import sys sys.path.append(os.path.abspath('../../')) from app import addNewUserDB import models KEY_INPUT = "input" KEY_EXPECTED = "expected" USER_W = "UserWrong" INITIAL_USERNAME = 'Oscar' class AddUserTestCase(...
StarcoderdataPython
6406939
<gh_stars>1-10 # # Copyright (C) 2012-2020 Euclid Science Ground Segment # # 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 3.0 of the License, or (at your opt...
StarcoderdataPython
12833286
<filename>2021/19/scan.py #!/usr/bin/env python import numpy as np from io import StringIO from itertools import permutations def perms(arr): for columns in permutations(range(3)): for x in (1, -1): for y in (1, -1): for z in (1, -1): a = arr[:, columns] * ...
StarcoderdataPython
11289867
question_style = "bold blue" answer_style = "italic" answer_padding_style = (1, 0, 1, 4) special_answer_padding_style = (0, 0, 0, 4) warning_style = "bold red" answer_link_style = "white" answer_link_padding_style = (0, 0, 0, 4)
StarcoderdataPython
1918143
import os import biothings, config biothings.config_for_app(config) from config import DATA_ARCHIVE_ROOT import biothings.hub.dataload.dumper import datetime class FigshareDumper(biothings.hub.dataload.dumper.DummyDumper): # type: resource SRC_NAME = "covid_figshare" # override in subclass accordingly ...
StarcoderdataPython
11292911
<reponame>sufengniu/kaggle_ai2 from nltk.stem.porter import * import itertools import os import string exclude = set(string.punctuation) stemmer = PorterStemmer() def load_d_word_count(path = 'data/ck-12-word-count.txt'): d = {} for line in open(path): lst = line.strip('\n').split('\t') d[lst[0...
StarcoderdataPython
147136
<reponame>simple2source/roadkarma<filename>sorting/shell_sort.py # shell sort # 时间复杂度: 最优时间复杂度O(n^1.3) # 最坏时间复杂度O(n^2) # 平均时间复杂度O(nlogn) ~ O(n^2) # 稳定性:不稳定 # 不需要额外空间 O(1) def shell_sort(alist): length = len(alist) gap = length // 2 while gap > 0: fo...
StarcoderdataPython
1876702
<filename>src/unittest_parallel/main.py # Licensed under the MIT License # https://github.com/craigahobbs/unittest-parallel/blob/main/LICENSE """ unittest-parallel command-line script main module """ import argparse from contextlib import contextmanager from io import StringIO import multiprocessing import os import ...
StarcoderdataPython
3409064
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** 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 _utilities from...
StarcoderdataPython
12836737
from collections import namedtuple import requests, pickle from abc import ABCMeta, abstractmethod from bs4 import BeautifulSoup from utilities import * from random import randint from threading import Thread # Tuple object Quote = namedtuple('Quote', ['text', 'author']) class QuoteException(Exception): def __...
StarcoderdataPython
4873703
''' Output Format: Output the integer number indicating the total number of occurrences of the substring in the original string. Sample Input: ABCDCDC CDC Sample Output: 2 ''' CODE: def count_substring(string, sub_string): count = 0 for i in range(len(string)-len(sub_string)+1): if (stri...
StarcoderdataPython
6639906
<filename>zodiwiki/__init__.py from zodiwiki.app import app import zodiwiki.routes from zodiwiki.__data__ import __version__, __author__ try: from zodiwiki.secrets import __secret_key__ except ImportError: pass else: app.secret_key = __secret_key__ del __secret_key__
StarcoderdataPython
5051889
<filename>Python_Tello(DJI_UAV)/pratice/01_Takeoff.py from djitellopy import tello from time import sleep # 官方的demo 写复杂了,用了线程 和 命令行响应 还有Python 版本变换 # 这个第三方教程比较简单 但是 有点 问题 就是执行的时候 用 Python3, python2 会不到大疆的库 me = tello.Tello() me.connect() print(me.get_battery()) me.takeoff() me.send_rc_control(0,50,0,0) sleep(...
StarcoderdataPython
1710268
<gh_stars>0 #!/usr/bin/python3 """ returns an object (Python data structure) represented by a JSON string """ import json def from_json_string(my_str): """ returns an object (Python data structure) represented by a JSON string: """ return json.loads(my_str)
StarcoderdataPython
6571986
import os import sys import time from joblib import Parallel, delayed import argparse def render(dst, item_id): f_out = dst f_item = item_id os.system( 'blender --background --python render_custom.py -- --output_folder %s --item %s' % (f_out, f_item) ) def main(): dst = 'D:/Data/ShapeNetRendering_high\\0300...
StarcoderdataPython
65251
<reponame>jacobcheatley/trpg from .base_function import Function # OTHER/NORMAL STATS # CURRENT VALUE SETTERS class IncStatFunction(Function): def __init__(self, args): self.name = args[0] self.value = args[1] def _do_function(self, campaign): campaign.player.stats.other[self.name].cu...
StarcoderdataPython
1990180
n = int(input()) print(n % 3)
StarcoderdataPython
11215528
<gh_stars>10-100 from sciwing.tokenizers.word_tokenizer import WordTokenizer import pytest class TestWordTokenizer: def test_sample_word_tokenization(self): sample_sentence = "I like big apple." tokenizer = WordTokenizer() tokens = tokenizer.tokenize(sample_sentence) assert tokens...
StarcoderdataPython
8184135
__all__ = ( "TrackmaniaException", "TMIOException", "InvalidPlayerException", "NoUserAgentSetError", "InvalidUsernameError", "InvalidIDError", "InvalidTrophyNumber", "InvalidTOTDDate", ) # pylint: disable=unnecessary-pass class TrackmaniaException(Exception): """BASE exception clas...
StarcoderdataPython
6599127
<filename>write.py #!/usr/bin/python #-*- encoding:utf-8 -*- import os import time import random chars="<KEY>" length=input("Lines?\n:") firstline=raw_input("First word?\n:") times=input("Number of poems?\n:") os.system("open /Applications/TextEdit.app/") time.sleep(1) os.system("""osascript -e 'tell application "Syste...
StarcoderdataPython
8012410
import tensorflow as tf import numpy as np #Convolution implementation def conv(batch_input, out_channels, stride, filterSize=4, initScale = 0.02, useXavier=False, paddingSize = 1, useBias=False): with tf.variable_scope("conv"): in_height, in_width, in_channels = [batch_input.get_shape()[1], batch_input.ge...
StarcoderdataPython
12804989
from setuptools import setup from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='pyarc', packages=['pyarc', "pyarc.data_structures", "pyarc.algorithms", "pyarc.qcba", "pya...
StarcoderdataPython
3210623
<gh_stars>0 # -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-02-08 07:43 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('polls', '0001_initial'), ] operations = [ migrations.AlterModelOptions( ...
StarcoderdataPython
6521555
<filename>test/unit/test_version.py import unittest from unittest.mock import patch, MagicMock import dbt.main import dbt.version import sys class VersionTest(unittest.TestCase): @patch("dbt.version.__version__", "0.10.0") @patch('dbt.version.requests.get') def test_versions_equal(self, mock_get): ...
StarcoderdataPython
384149
<filename>src/COCCharGen/Generator.py class Generator(): """Virtual class for Generators.""" def generate_char(self, char): self.generate_basic_info(char) self.generate_characteristics(char) self.generate_status(char) self.generate_combact_stat(char) self.generate_skills(...
StarcoderdataPython
3491212
# simple script for removing exif data in training and validation images # issues that can be caused are: https://github.com/codelucas/newspaper/issues/542 import glob import piexif from multiprocessing import Pool from multiprocessing import cpu_count dirs = ['../external_data/ImageNet/ILSVRC2012_img_train/**/*.JPE...
StarcoderdataPython
9707544
# -*- coding: utf-8 -*- from zope.interface import Interface, implements from twisted.internet import protocol from protocol.AgentControlProtocol import AgentControlProtocol class IBasicAgentFactory(Interface): def doSomething(stuff): """Return a deferred returning a string""" def buildProtocol(ad...
StarcoderdataPython
11216822
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2014 <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 re...
StarcoderdataPython
3510531
<reponame>robot2051/dto-digitalmarketplace-supplier-frontend import os import jinja2 from dmutils.status import enabled_since, get_version_label class Config(object): VERSION = get_version_label( os.path.abspath(os.path.dirname(__file__)) ) SESSION_COOKIE_NAME = 'dm_session' SESSION_COOKIE_PAT...
StarcoderdataPython
6501650
<reponame>mminamina/311-data import pandas as pd from .data_access import load_batch, load_meta def get_batch_nums(table, startDate, endDate): batches = load_meta(table)['batches'] return [batch_num for batch_num, batch in enumerate(batches) if ( startDate <= pd.to_datetime(batch['endDate']) and ...
StarcoderdataPython
4971489
#/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (C) 2020 The F4PGA Authors. # # Use of this source code is governed by a ISC-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/ISC # # SPDX-License-Identifier: ISC import os import unittest import pprint import tem...
StarcoderdataPython
389380
<filename>product/migrations/0015_auto_20170126_0132.py # -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2017-01-26 01:32 from __future__ import unicode_literals import ckeditor_uploader.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('produ...
StarcoderdataPython
3554456
# ==============================================================================================================================================================================================================================================================================================================================...
StarcoderdataPython
3317221
import io from typing import Any, List import numpy as np import numpy.typing as npt AR_i8: npt.NDArray[np.int64] REC_AR_V: np.recarray[Any, np.dtype[np.record]] AR_LIST: List[npt.NDArray[np.int64]] format_parser: np.format_parser record: np.record file_obj: io.BufferedIOBase reveal_type(np.format_parser( # E: num...
StarcoderdataPython
1627678
from django.contrib.syndication.views import Feed from wagtail.wagtailcore.url_routing import RouteResult from datetime import datetime import pytz eastern = pytz.timezone('US/Eastern') class FilterableFeed(Feed): item_guid_is_permalink = False def __init__(self, page, context): self.page = page ...
StarcoderdataPython
3282547
<reponame>Wyss/customarrayformatter # file openpyxl/reader/workbook.py # Copyright (c) 2010-2011 openpyxl # # 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 wit...
StarcoderdataPython
5150509
<reponame>MaxRink/pretix<filename>src/pretix/base/payment.py<gh_stars>0 import logging from collections import OrderedDict from decimal import ROUND_HALF_UP, Decimal from typing import Any, Dict, Union import pytz from django import forms from django.conf import settings from django.contrib import messages from django...
StarcoderdataPython
11386206
from typing import List, Dict # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def listnode_to_array(li: ListNode) -> List[int]: array = [] while li is not None: array.append(li.val) li = li.next ...
StarcoderdataPython
197290
<gh_stars>0 # -*- coding: utf-8 -*- """ Operations on genomic intervals stored in GTF file note: - all the exons of a gene should be on the same strand. Genes with exons trans- spliced from the other strand, like mod(mdg4) in D. melanogaster, should be excluded (before or after). - stop codon is not part of the CD...
StarcoderdataPython
3354795
<filename>movieapp_backend/movie_app/models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone # Create your models here. class MoviePost(models.Model): post_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) image_u...
StarcoderdataPython
6438525
<filename>db/dev/weighted_strings.py import bisect import csv import functools import glob import itertools import random ################################################################################ class WeightedStrings: def __init__(self, data): if not isinstance(data, dict): ...
StarcoderdataPython
3297189
import unittest from models import * class TestUser(unittest.TestCase): def setUp(self): self.user = User("Dfdf", "Dfdf", "dfdfdf", "dfdf") if __name__ == '__main__': unittest.main() class TestBlog(unittest.TestCase): def setUp(self): self.blog = Blog("vcvcv", "sdsd", "dsd","sdsd", 12...
StarcoderdataPython
4815272
""" Minimal abstract regressor class for ESL exercises.""" import numpy as np from sklearn.base import BaseEstimator, RegressorMixin class EslRegressor(BaseEstimator, RegressorMixin): """ Abstract regressor class for ESL.""" def __init__(self): self._n_fit_points = None self._n_features = N...
StarcoderdataPython
1627381
<filename>repos/system_upgrade/el7toel8/actors/registeryumadjustment/actor.py from leapp.actors import Actor from leapp.models import DNFWorkaround from leapp.tags import FactsPhaseTag, IPUWorkflowTag class RegisterYumAdjustment(Actor): """ Registers a workaround which will adjust the yum directories during t...
StarcoderdataPython
1749806
<reponame>gideontong/CodeQuest<gh_stars>1-10 """ Source: Stack Abuse Binary search follows a divide and conquer methodology. It is faster than linear search but requires that the array be sorted before the algorithm is executed """ def BinarySearch(lys, val): first = 0 last = len(lys)-1 index = -1 w...
StarcoderdataPython
11396436
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # =========================================================================== # Copyright © 2020 <NAME>. All rights reserved. # Created by <NAME> on 2020-03-05. # # This file is distributed under the BSD License. # License text is included with the source distribution. # =...
StarcoderdataPython
182574
<filename>app/scrape/not_a_bot.py from selenium import webdriver import os import time class Not_a_IG_bot: def __init__(self, username, password): self.username = username self.password = password options = webdriver.ChromeOptions() options.add_argument('headless') ...
StarcoderdataPython
9796559
import numpy as np from numpy.testing import assert_array_equal, assert_array_almost_equal, assert_equal from tadataka.so3 import is_rotation_matrix, exp_so3, log_so3, tangent_so3 def test_is_rotation_matrix(): M = np.array([[-1, 0, 0], [0, -1, 0], [0, 0, 1]]) assert(is_ro...
StarcoderdataPython
8129514
class CountFromBy: def __init__(self,v: int=0,i: int=1) -> None: self.val = v self.incr = i def increase(self) -> None: self.val += self.incr def __repr__(self) -> str: return str(self.val)
StarcoderdataPython
11325447
<gh_stars>0 ''' Suite of tests for the Consensus module ''' import unittest import ncov.parser test_lineage = ncov.parser.Lineage(file='data/sample_lineages.csv') class LineageTest(unittest.TestCase): def test_create_lineage_dictionary(self): lineage_dict = test_lineage.create_lineage_dictionary() ...
StarcoderdataPython
3372716
#!/usr/bin/env python # -*- coding: utf-8 -*- import yaml import glob import logging import os import pandas as pd import gspread from oauth2client.service_account import ServiceAccountCredentials __author__ = '<NAME>' class _GoogleAPI(object): """ Google API Client base class """ SERVICE_NAME = N...
StarcoderdataPython
3297277
<filename>app/external/pytaw/setup.py from setuptools import setup setup( name='pytaw', version='0.0.1', packages=['pytaw'], url='https://github.com/6000hulls/pytaw', license='', author='6000hulls', author_email='<EMAIL>', description='PYTAW: Python YouTube API Wrapper' )
StarcoderdataPython
4902840
<reponame>ni/grpc-device<filename>source/codegen/metadata/nirfmxinstr/functions.py functions = { 'BuildCalibrationPlaneString': { 'parameters': [ { 'direction': 'in', 'name': 'calibrationPlaneName', 'type': 'char[]' }, { ...
StarcoderdataPython
1661671
<reponame>vidyadeepa/the-coding-interview def increment(occurences, i): if i in occurences.keys(): occurences[i] += 1 else: occurences[i] = 1 def even_element(l): """ Runtime: O(n) """ occurences = {} [increment(occurences, i) for i in l] for k in occurences: if occurences[k] % 2 == 0: ...
StarcoderdataPython
3479190
import logging from collections import Callable from pathlib import Path import time from pygraphviz import AGraph from src.env import get_env def draw_nf_graph(add_nodes_edges: Callable[[AGraph]]): if not get_env().debug.nf_visualize: return graph = AGraph(directed=True) logging.info("DRAWING...
StarcoderdataPython
6616923
import pyjadx import argparse import threading from multiprocessing import Process from threading import Thread import time def load_apk(apk, i): print(apk, i) jadx = pyjadx.Jadx() jadx.load(args.apk) #time.sleep(10) def test_threads(apk): th = [] for i in range(3): process = Thread(ta...
StarcoderdataPython
9607599
import re def word_count(phrase): pat = re.compile(r"""[a-zA-Z0-9]+'*[a-zA-Z]*""") words = [i.strip("'").lower() for i in pat.findall(phrase)] counter = dict() for i in words: counter[i] = counter.get(i, 0) + 1 return counter
StarcoderdataPython
3576317
class Board: '''A Board object that keeps track of which tiles are being occupied and by which player each tile is being occupied by''' def __init__(self): """Initializes an 8x8 Board with 12 pieces for player1 and 12 for player2 """ #"o" is empty tile #"p1" is tile filled ...
StarcoderdataPython
6502511
<gh_stars>100-1000 import collections import sys from lib.core import Tokenizer from lib.utilities import url_to_json # Query counts the number of distinct authors contributing to a project. QUERY = ''' SELECT c.author_id, COUNT(*) FROM commits c JOIN project_commits pc ON pc.commit_id = c.id WHERE...
StarcoderdataPython
298749
<gh_stars>0 import time # FrogRiverOne (Easy) def solution(X, A): if X > len(A): return -1 places = [0 for v in range(len(A) + 1)] counter = X for index, second in enumerate(A): if places[second] == 0: places[second] = 1 counter -= 1 if counter == 0: ...
StarcoderdataPython
3563644
<filename>src/scrap008.py # https://medium.com/@JuanPabloHerrera/use-python-and-web-scraping-to-go-on-your-dream-vacation-ba965687e4b5 import requests from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionCh...
StarcoderdataPython
12818653
<reponame>artem7902/OSBot-AWS import sys ; sys.path.append('..') import unittest from unittest import TestCase from pbx_gs_python_utils.utils.Dev import Dev from pbx_gs_python_utils.utils.Misc import Misc from osbot_aws.apis.Fargate import Fargate @unittest.skip("Needs test that create and destroy the test data") cla...
StarcoderdataPython
1959771
def main(): n,k = map(int,input().split()) s = list(int(input()) for _ in range(n)) ans = 0 right = 1 length = 1 index = 0 mul = s[0] while index < n: while True: if right < n and mul*s[right] <= k: mul *= s[right] right += 1 ...
StarcoderdataPython
1858909
class BaseLRSchedule(object): def _update_optimizer(self, lr, optimizer=None): if optimizer is not None: for param_group in optimizer.param_groups: param_group['lr'] = lr class Constant(BaseLRSchedule): def __init__(self, base_lr=0.001): self.base_lr = base_lr ...
StarcoderdataPython
9617065
from threading import Thread import os import time def square_numbers(): for i in range(100): i * i time.sleep(0.1) def main(): threads = [] num_threads = 10 # create processes for i in range(num_threads): t = Thread(target=square_numbers) threads.append(t) # ...
StarcoderdataPython
6427062
"""Test which packages give errors when trying to document.""" import importlib import pip import os def builtin_packages(): """Test builtin packages.""" builtin_packages = "" with open('../builtin_list.txt') as f: builtin_packages = f.readlines() list_builtin_errors = list() f...
StarcoderdataPython
11237903
<filename>src/bund/element.py<gh_stars>0 ## ## ## from ctx import Ctx import zmq.green as zmq import gevent from gevent import monkey; monkey.patch_all() from keyring import KeyRing class Element: def __init__(self, name, ctx): self.ctx = ctx self.name = name self.namespace = ctx.namespace...
StarcoderdataPython
9754086
def avg(n): if not n: return none return sum(n)/len(n) l = [1,2,3,4,5] expected = 3 assert expected = avg(l), "Inccorect cal" print()
StarcoderdataPython