id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
154439
<gh_stars>1000+ #!/usr/bin/env python3 import binascii import sys from collections import defaultdict import cereal.messaging as messaging from common.realtime import sec_since_boot def can_printer(bus=0): """Collects messages and prints when a new bit transition is observed. This is very useful to find signals ...
StarcoderdataPython
3363368
<reponame>CryptoSalamander/DeepFake-Detection import os import random ri = random.randint DIR = "." Folder = [ foldername for foldername in os.listdir(DIR) if foldername.find('_') != -1 ] for folder in Folder: mp4s = [ filename for filename in os.listdir("./" + folder) if filename[-4:] == '.mp4' ] Len = len...
StarcoderdataPython
160089
<reponame>bparazin/skyportal __all__ = ['Spectrum', 'SpectrumReducer', 'SpectrumObserver'] import warnings import json import sqlalchemy as sa from sqlalchemy.dialects import postgresql as psql from sqlalchemy.orm import relationship import numpy as np import yaml from astropy.utils.exceptions import AstropyWarning ...
StarcoderdataPython
3253506
<reponame>DanPorter/Dans_Diffraction<filename>Dans_Diffraction/functions_scattering.py # -*- coding: utf-8 -*- """ Module: functions_scattering.py Functions: intensity(structurefactor) Returns the squared structure factor phase_factor(hkl, uvw) Return the complex phase factor: phase_factor_qr(q, r) Return ...
StarcoderdataPython
4802138
<gh_stars>1-10 """ Sync full-text search indices with the database - Mark events for later syncing - Sync events - Rebuild the indices """ import logging from app.models.search.event import SearchableEvent from app.views.elastic_search import client from app.views.redis_store import redis_store logger = logging.get...
StarcoderdataPython
3270895
<gh_stars>1-10 import qiskit.circuit.library as library import math, qiskit, random import networkx as nx import numpy as np from qcg.generators import gen_supremacy, gen_hwea, gen_BV, gen_sycamore, gen_adder from qiskit_helper_functions.random_benchmark import RandomCircuit def factor_int(n): nsqrt = math.ceil(m...
StarcoderdataPython
1749857
<reponame>EGAMAGZ/Terminal-Music-Player<filename>pymusicterm/ui/menus.py<gh_stars>1-10 import py_cui from typing import List from py_cui import widget_set class LocalPlayerSettingsMenu: MENU_OPTIONS:List[str]=["Repeat All","Repeat","Shuffle","Block N|P key on repeat"] TITLE:str="Player Settings" ROW:int=...
StarcoderdataPython
3342431
<reponame>alexxxiong/pybindx import ntpath from pygccxml import declarations from pybindx.writers import base_writer from pybindx.writers import method_writer from pybindx.writers import class_arg_writer from pybindx.writers import constructor_writer class CppClassWrapperWriter(base_writer.CppBaseWrapperWriter): ...
StarcoderdataPython
6425
# Generated by Django 3.0.7 on 2020-08-24 06:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('datasets', '0008_auto_20200821_1427'), ] operations = [ migrations.AddField( model_name='rawdar', name='AsB', ...
StarcoderdataPython
1722953
from autosklearn.estimators import AutoSklearnClassifier
StarcoderdataPython
199253
<filename>download/xml_pickle/xml_pickle-0.30.py """Store Python objects to (pickle-like) XML Documents Note 0: See http://gnosis.cx/publish/programming/xml_matters_1.txt for a detailed discussion of this module. Note 1: The XML-SIG distribution is changed fairly frequently while it is in beta versi...
StarcoderdataPython
3200827
<filename>permission/views.py from django.shortcuts import render from django.contrib.contenttypes.models import ContentType # Create your views here. # from reception.models import index from django.contrib.auth.models import User,Permission,Group def useraddr(): username = request.POST.get('username') password = ...
StarcoderdataPython
74972
class Test: """ Lorem ipsum dolor sit amet, consectetur adipiscing elit, deserunt mollit anim id est laborum. .. sourcecode:: pycon >>> # extract 100 LDA topics, using default parameters >>> lda = LdaModel(corpus=mm, id2word=id2word, num_topics=100, distributed=True) using distrib...
StarcoderdataPython
149742
<reponame>mutalyzer/spdi-parser<filename>mutalyzer_spdi_parser/convert.py """ Module for converting SPDI descriptions and lark parse trees to their equivalent dictionary models. """ from lark import Transformer from .spdi_parser import parse def to_spdi_model(description): """ Convert an SPDI description to...
StarcoderdataPython
111396
<gh_stars>100-1000 """ Paper: Recurrent Neural Networks with Top-k Gains for Session-based Recommendations Author: <NAME>, and <NAME> Reference: https://github.com/hidasib/GRU4Rec https://github.com/Songweiping/GRU4Rec_TensorFlow @author: <NAME> """ import numpy as np from model.AbstractRecommender import S...
StarcoderdataPython
1600058
from flask import jsonify from flask_sqlalchemy import SQLAlchemy from src.webservice.base import Base db = SQLAlchemy() Base.query = db.session.query_property() class Menu(Base): __tablename__ = 'tbl_Menu' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) parent = db.Colum...
StarcoderdataPython
1789287
<filename>tests/circuit/test_symm.py<gh_stars>1-10 # -*- coding: utf-8 -*- import unittest import freqerica.circuit.symm class BasicTestSuite(unittest.TestCase): """Basic test cases.""" def test_SymmRemoveClifford(self): n_qubit = 4 dim = 2**n_qubit from qulacs import QuantumState ...
StarcoderdataPython
197573
# -*- coding: utf-8 # flake8: noqa: F401 # Core import pytest # Django from django.contrib.admin.sites import AdminSite from django.contrib.admin.options import ModelAdmin # Models from custom_auth_user.models import AuthToken # Admins from custom_auth_user.admin import * class MockRequest: pass request = Mo...
StarcoderdataPython
4816001
<gh_stars>0 version = '0.0.1' time = '2020-09-02 10:00:25'
StarcoderdataPython
3234952
#!/usr/bin/env python3 # This file is a part of toml++ and is subject to the the terms of the MIT license. # Copyright (c) 2019-2020 <NAME> <<EMAIL>> # See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text. import sys import re import os import os.path as path import traceback de...
StarcoderdataPython
44896
<filename>test_autofit/tools/test_edenise/test_import.py import pytest from autofit.tools.edenise import Package, Import, LineItem @pytest.fixture( name="import_" ) def make_import(package): return Import( "from autofit.tools.edenise import Line", parent=package ) @pytest.fixture( n...
StarcoderdataPython
1654153
<gh_stars>0 """ Search integral/derivative algorithm class """ from ..items import Items from ..sequence import integral, derivative, summation, product from ..utils import sequence_matches from .base import RecursiveAlgorithm __all__ = [ "SummationAlgorithm", "ProductAlgorithm", "IntegralAlgorithm", ...
StarcoderdataPython
1664172
import discord, firebase_api, requests from discord.ext import commands import random TOKEN = '<KEY>' PREFIX = "!" class MyClient(discord.Client): async def on_ready(self): self.db = firebase_api.Db( "https://project-b-5b43c.firebaseio.com/", "key.json" ) print('L...
StarcoderdataPython
31710
<reponame>mac389/semantic-distance import os, json, matplotlib matplotlib.use('Agg') import seaborn as sns import matplotlib.pyplot as plt import numpy as np import pandas as pd READ = 'rb' directory = json.load(open('directory.json',READ)) filename = os.path.join(directory['data-prefix'],'test-similarity-matrix...
StarcoderdataPython
4832768
import tkinter from PIL import Image, ImageTk class LoginPage(tkinter.Frame): def __init__(self, parent, App): self.application = App self.config = App.config super().__init__(parent) self.configure(bg="grey") self.grid(row=0, column=0, sticky="nsew") ...
StarcoderdataPython
3236032
# This Python file uses the following encoding: utf-8 import os from pathlib import Path import sys import requests import asyncio import pproxy import nest_asyncio nest_asyncio.apply() from PySide6.QtWidgets import QApplication, QWidget, QListWidgetItem, QSystemTrayIcon from PySide6.QtCore import QFile, QThread, Q...
StarcoderdataPython
1761597
from dataclasses import dataclass import logging from typing import ClassVar from bitey.cpu.arch import EightBitArch @dataclass class AddressingMode: """ Addressing mode base class """ bytes: int """ The number of bytes an instruction with this addressing mode takes, including the instruc...
StarcoderdataPython
3365276
<reponame>cliisberg/cvrapi-python-client<filename>cvrapi_client/client.py from functools import partial from .api import CVRAPI class CVRAPIClient(object): METHODS = ['get', 'post'] def __init__(self, *args): self.api = CVRAPI(*args) def __getattr__(self, method): return partial(getattr(s...
StarcoderdataPython
3338789
from autofunc.find_similarities import find_similarities import pandas as pd import os.path script_dir = os.path.dirname(__file__) file_to_learn = os.path.join(script_dir, '../autofunc/assets/consumer_systems.csv') train_data = pd.read_csv(file_to_learn) ## Make similarity dataframe similarity_df = find_similarities...
StarcoderdataPython
1619439
<filename>pdbtools/pdb_tidy.py #!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2018 <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/LI...
StarcoderdataPython
96673
#!/usr/bin/env python # # Copyright (c) 2018 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # # vim: tabstop=4 shiftwidth=4 softtabstop=4 # All Rights Reserved. # from cgtsclient.common import utils from cgtsclient import exc from cgtsclient.v1 import ihost as ihost_utils def _print_label_show(ob...
StarcoderdataPython
1654294
<filename>datasets/GTSRB_SS.py """ Module for managing GTSRB_SS dataset download from https://www.towardsautonomy.com/perception/traffic_sign_classification """ import numpy as np import os import urllib from .ImageDataset import ImageDataset import pickle import h5py import sklearn import sklearn.model_selection f...
StarcoderdataPython
1644049
#Creating Dictionary d = {22:"ss",23:"ftp",53:"dns"} print(d) #Length print(len(d)) #Deleting del d[22] print(d)
StarcoderdataPython
3320876
from collections import OrderedDict from pathlib import Path import pytest from Pegasus.yaml import dumps, loads @pytest.mark.parametrize( "s, expected", [ ("key: 1", 1), ("key: 2018-10-10", "2018-10-10"), ("key: yes", "yes"), ("key: true", True), ], ) def test_loads(s, e...
StarcoderdataPython
4829956
<reponame>forging2012/opencmdb-backend from flask_security import roles_accepted from webargs.flaskparser import use_args from api.models import (Aggregation, Mould) from api.utils.custom.error import error from api.utils.custom.interface_tips import InterfaceTips from api.utils.custom.validators import validate_valid...
StarcoderdataPython
3342850
import pickle from sklearn import datasets iris=datasets.load_iris() x=iris.data y=iris.target #labels for iris dataset labels ={ 0: "setosa", 1: "versicolor", 2: "virginica" } #split the data set from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test=train_test_split(x,y,test_size...
StarcoderdataPython
3226491
import pytest import datetime from pupa.scrape import Event def event_obj(): e = Event( name="get-together", start_date=datetime.datetime.utcnow().isoformat().split('.')[0] + 'Z', location_name="Joe's Place", ) e.add_source(url='http://example.com/foobar') return e def test_b...
StarcoderdataPython
113427
<reponame>coderdq/vuetest<filename>WEB21-1-12/WEB2/power/migrations/0001_initial.py # Generated by Django 2.2 on 2020-10-15 01:02 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( ...
StarcoderdataPython
1648105
import requests from .builder import AmazonRequestBuilder from .response import ( AmazonItemSearchResponse, AmazonItemLookupResponse, AmazonSimilarityLookupResponse, ) class AmazonProductAPI(object): def __init__(self, access_key, secret_key, associate_tag): self.access_key = access_key ...
StarcoderdataPython
1788790
<filename>05_Practice1/Step03/5_3_sang.py<gh_stars>0 a = sorted(map(int, input().split())) print(a[1])
StarcoderdataPython
1643070
"""Tests using pytest_resilient_circuits""" # -*- coding: utf-8 -*- # Copyright © IBM Corporation 2010, 2019 from __future__ import print_function, unicode_literals import pytest from resilient_circuits.util import get_config_data, get_function_definition from resilient_circuits import SubmitTestFunction, FunctionResu...
StarcoderdataPython
178297
from credmark.cmf.model import Model @Model.describe( slug='contrib.neilz', display_name='An example of a contrib model', description="This model exists simply as an example of how and where to \ contribute a model to the Credmark framework", version='1.0', developer='neilz.eth', outpu...
StarcoderdataPython
1616735
# -*- coding=utf-8 -*- from flask.ext.wtf import Form from ..models import Category from wtforms import StringField, SubmitField, PasswordField, TextAreaField from wtforms.validators import Required, length, Regexp, EqualTo from wtforms.ext.sqlalchemy.fields import QuerySelectField class LoginForm(Form): username...
StarcoderdataPython
4838089
from __future__ import annotations from unittest import TestCase from jsonclasses.exceptions import ValidationException from tests.classes.simple_config_user import SimpleConfigUser from tests.classes.simple_folder import SimpleFolder from tests.classes.simple_node import SimpleNode from tests.classes.simple_shape_sett...
StarcoderdataPython
193204
import numpy as np import pytest from ansys.dpf import core as dpf from ansys.dpf.core import examples @pytest.fixture() def local_server(): try : for server in dpf._server_instances : if server() != dpf.SERVER: server().info #check that the server is responsive ...
StarcoderdataPython
1755055
<filename>denoising.py from numpy import * import numpy as np import scipy import pywt from statsmodels.robust import mad import matplotlib.pyplot as plt def waveletSmooth( x, wavelet="db4", level=1, title=None ): # calculate the wavelet coefficients # returns tuple [cA,cDn,...,cD1] one approx. and details coe...
StarcoderdataPython
1624089
<reponame>krish8484/ITF1788<gh_stars>0 # # ITF1788 # # Interval Test Framework for IEEE 1788 Standard for Interval Arithmetic # # # Copyright 2014 # # <NAME> (<EMAIL>) # <NAME> (<EMAIL>) # # Department of Computer Science # University of Wuerzburg, Germany # # Licensed under t...
StarcoderdataPython
3375198
<filename>jupyterlab_extension/services.py # -*- coding: utf-8 -*- import json import os import re import requests from unicodedata import normalize DATASETS_ENDPOINT = os.getenv("DATASETS_ENDPOINT", "http://datasets.platiagro:8080") PROJECTS_ENDPOINT = os.getenv("PROJECTS_ENDPOINT", "http://projects.platiagro:8080")...
StarcoderdataPython
3856
_base_ = '../faster_rcnn/faster_rcnn_x101_64x4d_fpn_1x_coco.py' model = dict( backbone=dict( num_stages=4, #frozen_stages=4 ), roi_head=dict( bbox_head=dict( num_classes=3 ) ) ) dataset_type = 'COCODataset' classes = ('luchs', 'rotfuchs', 'wolf') data = dict...
StarcoderdataPython
1736612
<filename>human_agent.py from agent import Agent class HumanAgent(Agent): # overriding abstract method def reinforce_owned_territory(self, state): territory_name = input('Reinforce owned territory: ').strip() return state.board.territories[territory_name] # overriding abstract method ...
StarcoderdataPython
4808163
# Copyright 2020 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 agreed to in writing, ...
StarcoderdataPython
1611215
<gh_stars>100-1000 # coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LIC...
StarcoderdataPython
49408
<gh_stars>10-100 # # Module with functions for # Gruenbichler and Longstaff (1996) model # # (c) Dr. <NAME> # Listed Volatility and Variance Derivatives # import math import numpy as np import scipy.stats as scs def futures_price(v0, kappa, theta, zeta, T): ''' Futures pricing formula in GL96 model. Paramete...
StarcoderdataPython
3356790
<gh_stars>0 import requests from bs4 import BeautifulSoup import time import random HOST = "http://www.ecvv.com{}" def open_company_file(start): with open("file_cs-uri-stem_product_W3SVC.txt", 'r') as r: ret = r.readlines()[start + 1:] return ret def open_products_file(start): with open("file_cs...
StarcoderdataPython
52900
<filename>setup.py from setuptools import setup, find_packages setup( name='t3cpo', packages=find_packages(exclude=['tests', '.github']), version='0.1', license='MIT', description='Python wrapper for the several 3Commas api endpoints', author='mmeijden', author_email='<EMAIL>', # Type in y...
StarcoderdataPython
1742390
<filename>tests/utils/test_ghash.py # tests/utils/test_ghash.py # ========================= # # Copying # ------- # # Copyright (c) 2018 kado authors. # # This file is part of the *kado* project. # # kado is a free software project. You can redistribute it and/or # modify if under the terms of the MIT License. # # This...
StarcoderdataPython
1745893
class 문석쌤튜플(tuple): def __add__(self, other): # '+' 연산자를 오버로딩할(내가 정의하는 함수로 덮어씌울) 거예요 assert len(self) == len(other) # self랑 other(더하는 두 튜플)가 같은 길이를 가졌다고 가정 return tuple([x + y for x, y in zip(self, other)]) # 더해버려~
StarcoderdataPython
3339588
# Copyright 2016 The Johns Hopkins University Applied Physics Laboratory # # 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...
StarcoderdataPython
186821
# -*- coding: utf-8 -*- from datetime import datetime import tensorflow as tf import tensornet as tn import numpy as np def read_dataset(data_path, days, match_pattern, batch_size, parse_func, num_parallel_calls = 12): ds_data_files = tn.data.list_files(data_path, days=days, match_pattern=match_pattern) datas...
StarcoderdataPython
3205727
<filename>sunnysouth/marketplace/serializers/addresses.py # Django REST Framework from rest_framework import serializers # Models from sunnysouth.marketplace.models import Address class AddressModelSerializer(serializers.ModelSerializer): class Meta: model = Address fields = '__all__' rea...
StarcoderdataPython
453
"""empty message Revision ID: 0084_add_job_stats Revises: 0083_add_perm_types_and_svc_perm Create Date: 2017-05-12 13:16:14.147368 """ # revision identifiers, used by Alembic. revision = "0084_add_job_stats" down_revision = "0083_add_perm_types_and_svc_perm" import sqlalchemy as sa from alembic import op from sqlal...
StarcoderdataPython
3233950
<gh_stars>1-10 from typing import Tuple, List from timeatlas.abstract import AbstractBaseMetadataType class Unit(AbstractBaseMetadataType): """ Defines a physical unit of measurement, like Celsius.""" def __init__(self, name: str, symbol: str, data_type: str): self.name = name self.symbol = ...
StarcoderdataPython
3263354
<gh_stars>10-100 from django.contrib.messages import constants as messages from path.base import STATIC_DIR, TEMPLATES_DIR from django.core.urlresolvers import reverse_lazy from datetime import timedelta SECRET_KEY = '<secret_key>' ADMINS = (<admins_tuple>) INSTALLED_APPS = ( 'django.contrib.auth', 'django....
StarcoderdataPython
1652589
<gh_stars>1-10 #Ref: <NAME> """ How do we know how many clusters? Use AIC/BIC Bayesian information criterion (BIC) can be helpful to pick the right number of parameters. BIC estimates the quality of a model using penalty terms for # parameters. If we fit data with 100 gaussians we will be overfitting. BIC provides op...
StarcoderdataPython
1673156
<reponame>Autodesk/py-cloud-compute-cannon<filename>pyccc/_native.py # Copyright 2016-2018 Autodesk 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...
StarcoderdataPython
1768830
<filename>yt/frontends/tipsy/io.py """ Tipsy data-file handling function """ from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (c) 2014, yt Development Team. # # Distributed under the terms of the Modified BSD License. # # The full lice...
StarcoderdataPython
1796231
from numpy.core.defchararray import zfill import taichi as ti import numpy as np from .camera import * from .shading import * from .renderer_utils import ray_aabb_intersection, intersect_sphere, ray_plane_intersect, reflect, refract inf = 1e8 eps = 1e-4 @ti.data_oriented class ParticleRenderer: padding = 3 # ext...
StarcoderdataPython
1765682
from firedrake import * from MS_system import MS_constraint import numpy as np from ReducedFunctionalSafe import ReducedFunctionalSafe from firedrake_adjoint import * def parameter_optimization(target): # Create the Augmented system problem = MS_constraint() # Compute the initial guess proble...
StarcoderdataPython
1734006
from enum import Enum, unique @unique class StackStatus(Enum): IN_PROGRESS = "in progress" QUEUED = "queued" DONE = "done" READY = "ready"
StarcoderdataPython
3370467
from dataclasses import dataclass from typing import Dict, List, Optional @dataclass class HttpTransactionData: """Dataclass for HTTP Transaction objects. See also: https://github.com/ssllabs/ssllabs-scan/blob/master/ssllabs-api-docs-v3.md#httptransaction """ requestUrl: str """Request URL""" ...
StarcoderdataPython
1744958
from django.http import HttpRequest from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.decorators import api_view from workflows.services import WorkflowServices, WorkflowActions class Workflows(APIView): """ Class to get and post workflows """ de...
StarcoderdataPython
73224
<reponame>ttungbmt/BecaGIS_GeoPortal<gh_stars>0 # -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # 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 #...
StarcoderdataPython
54221
def foo(a, b, *, bar=True): print(bar) # 直接调用报错 foo(1, 2, 3)
StarcoderdataPython
20860
# Copyright 2015 Huawei Technologies Co.,LTD. # # 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 agree...
StarcoderdataPython
103665
<gh_stars>0 # Hash таблицы - часто поиск забирает O(1) времени и старается искать примерное положение ключа(значения) я чейки которое нам нужно from hashlib import md5 , sha1 data = [22,40,102,105,23,31,6,5] hash_table = [None] *15 tbllen = len(hash_table) def hash_function(value,table_size): return value % tabl...
StarcoderdataPython
26645
<reponame>hongren798911/haha num1 = 100 num2 = 200 num3 = 300 num4 = 400 num5 = 500 mum6 = 600 num7 = 700 num8 = 800
StarcoderdataPython
3250936
import socket from threading import Thread #Permet de faire tourner des fonctions en meme temps (async) import time class reseau: """ Class reseau demandant 1 paramètre : - sock : par default : socket.socket(socket.AF_INET, socket.SOCK_STREAM) """ def __init__(self, sock = socket.socket(socket...
StarcoderdataPython
1613169
from gensim.models import Word2Vec from ..lib import node2vec ''' TODO: migrate to https://github.com/eliorc/node2vec ''' def process(nx_g, args, gene_vec_conv=lambda x: x): """Generates node2vec representation of genes for given pathway network Parameters ---------- nx_g: :networkx.classes.graph.Gr...
StarcoderdataPython
3258545
<gh_stars>0 #!/usr/bin/python # -*- coding: utf-8 -*- """装饰器""" import functools # =============================== # 最基本的decorator # =============================== def log(func): @functools.wraps(func) # 把原始函数的__name__等属性复制到 wrapper()函数中 def wrapper(*args, **kw): print('call %s():' % fu...
StarcoderdataPython
107332
from textwrap import dedent import pytest from pylox.lox import Lox # Base cases from https://github.com/munificent/craftinginterpreters/blob/master/test/string/error_after_multiline.lox TEST_SRC = dedent( """\ // Tests that we correctly track the line info across multiline strings. var a = "1 2 ...
StarcoderdataPython
1725116
import sys import os import re import mxnet as mx import collections import math sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from config import config ######################################################################## ############### HELPERS FUNCTIONS FOR MODEL ARCHITECTURE ############### #...
StarcoderdataPython
1619058
""" Cisco_IOS_XR_ip_iarm_v6_oper This module contains a collection of YANG definitions for Cisco IOS\-XR ip\-iarm\-v6 package operational data. This module contains definitions for the following management objects\: ipv6arm\: IPv6 Address Repository Manager (IPv6 ARM) operational data Copyright (c) 2013\-2018...
StarcoderdataPython
3259261
<filename>predict-social-media-ad-purchased.py<gh_stars>0 #!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd # In[3]: data=pd.read_csv('data.csv') # In[4]: data.isnull().sum() # In[5]: data.head() # In[10]: data = data.drop('User ID', axis=1) # In[11]: data.head() # In[13]: fr...
StarcoderdataPython
3360106
<gh_stars>1000+ # Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 from copy import deepcopy import numpy as np from ...algorithm import Algorithm from ...algorithm_selector import COMPRESSION_ALGORITHMS from ....graph import model_utils as mu from ....graph import node_utils as nu fro...
StarcoderdataPython
126843
from vistrails.core.modules.utils import make_modules_dict try: # read_numpy requires numpy import numpy except ImportError: # pragma: no cover numpy_modules = [] else: from read_numpy import _modules as numpy_modules from read_csv import _modules as csv_modules from read_excel import _modules as exce...
StarcoderdataPython
1616602
from treelist import TreeList a = TreeList([1, 2, 3, 3, 3, 4, 5, 7, 8]) print(f"a[{a.leftmost(lambda x: x > 3)}] > 3") print(a) for i in range(1, 8 + 1): print(f"{i} => {a.bisect_left(i)} .. {a.bisect_right(i)}")
StarcoderdataPython
122952
<reponame>ctoth/platform_utils<filename>platform_utils/clipboard.py import platform def set_text_windows(text): """ Args: text: Returns: """ import win32clipboard import win32con win32clipboard.OpenClipboard() try: win32clipboard.EmptyClipboard() ...
StarcoderdataPython
147559
from typing import List, Tuple import helper import inputHelper from puzzleBase import PuzzleBase CardList = List[int] Const_Player1: str = "Player 1" Const_Player2: str = "Player 2" class InputData: expectedAnswer: int player1Deck: CardList player2Deck: CardList def __init__(self, name: str...
StarcoderdataPython
1717837
from Module import AbstractModule class Module(AbstractModule): def __init__(self): AbstractModule.__init__(self) def run( self, network, in_data, out_attributes, user_options, num_cores, out_filename): import itertools from genomicode import SimpleVariantMatrix ...
StarcoderdataPython
93242
from abc import ABC, abstractmethod from copy import copy from typing import Any, Optional import numpy as np from gym.spaces import Space from gym.utils import seeding class Operator(ABC): # Set these in ALL subclasses suboperators: tuple = tuple() grid_dependant: Optional[bool] = None action_depe...
StarcoderdataPython
152714
# -*- coding: utf-8 -*- # django-read-only-admin # tests/test_utils.py from typing import List # pylint: disable=W0611 from django.test import TestCase from django.test.utils import override_settings from read_only_admin.utils import ( get_read_only_permission_name, get_read_only_permission_codename, ) ...
StarcoderdataPython
4841840
import json import glob import pickle import pandas as pd import os HEAD_LEN = 510 def GenerateDatasetFromJson(): ''' return: a list of list of list, first dimension is each document, second dimension is doc_list and label_list of each document, third dimension is number of sentences ...
StarcoderdataPython
1792360
# @Author: Ivan # @Time: 2020/11/16 import os import time import argparse import torch from torch import nn import torch.optim as optim import torch.nn.functional as F from torchvision import utils import matplotlib.pyplot as plt from utils.datasets import create_dataloader from utils.util import parse_cfg from models ...
StarcoderdataPython
1659220
import logging from django.conf import settings from django.db import models import sendgrid from pokewatch.pokedex.models import Pokemon logger = logging.getLogger(__name__) class Place(models.Model): label = models.CharField(unique=True, max_length=255) latitude = models.DecimalField(max_digits=17, deci...
StarcoderdataPython
1711136
<gh_stars>1-10 import random import os #file=open('jio-num.txt','w') #this is very simple code, you can change this according #to your need but the change should comited to this repo. df=[] #first == '6296' for i in range(1001): x='+916297'+'%s'%random.randint(100000,999999) y='+916296'+'%s'%random.randint(100000,99...
StarcoderdataPython
103105
from soccer_geometry.transformation import Transformation from soccer_geometry.camera import Camera
StarcoderdataPython
184591
import typing import pytest from energuide import bilingual from energuide import element from energuide.embedded import code from energuide.embedded import distance from energuide.embedded import insulation from energuide.embedded import window from energuide.exceptions import InvalidEmbeddedDataTypeError @pytest.fi...
StarcoderdataPython
3357232
<gh_stars>0 # Polycarpus works as a DJ in the best Berland nightclub, # and he often uses dubstep music in his performance. # Recently, he has decided to take a couple of old songs and make dubstep remixes from them. # Let's assume that a song consists of some number of words (that don't contain WUB). # To mak...
StarcoderdataPython
199837
<reponame>penghou620/airflow # -*- coding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache ...
StarcoderdataPython
3302975
<reponame>Hoter11/WebProject # -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-19 10:25 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0003_entry_text'), ] operations = [ mi...
StarcoderdataPython