input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import random, copy
import matplotlib.cm as cm
import itertools
import scipy.stats
import math
import statistics
import pysan.multisequence as pysan_ms
from itertools import combinations
random.seed('1<PASSWORD>')
def gene... | |
"""
Train utils
**************************************
Losses, training loops and helper functions used during training.
"""
from pennylane import numpy as np
import autograd.numpy as np
from autograd.numpy import exp
import itertools
import time
def hinge_loss(labels, predictions, type='L2'):
"""
Args:
labels:
... | |
# -*- coding: utf-8 -*-
from __future__ import print_function
import abc
import copy
import functools
import hashlib
import os
import pathlib2
from .._protos.public.modeldb.versioning import Dataset_pb2 as _DatasetService
from ..external import six
from .._internal_utils import (
_file_utils,
_request_utils,
_u... | |
the replay-memory.
# These have HIGH estimation errors for the Q-values.
idx_hi = np.random.choice(self.idx_err_hi,
size=self.num_samples_err_hi,
replace=False)
# Combine the indices.
idx = np.concatenate((idx_lo, idx_hi))
# Get the batches of states and Q-values.
states_batch = self.states[idx]
q_values_bat... | |
<filename>sdk/python/pulumi_exoscale/instance_pool.py
# 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 warnings
import pulumi
import pulumi.runtime
from typing import Any, Mappi... | |
#
# COPYRIGHT (C) 2012-2013 TCS Ltd
#
"""
.. module:: snpdb
:platform: Unix, Windows, MacOSX
:synopsis: Class for accessing SNP information from an sqlite
database
.. moduleauthor:: <NAME> (<EMAIL>); modified by <EMAIL>
Class for accessing variant information from an sqlite database. This is
primarily intended for... | |
file for later
execution.
If you have a Windows system, often these executable machine language programs have a
suffix of .exe or .dll which stand for executable and dynamic link
library respectively. In Linux and Macintosh, there is no suffix that uniquely marks
a file as executable.
If you were to open an executabl... | |
based on managed rules.
"""
return pulumi.get(self, "tag_key_scope")
@tag_key_scope.setter
def tag_key_scope(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "tag_key_scope", value)
@property
@pulumi.getter(name="tagValueScope")
def tag_value_scope(self) -> Optional[pulumi.Input[str]]:
"""
The ru... | |
1.1155787450000001)]),
('P',
[(5.5831385290000002, -0.1283927634),
(2.174045204, 0.5852047641),
(0.95702005089999997, 0.54394420399999999)]),
('D',
[(5.5831385290000002, 0.12506621379999999),
(2.174045204, 0.66867855769999995),
(0.95702005089999997, 0.30524682450000001)]),
('S',
[(0.62358164199999999, -0.3842... | |
<gh_stars>0
#-*- encoding: utf-8 -*-
#
# Copyright (c) 2013, 2014, 2017 NORDUnet A/S
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above c... | |
: { stpair : { path1 : %x, path2: %y, ...}}}
#or { alg : { stpair : { path1 : [%x, di,...] , path2 : [%y, dj,...], ...} ... } ... }
algstpathlen={}
for d in Zless1:#demands:
#TODO analysis path utilization and when Z<1 we can some how find the relationship
#between optimal link using for each s-t pair compared wit... | |
<filename>coherence/backends/gstreamer_renderer.py
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2006,2007,2008,2009 <NAME> <<EMAIL>>
from sets import Set
from twisted.internet import reactor, defer
from twisted.internet.task import LoopingCall
from twisted.python impo... | |
0.354971],
[0.190367, 0.039309, 0.361447],
[0.197297, 0.038400, 0.367535],
[0.204209, 0.037632, 0.373238],
[0.211095, 0.037030, 0.378563],
[0.217949, 0.036615, 0.383522],
[0.224763, 0.036405, 0.388129],
[0.231538, 0.036405, 0.392400],
[0.238273, 0.036621, 0.396353],
[0.244967, 0.037055, 0.400007],
[0.251620, ... | |
# -*- coding: utf-8 -*-
# Copyright 2017 Google LLC 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 ... | |
<gh_stars>1-10
# django-openid-auth - OpenID integration for django.contrib.auth
#
# Copyright (C) 2009-2010 Canonical Ltd.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must ret... | |
# Copyright 2019 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | |
import os
import settings
import subprocess
import shlex
from logger import Logger
'''Wrapper around rdiff-backup
This module provides facilites for centrally managing a large set of
rdiff-backup backup jobs. Backup job management is built around common tools
like cron, run-parts, and xargs. The base features includ... | |
from __future__ import annotations # postpone evaluation of annotations
import logging
from typing import Any, Dict, List, Optional, Tuple
import cv2
import numpy as np
import numpy.typing as npt
from pyquaternion import Quaternion
from scipy import ndimage
from scipy.spatial.transform import Rotation as R
from sqlal... | |
<reponame>zerorock1312/lt-maker-master
from app.constants import WINWIDTH, WINHEIGHT, TILEX, TILEY
from app.utilities import utils
from app.sprites import SPRITES
from app.engine.sound import SOUNDTHREAD
from app.data.database import DB
from app.engine import engine, image_mods
from app.engine.state import MapState
fr... | |
= np.zeros(indices.shape[1])
x_com, y_com, z_com = center_of_mass(plane)
for point in range(indices.shape[1]):
dist[point] = np.sqrt(
(indices[0, point] - x_com) ** 2
+ (indices[1, point] - y_com) ** 2
+ (indices[2, point] - z_com) ** 2
)
median_dist = np.median(dist)
if debugging:
gu.scatter_plot(
np.asarra... | |
+ browse_string) # if not, assume that it is a URL without protcol and add it
browser_msg = "glue browse [ " + browse_string + " ] complete\n"
self.view.run_command('glue_writer', {'text': browser_msg, 'command': glue_command, 'exit': False})
else:
browser_error_msg = "Please enter a URL or local filepath after the... | |
import torch
from collections import OrderedDict
import json
import math
import config as cfg
import ipeps.ipeps as ipeps
class IPEPS_U1SYM(ipeps.IPEPS):
def __init__(self, sym_tensors, coeffs, vertexToSite=None, lX=None, lY=None, \
peps_args=cfg.peps_args, global_args=cfg.global_args):
r"""
:param sym_tensors: li... | |
# Copyright 2016 <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 agreed to in writing, software
... | |
take up the full area."""
return self.SetFlag(self.optionMaximized, True)
def Minimize(self):
"""
Makes the pane minimized in a L{AuiToolBar}.
Clicking on the minimize button causes a new L{AuiToolBar} to be created
and added to the frame manager, (currently the implementation is such that
panes at West will... | |
please pass async_req=True
>>> thread = api.v1_departments_id_history_get_with_http_info(id, async_req=True)
>>> result = thread.get()
:param id: instance id of department history record (required)
:type id: str
:param page:
:type page: int
:param page_size:
:type page_size: int
:param sort: Sorting criteria... | |
# Copyright 2014 Google Inc. All Rights Reserved.
"""Command for creating instances."""
import collections
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.compute.lib import addresses_utils
from googlecloudsdk.compute.lib import base_classes
from googlecloudsdk.compute.lib import constants
from goog... | |
| ord(self.co.code[index + 3])
def nextsignedword(self):
return shortmask(self.nextword())
def opcode_0x00(self):
"nop"
# JVMS: Push null (== None)
def opcode_0x01(self):
"aconst_null"
self.stack.push(None)
def opcode_0x02(self):
"iconst_m1"
self.stack.push(-1)
def opcode_0x03(self):
"iconst_0"
self.... | |
'num_filters' : 128},
'bypass': 4},
2 : {'deconv' : {'filter_size' : 3, 'stride' : 2, 'num_filters' : n_classes},
'bypass': [0,1]},
}
}
def cfg_mom_flat_concat(n_classes, use_cond=False, method='sign', nonlin='relu'):
return {
'use_cond': use_cond,
# ONLY USED IF use_cond = True!!!
'cond_scale_factor': 4,
'co... | |
= color;
} else {
discard;
}
}
"""
}
_Margins = namedtuple('Margins', ('left', 'right', 'top', 'bottom'))
# Margins used when plot frame is not displayed
_NoDisplayMargins = _Margins(0, 0, 0, 0)
def __init__(self, margins):
"""
:param margins: The margins around plot area for axis and labels.
:type marg... | |
<reponame>py-sdl/py-sdl2
import os
import sys
import ctypes
import pytest
from io import BytesIO
import sdl2
if sys.version_info[0] >= 3:
byteify = bytes
stringify = lambda x, enc: x.decode(enc)
else:
byteify = lambda x, enc: x.encode(enc)
stringify = lambda x, enc: str(x)
@pytest.fixture
def testfile_path():
t... | |
<gh_stars>1000+
"""Conll parser"""
import re
import argparse
import time
import os
import io
import pickle
import spacy
import numpy as np
from tqdm import tqdm
from neuralcoref.train.compat import unicode_
from neuralcoref.train.document import (
Mention,
Document,
Speaker,
EmbeddingExtractor,
MISSING_WORD,
... | |
the dataframe ################
if 'vbat' not in df.columns.values:
raise ValueError("This function requires battery voltage in the loaded dataframe for contextual plotting")
################# Make sure the model is in eval mode ################
model.eval()
################### Take the specific action rnage! ###... | |
<filename>easyawscli.py
#!/usr/bin/python3
from os import system, name
import boto3
from botocore.exceptions import ClientError
import getpass
import requests
# from SecureString import clearmem
source_code_url = "https://github.com/navilg/easyawscli"
def main_menu():
print("\n\n---Main Menu---\n")
print("0. Logou... | |
for name, ext in required_fields:
field = cls.__fields__[name]
ext_field = cls.__fields__[ext]
value = values.get(field.alias, _missing)
if value not in (_missing, None):
continue
ext_value = values.get(ext_field.alias, _missing)
missing_ext = True
if ext_value not in (_missing, None):
if isinstance(ext_value,... | |
= scale_data_1[loc_mask]
if self.scale_mode == 'linear':
scale_space -= min_scale ## smallest value is 0
scale_space *= 1.0/( max_scale - min_scale ) ## largest value is 1
else: # log
scale_space *= 1.0/min_scale ## smallist is 0
np.log(scale_space, out=scale_space)
scale_space *= 1.0/np.log( max_scale/min_scal... | |
#!/usr/bin/python
# -*- coding: utf-8 -*-
DOCUMENTATION = '''
---
module: oracle_asmdg
short_description: Manage diskgroups in an Oracle database
description:
- Manage diskgroups in an Oracle database
version_added: "2.1.0.0"
options:
name:
description:
- The name of the diskgroup
required: true
default: No... | |
for scope in cmds_formatted:
permissions = {}
new_cmds = cmds_formatted[scope]
existing_cmds = await self.req.get_all_commands(guild_id=scope)
existing_by_name = {}
to_send = []
changed = False
for cmd in existing_cmds:
existing_by_name[cmd["name"]] = model.CommandData(**cmd)
if len(new_cmds) != len(existing_... | |
= parser.get_metadata('ascii')
return parser
def parse(self):
line_no = 0
section_line_no = 0
for line in self.voxfile:
section_line_no += 1
line_no += 1
debug().current_line_num = line_no
line = line.strip()
if line.startswith('//'):
continue
if line.startswith('#'):
token_state = self.State.from_to... | |
<reponame>gmr/dynamodb-backup
#!/usr/bin/env python3
"""
Backup DynamoDB to CSV or Avro
"""
import argparse
import base64
import csv
import datetime
import gzip
import io
import json
import logging
import multiprocessing
import pathlib
import queue
import sys
import tempfile
import time
import typing
from urllib impor... | |
same length as the paths), fscan will assign a different integration
time to each acquisition point.
-If integ_time is positive, it specifies seconds and if negative, specifies
monitor counts.
IMPORTANT Notes:
-no spaces are allowed in the indepvar string.
-all funcs must evaluate to the same number of points
... | |
<filename>Assistant.py
import pyttsx3 #pip install pyttsx3
import speech_recognition as sr #pip install speechRecognition
import datetime
import wikipedia #pip install wikipedia
import webbrowser
import os
import smtplib
import requests
import json
import wolframalpha
import subprocess
import wolframalpha
i... | |
# Copyright 2017 The TensorFlow Authors. 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 ... | |
" + outdirfile + " -h " + size + " -D -b '#ffffff'"
fileonweb = '/get?image=' + outfile
if format == 'shapefile':
thisfilter = year + '_' + code + '_'
infile = year + '_' + code + '_' + 'tmp.json'
outfile = year + '_' + code + '_' + 'tmp.shp'
indirfile = imagepathloc + '/' + infile
outdirfile = imagepathloc + '... | |
# -*- coding:utf-8 -*-
import os
import time
import six
import eventlet
import cPickle
import contextlib
import mysql
import mysql.connector
from simpleutil.config import cfg
from simpleutil.log import log as logging
from simpleutil.utils.systemutils import ExitBySIG
from simpleutil.utils.systemutils import UnExceptE... | |
'''
Original repository:
https://github.com/eriklindernoren/PyTorch-YOLOv3
https://github.com/junsukchoe/ADL
'''
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.pa... | |
physics" and other longitudinal studies (where we ask you to come back for more than one session), we'll be collecting enough data to give you a report of your child's responses after you complete all the sessions. Because this is a fairly labor-intensive process (we generally have two undergraduates watch each video a... | |
<gh_stars>100-1000
"""Variables common across modules"""
# pylint: disable=too-many-lines
import os
import ssl
import string
import sys
import platform
import re
GAM_AUTHOR = '<NAME> <<EMAIL>>'
GAM_VERSION = '6.22'
GAM_LICENSE = 'Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0)'
GAM_URL = 'https://jayl... | |
#!/usr/bin/env python3
# *******************************************************
# Copyright (c) VMware, Inc. 2020. All Rights Reserved.
# SPDX-License-Identifier: MIT
# *******************************************************
# *
# * DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
# * WARRANTIES OR CONDITI... | |
h = ((c - f) / g) * e + d
mydict['layers_module1_1/resnet_block2_0_2/resnet_unit2_5/conv_bn_relu1_1/conv_bn1_0/conv1_0/weights:0'] = b
mydict['layers_module1_1/resnet_block2_0_2/resnet_unit2_5/conv_bn_relu1_1/conv_bn1_0/batchnorm1_0/BatchNorm/gamma:0'] = e
mydict['layers_module1_1/resnet_block2_0_2/resnet_unit2_5/co... | |
<reponame>nikunjpansari/stochastic-optimization
"""
Clinical Trials Policy class
<NAME> (c) 2018
Adapted from code by <NAME> (c) 2018
"""
from collections import namedtuple
import numpy as np
from scipy.stats import binom
import scipy
import math
import pandas as pd
import copy
from ClinicalTrialsModel import Clinica... | |
<gh_stars>1-10
# Copyright (c) 2013-2020 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditi... | |
#
# Copyright (c) 2008-2015 Citrix Systems, 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 ... | |
# INTERNAL_ONLY_PROPERTIES defines the properties in the config that, while settable, should
# not be documented for external users. These will generally be used for internal test or only
# given to customers when they have been briefed on the side effects of using them.
INTERNAL_ONLY_PROPERTIES = {
"__module__",
"__... | |
at the start
handler.assert_allclose(
funcs["DVCon1_volume_constraint_0"], 4.0 * np.ones(1), name="volume_base", rtol=1e-7, atol=1e-7
)
def test_4(self, train=False, refDeriv=False):
"""
Test 4: LeTe Constraint using the ilow, ihigh method
There's no need to test this with the rectangular box
because it doesn... | |
<reponame>phoenix-xhuang/ymir
from enum import Enum
import json
import os
import shutil
import time
from typing import Any, Callable, Dict, List, Optional, Tuple
import uuid
import xml.etree.ElementTree as ElementTree
import lmdb
from PIL import Image, UnidentifiedImageError
from mir.protos import mir_command_pb2 as ... | |
# Reverse photography
##h3D-II sensor size
# 36 * 48 mm, 0.036 x 0.048m
## focal length
# 28mm, 0.028m
## multiplier
# 1.0
from skimage import io
import matplotlib.pyplot as plt
import numpy as np
import cv2
from scipy.spatial import distance
import shapefile as shp
def buildshape(corners, filename):
"""build a s... | |
<reponame>harsh306/rl-project<filename>src/coinrun/trainers/batched_minecraft_mix.py
import os
import logging
import glob
import re
import math
import time
import csv
import multiprocessing
from queue import Empty
from collections import defaultdict
import pickle
import numpy as np
import random
logger = logging.getL... | |
import torch
import numpy as np
import random
import argparse
from utils import plot_utils, eval_utils
from collections import defaultdict
import matplotlib.pyplot as plt
import matplotlib.patheffects as pe
from sklearn.neighbors import KernelDensity
from scipy.stats import gaussian_kde
import pandas as pd
hyperpa... | |
== CONTAINER_FORMAT_HYBRID_VM:
clients = self._get_hybrid_service_clients_by_node(provider_node)
try:
is_docker_service_up = self._clients_wait_hybrid_service_up(clients)
except Exception, e:
LOG.error('docker is not start, exception: %s' % traceback.format_exc(e))
raise e
if is_docker_service_up:
try:
self.... | |
from datetime import datetime, timedelta
from os import PathLike
from pathlib import Path
from typing import Collection
import fiona
import fiona.crs
import numpy
import rasterio
from rasterio.enums import Resampling
import scipy.interpolate
import xarray
import PyOFS
from PyOFS import CRS_EPSG, LEAFLET_NODATA_VALUE,... | |
<gh_stars>10-100
import os
import csv
import imageio
from PIL import Image
import numpy as np
from scipy import stats
import torch
import torch.nn.functional as F
from torchvision.utils import save_image
from myGym.vae.vis_helpers import (read_loss_from_file, add_labels, make_grid_img,
FPS_GIF, concatenate_pad)
import... | |
<filename>affine_model_with_default.py<gh_stars>0
import numpy as np
import itertools
from scipy.integrate import quad, IntegrationWarning
"""
risk-free: delta + S(a_m X_m) + S(c_i Y_i)
spread: spread + S(b_m X_m) + S(d_i Y_i)
"""
def beta_m(alpha_m, sigma_m, a_m, b_m):
"""
Implements Eq. from Nawalka... | |
from math import sqrt
from numpy import (array, unravel_index, nditer, linalg, random, subtract,
power, exp, pi, zeros, arange, outer, meshgrid, dot,
logical_and)
from collections import defaultdict
from warnings import warn
# for unit tests
from numpy.testing import assert_almost_equal, assert_array_almost_equal
f... | |
ID: 22062
m = p7.match(line)
if m:
ser_dict['session_id'] = int(m.groupdict()['session_num'])
continue
# IKEv2 SA: local 1.1.1.1/4500 remote 172.16.58.3/38452 Active
m = p8.match(line)
if m:
count = 0
ike_version = m.groupdict()['version']
ikev2_dict = ser_dict.setdefault(ike_version, {})
ikev2_dict['local... | |
3]])
assert quantity.boundary_values.shape[0] == len(self.mesh4.boundary)
def test_set_values(self):
quantity = Quantity(self.mesh4)
# get referece to data arrays
centroid_values = quantity.centroid_values
vertex_values = quantity.vertex_values
quantity.set_values([[1, 2, 3], [5, 5, 5], [0, 0, 9], [-6, 3, 3]... | |
"""
PyAltmetric
This is a python wrapper for the Altmetric API.
For more information on the Altmetric API visit http://api.altmetric.com/.
Some pieces of this library were inspired by or derived from the altmetric api
wrapper altmetric.py which is licensed under the MIT open source license.
If you display Altmetric ... | |
str(i + 1)
hostname = self._input("Hostname%s" % dns_message, default,
datatype="hostname")
if dns_domain is not None and not hostname.endswith(dns_domain):
hostname += "." + dns_domain
component["hostname"] = hostname
return hostname
def _setup_ip_addresses(self, deployment, i, hostname, is_vsc):
component... | |
'_')
s = s.replace('\xc0', '_')
s = s.replace('\xd9', '_')
s = s.replace('\xda', '_')
s = s.replace('\xf8', '_')
return s
########################################################################
# handlers.
########################################################################
def _handler_command_run_tes... | |
of all images, replace ``10%`` of all pixels with either the
value ``0`` or the value ``255`` (same as in the previous example). For
the other ``50%`` of all images, replace *channelwise* ``10%`` of all
pixels with either the value ``0`` or the value ``255``. So, it will be
very rare for each pixel to have all chan... | |
int
:param RulePaths: 需要鉴权的url路径列表。
:type RulePaths: list of str
"""
self.KeyAlpha = None
self.KeyBeta = None
self.KeyGamma = None
self.SignParam = None
self.TimeParam = None
self.ExpireTime = None
self.TimeFormat = None
self.FailCode = None
self.ExpireCode = None
self.RulePaths = None
def _deserialize(... | |
import os
import glob
import scipy
import paddle
import random
import numpy as np
import json
import paddle.vision.transforms.functional as F
from paddle.io import DataLoader,Dataset
from paddle.vision import transforms
from PIL import Image
# from scipy.misc import imread
import skimage
from skimage.feature import can... | |
# 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... | |
<filename>qiskit/visualization/text.py
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.a... | |
= t
if hasattr(self, '_set'):
self._set()
def _unset_member_vnf_index(self):
self.__member_vnf_index = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="member-vnf-index", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='urn:etsi:osm:y... | |
Linearize non-linear problem """
H = zeros((param_size, param_size))
g = zeros(param_size)
# Form Hessian and R.H.S of Gauss newton
for _, factor in self.factors.items():
factor_params = [params[pid].param for pid in factor.param_ids]
r, jacobians = factor.eval(factor_params)
# Form Hessian
nb_params = len(fa... | |
dropcol_importances(rf, X_train, y_train)
"""
if X_valid is None: X_valid = X_train
if y_valid is None: y_valid = y_train
model_ = clone(model)
model_.random_state = 999
model_.fit(X_train, y_train)
if callable(metric):
baseline = metric(model_, X_valid, y_valid, sample_weights)
else:
baseline = model_.score(... | |
'Zerg',
'type': 'Upgrade',
'is_morph': False,
},
'DehakaPrimalWeaponsLevel2': {
'build_time': 190,
'built_from': ['DehakaHatchery'],
'display_name': 'Primal Attacks Level 2',
'race': 'Zerg',
'type': 'Upgrade',
'is_morph': False,
},
'DehakaPrimalWeaponsLevel3': {
'build_time': 220,
'built_from': ['DehakaHa... | |
'{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
TopicRuleErrorActionS3.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
TopicRuleErrorActionS3.__key_warning(key)
return super().get(key, default)
def __init__(__self__, *,
bucket_... | |
from sqlalchemy import create_engine, Column, Integer, BigInteger, String, Boolean, MetaData, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.types import DateTime, Date, Interval
from sqlalchemy.pool import NullPool
from .conf imp... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Provide constants and composite types for binding with ctypes.
"""
from __future__ import absolute_import
import ctypes
import ctypes.util
import os
from .utils import coerce_char_p, python_2_unicode_compatible, read_ejdb_config
JDBIDKEYNAME = '_id'
# enum { /** Da... | |
"""
result = RectangleList()
islands = list(self.islands(useexitstatus=True))
onepixel = self.onepixel
gxdict = collections.defaultdict(dict)
gydict = collections.defaultdict(dict)
primaryregionsx = {}
primaryregionsy = {}
shape = {tuple(r.shape) for r in self.rectangles}
if len(shape) > 1:
raise ValueError(... | |
#! /usr/bin/env python3
import collections
import datetime
import pprint
import re
import urllib.parse
import uuid
import voluptuous as v
import pymongo
import bson
s_old_story_base = v.Schema({
"_id": bson.objectid.ObjectId,
"id": str,
"url": v.Url(),
"title": str,
"scraped": v.Any(datetime.datetime, None),
"m... | |
<filename>pysrc/generator.py
#!/usr/bin/env python
# -*- python -*-
#BEGIN_LEGAL
#
#Copyright (c) 2019 Intel Corporation
#
# 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.... | |
self._client.report_instances_status(instance_id=self.instance_id, **_params)
def allocate_public_ip_address(self, **params):
_params = _transfer_params(params)
self._client.allocate_public_ip_address(instance_id=self.instance_id, **_params)
def attach_classic_link_vpc(self, **params):
_params = _transfer_params... | |
# encoding: utf-8
import os
import re
import sys
import gzip
import time
import json
import socket
import random
import weakref
import datetime
import functools
import threading
import collections
import urllib.error
import urllib.parse
import urllib.request
import collections.abc
import json_dict
from . import util... | |
<gh_stars>1-10
import sys
import datetime
import time
import selenium
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from .config.aaConfig import aaConfig
from .parser.a... | |
<= 0)
m.e968 = Constraint(expr= m.x472 - 20 * m.b1052 <= 0)
m.e969 = Constraint(expr= m.x473 - 24 * m.b1053 <= 0)
m.e970 = Constraint(expr= m.x474 - 21 * m.b1054 <= 0)
m.e971 = Constraint(expr= m.x475 - 20 * m.b1055 <= 0)
m.e972 = Constraint(expr= m.x476 - 20 * m.b1056 <= 0)
m.e973 = Constraint(expr= m.x477 - 24 * m.b1... | |
<filename>exocartographer/gp_illumination_map.py
from __future__ import division
import numpy as np
import healpy as hp
from . import gp_map as gm
from .gp_map import draw_map_cl, map_logprior_cl
from .util import logit, inv_logit, flat_logit_log_prior
from .analytic_kernel import viewgeom, kernel
def quaternion_... | |
a list of string or a list of pair
of string (see details in ``encode_plus``).
batch_entity_spans_or_entity_spans_pairs (:obj:`List[List[Tuple[int, int]]]`,
:obj:`List[Tuple[List[Tuple[int, int]], List[Tuple[int, int]]]]`, `optional`)::
Batch of entity span sequences or pairs of entity span sequences to be encoded ... | |
\
'ORDER BY forecastdate DESC LIMIT 1'.format(algoCode, ID)
latest_date = pd.read_sql_query(date_query, self.engine) # most recent forecast date calculation
# if table has forecast prices already find the latest one and delete it
# need to use most recent data for today if before market close at 4pm
if not latest... | |
<filename>code_python/1.2/edge-extract.py
# ------------------------------------------------------------------------------
# IMPORTS
# ------------------------------------------------------------------------------
from sys import version_info
from sys import path as syspath
from os import path
import json
_CURRENT_DIR... | |
import os
import sys
import glob
import gzip
import multiprocessing
import re
import uuid
from core.log import log
from core.config import HotSOSConfig
class FileSearchException(Exception):
def __init__(self, msg):
self.msg = msg
class FilterDef(object):
def __init__(self, pattern, invert_match=False):
"""
... | |
variables in the stochastic process.
* **phi** (`ndarray`):
The random phase angles used in the simulation of the stochastic process.
The shape of the phase angles (`nsamples`, `number_of_variables`, `number_frequency_intervals[0]`, ...,
`number_frequency_intervals[number_of_dimensions-1]`)
* **b_ampl** (`ndarr... | |
<reponame>amarallab/waldo
# coding: utf-8
# Description:
# This notebook is an attempt to implement the state behaivior model from
# The Geometry of Locomotive Behavioral States in C. elegans
# Gallagher et al.
#
### Imports
# In[2]:
# standard imports
import os
import sys
import numpy as np
import scipy
import sci... | |
<gh_stars>1-10
#!/usr/bin/env python3
import sys
import os
import getopt
import shutil
import json
import urllib.request
import hashlib
import tarfile
import re
exe_name = 'docker-bundle'
project_name = 'Docker-bundle'
bundle_install_dir = 'docker'
bundles_dir = 'bundles'
version_code = '0.1.0'
version_number = 1
# ... | |
<filename>omnitool/tlib.py
"""Low level interface to Terraria data"""
from struct import unpack, pack, Struct
import sys
from .database import items, rev_items, multitiles
is_exe = hasattr(sys, "frozen")
### Parser for .wld data types ###
def decode7bit(bytes):
lbytes = list(bytes)
value = 0
shift = 0
while True... | |
"""
Functions for creating a graph from a skeletonized image (produce_graph) and
for simplifying graphs in various ways.
Graphs are NetworkX graphs where nodes are points, represented as (x,y) pairs.
Some vocabulary:
A juncture is a node with less than 2 or more than 2 edges.
A bridge is a node with exactly 2 edges... | |
color = 'r', rasterized = True)
ax1.plot(t, quasars_total / norm, color = PlotScripts.colors[model_number], linestyle = PlotScripts.linestyles[0], rasterized = True, linewidth = PlotScripts.global_linewidth)
p = np.where((ZZ < 15))[0]
#ax1.plot(ZZ[p], quasars_total[p] / norm, color = PlotScripts.colors[model_numb... | |
determines the heading along the line, using a "thinned"
version of the line. The degree of thinning is based on the size of the
offset; the larger the offset, the greater the distance between sample
locations used to construct the thinned lined used for determining headings.
The thinned line is splined at a freque... | |
# stdlib
from io import StringIO
# lib
from django.core.management import call_command
from django.urls import reverse
from rest_framework import status
# local
from api.models import BISList, Character, Gear, Team, Tier
from api.serializers import BISListSerializer
from .test_base import SavageAimTestCase
class BISL... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.