input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<reponame>JesusZerpa/pscript<gh_stars>1-10
"""
PScript standard functions.
Functions are declared as ... functions. Methods are written as methods
(using this), but declared as functions, and then "apply()-ed" to the
instance of interest. Declaring methods on Object is a bad idea (breaks
Bokeh, jquery).
"""
import r... | |
# Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... | |
atom explicit valence, atom implicit valence, aromaticity.
edge_featurizer : callable, rdkit.Chem.rdchem.Mol -> dict
Featurization for edges like bonds in a molecule, which can be used to update
edata for a DGLGraph. By default, we consider descriptors including bond type,
whether bond is conjugated and whether bon... | |
vrouters_list_ops[n]['href'])
ops_basic_data = []
host_name = vrouters_list_ops[n]['name']
ip_address = vrouters_ops_data.get(
'VrouterAgent').get('self_ip_list')[0]
version = json.loads(vrouters_ops_data.get('VrouterAgent').get('build_info')).get(
'build-info')[0].get('build-id')
version = version.split('-')
v... | |
import os
import unittest
from programy.utils.parsing.linenumxml import LineNumberingParser
import xml.etree.ElementTree as ET # pylint: disable=wrong-import-order
from programy.parser.aiml_parser import AIMLParser
from programy.dialog.sentence import Sentence
from programy.parser.pattern.nodes.oneormore import Pattern... | |
<reponame>SGrosse-Holz/tracklib<filename>tracklib/analysis/neda/models.py
"""
The inference models, and the interface they have to conform to.
"""
import abc
import functools
import numpy as np
import scipy.optimize
from tracklib import Trajectory
from tracklib.models import rouse
from .util import Loopingtrace
cla... | |
find_name_components(_compartment)[1:]
compartments_strata.reverse()
compartments_strata.append("")
# loop through each stratification of the parameter and adapt if the parameter is available
for stratum in compartments_strata:
if stratum in self.available_death_rates:
all_sub_parameters.append("universal_death_... | |
# -*- coding: utf-8 -*-
# Copyright (c) 2017 - for information on the respective copyright owner
# see the NOTICE file and/or the repository https://github.com/boschresearch/statestream
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.... | |
open(filename, 'wt') as file:
file.write(self.graphviz_string(**options))
### Spectrum
def spectrum(self, laplacian=False):
r"""
Return a list of the eigenvalues of the adjacency matrix.
INPUT:
- ``laplacian`` -- boolean (default: ``False``); if ``True``, use the
Laplacian matrix (see :meth:`kirchhoff_matri... | |
text, charset, errors="replace"):
""" convert text for mail to unicode"""
if text is None:
text = ""
if PY2:
if isinstance(text, str):
if charset is None:
text = unicode(text, "utf-8", errors)
else:
text = unicode(text, charset, errors)
else:
raise Exception("Unsupported mail text type %s" % type(text))
ret... | |
<reponame>howardpchen/pynetdicom<filename>pynetdicom/acse.py
"""
ACSE service provider
"""
import logging
from pynetdicom.pdu_primitives import (
A_ASSOCIATE, A_RELEASE, A_ABORT, A_P_ABORT,
AsynchronousOperationsWindowNegotiation,
SOPClassCommonExtendedNegotiation,
SOPClassExtendedNegotiation,
UserIdentityNegotia... | |
from ticktick.helpers.hex_color import check_hex_color, generate_hex_color
from ticktick.managers.check_logged_in import logged_in
class ProjectManager:
"""
Handles all interactions for projects.
"""
def __init__(self, client_class):
self._client = client_class
self.access_token = self._client.access_token
de... | |
# Copyright (c) 2021 <NAME>. All Rights Reserved.
"""Emmental parse_args."""
import argparse
from argparse import ArgumentParser, Namespace
from typing import Any, Dict, Optional
from emmental.utils.utils import (
nullable_float,
nullable_int,
nullable_string,
str2bool,
str2dict,
)
def parse_args(parser: Opti... | |
<reponame>IrisSorin/mailcat
#!/usr/bin/python3
import aiohttp
import asyncio
import argparse
import base64
import datetime
import json
import logging
import random
import smtplib
import string as s
import sys
import threading
import re
from time import sleep
from typing import Dict, List
import dns.resolver
from requ... | |
"Occult Claw+4",
902705: "Occult Claw+5",
902800: "Fire Claw",
902801: "Fire Claw+1",
902802: "Fire Claw+2",
902803: "Fire Claw+3",
902804: "Fire Claw+4",
902805: "Fire Claw+5",
902806: "Fire Claw+6",
902807: "Fire Claw+7",
902808: "Fire Claw+8",
902809: "Fire Claw+9",
902810: "Fire Claw+10",
... | |
4}, {"a": 5}, {"a": 6}]],
"expected": lambda: StructuredTensor.from_fields(
shape=[2, None], fields={
"a": ragged_factory_ops.constant([[1, 2, 3], [4, 5, 6]])})
},
{
# TypeSpec can be used to specify StructuredTensor shape.
"testcase_name": "MatrixOfDictWithTypeSpec",
"pyval": [[{"a": 1}, {"a": 2}, {"a": 3},],
... | |
<gh_stars>1-10
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# #
# The code is hosted on GitHub at https://github.com/aiidateam/aiida-core #
# For further information on... | |
Rx"])
self.result_table_set_precision(3)
for r in self.pkt_cnts:
self.result_table_add(r)
self.result_table_print()
elif stress is not None and self.pkt_cnts:
print("\n") # tables separation
hdr_row = ['direction', 'size', 'flows',
'Tx queues DUT / Tester', 'type',
'Tester Tx, b/s',
'DUT Rx, b/s',
'FW missi... | |
# -*- coding: utf-8 -*-
# farmeconomy.py module
# authors: <NAME> & <NAME>
# An OOP implementation
import numpy as np
from matplotlib import pyplot as plt
from scipy.optimize import minimize
from collections import namedtuple
class Economy(object):
""" Economy with an Equilibrium Farm Size Distribution
At present ... | |
from __future__ import (division, absolute_import, print_function, unicode_literals)
import os
import numpy as np
import gzip
import os.path
import nltk
import logging
from nltk import FreqDist
from .WordEmbeddings import wordNormalize
from .CoNLL import readCoNLL
import sys
if (sys.version_info > (3, 0)):
import pi... | |
below their values), and recalculate the mass of
# the by-percent fermentables.
if (len(self._fermfilter('r')) > 0
and len(self._fermfilter('p')) > 0):
iters = 30
if mext > 0.0001:
self._once(notice,
'finding the solution for fixed '
'percentages and masses\n')
for g in range(iters):
f... | |
<filename>predictit/contract.py
import datetime as dt
from collections import namedtuple
from decimal import Decimal
from .utils import concurrent_get
class Contract(object):
"""Interact with PredictIt contracts
This class handles contract-level transactions with PredictIt,
including trading and viewing order bo... | |
they are
specified by a function or dictionary mapping labels to colors; this
option is incompatible with ``edge_color`` and ``edge_colors``.
- ``edge_size`` -- float (default: ``0.02``)
- ``edge_size2`` -- float (default: ``0.0325``); used for
:class:`~sage.plot.plot3d.tachyon.Tachyon` sleeves
- ``pos3d`` -- ... | |
:type frames: array-like
:param t_bin: screen refresh rate
:type t_bin: float
:return: tuple of (stim_times, stim_frames)
"""
beg_extrap_val = -10001
end_extrap_val = -10000
idxs_up, idxs_dn = get_rf_ttl_pulses(ttl_signal)
X = np.sort(np.concatenate([idxs_up, idxs_dn]))
Xq = np.arange(frames.shape[0])
# mak... | |
0xFFD7CF,
"Shy Green": 0xE5E8D9,
"Shy Guy Red": 0xAA0055,
"Shy Mint": 0xE0E4DB,
"Shy Moment": 0xAAAAFF,
"Shy Pink": 0xDFD9DC,
"Shy Smile": 0xDCBBBE,
"Shy Violet": 0xD6C7D6,
"Shylock": 0x5AB9A4,
"Shyness": 0xF3F3D9,
"Siam": 0x686B50,
"Siam Gold": 0x896F40,
"Siamese Green": 0x9DAC79,
"Siamese Kitten": 0xEFE1... | |
<reponame>ajmal017/amp
"""
Basic functions processing financial data.
Import as:
import core.finance as fin
"""
import datetime
import logging
from typing import Any, Dict, List, Optional, Union, cast
import numpy as np
import pandas as pd
import statsmodels.api as sm
import core.signal_processing as csigna
import... | |
1] + 1.0
ex_ctr_x = ex_rois[:, 0] + 0.5 * ex_widths
ex_ctr_y = ex_rois[:, 1] + 0.5 * ex_heights
gt_widths = gt_rois[:, 2] - gt_rois[:, 0] + 1.0
gt_heights = gt_rois[:, 3] - gt_rois[:, 1] + 1.0
gt_ctr_x = gt_rois[:, 0] + 0.5 * gt_widths
gt_ctr_y = gt_rois[:, 1] + 0.5 * gt_heights
targets_dx = (gt_ctr_x - ex_ctr... | |
category))
delete_query = Template(
textwrap.dedent("""
DELETE EDGE BADGE_FOR "{{ badge_name }}" -> "{{ uri }}";
DELETE EDGE HAS_BADGE "{{ uri }}" -> "{{ badge_name }}";
"""))
self._execute_query(query=delete_query.render(badge_name=badge_name,
uri=id),
param_dict={})
@timer_with_counter
def get_badges(self... | |
= _Class("SAScreenActionList")
SAReminderSiriKitInteraction = _Class("SAReminderSiriKitInteraction")
SAHAActionRequest = _Class("SAHAActionRequest")
SAUILParsedExpression = _Class("SAUILParsedExpression")
SAUILParsedAttachmentExpression = _Class("SAUILParsedAttachmentExpression")
SASmsSms = _Class("SASmsSms")
SAAttachm... | |
list of dicts separated by face index
"""
csgrid = csgrid_GMAO(csres, offset=0)
csgrid_list = [None] * 6
for i in range(6):
lat = csgrid['lat'][i].flatten()
lon = csgrid['lon'][i].flatten()
lon, lat = scs_transform(
lon, lat, stretch_factor, target_lon, target_lat)
lat = lat.reshape((csres, csres))
lon = lon... | |
<filename>main.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'stardew_toolbox.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
"""
MIT... | |
# -*- coding: utf-8 -*-
"""
Released on April 29, 2019
@author: <NAME> <<EMAIL>>; <NAME> <<EMAIL>>
The code is part of BMSS software.
Copyright (c) 2019, National University of Singapore.
"""
#############################################################################
# The LogicGates System class
###############... | |
<reponame>papomail/NeonateMRS_UCLH_Python3
# -*- coding: utf-8 -*-
"""
Spec_Module
Version 1.4.2
Modified 21/02/2020
Python3 version of the script. Converted from: Version 1.3.1
Created on 11 Dic 2019 @author: <NAME>
...
Version 1.3.1
Modified 1/10/2015
Defines objects of class Spec_Module
Created on Thu Oct 0... | |
import socket, serial, os, time, pickle, math, json, glob, subprocess, ConfigParser
config = ConfigParser.ConfigParser()
config.read("ardustatrc.txt")
pycommand = str(config.get("values","pycommand"))
portconstant = int(config.get("values","portconstant"))
loggingpause = float(config.get("values","loggingpause... | |
no doc
def __init__(self, *args, **kwargs): # real signature unknown
pass
_fields = ()
class excepthandler(AST):
# no doc
def __init__(self, *args, **kwargs): # real signature unknown
pass
__weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""list of weak refere... | |
#This states the metadata for the plugin
bl_info = {
"name": "AssetGen",
"author": "Developed by <NAME> aka zero025 (<EMAIL>) and surpervised by <NAME> aka Linko (<EMAIL>)",
"version": (0, 1),
"blender": (2, 79),
"api": 39347,
"location": "3D View > Object Mode > Tools > AssetGen",
"description": "Game developme... | |
<filename>dipy/tracking/streamline.py<gh_stars>1-10
from copy import deepcopy
from warnings import warn
import types
from scipy.spatial.distance import cdist
import numpy as np
from nibabel.affines import apply_affine
from nibabel.streamlines import ArraySequence as Streamlines
from dipy.tracking.streamlinespeed impor... | |
<gh_stars>1-10
import tkinter
from tkinter import ttk
import cv2
from PIL import Image, ImageTk
import socket
import json
from vidgear.gears import NetGear
import threading
import os
import webbrowser
HOST = '10.0.0.8'
PORT = 6005
class Menubar(ttk.Frame):
def __init__(self, parent):
"""
Constructor:
Ini... | |
range(2):
brick_ = brick.Brick()
brick_.set_position([-1, i * 4 + 1, 5])
brick_.set_direction(0)
list_brick_.append(brick_)
for i in range(2):
for j in range(2):
brick_ = brick.Brick()
brick_.set_position([i * 2 + 2, j * 4 + 1, 5])
brick_.set_direction(0)
list_brick_.append(brick_)
for i in range(2):
br... | |
progress information. It passes a single positional argument
to the callable which is a dict of information about progress.
:type progressCallback: callable
:returns: the file that was created.
"""
if filename is None:
filename = filepath
filename = os.path.basename(filename)
filepath = os.path.abspath(filepath... | |
method is called asynchronously,
returns the request thread.
"""
all_params = ['cluster_firmware_upgrade_item']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create... | |
parent_id):
request = {'page': '1', 'pageSize': self.MAX_PAGE_SIZE, 'partialParameters': 'parent_id={}'.format(parent_id)}
result = requests.post(str(self.api_url) + self.FILTER_RUNS,
data=json.dumps(request), headers=self.header, verify=False)
if hasattr(result.json(), 'error') or result.json()['status'] != self.R... | |
'Chatham', 'state': 'Massachusetts'},
{'city': 'Chatham', 'state': 'New Jersey'},
{'city': 'Chatham', 'state': 'Illinois'},
{'city': 'Chattanooga', 'state': 'Tennessee'},
{'city': 'Cheat Lake', 'state': 'West Virginia'},
{'city': 'Cheektowaga', 'state': 'New York'},
{'city': 'Cheektowaga', 'state': 'New York'},
... | |
tracer.get_sparse_matrix(format)
def sparse_matrix_and_bias(self, x, *condition_args, format: str = None, **kwargs):
key = self._condition_key(x, condition_args, kwargs)
tracer = self._get_or_trace(key)
return tracer.get_sparse_matrix(format), tracer.bias
def _condition_key(self, x, condition_args, kwargs):
kwa... | |
<reponame>radhermit/bite
import argparse
from collections import OrderedDict
from functools import partial
from snakeoil.cli import arghparse
from .. import const
from ..exceptions import BiteError
from ..argparser import (
ParseStdin, Comment, IntList, IDList, StringList, IDs, ID_Maps, ID_Str_Maps,
TimeIntervalArg... | |
tree[6].set_numerical_test_node(
feature_id=5, opname='<', threshold=1,
default_left=True, left_child_key=11, right_child_key=12)
tree[11].set_leaf_node(leaf_value=0.125240386)
tree[12].set_leaf_node(leaf_value=-0.0480586812)
tree[0].set_root()
builder.append(tree)
tree = treelite.ModelBuilder.Tree()
tree[0].s... | |
<gh_stars>0
import os
from abc import ABCMeta, abstractmethod
from copy import copy
from typing import Optional, Tuple, Iterable, List
import pgpy
from cryptography.hazmat.primitives.hashes import Hash, SHA256
from pgpy import PGPKey, PGPUID
from pgpy.types import Fingerprint
from git_anon.custom_exception import Cus... | |
<filename>admin_tabs/helpers.py
# -*- coding: utf-8 -*-
from django.contrib.admin.helpers import AdminForm, Fieldset
from django.contrib.admin import ModelAdmin
from django.contrib.admin.options import csrf_protect_m
from django.db import transaction
class AdminCol(object):
"""
One column in the admin pages.
"""
d... | |
<reponame>cwood1967/SBEMimage
# -*- coding: utf-8 -*-
# ==============================================================================
# This source file is part of SBEMimage (github.com/SBEMimage)
# (c) 2018-2020 <NAME> Institute for Biomedical Research, Basel,
# and the SBEMimage developers.
# This software is licen... | |
<reponame>kaihami/GREPY<filename>GREPY_GUI.py<gh_stars>0
import wx
import os
import wx.lib.scrolledpanel as scrolled
from bs4 import BeautifulSoup
from urllib2 import urlopen
from threading import *
from multiprocessing import cpu_count, Pool
import datetime
from Bio.KEGG.REST import kegg_get
from Bio.Blast import NCBI... | |
new users to the chat
- `can_pin_messages` :`bool` Pass True, if the administrator can pin messages, supergroups only
**Returns:**
- A `tuple`, on success a `bool` as first member and a botApiResponse object as second member
"""
data = {
"chat_id": chat_id,
"user_id": user_id,
"is_anonymous": is_anonymous,
"... | |
<reponame>cmusatyalab/nephele
#!/usr/bin/env python
import sys
import os
import ast
import json
import math
from collections import OrderedDict
from .configuration import VMOverlayCreationMode
from operator import itemgetter
import logging
LOG = logging.getLogger(__name__)
_process_controller = None
stage_names = [... | |
parent = self)
""" Teacher Present Assignment Error """
if retrieveDataEntries[8] == 0:
teacherPresMessage = wx.MessageBox('Child present but no teacher presence assigned',\
caption = 'Error on Teacher Presence Assignment:',\
style = wx.OK, parent = self)
""" Task Assignment Error """
if retrieveD... | |
<reponame>luizfloripa/instagramy
""" Parsers for Instagramy """
import json
from datetime import datetime
from html.parser import HTMLParser
from collections import namedtuple
from .exceptions import RedirectionError
from .requests import get
def _nodes_classfier(nodes: list):
post_lists = []
for node in nodes:
... | |
<reponame>marromlam/quick-memos<filename>ProjectMaker.py
# -*- coding: UTF-8 -*-
##########################################################################################
# Importing packages. ####################################################################
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.... | |
#!/usr/bin/env python3
"""@@@
Main Module: Motif.py (adapted to chromatin starting from RNA/Motif-bkp160630.py)
Objects: Motif
Link
LGroup
ndx
Map
--- motif class objects
AST
APT
XLoop
MBL
Branch
Stem
PseudoKnot
ArchMP
MultiPair
Functions: stemType2PairList
disp_Motif
copyStem
ins_so... | |
24).
.. note::
Of course, failure to produce a minimal polynomial does not
necessarily indicate that this number is transcendental.
"""
if algorithm is None or algorithm.startswith('numeric'):
bits_list = [bits] if bits else [100,200,500,1000]
degree_list = [degree] if degree else [2,4,8,12,24]
for bits in b... | |
`separator` is not given as `None`, ``ContentParameterSeparator``, `str`, neither as `tuple` instance.
- If `separator was given as `tuple`, but it's element are not `str` instances.
ValueError
- If `separator` is given as `str`, but it's length is not 1.
- If `separator` is given as `str`, but it is a space charac... | |
<filename>scalpel/typeinfer/typeinfer.py
"""
This module is the main module of typeinfer. The module contains a single class named TypeInference which processes
files and infer types.
"""
import os
import ast
import astunparse
from typing import List
from pprint import pprint
from scalpel.typeinfer.visitors import ge... | |
import numpy as np
import math
from copy import deepcopy
from collections import deque
from collections import OrderedDict
class FLC():
""" FLC filter class
Attributes
----------
n : int
Number of harmonics
X : ndarray
Reference input vector
W : ndarray
Weights
V : ndarray
Angular frequencies
mu : float
... | |
<filename>0900-hp/hplip-3.21.12/fax/pmlfax.py
# -*- coding: utf-8 -*-
#
# (c) Copyright 2003-2015 HP Development Company, L.P.
#
# 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 ... | |
<reponame>cxiang26/mygluon_cv<gh_stars>10-100
# -*- coding: utf-8 -*-
"""Fully Convolutional One-Stage Object Detection."""
from __future__ import absolute_import
import os
import warnings
import numpy as np
import mxnet as mx
from mxnet import autograd
from mxnet.gluon import nn, HybridBlock
from ...nn.bbox import B... | |
the message silently. Users will receive a notification with no sound.
:type disable_notification: :obj:`typing.Union[base.Boolean, None]`
:param reply_to_message_id: If the message is a reply, ID of the original message
:type reply_to_message_id: :obj:`typing.Union[base.Integer, None]`
:param reply_markup: Additio... | |
pos in self.points:
if dim in self.points[pos]:
positions.append(pos)
break
if len(positions) != len(dims):
raise Exception("""Could not get an appropriate grip point position for the given dimensions:
%s """ % (dims,))
return positions
else:
position = None
for pos in self.points:
if dims in self.points[pos... | |
#!/usr/bin/python
# Project : diafuzzer
# Copyright (C) 2017 Orange
# All rights reserved.
# This software is distributed under the terms and conditions of the 'BSD 3-Clause'
# license which can be found in the file 'LICENSE' in this package distribution.
from struct import pack, unpack
from cStringIO import StringIO... | |
from __future__ import unicode_literals
import collections
import six
from egnyte import base, exc
class FileOrFolder(base.Resource):
"""Things that are common to both files and folders."""
_url_template = "pubapi/v1/fs%(path)s"
_lazy_attributes = {'name', 'folder_id', 'is_folder'}
def _action(self, action, d... | |
<gh_stars>1-10
'''
Created : Jan 16, 2017
Last major update : June 29, 2017
@author: <NAME>
Purpose:
Fast density clustering
'''
import numpy as np
import time
from numpy.random import random
import sys, os
from .density_estimation import KDE
import pickle
from collections import OrderedDict as OD
from sklearn.ne... | |
os.stat('tmp/stefan_full_rgba_ecwv3_meta.ecw.aux.xml')
gdaltest.post_reason('fail')
return 'fail'
except:
pass
return 'success'
###############################################################################
# Test setting/unsetting file metadata of a ECW v3 file
def ecw_42():
if gdaltest.ecw_drv is None or g... | |
<filename>line/client.py
# -*- coding: utf-8 -*-
"""
line.client
~~~~~~~~~~~
LineClient for sending and receiving message from LINE server.
:copyright: (c) 2014 by <NAME>.
:license: BSD, see LICENSE for more details.
"""
import re
import requests
import sys
from api import LineAPI
from models import LineGroup, ... | |
import asyncio
import os
import random
import aiohttp
import json
import re
import io
import discord
from discord.ext import commands
from discord.ext.commands import BucketType
from datetime import datetime
import humor_langs
import wikipedia
import asyncpraw
import urllib.parse
import ffmpy
import textwrap
from tr... | |
m.x633 <= 0)
m.e680 = Constraint(expr= -10 * m.b95 + m.x637 <= 0)
m.e681 = Constraint(expr= -10 * m.b96 + m.x641 <= 0)
m.e682 = Constraint(expr= -10 * m.b97 + m.x645 <= 0)
m.e683 = Constraint(expr= -10 * m.b98 + m.x649 <= 0)
m.e684 = Constraint(expr= -10 * m.b99 + m.x653 <= 0)
m.e685 = Constraint(expr= -10 * m.b100 + m... | |
# ======================================================================
# Imports
# ======================================================================
import os
import copy
import numpy as np
from scipy import sparse
from scipy.sparse import linalg
from pyspline import Volume
from pyspline.utils import openTecplot... | |
np.empty(tableShape)
counts = []
with mp.Parallelize(counts=counts) as tasker:
for task in tasker:
count = np.zeros(tableShape[1:], dtype=float)
for i, t in enumerate(tVals):
n = nev[i] / tasker.numWorkers()
for j in range(int(n)):
if j % 10000 == 0:
print("%d/%d %d/%d" % (i, len(tVals), j, int(n)))
tasker.pr... | |
planted set, blue planted set, and the planted region.
"""
_, _, reg = region_plant_f(traj_start + traj_end, r, .5, q)
flux_region = []
out_region = []
for st_pt, end_pt in zip(traj_start, traj_end):
if reg.contains(st_pt) and not reg.contains(end_pt):
flux_region.append((st_pt, end_pt))
elif reg.contains(end_... | |
<filename>examples/DataAnalysis/CentralBase.py
# encoding: UTF-8
import sys
import json
from pymongo import MongoClient
from vnpy.trader.app.ctaStrategy.ctaBase import DATABASE_NAMES
import pandas as pd
import numpy as np
import datetime as dt
import talib as ta
from interval import Interval
import time
#方向
M_TO_UP ... | |
# Copyright (c) 2013-2014, Clemson University
# 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 copyright notice, this
# list of conditions... | |
['Equipment'],
'VISUAL ACUITY MEASUREMENTS IOD': ['Equipment'],
'US MULTI-FRAME IMAGE IOD': ['Equipment'],
'ENHANCED X-RAY RF IMAGE IOD': ['Equipment'],
'RT BEAMS DELIVERY INSTRUCTION IOD': ['Equipment'],
'SUBJECTIVE REFRACTION MEASUREMENTS IOD': ['Equipment'],
'US IMAGE IOD': ['Equipment'],
'GENERAL ECG IOD': [... | |
<reponame>Unitek-KL/csp
# coding: utf-8
"""*****************************************************************************
* Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip p... | |
fig.add_subplot(2,len(thetas)+1,i+2)
DFM.hist2d(x_obs[0], x_obs[1], levels=[0.68, 0.95],
range=[ranges[0], ranges[1]], bins=20, color='k',
contour_kwargs={'linestyles': 'dashed'},
plot_datapoints=False, fill_contours=False, plot_density=False, ax=sub)
DFM.hist2d(_x[0], _x[1], levels=[0.68, 0.95],
range=[ranges[... | |
'view_fs_ogle_summary': [['name', 'raDeg', 'decDeg'],1008],
'cbats': [['name', 'raDeg', 'decDeg'],1009],
'view_cbats_sn': [['name', 'raDeg', 'decDeg'],1010],
'view_cbats_psn': [['name', 'raDeg', 'decDeg'],1011],
# 2015-03-16 KWS Added fs_brightsnlist_discoveries (bright SN list)
'fs_brightsnlist_discoveries': [['n... | |
antenna rot. corr., vertical channel
'SQI': normalized_coherent_power,
# Signal quality index
'SQIh': normalized_coherent_power,
# Signal quality index, horizontal channel
'SQIv': None, # Signal quality index, vertical channel
'CCOR': None, # Clutter power correction
'CCORh': None, # Clutter power correction, ... | |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 14 11:55:08 2018
@author: <NAME>
"""
import pytest
import itertools
import numpy as np
import pandas as pd
import scipy.sparse as sps
from sklearn.datasets import make_blobs
from sklearn.linear_model import Ridge
from sklearn.base import is_classifier, is_regressor
fro... | |
<reponame>trussworks/edd<filename>server/main/forms.py
import collections
import json
import logging
from copy import deepcopy
from functools import partial
from django import forms
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.... | |
shipping_zone.name,
"countries": [{"code": c.code} for c in shipping_zone.countries],
"channels": [{"name": c.name} for c in shipping_zone.channels.all()],
},
"meta": None,
}
)
assert deliveries[0].payload.payload == expected_payload
assert len(deliveries) == len(webhooks)
assert deliveries[0].webhook == webho... | |
options:
self.multiprocess_min_port = int(options[ARG_MULTIPROCESS_MIN_PORT])
if self.IsApiServer():
assert self.port == self.api_port
if self.IsBackend():
self.InitBackendEntry()
if not self.Type():
self.SetType(DevProcess.TYPE_MASTER)
def InitBackendEntry(self):
"""Finds the entry for the backend this p... | |
sampleGiven(self, value):
return value[self.value]
def evaluateInner(self, context):
return StarredDistribution(valueInContext(self.value, context), self.lineno)
def __str__(self):
return f'*{self.value}'
class MethodDistribution(Distribution):
"""Distribution resulting from passing distributions to a metho... | |
<reponame>baldurk/Vulkan-LoaderAndValidationLayers<gh_stars>1-10
#!/usr/bin/env python3
#
# Copyright (c) 2015-2016 The Khronos Group Inc.
# Copyright (c) 2015-2016 Valve Corporation
# Copyright (c) 2015-2016 LunarG, Inc.
# Copyright (c) 2015-2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "Lic... | |
cosmo_fns=None, DA=None, H=None,
rescale_da=1., rescale_h=1.):
"""
Transform constraints on D_A(z) and H(z) into constraints on the LSS
distance measures, D_V(z) and F(z).
Parameters
----------
z : float
Redshift of the current bin
F : array_like
Fisher matrix for the current bin
paramnames : list
... | |
curve grows 'into' the surface
elif (test_u_direction[3] > 0): # compare projection path to surface normal: dot product positive
direction = -1 # > curve grows 'out of' the surface
# initialize error
error = 1.0
# set up binary search loop
loop_count = 0
while (error > tol and loop_count < 100)... | |
#!/usr/bin/env python
# Copyright (c) 2018, 2019, 2020 CNRS and Airbus S.A.S
# Author: <NAME>
#
# 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
# noti... | |
<reponame>KevinVolkSTScI/wfss_overlap<filename>wfss_overlap_tool.py
#! /usr/bin/env python
#
"""
Tool to access the possibility of overlap of spectra for a field of view.
This code takes as input either a pair or Mirage source input files (one for
stars and one for galaxies) or a scene image made from such input files... | |
from __future__ import print_function
from .backtrack import mfe, boltzmann_sample, enumerative_backtrack
from .parameters import get_params
from .util.wrapped_array import WrappedArray, initialize_matrix
from .util.secstruct_util import *
from .util.output_util import _show_results, _show_matrices
from .util.sequence_... | |
__author__ = 'abel'
import tempfile
import os
import numpy as np
def int_to_xyz(molecule, no_dummy=True):
internal = molecule.get_full_z_matrix()
coordinates = [[0.0, 0.0, 0.0]]
for line in internal[1:]:
bi = int(line[0]) #bond index
B = line[1] #bond value
ai = int(line[2]) #Angle index
A = line[3] #Angle v... | |
## Data processing
## Processing JSON file
import csv
import os
import collections
import json
import logging
from copy import deepcopy
import numpy as np
import torch
PAD = '<pad>'
UNK = '<unk>'
USR = 'YOU:'
SYS = 'THEM:'
BOD = '<d>'
EOD = '</d>'
BOS = '<s>'
EOS = '<eos>'
SEL = '<selection>'
#SPECIAL_TOKENS_DEAL = [... | |
<filename>reflred/bruker.py
"""
Data loader for Bruker table-top X-ray source raw file format.
"""
import sys
import struct
import logging
import numpy
if sys.version_info[0] >= 3:
def tostr(s):
return s.decode('ascii')
else:
def tostr(s):
return s
MEAS_FLAG = {
0: 'unmeasured',
1: 'measured',
2: 'active',
3... | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""ResNe(X)t Head helper."""
import torch
import torch.nn as nn
from detectron2.layers import ROIAlign
class ResNetRoIHead(nn.Module):
"""
ResNe(X)t RoI head.
"""
def __init__(
self,
dim_in,
num_classes,
pool_siz... | |
#!/usr/bin/env python
# sections marked by "FIGURE_START, shouldbeone" indicate that a new figure is going to be made.
r'''
COMPANION SCRIPT #1, TESTED ONLY ON PYTHON 2.7, FOR:
Mannige RV (2017) (article title TBD).
'''
output_fig_dir = '../manuscript/automated_figures/'
# This takes a LONG time to calculate (many
... | |
import time
import os
import io
import zipfile
import pickle
from typing import Union, Type, Optional, Dict, Any, List, Tuple, Callable
from abc import ABC, abstractmethod
from collections import deque
import gym
import torch as th
import numpy as np
from stable_baselines3.common import logger
from stable_baselines3.... | |
<filename>TurtleArt/talogo.py
# -*- coding: utf-8 -*-
#Copyright (c) 2007-8, Playful Invention Company.
#Copyright (c) 2008-11, <NAME>
#Copyright (c) 2008-10, <NAME>
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to d... | |
# coding=utf-8
# Copyright 2021 The jax_verify 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 law or... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.