id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
5726
import uuid import pickle import pytest import argparse from collections import namedtuple from six import text_type from allure.common import AllureImpl, StepContext from allure.constants import Status, AttachmentType, Severity, \ FAILED_STATUSES, Label, SKIPPED_STATUSES from allure.utils import parent_module, p...
StarcoderdataPython
5086783
""" adjusts module path to account for virtual namespace This is required primarily for testing. """ import sys import os import pkg_resources VIRTUAL_NAMESPACE = 'tiddlywebplugins' local_package = os.path.abspath(VIRTUAL_NAMESPACE) sys.modules[VIRTUAL_NAMESPACE].__dict__['__path__'].insert(0, local_package)
StarcoderdataPython
3415831
<gh_stars>0 import os import pprint import pytest from dotenv import load_dotenv, find_dotenv from hvac import Client from pydantic import ValidationError from builder.train_builder import TrainBuilder from builder.messages import BuildMessage, BuildStatus, BuilderCommands from builder.tb_store import VaultEngines ...
StarcoderdataPython
11276820
<filename>recognizeApp/networks/v1.py import os.path import numpy as np import matplotlib.image import matplotlib.pyplot as plt from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D from keras.layers import Activation, Dropout, Flatten...
StarcoderdataPython
12838888
class Solution(object): def sortColors(self, nums): def triPartition(nums, target): i,j,n = 0, 0,len(nums) -1 while j <= n: if nums[j] < target: nums[i], nums[j] = nums[j], nums[i] i += 1 j += 1 ...
StarcoderdataPython
221418
<filename>shexer/model/shape.py STARTING_CHAR_FOR_SHAPE_NAME = "@" class Shape(object): def __init__(self, name, class_uri, statements): self._name = name self._class_uri = class_uri self._statements = statements @property def name(self): return self._name @property ...
StarcoderdataPython
6541925
<reponame>gavindsouza/instagram-to-sqlite import json import os from types import SimpleNamespace from typing import Any import click from sqlite_utils.db import _hash class Namespace(SimpleNamespace): def __init__(self, *args, **kwargs: Any) -> None: if args and isinstance(args[0], dict): kw...
StarcoderdataPython
125321
<gh_stars>0 """Workflow package.""" import os import inspect import json from collections import OrderedDict import logging from collections import namedtuple import copy_reg import types __version__ = 0.3 ############################################################################# # Enable pickling of instance m...
StarcoderdataPython
6605086
<filename>pymoo/algorithms/so_de.py import numpy as np from pymoo.algorithms.genetic_algorithm import GeneticAlgorithm from pymoo.docs import parse_doc_string from pymoo.model.mating import Mating from pymoo.model.population import Population from pymoo.model.replacement import ImprovementReplacement from pymoo.model....
StarcoderdataPython
8173916
# -*- coding: utf-8 -*- """ .. module:: import_csv_for_factors :synopsis: module importing data for SAOB .. moduleauthor:: <NAME> <<EMAIL>> """ import pandas as pd def _common_read(csv_file, raters): """Reads data from a csv file containing parents and sometimes teachers and clinicians severity assessments...
StarcoderdataPython
4813479
<filename>memory_orig/inoutput_confirm.py<gh_stars>1-10 #์ผ๋‹จ์€ ๋ฌธ์ œ์™€ ์‚ฌ์šฉ์ž ์ž…๋ ฅ ๋‹ต๋ณ€์ด ์ผ์น˜ํ•œ๋‹ค๋Š” ๊ฐ€์ • ํ•˜์—~~ Qscreen = [ [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], ...
StarcoderdataPython
8185100
<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- #--------------------------------------------------------------------------------- # _____ _ _ ______ _ # (_____) | (_) (____ \ (_) # _ ____ _ | |_ ____ ___ ...
StarcoderdataPython
9639996
"""discriminator_on_related.py The HasAddresses mixin will provide a relationship to the fixed Address table based on a fixed association table. The association table will also contain a "discriminator" which determines what type of parent object associates to the Address row. This is a "polymorphic association". ...
StarcoderdataPython
11317458
# <NAME> # <EMAIL> import numpy as np import pandas as pd from flam2millijansky.flam2millijansky import flam2millijansky from hstphot.container import Container def prepare_KN_nebular_spc(wavelength_angstrom,luminosity_per_angstrom,luminosity_distance_mpc,container): """ prepare_KN_nebular_spc function prepar...
StarcoderdataPython
3334018
<filename>data/transcoder_evaluation_gfg/python/MINIMUM_ROTATIONS_REQUIRED_GET_STRING.py # Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( str ) : tmp = str + st...
StarcoderdataPython
5005493
# Title: Balanced Binary Tree # Link: https://leetcode.com/problems/balanced-binary-tree/ from collections import deque # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Codec: ...
StarcoderdataPython
11265901
<reponame>cangoosechain/cats-swap import os import json import hashlib from script.utils.log import Log class CdvTool(object): def __init__(self): log = Log("coin_maker_log") self.log = log.logger @staticmethod def sha256(data_sha256): return hashlib.sha256(data_sha256.encode(enco...
StarcoderdataPython
1773995
def answer(): return 42 class School(): def food(self): return 'awful' def age(self): return 300
StarcoderdataPython
6649235
#!/usr/bin/python #-*- coding: utf-8 -*- from unscrapulous.utils import * SOURCE = 'https://www1.nseindia.com/invest/dynaContent/arbitration_award.jsp?requestPage=main&qryFlag=yes' OUTPUT_DIR = '/tmp/unscrapulous/files' OUTPUT_FILE = 'arbitration-awards-nse.csv' def main(conn, session): create_dir(OUTPUT_DIR) ...
StarcoderdataPython
3333773
<filename>Assignment_2/naive_bayes.py # Multinomial Event Model # Given a review predict the rating (1-10) # y is Multinomial phi1 to phi10 # Every position has same multinomial theta1 to theta|V| import itertools import math import matplotlib.pyplot as plt import numpy as np import re import sys import random from co...
StarcoderdataPython
5127389
<reponame>legacyai/tf-transformers # coding=utf-8 # Copyright 2021 TF-Transformers Authors and 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 #...
StarcoderdataPython
1767962
<filename>cwbot/managers/BaseManager.py import weakref import time import abc import logging from cwbot import logConfig import cwbot.util.DebugThreading as threading from cwbot.util.textProcessing import toTypeOrNone from cwbot.common.objectContainer import ModuleEntry from cwbot.common.exceptions import Fatal...
StarcoderdataPython
350054
<gh_stars>1-10 #!/usr/bin/python -S """Python implementation of the experiment framework.""" import logging import os import subprocess logger = logging.getLogger(__name__) EXPERIMENTS_TMP_DIR = '/tmp/experiments' EXPERIMENTS_DIR = '/fiber/config/experiments' _experiment_warned = set() _experiment_enabled = set() ...
StarcoderdataPython
6485420
<filename>marlo/envs/make_env.py import argparse import os import shutil from pathlib import Path parser = argparse.ArgumentParser(description='Make a Marlo Env') parser.add_argument('--name', type=str, required=True, help='the environment name') parser.add_argument('--mission_file', type=str, required=True, help='t...
StarcoderdataPython
1714618
import AtlejgTools.SimulationTools.UnitConversion as u ''' assumes all values are si r_i : inner radius [m] r_o : outer radius [m] omega : rotational speed [rad/s] mu : dynamic viscosity [kg/m/s] rho : density assumes outer wall is stationary References: r1: Technical Note 2006-1: Pine Rese...
StarcoderdataPython
6495789
<reponame>slin96/mmlib import os import random import numpy as np import torch SEED = 42 def deterministic(func, f_args=None, f_kwargs=None): """ Executed the given function in a deterministic calling set_deterministic before :param func: The function to execute. :param f_args: The args for the func...
StarcoderdataPython
6539824
from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.views import View # Create your views here. from .models import BenURL def Ben_redirect_view(request, shortcode=None, *args, **kwargs): # function based view # in the page the url which be...
StarcoderdataPython
11241117
#libreria per generare grafici import matplotlib.pyplot as plt #lib to remove files import os print("Make the Rewards Plot") f=open("rewards_taxi_value_iteration.txt","r") n=0 stringa=f.readline() #conto le ricompense while stringa!="": n+=1 stringa=f.readline() newRewards=[] rewards=[0 for i in range(n)] ...
StarcoderdataPython
47163
<filename>tests/test_altitudo.py #!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `altitudo` package.""" import pytest from click.testing import CliRunner from altitudo import cli, altitudo def test_command_line_interface(): """Test the CLI.""" runner = CliRunner() result = runner.invoke(cli....
StarcoderdataPython
1967202
# Generated by Django 3.1.5 on 2021-01-26 20:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('almanac', '0004_auto_20210127_0919'), ] operations = [ migrations.AlterField( model_name='session', name='time', ...
StarcoderdataPython
3360697
""" Models for event app """ from .event import Event from .eventregistration import EventRegistration __all__ = ["Event", "EventRegistration"]
StarcoderdataPython
3302273
<gh_stars>0 # Copyright 2019 Adobe # All Rights Reserved. # # NOTICE: Adobe permits you to use, modify, and distribute this file in # accordance with the terms of the Adobe license agreement accompanying # it. If you have received this file from a source other than Adobe, # then your use, modification, or distrib...
StarcoderdataPython
1736776
from datetime import date, timedelta, datetime, timezone # __pragma__('opov') def fix_time (dt): if dt.hour > 23: dt = dt - timedelta (minutes=60) if dt.minute > 50: dt = dt - timedelta (minutes=10) return dt def run (autoTester): # timezone tz = timezone.utc autoTester.check...
StarcoderdataPython
6445404
<gh_stars>0 # -*- coding: utf-8 -*- import os import json from landez.sources import DownloadError import mock import shutil from io import BytesIO import zipfile from django.test import TestCase from django.conf import settings from django.core import management from django.core.management.base import CommandError fr...
StarcoderdataPython
11320640
import requests import pandas as pd from quest import util from quest.static import ServiceType, DatasetSource from quest.plugins import ProviderBase, SingleFileServiceBase class UsgsNlcdServiceBase(SingleFileServiceBase): service_type = ServiceType.GEO_DISCRETE unmapped_parameters_available = False geom...
StarcoderdataPython
6481960
from os.path import dirname from hamcrest import assert_that, contains from microcosm.api import create_object_graph from microcosm_postgres.context import SessionContext, transaction from microcosm_eventsource.func import last from microcosm_eventsource.tests.fixtures import Task, TaskEvent, TaskEventType class Te...
StarcoderdataPython
327018
from __future__ import absolute_import, division, unicode_literals from io import open import os import tempfile from wsgiref.util import FileWrapper from celery import states from celery.exceptions import Ignore from celery.task import task from celery.utils.log import get_task_logger from django.conf import settings ...
StarcoderdataPython
6666562
<gh_stars>1-10 import numpy as np from pyrodash.blocks import Arrow class Spins: """ Class to build and draw the spins of an Up Tetrahedron. The class generates, from the spin values passed to its constructor, the axis of the spins and their respectives colors, and use the Arrow class to build a...
StarcoderdataPython
9781160
"""Internal API endpoint constant library. _______ __ _______ __ __ __ | _ .----.-----.--.--.--.--| | _ | |_.----|__| |--.-----. |. 1___| _| _ | | | | _ | 1___| _| _| | <| -__| |. |___|__| |_____|________|_____|____ |____|__| |__|__|__|_____| |: 1 | ...
StarcoderdataPython
3225373
# -*- coding: utf-8 -*- # The dos-azul-lambda request handling stack is generally structured like so: # # /\ * Endpoint handlers, named for the DOS operation converted to # /__\ snake case (e.g. list_data_bundles). # / \ * ElasticSearch helper functions that implement common query types # /______\ ...
StarcoderdataPython
9762073
<reponame>Venafi/pytpp<gh_stars>1-10 from pytpp.attributes._helper import IterableMeta, Attribute from pytpp.attributes.metadata_base import MetadataBaseAttributes class MetadataListAttributes(MetadataBaseAttributes, metaclass=IterableMeta): __config_class__ = "Metadata List" single = Attribute('Single')
StarcoderdataPython
1717818
x_nums = list(map(float, input().split())) y_nums = list(map(float, input().split())) # points = [] # for index in range(0, len(x_nums)): # current = (x_nums[index], y_nums[index]) # points.append() points = list(zip(x_nums, y_nums)) print(points) print(points[0][0])
StarcoderdataPython
5076343
# ref: https://www.youtube.com/watch?v=O20Y1XR6g0A&list=PLoVvAgF6geYMb029jpxqMuz5dRDtO0ydM&index=4 #import os from influxdb import InfluxDBClient from config import HOST, PORT, USERNAME, PASSWORD, DATABASE, TEMPERATURE, HUMIDITY, ROOM1 # following config moved to config.py file # InfluxDB credentials #HOST = o...
StarcoderdataPython
5081380
<reponame>StawaDev/Estrapy-API<filename>Estrapy/games.py<gh_stars>1-10 from io import BytesIO from PIL import Image from .http import get_api, BASE_URL from .base import Base, ObjectConverter from typing import Union, Optional import json import requests import random as rd import time __all__ = ("Games", "AniGames", ...
StarcoderdataPython
376476
<reponame>gtank/blake2 #!/bin/env python3 import json import sys from pyblake2 import blake2s, blake2b def write_blake2s_tests(output_fn): fd = open(output_fn, 'w') key_bytes = bytearray(range(32)) fd.write('[\n') for i in range(8): salt_bytes = bytearray(range(i+1)) test = { ...
StarcoderdataPython
8098525
import robin_stocks as r import pytz import datetime as dt import re import holidays import numpy as np username = '' password = '' login = r.login(username, password) #rlt = r.load_account_profile() #rlt = r.load_portfolio_profile() #rlt = r.get_all_option_positions() #Returns all option positions ever held for the a...
StarcoderdataPython
3532318
<filename>tests/run_python3_post_pretty.py import requests r = requests.post("http://localhost:8000/tag", data={ "data": "Fรถrdomen har alltid sin rot i vardagslivet - <NAME>".encode("utf-8"), "pretty": 1, }) print(r.text)
StarcoderdataPython
274076
import os from quotes_api.app import create_app app = create_app(configuration=os.getenv("APP_CONFIGURATION", "production"))
StarcoderdataPython
4908627
<reponame>sebimarkgraf/rllib """Template for a Model Based Agent. A model based agent has three behaviors: - It learns models from data collected from the environment. - It optimizes policies with simulated data from the models. - It plans with the model and policies (as guiding sampler). """ from itertools import ch...
StarcoderdataPython
3591448
""" This problem was asked by Facebook. Given a 32-bit integer, return the number with its bits reversed. For example, given the binary number 1111 0000 1111 0000 1111 0000 1111 0000, return 0000 1111 0000 1111 0000 1111 0000 1111. """ # take a bit from number one by one add it to the resultant reversed nu...
StarcoderdataPython
4963271
<gh_stars>1-10 import re def extract_libraries(files): """Extracts a list of imports that were used in the files Parameters ---------- files : []string Full paths to files that need to be analysed Returns ------- dict imports that were used in the provided files, mapped a...
StarcoderdataPython
4940076
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import struct from pcc.compiler.assembler import Assembler, ProcessorRegister, ShiftMode # http://ref.x86asm.net/coder64.html # https://www.amd.com/system/files/TechDocs/24594.pdf # page 74 for # integer calling register order: # rdi - rsi - rdx - rcx - r8 - r9 - r...
StarcoderdataPython
3227084
<filename>sfa/methods/Remove.py from sfa.util.faults import * from sfa.util.xrn import Xrn from sfa.util.method import Method from sfa.util.parameter import Parameter, Mixed from sfa.trust.credential import Credential class Remove(Method): """ Remove an object from the registry. If the object represents a PLC ...
StarcoderdataPython
6541650
<filename>sordini.py<gh_stars>0 from kafka import KafkaProducer import zlib import os try: defaultKafkaBroker = os.getenv("SORDINI_BROKER") except: kErr("SORDINI_BROKER env variable not set - any calls without the broker specified will fail") defaultKafkaBroker = None try: defaultKafkaTopic = os.geten...
StarcoderdataPython
5096480
from .models import Movie, Task from rest_framework import serializers from django.contrib.auth import get_user_model from django.contrib.auth.models import User def getFields(model): """ Dynamic way of adding all fields manually instead of '__all__' """ immutable_list = model._meta.get_fields() fields_li...
StarcoderdataPython
1981238
import pytest class TestUserPermissions: @pytest.mark.django_db def test_user(self, user_factory): jimmy = user_factory() assert jimmy.has_perm('view_user', jimmy) assert jimmy.has_perm('change_user', jimmy) assert jimmy.has_perm('delete_user', jimmy) @pytest.mark.django_...
StarcoderdataPython
399690
#!/usr/bin/python """ Configure and run tools """ from subprocess import call import os import sys ENV_RESOURCES_PATH = os.getenv("RESOURCES_PATH", "/resources") ENV_WORKSPACE_TYPE = os.getenv("WORKSPACE_TYPE", "cpu") ENV_WORKSPACE_HOME = os.getenv("WORKSPACE_HOME", "/workspace") ENV_WORKSPACE_BASE_URL = os.getenv("...
StarcoderdataPython
3277070
from typing import Iterator, List from dataclasses import dataclass, field from pathlib import Path import random import tempfile import unittest from rlbot.training.training import Pass, Fail, FailDueToExerciseException from rlbottraining.common_graders.timeout import FailOnTimeout from rlbottraining.exercise_runner...
StarcoderdataPython
131851
<gh_stars>0 from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from .models import Post, Comment from .forms import CommentForm, PostForm, LoginForm im...
StarcoderdataPython
4999164
<reponame>thefstock/FirstockPy """ Request and response models for save fcm token """ from typing import Optional from datetime import datetime from pydantic import BaseModel from ....common.enums import ResponseStatus from ....utils.decoders import build_loader, datetime_decoder __all__ = ['SaveFCMTokenRequestModel...
StarcoderdataPython
5162945
<reponame>john04047210/mira_wepy_server # -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2018 QiaoPeng. # # Invenio is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of ...
StarcoderdataPython
3570016
<reponame>scottwedge/OpenStack-Stein # 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.apache.org/licenses/LICENSE-2.0 # # Unless requi...
StarcoderdataPython
1697119
<reponame>DouglasYuen/LocalisationCleaner<gh_stars>0 import sys ## Main function, reads from the filename passed in and writes to the output file specified ## The expected number of command line arguments has a size of 3, so don't run if not all parameters are present def Main(): if len(sys.argv) == 3: inputName =...
StarcoderdataPython
6537766
<filename>federal/2013/code/budget2013_common.py # coding: utf-8 import codecs import pickle import json import re import argparse def join_lines(lines): return " ".join([line.strip() for line in lines]) epsilon = 1e-4 def numbers_equal(n1, n2): return abs(n1 - n2) < epsilon def parse_value(s): return float(s.re...
StarcoderdataPython
1797372
from optparse import OptionParser import os import sys ################################################################################ # generate_activations.py # # Create a tsv activations file for each of the flanks found in the flanks # fasta file. ################################################################...
StarcoderdataPython
6569606
<reponame>kevintmcdonnell/stars from io import StringIO from os import path as p import unittest import unittest.mock as mock import sbumips ''' https://github.com/sbustars/STARS Copyright 2020 <NAME>, <NAME>, and <NAME> Developed by <NAME> (<EMAIL>), <NAME> (<EMAIL>), and <NAME> (<EMAIL>) Permission is hereby gra...
StarcoderdataPython
1947669
<filename>src/parameters.py ################################################################################################### # Repository: https://github.com/lgervasoni/urbansprawl # MIT License ################################################################################################### storage_folder = 'dat...
StarcoderdataPython
260870
<reponame>jason-168/MLCode # Code from Chapter 14 of Machine Learning: An Algorithmic Perspective (2nd Edition) # by <NAME> (http://stephenmonika.net) # You are free to use, change, or redistribute the code in any way you wish for # non-commercial purposes, but please maintain the name of the original author. # This ...
StarcoderdataPython
3543650
"""States are containers for occupancy values. States hold a number of numpy arrays which are all of the same length. state.q_val holds a numpy array of quantity values These are the most important values in the system, they show the quantity of material (in moles) of a given species in a given compartment. The ...
StarcoderdataPython
8043448
<gh_stars>0 import pandas as pd import matplotlib.pyplot as plt def calculate(model): data = pd.read_csv(model + '.csv') data['Accuracy'] = data['correctPredictions'] / (data['totalPredictions'] + data['totalAnswers'] - data['correctPredictions']) data['Precision'] = data['correctPredictions'] / data['tot...
StarcoderdataPython
4950904
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2016 Red Hat, 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 req...
StarcoderdataPython
6450847
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np def dice_loss(pred, target): ''' pred: (M, H, W) target: (N, H, W) ''' smooth = 1. pflat = pred.reshape(pred.shape[0], 1, -1) tflat = target.reshape(1, target....
StarcoderdataPython
9701733
# -*- coding: utf-8 -*- """Command line interface for Axonius API Client.""" from ...context import CONTEXT_SETTINGS, click from ...options import AUTH, add_options from .grp_common import EXPORT, handle_export USER_NAME = click.option( "--name", "-n", "name", help="Name of user", required=True, ...
StarcoderdataPython
3518425
class Casa: def __init__(self, pared): self.pared = pared def superficie_acristalada(self): return sum(self.pared.area) class Pared: def __init__(self, ventana, orientacion): self.ventana = ventana self.orientacion = orientacion self.area = self.ventana.get_ar...
StarcoderdataPython
3591509
from .db import db class CookingList(db.Model): __tablename__ = 'cooking_lists' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False) recipe_id = db.Column(db.Integer, db.ForeignKey( "recipes.id"), nullable=False) created_a...
StarcoderdataPython
3261722
from django_evolution.mutations import ChangeField MUTATIONS = [ ChangeField('Repository', 'bug_tracker', max_length=256), ]
StarcoderdataPython
3464998
from sklearn.svm import LinearSVC from sklearn.naive_bayes import GaussianNB from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import LabelEncoder import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns fro...
StarcoderdataPython
1738231
<filename>setup.py<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- import re from setuptools import setup, find_packages def load_requirements(fname): is_comment = re.compile("^\s*(#|--).*").match with open(fname) as fo: return [line.strip() for line in fo if not is_comment(line) and line.str...
StarcoderdataPython
30115
from typing import Tuple from abc import abstractmethod from torch import Tensor from torch.nn import Module class BaseDiscriminator(Module): @abstractmethod def forward_(self, z: Tensor) -> Tuple[Tensor, Tensor]: raise NotImplementedError def forward(self, z: Tensor) -> Tuple[Tensor, Tensor]: #...
StarcoderdataPython
6665035
import chainer import numpy as np from test.util import generate_kernel_test_case, wrap_template from webdnn.frontend.chainer.converter import ChainerConverter @wrap_template def template(n=2, c_in=4, h_in=6, w_in=8, c_out=10, ksize=3, stride=1, pad=0, nobias=True, EPS=1e-5, description=""): link = chainer.links...
StarcoderdataPython
200235
<reponame>karolinyoliveira/leetcode-ebbinghaus-practice from typing import List def threeSum(nums: List[int]) -> List[List[int]]: response = [] nums.sort() for i, n in enumerate(nums): if i > 0 and n == nums[i - 1]: continue l, r = i + 1, len(nums) - 1 ...
StarcoderdataPython
5160360
<reponame>newfacade/machine-learning-notes # EM ## Mixtures of Gaussians given a training set $\left\{x^{(1)},...,x^{(n)}\right\}$ with no labels. each point $x^{(i)}$ has a latent variable $z^{(i)}$, the data is specified by a joint probability $p(x^{(i)}, z^{(i)}) = p(x^{(i)}| z^{(i)})p(z^{(i)})$ mixtures of gauss...
StarcoderdataPython
56084
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import copy import unittest from analysis.linear import feature from analysis.linear.feature import ChangedFile from analysis.linear.feature import MetaFeat...
StarcoderdataPython
5071106
<filename>mrjob/aws.py # -*- coding: utf-8 -*- # Copyright 2013 Lyft # # 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 appl...
StarcoderdataPython
11248581
<filename>AtCoder/ABC132/B.py n = int(input()) p_list = list(map(int, input().split())) ans = 0 for i in range(n - 2): p1 = p_list[i] p2 = p_list[i + 1] p3 = p_list[i + 2] if min(p1, p2, p3) != p2 and max(p1, p2, p3) != p2: ans += 1 print(ans)
StarcoderdataPython
3339962
<filename>test/point_source_tests.py import numpy as np import unittest from paltas.PointSource.point_source_base import PointSourceBase from paltas.PointSource.single_point_source import SinglePointSource from lenstronomy.LensModel.lens_model import LensModel from lenstronomy.LightModel.light_model import LightModel f...
StarcoderdataPython
4954239
<filename>neo/Core/State/UnspentCoinState.py import sys from .StateBase import StateBase from .CoinState import CoinState from neo.IO.BinaryReader import BinaryReader from neo.IO.MemoryStream import MemoryStream, StreamManager class UnspentCoinState(StateBase): Items = None def __init__(self, items=None):...
StarcoderdataPython
276070
<filename>deep_gw_pe_followup/__init__.py import os DIR = os.path.dirname(__file__) def get_mpl_style(): return os.path.join(DIR, "plotting.mplstyle")
StarcoderdataPython
11359441
API_REQUEST_ERROR = "\nSomething went wrong. Check your network connection.\n" CITIES_COUNT_ERROR = ( "\nUnfortunately, no such city has been found. " "You should enter the exact name of the city " "to get an accurate forecast.\n" ) NO_FORECASTS_ERROR = "\nThere is no forecast for tomorrow for this city.\n"...
StarcoderdataPython
399003
import heapq class PriorityQueue: def __init__(self): self.elements = [] def empty(self): return len(self.elements) == 0 def put(self, item, priority): heapq.heappush(self.elements, (priority, item)) def get(self): return heapq.heappop(self.elements)[1] dirs_motion ...
StarcoderdataPython
8030013
from flask import session, redirect, request, url_for, flash from functools import wraps def check_session(f): @wraps(f) def func(*args, **kwargs): if 'loggedIn' not in session: return redirect(url_for('auth.index')) return f(*args, **kwargs) return func
StarcoderdataPython
1635451
<reponame>paulondc/chilopoda<filename>src/lib/kombi/Crawler/__init__.py<gh_stars>1-10 from .PathHolder import PathHolder from .Crawler import Crawler, CrawlerError, CrawlerInvalidVarError, CrawlerInvalidTagError, CrawlerTestError, CrawlerTypeError from . import Fs from . import Generic from .Matcher import Matcher from...
StarcoderdataPython
9601963
""" ๋ณ‘์—ญ๋ช…๋ฌธ๊ฐ€๋ž€๊ฒŒ์žˆ๊ธธ๋ž˜ ๊ถ๊ธˆํ•ด์„œ ์†ŒํŒ…ํ•ด๋ณธ๊ฑฐ... ์ง€์—ญ์ฝ”๋“œ๊ฐ€ ์™œ์ธ์ง€ 2~16๋ฐ–์—์—†์Œ 1์–ด๋””๊ฐ? """ import json import requests year = 2018 base_url = 'https://open.mma.go.kr/caisGGGS/hall/mmg/listAllCall.json?yr={year}&jbc_cd={num}&callback' dutydata_url = 'https://open.mma.go.kr/caisGGGS/hall/mmg/memberCall.json?yr={year}&grno={grno}&callback' def remove_b...
StarcoderdataPython
1882969
<reponame>pyghassen/jasmin<filename>jasmin/routing/test/test_throwers.py<gh_stars>0 import mock from twisted.internet import reactor, defer from twisted.trial import unittest from jasmin.queues.factory import AmqpFactory from jasmin.queues.configs import AmqpConfig from jasmin.routing.configs import deliverSmHttpThrowe...
StarcoderdataPython
8045934
<gh_stars>100-1000 from flask import Blueprint, request, jsonify, make_response from app.roles.models import Roles, RolesSchema from flask_restful import Api from app.baseviews import Resource from app.basemodels import db from sqlalchemy.exc import SQLAlchemyError from marshmallow import ValidationError roles = Bluep...
StarcoderdataPython
87135
<reponame>rituraj-iter/ASSIGNMENTS<filename>Sem-5/PIP/Minor Assignment 8/A8Q3.py<gh_stars>1-10 def power(n, m): if m == 0: return 1 elif m == 1: return n return (n*power(n, m-1)) print(power(2,3))
StarcoderdataPython
11206092
<reponame>jfklima/prog_pratica s = 'Fulano' while s != '': print(s) s = s[:-1]
StarcoderdataPython
3262595
""" 350. Intersection of Two Arrays II What if the given array is already sorted? How would you optimize your algorithm? - Use intersect_three - Time: O(M+N) - Space: O(1) What if nums1's size is small compared to nums2's size? Which algorithm is better? - Use intersect_two - Time: O(M+N) - Space: O(min(M, N)) Wh...
StarcoderdataPython
8103250
# # Playlist generator for LightshowPi # Author: <NAME> (<EMAIL>) # # How To: # cd to the location of the playlist script (i.e. "lightshowpi/tools/generatePlaylist") # run "python generatePlaylist.py" # Enter the path to the folder of songs which you desire a playlist for then press <enter> (i.e. # "/home/pi/lightshowp...
StarcoderdataPython
6562163
<gh_stars>1-10 from . import ServiceMixin, ForecastMixin, EpisodeMixin from indice_pollution.history.models import Zone class Service(ServiceMixin): is_active = True website = 'http://www.atmo-grandest.eu/' nom_aasqa = 'ATMO Grand Est' licence = 'OdbL v1.0' insee_list = [ '8105', '57463', '...
StarcoderdataPython