id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
4805318
<reponame>ian0/ARC """NUI Galway CT5132/CT5148 Programming and Tools for AI (<NAME>) Solution for Assignment 3: File ed36ccf7.json Student name(s): <NAME> Student ID(s): 12100610 """ import numpy as np import sys from common_utils import load_file, print_grid def solve(grid): """ Given the input grid fro...
StarcoderdataPython
133876
<filename>raft/node.py import os import json import time import random import logging from .log import Log from .rpc import Rpc from .config import config # logging.basicConfig(level=logging.INFO, # format='%(asctime)s %(levelname)s %(name)s %(funcName)s [line:%(lineno)d] %(message)s') logger = l...
StarcoderdataPython
3362947
<filename>ail/wrapper/vev_norm_wrapper.py import math from copy import deepcopy from typing import Dict, Union import gym import numpy as np from ail.common.running_stats import RunningMeanStd from ail.common.type_alias import GymEnv, GymStepReturn class VecNormalize(gym.Wrapper): """ A moving average, nor...
StarcoderdataPython
3311378
from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator from .models import * from .forms import ToolForm # Create your views here. @login_required() def index(request): # GETアクセス時の処理 tools = Tool.objects.all() para...
StarcoderdataPython
3286607
<reponame>yurithebest1/vision4j-collection<filename>external/keras-vgg16-classification/classifier.py from keras.applications.vgg16 import VGG16 from keras.applications.vgg16 import preprocess_input from keras.preprocessing import image from time import time from PIL import Image import numpy as np import cv2 import te...
StarcoderdataPython
145236
from flask import Flask, render_template, request, session from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt from flask_login import LoginManager from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from flask_babel import Babel import os from .config import Develop...
StarcoderdataPython
3234662
class Solution: def divide(self, dividend: int, divisor: int) -> int: if divisor == 0: return None diff_sign = (divisor < 0) ^ (dividend < 0) dividend = abs(dividend) divisor = abs(divisor) result = 0 max_divisor = divisor shift_count = 1 ...
StarcoderdataPython
1621489
import pandas as pd import numpy as np import seaborn as sns from matplotlib import gridspec import matplotlib.pyplot as plt from sklearn.manifold import TSNE from drosoph_vae.data_loading import get_3d_columns_names from drosoph_vae.settings import config, skeleton from drosoph_vae.settings.config import SetupConfig ...
StarcoderdataPython
1790203
<filename>src/regnet/tests/test_train.py<gh_stars>0 # from src.regnet.models.train_model import train_with_params # def test_train(): # train_with_params(epochs=1)
StarcoderdataPython
180018
# -*- coding: utf-8 -*- import json # jsonfy search result import psycopg2 import sys # sys.exit() import ldap3 as ldap # ldap connection request from ldap3 import Server,Connection , NTLM, ALL, MODIFY_ADD, MODIFY_REPLACE try: con_db = psycopg2.connect(database='localmap-dev', user='localmap-dev', host='laura.de...
StarcoderdataPython
138889
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
StarcoderdataPython
1768174
import pytest from solution import solution @pytest.mark.parametrize( ["A", "res"], [ ([2, 1, 4, 5, 6, 7, 9, 8], 3), ([1, 2, 4, 5, 3, 9, 8, 7], 6) ] ) def test_solution(A, res): assert solution(A) == res
StarcoderdataPython
186563
import logging from django.core.management.base import BaseCommand from product.models import Shop logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'This command create sample instances of model `Shop` into DB.' def get_model(self): model = Shop return model def...
StarcoderdataPython
3342809
""" AWS API-Gateway Authorizer ========================== This authorizer is designed to be attached to an AWS API-Gateway, as a Lambda authorizer. It assumes that AWS Cognito is used to authenticate a client (UI) and then API requests will pass a JSON Web Token to be validated for authorization of API method calls. ...
StarcoderdataPython
3204263
# import tensorflow as tf # # embedding_table = tf.Variable(initial_value=None,name="embedding_table") # # Add ops to save and restore all the variables. # saver = tf.compat.v1.train.Saver({"embedding_table": embedding_table}) # # # Later, launch the model, use the saver to restore variables from disk, and # # do some ...
StarcoderdataPython
19920
<gh_stars>0 __author__ = 'sibirrer' # this file contains a class to make a Moffat profile __all__ = ['Moffat'] class Moffat(object): """ this class contains functions to evaluate a Moffat surface brightness profile .. math:: I(r) = I_0 * (1 + (r/\\alpha)^2)^{-\\beta} with :math:`I_0 = amp...
StarcoderdataPython
3384726
<reponame>rtraas/morpy<gh_stars>0 import rebound as rb import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt def perspective(sim,savename=None): #fig = rb.OrbitPlot(sim,slices=0.5,xlim=[-5.,5],ylim=[-5.,5]) fig = rb.OrbitPlot(sim,slices=0.5) if savename is not None: plt.savefig(sa...
StarcoderdataPython
3353327
import tensorflow as tf import tensorflow.contrib.layers as layers import numpy as np import chess from chess_env import FULL_CHESS_INPUT_SHAPE # A convolutional block as described in AlphaGo Zero def conv_block(tensor, specs): tensor = layers.convolution2d(tensor, num_outputs=...
StarcoderdataPython
1644568
<reponame>rgerganov/mykioxi #!/usr/bin/env python3 import datetime import asyncio import argparse import sys import bleak CHARACTERISTIC_UUID = "49535343-1e4d-4bd9-ba61-23c647249616" class DataPrinter: def __init__(self): self.last_bpm = -1 self.last_spo2 = -1 self.last_pleth = -1 de...
StarcoderdataPython
1773806
# Google from googletrans import Translator # Comment en faire: Dans la main: get_main_args = analyzer_input_args() # input_excel_name = get_main_args.input_ecelname etc.. def analyzer_input_args(): parser = argparse.ArgumentParser(description='Game Simulation Parameters') ...
StarcoderdataPython
3396671
<filename>scripts/check_latex_spelling.py import argparse, os # incorrect -> correct corrections = { "pointcloud" : "point cloud", "Pointcloud" : "Point cloud", "voxelgrid" : "voxel grid", "Voxelgrid" : "Voxel grid", "levelset" : "level set", "Levelset" : "Level set", "ray-trac" : "raytrac",...
StarcoderdataPython
76079
""" Splits the given Manga Volume CBZ into the CBZs of the individual chapters """ import re import shutil import zipfile from collections import defaultdict from operator import attrgetter from pathlib import Path root = Path("/path/to/volumes/") output = root / "chapters" CHAP_PAT = re.compile(r"c(?P<num>\d{3})") ...
StarcoderdataPython
167988
class Constants: ha2kcalmol = 627.509 # Hartee^-1 kcal mol^-1 ha2kJmol = 2625.50 # Hartree^-1 kJ mol^-1 eV2ha = 0.0367493 # Hartree ev^-1 a02ang = 0.529177 # Å bohr^-1 ang2a0 = 1.0 / a02ang # bohr Å^-1 kcal2kJ = 4.184 # kJ kcal^-1
StarcoderdataPython
4822177
import unittest from jump_game_iv import Solution class Test(unittest.TestCase): def test_1(self): solution = Solution() self.assertEqual( solution.minJumps([100, -23, -23, 404, 100, 23, 23, 23, 3, 404]), 3 ) def test_2(self): solution = Solution() self.as...
StarcoderdataPython
3256324
<filename>Core/Logic/FJudgementCompiler.py # Copyright (c) 2012 The Khronos Group Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation th...
StarcoderdataPython
1625572
<reponame>sylvielamythepaut/climetlab # (C) Copyright 2020 ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtu...
StarcoderdataPython
3394522
num = int(input('Digite um número natural (até milhar): ')) n = str(num) print(""" Analisando o número: {} Unidade: {} Dezena: {} Centena: {} Milhar: {} """ .format(num, n[3],n[2],n[1],n[0]))
StarcoderdataPython
3367251
from setuptools import setup # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='testfun...
StarcoderdataPython
1654581
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from DataJoin.common import common_pb2 as DataJoin_dot_common_dot_common__pb2 from DataJoin.common import data_join_service_pb2 as DataJoin_dot_common_dot_data__join__service__pb2 from google.protobuf import empty_pb2 as google_dot_proto...
StarcoderdataPython
9822
<filename>pywallet/network.py class BitcoinGoldMainNet(object): """Bitcoin Gold MainNet version bytes. """ NAME = "Bitcoin Gold Main Net" COIN = "BTG" SCRIPT_ADDRESS = 0x17 # int(0x17) = 23 PUBKEY_ADDRESS = 0x26 # int(0x26) = 38 # Used to create payment addresses SECRET_KEY = 0x80 # int(...
StarcoderdataPython
4801806
import collections fruit = collections.Counter(['apple', 'orange', 'pear', 'apple', 'orange', 'apple']) print(fruit) print(fruit['orange']) print('fruit.most_common(1):', fruit.most_common(1)) fruit1 = collections.Counter(['apple', 'orange', 'pear', 'orange']) fruit2 = collections.Counter(['banana', 'apple', 'apple'...
StarcoderdataPython
3322310
"""Module for development/debugging execution of the Web Service In production the service will probably be executed using asgi in a proper webserving environment in a container. This file can be used for development/testing/debugging of the webservice using uvicorn as development web server. Usage: Call with activa...
StarcoderdataPython
3365697
# Copyright (c) 2011 Tencent Inc. # All rights reserved. # # Author: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # Date: October 20, 2011 """ This is the scons rules helper module which should be imported by Scons script """ import os import shutil import s...
StarcoderdataPython
1649042
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals THEME = "themes/Flex" AUTHOR = "<NAME>" SITENAME = "<NAME>" DOMAIN = "http://localhost:8000" PATH = "content" TIMEZONE = "Asia/Kathmandu" DEFAULT_LANG = "en" THEME_COLOR_ENABLE_USER_OVERRIDE = True # Feed generation is usual...
StarcoderdataPython
117467
# -*- coding: utf-8 -*- """ canteen ~~~~~~~ a minimal web framework for the modern web :author: <NAME> <<EMAIL>> :copyright: (c) <NAME>, 2014 :license: This software makes use of the MIT Open Source License. A copy of this license is included as ``LICENSE.md`` in the root of the ...
StarcoderdataPython
161358
<reponame>teddy4445/lecture_website_app_generator import zipfile import sys import os from web_logic.github_pages_manager import GithubPagesManager def create_new_user(user_name) -> None: # TODO: insert user to DB pass manager = GithubPagesManager() dir_path = '\\'.join([manager.users_websites_folde...
StarcoderdataPython
3304640
#!/usr/bin/env python3 """ Data-transformer-app. 1. Grub CSV files located in ./data/original_data folder with SaveEcoBot structure (device_id,phenomenon,value,logged_at,value_text). 2. Separate CSV files per device_id and sensor type (phenomenon) and write result to ./data/csv/*.csv files. 3. Transform data f...
StarcoderdataPython
3399978
<reponame>mikofski/solar-data-tools # -*- coding: utf-8 -*- ''' Utilities Module This module contains utility function used by other modules. ''' import sys import numpy as np import cvxpy as cvx def total_variation_filter(signal, C=5): ''' This function performs total variation filtering or denoising on a 1...
StarcoderdataPython
4839751
<gh_stars>0 from unet.unet_base_binary_arch import * IMG_HEIGHT = IMG_WIDTH = 256 IMG_CHANNELS = 3 def retMask(img, weights_path): """Return mask given image aand weights path""" # Below line needed only if weights are to be loaded and not the entire model. #model = uNet() model=load_model(weights_path, custom_ob...
StarcoderdataPython
40100
# -*- coding: utf-8 -*- # Copyright 2013-2014 Eucalyptus Systems, Inc. # # Redistribution and use of this software 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 notice, # this...
StarcoderdataPython
3308174
import requests from connection.connection_variables import link_for_rebill from parameters.subscription.case_1.subsciption_params import * from parameters.rebill.case_1.rebill_params import * from parameters.cancel.case_1.cancel_params import * def case_one_subscription(): return requests.get(link_for_rebill, ca...
StarcoderdataPython
1735158
""" Cubicle is a high-level language for describing the structure, formatting, and boilerplate for tabular reports (and perhaps eventually also charts), combined with an API for populating and emitting these via xlsxwriter. """ from . import compiler, dynamic, runtime, version from .version import __version__, __versi...
StarcoderdataPython
3360434
from os import environ import sys from dotenv import load_dotenv from explorerClient.eth import ETHExplorerClient if __name__ == "__main__": load_dotenv() # client = ETHExplorerClient.create(rpc_endpoint=str(environ.get("APP_API_CLIENT_INFURA_RPC_ENDPOINT")) client = ETHExplorerClient.create(rpc_endpoint...
StarcoderdataPython
190038
<filename>servi-bench/benchmarks_old/cpustress/google/nodejs/cpustress_benchmark.py import os from timeit import default_timer as timer def setup(): os.system('sls deploy') # TODO: need a harness-supported way of injecting credentials for all sls calls # os.system('sls deploy --credentials=/path/to/credent...
StarcoderdataPython
3333558
from flask_wtf import FlaskForm from wtforms import SubmitField, SelectField class TagSetupForm0(FlaskForm): submit = SubmitField("Parse Part 1") class TagSetupForm1(FlaskForm): submit = SubmitField("Parse Part 2") class NewNationForm(FlaskForm): select = SelectField("Add Nation") submit = SubmitFie...
StarcoderdataPython
27434
# -*- coding: utf-8 -*- """ Created on Fri Nov 30 13:44:34 2018 @author: Moha-Thinkpad """ from tensorflow.keras import optimizers from tensorflow.keras.models import Model import datetime import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import tensorflow.keras import argpa...
StarcoderdataPython
1747194
<gh_stars>10-100 # ==BEGIN LICENSE== # # MIT License # # Copyright (c) 2018 SRI Lab, ETH Zurich # # 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 lim...
StarcoderdataPython
131228
# -*- coding: utf-8 -*- from app.constants import S_OK, S_ERR import random import math import base64 import time import ujson as json import sys import argparse from app import cfg from app import util def cron_chiayi_city(): pass def parse_args(): ''' ''' parser = argparse.ArgumentParser(description...
StarcoderdataPython
156366
<reponame>PsiPhiTheta/LeetCode class Solution: def reverseString(self, s): """ :type s: str :rtype: str """ output = list(s) output = output[::-1] output = "".join(output) return output
StarcoderdataPython
1675258
<gh_stars>1-10 #!/usr/bin/env python3 # -*- coding:utf-8 -*- """ new_task.py to allow arbitrary messages to be sent from the command line. This program will schedule tasks to our work queue. The main idea behind Work Queues is to avoid doing a resource-intensive task immediately and having to wait for it to complete. ...
StarcoderdataPython
3288852
# ***** BEGIN GPL LICENSE BLOCK ***** # # Script copyright (C) <NAME> # # This program 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 the License, or (at your option) any later version. ...
StarcoderdataPython
62835
<reponame>netrack/bayes import aiofiles import asyncio import io import pathlib import tarfile import shutil from typing import IO def run(main): loop = asyncio.new_event_loop() try: return loop.run_until_complete(main) finally: loop.close() async def reader(path: pathlib.Path, chunk_si...
StarcoderdataPython
31492
<reponame>wallisyan/alibabacloud-python-sdk-v2<gh_stars>0 # Copyright 2018 Alibaba Cloud Inc. 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...
StarcoderdataPython
3230337
import unittest from User import User class TestUser(unittest.TestCase): def setUp(self): self.new_user = User("John","Paul") def tearDown(self): ''' clean up after each test to prevent errors ''' User.userList = [] #2nd test def test__init(self): ...
StarcoderdataPython
187726
<filename>flashnrf.py """ This file contains example code meant to be used in order to test the pynrfjprog API and Hex. If multiple devices are connected, pop-up will appear. Sample program: program_hex.py Requires nrf51-DK or nrf52-DK for visual confirmation (LEDs). Run from command line...
StarcoderdataPython
38870
<reponame>qorrect/sisy ''' Created on Feb 7, 2017 @author: julien ''' import unittest from keras.layers.core import Dense from minos.experiment.experiment import ExperimentParameters, Experiment,\ check_experiment_parameters, InvalidParametersException from minos.experiment.training import Training from minos.mo...
StarcoderdataPython
4840524
import datetime def return_dif(target_year, target_mont, target_day): today = datetime.date.today() targer = datetime.date(int(target_year), int(target_mont), int(target_day)) if targer < today: output_day = today - targer print('Эта дата уже наступила и прошла', output_day.days) r...
StarcoderdataPython
160175
<filename>setup.py<gh_stars>0 from distutils.core import setup setup( name='Model Generator', version='1', packages=['generator'], license='MIT', long_description='Project to generate model for Whisper product' )
StarcoderdataPython
3361944
from __future__ import absolute_import, unicode_literals from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.forms import SetPasswordForm from django.contrib.auth.models import Group from django.contrib.contenttypes.models import ContentType from django.core.exce...
StarcoderdataPython
26900
<reponame>rancp/ducktape-docs # Copyright 2016 Confluent Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
StarcoderdataPython
9639
<reponame>cirobarradov/kafka-connect-hdfs-datalab<filename>kafka-connect-azblob/docs/autoreload.py #!/usr/bin/env python from livereload import Server, shell server = Server() server.watch('*.rst', shell('make html')) server.serve()
StarcoderdataPython
4813204
<filename>ProblemSet1/FileCreator/create2Drules.py f= open("ProblemSet1/gameOfLife.txt","w+") get_bin = lambda x, n: format(x, 'b').zfill(n) for i in range(512): bistr = get_bin(i, 9) numneig = bistr.count('1') if bistr[4] == '1': if numneig < 3 or numneig > 4: bistr = bistr +...
StarcoderdataPython
1659810
<reponame>jiupinjia/neural-magic-eye import argparse import numpy as np import matplotlib.pyplot as plt import datasets from neural_decoder import * # settings parser = argparse.ArgumentParser() parser.add_argument('--dataset', type=str, default='mnist', metavar='str', help='dataset name f...
StarcoderdataPython
1612298
<gh_stars>0 """ pearlmemory is a variation of french-genanki-jupyter made for German learners. Copyright (C) 2020 errbufferoverfl. This program 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 3 o...
StarcoderdataPython
1730604
from unittest import TestCase from parameterized import parameterized from src.util.load_data import load_data from src.year2021.day22 import Cuboid, part_1, part_2, prepare_data from test.decorators import sample data = load_data(2021, 22) @sample class Test2021Day22Samples(TestCase): prepared_data: list[li...
StarcoderdataPython
1725868
<filename>rssant_common/blacklist.py<gh_stars>0 import re from urllib.parse import urlparse def _parse_blacklist(text): lines = set() for line in text.strip().splitlines(): if line.strip(): lines.add(line.strip()) items = [] for line in list(sorted(lines)): items.append(r'(...
StarcoderdataPython
75987
from src.data_loader.data_set import Data_Set from src.utils import read_json from easydict import EasyDict as edict from src.constants import TRAINING_CONFIG_PATH from src.data_loader.utils import error_in_conversion, get_data from tqdm import tqdm def main(): train_param = edict(read_json(TRAINING_CONFIG_PATH))...
StarcoderdataPython
1677787
<reponame>torrotitans/torro_community #!/usr/bin/python # -*- coding: UTF-8 -* from flask_restful import Api from api.form.interface_base_form import interfaceBaseForm from api.form.interface_detail_form import interfaceDetailForm, interfaceDetailFormList from api.form.interface_edit_form import interfaceEditForm from...
StarcoderdataPython
1682365
#! /usr/bin/env python """ File: plot_sin_eps.py Copyright (c) 2016 <NAME> License: MIT Course: PHYS227 Assignment: B.2 Date: March 17th, 2016 Email: <EMAIL> Name: <NAME> Description: Studies a function for different parameter values """ from __future__ import division import numpy as np import matplotlib.pyplot as p...
StarcoderdataPython
3263893
<reponame>ffffff0x/python-hacker<filename>com/binghe/hacker/tools/script/network/loic/analysis_loic_online.py<gh_stars>10-100 #!/usr/bin/env python # -*- coding: utf-8 -*- # -*- coding: gbk -*- # Date: 2019/2/17 # Created by 冰河 # Description 实时检测DDos攻击 # 要识别攻击,需要设置一个不正常的数据包的阈值,如果某一个用户发送到某个地址的数据包的数量超过 # ...
StarcoderdataPython
46104
<gh_stars>1-10 #!/usr/bin/env python3 """Module for parsing tem setting files""" from base.rcon import echo import base.settings class TemParseError(Exception): """Tem Parser Exception""" def __init__(self, value): Exception.__init__(self) self.value = value def __str__(self): retu...
StarcoderdataPython
1763295
import torch import torch.nn as nn import numpy as np from model.layers import PointNet, GeneralKNNFusionModule, EquivariantLayer, InstanceBranch, JointBranch2 import index_max class OMAD_PriorNet(nn.Module): def __init__(self, surface_normal_len=0, basis_num=10, ...
StarcoderdataPython
1696860
<reponame>hsoft/hscommon<filename>util.py<gh_stars>1-10 # Created By: <NAME> # Created On: 2011-01-11 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are als...
StarcoderdataPython
197079
<filename>app/core/events.py from hq2redis import HQ2Redis from loguru import logger from app import settings, state from app.core.logging import init_logger from app.db.events import ( close_db_connection, close_redis_connection, connect_to_db, connect_to_redis, ) from app.schedulers import load_jobs_...
StarcoderdataPython
3276184
<filename>neon_api_proxy/api_connector.py # NEON AI (TM) SOFTWARE, Software Development Kit & Application Development System # All trademark and other rights reserved by their respective owners # Copyright 2008-2021 Neongecko.com Inc. # BSD-3 # Redistribution and use in source and binary forms, with or without # modifi...
StarcoderdataPython
1669887
""" Кастомизация админки FastAPI Admin https://fastapi-admin.github.io/reference/resource/ """ from fastapi_admin.app import app from fastapi_admin.resources import Model from app.models import Booking, Hotel, User @app.register class HotelResource(Model): label = "Hotels" model = Hotel @app.register class...
StarcoderdataPython
1667956
<filename>squadron/libraries/apt/test_apt.py import json from . import schema, verify, apply import wrap_apt from mock import MagicMock import os def set_test_hook_if_not_root(hook=True): if(os.geteuid() != 0): wrap_apt.FAKE_RETURN = hook def test_schema(): assert len(schema()) > 0 def test_verify_fa...
StarcoderdataPython
3290814
<reponame>johannvk/ProjectEuler import operator # Integer Right Triangles # Implementing stupid brute force trials: def brute_force_triangle_check(max_perim): for p in range(3, max_perim + 1): for a in range(1, p - 2): b = 0.5*(p - a) c = 0.5*(p - a) ...
StarcoderdataPython
3300947
<filename>shared/gast_to_code/gast_to_code_router.py import shared.gast_to_code.general_helpers as general_helpers from shared.gast_to_code.converter_registry import ConverterRegistry def gast_to_code(gast, out_lang, lvl=0): """ gast router that takes generic ast and the output language that the gast need...
StarcoderdataPython
3202957
#!/usr/bin/env python # Copyright (c) 2013 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. """Tests for module json_summary_combiner.py""" import filecmp import os import shutil import tempfile import unittest import jso...
StarcoderdataPython
62356
<filename>oving_02/oppg2.py #!/usr/bin/env python3 # O<NAME> <NAME> # 2.a # x = 10 print("{:<21}{}".format("x = 10 :", "Datatypen til x er int")) # x = 10 + 10 print("{:<21}{}".format("x = 10 + 10 :", "Datatypen til x er int")) # x = 5.5 print("{:<21}{}".format("x = 5.5 :", "Datatypen til x er float")) # x = 10 + 5.5...
StarcoderdataPython
8780
# -*- coding: utf-8 -*- from cwr.acknowledgement import AcknowledgementRecord, MessageRecord from cwr.agreement import AgreementRecord, AgreementTerritoryRecord, \ InterestedPartyForAgreementRecord from cwr.group import Group, GroupHeader, GroupTrailer from cwr.info import AdditionalRelatedInfoRecord from cwr.pars...
StarcoderdataPython
99480
<reponame>hylang/comphyle<filename>comphyle/jinja.py #!/usr/bin/env python from email.Utils import formatdate from jinja2 import Template import time import os def rfc_2822(dateobj): return formatdate(time.mktime(dateobj.timetuple())) def render_fd(fpath, ctx): output_name = fpath.replace(".jinja2", "") ...
StarcoderdataPython
1664110
velocidade = float(input('Qual é a velocidade atual do carro ? ')) if velocidade > 80: print('MULTADO ! Você excedeu o limite de velocidade que é de 80km/h') multa = (velocidade - 80) * 7 print('Você deve pagara a multa de R$ {:.2f}'.format(multa)) print('Tenha um bom dia e dirija om segurança ! ')
StarcoderdataPython
44297
#<NAME> # todo mov not working import nuke from PySide import QtGui def run(node): clipboard = QtGui.QApplication.clipboard() filename = node['file'].evaluate() filesplit = filename.rsplit('.',-2) filesplit[1] = '%0'+str(len(filesplit[1]))+'d' filep = '.'.join(filesplit) filenameFrame = nuke.getFileN...
StarcoderdataPython
1753953
<gh_stars>0 import contextlib import itertools import re import subprocess import sys from array import array from collections import namedtuple from gopro_overlay.common import temporary_file from gopro_overlay.dimensions import dimension_from, Dimension def run(cmd, **kwargs): return subprocess.run(cmd, check=...
StarcoderdataPython
1682421
# # Copyright (c) 2020 Idiap Research Institute, http://www.idiap.ch/ # Written by <NAME> <<EMAIL>>, # <NAME> <<EMAIL>> # import unittest import os import time import torch from fast_transformers.aggregate import aggregate_cpu, broadcast_cpu class TestAggregateCPU(unittest.TestCase): def test_aggregate(self):...
StarcoderdataPython
81182
<reponame>blackbat13/stv import sys from stv.models import SimpleVotingModel from stv.comparing_strats import StrategyComparer no_voters = int(sys.argv[3]) no_candidates = int(sys.argv[4]) heuristic = int(sys.argv[5]) simple_voting = SimpleVotingModel(no_candidates, no_voters) simple_voting.generate() print(simple_...
StarcoderdataPython
4813931
<gh_stars>1-10 #!/usr/bin/env python3 import sys TILE = [' ', 'U', 'R', 'D', 'L', '#', 'S', 'S', 'S', 'S'] with open(sys.argv[1], 'r') as fd: txt = fd.read() print(*[(TILE[ord(i) - 48] if 48 <=ord(i) < 58 else i) for i in txt], sep='')
StarcoderdataPython
104998
from mgt.datamanagers.data_manager import Dictionary class DictionaryGenerator(object): @staticmethod def create_dictionary() -> Dictionary: """ Creates a dictionary for a REMI-like mapping of midi events. """ dictionary = [{}, {}] def append_to_dictionary(word): ...
StarcoderdataPython
3257418
from django.contrib.auth.models import AbstractUser from django.db import models from django.urls import reverse from django.utils.translation import gettext_lazy as _ class User(AbstractUser): name = models.CharField(_("Name of User"), blank=True, max_length=255) class Meta: verbose_name = _("user")...
StarcoderdataPython
4827224
<reponame>anisayari/pywikibot<filename>pywikibot/families/commons_family.py # -*- coding: utf-8 -*- """Family module for Wikimedia Commons.""" # # (C) Pywikibot team, 2005-2018 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals from pywikibot import family ...
StarcoderdataPython
1701824
from __future__ import division import glob import numpy as NP from functools import reduce import numpy.ma as MA import progressbar as PGB import h5py import healpy as HP import warnings import copy import astropy.cosmology as CP from astropy.time import Time, TimeDelta from astropy.io import fits from astropy import ...
StarcoderdataPython
4828965
from __future__ import absolute_import from django.core.exceptions import ImproperlyConfigured from django.db.models.loading import get_app from django.test import TestCase from django.test.utils import override_settings from django.utils import six from .models import Empty class EmptyModelTests(TestCase): def...
StarcoderdataPython
3297374
import arrow from api.serializers import TenureSerializer, UserInvitationSerializer from rest_framework import serializers from rest_framework.test import APITestCase from ..handlers import get_new_tentative_end_date from .utils import (create_fake_society, create_tenure, get_deadline, get_fake_use...
StarcoderdataPython
53718
# coding: utf-8 import argparse import time from watchdog.observers import Observer from pywatcher import PyWatcher from logging import getLogger, Formatter, StreamHandler, DEBUG logger = getLogger(__name__) formatter = Formatter('%(asctime)s - %(levelname)s - %(message)s') handler = StreamHandler() handler.setLevel(...
StarcoderdataPython
85568
import sys import os from collections import OrderedDict from ttfautohint._compat import ( ensure_binary, ensure_text, basestring, open, IntEnum, ) USER_OPTIONS = dict( in_file=None, in_buffer=None, out_file=None, control_file=None, control_buffer=None, reference_file=None, reference_bu...
StarcoderdataPython
1643235
<filename>www/controllers/api/session.py from django.http import HttpResponse, HttpResponseNotFound from django.views.generic import View from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from rest_framework import serializers, viewsets from rest_framework.permiss...
StarcoderdataPython
1658415
import math def _get_distance(vec_a, vec_b): return math.sqrt( ( vec_b[0] - vec_a[0] ) ** 2 + (vec_b[1] - vec_a[1]) ** 2 ) def get_points(vec_a, vec_b): """ return the points that intersect """ # a = (r02 - r12 + d2 ) / (2 d) distance = _get_distance( vec_a, vec_b ) try: # a = (r02 - r12 + d2 ) / (2 d) a = ...
StarcoderdataPython
1721497
keys=input('Enter elements separated by ,(comma) for keys: ').split(',') values=input('Enter elements separated by ,(comma) for values: ').split(',') mydict={keys[i]:values[i] for i in range(len(keys))} newdict={values[i]:keys[i] for i in range(len(values))} print('Dict : ',mydict) print('Inverted Dict :',newdict)
StarcoderdataPython