input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
import os
import numpy as np
import random
class Reader(object):
def __init__(self, dataset_dir, listfile=None):
self._dataset_dir = dataset_dir
if listfile is None:
listfile_path = os.path.join(dataset_dir, "listfile.csv")
else:
listfile_path = listfile
with open(listfile_path, "r") as lfile:
self._data = lf... | |
bollo_presente = False
bollo = 0
for k,v in lista_codici_iva.iteritems():
codice_iva = k
importo_netto = v
# print "LISTA CODICI : ",codice_iva,importo_netto
dettaglio_iva = db(db.anagrafica_codici_iva.codice_iva == codice_iva).select().first()
percentuale_iva = dettaglio_iva.percentuale_iva
descrizione... | |
#!/usr/bin/env python
################################################################################
# $Id$
# $Revision$
# $Date$
################################################################################
#
# Written by <NAME>
# see LICENSE.txt for license information
#
#########################################... | |
self.z[t, l*self.r_part:(l+1)*self.r_part]
Y[idx] = self.y[t, l]
idx += 1
idx_list.append(idx)
if self.k == 1:
pars[:, 0], u_hat_temp[:, 0] = self.multivariate_OLS(Y, X)
elif self.k == 21:
pars[:, l], u_hat_temp[:, l] = self.multivariate_OLS(Y, X)
zeros = np.zeros((max_delay_AR+288, self.k), dtype=np.float32)
... | |
Got %d, expected %d' \
% (i, curSessionCount, curRes.cNumSessions));
fRc = False;
break;
if curGuestSession is not None \
and curGuestSession.name != curGuestSessionName:
reporter.error('Test #%d failed: Session name does not match: Got "%s", expected "%s"' \
% (i, curGuestSession.name, curGuestSessionName));
f... | |
5*np.log(2) +
5*np.log(1 - mckin/mbkin)))/(45927*mbkin**9) -
(321536*mckin**10*(np.log(2) + np.log(1 - mckin/mbkin))*
(1 + 5*np.log(2) + 5*np.log(1 - mckin/mbkin)))/(229635*mbkin**10) -
(4115968*(np.log(2) + np.log(1 - mckin/mbkin))*(1 + 6*np.log(2) +
6*np.log(1 - mckin/mbkin)))/2525985 +
(16463872*mckin*(np.log(... | |
<reponame>Brown-University-Library/easyrequest_project<filename>easyrequest_app/views.py
# -*- coding: utf-8 -*-
import datetime, json, logging, os, pprint
from django.conf import settings as project_settings
from django.contrib.auth import logout
from django.core.urlresolvers import reverse
from django.http import H... | |
"""
Manages finding, running and recoding benchmark results.
This module has shamelessly borrows from
the `airspeed velocity (asv) <http://asv.readthedocs.io/en/latest>`_
file `benchmark.py <https://github.com/spacetelescope/asv/blob/master/asv/benchmark.py>`_.
See the `airspeed velocity (asv) <http://asv.readthedocs.... | |
import numpy as np
import pytest
from pandas.errors import UnsupportedFunctionCall
from pandas import (
DataFrame,
DatetimeIndex,
Series,
date_range,
)
import pandas._testing as tm
from pandas.core.window import ExponentialMovingWindow
def test_doc_string():
df = DataFrame({"B": [0, 1, 2, np.nan, 4]})
df
df... | |
of example IDs for my_vars.TP/TN/FP/FN
Returns
-------
dict.
Updated confusion matrix.
"""
# print("neighbors:\n{}".format(neighbor))
predicted = rule[class_col_name]
true = example[class_col_name]
# print("example label: {} vs. rule label: {}".format(predicted, true))
predicted_id = example.name
# Potenti... | |
# ~~~
# This file is part of the paper:
#
# "A NON-CONFORMING DUAL APPROACH FOR ADAPTIVE TRUST-REGION REDUCED BASIS
# APPROXIMATION OF PDE-CONSTRAINED OPTIMIZATION"
#
# https://github.com/TiKeil/NCD-corrected-TR-RB-approach-for-pde-opt
#
# Copyright 2019-2020 all developers. All rights reserved.
# License: Licensed as ... | |
to networks and information systems relevant to essential functions are identified, analysed, prioritised, and managed.", # noqa: E501
"score": 2
}, {
"answer": "Your approach to risk is focused on the possibility of adverse impact to your essential function, leading to a detailed understanding of how such impact mi... | |
<reponame>kursawe/hesdynamics<gh_stars>0
# import PyDDE
import numpy as np
import scipy.signal
import scipy.optimize
import scipy.interpolate
import multiprocessing as mp
from numba import jit
from numpy import ndarray, number
import os
import matplotlib as mpl
import matplotlib.pyplot as plt
# import seaborn.apionly a... | |
+ 1)
plt.plot(band / 1e6, np.abs(response), 'b.-')
plt.plot(band / 1e6, np.abs(response_guess), 'g')
plt.plot(band / 1e6, np.abs(response_fit), 'r')
plt.xlabel('Frequency (MHz)')
plt.ylabel('Amplitude (nm)')
plt.tight_layout(pad=0.0, w_pad=0.0, h_pad=0.0)
plt.subplot(resonances, 2, (n + 1) + 2)
plt.plot(band /... | |
Leakage': 0.00611897,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00348781,
'Renaming Unit/Peak Dynamic': 4.56169,
'Renaming Unit/Runtime Dynamic': 0.451536,
'Renaming Unit/Subthreshold Leakage': 0.070483,
'Renaming Unit/Subthreshold Leakage with power gating': 0.0362779,
'Runtime ... | |
'P*7d'
kaihimore(moves)
if oute.oute == 0:
depth1.append(moves)
if Wboard.l>0:
moves = 'L*7d'
kaihimore(moves)
if oute.oute == 0:
depth1.append(moves)
if Wboard.n>0:
moves = 'N*7d'
kaihimore(moves)
if oute.oute == 0:
depth1.append(moves)
if Wboard.s>0:
moves = 'S*7d'
kaihimore(moves)
if oute.oute == 0:... | |
# License is MIT: see LICENSE.md.
"""Nestle: nested sampling routines to evaluate Bayesian evidence."""
import sys
import warnings
import math
import numpy as np
try:
from scipy.cluster.vq import kmeans2
HAVE_KMEANS = True
except ImportError: # pragma: no cover
HAVE_KMEANS = False
__all__ = ["sample", "print_pr... | |
<filename>amznas.py
#!/usr/bin/env python
# Command line utility for Amazonian Nasality project
# TODO: check --lx param
# TODO: try to prevent lx recording when not requested
try:
import os
import re
import glob
import subprocess
import yaml
import numpy as np
from pathlib import Path
from datetime import d... | |
# This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) <NAME> <<EMAIL>>
# This program is published under a GPLv2 license
# flake8: noqa: E501
"""
Unit testing infrastructure for Scapy
"""
from __future__ import absolute_import
from __future__ import print_functi... | |
and self.default is not None:
_dict['Default'] = self.default
if hasattr(self, 'sw') and self.sw is not None:
_dict['SW'] = self.sw.to_dict()
if hasattr(self, 'pkc_s11') and self.pkc_s11 is not None:
_dict['PKCS11'] = self.pkc_s11.to_dict()
return _dict
def _to_dict(self):
"""Return a json dictionary represent... | |
<gh_stars>100-1000
# Software License Agreement (BSD License)
#
# Copyright (c) 2008, <NAME>, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retai... | |
None ) : return ( [ None , None ] )
if 89 - 89: o0oOOo0O0Ooo % o0oOOo0O0Ooo
return ( [ packet , Oo000o0o0 ] )
if 8 - 8: Ii1I % oO0o - o0oOOo0O0Ooo
if 14 - 14: OOooOOo * IiII
def lcaf_decode_eid ( self , packet ) :
oOO0OOOoO0ooo = "BBB"
I1111ii1i = struct . calcsize ( oOO0OOOoO0ooo )
if ( len ( packet ) < I1111i... | |
* self._n_joints]
actions_speeds = actions_speeds.reshape(
(2, self._n_joints))
actions_accelerations = actions[:, 2 * self._n_joints:]
actions_accelerations = actions_accelerations.reshape(
(2, self._n_joints))
speeds = np.vstack([self._previous_hermite_speeds, actions_speeds])
accelerations = np.vstack([self._... | |
trimmedPatchesLR = patchesLR[booleanMask]
trimmedPathcesHR = patchesHR[booleanMask]
return (trimmedPatchesLR, trimmedPathcesHR)
def removeCorruptedTestPatchSets(patchesLR: np.ma.masked_array,
clarityThreshold: float) -> np.ma.masked_array:
'''
Input:
patchesLR: np.ma.masked_array[numImgSet, numPatches, numLowRe... | |
import asyncio
import re
import warnings
from math import sqrt
from html import unescape
from base64 import b64decode
from urllib.parse import unquote, urlparse
import aiohttp
import async_timeout
from .errors import BadStatusError
from .utils import log, get_headers, IPPattern, IPPortPatternGlobal
class Provider:... | |
route into Intake Chords Func, else an empty Set"""
chords_set = set()
if not self.intake_bypass:
chords_set = self.intake_chords_set
return chords_set
def init_unichars_func(self, unichars, optchords):
"""Let people type the From Chars in place of the To Chars"""
unichords = unichars.encode()
funcs = self... | |
: {'none', 'deterministic', 'fft', 'fft_tiling', 'winograd', 'guess_once',
'guess_on_shape_change', 'time_once', 'time_on_shape_change'}
Default is the value of :attr:`config.dnn.conv.algo_bwd_data`.
"""
__props__ = ('algo', 'inplace',)
__input_name__ = ('kernel', 'grad', 'output', 'descriptor', 'alpha',
'beta'... | |
import numpy as np
from .hetero_likelihoods import GaussianHeteroNoise, Gaussian
import gpflow
from gpflow.param import Param
from gpflow import transforms
from gpflow.model import Model
from gpflow.mean_functions import Zero
import tensorflow as tf
from gpflow.param import AutoFlow, DataHolder, ParamList
from gpflow._... | |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, sys, subprocess, bs4,signal, urllib.request, urllib.error, urllib.parse, json,socket
import requests
import re
import json
import sys
import urllib3
import core
import http.client
import socket
from time import sleep
import os as sistema
import readline, rlcompleter... | |
then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remo... | |
info overloaded class method 2.
Args:
exp_stack: The expected call stack
capsys: Pytest fixture that captures output
"""
exp_caller_info = CallerInfo(mod_name='test_diag_msg.py',
cls_name='ClassGetCallerInfo2',
func_name='get_caller_info_c2bt',
line_num=7479)
exp_stack.append(exp_caller_info)
update_stack(e... | |
from pycassa import NotFoundException
from pycassa.pool import ConnectionPool
from pycassa.columnfamily import ColumnFamily
from pycassa.util import OrderedDict, convert_uuid_to_time
from pycassa.system_manager import SystemManager
from pycassa.types import (LongType, IntegerType, TimeUUIDType, LexicalUUIDType,
AsciiT... | |
>>> bnd_verts = [k for k, _ in enumerate(msh.vertices)]
>>> msh.insert_boundary_vertices(0, bnd_verts)
>>> print(msh.vertices)
[[0. 0.]
[0. 1.]
[1. 1.]
[1. 0.]]
>>> print(msh.material_regions)
[]
>>> # add a material region to the mesh
>>> # this material region fills the bottom half of the mesh
>>> import ... | |
('renorm', (S, S, S), (1, 2, 3), 'norm_1'),
('renorm', (S, S, S), (inf, 2, 0.5), 'norm_inf'),
('repeat', (S,), (2,), 'single_number'),
('repeat', (), (2, 3), 'scalar'),
('repeat', (2, 2), (3, 2)),
('repeat', (2, 2), (1, 3, 1, 2), 'unsqueeze'),
('cumsum', (S, S, S), (0,), 'dim0', (), [0]),
('cumsum', (S, S, S), (... | |
finish_migration(self, context, migration, instance, disk_info,
network_info, image_meta, resize_instance=False,
block_device_info=None, power_on=True):
"""Completes a resize, turning on the migrated instance."""
vm_ref = vm_util.get_vm_ref(self._session, instance)
flavor = instance.flavor
boot_from_volume = com... | |
<gh_stars>1-10
import copy
from enum import Enum
from direct.gui.OnscreenText import CollisionTraverser, CollisionHandlerQueue, CollisionNode, \
CollisionRay, OnscreenText, TransparencyAttrib, CollisionSphere
from direct.task import Task
from panda3d.core import BitMask32, LPoint3
from direct.gui.DirectButton import ... | |
' { "key":"radar-vl", "type":"double", "default":0 },\n'
' { "key":"radar-f", "type":"double", "default":0 } ], '
'"url":"Vocoder", \n'
' "tip":"Released under terms of the GNU General Public License '
'version 2" },\n'
' { "id":"Vocoder", "name":"Vocoder", "params":\n'
' [ \n'
' { "key":"dst", "type":"double", ... | |
SHORT STRING | LONG STRING =========
"""
if self.peek_token(1, 3) == '""':
string = self.lex_string(char + self.eat_token('""'))
else:
string = self.lex_string(char)
tokens.append(Token(string, TokenKind.STRING, *self.get_line_info()))
elif char == ".":
"""
========= DELIMITER | FLOAT =========
"""
char =... | |
<filename>groupy/groupy.py
# This file is just to mess around with creating Groups in python
import re
class Gel:
"""
A group element.
The Gel object consists of a name and a permutation. The permutation is some bijection from the set of numbers from
1 to n onto itself in the form of a tuple. Since any group el... | |
= property(__class.value, __class.set, None, None)
_ElementMap.update({
__Reference.name() : __Reference,
__Para.name() : __Para,
__Include.name() : __Include,
__List.name() : __List,
__Table.name() : __Table,
__Term.name() : __Term
})
_AttributeMap.update({
__class.name() : __class
})
_module_typeBindings.... | |
import ctypes
import platform
import time
from time import sleep
import numpy as np
import pybullet as p
from igibson.render.mesh_renderer.mesh_renderer_settings import MeshRendererSettings
from igibson.render.mesh_renderer.mesh_renderer_vr import MeshRendererVR, VrSettings
from igibson.render.viewer import ViewerVR
... | |
# Anton's Code
# Teacher Notes - OCR, Optical Character Recognition, numpy, imagine => matrix, stackoverflow.com/questions/52633697/selenium-python-how-to-capture-network-traffics-response#make sure you're not downloading at a high rate or risk getting blocked?
# Note* I know the offline section is fairly redundant b... | |
self._formula_description = ClientGUICommon.SaneMultilineTextCtrl( my_panel )
( width, height ) = ClientGUICommon.ConvertTextToPixels( self._formula_description, ( 90, 8 ) )
self._formula_description.SetInitialSize( ( width, height ) )
self._formula_description.Disable()
self._edit_formula = ClientGUICommon... | |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... | |
<filename>pter/searcher.py<gh_stars>0
import datetime
import string
from pytodotxt import Task
class Searcher:
def __init__(self, text=None, casesensitive=True, default_threshold=None, hide_sequential=True):
self.words = set()
self.not_words = set()
self.projects = set()
self.not_projects = set()
self.contexts... | |
i11iIiiIii . OOooOOo / Oo0Ooo * O0 % oO0o % iIii1I11I1II1
if 78 - 78: iIii1I11I1II1 - Ii1I * OoO0O00 + o0oOOo0O0Ooo + iII111i + iII111i
if 11 - 11: iII111i - OoO0O00 % ooOoO0o % iII111i / OoOoOO00 - OoO0O00
if 74 - 74: iII111i * O0
if 89 - 89: oO0o + Oo0Ooo
if 3 - 3: i1IIi / I1IiiI % I11i * i11iIiiIii / O0 * I11i
... | |
<filename>src/pyrin/packaging/manager.py
# -*- coding: utf-8 -*-
"""
packaging manager module.
"""
import os
import inspect
from threading import Lock
from importlib import import_module
from time import time
import pyrin.application.services as application_services
import pyrin.configuration.services as config_serv... | |
"""
Functions for explaining text classifiers.
"""
from functools import partial
import itertools
import json
import re
import numpy as np
import scipy as sp
import sklearn
from sklearn.utils import check_random_state
from . import explanation
from . import lime_base
class TextDomainMapper(explanat... | |
upper boundary
Returns:
Booleans: True/False.
Examples:
>>> model.set_boundary("reaction", 'HEX1', 0.001, 100.0)
See Also:
set_constrain
"""
if group == "reaction":
dic_temp = self.reactions
elif group == "metabolite":
dic_temp = self.metabolites
elif group == "reversible":
dic_temp = self.reversible
... | |
import numpy as np
import h5py
import scipy.io
from math import floor
from enum import Enum
from collections import namedtuple as tuple
# from keras.preprocessing.image import Iterator # For random batch sizes
class Dataset(Enum):
TRAIN=0
VALID=1
TEST=2
class DataFile(Enum):
NAME=0
X=1
Y=2
class ModelData(ob... | |
"""Control the sc2monitor."""
import asyncio
import logging
import math
import time
from datetime import datetime, timedelta
from operator import itemgetter
import aiohttp
import sc2monitor.model as model
from sc2monitor.handlers import SQLAlchemyHandler
from sc2monitor.sc2api import SC2API
logger = logging.getLogge... | |
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00248228,
'Renaming Unit/Peak Dynamic': 3.58947,
'Renaming Unit/Runtime Dynamic': 0.0437228,
'Renaming Unit/Subthreshold Leakage': 0.0552466,
'Renaming Unit/Subthreshold Leakage with power gating': 0.0276461,
'Runtime Dynamic': 1.55628,
'... | |
<reponame>hilbix/fusetree
import fuse
from fuse import fuse_file_info
from typing import Dict, Iterator, Iterable, Sequence, Tuple, Optional, Any, NamedTuple, Union, List
import logging
import errno
import time
import threading
import traceback
from . import util
from .types import *
class Node:
"""
A node is the ... | |
PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinSession.get_resource_ids_by_bin
id_list = []
for authorization in self.get_authorizations_by_vault(vault_ids):
id_list.append(authorization.get_id()... | |
= "sensors.NumericSensor_4_0_3.ReadingChangedEvent:1.0.0"
def __init__(self, newReading, source):
super(raritan.rpc.sensors.NumericSensor.ReadingChangedEvent, self).__init__(source)
typecheck.is_struct(newReading, raritan.rpc.sensors.NumericSensor.Reading, AssertionError)
self.newReading = newReading
def encode... | |
<filename>ddi_search_engine/Bio/EUtils/MultiDict.py
"""Dictionary-like objects which allow multiple keys
Python dictionaries map a key to a value. Duplicate keys are not
allowed, and new entries replace old ones with the same key. Order is
not otherwise preserved, so there's no way to get the items in the
order they w... | |
<filename>index_publish_results_to_excel.py
import argparse
import datetime as dt
import math
import os
import pandas as pd
from openpyxl import Workbook
from src.config.appConfig import loadAppConfig
from src.repos.latestRevData import LatestRevsRepo
from src.repos.gensMasterDataRepo import GensMasterRepo
from src.r... | |
of the found motif IDs
motifID_lst: List[str]
# list of the found motif names
motifName_lst: List[str]
# list of the found motif widths
motif_width_lst: List[int]
# list of the found motif site counts
site_counts_lst: List[int]
# list of the found motif alphabet lengths
alphalen_lst: List[int]
# list of the f... | |
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Layer, Lambda, Input, Conv2D, TimeDistributed, Dense, Flatten
from utils import bbox_utils, train_utils
import tensorflow.keras.regularizers as KR
import tensorflow.keras.layers as KL
import tensorflow.keras.initialize... | |
self.nb_steps = nb_steps
p_f = 1 / (365 * (24 / time_ss) * time_r)
beta = stats.norm.ppf((1 - p_f), loc=0, scale=1) # Reliability
theta = np.linspace(0, 2 * np.pi, num = nb_steps)
# Vary U1, U2 along circle sqrt(U1^2+U2^2)=beta
U1 = beta * np.cos(theta)
U2 = beta * np.sin(theta)
comp_1 = stats.exponwe... | |
<filename>tests/test_entity/test_entity_profile.py
"""Test entity profile."""
import os
import shutil
import unittest
from pathlib import Path
import emmental
import numpy as np
import torch
import ujson
from pydantic import ValidationError
from bootleg.run import run_model
from bootleg.symbols.entity_profile import ... | |
0.12805900959162*
m.x1567)) + m.x1176 == 1)
m.c349 = Constraint(expr=-5/(1 + 30*exp((-0.128834434867751*m.x1476) - 0.250018751406355*m.x1499 - 0.1162398726011*
m.x1568)) + m.x1177 == 1)
m.c350 = Constraint(expr=-5/(1 + 30*exp((-0.114914790682709*m.x1477) - 0.239354699729529*m.x1500 - 0.105284214737684*
m.x1569)) +... | |
"""
node.py
Contains the base class for Nodes.
"""
import traceback
from logging import Logger
from functools import wraps
from typing import Any, Union, Tuple, Dict, Optional, Type, List, Callable, TypeVar
from .. import NodeBase
from .. import QtGui, QtCore, Signal, Slot, QtWidgets
from ..data.datadict import Data... | |
<reponame>dmyersturnbull/sauronlab<filename>sauronlab/viz/figures.py
from __future__ import annotations
import matplotlib.legend as mlegend
from matplotlib import patches
from mpl_toolkits.axes_grid1 import make_axes_locatable
from pocketutils.plotting.color_schemes import FancyCmaps, FancyColorSchemes
from pocketutil... | |
= input("Unit Type:")
value = float(input("Numerical Value:"))
if index == "1":
print("In Celsius is:" + str(value))
print("In Fahrenheit is:" + str((value * 9/5) + 32))
print("In Kelvin is:" + str(value + 273.15))
temperature()
elif index == "2":
print("In Celsius is:" + str((value-32)*(5/9)))
print(... | |
(top left of medal)
:param x_coord: x coordinate to check (top left of medal)
:return: None
"""
rows = self.rows
columns = self.columns
if x_coord < columns - 1 and y_coord < rows - 1:
for i in range(2):
for j in range(2):
if self.medal_grid.grid[y_coord + i][x_coord + j] != -1:
return False
return True
ret... | |
#!/usr/bin/env python
from __future__ import print_function
import skimage as skimage
from skimage import transform, color, exposure, io
from skimage.viewer import ImageViewer
import random
from random import choice
import numpy as np
from collections import deque
import time
import math
import os
import pandas as pd
... | |
import tensorflow as tf
from .print_object import print_obj
def get_variables_and_gradients(loss, scope):
"""Gets variables and their gradients wrt. loss.
Args:
loss: tensor, shape of [].
scope: str, the network's name to find its variables to train.
Returns:
Lists of variables and their gradients.
"""
func_... | |
lists but just values.
Parameters
----------
base : array
Input array to extend.
names : string, sequence
String or sequence of strings corresponding to the names
of the new fields.
data : array or sequence of arrays
Array or sequence of arrays storing the fields to add to the base.
dtypes : sequence of data... | |
LAYER POLYGONS TO PASS TO SELF.POLYGONS AND ONTO THE GRAV/MAG ALGORITHMS
# FIRST SET UP XY DATA; IF LAYER IS BELOW LAYER 0 THEN ATTACH THE ABOVE LAYER TO COMPLETE THE POLYGON;
# ELSE USE TOP LAYER CHECK FOR 'FIXED' LAYER MODE AND FIND LAST LAYER TO MAKE POLYGON
if i >= 1 and self.layer_list[i].type == 'fixed':
# C... | |
# Copyright (C) 2019 Intel Corporation.
# SPDX-License-Identifier: BSD-3-Clause
"""the tool to generate ASL code of ACPI tables for Pre-launched VMs.
"""
import sys, os, re, argparse, shutil, ctypes
from acpi_const import *
import board_cfg_lib, common
import collections
import lxml.etree
sys.path.append(os.path.jo... | |
<filename>cadquery/cq.py
"""
Copyright (C) 2011-2015 Parametric Products Intellectual Holdings, LLC
This file is part of CadQuery.
CadQuery is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
ver... | |
not exist."
logger.info(msg % resource)
return
if not self.force:
slang = self.get_resource_option(resource, 'source_lang')
for language in stats:
if language == slang:
continue
if int(stats[language]['translated_entities']) > 0:
msg = (
"Skipping: %s : Unable to delete resource because it "
"has a not empty... | |
<filename>analysis/value_strategy_funcs.py
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
from scipy import stats
from linearmodels import FamaMacBeth
from decimal import Decimal
from data_source import local_source
from tqdm import tqdm as pb
import datetime
def DataFrame_Updater(df_old, df_new, b... | |
#Author: <NAME>
import numpy as np
import os
import h5py
import pandas as pd
from AxonImaging import signal_processing as sp
def get_processed_running_speed (vsig,vref,sample_freq, smooth_filter_sigma = 0.05, wheel_diameter = 16.51, positive_speed_threshold= 70, negative_speed_threshold= -5):
''' Returns... | |
from markupsafe import escape
from sqlalchemy import and_, desc, false, true
from galaxy import managers, model, util, web
from galaxy.model.item_attrs import UsesItemRatings
from galaxy.util.json import loads
from galaxy.util.sanitize_html import sanitize_html, _BaseHTMLProcessor
from galaxy.web import error, url_for... | |
14, -4, -4): (0, 1),
(8, 14, -4, -3): (0, 1),
(8, 14, -4, -2): (0, 1),
(8, 14, -4, -1): (0, 1),
(8, 14, -4, 0): (0, 1),
(8, 14, -4, 1): (0, 1),
(8, 14, -4, 2): (0, 1),
(8, 14, -4, 3): (0, 1),
(8, 14, -4, 4): (0, 0),
(8, 14, -4, 5): (-1, -1),
(8, 14, -3, -5): (0, 1),
(8, 14, -3, -4): (0, 1),
(8, 14, -3, -3):... | |
MD_OFX_DEFAULT_SETTINGS_FILE = moduleBuild.MD_OFX_DEFAULT_SETTINGS_FILE
if len(moduleBuild.MD_OFX_DEBUG_SETTINGS_FILE) > 0:
MD_OFX_DEBUG_SETTINGS_FILE = moduleBuild.MD_OFX_DEBUG_SETTINGS_FILE
if len(moduleBuild.MD_EXTENSIONS_DIRECTORY_FILE) > 0:
MD_EXTENSIONS_DIRECTORY_FILE = moduleBuild.MD_EXTENSIONS_DIRECTORY_FIL... | |
glEndList()
glNewList(self.displistUnselected, GL_COMPILE)
self._render(False)
glEndList()
def render(self, selected=False):
if selected:
glCallList(self.displistSelected)
else:
glCallList(self.displistUnselected)
def _render(self, selected=False):
pass
class Cube(SelectableModel):
def __init__(self, col... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICE... | |
<filename>source/strategy/strategy_base.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from abc import ABC, ABCMeta
from typing import Any, Callable
from copy import copy
from ..common.constant import (
Interval,
OrderFlag, OrderType, Offset, Direction
)
from ..common.datastruct import (
TickData, BarData,
OrderR... | |
as pd\n"
)
f.write("import pyemu\n")
for ex_imp in self.extra_py_imports:
f.write("import {0}\n".format(ex_imp))
for func_lines in self._function_lines_list:
f.write("\n")
f.write("# function added thru PstFrom.add_py_function()\n")
for func_line in func_lines:
f.write(func_line)
f.write("\n")
f.write("def ... | |
<filename>nxt_editor/dockwidgets/hotkey_editor.py
# Built-in
import logging
# External
from Qt import QtWidgets, QtGui, QtCore
# Internal
import nxt_editor
from nxt_editor.dockwidgets.dock_widget_base import DockWidgetBase
from nxt_editor import colors, dialogs
logger = logging.getLogger(nxt_editor.LOGGER_NAME)
TOOL... | |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | |
import mxnet as mx
from mxnet.gluon import loss
from models.loss import pairwise_distance
def unique(F, data):
"""
Returns the unique elements of a 1D array
:param F:
:param data:
:return:
"""
sdata = F.reshape(data, (-1,))
sdata = F.sort(sdata, axis=-1)
mask = F.concat(F.ones(1, ctx=sdata.context, dtype=sd... | |
the compressed data doesn't have its content size embedded within it,
decompression can be attempted by specifying the ``max_output_size``
argument:
>>> dctx = zstandard.ZstdDecompressor()
>>> uncompressed = dctx.decompress(data, max_output_size=1048576)
Ideally, ``max_output_size`` will be identical to the deco... | |
import logging
import time
import random
import math
import os
import json
import spacy
import pandas as pd
import copy
import numpy as np
from tqdm import tqdm
from nltk.tokenize import word_tokenize
from spacy.tokens import Token
from spacy.tokens import Span
from spacy.tokens import Doc
import src.graph as graph
f... | |
part, can swear with all certainty that there is no way to reconcile everyone at once, and what pleases one will provoke whingeing and sulking in another, and will undoubtedly cause a third to reach for his knife… What then are we to do? How should we live? Why, as we like, as our soul urges, disregarding all the brayi... | |
<reponame>siddheshshaji/FLAML
import numpy as np
import math
from flaml.tune import Trial
from flaml.scheduler import TrialScheduler
import logging
logger = logging.getLogger(__name__)
class OnlineTrialRunner:
"""Class for the OnlineTrialRunner."""
# ************NOTE about the status of a trial***************
#... | |
if necessary, by
removing lower-quality *rules. Return a list containing any rules
whose numerosities dropped to zero as a result of this call. (The
list may be empty, if no rule's numerosity dropped to 0.) The
model argument is a ClassifierSet instance which utilizes this
algorithm.
Usage:
deleted_rules = mode... | |
#!/usr/bin/env python
# native packages
import argparse
from collections import defaultdict
import glob
import logging
import os
import shutil
import sys
import time
# external packages
import dask
import numpy as np
import pandas as pd
import yaml
# local packages
import download.download as download
import label.l... | |
#for data cleaning and analysis
import pandas as pd
import numpy as np
from random import randint
#for visualization
import matplotlib.pyplot as plt
import seaborn as sns
#for directory-related functions
import os
import glob
import getpass
#for web-scraping baseball data
import pybaseball as pyb
#for drafting
imp... | |
# return '{:02d}m:{:02d}s:{:03d}ms'.format(m, s, ms)
return '{:02d}m:{:02d}s'.format(m, s)
def get_time_h_mm_ss(self, time_ms, symbol=True):
"""
Returns time in h:mm:ss format.
:param time_ms:
:param symbol:
:return:
"""
s, ms = divmod(int(time_ms), 1000)
m, s = divmod(s, 60)
h, m = divmod(m, 60)
if not ... | |
sigma score for the customers
# associated to the chosen route.
eps_bar = eps_unrouted[route_seed_idx,associated_cols]
# NOTE: CMT 1979 does not specify what happens if S is empty, we assume
# we need (and can) omit the calculation of eps_prime in this case.
brdcast_rs_idxs = [[rsi] for rsi in route_seed_idxs]... | |
if (self.calcCluster):
self.chi0Ma = self.chic0M
else:
self.chi0Ma = self.chi0M
self.pm = np.dot(self.GammaM, self.chi0Ma)/(self.invT*float(self.Nc))
if self.vertex_channel in ("PARTICLE_PARTICLE_SUPERCONDUCTING","PARTICLE_PARTICLE_UP_DOWN","PARTICLE_PARTICLE_SINGLET"):
self.pm2 = np.dot(sqrt(real(self.chi0Ma)... | |
= conv_raw_prob)
# sum up losses and take mean accross batch
giou_loss = tf.reduce_mean(tf.reduce_sum(giou_loss, axis = [1,2,3,4]))
conf_loss = tf.reduce_mean(tf.reduce_sum(conf_loss, axis = [1,2,3,4]))
prob_loss = tf.reduce_mean(tf.reduce_sum(prob_loss, axis = [1,2,3,4]))
if np.isnan(giou_loss):
giou_loss ... | |
size in six.moves.range(length, length + 1):
end = start + size
if end > item_length:
continue
yield _to_xapian_term(item[start:end])
def edge_ngram_terms(value):
for item, length in _get_ngram_lengths(value):
yield _to_xapian_term(item[0:length])
def add_edge_ngram_to_document(prefix, value, weight):
"""
S... | |
probability
})
for order_id in probabilities:
if probabilities[order_id] is None:
continue
order_probabilities = probabilities[order_id]
best_expected_f1 = 0
best_expected_f1_products = None
for k in order_probabilities:
f1_for = k['positive']
# if len(f1_for) == 0:
# # Skip P(None)
# continue
total_... | |
import json
from pathlib import Path
from shutil import Error
from unittest.mock import mock_open, patch
import gdk.CLIParser as CLIParser
import gdk.common.consts as consts
import gdk.common.exceptions.error_messages as error_messages
import gdk.common.parse_args_actions as parse_args_actions
import gdk.common.utils ... | |
union
# of proposals from all levels
# NOTE: When FPN is used, the meaning of this config is different from Detectron1.
# It means per-batch topk in Detectron1, but per-image topk here.
# See the "find_top_rpn_proposals" function for details.
_C.MODEL.RPN.POST_NMS_TOPK_TRAIN = 2000
_C.MODEL.RPN.POST_NMS_TOPK_TEST = 100... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.