input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
import json
import struct
class ClassFile:
def __init__(self):
pass
@staticmethod
def serialize(d):
r = {}
magic = d[:4]
d = d[4:]
minor = int.from_bytes(d[:2], "big")
d = d[2:]
major = int.from_bytes(d[:2], "big")
d = d[2:]
r["version"] = {"major": major, "minor": minor}
r["pool"], d = ConstPool.s... | |
import numpy as np
from pyannote.audio.keras_utils import load_model
from pyannote.audio.signal import Binarize, Peak
from pyannote.audio.features import Precomputed
import my_cluster
from pyannote.core import Annotation
from pyannote.audio.embedding.utils import l2_normalize
from pyannote.database import get_annotated... | |
<reponame>nanjekyejoannah/pypy
""" Libffi wrapping
"""
from __future__ import with_statement
from rpython.rtyper.tool import rffi_platform
from rpython.rtyper.lltypesystem import lltype, rffi
from rpython.rtyper.lltypesystem.lloperation import llop
from rpython.rtyper.tool import rffi_platform
from rpython.rlib.unroll... | |
#
# For licensing see accompanying LICENSE.txt file.
# Copyright (C) 2020 Apple Inc. All Rights Reserved.
#
from pylab import *
import argparse
import h5py
import glob
import os
import PIL.ImageDraw
parser = argparse.ArgumentParser()
parser.add_argument("--scene_dir", required=True)
parser.add_argument("--camera_nam... | |
and type P")]
for atom in mda_universe.atoms:
if atom.resname == group1 or atom.resname == group2:
if atom.resid in lower_membrane:
if atom.type == "P" or atom.name == c_atom_name:
if atom.resname not in membrane["Lower"]:
membrane["Lower"][atom.resname] = [atom.id]
else:
membrane["Lower"][atom.resname]... | |
#
# Copyright 2005,2007,2012 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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 3, or (at your option)
# any later ve... | |
<filename>tests/test_base.py
"""Unit tests for instrupy.base.
"""
import unittest
import numpy as np
import random
from deepdiff import DeepDiff
from instrupy import InstrumentModelFactory, Instrument
from instrupy.basic_sensor_model import BasicSensorModel
from instrupy.passive_optical_scanner_model import PassiveOpt... | |
# coding: utf-8
#
# Known issues: Recentering on resize and when switching between
# different image types. Ring centre on image switch.
from __future__ import absolute_import, division, print_function
import imp
import math
import os
import wx
from . import pyslip
from . import tile_generation
from ..rstbx_frame i... | |
want to change the documentation of an endpoint, you can either use the
update_docs() function or the online admin interface at https://admin.sclble.net.
Args:
path: The path referencing the onnx model location (i.e., the .onnx file location).
cfid: a string with a valid computeFunction ID.
example: String exampl... | |
listener.enterForStatement(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitForStatement" ):
listener.exitForStatement(self)
class RetStatementContext(GenStatementContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a EvansParser.GenStatementContext
super()._... | |
<<<<<<< HEAD
"""
Nomenclature:
Host machine
Machine on which this pexpect script is run.
Container
Container created to run the modules on.
container_child - pexpect-spawned child created to create the container
host_child - pexpect spawned child living on the host container
"""
#The MIT License (MIT)
#
#Copyright... | |
<filename>variableProcessing/BFSVM_class/bfsvmClass.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 18 18:20:34 2020
@author: ishidaira
"""
from cvxopt import matrix
import numpy as np
from numpy import linalg
import cvxopt
from sklearn import preprocessing
from sklearn.svm import SVC
from ... | |
"""Dashborad views."""
from django.shortcuts import get_object_or_404, render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.views import generic
from wallet.models import Transaction
from scheduler.models import BookingRecord, Session
from account.mode... | |
repr don't break
repr(self.fs)
self.assertIsInstance(six.text_type(self.fs), six.text_type)
def test_getmeta(self):
# Get the meta dict
meta = self.fs.getmeta()
# Check default namespace
self.assertEqual(meta, self.fs.getmeta(namespace="standard"))
# Must be a dict
self.assertTrue(isinstance(meta, dict))
... | |
pass
def prepend(self, draw_func):
'''
'''
pass
def property_overridable_library_set(self):
'''
'''
pass
def property_unset(self):
'''
'''
pass
def remove(self, draw_func):
'''
'''
pass
def type_recast(self):
'''
'''
pass
def values(self):
'''
'''
pass
class VIEW3D_MT_object_... | |
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import pickle
from combined_thresh import combined_thresh
from perspective_transform import perspective_transform
def line_fit(binary_warped, T):
"""
Find and fit lane lines
"""
# Assuming you have created a warped bina... | |
id = objid
idstr = str("%05d" % id)
self.pngs = glob.glob(self.dir+'*'+idstr+'*.png')+glob.glob(self.dir+'*'+idstr+'*.pdf')
if len(self.pngs) == 0:
sys.exit(' - Did not find any png files to open. Looked for '+
self.dir+'*'+idstr+'*.png --> ABORTING')
self.file = self.pngs[0].split('/')[-1]
# order the pngs to... | |
the same level as the module
# we pass our default here
super(Nodz, self).__init__(parent, configPath=self.BASE_CONFIG_PATH)
self.initialize_configuration()
self.config = self.configuration_data
self._rename_field = RenameField(self)
self._search_field = SearchField(self)
self._creation_field = SearchField(self... | |
<reponame>pickxiguapi/MiniC-Compiler
import os
class NewT():
# 申请临时变量
def __init__(self, value):
global newT_num
self.value = value
self.name = 'T' + str(newT_num)
newT_num += 1
def __str__(self):
return self.name
def __repr__(self):
return '\nname:{:10}value:{:5}'.format(self.name, self.value)
def isdi... | |
<filename>pysem/model_generalized_effects.py
# -*- coding: utf-8 -*-
"""Generalized Random Effects SEM."""
from .utils import chol_inv, chol_inv2, cov
from scipy.linalg import solve_sylvester
from .model_means import ModelMeans
from itertools import combinations
from functools import partial
from . import startingvalue... | |
<reponame>jlisee/xpkg<gh_stars>1-10
# Author: <NAME> <<EMAIL>>
# Python Imports
import json
import os
import tarfile
from collections import defaultdict
# Project Imports
from xpkg import build
from xpkg import linux
from xpkg import util
from xpkg import paths
xpkg_root_var = 'XPKG_ROOT'
xpkg_tree_var = 'XPKG_TREE... | |
<reponame>luqizheng/rtmplite
#!/usr/bin/env python
# (c) 2011, <NAME> <<EMAIL>>. No rights reserved.
# Experimental rendezvous server for RTMFP in pure Python.
#
# This is a re-write of OpenRTMFP's Cumulus project from C++ to Python to fit with rtmplite project architecture.
# The original Cumulus project is in C++ and... | |
<gh_stars>10-100
import warnings
from django.conf import settings
from django.core.files.base import ContentFile
import six
from smartfields.fields import ImageFieldFile
from smartfields.processors.base import BaseFileProcessor
from smartfields.utils import ProcessingError
from smartfields.processors.mixin import Clou... | |
- now)
if task_details.io_timeout:
out = min(out, last_io + task_details.io_timeout - now)
out = max(out, 0)
logging.debug('calc_yield_wait() = %d', out)
return out
def kill_and_wait(proc, grace_period, reason):
logging.warning('SIGTERM finally due to %s', reason)
proc.terminate()
try:
proc.wait(grace_period... | |
'Ölmezbey':'',
'Özbek':'',
'Özben':'',
'Özberk':'',
'Özbey':'',
'Özbil':'',
'Özbilek':'',
'Özbilen':'',
'Özbilge':'',
'Özbilgin':'',
'Özbilir':'',
'Özbir':'',
'Özcebe':'',
'Pembe':'',
'Pembegül':'',
'Rebi':'',
'Rebii':'',
'Rebiyye':'',
'Rehber':'',
'Sebih':'',
'Sebil':'',
'Sebile':'',
'Seblâ':'',
... | |
<gh_stars>1-10
""" Utils for Postgres.
Most useful are: :func:`read_from_pg`, :func:`write_to_pg`, :func:`execute_batch`
"""
from typing import Dict, List, Set, Optional, Iterator, Iterable, Any
from contextlib import contextmanager
from itertools import chain
from logging import Logger
import jaydebeapi
import dat... | |
#!/usr/bin/env python
# Copyright (c) 2014, Palo Alto Networks
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" A... | |
# -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "... | |
'v0', SV.simZero)
return self.add_logmsg(iaddr, simstate, str(a0))
class MIPStub_setrlimit(MIPSimStub):
def __init__(self) -> None:
MIPSimStub.__init__(self, 'setrlimit')
def simulate(self, iaddr: str, simstate: "SimulationState") -> str:
a0 = self.get_arg_val(iaddr, simstate, 'a0')
a1 = self.get_arg_val(iadd... | |
a merge or pull request operation.
"""
startLine: Optional[LineNumber] = None
endLine: Optional[LineNumber] = None
hunkContent: Optional[HunkContent] = None
class MergeHunk(BaseModel):
"""
Information about merge hunks in a merge or pull request operation.
"""
isConflict: Optional[IsHunkConflict] = None
so... | |
<reponame>anthem-ai/fhir-types
from typing import Any, List, Literal, TypedDict
from .FHIR_Attachment import FHIR_Attachment
from .FHIR_code import FHIR_code
from .FHIR_CodeableConcept import FHIR_CodeableConcept
from .FHIR_Contract_ContentDefinition import FHIR_Contract_ContentDefinition
from .FHIR_Contract_Friendly ... | |
types = self.contact_types[i]
for j in range(len(types)):
nb = self.contact_ids[i][j]
# Specific selection function
if ((plates_pairs == 'all')
or ('('+str(i)+','+str(nb)+')' == plates_pairs)
or ('('+str(i)+','+str(nb)+')' in plates_pairs)
or ('('+str(nb)+','+str(i)+')' == plates_pairs)
or ('('+str... | |
data points for each node.\
They are archetypal for what the node represents and what subgroup of\
the data it encapsulates.')
header = context.feature_names
representatives = np.array(
[np.round(d['representative'][0], 2) for d in desc['nodes']])
cells = representatives.T
plot = p.plot_table(header, cells)
# ... | |
<filename>ganimides_server/ganimides_openBankingAPI/_ganimides_openBankingAPI_init_test.py
#!flask/bin/python
import os
import sys
if not (os.path.dirname(os.path.dirname(__file__)) in sys.path): sys.path.append(os.path.dirname(os.path.dirname(__file__)))
if not (os.path.dirname(__file__) in sys.path): sys.path.append(... | |
robes
And may not wear them. O, here comes my nurse,
Enter Nurse, with cords.
And she brings news; and every tongue that speaks
But Romeo's name speaks heavenly eloquence.
Now, nurse, what news? What hast thou there? the cords
That Romeo bid thee fetch?
Nurse. Ay, ay, the cords.
[Throws them down.]
Jul. Ay... | |
value of 0.5.
regul_Sigma : float (optional)
Regularization parameter for Sigma. Try first a value of 0.001.
min_val_C : float (optional)
Minimum value to bound connectivity estimate. This should be zero
or slightly negative (too negative limit can bring to an inhibition
dominated system). If the empirical covari... | |
0
f = open(fn, 'w')
print("Starting size of data frame: %i" % len(hostDF), file=f)
try:
os.makedirs('quiverMaps')
except:
print("Already have the folder quiverMaps!")
for i in np.arange(len(step_sizes)):
try:
# if True:
transient_name = SN_names[i]
print("Transient: %s"% transient_name, file=f)
ra = transi... | |
info from LVIS api.
"""
try:
import lvis
assert lvis.__version__ >= '10.5.3'
from lvis import LVIS
except AssertionError:
raise AssertionError('Incompatible version of lvis is installed. '
'Run pip uninstall lvis first. Then run pip '
'install mmlvis to install open-mmlab forked '
'lvis. ')
except ImportErr... | |
<reponame>emencia/emencia_paste_djangocms_2
"""
.. _buildout: http://www.buildout.org/
.. _virtualenv: http://www.virtualenv.org/
.. _pip: http://www.pip-installer.org
.. _Foundation 3: http://foundation.zurb.com/old-docs/f3/
.. _Foundation: http://foundation.zurb.com/
.. _Foundation Orbit: http://foundation.zurb.com/o... | |
# -*- coding: utf-8 -*-
# --------------------------
# Copyright © 2014 - Qentinel Group.
#
# 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
#
# Un... | |
ipv6_capture_hostname: Determines if the IPv6 host name and lease
time is captured or not while assigning a fixed address.
ipv6_ddns_domainname: The Grid-level DDNS domain name value.
ipv6_ddns_enable_option_fqdn: Controls whether the FQDN option sent
by the client is to be used, or if the server can automatically
... | |
words 1/quantile_error_scale is how much error is ok
as a fraction of the bin size
be cognizant of ntile, and this value, as passing a small
relativeError can increase compute time dramatically
defaults to 5
sample_size: Optional[int]
size of sample used to calculate quantile bin boundaries
no sampling if... | |
from typing import Tuple
import pytest
from more_itertools import only
from adam.ontology.phase2_ontology import gravitationally_aligned_axis_is_largest
from adam.axes import HorizontalAxisOfObject, FacingAddresseeAxis, AxesInfo
from adam.language_specific.english.english_language_generator import (
PREFER_DITRANSITI... | |
dd in other_dims:
# triangular smoothing
kernel = [1, 2, 1]
window = _window1d(g1, dd, [-1, 0, 1], bound, value)
g1 = _lincomb(window, kernel, dd, ref=g1)
# central finite differences
kernel = [-1, 1]
window = _window1d(g1, d, [-1, 1], bound, value)
g1 = _lincomb(window, kernel, d, ref=g1)
g1 = g1.square() if ... | |
policy. A higher number specifies a lower priority. If a request matches the listen policies of more than one virtual server the virtual server whose listen policy has the highest priority (the lowest priority number) accepts the request.<br/>Default value: 101<br/>Maximum length = 101
"""
try :
self._listenprio... | |
<filename>test/dbtvault_harness_utils.py
import glob
import json
import logging
import os
import re
import shutil
import sys
from hashlib import md5, sha256
from pathlib import Path
from typing import List
import pandas as pd
import pexpect
import yaml
from _pytest.fixtures import FixtureRequest
from behave.model impo... | |
is no formal proof that ECDSA, even with this additional restriction,
is free of other malleability. Commonly used serialization schemes will
also accept various non-unique encodings, so care should be taken when this
property is required for an application.
The secp256k1_ecdsa_sign function will by default create... | |
root_struct = None
meta = None
meta_tups = None
else:
# shared memory path
if sys.platform != 'win32':
# TJD this path needs to be tested more
if has_ext:
return _read_sds(path, sharename=sharename, info=info, include=include, stack=stack, sections=sections, threads=threads, filter=filter)
dir, sche... | |
<filename>src/cogent3/align/pairwise.py
#!/usr/bin/env python
"""Align two Alignables, each of which can be a sequence or a subalignment
produced by the same code."""
# How many cells before using linear space alignment algorithm.
# Should probably set to about half of physical memory / PointerEncoder.bytes
HIRSCHBER... | |
from Tkinter import *
from Bio.SCOP import Node
from Bio import SCOP
from os import *
from shutil import copy
import re
import Pmw
import urllib
import parms
#from ScopFrame import ScopFrame
import MolecularSystem
from GUICards import *
from BlissMolecularViewer import *
#location of plusImage, minusImage
gifs_dir =... | |
r[4][i] == -1:
ant_str += '(' + 'ro_' + str(reaction_index) + '_' + str(reg) + ' + (1 - ' + 'ro_' \
+ str(reaction_index) + '_' + str(reg) + ')/(1 + S' + str(reg) + '/kma_' \
+ str(reaction_index) \
+ '_' + str(reg) + '))^ma_' + str(reaction_index) + '_' + str(reg) + '*'
if r[5][i] == 'a' and r[4][i] == 1:
ant_st... | |
# Copyright 2017 QuantRocket - 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... | |
<gh_stars>10-100
from abc import ABC, abstractmethod
import inspect
import re
import textwrap
from typing import Generator, Set
from clang.cindex import Cursor, CursorKind, TokenKind, TypeKind
from .types import *
from .registry import xr_registry
class SkippableCodeItemException(Exception):
pass
class CodeItem(... | |
import base64
from collections import namedtuple
import errno
from java.security.cert import CertificateFactory
import uuid
from java.io import BufferedInputStream
from java.security import KeyStore, KeyStoreException
from java.security.cert import CertificateParsingException
from javax.net.ssl import TrustManagerFacto... | |
"""
Utility functions for champs coompetition LGB
1. Training using LGB
2. Hyperopt
"""
import numpy as np
from numpy.linalg import svd, norm
from scipy.stats import hmean
import pandas as pd
import os
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split, StratifiedKFo... | |
ClassVar[str] = "path_expression"
class_model_uri: ClassVar[URIRef] = LINKML.PathExpression
followed_by: Optional[Union[dict, "PathExpression"]] = None
none_of: Optional[Union[Union[dict, "PathExpression"], List[Union[dict, "PathExpression"]]]] = empty_list()
any_of: Optional[Union[Union[dict, "PathExpression"], L... | |
which to sort the scores
scores_sort = np.argsort(-scores)[:max_detections]
image_boxes = boxes[0, indices[scores_sort], :]
# print('seletec_boxes',image_boxes.shape)
# print(image_boxes)
# filter out of lung
if args.lung_filter:
client_paths = ['private_1', 'private_2', 'private_3']
# client_paths = ['privat... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012 pyReScene
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights ... | |
is not None:
value = os.environ[os_key]
if value is None:
value = default
return value
def initialize_plugin(self) -> None:
"""
Code to initialize the plugin
"""
swift_credentials = {
"user_domain_name": self.get_config_value(
"user_domain_name", "OS_USER_DOMAIN_NAME", default="default"
),
"project_domain... | |
<filename>fairSMOTE/fairsmote.py
from __future__ import print_function, division
from sklearn.neighbors import NearestNeighbors as NN
from aif360.datasets import StandardDataset
from sklearn.linear_model import LogisticRegression
import pandas as pd
import random
class Fairsmote:
def __init__(self,df,protected_a... | |
instance.
ValueError
If `root_path` was given as empty string.
"""
if root_path is None:
try:
maybe_module = sys.modules[import_name]
except KeyError:
pass
else:
maybe_file_name = getattr(maybe_module, '__file__')
if maybe_file_name is not None:
return os.path.dirname(os.path.abspath(maybe_file_name))
# F... | |
<filename>desietc/online.py
"""OnlineETC class that intefaces with ICS via callouts implemented by ETCApp.
Original code written by <NAME> and copied here 16-Feb-2021 from
https://desi.lbl.gov/trac/browser/code/online/ETC/trunk/python/ETC/ETC.py
The ETCApp code is hosted at
https://desi.lbl.gov/trac/browser/code/onli... | |
False
* sendInvite: If set to true when creating a user, an invitation email will be sent (if the user is created in active state). True or False
* authType: The authentication type for the user. 'ad' (AD), 'sso' (SAML SSO), 'egnyte' (Internal Egnyte)
* userType: The Egnyte role of the user. 'admin' (Administrator),... | |
= 1
for media_type, model in dm_person_models.items():
if not media_type == 'Twitter':
self.write_primary_row_heading(ws, media_type, c=c+1, r=4)
secondary_counts = OrderedDict()
country = model.sheet_name() + '__country'
for code, answer in YESNO:
counts = Counter()
rows = model.objects\
.values('sex', count... | |
[3, 's66'],
# [3, 's67'],
# [3, 's68'],
# [3, 's69'],
# [3, 's60'],
# [3, 's71'],
# [3, 's72'],
# [3, 's73'],
# [3, 's74'],
# [3, 's75'],
# [3, 's76'],
# [3, 's77'],
# [3, 's78'],
# [3, 's79'],
# [3, 's70'],
['s61', 's62'],
['s61', 's63'],
['s62', 's63'],
]
sybil_edges5 = [
[6, 's81'],
[6, 's82'],
... | |
progress percent on failure and final 'success' status
self.response._update_status(pywps_status_id, message, self.percent) # noqa: W0212
self.log_message(status=status, message=message, progress=progress)
def step_update_status(self, message, progress, start_step_progress, end_step_progress, step_name,
target_hos... | |
<gh_stars>0
from __future__ import print_function
import sys
import os
import re
import math
import argparse
import webbrowser
import random
import copy
if sys.version_info < (3,):
import ConfigParser as configparser
import StringIO
from urllib2 import urlopen as urlopen, HTTPError
from BaseHTTPServer import HTTP... | |
math.cos(0.47240363594 + 24499.0740637739 * self.t)
X3 += 0.00000000000 * math.cos(4.58808593083 + 2119.00767786191 * self.t)
X3 += 0.00000000000 * math.cos(1.93271006548 + 52179.9314359899 * self.t)
X3 += 0.00000000000 * math.cos(2.71699794579 + 27043.2590656993 * self.t)
X3 += 0.00000000000 * math.cos(0.783211302... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 10 15:52:02 2018
@author: branko
"""
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
from utils import tile_raster_images
import math
import matplotlib.pyplot as plt
plt.rcParams['image.cmap'] =... | |
#! /usr/bin/env python3
"""Tests for templite."""
from re import escape
from templite import Templite, TempliteSyntaxError
from unittest import TestCase, main
# pylint: disable=W0612,E1101
# Disable W0612 (Unused variable) and
# E1101 (Instance of 'foo' has no 'bar' member)
class AnyOldObject(object):
"""Simple test... | |
#!/usr/bin/env python
import sys
import os
import random
import copy
import time
import traceback
import inspect
import imp
#http://stackoverflow.com/questions/606561/how-to-get-filename-of-the-main-module-in-python
def main_is_frozen():
return (hasattr(sys, "frozen") or # new py2exe
hasattr(sys, "importers") # old... | |
'vm_state', 'instance_type_id', 'deleted']
query_filters = [key for key in filters.iterkeys()
if key in exact_match_filter_names]
for filter_name in query_filters:
# Do the matching and remove the filter from the dictionary
# so we don't try it again below..
query_prefix = _exact_match_filter(query_prefix, filt... | |
polling_interval
self.inc_script_names = inc_script_names
self._script_name_counter = 0
self._shutdown_lock = threading.Lock()
self._shutdown_thread = False
if client is None:
client = APIClient()
self.client = client
# A list of ContainerFuture objects for submitted jobs.
self._futures = []
def _make_fut... | |
= el
else:
local_sum = self.py.add(local_sum, el)
enc_b = self.get_map(b[x])
ts = self.py.add_plain(local_sum, enc_b, True)
ts = self.py.square(ts)
out_name = out_folder + "/square_"+str(x)
ts.save(out_name)
if self.verbosity:
perc = int(((x+1)/w.shape[1]) * 100)
print(str(perc)+"% (" + str(x+1) + "/" + s... | |
<reponame>Sascha0912/SAIL
import numpy as np
import pandas as pd
from sail.sobol2indx import sobol2indx
from sail.sobol_lib import i4_sobol_generate
from sail.initialSampling import initialSampling
from sail.createPredictionMap import createPredictionMap
from sail.getValidInds import getValidInds
from gaussianProcess... | |
selectedPlugin = models.Plugin.objects.get(
name=pluginName, selected=True, active=True
)
pluginDict = {
"id": selectedPlugin.id,
"name": selectedPlugin.name,
"version": selectedPlugin.version,
"userInput": userInput,
"features": [],
}
except models.Plugin.DoesNotExist:
pluginDict = {
"id": 9999,
"name": p... | |
# ******************
# MODULE DOCSTRING
# ******************
"""
LOMAP: Graph generation
=====
Alchemical free energy calculations hold increasing promise as an aid to drug
discovery efforts. However, applications of these techniques in discovery
projects have been relatively few, partly because of the difficulty of... | |
<gh_stars>0
# -----------------------------------------------------------------------------
# Name: FishingLocations.py
# Purpose: Support class for FishingLocations
#
# Author: <NAME> <<EMAIL>>
#
# Created: July 15, 2016
# License: MIT
# ------------------------------------------------------------------------------
f... | |
None:
msg = f"Currently only composed ValueSets are supported. {self.definition}"
raise Exception(msg)
if "exclude" in compose:
msg = "Not currently supporting 'exclude' on ValueSet"
raise Exception(msg)
# "import" is for DSTU-2 compatibility
include = compose.get("include") or compose.get("import") or []
if ... | |
<gh_stars>10-100
#!/usr/bin/python3
'''
NAME:
ap_ctl.py
PURPOSE:
Script that logs into an AP via Serial, SSH, or Telnet to read data or execute commands
EXAMPLE:
./ap_ctl.py --scheme "serial" "--tty "Serial port for accessing AP" --prompt "#" --dest <ip if using SSH or Telnet> --port <port , none for serial> --user... | |
<filename>prep/prepare_bodymap.py
# Prepare bodymap will parse labels from the FMA
# - including terms likely to be found in social media
from PyDictionary import PyDictionary # pip install PyDictionary
from svgtools.generate import create_pointilism_svg
from svgtools.utils import save_json
from nlp import processTex... | |
self._cm_rnn_start_ind += len(fc_layers_pre)
# We use odd numbers for actual layers and even number for all
# context-mod layers.
rem_cm_inds = range(2, 2*(len(fc_layers_pre)+len(rnn_layers)+\
len(fc_layers))+1, 2)
num_rec_cm_layers = len(rnn_layers)
if has_rec_out_layer and not self._context_mod_outputs:
num_... | |
print(tcolors.ERROR + "ERROR: could not checkout ip '%s' at %s." % (ip['name'], ip['commit']) + tcolors.ENDC)
errors.append("%s - Could not checkout commit %s" % (ip['name'], ip['commit']));
continue
os.chdir(cwd)
print('\n\n')
print(tcolors.WARNING + "SUMMARY" + tcolors.ENDC)
if len(errors) == 0:
print(tcolors.... | |
import winreg
from os import scandir, makedirs, getenv
from re import sub, compile, escape
from textwrap import fill
from time import sleep
from urllib.parse import urlencode
import inquirer
import malclient
import pyloader
from bs4 import BeautifulSoup
from msedge.selenium_tools import Edge, EdgeOptions
from tabulate ... | |
'''
@author: <NAME> (jakpra)
@copyright: Copyright 2020, <NAME>
@license: Apache 2.0
'''
import sys
import math
from operator import itemgetter
from collections import OrderedDict, Counter
import time
import random
import torch
import torch.nn.functional as F
import torch.optim as optim
from .oracle.oracle import m... | |
#!/usr/bin/env python
## Fraunhofer IIs
## <NAME>
## Mostly base on Spawn_npc.py from tutorial
### Carla Traffic Manager
### Vehicles selfcontrol
import glob
import os
import sys
import time
import pandas as pd
try:
sys.path.append(glob.glob('../carla/dist/carla-*%d.%d-%s.egg' % (
sys.version_info.major,
sys.ver... | |
target_vertex, parent_dict):
'''Used to Return shortest path between two vertices, used in bfs_shortestpath_notree'''
path = [target_vertex]
parent = parent_dict[target_vertex]
#get path, composed of vertices
while parent != source_vertex:
path.insert(0,parent)
parent = parent_dict[parent]
path.insert... | |
<filename>generated/nidmm/_library.py
# -*- coding: utf-8 -*-
# This file was generated
import ctypes
import threading
from nidmm._visatype import * # noqa: F403,H303
class Library(object):
'''Library
Wrapper around driver library.
Class will setup the correct ctypes information for every function on first call... | |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import pandas as pd
from functools import partial
from types import SimpleNamespace
from PyQt5 import QtCore
from PyQt5.QtGui import QFont, QStandardItemModel, QStandardItem
from PyQt5.QtCore import pyqtSignal, Qt, QAbstractTableModel, QModelIndex, QRect, QVariant... | |
or more items
if len(valid_reactant_nodes) < 5000 and not force_parallel:
output = []
worker(valid_reactant_nodes)
comp_node_set = comp_node_set.union(set(output))
else:
with mp.Manager() as manager:
# Initialize output list in manager
output = manager.list()
# Initialize processes
procs = []
for work in c... | |
#!/usr/bin/env python
"""Resource Registry implementation"""
__author__ = '<NAME>'
from pyon.core import bootstrap
from pyon.core.bootstrap import IonObject, CFG
from pyon.core.exception import BadRequest, NotFound, Inconsistent
from pyon.core.object import IonObjectBase
from pyon.core.registry import getextends
fro... | |
<reponame>ShubhamPandey28/sunpy
"""
Common solar physics coordinate systems.
This submodule implements various solar physics coordinate frames for use with
the `astropy.coordinates` module.
"""
import numpy as np
import astropy.units as u
from astropy.coordinates import Attribute, ConvertError
from astropy.coordinate... | |
warnings.warn('as_pandas_df is deprecated and will be removed in future release, '
'please use "to_pandas" method',
FutureWarning, stacklevel=2)
return self.to_pandas()
@classmethod
def from_pandas(cls, df: 'pd.DataFrame', tz: str = 'UTC') -> 'Dataset':
"""
Creates a riptable Dataset from a pandas DataF... | |
distribution by calculating its
_moments """
height = x = y = width_x = width_y = 0.0
total = data.sum()
if total > 0.0:
xx, yy = np.indices(data.shape)
x = (xx * data).sum() / total
y = (yy * data).sum() / total
col = data[:, int(y)]
width_x = np.sqrt(np.abs((np.arange(col.size) - y) ** 2 * col).sum(... | |
= [" interiming ", " foreseeing ", " tarrying ", " holding onto thine hat "]
move = [" persuade ", " inspire ", " excite "]
moving = [" persuading ", " inspiring ", " exciting "]
win = [" triumph "]
won = [" achieved "]
reward = [" endowment", " conferment", " guerdon", " spoil"]
almost = [" nigh ", " well-nigh "... | |
<filename>abacus_extension.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module defines a class `PartitionExt` which extends the `Partition` class in SageMath with
methods related to the computation of the generalized core and quotient decomposition as described in [Pearce, 2020].
See the docstring of the ... | |
check_obj.apply(check_fn, axis=1)
if isinstance(check_obj, pd.DataFrame)
else check_obj.map(check_fn)
if isinstance(check_obj, pd.Series)
else check_fn(check_obj)
)
else:
# vectorized check function case
check_output = check_fn(check_obj)
# failure cases only apply when the check function returns a boolean
#... | |
outfile.write('/>%s' % (eol_, ))
def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='nrProc'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='nrProc', fromsubclass_=False, pretty_print=True):
pass
def build(self, node):
already_processed = set()
self.buildAttr... | |
<reponame>learning310/U-Time
"""
"""
import os
import numpy as np
from argparse import ArgumentParser, Namespace
from utime.bin.evaluate import (set_gpu_vis,
get_and_load_one_shot_model,
get_logger)
from utime.hypnogram.utils import dense_to_sparse
from utime.io.channels import infer_channel_types, VALID_CHANNEL_TY... | |
#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "Lice... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.