id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
203312
"""Process ONET job titles into a common format""" import pandas as pd from skills_ml.algorithms.nlp import transforms, lowercase_strip_punc class Onet_Title(object): """An object representing job title data from different ONET files Originally written by <NAME> """ def __init__(self, onet_cache): ...
StarcoderdataPython
11243017
<filename>tests/config/should_ignore_ext.py print('Should not get loaded by figura!') # functions in figura files are supposed to raise an error ("Config construct of unsupported type") def should_not_get_loaded(): pass
StarcoderdataPython
3506075
import unittest from unittest.mock import Mock, patch from nuplan.common.actor_state.scene_object import SceneObject, SceneObjectMetadata class TestSceneObject(unittest.TestCase): """Tests SceneObject class""" @patch("nuplan.common.actor_state.tracked_objects_types.TrackedObjectType") @patch("nuplan.com...
StarcoderdataPython
5100523
import argparse def parse_arguments(*args): parser = argparse.ArgumentParser() ###############added options####################################### parser.add_argument('-lr', '--learning_rate', default=1e-3, type=float, help='Learning rate for the generator') parser.add_argument...
StarcoderdataPython
6515130
def dfs(adjacency_list, current_vertex, visited, result_stack): visited[current_vertex] = True for neighbour_vertex in adjacency_list[current_vertex]: if not visited[neighbour_vertex]: dfs(adjacency_list, neighbour_vertex, visited, result_stack) result_stack.append(current_v...
StarcoderdataPython
4957488
from typing import cast from logging import Logger from logging import getLogger from unittest import TestSuite from unittest import main as unitTestMain from tests.TestBase import TestBase # import the class you want to test here from metamenus.Configuration import Configuration class TestConfiguration(TestBase...
StarcoderdataPython
1625467
<gh_stars>1-10 import ode import numpy as np import matplotlib.pyplot as plt qe = 1.60217662e-19 me = 9.10938356e-31 B0 = 0.1 # RHS of the ODE problem, dy/dx = f(x,y) def fun(t,y): vx = y[3] vy = y[4] vz = y[5] # Charge-to-mass ratio (q/m) qm = -qe/me # E-field [V/m] Ex = 0.0 Ey = 0.0 Ez = ...
StarcoderdataPython
255901
<filename>python/week1/euro.py PRICES = [0.01, 0.02, 0.05, 0.10, 0.20, 0.50, 1, 2] QUESTIONS = [ "Voer het aantal 1 centen in:\n", "Voer het aantal 2 centen in: \n", "Voer het aantal 5 centen in: \n", "Voer het aantal 10 centen in: \n", "Vo...
StarcoderdataPython
3436988
#Ler o preço de um produto e calculá-lo com 5% de desconto preco = float(input("Digite o valor do produto: R$")); desc = (preco/100) * 5; novopreco = preco - desc; prazo= preco + (preco/100*8); #Cálculo do produto à prazo com 8% de acréscimo; print(f"O produto custava R${preco:.2f}, agora com desconto passou a cu...
StarcoderdataPython
1689753
<filename>c7n/resolver.py # Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 import csv import io import json import logging import itertools from urllib.request import Request, urlopen from urllib.parse import parse_qsl, urlparse import zlib from contextlib import closing import jmespath ...
StarcoderdataPython
1636051
<filename>mex11.py #!/usr/bin/env python3.6 # used in Unix/Linux OS import sys def print_uniq_lines(file_list): print('file_list: ', file_list, type(file_list)) all_lines = set() #print('file_list: ', file_list, type(file_list)) for f in file_list: ...
StarcoderdataPython
6488409
<gh_stars>0 """Helper functions to create backbone model.""" # Copyright (C) 2020 Intel Corporation # # 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...
StarcoderdataPython
6705170
import pickle from lasagne.layers import ConcatLayer from lasagne.layers import DenseLayer from lasagne.layers import InputLayer from lasagne.layers import Layer from lasagne.nonlinearities import identity from lasagne.nonlinearities import softmax from lasagne.objectives import categorical_crossentropy from lasagne.u...
StarcoderdataPython
9744816
from enum import Enum from dataclasses import dataclass class TokenType(Enum): NUM = 0 VAR = 1 PLUS = 2 MINUS = 3 MULTIPLY = 4 DIVIDE = 5 POWER = 6 LEFT_PARENTHESES = 7 RIGHT_PARENTHESES = 8 @dataclass class Token: type: TokenType value: any = None def __repr__(self):...
StarcoderdataPython
4846625
<filename>3d/linear_waves_flat_3D/linear_waves_flat_3D_01_GAZ/tank_batch.py simFlagsList[0]['storeQuantities']= ["q:'phi_solid'","q:'velocity_solid'"] #simFlagsList[0]['storeQuantities']= ["q:velocity_solid"] start quit
StarcoderdataPython
3409508
<reponame>Nitinsd96/Air-Pollution-Monitoring-System<gh_stars>0 ##### # # This class is part of the Programming the Internet of Things # project, and is available via the MIT License, which can be # found in the LICENSE file at the top level of this repository. # # Copyright (c) 2020 by <NAME> # import logging impor...
StarcoderdataPython
4895688
<reponame>casutton/bayes-qnet #!/usr/bin/python from scipy.optimize import * from scipy.integrate import * import distributions import misc import mytime import numpy ln = distributions.LogNormal (0, 1) N = 100 tmr = mytime.timeit() allint = [] for i in xrange(N): allint.append (misc.mcint (ln.lpdf, 0, 3)) ...
StarcoderdataPython
3418605
from textwrap import dedent from flake8_plugin_utils import assert_error, assert_not_error from {{cookiecutter.project_slug}}.errors import {{cookiecutter.error_name}}Error from {{cookiecutter.project_slug}}.visitor import {{cookiecutter.plugin_name}}Visitor def test_error(): code = dedent( """ ...
StarcoderdataPython
62722
<gh_stars>100-1000 import numpy as np import pytest import elfi def test_sample(): n_samples = 10 parameter_names = ['a', 'b'] distance_name = 'dist' samples = [ np.random.random(n_samples), np.random.random(n_samples), np.random.random(n_samples) ] outputs = dict(zip(...
StarcoderdataPython
8197897
<gh_stars>0 """Faça um Programa que peça um número correspondente a um determinado ano e em seguida informe se este ano é ou não bissexto""" ano = int(input('Digite um ano parasaber se é bissexto: ')) if ano % 4 == 0 and ano % 100 != 0 or ano % 400 == 0: print('O ano é Bissexto!') else: print('O ano Não é Biss...
StarcoderdataPython
6686
<reponame>natedogg484/react-flask-authentication from flask import Flask from flask_cors import CORS from flask_restful import Api from flask_sqlalchemy import SQLAlchemy from flask_jwt_extended import JWTManager app = Flask(__name__) CORS(app) api = Api(app) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.d...
StarcoderdataPython
1666190
<gh_stars>1-10 import pytest from AcadeMeData.models import University, Degree, Professor, User, Course, MessageBoards @pytest.fixture def generate_university(university_id=5, name='The Technion', location="Haifa", description="Best University in Israel"): university = University(universit...
StarcoderdataPython
6681279
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.pipeline import Pipeline from mne.decoding import CSP from BIpy.data_processing import get_windows, LowpassWrapper import numpy as np class DummyClassifier(): """Dummy classifier for testing purpose""" def __init__(self): ...
StarcoderdataPython
135879
from .profile import profile_getaddrinfo, profile_getaddrinfo_async
StarcoderdataPython
72907
import logging import os import torch from dataset import MonoDataset from torch.utils.data import DataLoader from tqdm import tqdm from transformers import T5ForConditionalGeneration from transformers import T5Tokenizer from utils import calculate_bleu_score from utils import load_config from finetune_t5 import EXPE...
StarcoderdataPython
11321688
<gh_stars>1-10 ### # Copyright 2021 New H3C Technologies Co., Ltd. # # 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 requi...
StarcoderdataPython
9685787
<reponame>alexdlaird/twilio-taskrouter-demo """ Settings common to all deployment methods. """ import os import socket from conf.settings import PROJECT_ID __author__ = '<NAME>' __copyright__ = 'Copyright 2018, <NAME>' __version__ = '0.2.1' # Define the base working directory of the application BASE_DIR = os.path.n...
StarcoderdataPython
372958
# Import Modules import gc import numpy as np import pandas as pd import shutil import tensorflow as tf from utils import * from tqdm import tqdm # Constants patch_size = 1024 generate_stage2 = False # Generate Stage 1 ... OR ... Generate Stage 2 based on Pseudo Labelling # Required Folders -...
StarcoderdataPython
9654597
<reponame>mano8/utils<gh_stars>0 # -*- coding: utf-8 -*- """ UType unittest class. Use pytest package. """ import pytest from ve_utils.utype import UType as Ut class TestUType: """UTime unittest class.""" def test_has_valid_length(self): """Test has_valid_length method""" assert Ut.has_valid_...
StarcoderdataPython
6531453
<filename>bin/check_samplesheet.py #!/usr/bin/env python # This script is based on the example at: https://raw.githubusercontent.com/nf-core/test-datasets/viralrecon/samplesheet/samplesheet_test_illumina_amplicon.csv import os import sys import errno import argparse def parse_args(args=None): Description = "Ref...
StarcoderdataPython
4822569
<reponame>zangobot/secml<filename>src/secml/parallel/__init__.py from .parfor import parfor, parfor2
StarcoderdataPython
78272
<reponame>PhilippGoecke/kube-hunter import json import logging import time from enum import Enum import re import requests import urllib3 import uuid from kube_hunter.conf import get_config from kube_hunter.core.events.event_handler import handler from kube_hunter.core.events.types import Vulnerability, Event, K8sVer...
StarcoderdataPython
1998882
<filename>realtime-feed/app.py<gh_stars>0 # ./app.py from flask import Flask, render_template, request, jsonify from pusher import Pusher import uuid # create flask app app = Flask(__name__) # configure pusher object pusher = Pusher( app_id='526937', key='00e43de0549d95ef2e5f', secret='9f555fe422de52f88f...
StarcoderdataPython
4951265
from typing import List, Tuple, Optional import math import numpy as np from itertools import product from queue import PriorityQueue from abc import abstractmethod from itertools import chain from pprint import pprint import logging from lane_detection.segment import Segment # Configure logging should be moved log...
StarcoderdataPython
3540433
""" Authors: <NAME> (<EMAIL>) <NAME>, <NAME>, <NAME>, <NAME> Dr. <NAME> (<EMAIL>) --- Versions --- 0.1 - initial version """ # https://doc.qt.io/qtforpython/gettingstarted.html import os import sys import getopt import shutil from pathlib import Path import xml.etree.ElementTree as ET # https://docs.python.org/2/lib...
StarcoderdataPython
6598784
<reponame>fiazkhan420/khan #!/usr/bin/python2 # coding=utf-8 import os import sys import time import datetime import re import threading import json import random import requests import hashlib import cookielib import uuid from multiprocessing.pool import ThreadPool from requests.exceptions import ConnectionError __au...
StarcoderdataPython
11265737
import json import pandas as pd from pathlib import Path from itertools import repeat from collections import OrderedDict import numpy as np import matplotlib.pyplot as plt import itertools import sklearn import io from sklearn.metrics import confusion_matrix from torchvision import transforms from PIL import Image fro...
StarcoderdataPython
1731757
from __future__ import annotations # pylint: disable=no-member import datetime from typing import List, Any from instascrape.core._static_scraper import _StaticHtmlScraper from instascrape.core._mappings import _PostMapping class Post(_StaticHtmlScraper): _Mapping = _PostMapping def load(self, keys: List[st...
StarcoderdataPython
4896066
<reponame>Rishav1/PySyft import glob import os import sys import time import urllib.request from pathlib import Path from zipfile import ZipFile import pytest import nbformat import numpy as np import pandas as pd import papermill as pm import torch import syft as sy from syft import TorchHook from syft.workers.webso...
StarcoderdataPython
6429560
<gh_stars>100-1000 # Copyright (c) 2020, <NAME> # License: MIT License import os import time from ezdxf.lldxf.tagger import ascii_tags_loader, tag_compiler from ezdxf.recover import safe_tag_loader from ezdxf import EZDXF_TEST_FILES BIG_FILE = os.path.join(EZDXF_TEST_FILES, "CADKitSamples", "torso_uniform.dxf") de...
StarcoderdataPython
6654334
# test_src.py # ----------- # Basically a sample script that can be run to unlock any # Achievements specified below import dev_achievements # HelloWorldAchievement print('Helo world', end='') print('\nHello World!') # AssignAchievement x = 4 # MathOperatorsAchievement x += 1 # BitwiseOperatorsAchievement x <<...
StarcoderdataPython
9734761
__source__ = 'https://leetcode.com/problems/number-of-segments-in-a-string/' # https://github.com/kamyu104/LeetCode/blob/master/Python/number-of-segments-in-a-string.py # Time: O(n) # Space: O(1) # Count the number of segments in a string, # where a segment is defined to be a contiguous # sequence of non-space charact...
StarcoderdataPython
204775
from flask_wtf import FlaskForm from wtforms.fields import SelectMultipleField from wtforms.validators import DataRequired class SelectForm(FlaskForm): response = SelectMultipleField('Response', choices = [], \ validators=[DataRequired()])
StarcoderdataPython
11849
#!/usr/bin/env python3 # NOTE: this file does not have the executable bit set. This tests that # Meson can automatically parse shebang lines. import sys template = '#define RET_VAL %s\n' output = template % (open(sys.argv[1]).readline().strip()) open(sys.argv[2], 'w').write(output)
StarcoderdataPython
9654499
<filename>homeassistant/components/message_bird/notify.py """MessageBird platform for notify component.""" import logging import voluptuous as vol from homeassistant.const import CONF_API_KEY, CONF_SENDER import homeassistant.helpers.config_validation as cv from homeassistant.components.notify import ( ATTR_TARG...
StarcoderdataPython
1894466
import unittest import torch.cuda as cuda from inferno.utils.model_utils import ModelTester class UNetTest(unittest.TestCase): def test_unet_2d(self): from inferno.extensions.models import UNet tester = ModelTester((1, 1, 256, 256), (1, 1, 256, 256)) if cuda.is_available(): tes...
StarcoderdataPython
6554690
from setuptools import setup with open("README.md", "r") as fh: long_description = fh.read() setup(name='PyTorch-ProbGraph', version='0.0.1', description='Hierarchical Probabilistic Graphical Models in PyTorch', long_description=long_description, author='<NAME>, <NAME>', author_email...
StarcoderdataPython
1988392
<reponame>suzaku/plain_obj from keyword import iskeyword from collections import OrderedDict def new_type(type_name, field_names): if isinstance(field_names, str): # names separated by whitespace and/or commas field_names = field_names.replace(',', ' ').split() check_name(type_name) seen_f...
StarcoderdataPython
3282948
<filename>processSingleJobs.py #!/usr/bin/python #------------------------------------------------------------------------------ # Name: processSingleJobs.py # Author: <NAME>, 20150205 # Last Modified: 20150218 #This is a follow-up to the lookThresh.py script; it reads the top_jobs.txt list # and an...
StarcoderdataPython
1681461
# Enter your code here. Read input from STDIN. Print output to STDOUT T=int(input()) for i in range(T): element1=int(input()) A=set(map(int,input().split())) element2=int(input()) B=set(map(int,input().split())) if A.issubset(B): print("True") else: print("False")
StarcoderdataPython
8190473
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 29 12:50:17 2018 @author: Simon Trains the NN with the parameters: dropout=0.3 Size of first hidden lauer: 350 One hidden layers Sigmoid Activation Using matrix from folder: 03-01-2019 11.04 Using GP matrix shape No options should be used when cal...
StarcoderdataPython
236901
<reponame>zoubohao/YOLO-V1-Pytorch from abc import ABC import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import cv2 class Mish(nn.Module): def __init__(self): super(Mish,self).__init__() def forward(self,x): return x * torch.tanh(F.softplus(x)) class Conv2...
StarcoderdataPython
9710687
from iBott.robot_activities import RobotException, get_instances import iRobot.robot as robot import iRobot.settings as settings class BusinessException(RobotException): """Manage Exceptions Caused by business errors""" def __init__(self, message=None, action=None, element=None): self.robotClass = ge...
StarcoderdataPython
6676447
<reponame>deredsonjr/testerepository #----------------------------------------------- #Introdução a Programação dos Computadores - IPC #Universidade do Estado do Amazonas - UEA #Prof. Jucimar Jr. #<NAME> -|- 1715310011 #<NAME> -|- 1715310026 #<NAME> do nascimento -|- 1515200550 #<NAME> -|-...
StarcoderdataPython
3200913
# Desqafio104 o programa possui uma função que verifica se o input é um numero int def leiaInt (num): while True: if num.isnumeric(): return num #print(f'Você digitou {num}') #break else: print(f' {num} Não é um numero, digite um numero') ...
StarcoderdataPython
293622
from .. import pytib
StarcoderdataPython
3297295
""" Generate cards JSON from APK CSV source. """ import csv import logging import os import re from .base import BaseGen from .util import camelcase_split logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) class Cards(BaseGen): def __init__(self, config): super().__init__(conf...
StarcoderdataPython
1661126
<reponame>Morabaraba/calculate from distutils.core import setup setup( name='calculate', version='0.1', packages=['calculate',], license='beerware', long_description=open('README.md').read(), )
StarcoderdataPython
6409474
"""Define all exceptions that occur in pysg. """ class Error(Exception): """Base class for exceptions.""" pass class ParameterError(Error): """Exception raised for invalid camera parameter.""" def __init__(self, expr, msg): self.expr = expr self.msg = msg class PyrrTypeError(Error...
StarcoderdataPython
11223085
<gh_stars>1-10 from distutils.core import setup setup( name = "hookah", version="0.0.9", description="The webhook event broker", author="<NAME>", author_email="<EMAIL>", url="http://github.com/progrium/hookah/tree/master", download_url="http://github.com/progrium/hookah/tarball/master", classifiers=...
StarcoderdataPython
3325917
<filename>test/test_user.py import pytest import mock import builtins import user # ToDo def test_get_number_of_players(): expected_result = 2 with mock.patch.object(builtins, "input", lambda input_str: str(expected_result)): assert user.get_number_of_players() == expected_result
StarcoderdataPython
342612
<reponame>lqez/pynpk from __future__ import with_statement import os.path import re from setuptools import find_packages, setup from setuptools.command.test import test import sys try: with open(os.path.join(os.path.dirname(__file__), 'requirements.txt')) as f: requirements = [i for i in f if not i.startsw...
StarcoderdataPython
4800807
def iloczyn_ciagu(* ciag): if len(ciag) == 0: return 0.0 else: iloczyn=1.0 for elem in ciag: #iloczyn = iloczyn*elem iloczyn*=elem return iloczyn print(iloczyn_ciagu()) print(iloczyn_ciagu(1, 2, 3, 4)) print(iloczyn_ciagu(1, 2, 3, 4, 5, 6, 7...
StarcoderdataPython
1768532
gent_centre_31370 = geopandas.GeoSeries([gent_centre], crs="EPSG:4326").to_crs("EPSG:31370")
StarcoderdataPython
4917382
from torch.testing._internal.common_utils import TestCase, run_tests from torch.testing import check_cuda_kernel_launches, check_code_for_cuda_kernel_launches class AlwaysCheckCudaLaunchTest(TestCase): def test_check_code(self): """Verifies that the regex works for a few different situations""" #...
StarcoderdataPython
6619747
# coding: utf-8 """ ThingsBoard REST API ThingsBoard open-source IoT platform REST API documentation. # noqa: E501 OpenAPI spec version: 3.3.3-SNAPSHOT Contact: <EMAIL> Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import re # noq...
StarcoderdataPython
11297191
class FModifierFunctionGenerator: amplitude = None function_type = None phase_multiplier = None phase_offset = None use_additive = None value_offset = None
StarcoderdataPython
11206941
# This import verifies that the dependencies are available. import psycopg2 # noqa: F401 # GeoAlchemy adds support for PostGIS extensions in SQLAlchemy. In order to # activate it, we must import it so that it can hook into SQLAlchemy. While # we don't use the Geometry type that we import, we do care about the side # ...
StarcoderdataPython
1733942
from app.Process.process_update import RequestsDataFile from app.Process.process_quest import StatisticsSearch class Startup: def __init__(self): self.datafile = RequestsDataFile() self.search = StatisticsSearch() def initial_menu(self): print("--------- Sars-Cov-2 data analysis system...
StarcoderdataPython
1601264
<filename>mysite/client/views.py from django.http import HttpResponse from django.shortcuts import render # Create your views here. # All Django wants returned is an HttpResponse. Or an exception. def index(request): # The code below loads the template called client/index.html # and passes it a context. ...
StarcoderdataPython
9684820
<reponame>PhiladelphiaController/gun-violence from .. import data_dir from . import EPSG from .core import geocode, Dataset from .geo import * from .fred import PhillyMSAHousingIndex import os from glob import glob import pandas as pd import geopandas as gpd import numpy as np try: from phila_opa.db import OPADat...
StarcoderdataPython
4813983
import os import sys from dotenv import load_dotenv from mitto_sdk import Mitto load_dotenv() BASE_URL = os.getenv("MITTO_BASE_URL") API_KEY = os.getenv("MITTO_API_KEY") JOB = { "name": "sql_select_1_from_api", "title": "[SQL] Select 1 from API", "type": "sql", "tags": [ "sql" ], "co...
StarcoderdataPython
233055
<gh_stars>0 from os import environ as env import os import network import certs def get_path(website_id): return os.path.abspath(f"{env['NGINX_SITES_DIR']}/website_{website_id}.conf") def deal_with_certs(website_id, domain): if certs.has_certs(website_id, domain): certs.copy_certs(website_id, domain...
StarcoderdataPython
1838262
#*****************************************************# # This file is part of GRIDOPT. # # # # Copyright (c) 2015-2017, <NAME>. # # # # GRIDOPT is released under the BSD 2-clause license. # ...
StarcoderdataPython
4944133
from BeautifulSoup import BeautifulSoup from collections import defaultdict import re import hashlib import json import nltk import sys from datetime import datetime import urllib import urllib2 from threading import Thread import extract import operator from BeautifulSoup import BeautifulSoup class WebsiteMiner(Thr...
StarcoderdataPython
3553481
<reponame>mattjudge/field-photogrammetric-reconstruction """ Author: <NAME> 2017, except `set_axes_equal` This module provides: :class:`Pointcloud` as a container for point clouds and associated projection matrices :func:`align_points_with_xy` to align point clouds on the XY plane :func:`visualise_heatmap...
StarcoderdataPython
3505536
class C(tuple): def __new__(cls, tpl, val): print("C.__new__") obj = tuple.__new__(cls, tpl) #print("in new:", type(obj)) assert type(obj) is C obj.val = val return obj o = C((1, 2), 3) assert type(o) is C print(o) print(o.val) print("--") class C(tuple): de...
StarcoderdataPython
8124444
<reponame>DuckMcFuddle/forum-sweats from aiohttp import web from . import discordbot, commands import asyncio import os routes = web.RouteTableDef() @routes.get('/') async def index(request): return web.Response(text='e') @routes.get('/kill') async def kill_bot(request): if request.query.get('token') == os.gete...
StarcoderdataPython
11395799
<reponame>TovarnovM/easyvec<filename>tests/test_vec2.py from easyvec import Vec2 import numpy as np from pytest import approx def test_constructor1(): v = Vec2(1,2) assert v is not None assert v.x == approx(1) assert v.y == approx(2) def test_constructor2(): v = Vec2.from_list([1, 2]) assert v...
StarcoderdataPython
4877353
<gh_stars>10-100 from .pynnotator import Pynnotator
StarcoderdataPython
8032729
# -*- coding: utf-8 -*- from helper_functions.main_script_NDL import Generate_all_dictionary, Generate_corrupt_and_denoising_results, compute_all_recons_scores from helper_functions.final_plots_display import diplay_ROC_plots, all_dictionaries_display, top_dictionaries_display, all_dictionaries_display_rank, recons_di...
StarcoderdataPython
11214422
<filename>800/19_05_2021/469A.py def main(): lst1 = 'I become the guy.' lst2 = 'Oh, my keyboard!' n = int(input()) p = input().split()[1:] q = input().split()[1:] set_pq = set(p+q) if len(set_pq) == n: print(lst1) else: print(lst2) if __name__ == "__main__": main(...
StarcoderdataPython
9798343
import json from django.core.urlresolvers import reverse from rest_framework import status from rest_framework.test import APIClient from openslides import __version__ as version from openslides.core.config import ConfigVariable, config from openslides.core.models import CustomSlide, Projector from openslides.utils.r...
StarcoderdataPython
4869749
<filename>google_problems/problem_69.py """This problem was asked by Google. A regular number in mathematics is defined as one which evenly divides some power of 60. Equivalently, we can say that a regular number is one whose only prime divisors are 2, 3, and 5. These numbers have had many applications, from helping...
StarcoderdataPython
1904314
## factory boy import factory # Own from portfolio.models import Account class AccountFactory(factory.django.DjangoModelFactory): """ Factory for creating accounts """ class Meta: model = Account # Account name by default will be 'Account 1' for the first created # account, 'Account...
StarcoderdataPython
1967649
# coding=utf-8 import requests from bs4 import BeautifulSoup as bs class ImomoeClientMainPage(object): def __init__(self): self.base_url = "http://www.imomoe.in" r = requests.get(self.base_url) self.mp_html = r.content self.soup = bs(self.mp_html, "lxml") self.all_div = ...
StarcoderdataPython
9767223
# Third party code # # The following code are copied or modified from: # https://github.com/google-research/motion_imitation # Lint as: python3 """Defines the minitaur robot related constants and URDF specs.""" LEG_ORDER = ["front_left", "back_left", "front_right", "back_right"]
StarcoderdataPython
11359697
import sys from PyQt5.QtWidgets import * class MyWindow(QMainWindow): def __init__(self): super().__init__() self.setGeometry(300, 300, 400, 300) self.line_edit1 = QLineEdit(self) self.line_edit1.move(10, 10) self.line_edit1.resize(200, 30) app = QApplication(sys.argv) ...
StarcoderdataPython
1784731
""" Problem Statement: - The concept of loops or cycles is very common in graph theory. A cycle exists when you traverse the directed graph and come upon a vertex that has already been visited. You have to implement the detect_cycle function which tells you whether or not a graph contains a cycle. Inpu...
StarcoderdataPython
300212
import json from typing import Optional import uvicorn import yaml from fastapi import FastAPI from pydantic import BaseModel, Field from typhoon.core.components import Component from typhoon.core.dags import IDENTIFIER_REGEX, Granularity, DAGDefinitionV2, TaskDefinition, add_yaml_representers from typhoon.core.glue ...
StarcoderdataPython
1741690
"""Python wrappers around TensorFlow ops. This file is MACHINE GENERATED! Do not edit. Original C++ source file: map_ops.cc """ import collections from tensorflow.python import pywrap_tfe as pywrap_tfe from tensorflow.python.eager import context as _context from tensorflow.python.eager import core as _core from tens...
StarcoderdataPython
9681391
from json import load import pygame from pygame.locals import KEYDOWN, K_DOWN, K_LEFT, K_RIGHT, K_UP, QUIT from quicknet.client import QClient with open('settings.json') as file: SETTINGS = load(file) SELF = None RUN = True PLAYERS = {} game_client = QClient(SETTINGS["ip_addr"], SETTINGS["port"]) @game_client....
StarcoderdataPython
9666307
<reponame>pazamelin/openvino from jinja2 import Template from os import path, remove from shutil import rmtree def create_content(template: str, notebooks_data: dict, file_name: str): """Filling rst template with data :param template: jinja template that will be filled with notebook data :type template: ...
StarcoderdataPython
209201
#!/usr/bin/env python # coding: utf-8 # Pybank Financial Analysis import os import csv csvpath = os.path.join('Resources','budget_data.csv') analysis = os.path.join('analysis', 'Analysis.txt') # Declare variables and lists count = 0 months = [] revenue = [] prev_rev = 0 chg_lst =[] # Opening the CSV file with open...
StarcoderdataPython
147639
<filename>mlcomp/contrib/criterion/triplet.py<gh_stars>100-1000 import torch import torch.nn.functional as F from catalyst.contrib.nn.criterion.functional import cosine_distance, \ batch_all, _EPS def triplet_loss( embeddings: torch.Tensor, labels: torch.Tensor, margin: float = 0.3, reduction='mea...
StarcoderdataPython
3537160
<filename>alipcs_py/commands/list_files.py from typing import Optional, List from alipcs_py.alipcs import AliPCSApi from alipcs_py.alipcs.inner import PcsFile from alipcs_py.common.path import join_path from alipcs_py.commands.log import get_logger from alipcs_py.commands.sifter import Sifter, sift from alipcs_py.comm...
StarcoderdataPython
6451164
# -------------------------------------------------------------------------- # Source file provided under Apache License, Version 2.0, January 2004, # http://www.apache.org/licenses/ # (c) Copyright IBM Corp. 2015, 2016 # -------------------------------------------------------------------------- """ Problem Descriptio...
StarcoderdataPython
4950096
<reponame>sre-ish/website<gh_stars>0 #!/bin/python # Download a tgz file from a pre-defined URL # Uncompresses it and install it under a directory (e.g /shared/) import os import sys import tarfile def untar(d,f): fpath = d + f tar = tarfile.open(fpath) tar.extractall(d) tar.close() return # --- * --- def...
StarcoderdataPython
1773112
#!/usr/bin/env python # -*- coding: utf-8 -*- # Python version: 3.6 import argparse def args_parser(): parser = argparse.ArgumentParser() # federated arguments parser.add_argument('--alg', type=str, default='fedavg', choices=['fedavg', 'fedprox'], help="client nets aggregation algorithm") parser.add_a...
StarcoderdataPython
324911
<gh_stars>100-1000 """ test utils functions """ # pylint: disable= invalid-name import numpy as np import pytest from autofaiss.utils.array_functions import multi_array_split def test_multi_array_split(): """test multi_array_split fct number 1""" assert len(list(multi_array_split([np.zeros((123, 2)), np.zer...
StarcoderdataPython