input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<filename>flexx/app/pair.py
"""
Base class for objects that live in both Python and JS.
This basically implements the syncing of signals.
"""
import sys
import json
import weakref
import hashlib
from .. import react
from ..react.hassignals import HasSignalsMeta, with_metaclass
from ..react.pyscript import create_js_s... | |
<filename>mqlight/client.py<gh_stars>10-100
# python-mqlight - high-level API by which you can interact with MQ Light
#
# Copyright 2015-2017 IBM Corp.
#
# 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 L... | |
<filename>notebooks/utils.py
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import numpy as np
import pandas as pd
from collections import OrderedDict
from cycler import cycler
import warnings
warnings.filterwarnings('ignore')
matplotlib.style.use('ggplot')
matplotlib.rcParams['axe... | |
#!/usr/bin/env python
###########################################################
# GDPR scanner, by <NAME>
# see https://github.com/blookot/elastic-gdpr-scanner
###########################################################
# This script requires Python 3!
import sys
MIN_PYTHON = (3, 0)
if sys.version_info < MIN_PYTHO... | |
<reponame>pshen/pg_view<gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import sys
import glob
import logging
from optparse import OptionParser
from operator import itemgetter
from datetime import datetime, timedelta
from numbers import Number
from multiprocessing import Process, JoinableQ... | |
# coding: utf-8
import pprint
import re
import six
class ListInstancesRespInstances:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
opena... | |
to be fully up before continuing
while serverStartupStatus != 200:
try:
#urllib GET request
statusRequest = urllib.request.urlopen(statusURL)
serverStartupStatus = statusRequest.code
except Exception as e:
if currTime > timeoutVal:
#We have reached timeout and the server is not started
raise e
if e... | |
corrected phases
use_correct_sigma: bool
flag to use corrected phase errors
use_model: bool
flag to use precomputed model data
Returns
-------
None, update self.twiss_from_phase dictionary
"""
self.data_phase = {}
fx = self.fx_correct if use_correct else self.fx
fy = self.fy_correct if use_correct else se... | |
<filename>analysis/calc.py
"""Energy calculations and histograms."""
import abc
import collections
import datetime
import functools
import itertools
import math
import os
import pickle
import warnings
import numpy
import pandas
from matplotlib import pyplot
# Use seaborn's plotting styles.
try:
im... | |
== -1/2
assert Rotation.d(2, 2, -2, pi/2).doit() == 1/4
assert Rotation.d(2, 1, 2, pi/2).doit() == 1/2
assert Rotation.d(2, 1, 1, pi/2).doit() == -1/2
assert Rotation.d(2, 1, 0, pi/2).doit() == 0
assert Rotation.d(2, 1, -1, pi/2).doit() == 1/2
assert Rotation.d(2, 1, -2, pi/2).doit() == -1/2
assert Rotation.d(2,... | |
"""
Parameters
----------
info_MDP: This is an object of Class mushroom_rl.environment.MDPInfo. It contains the action and observation spaces,
gamma and the horizon of the MDP.
Returns
-------
This method returns True if the algo_params were set successfully, and False otherwise.
"""
self.info_MDP = inf... | |
<filename>actions.py
"""Sublime Text commands performing vim actions.
If you are implementing a new action command, stick it here.
Action parsers belong instead in Vintageous/vi/actions.py.
"""
import sublime
import sublime_plugin
from Vintageous.state import IrreversibleTextCommand
from Vintageous.sta... | |
import torch
from torch.utils.data.dataloader import DataLoader
from torch.utils.data.sampler import RandomSampler, SequentialSampler
from transformers import Trainer
from .dataset_utils import SimpleDataset, extract_keys
import gc
import inspect
import datasets
from torch.optim.lr_scheduler import MultiplicativeLR
fro... | |
<filename>skspec/IO/gwu_interfaces.py
''' Utilities for converting various file formats to a skspec TimeSpectra.
To convert a list of raw files, use from_spec_files()
To convert old-style timefile/spectral data file, use from_timefile_datafile()
To convert spectral datafiles from Ocean Optics USB2000 and USB650, pas... | |
22197,
22198,
22200,
22201,
22202,
22203,
22204,
22205,
22206,
22207,
22208,
22209,
22212,
22214,
22216,
22217,
22218,
22219,
22220,
22221,
22222,
22223,
22224,
22225,
22226,
22227,
22228,
22229,
22231,
22232,
22234,
22235,
22236,
22237,
22238,
22239,
22240,
22241,
22242,
22243,
... | |
<filename>python/smqtk/web/iqr_service/iqr_server.py
import base64
import binascii
import collections
import json
import multiprocessing
import time
import traceback
import uuid
import flask
# import smqtk.algorithms
from smqtk.algorithms import (
get_classifier_impls,
get_descriptor_generator_impls,
get_nn_index_... | |
"""Support for aggregation-based AMG"""
__docformat__ = "restructuredtext en"
import numpy
import scipy
from scipy.sparse import isspmatrix_csr, isspmatrix_bsr
from pyamg.multilevel import multilevel_solver
from pyamg.util.utils import relaxation_as_linear_operator
from pyamg.relaxation.smoothing import change_smoot... | |
"""
Custom Jinja2 template filters
"""
import re
import logging
import ipaddresstools as ipv4
J2_FILTER_LOGGER = logging.getLogger('qct_template_filter')
def filter_check_u_ip_address(value):
"""Function to check for a unicast ipv4 address in a template
:type value: String
:param value: Value to check if it is a... | |
import calendar
import datetime
import email.utils
import flask
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
import logging
from requests.exceptions import RequestException
from time import sleep
from typing import Callable, Collection
import urllib.parse
import netaddr
import py... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `gffpandas` package."""
# standard library imports
import shutil
import time
from pathlib import Path
# first-party imports
import gffpandas.gffpandas as gff3pd
# third-party imports
import pandas as pd
# module imports
from . import print_docstring
# glo... | |
import json
import os
import urllib3
import time
urllib3.disable_warnings() #for now
import requests #https://requests.readthedocs.io/en/master/
from base64 import b64encode
import logging
from jinja2 import Template
import humanfriendly
from urllib.parse import urlparse
from urllib.parse import urlencode
class Nuta... | |
"""Basic tests for the CherryPy core: request handling."""
from cherrypy.test import test
test.prefer_parent_path()
import cherrypy
from cherrypy import _cptools, tools
from cherrypy.lib import http, static
import types
import os
localDir = os.path.dirname(__file__)
log_file = os.path.join(localDir, "test.log")
log_... | |
# coding: utf-8
"""
FeersumNLU API
This is the HTTP API for Feersum NLU. See https://github.com/praekelt/feersum-nlu-api-wrappers for examples of how to use the API. # noqa: E501
OpenAPI spec version: 2.0.54.dev2
Contact: <EMAIL>
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __futu... | |
),
"x10Lockout" : SettingsCommand( True, 1, "TIME", 16, 532, 16, 0, -1, "X10 Lockout Time (start HH:MM)", {} ),
"x10Phase" : SettingsCommand( True, 1, "BYTE", 8, 748, 8, 0, -1, "X10 3 Phase and frequency", { '0':"Disable", '1':"50 Hz", '2':"60 Hz"} ),
"panelSerialCode": SettingsCommand( False, 1, "BYTE", 8,0x437, 8... | |
True.
:type _preload_content: bool, optional
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:param _request_auth: set to override the auth_settings for an a single
request; this eff... | |
"""
<NAME>
Domicidal
Python Discord | Game Jam 2020
"""
# Standard Library
from math import atan2, degrees, radians, sin, cos, sqrt
import os
from pathlib import Path
import random
import time
# Third Party
import arcade
import PIL
from pyglet import gl
# Local
from game.utils import pathfinding
UPDATES_PER_FRAME = ... | |
#!/usr/bin/env python
"""Events framework with publisher, subscriber and repository."""
__author__ = '<NAME> <<EMAIL>>, <NAME>'
import functools
import sys
import threading
import traceback
from gevent import event as gevent_event
from pyon.core import bootstrap, MSG_HEADER_ACTOR
from pyon.core.bootstrap import CFG... | |
-sP -v {} -oN output.txt".format(self.lineEdit_site.text().lower()))
with open("output.txt","r+") as file:
info=file.read()
self.plainTextEdit_result.clear()
self.plainTextEdit_result.insertPlainText(info)
msg1 = QMessageBox()
msg1.setWindowTitle("Information")
msg1.setBaseSize(300,300)
msg1.setWindowIcon(QtGui... | |
<filename>pydef_core/formation_energy_corrections.py
import numpy as np
import pydef_core.figure as pf
import pydef_core.basic_functions as bf
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def potential_alignment_correction(host_cell, defect_cell, defects, spheres_radius, plotsphere=True, di... | |
self.play(path.move_to, ORIGIN)
self.play(path.set_height, 7.2, run_time=2)
self.wait(5)
# draw curves without displaying gears and rods
class OnlyCurve(Scene):
CONFIG = {
'camera_config': {
'background_color': WHITE,
},
'gears_config':{
'r1': 3,
'z': [36, 75, 36, 30],
'l': [0.95, 1.25, 0.9, 3.6],
'a': [P... | |
== (1 - self.Gas_M[1,'CH4',t]/self.Gas_M[0,'CH4',t])
#self.eq_c8 = Constraint(expr=self.X_gas ==
# (1 - self.Gas_M[1,'CH4']/self.Gas_M[0,'CH4']),
# doc = 'Conversion of gas fuel')
self.eq_c8 = Constraint(self.t, rule=rule_eq_c8,
doc = 'Conversion of gas fuel')
# ^ specifies X_gas from molar flow rates
def rul... | |
import logging
import json
from textwrap import dedent
from airflow.hooks.postgres_hook import PostgresHook
from util.loader import column_names as col
from util.loader import provider_details as prov
from psycopg2.errors import InvalidTextRepresentation
logger = logging.getLogger(__name__)
LOAD_TABLE_NAME_STUB = 'pr... | |
implementations inside
`resample_cube_spatial`.
Returns
-------
save_result :
Class instance implementing 'resample_cube_spatial' process.
"""
return ResampleCubeSpatial()
class ResampleCubeSpatial:
"""
Class implementing 'resample_cube_spatial' processe.
"""
@staticmethod
def exec_xar(data, target, m... | |
<gh_stars>100-1000
# -*- coding: utf-8 -*-
import codecs
import warnings
import re
from contextlib import contextmanager
from parso.normalizer import Normalizer, NormalizerConfig, Issue, Rule
from parso.python.tree import search_ancestor
from parso.parser import ParserSyntaxError
_BLOCK_STMTS = ('if_stmt', 'while_stm... | |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 7 13:24:29 2017
@author: ejreidelbach
"""
#------------------------------------------------------------------------------
# Obtain Rankings and Standings Information from the ESPN website
# ----------------------------------------------------------... | |
"""
Deep Belief Net for MINST dataset
DBN uses the code found at: https://github.com/mdenil/dropout with modifications
Modified by <NAME>
Additional Modifications by <NAME>, <NAME>, <NAME>
Date: July 20, 2016
"""
import numpy as np
import pickle
import os, sys
import time
import matplotlib.pyplot as plt
from collect... | |
#!/usr/bin/env python3
from api import api
from api import critical
import argparse
import logging
from logging.handlers import RotatingFileHandler
import numpy as np
import os
import re
import sys
import time
# create logger with 'rocket'
logger = logging.getLogger('rocket')
logger.setLevel(logging.DEBUG)
# create ... | |
## \author <NAME>
##
## This workflow corrects the succeptiblity artifacts of the input DWI data,
## and aligns that to corresponding t2 image space
## Important outputs: CorrectedDWI_in_T2Space, DWIBrainMask
"""
CorrectionWorkflow.py
============================
Description:
The purpose of this is to...
Author:
Us... | |
<gh_stars>0
'''
experiment (:mod:`calour.experiment`)
=====================================
.. currentmodule:: calour.experiment
Classes
^^^^^^^
.. autosummary::
:toctree: generated
Experiment
'''
# ----------------------------------------------------------------------------
# Copyright (c) 2016--, Calour develo... | |
<filename>lib/hypervisor/hv_kvm/__init__.py
#
#
# Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013, 2014 Google 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:
#
# 1. Redistributions of so... | |
aborted operation")
except AssertionError:
return printerror("Receiver rejected")
except timeout:
return printerror("Operation timed out")
except Exception:
return printerror("Error while sending headers to receiver")
print(f"[ {gethostname()}-{b64encode(self.token).decode()} ] "
f"is now sending file ({Progre... | |
odd-sized or integers larger than 8 bytes
# Don't naively go over 16 bytes, in order to prevent infinite loops.
result = 0
if hasattr(int, 'from_bytes'):
result = int.from_bytes(data, 'big')
else:
for byte in data:
result = (result << 8) | unpack('>B', byte)[0]
else:
raise InvalidPlistException("Encountered in... | |
else:
cred = credential.Credential(
g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey], g_param[OptionsDefine.Token]
)
http_profile = HttpProfile(
reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
reqMethod="POST",
endpoint=g_param[OptionsDefine.Endp... | |
<filename>bin/pre_scripts/snapshot_v.0.2.py<gh_stars>1-10
import os
import numpy as np
from subprocess import call
from collections import Counter
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
################################################################################################
###... | |
1.0],
'PAN': [0.12267005290619887,
0.1566068190578219,
0.16545763116614304,
0.1670303557942864,
0.16724181608188166,
0.2612863303461708,
0.31254617932251366,
0.32651601125600277,
0.3290541407816412,
0.45883812725218426,
0.5295781124397512,
0.5488568603054327,
0.6831859326279057,
0.7564032597016747,
0.849... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Notes:
InlineKeyboardButton:
callback_data:
has a common format of ".method_name param1 param2 ...".
currently used methods are:
- .vote <poll_id> <answer_id>
vote for an answer <answer_id> in poll <poll_id>.
- .update <poll_id>
update poll view in private chat... | |
default: if value is None, set to this
out_type: cast return as this type
Returns:
Formatted value of type out_type
"""
if value is None:
value = default
if isinstance(value, SpecialTagDirective):
result = value.get_value(self)
return types.cast_to_type(result, out_type)
if isinstance(value, str):
result ... | |
# Copyright <NAME> <<EMAIL>>. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | |
"Venom Gyre",
"Shrapnel Ballista",
"Awakened Arrow Nova Support",
"Wintertide Brand",
"Awakened Vicious Projectiles Support",
"Frost Shield",
"Crackling Lance",
"Anomalous Essence Drain",
"Divergent Lightning Warp",
"Venom Gyre",
"Onslaught Support",
"Spell Totem Support",
"Infernal Cry",
"Trap Support",
... | |
of a Static Flat Plate system
from dii and gii. If any is missing then is calculated from ghi, dhi and dhi
using corresponding pvlib function.
Internal `aoi_limit` parameter from `module_parameters` sets the limit
of tracking of the Static CPV system and therefore when the dii irradiance
is added to the poa_diff... | |
msgBox.setIcon(QtWidgets.QMessageBox.Information)
msgBox.setText('Looks like there are no hardware interfaces configured. Plese do so using the'
' preferences menu.')
connectButton = msgBox.addButton(self.tr('Take me to preferences'), QtWidgets.QMessageBox.ActionRole)
msgBox.setStandardButtons(QtWidgets.QMessageBox... | |
<reponame>XSEDE/XSEDE_Information_Warehouse
from django.urls import reverse, get_script_prefix
from django.utils.encoding import uri_to_iri
from django.utils import timezone
from rest_framework import serializers
from rest_framework.relations import PrimaryKeyRelatedField
from glue2_db.models import ComputingManager, C... | |
+ js['status'])
else:
col_list.append(row[i])
else:
col_list.append(row[i])
answer = dict(zip(keys, col_list))
items.append(answer)
table = TableCls(items, html_attrs = {'width':'100%','border-spacing':0})
folder_options = ""
folder_options += '<option value="switch to">switch to</option>'
folder_options += '... | |
<reponame>xyabc/laygo_obsolete
#!/usr/bin/python
########################################################################################################################
#
# Copyright (c) 2014, Regents of the University of California
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or ... | |
<filename>HSTB/kluster/gui/backends/_qgis.py
import os, sys
import numpy as np
from typing import Union
from pyproj import CRS
from osgeo import gdal
from HSTB.kluster.gui.backends._qt import QtGui, QtCore, QtWidgets, Signal, qgis_enabled, found_path
if not qgis_enabled:
raise EnvironmentError('Unable to find qgis di... | |
#!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
Implementation of the OSGi LogService, based on Python standard logging
:author: <NAME>
:copyright: Copyright 2020, <NAME>
:license: Apache License 2.0
:version: 1.0.1
..
Copyright 2020 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");... | |
= cms.untracked.double(0.0)
)
VerificationCommonParameters = cms.PSet(
MCTruthCollection = cms.InputTag("generatorSmeared"),
verboseDBE = cms.untracked.bool(False)
)
apd_sim_parameters = cms.PSet(
apdAddToBarrel = cms.bool(False),
apdDigiTag = cms.string('APD'),
apdDoPEStats = cms.bool(True),
apdNonlParms = cms... | |
`control_zone_air_node_name` or None if not set
"""
return self["Control Zone Air Node Name"]
@control_zone_air_node_name.setter
def control_zone_air_node_name(self, value=None):
"""Corresponds to IDD field `Control Zone Air Node Name`"""
self["Control Zone Air Node Name"] = value
class SetpointManagerMixed... | |
<reponame>gao-lab/Cell_BLAST
r"""
Latent space / encoder modules for DIRECTi
"""
import typing
import abc
import numpy as np
import sklearn.metrics
import tensorflow as tf
from . import module, nn, utils
class Latent(module.Module):
r"""
Abstract base class for latent variable modules.
"""
def __init__(
self... | |
'*' vsphere.ntp_configure my.vcenter.location root bad-password '[192.168.3.11, 172.16.17.32]' \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
if not isinstance(ntp_serv... | |
from moviepy.editor import VideoFileClip
from camera_calibration import camera_calibration
import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from pipeline import pipeline
ret, mtx, dist, rvecs, tvecs = camera_calibration()
# straight_lines1.jpg
src = np.float32([[209, 719... | |
#!/usr/bin/env python3
from collections import defaultdict
import numpy as np
from pgmpy.base import UndirectedGraph
from pgmpy.factors import factor_product
class ClusterGraph(UndirectedGraph):
r"""
Base class for representing Cluster Graph.
Cluster graph is an undirected graph which is associated with a subs... | |
"""
NOLIMIT = -1
#
# Groups
#
groups_df = self.client.iam.groups.list(all=True).to_pandas()
available_group_columns = [
column
for column in groups_df.columns
if column in ["name", "id", "sourceId", "capabilities"]
] # fmt: skip
if groups_only:
#
# early exit
#
self.deployed = {"groups": groups_df[avai... | |
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize(models.OdataError, response)
raise Ht... | |
"--backupOnRestartDir", action="store", type=str, dest="backup_on_restart_dir",
metavar="DIRECTORY", help=
"Every time a mongod restarts on existing data files, the data files will be backed up underneath the input directory."
)
parser.add_argument(
"--replayFile", action="store", type=str, dest="replay_file", me... | |
"border: 2px white;"
"border-radius: 5px;"
"padding: 0 8px;"
"font-size: 12px;}"
"QLineEdit:focus { "
"background-color:rgb(0 0, 0,0);}"
);
self.updatedvaluebox.move(395, 345)
self.updatedvaluebox.resize(150, 20)
self.updatedvaluebox.setMaxLength(15)
self.updatedvaluebox.setValidator(QIntValidator())
self.up... | |
<filename>cc/translator.py
from cc.ast import *
from cc.parser import Parser
from .assembler import *
class Translator:
"""
Will translate the AST into DCPU16 code
We use the ABI asm specified here:
https://github.com/0x10cStandardsCommittee/0x10c-Standards/blob/master/ABI/ABI%20draft%202.txt
"""
... | |
<reponame>zlish12/aws-inventory
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import argparse
import sys
import os
import logging
import boto3
import xlsxwriter
import datetime
from aws_exporter import __version__
from pprint import pprint
from prettytable import PrettyTable
... | |
<filename>tools/fuchsia/comparative_tester/generate_perf_report.py
#!/usr/bin/env python3
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""generate_perf_report.py is to be used after comparative_tester.py... | |
module calculate a hash value.
You may prefer, for example, to keep all of a given user's
objects on the same memcache server, so you could use the
user's unique id as the hash value.
@return: Nonzero on success.
@rtype: int
@param time: Tells memcached the time which this value should
expire, either as a delt... | |
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_website_by_id(self, id, body, **kwa... | |
if key not in self._fields and key[0] != '_']
if len(unexpected_args) > 0:
raise ValueError(
'Received unexpected construction argument {} for attribute '
'collection {}'.format(unexpected_args, self._fields))
for attribute in self._fields:
if attribute in kwargs:
try:
setattr(self, attribute, kwargs.get(attri... | |
import os
from pathlib import Path
from typing import Tuple
import boto3
from botocore.client import Config
import gzip
import re
from uuid import uuid4
import json
import query_string
import smart_open.s3
import shutil
import tempfile
import io
from urllib.parse import urlencode
import logging
from .__util_versioned... | |
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import next
from builtins import range
from builtins import object
import os
import re
import sys
import json
import time
import socket
import getpass
import configparser
i... | |
'Id': 'ef978820f195dede62e206bbd41568463ab2b79260bc63835a72154fe7e196a2',
'Size': 0,
},
]
assert utils.check_docker_image('test_service', 'tag2') is False
@mock.patch('paasta_tools.utils.build_docker_image_name', autospec=True)
def test_check_docker_image_true(mock_build_docker_image_name):
fake_app = 'fake_app'... | |
<reponame>miketrumpis/ecogdata<gh_stars>0
import os
import pytest
import numpy as np
from ecogdata.datasource.array_abstractions import HDF5Buffer
from ecogdata.datasource.memmap import MappedSource, MemoryBlowOutError
from ecogdata.datasource.basic import PlainArraySource
from .test_array_abstractions import _create_... | |
<gh_stars>0
# Copyright (c) 2020 Microsoft Corporation. Licensed under the MIT license.
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import math
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss, MSELoss
from tr... | |
Obtain Device ID
print("Attempting to obtain the UCS FI Device Connector Device "
"ID...")
get_ucs_fi_device_connector_device_id = _request_ucs_fi_device_connector_device_id(
ucs_fi_device_console_ip,
ucs_fi_device_console_login
)
if get_ucs_fi_device_connector_device_id.status_code == 200:
ucs_fi_devi... | |
'cmap': 'Blues', 'norm': "log",
'fancyticks': True,
'minorticks': True,
'title': {},
'sharey': False,
'sharex': False, # removes angular citkscitks
'fontsize': 14,
'labelsize': 14
}
#
if plot_x_i == 2:
dunb_dic_xy['cbar'] = {'location': 'bottom -.05 .00', 'label': r'$D_{\rm{unb}}$ [GEO]', # 'fmt': '%.1e',
'... | |
#!/usr/bin/env python
# vi: set ft=python sts=4 ts=4 sw=4 et:
######################################################################
#
# See COPYING file distributed along with the psignifit package for
# the copyright and license terms
#
######################################################################
__docfor... | |
is both faster and more
optimal...
Note that if 'spectrum' and 'template' are of different lengths,
the longer one will be trimmed at the end to make the lengths match.
:REQUIREMENTS:
`emcee <http://TBD>`_
"""
#2012-04-25 20:53 IJMC: Created
# 2012-09-23 20:17 IJMC: Now spectrum & template can be different l... | |
<reponame>vivin/syma
#
# Python virtual remote control for Syma S107. This program sends data to the serial port
# when it receives an acknowledgement for more data from the arduino. The UI simulates
# (rather crudely) a throttle stick, and a yaw/pitch stick, along with a trim control.
#
# This script also includes a ... | |
# [rad / m]
max_turn_length = min(length,
min(200.0,
length if turning_rate == 0.0 else \
(120 * pi / 180.0) / fabs(turning_rate)))
turn_length = random.uniform(1, max_turn_length)
# print('seg: ', turning_rate, turn_length, max_turn_length)
segment_length = turn_length \
if turning_rate == 0 else \
min(turn... | |
(from)":"wind_deg"}, inplace=True)
df.rename(columns={"wind_speed (m/s)":"wind_speed"}, inplace=True)
df['time'] = pd.to_datetime(df['time'], format="%d/%m/%Y %H:%M")
#df['time'] = pd.to_datetime(df['time'], utc=True, format="%d/%m/%Y %H:%M")
#df.set_index(['time'], inplace=True)
for index, row in df.iterrows():... | |
= te.fit_transform(df[['a', 'b', 'c']], df['y'])
assert 'a' in dfo
assert 'b' in dfo
assert 'c' in dfo
assert 'y' not in dfo
assert dfo.shape[0] == 10
assert dfo.shape[1] == 3
assert dfo.loc[0, 'b'] == 1
assert dfo.loc[1, 'b'] == 1
assert dfo.loc[2, 'b'] == 5
assert dfo.loc[3, 'b'] == 5
assert dfo.loc[4, 'b'... | |
MixedContainer.TypeString:
outfile.write('<%s>%s</%s>' % (
self.name, self.value, self.name))
elif self.content_type == MixedContainer.TypeInteger or \
self.content_type == MixedContainer.TypeBoolean:
outfile.write('<%s>%d</%s>' % (
self.name, self.value, self.name))
elif self.content_type == MixedContainer.Type... | |
<gh_stars>0
# The original code requires pylcaio release v1.0, from Agez, found at:
# https://github.com/MaximeAgez/pylcaio
import pandas as pd
import numpy as np
import os, sys
import pickle
import logging
import pylcaio
fp_results = os.path.join(os.path.curdir, 'results')
fp_output = os.path.join(os.path.curdir, 'o... | |
available_packet_length):
query_chunk = stats_query_enc[i:i + available_packet_length]
chunk_packet = FeslPacket.build(
b'rank\xf0\x00\x00\x00',
b'size=' + encoded_query_size.encode('utf8') + b'\ndata=' + query_chunk,
tid
)
chunk_packets.append(chunk_packet)
return chunk_packets
@staticmethod
def is_valid_l... | |
enzyme
Returns:
:obj:`tuple`:
* :obj:`Compound`: or :obj:`Enzyme`: compound or enzyme
* :obj:`dict`: additional properties of the compound/enzyme
* `is_wildtype` (:obj:`bool`): indicates if the enzyme is wildtype or mutant
* `variant` (:obj:`str`): description of the variant of the eznyme
* `modifier_type` (:... | |
<reponame>dngfx/MagicBot<filename>modules/coins.py
# --depends-on commands
# --depends-on permissions
import datetime, decimal, functools, math, random, re, time
from src import ModuleManager, utils
SIDES = {"heads": 0, "tails": 1}
DEFAULT_REDEEM_DELAY = 150 # 300 seconds, 2.5 minutes
DEFAULT_REDEEM_AMOUNT = 10000
D... | |
Constraint(expr= m.x6661 - 320*m.b7092 <= 0)
m.c5129 = Constraint(expr= m.x6662 - 320*m.b7093 <= 0)
m.c5130 = Constraint(expr= m.x6663 - 320*m.b7091 <= 0)
m.c5131 = Constraint(expr= m.x6664 - 320*m.b7092 <= 0)
m.c5132 = Constraint(expr= m.x6665 - 320*m.b7093 <= 0)
m.c5133 = Constraint(expr= m.x6634 - 330*m.b7070 <... | |
+ hex(self.us_ok) + ', bat_vol_x100 = ' + '{:=4}'.format(int(self.bat_vol_x100)))
print('ps2_button = ' + hex(self.ps2_button) + ', ' + '{:=3}'.format(int(self.ps2_analogRX)) + ', ' + '{:=3}'.format(int(self.ps2_analogRY)) + ', ' + '{:=3}'.format(int(self.ps2_analogLX)) + ', ' + '{:=3}'.format(int(self.ps2_analogLY)))... | |
'', f'get_input_name {name=}'
return f'{module}__{inputtype}{shortname}'
else:
return f'{inputtype}{name}'
def gql_to_edb_name(self, name: str) -> str:
'''Convert the GraphQL field name into an EdgeDB type/view name.'''
if '__' in name:
return name.replace('__', '::', 1)
else:
return name
def _get_descripti... | |
metadata={
"type": "Element",
"namespace": "",
},
)
velocity_sensing: Optional["Sensor.Gps.VelocitySensing"] = field(
default=None,
metadata={
"type": "Element",
"namespace": "",
},
)
@dataclass
class PositionSensing:
"""
Parameters related to GPS position measurement.
Parameters
----------
horizont... | |
not None
assert probability[0].count[0].get("data")[0].get("data")[0].get("bin") is not None
assert probability[0].count[0].get("data")[0].get("data")[0].get("count") is not None
assert probability[0].count[0].get("data")[0].get("data")[0].get("count").get("low") is not None
assert probability[0].count[0].get("data... | |
loop quantum: 100
Backup inbound read job time quantum: 1000, Backup outbound read job time quantum: 1000
Backup inbound read job loop quantum: 100, Backup outbound read job loop quantum: 100
Label allocation:
Current number of LDP labels allocated: 0
Total number of LDP labels allocated: 0
Total number of LDP la... | |
frame_size_score = -1 * abs(self.frame - bin_ctx.frame) * FUNC_FRAME_SCORE
# check for a probable match
if abs(frame_size_score) <= FRAME_SIZE_THRESHOLD * FUNC_FRAME_SCORE:
frame_size_score += ARTIFACT_MATCH_SCORE
logger.debug("Frame size score: %f", frame_size_score)
score += frame_size_score
# 5. Match calls
c... | |
import csv
import marshmallow_dataclass as md
from io import StringIO
from datetime import datetime, timedelta
from functools import partial
from flask import make_response
from originexample import logger
from originexample.auth import User, UserQuery, requires_login
from originexample.db import inject_session, atomi... | |
f'{t} was unsilenced.'
""" Admin commands
# The commands below are relatively dangerous,
# and are generally for managing players.
"""
@command(Privileges.Admin, hidden=True)
async def ban(p: 'Player', c: Messageable, msg: Sequence[str]) -> str:
"""Ban a specified player's account, with a reason."""
if len(msg) < 2... | |
Finger Selection pattern stored in hsFingUnsel
try:
fieldSelectionMatch = FieldChoice.objects.filter(field__iexact='FingerSelection',
machine_value=self.hsFingUnsel)
except:
print('set_unselectedFingers failed for: ', self)
return
if not fieldSelectionMatch:
# no finger selection
return
# get the pattern, onl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.