input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
rejected the transfer """
pass
def set_date(self, date):
""" This function is called by the simulation class to set the current date
for the simulation """
# if there is an inconsistency in the date progression, report
# a warning on the command line
delta = (date - self._current_date).days
if delta != 1:
war... | |
<filename>database_creator.py
# -*- coding: utf-8 -*-
"""
Created on Mon May 18 14:56:53 2020
@author: Dainean
"""
#Prepare the python system
import pandas as pd
import numpy as np
import fnmatch #For filtering
import os #move around in our OS
from astropy.io import fits #Working with fits
from astropy.cosmology i... | |
#!/usr/bin/env python3
from . import command_codes as cc
import asyncio
from collections import namedtuple
import logging
import re
from typing import List, Callable, Union, Sequence, Any
from types import coroutine
class LoggerMetaClass(type):
def __new__(mcs, name, bases, namespace):
inst = type.__new__(mcs, n... | |
database dump to SQL file.
@param progress callback(name, count) to report progress,
returning false if export should cancel
"""
result = False
tables, namespace, cursors = db.schema["table"], {}, []
def gen(func, *a, **kw):
cursor = func(*a, **kw)
cursors.append(cursor)
for x in cursor: yield x
try:
with... | |
(`pulumi.Input[float]`) - The volume size, in gibibytes (GiB).
* `type` (`pulumi.Input[str]`) - The volume type. Valid options are `gp2`, `io1`, `standard` and `st1`. See [EBS Volume Types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html).
* `volumesPerInstance` (`pulumi.Input[float]`) - The n... | |
save_process.start()
save_process.join()
save_process.terminate()
# empty the dictionaries to release the memory because they are not needed anymore
self.init_algorithm_attributes()
# if this is not the last chunk, set up the next chunk of SNPs
if not self.is_last_chunk():
self.setup_next_chunk()
else:
# if ... | |
not found on disk' % uri)
a_dataset = gdal.Open(a_uri)
b_dataset = gdal.Open(b_uri)
self.assertEqual(a_dataset.RasterXSize, b_dataset.RasterXSize,
"x dimensions are different a=%s, second=%s" %
(a_dataset.RasterXSize, b_dataset.RasterXSize))
self.assertEqual(a_dataset.RasterYSize, b_dataset.RasterYSize,
"y dim... | |
f.write(s + "\n")
for number in numberOfElements:
if number <= len(bigElements):
m1 = MassFunction(*[(x, 1.0/number) for x in random.sample(bigElements, number)])
m2 = MassFunction(*[(x, 1.0/number) for x in random.sample(bigElements, number)])
m3 = MassFunction(*[(x, 1.0/number) for x in random.sample(bigElement... | |
<reponame>RUAN-ZX/smileToLife_backend
import os
import random
from time import time
from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
import uuid,hashlib
from .models import message, user,comment,like,Dislike
import json
commentExampleList = [
"一年之计,... | |
'HKT', 'zh': u('\u9999\u6e2f\u79fb\u52a8\u901a\u8baf'), 'zh_Hant': u('\u9999\u6e2f\u79fb\u52d5\u901a\u8a0a')},
'852679':{'en': '3', 'zh': '3', 'zh_Hant': '3'},
'852680':{'en': 'HKT', 'zh': u('\u9999\u6e2f\u79fb\u52a8\u901a\u8baf'), 'zh_Hant': u('\u9999\u6e2f\u79fb\u52d5\u901a\u8a0a')},
'852681':{'en': 'China Unicom'... | |
<filename>align_images/cc2d.py
#!/usr/bin/env python3
''' A set of methods for computing the cross-correlation of 2D images.
Currently, 3 methods are provided for computing the cross-correlation (CC),
each implementing different boundary conditions:
- explicit: multiplication in the real space.
- dft: multiplication... | |
if kargs.get('min',False):
minStyle = kargs.get('minStyle', kargs.get('minmaxStyle', '--'))
minColor = kargs.get('minColor', kargs.get('minmaxColor', col))
minMarker = kargs.get('minMarker', kargs.get('minmaxMarker', ''))
ax.plot(xvalues, np.min(p, axis=1), color=minColor, linewidth=kargs.get('linewidth',1),linesty... | |
of calling loop() if you
wish to call select() or equivalent on.
Do not use if you are using the threaded interface loop_start()."""
if self._sock == None and self._ssl == None:
return MOSQ_ERR_NO_CONN
now = time.time()
self._check_keepalive()
if self._last_retry_check+1 < now:
# Only check once a second at m... | |
import logging
from protocols.protocol_7_2_1.reports import Assembly, Program, InterpretationRequestRD, CancerInterpretationRequest, \
InterpretedGenome as InterpretedGenomeGelModel
from protocols.protocol_7_7.participant import Referral as ReferralGelModel
class PreviousData(Exception):
pass
class WorkspacePerm... | |
# additional functions
def compareVal(a, b):
return (a > b) - (a < b)
def arrayCopy(fromArray, fromIndex, toArray, toIndex, length): # thanks to Bee Sort for improving readability on this function
toArray[toIndex:toIndex + length] = fromArray[fromIndex:fromIndex + length]
#
# MIT License
#
# Copyright (c) 20... | |
import copy
import json
import pickle
import os
import glob
from collections import defaultdict
from traceback import print_exc
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import sklearn
from modnet.models import MODNetModel, EnsembleMODNetModel
from modnet.matbench.benchma... | |
<reponame>ratschlab/immunopepper
"""Contains all the output computation based on gene splicegraph"""
from collections import defaultdict
import logging
import numpy as np
from .filter import add_dict_kmer_forgrd
from .filter import add_dict_peptide
from .filter import add_set_kmer_back
from .filter import get_filtere... | |
ix, others, tmp_wrapped = \
self._prefetch_process[split].get()
ix1 = 0
ix2 = 0
video_id = self.info['videos'][ix]['video_id']
if split == 'train':
# get the video_id
# print('train: id:{}'.format(ix))
ix1 = self.train_label_start_ix[ix] # label_start_ix starts from 0
ix2 = self.train_label_end_ix[i... | |
<gh_stars>0
"""Routes related to recipe data."""
import os
import random
import traceback
from functools import reduce
import peewee as pw
from flask import Blueprint, current_app, request, session
from recapi import utils
from recapi.models import recipemodel, storedmodel, tagmodel
from recapi.models.usermodel impo... | |
if self.reac_bonds != {frozenset({inst[-2], inst[-3]}), frozenset({inst[-4], inst[-5]}), frozenset({inst[0], inst[1]})}:
# # new = 0
# if new:
# self.reactions[name].append(inst)
return 0
def search_Korcek_step2_even(self, natom, atom, bond, rad):
"""
Korcek step 2 for cyclic peroxides with even number of atoms... | |
# -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox
import matplotlib.pyplot as plt
import pyroomacoustics as pra
from pyroomacoustics.doa import circ_dist
import numpy as np
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("... | |
be a str without space ' ' or underscore '_'
(automatically removed if present)
Type : None / str
Type of object (i.e.: 'Tor' or 'Lin' for a :class:`~tofu.geom.Ves`)
Deg : None / int
Degree of the b-splines constituting the :mod:`tofu.mesh` object
Exp : None / str
Flag specifying the experiment (e.g.: 'WEST', 'A... | |
fs = float(matData["fs"][0,0])
else:
fs = 1
return {'data': data, 'fs': fs, 'wfmID': wfmID, 'wfmFormat': wfmFormat}
def sine_generator(fs=100e6, freq=0, phase=0, wfmFormat='iq', zeroLast=False):
"""
Generates a sine wave with optional frequency offset and initial
phase at baseband or RF.
Args:
fs (float): Sam... | |
import CHANGED
from persistent._compat import _b
cache = self._makeOne()
oids = []
for i in range(100):
oid = _b('oid_%04d' % i)
oids.append(oid)
state = UPTODATE if i > 0 else CHANGED
cache[oid] = self._makePersist(oid=oid, state=state)
self.assertEqual(cache.cache_non_ghost_count, 100)
cache.full_sweep()
... | |
fill_value=np.nan
)
yzoutput = np.empty((zoutput[:, :, 0].size, 2))
yzoutput[:, 0] = zoutput[:, :, 0].ravel()
yzoutput[:, 1] = youtput[:, :, 0].ravel()
averts2d = interp_func(yzoutput)
averts2d = averts2d.reshape(
(self.nlay + 1, self.nrow + 1, 1)
)
averts = averts2d * np.ones(shape_verts)
else:
# 3d interpo... | |
<gh_stars>1-10
"""Generated message classes for gkebackup version v1.
"""
# NOTE: This file is autogenerated and should not be edited by hand.
from __future__ import absolute_import
from apitools.base.protorpclite import messages as _messages
from apitools.base.py import encoding
from apitools.base.py import extra_t... | |
== "PUT":
return self.put_vci_configuration()
elif flask.request.method == "PATCH":
return self.patch_vci_configuration(vnfId, flask.request.values.get("vnfConfigModifications"))
elif flask.request.method == "DELETE":
return self.delete_vci_configuration()
def vnf_operation(self, vnfId, operationI... | |
import warnings
from scipy.stats.stats import pearsonr
from geosoup.common import Handler, Opt, Sublist, np
__all__ = ['Samples']
class Samples:
"""
Class to read and arrange sample data.
Stores label and label names in y and y_names
Stores feature and feature names in x and x_names.
Currently the... | |
<reponame>fameshpatel/olfactorybulb<filename>prev_ob_models/exclude/GilraBhalla2015/analysis/fit_odor_morphs_withFULLlin.py
# -*- coding: utf-8 -*-
########## THIS FITTING PROGRAM IS MEANT TO BE A CLONE OF MUKUND'S AND ADIL'S MATLAB ONE
## USAGE: python2.6 fit_odor_morphs.py ../results/odor_morphs/2011-01-13_odormorph... | |
#!/usr/bin/env python
# encoding: utf-8
# General utility methods.
#
# https://github.com/stefanvanberkum/CD-ABSC
#
# Adapted from Trusca, Wassenberg, Frasincar and Dekker (2020).
# https://github.com/mtrusca/HAABSA_PLUS_PLUS
#
# <NAME>., <NAME>., <NAME>., <NAME>. (2020) A Hybrid Approach for Aspect-Based Sentiment An... | |
except Exception as e:
message = self._message(inspect.stack()[0][3], e)
self.logger.exception(message)
raise
def subnet_deletion_event(self):
# This is an event from CloudTrail, so the location of the IDs in the event are different:
try:
detail = self.event.get("detail")
subnet_id = detail.get("requestParamet... | |
409081, 409099, 409121, 409153, 409163,
409177, 409187, 409217, 409237, 409259, 409261, 409267, 409271,
409289, 409291, 409327, 409333, 409337, 409349, 409351, 409369,
409379, 409391, 409397, 409429, 409433, 409441, 409463, 409471,
409477, 409483, 409499, 409517, 409523, 409529, 409543, 409573,
409579, 409589, 409... | |
# encoding: UTF-8
"""Library for running an EPICS-based virtual accelertor using IMPACT particle tracker."""
import cothread
import logging
import math
import numpy
import os.path
import random
import re
import shutil
import subprocess
import tempfile
import threading
import time
from collections import OrderedDict
f... | |
__eq__(self, o):
"""__eq__(IntsConstDataSet2D self, IntsConstDataSet2D o) -> bool"""
return _RMF_HDF5.IntsConstDataSet2D___eq__(self, o)
def __ne__(self, o):
"""__ne__(IntsConstDataSet2D self, IntsConstDataSet2D o) -> bool"""
return _RMF_HDF5.IntsConstDataSet2D___ne__(self, o)
def __lt__(self, o):
... | |
# vim: expandtab:ts=4:sw=4
from __future__ import absolute_import
import numpy as np
from sklearn.utils.linear_assignment_ import linear_assignment
import EKF
import pdb
from mbest_ilp import new_m_best_sol
from multiprocessing import Pool
from functools import partial
#from mbest_ilp import m_best_sol as new_m_best_so... | |
<gh_stars>0
# Copyright (C) 2018 Arm Limited or its affiliates. All rights reserved.
#
# SPDX-License-Identifier: Apache-2.0
#
# 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
#
# www.apache.or... | |
!= api.ssn:
rvol = api.find_repl_volume(item['volume']['id'],
rssn, None)
# if there is an old replication whack it.
api.delete_replication(svol, rssn, False)
if api.start_replication(
svol, rvol,
item['specs']['replicationtype'],
self._get_qos(rssn),
item['specs']['activereplay']):
# Save our replication_dri... | |
<filename>nanoraw/plot_commands.py
import os, sys
import h5py
import Queue
import numpy as np
import multiprocessing as mp
from time import sleep
from collections import defaultdict
from itertools import repeat, groupby
from pkg_resources import resource_string
# import nanoraw functions
import nanoraw_stats as ns
... | |
import numpy as np
import pandas as pd
import sys
from tqdm import tqdm
import h5py
from sklearn.metrics.pairwise import cosine_similarity
import pkg_resources
import re
import itertools
import os
import matplotlib.pyplot as plt
from sys import stdout ### GET rid of later
from .context import context_composite, contex... | |
player:\n"
for upgrade in self.__upgrade_list:
res += str(upgrade) + "\n"
return res
def level_up(self):
# type: () -> None
while self.exp >= self.required_exp:
self.level += 1
self.required_exp *= mpf("10") ** triangular(self.level)
def roll_dice(self, game):
# type: (Game) -> None
self.location += Dice(... | |
<reponame>splunk-soar-connectors/sep14
# File: sep14_connector.py
#
# Copyright (c) 2017-2022 Splunk 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/LI... | |
<filename>Scripts/build/lib.linux-x86_64-2.7/rdpy/protocol/rfb/rfb.py
#
# Copyright (c) 2014-2015 <NAME>
#
# This file is part of rdpy.
#
# rdpy 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 3... | |
#!/usr/bin/env python3
import sys, os, zlib, struct, math, argparse, time, operator
import getopt, hashlib, collections, binascii, stat, difflib
# ./.fkgit, same as ./.git
baseName = '.git'
# Data for one entry in the git index (.git/index)
''' Parse Index File.
| 0 | 4 | 8 | C |
|-------------|--------------|-----... | |
req_dict_with_format = dict(req_dict)
req_dict_with_format["format"] = "json" \
if out_format == "dict" else out_format
# Set the payload on the request message (Python dictionary to JSON
# payload)
MessageUtils.dict_to_json_payload(request, req_dict_with_format)
# Perform a synchronous DXL request
response = ... | |
the ith cut incoming edges.
# (iii) decode q_values
# (iv) q_vals[i] <- the ith cut q_values from the ith replica's
decoder_inputs = (cut_encoding, edge_index_dec, edge_attr_dec)
cut_decoding, _, _ = self.decoder_conv(decoder_inputs)
# take the decoder output only at the cut_index and estimate q values
return sel... | |
<reponame>quest-gmulcahy/bacpypes<filename>tests/test_utilities/test_state_machine.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Test Utilities State Machine
----------------------------
"""
import unittest
from bacpypes.debugging import bacpypes_debugging, ModuleLogger
from ..state_machine import State, Stat... | |
)
labels = inputs.clone()
# We sample a few tokens in each sequence for masked-LM training (with probability args.mlm_probability defaults to 0.15 in Bert/RoBERTa)
probability_matrix = torch.full(labels.shape, self.mlm_probability)
special_tokens_mask = [
self.tokenizer.get_special_tokens_mask(val, already_has_sp... | |
<reponame>smolar/tripleo-heat-templates<filename>tools/yaml-validate.py
#!/usr/bin/env python
# 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
#
# ... | |
<reponame>ericmehl/cortex
##########################################################################
#
# Copyright (c) 2007-2013, Image Engine Design Inc. All rights reserved.
# Copyright (c) 2012, <NAME>. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are pe... | |
= EmailTemplate.objects.get(name=operation.email_template_contributor_name)
if operation.email_template_participant_name:
email_template_participant = EmailTemplate.objects.get(name=operation.email_template_participant_name)
template_data = dict(
semester=semester,
evaluations=applicable_evaluations,
target_stat... | |
import attr
import datetime as dt
import geojson
import numpy as np
import shapely
from faker import Faker
from functools import partial
from random import Random
from shapely.geometry import Point, Polygon, MultiPolygon
from .base import TohuBaseGenerator, SeedGenerator
from .item_list import ItemList
from .logging ... | |
import logging
import os
import threading
from galaxy import util
from tool_shed.util import common_util
from tool_shed.util import container_util
from tool_shed.util import readme_util
from tool_shed.utility_containers import utility_container_manager
log = logging.getLogger( __name__ )
class FailedTest( object ... | |
# Hamiltonian Neural Networks | 2019
# <NAME>, <NAME>, <NAME>
import torch, argparse
import numpy as np
import os, sys
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
PARENT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(PARENT_DIR)
from nn_models import MLP, MLP_sgp4
from hn... | |
( ) :
return ( platform . uname ( ) [ 0 ] == "Darwin" )
if 53 - 53: Ii1I % Ii1I * o0oOOo0O0Ooo + OoOoOO00
if 92 - 92: OoooooooOO + i1IIi / Ii1I * O0
if 100 - 100: ooOoO0o % iIii1I11I1II1 * II111iiii - iII111i
if 92 - 92: ooOoO0o
if 22 - 22: Oo0Ooo % iII111i * I1ii11iIi11i / OOooOOo % i11iIiiIii * I11i
if 95 - 95... | |
"""
Accepts same args as draw_on, but uses maplotlib
Args:
channel (int | str): category index to visualize, or special key
"""
# If draw doesnt exist use draw_on
import numpy as np
if image is None:
if imgspace:
dims = self.img_dims
else:
dims = self.bounds
shape = tuple(dims) + (4,)
image = np.zeros(sh... | |
<gh_stars>0
import os
import csv
import traceback
import shutil
from pathlib import Path
from os.path import basename
from utils import Config, Editor, Rubric, Process
import difflib
import re
class PythonMarker:
"""
The marker script for Python submissions.
Attributes:
----------
extension
The extension of Pyt... | |
Field("mapmaker_enabled", "boolean", default=False),
Field("mapmaker", default="Google MapMaker"),
Field("mapmakerhybrid_enabled", "boolean", default=False),
Field("mapmakerhybrid", default="Google MapMaker Hybrid"),
Field("earth_enabled", "boolean", default=True),
Field("streetview_enabled", "boolean", default=Tr... | |
abstracttree("do\n\nla\ndo") == Collection(
[UnnamedPassage([Line([do])]), UnnamedPassage([Line([la]), Line([do])])]
)
assert abstracttree("do\n\n\nla\ndo") == Collection(
[UnnamedPassage([Line([do])]), UnnamedPassage([Line([la]), Line([do])])]
)
assert abstracttree("do\n\nla\n\ndo") == Collection(
[
UnnamedPas... | |
<gh_stars>1-10
import unittest, doctest
from test import test_support
from collections import namedtuple, Counter, Mapping
import pickle, cPickle, copy
from random import randrange
import operator
from collections import Hashable, Iterable, Iterator
from collections import Sized, Container, Callable
from collections im... | |
<reponame>clay3899/Freestyle
import pygame as pg
from settings import *
from os import path
vec = pg.math.Vector2
class Player(pg.sprite.Sprite):
"""
Creates the Player class to provide a template for players in the game.
"""
def __init__(self, game, img):
"""
Initializes (sets up) the player class.
Paramete... | |
<reponame>alvaroabascar/spaCy
from typing import List, Sequence, Dict, Any, Tuple, Optional
from pathlib import Path
from collections import Counter
import sys
import srsly
from wasabi import Printer, MESSAGES, msg
import typer
from ._util import app, Arg, Opt, show_validation_error, parse_config_overrides
from ._util... | |
# -*- coding: utf-8 -*-
'''Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2019, 2020 <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 wi... | |
"{4}::\n {5}:::\n{6}\n".format(
numerum_archiva, # 0
'Rēs interlinguālibus', # 1
'/download link/@eng-Latn', # 2
'link:{0}.no11.tbx[{0}.no11.tbx]'.format(
numerum_archiva
),
'Rēs linguālibus', # 4
'Lingua Anglica (Abecedarium Latinum)', # 5
_pad(self.notitiae.translatio(
'{% _🗣️ 1603_1_99_101_8 🗣️_ %}'), 4)... | |
res = t.update(row, namemapping)
if res:
row[(namemapping.get(t.key) or t.key)] = res
self._after_update(row, namemapping)
def _before_update(self, row, namemapping):
return None
def _after_update(self, row, namemapping):
pass
def ensure(self, row, namemapping={}):
"""Lookup the given member. If that fail... | |
0: # likely found
# Sample output format ------------------------------------------
# Package: mysql-server
# Status: install ok installed
# Priority: optional
# Section: database
# Installed-Size: 107
# Maintainer: <NAME> <<EMAIL>>
# Architecture: all
# Source: mysql-5.7
# Version: 5.7.25-0ubuntu0.16.04.2
#... | |
# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
import datetime
import json
from jsonschema import Draft4Validator
import pytz
from django.urls import reverse
from django.contrib.auth import get_user_model
from accelerator.models import (
EntrepreneurProfile,
ExpertProfile,
MemberProfile,
)
from impact.tes... | |
enabled,no weather, no occupancy.
# other inputs are
# zone2/sensor - current temperature
# scheduled & manual setpoint changes
send = [
(Events.evtRuntime30,6),
(evtZone2SetPoint14,5),
(evtZone2Disable,3),
(evtZone2SetPoint18,4),
(evtZone2Enable,3),
(evtZone2ManSetPoint14,3),
(evtZone2Disable... | |
import logging
from typing import Union
from copy import deepcopy
from glob import glob
from numpy import array, ndarray, round
from pandas.errors import ParserError
from tqdm import tqdm
from os.path import join
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('TkAgg')
from . import utilities as util... | |
receiveData_OpenDoor(self):
self.log("[Behaviour OpenDoor] -- Receiving Data")
# TYPICAL RECEIVE CALL #
self.waitForAllMessages() #
# END OF TYPICAL RECEIVE CALL #
# BEGIN OF RECEIVE BODY CALL #
print "[Behaviour OpenDoor] -- Receiving Data\n"
# END OF RECEIVE BODY CALL #
pass
##### Execute behaviour ... | |
Defaults to 1000.
size : int or tuple of ints, optional
Size to pass for generating samples from the alternative
distribution. Defaults to None.
return_samples : boolean, optional
If True, return the bootstrapped statistic or jackknife
values. Defaults to False.
theta_star : array_like, optional
Bootstrapped st... | |
constant for id
if (kern['id_port'] != None):
tcl_user_app.instBlock(
{
'name':'xlconstant',
'inst': 'applicationRegion/id_' + str(kern['num']),
'properties':['CONFIG.CONST_WIDTH {32}',
'CONFIG.CONST_VAL {'+ str(kern['num'])+'}']
}
)
tcl_user_app.makeConnection(
'net',
{
'name':'applicationRegion/id_' + st... | |
action_args = {}
capacity = parsed_args.capacity
adjustment = parsed_args.adjustment
percentage = parsed_args.percentage
min_size = parsed_args.min_size
max_size = parsed_args.max_size
min_step = parsed_args.min_step
wait = parsed_args.wait
if sum(v is not None for v in (capacity, adjustment, percentage,
min... | |
<reponame>lund5000/chirpradio
# -*- coding: utf-8 -*-
###
### Copyright 2009 The Chicago Independent Radio Project
### 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 Licen... | |
from operator import mul
import sys
import matplotlib.pyplot as plt
import numpy as np
from holoviews import opts
from scipy.signal.ltisys import dfreqresp
from scipy.spatial import Voronoi
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from skl... | |
import logging
import os
import sys
from collections import Counter
import SimpleITK as sitk
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms
import numpy as np
from matplotlib.ticker import PercentFormatter
from sklearn.metrics import confusion_matrix
f... | |
<filename>Backend/src/__init__.py
import os
import psycopg2
from . import FunctionML
from . import MLPRegressor
from . import Regressors
from flask import Flask, render_template, request
from flask_cors import CORS
from flask_bcrypt import Bcrypt
from flask_sqlalchemy import SQLAlchemy
import pandas as pd
import os
imp... | |
<reponame>gmftbyGMFTBY/SimpleReDial-v1
from header import *
from .utils import *
from .util_func import *
class GPT2Dataset(Dataset):
def __init__(self, vocab, path, **args):
self.args = args
self.vocab = vocab
self.pad = self.vocab.convert_tokens_to_ids('[PAD]')
self.sep = self.vocab.convert_tokens_to_ids('[S... | |
= resize_image(image, resize_height, resize_width)
image = np.asanyarray(image)
if normalization:
image = image_normalization(image)
# show_image("src resize image",image)
return image
def read_image_batch(image_list):
'''
批量读取图片
:param image_list:
:return:
'''
image_batch = []
out_image_list = []
for im... | |
string names of the analysis and the values stored are
6x1 np.array[float] vectors containing the 3 internal forces and
3 moments at the first node.
- `F2 (dict)`: This dictionary contains the results of an analysis set. The
keys are the string names of the analysis and the values stored are
6x1 np.array[float] ve... | |
return -1
try:
optimizerName=datHyperPara['optimizer']
except Exception as e:
self.pathOfData=None
data_details=self.upDateStatus()
self.updateStatusWithError(data_details,'Training Failed',"Couldn't find hyperparameters optimizerName >> "+ str(e),traceback.format_exc(),self.statusFile)
return -1
try:
learni... | |
<filename>nngen/verify/basic.py
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import numpy as np
import nngen.util as util
def add(x, y, dtype=None, name=None, par=1,
x_dtype=None, y_dtype=None):
x_point = 0 if x_dtype is None else x_dtype.point
y_p... | |
# ----------------------------------------------------------------------------
# Copyright (c) 2016--, gneiss development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ------------------------------------------------... | |
4 7 4 7 7 7]
[2 4 2 6 4 5 6 7]
[3 7 6 3 7 7 6 7]
[4 4 4 7 4 7 7 7]
[5 7 5 7 7 5 7 7]
[6 7 6 6 7 7 6 7]
[7 7 7 7 7 7 7 7]
TESTS::
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: H = HasseDiagram({0:[2,3],1:[2,3]})
sage: H.join_matrix()
Traceback (most recent call last):
...
ValueEr... | |
(33.9225, -116.850555556),
"KBNO": (43.5919444444, -118.955555556),
"KBNW": (42.0494444444, -93.8475),
"KBOI": (43.5641666667, -116.222777778),
"KBOS": (42.3641666667, -71.005),
"KBOW": (27.9433333333, -81.7833333333),
"KBPG": (32.2125, -101.521666667),
"KBPI": (42.585, -110.111111111),
"KBPK": (36.3688888889, ... | |
<reponame>Tim232/Python-Things<filename>Projects/DeepLearningProject/image_classification/cnn_for_cifar_10/ensemble_cnn_model_cifar_10_v02.py
import tensorflow as tf
class Model:
def __init__(self, sess, name):
self.sess = sess
self.name = name
self._build_net()
def _build_net(self):
with tf.variable_scope(self... | |
= value
@property
def region_name(self) -> str:
"""Name of the region for which FCI is calculated ??? Developed Markets, Emerging
Markets, Euro Area, Global."""
return self.__region_name
@region_name.setter
def region_name(self, value: str):
self._property_changed('region_name')
self.__region_name = value
... | |
import qiskit
import qtm.progress_bar
import qtm.constant
import qtm.qfim
import qtm.noise
import qtm.optimizer
import qtm.fubini_study
import numpy as np
import types, typing
def measure(qc: qiskit.QuantumCircuit, qubits, cbits=[]):
"""Measuring the quantu circuit which fully measurement gates
Args:
- qc (Quantu... | |
:])
elif survey_type.lower() in ["dipole-dipole", "dipole-pole"]:
srcClass = dc.sources.Dipole([rxClass], P[ii, :], P[ii + 1, :])
source_list.append(srcClass)
return source_list
def xy_2_lineID(dc_survey):
"""
Read DC survey class and append line ID.
Assumes that the locations are listed in the order
they w... | |
0], dtype=np.float32
)
output[name]["colors"][s]["g"] = np.array(
colors[:, 1], dtype=np.float32
)
output[name]["colors"][s]["b"] = np.array(
colors[:, 2], dtype=np.float32
)
else:
colors = np.array([cmaps[s](x) for x in data[mapping["c"]][s]])
colors = np.round(colors * 255.0)
output[name]["colors"][s]["r"]... | |
"""
An implementation of the confluent hypergeometric function.
"""
from __future__ import division
import numpy as np
from numpy import pi
from numpy.lib.scimath import sqrt
from scipy.special import gamma, rgamma, jv, gammaln, poch
import warnings
from hyp1f1_decimal import hyp1f1 as hyp1f1_decimal
tol = 1.0e-15... | |
def set_default_selinux_context(self, path, changed):
if not HAVE_SELINUX or not self.selinux_enabled():
return changed
context = self.selinux_default_context(path)
return self.set_context_if_different(path, context, False)
def set_context_if_different(self, path, context, changed, diff=None):
if not HAVE_SELIN... | |
the value is the data itself.
For more information, see `Data Types <https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes>`__ in the *Amazon DynamoDB Developer Guide* .
- **S** *(string) --*
An attribute of type String. For example:
``"S": "Hell... | |
with stats is not supported (yet)")
if is_scalar(mapt):
return
if list in mapt.keys():
other_keys = [k for k in mapt if k != list]
for e in other_keys:
if e in mapt[list]:
tomerge = mapt.pop(e)
if mode_inst:
for typ in tomerge:
if not type(typ) == type:
continue
if not typ in mapt[list][e]:
mapt[list][e][t... | |
"manual_scaling")
@manual_scaling.setter
def manual_scaling(self, value: Optional[pulumi.Input['StandardAppVersionManualScalingArgs']]):
pulumi.set(self, "manual_scaling", value)
@property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
"""
Full Serverless VPC Access Connector name e.g. /project... | |
mc #Hope this helps with resource leaks!
if e_errors.is_ok(status['status'][0]):
#use_type = "%s=%s" % (status['drive_id'],
# use_type)
use_type = status['drive_id']
#Regardless of an error or not, we found the
# mover we were looking for. Give up.
break
### Without an explicit colle... | |
to update
parentChildren = None
if hasattr(value, '_children'):
parentChildren = value._children
# check if this is a valid parent
tmp = "Cannot change to that parent, "
if value is None:
# an object can be an orphan
pass
elif value is self:
# an object cannot be its own parent
raise TypeError(tmp+"becaus... | |
file name')
else:
comp = ccache.get_compound(cid)
comp.molfile = mol
all_comp_data[cid] = comp
met_to_comp_dict[met] = cid
print( met+ ' was inserted as mol file. it mapped to the kegg id' + cid)
else:
warnings.warn("unexpected metabolite name:" + met)
comp = None
# we got a hit so it's a bigg metabolite, ... | |
#
# 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 use... | |
<reponame>tguillemLSST/CLMM
"""Tests for dataops.py"""
import numpy as np
from numpy import testing
import clmm
from clmm import GCData
import clmm.dataops as da
import clmm.theory as theo
TOLERANCE = {'atol':1.e-7, 'rtol':1.e-7}
def test_compute_cross_shear():
shear1, shear2, phi = 0.15, 0.08, 0.52
expected_cros... | |
<gh_stars>10-100
import math
import sys
import numpy as np
import scipy.spatial
from pychemia import Composition, Structure, pcm_log
from pychemia.analysis import ClusterAnalysis, ClusterMatch
from pychemia.code.lennardjones import lj_compact_evaluate
from pychemia.utils.mathematics import unit_vector, length_vectors,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.