text stringlengths 2 999k |
|---|
import FWCore.ParameterSet.Config as cms
standAloneMuonsMCMatch = cms.EDProducer("MCTrackMatcher",
trackingParticles = cms.InputTag("mix","MergedTrackTruth"),
tracks = cms.InputTag("standAloneMuons"),
genParticles = cms.InputTag("genParticles"),
associator = cms.InputTag('trackAssociatorByHits')
)
|
import unittest
import redis
import uuid
import threading
from token_redis import *
class TestCh02(unittest.TestCase):
def setUp(self):
import redis
self.conn = redis.Redis(db=15)
def tearDown(self):
conn = self.conn
to_del = (
conn.keys('login:*') + conn.keys('rece... |
"""Tests for the token-based transformers in IPython.core.inputtransformer2
Line-based transformers are the simpler ones; token-based transformers are
more complex. See test_inputtransformer2_line for tests for line-based
transformations.
"""
import nose.tools as nt
import string
from IPython.core import inputtransfo... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-03 10:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('umklapp', '0011_auto_20160603_0912'),
]
operations = [
migrations.AlterField... |
from mixer.backend.django import mixer
from django.db.utils import IntegrityError
from django.test import TestCase
from user.models import User
class UserModelsTestCase(TestCase):
"""
Test User model
"""
def test_unique_email(self):
mixer.blend(User, email="test@user.com")
with self... |
"""
Estimate the Rosenbrock function parameters a and b
for the function f(x,y) = (a - x)^2 + b(y - x^2)^2
using generated data similar to a typical parameter
estimation problem
"""
import time
import numpy as np
import pandas as pd
from scipy.optimize import minimize
from scipy.optimize import Bounds
from estimator.m... |
import requests
from innexiaBot import dispatcher
from innexiaBot.modules.disable import DisableAbleCommandHandler
from telegram import ParseMode, Update
from telegram.ext import CallbackContext, run_async
@run_async
def paste(update: Update, context: CallbackContext):
args = context.args
message = update.eff... |
from . import spsolve
from heapq import heappush, heappop
import numpy as np
import warnings
class GraphTraversal:
"""
Traverse a supply chain, following paths of greatest impact.
This implementation uses a queue of datasets to assess. As the supply chain is traversed, datasets inputs are added to a list sorted ... |
import os
import sys
import django
BASE_PATH = os.path.dirname(__file__)
def main():
"""
Standalone django model test with a 'memory-only-django-installation'.
You can play with a django model without a complete django app installation.
http://www.djangosnippets.org/snippets/1044/
"""
os.envir... |
import pytest
from helpers.cluster import ClickHouseCluster
cluster = ClickHouseCluster(__file__)
node1 = cluster.add_instance('node1', with_zookeeper=True)
node2 = cluster.add_instance('node2', with_zookeeper=True)
# no adaptive granularity by default
node3 = cluster.add_instance('node3', image='yandex/clickhouse-s... |
from typing import List
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
class SoftCrossEntropyLoss(nn.Module):
"""
Calculate the CrossEntropyLoss with soft targets.
:param weight: Weight to assign to each of the classes. Default: None
:type weight: list of... |
from datetime import date
ano = int(input('Qual ano você quer analisar? (Coloque zero para o ano atual.) '))
if ano == 0:
ano = date.today().year
if ano % 4 == 0 and ano % 100 != 0 or ano % 400 == 0:
print('O ano {} é bissexto'.format(ano))
else:
print('O ano {} não é bissexto.'.format(ano))
|
__version__ = '1.31'
|
"""
Original code from John Schulman for CS294 Deep Reinforcement Learning Spring 2017
Adapted for CS294-112 Fall 2017 by Abhishek Gupta and Joshua Achiam
Adapted for CS294-112 Fall 2018 by Soroush Nasiriany, Sid Reddy, and Greg Kahn
"""
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
im... |
#!/usr/bin/env python
# *-* coding: UTF-8 *-*
"""
Organizaţia Internaţională a Aviaţiei Civile propune un alfabet în care
fiecărei litere îi este asignat un cuvânt pentru a evita problemele în
înțelegerea mesajelor critice.
Pentru a se păstra un istoric al conversațiilor s-a decis transcrierea lor
conform următoarelor... |
def response_mapper(response_list, key=None):
if key:
return [stadistic[key] for stadistic in response_list]
return response_list
|
# Definition for a undirected graph node
# class UndirectedGraphNode:
# def __init__(self, x):
# self.label = x
# self.neighbors = []
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
root = UndirectedG... |
#위에서 아래로 정렬
n = 3
array = [15, 27, 12]
result = sorted(array, reverse=True)
for i in result:
print(i, end=' ')
print(' ')
|
"""
This is a module for downloading menus from dining.rice.edu.
The main external method to use is "process_servery_menu(servery)"
Servery is one of the following:
'seibel'
'north'
'baker'
'sid'
'west'
'south'
The result is a dict of the following structure:
{
'base_date': The day the me... |
# -*- coding: utf-8 -*-
#
# pynsq documentation build configuration file, created by
# sphinx-quickstart on Sun Jun 16 16:18:30 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All c... |
# Generated by Django 3.2.7 on 2021-11-23 11:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0003_auto_20211028_1323'),
]
operations = [
migrations.AddField(
model_name='document',
name='author',
... |
from custom_components.script_engine.engine import Engine
from custom_components.script_engine.decorator import ToState
class _Script_ExampleSimple(Engine):
@ToState(id="group.family", state="home")
def _script_is_home(self, *args, **kwargs):
self.hass.services.call( "light", "turn_on", target = { "e... |
import json
from pathlib import Path
from sphinx.application import Sphinx
from idom.core.vdom import VDOM_JSON_SCHEMA
def setup(app: Sphinx) -> None:
schema_file = Path(__file__).parent.parent / "vdom-json-schema.json"
current_schema = json.dumps(VDOM_JSON_SCHEMA, indent=2, sort_keys=True)
# We need t... |
from nearest import nearest_square
def test_nearest_square_5():
assert(nearest_square(5) == 4)
def test_nearest_square_12():
assert(nearest_square(12) == 9) |
# -*- coding: utf-8 -*-
from limonero.models import *
from flask import current_app
def test_storage_fail_not_authorized(client):
tests = [
lambda: client.get('/storages'),
lambda: client.post('/storages'),
lambda: client.get('/storages/1'),
lambda: client.patch('/storages/1'),
... |
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets 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 appl... |
#! /usr/bin/env python3
"""
Bishbot - https://github.com/ldgregory/bishbot
Leif Gregory <leif@devtek.org>
space.py v0.1
Tested to Python v3.7.3
Description:
Bot commands for the Space channel
Changelog:
20200603 - Initial code
Copyright 2020 Leif Gregory
Licensed under the Apache License, Version 2.0 (the "Licens... |
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: Mcl_Cmd_GeZu_KernelMemory_Tasking.py
def TaskingMain(namespace):
import mcl.tasking
procedure = mcl.tasking.GetProcedureNumber()
if pro... |
'''
Created on Dec 20, 2014
@author: scarriere
'''
from event.IngoingEvent import IngoingEvent
from aiclient.Singleton import Singleton
from world.World import World
class StartGameEvent(IngoingEvent):
def __init__(self):
pass
def fillArguments(self, string):
pass
def execut... |
from flask import render_template, url_for, request, redirect
from flask.ext.login import login_required, current_user
import rfk
import rfk.site
import rfk.database
import rfk.liquidsoap
from rfk.site.helper import permission_required
from rfk.site.forms.stream import new_stream
from rfk.database.streaming import Str... |
# -*- coding: utf-8 -*-
# Owner(s): ["module: unknown"]
import itertools
import logging
import re
import torch
from torch import nn
from torch.ao.sparsity import BaseSparsifier, WeightNormSparsifier, FakeSparsity, NearlyDiagonalSparsifier
from torch.nn.utils.parametrize import is_parametrized
from torch.testing._int... |
from django.db import models
from usuarios.models import Usuario
from corporaciones.models import Corporacion
class Votante(models.Model):
usuario = models.ForeignKey(Usuario)
codigo = models.BigIntegerField(unique=True, primary_key=True)
plan = models.ForeignKey(Corporacion)
is_active = models.BooleanField(defaul... |
# Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
"""
============================================================
Single estimator versus bagging: bias-variance decomposition
============================================================
This example illustrates and compares the bias-variance decomposition of the
expected mean squared error of a single estimator again... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License... |
#!/usr/bin/env python
#
# Copyright 2013 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
import numpy as np
import torch
import os
import random
class EarlyStopMonitor(object):
def __init__(self, max_round=3, higher_better=True, tolerance=1e-3):
self.max_round = max_round
self.num_round = 0
self.epoch_count = 0
self.best_epoch = 0
self.last_best = None
... |
# Copyright 2018 ICON Foundation
#
# 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 writi... |
import numpy as np
from sklearn.ensemble import GradientBoostingClassifier, GradientBoostingRegressor
from sklearn.ensemble._gb import BaseGradientBoosting
from .tree import RRDecisionTreeRegressor
class RRBaseGradientBoosting(BaseGradientBoosting):
"""Abstract base class for Random Rotation Gradient Boosting."""... |
import glob
import numpy as np
#import matplotlib.pyplot as plt
mt_files = glob.glob("../logs/mt_*.log")
mp_files = glob.glob("../logs/mp_*.log")
print(mt_files)
print(mp_files)
values = {}
for fn in mt_files:
with open(fn, "r") as file:
values[fn] = np.array([float(x.rstrip()) for x in file.readlines()]... |
# https://github.com/fixstars/ion-csharp/blob/master/test/Test.cs
from ionpy import Node, Builder, Buffer, PortMap, Port, Param, Type, TypeCode
import numpy as np # TODO: rewrite with pure python
def test_all():
t = Type(code_=TypeCode.Int, bits_=32, lanes_=1)
input_port = Port(key='input', type=t, dim=2)
... |
import typing
import logging
from pandas import DataFrame
class ReferenceLookup:
def __init__(
self, key: str, field: typing.Any, dict: typing.Any, multivalue: bool = False
):
self.key = key
self.field = field
self.dict = dict
self.multivalue = multivalue
def loo... |
# @lc app=leetcode id=713 lang=python3
#
# [713] Subarray Product Less Than K
#
# https://leetcode.com/problems/subarray-product-less-than-k/description/
#
# algorithms
# Medium (41.34%)
# Likes: 2990
# Dislikes: 106
# Total Accepted: 125.1K
# Total Submissions: 298.2K
# Testcase Example: '[10,5,2,6]\n100'
#
# G... |
"""
Extract Cells Inside Surface
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Extract the cells in a mesh that exist inside or outside a closed surface of
another mesh
"""
###############################################################################
# sphinx_gallery_thumbnail_number = 2
import pyvista as pv
from pyvista import exa... |
#!/usr/bin/env python3
import socket
SERVER_PORT = 9099
BUF_SIZE = 1024
colors = [(192, 133, 19),
(181, 18, 27),
(76, 91, 105),
(182, 151, 93),
(0, 120, 255),
(20, 20, 20)]
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("", SERVER_PORT)) # bind... |
from setuptools import setup
from setuptools import find_packages
from distutils.command.clean import clean
from distutils.extension import Extension
from distutils.sysconfig import get_config_vars
from Cython.Build import cythonize
import os, platform, sys, fnmatch
import numpy
def setup_package():
# Get Platfo... |
#!/usr/bin/python3
from __future__ import print_function
from Tkinter import *
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from PIL import Image, ImageTk
import datetime
import json
import locale
import time
import locale
import threading
import fe... |
### Loader functions:
_VERSION = '1.3.3'
def setversion(version):
if version != _VERSION:
raise ValueError, 'Dynamic versioning not available'
def setalphaversions(*alpha_versions):
if alpha_versions != ():
raise ValueError, 'Dynamic versioning not available'
def version(alpha = 0):... |
'''
What about deleting the input of an Entry object, every time, we are showing the content in our function show_entry_fields()? No problem! We can use the delete method. The delete() method has the format delete(first, last=None). If only one number is given, it deletes the character at index. If two are given, the r... |
import os
import unittest
from checkov.cloudformation.checks.resource.aws.RedShiftSSL import check
from checkov.cloudformation.runner import Runner
from checkov.runner_filter import RunnerFilter
class TestRedShiftSSL(unittest.TestCase):
def test_summary(self):
runner = Runner()
current_dir = os.p... |
import re
import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
class TestSeriesReplace:
def test_replace(self, datetime_series):
N = 100
ser = pd.Series(np.random.randn(N))
ser[0:4] = np.nan
ser[6:10] = 0
# replace list with a single value
... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.21
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... |
# AUTOGENERATED! DO NOT EDIT! File to edit: 00_core.ipynb (unless otherwise specified).
__all__ = ['rgb2gray', 'otsu_thresh_4largest_component', 'component_closest_center', 'get_center', 'denormalizePatches',
'figs_horizontal2', 'figs_comparison', 'figs_horizontal3', 'plot_inpaints_pairs', 'channels_first_l... |
#!/usr/bin/env python3
import argparse
import pandas as pd
import sys
def get_args():
'''This function parses and return arguments passed in'''
parser = argparse.ArgumentParser(
prog='normalizedReadCount',
description='Counts reads aligned to genome, and normalize by genome size')
parser... |
from .api_token import APITokenData
from .login import LoginData, LoginResponse
from .user import UserData
from .campaign import CampaignData
from .product import ProductData
from .payment import PaymentData
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Determine pixel/inch ratio from linescan across ruler
Inputs:
filename - full path to csv file containing Position and Intensity Value
Assumes:
Image is taken of inch side of ruler, and smallest ticks are 1/8 inch increment
@author: tabatabai
"""
import numpy as np
... |
# This file is MACHINE GENERATED! Do not edit.
# Generated by: tensorflow/python/tools/api/generator/create_python_api.py script.
"""Code for model cloning, plus model-related API entries.
"""
from __future__ import print_function
from tensorflow.python.keras import Model
from tensorflow.python.keras import Sequenti... |
import torch
from torch import nn
import torch.nn.functional as F
class Network(nn.Module):
def __init__(self, input_size, output_size, hidden_layers, drop_p=0.5):
''' Builds a feedforward network with arbitrary hidden layers.
Arguments
---------
input_size: in... |
#!/usr/bin/env python
import os
import sys
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import scoped_session
from chatter4.models import Base
from pyramid.paster import (
get_appsettings,
setup_logging,
)
DBSes... |
# Calcular o IMC de uma pessoa
cores = {
'limpo':'\033[m',
'verde':'\033[32m',
'amarelo':'\033[33m',
}
linha = f'{cores["amarelo"]}-=' * 26 + f'{cores["limpo"]}'
print(linha)
print('Vamos calcular seu IMC!')
print(linha)
peso_kg = str(input('Preciso saber seu peso, em Quilogramas: ')).strip()
alt_metros ... |
"""
/*
* Copyright (c) 2021, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
"""
from utils.GlobalVars import *
from recbole.config import Config, EvalSetting
from r... |
def hanoi(n, A, B, C):
if n == 1:
print(A, '--->', C)
else:
hanoi(n-1, A, C, B)
hanoi(1, A, B, C)
hanoi(n-1, B, A, C)
if __name__ == "__main__":
hanoi(3, 'A', 'B', 'C')
|
import pytest
import stix2generator.exceptions
def test_string(object_generator, num_trials):
for _ in range(num_trials):
value = object_generator.generate_from_spec({
"type": "string",
"minLength": 1,
"maxLength": 5
})
assert 1 <= len(value) <= 5
... |
import pygame
pygame.init()
# set the size of the window
screen_size = (800, 600)
screen = pygame.display.set_mode(screen_size)
# set the background color for the window
color = (0, 0, 0)
screen.fill(color)
# create a box at the coordinates 100, 100 with the size 10, 10
# and the color (255, 255, 255)
color = (255,... |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
"""
@ide: PyCharm
@author: Lauro Ângelo Gonçalves de Moraes
@contact: lauromoraes@ufop.edu.br
@created: 20/06/2020
"""
import tensorflow as tf
from tensorflow.keras import models
from tensorflow.keras.layers import (
Input,
Embedding,
Conv2D,
Conv1D,
MaxP... |
# 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, software
# distribu... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import getdate, nowdate
no_cache = 1
no_sitemap = 1
def get_context(context):
result = []
q = "select employee_name, work_... |
from contextlib import nullcontext
import pandas as pd
from pprint import pprint
from neo4j import GraphDatabase, basic_auth
from py2neo import Graph
empty_cq = """
// Your query goes here
"""
'''
This is a neo4j library 1.0
'''
class Neo_lib:
def __init__(self, neo_url, neo_user, neo_pwd, neo_database):
... |
# -*- coding: utf-8 -*-
'''
Created on 1983. 08. 09.
@author: Hye-Churn Jang, CMBU Specialist in Korea, VMware [jangh@vmware.com]
'''
name = 'ChangeName' # subscription action name
sdk = 'vra' # imported SDK at common directory
inputs = {
'VraManager': 'constant'
} |
""" In General, this function does pretty much just this pretty
simple thing. This can't be deduced by the test's documentation
though, and must be written by the author.
"""
|
import json
import time
import calendar
from threading import Thread
from binance.definitions import OrderSide, OrderStatus
from decimal import Decimal
class Tracker(Thread):
def __init__(self, connection, interval=30):
super().__init__()
self.connection = connection
self.tracking_list = [... |
"""Provides functionality for ranking Records and their differences."""
from .db import sesh
from .record import Record, RA
from .difference import Diff, difference
from .filter import filter_
from .exceptions import FilterMetricError
def rank(date, metric, usernames=None, record_filters=None):
"""Rank the Record... |
from typing import List
from torch.optim import Adam
from neuralNets.flair.flair.data_fetcher import NLPTaskDataFetcher, NLPTask
from neuralNets.flair.flair.data import TaggedCorpus
from neuralNets.flair.flair.embeddings import TokenEmbeddings, WordEmbeddings, StackedEmbeddings, CharLMEmbeddings, CharacterEmbeddings , ... |
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path
from django.views import defaults as default_views
from django.views.generic import TemplateView
from rest_framework.authtoken.views import obtain_auth_token
from drf_yasg i... |
""""""
""" _e-e_
_(-._.-)_
.-( `---' )-.
__\ \\\___/// /__
'-._.'/M\ /M\`._,-
Froggy's Home
"""
from flask import Flask, make_response, request, render_template, redirect, url_for, jsonify
from configparser import SafeConfigParser
import froggy, os, functools, subprocess, shlex
TEMPLATE_FOLDER =... |
#
# Copyright 2019 The FATE 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.FileItem import FileItem
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.AntMerchantExpandIndirectBindConsultModel import AntMerchantExpandIndirectBindConsultModel
class AntMerchantExpandIndirectBindConsul... |
'''
@Author: Shuai Wang
@Github: https://github.com/wsustcid
@Version: 1.0.0
@Date: 2020-09-11 23:42:23
@LastEditTime: 2020-10-13 22:32:20
'''
import os
import sys
import argparse
from datetime import datetime
import time
from tqdm import tqdm
import time
import numpy as np
import tensorflow as tf
base_dir = os.path... |
# import pandas as pd
# data = pd.read_csv('deputes-active.csv')
# print(data.head())
from pyprotege.ontology import Ontology
from pyprotege.ontology_class import OntologyClass
from pyprotege.data_property import DataProperty
from pyprotege.object_property import ObjectProperty
from pyprotege.individual import Indivi... |
#!/usr/bin/env python3
from env import env
from run_common import AWSCli
from run_common import print_session
aws_cli = AWSCli('us-east-1')
ses = env['ses']
def terminate_config_set():
for cs in ses['CONFIGURATION_SETS']:
name = cs['NAME']
cmd = ['ses', 'delete-configuration-set',
... |
# Copyright (c) 2021 Oleg Polakow. All rights reserved.
# This code is licensed under Apache 2.0 with Commons Clause license (see LICENSE.md for details)
"""Utilities for requests."""
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from urllib.parse imp... |
import json
import os
import time
import schedule
with open(r'..\..\secrets.json') as f:
s = f.read()
d = json.loads(s)
PYTHONPATH_ABS = d['PYTHONPATH_ABS']
REPO_ROOT = d['REPO_ROOT']
def calld_django_send_diary_user_email():
time_string = time.strftime('%Y%m%d%H%M%S')
print(time_string)
print('sta... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# ritpytrading documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 9 13:47:02 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
... |
# -*- coding: utf-8 -*-
"""
Common utility functions for the reclass adapters
http://reclass.pantsfullofunix.net
"""
from __future__ import absolute_import, print_function, unicode_literals
import os
# Import python libs
import sys
def prepend_reclass_source_path(opts):
source_path = opts.get("reclass_source_pa... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""This file contains tests for the mrt_file.py file.
For specifics on each test, see the docstrings under each function.
"""
from subprocess import check_call
import pytest
from ..mrt_file import MRT_File
from ..mrt_parser import MRT_Parser
from ..tables import MRT_... |
import pytest
import requests
from unittest.mock import patch
def test_token_auth_wrong_token(
client, settings, mocked_token_auth, not_auth_response):
"""Assert that on authentication error the handle_auth_exception method
of TokenAuth gets called."""
client.settings = settings
client.aut... |
def quandl_apikey_set(apikey, filename=None):
"""Store the Quandl Token in $HOME/.updoon_quandl
Parameters:
-----------
apikey : str
The API Key from the Quandl Website.
See https://www.quandl.com/account/api
filename : str
Absolute path to the text where the
Quand... |
"""
百分制成绩转等级制成绩
90分以上,输出A
80分~89分,输出B
70分~79分,输出C
60分~69分,输出D
60分以下,输出E
Version: 0.1
Author: 骆昊
Date: 2018-02-28
"""
score = float(input('请输入成绩: '))
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'E'
print('对应的等级是... |
from types import MethodType
import pandas as pd
import numpy as np
from .server_side import VeneerNetworkElementActions
from .utils import _quote_string
GET_LOSS_TABLE_SCRIPTLET='''
ignoreExceptions=False
fn = target.lossFct
for row in fn:
result.append((row.Key,row.Value))
'''
class VeneerLossNodeActions(Veneer... |
#!/usr/bin/env python
import pcbnew
import math
class Vec:
def __init__(self, x=0, y=0):
if type(x) in [pcbnew.wxPoint, Vec]:
self.x = x.x
self.y = x.y
else:
self.x = x
self.y = y
def __add__(self, o):
return Vec(self.x + o.x, self.y + o... |
from typing import Iterable, Optional
from app.integrations.mailchimp import exceptions
from app.integrations.mailchimp.http import MailchimpHTTP
from app.integrations.mailchimp.member import MailchimpMember
from users.models import User
class AppMailchimp:
def __init__(self):
self.http = MailchimpHTTP()... |
import unittest
import lambda_function
class FindTaco(unittest.TestCase):
def test_find_none(self):
self.assertEqual(lambda_function.find_taco("test test :taco test"), 0)
def test_find_one(self):
self.assertEqual(lambda_function.find_taco("test test :taco: test"), 1)
def test_find_two(s... |
def search_recommendations():
query = """
query ($id: Int, $type: MediaType, $search: String) {
Media(search: $search, id: $id, type: $type) {
recommendations {
edges {
node {
mediaRecommendation {
id
... |
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Employee(Base):
"""Person that works for a company."""
__tablename__ = "employee"
id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
name = sa.Column(sa.String, index=True, n... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016-2018 by Ihor E. Novikov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any la... |
#!/usr/bin/env python3
import os
import frida
import glob
import time
import json
from frida_tools.application import ConsoleApplication
PWD = os.path.dirname(os.path.abspath(__file__))
class Application(ConsoleApplication):
SESSION_ID_LENGTH = 32
MASTER_KEY_LENGTH = 48
def _add_options(self, parser):... |
"""
WSGI config for BeltReviewer project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO... |
import numpy as np
import benchml.transforms as btf
from benchml.hyper import BayesianHyper, GridHyper, Hyper
from benchml.models.mod_dscribe import compile_dscribe, compile_dscribe_periodic
def compile_null(**kwargs):
return []
def compile_physchem(custom_fields=None, with_hyper=False, **kwargs):
if custo... |
from conqueror.app import app
from conqueror.cassandra import session
from conqueror.utils import as_json
@app.route('/v1/view-businesses/<string:sector>')
@as_json
def get_businesses(sector: str):
"""
Get a list of Russian businesses to post reviews for
---
parameters:
- in: path
name: sect... |
from django.urls import re_path
from . import views
urlpatterns = [
re_path(r'^APP/queue/(?P<identifier>ark:\/\d+\/.+?)/$', views.queue, name='app-detail'),
re_path(r'^APP/queue/$', views.queue, name='app-list'),
re_path(r'^queue/$', views.queue_recent, name='replication-index'),
re_path(r'^queue/(?P<i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.