input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<filename>qcengine/util.py
"""
Several import utilities
"""
import importlib
import io
import json
import operator
import os
import shutil
import signal
import subprocess
import sys
import tempfile
import time
import traceback
from contextlib import contextmanager
from pathlib import Path
from typing import Any, Calla... | |
# coding=utf-8
import tensorflow as tf
from colorama import Fore
import numpy as np
import logging
from collections import OrderedDict
import Putil.DenseNet.model_base as dmb
from tensorflow.contrib import layers
import Putil.np.util as npu
import Putil.tf.util as tfu
def get_image_summary(img, idx=0):
"""
Make an ... | |
"{}" has status: "{}"'
.format(var, job, status))
return row[4]
return None
@staticmethod
def squeue(name=None):
"""Run the SLURM squeue command and return the stdout split to rows.
Parameters
----------
name : str | None
Optional to check the squeue for a specific job name (not limited
to the 8 shown char... | |
import negation.modifiers as modifiers
from abc import ABC, abstractmethod
import re
import pandas as pd
from pprint import pprint
class RiskVar(ABC):
_df_atr_exclude = ["object", "mod"]
def __init__(self, object):
self.object = object
self.literal = object.getLiteral()
self.cat = object.categoryString()
self.p... | |
<filename>sim21/unitop/EquiliReactor.py
"""Models a Equilibrium reactor
Classes:
ReactionDisplay - For rendering reaction
EquilibriumReaction - Equilibrium reaction class
InternalEqmReactor - Internal equilibrium reactor
EquilibriumReactor - General equilibrium reactor
"""
import math
# Common constants
from sim21.un... | |
import math
import logging
import numpy as np
from os.path import join
import os
import torch
from torch import nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from collections import OrderedDict
from .dla import DLAMain,BasicBlock,DLAUp,IDAUp
# from .DCNv2.dcn_v2 import DCN
from ..regist... | |
#
# Autogenerated by Thrift
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
from cyclozzo.thrift.Thrift import *
from ttypes import *
from cyclozzo.thrift.Thrift import TProcessor
from cyclozzo.thrift.transport import TTransport
from cyclozzo.thrift.protocol import TBinaryProtocol, TProtocol
try... | |
is None:
a_alpha_ijs, a_alpha_roots, a_alpha_ij_roots_inv = a_alpha_aijs_composition_independent(a_alphas, kijs)
z_products = [[zs[i]*zs[j] for j in range(N)] for i in range(N)] # numba : delete
# z_products = np.zeros((N, N)) # numba: uncomment
# for i in range(N): # numba: uncomment
# for j in range(N): # numba: u... | |
None], self.xy_shift, 'bilinear')
self.gausswin = gausswin[:, :, :, 0] # get rid of color channels
self.gausswin_batch = tf.gather(self.gausswin, self.batch_inds)
self.illumination *= tf.to_complex64(self.gausswin_batch) # gaussian window
# forward propagation:
def propagate_1layer(field, t_i):
# field: the inp... | |
# -*- coding: utf-8 -*-
"""
Tests for functionalities in geofileops.general.
"""
from pathlib import Path
import sys
import geopandas as gpd
import pandas as pd
import pytest
import shapely.geometry as sh_geom
# Add path so the local geofileops packages are found
sys.path.insert(0, str(Path(__file__).resolve().paren... | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import glob
import re
import os.path as osp
def list_pictures(directory, ext='jpg|jpeg|bmp|png|ppm'):
return sorted([os.path.join(root, f)
for root, _, files in os.walk(directory) for f in files
... | |
"""
Base class for plugins - frameworks or systems that may:
* add code at startup
* allow hooks to be called
and base class for plugins that:
* serve static content
* serve templated html
* have some configuration at startup
"""
import os.path
import sys
import imp
import pkg_resources
pkg_resources.require( 'M... | |
<filename>sqlitehouse.py
# -*- coding: utf-8 -*-
import logging
import random
import sqlite3
from contextlib import closing
logger = logging.getLogger(__name__)
def clean(line):
"""Strip a string of non-alphanumerics (except underscores).
Can use to clean strings before using them in a database query.
Args:
line... | |
<filename>lib/custom_operations/custom_check.py
# --------------------------------------------------------
# PyTorch Faster R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by <NAME>, based on code from <NAME>
# --------------------------------------------------------
import os
import sys
imp... | |
func = sys._getframe().f_code.co_name # pylint: disable=protected-access
logging.info(f'Switching sites on `Tableau REST API` (site={contenturl})')
url = f'{self.baseapi}/auth/switchSite'
body = {'site': {'contentUrl': contenturl}}
request = self.session.post(url, json=body)
response = Response(request, func)
... | |
import pandas as pd
from pyparsing import *
from utils import *
texttest = """
Record Number 1802
Weapon Scoring
Application ID: 13
Record Type: 3
Record Subtype: 2
Minor Frame: 01196646
Time (UTC): 18:41:47.563
Recording Length: 284 (16-bit words)
Tail Number: 0
Tail Year: 0
Date: 07/28/20
Mode: STRIKE
Laun... | |
= self.genotypes[i]
# Getting the genotype
o_geno = self.pedfile.get_geno_marker(marker)
np.testing.assert_array_equal(o_geno, e_geno)
# Asking for an unknown marker should raise an ValueError
with self.assertRaises(ValueError) as cm:
self.pedfile.get_geno_marker("dummy_marker")
self.assertEqual(
"dummy_marke... | |
<filename>01_build_caliber_codelist.py
# Databricks notebook source
# MAGIC %md
# MAGIC # Build CALIBER codelist
# MAGIC
# MAGIC **Description**
# MAGIC
# MAGIC 1. Imports the CALIBER codelist dictionary from *<NAME>., <NAME>., <NAME>. et al. A chronological map of 308 physical and mental health conditions from 4 m... | |
test_one_arg_encoder(self):
import _codecs
def search_function(encoding):
def encode_one(u):
return (b'foo', len(u))
def decode_one(u):
return (u'foo', len(u))
if encoding == 'onearg':
return (encode_one, decode_one, None, None)
return None
_codecs.register(search_function)
assert u"hello".encode("onearg") =... | |
self.assertEqual(b.shape[2], a.shape[1])
self.assertEqual(b.shape[3], a.shape[2])
self.assertEqual(b.lshape[0], a.shape[0])
self.assertEqual(b.lshape[1], 1)
self.assertEqual(b.lshape[2], a.shape[1])
self.assertLessEqual(b.lshape[3], a.shape[2])
self.assertIs(b.split, 3)
# exceptions
with self.assertRaises(Ty... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
## Project: Simple4All - January 2013 - www.simple4all.org
## Contact: <NAME> - <EMAIL>
## Contact: <NAME> - <EMAIL>
import sys
import os
import re
from util.xpath_extensions_for_ossian import *
## These imports now handled by xpath_extensions_for_ossian:--
# import lxm... | |
not False) \
and include_derivs_dataset_description:
self._download_derivative_descriptions(
include_derivs, directory)
results = [delayed(sub.download)(
directory=directory,
include_derivs=include_derivs,
suffix=suffix,
overwrite=overwrite,
pbar=pbar,
pbar_idx=idx,
) for idx, sub in enumerate(self.subjects... | |
# Copyright (c) 2020 PaddlePaddle 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 applicabl... | |
<filename>nativecompile/x86_reader.py
# Copyright 2015 <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 ... | |
"""This module contains the `Edb` class.
This module is implicitily loaded in HFSS 3D Layout when launched.
"""
import os
import sys
import traceback
import warnings
import gc
import pyaedt.edb_core.EDB_Data
import time
try:
import ScriptEnv
ScriptEnv.Initialize("Ansoft.ElectronicsDesktop")
inside_desktop = True... | |
# if taxid not in taxid_2_rank__taxid_set:
# line2write = str(taxid) + "\t" + rank + "\n"
# fh_out_taxid_2_rank.write(line2write)
# taxid_2_rank__taxid_set.update([taxid])
#
# def write_Child_2_Parent_table_Taxa_for_SQL(self, fn_out):
# # type_number = "-3" # entity type = "DOID diseases" from Lars's Entities and... | |
the positions history to refill if animating this process <<<< needs updating for DOFtype
# ------------------------- perform linearization --------------------------------
if solveOption==0: # ::: forward difference approach :::
for i in range(n): # loop through each DOF
X2 = np.array(X1, dtype=np.float_) ... | |
<gh_stars>1-10
# coding: utf-8
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from ks_api_client.api_client import ApiClient
from ks_api_client.exceptions import ( # noqa: F401
ApiTypeError,
ApiValueError
)
class SuperMultipleOrderApi(obje... | |
<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# =======================================================
"""engine_common
* SearchEngine Classから呼び出す、各検索エンジンで共通の処理を保持させる継承用Classである `CommonEngine` を持つモジュール.
"""
import requests
import os
import pickle
# selenium driver auto install packages
import chrome... | |
"nullable": True,
"alias": "是否自愈",
"description": "是否自愈",
"dim": "self_healing",
"type": "BOOLEAN"
}, {
"buildIn": True,
"field": "weight",
"nullable": True,
"alias": "健康权重",
"description": "健康权重",
"dim": "weight",
"type": "INTEGER"
}]
}, {
"metaReq": {
"description": "异常实例模型(增量分区)",
"tableAlias": "dwd_... | |
int]])
def test_err_union_with_custom_type(self, typ):
with pytest.raises(TypeError) as rec:
msgspec.msgpack.Decoder(typ)
assert "custom type" in str(rec.value)
assert repr(typ) in str(rec.value)
@pytest.mark.parametrize("typ", [Union[dict, Person], Union[Person, dict]])
def test_err_union_with_struct_and_dict(... | |
"""
CRAR Neural network using Keras
"""
import numpy as np
from keras import backend as K
from keras.models import Model
from keras.layers import Input, Layer, Dense, Flatten, Activation, Conv2D, MaxPooling2D, UpSampling2D, Reshape, Permute, Add, Subtract, Dot, Multiply, Average, Lambda, Concatenate, BatchNormalizati... | |
an emphasis
on converting raw user intent into more organized structures rather than
producing string output. The top-level :class:`.CompileState` for the
statement being executed is also accessible when the execution context
works with invoking the statement and collecting results.
The production of :class:`.Com... | |
table')
if category_names != '' and category_names != None:
try:
ds.GetRasterBand(1).SetRasterCategoryNames(category_names)
except:
print ('Could not write category names')
print(('Writing: ' + output_name.split('/')[-1]))
print(('Datatype of ' + output_name.split('/')[-1] + ' is: ' + dt))
for band in range(ban... | |
value = 'CKM2x2*Ru2x2',
texname = '\\text{I63x22}')
I63x33 = Parameter(name = 'I63x33',
nature = 'internal',
type = 'complex',
value = 'CKM3x3*Ru3x3',
texname = '\\text{I63x33}')
I63x36 = Parameter(name = 'I63x36',
nature = 'internal',
type = 'complex',
value = 'CKM3x3*Ru6x3',
texname = '\\text{I63x36}')
I6... | |
<filename>eddy/fit_cube.py
"""
Class to load up a velocity map and fit a Keplerian profile to it. The main
functions of interest are:
disk_coords: Given geometrical properties of the disk and the emission
surface, will deproject the data into a face-on view in either polar or
cartesian coordaintes.
keplerian: Bui... | |
<filename>src/specific_models/bot-iot/attack_identification/lstm.py
# Author: <NAME>
# github.com/kaylani2
# kaylani AT gta DOT ufrj DOT br
### K: Model: LSTM
import sys
import time
import pandas as pd
import os
import math
import numpy as np
from numpy import mean, std
from unit import remove_columns_with_one_value, ... | |
+ response.data.decode('utf-8'))
def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_available_capacity_bandwidth_profile_peak_information_rate_get(self):
"""Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_av... | |
#!/usr/bin/env python3
# need this to generate randomness
import random
# defining the text lists
# list of scientific fields
fieldList = ['physics', 'biology', 'chemistry',
'economics', 'history', 'sociology',
'mathematics']
# list of journals
journalList = ["Journal of {}", "{} Review Letters", "Annals of {}",
... | |
out_score, det_point[0][1], det_point[0][0]])
# print([i, 0, out_score, det_point[1][1], det_point[1][0]])
true_res[i] = point # [num_guidewire, num_point, 2]
# print(point)
print('avg_infer_time:' + str(inference_time / self.inference_num))
return true_res, pred_res
def compute_aps(self, true_res, pred_res, thr... | |
from __future__ import division
import ogr
import glob
import gdal
import osr
import osgeo
import numpy as np
import os, os.path, shutil
import osgeo.ogr
import osgeo.osr
from gdalconst import *
import csv
import xlrd
from osgeo import ogr
from TEST1.TASTE1.gis.vector.write import *
from math import radians, cos, sin,... | |
<filename>python/RLrecon/environments/fixed_environment.py
from __future__ import print_function
import numpy as np
from environment import BaseEnvironment
from RLrecon import math_utils
class FixedEnvironmentV0(BaseEnvironment):
def __init__(self,
world_bounding_box,
random_reset=True,
radius=7.0,
height=3.0,
... | |
# base functions originally from https://github.com/pclucas14/pixel-cnn-pp/blob/master/utils.py#L34
import pdb
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.nn.utils import weight_norm as wn
import numpy as np
from IPython import embed
def to_scalar(a... | |
<reponame>alexmerkel/ytarchiver
#!/usr/bin/env python3
''' ytapost - youtube archiver post processing steps '''
import os
import sys
import subprocess
import argparse
import shutil
import sqlite3
import json
import time
from datetime import datetime, timezone
from pycountry import languages
import ytacommon as yta
imp... | |
"""Module for univariate densities (see also :mod:`ddl.independent`)."""
from __future__ import division, print_function
import logging
import warnings
import numpy as np
import scipy.stats
from sklearn.base import BaseEstimator
from sklearn.exceptions import DataConversionWarning, NotFittedError
from sklearn.utils.v... | |
<gh_stars>10-100
# Author: <NAME>, Ph.D. candidate
# Department of Civil and Systems Engineering, Johns Hopkins University
# Last update: March 25, 2021
#######################################################################################################################
##############################################... | |
# 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, Mapping, Optional, Sequence, Union, overload
from . import ... | |
# -*- coding: utf-8 -*-
from datetime import datetime
import mock
import pytest
import random
from django.utils import timezone
from api.base.settings.defaults import API_BASE
from api.nodes.serializers import NodeContributorsCreateSerializer
from framework.auth.core import Auth
from osf.models import PreprintLog
from... | |
in %s is managed by system '%s'. Are you sure you want to modify it? [y/n]: " %
(p.prefix, vrf_format(p.vrf), p.authoritative_source))
# If the user declines, short-circuit...
if res.lower() not in [ 'y', 'yes' ]:
print("Operation aborted.")
return
try:
p.save()
except NipapError as exc:
print("Could not sav... | |
= Box(children=row, layout=box_layout)
name_btn = Button(description='exhausted_macrophage_death_rat', disabled=True, layout=name_button_layout)
name_btn.style.button_color = 'lightgreen'
self.float574 = FloatText(value='0.01', step='0.001', style=style, layout=widget_layout)
units_btn = Button(description='1/min',... | |
#!/usr/bin/env python
# Copyright (c) 2018, DIANA-HEP
# All rights reserved.
#
# 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 retain the above copyright notice, this
# list of... | |
provided. Note that this is a folder name, not a path, defaults to
'None'
:type m1_val_images_folder: str, optional
:param m2_val_images_folder: Folder name that contains the validation images for the second modality. This
folder should be contained in the dataset path provided. Note that this is a folder name, not... | |
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may ... | |
show_docx(self, event):
self.docx_frame.setVisible(True)
self.docx_frame.toFront()
self.docx_frame.setAlwaysOnTop(True)
def create_summary(self):
self.summary_frame = JFrame("Summary")
self.summary_frame.setLayout(BorderLayout())
self.summary_frame.setSize(800, 600)
self.summary_frame.setLocationRelativeTo(Non... | |
from twisted.internet.defer import Deferred
from twisted.internet.protocol import Factory, ClientFactory
from twisted.internet.task import LoopingCall
from twisted.protocols.amp import AMP, Command, Integer, String, Boolean, AmpList, ListOf, IncompatibleVersions
from twisted.python import log
from twisted.words.protoco... | |
virtual global IPv6 IP address
**type**\: list of :py:class:`GlobalIpv6Address <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ipv4_vrrp_cfg.Vrrp.Interfaces.Interface.Ipv6.SlaveVirtualRouters.SlaveVirtualRouter.GlobalIpv6Addresses.GlobalIpv6Address>`
"""
_prefix = 'ipv4-vrrp-cfg'
_revision = '2015-11-09'
def __init_... | |
#!/usr/bin/env python3
class Dummy(object):
pass
def getWidth(xmlfile):
from xml.etree.ElementTree import ElementTree
xmlfp = None
try:
xmlfp = open(xmlfile,'r')
print('reading file width from: {0}'.format(xmlfile))
xmlx = ElementTree(file=xmlfp).getroot()
#width = int(xmlx.find("component[@name='coordinate1... | |
import tkinter
from tkinter import ttk
import random
import time
import tkinter.messagebox
class SortingVisualizer:
"""
Main GUI
"""
def __init__(self, main):
"""
Init GUI
:param main: tkinter.Tk()
"""
self.FINISHED_SORTING = False
self.box_color = "#5555ff"
###### Basic Layout ######
"""_____________... | |
to complexes,
surfaces, chains, ligands, and interfaces. A complete hierarchy of all possible
PyMOL groups and objects is shown below:
<PDBFileRoot>
.Complex
.Complex
.Surface
.Chain<ID>
.Complex
.Complex
.Surface
.Chain
.Chain
.NonInterface
.Chain
.Surface
.Surface
.Hydrophobicity
.Hydrophobicity_Ch... | |
= self.master.cell
cell.add_node(srv_1)
cell.add_node(srv_2)
cell.add_node(srv_3)
cell.add_node(srv_4)
app1 = scheduler.Application('app1', 4, [1, 1, 1], 'app',
schedule_once=True)
app2 = scheduler.Application('app2', 3, [2, 2, 2], 'app')
cell.add_app(cell.partitions[None].allocation, app1)
cell.add_app(cell... | |
<gh_stars>0
#!/usr/bin/env python
import os
import argparse
from plantcv import plantcv as pcv
# Parse command-line arguments
def options():
parser = argparse.ArgumentParser(description="Imaging processing with opencv")
parser.add_argument("-i", "--image", help="Input image file.", required=True)
parser.add_argum... | |
- x1: not used
- x2: not used
3. triangle
- x1: not used
- x2: not used
4. expon_min
- x1: slope {0 = no slope -> 10 = sharp slope}
- x2: not used
5. expon_max
- x1: slope {0 = no slope -> 10 = sharp slope}
- x2: not used
6. biexpon
- x1: bandwidth {0 = huge bandwidth -> 10 = narrow bandwidth}
- x2: not us... | |
<gh_stars>1-10
from __future__ import absolute_import, print_function
from PyDSTool.common import *
from PyDSTool.errors import *
from PyDSTool.utils import remain, info
from PyDSTool.Points import Point, Pointset
from numpy import array, asarray, NaN, Inf, isfinite
from PyDSTool.matplotlib_import import gca, plt
from... | |
import os
import sys
import csv
import json
import math
import enum
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
from os import listdir
from os.path import isfile, join
from skimage import measure
from skimage import filters
from scipy import ndimage
class OutputShapeType(enum.Enum... | |
request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_amendment_swagger_with_http_info(query_string, callback=callback_function)
:param callback function: The callback function
for asynchronous r... | |
import time
import pytest
from py_ecc import (
bn128,
optimized_bn128,
bls12_381,
optimized_bls12_381,
)
from py_ecc.fields import (
bls12_381_FQ,
bls12_381_FQ2,
bls12_381_FQ12,
bn128_FQ,
bn128_FQ2,
bn128_FQ12,
optimized_bls12_381_FQ,
optimized_bls12_381_FQ2,
optimized_bls12_381_FQ12,
optimized_bn128_F... | |
<reponame>fchapoton/sage
r"""
Subcrystals
These are the crystals that are subsets of a larger ambient crystal.
AUTHORS:
- <NAME> (2013-10-16): Initial implementation
"""
#*****************************************************************************
# Copyright (C) 2013 <NAME> <tscrim at ucdavis.edu>
#
# Distributed... | |
<gh_stars>0
""" This contains the list of all drawn plots on the log plotting page """
from html import escape
from bokeh.layouts import widgetbox
from bokeh.models import Range1d
from bokeh.models.widgets import Div, Button
from bokeh.io import curdoc
from scipy.interpolate import interp1d
from config import *
from... | |
# coding: utf-8
"""
Thingsboard REST API
For instructions how to authorize requests please visit <a href='http://thingsboard.io/docs/reference/rest-api/'>REST API documentation page</a>.
OpenAPI spec version: 2.0
Contact: <EMAIL>
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __futu... | |
request to stop the solution process.
Otherwise, new request with updated solution process information.
"""
resp: dict = request.response
# change the number of iterations
if "n_iterations" in resp:
# "expand" the numpy arrays used for storing information from iteration rounds
if resp["n_iterations"] > self.... | |
# This routine computes the first-order
# transit timing variations in Agol & Deck (2015). Please
# cite the paper if you make use of this code in your research.
import numpy as np
import matplotlib.pyplot as plt
class Planet(object):
def __init__(self, mass_ratio=None, trans0=None, period=None, ecos=None,
esin=No... | |
= np.linalg.pinv(D_FDSP)
print 'SPS - FDSP Rec:'
print R_FDSP.shape
if VISU == True:
fig2, ax = plt.subplots()
fig2.set_size_inches(12,4)
#Rx and Ry are in radians. We want to show IM in microns RMS SURF of tilt
#We found using DOS that a segment tilt of 47 mas is equivalent to 0.5 microns RMS of tilt on an M1... | |
self.numValidStructsFound = 0
multiCmdFile = open(self.multiCmdFile, 'w+')
multiCmdFile.write('_LINES = 10000\n')
print("\nTelemetry Object List")
for i in range(len(self.telemetryObjectList)):
dataObjectName = self.telemetryObjectList[i][0]
typeDefName = self.getTypeDefName(dataObjectName)
try:
print("%3i/%i:... | |
'physical', 'pink', 'plain', 'planned', 'plastic',
'pleasant', 'pleased', 'poised', 'polish', 'polite', 'political', 'poor',
'popular', 'positive', 'possible', 'post-war', 'potential', 'powerful',
'practical', 'precious', 'precise', 'preferred', 'pregnant',
'preliminary', 'premier', 'prepared', 'present', 'presid... | |
#!/usr/bin/env python
# Copyright 2010,2011 Mozilla Foundation. 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... | |
= np.log(astroA.res_d['area'])
times = astroA.res_d['time_s']
r, p = stat_utils.get_pearsonr(times, areas)
df = pd.DataFrame({'Size': areas, 'Time': times})
title ='Size vs Time correlation plot'
text = 'r = {}, p < {}'.format(general_utils.truncate(r, 2), p)
for kind in ['reg', 'hex', 'kde']:
plotly_utils.sea... | |
as an empty list
all_tags = []
if bool(use_tag_labels): # if use_tag_labels is 1, append the tags to all_tags list
all_tags.extend([tag + "_tag" for tag in Dataset.tags])
if bool(use_malicious_labels): # if use_malicious_labels is 1, append malware label to all_tags list
all_tags.append("malware")
# crete tempor... | |
import os
import yaml
import zipfile
import lmctl.files as files
import lmctl.project.handlers.interface as handlers_api
import lmctl.project.validation as project_validation
import lmctl.utils.descriptors as descriptor_utils
from .brent_content import BrentResourcePackageContentTree, BrentPkgContentTree
class Opensta... | |
None))
def reconfig(self, *,
shape=None,
metric=None):
"""
Reconfig objective
Arguments:
shape: objective layer shape
metric: loss metric
"""
if metric is not None:
if 'loss' in metric or ('accuracy' or 'acc') in metric:
if 'loss' in metric:
self._evaluation['metric']['loss'] = 0
if ('accuracy' or 'acc') ... | |
#! /usr/bin/env python3
# coding: utf-8
from __future__ import annotations
from collections.abc import Iterator
import math
from operator import itemgetter
import typing as t
from dropbox import Dropbox
import gpxpy
import pendulum
from psycopg2.extensions import connection
import slack
from gargbot_3000 import comm... | |
"""
A decision is the act of picking an option at a choice, after which one
experiences an outcome. Note that the handling of extended/hidden/uncertain
outcomes is not yet implemented.
Decisions have information on both a player's prospective impressions of the
choice in question (as a decision model plus goal sa... | |
<reponame>beasyx0/blog_api
from datetime import timedelta
from rest_framework import generics
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.status import HTTP_200_OK, HTTP_201_CREATED, HTTP_204_NO_CONTENT, HTTP_40... | |
= self.nsmap), 'text')
''' Foreign Keys '''
existence_test_and_add(self, 'person_historical_index_id', self.person_historical_index_id, 'no_handling')
existence_test_and_add(self, 'export_index_id', self.export_index_id, 'no_handling')
''' Shred to database '''
shred(self, self.parse_dict, HUDHomelessEpisodes)
... | |
gdal.Open('data/6band_wrong_number_extrasamples.tif')
assert gdal.GetLastErrorMsg().find('Wrong number of ExtraSamples') >= 0
assert ds.GetRasterBand(6).GetRasterColorInterpretation() == gdal.GCI_AlphaBand
###############################################################################
# Test that we can read a one-t... | |
from __future__ import annotations
from dataclasses import dataclass, field
from typing import List, Dict, TYPE_CHECKING
from reamber.base.Map import Map
from reamber.base.lists import TimedList
from reamber.sm.SMBpm import SMBpm
from reamber.sm.SMConst import SMConst
from reamber.sm.SMFake import SMFake
from reamber... | |
self._append_error( FESyntaxErrors.CONTAINER_END )
return True
else:
return False
#-------------------------------------------------------------------------
def _del_statement(self) -> bool:
#=======================================================================
# <del statement> ::= 'del' <identifiers list>
... | |
<reponame>ORANGE-XFM/Cloudnet-TOSCA-toolbox<gh_stars>10-100
######################################################################
#
# Software Name : Cloudnet TOSCA toolbox
# Version: 1.0
# SPDX-FileCopyrightText: Copyright (c) 2020-21 Orange
# SPDX-License-Identifier: Apache-2.0
#
# This software is distributed under... | |
("Gibbs time")
print "Events per sec = ", (st['nevents'] / secs)
print
print "TOT_MC ",
for x in tot: print " %.10f" % x,
print
print "TOT_GIB ",
for x in tot_gibbs: print " %.10f" % x,
print
def test_mm1_response_stationary (self):
sampling.set_seed(2334)
net = self.mm1
nt = 250
pct = 0.1
nreps = 10... | |
<filename>CrvDatabase/Fibers/Fibers.py
# -*- coding: utf-8 -*-
##
## File = "Fibers_2017Jun29.py"
## Derived from File = "Fibers_2016Jun24.py"
## Derived from File = "Fibers_2016Jun10.py"
## Derived from File = "Fibers_2016Jun10.py"
## Derived from File = "Fibers_2016Jun9.py"
## Derived from File = "Fibers_2016Jun8.py"... | |
if s.is_positive is None])
eq = eq.subs(reps)
return eq, dict([(r, s) for s, r in reps.items()])
def _polarify(eq, lift, pause=False):
from sympy import polar_lift, Integral
if eq.is_polar:
return eq
if eq.is_number and not pause:
return polar_lift(eq)
if isinstance(eq, Symbol) and not pause and lift:
return... | |
and row['address_desc_short'] is not None:
gen_row['address_desc_short'] = self.random_alpha_string(20, True)
if 'delivery_instructions' in row and row['delivery_instructions'] is not None:
gen_row['delivery_instructions'] = self.random_alpha_string(40, True)
if 'unit_no' in row and row['unit_no'] is not None:
gen... | |
overplot_behind or force_line_plot
are set the marker size will be double overplot_markersize so
the color is visible.
assessment_overplot_category : dict
Lookup to categorize assessments into groups. This allows using
multiple terms for the same quality control level of failure.
Also allows adding more to the de... | |
import polars
from pyquokka.nodes import *
from pyquokka.utils import *
import numpy as np
import pandas as pd
import time
import random
import pickle
from functools import partial
import random
#ray.init("auto", _system_config={"worker_register_timeout_seconds": 60}, ignore_reinit_error=True, runtime_env={"working_... | |
<filename>autotest/ogr/ogr_mysql.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test MySQL driver functionality.
# Author: <NAME> <even dot rouault at mines dash paris dot ogr>
#
########... | |
field_vals_dict: contains a dictionary indexed by field (sex, age, preference, etc.), and containing the current value
# of the field that must be translated into the current language.
location = ''
return_dict = {
'age': '----',
'sex': '----',
'sub_region': '----',
'region': '----',
'country': '----',
'loca... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
**Project Name:** MakeHuman
**Product Home Page:** http://www.makehumancommunity.org/
**Github Code Home Page:** https://github.com/makehumancommunity/
**Authors:** <NAME>, <NAME>
**Copyright(c):** MakeHuman Team 2001-2019
**Licensing:** AGPL3
This file is par... | |
#!/usr/bin/env python
"""
run_1yr_benchmark.py: Driver script for creating benchmark plots and testing
gcpy 1-year TransportTracers benchmark capability.
Run this script to generate benchmark comparisons between:
(1) GCC (aka GEOS-Chem "Classic") vs. GCC
(2) GCHP vs GCC (not yet tested)
(3) GCHP vs GCHP (not yet ... | |
time.time()
# In[ ]:
print("Training took {:.2f}s".format(t1 - t0))
# Oh no! Training is actually more than twice slower now! How can that be? Well, as we saw in this chapter, dimensionality reduction does not always lead to faster training time: it depends on the dataset, the model and the training algorithm. Se... | |
support existing_axes that aren't a slice by using transpose,
# but that could lead to unpredictable performance consequences because
# transposes are not free in TensorFlow. If we did transpose
# automatically, the user might never realize that their data is being
# produced with the wrong order. (The later wi... | |
from __future__ import print_function
from __future__ import absolute_import
from builtins import zip
from builtins import range
from . import parobject as php
import numpy as nm
import re
def base_smica(root_grp, hascl, lmin, lmax, nT, nP, wq, rqhat, Acmb, rq0=None, bins=None):
if bins == None:
nbins = 0
else:
b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.