id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
1789443
class Matrix: def __init__(self, matrix_string = ""): # Creo una lista de listas a partir del matrix_string; e es cada elemento de matrix_string.splitlines # (ej:'9 8 7'), e.split() es una lista hecha de cada iteracion de e (ej: [9,8,7]) self.matrix_List = [[int(num) for num in e.split()]...
StarcoderdataPython
3281226
from django.utils.deprecation import MiddlewareMixin class MultipleProxyMiddleware(MiddlewareMixin): FORWARDED_FOR_FIELDS = [ 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED_HOST', 'HTTP_X_FORWARDED_SERVER', ] def process_request(self, request): """ Rewrites the proxy he...
StarcoderdataPython
5016416
import sys sys.path.append('.') import unittest import numpy as np ### Custom Imports from environment.custom.knapsack.env import Knapsack from environment.custom.knapsack.backpack import Backpack, EOS_BACKPACK, NORMAL_BACKPACK from environment.custom.knapsack.item import Item class TestKnapsackEnv(unittest.TestCase...
StarcoderdataPython
3533190
import os, psutil, sys, time from library.city import * from library.database import * from multiprocessing import Process from IPython import embed from time import sleep from random import randint GLOBAL_THREADS = 3 def general_scraping(total_threads, thread_number): for city in City.select().where(City.finis...
StarcoderdataPython
3346055
<filename>Python/src/modules/Database/database.py import sqlite3 class DB: def __init__(self): self.__connection = sqlite3.connect("./database/database.db") self.__cursor = self.__connection.cursor() def getPriceByID(self, code:str) -> int: return int(((self.__cursor.execute('SELECT p...
StarcoderdataPython
197340
<filename>qf_lib/common/enums/matplotlib_location.py # Copyright 2016-present CERN – European Organization for Nuclear Research # # 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
6616410
<reponame>codeclimate-testing/falcon from testing_helpers import wrap @wrap def store_slice(): x = range(100) x[10:20] = range(50, 60) return x def test_store_slice(): store_slice() @wrap def store_slice1(): x = range(100) x[10:] = range(50, 60) return x def test_store_slice1(): store_slice1() @wr...
StarcoderdataPython
3456813
<filename>test.py #!/usr/bin/python from scheduler import scheduler import json scheduler = scheduler.Scheduler() class MyScheduler(object): @scheduler.on("new") def onNew(body): print "state: new received {}".format(body) scheduler.moveTo("running", json.dumps(body)) @scheduler.on("...
StarcoderdataPython
6495130
<reponame>naotohori/cafysis ATOM_MASS = { "H": 1.00797, "C": 12.0107, "N": 14.0067, "O": 15.9994, "Na": 22.98977, "Mg": 24.305, "P": 30.97376, "S": 32.06, "Cl": 35.453, "K": 39.0983, "Ca": 40.08, "Mn": 54.9380, "Fe": 55.847, "Cu": 63.546, "Zn": 65.38, "Br...
StarcoderdataPython
5197407
def counting_triangles(V):
StarcoderdataPython
6422108
import ast import gzip from typing import Callable, Dict, Tuple, Union class JuliaExternalModulePlugins: def visit_gzipopen(t_self, node: ast.Call, vargs: list[str]): JuliaExternalModulePlugins._generic_gzip_visit(t_self) if vargs: return f"GZip.open({', '.join(vargs)})" # eli...
StarcoderdataPython
11390759
# Copyright 2020 MONAI Consortium # 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 writing, s...
StarcoderdataPython
3410703
<reponame>IoT-BA/project_noe-backend # -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-10-05 22:58 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0059_lorawanrawpoint_node'), ] operations ...
StarcoderdataPython
6637961
# For deployment, change this to the hostname or IP address # of your server ALLOWED_HOSTS=['127.0.0.1'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'af_db.db' } } # This is for django-debug-toolbar which is an optional # development tool INTERNAL_IPS = ('127.0.0...
StarcoderdataPython
5185780
from sklearn.ensemble import GradientBoostingRegressor from sklearn.datasets import load_boston from sklearn.utils import shuffle from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split import numpy as np from typing import Tuple def divide_datos( xdata: np.array, y: np...
StarcoderdataPython
1958388
""" PyPages ------- Do pagination in python like a charm. Links ````` * `documentation <https://github.com/fengsp/pypages>`_ * `development version <http://github.com/fengsp/pypages/zipball/master#egg=pypages-dev>`_ """ from setuptools import setup setup( name='PyPages', version='0.1', url='https://...
StarcoderdataPython
12855481
import numpy as np from .cnn import CNN from .kviews import KViews from .. import const class EndToEnd(): def __init__( self, bg_model: CNN, rs_model: KViews ) -> None: self.name = 'EndToEnd' self.bg_model = bg_model self.rs_model = rs_model def metadata(...
StarcoderdataPython
4950267
<filename>src/electionguardFlaskApi/election_controller.py from typing import List import pickle import os from electionguard.ballot import PlaintextBallot, CiphertextBallot from electionguardFlaskApi.election import * # Define filenames for data storage METADATA = '/metadata.obj' CONTEXT = '/context.obj' ENCRYPTER ...
StarcoderdataPython
1931068
from datetime import datetime from .base import ServiceBase from wafec.fi.hypothesis.models import * from .test_service import TestService from wafec.fi.hypothesis.exceptions import NotFoundException from sqlalchemy import and_ class ParameterService(ServiceBase): def __init__(self): ServiceBase.__init_...
StarcoderdataPython
6669152
from __future__ import absolute_import import tensorflow as tf from .core import DecomonLayer import tensorflow.keras.backend as K from tensorflow.keras.backend import bias_add, conv2d import numpy as np from tensorflow.keras.constraints import NonNeg from tensorflow.keras import initializers # from tensorflow.python....
StarcoderdataPython
11264784
import pytest from fixture import Application import json import os.path import ftputil target = None webfixture = None def load_config(file): global target if target is None: with open(file) as targetfile: target = json.load(targetfile) return target @pytest.fixture(scope="session")...
StarcoderdataPython
6610397
# coding=utf-8 from __future__ import unicode_literals, print_function from pylexibank.dataset import CldfDataset, TranscriptionReport from clldutils.misc import slug from clldutils.path import Path from pylexibank.lingpy_util import getEvoBibAsSource, iter_alignments from pylexibank.util import download_and_unpack_z...
StarcoderdataPython
3308667
<filename>ipsn_ranking_server.py #!/usr/bin/env python import SimpleHTTPServer import SocketServer class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): if self.path == '/': self.path = '/ranking.html' return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GE...
StarcoderdataPython
1889764
<reponame>hishizuka/pyqtgraph """ Demonstrate the use of layouts to control placement of multiple plots / views / labels """ ## Add path to library (just for examples; you do not need this) import initExample from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph as pg import numpy as np app = pg.mkQApp("Gradiant...
StarcoderdataPython
6635349
import csv import random def generating_data(): """Reading and generating necessary data about random word.""" with open('word-meaning-examples.csv', encoding='utf-8') as csv_file: csv_reader = csv.DictReader(csv_file) num = random.randint(0, 13160) data = {} for row in...
StarcoderdataPython
6427178
<reponame>lucasemmanuelferreiradearaujo/AulasDePython ''' Crie um programa que leia nome, ano de nascimento e carteira de trabalho e cadastre-os (com idade) em um dicionario se por acaso a CTPS for diferente de ZERO, o diconario recebera também o ano de contratação e o salario. Calcule e acrescente, alem da idade, com ...
StarcoderdataPython
9785115
import time, base64 #thanks to alexlavr #see: http://meta.osqa.net/question/25/installation-issue-importerror-cannot-import-name-auth_providers#43 try: from hashlib import md5 as md except ImportError: from md5 import new as md from openid.store import nonce as oid_nonce from openid.store.interface import Ope...
StarcoderdataPython
6647905
from flask import Blueprint from flask_restx import Api blueprint = Blueprint("api", __name__) api = Api( blueprint, title="MyToob Core API", version="1.0", description="API for managing MyToob Movies" ) from . resources.trip import ns_trips api.add_namespace(ns_trips)
StarcoderdataPython
1890688
<reponame>r-peschke/openslides-backend<gh_stars>0 from ....models.models import Role from ...generics.update import UpdateAction from ...util.default_schema import DefaultSchema from ...util.register import register_action from .deduplicate_permissions_mixin import DeduplicatePermissionsMixin @register_action("role.u...
StarcoderdataPython
235298
<reponame>contrerasadolfo/Restaurant-app-Api from django.test import TestCase from django.contrib.auth import get_user_model class ModelTests(TestCase): def test_create_user_with_email_successful(self): """Crear un nuevo usuario con un correo electrónico de forma exitosa""" email = '<EMAIL>' ...
StarcoderdataPython
1917587
from datetime import datetime from pprint import pprint from demo_hospital import demo2 # from solver_googleOR import solver from solver_with_urgency import solver print(demo2) schedule = solver(demo2, datetime.now()) pprint(schedule)
StarcoderdataPython
8184400
<reponame>StefanIGit/arjuna # This file is a part of Arjuna # Copyright 2015-2021 <NAME> # Website: www.RahulVerma.net # 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.o...
StarcoderdataPython
1832662
import numpy as np import tensorflow as tf import cv2 import time import os, random, re, pickle import imgaug as ia from imgaug import augmenters as iaa def atoi(text): return int(text) if text.isdigit() else text def natural_keys(text): return [ atoi(c) for c in re.split('(\d+)', text) ] # https://stackoverf...
StarcoderdataPython
4961813
# Copyright (c) 2020 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. """Enforces workaround list is alphabetically sorted. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details on th...
StarcoderdataPython
1838474
# Import the necessary methods from tweepy library from tweepy import OAuthHandler from tweepy import API from classes.KafkaPC import KafkaPC class TwitterP(KafkaPC): def __init__(self, config_path=None, in_topic=None, in_group=None, in_schema_file=None, out_topic=None, out_schema_file=None): ...
StarcoderdataPython
135400
"""Dummy sensor script Sends dummy data to BuildingDepot. This script sends noises to uuids[0] to [9], and sends sin waves to uuids[10] to [13]. This emulates the situation where a TI SensorTag is being shaken """ import time import math import random from json_setting import JsonSetting from buildingdepot_helper im...
StarcoderdataPython
9726557
import os from photogrammetry_importer.types.point import Point from photogrammetry_importer.file_handlers.ply_file_handler import PLYFileHandler from photogrammetry_importer.utility.blender_logging_utility import log_report class DataSemantics(object): def __init__(self): self.x_idx = None self....
StarcoderdataPython
308089
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import boto3 import os import traceback import auditors def get_queue_url(queue_arn): # Given a queue_arn like "arn:aws:sqs:us-east-1:123456789012:remediator-queue" # returns "https://queue.amazonaws.com/123456789012/remediator-queue" parts = queu...
StarcoderdataPython
5178439
#!/usr/bin/env python """ Concatenate files containing trial data. SCL; Feb 2012. """ import sys import pickle if __name__ == "__main__": if len(sys.argv) < 3: print "Usage: %s FILE1 [...] OUTPUT" % sys.argv[0] exit(1) times = [] world_data = [] for file_index in range(len(sys.argv)...
StarcoderdataPython
11227875
# Copyright (c) Microsoft Corporation # All rights reserved. # # MIT License # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the Software without restriction, including without limitation # the rights to ...
StarcoderdataPython
5024167
# Copyright 2022 The Kubeflow 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/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
StarcoderdataPython
5048059
import platform #This programe is create by <NAME> # Github: https://github.com/sujitmandal # Pypi : https://pypi.org/user/sujitmandal/ # LinkedIn : https://www.linkedin.com/in/sujit-mandal-91215013a/ def slash(): if platform.system() == 'Linux': system = '/' elif platform.system() == 'Win...
StarcoderdataPython
1875007
import sys from DB import db, User from Security import password if 'y' != input('Tämä tuohoaa tietokannan, oletko varma? [y/n]'): sys.exit() db.drop_all() db.create_all() u = User() u.username = 'swat' u.password_hash = password.hash('<PASSWORD>') u.email = '<EMAIL>' u.admin = True db.session.add(u) db.sessio...
StarcoderdataPython
4854137
"""Unit tests for initialization of secrets.""" import unittest from unittest.mock import Mock from external.initialization.secrets import initialize_secrets class TestSecrets(unittest.TestCase): """Unit tests for initialization of secrets.""" def setUp(self): """Set up database mocks.""" s...
StarcoderdataPython
11387090
<reponame>snchvn/Python-Discord-NPC-bot<gh_stars>0 import discord import random import os # Mission giver Discord bot. Randomly allocates pre-written mission scripts to members of voice channel. # Read your Discord Bot's connecting token from Heroku config vars access_token = os.environ["ACCESS_TOKEN"] channel_id = ...
StarcoderdataPython
1668535
<filename>tracardi/process_engine/action/v1/internal/inject_event/model/configuration.py from pydantic import BaseModel, validator class Configuration(BaseModel): event_id: str @validator("event_id") def event_id_can_not_be_empty(cls, value): if len(value) == 0: raise ValueError("Even...
StarcoderdataPython
1671218
# -*- coding: utf-8 -*- from __future__ import unicode_literals """ 维吉尼亚密码破解 """ from pycipher import Vigenere from ..utils import get_raw_plain_text import re LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def find_key_by_plain_cipher(plain, cipher): # key = '<KEY>' # cipher = '''jwm ewrboya fe gjbxcd hrzcvt.'''...
StarcoderdataPython
3487964
from chainer0.variable import Variable from chainer0.function import Function from chainer0.function import grad from chainer0.link import Link from chainer0.link import Chain from chainer0.functions import basic_math from chainer0.functions import array from chainer0.optimizer import Optimizer from chainer0.configurat...
StarcoderdataPython
3571663
""" Is a message-queueing, a rabbitMQ, that allows 'Meter' and 'PV_simulator' to communicate with each other. It receives messages from 'Meter' and sends them to 'PV_simulator' """ import aio_pika from typing import Callable from logging import Logger class Broker: def __init__(self,address: str, queue_name:str, ...
StarcoderdataPython
9727736
class Solution: def totalFruit(self, tree): """ :type tree: List[int] :rtype: int """ # each basket has one kind # longest sub-array that has two kinds of fruits # need to remember the last seen index of each fruit ans = 0 i = 0 s, idxe...
StarcoderdataPython
8181156
## Copyright (c) 2015 SONATA-NFV, 2017 5GTANGO [, ANY ADDITIONAL AFFILIATION] ## 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/licen...
StarcoderdataPython
6466760
#Resolvendo o problema do arquivo não fechar quando ocorrer erro no código try: arquivo = open('pessoas.csv') for linha in arquivo: print('Nome: {}, Idade: {}'.format(*linha.strip().split(','))) #Usando * irá extrair os elementos de uma coleção de dados (lista, tuplas dicionários, sets, etc) except...
StarcoderdataPython
3415237
<reponame>ehaka/lie-algebra-gradings from lie_gradings.classification.classified_lie_algebra import ClassifiedNilpotentLieAlgebra __all__ = ['L1_1'] def L1_1(F): sc = {} return ClassifiedNilpotentLieAlgebra(F, 'L1_1', sc, names=['X_1'])
StarcoderdataPython
376742
<reponame>dkirkby/batoid import os import numpy as np import batoid from test_helpers import timer from batoid.utils import normalized @timer def test_plane_refraction_plane(): import random random.seed(5) wavelength = 500e-9 # arbitrary plane = batoid.Plane() m1 = batoid.ConstMedium(1.1) m2 ...
StarcoderdataPython
3418424
#!/usr/bin/python # # Copyright 2002-2019 Barcelona Supercomputing Center (www.bsc.es) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
StarcoderdataPython
5114496
import ast import logging from typing import List, Set from grimp.application.ports.importscanner import AbstractImportScanner from grimp.domain.valueobjects import DirectImport, Module from grimp import exceptions logger = logging.getLogger(__name__) class NotAnImport(Exception): pass class ImportScanner(Abs...
StarcoderdataPython
1835443
<gh_stars>0 from bs4 import BeautifulSoup from bs4.element import NavigableString, Tag tags = { 'ignore': ['head', 'a', 'map', 'style', 'meta', 'base', 'link', 'script', 'noscript', 'img'], 'table': ['table'], 'table_cell': ['td', 'th'], 'table_colspan': 'colspan', 'table_row': ['tr'...
StarcoderdataPython
8169361
<reponame>ptrebert/reference-data # coding=utf-8 import os as os import io as io import re as re import gzip as gz import functools as fnt from pipelines.auxmod.auxiliary import read_chromsizes, check_bounds, open_comp def adjust_coordinates(regtype, start, end, strand): """ :param regtype: :param start...
StarcoderdataPython
11255236
<gh_stars>0 """ whois_bridge service for Windows """ import os import sys import logging import win32service import win32serviceutil import servicemanager import jaraco.logging log = logging.getLogger(__name__) class Service(win32serviceutil.ServiceFramework): _svc_name_ = 'whois_bridge' _svc_display_nam...
StarcoderdataPython
203607
#!/usr/bin/env python2 import os import json import unittest from partialView.partialView import PartialView, PodDescriptor class TestPartialView(unittest.TestCase): @classmethod def setUpClass(cls): pass def setUp(self): self.partialView = PartialView("172.16.31.10") self.descr...
StarcoderdataPython
65207
#------------------------------------------------------------------------- # Copyright (c) Microsoft. 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.apa...
StarcoderdataPython
4893959
import os import cv2 as cv import mediapipe as mp from ILib.utils import makeFolder, collect_image_files class AutoAligner(): def __init__(self): self.mp_drawing = mp.solutions.drawing_utils self.mp_pose = mp.solutions.pose self.mp_holistic = mp.solutions.holistic self.mp_face_det...
StarcoderdataPython
187133
<filename>digsby/src/msn/p12/__init__.py<gh_stars>10-100 from MSNP12Switchboard import MSNP12Switchboard as Switchboard from MSNP12Notification import MSNP12Notification as Notification
StarcoderdataPython
110169
import ujson from dataclasses import dataclass, asdict @dataclass class BaseModelMixin: @property def as_json_string(self): return ujson.dumps(asdict(self)) @classmethod def from_json(cls, jstr): if not jstr: return None d = ujson.loads(jstr) return cls(**d...
StarcoderdataPython
254036
<gh_stars>0 from datetime import datetime nascimento = int(input('Insira seu ano de nascimento: ')) idade = datetime.today().year - nascimento if idade < 18: print('Você ainda vai se alistar') tempo = 18 - idade print(f'Falta {tempo} anos para você se alistar') elif idade == 18: print('Está na hora de...
StarcoderdataPython
11222655
from flask import Flask, request, render_template import tweepy from textblob import TextBlob import plotly.plotly as py import plotly.graph_objs as go import plotly plotly.tools.set_credentials_file(username='lastps', api_key='cB0kWozoTEjQDZJpCUhP') def Gauge_Printer(): base_chart = { "values": [40, 10, ...
StarcoderdataPython
3358200
from sqlalchemy import Boolean, Column, String from models.base import Base class User(Base): __tablename__ = "users" email = Column(String, unique=True, index=True, nullable=False) password = Column(String, nullable=False) active = Column(Boolean, nullable=False, default=True)
StarcoderdataPython
11311720
""" Tests for the basic functions in tedopa/tmps.py To check if the whole time evolution works (i.e. the more advanced functions orchestrating the basic functions) see test_tmps_for_transverse_ising_model.py """ import pytest as pt import numpy as np from numpy.testing import assert_array_almost_equal from tedopa imp...
StarcoderdataPython
12783
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Taskmaster-2 implementation for ParlAI. No official train/valid/test splits are available as of 2020-05-18, so we m...
StarcoderdataPython
6547092
import unittest from spacel.model.aws import INSTANCE_VOLUMES # AWS < Heinz INSTANCE_TYPE_COUNT = 54 class TestInstanceTypes(unittest.TestCase): def test_instance_volumes(self): self.assertEqual(INSTANCE_TYPE_COUNT, len(INSTANCE_VOLUMES))
StarcoderdataPython
3537625
<reponame>helinwang/pytorch-semseg import torch import argparse import numpy as np import scipy.misc as misc import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import csv from ptsemseg.models import get_model from ptsemseg.utils import convert_state_dict N_CLASSES = 151 class Classifie...
StarcoderdataPython
10438
<gh_stars>0 from setuptools import setup from nats.aio.client import __version__ EXTRAS = { 'nkeys': ['nkeys'], } setup( name='nats-py', version=__version__, description='NATS client for Python', long_description='Python client for NATS, a lightweight, high-performance cloud native messaging syst...
StarcoderdataPython
1693007
from django.urls import path from .views import show_foilaw urlpatterns = [ path("<slug:slug>/", show_foilaw, name="publicbody-foilaw-show"), ]
StarcoderdataPython
121950
# -*- coding: utf-8 -*- """ Created on Wed Oct 28 09:27:49 2020 @author: <NAME> """ import pickle import pandas as pd import numpy as np from country import country from scipy.integrate import solve_ivp from scipy.optimize import minimize from scipy.optimize import dual_annealing from scipy.optimize i...
StarcoderdataPython
1897236
_zfpy = None try: import zfpy as _zfpy except ImportError: # pragma: no cover pass if _zfpy: from .abc import Codec from .compat import ndarray_copy, ensure_contiguous_ndarray, ensure_bytes import numpy as np # noinspection PyShadowingBuiltins class ZFPY(Codec): """Codec providi...
StarcoderdataPython
367956
from Traceroute import Traceroute from datetime import datetime import bases import detector import sys import parameters as param def main(hitlist, numCortes, tamanhoJanela, iface = None, source = None): conjuntoBase = [x for x in bases.main(hitlist, iface, source) if not x[param.INCOMPLETE]] cortesNaJanela =...
StarcoderdataPython
6445746
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2019, AGB & pysat team # Full license can be found in License.md #----------------------------------------------------------------------------- """ Routines to extract observational-style data from model output Routines -------- satellite_view_through_model...
StarcoderdataPython
9640020
#!/usr/local/bin/python3 # on mac: brew install python3 # # helper script to update all version numbers (mac, windows, frontend) import sys, os, os.path, re pj = os.path.join def match_replace_group(s, m, group, replacement): b = m.start(1) e = m.end(1) return s[:b] + replacement + s[e:] def replace_string(s, v...
StarcoderdataPython
12840211
import emcee import numpy as np from matplotlib import pyplot as plt from remu import binning, likelihood, likelihood_utils, plotting with open("../01/reco-binning.yml") as f: reco_binning = binning.yaml.full_load(f) with open("../01/optimised-truth-binning.yml") as f: truth_binning = binning.yaml.full_load(f...
StarcoderdataPython
327231
import unittest from src.assignments.Assignment9.invoice import Invoice from src.assignments.Assignment9.invoice_item import InvoiceItem class Test_Assign8(unittest.TestCase): invoice_items = [] #list of Invoice Item instance objects def test_invoice_item_extended_cost_w_qty_10_cost_5(self): ''' ...
StarcoderdataPython
8047322
import fileinput import numpy as np from numpy.core.numeric import count_nonzero def main(): folds: list[tuple[str, int]] = [] dots: list[tuple[int, int]] = [] max_x = 0 max_y = 0 for line in fileinput.input(): line = line.strip() if not line: continue if line....
StarcoderdataPython
6627314
<gh_stars>0 # -*- coding: utf-8 -*- # 获取客户端引擎API模块 import client.extraClientApi as clientApi # 获取客户端system的基类ClientSystem ClientSystem = clientApi.GetClientSystemCls() # 在modMain中注册的Client System类 class TutorialClientSystem(ClientSystem): # 客户端System的初始化函数 def __init__(self, namespace, systemName): #...
StarcoderdataPython
11392867
<gh_stars>1-10 # Copyright 2011,2012,2013 <NAME> # # 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 a...
StarcoderdataPython
9735612
#!/usr/bin/env python2 # # dockbar.py # # Example program places a coloured bar across the top of the # current monitor # # demonstrates # # (a) creating the bar as an undecorated "dock" window # (b) setting its colour # (c) getting the number of monitors and their sizes # # ...
StarcoderdataPython
9710522
<reponame>elraro/tweetfs-release # unpack a dict into a dir or file from bitstring import BitArray import bson from os.path import exists from os import chdir, chmod, mkdir, tmpfile from util import is_file, is_dir, assert_type def fatal_if_exists(name, kind): '''Fail if a file exists.''' if exists(name): ...
StarcoderdataPython
6417063
<gh_stars>0 # Copyright 2015 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
StarcoderdataPython
3370562
import math import numpy as np import shapely.geometry as geom from shapely import affinity import itertools from matplotlib import pyplot as plt from matplotlib import patches from descartes import PolygonPatch class Environment: def __init__(self, obstacles, start, goal_region, bounds=None): self.enviro...
StarcoderdataPython
5171246
<reponame>gerryjenkinslb/cs22-slides-and-py-files from pythonds.basic.stack import Stack ''' :param decNumber: value to convert to binary :return: string displaying binary value for decNumber ''' def divide_by_2(dec_number): rem_stack = Stack() while dec_number > 0: remainder = dec_number % 2 ...
StarcoderdataPython
8063089
<gh_stars>1-10 # -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-02-28 14:53 from __future__ import unicode_literals import django.core.validators from django.db import migrations, models import re class Migration(migrations.Migration): dependencies = [ ('judge', '0006_auto_20160227_1550'), ...
StarcoderdataPython
3207642
#! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = 'kute' # __mtime__ = '2016/12/24 20:45' """ 多线程,协称 执行器 """ import os import attr import gevent from gevent import monkey from gevent.pool import Pool monkey.patch_all() def valide_func(instance, attribute, value): if not callable(value): ...
StarcoderdataPython
1978893
from __future__ import annotations import parsedatetime from subtypes import Enum class MetaInfoMixin: _calendar = parsedatetime.Calendar() class Enums: class WeekDay(Enum): """An Enum holding the days of the week.""" MONDAY = MON = Enum.Alias() TUESDAY = TUE = E...
StarcoderdataPython
9624018
<reponame>PicusZeus/modern_greek_accentuation from modern_greek_accentuation.accentuation import convert_to_monotonic if __name__ == '__main__': print(convert_to_monotonic('ἐν τῷ πρόσθεν λόγῳ δεδήλωται'))
StarcoderdataPython
11244557
<reponame>dzil123/godot-gdscript-toolkit<filename>tests/common.py import os def write_file(tmp_dir, file_name, code): file_path = os.path.join(tmp_dir, file_name) with open(file_path, "w") as fh: fh.write(code) return file_path
StarcoderdataPython
7247
# Copyright 2020 Soil, Inc. # Copyright (c) 2011 X.commerce, a business unit of eBay Inc. # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); yo...
StarcoderdataPython
5001311
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "<NAME>" __email__ = "<EMAIL>" __description__ = ''' Camera image source. Searches for a connected camera (that is not shaded). ''' import sys import os import cv2 import numpy as np class WebCamera: """ Camera input. An active switch...
StarcoderdataPython
8010406
from queue import LifoQueue stack = LifoQueue(maxsize = 3) print(stack.qsize()) stack.put('a') stack.put('b') stack.put('c') print("Full: ", stack.full()) print("Size: ", stack.qsize()) print('\nElements poped from the stack') print(stack.get()) print(stack.get()) print(stack.get()) print("\nEmpty: ", stack....
StarcoderdataPython
5088584
__all__ = [ "__version__", "Lockfile", "Pipfile", ] __version__ = '0.2.3.dev0' from .lockfiles import Lockfile from .pipfiles import Pipfile
StarcoderdataPython
11396879
from django.db import models from django.urls import reverse # Create your models here. class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) slug = models.SlugField(max_length=50) birthday = models.DateField() class Meta: abs...
StarcoderdataPython
164179
#!/usr/bin/python with open('INCAR', 'r') as file: lines=file.readlines() for n,i in enumerate(lines): if 'MAGMOM' in i: # print(i) items=i.split() index=items.index('=') moments=items[index+1:] # print(moments) magmom='' size=4 for i in ra...
StarcoderdataPython
147903
from methods.indirect_influence import indirect_pagerank, indirect_paths from methods.direct_influence import pairwise_inf from classes.GraphQW import GraphQW, nx """ LRIC centrality Arguments: graph - input graph (Graph or DiGraph object, NetworkX package) q (optional) - quota (threshold of influence) for each node ...
StarcoderdataPython