input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<reponame>gottaegbert/penter
import tensorflow as tf
import tensorflow_datasets as tfds
import collections
import unicodedata
import os,sys
import numpy as np
def convert_to_unicode(text):
"""Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
if isinstance(text, str):
return text
elif... | |
<filename>cmg_ts2cf_loop.py
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <markdowncell>
# #Convert existing time series NetCDF files in 4D (T,Z,Y,X) "grid" format to CF-1.6 format
# <markdowncell>
# All the USGS time series data has traditionally been stored in PMEL EPIC-compliant NetCDF files. These files ... | |
1, 1, 1, 1, 1, ], # Always part of main galaxy
[ 0, 1, 0, 0, 0, ], # CGM -> main galaxy -> CGM
]).astype( bool )
# Run the function
actual = self.classifier.identify_is_in_main_gal()
npt.assert_allclose( expected, actual )
########################################################################
def test_iden... | |
#Classes Challenge 40: Epidemic Outbreak GUI App
import math
import random
import tkinter
class Simulation():
"""A class to control a simulation and facilitate the spread of a disease."""
def __init__(self):
"""Initialize attributes"""
self.day_number = 1
#Get simulation initial conditions from the user
#Pop... | |
'Colorado'},
{'city': 'Cranford', 'state': 'New Jersey'},
{'city': 'Cranston', 'state': 'Rhode Island'},
{'city': 'Crawford', 'state': 'New York'},
{'city': 'Crawfordsville', 'state': 'Indiana'},
{'city': 'Cresskill', 'state': 'New Jersey'},
{'city': 'Crest Hill', 'state': 'Illinois'},
{'city': 'Crestline', 'sta... | |
close_txn:
start = self.run_cbq_query(query="SELECT ADVISOR({'action': 'start', 'duration': '15m'})", server=self.master)
session = start['results'][0]['$1']['session']
# Run query in transaction
results = self.run_cbq_query(query="BEGIN WORK", server=self.master)
query_params = {'txid': results['results'][0]['txi... | |
<filename>tests/test_connection.py
'''
Unit tests for trio_websocket.
Many of these tests involve networking, i.e. real TCP sockets. To maximize
reliability, all networking tests should follow the following rules:
- Use localhost only. This is stored in the ``HOST`` global variable.
- Servers use dynamic ports: by pa... | |
If the data is in one-hot format, this is used to determine which channels to apply.
independent: whether to treat ``applied_labels`` as a union of foreground labels.
If ``True``, the connected component analysis will be performed on each foreground label independently
and return the intersection of the largest comp... | |
<reponame>qnano/photonpy<gh_stars>1-10
import numpy as np
import time
import tqdm
import os
from photonpy import Context, GaussianPSFMethods, Estimator, Dataset
import photonpy.cpp.spotdetect as spotdetect
from photonpy.cpp.calib import GainOffset_Calib
from photonpy.cpp.calib import GainOffsetImage_Calib
from photo... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# #
# RMG - Reaction Mechanism Generator #
# #
# Copyright (c) 2002-2019 Prof. <NAME> (<EMAIL>), #
# Prof. <NAME> (<EMAIL>) and the RMG Team (<EMAIL>) #
# #
# Permission is hereby granted, free... | |
# Copyright ClusterHQ Inc. See LICENSE file for details.
"""
Tests for the Volumes Plugin API provided by the plugin.
"""
import random
from uuid import uuid4
from bitmath import TiB, GiB, MiB, KiB, Byte
from twisted.web.http import OK, NOT_ALLOWED, NOT_FOUND
from twisted.internet.task import Clock, LoopingCall
fro... | |
1567 3.732446480362260781946102655672169E-944 1.866223240181130390973051327836085E-944
1568 9.331116200905651954865256639180425E-945 4.665558100452825977432628319590213E-945
1569 2.332779050226412988716314159795107E-945 1.166389525113206494358157079897553E-945
1570 5.831947625566032471790785399487765E-946 2.91597... | |
<gh_stars>1-10
import json
import logging
import ssl
import time
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from enum import Enum
from typing import Callable, Dict, Iterable, List, Optional, Tuple
from urllib.parse import urljoin
import requests
from dateutil import par... | |
"V77"
V77_0 = "V77.0"
V77_1 = "V77.1"
V77_2 = "V77.2"
V77_3 = "V77.3"
V77_4 = "V77.4"
V77_5 = "V77.5"
V77_6 = "V77.6"
V77_7 = "V77.7"
V77_9 = "V77.9"
V78 = "V78"
V78_0 = "V78.0"
V78_1 = "V78.1"
V78_2 = "V78.2"
V78_3 = "V78.3"
V78_4 = "V78.4"
V78_5 = "V78.5"
V78_6 = "V78.6"
V78_7 = "V78.7"
V78_9 = "V7... | |
<filename>src/strainge/kmertools.py
# Copyright (c) 2016-2019, Broad Institute, 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 retain the above copyri... | |
from datetime import timedelta
from functools import partial
import itertools
from parameterized import parameterized
import numpy as np
from numpy.testing import assert_array_equal, assert_almost_equal
import pandas as pd
from toolz import merge
from zipline.pipeline import SimplePipelineEngine, Pipeline, CustomFacto... | |
<reponame>carmineceraolo/isotools
import matplotlib.colors as plt_col
import matplotlib.patches as patches
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
import numpy as np
from math import log10
import logging
logger = logging.getLogger('isotools')
def _label_overlap(pos1, pos2, width, ... | |
_BBD300 = np.sum(Close[:-301:-1])/300-(np.std(Close[-301:-1])*2) # Lower BollingerBand
_DiffD300_C = (Close[-1]-_BBD300)/_BBD300
_DiffD300_H3 = (_SMA_H3-_BBD300)/_BBD300
_BBD377 = np.sum(Close[:-378:-1])/377-(np.std(Close[-378:-1])*2) # Lower BollingerBand
_DiffD377_H3 = (_SMA_H3-_BBD377)/_BBD377
_DiffD377_... | |
found",
228: "unable to process request",
229: "events out of sequence - image inconsistency",
230: "the specified policy does not exist in the configuration database",
231: "schedule windows overlap",
232: "a protocol error has occurred",
233: "premature eof encountered",
234: "communication interrupted",
235: "inadeq... | |
<reponame>roni-permana-saputra/HiDO-MPC-ResQbot
"""
HiDO-MPC Class ResQbot
author: <NAME>
2021
"""
from casadi import *
import numpy as np
import time
def cal_heading_line(target_pose):
# line define by ax + by + c = 0
# tan_theta = -(a/b)
tan_theta = np.tan(target_pose.yaw)
b = -1
a = tan_theta
c = -((a*targ... | |
should not happen, right ??? "
print aArchive
sys.exit(-1)
else:
mergeArchiveList += [aArchive]
print len(mergeArchiveList), mergeArchiveList[:3], mergeArchiveList[-3:]
print " "
# example list of file names ...
# [ 'BAIZE_p_TCGA_b138_SNP_N_GenomeWideSNP_6_A02_808774.hg19.seg.txt', 'BAIZE_p_TCGA_b138_SNP_N_Gen... | |
calculations. (G is automaticall converted to \\Gamma)
n (int): Number of points between each high symmetry points.
This is also only required for HSE calculations. This number should be
known by the user, as it was used to generate the KPOINTS file.
fontsize (float): Font size of the text in the figure.
save (bo... | |
<filename>yasql/apps/redisms/redisApi.py
# -*— coding: utf-8 -*-
# __author__ : pandonglin
import redis, time
REDIS_READ_CMDS = [ # 查redis询命令列表
"help",
"info",
"exists",
"keys",
"type",
"ttl",
"scan",
"get",
"mget",
"strlen",
"hexists",
"hget",
"hlen",
"hmget",
"hvals",
"hscan",
"lindex",
"llen",
... | |
IMAGE IOD': ['Image'],
'XRF IMAGE IOD': ['Image'],
'DIGITAL X-RAY IMAGE IOD': ['Image'],
'RT IMAGE IOD': ['Image'],
'CR IMAGE IOD': ['Image'],
'X-RAY ANGIOGRAPHIC IMAGE IOD': ['Image'],
},
# ReferencedDateTime
0x0040A13AL: {
'SPECTACLE PRESCIPTION REPORT IOD': ['Document'],
'KEY OBJECT SELECTION DOCUMENT IOD': [... | |
DFA.unpack(u""),
DFA.unpack(u""),
DFA.unpack(u""),
DFA.unpack(u""),
DFA.unpack(u""),
DFA.unpack(u""),
DFA.unpack(u""),
DFA.unpack(u""),
DFA.unpack(u""),
DFA.unpack(u""),
DFA.unpack(u""),
DFA.unpack(u""),
DFA.unpack(u""),
DFA.unpack(u""),
DFA.unpack(u""),
DFA.unpack(u""),
DFA.unpack(u""),
DFA.unpack(u""... | |
<filename>gtcheck/app.py
#!/usr/bin/env python3
import datetime
import imghdr
import json
import logging
import math
import os
import re
import shutil
import webbrowser
from collections import defaultdict
from configparser import NoSectionError
from hashlib import sha256, sha1
from logging import Formatter
from logging... | |
be called with an iterator of ALL tokens from the text,
with the tokens for matched terms having the ``matched`` attribute set
to True.
If this method returns False, the fragmenter's ``fragment_matches``
method will be called with a LIST of matching tokens.
"""
return True
def fragment_tokens(self, text, all_... | |
it, however, if there are
# points to be excluded, one has to be able to exclude them.
# We can only hope that the sequence is properly arranged
ydata = ydata[idx]
xdata = xdata[idx]
sigma = sigma[idx]
idx = numpy.isfinite(xdata)
filter_xdata = False
if False in idx:
# What to do?
try:
# Let's see if the fun... | |
],
),
(
[
[0.97931, 0.0219899, 0.201169],
[-0.0159226, 0.99937, -0.0317288],
[-0.201739, 0.0278692, 0.979043],
],
[
[-0.980952, 0.00507266, -0.19419],
[0.00310821, 0.999941, 0.010419],
[0.194231, 0.00961706, -0.98091],
],
),
(
[
[0.999616, 0.00550326, -0.0271537],
[-0.0048286, 0.99968, 0.0248495],
[0.... | |
get all the nodes
nodes = local_tree.findall('.//*')
for node in nodes:
# skip non-leaf nodes
if len(node) == 0 and node.get('admix') != '1':
graph += "label\t{node}\t{node}\n".format(node=node.tag)
# build the list of edges
graph += self.export_qpgraph_node(local_tree)
return graph
def export_qpgraph_node... | |
if self.cachedir and what.startswith('BODY[') and what[5] in '123456789T]':
try:
open(os.path.join(self.cachedir,'%d_body_%s' % (uid,what[5:-1].replace('.','_')))).read()
except OSError:
return None
elif self.cachedir and what.startswith('BINARY[') and what[5] in '123456789T]':
try:
return open(os.path.join(self... | |
from adsputils import setup_logging, get_date, load_config
from myadsp import tasks, utils
from myadsp.models import KeyValue
import os
import time
import argparse
import logging
import warnings
import datetime
import gzip
import random
import json
try:
from urllib.parse import quote_plus
except ImportError:
from ur... | |
stimdur * 1000.0 # stim dur in ms
else:
sys.exit('not recognizable AEP software version...')
else:
fs = 20000.0
stimdur = 0.150
stimdur_ms = stimdur * 1000.0
si = file.si / 1000.0
isi = stimdur + si
stimPolarity = 2
# -------------- initialize parameters -------------------------------
# nrep = file.... | |
<gh_stars>1-10
#!/usr/local/python/bin/python
# gb2tab - comprehensive GenBank format parser/extractor
#
# Copyright (C) 2004 - 2008 <NAME>, <EMAIL>
#
# gb2tab is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; ... | |
<gh_stars>1-10
import numpy as np
import scipy
import numpy.matlib
def norm(X, V, T):
"""Normalizes the X, Y (X + V) matrix to have zero means and unit covariance.
We use the mean of X, Y's center and scale parameters to normalize T.
Arguments
---------
X: 'np.ndarray'
Current state. This corresponds to, for e... | |
Anything),
BinaryExpression(Group, Keyword('deletegroupwhenempty'), Boolean, Nothing),
BinaryExpression(Array, Keyword('deleterange'), Array, Nothing),
BinaryExpression(TeamMember, Keyword('deleteresources'), Array, Nothing),
BinaryExpression(Object, Keyword('deletevehiclecrew'), Object, Nothing),
BinaryExpression... | |
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.study_get_study_job_deprecated_with_http_info(tenant_id, user_id, study_id, job_id, **kwargs) # noqa: E501
def study_get_study_job_deprecated_with_http_info(self, tenant_id, user_id, study_i... | |
from qiskit import Aer, IBMQ, QuantumRegister, ClassicalRegister, QuantumCircuit, execute
import getpass, random, numpy, math
def title_screen ():
print("\n\n\n\n\n\n\n\n")
print(" ██████╗ ██╗ ██╗ █████╗ ███╗ ██╗████████╗██╗ ██╗███╗ ███╗ ")
print(" ██╔═══██╗██║ ██║██╔══██╗████╗ ██║╚══██╔══╝██║ ██║████╗ ████║ ")
p... | |
= None
self.ConcatCompleteEvent = None
self.SnapshotByTimeOffsetCompleteEvent = None
self.WechatPublishCompleteEvent = None
self.WechatMiniProgramPublishCompleteEvent = None
def _deserialize(self, params):
self.EventHandle = params.get("EventHandle")
self.EventType = params.get("EventType")
if params.get("Fil... | |
<filename>ch/meeting_tools.py<gh_stars>0
"""
这个文件应该放在全局可以import的位置供xl.py调用
比如说现在我的D:/anaconda/Lib
(xl.py按照要求放在了C:/Users/c2534/.qqbot-tmp/plugins)
有时候(脚本运行后修改这个文件)这个文件会不起作用,手动重启qqbot用命令 qq fresh-restart扫码
"""
import datetime
from openpyxl import load_workbook, Workbook
import os
import re
# todo 规范一下好
def botreply(b... | |
<reponame>Satcomx00-x00/circo----Cisco
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
circo.py source code
"""
from __future__ import print_function
import sys
import re
import argparse
import time
import threading
import collections
import socket
import ConfigParser
import requests
import pyaes
import pyscrypt
from... | |
focus on current menu group view
global CURR_GROUP_VIEW
global CURR_GROUP
global CURR_ENTITIE
global CURR_ENTITIE_ENTERED
global CURR_ENTITIE_POSITION
CURR_GROUP = None
CURR_ENTITIE = None
CURR_ENTITIE_ENTERED = False
CURR_ENTITIE_POSITION = None
CURR_GROUP_VIEW = get_curr_group_view()
def set_next_group_vi... | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cntk as C
import numpy as np
from .common import floatx, epsilon, image_dim_ordering, image_data_format
from collections import defaultdict
from contextlib import contextmanager
import warnings
C.set_g... | |
without reading/decoding response data.
Default is True.
_request_timeout (float/tuple): 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.
Default is None.
_check_input_type (bool): specifies if type checking
... | |
[107.5673473,-6.8934426],
[107.567197,-6.8937036],
[107.5674331,-6.8938474],
[107.567197,-6.8937036],
[107.5670468,-6.8939539],
[107.567197,-6.8937036],
[107.5673473,-6.8934426],
[107.5673918,-6.8934267],
[107.5675618,-6.8934853],
[107.5677549,-6.8935971],
[107.5677818,-6.893677],
[107.5676852,-6.8938634],
... | |
"""Logic to handle custom_cards."""
import json
import os
from typing import IO, Any
import requests
from requests import RequestException
import yaml
from pyupdate.ha_custom import common
from pyupdate.log import Logger
class Loader(yaml.SafeLoader):
"""YAML Loader with `!include` constructor."""
def __init__(se... | |
+ m.b405 <= 0)
m.c367 = Constraint(expr= - m.b58 + m.b406 <= 0)
m.c368 = Constraint(expr= - m.b58 + m.b407 <= 0)
m.c369 = Constraint(expr= - m.b58 + m.b408 <= 0)
m.c370 = Constraint(expr= - m.b58 + m.b409 <= 0)
m.c371 = Constraint(expr= - m.b58 + m.b410 <= 0)
m.c372 = Constraint(expr= - m.b58 + m.b411 <= 0)
m.c3... | |
import codecs
import os
import os.path
import string
import random
from random import shuffle
import csv
import time
import hashlib
import struct
import binascii
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
DefaultSize = "mode con: cols=100 lines=20"
os.system(DefaultSize)
pre = "C:\Pr... | |
from __future__ import division
import torch
import math
import argparse
import time
from torch.autograd import Variable
from PIL import ImageDraw
def detect_arg_parse():
"""
Parse arguments to the detect module.
:return: parser.parse_args()
"""
parser = argparse.ArgumentParser(description='YOLO v3 Detection M... | |
<gh_stars>10-100
""" Storage class for sets of pandas object. Similar to a panel,
but does inherently store 3d data. Data can be converted to 3d through
methods, but otherwise is just a container."""
from collections import OrderedDict, Iterable
from copy import deepcopy
import logging
from skspec.logger import lo... | |
<reponame>cancerregulome/gidget
# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
import miscTCGA
import tsvIO
import random
import sys
# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
NA_VALUE = -999999
# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#... | |
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 l... | |
lambda self : None;
def GetColumn(*args, **kwargs):
"""GetColumn(self) -> int"""
return _propgrid.PropertyGridEvent_GetColumn(*args, **kwargs)
def GetMainParent(*args, **kwargs):
"""GetMainParent(self) -> PGProperty"""
return _propgrid.PropertyGridEvent_GetMainParent(*args, **kwargs)
def GetProperty(*args, **k... | |
enabled')
def test_transpose_and_arithmetic_op_broadcast_gpu(self):
self._transpose_and_arithmetic_op_broadcast_helper(gpu_dev)
def test_batchnorm_training_dnnl(self):
dev = cpu_dev
def _np_bn_training(x, scale, bias, rm, rv, momentum=0.1, e=1e-5):
channel = x.shape[1]
np.testing.assert_array_almost_equal(scal... | |
<reponame>wang-h-w/traffic-sign-detection<filename>EnvDetection/TSD_env_test.py<gh_stars>1-10
"""
Modified by: <NAME>, <NAME> and <NAME>
"""
import numpy as np
import cv2
import os
from core.model import P_Net, R_Net, O_Net
from core.detector import Detector
from core.fcn_detector import FcnDetector
from core.MtcnnDet... | |
"""
Affine plane curves over a general ring
AUTHORS:
- <NAME> (2005-11-13)
- <NAME> (2005-11-13)
- <NAME> (2006-01)
"""
#*****************************************************************************
# Copyright (C) 2005 <NAME> <<EMAIL>>
#
# Distributed under the terms of the GNU General Public License (GPL)
#
# Th... | |
* 3 + 5
# bit = np.cumsum(test['y'][::-1])
# test['z'] = bit
# test['w'] = bit / test.a
# test
#
# df[f'exag_{line}'] = exleaUC + exixgtaUC * self.density_df.loss + mass
# df[f'exag1_{line}'] = exleaUC1 + exixgtaUC * self.density_df.loss + mass
# is this ever used?
# df[f'exleag_{line}'] = exleaUC / df.gF
# d... | |
0.04 & 0.04 & 0.50 & 0.01 & 0.00
# [Cars3d] random & 17568 & 0.56 & 0.13 & 0.15 & 0.54 & 0.10 & 0.04
#
# [Shapes3d] Factor Name & Factor Size & rsame_ratio (mse) & rank_corr (mse) & linear_corr (mse) & rsame_ratio (aug) & rank_corr (aug) & linear_corr (aug)
# [Shapes3d] floor_hue & 10 & 0.82 & 0.76 & 0.62 & 0.82 & 0.74... | |
for the generated footsteps
footsteps_path: str
# Footsteps scaling factor
footstep_scaling: float
# Time scaling factor
time_scaling: int
# Footsteps list
contact_phase_list: blf.contacts.ContactPhaseList = None
@staticmethod
def build(footsteps_path: str, footstep_scaling: float, time_scaling: int) -> "F... | |
Y.shape[1] == %d" % (
X.shape[1], Y.shape[1]))
return X, Y
def manhattan_distances(X, Y=None, sum_over_features=True,
size_threshold=None):
""" Compute the L1 distances between the vectors in X and Y.
With sum_over_features equal to False it returns the componentwise
distances.
Read more in the :ref:`User G... | |
'''
Loss building blocks.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import math
from absl import flags
import numpy as np
import pdb
import itertools
from ..utils import suncg_parse
# from ..utils import quatUtils
# -------------- flags -------------#
# ... | |
<reponame>HansGR/WorldsCollide
from functools import total_ordering
@total_ordering
class DataPointer:
def __init__(self, address, data_address):
self.address = address
self.data_address = data_address
def __eq__(self, other):
return ((self.data_address, self.address) == (other.data_address, other.address))
de... | |
+= self.size_scale * dy
if self.scaleImage < 0:
self.scaleImage = 0.0
self.resize_image()
self.lastPos = event.pos()
def resize_image(self):
new_pix = vpPixmap.scaled(viewport.size()*self.scaleImage,
aspectMode=Qt.KeepAspectRatio)
self.resize(new_pix.size())
c = viewport.rect().center()
self.se... | |
],
color = [ 'Identity(1,2)' ],
lorentz = [ L.SSSS1 ],
couplings = {(0,0):C.GC_411})
V_519 = Vertex(name = 'V_519',
particles = [ P.sd3__tilde__, P.sd3, P.sl3__plus__, P.sl3__minus__ ],
color = [ 'Identity(1,2)' ],
lorentz = [ L.SSSS1 ],
couplings = {(0,0):C.GC_442})
V_520 = Vertex(name = 'V_520',
particles =... | |
* forward_vec - half_y_len * sideward_vec]
return corners
def get_pedestrian_bounding_box_corners(actor):
bbox = actor.bounding_box
loc = carla.Vector2D(bbox.location.x, bbox.location.y) + get_position(actor)
forward_vec = get_forward_direction(actor).make_unit_vector()
sideward_vec = forward_vec.rotate(np.deg2ra... | |
Heroism':1,
'Potion of Antidote':1,
'Infusion of Claws':1,
'Infusion of Vitality':1,
'Rune of Shielding':1,
'Rune of Armor':1,
'Hand Grenade':10,
'Smoke Grenade':2,
},
}
#----
# Союзники (армия) (<NAME>):
metadict_chars['Warrior 2 lvl (абордажник-ветеран)'] = {
'base_unit':'Warrior 2 lvl (grenadier line-inf... | |
failed. Bot does not have sufficient permissions to remove {} from {}'.format(
rem_role.mention,
base_role.mention))
except discord.HTTPException:
await self.bot.say('Remove failed, role could not be removed for some reason ¯\_(ツ)_/¯')
@roles.command(pass_context=True)
async def replace(ctx, base_role: discord.R... | |
try:
import logging
except ImportError:
class logging:
def debug(self, *args, **kwargs):
pass
def __assert_data_tuple(data, num):
"""Internal helper to ensure data is a tuple of given `num` length."""
if not isinstance(data, tuple):
data = (data,)
if not len(data) == num:
raise AssertionError()
return data
... | |
"""Easy and efficient time evolutions.
Contains an evolution class, Evolution to easily and efficiently manage time
evolution of quantum states according to the Schrodinger equation,
and related functions.
"""
import functools
import numpy as np
from scipy.integrate import complex_ode
from .core import (qarray, iso... | |
<gh_stars>1-10
"""
**Module - View Controller for Affiliates API**
*Class Definitions for managing access to the database and validation of user input*
"""
__developer__ = "mobius-crypt"
__email__ = "<EMAIL>"
__twitter__ = "@blueitserver"
__github_repo__ = "https://github.com/freelancing-solutions/memberships-and-af... | |
<gh_stars>1-10
# -*- coding: utf-8 -*-
"Tests for keyboard support."
# std imports
import functools
import tempfile
import signal
import curses
#import time
import math
import tty # NOQA
import pty
import sys
import os
# local
from .accessories import (
init_subproc_coverage,
read_until_eof,
read_until_semaphore,
... | |
= embed)
@commands.command(aliases=["pm"], description="Use your laptop to post some reddit memes")
@commands.check(custom_cooldown(1,30,1,12,BucketType.user))
async def postmeme(self, ctx):
await self.check_acc(ctx.author)
data = await self.bc.economy.find(ctx.author.id)
choices = ["d", "a", "n", "k"]
res = a... | |
query contains stopwords between its start and end
in the query. Stopwords are never match by construction.
"""
# The query side of the match may not be contiguous and may contain
# unmatched stopword tokens.
query = self.query
qspan = self.qspan
# note: to avoid breaking many tests we check query presence
if ... | |
from collections import OrderedDict
import itertools
from operator import getitem
from crispy_forms.bootstrap import FieldWithButtons, StrictButton, Field, Div
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied, ObjectDoesN... | |
"deviceModel":None,
"createDate":"2019-04-08 15:30:09",
"remark":"",
"isOnline":False,
"deviceType":1,
"bindAreaIds":[
23120
],
"topId":22953,
"mac":"A1:A1:A5:A1:B1:86"
},
{
"deviceId":13348,
"sn":None,
"deviceName":"AP设备",
"softwareVersion":None,
"deviceModel":None,
"createDate":"2019-04-08 15:30:09",... | |
# coding: utf-8
"""
Jamf Pro API
## Overview This is a sample Jamf Pro server which allows for usage without any authentication. The Jamf Pro environment which supports the Try it Out functionality does not run the current beta version of Jamf Pro, thus any newly added endpoints will result in an error and should b... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import requests
from core.get_modules import load_all_modules
API_URL = 'http://127.0.0.1:5000'
class TestApi(unittest.TestCase):
def test_index(self):
"""
Test if the API is running
"""
response = requests.get(API_URL)
self.assertEqual(response.st... | |
"""
topology data for routers
based on: mockTopoData.js by tylevine on 7/7/14.
Used to create API response for to UI
updated 20150312 with more nodes (50 state capitals)
"""
topologyData = {
'nodes': [{
'name': 'sfc',
'latitude': 38.4815631942872,
'ipaddress': 'fc00:db20:35b:7399::5',
'site': 'sfc',
'long... | |
<gh_stars>10-100
#!/usr/bin/env python3
# coding=utf-8
# author: @netmanchris
# -*- coding: utf-8 -*-
"""
This module contains functions for working with the system configuration
capabilities of the HPE IMC NMS platform using the RESTful API
"""
# This section imports required libraries
import json
import requests
... | |
* uk_12
+ 94864 * uk_120
+ 416724 * uk_121
+ 735196 * uk_122
+ 142296 * uk_123
+ 1830609 * uk_124
+ 3229611 * uk_125
+ 625086 * uk_126
+ 5697769 * uk_127
+ 1102794 * uk_128
+ 213444 * uk_129
+ 1325884 * uk_13
+ 74088 * uk_130
+ 49392 * uk_131
+ 216972 * uk_132
+ 382788 * uk_133
+ 74088 * uk_134
+ 32928... | |
search only)
if pattern == '*':
files.append(os.path.join(dirName,'.'))
files.append(os.path.join(dirName,'..'))
if pattern != '':
for file in os.listdir(dirName):
if fnmatch.fnmatch(file.lower(),pattern.lower()):
entry = os.path.join(dirName, file)
if os.path.isdir(entry):
if searchAttributes & smb.ATTR_DIRE... | |
from api.api import common_api
from config import engine
from flask import jsonify , current_app
from sqlalchemy.sql import text
import requests
import time
from datetime import datetime
from api.fake_data import sl_mock_data
try:
from secrets_dict import SHELTERLUV_SECRET_TOKEN
except ImportError:
# Not running lo... | |
0:
print("ERROR: we have an empty cluster list for {}?".format(current_neuron_index))
continue
if current_best_K == 1:
# uniform distrubtion or a higher value of k needed!
print('Neuron {} has a K of 1, may require further investigation!'.format(current_neuron_index))
jitterer(x_data=cluster_list, colour_flag='cl... | |
<filename>spekpy/SpekPy.py
# For compatibility with Python2 #
from __future__ import print_function, division, absolute_import
##################################
from . import __version__
import spekpy.SpekConstants as Const
from spekpy.IO import find_file, path_file, read_spectrum_from_disk, \
get_script_path, is_fil... | |
# (c) Copyright 2015-2016 Hewlett Packard Enterprise Development LP
# (c) Copyright 2017 SUSE LLC
import logging
import inspect
import pykka
import copy
import time
import traceback
from bll.common import util
from bll.common.exception import InvalidBllRequestException, BllException
from bll.api.auth_token import Tok... | |
<gh_stars>0
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in ... | |
if bad_file is not None:
sss_info.load_bad_channels(bad_file)
if sss_info is not None:
sss_info = sss_info.info
# pca / erm / erm_pca
extra_raws = dict()
for key, which, erm in [
('raw_pca', 'pca', False),
('raw_erm', 'raw', 'only'),
('raw_erm_pca', 'pca', 'only')]:
these_fnames = get_raw_fnames(
p, subj, w... | |
ParamAttr as bias_attr. If the Initializer of the bias_attr
is not set, the bias is initialized zero. Default: None.
data_format(str, optional): Data format that specifies the layout of input.
It can be "NCHW" or "NHWC". Default: "NCHW".
Attribute:
**weight** (Parameter): the learnable weights of filters of this... | |
__all__ = (
'ActivityAssets',
'ActivityBase',
'ActivityParty',
'ActivitySecrets',
'ActivityTimestamps',
'ACTIVITY_TYPES',
)
from datetime import datetime
from ..utils import DISCORD_EPOCH_START
from ..color import Color
from . import activity_types as ACTIVITY_TYPES
DEFAULT_CUSTOM_ID = 'UNKNOWN'
CUSTOM_IDS =... | |
This simulates another app (e.g. QGIS) having a connection open, potentially
with some active reader/writer.
Note: we use a subprocess here instead of just using sqlite3 module from python
because pygeodiff and python's sqlite3 module have their own sqlite libraries,
and this does not work well when they are used ... | |
"""
BSD 3-Clause License
Copyright (c) 2020, Cyber Security Research Centre Limited
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 source code must retain the above copyright not... | |
Examples
--------
>>> gh = xr.DataArray(np.random.normal(size=(3,4,4)),
... coords=[('level', [400, 500, 600]), ('lat', np.arange(-90,90,45)),
... ('lon', np.arange(0,360,90))])
>>> doppyo.diagnostic.thermal_wind(gh, plevel_lower=400, plevel_upper=600)
<xarray.Dataset>
Dimensions: (lat: 4, lon: 4)
Coordinat... | |
from base_classes import *
class income_statement(financial_statement):
''' __init__ will create the necessary accounts for an income statement.
--------------------------------------------------------------------------
No data must be added initially, use function add_data for this '''
def __init__(self, data=Non... | |
<gh_stars>0
#!/usr/bin/env python3
# Copyright (c) 2018 NVIDIA Corporation. All rights reserved.
# This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
# https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode
from __future__ import print_function
#######... | |
= 10
histplot(flat_series, element="bars", fill=False, bins=n, ax=ax1)
histplot(flat_series, element="poly", fill=False, bins=n, ax=ax2)
bar_heights = np.array([b.get_height() for b in ax1.patches])
bar_widths = np.array([b.get_width() for b in ax1.patches])
bar_edges = np.array([b.get_x() for b in ax1.patches])
... | |
localctx = SQLGramaticaParser.ShowColumnsContext(self, self._ctx, self.state)
self.enterRule(localctx, 56, self.RULE_showColumns)
try:
self.enterOuterAlt(localctx, 1)
self.state = 401
self.match(SQLGramaticaParser.SHOW)
self.state = 402
self.match(SQLGramaticaParser.COLUMNS)
self.state = 403
self.match(SQLGram... | |
len(unified_event_list)
for process in process_list:
if process.pid > 9990: # fix up framebuffer ticks
process.tick = start_tick
print process.uid, process.pid, process.tgid, \
process.task_name, str(process.tick)
for thread in process.children:
if thread.pid > 9990:
thread.tick = start_tick
print "\t", threa... | |
<reponame>BlazesRus/Bforartists<gh_stars>1-10
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any l... | |
elif setup["name"] == "setup_wait_until_db_result_succeed":
# setup_cell = "${{setup_wait_until_db_result_succeed({0}||{1}||{2}||$DB_CONNECT)}}".format(setup["args"]["wait_time"], setup["args"]["sql"], setup["args"]["expect_value"])
# elif setup["name"] == "setup_server_upload_file":
if setup["name"] == "setup_serve... | |
<reponame>KotlinIsland/flake8-pyi<gh_stars>0
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import ast
import logging
import optparse
import re
import sys
from collections import Counter
from collections.abc import Iterable, Iterator, Sequence
from contextlib import contextmanager
from copy ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.