input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<gh_stars>1-10
import os
import sys
import numpy as np
# require pythonnet, pip install pythonnet
import clr
from System import String
# sys.path.append("DLLs")
clr.AddReference("ThermoFisher.CommonCore.Data")
clr.AddReference("ThermoFisher.CommonCore.RawFileReader")
import ThermoFisher
from ThermoFisher.CommonCore.Da... | |
<gh_stars>1-10
"""
File that involves dataloaders for the Visual Genome dataset.
"""
import json
import os
import h5py
import numpy as np
import torch
from PIL import Image
from torch.utils.data import Dataset
from torchvision.transforms import Resize, Compose, ToTensor, Normalize
from dataloaders.blob import Blob
fr... | |
import re
from typing import Dict, List, Union, Tuple, Callable, Any
import ipywidgets as ipw
import traitlets
from optimade.models.utils import CHEMICAL_SYMBOLS
from aiidalab_optimade.exceptions import ParserError
from aiidalab_optimade.logger import LOGGER
__all__ = ("FilterTabs",)
class FilterTabs(ipw.Tab):
... | |
import string
class Equacalc:
def __init__(self):
var = 0
Raddvar = ''
Rmulvar = ''
Rvarlist = []
Laddvar = ''
Lmulvar = ''
Lvarlist = []
tempvar = 0
templisty = []
newequa1 = 0
negmulflag = 0
negmulflag2 = 0
Laddsubliketerms = 0
Raddsubliketerms = 0
Lmuldivliketerms = 0
Rmuldivlikete... | |
math.cos(1.73021765373 + 104344.49901929598 * self.t)
Z0 += 0.00000000010 * math.cos(2.77364193598 + 77829.99768684579 * self.t)
Z0 += 0.00000000010 * math.cos(2.83314383566 + 104202.04936916218 * self.t)
Z0 += 0.00000000010 * math.cos(4.05963464737 + 26089.38761428249 * self.t)
Z0 += 0.00000000012 * math.cos(5.403... | |
# Lint as: python2, python3
# Copyright 2017 Google Inc. 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 require... | |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... | |
<reponame>swederik/structurefunction<gh_stars>1-10
import os
import os.path as op
import nipype.interfaces.io as nio # Data i/o
import nipype.interfaces.utility as util # utility
import nipype.pipeline.engine as pe # pypeline engine
import nipype.interfaces.fsl as fsl
import nipype.interfaces.freesurfer as fs
import ni... | |
self.__cmp__(other) != 0
def __lt__(self: FixedPointType, other: Any) -> bool:
"""Less than comparison operator."""
return self.__cmp__(other) < 0
def __le__(self: FixedPointType, other: Any) -> bool:
"""Less than or equal to comparison operator."""
return self.__cmp__(other) <= 0
def __gt__(self: FixedPointT... | |
nan ],
[ 870, 42.1211, 0.1440, 63.9225, 0.0949, 39.8764, 0.1521, 22.0460, 0.2751, 1.39e-06, 1.38e-06, 1.39e-06, nan ],
[ 880, 42.8106, 0.1450, 66.0631, 0.0939, 40.5434, 0.1531, 21.5649, 0.2878, 1.39e-06, 1.33e-06, 1.27e-06, nan ],
[ 890, 42.5972, 0.1490, 65.4134, 0.0970, 40.9589, 0.1550, 21.8761, 0.2902, 1.26e-06, 1... | |
# This script is designed to visualise the outputs from optimisation, particularly the investment related decisions.
# Author name: <NAME>
# Author email = <EMAIL>
# Organisation = Imperial College London
# Date: 05 March 2019
# Version: 1.0
##Elegancy GIS Outputs=name
##Outputs_path=string C:\Users\JohnDoe\Desktop\Op... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 <NAME> (Nagoya University)
# based on a WaveNet script by <NAME> (Nagoya University)
# (https://github.com/kan-bayashi/PytorchWaveNetVocoder)
# based on sprocket-vc script by <NAME> (Nagoya University)
# (https://github.com/k2kobayashi/sprocket)
# Apache ... | |
chosen so that
# the relevant dual optimality criterion (see (3.10) in
# boyd-2010-distributed) is satisfied.
return (self.lmbda / self.rho) * np.sign(self.Y)
def ystep(self):
r"""Minimise Augmented Lagrangian with respect to
:math:`\mathbf{y}`."""
self.Y = np.asarray(sp.prox_l1(self.AX + self.U,
(self.lmbd... | |
<filename>mobile_insight/analyzer/kpi/lte_handover_prediction_analyzer.py
#!/usr/bin/python
# Filename: lte_handover_prediction_analyzer.py
"""
A file that count the occurrences of handover triggered by different events
Author: <NAME>
"""
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.et... | |
disk in drive' waning on windows
"""
# StackOverflow Ref: https://goo.gl/9gYdef
if _platform == "win32":
kernel32.SetThreadErrorMode(SEM_FAIL, ctypes.byref(oldmode))
@staticmethod
def resume_windows_warning():
"""
Resumes waning on windows
"""
if _platform == "win32":
# Resume windows error
kernel32.SetThr... | |
that meets all of the scheduling requirements (resource request, requiredDuringScheduling affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding "weight" to the sum if the node matches the corresponding matchExpressions; the node(s) with the highest sum are the most prefer... | |
setattr(new_version, attr, data)
return new_version
def get_active_version(self):
"""
Returns the active version of the motion.
If no active version is set by now, the last_version is used.
"""
if self.active_version:
return self.active_version
else:
return self.get_last_version()
def get_last_version(sel... | |
output.append(item)
try:
raw = json.loads(json.dumps(output, cls=DatetimeEncoder))
except ValueError as e:
return_error('Could not decode/encode the raw response - {err_msg}'.format(err_msg=e))
ec = {'AWS.EC2.DeletedFleets': raw}
human_readable = tableToMarkdown('AWS Deleted Fleets', data)
return_outputs(human_... | |
<reponame>Ling-Jun/geo-deep-learning<filename>train_segmentation.py
import os
import time
import h5py
import torch
import warnings
import functools
import numpy as np
from PIL import Image
from tqdm import tqdm
from pathlib import Path
from shutil import copy
from datetime import datetime
from typing import Sequence
fr... | |
<reponame>EMBEDDIA/PropStar<filename>propStar.py
## propStar example use, skrlj 2020 use at own discretion
import pandas as pd
import queue
import networkx as nx
import tqdm
from collections import defaultdict, OrderedDict
from sklearn.dummy import DummyClassifier
from sklearn.feature_extraction.text import TfidfVecto... | |
from __future__ import division
from collections import OrderedDict
from functools import partial
import gzip
import io
import os
import logging
import os.path
import h5py
import numpy
from picklable_itertools.extras import equizip
from progressbar import ProgressBar
from PIL import Image
from scipy.io.matlab import l... | |
23889,
"name": "Производственная практика, по получению профессиональных умений и опыта профессиональной деятельности",
"term": 10,
"course_project": False
},
{
"id": 23615,
"name": "Производственная практика, преддипломная",
"term": 4,
"course_project": False
},
{
"id": 23615,
"name": "Производственная пр... | |
<reponame>Chromico/bk-base
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
-------------------... | |
net.add_lane("emser", "emexr",
StraightLane(np.array([491, -196]), np.array([501, -202]), line_types=[n, n], forbidden=True))
net.add_lane("emsel", "emwxl",
StraightLane(np.array([487, -196]), np.array([467, -210]), line_types=[n, n], forbidden=True))
net.add_lane("emsel", "emnxl",
StraightLane(np.array([487, -196... | |
the parameter list
Returns
dict: Dictionary containing featurizer specific metadata as a subdict under the keys
['ECFPSpecific','AutoencoderSpecific']
"""
feat_metadata = {}
# MJT: I changed params.featurizer in this instance to self.feat_type to be syntactically consistent
if self.feat_type == 'ecfp':
ecfp_pa... | |
'''
TODO:
- avg training loss
- baseline? ie what is the prediction
'''
from tokenizers import CharBPETokenizer
import torch
import torch.nn as nn
from torchtext import data
from picotext.model import RNN_lm, RNN_tr
from picotext.utils import batchify, get_batch, repackage_hidden
from picotext.utils import load_pret... | |
# -*- coding: utf-8 -*-
"""Developer convenience functions for ibs (detections).
TODO: need to split up into sub modules:
consistency_checks
feasibility_fixes
move the export stuff to dbio
then there are also convineience functions that need to be ordered at least
within this file
"""
import logging
from os.path... | |
""" Cisco_IOS_XR_infra_xtc_oper
This module contains a collection of YANG definitions
for Cisco IOS\-XR infra\-xtc package operational data.
This module contains definitions
for the following management objects\:
pce\-lsp\-data\: PCE LSP's data
pce\-peer\: pce peer
pce\-topology\: pce topology
pce\: pce
Copyrig... | |
-m.b1018 + m.b1019 - m.b1139 <= 0)
m.e1827 = Constraint(expr= -m.b1018 - m.b1019 + m.b1020 - m.b1140 <= 0)
m.e1828 = Constraint(expr= m.b1021 - m.b1141 <= 0)
m.e1829 = Constraint(expr= -m.b1021 + m.b1022 - m.b1142 <= 0)
m.e1830 = Constraint(expr= -m.b1021 - m.b1022 + m.b1023 - m.b1143 <= 0)
m.e1831 = Constraint(expr= m... | |
<gh_stars>0
# Copyright 2014 Rackspace, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | |
varps = []
a, b, varp = pylab.hist(diff,bins=arange(-0.2,0.2,0.016))
#print a,b,varp
varps.append(varp[0])
diff_cut = []
for d in range(len(diff)):
if abs(d) < 0.25:
diff_cut.append(diff[d])
list = scipy.array(diff_cut)
mu = list.mean()
median = scipy.median(diff_cut)
sigma = list.std()
print 'mu', mu
... | |
<gh_stars>0
import abc
import inspect
import logging
import time
import typing
from d3m import exceptions, types, utils
from d3m.metadata import base as metadata_base, hyperparams, params, problem
__all__ = (
'Inputs', 'Outputs', 'Params', 'Hyperparams', 'CallResult', 'MultiCallResult', 'DockerContainer',
'Primitiv... | |
* phase * qm)
# Calculate polarisation with incident neutron
sf[n] = np.dot(sfm, incident_polarisation_vector)
return sf
def sf_magnetic_xray(q, r, moment, magnetic_formfactor=None, occ=None, debyewaller=None, **kwargs):
"""
Calculate the non-resonant magnetic component of the structure factor
:param q: [n,3] ... | |
lms/djangoapps/lms_xblock/apps.py
def descriptor_global_local_resource_url(block, uri):
"""
See :meth:`xblock.runtime.Runtime.local_resource_url`.
"""
raise NotImplementedError("Applications must monkey-patch this function before using local_resource_url for studio_view") # lint-amnesty, pylint: disable=line-too-lo... | |
#Copyright 2014 Blackberry Limited
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, so... | |
"""Stochastic compartmental models."""
import logging
from pathlib import Path
import numpy as np
import pypfilt
from .model import Model
class SEEIIR(Model):
"""A stochastic SEEIIR compartment model."""
__info = [
("S_U", False, 0, 1),
("E1_U", False, 0, 1), ("E2_U", False, 0, 1),
("I1_U", False, 0, 1), ("I2_... | |
|
(y > ub_b) |
(z > ub_c)
)
if return_as_new_model:
return model.select(~s)
else: # usual
self.add_model_by_id( model.select(~s), 'model')
# Methods for sharpening and comparing maps, models and calculating FSC values
def get_rms_f_list(self,
map_id = 'map_manager',
d_min = None, # minimum resolution for ... | |
# merge.py - directory-level update/merge handling for Mercurial
#
# Copyright 2006, 2007 <NAME> <<EMAIL>>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from node import nullid, nullrev, hex, bin
from i18n import _
from mercuria... | |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Module for reading 3D dicom data"""
from loguru import logger
from typing import Union
# import numpy as np
# import h5py
from pathlib import Path
import os.path
import sys
from .image import DataPlus, transform_orientation, transform_orientation_voxelsize
import p... | |
in range(3, 13):
for m in range(4, 13):
if m == l + 1 and l == k + 1 and k == j + 1 and j == i + 1:
STRAIGHT_SHCHD.append({S[i], H[j], C[k], H[l], D[m]})
STRAIGHT_SHCHD.append({S[9], H[10], C[11], H[12], D[0]})
STRAIGHT_SHCDS = []
for i in range(13):
for j in range(1, 13):
for k in range(2, 13):
for l in range(3... | |
* yscale) - y_min
steep = False
if abs(xl-xr) < abs(yl-yr):
xl,yl = yl,xl
xr,yr = yr,xr
steep = True
if xr < xl:
xr,xl = xl,xr
yr,yl = yl,yr
# Start at left endpoint
x = xl
y = yl
# Delta X and Y
dx = xr - xl
dy = yr - yl
# Test for vertical line
if dx == 0:
if dy == 0:
# Single plot point
if st... | |
<reponame>coderepocenter/AxisUtilities
from __future__ import annotations
from typing import Iterable, Callable
import numpy as np
import dask.array as da
from numba import prange
from scipy.sparse import csr_matrix
from axisutilities import Axis
class AxisRemapper:
"""
`AxisRemapper` facilitates conversion betw... | |
waveguide: The base waveguide material and size in the form of :code:`Box`.
wavelength: Wavelength for the mode solver.
num_modes: Number of modes that should be solved.
wg_height: The waveguide height.
sub_eps: The substrate epsilon (defaults to air)
sub_height: The height of the substrate (or the min height of t... | |
import datetime
from urllib.parse import urlparse
import logging
import threading
import ujson
import grpc
from grpc._cython import cygrpc
from ..grpc_gen import milvus_pb2_grpc
from ..grpc_gen import milvus_pb2 as grpc_types
from .abstract import ConnectIntf, CollectionSchema, IndexParam, PartitionParam, TopKQueryRe... | |
for self.all_letters
def find_negative_letters(num_string):
return ''.join([i for i in self.all_letters if i not in num_string])
#Returns True iff string1 contains all letters in string2
def contains(num_string1,num_string2):
for i in num_string2:
if i not in num_string1:
return False
return Tr... | |
= self.zenith_cut.get_bounds()[1]
if not self.quiet:
if exp_radius == 180:
print 'Constructing all-sky livetime cube'
else:
print('Constructing livetime cube about RA,Dec = ({0:0.3f},{1:0.3f}) with a radius of {2:0.3f} deg.'.format(roi_dir.ra(),roi_dir.dec(),exp_radius))
for i in xrange(1+self.use_weighted_liveti... | |
from archipelago import archipelago
from archipelago.setup import main_setup, parl_init_TWFY, parl_init_GOV
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import unittest
import sqlite3
import json
from lxml import etree
import os
# ----------------------------- ARCHIPELAGO TESTS ---... | |
# coding: utf-8
"""
tweak-api
Tweak API to integrate with all the Tweak services. You can find out more about Tweak at <a href='https://www.tweak.com'>https://www.tweak.com</a>, #tweak.
OpenAPI spec version: 1.0.8-beta.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apac... | |
'AuthDBChange:AuthGroup$A group!1800': {
'app_version': u'v1a',
'auth_db_rev': 3,
'change_type': change_log.AuthDBChange.CHANGE_GROUP_DELETED,
'class_': [u'AuthDBChange', u'AuthDBGroupChange'],
'comment': u'Deleted',
'old_description': u'Another blah',
'old_owners': u'another-owners',
'target': u'AuthGroup$A gr... | |
parallel_reject_flags_length = Combine(word_reject_flags_prefix +
word_reject_flags_length +
Groups.positions_in_bracket())
one_reject_flags = simple_reject_flags | parallel_reject_flags | parallel_reject_flags_slash | simple_reject_flags_length | parallel_reject_flags_length
return ZeroOrMore(one_reject_flags)
... | |
images in a TIFF file.
"""
yield self.read_image(verbose=verbose)
while not self.LastDirectory():
self.ReadDirectory()
yield self.read_image(verbose=verbose)
self.SetDirectory(0)
def __del__(self):
self.close()
@debug
def FileName(self): return libtiff.TIFFFileName(self)
@debug
def CurrentRow(self): retur... | |
for this instruction.
op = 0xa5
#: The JVM instruction name as appears in the specification.
name = 'if_acmpeq'
#: Alias for the `name` property.
mnemonic = name
#: List of operands this instruction takes, if any.
fmt = (('>h', 'B'),)
#: True if this instruction can be prefixed by WIDE.
can_be_wide = False
c... | |
str(temperature)).replace('_num-atoms_', str(vac_atoms)).replace('_num-steps_', str(steps2)).replace('disang_file', 'disang%02d' %int(i)))
else:
for line in fin:
fout.write(line.replace('_temperature_', str(temperature)).replace('_num-atoms_', str(vac_atoms)).replace('_num-steps_', str(steps1)).replace('disang_file'... | |
event.vertices[0]
mu.setTrackForDxyDz(self.cfg_ana.muon_dxydz_track)
# Set tight id if specified
if hasattr(self.cfg_ana, "mu_tightId"):
for mu in allmuons:
mu.tightIdResult = mu.muonID(self.cfg_ana.mu_tightId)
# Compute relIso in 0.3 and 0.4 cones
for mu in allmuons:
if self.cfg_ana.mu_isoCorr=="rhoArea" :
... | |
<reponame>dmivilensky/highlight
import json
# Create your views here.
import os
import asyncio
import sys
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from bson.objectid import ObjectId
# from .forms import UploadFileForm
import docx
import time
import datetime
from .logg... | |
import functools
import inspect
import logging
import re
import unicodedata
from typing import TYPE_CHECKING, Any, Dict, Iterable, Union
from anyascii import anyascii
from django.apps import apps
from django.conf import settings
from django.conf.locale import LANG_INFO
from django.core.exceptions import ImproperlyConf... | |
from allauth.socialaccount.adapter import get_adapter
from rest_framework.response import Response
from rest_framework import viewsets, status
from django.contrib.auth.models import User
from rest_framework.decorators import action
from rest_framework.authentication import TokenAuthentication
from .models import Profil... | |
iterhelper = context.make_helper(builder, resty)
iterhelper.parent = d
iterhelper.state = iterhelper.state.type(None)
return impl_ret_borrowed(
context,
builder,
resty,
iterhelper._getvalue(),
)
return codegen
@intrinsic
def _dict_items(typingctx, d):
"""Get dictionary iterator for .items()"""
resty = typ... | |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Li... | |
allowed to run before the controller terminates the io.argoproj.workflow.v1alpha1. A value of zero is used to terminate a Running workflow",
)
affinity: Optional[v1.Affinity] = Field(
None,
description="Affinity sets the scheduling constraints for all pods in the io.argoproj.workflow.v1alpha1. Can be overridden by ... | |
from __future__ import absolute_import
from ..coordinate import Coordinate
from ..roi import Roi
from .shared_graph_provider import\
SharedGraphProvider, SharedSubGraph
from ..graph import Graph, DiGraph
from pymongo import MongoClient, ASCENDING, ReplaceOne, UpdateOne
from pymongo.errors import BulkWriteError, WriteE... | |
def set_Version(self, Version):
self.Version = Version
def get_UploadId(self):
return self.UploadId
def set_UploadId(self, UploadId):
self.UploadId = UploadId
def get_ShipmentDetail(self):
return self.ShipmentDetail
def set_ShipmentDetail(self, ShipmentDetail):
self.ShipmentDetail = ShipmentDetail
def hasCont... | |
the higher, the more strict
- plot: (optinal) True if results are to be plotted
RETURNS:
- segmentLimits: list of segment limits in seconds (e.g [[0.1, 0.9], [1.4, 3.0]] means that
the resulting segments are (0.1 - 0.9) seconds and (1.4, 3.0) seconds
'''
if Weight >= 1:
Weight = 0.99
if Weight <= 0:
Weight = ... | |
from __future__ import division, print_function
import math
import itertools
import os
import sys
import subprocess
import shapelib
import numpy
from .config import config
from . import scheduler
def window(iterable, size=2, step=1):
"""
iterate over subseqs of iterable
"""
iterators = itertools.tee(iterable, ... | |
<gh_stars>1-10
#!/usr/bin/env python3
import argparse
import ast
import datetime
import fnmatch
import hashlib
import os
import shutil
import subprocess
import sys
# Python 2 compatibility fix.
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
class Error(Exception):
pass
class _Path(object... | |
self.delta).astype(bool)
distance_factors.eliminate_zeros()
kernel_matrix = distance_factors
# return dist_knn, which is required for cdist_k_nearest_neighbor in
# order to do a follow-up cdist request (then as reference_dist_knn as input).
if is_pdist:
ret_cdist: Optional[Dict[str, np.ndarray]] = dict(
referen... | |
<gh_stars>1-10
from datafs.managers.manager_dynamo import DynamoDBManager
from datafs.datafs import cli
from datafs._compat import u
from datafs import DataAPI, get_api, to_config_file
import os
from click.testing import CliRunner
import pytest
import traceback
import ast
import re
@pytest.yield_fixture(scope='modul... | |
<reponame>cstone112/content<gh_stars>1-10
'''IMPORTS'''
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401 # pylint: disable=unused-wildcard-import
from CommonServerUserPython import * # noqa: F401
import base64
import json
import requests
import re
from datetime import datetime, ... | |
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
import pytest # noqa: F401
import numpy as np # noqa: F401
import awkward as ak # noqa: F401
to_list = ak._v2.operations.convert.to_list
def test_keep_None_in_place_test():
v2_array = ak._v2.highlevel.Array([[3, 2, 1], [], None... | |
<reponame>ryjmacdonell/geomtools<filename>gimbal/substitute.py
"""
Substitution of molecular geometries with functional groups.
Given a cartesian geometry and element labels, a substituent can
be added knowing (a) the substituent identity (b) the desired
position to substitute and (c) the bond axis for substitution.
... | |
<reponame>andrewmkiss/PyXRF<filename>pyxrf/core/utils.py<gh_stars>10-100
import numpy as np
import scipy
import time as ttime
import logging
logger = logging.getLogger(__name__)
# =================================================================================
# The following set of functions are separated from th... | |
= g.toUnicodeFileEncoding(tail)
return head, tail
#@+node:ekr.20031218072017.2159: *3* g.os_path_splitext
def os_path_splitext(path):
path = g.toUnicodeFileEncoding(path)
head, tail = os.path.splitext(path)
head = g.toUnicodeFileEncoding(head)
tail = g.toUnicodeFileEncoding(tail)
return head, tail
#@+node:ekr.200... | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tensorflow.python.framework import ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
import numpy as np
import time
import ptb_reader
import... | |
{'NotifyWatcherId': {'type': 'string'},
'error': {'$ref': '#/definitions/Error'}},
'required': ['NotifyWatcherId'],
'type': 'object'},
'Number': {'additionalProperties': False,
'properties': {'Build': {'type': 'integer'},
'Major': {'type': 'integer'},
'Minor': {'type': 'integer'},
'Patch': {'type': 'integer'},
... | |
<gh_stars>1-10
import sys
import logging
import traceback
import time
import cv2
import asyncio
import numpy as np
from FPS import FPS
from enum import IntEnum
import json
from OpenVINO_Engine import OpenVINO_Util, OpenVINO_Engine
from OpenVINO_Config import Engine_State, Model_Flag
from concurrent.futures import Threa... | |
self._exp.fetch_trials_data(trial_indices=[max(self._exp.trials)]),
]
)
@abstractmethod
def generate_evaluate_new_parameter_values(
self,
evaluation_function: Callable,
arm_count: int = -1 # -1 means
# create all arms (i.e. all combinations of parameter values)
) -> None:
"""A place holder method for users t... | |
sage: FW(y) == x
True
sage: FW(z) == x
True
.. WARNING::
Must be implemented in style "PW0" and "W0P".
"""
PW0 = self.realization_of().PW0()
return self(PW0.from_classical_weyl(w))
def from_dual_classical_weyl(self, w):
r"""
Return the image of `w` from the finite Weyl group of dual form into ``self``.
... | |
# -*- 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 the license, s... | |
# container-service-extension
# Copyright (c) 2017 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: BSD-2-Clause
from urllib.parse import urlparse
import click
import pika
from pyvcloud.vcd.api_extension import APIExtension
from pyvcloud.vcd.client import BasicLoginCredentials
from pyvcloud.vcd.client imp... | |
<reponame>pyviz/nbsite
import os
import glob
import logging
import requests
import sphinx.util
try:
import bs4
except:
bs4 = None
from .thumbnailer import notebook_thumbnail, execute
logger = sphinx.util.logging.getLogger('nbsite-gallery')
logging.getLogger(requests.packages.urllib3.__package__).setLevel(logging.... | |
import sqlite3
import pandas
import itertools
import networkx as nx
from gtfspy.gtfs import GTFS
from gtfspy.util import timeit
from scripts.all_to_all_settings import *
def attach_database(conn, other_db_path, name="other"):
cur = conn.cursor()
cur.execute("ATTACH '%s' AS '%s'" % (str(other_db_path), name))
cur... | |
import abc
import asyncio
import base64
import hashlib
import keyword
import os
import re
from contextlib import contextmanager
from pathlib import Path
from types import MappingProxyType
from typing import ( # noqa
TYPE_CHECKING,
Any,
Awaitable,
Callable,
Container,
Dict,
Generator,
Iterable,
Iterator,
List,... | |
success + " " + author + " (" + ", ".join(commit_hashes) + ")</li>"
committers_comment += "</ul>"
if num_missing > 0:
support_url = "https://jira.linuxfoundation.org/servicedesk/customer/portal/4"
# Group commits by author.
committers = {}
# Consider the case where github Id does not exist
for commit, author in... | |
"""
repurpose_trans_rules_agrosuccess.py
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The objectives of this script are are:
1. Map land cover types represented in Millington 2009 to land cover types
represented in AgroSuccess.
2. Identify land cover types present in Millington 2009 and not in AgroSuccess,
and vice versa.
3... | |
<reponame>sparks-baird/RoboCrab<filename>crabnet/kingcrab.py<gh_stars>0
import numpy as np
import pandas as pd
import torch
from torch import nn
# %%
RNG_SEED = 42
torch.manual_seed(RNG_SEED)
np.random.seed(RNG_SEED)
data_type_torch = torch.float32
# %%
class ResidualNetwork(nn.Module):
"""
Feed forward Residual... | |
#!/usr/bin/env python3
"""
Surrogate utility.
Attributes
----------
LGR
Logger
"""
import logging
from copy import deepcopy
from math import factorial, floor, ceil
import numpy as np
from nigsp.operations.timeseries import graph_fourier_transform
from nigsp.operations.laplacian import decomposition
LGR = loggin... | |
)
self.assertEqual( bPrims[0].attribValue( "Cd" ), ( 0, 0, 0 ) )
self.assertEqual( cPrims[0].attribValue( "Cd" ), ( 1, 0, 0 ) )
self.assertEqual( dPrims[0].attribValue( "Cd" ), ( 0.5, 0.5, 0 ) )
def testSaveLoadCortexObjects( self ) :
self.writeSCC()
sop = self.sop()
sop.parm( "geometryType" ).set( IE... | |
empty data."))
if (self.view): raise(Data.Unsupported("Cannot retype a data view, either retype original data or copy and then retype."))
# Handle a single column or type being provided.
if (type(columns) == str): columns = [columns]
elif (type(columns) == int): columns = [self.names[columns]]
# Initialize "column... | |
) -> "SupervisionSegment":
"""
Return a copy of the current segment, transformed with ``transform_fn``.
:param transform_fn: a function that takes a segment as input, transforms it and returns a new segment.
:return: a modified ``SupervisionSegment``.
"""
return transform_fn(self)
def transform_text(
self, tr... | |
+----------+-------+--------+
| Exponent | Name | Suffix |
+==========+=======+========+
| 1E-24 | yocto | y |
+----------+-------+--------+
| 1E-21 | zepto | z |
+----------+-------+--------+
| 1E-18 | atto | a |
+----------+-------+--------+
| 1E-15 | femto | f |
+----------+-------+--------+
| 1E-12 | pic... | |
and the previous revision.
:type DevicePolicyChangedCols: String
| ``api version min:`` 2.5
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param DevicePolicyChangedCols: The fields that changed between this revision of the record and the previous revision.
:type DevicePolicyChangedCols:... | |
<reponame>LilSpazJoekp/docstrfmt
import asyncio
import contextlib
import glob
import os
import signal
import sys
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from copy import copy
from functools import partial
from multiprocessing import Manager as MultiManager
from multiprocessing import free... | |
<reponame>zhengp0/regm
"""
Variable module
"""
from collections.abc import Iterable
from copy import deepcopy
from dataclasses import dataclass, field
from typing import List, Union
import numpy as np
from xspline import XSpline
from regmod.data import Data
from regmod.prior import (Prior, GaussianPrior, UniformPrior... | |
A_frag = set(ugraph.bfsearch1d(idxB,idxA))
B_frag = set(ugraph.bfsearch1d(idxA,idxB))
# Compare fragments. They may be equal in case of cyclic systems
if (B_frag is None) or (A_frag is None) or (B_frag == A_frag):
return None
# Choose smaller fragment
if len(A_frag) > len(B_frag):
# if B_frag, rotation around ... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 11 09:37:49 2018
Modified on 11/27/2018 to clean up comments
Modified Wed Dec 5 2018 (Fix Issue 2, Handle DC Loads)
Modified on 02/25/2019 for version 0.1.0
Modified on Wed 01/20/2021 to add computeOutputResults
@author: <NAME>
---------------------... | |
<filename>src/mmd/PmxReader.py
# -*- coding: utf-8 -*-
#
import struct
import hashlib
from mmd.PmxData import PmxModel, Bone, RigidBody, Vertex, Material, Morph, DisplaySlot, RigidBody, Joint, Ik, IkLink, Bdef1, Bdef2, Bdef4, Sdef, Qdef # noqa
from module.MMath import MRect, MVector3D, MVector4D, MQuaternion, MMatrix4... | |
# 3
(4, TType.STRUCT, 'te', (TimedOutException, TimedOutException.thrift_spec), None, ), # 4
)
def __init__(self, success=None, ire=None, nfe=None, ue=None, te=None,):
self.success = success
self.ire = ire
self.nfe = nfe
self.ue = ue
self.te = te
def read(self, iprot):
if iprot.__class__ == TBinaryProtocol.... | |
# Import standard functions from numpy.
import numpy as np
from numpy.random import normal
# Import matplotlib and set related parameters.
import matplotlib.pyplot as plt
fig_width = 12
# Import SciPy utility functions for linear dynamical systems.
from scipy.signal import lti
from scipy.signal import dlti, dlsim
# ... | |
<filename>src/config/device-manager/test/test_dm_ansible_dci_gateway.py
#
# Copyright (c) 2020 Juniper Networks, Inc. All rights reserved.
#
from __future__ import absolute_import
from attrdict import AttrDict
from cfgm_common.tests.test_common import retries
from cfgm_common.tests.test_common import retry_exc_handle... | |
# coding: utf-8
# pylint: disable=invalid-name, protected-access, too-many-locals, too-many-arguments, too-many-statements
"""Executor manager."""
from __future__ import absolute_import
import logging
import numpy as np
from .base import mx_real_t
from . import ndarray as nd
from .context import cpu
from .io import D... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.