input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
# --------------------------------------------------------
# Pytorch Multi-GPU Faster R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by <NAME>, <NAME>, based on code from Ross Girshick
# --------------------------------------------------------
from __future__ import absolute_import
from __fu... | |
import math
import numpy as np
import warnings
from collections import Counter
from sklearn.cluster import MiniBatchKMeans
from sklearn.metrics import calinski_harabasz_score, davies_bouldin_score
from sklearn.preprocessing import MinMaxScaler
from .metrics import gap_statistic, silhouette_score_block
from ..utils.os... | |
"image_uri"
elif key == "problemType":
suggest = "problem_type"
elif key == "containerArguments":
suggest = "container_arguments"
elif key == "containerEntrypoint":
suggest = "container_entrypoint"
elif key == "postAnalyticsProcessorSourceUri":
suggest = "post_analytics_processor_source_uri"
elif key == "recor... | |
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import StateData
from direct.gui.DirectGui import *
from direct.interval.IntervalGlobal import *
from libotp import WhisperPopup
from panda3d.core import *
from pizzapi import *
from toontown.battle import Fanfare
from toontown.toonbase import Toont... | |
Caso 2: manca il segmento ma ne ho altri. errore.
exit("Error: the linesegments of the door does not belong to the space")
def set_centroid(self,centroid) :
'''
nel caso della mappa topologica e basta, o per altri motivi, potrei volere settare il centroide ad un valore separato
'''
if self.centroid :
print("War... | |
"""Flexible code for histogramming per-snp and per-replica statistics for selected SNPs in selected replicas in
selected scenarios and/or demographies."""
from Operations.Shari_Operations.localize.Scenario import GetScenarios, GetSelectionScenarios
from Operations.MiscUtil import Dict, compile_expr, dbg, Histogrammer... | |
<filename>hugdatafast/fastai.py
from functools import partial
from pathlib import Path
import json
from tqdm import tqdm
from torch.nn.utils.rnn import pad_sequence
import datasets
from fastai.text.all import *
@delegates()
class MySortedDL(TfmdDL):
"A :class:`DataLoader` that do smart batching and dynamic padding. ... | |
A 470 152.647 104.508 -64.137 1.00 97.78 N
ATOM 31 CA ASP A 470 153.692 105.026 -65.011 1.00 92.19 C
ATOM 32 C ASP A 470 153.455 104.600 -66.454 1.00 84.38 C
ATOM 33 O ASP A 470 153.701 105.375 -67.384 1.00 87.02 O
ATOM 34 CB ASP A 470 155.069 104.557 -64.536 1.00 87.01 C
ATOM 35 CG ASP A 470 156.186 105.479 -64.984 1.... | |
if passNum < 3:
std_threshold2 = std_threshold2*0.9
pre_window2 = pre_window2*1.75
passNum = passNum+1
event_time = nextPass
for Sidx,val in enumerate(event_idx):
whole_trace[int(val[0]):int(event_fall[Sidx,1])] = np.nan
else:
keepLokking = False
for passes in results.keys():
for st, en in results[passes... | |
import math
import random
import torch.nn as nn
from transformers.models.fsmt.configuration_fsmt import FSMTConfig
from transformers.models.fsmt.modeling_fsmt import (
SinusoidalPositionalEmbedding,
EncoderLayer,
DecoderLayer,
FSMTModel as _FSMTModel,
FSMTForConditionalGeneration as _FSMTForConditionalGeneration,
... | |
<gh_stars>0
input = """bot 119 gives low to bot 18 and high to bot 3
bot 69 gives low to bot 47 and high to bot 172
bot 51 gives low to output 6 and high to bot 174
bot 11 gives low to bot 94 and high to bot 165
bot 42 gives low to bot 0 and high to bot 95
bot 195 gives low to bot 69 and high to bot 99
bot 96 gives low... | |
dibujarGorila(supPant, x+47, y, BRAZO_IZQ_ARRIBA)
pygame.display.update()
time.sleep(2)
dibujarGorila(supPant, x-13, y, BRAZO_IZQ_ARRIBA)
dibujarGorila(supPant, x+47, y, BRAZO_DER_ARRIBA)
pygame.display.update()
time.sleep(2)
for i in range(4):
dibujarGorila(supPant, x-13, y, BRAZO_IZQ_ARRIBA)
... | |
(0x218, 'M', u'ș'),
(0x219, 'V'),
(0x21A, 'M', u'ț'),
(0x21B, 'V'),
(0x21C, 'M', u'ȝ'),
(0x21D, 'V'),
(0x21E, 'M', u'ȟ'),
(0x21F, 'V'),
(0x220, 'M', u'ƞ'),
(0x221, 'V'),
(0x222, 'M', u'ȣ'),
(0x223, 'V'),
(0x224, 'M', u'ȥ'),
(0x225, 'V'),
(0x226, 'M', u'ȧ'),
(0x227, 'V'),
(0x228, 'M', u'ȩ... | |
<gh_stars>1-10
import os.path as osp
import glob
import pickle
import random
import glob
import pickle
import torch
import os.path as osp
import numpy as np
import networkx as nx
import torch_geometric as tg
from torch_geometric.data import Data
from torch_geometric.utils import degree
from torch_scatter import scatter... | |
import logging
import numpy as np
import pandas as pd
from pandas.api.types import is_numeric_dtype
from pathlib import Path
logger = logging.getLogger(__name__)
class CustomPreprocessor():
def __init__(
self,
df: pd.DataFrame,
cfg: object
):
"""CustomPreprocessor customizes checks and cleans VAERS data from ... | |
return merge_latency[ss]
snodes = state2nset(ss, idn)
if len(stage_seqs) == 1:
assert len(snodes) == 1
merge_latency[ss] = float(
np.mean(cost_model.get_stage_latency([[snodes[0]]], batch_size, warmup, number, repeat)))
else:
convs = [nd for nd in snodes if isinstance(nd, Conv)]
assert len(convs) == len(snodes)... | |
<gh_stars>1-10
# Non-local block using embedded gaussian
# DyReG
import torch
from torch import nn
from torch.nn import functional as F
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import sys
import os
sys.path.append(os.path.abspath(os.path.join(
os.path.dirname(os.path.realpath(__file__)), '... | |
<gh_stars>1-10
# This file is part of Buildbot. Buildbot 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANT... | |
the intensity of the first 50 frames as the meta-representation
im_stack = np.zeros((min(50, frame_num), self.height, self.width))
for i in range(min(50, frame_num)):
im_i = pl.imread(self.file_list_trench_detect[i])
if np.max(im_i) > 255:
im_i = self.to_8_bit(im_i)
if self.drift_correct == 1:
# correct for drif... | |
indoor temperature above which ventilation is shutoff.
| Units: C
| Default value: 100.0
| value >= -100.0
| value <= 100.0
Args:
value (float): value for IDD Field `Maximum Indoor Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `maximum_indoor_temperature` or ... | |
import keras
from keras import layers
import torch
import torch.nn as nn
import torchmetrics
from sklearn.preprocessing import *
import numpy as np
import aiqc
from aiqc import *
# Still required even with `*` above.
from aiqc import datum
name = "tests"
def list_test_queues(format:str=None):
queues = [
{
... | |
<reponame>kufusha/cabot<gh_stars>10-100
#!/usr/bin/env python3
# Copyright (c) 2021 IBM Corporation
#
# 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 l... | |
# encoding=utf-8
r"""
The :code:`api.py` file stores all the :code:`Petfinder` class and all associated functions and methods for
interacting with the Petfinder API. Before getting started with :code:`petpy`, please be sure to obtain an
API and secret key from Petfinder by registering for an account on the Petfinder ... | |
from printind.printind_decorators import printi_all_method_calls as printidc
from printind.printind_function import printi, printiv
from tensorforce.environments import Environment
import tensorforce
from tqdm import tqdm
import numpy as np
import matplotlib.pyplot as plt
# a bit hacky, but meeehh... FIXME!!
import sy... | |
# Mika "AgenttiX" Mäki & <NAME>, 2017
## @package toolbox_2
# This program serves as a collection of supplementary functions for data_analysis.py
# pylint: disable=wrong-import-order
# To prevent Matlab from loading, comment this line and uncomment the line in simulate_extinction()
import toolbox
from math import fa... | |
Delete the connections going into the blendshape.
"""
outputs = attr.get_attribute_outputs('%s.weight' % self.pose_control)
removed_already = False
if outputs:
for output in outputs:
removed_already = False
if cmds.nodeType(output) == 'multiplyDivide':
node = output.split('.')
fou... | |
CantSellMoreThanOne
else:
await self.sell_1(ctx, ctx.author, "guitar", 75000)
if item.lower() == "drum":
if amt > 1:
raise CantSellMoreThanOne
else:
await self.sell_1(ctx, ctx.author, "drum", 100000)
if item.lower() == "lotterytk":
if amt > 1:
raise CantSellMoreThanOne
else:
await self.sell_1(ctx, ctx.autho... | |
self.draw_app.ui.slot_axis_radio.set_value('A')
elif self.draw_app.ui.slot_axis_radio.get_value() == 'A':
self.draw_app.ui.slot_axis_radio.set_value('X')
# ## Utility geometry (animated)
self.draw_app.update_utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
def clean_up(self):
self.draw_app.sel... | |
<reponame>icanbwell/SparkFhirSchemas<filename>spark_fhir_schemas/stu3/complex_types/claim.py
from typing import Union, List, Optional
from pyspark.sql.types import StructType, StructField, StringType, ArrayType, DataType
# This file is auto-generated by generate_schema so do not edit manually
# noinspection PyPep8Na... | |
grouping of information about the connection to the remote resource.
:param pulumi.Input[Sequence[pulumi.Input[str]]] group_ids: The ID(s) of the group(s) obtained from the remote resource that this private endpoint should connect to. Required on PUT (CreateOrUpdate) requests.
:param pulumi.Input[str] private_link_se... | |
import json
from django.core.urlresolvers import reverse
from django.shortcuts import render, get_object_or_404
from django.conf import settings
from django.contrib import messages
from django.core.exceptions import ValidationError
from django.http import HttpResponseRedirect, HttpResponse, Http404, JsonResponse
from d... | |
"""
`dumpsqsh` - a tool for viewing or extracting SquashFS contents
Author: (C) 2019 <NAME> <<EMAIL>>
"""
import struct
from binascii import b2a_hex
import datetime
import os
import os.path
import lzma
import zlib
try:
import lzo
except ImportError:
lzo = False
try:
import lz4.block
except ImportError:
lz4 = Fa... | |
import numpy
import numpy as np
import math
from scipy.interpolate import InterpolatedUnivariateSpline as interpolate
from scipy.integrate import simps
from scipy.integrate import romberg
import sys
#sys.path.append("/global/homes/c/chmodi/Programs/Py_codes/modules/")
import mycosmology as cosmo_lib
class Mass_Func(... | |
not in self.bombing_agents.keys():
keys_to_add.append( ((r,c), self.bombing_agents[key]) )
#down
r = key[0]+1
c = key[1]
if (r < 11):
if bomb_life_map[r][c] > 0 and (r,c) not in self.bombing_agents.keys():
keys_to_add.append( ((r,c), self.bombing_agents[key]) )
#left
r = key[0]
c = key[1]-1
if (c >= 0):
if ... | |
from .canvas import Canvas, Point, Line
from .command import BaseCommand, PenCommand, MoveCommand, ClearCommand, ColorCommand
from .parser import Parser
class Drawer(Parser):
"""
Abstraction for processing a btye stream and generating draw lines, commands and pen up/down points
on a canvas.
"""
default_canvas =... | |
<reponame>hamolicious/Red-Dot<gh_stars>1-10
from dearpygui.core import *
from dearpygui.simple import *
import cv2
import json
import os
import sys
from time import time, gmtime
from threading import Thread
from math import sqrt
def print_stamped(text):
time_stamp = gmtime(time())
log_info(text, logger='reportLogger... | |
st))
def select_mother_EBV_top(self, cat, st): # tukaj je trenutna categorija, saj jih doloačs koec generacije
selRow = list(
self.ped.loc[(self.ped.cat == cat), 'EBV'].sort_values(ascending=False)[:st].index) # katere izbereš
return list(self.ped.loc[selRow, 'Indiv'])
def write_ped(self, path):
pedNB = self.pe... | |
<filename>preprocess.py
from __future__ import print_function
import numpy as np
import pandas as pd
import random
import argparse
import os
import sys
from shutil import copyfile
import pickle as pkl
def command_parser():
parser = argparse.ArgumentParser()
parser.add_argument('-f', dest='filename', help='Input fil... | |
<gh_stars>1000+
# Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import collections
import funct... | |
import os
import subprocess
import numpy as np
import matplotlib.pyplot as pyplot
import matplotlib.cm as cm
from matplotlib.colors import Normalize
from matplotlib.backends.backend_pdf import PdfPages
from mpl_toolkits.axes_grid1 import make_axes_locatable
from simtk import unit
import openmmtools
from cg_openmm.utili... | |
Returns: true if one or more instance of the attributeType parameter is applied to this
member; otherwise, false.
"""
pass
def ToString(self):
"""
ToString(self: _MethodBase) -> str
Provides COM objects with version-independent access to the
System.Object.ToString method.
Returns: ... | |
from typing import List, Optional, Tuple, Union
import numpy as np
from transformers import *
from summarizer.bert_parent import BertParent
from summarizer.cluster_features import ClusterFeatures
from summarizer.sentence_handler import SentenceHandler
class ModelProcessor(object):
aggregate_map = {
'mean': np.me... | |
<reponame>dorinapetra/probing
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2019 <NAME> <<EMAIL>>
#
# Distributed under terms of the MIT license.
import os
import gzip
import logging
import numpy as np
import unidecode
from transformers import AutoTokenizer
from probing.data.base_data import BaseDat... | |
# Copyright (c) 2021-2022, NVIDIA CORPORATION. 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 appli... | |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import json
import time
import pdb
import platform
import string
import random
# 此脚本与create_script.sh由算法同事
# 帮忙维护,当代码变更时需更新此版本号
code_version="1.0"
def create_hccl_mindspore():
done = 0
rank_id = 0
hccl_data = {}
# for test only
#os.environ['DLWS_WORKER_NUM... | |
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmD1A"]["name"] + "-shared-scope-domain-withsubdomainaccess-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD1A"]["displayname"] + "-shared-scope-domain-withsubdomainaccess-domain-admin"
try:
vm = VirtualMa... | |
"order_id" field but a maker/taker_order_id field
if 'maker_order_id' in message:
if message['maker_order_id'] == self.currentOrderId:
print("GDAX - Current order msg: %s" % message)
if message['type'] == 'match' and 'size' in message:
# To preserve buy price calculation integrity,
# matched order must be process... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2018 Open Energy Efficiency, 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
Unle... | |
import numpy as np
>>> from vectorbt.signals.nb import generate_stop_ex_nb
>>> entries = np.asarray([False, True, False, False, False])[:, None]
>>> ts = np.asarray([1, 2, 3, 2, 1])[:, None]
>>> generate_stop_ex_nb(entries, ts, -0.1, True, 1, True, True)
array([[False],
[False],
[False],
[ True],
[False]])
... | |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from test_data import generate_test
from time import time
from sklearn.svm import OneClassSVM
from admm_graph_OP_twe... | |
#!/bin/python3
# -*- coding: utf-8 -*-
#==============================
# Author: <NAME>
# Last modified: 2018-06-29 14:48
# Filename: downloader.py
# Description:
#
#=============================#
# change from keras.utils
import hashlib
import os
import gzip
import tarfile
import zipfile
import gzip
import six
impo... | |
len(args) > 0:
register_handle(self, args[0])
DownCast = staticmethod(_ShapeUpgrade.Handle_ShapeUpgrade_Tool_DownCast)
__swig_destroy__ = _ShapeUpgrade.delete_Handle_ShapeUpgrade_Tool
Handle_ShapeUpgrade_Tool.Nullify = new_instancemethod(_ShapeUpgrade.Handle_ShapeUpgrade_Tool_Nullify,None,Handle_ShapeUpgrade_Tool... | |
"""Module to implement training operations for Neural Networks."""
import os
import math
from abc import ABC, abstractmethod
import tensorflow as tf
from tensorflow.python.client import device_lib
import nasgym.utl.configreader as cr
from nasgym import nas_logger
from nasgym import CONFIG_INI
from nasgym.net_ops.net_b... | |
sqrt(a_ + x_ ** S(2) * WC("b", S(1)))
/ (
sqrt(c_ + x_ ** S(2) * WC("d", S(1)))
* sqrt(e_ + x_ ** S(2) * WC("f", S(1)))
),
x_,
),
cons2,
cons3,
cons8,
cons29,
cons50,
cons127,
cons155,
)
rule1025 = ReplacementRule(pattern1025, replacement1025)
pattern1026 = Pattern(
Integral(
sqrt(c_ + x_ ** S(2) * W... | |
of the taps; one of 'corner', 'flange', 'D', or 'D/2',
[-]
Returns
-------
C : float
Coefficient of discharge of the orifice, [-]
Notes
-----
The following limits apply to the orifice plate standard [1]_:
The measured pressure difference for the orifice plate should be under
250 kPa.
There are roughne... | |
<filename>udkm1Dsim/structures/structure.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# The MIT License (MIT)
# Copyright (c) 2020 <NAME>
#
# 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 Softwar... | |
(self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
all_structs.append(GetConsumerByEmailPassword_result)
GetConsumerByEmailPassword_result.thrift_spec = (
(0, TType.STRUC... | |
<filename>bin/scientificLaws.py
from functools import reduce
try:
import binutil # required to import from dreamcoder modules
except ModuleNotFoundError:
import bin.binutil # alt import if called as module
from bin.rational import RandomParameterization
from dreamcoder.domains.arithmetic.arithmeticPrimitives import... | |
makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.releases_listByDistributionGroup(distribution_group_name, owner_name, app_name, async=True)
>>> result = thread.get()
:param async bool
:param string distribution_group_name: The name of the ... | |
names
by stringing together the state names in the equivalence
classes. Else we keep the name of the representative of
eqch equivalence class.
"""
if (len(D["Q"]) == 1): # Already minimal
return D
else:
# Build a dict of all state combinations of DFA.
# Function state_combos also imparts a -1 for each state p... | |
the chosen solution TODO: anglesToHkl need no
# longer check the pseudo_angles as they will be generated with the
# same function and it will prove nothing
pseudo_angles = self.get_virtual_angles(position, False)
try:
for constraint in [
self.constraints._reference,
self.constraints._detector,
]:
for constrain... | |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class Projec... | |
class TypedRead:
def __init__( self, ty, nm, buf_size_in_cl = "128", max_burst_count = "1<<24", buf_size_in_burst_reqs = None):
self.ty = ty
self.nm = nm
self.buf_size_in_cl = buf_size_in_cl
self.max_burst_count = max_burst_count
if buf_size_in_burst_reqs is None:
buf_size_in_burst_reqs = buf_size_in_cl
self.b... | |
<gh_stars>1-10
import tensorflow as tf
import numpy as np
from tensorflow import keras
from tensorflow.keras import layers
image_Width = 448
image_Height = 448
channel = 3
label_size = 20 # pascal VOC 2012 Dataset
grid = 7
batchsize = 1
Learning_Rate = 0.00001
box_per_cell = 2 # one cell have 2 box
boundary1 = grid *... | |
"""This module provides configuration values used by the application."""
import logging
import os
from collections.abc import Mapping, Sequence
from logging import config as lc
from typing import Any, Optional, Union, final
import jinja2
import yaml
from pydantic import AnyHttpUrl, BaseModel, BaseSettings, EmailStr, H... | |
import logging
import os
import json
import time
import unittest
import sys
import requests
import msal
from tests.http_client import MinimalHttpClient
from msal.oauth2cli import AuthCodeReceiver
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG if "-v" in sys.argv else logging.INFO)
def... | |
to cumulative buffers
self.cur_node[bs_idx, num_partial] = t[-1]
self.cur_cap[bs_idx, num_partial] = (
1.0 - self.demands[bs_idx].gather(dim=-1, index=t).sum()
)
self.cur_time_to_depot[bs_idx, num_partial] = self.time_to_depot[bs_idx, t[-1]]
# recalculate current time of vehicle
tm = self._recompute_cost(t, bs_... | |
# This code is an alternative implementation of the paper by
# <NAME>, <NAME>, and <NAME>. "Age Progression/Regression by Conditional Adversarial Autoencoder."
# IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2017.
#
# Date: Mar. 24th, 2017
#
# Please cite above paper if you use this code
#
from __... | |
import numpy as np
from pyuvdata import UVData
import matplotlib
from matplotlib import gridspec
import copy
def apply_random_flags(uvd, flag_frac, seed=None, inplace=False,
zero_flagged_data=False):
"""
Randomly flag a set of frequency channels. Flags are applied
on top of any existing flags, and are applied t... | |
(is_singlefile and self.ext is MULTIFILE_EXT) or (not is_singlefile and self.ext is not MULTIFILE_EXT):
raise ValueError('Inconsistent object definition : is_singlefile and self.ext should be consistent')
def __str__(self) -> str:
return self.get_pretty_location()
def get_pretty_file_mode(self):
"""
Utility met... | |
:py:class:`ndarray <numpy.ndarray>` of shape `(Q, Z)`
The columnized version of `X` (assumed to include padding)
X_shape : 4-tuple containing `(n_ex, in_rows, in_cols, in_ch)`
The original dimensions of `X` (not including padding)
W_shape: 4-tuple containing `(kernel_rows, kernel_cols, in_ch, out_ch)`
The dimensio... | |
<reponame>Borda/pyBPDL
"""
tools for registering images to reconstructed image using Atlas
SEE:
* http://insightsoftwareconsortium.github.io/SimpleITK-Notebooks/
* https://bic-berkeley.github.io/psych-214-fall-2016/dipy_registration.html
Copyright (C) 2017-2020 <NAME> <<EMAIL>>
"""
import logging
import time
# impor... | |
= node._moments.get_converter(moments_class)
except AttributeError:
from .constant import Constant
return Constant(
moments_class.from_values(node, **kwargs),
node
)
else:
node = converter(node)
converter = node._moments.get_instance_converter(**kwargs)
if converter is not None:
from .converters import NodeC... | |
)
# Create a log entry for the proposal
self.log_user_action(ProposalUserAction.ACTION_SEND_REFERRAL_TO.format(referral.id, self.lodgement_number, '{}({})'.format(user.get_full_name(), user.email)), request)
# Create a log entry for the organisation
if self.applicant:
self.applicant.log_user_action(ProposalUserAct... | |
<reponame>likun-stat/scalemixture_spline<filename>scratch.py
import os
os.chdir("/Users/LikunZhang/Desktop/PyCode/")
import scalemixture_py.integrate as utils
import scalemixture_py.priors as priors
import scalemixture_py.generic_samplers as sampler
import numpy as np
import cProfile
import matplotlib.pyplot as plt
f... | |
assumed
:return: list of follower objects
"""
followers = []
followers_batch = self.get_user_followers(username=username)
while len(followers_batch) > 0:
followers += followers_batch
followers_batch = self.get_user_followers(username=username)
return followers
def pin(self, board_id, image_url, description='... | |
<reponame>ashishpatel26/interpret<gh_stars>0
# Copyright (c) 2019 Microsoft Corporation
# Distributed under the MIT software license
# TODO: Add unit tests for internal EBM interfacing
from sys import platform
import ctypes as ct
from numpy.ctypeslib import ndpointer
import numpy as np
import os
import struct
import l... | |
def __init__(self, starred=None, all=None, category=None, drive_id=None, fields=None,
image_thumbnail_process=None, image_url_process=None, limit=None, marker=None, order_by=None, order_direction=None,
parent_file_id=None, status=None, type=None, url_expire_sec=None, video_thumbnail_process=None):
# starred
self.st... | |
<reponame>BrunoGomesCoelho/Eat-Move-Learn
from kaggle_environments.envs.hungry_geese.hungry_geese import Observation, Configuration, Action, adjacent_positions, \
row_col, translate, min_distance
from kaggle_environments import make
import gym
from gym import spaces
import torch as th
import torch.nn as nn
import to... | |
line in sys.stdin])
# Then iterate over it:
for line in full_stdin.splitlines():
print(line)
# Long Hand:
import sys
L = []
for line in sys.stdin:
L += [line]
full_stdin = "".join(L)
def option_2__raw_input():
"""If We're given line count:"""
# Longhand:
L = []
for _ in range(int(input())):
L += [inpu... | |
import argparse
import sys
import os
import fabric
import random
import json
import io
import yaml
import shutil
import subprocess
from github import Github
import validators
from invoke import UnexpectedExit
from configparser import ConfigParser
LOC_INSTALLER = {
'python3.6': {
'installer': 'pip',
'filename': 'r... | |
handling.
rpc = self._transport._wrapped_methods[
self._transport.update_certificate_map_entry
]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata(
(("certificate_map_entry.name", request.certificate_map_ent... | |
raise ValueError(
"Found kernel containing only non-finite values.\
Please increase kernel size")
median_corrected_arr = np.median(
kernel_cropped_arr[np.isfinite(kernel_cropped_arr)])
# Replacing bad data with finite median
projection[x_idx, y_idx] = median_corrected_arr
callback(arr.shape[0], 'Nonfinite med... | |
model which just
shifts the Lorentzian peak with a simple cosine by 2 MHz.
'''
if MC is None:
MC = self.instr_MC.get_instr()
s1 = swf.None_Sweep(name='Heterodyne Frequency',
parameter_name='Frequency',
unit='Hz')
s2 = swf.None_Sweep(name='Flux', parameter_name=fluxChan,
unit='A')
fluxcurrent = self.instr_Fl... | |
<filename>fhirclient/models/appointment.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/Appointment) on 2019-01-22.
# 2019, SMART Health IT.
from . import domainresource
class Appointment(domainresource.DomainResource):
"""
A
b
o... | |
<filename>MODULES_DATA/Discovery_SecuritySoftwareDiscovery_ListAVByTasklist/avlist.py
# -*- coding: utf-8 -*-
# @File : avList.py
# @Date : 2021/7/26
# @Desc :
avList_zh = {
"360tray.exe": "360安全卫士-实时保护",
"360safe.exe": "360安全卫士-主程序",
"ZhuDongFangYu.exe": "360安全卫士-主动防御",
"360sd.exe": "360杀毒",
"a2guard.exe": "a-squ... | |
from redux_tests.testRig import emptyHand, holding, inRegion, placedAndHolding, placed
from hpn.traceFile import debug
from util.planUtil import ObjGraspB, PoseD, ObjPlaceB
from mm_operators.mmGenGrasp import potentialGraspConfGen, graspConfHypGen
from redux_tests.testRig import typicalErrProbs
from redux_tests.testObj... | |
<reponame>mahabul123/diffractem<filename>diffractem/stream_parser.py<gh_stars>1-10
import pandas as pd
from io import StringIO
import numpy as np
import re
from typing import Union, Optional
BEGIN_GEOM = '----- Begin geometry file -----'
END_GEOM = '----- End geometry file -----'
BEGIN_CELL = '----- Begin unit cell --... | |
<reponame>heprom/pymicro
"""The dct module provide helpers functions to work with experimental diffraction contrast tomography data.
"""
import os
import h5py
import numpy as np
from scipy import ndimage
from matplotlib import pyplot as plt, cm
from pymicro.xray.experiment import ForwardSimulation
from pymicro.crystal.... | |
list(cs_100[1].data['GLON']), 'GLAT': list(cs_100[1].data['GLAT'])})
df_cs_100.to_csv(self.path + 'catalogs/' + 'cs_100' + '.csv', index=False)
df_cs_143 = pd.DataFrame(data={'RA': list(cs_143[1].data['RA']), 'DEC': list(cs_143[1].data['DEC']), 'GLON': list(cs_143[1].data['GLON']), 'GLAT': list(cs_143[1].data['GLAT']... | |
<filename>src/model.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
# Modifications Copyright 2017 <NAME>
#
# 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.apach... | |
import operator
import re
import sys
import sympy
import pyparsing
from chempy import Substance
from chempy import balance_stoichiometry
from chemsolve.element import Element
from chemsolve.element import SpecialElement
from chemsolve.compound import Compound
from chemsolve.compound import FormulaCompound
from chems... | |
<reponame>carbo-T/TF<filename>img_proc/multiThread.py
import tensorflow as tf
import numpy as np
import threading
import time
import os
import preprocessing
import mnist_inference
import matplotlib.pyplot as plt
# ********** queue operation ***********
def queue_op():
# FIFOQueue & RandomShuffleQueue
# maximum 2 in... | |
<gh_stars>0
""" XVM (c) www.modxvm.com 2013-2017 """
#####################################################################
# MOD INFO
XFW_MOD_INFO = {
# mandatory
'VERSION': '0.9.19.0.1',
'URL': 'http://www.modxvm.com/',
'UPDATE_URL': 'http://www.modxvm.com/en/download-xvm/',
'GAME_VERSIONS': ['0.9.19.0.1'],
#... | |
}}
will be rendered as:
.. code-block:: text
['a', 'b', 'c']
'''
ret = None
if isinstance(values, Hashable):
ret = set(values)
else:
ret = []
for value in values:
if value not in ret:
ret.append(value)
return ret
@jinja_filter('min')
def lst_min(obj):
'''
Returns the min value.
.. code-block:: jin... | |
is connected backwards
sectionID = k
_from = v["tonodeid"]
_to = v["fromnodeid"]
phases = list(v["phase"])
try:
api_source = PowerSource(model)
except:
pass
api_source.name = _from + "_src"
try:
api_source.nominal_voltage = (
float(source_equivalent_data["voltage"]) * 10 ** 3
)
except:
pass
try:
api... | |
settle.." % (self.hardwareDelay+3))
time.sleep(self.hardwareDelay+3)
def toggleLvSupplies(self):
currentState = self.app_main.pwr_card.lvEnableGet()
nextState = not currentState
self.app_main.pwr_card.lvEnableSet(nextState)
stateNow = self.app_main.pwr_card.lvEnableGet()
if nextState != None and s... | |
if name_kwargs.get('fixed') is not None:
param.var_dict[self.name] = name_kwargs['fixed'].copy()
return
def from_dict_to_vector(self, vector_list, var_dict, **kwargs):
vector_list.append(var_dict[self.name].flatten())
return
def from_vector_to_dict(self, var_dict, vector, vector_index, **kwargs):
n = kwargs[se... | |
<gh_stars>0
import gzip
import random
import re
import statistics
import subprocess
from distutils.spawn import find_executable
"""
Run doctests:
python3 -m doctest gplib.py
"""
#######################################################################
def graphprot_predictions_get_median(predictions_file):
"""
... | |
the visibilities from frequency axis onto delay (time) axis
using an IFFT. This is performed for noiseless sky visibilities, thermal
noise in visibilities, and observed visibilities.
Inputs:
pad [scalar] Non-negative scalar indicating padding fraction
relative to the number of frequency channels. For e.g., a
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.