input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<reponame>dashirn/FAST_RNN_JAX
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 29 16:30:31 2021
@author: dashirn
Train modular network on task primitives & task-specific readouts.
Dependcies: pickle, jax, numpy, rnn_build_modular_g, rnn_tasks
"""
import pickle
import jax.numpy as np
from jax i... | |
is_bailout_needed == "n":
game_end_height = int(rpc_connection.getinfo()["blocks"])
while True:
current_height = int(rpc_connection.getinfo()["blocks"])
height_difference = current_height - game_end_height
if height_difference == 0:
print(current_height)
print(game_end_height)
print(colorize("Waiting for next b... | |
i != len(spu.servers) -1:
servers += ','
sock.Success( servers )
def do_crutservers( self, sock, args ):
if len(sock.node.crutservers) == 0:
sock.Failure( SockWrapper.UNKNOWNPARAM, "CRUTClient %d doesn't have servers" % (sock.SPUid) )
return
crutservers = "%d " % len(sock.node.crutservers)
for i in range(len(... | |
get an error at plot-time.
if hasattr(tohist1, 'compressed'):
tohist1 = tohist1.compressed()
if hasattr(tohist2, 'compressed'):
tohist2 = tohist2.compressed()
# Compute 2-D histogram
hist, xedges, yedges = \
np.histogram2d(tohist1, tohist2, bins=b, weights=weights)
hist = hist.T
# Recover bin centers
bc = ... | |
Point(2,2)
>>> pl = Plane(Point(0,0,1), Vector(0,0,1))
>>> result = pt.project_3D(pl, 2)
>>> print(result)
Point(2.0,2.0,1.0)
"""
if coordinate_index==0:
point=plane.point_yz(self.x,self.y)
elif coordinate_index==1:
point=plane.point_zx(self.x,self.y)
elif coordinate_index==2:
point=plane.point_xy(self.... | |
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.contrib.postgres.search import SearchQuery
from django.contrib.postgres.search import SearchVector
from django.core.files.storage import get_storage_class
from django.db imp... | |
pool._reclaimed.append(new_d)
# We're inside GC!
# pool._append_to_queue is not useful because
# deque.append causes deadlock
else:
warnings.warn(UserWarning("DataPool: an object collected during cyclic garbage collection; discarded"))
# data is discarded
@staticmethod
def _check_cleanness(d, in_pool_ok=False)... | |
mars", u"%d. apríl",
u"%d. maí", u"%d. júní", u"%d. júlí", u"%d. ágúst",
u"%d. september", u"%d. október", u"%d. nóvember",
u"%d. desember"])
addFmt2('it', False, u"%%d %s", False)
addFmt1('ja', False, makeMonthList(u"%d月%%d日"))
addFmt2('jv', False, u"%%d %s", True)
addFmt2('ka', False, u"%%d %s")
addFmt1('ko', Fals... | |
<filename>auto_punch_a_card.py<gh_stars>1-10
# coding:utf-8
# Copyright (c) 2020 YBM.eli0t All rights reserved.
# Power by Eli0t
# 目前需要填写:
# 编号
# amap_key(获取位置和经纬度) 高德地图 API 的 key 使用API前您需先申请Key。若无高德地图API账号需要先申请账号。
# whoami_value(可以通过编号计算出,目前仅支持 1872 中队)
# X-CSRF-Token 变化情况未知
# cookie 一般不变化
import requests
import json... | |
< ranges[0] + ranges[1]:
random_angle += offset_angles[0]
else:
random_angle += offset_angles[1]
hue = ((reference_angle + random_angle) / 360) % 1
saturation = random.uniform(saturation_range[0], saturation_range[1])
luminance = lerp(luminance_range[0], luminance_range[1], i / (count - 1))
colours[i] = hsl_to_r... | |
'handles': 99,
'pass': 84,
'off_rebound': 36,
'dunk': 30
},
'defense': {
'def_rebound': 43,
'inside_defense': 32,
'post_defense': 32,
'outside_defense': 62,
'block': 45,
'steal': 66
},
'physical': {
'speed': 86,
'vertical': 81,
'strength': 37
}
}, tendencies={
'offense': {
'shoot_mid': 80,
'shoot_t... | |
<filename>WassersteinGAN/src/utils/data_utils.py
import cv2
import glob
import h5py
import imageio
import matplotlib.pylab as plt
import matplotlib.gridspec as gridspec
import numpy as np
import os
from scipy import stats
from keras.datasets import mnist, cifar10
from keras.optimizers import Adam, SGD, RMSprop
from ke... | |
FIXME: Should have more efficient open_tagfile() that
# does all checksums in one go while writing through,
# adding checksums after closing.
# Below probably OK for now as metadata files
# are not too large..?
checksums[SHA1] = checksum_copy(tag_file, hasher=hashlib.sha1)
tag_file.seek(0)
checksums[SHA256] = ... | |
= np.eye(self.bsize, dtype=dtype)
# return W
# return _initializer
def checker_init(self):
def _initializer(shape, dtype=np.float32, partition_info=None):
gate = np.empty(self.blocks, dtype=dtype)
for w, (c, k) in enumerate(self.updat_list):
gate[w] = (c & 1) ^ (k & 1) ^ 1
return gate
return _initializer
# g... | |
<gh_stars>1-10
"""
.. py:module:: modules
:synopsis: The module management
.. moduleauthor:: <NAME> <<EMAIL>>
This is the docstring of the :py:mod:`modules` module.
"""
from collections import namedtuple, defaultdict
import importlib as imp
import inspect
import os
import random
import string
import sys
import threa... | |
self.ax_table is not None:
self.ax_table_ref = model.TableM(self.ax_table)
if self.ath_table is not None:
self.ath_table_ref = model.TableM(self.ath_table)
if self.az_table is not None:
self.az_table_ref = model.TableM(self.az_table)
if self.ge_table is not None:
self.ge_table_ref = model.TableM(self.ge_table)
... | |
"""
Core functionality and main computation functions are defined here. There are
low level implementations:
* :func:`cross_correlate`
* :func:`cross_correlate_fft`
* :func:`auto_correlate`
* :func:`auto_correlate_fft`
* :func:`cross_difference`
* :func:`auto_difference`
Functions for calculating tau-dependent mean... | |
3, 1)
# Open to remove white holes
# masked = imopen(masked, 3, 2)
# masked = imfill(masked)
kernel_dilation = np.ones((5, 5), np.uint8)
masked = cv2.dilate(masked, kernel_dilation, iterations=2)
# Apply foreground mask (dilated) to the image and perform detection on that
# masked = cv2.bitwise_and(cv2.cvtColor... | |
}
},
}
# 'covsurver_prot_mutations': {
# '$regex': mut, '$options': 'i'
# },
query_this_week = query.copy()
query_prev_week = query.copy()
query_this_week['collection_date'] = {'$lt': today_date, '$gte': last_week_date}
query_prev_week['collection_date'] = {'$lt': last_week_date, '$gte': previous_week_date}
r... | |
from __future__ import print_function, division, absolute_import
import numpy as np
from scipy.misc import imsave, imread, imresize
from sklearn.feature_extraction.image import reconstruct_from_patches_2d, extract_patches_2d
from scipy.ndimage.filters import gaussian_filter
from keras import backend as K
import os
i... | |
else:
# print('empty table')
pass
# print(database.queued_queries)
# for query in database.queued_queries:
# print(query)
# database.query(query)
database.execute_queue()
# print(database.path)
return {'tables': newtables, 'output': output}
def addeditpartlist(d, output={'message': ''}):
from iiutilities ... | |
space
if rowCount > 12:
self.figure.subplots_adjust(hspace=0)
else:
self.figure.subplots_adjust(hspace=0.1)
axisRangeNumbers = (0, 1)
self.setAxisRange('x', axisRangeNumbers, 0)
# turn off grid
self.grid = False
class GraphColorGridLegend(Graph):
'''
Grid of discrete colored "blocks" where each block can ... | |
note::
:class: toggle
CAA V5 Visual Basic Help (2020-07-06 14:02:20.222384))
| o Func GetAntiAliasingOffsetInfo(CATBSTR ioAdminLevel,
| CATBSTR ioLocked) As boolean
|
| Retrieves information about the AntiAliasingOffset setting
| parameter.
| Refer to SettingController for a detailed description.
:param str... | |
model_version=expected['model_version'],
prediction_ids=ids,
prediction_labels=labels,
features=None,
feature_names_overwrite=None,
prediction_timestamps=None)
for _, bulk in records.items():
assert isinstance(bulk, public__pb2.BulkRecord)
for r in bulk.records:
assert isinstance(r, public__pb2.Record)
assert... | |
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-节点管理(BlueKing-BK-NODEMAN) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance ... | |
<gh_stars>1-10
import torch
import torch.nn as nn
import torch.nn.functional as F
import itertools
from util.image_pool import ImagePool
from .base_model import BaseModel
from . import networks
class ForkGANModel(BaseModel):
"""
This class implements the ForkGAN model, for learning image-to-image translation withou... | |
import numpy as np
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
assert torch.cuda.is_available()
cuda_device = torch.device("cuda") # device object representing GPU
#This model stands for MobileNet ImageNet
#model_id = 10 (regardless of the file name)
class custom_cn... | |
node.attrib, already_processed)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
return self
def buildAttributes(self, node, attrs, already_processed):
pass
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == ... | |
<filename>scripts/klf14_b6ntac_exp_0075_pipeline_v4_validation.py
"""
Validate pipeline v4:
* segmentation
* dmap (0056)
* contour (0070)
* classifier (0074)
* segmentation correction (0053) networks
"""
"""
This file is part of Cytometer
Copyright 2021 Medical Research Council
SPDX-License-Identifier: Apache-2.... | |
!= 0" % (node.offset,))
self.o()
self.o(" @property")
self.o(" def %s(self) -> typing_.Optional[bytes]:" % (uname))
self.output_doc(node, " ")
self.o(" if not self.has_%s:" % (uname))
self.o(" return None")
self.o(
" (o, s) = self._get_ptr%s(%d, scalgoproto.BYTES_MAGIC)"
% ("_inplace" if node.inplace else "", ... | |
"""
Hierarchical clustering (:mod:`scipy.cluster.hierarchy`)
========================================================
.. currentmodule:: scipy.cluster.hierarchy
These functions cut hierarchical clusterings into flat clusterings
or find the roots of the forest formed by a cut by providing the flat
cluster ids of each ... | |
<reponame>openamundsen/openamundsen
import loguru
from openamundsen import constants, errors, forcing, util
import pandas as pd
from pathlib import Path
import xarray as xr
def read_meteo_data(
meteo_format,
meteo_data_dir,
start_date,
end_date,
meteo_crs=None,
grid_crs=None,
bounds=None,
exclude=None,
inclu... | |
from __future__ import absolute_import
import random
import logging
from datetime import datetime
from time import time
from django.utils import timezone
from django.conf import settings
import sentry_sdk
from sentry_sdk.tracing import Span
from sentry_relay.processing import StoreNormalizer
from sentry import feat... | |
<reponame>googleapis/googleapis-gen<gh_stars>1-10
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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/LICENS... | |
CV scores
cv_trainmisclassifiedsamples.append(train[cv_pipeline.modelParameters['Logistic']['MisclassifiedSamples']])
cv_trainclasspredictions.append([*zip(train, cv_pipeline.modelParameters['Logistic']['ClassPredictions'])])
# TODO: add the roc curve interpolation in the fitting method
cv_trainroc_curve.append(cv... | |
lemma == 'vienas':
word = 'vienoms'
elif lemma.endswith('dešimtis'):
word = lemma[:-2] + 'ims'
elif lemma.endswith('etas') \
or (num.num_type == 'kiek'
and (lemma == 'šimtas' or lemma == 'milijonas' or lemma == 'milijardas')) \
or lemma == 'ketvertas':
return
elif lemma.endswith('as'):
if num.degree == 'aukšč... | |
from __future__ import absolute_import
from builtins import str
from builtins import range
from builtins import object
try:
from collections import OrderedDict # 2.7
except ImportError:
from sqlalchemy.util import OrderedDict
from ckan.lib import helpers as h
from logging import getLogger
import re
from . import he... | |
<reponame>adsharma/pyserde
import dataclasses
import decimal
import enum
import itertools
import logging
import pathlib
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Tuple
import pytest
import more_itertools
import serde
import serde.compat
from serde import asdict, astuple, deseri... | |
the same thing.
"""
if not context.MPI_DISTRIBUTABLE or serial:
return runActionsInSerial(o, r, cs, actions)
useForComputation = [True] * context.MPI_SIZE
if numPerNode != None:
if numPerNode < 1:
raise ValueError("numPerNode must be >= 1")
numThisNode = {nodeName: 0 for nodeName in context.MPI_NODENAMES}
for... | |
the number of returned results to this many.
:param str filter: Expression to filter the result set. Defaults to filter down to active instruments only, i.e. those that have not been deleted. Read more about filtering results from LUSID here https://support.lusid.com/filtering-results-from-lusid.
:param list[str] ins... | |
pdf_service = conf['PDF_SERVICE']
if pdf_service == 'DocRaptor':
from cla.models.docraptor_models import DocRaptor as pdf
elif pdf_service == 'MockDocRaptor':
from cla.models.docraptor_models import MockDocRaptor as pdf
else:
raise Exception('Invalid PDF service selected in configuration: %s' % pdf_service)
pdf_... | |
Shape_Writer(self.log,self.shapeOutFutureFilename,method_object.outputFutureDetailFieldsShape,self.boolAddShapeFields ,self.userFieldShapeMap, self.referentialSpaceWKT)
self.sendMessage("INFO","Create future - Shape File Output Handler")
else:
self.sendMessage("INFO","Process Cancel Request By User - Create Shape Fi... | |
<gh_stars>1-10
# @Author : <NAME>
# @Email : <EMAIL>
SimuData = \
{ 'Begin_Day_of_Month' : 1,
'Begin_Month' : 1,
'End_Day_of_Month' : 31,
'End_Month' : 12,
'SaveLogFiles' : False, #if True, computing folder is not removed thus all energyplus outpus files are preserved
#'FloorZoningLevel' : True, #1 zone per floor... | |
import re
import sys
sys.path.append('deps')
import glob
import serial
import subprocess
import time
import os
import zipfile
from collections import namedtuple
from os import listdir
from os.path import isfile, join
import platform
# Defaults
DEFAULT_VERSION = 'v1.1.0'
DEFAULT_CHOOSE_OPERATION = False
DEFAULT_INTERAC... | |
dictionary
Keyword arguments passed to plt.quiver()
Returns
-------
quiver : matplotlib.pyplot.quiver
Vectors of specific discharge.
"""
warnings.warn(
"plot_discharge() has been deprecated and will be replaced "
"in version 3.3.5. Use plot_vector() instead, which should "
"follow after postprocessing.get_s... | |
is not None:
self.receive_phone_num = m.get('receive_phone_num')
if m.get('auth_instance_biz_uuid') is not None:
self.auth_instance_biz_uuid = m.get('auth_instance_biz_uuid')
return self
class SendDasSmsResponse(TeaModel):
def __init__(
self,
req_msg_id: str = None,
result_code: str = None,
result_msg: str =... | |
# 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
# "License"); you may not use... | |
user.user_agent = request.user_agent
user.save()
if not service:
# TODO: check that return_to is a local url
redirect = return_to
else:
raise BadRequestError("Invalid service '%s'." % service)
if params.get('invitoken'):
confirm_invitation(request)
return {
'auth': True,
'redirect': redirect,
'csrf_token... | |
#!/usr/bin/env python3
"""A pipeline to extract repeat expansion variants from ClinVar XML dump. For documentation refer to README.md"""
from collections import Counter
import logging
import numpy as np
import pandas as pd
from eva_cttv_pipeline import clinvar_xml_utils
from . import biomart, clinvar_identifier_pars... | |
<gh_stars>0
##########################################################################
#
# Common code generation functions
#
# These functions are called from the target-specific code generators
#
##########################################################################
import re
import datetime
import glob
import ... | |
* self.t)
X0 += 0.00000000150 * math.cos(0.46939872247 + 104371.52614468009 * self.t)
X0 += 0.00000000166 * math.cos(0.65776448592 + 522.8212355773 * self.t)
X0 += 0.00000000149 * math.cos(4.09099834194 + 23889.0596157707 * self.t)
X0 += 0.00000000125 * math.cos(0.99047205683 + 65697.31390725628 * self.t)
X0 += 0.... | |
<reponame>vbisserie/elastalert2<filename>tests/alerters/pagerduty_test.py
import json
import mock
import pytest
from requests import RequestException
from elastalert.alerters.pagerduty import PagerDutyAlerter
from elastalert.loaders import FileRulesLoader
from elastalert.util import EAException
def test_pagerduty_a... | |
"4355 4452 4523",
45885: "4355 4452 4524",
45886: "4355 4452 4525",
45887: "4355 4452 4526",
45888: "4355 4452 4527",
45889: "4355 4452 4528",
45890: "4355 4452 4529",
45891: "4355 4452 4530",
45892: "4355 4452 4531",
45893: "4355 4452 4532",
45894: "4355 4452 4533",
45895: "4355 4452 4534",
45896: "4355 44... | |
<reponame>Jappenn/CCL
import tempfile
import numpy as np
from numpy.testing import (
assert_raises, assert_no_warnings, assert_almost_equal)
import pytest
import pyccl as ccl
def test_parameters_lcdm_defaults():
cosmo = ccl.Cosmology(
Omega_c=0.25,
Omega_b=0.05,
h=0.7,
A_s=2.1e-9,
n_s=0.96)
assert np.allclo... | |
from django.shortcuts import render, redirect
from django.utils.html import escape
from . import forms
from django.views.generic import TemplateView
from django.contrib.auth import logout, authenticate, login
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
im... | |
self.temp.append(float(vals[6]))
self.tide_grav.append(0.0)
self.airpress_grav.append(0.0)
class Survey(Chanlist):
"""
Survey reading dataset from recording files.
The instance of Survey class must be setted before send to Campaign class.
% 55555 一个闭合结束, one loop
% 99999 整个测量结束, one survey
% 44444 66666 一天内... | |
<reponame>googleinterns/advertiser-quality-from-sites
# Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | |
get average of vertex-level data within parcels
# set all NaN values to 0 before calling `_stats` because we are
# returning sums, so the 0 values won't impact the sums (if we left
# the NaNs then all parcels with even one NaN entry would be NaN)
currdata = np.squeeze(data[start:end, idx])
isna = np.isnan(currdata... | |
import ssl
import logging
import datetime
import pytz
from multidict import CIMultiDictProxy
from typing import List, Optional
from cryptoxlib.CryptoXLibClient import CryptoXLibClient, RestCallType
from cryptoxlib.clients.bitpanda import enums
from cryptoxlib.clients.bitpanda.exceptions import BitpandaRestException, B... | |
= list(iinc)
aiinc.extend(iisnc)
miianc = max(aiinc)
# Header
if np.isfinite(fill_value):
fval = str(fill_value)
else:
fval = 'NaN'
if header:
var, svar = _get_header(
f, head, sep, iinc, iisnc,
squeeze=squeeze,
fill=fill, fill_value=fval, sfill_value=sfill_value,
strip=strip, full_header=full_header,
tr... | |
<reponame>elemental-lf/docker-unoconv
import os
import subprocess
from collections import namedtuple
from io import BytesIO, SEEK_SET
from typing import ByteString, List, Optional, Tuple, BinaryIO
from PIL import Image
from fs import open_fs
from celery import Celery
from fs.errors import ResourceNotFound
app = Celer... | |
= (centroid[1] * self.j["transform"]["scale"][1]) + self.j["transform"]["translate"][1]
centroid[2] = (centroid[2] * self.j["transform"]["scale"][2]) + self.j["transform"]["translate"][2]
return centroid
else:
return None
def get_identifier(self):
"""
Returns the identifier of this file.
If there is one in m... | |
<reponame>Luojiahong/Pycker
# -*- coding: utf-8 -*-
"""
Pycker Viewer provides a GUI to visualize seismic traces and manually pick
first break arrival times.
Author: <NAME> <<EMAIL>>
License: MIT
"""
from matplotlib.figure import Figure
from matplotlib.gridspec import GridSpec
from matplotlib.ticker import FormatStr... | |
del_items(0x8007DD34)
SetType(0x8007DD34, "int GetTpY__FUs(unsigned short tpage)")
del_items(0x8007DD50)
SetType(0x8007DD50, "int GetTpX__FUs(unsigned short tpage)")
del_items(0x8007DD5C)
SetType(0x8007DD5C, "void Remove96__Fv()")
del_items(0x8007DD94)
SetType(0x8007DD94, "void AppMain()")
del_items(0x8007DE3C)
SetType... | |
'vcmpunord_ssd xmm8, xmm15, qword ptr [r8]')
Buffer = b'\xc4\x01\x83\xc2\x00\x14\x11\x11\x11\x11\x11\x11\x11\x11\x11'
myDisasm = DISASM()
myDisasm.Archi = 64
Target = create_string_buffer(Buffer,len(Buffer))
myDisasm.EIP = addressof(Target)
InstrLength = Disasm(addressof(myDisasm))
assert_equal(myDisasm.Argumen... | |
""" miscellaneous sorting / groupby utilities """
from collections import defaultdict
from typing import (
TYPE_CHECKING,
Callable,
DefaultDict,
Dict,
Iterable,
List,
Optional,
Tuple,
Union,
)
import numpy as np
from pandas._libs import algos, hashtable, lib
from pandas._libs.hashtable import unique_label_in... | |
0xa2, 0x22, 0xa0,
0x64, 0x42, 0x42, 0x4a, 0xa4, 0x66, 0x62, 0x28,
0x20, 0xb6, 0x22, 0xe6, 0x24, 0x04, 0x1f, 0x48,
0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x4f,
0xfe, 0... | |
'''
<NAME>
Python F-16 subf16
outputs aircraft state vector deriative
'''
# x[0] = air speed, VT (ft/sec)
# x[1] = angle of attack, alpha (rad)
# x[2] = angle of sideslip, beta (rad)
# x[3] = roll angle, phi (rad)
# x[4] = pitch angle, theta (rad)
# x[5] = yaw angle, psi (rad)
# x[6] = roll rate, P (rad/sec)
# x[7] = ... | |
= self.labels[:i] + new_labels + self.labels[i + 1:]
self.data = np.reshape(self.data, new_shape)
self.labels = new_labels
def contract_internal(self, label1, label2, index1=0, index2=0):
"""By default will contract the first index with label1 with the
first index with label2. index1 and index2 can be specified... | |
<reponame>oleksiilytvyn/grailkit
# -*- coding: UTF-8 -*-
"""
Implements access to bible files.
Grail bible format consists of standard grail DNA format plus
two additional tables: `books` and `verses`.
SQL structure:
.. code:: sql
CREATE TABLE books
(id INTEGER PRIMARY KEY AUTOINCREMENT,
osisid TEXT,
... | |
""" imported math and Mathematics class """
import math
class Mathematics():
"""This class is made for making math calculations"""
@classmethod
def print_menu(cls):
"""Printing the menu"""
print("\n\n***** Mathematical Operations *****")
print("1- Factorial\n2- Multiplication Table\n3- Fibonacci\n4- Sum up to giv... | |
<filename>tensorflow_datasets/text/civil_comments.py<gh_stars>0
# coding=utf-8
# Copyright 2022 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www... | |
<filename>nerblackbox/modules/ner_training/metrics/ner_metrics.py
from dataclasses import dataclass
from dataclasses import asdict
from typing import List, Tuple, Callable
import numpy as np
from sklearn.metrics import accuracy_score as accuracy_sklearn
from sklearn.metrics import precision_score as precision_sklearn
... | |
# Copyright 2015 OpenStack Foundation
# 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 l... | |
import argparse
import gc
import math
import os
from argparse import Namespace
from datetime import timedelta
from multiprocessing import cpu_count
from typing import List
import joblib
import numpy as np
import pandas as pd
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional a... | |
None
self.ClusterIp = None
self.NodePort = None
self.CpuLimit = None
self.MemLimit = None
self.AccessType = None
self.UpdateType = None
self.UpdateIvl = None
self.ProtocolPorts = None
self.Envs = None
self.ApplicationName = None
self.Message = None
self.Status = None
self.MicroserviceType = None
self.CpuR... | |
<reponame>justyncw/STAR_MELT<filename>utils_saha_av.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 10 11:23:41 2021
@author: jcampbellwhite001
"""
from numpy import *
from scipy.special import gamma
from matplotlib import *
from matplotlib.pyplot import *
import numpy as np
import pandas as ... | |
<filename>ixian/task.py
# Copyright [2018-2020] <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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | |
# -*- coding: utf-8 -*-
"""
Keras (with Tensorflow) re-implementation of TP-GAN.
Main part of this code is implemented reffering to author's pure Tensorflow implementation.
https://github.com/HRLTY/TP-GAN
original paper
<NAME>., <NAME>., <NAME>., & <NAME>. (2017). Beyond face rotation: Global and local perception gan ... | |
<gh_stars>10-100
import qctests.ICDC_aqc_01_level_order as ICDC
import qctests.ICDC_aqc_06_n_temperature_extrema as ICDC_nte
import util.testingProfile
import util.main as main
import numpy as np
##### ICDC number of temperature extrema.
##### --------------------------------------------------
class TestClass:
para... | |
= status
ret['cbfired'] = cbfired
ret['elapsed'] = int(time.time() - cmdstart)
if verbose:
self.debug("done with exec")
except CommandTimeoutException, cte:
self.lastexitcode = SshConnection.cmd_timeout_err_code
elapsed = str(int(time.time() - start))
self.debug("Command (" + cmd + ") timeout exception after " ... | |
<reponame>inetrg/spoki<filename>evaluation/src/cse/logs/phasematcher.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
These classes reads JSON data from a variety sources and parse them into
objects that support a `from_dict` method.
"""
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__copyright__ = "Copyright 2... | |
flags["ZF"]:
return next_addr
if opcode == "jne" and not flags["ZF"]:
return next_addr
if opcode == "jg" and not flags["ZF"] and (flags["SF"] == flags["OF"]):
return next_addr
if opcode == "jge" and (flags["SF"] == flags["OF"]):
return next_addr
if opcode == "ja" and not flags["CF"] and not flags["ZF"]:
return... | |
<filename>wtfile.py
from functools import partial
import fnmatch
import glob
import os
import re
import stat
import shutil as sh
import sys
VERBOSE = False
__print = print # pylint: disable=invalid-name
def print(*_, **__):
verbose = __.pop('verbose', True)
if VERBOSE or verbose:
__print(*_, **__)
def TODO(*_... | |
common.Checkpointer(
ckpt_dir=os.path.join(self._train_dir, 'policy'),
max_to_keep=self._max_ckpt,
behave_metrics=metric_utils.MetricsGroup(
self._behavior_metrics + [self._iteration_metric],
'behavior_metrics'),
**all_iterable)
else:
self._rb_checkpointer = tf.train.CheckpointManager(
tf.train.Checkpoint(repl... | |
"""test_mainmodel.py - tests the mainmodel module
<NAME> (TRI/Austin, Inc.)
"""
__author__ = '<NAME>'
import models.mainmodel as model
import models.dataio as dataio
import models.abstractplugin as abstractplugin
import models.config as config
import models.ultrasonicgate as ultrasonicgate
import controllers.pathfin... | |
import re
import pymongo
from bson.dbref import DBRef
from pymongo.read_preferences import ReadPreference
from mongoengine import signals
from mongoengine.base import (
BaseDict,
BaseDocument,
BaseList,
DocumentMetaclass,
EmbeddedDocumentList,
TopLevelDocumentMetaclass,
get_document,
)
from mongoengine.common ... | |
<filename>supersid/supersid_plot.py<gh_stars>10-100
#!/usr/bin/python
'''
supersid_plot
version: 1.3.1 enhanced for Python 2.7 and 3.3
Original Copyright: Stanford Solar Center - 2008
Copyright: <NAME> - 2012
Support one to many files as input, even in Drag & Drop
Draw multi-stations graphs
Offer the possibili... | |
import discord
import asyncio
import os
import random
import traceback
import sys
from datetime import datetime, timedelta
from io import BytesIO, StringIO
from config import *
from settings import *
import json
import urllib.request
################## START INIT #####################
client = discord.Client()
session... | |
Bots can currently send audio
files of up to 50 MB in size, this limit may be changed in the future.
For backward compatibility, when both fields title and description are
empty and mime-type of the sent file is not "audio/mpeg", file is sent
as playable voice message. In this case, your audio must be in an .ogg
... | |
evt
def create_aliyun_vpc_virtualrouter_entry_remote(dst_cidr_block, vrouter_uuid, vrouter_type, next_hop_type, next_hop_uuid, session_uuid=None):
action = api_actions.CreateAliyunVpcVirtualRouterEntryRemoteAction()
action.dstCidrBlock = dst_cidr_block
action.vRouterUuid = vrouter_uuid
action.vRouterType = v... | |
<filename>ebttools/gui/main.py
# -*- coding: utf-8 -*-
"""
Copyright (c) 2016 <NAME>
Main GUI class of the EBT evaluation program
Program to evaluate EBT-films
A scannend image can be loaded and an area of interest selected
From that area a dose distrubtion can be calculated using a calibration file
and that... | |
None: # pragma: no cover
# This really shouldn't be possible since _register_subcommands would prevent this from happening
# but keeping in case it does for some strange reason
raise CommandSetRegistrationError('Could not find argparser for command "{}" needed by subcommand: {}'
.format(command_name, str(method)))
... | |
2 * np.pi * self._l * x)
c = sum(a * b) / 2 * self.dim + (2 ** (self.dim - 1)) * (1 + self._alpha)
return c
def f_bowl(self, x):
"Quadratic centre function"
a = 20 * (x) ** 2
c = sum(a)
return c
def f_quad(self, x):
"Combination of different x^n-functions"
c = np.zeros(self._q)
for i in range(self._q):
x... | |
<filename>VSR/Backend/TF/Framework/LayersHelper.py<gh_stars>1000+
"""
Copyright: <NAME> 2017-2020
Author: <NAME>
Email: <EMAIL>
Created Date: Sep 5th 2018
commonly used layers helper
"""
from VSR.Util import to_list
from .. import tf
from ..Util import (
SpectralNorm, TorchInitializer, pixel_shift, pop_dict_wo_keyer... | |
# Copyright 2018 GoDaddy
#
# 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... | |
<reponame>verkaik/modflow6-parallel
# tests to ability to run flow model first followed by transport model
import os
import shutil
import numpy as np
try:
import pymake
except:
msg = 'Error. Pymake package is not available.\n'
msg += 'Try installing using the following command:\n'
msg += ' pip install https://git... | |
<filename>accbpg/functions.py<gh_stars>10-100
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import numpy as np
class RSmoothFunction:
"""
Relatively-Smooth Function, can query f(x) and gradient
"""
def __call__(self, x):
assert 0, "RSmoothFunction: __... | |
# If successfully sent:
if bytes_sent == bytes_total:
# Show a confirmation to the user so they know the job was sucessful and provide the option to switch to
# the monitor tab.
self._success_message = Message(
i18n_catalog.i18nc("@info:status", "Print job was successfully sent to the printer."),
lifetime=5, dism... | |
diagonal cases:
# first case: increasing the row number and the column number:
elif i + 4 < len(board) and j + 4 < len(board):
temp = []
for a in range(5):
temp.append(board[i+a][j+a])
if (temp == ["b"] * 5):
return 1, i, j
if (temp == ["w"] * 5):
return 0, i, j
# second case: increasing the row num... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.