id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
20819
import os import fnmatch from pathlib import Path from jinja2 import Template from .Metadata import Metadata class JSGenerator: def __init__(self, j): """ """ self._j = j self._generated = False def _check_process_file(self, path): bname = os.path.basename(path) ...
StarcoderdataPython
11293596
""" Given a string, return whether it represents a number. Here are the different kinds of numbers: "10", a positive integer "-10", a negative integer "10.1", a positive real number "-10.1", a negative real number "1e5", a number in scientific notation And here are examples of non-numbers: "a" ...
StarcoderdataPython
9633916
<gh_stars>0 from flask import Flask from config import Config from flask_sqlalchemy import SQLAlchemy from flask_cors import CORS app = Flask(__name__, static_folder='../static/dist', template_folder='../static/src') CORS(app) app.config.from_object(Config) db = SQLAlchemy(app) from app import routes, mod...
StarcoderdataPython
4868193
# -*- coding: utf-8 -*- from django import VERSION from django.template import Library register = Library() if VERSION >= (1, 5): from .absolute import absolute, site register.tag(absolute) register.tag(site) else: from django.templatetags.future import url from .absolute import AbsoluteUrlNod...
StarcoderdataPython
1906062
<gh_stars>0 import toolz, pyrsistent, hypothesis, effect, pytest class User(object): def __init__(self, id, name, organization): self.id = id self.name = name self.organization = organization def load_from_db(store, id): name, org = store.find(User, id=id) return User(id, name, org) def load_owned_prod...
StarcoderdataPython
1633262
import asyncio import time import traceback from src import database, amino_async, configs from src.utils import service_align, logger, file_logger DEVICES = open(configs.DEVICES_PATH, "r").readlines() async def login(account: tuple): client = amino_async.Client() email = account[0] password = account[...
StarcoderdataPython
8117294
import sqlite3 import datetime from flask import Flask, render_template from bokeh.plotting import figure from bokeh.resources import INLINE from bokeh.embed import components app = Flask(__name__) @app.route('/') def index(): return 'hello world' @app.route('/chart') def chart(): # create chart p = f...
StarcoderdataPython
6488960
"""Helper module for handling files on the os.""" import os import os.path def get_all_file_names(path, extension=None): """Returns all files in the given directory. Args: path(string): Path to an existing directory. extension(string, optional): Set this to get only a certain ...
StarcoderdataPython
3343728
from __future__ import annotations import aiosqlite from bot.config import Config from bot.data import channel_points_handler from bot.data import command from bot.data import esc from bot.data import format_msg from bot.message import Message async def ensure_motd_table_exists(db: aiosqlite.Connection) -> None: ...
StarcoderdataPython
5160514
<reponame>actris-cloudnet/model-evaluation import os import netCDF4 from typing import Union from datetime import datetime from cloudnetpy import utils, output from model_evaluation import version from model_evaluation.products.model_products import ModelManager from model_evaluation.metadata import MetaData, MODEL_ATT...
StarcoderdataPython
11377310
#!python # -*- coding: utf-8 -*- """ VRT Widesky low-level Password mix-in. """ class PasswordOpsMixin(object): """ The Password operations mix-in implements low-level support for modifying the current Widesky user's password. """ def update_password(self, new_password, callback=None): ""...
StarcoderdataPython
4906160
"""This module implements a multilayer perceptron Author: <NAME>""" import torch.nn as nn class RegressorMlp(nn.Module): """Class to construct fully connected neural networks with a number of hidden layers""" def __init__(self, layer_sizes, afunc=nn.ReLU): """Initialize a multilayer perceptron ...
StarcoderdataPython
6509489
<filename>tests/test_gs.py # -*- coding: utf-8 -*- """ use Kreuz spikes from Fig 2B to test global_sync code """ from __future__ import print_function, division import numpy as np import numpy.testing as nptest import pandas as pd from burst_sync import global_sync as gs def test_get_phase_spikes(): spikes = ...
StarcoderdataPython
11263500
<reponame>dvdzhang/uncertainty-baselines # coding=utf-8 # Copyright 2022 The Uncertainty Baselines Authors. # # 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/licen...
StarcoderdataPython
1695121
<filename>test/python/mock/test_new_qasm_backend.py # This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses...
StarcoderdataPython
5040270
import matplotlib.pyplot as plt import numpy as np label = ['Adventure', 'Action', 'Drama', 'Comedy', 'Thriller/Suspense', 'Horror', 'Romantic Comedy', 'Musical', 'Documentary', 'Black Comedy', 'Western', 'Concert/Performance', 'Multiple Genres', 'Reality'] no_movies = [941,854,4595,2125,942,509,548,149,19...
StarcoderdataPython
19760
<gh_stars>10-100 import random as rnd from itertools import combinations from time import perf_counter as pfc def seite_ermitteln(versuch): seite = [0]*anz_kugeln links = set(versuch[:len(versuch)//2]) for nr in versuch: seite[nr] = -1 if nr in links else 1 return seite def wiegen(nr, gewicht, seite): ...
StarcoderdataPython
290090
<filename>backend/attention_keeper/controller/event.py import multiprocessing import time import feedparser import psutil as psutil from flask import current_app from flask_api import status from attention_keeper.model.event import Event from attention_keeper.model.item import Item from attention_keeper.util import l...
StarcoderdataPython
3515930
<reponame>muma7490/PyLightSupport import os import json import logging.config def setup_logging( default_path = f"{os.path.dirname(__file__)}/logsettings.json", default_level=logging.DEBUG,): '''Setup logging configuration ''' logging.getLogger("huey.contrib.djhuey.management.commands.run_huey").setLevel...
StarcoderdataPython
5150278
import time LOCATOR_LIST = [ "text", "textContains", "textMatches", "textStartsWith", "className", "classNameMatches", "description", "descriptionContains", "descriptionMatches", "descriptionStartsWith", "checkable", "checked", "clickable", "longClickable", "...
StarcoderdataPython
3376251
# Generated by Django 2.2.7 on 2019-11-20 20:04 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('ems', '0003_auto_20191120_1910'), ] operations = [ migrations.RenameModel( old_name='Entry', ...
StarcoderdataPython
1687360
"""Export annotated corpus data to format-preserved xml.""" import logging import os import xml.etree.ElementTree as etree import sparv.util as util from sparv import (AnnotationData, Config, Document, Export, ExportAnnotations, SourceAnnotations, Text, exporter) from . import xml_utils log = logging.getLogger(__nam...
StarcoderdataPython
8002802
<reponame>GearPlug/predictivoAPI-python class BaseError(Exception): pass class BadRequest(BaseError): pass class APIKeyMissing(BaseError): pass class Forbidden(BaseError): pass class ResourceNotFound(BaseError): pass class MethodNotAllowed(BaseError): pass class ResourceNestingTooDee...
StarcoderdataPython
9657622
import os import pygame from pygame_gui.elements import UILabel import pycraft_gui from pycraft import World from pycraft_gui.gui_app import GuiApp from pycraft_gui.constants import PYCRAFT_WORLD_MENU_HOVERED, PYCRAFT_WORLD_MENU_UNHOVERED, \ PYCRAFT_WORLD_MENU_SELECTED from pycraft_gui.pycraft_world_menu import P...
StarcoderdataPython
1627020
from autogoal.contrib.ensemble._stacking import StackingEnsemble
StarcoderdataPython
12809861
#!/usr/bin/python import unittest from coffee_calc import CoffeeCalc class TestBrixConverter(unittest.TestCase): """ Tests all the functions in our conversion class, which backs the API responses in our Main app. """ def setUp(self): self.cc = CoffeeCalc() def test_tds_takes_float_or_i...
StarcoderdataPython
9705994
#!/usr/bin/python # -*- coding: utf-8 -*- """Tests for the Microsoft Office MRUs Windows Registry plugin.""" import unittest from plaso.formatters import winreg as _ # pylint: disable=unused-import from plaso.lib import timelib from plaso.parsers.winreg_plugins import officemru from tests.parsers.winreg_plugins imp...
StarcoderdataPython
239553
#!/usr/bin/python # # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
StarcoderdataPython
4946753
class Person: def __init__(self,Initialage): if(Initialage < 0): self.age=0 print("Age is not valid, setting age to 0.") self.age=Initialage def yearPasses(self): self.age+=1 def amIOld(self): if(self.age<13): print("You are young") ...
StarcoderdataPython
12835679
from fastapi import Depends, HTTPException from starlette.requests import Request from starlette.responses import RedirectResponse from starlette.status import HTTP_303_SEE_OTHER, HTTP_404_NOT_FOUND from examples.models import Config from fastapi_admin.app import app from fastapi_admin.depends import get_resources fro...
StarcoderdataPython
3462011
import numpy wl = 460 mappings = [[561, 1, 7023] , [488, 2, 12873] , [460, 3, 6633]] search = wl for (wav, ch, amp) in mappings: if wav == wl: channel = ch rfamp = amp else : pass print("Channel = ", channel) print("Amplitude = ", rfamp) for i in range(0,11 ): print(i)
StarcoderdataPython
5076350
import requests import random import tweepy from PIL import Image, ImageDraw from io import BytesIO from tempfile import mkstemp import os FFZ_API = 'https://api.frankerfacez.com/' FFZ_EMOTE_URL = 'http://www.frankerfacez.com/emoticons/{}' USER_AGENT = "rainbodl (https://github.com/codl/rainbodl)" HEADERS = {'User-Ag...
StarcoderdataPython
4937960
<filename>catcoin/xtn.py from __future__ import print_function import os, sys, time, toolz, traceback as tb from catcoin.api import * PID_FNAME = 'xtn.pid' def init(): connect(); xconnect() def cb(msg): xid = scrape_xid(msg) if db_get(xid): print("Transaction already exists, discarding . . .") ...
StarcoderdataPython
12863757
############################################################################### # Copyright 2019 <NAME>. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including witho...
StarcoderdataPython
9615789
from typing import ( Callable, Union, List, Optional, Dict, Any, Type, Mapping ) from functools import wraps from collections.abc import Mapping as ABCMapping from flask import Response, jsonify, current_app from webargs.flaskparser import FlaskParser as BaseFlaskParser from marshmallow import ValidationError ...
StarcoderdataPython
6607783
<gh_stars>0 # -*- coding: utf-8 -*- """ Created on Mon Aug 30 11:22:14 2021 @author: <NAME> """ def skriv_firkant(hoyde=5, bredde=5, tegn="*"): for j in range(hoyde): for i in range(bredde): print(tegn, end="") print() hoyde = int(input("Høyde: ")) bredde = int(input("Br...
StarcoderdataPython
11354030
<filename>custom_api/core/serializers.py from django.db import models from django.db.models import fields from rest_framework import serializers from .models import Post class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = { 'title','description' ...
StarcoderdataPython
1864064
test = { 'name': 'q2_1', 'points': 1, 'suites': [ { 'cases': [ {'code': '>>> prof_names.num_columns == 2\nTrue', 'hidden': False, 'locked': False}, {'code': '>>> prof_names.num_rows == 71\nTrue', 'hidden': False, 'locked': False}, { ...
StarcoderdataPython
6563923
import threading from pathlib import Path from alembic import command from alembic.config import Config from alembic.util.exc import CommandError from sqlalchemy import create_engine from sqlalchemy import event from sqlalchemy.engine import Engine from sqlalchemy.exc import OperationalError from sqlalchemy.orm import...
StarcoderdataPython
6662119
<filename>feature_gen/vgg.py ''' Modified from https://github.com/pytorch/vision.git ''' import math import torch import torch.nn as nn import torch.nn.init as init import torch.nn.functional as F __all__ = ['VGG', 'vgg', 'vgg_s', 'fc', 'resnet'] IN_CHANNELS = 3 CLASSES = 10 class VGG(nn.Module): ''' VGG mo...
StarcoderdataPython
102109
""" funcio def aplicar(valor1, valor2, operacio) ef operacio (): resultat = input( ' Quina operació vols fer?? (multiplicar sumar o restar) \n' ) return resultat return varo1 operacio valor2 """ #Definició def operacionvalores (valor1,valor2,operacion) : if operacion == "sumar": resultat = va...
StarcoderdataPython
6495669
from werkzeug.security import generate_password_hash, check_password_hash from flask_login import UserMixin from app import db class Account(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(10), unique=True, nullable=False) email = db.Column(db.String(30)) ...
StarcoderdataPython
3222921
import voluptuous as vol from esphome import pins from esphome.components import light from esphome.components.light import AddressableLight from esphome.components.power_supply import PowerSupplyComponent import esphome.config_validation as cv from esphome.const import CONF_CLOCK_PIN, CONF_COLOR_CORRECT, CONF_DATA_PI...
StarcoderdataPython
3285655
from marmot.features.feature_extractor import FeatureExtractor from marmot.util.ngram_window_extractor import left_context, right_context class PairedFeatureExtractor(FeatureExtractor): ''' Paired features: - target token + left context - target token + right context - target token + s...
StarcoderdataPython
9772431
<filename>test/test_generation.py # Note: This file was taken mostly as is from the svg.path module (v 2.0) #------------------------------------------------------------------------------ from __future__ import division, absolute_import, print_function import unittest from svgpathtools import * class TestGeneration(u...
StarcoderdataPython
1624312
<gh_stars>0 import requests from bs4 import BeautifulSoup import json def getTitle(id=1): url = f"https://www.handspeak.com/word/search/index.php?id={id}" get_url = requests.get(url) get_text = get_url.text soup = BeautifulSoup(get_text, "html.parser") title = list(soup.select('h1')[0].text.strip(...
StarcoderdataPython
6649554
<reponame>Cal-CS-61A-Staff/examtool from os import getenv from examtool.api.server_delegate import server_only from examtool.api.utils import as_list if getenv("ENV") == "SERVER": from google.cloud import firestore from google.cloud.exceptions import NotFound BATCH_SIZE = 400 assert BATCH_SIZE < 500 def cl...
StarcoderdataPython
5104266
<gh_stars>0 import numpy as np from keras import Sequential from keras.layers import Lambda, Conv2D, BatchNormalization, Activation, MaxPooling2D, Dropout, GlobalAveragePooling2D, \ Dense from mydeep_api.dataset.numpy_column import NumpyColumn from mydeep_keras.k_model import KModel, KFitConfig def test_fit(): ...
StarcoderdataPython
3590362
"""Team prize test""" import datetime from django.contrib.auth.models import User from django.test import TransactionTestCase from apps.managers.team_mgr.models import Group, Team from apps.utils import test_utils from apps.managers.challenge_mgr.models import RoundSetting class DormTeamPrizeTests(TransactionTestCas...
StarcoderdataPython
6484262
#87671-<NAME> 87693-<NAME> Grupo 15 # -*- coding: utf-8 -*- """ Created on Mon Oct 16 20:31:54 2017 @author: mlopes """ import numpy as np import random from tempfile import TemporaryFile outfile = TemporaryFile() class finiteMDP: def __init__(self, nS, nA, gamma, P=[], R=[], absorv=[]): self.nS = nS #...
StarcoderdataPython
9621135
def replace_project_name(project_name): # Read in the file files = ['./app/templates/base.html', './app/templates/auth/login.html', './app/templates/main/index.html'] for file in files: with open(file, 'r') as f: filedata = f.read() # Replace the target string filedata =...
StarcoderdataPython
8076694
from datetime import datetime from django.http import HttpRequest from django.test import TestCase from django.utils.crypto import get_random_string from zentral.core.events.base import BaseEvent, EventMetadata from zentral.core.incidents.events import (IncidentCreatedEvent, IncidentSeverityUpdatedEvent, ...
StarcoderdataPython
239517
<filename>tests/test_mcpython/common/block/test_Barrel.py """ mcpython - a minecraft clone written in python licenced under the MIT-licence (https://github.com/mcpython4-coding/core) Contributors: uuk, xkcdjerry (inactive) Based on the game of fogleman (https://github.com/fogleman/Minecraft), licenced under the MIT-...
StarcoderdataPython
6561377
# Copyright 2019 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-2.0 # # Unless required by applicable law or agreed to in wri...
StarcoderdataPython
12810370
from scipy.optimize import minimize from .measure.measure_sample import dst,hst,dst_source from .measure.measure_sim import sep_purity, fid_ref, c_entropy def vcirc_test( x, statein, vcirc, test_func=sep_purity, ansatz_li=None, update=False, *args, **kw...
StarcoderdataPython
11290678
<reponame>boweyism/devops-for-data from src.jobs.word_count import get_keyval, run def test_get_keyval(): words = ['this', 'are', 'words', 'words'] expected_results = [['this', 1], ['are', 1], ['words', 1], ['words', 1]] assert expected_results == get_keyval(words) def test_word_count_run(spark_session...
StarcoderdataPython
11284422
<reponame>Nic30/libEveryPacketClassifier<filename>tests/benchmark_graph_gen.py import json from os import listdir import os from typing import List, Tuple import matplotlib.pyplot as plt from tests.constants import RULESET_ROOT # @lru_cache(maxsize=512) def get_real_rule_cnt(ruleset:str, rule_cnt:str): with open...
StarcoderdataPython
6672373
# 24. 两两交换链表中的节点 # 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 # 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 # 示例: # 给定 1->2->3->4, 你应该返回 2->1->4->3. # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def swapPairs(self, head: ListNode) -> List...
StarcoderdataPython
220229
from raw_preprocessing.preprocessor import run_parse if __name__ == '__main__': run_parse(10)
StarcoderdataPython
6702647
# coding=utf-8 # *** WARNING: this file was generated by pulumigen. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** from . import _utilities import typing # Export this package's modules as members: from .kustomize import * from .provider import * from .yaml import * # Make subpac...
StarcoderdataPython
4919645
"""Utility module for system checks""" import subprocess def check_fsl(): """ This function checks for the correct installation of freesurfer. It does so by calling 'freesurfer' to the main terminal and checking for errors. """ # Initialize test vars test_ok = True error_msg = "" ...
StarcoderdataPython
179833
<gh_stars>0 __author__ = '<NAME>' import MySQLdb as mdb def retrieve_connection(db): """ Retrieves Database connection object for a given connection parameters. :param db: Json object containing connection parameters :type db: dict :return: MySQLDB.Connection object """ con = mdb.connect...
StarcoderdataPython
3504464
from .base import BrokerBase from .context import TradingContext from .broker import CryptoBroker from .backtest import BacktestBroker from .dryrun import DryrunBroker
StarcoderdataPython
3419524
'/a/b/c'
StarcoderdataPython
6621204
<gh_stars>0 # SPDX-FileCopyrightText: 2021 <NAME> <<EMAIL>> # # SPDX-License-Identifier: MIT import glob import os import shutil import subprocess import xarray as xr from termcolor import cprint from trace_for_guess.skip import skip def calculate_fsdscl(cldtot_file, fsds_file, fsdsc_file, out_file): """Re-con...
StarcoderdataPython
9625489
<reponame>Claayton/ExerciciosPython # Ex029.2 """Write a program that reads the speed of car If he exceeds the speed of 80km/h, show a message saying that he was fined The fine will coast R$:7.00 for each km above the limit""" print('=-'*15) print('\033[31mRADAR MY FINE, MY LIFE, SPEED LIMIT: 80Km/h\033[m') print('=-'...
StarcoderdataPython
4970374
# Copyright (C) 2019 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """Integration test for Assessment object sync cron job.""" import ddt import mock from ggrc import settings from ggrc.integrations.synchronization_jobs import assessment_sync_job from ggrc.integrations.sy...
StarcoderdataPython
12862133
<gh_stars>0 # This an autogenerated file # # Generated with CRSAxialFrictionModel from typing import Dict,Sequence,List from dmt.entity import Entity from dmt.blueprint import Blueprint from .blueprints.crsaxialfrictionmodel import CRSAxialFrictionModelBlueprint from typing import Dict from sima.sima.moao import MOAO ...
StarcoderdataPython
1796049
<filename>src/the_tale/the_tale/game/abilities/tests/test_requests.py import smart_imports smart_imports.all() class AbilityRequests(utils_testcase.TestCase): def setUp(self): super(AbilityRequests, self).setUp() game_logic.create_test_map() self.account = self.accounts_factory.create...
StarcoderdataPython
6431506
import numpy as np import torch from .cut_model import CUTModel from . import networks from .patchnce import PatchNCELoss import util.util as util from .modules import loss import torch.nn.functional as F from util.util import gaussian from util.iter_calculator import IterCalculator from util.network_group import Netwo...
StarcoderdataPython
6498011
<reponame>royalbhati/fastai import torch import torch.nn as nn from torch.autograd import Variable from functools import reduce class LambdaBase(nn.Sequential): def __init__(self, fn, *args): super(LambdaBase, self).__init__(*args) self.lambda_func = fn def forward_prepare(self, input): ...
StarcoderdataPython
349031
<filename>src/tests/comments/test_comment.py<gh_stars>0 from django.test import TestCase from comments.models import Comment from articles.models import Article from django.contrib.auth.models import User class CommentTestCase(TestCase): admin = None def set_up_user(self): user=User.objects.create_us...
StarcoderdataPython
6605717
import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../src'))) from api_key_loader import ApiKeyLoader from env_loader import EnvLoader from ingredients_input import IngredientsInput from search_recipes_by_ingredients import SearchRecipesByIngredients from recipe_view impor...
StarcoderdataPython
4871694
<gh_stars>1-10 import netifaces print("Finding your Interface.....") list_of_interfaces = netifaces.interfaces() print(list_of_interfaces) def interface(): interf = input("Enter your interface:") if interf in list_of_interfaces: return interf else: print("Interface not found be sure...
StarcoderdataPython
114963
#!/usr/bin/env python import os import ssl import sys import json import redis import asyncio import websockets from datetime import datetime LOG_FILE="/var/log/honeybot.log" if not os.environ["HB_ID"]: log("{} [ERROR] HB_ID environment variable is not set".format(str(datetime.now()))) sys.exit("HB_ID environ...
StarcoderdataPython
3302805
<reponame>DongjunLee/kino-bot<filename>kino/notifier/scheduler.py<gh_stars>100-1000 # -*- coding: utf-8 -*- import json import random from .skill_list import SkillList from .between import Between from ..functions import RegisteredFuctions from ..slack.resource import MsgResource from ..slack.slackbot import Slack...
StarcoderdataPython
9799184
from dateparser import parse from datetime import datetime, timedelta import re import iwant_bot.pipeline class IwantRequest(object): """Valid iwant command create this object, which extracts information with /iwant requests. Other_words are expected words in the user message, which should be removed before d...
StarcoderdataPython
3398787
<reponame>AI0702/Among-Us-clone<filename>settings.py<gh_stars>0 import pygame # define some colors (R, G, B) WHITE = (255, 255, 255) BLACK = (0, 0, 0) SKYBLUE = (135, 206, 235) DARKGREY = (40, 40, 40) LIGHTGREY = (100, 100, 100) GREEN = (0, 255, 0) RED = (255, 0, 0) YELLOW = (255, 255, 0) Orange = (255, 165, 0) Brown ...
StarcoderdataPython
5078369
<gh_stars>0 # flake8: noqa from .client import Client from .compatpatch import ClientCompatPatch from .endpoints.common import MediaTypes from .endpoints.upload import MediaRatios from .errors import ( ClientError, ClientLoginError, ClientLoginRequiredError, ClientCookieExpiredError, ClientThrottledError, Clie...
StarcoderdataPython
1677334
from unittest import TestCase from unittest.mock import MagicMock from giru.core.commands import Julien from giru.core.commands import julien as JULIEN_PICTURES from tests.mixins import CommandTestCaseMixin class JulienCommandTestCase(CommandTestCaseMixin, TestCase): def test_it_sends_a_photo(self): expe...
StarcoderdataPython
8100821
<filename>block.py from ursina import * from ursina import curve # Normal Block Class class NormalBlock(Entity): def __init__(self, position = (0, 0, 0), rotation = (0, 0, 0), scale = (5, 0.8, 5)): super().__init__( model = "cube", scale = scale, color = "#AFFF3C", ...
StarcoderdataPython
5004233
import login from BioSimSpaceCloud import ObjectStore as objstore import datetime import sys bucket = login.login() key = sys.argv[1] try: filename = sys.argv[2] except: filename = None if filename: objstore.get_object_as_file(bucket, key, filename) else: data = objstore.get_string_object(bucket, ...
StarcoderdataPython
179865
<gh_stars>0 import os from scope_plot.specification import Specification FIXTURES_DIR = os.path.join( os.path.dirname(os.path.realpath(__file__)), "..", "__fixtures") def test_bokeh_errorbar_spec(): figure_spec = Specification.load_yaml( os.path.join(FIXTURES_DIR, "bokeh_errorbar.yml")) assert fi...
StarcoderdataPython
1864927
""" Officially supported builder workflows """ import aws_lambda_builders.workflows.python_pip import aws_lambda_builders.workflows.nodejs_npm import aws_lambda_builders.workflows.ruby_bundler import aws_lambda_builders.workflows.go_dep import aws_lambda_builders.workflows.go_modules import aws_lambda_builders.workflo...
StarcoderdataPython
9722245
import os def tru(val): return val def notdefault(val): return val if val != 'default' else None def is_subdir(path, directory): path = os.path.realpath(path) directory = os.path.realpath(directory) relative = os.path.relpath(path, directory) return not (relative == os.pardir or relative.s...
StarcoderdataPython
65801
n = [ 1 ] + [ 50 ] * 10 + [ 1 ] with open('8.in', 'r') as f: totn, m, k, op = [ int(x) for x in f.readline().split() ] for i in range(m): f.readline() for i, v in enumerate(n): with open('p%d.in' % i, 'w') as o: o.write('%d 0 %d 2\n' % (v, k)) for j in range(v): ...
StarcoderdataPython
5073955
<reponame>lucaskup/VizFracSet # -*- coding: utf-8 -*- """ Created on Fri Jun 26 18:22:52 2020 @author: LKUPSSINSKU """ #to install the library: #pip install git+https://github.com/philferriere/cocoapi.git#subdirectory=PythonAPI from pycocotools.coco import COCO import numpy as np import imageio as io dataDir='../da...
StarcoderdataPython
8146340
# import python from abc import ABC # import genie from genie.conf.base.config import CliConfig from genie.conf.base.cli import CliConfigBuilder from genie.conf.base.attributes import UnsupportedAttributeWarning, \ AttributesHelper class Pim(ABC): class DeviceAttributes(A...
StarcoderdataPython
5064619
import random import numpy as np from itertools import combinations import torch import torch.nn.functional as F random.seed(0) def get_random_triplets(embeddings) -> torch.Tensor: ''' For each image in data (Anchor), randomly sample a Positive image from its class. Then from each of the other classes ...
StarcoderdataPython
5129909
# # Generic classes for the sector implementation in subtraction schemes # import commons.generic_sectors as generic_sectors import madgraph.various.misc as misc class Sector(generic_sectors.GenericSector): """ Class implementing a particular sector, with attributes identifying it and methods for its evaluat...
StarcoderdataPython
1927500
<gh_stars>0 '''Example 09 Shows how to embed visvis figures in a wxPython GUI. Visvis can also be embedded in Qt4 (PyQt), GTK, and FLTK. Based on http://code.google.com/p/visvis/wiki/example_embeddingInWx ''' import wx from pycalfem import * from pycalfem_utils import * from pycalfem_mesh import * import pycalfem_vis...
StarcoderdataPython
9648406
<reponame>Sigmanificient/codewars<gh_stars>1-10 """Kata url: https://www.codewars.com/kata/55d24f55d7dd296eb9000030.""" def summation(num: int) -> int: return sum(range(1, num + 1))
StarcoderdataPython
6702496
<filename>anno/managers.py<gh_stars>0 from django.db.models import Manager from django.db.models import Q class SearchManager(Manager): '''builds Q expression for `platform` annotation property. to build a custom search, extend this class and override the 'search_expression' method. ''' def sear...
StarcoderdataPython
301614
""" Position controller module. """ import math from highlevel.logger import LOGGER from highlevel.robot.entity.configuration import Configuration from highlevel.util.filter.odometry import OdometryFunc from highlevel.util.geometry.vector import Vector2 from highlevel.util.probe import Probe from highlevel.util.type i...
StarcoderdataPython
11302433
<reponame>Henrique-Sc/cursoemvideo-python pessoa = ('Henrique', 15, 'M', 45) lanche = 'Hambúguer' del pessoa # Apaga da memória qualquer variavel selecionada print(pessoa)
StarcoderdataPython
105721
<reponame>MHelena45/feup-iope import math from gurobipy import * d={} d={ ("Doce","Doce"): 0, ("Doce","Bom"):math.inf, ("Doce","Sky"):6000, ("Doce","Moon"):5000, ("Doce","Mars"):5500, ("Bom","Doce"):math.inf, ("Bom","Bom"):0, ("Bom","Sky"): 6000, ("Bom","Moon"): 5800, ("Bom","Mars"):4800, ("Sky","Doce"): ...
StarcoderdataPython
6522444
''' Finite State Machine algorithm used to assess score of Python found in statements of the form 'Python is ___'. The 2 possible scores are 'positive' and 'negative'. Reference: http://www.python-course.eu/finite_state_machine.php +--------------+-------------+--------------+ | From State | Input | To State...
StarcoderdataPython
5124082
from zope.interface import Interface from guillotina.fields.annotation import BucketListField class IVersioning(Interface): diffs = BucketListField(readonly=True, annotation_prefix="diffs-", bucket_len=5) class IVersioningMarker(Interface): """Marker interface an object is Versioning""" class IDiffCalcula...
StarcoderdataPython
8018331
<filename>tests/test_hybrid.py """ test_hybrid: unit tests for Hybrid <NAME> <<EMAIL>> Copyright 2020-2021, <NAME> License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0) """ import dataclasses import sourdough @dataclasses.dataclass class AnElement(sourdough.quirks.Element): pass @dataclasses.datac...
StarcoderdataPython
1790682
<gh_stars>1-10 from flask import Blueprint, request, jsonify from flask import current_app as app from flask_pymongo import PyMongo import pymongo, ssl, sys, json from bson.json_util import dumps import uuid user_roles_bp = Blueprint('user_roles', __name__) @user_roles_bp.route('/roles', methods=['GET']) def roles():...
StarcoderdataPython