id
stringlengths
2
8
text
stringlengths
16
264k
dataset_id
stringclasses
1 value
3416556
import torch from torch.distributed.shard.sharded_tensor import ( sharded_op_impl, ) def validate_param(param, param_name): if param is None: raise ValueError(f"param: {param_name} shouldn't be None!") @sharded_op_impl(torch.nn.init.uniform_) def uniform_(types, args=(), kwargs=None, pg=None): r""...
StarcoderdataPython
5191056
<filename>Code/Python/DataStructures/class_practice2.py class person: age = 0 initialAge = 24 gender = "male" height = "6 foot 0 inches" newPerson = person() print(newPerson.age) print(newPerson.height) class people: def __init__(self,name,age): self.name = name self.age = age new...
StarcoderdataPython
3553988
<gh_stars>0 """ The following description is taken from the official website: https://www.robots.ox.ac.uk/~vgg/data/voxceleb/ VoxCeleb is an audio-visual dataset consisting of short clips of human speech, extracted from interview videos uploaded to YouTube. VoxCeleb contains speech from speakers spanning a wide ran...
StarcoderdataPython
8060313
<gh_stars>0 #!/usr/bin/env python3 from typing import List def merge_sort(A: List) -> List: """Merge sort algorithm""" if len(A) > 1: mid = len(A) // 2 L, R = A[:mid], A[mid:] n1, n2 = len(L), len(R) merge_sort(L) merge_sort(R) i = j = k = 0 while i ...
StarcoderdataPython
3310932
<filename>SimG4CMS/HcalTestBeam/test/python/run2002_cfg.py import FWCore.ParameterSet.Config as cms process = cms.Process("PROD") process.load("SimGeneral.HepPDTESSource.pdt_cfi") process.load("IOMC.EventVertexGenerators.VtxSmearedGauss_cfi") process.load("SimG4CMS.HcalTestBeam.TB2002GeometryXML_cfi") process.load(...
StarcoderdataPython
3369832
input = """ """ output = """ {x(2)} """
StarcoderdataPython
9649998
<gh_stars>1-10 import collections import io import logging import ujson class Settings(collections.MutableMapping): def __init__(self, *args, **kwargs): self._logger = logging.getLogger('Settings') self.store = dict() self.update(dict(*args, **kwargs)) if 'path' in kwargs: ...
StarcoderdataPython
11295559
<filename>tcp_client.py #-*- coding: utf-8 -*- import socket import sys tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: host = input("INFORME O IP COM O QUAL DESEJA SE COMUNICAR: ") tcp_client.connect((host, 5555)) while(True): msg = input("Informe uma mensagem p/ e...
StarcoderdataPython
139957
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-10 10:11 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dashboard2', '0003_config_latest_value'), ] operations = [ migrations.Alter...
StarcoderdataPython
12824460
"""trna_generate_bed.py - generate a bed file from a fasta file of pre-tRNAs ================================================================ Purpose ------- This script takes as an input a fasta file of pre-tRNAs and will generate a bed file using the name of each fasta read as the chromosome name and will output th...
StarcoderdataPython
37082
<filename>tests/archive/test_archive_value.py # This file is part of the History Store (histore). # # Copyright (C) 2018-2021 New York University. # # The History Store (histore) is released under the Revised BSD License. See # file LICENSE for full license details. """Unit test for archived cell values.""" import py...
StarcoderdataPython
9775787
<filename>dsfinterp/dsfsave.py ''' Created on Jan 28, 2014 @author: <NAME> ''' from logger import vlog from abc import ABCMeta, abstractmethod class DsfSave(object): ''' Abstract class for dynamic structure factor savers ''' __metaclass__ = ABCMeta def __init__(self): ''' Constructor ''' ...
StarcoderdataPython
1763673
import json from pprint import pprint from itertools import combinations from gensim.models import TfidfModel from gensim.corpora import Dictionary from nltk import ngrams from scipy.spatial.distance import cosine from sklearn.cluster import DBSCAN import numpy as np from settings import * def preprocess_blob(blob): ...
StarcoderdataPython
3518420
from flask import Flask, jsonify from flask_restful import Resource, marshal_with from .. import api class Home(Resource): def get(self): return "OK" api.add_resource(Home, '/')
StarcoderdataPython
8044675
<reponame>jasperro/core """Support for switching devices via Pilight to on and off.""" import logging import voluptuous as vol from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice from homeassistant.const import CONF_SWITCHES import homeassistant.helpers.config_validation as cv from .base_class ...
StarcoderdataPython
4907475
<reponame>dee6600/invpend_experiment #! /usr/bin/env python import rospy import random import math from cartpole_v0 import CartPole class Testbed(CartPole): def __init__(self): CartPole.__init__(self) self.start = rospy.Time.now() def random_move(self): """ Control cart with random ve...
StarcoderdataPython
3590508
# 15/15 num_of_flowers = int(input()) table = [list(map(int, input().split())) for _ in range(num_of_flowers)] def rotate_table(tb): new_table = [[] for i in range(num_of_flowers)] for row in reversed(tb): for index, flower in enumerate(row): new_table[index].append(flower) origin...
StarcoderdataPython
9762601
# -*- coding: utf-8 -*- """ Homework: Calibrate the Camera with ZhangZhengyou Method. Picture File Folder: ".\pic\RGB_camera_calib_img", Without Distort. By YouZhiyuan 2019.11.18 """ import os import numpy as np import cv2 import glob def calib(inter_corner_shape, size_per_grid, img_dir, img_type): # criteria: o...
StarcoderdataPython
3574922
<reponame>vincent-lg/levantine<filename>src/context/character/complete.py # Copyright (c) 2020, <NAME> # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must reta...
StarcoderdataPython
1644027
<gh_stars>0 arp_table = [('10.220.88.1', '0062.ec29.70fe'), ('10.220.88.20', 'c89c.1dea.0eb6'), ('10.220.88.21', '1c6a.7aaf.576c'), ('10.220.88.28', '5254.aba8.9aea'), ('10.220.88.29', '5254.abbe.5b7b'), ('10.220.88.30', '5254.ab71.e119'), ('10.220.88.32', '5254.abc7.26aa'), ('10.220.88.33', '5254.ab3a.8d26'), ...
StarcoderdataPython
9663256
import click from awsscripter.stack.helpers import catch_exceptions, confirmation from awsscripter.stack.helpers import get_stack_or_env from awsscripter.stack.stack_status import StackStatus @click.command(name="create") @click.argument("path") @click.argument("change-set-name", required=False) @click.option( "...
StarcoderdataPython
239544
import sys import cv2 import random import numpy as np import pandas as pd from Ui_no5_ui import Ui_MainWindow from matplotlib import pyplot as plt from PyQt5.QtWidgets import QMainWindow, QApplication import keras from keras.datasets import cifar10 from keras.applications.vgg16 import VGG16 from keras.mod...
StarcoderdataPython
3581216
import os; import sys; from Npp import * ## # @brief set the path to cook path="D:\\Users\\draap\\Desktop\\cooking" ## # @brief Do some operate about the file # def run_menu_command(): ##### Space to TAB # Edit->Blank Operations notepad.runMenuCommand("Blank Operations", "Trim Trailing Space") # no...
StarcoderdataPython
3302536
<filename>lib_bre/lib_bre/__init__.py<gh_stars>0 from .transformers import * from .library import *
StarcoderdataPython
6460456
""" Схемы graphql. """ import graphene from .querys import RootQuery # from .mutations import Login schema = graphene.Schema(RootQuery) """ <EMAIL> asgagag """
StarcoderdataPython
8047200
from typing import Dict from Tools import counter as c from enum import Enum import copy class GameError(Exception): pass class CatSearchingError(GameError): pass class FrozenError(GameError): def __init__(self, type_of): super(FrozenError, self).__init__(self, f"This {type_of} is frozen") ...
StarcoderdataPython
1998654
import json import pathlib import pytest import znjson @pytest.fixture def simple_dict(): return {"a": 10, "b": 20} def test_encoder_serializable(simple_dict): _ = json.dumps(simple_dict, cls=znjson.ZnEncoder) def test_decoder_serializable(simple_dict): data_str = json.dumps(simple_dict, cls=znjson....
StarcoderdataPython
3303622
import json import numpy as np from scipy.special import wofz class spec(object): """docstring for spectra.""" def __init__(self,dict,nruns=1,nmodel=1,out_dir='./_output/', npoints=1000, spec_max = -0.1, spec_min = 1.): super(spec, self).__init__() ...
StarcoderdataPython
210241
<gh_stars>10-100 #!/usr/bin/env python COPY_GOOGLE_DOC_KEY = '<KEY>'
StarcoderdataPython
3237828
#Aula 10 do Curso Python em Video! #By Rafabr import time,sys,subprocess subprocess.run(['clear']) print('\n'+'*'*80) print('Aula 10 - Exemplos e Testes'.center(80)+'\n') print('Questionário sobre carros:') tem_carro = str(input('Voçe possui carro? (s/n) : ')).strip().lower() if tem_carro == 's': pass else: ...
StarcoderdataPython
4861468
<reponame>llduyll10/film_project<gh_stars>0 from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import TokenAuthentication from rest_fra...
StarcoderdataPython
11221349
""" Prisma Cloud Compute API Images Endpoints Class """ import urllib.parse # Credentials (Manage > Authentication > Credentials store) class CredentialsPrismaCloudAPIComputeMixin: """ Prisma Cloud Compute API Credentials Endpoints Class """ def credential_list_read(self): return self.execute_compu...
StarcoderdataPython
3503753
<reponame>ramavarjah/flask-booking<gh_stars>0 from .utils import thingworx
StarcoderdataPython
1906327
import requests import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import common.functions as functions from common.xml_validator import xml_validator class heredicare_interface: def __init__(self): self.base_url = "https://portal.img.med.uni-tuebingen.de/ah...
StarcoderdataPython
1961977
<filename>openvariant/annotation/annotation.py """ Annotation ==================================== A core class to represent the schema which files will be parsed. """ import logging import re from typing import List from yaml import safe_load, YAMLError from openvariant.annotation.builder import AnnotationTypesBuild...
StarcoderdataPython
6466844
from kafka import KafkaConsumer import logging import argparse import os def run_job(broker): consumer = KafkaConsumer('example', bootstrap_servers=broker) for msg in consumer: print(str(msg.value, 'utf-8')) def get_arg(env, default): return os.getenv(env) if os.getenv(env, '') is not '' else de...
StarcoderdataPython
46910
<reponame>anhinga/2019-python-drafts<filename>dash-cytoscape/cyto-edit-graph.py # based on cyto-multiselect-callback.py # added ability to add nodes and edges # + experiments with styling # + logging (but not enough to conveniently store changes between sessions) #import json import datetime print("START") with ope...
StarcoderdataPython
6528852
<reponame>LudovicRousseau/pycryptoki<filename>pycryptoki/hsm_management.py """ Methods responsible for pycryptoki 'hsm management' set of commands. """ from _ctypes import pointer from ctypes import byref, create_string_buffer, cast from .attributes import Attributes, to_byte_array from .common_utils import AutoCArray...
StarcoderdataPython
4874712
<reponame>CIS-560/pokemon_breeding_django<filename>web/urls.py from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from apps.pokemon_app import views from django.contrib.auth import views as auth_views admin.autodiscover() urlpatterns = [] # Debug Toolbar if set...
StarcoderdataPython
3582393
<reponame>Acidburn0zzz/pontoon from silme.core import EntityList, Entity, Comment from .structure import GettextStructure import re class GettextParser(): patterns = {} patterns['entity'] = re.compile('^msgid "([^"]*)"\nmsgstr ((?:"[^"]*"\n?)*(?:"[^"]*"))$',re.M|re.S) patterns['comment'] = re.compile('^#([...
StarcoderdataPython
5168756
<filename>library/icinga2_ca.py<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # (c) 2020, <NAME> <<EMAIL>> # BSD 2-clause (see LICENSE or https://opensource.org/licenses/BSD-2-Clause) from __future__ import absolute_import, division, print_function # import json import os from ansible.module_utils.basic ...
StarcoderdataPython
288355
#!/usr/bin/env python # -*- coding:utf8 -*- # class htmlfind: def __init__(self, html, reg, which): self.s = '' self.start = 0 self.which = 0 self._begin(html, reg, which) def _begin(self, s, reg, which): if isinstance(s, unicode): s = s.encode('utf-8') ...
StarcoderdataPython
1883994
import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 7) a, b, c, d = map(int, input().split()) if a <= d and c <= b: print('Yes') else: print('No')
StarcoderdataPython
3371700
<reponame>nikofil/mitmproxy import mitmproxy from mitmproxy.net import tcp from mitmproxy import ctx class CheckALPN: def __init__(self): self.failed = False def configure(self, options, updated): self.failed = mitmproxy.ctx.master.options.http2 and not tcp.HAS_ALPN if self.failed: ...
StarcoderdataPython
1614768
<reponame>saphid/OMDbCLI<filename>src/client.py """ This module handles calling OMDbAPI Usage: client = OMDbClient(apikey="xxxxxx") movie = client.get_movie_by_id(id="tt0086190") print(movie.title) """ import logging import sys from typing import Dict, List, Any, Optional import reques...
StarcoderdataPython
3284699
<reponame>changgoo/pyathena-1 import numpy as np import matplotlib.pyplot as plt import astropy.units as au import astropy.constants as ac # from radps_sp.mass_to_lum import _mass_to_lum # import hii class Cloud(object): """ Simple class for spherical clouds Initialize by giving two of M, R, or Sigma (in...
StarcoderdataPython
23277
class Cpf: def __init__(self, documento): documento = str(documento) if self.cpf_eh_valido(documento): self.cpf = documento else: raise ValueError("CPF inválido!") def cpf_eh_valido(self, documento): if len(documento) == 11: return True ...
StarcoderdataPython
311455
<reponame>Balothar12/uefg import pathlib as pl class ProjectDirectoryDoesNotExist(Exception): def __init__(self, directory: pl.Path): self.message = f"Directory {directory} does not exist, please specify a valid project directory." class ProjectFileDoesNotExist(Exception): def __init__(self, direc...
StarcoderdataPython
4904431
<filename>BigDataMicroMajor/Python/ComputerNetwork/VirtualStreetlight/Switch/test2.py # -*- coding: utf-8 -*- # @Time : 2021/1/1 15:57 # @Author : 咸鱼型233 # @File : test2.py # @Software: PyCharm # @Function: import socket def send_msg(udp_socket): # 获取发送内容 ip_dst = input("请输入对方的ip:") port_dst = int(...
StarcoderdataPython
1733255
<filename>envs/env_utils.py import numpy as np def MinMaxScaler(data): """Min Max normalizer. Args: - data: original data Returns: - norm_data: normalized data """ numerator = data - np.min(data, 0) denominator = np.max(data, 0) - np.min(data, 0) norm_data = numerator / (deno...
StarcoderdataPython
3231872
<reponame>codespider/greeter-grpc-service import logging import os import requests from greeter_grpc import greeter PORT = os.environ.get('GREETING_SERVICE_PORT', 50051) CONSUL_REGISTRATION_ENABLED = os.environ.get('CONSUL_REGISTRATION_ENABLED', 'FALSE') CONSUL_SERVICE_NAME = os.environ.get('CONSUL_SERVICE_NAME', 'gr...
StarcoderdataPython
8120176
<reponame>pnuz3n/respa import logging from parler.admin import TranslatableAdmin from parler.forms import TranslatableModelForm from django.core.exceptions import ValidationError from django import forms from django.contrib import admin from django.contrib.admin import site as admin_site from .models import Notificatio...
StarcoderdataPython
11337150
<gh_stars>0 num1 = float(input('Digite um número: ')) num2 = float(input('Digite um número: ')) if num1 > num2: print('O número {:.2f} é maior que o número {:.2f}'.format(num1,num2)) elif num1 < num2: print('O número {:.2f} é maior que o número {:.2f}'.format(num2,num1)) else: print('O número {:.2f} é igual...
StarcoderdataPython
11375399
<gh_stars>10-100 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Problem list: * next of the register should be driven from * all assignments to a register has to be in stame process. * The nop assignment should assign only a reange which corresponds to a current range assigned by statement. """ from hwt.code im...
StarcoderdataPython
270077
from numba import jit import numpy as np import math @jit(nopython=True, fastmath=True) def init_w(w, n): """ :purpose: Initialize a weight array consistent of 1s if none is given This is called at the start of each function containing a w param :params: w : a weight vector, if one was g...
StarcoderdataPython
1969896
<filename>BasicConcepts/Functions/FunctionWithLiteralReturnValue.py def GetNumber(): # Here is the return statement for our function. # Notice the "return" keyword, a space, and then the value we want to return. return 1 # Here we're calling our function. When functions return a value, # we can store that...
StarcoderdataPython
3235992
# -*- coding: utf-8 -*- # @Author: 1uci3n # @Date: 2021-02-17 00:04:36 # @Last Modified by: 1uci3n # @Last Modified time: 2021-02-17 00:54:18 class Solution(object): def arrayPairSum(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) / 2 # a = [n...
StarcoderdataPython
3505081
# Try somethings out saw basically this for someonelse but then tried 4sum rather than 2sum # Was really not good enough the other was better in terms of speed but same memory class Solution: def divide(self, dividend: int, divisor: int) -> int: if (dividend, divisor) == (-2**31, -1): return 2**31-1 ...
StarcoderdataPython
1601723
x = [int(n) for n in input().split()] n = x[0] m = x[1] a = x[2] initSquare = int((n/a))*int((m/a)) coveringTop = 0 coveringRight = 0 if n%a != 0: coveringTop = int((m/a)) if m%a != 0: coveringRight = int((n/a)) if m%a != 0 and n%a != 0 : print(initSquare + coveringTop + coveringRight +1) else: prin...
StarcoderdataPython
8055815
import os import sys,inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0,parentdir) import pglet from pglet import Text, Textbox, Button, Checkbox def main(page): logged_user = Text(page.user_name) def ...
StarcoderdataPython
23208
counter_name = 'I0_PIN' Size = wx.Size(1007, 726) logfile = '/net/helix/data/anfinrud_1502/Logfiles/I0_PIN-2.log' average_count = 1 max_value = 11 min_value = 0 start_fraction = 0.401 reject_outliers = False outlier_cutoff = 2.5 show_statistics = True time_window = 172800
StarcoderdataPython
1912081
<gh_stars>0 import os, sys from shutil import copyfile class GetAlleles: def __init__(self, option, stFile, alleles): workingdir = os.getcwd() + '/' galaxydir = workingdir.split('/galaxy')[0] print workingdir print galaxydir copyfile(galaxydir + '/galaxy/tools/straintracer/GetMlst.class', workingdir + "/Get...
StarcoderdataPython
1989775
# -*- coding: utf-8 -*- ############################################################################### # # Copyright (c) 2019 HERE Europe B.V. # # SPDX-License-Identifier: MIT # License-Filename: LICENSE # ############################################################################### from qgis.PyQt.QtCor...
StarcoderdataPython
4925902
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from abc import abstractmethod import copy from typing import Dict, List from botbuilder.core.turn_context import TurnContext from botbuilder.schema import InputHints, ActivityTypes from botbuilder.dialogs.choices import ( ...
StarcoderdataPython
11304637
<filename>src/scraper/validahyphe/__init__.py from twisted.internet import reactor from txjsonrpc.web.jsonrpc import Proxy version = '0.3' version_info = 'validalab-scraping' def print_value(value): import pprint pprint.pprint(value) def print_error(error): print(' !! ERROR: ', error) def shutdown():...
StarcoderdataPython
11311629
from __future__ import print_function import math key = int(math.pi * 1e14) text = input("Enter text : ") values = reverse = [] def encryptChar(target): #algorithm target = (((target + 449 ) / key) - 449) return target def decryptChar(target): target = (((target + 449) / key) - 42) return target ...
StarcoderdataPython
5108020
# Copyright 2018 eBay Inc. # Copyright 2012 OpenStack LLC. # 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 # # https://www.apache.org/licenses/LICENSE-2.0...
StarcoderdataPython
5074627
<filename>project_version/services.py """ Provide services for command line interface. """ from github import Github from project_version.abstarct import AbstractCheckProjectVersion from project_version.utils import ( get_non_capitalized_pull_request_title, parse_project_version, ) class GitHubCheckProjectVe...
StarcoderdataPython
6415126
class ShipRocketException(Exception): """ Custom Exception thrown """ def __init__(self, message, code: int = None): super(ShipRocketException, self).__init__(message, code) self.code = code self.message = message
StarcoderdataPython
4932109
from three_state_totalistic_ca import TotalisticCell1D class TestThreeStateTotalisticCA: def test_step(self): rule_num = 777 gen_count = 4 ca = TotalisticCell1D(rule_num, gen_count) ca.start_single() for i in range(3): ca.step() expected_values = \ ...
StarcoderdataPython
9739551
import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.autograd import Variable import random, math, os, time from torch.optim.lr_scheduler import StepLR, ExponentialLR import numpy as np np.set_printoptions(threshold=np.inf) import pandas as pd import matplotlib.pypl...
StarcoderdataPython
1837206
class Resource: _standing_time = 0 _task = None def is_free(self): return self._task is None def assign(self, bid, time): if self.is_free(): self._task = bid self._task.start(time) def process(self, time): if self.is_free(): self._standi...
StarcoderdataPython
1937188
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "<NAME>" import spacy import csv nlp = spacy.load("fr_core_news_sm") """ use Spacy to extract keywords' POS tagging input : csv file that contains document numbers and keywords assigned to each document output exemple in ../data_additional/spacy_pos """ de...
StarcoderdataPython
39062
"""Main module.""" from functools import reduce class Calc: def add(self, *args): return sum(args) def subtract(self, a, b): return a - b def multiply(self, *args): if not all(args): raise ValueError return reduce(lambda x, y: x*y, args) def divide(self...
StarcoderdataPython
5191195
<gh_stars>1-10 import time import requests from features.src.support import helpers import os start_time = time.time() class Space: def createSpace(self, spaceName): # Tokens are stored in a form of "<access_token>;<refresh_token>(;<username>)" theToken = helpers.get_user_tokens().split(";")[0] ...
StarcoderdataPython
196485
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Indian - Purchase Report(GST)', 'version': '1.0', 'description': """GST Purchase Report""", 'category': 'Accounting', 'depends': [ 'l10n_in', 'purchase', ], 'data': ...
StarcoderdataPython
11263648
<reponame>simonchristensen1/Zeeguu-Core<filename>zeeguu_core/model/starred_article.py from datetime import datetime, time from sqlalchemy.orm.exc import NoResultFound import zeeguu_core from sqlalchemy import Column, UniqueConstraint, Integer, ForeignKey, String, DateTime, Boolean from sqlalchemy.orm import relations...
StarcoderdataPython
6590361
#Different types of data in python #1. Strings #2. Numeric # a. integer (int) # b. real (float) # c. complex (complex) #3. Sequences # a. lists # b. tuples # c. range* #4. Boolean - True or False #5. Many many more types #Strings # A string is a series of characters. ANything in quotation marks: "This is ...
StarcoderdataPython
3286990
import numpy as np from sklego.dummy import RandomRegressor import pytest def test_values_uniform(random_xy_dataset_regr): X, y = random_xy_dataset_regr mod = RandomRegressor(strategy="uniform") predictions = mod.fit(X, y).predict(X) assert (predictions >= y.min()).all() assert (predictions <= y....
StarcoderdataPython
3220847
from typing import Any, List from adapters.base_adapter import BaseProblemAdapter from models.problem import Problem, Move class CRGProblemAdapter(BaseProblemAdapter): """ Map problem data to a Python object that the renderer can use. """ def map_problem(self, problem_data: List[Any]) -> Problem: ...
StarcoderdataPython
3566989
N = int(input()) A = [int(x) for x in input().split()] left = [-1] * N for i in range(1, N): now = i-1 while now != -1 and A[now] <= A[i]: now = left[now] left[i] = now right = [-1] * N for i in reversed(range(N-1)): now = i+1 while now != -1 and A[now] <= A[i]: now = right[now] ...
StarcoderdataPython
1774996
<filename>Leetcode/300. Longest Increasing Subsequence/solution3.py<gh_stars>10-100 class Solution: def lengthOfLIS(self, nums: List[int]) -> int: if not nums: return 0 result = [] for num in nums: if not result or num > result[-1]: result.append(num) ...
StarcoderdataPython
6610042
<gh_stars>1-10 # # Copyright 2002.2.rc1710017 Barcelona Supercomputing Center (www.bsc.es) # # 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
9716236
""" MIT License Copyright (c) 2020 MyerFire 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, copy, modify, merge, publi...
StarcoderdataPython
9783935
<reponame>bcgov-c/ligo-lib import filecmp import os import pytest import shutil import linker.core.link_json as lj from test.linker.utils import Utils @pytest.fixture(params=[ 'levenshtein', pytest.param('combination', marks=pytest.mark.slow) ]) def context(request): work_path = os.path.join(os.path.dirn...
StarcoderdataPython
1615981
<reponame>stormi/tsunami # -*-coding:Utf-8 -* # Copyright (c) 2010 <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright noti...
StarcoderdataPython
351712
<reponame>flavioribeiro/brave import time, pytest, inspect from utils import * def test_initial_state_option_on_startup(run_brave, create_config_file): ''' Test that if 'initial_state' is set as a property, it is honored. It can be set for inputs, outputs and mixers. ''' output_image_location0 = c...
StarcoderdataPython
1798352
<filename>lambdarado/_wrap_handler_default.py # SPDX-FileCopyrightText: (c) 2021 <NAME> <github.com/rtmigo> # SPDX-License-Identifier: MIT import json import os from aws_lambda_context import LambdaContext from typing import Dict from lambdarado._common import AwsHandlerFunc def _is_true_environ(key: str, default:...
StarcoderdataPython
4837867
<reponame>opencv/deep-person-reid import argparse import os import re import tempfile from pathlib import Path from subprocess import run # nosec import json import numpy as np from ruamel.yaml import YAML def get_lr_sets(model_name: str): if "mobilenet" in model_name: return {"COCO": 0.0001, "VOC": 0.0...
StarcoderdataPython
3404539
<gh_stars>10-100 #!/usr/bin/env python3.8 # Copyright 2020, Schweitzer Engineering Laboratories, Inc # SEL Confidential import random import json import itertools from ..init import ( uut, UTLOG, LOGID, nose, ) from .. import tools @tools.setup(progress_bar=True) def test_str_base_resolution(): ""...
StarcoderdataPython
3314946
from __future__ import print_function # Adapted from https://github.com/benthor/remotty/blob/master/socketclient.py import sys import tty import fcntl import os import termios import threading import errno import logging log = logging.getLogger(__name__) class SocketClient: def __init__(self, socket_in=...
StarcoderdataPython
5051979
import argparse import datetime import gym import numpy as np import itertools import torch import imageio import envs from torch.utils.data import DataLoader, ConcatDataset from padding_onehot.replay_memory_dataset import ReplayMemoryDataset from padding_onehot.skeleton_encoder import SkeletonEncoder from padding_one...
StarcoderdataPython
11205191
def response(hey_bob): hey_bob = hey_bob.strip() if hey_bob == "": return "Fine. Be that way!" elif hey_bob[-1] == '?': # will give you an error if the string is empty if hey_bob.isupper(): return "Calm down, I know what I'm doing!" else: return "Sure." e...
StarcoderdataPython
5013962
from datetime import datetime from typing import List from fastapi_mqtt import FastMQTT from app import logger from app.cache.model import Product as CacheProduct, Coupon as CacheCoupon from app.config.config import COUPON_PREDICTION_TOPIC_NAME from app.event_emitters.model import Customer, PredictionResult, Recommen...
StarcoderdataPython
5194135
<reponame>nortti/trump-tweet-reception-predictor #!/usr/bin/env python import os import sys import json import urllib from requests_oauthlib import OAuth1Session def get_tweets_json(screen_name): client_key = os.environ['client_key'] client_secret = os.environ['client_secret'] twitter = OAuth1Session(cli...
StarcoderdataPython
188196
<gh_stars>0 from configparser import ConfigParser from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker config = ConfigParser() config.read('db.ini') if config['database']['type'] == 'sqlite': path = config['sqlite']['path'] engine...
StarcoderdataPython
3426592
<gh_stars>1-10 # TOOL gunzip.py: "Extract .gz file" (Extract a gzip file, which usually has a file extension .gz) # INPUT input_file: "Gzip file" TYPE GENERIC (Gzip compressed file) # OUTPUT output_file: "Extracted file" import gzip import shutil from tool_utils import * def main(): infile = gzip.open('input_fil...
StarcoderdataPython
105114
import numpy as np from scipy.interpolate import RectBivariateSpline def TemplateCorrection(T, It1, rect, p0 = np.zeros(2)): threshold = 0.1 x1_t, y1_t, x2_t, y2_t = rect[0], rect[1], rect[2], rect[3] Iy, Ix = np.gradient(It1) rows_img, cols_img = It1.shape rows_rect, cols_rect = T.sh...
StarcoderdataPython
6431393
import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt from matplotlib import patheffects, patches def show_img(img, figsize=None, fig=None, ax=None): if not ax: fig, ax = plt.subplots(figsize=figsize) ax.imshow(img) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_...
StarcoderdataPython
246323
<filename>Fancy_aggregations/supervised_MPA.py # -*- coding: utf-8 -*- """ Created on Wed Dec 30 13:30:43 2020 @author: javi- """ import numpy as np import sklearn.linear_model from . import penalties as pn from . import binary_parser as bp # ========================================================================...
StarcoderdataPython