text string | size int64 | token_count int64 |
|---|---|---|
import FWCore.ParameterSet.Config as cms
from CalibTracker.SiStripCommon.ShallowEventDataProducer_cfi import *
from CalibTracker.SiStripCommon.ShallowDigisProducer_cfi import *
from CalibTracker.SiStripCommon.ShallowClustersProducer_cfi import *
from CalibTracker.SiStripCommon.ShallowTrackClustersProducer_cfi import *... | 2,418 | 758 |
if __name__ == '__main__':
from .system import MyApp
MyApp().run()
| 75 | 27 |
import numpy as np
from scipy.special import expit, logit
import time
import logging
np.random.seed(4) # 4
logger = logging.getLogger(__name__)
fr = logging.Formatter('%(asctime)s:%(levelname)s:%(message)s')
sh = logging.StreamHandler()
# sh.setFormatter(fr)
logger.addHandler(sh)
logger.setLevel(logging.DEBUG)
logge... | 18,656 | 6,389 |
# app config
default_app_config = 'sensorAtlas.apps.sensorAtlasConfig'
| 71 | 24 |
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from api import views
router = DefaultRouter()
router.register('countries', views.CountryViewSet)
router.register('states/(?P<country>[^/.]+)', views.StateViewSet)
router.register('addresses', views.AddressViewSet)
app_name = 'api... | 376 | 114 |
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2021 Filipe Laíns <lains@riseup.net>
def test_dispatch(basic_device):
basic_device.protocol_dispatch([0x03, 0x02, 0x01]) # unrelated
basic_device.protocol_dispatch([0x20]) # invalid length short
basic_device.protocol_dispatch([0x21]) # invalid le... | 1,401 | 703 |
# Copyright (c) 2013 Red Hat, Inc.
# Copyright 2014 Catalyst IT 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 a... | 4,314 | 1,216 |
""" Tests for Explainer class.
"""
import pytest
import shap
def test_wrapping_for_text_to_text_teacher_forcing_logits_model():
""" This tests using the Explainer class to auto choose a text to text setup.
"""
transformers = pytest.importorskip("transformers")
def f(x): # pylint: disable=unused-arg... | 792 | 273 |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib import admin
from django.conf.urls.static import static
from django.conf.urls.i18n import i18n_patterns
from django.views.decorators.cache import cache_page
from django.conf.urls import url, include, handler404, handler500
admin.autodiscover(... | 1,301 | 465 |
from wtforms import Form, StringField
from wtforms.validators import DataRequired
from flask_appbuilder.fieldwidgets import BS3TextFieldWidget
from flask_appbuilder.forms import DynamicForm
class MyForm(DynamicForm):
field1 = StringField(('Field1'),
description=('Your field number one!'),
validato... | 486 | 129 |
import zmq
context = zmq.Context()
socket = context.socket(zmq.PAIR)
address = "tcp://127.0.0.1:5000"
def client(address):
socket.connect(address)
def server(address):
socket.bind(address)
def send(data):
socket.send_string(data)
def recv():
try:
return socket.recv(flags=zmq.NOBLOCK)
ex... | 403 | 147 |
from pathlib import Path
import numpy as np
path: Path
d1: np.DataSource
d1.abspath(path) # E: incompatible type
d1.abspath(b"...") # E: incompatible type
d1.exists(path) # E: incompatible type
d1.exists(b"...") # E: incompatible type
d1.open(path, "r") # E: incompatible type
d1.open(b"...", encod... | 410 | 169 |
### this works on linux only
try:
import fcntl
import subprocess
import signal
import os
except:
session.flash='sorry, only on Unix systems'
redirect(URL(request.application,'default','site'))
forever=10**8
def kill():
p = cache.ram('gae_upload',lambda:None,forever)
if not p or p.poll... | 2,821 | 894 |
import torch
import torch.nn as nn
from basicts.archs.AGCRN_arch.AGCN import AVWGCN
class AGCRNCell(nn.Module):
def __init__(self, node_num, dim_in, dim_out, cheb_k, embed_dim):
super(AGCRNCell, self).__init__()
self.node_num = node_num
self.hidden_dim = dim_out
self.gate ... | 1,110 | 444 |
from numpy import log10, isnan
def signOfFeasible(p):
r = '-'
if p.isFeas(p.xk): r = '+'
return r
textOutputDict = {\
'objFunVal': lambda p: p.iterObjFunTextFormat % (-p.Fk if p.invertObjFunc else p.Fk),
'log10(maxResidual)': lambda p: '%0.2f' % log10(p.rk+1e-100),
'log10(MaxResidual/ConTol)':lambda p: '... | 1,763 | 704 |
import os
from main import main
from pprint import pprint
def parse(lines):
# world bounds
wx = int(lines[0].split()[0])
wy = int(lines[0].split()[0])
# initial position
x = int(lines[1].split()[0])
y = int(lines[1].split()[1])
cmds = []
# command / step pair
it = iter(lines[2].... | 1,833 | 671 |
import itertools
from typing import List, Tuple
from card_utils import deck
from card_utils.deck.utils import (
rank_partition,
suit_partition,
ranks_to_sorted_values
)
from card_utils.games.gin.deal import new_game
def deal_new_game():
""" shuffle up and deal each player 7 cards,
put one car... | 5,749 | 2,087 |
"""
Testing of TestDice.
"""
from evennia.commands.default.tests import BaseEvenniaCommandTest
from mock import patch
from . import dice
@patch("evennia.contrib.rpg.dice.dice.randint", return_value=5)
class TestDice(BaseEvenniaCommandTest):
def test_roll_dice(self, mocked_randint):
self.assertEqual(dice... | 899 | 366 |
#!/usr/bin/python3
import argparse
import logging
import signal
import time
from logging import debug, error, info, warning
import pythonosc.osc_server
import pythonosc.udp_client
from pythonosc.dispatcher import Dispatcher
import hid
LOG_FORMAT = '%(message)s'
POLL_INTERVAL = 1
# Supported USB relay vendor-id and... | 9,247 | 2,619 |
import numpy as np
import matplotlib.pyplot as plt
import os
path = "/Users/petermarinov/msci project/electrode data/test data/data/"
filenames = []
for f in os.listdir(path):
if not f.startswith('.'):
filenames.append(f)
i=-12
data = np.genfromtxt(path + filenames[i])
V = np.zeros((200,20... | 1,408 | 750 |
#!/usr/bin/env python
"""
get_first_movie.py
Usage: get_first_movie "movie title"
Search for the given title and print the best matching result.
"""
import sys
# Import the IMDbPY package.
try:
import imdb
except ImportError:
print 'You bad boy! You need to install the IMDbPY package!'
sys.exit(1)
if... | 1,355 | 437 |
#!/usr/bin/env python
# -*- mode: python -*-
import re
import struct
import types
def items_in_order(dict, order=[]):
"""return all items of dict, but starting in the specified order."""
done = { }
items = [ ]
for key in order + dict.keys():
if not done.has_key(key) and dict.has_key(key):
... | 14,079 | 5,225 |
from xml.dom import minidom
from xml.etree import ElementTree
from xml.etree.cElementTree import Element, SubElement, ElementTree, tostring
class PNMLModelGenerator:
def generate(self, tasks):
top = Element('pnml')
child = SubElement(top, 'net',
attrib={'id': "net1", 't... | 1,180 | 361 |
# -*- coding: utf-8 -*-
# ***********************************
# Author: Pedro Jorge De Los Santos
# E-mail: delossantosmfq@gmail.com
# Blog: numython.github.io
# License: MIT License
# ***********************************
from nusa import *
"""
Logan, D. (2007). A first course in the finite element analysis.
... | 969 | 467 |
from data_reader.reader import CsvReader
from util import *
import numpy as np
import matplotlib.pyplot as plt
class LogisticRegression(object):
def __init__(self, learning_rate=0.01, epochs=50):
self.__epochs= epochs
self.__learning_rate = learning_rate
def fit(self, X, y):
self.w_ =... | 2,919 | 1,116 |
from wavefront_reader.wavefront_classes.objfile import ObjFile
from .readface import read_face
def read_objfile(fname):
"""Takes .obj filename and return an ObjFile class."""
obj_file = ObjFile()
with open(fname) as f:
lines = f.read().splitlines()
if 'OBJ' not in lines[0]:
raise Valu... | 1,413 | 419 |
# Directions
UP = 'UP'
DOWN = 'DOWN'
LEFT = 'LEFT'
RIGHT = 'RIGHT'
# Colors
RED = (255, 0, 0)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)
| 157 | 99 |
"""
Utils for video_pipeline app.
"""
from django.conf import settings
from edx_rest_api_client.client import OAuthAPIClient
def create_video_pipeline_api_client(api_client_id, api_client_secret):
"""
Returns an API client which can be used to make Video Pipeline API requests.
Arguments:
api_cli... | 520 | 158 |
#!/usr/bin/env python3
"""
Created on March 18 2020
@author: Melchior du Lac
@description: Extract the taxonomy ID from an SBML file
"""
import argparse
import tempfile
import os
import logging
import shutil
import docker
def main(inputfile, output):
"""Call the extractTaxonomy docker to return the JSON file
... | 2,695 | 750 |
# coding: utf-8
"""
Browse API
<p>The Browse API has the following resources:</p> <ul> <li><b> item_summary: </b> Lets shoppers search for specific items by keyword, GTIN, category, charity, product, or item aspects and refine the results by using filters, such as aspects, compatibility, and fields values.<... | 10,460 | 3,023 |
from pathlib import Path
import pandas
from muller.dataio import import_tables
from loguru import logger
DATA_FOLDER = Path(__file__).parent.parent / "data"
def test_filter_empty_trajectories():
input_column_0 = ['genotype-1', 'genotype-2', 'genotype-3', 'genotype-4', 'genotype-5', 'genotype-6']
input_column_1 = [... | 1,878 | 893 |
import os
import sys
import posthoganalytics
from django.apps import AppConfig
from django.conf import settings
from posthog.utils import get_git_branch, get_git_commit, get_machine_id
from posthog.version import VERSION
class PostHogConfig(AppConfig):
name = "posthog"
verbose_name = "PostHog"
def read... | 1,548 | 460 |
import os
import json
import time
from datetime import timedelta
class TaskTimer:
def __init__(self):
self.time_performance = {}
self.start_times = {}
def start(self, task):
self.start_times[task] = time.time()
print('--- [{}] Start "{}"'.format(time.ctime(self.start_times[ta... | 836 | 265 |
#!/usr/bin/env python3
flags = ['QCTF{2a5576bc51a5c3feb82c96fe80d3a520}', 'QCTF{eb2ddbf0e318812ede843e8ecec6144f}', 'QCTF{5cdf65c6069a6b815352c3f1b4d09a56}', 'QCTF{69d7b7deb23746b8bd18b22f3eb92b50}', 'QCTF{44e37938c0bc05393b5b33a70c5a70db}', 'QCTF{3b37a953391e38ce0b8e168e9eaa6ec5}', 'QCTF{ee2848cb73236007d36cb5ae75c4... | 8,718 | 7,262 |
# Create your views here.
from django.core.urlresolvers import reverse
from django.http.response import JsonResponse, HttpResponse
from settings.settings import AUTHORIZED_KEYS_FILE, SITE_URL
from bioshareX.models import Share, SSHKey, MetaData, Tag
from bioshareX.forms import MetaDataForm, json_form_validate
from guar... | 18,186 | 5,476 |
import datetime
import os, sys
import pprint
import requests
from pandas.io.json import json_normalize
import pandas as pd
URL = 'https://wsn.latice.eu/api/query/v2/'
#URL = 'http://localhost:8000/wsn/api/query/v2/'
#TOKEN = os.getenv('WSN_TOKEN')
TOKEN = os.getenv('WSN_TOKEN')
path = os.getcwd()
def query(
limi... | 5,192 | 1,647 |
from django.utils import translation
from olympia import amo
from olympia.amo.tests import TestCase, ESTestCase
from olympia.addons.models import Addon
from olympia.reviews import tasks
from olympia.reviews.models import (
check_spam, GroupedRating, Review, ReviewFlag, Spam)
from olympia.users.models import UserPr... | 4,716 | 1,611 |
''' Spline2.py: wrapper for B. Thijsse et al.'s hyper-spline routines.
Yet another spline interpolation routine. The problem: given a set of
experimental data with noise, find the spline with the optimal number of
knots.
Solution : They use the usual kind of routines to determine least-squares
splines ... | 1,544 | 424 |
from __future__ import annotations
import elasticache_auto_discovery
from pymemcache.client.hash import HashClient
# elasticache settings
elasticache_config_endpoint = "your-elasticache-cluster-endpoint:port"
nodes = elasticache_auto_discovery.discover(elasticache_config_endpoint)
nodes = map(lambda x: (x[1], int(x[2... | 703 | 227 |
import numpy as np
from uniclass_to_nf_ea_com_source.b_code.configurations.common_constants.uniclass_bclearer_constants import PARENT_CODE_COLUMN_NAME, \
UNICLASS2015_OBJECT_TABLE_NAME
def add_parent_code_column_to_uniclass_objects_table(
dictionary_of_dataframes: dict)\
-> dict:
uniclass_201... | 659 | 249 |
import keras.backend as K
from keras.engine import Layer, InputSpec
from keras.layers import Concatenate
from keras import initializers
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
class MixtureDensityLayer(Layer):
"""
Layer for modeling arbitrary functions using neural ne... | 12,046 | 3,628 |
import json
from unittest import mock, TestCase
import check_availability
json_data = \
"""
{
"centers": [
{
"center_id": 1234,
"name": "District General Hostpital",
"name_l": "",
"address": "45 M G Road",
"address_l": "",
"state_name": "Maharashtra",
"state_name_l": ""... | 1,481 | 619 |
from django.contrib import admin
from proposals.models import Proposal, ProposalSessionType
admin.site.register(ProposalSessionType)
admin.site.register(Proposal,
list_display = ["title", "session_type", "audience_level", "cancelled", "extreme_pycon", "invited"]
) | 271 | 87 |
import sys
from cemc.mcmc import ReactionCrdInitializer, ReactionCrdRangeConstraint
import numpy as np
from itertools import product
import time
from numpy.linalg import inv
class CouldNotFindValidStateError(Exception):
pass
class CovarianceCrdInitializer(ReactionCrdInitializer):
"""Initializer for various ... | 12,805 | 3,742 |
from google.cloud import bigquery
from mysql.connector import connect
import os
# writeable part of the filesystem for Cloud Functions instance
gc_write_dir = "/tmp"
def get_file_mysql(mysql_configuration):
"""
Querying data using Connector/Python via *host* MySQL server.
The function return the f... | 3,810 | 1,055 |
from config import *
from fruit import *
from snakebody import *
from wall import *
def scoring(sp, ap):
global score
background_score = pygame.Surface(rectangle)
background_score.fill(color_gray)
score_text = score_font.render(f'Score: {score}', True, color_black, color_gray)
screen.blit(backg... | 2,413 | 848 |
import logging
from preprocessing_pipeline.so.util.config import LOG_LEVEL
def initialize_logger(logger_name):
"""
Configure a named logger (see https://stackoverflow.com/a/43794480).
"""
# create logger for module
module_logger = logging.getLogger(logger_name)
# set lowest log level the log... | 821 | 254 |
import random
# Ex. takes in 2d20 and outputs the string Rolling 2 d20
def roll_str(rolls):
numDice = rolls.split('d')[0]
diceVal = rolls.split('d')[1]
if numDice == '':
numDice = int(1)
return "Rolling %s d%s" % (numDice, diceVal)
# Ex. takes in 2d20 and outputs resultString = 11, 19 result... | 995 | 345 |
# -*- coding: utf-8 -*-
import datetime
from django.test import TestCase
from django.contrib.contenttypes.models import ContentType
from accounts.factories import UserFactory
from categories.factories import CategoryFactory
from documents.factories import DocumentFactory
from default_documents.models import Contrac... | 12,339 | 3,668 |
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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
... | 2,814 | 972 |
from .plots import (
ActivesInactivesPlot,
ConfusionPlot,
RocCurvePlot,
ProjectionPlot,
RegressionPlotRaw,
HistogramPlotRaw,
RegressionPlotTransf,
HistogramPlotTransf,
Transformation,
IndividualEstimatorsAurocPlot,
InidvidualEstimatorsR2Plot,
)
from .. import ZairaBase
from ... | 2,077 | 710 |
#
# Copyright (C) 2013 - 2017 Satoru SATOH <ssato @ redhat.com>
# License: MIT
#
# pylint: disable=missing-docstring,invalid-name,too-few-public-methods
# pylint: disable=ungrouped-imports
from __future__ import absolute_import
import anyconfig.backend.configobj as TT
import tests.backend.common as TBC
from anyconfig... | 2,198 | 768 |
__author__ = 'nhurman'
| 23 | 12 |
import requests
from scrapy.http import HtmlResponse
from sw_downloader.sw_downloader.spiders.smashing_magazine \
import SmashingMagazineSpider
class TestSmashingMagazineSpider:
def test_ruleset(self):
url = ('https://www.smashingmagazine.com/category/wallpapers')
response = requests.get(url... | 1,794 | 586 |
#var
#num, media, i: inteiro
media=0
for i in range(1,11,1):
num=int(input("Digite um número: "))
media = media+num
media=media/i
print (media) | 160 | 66 |
# -*- coding: utf-8 -*-
"""
rio.tasks
~~~~~~~~~~
Implement of rio tasks based on celery.
"""
from time import time
from celery import chord
from requests import ConnectionError
from celery.utils.log import get_task_logger
from rio.core import celery
from rio.core import sentry
from rio.utils.http import dispatch_w... | 4,289 | 1,310 |
import os
import uuid
import json
import argparse
import boto3
USERPOOL = {
'env_var_poolid': 'APPUSERPOOLID',
'env_var_cognito_url': 'COGNITOJWKSURL',
'env_var_pool_client': 'APPCLIENTID',
}
def create_user_pool(pool_name, region, stage):
client = boto3.client('cognito-idp')
resp = client.creat... | 2,932 | 994 |
import hmac
hmac_md5 = hmac.new('secret-key')
f = open('sample-file.txt', 'rb')
try:
while True:
block = f.read(1024)
if not block:
break
hmac_md5.update(block)
finally:
f.close()
digest = hmac_md5.hexdigest()
print digest | 269 | 107 |
# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
from Tea.model import TeaModel
from typing import Dict, List
class AddCityCarApplyHeaders(TeaModel):
def __init__(
self,
common_headers: Dict[str, str] = None,
x_acs_dingtalk_access_token: str = None,
):
... | 31,686 | 10,728 |
#!/usr/bin/env python
''' Este programa se repetirá 3 veces o hasta que se ingrese
la palabra "despedida" y desplegará sólo el número de intentos
fallidos hasta que cualquiera de los eventos ocurentradara. Al
ingresar la palabra "termina" el programa se detendrá.'''
entrada = ""
suma = 0
while su... | 560 | 207 |
"""
Singleton database instance
"""
from typing import TYPE_CHECKING, Any, List, ContextManager, Tuple, Iterable
if not TYPE_CHECKING:
from playhouse.sqlite_ext import SqliteExtDatabase, AutoIncrementField
else: # pragma: no cover
class SqliteExtDatabase:
"""
Mypy stub for the not type-hinted... | 1,337 | 357 |
import os
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.chrome.options import Options
from .driver import Driver
def remote(url, browser="chrome", **kwargs):
if browser != "chrome":
raise ValueError(f"Browser {browser... | 2,582 | 812 |
# Copyrigh 2015 Cisco Systems.
# 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... | 14,153 | 4,409 |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
"""
===================
prospect.viewer.cds
===================
Class containing all bokeh's ColumnDataSource objects needed in viewer.py
"""
import numpy as np
from pkg_resources import resource_filename
import bokeh.plotting a... | 15,656 | 5,113 |
# -*- coding: latin-1 -*-
import json
import pytest
from oidcendpoint.endpoint_context import EndpointContext
from oidcendpoint.oidc.authorization import Authorization
from oidcendpoint.oidc.read_registration import RegistrationRead
from oidcendpoint.oidc.registration import Registration
from oidcendpoint.oidc.token i... | 4,865 | 1,505 |
from django.contrib import admin
from modelapp.models import Project
# Register your models here.
class Projectadmin(admin.ModelAdmin):
list_display = ['startdate','enddate','name','assignedto','priority']
admin.site.register(Project,Projectadmin) | 253 | 68 |
def transaccion(retiro, saldo):
if retiro % 5 != 0:
return(saldo)
elif (saldo - retiro) < 0:
return(saldo)
elif saldo == retiro:
return(saldo)
else:
return(saldo - retiro - 0.5)
def main():
entrada = open("input.txt","r")
salida = open("output.txt","w")
T = ... | 621 | 246 |
import hashlib, json
# def hash(to_hash):
# h = hashlib.md5()
# h.update(bytes(str(to_hash), 'utf-8'))
# return h.hexdigest()
def hash(to_hash, proof_of_work):
s = ''.join(str(_) for _ in (to_hash[:2])) #Add block number and previous hash to string
s += ''.join(str(_) for _ in (to_hash[2])) #Add l... | 538 | 202 |
import logging
import time
import numpy as np
from eda import ma_data, tx_data
from sir_fitting_us import seir_experiment, make_csv_from_tx_traj
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.info("Fitting model.")
# initial values taken from previous fit, used to seed MH sampler efficie... | 1,008 | 398 |
#coding:utf-8
#gaussian plot (position category)
#Akira Taniguchi 2016/06/16
import itertools
import numpy as np
from scipy import linalg
import matplotlib.pyplot as plt
import matplotlib as mpl
from sklearn import mixture
from __init__ import *
from numpy.random import multinomial,uniform,dirichlet
from sci... | 6,877 | 3,572 |
#exclude
import condiment; condiment.install()
#endexclude
if WITH_TIMEBOMB:
timebomb = int(WITH_TIMEBOMB)
print 'timebomb feature is activated, and set to', timebomb
if WITH_INAPP_PURCHASE:
print 'inapp purchase feature is activated'
if WITH_TIMEBOMB and WITH_INAPP_PURCHASE:
print 'both features hav... | 338 | 121 |
import pathlib
import os
import sys
from multiprocessing import resource_tracker
def modify_resource_tracker():
# See discussion: https://bugs.python.org/issue39959
# See source code: https://github.com/python/cpython/blob/master/Lib/multiprocessing/resource_tracker.py
rt = resource_tracker._resource_tracker
def... | 1,096 | 380 |
import csv
import re
import unicodedata
import bs4
import wikia
from modules import utils
from modules.config import Config
class WikiaHandler():
def __init__(self):
config = Config()
self.scraping_config = config.get_scraping_config()
self.parsing_config = config.get_parsing_config()
... | 12,586 | 3,782 |
"""This module contains the general information for CimcvmediaExtMgmtRuleEntry ManagedObject."""
import sys, os
from ...ucsmo import ManagedObject
from ...ucscoremeta import UcsVersion, MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class CimcvmediaExtMgmtRuleEntryConsts():
MOUNT_PROTOCOL_CIFS = "cifs... | 3,949 | 1,534 |
# Copyright (c) 2021 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 appli... | 3,672 | 1,480 |
import mod
def foo():
return 1
try:
mod.foo = foo
except RuntimeError:
print("RuntimeError1")
print(mod.foo())
try:
mod.foo = 1
except RuntimeError:
print("RuntimeError2")
print(mod.foo)
try:
mod.foo = 2
except RuntimeError:
print("RuntimeError3")
print(mod.foo)
def __main__():
... | 327 | 125 |
# Spiro Ganas
# 9/27/17
#
# Python 3 script to
######### NOTES ########################################
# 1. Each "slice" is a 512x512 image, stored in a single .dcm file.
# 2. A 3-dimensional CT Scan consists of between 94 and 541 slices (according to the Stage 1 data).
# 3. We need to rescale all the CT scans so... | 2,295 | 801 |
import json
import os
from setuptools import find_packages, setup
PACKAGE_NAMESPACE_NAME = 'aistorms'
METADATA_FILE_NAME = 'metadata.json'
REQUIREMENTS_FILE_NAME = 'requirements.txt'
_metadata = \
json.load(
open(os.path.join(
os.path.dirname(__file__),
PACKAGE_NAMESPAC... | 852 | 288 |
#!/usr/bin/python
# Copied from https://raw.githubusercontent.com/srv/srv_tools/kinetic/bag_tools/scripts/merge.py since this script is
# not released for indigo.
"""
Copyright (c) 2015,
Enrique Fernandez Perdomo
Clearpath Robotics, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or w... | 3,357 | 1,128 |
from pathlib import Path
IPYTHON_STARTUP_FOLDER = Path.home() / ".ipython" / "profile_default" / "startup"
STARTUP_FILE = IPYTHON_STARTUP_FOLDER / "pyforest_autoimport.py"
def _create_or_reset_startup_file():
if STARTUP_FILE.exists():
STARTUP_FILE.unlink() # deletes the old file
# this is impor... | 1,567 | 491 |
"""
Copyright (c) 2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writin... | 23,430 | 7,578 |
from __future__ import division
print eval('1/2')
exec('print 1/2')
eval(compile('print 1/2', 'wat.py', 'exec'))
print eval(compile('1/2', 'wat.py', 'eval'))
print eval(compile('1/2', 'wat.py', 'eval', 0, 0))
print eval(compile('1/2', 'wat.py', 'eval', 0, ~0))
| 261 | 115 |
from .Document import Document
from .SpectrumDocument import SpectrumDocument
from .Spec2Vec import Spec2Vec
__all__ = [
"Document",
"SpectrumDocument",
"Spec2Vec"
]
| 180 | 58 |
""" Cisco_IOS_XR_wanphy_ui_oper
This module contains a collection of YANG definitions
for Cisco IOS\-XR wanphy\-ui package operational data.
This module contains definitions
for the following management objects\:
wanphy\: WANPHY operational data
Copyright (c) 2013\-2016 by Cisco Systems, Inc.
All rights reserved.... | 22,826 | 6,539 |
#!/usr/bin/env python3
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
import megengine as mge
import numpy as np
import pytest
from megengine.autodiff import GradManager
from basecls.solver.optimizer import LAMB
@pytest.mark.parametrize("weight_decay", [0.0, 0.001])
@pytest.mark.parametrize("betas", [(0.... | 773 | 331 |
import argparse
import logging
import os
import pathlib
import time
import log
import onenote_auth
import onenote
import pipeline
logger = logging.getLogger()
def main():
args = parse_args()
if args.verbose:
log.setup_logging(logging.DEBUG)
else:
log.setup_logging(logging.INFO)
# Al... | 2,180 | 701 |
# (c) 2017 Red Hat Inc.
#
# This file is part of Ansible
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import collections
import os
import json
import p... | 10,391 | 3,291 |
import sqlite3
import tkinter as tk
import pandas as pd
#----------------------------------------------
#Para criação do banco de dados retira o comentário (#) da linha 9 à 23 somente a primeira vez que rodar o cód,
#depois, basta comentar novamente.
#Criando o Banco de Dados
# conexao = sqlite3.connect('Clientes.db'... | 3,433 | 1,324 |
import math
import requests
from pygitbucket.exceptions import (
UnknownError,
InvalidIDError,
NotFoundIDError,
NotAuthenticatedError,
PermissionError,
)
class Client:
BASE_URL = "https://api.bitbucket.org/"
def __init__(self, user: str, password: str, owner=None):
"""Initial ses... | 14,382 | 3,803 |
# 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.
import torch
from torch.utils.data import Dataset
import numpy as np
# These input-data-processing classes take input data from a text file an... | 3,982 | 1,132 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Reads datasets, reads and writes contour coordinates.
"""
import numpy as np
import csv
def read_ecbenchmark_dataset(path='datasets/1year_dataset_A.txt'):
"""
Reads a 2D dataset that uses a an ASCI format with ';' as a seperator.
This format... | 3,594 | 1,158 |
"""
@file
@brief Test for :epkg:`cartopy`.
"""
import numpy
import numba
@numba.jit(nopython=True, parallel=True)
def logistic_regression(Y, X, w, iterations):
"Fits a logistic regression."
for _ in range(iterations):
w -= numpy.dot(((1.0 / (1.0 + numpy.exp(-Y * numpy.dot(X, w))) - 1.0) * Y), X)
r... | 601 | 241 |
class ToFile:
""" Classe que recebe uma instância de dados e os salva em um arquivo de saída. """
def __init__(self, path, data):
maxs = [len(x) + 4 for x in data.legend]
with open(path, 'w') as file:
file.write('id' + (' ' * 6))
for index, element in enumerate(data.legend):
file.write(... | 793 | 281 |
# Copyright (c) 2021 kamyu. All rights reserved.
#
# Google Code Jam 2021 Round 3 - Problem C. Fence Design
# https://codingcompetitions.withgoogle.com/codejam/round/0000000000436142/0000000000813bc7
#
# Time: O(NlogN) on average, pass in PyPy2 but Python2
# Space: O(N)
#
from random import seed, randint
# Compute t... | 4,056 | 1,645 |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 2.0.11
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (2,6,0):
def swig_import_helper():
from os.path impo... | 50,505 | 19,060 |
"""Tests for the AMP Renderer project."""
| 42 | 13 |
from pprint import pprint
'''The module has class Grid for solving sudoku.
Grid should be given as a list of integers or a path to a file.
'''
class Grid():
'''Class for solving sudoku.
'''
def __init__(self, path= None, grid= None) -> None:
'''Initialize grid, columns, squares.
'''
... | 3,564 | 1,300 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
import pytest
import logging
import json
import threading
from utils import get_random_dict
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INF... | 1,421 | 417 |
# GPLv3 License
#
# Copyright (C) 2020 Ubisoft
#
# 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.
#
# This program is dis... | 6,588 | 2,044 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import math, sys
import svgwrite
#
# http://www.w3.org/TR/SVG11/struct.html#UseElement
#
# For more information on tesselation / tiling see http://en.wikipedia.org/wiki/Wallpaper_group
# The organization of these tilings are from the interesting book
# Designing Te... | 17,258 | 8,310 |