text stringlengths 1 927k |
|---|
import torch
from allennlp.common.testing import AllenNlpTestCase
from allennlp.modules.seq2seq_encoders.gated_cnn_encoder import GatedCnnEncoder
class TestGatedCnnEncoder(AllenNlpTestCase):
def test_gated_cnn_encoder(self):
cnn_encoder = GatedCnnEncoder(
input_dim=32,
layers=[[[4... |
# Copyright (C) 2018 British Broadcasting 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 ... |
from chainer import cuda
from chainer import function
from chainer.utils import type_check
class SelectorBase(function.Function):
"""Select an array element from a given axis or set of axes."""
def __init__(self, axis=None, keepdims=False):
self.keepdims = keepdims
if axis is None:
... |
from django.urls import path
from employees_app.template_examples.views import index
urlpatterns = (
path('', index, name='templates index'),
) |
from enum import unique
from flask_pymongo import PyMongo
from pymongo import MongoClient
from settings import MONGO_URI
Client = MongoClient(MONGO_URI)
db = Client["Quizlet"]
users_db = db.users
auths_db = db.auths
decks_db = db.decks
cards_db = db.cards
users_db.create_index(("email"), unique=True)
users_db.create_... |
from . import __main__
name = "jonze"
train = __main__.train
test = __main__.test |
import json
import sys
from collections import OrderedDict
from anchore_engine.subsys import logger
from anchore_manager.util.proc import ExitCode
from anchore_manager.util.config import DEFAULT_CONFIG
import logging
# Sane default
_log_config = DEFAULT_CONFIG
def format_error_output(config, op, params, payload):
... |
import numpy as np
class LDA:
def __init__(self, n_components):
self.n_components = n_components
self.linear_discriminants = None
def fit(self, X, y):
n_features = X.shape[1]
class_labels = np.unique(y)
# Within class scatter matrix:
# SW = sum((X_c - mean_X_c... |
#!/usr/bin/env python
# Teardrop for pcbnew using filled zones
# This is the plugin WX dialog
# (c) Niluje 2019 thewireddoesntexist.org
#
# Based on Teardrops for PCBNEW by svofski, 2014 http://sensi.org/~svo
# Cubic Bezier upgrade by mitxela, 2021 mitxela.com
# Fixed fpr KiCAD 6 nightly by Gymb2015 (MISC)
import wx
... |
import pytest
import re
import math
import textwrap
from decimal import Decimal
def normalize_layout_string(layout_string):
"""normalize a layout string such that it is characterwise identical
to the output of the 'dump' command
"""
layout_string = layout_string.replace('\n', ' ')
# drop multiple ... |
import datetime
import math
from time import sleep
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from tqdm import trange, tqdm
# params
# for client id and secret, create a new application over at https://developer.spotify.com/dashboard
# when running this script for the first time, your browser will be redi... |
#!C:\Users\teste\PycharmProjects\desafios\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==40.8.0','console_scripts','easy_install-3.7'
__requires__ = 'setuptools==40.8.0'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.py... |
"""
Author: Moustafa Alzantot (malzantot@ucla.edu)
"""
import time
import os
import sys
import random
import numpy as np
import tensorflow as tf
from setup_inception import ImageNet, InceptionModel
import utils
from genattack_tf2 import GenAttack2
flags = tf.app.flags
flags.DEFINE_string('input_dir', '', 'Path f... |
import argparse
import json
import copy
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader
from datasets.shapenet import build_shapenet
from models.nerf import build_nerf
from models.rendering import get_rays_shapenet, sample_points, volume_render
def inner_loop(model, optim, imgs, p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
- author: Lkeme
- contact: Useri@live.cn
- file: AsyncioLoop
- time: 2019/9/18 12:54
- desc: 兼容不同系统的协程逻辑
"""
import asyncio
import platform
# 自动判断类型生成loop
def switch_sys_loop():
sys_type = platform.system()
if sys_type == "Windows":
loop = asyncio.Proa... |
from deficrawler.transformer import Transformer
class Mappers:
"""
Class to map the data from the subgraph data to the commom model defined in the json file.
For each field applies the transformaton (if needed) and retuns the entity with all
the fields.
"""
@staticmethod
def map_data(resp... |
# Copyright (c) 2019-2022 ThatRedKite and contributors
from typing import Optional
from discord.ext import commands
from wand.image import Image as WandImage
from wand.color import Color as WandColor
import discord
import si_prefix
from math import sin, atan
from io import BytesIO
from thatkitebot.backend import uti... |
# Copyright 2016 Alethea Katherine Flowers
#
# 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... |
import pandas as pd
csv1 = pd.read_csv('D:\my_documents\competition\government\Report\event1\\500-593.csv',header=None)
csv2 = pd.read_csv('D:\my_documents\competition\government\Report\event1\\comment594.csv',header=None)
csv3 = pd.read_csv('D:\my_documents\competition\government\Report\event1\\comment855.csv',header... |
# Copyright (c) 2021 zfit
import tensorflow as tf
import zfit
from zfit import z
class CustomPDF2D(zfit.pdf.BasePDF):
"""My custom, 2 dimensional pdf. The axes are: Energy, Momentum.
"""
def __init__(self, param1, param2, param3, obs, name="CustomPDF", ):
# we can now do complicated stuff her... |
from datetime import date, time, datetime, timedelta
def trabalhando_com_datetime():
data_atual = datetime.now()
print(data_atual)
print(data_atual.strftime('%d/%m/%Y %H:%M:%S'))
print(data_atual.strftime('%c'))
print(data_atual.weekday())
tupla = ('Segunda','Terça','Quarta','Quinta','Sexta','S... |
from pyopenproject.business.principal_service import PrincipalService
from pyopenproject.business.services.command.principal.find_all import FindAll
class PrincipalServiceImpl(PrincipalService):
def __init__(self, connection):
super().__init__(connection)
def find_all(self, filters=None):
re... |
from dataclasses import dataclass
@dataclass
class Icon:
name: str = ""
src: str = "" |
import autograd.numpy as np
class signalGenerator:
'''
This class inherits the Signal class. It is used to organize
1 or more signals of different types: square_wave,
sawtooth_wave, triangle_wave, random_wave.
'''
def __init__(self, amplitude=1, frequency=1, y_offset=0):
'''... |
# Generated by Django 3.0.9 on 2020-08-09 15:38
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('gifapp', '0010_auto_20200809_0123'),
]
operations = [
migrations.RemoveField(
model_name='comment',
name='parent_id',
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 8 22:09:47 2021
@author: Apple
"""
def start():
import numpy as np
import scipy.io as sio
import sklearn.ensemble
from sklearn import svm
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import confusion_matrix
from skl... |
from BinaryHeapPriorityQueue.binary_heap_pq import BinaryHeapPriorityQueue |
def get(mist_session, org_id):
uri = "/api/v1/orgs/%s" % org_id
resp = mist_session.mist_get(uri, org_id=org_id)
return resp
def create(mist_session, org_id, org_settings):
uri = "/api/v1/orgs/%s" % org_id
body = org_settings
resp = mist_session.mist_post(uri, org_id=org_id, body=body)
retu... |
from .functions import open_uri_with_browser
from .image_processing import get_colored_image_base64_by_region
from .settings import get_setting
from .shared import global_get
from .types import ImageDict
import sublime
POPUP_TEMPLATE = """
<body id="open-uri-popup">
<style>
img {{
width: {w}{si... |
"""
Módulo que representa um ticket, uma pessoa ou um serviço.
Não deve ser usado diretamente, mas obtido no retorno de algum método
da classe Entity ou Query.
Exemplo de uso:
>>> from pyvidesk.tickets import Tickets
>>> tickets = Tickets(token="my_token")
>>> ticket = ticket.get_by_id(3)
>>> print(ticket)
... <Mod... |
from networks.io import NetworkIO
from networks.context.io import ContextLevelNetworkIO
from debug import TextDebugKeys
class TextLevelNetworkIO(NetworkIO):
"""
IO for Text level classification via Neural Networks
"""
def __init__(self, model_name, ctx_model_name):
super(TextLevelNetworkIO, s... |
# Import modules
import groupdocs_conversion_cloud
from Common import Common
# This example demonstrates how to convert pdf document to word processing with advanced options
class ConvertPdfAndRemoveEmbeddedFiles:
@classmethod
def Run(cls):
# Create necessary API instances
apiInstance = group... |
import tkinter as tk
from tkinter import ttk
class ToggledFrame(tk.Frame):
"""
The ToggledFrame Class creates a expandable box for the grouping of tests
since this is not possible in TK inter
"""
def __init__(self, parent, text="", *args, **options):
tk.Frame.__init__(self, parent, *args,... |
Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import __future__
>>> __future__.all_feature_names
['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals'... |
"""An FTP client class and some helper functions.
Based on RFC 959: File Transfer Protocol (FTP), by J. Postel and J. Reynolds
Example:
>>> from ftplib import FTP
>>> ftp = FTP('ftp.python.org') # connect to host, default port
>>> ftp.login() # default, i.e.: user anonymous, passwd anonymous@
'230 Guest login ok, ac... |
"""
Polynomial Interfaces to Singular
AUTHORS:
- Martin Albrecht <malb@informatik.uni-bremen.de> (2006-04-21)
- Robert Bradshaw: Re-factor to avoid multiple inheritance vs. Cython (2007-09)
- Syed Ahmad Lavasani: Added function field to _singular_init_ (2011-12-16)
Added non-prime finite fields to _singular_in... |
import sigauth.middleware
from django.conf import settings
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
class SignatureCheckMiddleware(sigauth.middleware.SignatureCheckMiddlewareBase):
secret = settings.SIGNATURE_SECRET
def should_check(self, request):
if ... |
# Chained comparison between 3 variables
x = 4
# returns a bool(true or false) depending on what the condition evaluates to
print(1 < x < 11) # True
print(7 < x < 14) # False
print(8 < x * 8 < 64) # True
print(9 > x <= 6) # True
print(4 == x > 2) # True |
# Generated by Django 3.1.5 on 2021-01-28 12:14
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(aut... |
# Copyright 2008-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# 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... |
from rest_framework.permissions import BasePermission
from olympia.addons.utils import RestrictionChecker
class IsSubmissionAllowedFor(BasePermission):
"""
Like is_submission_allowed_for_request, but in Permission form for use in
the API. If the client is disallowed, a message property specifiying the
... |
#!/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.
from mcrouter.test.MCProcess import Memcached
from mcrouter.test.McrouterTestCase import McrouterTestCase
class TestS... |
import os
import subprocess
from bsm.util import which
from bsm.cmd import CmdResult
from bsm.cmd import CmdError
from bsm.cmd.pkg_base import PkgBase
from bsm.logger import get_logger
_logger = get_logger()
DEFAULT_EDITOR = ['vim', 'vi']
def _detect_editor(editors):
for editor in editors:
if which(edi... |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/02_navi_widget.ipynb (unless otherwise specified).
__all__ = ['NaviGUI', 'NaviLogic', 'Navi']
# Cell
from ipywidgets import (AppLayout, Button, IntSlider,
HBox, Output,
Layout, Label)
from traitlets import Int, observe, li... |
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
from sympy.core.backend import (diff, expand, sin, cos, sympify,
eye, symbols, ImmutableMatrix as Matrix, MatrixBase)
from sympy import (trigsimp, solve, Symbol, Dummy)
from sympy.core.compatibility import range
from sympy.physics.vector.vector import Vector, _check_vector
from sympy.utilities.misc i... |
import csv
from models.County import *
def get_county_data(filepath, year):
dictionary_of_counties = dict()
with open(filepath) as csvfile:
file_reader = csv.reader(csvfile)
row = []
while not row: # skip blank rows at the beginning
row = next(file_reader)
try:
... |
import argparse
from datetime import datetime
import git
import eparams
import eparams.constraints as cc
from eparams import eloader
_repo = git.Repo(__file__, search_parent_directories=True)
@eparams.params(frozen=True) # frozen means this cannot be changed easily
class Version:
time = datetime.now()
git... |
"""
rock.py
Zhiang Chen, Feb 2020
data class for mask rcnn
"""
import os
import numpy as np
import torch
from PIL import Image
import pickle
import matplotlib.pyplot as plt
"""
./datasets/
Rock/
data/
0_8.npy
0_9.npy
1_4.npy
...
"""
class Dataset(object):
... |
"""The tests for the InfluxDB component."""
import unittest
from unittest import mock
import influxdb as influx_client
from homeassistant.bootstrap import setup_component
import homeassistant.components.influxdb as influxdb
from homeassistant.const import EVENT_STATE_CHANGED, STATE_OFF, STATE_ON
from tests.common im... |
from __future__ import absolute_import, unicode_literals
from future.builtins import int, open, str
import os
import mimetypes
from json import dumps
from django.template.response import TemplateResponse
try:
from urllib.parse import urljoin, urlparse
except ImportError:
from urlparse import urljoin, urlpar... |
"""
LC 841 -- keys and rooms
There are N rooms and you start in room 0. Each room has a distinct number in 0, 1, 2, ..., N-1, and each room may have some keys to access the next room.
Formally, each room i has a list of keys rooms[i], and each key rooms[i][j] is an integer in [0, 1, ..., N-1] where N = rooms.length.... |
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... |
#
# 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 License, Version 2.0 (the
# "License"); you may not... |
import pytest
from chalice.app import Chalice
from chalice.config import Config
from chalice.constants import LAMBDA_TRUST_POLICY
from chalice.deploy import models
from chalice.deploy.appgraph import ApplicationGraphBuilder, ChaliceBuildError
from chalice.deploy.deployer import BuildStage, PolicyGenerator
from chalice... |
from logging_module import Logger
from random import randint
class ProxyPool(object):
def __init__(self, *proxies):
self.logger = Logger.get_logger()
self.proxies = []
for proxy in proxies:
self.add_proxy(proxy)
def add_proxy(self, proxy):
if proxy.is_alive():
... |
# Copyright (c) 2012-2013 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functiona... |
# coding: utf-8
from random import randint
from .base import BaseField
from ..api import display, special
class PickoutField(BaseField):
"""select an element randomly from the limited-choices."""
def __init__(self, choices, missing=None, callback=None):
"""PickoutField constructor
:param li... |
import unittest
from django.conf.urls import include, url
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.test import TestCase, override_settings
from rest_framework import filters, pagination, permissions, serializers
from rest_framework.compat import coreapi, coresche... |
"""distutils.dist
Provides the Distribution class, which represents the module distribution
being built/installed/distributed.
"""
__revision__ = "$Id: dist.py 77717 2010-01-24 00:33:32Z tarek.ziade $"
import sys, os, re
from email import message_from_file
try:
import warnings
except ImportError:
warnings =... |
#!/usr/bin/env python3
# Copyright (c) 2013-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Generate seeds.txt from Pieter's DNS seeder
#
NSEEDS=512
MAX_SEEDS_PER_ASN=2
MIN_BLOCKS = 615801
#... |
# 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 required by applica... |
import numpy as np
import Augmentor
import os
def _permute_index(l, seed):
"""
Creates a permutation of np.array([0, ..., l-1]) and its inverse
:param l: length of the array to permute
:param seed: permutation seed
:return: (s, s_inverse) where s is permutation of np.array([0, ..., l-1]) and s_inv... |
"""Compare vis_cpu with pyuvsim visibilities."""
import numpy as np
from pyuvsim.analyticbeam import AnalyticBeam
from vis_cpu import conversions, plot
nsource = 10
def test_source_az_za_beam():
"""Test function that calculates the Az and ZA positions of sources."""
# Observation latitude and LST
hera_l... |
import numpy as np
from ..core import utils
from ..core.utils import logger
from .conversion import bilby_to_lalsimulation_spins
from .utils import (lalsim_GetApproximantFromString,
lalsim_SimInspiralFD,
lalsim_SimInspiralChooseFDWaveform,
lalsim_SimInspiralW... |
#!/usr/bin/env python3
# Copyright (c) 2015-2019 The Bitcoin Core Developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test behavior of -maxuploadtarget.
* Verify that getdata requests for old blocks (>1week) are dropped
... |
import unittest
from lambdata_axel.ds_tools import DSDataFrame
data = {'numbers': [0, 1, 2, 3, 4, 5, 6, 7],
"alphabet": ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']}
class TestDSDataFrame(unittest.TestCase):
def setUp(self):
self.df = DSDataFrame(data)
def test_check_nulls(self):
column... |
from django.conf.urls.defaults import patterns, include, url
from feeds import StoryFeed
from models import Story
from views import diff, version, mark_as_read, toggle_tracking, backgroundcontent
from lsubscribe.views import subscribe
urlpatterns = patterns(
'',
url(r'^track/yes/', toggle_tracking, {'set_track... |
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2022 all rights reserved
#
# externals
import datetime
# superclass
from .Schema import Schema
# my declaration
class Time(Schema):
"""
A type declarator for timestamps
"""
# constants
format = "%H:%M:%S" # the default fo... |
"""
*****************************************
The OptimalBPM tools package.
*****************************************
Optimal BPM™ is a Business Process Management system (BPM) and surrounding tools
Optimalbpm-tools are a collection of tools made to solve some of the common problems in BPM.
htt... |
from .pdConnection import Credentials, PdConnection
__version__ = "0.2.6" |
from jason.ctrnn import CTRNN
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
import random
import sys
import json
import os
import math
from util.fitness_functions import fitness_maximize_output_change, fitness_frequency_match
def main():
trial_seed=1
sol_seed=6
s... |
from flask_sqlalchemy import SQLAlchemy
import zmq
# TODO: a better way of doing this
from config import Config, fatal_error_exit_or_backtrace
db = SQLAlchemy()
zmq_relay_socket = None
zeromq_context = None
cfg = Config.get_global_instance()
if cfg.zeromq_relay_uri:
zeromq_context = zmq.Context()
zmq_relay_... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018, qasr and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class Maintenance(Document):
pass |
import numpy as np
import tensorflow as tf
import tf_explain
INPUT_SHAPE = (28, 28, 1)
NUM_CLASSES = 10
AVAILABLE_DATASETS = {
'mnist': tf.keras.datasets.mnist,
'fashion_mnist': tf.keras.datasets.fashion_mnist,
}
DATASET_NAME = 'fashion_mnist' # Choose between "mnist" and "fashion_mnist"
# Load dataset
data... |
import time
from math import pi, cos, sin, tan
#test program to visulaize led sequences.
class leds:
num = 16
mindelay = 3
modedelay = 333
def test(self, c):
temp = ''
for i in range(0, self.num):
for n in c:
if i == n:
temp += '+'
... |
from Lemmatization.main import read_csv, check_for_prefix_chop
from Lemmatization.utility.helper import get_root_pos_rule_csv_path
class TrieNode:
def __init__(self):
# Initialising one node for trie
self.children = {}
self.last = False
self.word = None
self.char = None
c... |
from reviewlogic.value_objects.positive_integer_id import PositiveIntegerId
class ProposalId(PositiveIntegerId):
def __str__(self):
return str(self.value) |
"""Tests for the Google Assistant integration."""
from unittest.mock import MagicMock
from homeassistant.components.google_assistant import helpers
def mock_google_config_store(agent_user_ids=None):
"""Fake a storage for google assistant."""
store = MagicMock(spec=helpers.GoogleConfigStore)
if agent_user... |
#!/usr/bin/env python
"""
TODO: Document the module.
Provides classes and functionality for SOME_PURPOSE
"""
#######################################
# Any needed from __future__ imports #
# Create an "__all__" list to support #
# "from module import member" use #
#######################################
__all__ =... |
#! /usr/bin/env python
# coding=utf-8
from easydict import EasyDict as edict
__C = edict()
# Consumers can get config by: from config import cfg
cfg = __C
# YOLO options
__C.YOLO = edict()
# Set the class name
__C.YOLO.CLASSES = ... |
import tweepy
import logging
from botConfig import create_api
import time
from shutil import copyfile
import os,sys
import subprocess
from datetime import datetime
from unidecode import unidecode
import re
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
def check_mentions(api, since_id):
logg... |
# coding: utf-8
import os
from .models import Person
from nose.tools import with_setup
from django.conf import settings
from django.test.utils import get_runner
class TestClassWithoutUnittest(object):
"""
Uses a model to ensure the table exist, even with no migrations available.
"""
def setUp(self):
... |
<<<<<<< HEAD
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Author : MikeChan
# Email : m7807031@gmail.com
# Date : 06/21/2016
import time, sys, os, datetime, threading
from PyQt4.QtCore import *
from PyQt4.QtGui import *
#===== Global Varibles =====
now = datetime.datetime.now()
today = str( str(now).split(" ")[0].s... |
from tool.runners.python import SubmissionPy
class RemiSubmission(SubmissionPy):
def get_param(self, p, opcode, index, param):
modes = opcode // 100
for _ in range(index):
modes //= 10
mode = modes % 10
if mode == 0:
return p[param]
elif mode == 1:
... |
#
# tracker.py
#
# kevinabrandon@gmail.com
#
import sys
import traceback
import time
from time import sleep
from twitter import *
from configparser import ConfigParser
from string import Template
import datasource
import fa_api
import flightdata
import geomath
import screenshot
import aircraftdata
# AWSIOT import
fr... |
# Importing relevant libraries
import cv2
import imutils
import tflearn
import numpy as np
from PIL import Image
import tensorflow as tf
from tensorflow.python.framework import ops
from tflearn.layers.estimator import regression
from tflearn.layers.conv import conv_2d, max_pool_2d
from tflearn.layers.core import input... |
from .core import create_key
from .core import create_element_rand
from . import globals |
"""
Plots metrics that assess quality of single units. Some functions here generate plots for the
output of functions in the brainbox `single_units.py` module.
Run the following to set-up the workspace to run the docstring examples:
>>> from brainbox import processing
>>> import alf.io as aio
>>> import numpy as np
>>... |
# converter.py
# Örvar Kárason (ohk2@hi.is)
# 16. des. 2015
from nltk.tree import Tree
from nltk.parse import DependencyGraph
from collections import defaultdict, OrderedDict
import re
from sys import argv, stdin, stdout
import getopt
class UniversalDependencyGraph(DependencyGraph):
def __init__(self, tree_str=N... |
# -*- coding: utf-8 -*-
import os
import re
from requests import Session
from .changelogs import get, get_commit_log
"""
if os.environ.get("DEBUG", "") in ("TRUE", "True", "true"):
DEBUG = True
import logging
logging.basicConfig(level=logging.DEBUG)
else:
DEBUG = False
"""
__author__ = """Jannis Gebau... |
import numpy as np
def normalize_network(X, normalization=None):
"""
"""
X = X.copy()
if isinstance(normalization, str) and normalization == "None":
normalization = None
if normalization is None:
X = X.applymap(lambda w: int(w))
else:
X = X.applymap(lambda w: float(w)... |
# coding: utf-8
from __future__ import with_statement, print_function, absolute_import
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
import librosa
import pysptk
from wavenet_vocoder.mixture import discretized_mix_logistic_loss
from wavenet_vocoder.mixture import sample_fr... |
class TreeViewDrawMode(Enum,IComparable,IFormattable,IConvertible):
"""
Defines constants that represent the ways a System.Windows.Forms.TreeView can be drawn.
enum TreeViewDrawMode,values: Normal (0),OwnerDrawAll (2),OwnerDrawText (1)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==... |
import logging
from pathlib import Path
from typing import List, Optional
from great_expectations.datasource.data_connector.inferred_asset_file_path_data_connector import (
InferredAssetFilePathDataConnector,
)
from great_expectations.datasource.data_connector.util import (
get_filesystem_one_level_directory_g... |
# GENERATED BY KOMAND SDK - DO NOT EDIT
import komand
import json
class Component:
DESCRIPTION = "Query account info"
class Input:
ADDRESS = "address"
USER_ID = "user_id"
USERNAME_MD5 = "username_md5"
class Output:
RISK_SCORE = "risk_score"
class AccountLookupInput(komand.Input):
... |
from typing import List, Tuple
import pytest
from conftest import DeSECAPIV1Client, query_replication, NSLordClient, assert_eventually
def generate_params(dict_value_lists_by_type: dict) -> List[Tuple[str, str]]:
return [
(rr_type, value)
for rr_type in dict_value_lists_by_type.keys()
fo... |
# Copyright (C) 2017 MongoDB Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License, version 3,
# as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARR... |
#!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test wallet import RPCs.
Test rescan behavior of importaddress, importpubkey, importprivkey, and
impor... |
"""
TESTS is a dict with all you tests.
Keys for this will be categories' names.
Each test is dict with
"input" -- input data for user function
"answer" -- your right answer
"explanation" -- not necessary key, it's using for additional info in animation.
"""
TESTS = {
"Basics": [
{
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.