input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
IP range, the provided "
f"ending IP address of {storage_controller_vm_ip_range_end_address} is "
"the same as the provided starting IP address of "
f"{storage_controller_vm_ip_range_start_address}. Please provide a "
"different ending IP address and restart the HX Auto Deploy Tool.\n")
sys.exit(0)
# Verif... | |
<filename>sudokutools/solvers.py
"""High level solving of sudokus.
This module provides classes which represent typical sudoku solving
steps used by humans. Steps can be found and applied to a given
sudoku. But steps can also be printed without applying them, e.g. to inform
a user, what steps can be taken to solve the... | |
<gh_stars>1-10
# -*- coding: utf-8 -*-
from datetime import *
import pytest
import os
import sys
from v8 import *
from v8.utils import *
if is_py3k:
def toUnicodeString(s):
return s
else:
def toUnicodeString(s, encoding='utf-8'):
return s if isinstance(s, unicode) else unicode(s, encoding)
def testObject():
wit... | |
getattr(fixpart, attr)
stringified[attr] = val.replace(b'\x00', b'').decode('ascii')
fixpart = fixpart._replace(**stringified)
return fixpart
def read_fea_header(self, level=0):
'''Read header of FT_FEA with no fea subtype.'''
# TODO: combine feapart1 and feapart2
hdr = EspsHeader(level)
feapart1 = EspsFeapart1... | |
from __future__ import print_function
import numpy as np
from scipy.linalg import eigh, expm, norm
from scipy.sparse import csr_matrix, spmatrix
from math import factorial
import warnings
from functools import reduce
try:
import qutip
except ImportError:
qutip = None
class Setup(object):
sparse = False
def __ini... | |
to 0, the cookie is non-persistent and lasts
only until the end of the browser session (or equivalent). The
maximum allowed value for TTL is one day.
When the load balancing scheme is INTERNAL, this field is not used.
"""
return pulumi.get(self, "affinity_cookie_ttl_sec")
@affinity_cookie_ttl_sec.setter
def aff... | |
= max([abs(min(dtxlist)),abs(max(dtxlist))])
self.dtymax0 = max([abs(min(dtylist)),abs(max(dtylist))])
self.dtzmax0 = max([abs(min(dtzlist)),abs(max(dtzlist))])
self.dmaxset = 1
for i in range(self.num_z):
for j in range(self.num_x):
dtxi,dtzi,dtxj_up,dtxj_down,dtxj_left,dtxj_right,dtzj_up,dtzj_down,dtzj_left,d... | |
<reponame>AndresQuichimbo/landlab
import numpy as np
import pytest
from numpy import testing
from landlab import HexModelGrid, RasterModelGrid
from landlab.components import FlowAccumulator, Space
def test_route_to_multiple_error_raised():
mg = RasterModelGrid((10, 10))
z = mg.add_zeros("topographic__elevation", a... | |
<reponame>msarmie/horizon
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... | |
import json
import warnings
from enum import Enum
from typing import Any, List, Tuple, Union
import numpy as np
import torch
from mmhuman3d.core.cameras.cameras import PerspectiveCameras
from mmhuman3d.core.conventions.cameras.convert_convention import (
convert_camera_matrix,
convert_K_3x3_to_4x4,
convert_K_4x4_t... | |
'TTL': 300,
'Type': 'A'
}, # this is a ordinary record. should be not modified.
# we expect to have the tree without the ip that has weight 0.
] + policy_members_to_list(policy_members, policy_record)
expected = sorted(expected, key=sort_key)
actual = strip_ns_and_soa(
boto_client.list_resource_record_sets(Hoste... | |
<gh_stars>10-100
from __future__ import division, unicode_literals, absolute_import
import numpy as np
import logging
logger = logging.getLogger(__name__)
from .utils import dict_2_list
from collections import namedtuple
Variable = namedtuple("Variable", ("name","func","kwarg"), defaults=(None,None,{}) )
Constant = ... | |
if 'Load Preset' in selection:
# Rebuild settings menu using preset
settings_menu = build_settings_menu(silent=False)
else:
break
# Detect drives
if 'Detect drives' in selection[0]:
std.clear_screen()
std.print_warning(DETECT_DRIVES_NOTICE)
if std.ask('Are you sure you proceed?'):
std.print_standard('Forcing... | |
in use by the simulation data."""
dm = data.models
if file_type == 'undulatorTable':
if _is_tabulated_undulator_source(dm.simulation):
return dm.tabulatedUndulator.magneticFile == filename
return False
field = None
if file_type == 'mirror':
field = 'MirrorFile'
elif file_type == 'sample':
field = 'ImageFile'
... | |
# coding: utf-8
# ## Case study
#
# In this case study we'll walk through using Python to fetch some data, clean it, and then graph it. This may be a short project, but it combines a number of features of the language we've dicussed, and gives you a chance to a see a project worked through from beginning to end. At ... | |
iftrue
elif claripy.is_false(cond_v):
return iffalse
else:
data = iftrue.merge(iffalse)
return data
#
# Unary operation handlers
#
def _handle_Const(self, expr) -> MultiValues:
return MultiValues(offset_to_values={0: { claripy_value(expr.con.type, expr.con.value) }})
def _handle_Conversion(self, expr):
s... | |
'void'
else:
# TODO: extract informations needed for printing in case of function argument which itself has a function argument
arg_code = ', '.join('{}'.format(self._print_FuncAddressDeclare(i))
if isinstance(i, FunctionAddress) else '{0}{1}'.format(self.get_declare_type(i), i)
for i in args)
return '{}(*{})({})... | |
<filename>pyqstrat/account.py
from collections import defaultdict
from sortedcontainers import SortedDict
import math
import pandas as pd
import numpy as np
from pyqstrat.pq_types import ContractGroup, Trade, Contract
from types import SimpleNamespace
from typing import Sequence, Any, Tuple, Callable, Union, MutableSet... | |
i=None):
if i is None:
return self.getTokens(StlParser.Identifier)
else:
return self.getToken(StlParser.Identifier, i)
def COMMA(self):
return self.getToken(StlParser.COMMA, 0)
def RPAREN(self):
return self.getToken(StlParser.RPAREN, 0)
def accept(self, visitor):
if hasattr(visitor, "visitRosTopic"):
return... | |
the model to find out what features are more discriminative for the positive and negative classes
Usually the computationally light chi2 test against the class labels.
:param training_data: numpy ndarray representing the training dataset features
:param training_data_labels: numpy ndarray representing the training ... | |
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00248228,
'Renaming Unit/Peak Dynamic': 3.58947,
'Renaming Unit/Runtime Dynamic': 0.0907826,
'Renaming Unit/Subthreshold Leakage': 0.0552466,
'Renaming Unit/Subthreshold Leakage with power gating': 0.0276461,
'Runtime Dynamic': 3.10146,
'... | |
276.3,
266.1,
276.1,
268.1,
277.0,
273.4,
269.7,
],
]
],
units="K",
dtype="f8",
)
f.set_data(data, axes=("domainaxis0", "domainaxis1", "domainaxis2"))
# domain_ancillary
c = DomainAncillary()
c.set_properties({"units": "m"})
c.nc_set_variable("a")
data = Data([10.0], units="m", dtype="f8")
c.set_dat... | |
import numpy as np
from numba import jit
import numpy.lib.recfunctions as rfn
##########################################################################
def count_hsps(blast_out):
"""Iterate over blast output. It considers that the output
is in outfmt 6 and that all the hsp should be one after the
other
Args:
... | |
from fractions import Fraction as F
>>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
Fraction(13, 21)
>>> from decimal import Decimal as D
>>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
Decimal('0.5625')
If ``data`` is empty, StatisticsError will be raised.
"""
title = 'mean'
type_ = 'statistics'
... | |
# encoding=utf8
"""
Module containing functions for calculating or approximating factorials.
"""
import numpy as np
from decimal import Decimal, localcontext
def factorial(n, prec=100):
r"""
Function for calculating factorials using the standard approach as explained in the
Notes section. For ... | |
{
'storageAccountType': 'Standard_LRS'
},
'name': vm_name,
'createOption': 'FromImage'
}
},
'osProfile': {
'adminUsername': admin_username,
'computerName': vm_name,
'adminPassword': <PASSWORD>
},
'networkProfile': {
'networkInterfaces': [
{
'id': full_nic_id,
'properties': {
'primary': 'true'
}
}
]
... | |
<gh_stars>10-100
"""
Pytorch modules
"""
from collections import defaultdict
import copy
import json
import logging
from io import open
import torch
from torch import nn
from torch.nn import functional as F
# from apex.normalization.fused_layer_norm import FusedLayerNorm as LayerNorm
from torch.nn import LayerNorm
fr... | |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gui.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
... | |
originCoordLong, and originCoordName are used to specify a (named) coordinate. For the destination, the corresponding parameters are named either destId or destCoordLat, destCoordLong and destCoordName. It is also possible to define a via-stop/station. This forces the journey planner to search for trips which pass the ... | |
cb.solve()
error += cb.close()
if not forsystemhealth:
interpolate_bandpass_solutions(
msname,
sourcename,
thresh=interp_thresh,
polyorder=interp_polyorder,
mode='a'
)
caltables += [
{
'table': '{0}_{1}_bacal'.format(msname, sourcename),
'type': 'B',
'spwmap': spwmap
}
]
cb = cc.calibrater()
error ... | |
<reponame>faradayio/docker-crankshaft<gh_stars>10-100
import unittest
import numpy as np
import unittest
# from mock_plpy import MockPlPy
# plpy = MockPlPy()
#
# import sys
# sys.modules['plpy'] = plpy
from helper import plpy, fixture_file
import crankshaft.space_time_dynamics as std
from crankshaft import random_s... | |
0x47FA
MediaGaugeB251 = 0x47FB
MediaGaugeB252 = 0x47FC
MediaGaugeB253 = 0x47FD
MediaGaugeB254 = 0x47FE
MediaGaugeB255 = 0x47FF
# MediaGaugeC List
MediaGaugeC0 = 0x4800
MediaGaugeC1 = 0x4801
MediaGaugeC2 = 0x4802
MediaGaugeC3 = 0x4803
MediaGaugeC4 = 0x4804
MediaGaugeC5 = 0x4805
MediaGaugeC6 = 0x4806
MediaG... | |
<reponame>Amrib24/aws-secure-environment-accelerator
#!/usr/bin/env python
import os
import boto3
import botocore
import json
import threading
import time
import sys
import argparse
import base64
import re
from tabulate import tabulate
from os import path
parser = argparse.ArgumentParser(
description="A development... | |
<reponame>checkly/pulumi-checkly
# 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 warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequenc... | |
################################################################################
# Copyright (c) 2021 ContinualAI. #
# Copyrights licensed under the MIT License. #
# See the accompanying LICENSE file for terms. #
# #
# Date: 01-12-2020 #
# Author(s): <NAME>, <NAME> #
# E-mail: <EMAIL> #
# Website: avalanche.continualai... | |
import datetime
import json
from unittest import mock
import pytest
from simple_salesforce import SalesforceMalformedRequest
from cumulusci.tasks.push.push_api import (
BasePushApiObject,
MetadataPackage,
MetadataPackageVersion,
PackagePushError,
PackagePushJob,
PackagePushRequest,
PackageSubscriber,
Salesfor... | |
<reponame>formalabstracts/CNL-CIC<filename>2parser/parser_combinator.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 12 14:39:04 2021
@author: <NAME>
This file contains parser combinators.
The original name was parse.py, but that conflicts with a python lib.
The combinators should preserves ... | |
<reponame>selinozdas/ObsCo
from helpers import quick_sort,get_variances
from pprint import pprint
from db import mongo
import numpy as np
import pickle
from sklearn.externals import joblib
from sentiment import vect
from util import remove_common_adjectives
filename = 'obsco_model.sav'
model = joblib.load(open(filenam... | |
of the same type. Parameter default
values are instantiated once and cached to be reused when another
Parameterized object of the same type is instantiated.
Can be useful to easily modify large collections of Parameterized
objects at once and can provide a significant speedup.
"""
_share = False
_shared_cache =... | |
timeout):
"""
Sets the timeout limit for an order to the RAPI.
:param timeout: The value of the timeout in seconds.
:type timeout: float
"""
self.timeout_order = float(timeout)
def set_attempts(self, number):
"""
Sets number of attempts to be made to the RAPI before the script
ends.
:param number: T... | |
= parse_yaml(paths, fn)
all_run_data = copy.deepcopy(run_data) # all_run_data includes failed jobs
if show_fails:
# remove all jobs that have no PBS info in log file
for jobid in all_run_data:
if all_run_data[jobid]['PBS log']['Run completion date'] is None:
del run_data[jobid]
# (jobid, run completion date) ... | |
type
_MODULE_TYPE_ = {
"LIBRARY" : "BASE",
"SECURITY_CORE" : "SEC",
"PEI_CORE" : "PEI_CORE",
"COMBINED_PEIM_DRIVER" : "PEIM",
"PIC_PEIM" : "PEIM",
"RELOCATABLE_PEIM" : "PEIM",
"PE32_PEIM" : "PEIM",
"BS_DRIVER" : "DXE_DRIVER",
"RT_DRIVER" : "DXE_RUNTIME_DRIVER",
"SAL_RT_DRIVER" : "DXE_SAL_DRIVER",
... | |
all or a subset of the
columns from the input files.
For complete details, see the `1dcat Documentation.
<https://afni.nimh.nih.gov/pub/dist/doc/program_help/1dcat.html>`_
Examples
========
>>> from nipype.interfaces import afni
>>> cat1d = afni.Cat()
>>> cat1d.inputs.sel = "'[0,2]'"
>>> cat1d.inputs.in_fil... | |
import numpy as np
# Size of the maze
maze_size = (250, 400)
class Node:
# To save the index of the current node
node_index = 0
# To save the index of the parent node
parent_index = 0
# A list of all the possible actions [North, East, South, West, North-East, South-East, South-West, North-West]
... | |
2, "photos are missing in db"
assert tu.album_exists_in_db("FußÄ-Füße"), "unicode album is not in db"
def test_corrupted(self):
# load 1 album with a corrupted file
tu = TestUtils()
assert tu.is_env_clean(tu.conf['lycheepath']), "env not clean"
# load unicode album name
tu.load_photoset("corrupted_file")
# lau... | |
import argparse
import json
import multiprocessing
import os
import platform
import re
import shutil
import signal
import stat
import subprocess
import time
import traceback
import urllib
import uuid
import zipfile
from os.path import expanduser
import psutil
import requests
import yaml
from fedml.cli.edge_deploymen... | |
"""
Copyright (c) 2014 NavPy Developers. All rights reserved.
Use of this source code is governed by a BSD-style license that can be found in
LICENSE.txt
"""
import numpy as np
from . import wgs84
from ..utils import input_check_Nx3 as _input_check_Nx3
from ..utils import input_check_Nx3x3 as _input_check_Nx3x3
from .... | |
<reponame>TRO-HIT/nipype<filename>nipype/interfaces/freesurfer/preprocess.py
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Provides interfaces to various commands provided by FreeSurfer
"""
import os
import os.path as op
from... | |
(before_colon, after_docstring), colon, docstring, body = tokens
else:
raise CoconutInternalException("invalid match def joining tokens", tokens)
# after_docstring and body are their own self-contained suites, but we
# expect them to both be one suite, so we have to join them together
after_docstring, dedent = spl... | |
<filename>common/rtt_worker.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: <NAME>, ph4r05, 2018
# pip install shellescape sarge
import logging
import signal
import threading
import time
import sys
import os
import random
import socket
import typing
import shutil
import tempfile
import paramiko
import sshtu... | |
<gh_stars>0
#!/usr/bin/env python3
# module checking
try:
import os
import sys
import argparse
import getpass
import configparser
except:
print("Missing modules detected!")
sys.exit(1)
# Testing rich existence
try:
from rich import print
from rich.table import Table
except:
print("Error: >rich< module not f... | |
### Expected results for parse.py unit tests
# coding: utf-8
from collections import OrderedDict
book_1 = {
'book': {'filename': '1En', 'title': '1 Enoch', 'textStructure': ''},
'version': [
{
'attributes': {'title': 'Ethiopic 1', 'author': 'Anonymous', 'fragment': '', 'language': 'Ethiopic',},
'organisation_lev... | |
<gh_stars>0
import re, socket, json, sys, six
from xbmcswift2 import Plugin, xbmc, xbmcaddon, xbmcgui, xbmcplugin
from resources.lib.hamivideo.api import Hamivideo
import base64, time, os
try:
from multiprocessing.dummy import Pool as ThreadPool
threadpool_imported = True
except:
threadpool_imported = False
#import... | |
# -*- coding: utf-8 -*-
"""Тесты модуля matan"""
import unittest
import random
from fem.matan import Matrix
class TestMatrixOperations(unittest.TestCase):
"""Тестирование операций с матрицами"""
def test_create_col(self):
"""Тест на создание вектора столбца"""
col1 = Matrix([[1], [2], [3], [4]])
col2 = Matrix([... | |
"""
Classic cart-pole system implemented by <NAME> et al.
Copied from http://incompleteideas.net/sutton/book/code/pole.c
permalink: https://perma.cc/C9ZM-652R
"""
import math
import gym
from gym import spaces, logger
from gym.utils import seeding
import numpy as np
from scipy.integrate import ode
g = 9.8... | |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from vdp.model.v1alpha import healthcheck_pb2 as vdp_dot_model_dot_v1alpha_dot_healthcheck__pb2
from vdp.model.v1alpha import model_definition_pb2 as vdp_dot_mod... | |
'''
@FileName : init_guess.py
@EditTime : 2021-12-13 13:37:50
@Author : <NAME>
@Email : <EMAIL>
@Description :
'''
from core.utils.recompute3D import recompute3D
import torch
import numpy as np
from core.utils.umeyama import umeyama
import cv2
from core.utils.visualization3d import Visualization
from core.affinit... | |
#!/usr/bin/env python
from __future__ import print_function
import os
import sys
import time
import traceback
from github import GithubException, GithubObject
from issue_finder import CommitFinder, IssueFinder
from mantisdump import MantisDump, MantisSchema
# Python3 redefined 'unicode' to be 'str'
if sys.version_i... | |
<reponame>leozz37/makani
# Copyright 2020 Makani Technologies LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | |
import pytest
import matplotlib.pyplot as plt
import numpy as np
import popkinmocks as pkm
@pytest.fixture
def my_component():
ssps = pkm.model_grids.milesSSPs()
ssps.logarithmically_resample(dv=100.)
ssps.calculate_fourier_transform()
ssps.get_light_weights()
cube = pkm.ifu_cube.IFUCube(ssps=ssps, nx=9, ny=10)
... | |
<filename>tencentcloud/eiam/v20210420/eiam_client.py
# -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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... | |
str) == True :
r_function, v_function, r_buff, r_format, f_function = EXTRACT_INFORMATION_SIMPLE( op_value )
# it's a variable length opcode
else :
r_function, v_function, r_buff, r_format, f_function = EXTRACT_INFORMATION_VARIABLE( i, op_value, self.__raw_buff[ i : ] )
len_format = calcsize(r_format)
raw_buff =... | |
f')
plt.title('Electric field (Intensity/Mean)')
plt.xlabel('$x/r_f$')
if not subplot:
plt.show()
return
def plot_delay(self, subplot=False):
# get frequency to set the scale, enter in GHz
Freq = self.freq/1000
plt.subplot(2, 1, 1)
plt.plot(np.linspace(0, self.dx*self.nx, self.nx),
-self.dm/(2*self.dlam*Fre... | |
<filename>tests/test_urls.py
# -*- coding: utf-8 -*-
"""
Tests for the basecampy3.urls package.
"""
from __future__ import unicode_literals
import logging
import os
import re
import time
import unittest
import uuid
from datetime import date, datetime, timedelta
import dateutil
import pytz
from tzlocal import get_loc... | |
<gh_stars>0
import pytest
from anchore_engine.common.models.policy_engine import NVDReference
from anchore_engine.services.policy_engine.engine.vulns.mappers import (
ENGINE_DISTRO_MAPPERS,
ENGINE_PACKAGE_MAPPERS,
GRYPE_PACKAGE_MAPPERS,
EngineGrypeDBMapper,
JavaMapper,
VulnerabilityMapper,
)
@pytest.mark.param... | |
<filename>banyan/controllers/cloud_resource.py
import logging
from typing import List
from uuid import UUID
import copy
from time import sleep
from cement import Controller, ex
from banyan.controllers.base import Base
from banyan.api import BanyanApiClient
from banyan.model.cloud_resource import CloudResource, Clou... | |
<gh_stars>0
import os
import subprocess
from unittest import mock
from . import *
from .... import *
from mopack.builders.bfg9000 import Bfg9000Builder
from mopack.config import Config
from mopack.path import Path
from mopack.sources import Package
from mopack.sources.apt import AptPackage
from mopack.sources.sdist i... | |
<filename>ads/feature_engineering/feature_type/handler/feature_validator.py
#!/usr/bin/env python
# -*- coding: utf-8 -*--
# Copyright (c) 2021, 2022 Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
"""
The module that helps to regi... | |
<reponame>renato2099/weld
import pandas as pd
import grizzly_impl
from lazy_op import LazyOpResult, to_weld_type
from weld.weldobject import *
import utils
class SeriesWeld(LazyOpResult):
"""Summary
Attributes:
column_name (TYPE): Description
df (TYPE): Description
dim (int): Description
expr (TYPE): Descript... | |
(0,5) : self.tech_level+1
elif self.government == 7 : self.tech_level+=2
elif self.government == 13 : self.tech_level-=2
elif self.government == 14 : self.tech_level-=2
else:
self.tech_level =0
self.tech_level=min(self.tech_level,max_tl)
# CTM-sequence (specialized technology levels)
if self.population > 0:
# ... | |
<filename>vst_sim/src/vstsim/grasping/grasp_sampler.py
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
import copy
import logging
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
# import os, IPython, sys
import math
import random
import time
import scipy.stats ... | |
<filename>Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/courseware/tests/test_tabs.py
"""
Test cases for tabs.
"""
from unittest.mock import MagicMock, Mock, patch
import pytest
from crum import set_current_request
from django.contrib.auth.models import AnonymousUser
from dj... | |
assert sech(5*pi*I/4) == -sqrt(2)
assert sech(-5*pi*I/4) == -sqrt(2)
assert sech(pi*I/6) == 2/sqrt(3)
assert sech(-pi*I/6) == 2/sqrt(3)
assert sech(7*pi*I/6) == -2/sqrt(3)
assert sech(-5*pi*I/6) == -2/sqrt(3)
assert sech(pi*I/105) == 1/cos(pi/105)
assert sech(-pi*I/105) == 1/cos(pi/105)
assert sech(x*I) == 1... | |
DA: " + str(da))
tree = self.process_das([da])[0]
log_debug("RESULT: %s" % str(tree))
# append the tree to a t-tree document, if requested
if gen_doc:
zone = self.get_target_zone(gen_doc)
zone.ttree = tree.create_ttree()
zone.sentence = str(da)
# return the result
return tree
def init_slot_err_stats(self):
... | |
#!/usr/bin/python
# General imports
from __future__ import absolute_import, division, print_function
from sshutil.cmd import SSHCommand
import logging
import telnetlib
import socket
import json
import time
import random
from socket import AF_INET
from socket import AF_INET6
# ipaddress dependencies
from ipaddress imp... | |
<reponame>jfallaire/generator-ps-boilerplate-project<filename>generators/simple/templates/src/platform/extensionRunner/cdf/document_definition.py<gh_stars>1-10
"""
- THIS FILE IS GENERATED -
CoveoInterfaces/DocumentDefinition/CoveoDocumentDefinition.jid
"""
from attr import attrib, attrs
from enum import auto
from ... | |
DPR 633/72"
riferimento_ordine=""
quantita="1"
prezzo="2,00"
sconti=""
codice_iva="53"
u_m="Nr"
importo="2,00"
fattura.add_row(codice_articolo,descrizione,riferimento_ordine,u_m,quantita,prezzo,sconti,importo,codice_iva)
if not codice_iva in lista_codici_iva:
lista_codici_iva[codice_iva] = 2
... | |
(a_name, i, run))
clr_redraw()
if self.verbose and not self.ipy:
print('iter %d took %.3f seconds' % (i, time.time() - iter_time))
elif self.ipy:
iter_timebox.value = time.time() - iter_time
iter_progress.value += 1
iter_progress.description = 'Iter [%d/%d]' % (iter_progress.value, n_iter)
# run finished; st... | |
<filename>seraphsix/models/destiny.py
from datetime import datetime, timezone
from dataclasses import dataclass, field
from dataclasses_json import dataclass_json, config, LetterCase
from marshmallow import fields
from typing import Optional, List, Dict, Any
from seraphsix import constants
from seraphsix.tasks.parsing... | |
<reponame>Anikbh11/trident
"""
Ion fraction fields using Cloudy data.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2016, Trident Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed... | |
was not 'High'. ######################
if not test2_ok:
deficiency_type = ''
status = ''
global_EQR = np.nan
comment = 'not enough data for test2 (jan-may)'
elif test2_result > self.deficiency_limit or np.isnan(test2_result):
#### METHOD 1 ####
deficiency_type = 'seasonal'
global_EQR, status = self._calculate_... | |
import numpy as np
import torch
import itertools
from torchvision import datasets
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from skimage.measure import compare_psnr, compare_ssim
from skimage.restoration import denoise_nl_means, estimate_sigma
import skimage.io as sio
from glow.glow im... | |
# coding=utf-8
__source__ = 'https://leetcode.com/problems/super-egg-drop/'
# Time: O(KlongN)
# Space: O(NK)
# DP
# dp(K,N)= min(max(dp(K−1,X−1),dp(K,N−X))))
# 1≤X≤N
#
# Description: Leetcode # 887. Super Egg Drop
#
# You are given K eggs, and you have access to a building with N floors from 1 to N.
#
# Each egg is ide... | |
#!/usr/bin/env python
"""
Main process for updating audio files metadata from parsed configuration files.
All options defining specific metadata fields (``--artist``, ``--year``, etc.) override any
corresponding information fields found in configurations files from options ``--info`` or ``--all``.
Applied changes list... | |
self),
alignment=core.Qt.AlignHCenter | core.Qt.AlignVCenter)
hsizer.addSpacing(102) # 82)
hsizer.addWidget(qtw.QLabel(self.master.captions['C_WID'], self),
alignment=core.Qt.AlignVCenter)
hsizer.addSpacing(8) # 84)
hsizer.addWidget(qtw.QLabel(self.master.captions['C_IND'], self),
alignment=core.Qt.AlignVCenter)... | |
import os
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from sklearn.neighbors import (
NearestNeighbors, radius_neighbors_graph, kneighbors_graph)
from sklearn.utils.graph import graph_shortest_path
from scipy.spatial import distance_matrix
fro... | |
Register('csrce2', 8, 0x90006710),
Register('csrce3', 8, 0x90006718),
Register('csrce4', 8, 0x90006720),
Register('csrce5', 8, 0x90006728),
Register('csrce6', 8, 0x90006730),
Register('csrce7', 8, 0x90006738),
Register('csrce8', 8, 0x90006740),
Register('csrce9', 8, 0x90006748),
Register('csrcea', 8, 0x90006750... | |
#! python
## Copyright (c) 2018-2021, Carnegie Mellon University
## See LICENSE for details
## This script reads a file, cube-sizes.txt, that contains several cube size
## specifications for the 3D DFT. This script will:
## Generate a list of source file names for CMake to build
## Create the source files (by running... | |
<gh_stars>1-10
from medpy.io import load
from medpy.io import save
import numpy as np
from sklearn import utils
from os import listdir,makedirs
from os.path import isfile, join, isdir,exists
import os
from medpy.features import indices
import pickle
import medpy.metric
import scipy.ndimage as ndimage
import ... | |
('credit', False, Credit),
('credit-words', True, CreditWords),
('encoding', False, Encoding),
('software', True, Software),
('supports', False, Supports),
('encoding-date', True),
('part-list', False, PartList),
('part-group', False, PartGroup),
('group-name', True),
('group-symbol', True),
('group-... | |
'\U0001d54a',
'sopf;': '\U0001d564',
'spades;': '\u2660',
'spadesuit;': '\u2660',
'spar;': '\u2225',
'sqcap;': '\u2293',
'sqcaps;': '\u2293\ufe00',
'sqcup;': '\u2294',
'sqcups;': '\u2294\ufe00',
'Sqrt;': '\u221a',
'sqsub;': '\u228f',
'sqsube;': '\u2291',
'sqsubset;': '\u228f',
'sqsubseteq;': '\u2291',
'sq... | |
None:
if "buffer" not in args: args = {"buffer":""}
return args
args["buffer"]+=data
for iteration in range(args["buffer"].count("|")):
# Isolate a particular command
length = args["buffer"].index("|")
if length==0:
args["buffer"] = args["buffer"][1:]
continue
data = args["buffer"][0:lengt... | |
# qmpy/materials/entry.py
from datetime import datetime
import time
import os
from django.db import models
from django.db import transaction
import networkx as nx
from qmpy.db.custom import *
from qmpy.materials.composition import *
from qmpy.materials.element import Element, Species
from qmpy.materials.structure im... | |
Return a boolean FastArray set to True where duplicate rows exist,
optionally only considering certain columns
Parameters
----------
subset : str or list of str, optional
A column label or list of column labels to inspect for duplicate values.
When ``None``, all columns will be examined.
keep : {'first'... | |
# -*- test-case-name: flocker.node.agents.functional.test_ebs -*-
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
An EBS implementation of the ``IBlockDeviceAPI``.
"""
from subprocess import check_output
import threading
import time
import logging
from uuid import UUID
from bitmath import Byte, GiB
... | |
[]
starting_time = time.time()
self.DurationPerTrial = pd.Series(index=np.arange(repeats), dtype=float)
self.RetPerTrial = pd.Series(index=np.arange(repeats), dtype=float)
ret_per_trial = []
# Try as many times as required by the integer 'repeats'
for i in np.arange(repeats):
start_trial = time.time()
if not p... | |
KB = 0.53 * x_T
BMT = ((0.085 * x_CB - 0.002) * x_B * x_B) / (x_T * x_CB)
KG = 1.0 + 0.52 * x_D
constraintFuncs[8] = (KB + BMT - KG) - (0.07 * x_B)
constraintFuncs = np.where(constraintFuncs < 0, -constraintFuncs, 0)
f[3] = constraintFuncs[0] + constraintFuncs[1] + constraintFuncs[2] + constraintFuncs[3] + const... | |
import re
from flask import jsonify
from sqlalchemy import text
from db import db
class IcuDevelopments:
__build_obj = """
json_build_object(
'timestamp',
agg.timestamp,
'inserted',
agg.last_insert_date,
'last_updated',
agg.last_update,
'num_hospitals',
agg.num_hospitals,
'icu_low_state',
json_build_obj... | |
import sys
from ctypes import *
import platform
from .types import *
from ._platform import DLL_PATH, is_windows
def load_libtiepie():
"""Load libtiepie library and import all functions."""
if is_windows:
from ctypes.wintypes import HANDLE, HWND, LPARAM, WPARAM
api = CDLL(DLL_PATH)
api.LibInit.restype = None
... | |
import pickle
from abc import ABC, abstractmethod
from io import BytesIO
from db_classes import PRG
from geo_utilities import *
class XmlParser(ABC):
def __init__(self, xml_path: str, tags_tuple: tuple, event_type: str) -> None:
self.xml_path = xml_path
self.tags_tuple = tags_tuple
self.event_type = event_type
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.