input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
import IamAccount
from .models.iam_account_permissions import IamAccountPermissions
from .models.iam_api_key import IamApiKey
from .models.iam_app_registration import IamAppRegistration
from .models.iam_certificate import IamCertificate
from .models.iam_certificate_request import IamCertificateRequest
from .models.iam_... | |
<reponame>jacarvalho/SimuRLacra<filename>Pyrado/pyrado/policies/environment_specific.py
import math
import numpy as np
import torch as to
import torch.nn as nn
import pyrado
from pyrado.utils.data_types import EnvSpec
from pyrado.environments.sim_base import SimEnv
from pyrado.environments.pysim.quanser_ball_balancer ... | |
of sims) the goal soil moisture anomaly is calculated against the mean(axis=1)
of the soil moisture deficit array. The units should be in the same format as weather at home. assumes no
input data contains nan values
SMD is a monthly standardized dataset assumes a starting soil moisture for each month (see detrended_... | |
port, "submissions/{}/?index=7".format(submissions[0].id))
element_active = lambda browser: utils._get_active_element(browser) == utils._get_score_box(browser, 2)
WebDriverWait(browser, 10).until(element_active)
# Click the third comment box and navigate to the next submission
utils._get_comment_box(browser, 2).cl... | |
<reponame>ouyang-w-19/decogo
# MINLP written by GAMS Convert at 04/21/18 13:51:48
#
# Equation counts
# Total E G L N X C B
# 4601 0 1 4600 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc si
# Total cont binary integer sos1 sos2 scont sint
# 301 1 300 0 0 0 0 0
# FX 0 0 0 0 0 0 0 0
#
# Nonzero counts
# Total const NL... | |
or h5 object
"""
if type(h5_obj_or_filepath) is str:
h5_obj = _h5py.File(h5_obj_or_filepath, mode)
else:
h5_obj = h5_obj_or_filepath
for key, value in sorted(self.items()):
if isinstance(value, Container):
if key not in h5_obj.keys():
h5_group = h5_obj.create_group(key)
else:
h5_group = h5_obj[key]
value.to... | |
0 for seven days and above after."""
frozen = x == np.array([0, 0, 0, 0, 0, 0, 0, 1], bool)
return frozen.all(axis=axis)
tcond = (tas > frz).rolling(time=8).reduce(func)
pcond = pr > t
out = (tcond * pcond * 1).resample(time=freq).sum(dim="time")
return to_agg_units(out, tas, "count")
@declare_units(
pr="[pr... | |
and no part of the geometry lies in the
exterior of the shape.
This means that a shape does not contain its own boundary, nor points
nor lines lying entirely on the boundary.
A shape does contain itself.
"""
raise NotImplementedError()
def covers(self, other):
"""Return whether this shape covers some geometr... | |
canvas.
"""
layer = self.__class__() # Create instance of the derived class, not Layer.
layer.duration = 0 # Copy all transitions instantly.
layer.canvas = canvas
layer.parent = parent
layer.name = self.name
layer._x = self._x.copy()
layer._y = self._y.copy()
layer._width = self._width.copy()
layer._height = ... | |
# This source code is part of the Biotite package and is distributed
# under the 3-Clause BSD License. Please see 'LICENSE.rst' for further
# information.
__name__ = "biotite.structure.io.pdbqt"
__author__ = "<NAME>, <NAME>"
__all__ = ["PDBQTFile"]
import warnings
import numpy as np
import networkx as nx
from ....fil... | |
from __future__ import annotations
import asyncio
import logging
import signal
from collections import defaultdict
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
Dict,
List,
Optional,
overload,
)
from ferris.types import message
from .channel import Channel
from .connection... | |
numeric_times=args.numeric_times,
age=args.age,
tags=args.tags,
status=args.status))
except Exception as e:
if args.verbosity and args.verbosity > 2:
sys.stderr.write(get_traceback())
env.logger.error(e)
sys.exit(1)
#
# command purge
#
def get_purge_parser(desc_only=False):
parser = argparse.ArgumentParser... | |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class Functi... | |
stage.
input_coords (str, optional): The box coordinate format that the model outputs. Can be either 'centroids'
for the format `(cx, cy, w, h)` (box center coordinates, width, and height), 'minmax' for the format
`(xmin, xmax, ymin, ymax)`, or 'corners' for the format `(xmin, ymin, xmax, ymax)`.
normalize_coords (... | |
<filename>Producten/management/commands/verwerk_opdrachten.py
# -*- coding: utf-8 -*-
# Copyright (c) 2020-2021 <NAME>.
# All rights reserved.
# Licensed under BSD-3-Clause-Clear. See LICENSE file for details.
# werk de tussenstand bij voor deelcompetities die niet afgesloten zijn
# zodra er nieuwe ScoreHist records ... | |
modulestore().get_item(
BlockUsageLocator(course_locator, 'chapter', block_id='chapter3')
)
assert ch3.has_children_at_depth(0)
assert not ch3.has_children_at_depth(1)
@ddt.ddt
class SplitModuleCourseTests(SplitModuleTest):
'''
Course CRUD operation tests
'''
@patch('xmodule.tabs.CourseTab.from_json', side_e... | |
to lsit resources of.
embed (list): ?
Returns:
dict: server_response
"""
api_id = AWS.APIGateway.GetId(apig,api_name)
return apig.client.get_resources(restApiId=api_id,embed=embed)['items']
def Create(apig,api_name: str,name: str,parent_name='/'):
"""Creates a resource for an API.
... | |
don't really care to have the labels separated from the data
#This is difficult to test separately without a lot of setup but was shown to be accurate
#Checking for multiple items was the most difficult part to do properly but this expression is some kind of generator that will break as soon as a match is found "not... | |
1. `unit_id` - (randomization) unit id
1. `agg_type` - level of aggregation
1. `goal` - goal name
1. any number of dimensional columns, e.g. column `product` containing values `p_1`
1. `count` - number of observed goals
1. `sum_value` - value of observed goals
Returns:
set of dataframes with evaluation
Usage:... | |
import os
import glob
import shutil
# from scipy.ndimage import binary_fill_holes
import itertools
import numpy as np
import dippykit as dip
import matplotlib.pyplot as plt
from tqdm import tqdm
import cv2
from cv2 import INTER_AREA
from skimage import filters
from scipy.spatial import ConvexHull
from scipy.ndimage.m... | |
import datetime
import time
from typing import Any, Callable, Dict, Iterable, Optional, Tuple
import pendulum
import prefect
from prefect.client import Client
from prefect.core import Edge, Task
from prefect.engine.result import Result
from prefect.engine.runner import ENDRUN, call_state_handlers
from prefect.engine.... | |
# Copyright (c) 2018 Cisco and/or its affiliates.
# 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... | |
from __future__ import annotations
import collections
import inspect
from dataclasses import dataclass
from enum import Enum
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
from flytekit.common import constants as _common_constants
from flytekit.common.exceptions.user import FlyteValidation... | |
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey has `on_delete` set to the desired behavior.
# * Remove `managed = False` lines if you wish... | |
3218 3285 2840 1787 2139 446
227 5216 3873 2626 6310 5574 5121 5740 3783 1516 179 4476
228 5762 8422 8903 9353 8916 6325 1366 7352 8788 7357
229 1217 4034 3655 7181 5806 2452 8341 1144 7609 6938 8510
230 4299 1862 3627 9007 4107 9842 2772 662 1783 728 9082
231 3650 5508 423 8904 3982 3280 5364 3445 6103 408 6010
232 32... | |
<reponame>WDZRMPCBIT/SCoRE
from collections import defaultdict
# We use "Number" in a bunch of places throughout to try to generalize ints and floats.
# Unfortunately, mypy doesn't like this very much, so we have to "type: ignore" a bunch of things.
# But it makes for a nicer induced grammar, so it's worth it.
from... | |
<gh_stars>10-100
# The MIT License (MIT)
#
# Copyright (C) 2016 - <NAME> <<EMAIL>>
#
# 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 righ... | |
isinstance(val, str)) and hasattr(val, "__iter__"):
raise TypeError("{0}: y_test must be a 1d iterable"
"".format(fname_))
else:
raise TypeError("{0}: y_test should be a pandas DataFrame with one "
"column or a 1d iterable (ndarray, etc.)"
"".format(fname_))
# get class labels from the .classes_ property ... | |
<reponame>CDAT/libcdms
#! /usr/local/bin/python
# -*- Mode: Python; tab-width: 4 -*-
#
# Author: <NAME> <<EMAIL>>
# Copyright 1996, 1997 by <NAME>
# All Rights Reserved.
#
# This software is provided free for non-commercial use. If you are
# interested in using this software in a commercial context, or in
# purch... | |
len(masks) != len(trace_indexes):
raise ValueError("masks and trace_indexes do not have the same size.")
for i,v in zip(trace_indexes, masks):
self.trace_masks[i] = v
else:
self.trace_masks[trace_indexes] = masks
# --------- #
# Shift #
# --------- #
def get_yshifted_traceweight_mask(self, yshift, subpixeliz... | |
from abc import ABCMeta, abstractmethod
import matplotlib.pyplot as plt
import numpy as np
import scipy.linalg as la
from scipy.optimize import minimize
from scipy.special import factorial, factorial2
from ssmtoybox.mtran import SphericalRadialTransform, UnscentedTransform, GaussHermiteTransform, \
FullySymmetricStu... | |
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
warnings.simplefilter(action='ignore', category=UserWarning) # to surpress future warnings
import pandas as pd
import sys
import textstat
import numpy as numpy
import math
import gensim
from string import ascii_lowercase
#import Use_NN as nn... | |
= self.target_feature_list[-1].end_timestamp
self.end_clip_number = self.target_feature_list[-1].end_clip_number
def __str__(self):
print_string = 'SHRP2 NDS Video Event\n\n'
if self.preceding_feature:
print_string += 'Preceding Feature:\n{}\n\n'.format(
self.preceding_feature)
print_string += 'Target Feature... | |
"""
Click command to do static annotation searching via Stevedore plugins.
"""
import datetime
import errno
import os
import re
from abc import ABCMeta, abstractmethod
import yaml
from stevedore import named
from code_annotations import annotation_errors
from code_annotations.exceptions import ConfigurationException
... | |
ranges = []
baseRange = range(1,51)
for p in self.useddims:
staticParams.append(p)
if p == '1':
ranges.append([1])
else:
ranges.append(range(2,51,random.choice(baseRange)))
return (staticParams, itertools.product(*ranges))
def ppDecl(self, decl, pos):
res = ""
for s in decl:
res += ",".join(decl[s])
res ... | |
#!/usr/bin/python
# Copyright (c) 2020, 2021 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for d... | |
import numpy as np
from numpy import *
import matplotlib.pyplot as mpl
import h5py
import sys
import os
from matplotlib.pyplot import *
from plotnine import *
import pandas as p
import myggplottheme
class BSE:
def __init__(self,fileG4,draw=False,useG0=False,symmetrize_G4=False,phSymmetry=False,calcRedVertex=False... | |
= 5350 * sign(self.agent.team)
if self.agent.goalPred.game_seconds - self.agent.gameInfo.seconds_elapsed > 0.1:
if distance2D(self.agent.me.location, penetrationPosition) > 100:
return testMover(self.agent, penetrationPosition, 2300)
else:
if penetrationPosition[2] > 300:
self.activeState = LeapOfFaith(self.agent... | |
('st3', ''),
('stp', 'on')],
'hidden': False,
'hide_filters': [],
'layout': 'table',
'linktitle': _('Pending Services'),
'mustsearch': False,
'name': 'pendingsvc',
'num_columns': 5,
'owner': '',
'painters': [('service_description', 'service')],
'play_sounds': False,
'public': True,
'show_filters': [],
'so... | |
from behave import when, then, use_step_matcher
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select, WebDriver... | |
<gh_stars>0
import os
import time
import warnings
from collections import defaultdict
from pathlib import Path
import flopy
import geopandas as gpd
import numpy as np
import pandas as pd
import pyproj
from packaging import version
fm = flopy.modflow
mf6 = flopy.mf6
import gisutils
import sfrmaker
from gisutils import... | |
drift.
drift_metrics_min_spikes_per_interval: int
Minimum number of spikes for evaluating drift metrics per interval.
unit_ids: list
List of unit ids to compute metric for. If not specified, all units are used
**kwargs: keyword arguments
Keyword arguments among the following:
method: str
If 'absolute' (default)... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
MagnetCommunication.py
Author: <NAME>
Created on Mon Dec 18 15:35:21 2017
Last Edited: 06.12.2018
Python Version: 3.6.5
4G Magnet Power Supply
Class for sending commands to 4G Magnet Power Supply
IMPORTANT: Magnet has to be in remote mode, can only
be set locally
... | |
<filename>src/pyomexmeta/pyomexmeta.py
from __future__ import annotations
import ctypes as ct
import os
import sys
from contextlib import contextmanager
from sys import executable as _python_interpretor
from typing import List
from functools import wraps
try:
# for use from outside the package, as a pytho... | |
"font": font,
"borderwidth": bd,
"state": state,
"locale": locale,
"date_pattern": date_pattern,
"selectmode": selectmode,
'textvariable': self._textvariable,
'firstweekday': firstweekday,
'weekenddays': weekenddays,
'mindate': mindate,
'maxdate': maxdate,
'showweeknumbers': showweeknumbers,
'showothermonth... | |
import unittest
from soap.context import context
from soap.datatype import (
auto_type, int_type, float_type, FloatArrayType, ArrayType
)
from soap.expression import (
operators, Variable, Subscript, expression_factory
)
from soap.parser import parse
from soap.semantics.error import IntegerInterval
from soap.semanti... | |
7.01529154326273*m.x187*m.x187 + 29.5414539159021*m.x188*m.x188 +
38.1756318711238*m.x189*m.x189 + 8.58104823499548*m.x190*m.x190 + 7.69711583001143*m.x191*m.x191
+ 42.4371248163469*m.x192*m.x192 + 4.59409541976021*m.x193*m.x193 + 28.1235883297576*m.x194*
m.x194 + 47.6916842358554*m.x195*m.x195 + 27.1839166296889*m... | |
# This file contains fairly exhaustive tests of almost all the methods
# supported by the Python `str` type, and tests that `untrusted.string` type:
# * correctly supports the same methods
# * accepts `str` and/or `untrusted.string` arguments interchangeably
# * never returns `str` or any iterable of `str`, only an
# a... | |
0xF0, 0x00, # OOOO OOOO
0x10, 0x80, 0x00, # O O
0x10, 0x80, 0x00, # O O
0x08, 0x80, 0x00, # O O
0x0C, 0xFF, 0x80, # OO OOOOOOOOO
0x06, 0x81, 0x00, # OO O O
0x03, 0x82, 0x00, # OOO O
0x01, 0x82, 0x00, # OO O
0x00, 0xC1, 0x00, # OO O
0x00, 0x3F, 0x80, # OOOOOOO
0x00, 0x00, 0x00, #
0x00, 0x00, 0x00, # ... | |
@Cached(expire=10.)
def get_user_filters(self):
"""
returns a name:filter dictionary
"""
import json
prop = self.get_db_property('PANIC','UserFilters')
prop = [t.split(':',1) for t in prop]
return dict((t[0],unicode2str(json.loads(t[1]))) for t in prop)
def set_user_filters(self,filters,overwrite=True):
""... | |
folds - 1:
if exog is None:
pred = forecaster.predict_interval(
steps = steps,
last_window = last_window_y,
interval = interval,
n_boot = n_boot,
random_state = random_state,
in_sample_residuals = in_sample_residuals
)
else:
pred = forecaster.predict_interval(
steps = steps,
last_window = last_window_y,
e... | |
value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def thickness(self):
"""field `Thick... | |
<filename>gryphon/lib/exchange/itbit_btc_usd.py<gh_stars>1000+
"""
Exchange documentation: https://api.itbit.com/docs
"""
# -*- coding: utf-8 -*-
import base64
from collections import OrderedDict, defaultdict
import hashlib
import hmac
import json
import time
import urllib
import cdecimal
from cdecimal import Decimal... | |
from typing import Dict
from botocore.paginate import Paginator
class ListApps(Paginator):
def paginate(self, PaginationConfig: Dict = None) -> Dict:
"""
Creates an iterator that will paginate through responses from :py:meth:`Amplify.Client.list_apps`.
See also: `AWS API Documentation <https://docs.aws.amazon.com... | |
#!/usr/bin/python
"""
Copyright (c) 2016 King Mongkut's University technology Thonburi
Author: <NAME>
Contact: <EMAIL>
Version: 1.3b 2017-03-01
License: MIT License
The MIT License
Copyright (c) 2016 King Mongkut's University technology Thonburi
Permission is hereby granted, free of charge, to any person obtaining... | |
<reponame>nikmagini/pilot<filename>HPC/EventServer/EventServerJobManager.py
import inspect
import commands
import os
import re
import signal
import sys
import time
import Queue
import multiprocessing
import subprocess
import threading
import json
import traceback
try:
import yampl
except:
print "Failed to import yam... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Constants for wizards."""
import re
from typing import List, Optional, Union
class Sources:
"""Defaults for wizard source argument."""
CSV_STR: str = "csv text string"
CSV_PATH: str = "csv file {path}"
TEXT_STR: str = "text string"
TEXT_PATH: str = "text file {pa... | |
= ""
try:
rule_description = rule_params["Description"]
except KeyError:
rule_description = rule_name
my_params = [
{
'ParameterKey': 'RuleName',
'ParameterValue': rule_name,
},
{
'ParameterKey': 'RuleLambdaName',
'ParameterValue': self.__get_lambda_name(rule_name, rule_params),
},
{
'ParameterKey': 'D... | |
# Used at the time of inference to load the model, along w/ the weights.
# Use it in the following manner:
"""
from UNET_model_def import *
model_wghts = "{}/<my_model_weights_{}>.h5".format(data_dir, HOLDOUT)
model = <my_model_name>((None,None,None,1)) #giving the model definition
model.load_weights(model_wghts)
"""
... | |
<gh_stars>0
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate Leakage': 0.00662954,
'Peak Dynamic': 0.0,
'Runtime Dyn... | |
<reponame>OpenDaisy/daisy-client
# Copyright 2013 OpenStack Foundation
# Copyright (C) 2013 Yahoo! 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.a... | |
<reponame>LasseWolter/lhotse
import pickle
from typing import Callable, Dict, Optional, Sequence, Union
from tqdm.auto import tqdm
from lhotse import CutSet
from lhotse.serialization import LazyIteratorChain
from lhotse.utils import Pathlike, is_module_available
def export_to_webdataset(
cuts: CutSet,
output_path... | |
for the fleet.
:param pulumi.Input[str] fleet_type: Fleet type. Valid values are: `ON_DEMAND`, `ALWAYS_ON`
:param pulumi.Input[str] iam_role_arn: ARN of the IAM role to apply to the fleet.
:param pulumi.Input[int] idle_disconnect_timeout_in_seconds: Amount of time that users can be idle (inactive) before they are di... | |
# coding: utf-8
"""
LUSID API
FINBOURNE Technology # noqa: E501
The version of the OpenAPI document: 0.11.3192
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
class Bond(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
R... | |
self.kind = None
self.new_col = None
self.add_to = None
self.add_chr_prefix = True
self.id_field = None
self.temp = None
self.include_bed = None
self.include_if = "both"
self.load_genotype = True
self.gt_scores = None
# Track defaults for persistence
self.default_params = {k: v for k, v in self.__dict__.ite... | |
#############################################################
#collatrix_functions.py
#this script contains the functions used in all collatrix code
#created by <NAME> (<EMAIL>), October 2020
#updated by <NAME>, June 2021
##############################################################
#import modules
import pandas as p... | |
import csv, json, argparse, copy, re, os, urllib2
import numpy as np
from scipy.spatial import distance
from sklearn import manifold, metrics, decomposition, preprocessing
import igraph
import jsmin
import rdkit
from rdkit import Chem, DataStructs, Geometry
from rdkit.DataStructs import cDataStructs
from rdkit.Chem... | |
<reponame>Gee-3/pygna<filename>pygna/block_model.py<gh_stars>10-100
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
import logging
from pygna import output
from pygna.utils import YamlConfig
import pandas as pd
import random
import string
import seaborn as... | |
<reponame>ifwe/digsby
import logging
from traceback import print_exc
from util.introspect import memoize
log = logging.getLogger('pg_accounts2')
import wx
from gui.uberwidgets.PrefPanel import PrefPanel
from gui.pref.prefcontrols import HSizer, VSizer, mark_pref, SText
from wx import EXPAND
import protocols
from gui.te... | |
= c_int
lib.nxigetslab_.argtypes = [c_void_p, c_void_p, c_int_p, c_int_p]
def getslab(self, slab_offset, slab_shape):
"""
Get a slab from the data array.
Offsets are 0-origin. Shape can be inferred from the data.
Offset and shape must each have one entry per dimension.
Raises ValueError if this fails.
Corres... | |
from __future__ import absolute_import, division
from psychopy import locale_setup
from psychopy import prefs
from psychopy import sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy a... | |
<filename>Bio/HMM/MarkovModel.py<gh_stars>1-10
"""Deal with representations of Markov Models.
"""
# standard modules
import copy
import math
import random
# biopython
from Bio.Seq import MutableSeq
class MarkovModelBuilder:
"""Interface to build up a Markov Model.
This class is designed to try to separate the task... | |
complete before the upgrade rolls back. The timeout can be in either hh:mm:ss or in d.hh:mm:ss.ms format.
"""
return pulumi.get(self, "upgrade_domain_timeout")
@property
@pulumi.getter(name="upgradeReplicaSetCheckTimeout")
def upgrade_replica_set_check_timeout(self) -> str:
"""
The maximum amount of time to blo... | |
<filename>forest_benchmarking/classical_logic/ripple_carry_adder.py
"""
Circuit primitives for classical reversible logic
At the moment it is primarily using the simple adder construction in
[CDKM96] A new quantum ripple-carry addition circuit
Cuccaro, Draper, Kutin, and Moulton
https://arxiv.org/abs/quant-ph/04101... | |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 OpenStack Foundation.
# 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/L... | |
('2012-02-09')
)
db.time_record.create \
( daily_record = dr
, duration = 7.75
, work_location = '5'
, wp = '2'
)
dr = db.daily_record.create \
( user = user
, date = date.Date ('2012-02-10')
)
db.time_record.create \
( daily_record = dr
, duration = 7.5
, work_location = '5'
, wp = '2'
)
dr = db.dail... | |
<reponame>TheShadow29/vognet-pytorch
"""
To create the 4-way dataset
Main motivation:
Currently, not sure if the models ground
based only on object name, or is it really
learning the roles of the visual elements
correctly.
Thus, we create 4-way dataset, for every
data which has S-V-O statistics, we generate
counterfac... | |
# cython: auto_pickle=False,embedsignature=True,always_allow_keywords=False
# -*- coding: utf-8 -*
"""
Datastructures to help externalization.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# There are a *lot* of fixme (XXX and the like) in this file.
... | |
<gh_stars>0
import copy
import logging
import os
from pathlib import Path
import numpy as np
import tensorflow as tf
import tensorflow_addons as tfa
from typing import Any, List, Optional, Text, Dict, Tuple, Union
import rasa.utils.io as io_utils
from rasa.core.domain import Domain
from rasa.core.featurizers import ... | |
1, 0, 1, 1)
self.comboBox_23 = QComboBox(self.frame_24)
self.comboBox_23.addItem("")
self.comboBox_23.addItem("")
self.comboBox_23.addItem("")
self.comboBox_23.addItem("")
self.comboBox_23.addItem("")
self.comboBox_23.addItem("")
self.comboBox_23.addItem("")
self.comboBox_23.addItem("")
self.comboBox_23.addI... | |
<gh_stars>0
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.utils.html import format_html
from .helpers import facebook_get_json, facebook_post_json, facebook_base_get_json
from .settin... | |
quoteIdent(self, ident):
return '"%s"' % ident # escapes?
def null(self):
return r'\N'
def serialType(self, type):
return is_serial(type)
def intType(self, type):
t = type.lower()
return Database.intType(self, t) or \
self.serialType(type) or is_int(t)
def eanType(self, type):
# return the expected byte size... | |
GT in world frame for accuracy computation
yaw_only_objects, max_min_dict, transformed_annotations, _ = \
fat_image.visualize_pose_ros(
image_data, annotations, frame='table', camera_optical_frame=False,
input_camera_pose=camera_pose, ros_publish=True
)
max_min_dict['ymax'] = 0.85
max_min_dict['ymin'] = -0.85
... | |
<filename>spharpy/special.py
"""
Subpackage implementing or wrapping special functions required in the
spharpy package.
"""
from itertools import count
import numpy as np
import scipy.special as _spspecial
from scipy.optimize import brentq
def spherical_bessel(n, z, derivative=False):
r"""
Spherical bessel functio... | |
import re
from pathlib import Path
from functools import partial
from multiprocessing import Pool
from itertools import zip_longest
from articlenizer import articlenizer, encode_string, corrections, sentenize, util
from articlenizer.util import chunk_list
def annotation_to_dict(annotation):
"""Read BRAT annotation ... | |
= None, reply_markup: Union[types.InlineKeyboardMarkup, types.ReplyKeyboardMarkup, types.ReplyKeyboardRemove, types.ForceReply, ] = None, parse_mode: str = None, caption_entities: list = None, duration: int = None, performer: str = None, title: str = None, thumb: Union[types.InputFile, str, ] = None, disable_notificati... | |
self._validate_dimensions(labels, outputs)
labels = self.binarize(labels, self.label_thresh)
outputs = self.binarize(outputs, self.output_thresh)
# Calculate and sum each intersections and unions
# zero if Truth=0 or Prediction=0
intersection_sum = (outputs & labels).float().sum()
union_sum = (outputs | labels).... | |
{"gene1"},
{"gene1", "featgrp1"},
{},
),
)
def test_query_by_identifiers(self, ids):
obj = self.annot.to_annotation_collection()
r = obj.query_by_feature_identifiers(ids)
if r.is_empty:
assert len(ids) == 0
else:
assert {x.gene_id for x in r.genes} | {x.feature_collection_id for x in r.feature_collections} =... | |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import pickle
import tensorflow as tf
import keras
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split, learning_curve, GridSearchCV, StratifiedKFold
from sklearn.metrics impor... | |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import os
import torch
import torch.nn as nn
import torch.optim as optim
import pandas as pd
from skimage import io, transform
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
i... | |
matrices.
"""
y = np.empty(x.size, common_type(A, x))
_dot_csr_matvec_prange(A.data, A.indptr, A.indices, x.ravel(), y)
y.shape = x.shape
if isinstance(x, qarray):
y = qarray(y)
return y
def dot_sparse(a, b):
"""Dot product for sparse matrix, dispatching to parallel for v large nnz.
"""
out = a @ b
if isd... | |
error didn't raise IndexError"
x = ()
x += ()
if x != (): raise TestFailed, 'tuple inplace add from () to () failed'
x += (1,)
if x != (1,): raise TestFailed, 'tuple resize from () failed'
# extended slicing - subscript only for tuples
a = (0,1,2,3,4)
vereq(a[::], a)
vereq(a[::2], (0,2,4))
vereq(a[1::2], (1,3))
vereq(... | |
= list(location_integers[:-1])
new_location_integers.append(location_integers[-1] - 1)
# after a move, location is wrong, so remove from call_data
if 'location' in call_data:
del call_data['location']
if 'part' in call_data:
del call_data['part']
if 'part_top' in call_data:
del call_data['part_top']
if 'part_... | |
# Copyright International Business Machines Corp, 2020
#
# 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 ... | |
ang)
a2 = abs(limitingAngle - oldAng)
a = a2 / (a1+a2)
self.viewDir = self.viewDir * a + oldViewDir * (1-a)
self.viewDir = self.viewDir.normalize()
# store and limit history
self._viewDirHistory.insert(0,self.viewDir)
self._viewDirHistory[10:] = []
# Do a step in that direction
self.viewDir = self.viewD... | |
<filename>messy_pypi/done/main_terminalsnake.py
#!/usr/bin/env python3
import fcntl
import signal
import sys
import threading
import os
import termios
import time
import tty
import types
from select import select
from random import randint
# ["BORDURE", ["Snake directions", ,,,,,], "Apple", "Réactualise snake directio... | |
G4(crystal, i, ep_type, functional='Cosine',
Rc=6.5, eta=2, lamBda=1, zeta=1):
"""
Calculate G4 symmetry function.
G4 function is an angular function utilizing the cosine funtion of the
angle theta_ijk centered at atom i.
One can refer to equation 8 in:
<NAME>. (2011). Atom-centered symmetry functions for co... | |
#How to run this:
#Python libraries needed to run this file: Flask, Git Python, SQLAlchemy
#You will need to have Git installed, and it will need to be in your path.
#For example, on Windows you should be able to run a command like 'git pull' from the
#ordinary Windows command prompt and not just from Git Bash.
#You... | |
value is not None and not isinstance(value, bool):
raise BadValueError('Property %s must be a boolean, not a %s'
% (self.name, type(value).__name__))
return value
def convert(self, value):
if not value:
return False
if value in ['1', 'True', 'true', True]:
return True
else:
return False
class ReferencePro... | |
<reponame>bopopescu/SDK<gh_stars>0
# 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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.