input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
from config.utils import *
from collections import defaultdict
import config.anchor as anchor
import time
class MatchEngine(object):
"""A class that handles the book-keeping for the matching process.
Attributes
----------
logger (logger): elementals logger instance
disas (disassembler): disassembler layer handle... | |
<reponame>wpj1530882136/RCDemo<gh_stars>0
# -*- coding:utf8 -*-
# ==============================================================================
# Copyright 2017 Baidu.com, Inc. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with ... | |
#!/usr/bin/env python
"""Make ATLAS Stamps in the context of the transient server database.
Usage:
%s <configfile> [<candidate>...] [--detectionlist=<detectionlist>] [--customlist=<customlist>] [--limit=<limit>] [--earliest] [--nondetections] [--discoverylimit=<discoverylimit>] [--lastdetectionlimit=<lastdetectionlim... | |
<reponame>alexbowers/pulumi-aws
# 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... | |
import logging
import json
import glob
import pandas as pd
import multiprocessing
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.metrics... | |
<gh_stars>1-10
##########################################################################
#
# Copyright (c) 2012, <NAME>. All rights reserved.
# Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided... | |
= rest_get(host, secure_boot_uri, None, iLO_loginname, iLO_password)
# if the BIOS doesn't support PATCH, go get the Settings, which should
if not operation_allowed(headers, 'PATCH'): # this is GET-only
secure_boot_uri = secure_boot_settings['links']['Settings']['href']
status, headers, boot_settings = rest_get(ho... | |
# Copyright 2015 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 ... | |
<reponame>r1mikey/research-unix-v7
#!/usr/bin/env python3
from collections import deque
import os
import time
import sys
import struct
"""
struct filsys {
u16 s_isize; /* size in blocks of i-list */
v7_daddr_t s_fsize; /* size in blocks of entire volume */
i16 s_nfree; /* number of addresses in s_free */
v7_daddr... | |
available versions are:
- 2021-12-16
- 2021-01-21
- 2021-11-15
- 2021-12-06
"""
return AutomaticallyRetrievedGraph(
"RXNO", version, "kgobo", directed, preprocess, load_nodes,
load_node_types, load_edge_weights, auto_enable_tradeoffs, sort_tmp_dir, verbose, cache,
cache_path, cache_sys_var, kwargs
)()... | |
v S^2)
Defn: [v_0, sigma_2] --> [*, sigma_2]
sage: W.projection_map(1)
Simplicial set morphism:
From: Wedge: (S^2 v S^3 v S^2)
To: Quotient: (Wedge: (S^2 v S^3 v S^2)/Simplicial set with 3 non-degenerate simplices)
Defn: [*, sigma_2, sigma_2, sigma_3] --> [*, s_1 s_0 *, s_1 s_0 *, sigma_3]
Note that the codomai... | |
import json
from django.core import mail
from .. import test
from ...acl.test import patch_user_acl
from ...users.test import create_test_user
from ..models import Thread, ThreadParticipant
from ..test import other_user_cant_use_private_threads
from .test_privatethreads import PrivateThreadsTestCase
class PrivateTh... | |
<filename>neo4j/aio/__init__.py
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright (c) 2002-2019 "Neo4j,"
# Neo4j Sweden AB [http://neo4j.com]
#
# This file is part of Neo4j.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
... | |
'wcfg':{'bd':6},
'gridcfg':{'sticky':tkinter.E+tkinter.W, 'column': 3, 'row':-1,'columnspan':3},
'command':self.Close_cb})
def setNumEvals(self, event=None):
t = self.ifd.entryByName['run_type']['widget'].get()
self.ga_num_evals.set(self.runDict[t])
self.runType.set(t)
def set_crossover_mode(self, event=None... | |
# Copyright (c) 2022, NVIDIA 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.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | |
<reponame>yjbanov/chromium_build<filename>scripts/slave/recipe_modules/v8/testing.py<gh_stars>0
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import re
from recipe_engine.types import freeze
TEST_CONFI... | |
label = 'Tumor-Normal-{}'.format(tissue)
else:
n = gtex[gtex.tissue == tissue][gene].median()
label = 'Tumor-GTEx-{}'.format(tissue)
# Calculate l2fc for each tumor sample and save
l2fcs = []
for i, row in tumor[tumor.tissue == tissue].iterrows():
l2fcs.append(log2fc(row[gene], n))
# Create distribution
dist... | |
"""
Modular ball chaser robot.
To play yourself, type:
python modular_ball_chaser.py
Created by <NAME>. Licensed on the same terms as the rest of OpenAI Gym.
Modified by <NAME>.
"""
import numpy as np
import Box2D
from Box2D.b2 import fixtureDef
from Box2D.b2 import circleShape
from Box2D.b2 import polygonShape
fro... | |
# -*- coding: utf-8 -*-
"""
eve.flaskapp
~~~~~~~~~~~~
This module implements the central WSGI application object as a Flask
subclass.
:copyright: (c) 2013 by <NAME>.
:license: BSD, see LICENSE for more details.
"""
import eve
import sys
import os
from flask import Flask
from werkzeug.routing import BaseConver... | |
"metadataonly",
("prop", "1943:309"): "metadataonly",
("prop", "1943:31"): "metadataonly",
("prop", "1943:310"): "metadataonly",
("prop", "1943:311"): "metadataonly",
("prop", "1943:312"): "metadataonly",
("prop", "1943:313"): "metadataonly",
("prop", "1943:314"): "metadataonly",
("prop", "1943:315"): "metadata... | |
as uuid on user.id = uuid.user_id where uuid.uuid = '%s' """ % uuid
try:
cur.execute(sql)
except sqltool.Error as e:
funct.out_error(e)
else:
for user_id in cur.fetchall():
return user_id[0]
cur.close()
con.close()
def get_user_telegram_by_uuid(uuid):
con, cur = get_cur()
sql = """ select telegram.... | |
style.A.update({'type':'text/css'})
>>> html = style.render()
>>> a = '<style type="text/css">body { margin:4px; } p { color:blue; }</style>'
>>> b = '<style type="text/css">p { color:blue; } body { margin:4px; }</style>'
>>> html in (a,b) # order is indeterminate, so test both ways
True
>>> Style(body=dict(_moz_... | |
import base64
import json
import uuid
from abc import ABCMeta, abstractmethod # Abstract Base Class
import logging
from typing import List, Union, Dict, Any
from nexinfosys import Issue, IssuesOutputPairType
from nexinfosys.common.helper import create_dictionary, PartialRetrievalDictionary
logger = logging.getLogger... | |
# This file is part of PRAW.
#
# PRAW is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# PRAW is distributed in the hope that i... | |
the Android '
'NDK, not that you don\'t have a normal compiler '
'installed. Exiting.')
exit(1)
env['CC'] = '{toolchain_prefix}-gcc {cflags}'.format(
toolchain_prefix=toolchain_prefix,
cflags=env['CFLAGS'])
env['CXX'] = '{toolchain_prefix}-g++ {cxxflags}'.format(
toolchain_prefix=toolchain_prefix,
cxxflags=en... | |
try:
iwd = Path(job_ad["iwd"])
except KeyError:
raise KeyError("Could not find iwd in job ad.")
return iwd / container_image
def annex_inner_func(
logger,
annex_name,
nodes,
lifetime,
allocation,
queue_at_machine,
owners,
collector,
token_file,
password_file,
ssh_target,
control_path,
cpus,
mem_mb,... | |
from enum import Enum, auto
import itertools
from .figure import Figure, Circle
from .scene import Scene
from .util import Comment, divide, normalize_number, keys_for_triangle
class Property:
def __init__(self, property_key, point_set):
self.implications = []
self.property_key = property_key
self.point_set = poin... | |
<reponame>joschabach/micropsi2<filename>micropsi_core/nodenet/native_modules.py
"""
Builtin native modules
Currently contains
* GradientDescent for 3 layers (input, hidden, outpu)
* GradientDescent for LSTMS
"""
import os
nodetypes = {}
try:
import numpy as np
import theano
numpy_installed = True
except Import... | |
<filename>src/panfrost/bifrost/valhall/valhall.py
#encoding=utf-8
# Copyright (C) 2016 Intel Corporation
# Copyright (C) 2016 Broadcom
# Copyright (C) 2020 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Softwa... | |
<filename>rpython/jit/backend/llvm/llvm_api.py<gh_stars>1-10
from rpython.rtyper.lltypesystem import rffi, lltype
from rpython.translator.tool.cbuild import ExternalCompilationInfo
from rpython.rtyper.lltypesystem.rffi import str2constcharp, constcharp2str
class LLVMAPI:
def __init__(self, debug=False):
self.debug =... | |
import argparse
import time
import pickle
import os
import json
import numpy as np
# import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_probability as tfp
from utils import plot_mnist, generate_init_inducing_points, import_... | |
value=None):
"""Corresponds to IDD field `Drift Loss Fraction`"""
self["Drift Loss Fraction"] = value
@property
def blowdown_concentration_ratio(self):
"""field `Blowdown Concentration Ratio`
| Characterizes the rate of blowdown in the evaporative cooler.
| Blowdown is water intentionally drained from the cool... | |
word[6] == "n" :
toGuess = toGuess[:6] + "n" + toGuess[7:]
if word[1] != "N" and word[1] != "n" and word[2] != "N" and word[2] != "n" and word[3] != "N" and word[3] != "n" and word[4] != "N" and word[4] != "n" and word[5] != "N" and word[5] != "n" and word[6] != "N" and word[6] != "n" :
print("\nWrong!\n")
... | |
(120.4679, 0.48156900000000002),
(40.980319999999999, 0.34456520000000002)]),
('S',
[(786.28520000000003, 0.0024518629999999999),
(186.887, 0.032595789999999999),
(60.009349999999998, 0.1238242),
(22.25883, -0.043598900000000003),
(8.8851490000000002, -0.61771810000000005),
(3.6092110000000002, -0.4432823000000... | |
. is_exact_match ( address ) ) : return ( OooOoOoo0OOoo )
if 32 - 32: OoooooooOO . I1Ii111 - I1ii11iIi11i
return ( None )
if 29 - 29: OoO0O00
if 33 - 33: I1ii11iIi11i - O0
if 72 - 72: Oo0Ooo * iII111i - I11i
if 81 - 81: I1Ii111
if 85 - 85: O0 % OoOoOO00 . I1ii11iIi11i
if 46 - 46: OOooOOo * iIii1I11I1II1
if 33 ... | |
<filename>tests/integration/test_s3.py
import io
import os
import ssl
import boto3
import gzip
import json
import time
import uuid
import unittest
import datetime
import requests
from io import BytesIO
from pytz import timezone
from urllib.parse import parse_qs, quote
from botocore.exceptions import ClientError
from si... | |
:param cloned_requirements_count: Number of Requirments cloned so far.
:type cloned_requirements_count: int
:param cloned_shared_steps_count: Number of shared steps cloned so far.
:type cloned_shared_steps_count: int
:param cloned_test_cases_count: Number of test cases cloned so far
:type cloned_test_cases_count: ... | |
del_objects=del_objects)
def delete_object(self, container, obj):
"""
Deletes the object from the specified container.
The 'obj' parameter can either be the name of the object, or a
StorageObject representing the object to be deleted.
"""
return self._manager.delete_object(container, obj)
def copy_object(s... | |
<filename>qiskit/providers/ibmq/experiment/ibm_experiment_service.py<gh_stars>100-1000
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# 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 o... | |
self._md_template.translate_cols_dict.values():
handler = (
lambda x: self._md_template.str_cols_handlers[key][x])
key = "%s_id" % key
# Check if we have either to query the table with required columns
# or the dynamic table
if key in get_table_cols(self._table, conn_handler):
result = conn_handler.execute_fetch... | |
values include: "Default", "Copy", "Secondary", "PointInTimeRestore",
"Restore", "Recovery", "RestoreExternalBackup", "RestoreExternalBackupSecondary",
"RestoreLongTermRetentionBackup", "OnlineSecondary".
:type create_mode: str or ~azure.mgmt.sql.models.CreateMode
:param collation: The collation of the database.
:... | |
import numpy as np
import matplotlib.pyplot as plt
from qibo.models import Circuit
from qibo import gates
import aux_functions as aux
def rw_circuit(qubits, parameters, X=True):
"""Circuit that implements the amplitude distributor part of the option pricing algorithm.
Args:
qubits (int): number of qubits used for ... | |
"""
jobs.py - base notification routines
Author
<NAME> <<EMAIL>>
License
Copyright (c) 2010-2012 Massachusetts Institute of Technology.
MIT License (cf. MIT-LICENSE.txt or http://www.opensource.org/licenses/mit-license.php)
"""
import sys,os
import datetime
if "." not in sys.path:
sys.path.append(".")
if "DJANG... | |
df = df.dropna(subset=[CN.cdr3b, CN.epitope])
df = df[
(df[CN.cdr3b].map(is_valid_aaseq)) &
(df[CN.epitope].map(is_valid_aaseq))
]
logger.debug('Current df_enc.shape: %s' % str(df.shape))
logger.debug('Loaded Zhang data. Current df_enc.shape: %s' % str(df.shape))
return df
class IEDBTCREpitopeDFLoader(FileTCRE... | |
to shift and scale the distribution. Specifically,
this is equivalent to computing :math:`f(y)` where :math:`y=(x-loc)/scale`.
**Inputs:**
* **loc** (`float`):
location parameter
* **scale** (`float`):
scale parameter
The following methods are available for ``Rayleigh``:
* ``cdf``, ``pdf``, ``log_pdf``, ``i... | |
import numpy as np
import matplotlib as mpl
if os.environ.get('DISPLAY','') == '':
print('no display found. Using non-interactive Agg backend')
mpl.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import paths
import counterfactuals.infrastructurefunctions as infr
import counterfactua... | |
<reponame>schnusch/nimble2nix
#!/usr/bin/env nix-shell
#!nix-shell -i python3 -p git nim nix-prefetch-git python3Packages.packaging
import argparse
import contextlib
from functools import cache
import itertools
import json
import logging
import os
import shlex
import subprocess
import sys
import tempfile
import urllib.... | |
else:
v_sql = v_sql.replace('--#FILTER_PATTERN_REGEX_CASE_INSENSITIVE#', '').replace('#VALUE_PATTERN_REGEX_CASE_INSENSITIVE#', p_textPattern.replace("'", "''"))
else:
if p_caseSentive:
v_sql = v_sql.replace('--#FILTER_PATTERN_CASE_SENSITIVE#', '').replace('#VALUE_PATTERN_CASE_SENSITIVE#', p_textPattern.replace("'",... | |
assert isinstance(event, Event)
assert isinstance(event.assoc, Association)
assert isinstance(event.timestamp, datetime)
assert event.event.name == 'EVT_ABORTED'
scp.shutdown()
def test_abort_bind(self):
"""Test binding a handler to EVT_ABORTED."""
triggered = []
def handle(event):
triggered.append(event)
... | |
need any diffs
if not self.produce_diffs:
return {}
result = {}
for col in self.diff_generator_data:
# Only process attributes for which out it set.
attname = col['out']
incol = (col['in'] if 'in' in col and col['in'] else attname)
# if diff is False = copy the attribute as is.
if 'diff' in col and col['diff']... | |
label='IMF 1 with 11 knots')
axs[2].plot(time, imfs_31[2, :], label='IMF 2 with 31 knots')
axs[2].plot(time, imfs_51[3, :], label='IMF 3 with 51 knots')
for knot in knots_11:
axs[2].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1)
axs[2].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '-... | |
str):
lines.append(Line(x=args[i],
y=args[i+1],
format=args[i+2]))
i = i+3
else:
lines.append(Line(y=args[i+1],
x=args[i],
format=''))
i = i+2
# Next element is str --> no x-value
else:
lines.append(Line(y=args[i],
x='auto',
format=args[i+1]))
i = i+2
# These last cases could be run outside the while l... | |
<filename>pycrud/query.py
import dataclasses
import json
from dataclasses import dataclass, field
from typing import List, Union, Set, Dict, Any, Type, Mapping
from typing_extensions import Literal
from pycrud.const import QUERY_OP_COMPARE, QUERY_OP_RELATION, QUERY_OP_FROM_TXT
from pycrud.error import UnknownQueryOpe... | |
<reponame>ujjwalsh/CSB<filename>csb/bio/fragments/rosetta.py
"""
Rosetta fragment libraries.
This module defines the L{RosettaFragmentMap} objects, which describes a
fragment library in Rosetta NNmake format. L{RosettaFragmentMap} has a
static factory method for building a library from a fragment file:
>>> Rosetta... | |
<filename>Dietscheduler/lib/diet_sched.py
from pulp import *
from collections import defaultdict
import json
import math
import itertools
import datetime
class Menu:
'''class for all menues to be built'''
def __init__(self):
self.status = False
def calculate_menu(self,food_database,groups,exclude_list... | |
"""
In fit phase, only select motifs.
table: start index, weight, column it applies to, and count of rows that follow motif
slice into possible motifs
compare motifs (efficiently)
choose the motifs to use for each series
if not shared, can drop column part of index ref
combine the following values into forecasts... | |
tok in break_tokens:
if tok in tokenizer.encode(tokenizer._eos_token):
continue
new_tokens.append(tok)
# ipdb.set_trace()
response = tokenizer.decode(new_tokens).strip(' ,.')
return response
def convert_belief(belief):
dic = {}
for bs in belief:
if bs in [' ', '']:
continue
domain = bs.split(' ')[0]
slot ... | |
SLIDE MICROSCOPY IOD': ['Series'],
'12-LEAD ECG IOD': ['Series'],
'MR IMAGE IOD': ['Series'],
'ENHANCED MR COLOR IMAGE IOD': ['Series'],
'ENHANCED CT IMAGE IOD': ['Series'],
'XRF IMAGE IOD': ['Series'],
'RESPIRATORY WAVEFORM IOD': ['Series'],
'GENERAL AUDIO WAVEFORM IOD': ['Series'],
'GRAYSCALE SOFTCOPY PRESENT... | |
<gh_stars>1-10
""" Contains for for Gaussian process Bayesian optimization """
import logging
import random
import pprint
import heapq
from typing import Union
import numpy as np
import torch
from function_utils import CachedFunction, CachedBatchFunction
from gp import TanimotoGP, batch_predict_mu_var_numpy
from gra... | |
<reponame>armel/RRFDisplay
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
RRFDisplay version Raspberry Pi 3B et Orange Pi Zero
Learn more about RRF on https://f5nlg.wordpress.com
Check video about RRFDisplay on https://www.youtube.com/watch?v=rVW8xczVpEo
73 & 88 de F4HWN Armel
'''
import settings as s
import lib ... | |
np.cos(drive_cell[t - 1]))) * ((1.0 - s_de[:, t - 1]) / self.tau_R))
s_db[:, t] = s_db[:, t - 1] + self.dt * (-1.0 * (s_db[:, t - 1] / self.tau_ex) + np.exp(
-1.0 * self.eta * (1 + np.cos(drive_cell[t - 1]))) * ((1.0 - s_db[:, t - 1]) / self.tau_R))
s_dc[:, t] = s_dc[:, t - 1] + self.dt * (-1.0 * (s_dc[:, t - 1] ... | |
+f on the 2-dimensional topological manifold M
sage: g == f
True
"""
result = type(self)(self.parent())
for chart in self._express:
result._express[chart] = + self._express[chart]
if self._name is not None:
result._name = '+' + self._name
if self._latex_name is not None:
result._latex_name = '+' + self._late... | |
import numpy as np
def length(x, axis=-1, keepdims=True):
"""
Computes vector norm along a tensor axis(axes)
:param x: tensor
:param axis: axis(axes) along which to compute the norm
:param keepdims: indicates if the dimension(s) on axis should be kept
:return: The length or vector of lengths.
"""
lgth = np.sqr... | |
<reponame>chuckyin/Instruments
# coding=utf-8
# =============================================================================
# Copyright © 2017 FLIR Integrated Imaging Solutions, Inc. All Rights Reserved.
#
# This software is the confidential and proprietary information of FLIR
# Integrated Imaging Solutions, Inc. ("C... | |
else:
self.largest_mcs_mmp_result[(molid_L, molid_R)] = [
(self.ref_smi_props[ctx_id], ), (ctx_id, ), frag_L_id, frag_R_id]
# now build the final results on the fly
# double - for each one we compare against what we already have in self.largest_mcs_mmp_result
ctx_natoms = None
if cut_type_id >= 2:
for molid_... | |
<reponame>cdmacfadyen/MedPicPy<gh_stars>1-10
"""medpicpy's higher level functions to abstract over reading
in medical imaging data
"""
import glob
from pathlib import Path
from os.path import normpath
import pandas as pd
import numpy as np
import cv2
import logging
from . import io
from .utils import remove_sub_pat... | |
'Yulin, Guangxi', 'zh': u('\u5e7f\u897f\u7389\u6797\u5e02')},
'861777614':{'en': 'Yulin, Guangxi', 'zh': u('\u5e7f\u897f\u7389\u6797\u5e02')},
'861777615':{'en': 'Yulin, Guangxi', 'zh': u('\u5e7f\u897f\u7389\u6797\u5e02')},
'861777616':{'en': 'Baise, Guangxi', 'zh': u('\u5e7f\u897f\u767e\u8272\u5e02')},
'861777617'... | |
<reponame>ndessart/olympe<gh_stars>0
# -*- coding: UTF-8 -*-
# Copyright (C) 2019 Parrot Drones SAS
#
# 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
#... | |
"""
Operative and Processing Interface - OPI module of SOSim application.
Copyright (C) 2019 <NAME> & <NAME>
This file is part of SOSim - Subsurface Oil Simulator.
SOSim is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software F... | |
"""Implements a class for Latin Square puzzles.
A Latin Square is a square grid of numbers from 1..N, where a number may not
be repeated in the same row or column. Such squares form the basis of puzzles
like Sudoku, Kenken(tm), and their variants.
Classes:
LatinSquare: Implements a square puzzle constrained by not r... | |
################################################################################
# Copyright (c) 2017 <NAME>, <NAME>, <NAME>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restricti... | |
[False, True])
def test_numpy_properties(self):
data = np.arange(6).reshape(3, 2)
arr = TensorArray(data)
self.assertEqual(arr.numpy_ndim, data.ndim)
self.assertEqual(arr.numpy_shape, data.shape)
self.assertEqual(arr.numpy_dtype, data.dtype)
def test_bool_tensor_selection(self):
data = TensorArray([[1, 2], [3... | |
output = StockItem.objects.get(pk=output)
context['output'] = output
context['fully_allocated'] = build.isFullyAllocated(output)
context['allocated_parts'] = build.allocatedParts(output)
context['unallocated_parts'] = build.unallocatedParts(output)
except (ValueError, StockItem.DoesNotExist):
pass
return contex... | |
indicatorOfParameter == 215:
return '0to1'
if table2Version == 203 and indicatorOfParameter == 214:
return '0to1'
if table2Version == 203 and indicatorOfParameter == 213:
return 'kg m-2'
if table2Version == 203 and indicatorOfParameter == 212:
return 'kg/m2/h'
if table2Version == 203 and indicatorOfParamete... | |
enormous_training
assert training_size == (len(no_training) +
len(tiny_training) +
len(low_training) +
len(medium_training) +
len(high_training) +
len(huge_training))# +
#len(enormous_training))
no_testing = no_cer_set[no_training_size:]
tiny_testing = tiny_cer_set[tiny_training_size:]
low_testing = low_cer... | |
**kwargs):
mypatch = []
for key, value in kwargs.items():
mypatch.append(dict(path='/' + key, value=value, op='replace'))
return cgtsclient(request).icpu.update(cpu_id, mypatch)
def host_memory_list(request, host_id):
memorys = cgtsclient(request).imemory.list(host_id)
return [Memory(n) for n in memorys]
def ... | |
self.private_endpoint_status = None
class OriginGroup(Resource):
"""Origin group comprising of origins is used for load balancing to origins when the content cannot be served from CDN.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Resource ID.
:vartype id: str... | |
context.get_admin_context(), router1['id'],
{'subnet_id': sub['subnet']['id']})
self.l3_plugin.add_router_interface(
context.get_admin_context(), router['id'],
{'subnet_id': sub3['subnet']['id']})
self.l3_plugin.add_router_interface(
context.get_admin_context(), router1['id'],
{'subnet_id': sub_route_leak['subne... | |
<reponame>basvandervlies/cfengine_beautifier<filename>cfbeautifier/parser.py
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from . import lexer
from .util import ParserError
from . import structure
from . import util
from .version_abstraction import ... | |
<filename>main_fr.py
import imp
import time
#======================================================================
def board_print(board, move=[], num=0):
print("====== The current board(", num, ") is (after move): ======")
if move: # move not empty
print("move = ", move)
for i in [4, 3, 2, 1, 0]:
... | |
<filename>epic_stuff_and_things.py
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import sys
print("")
print("")
print("")
print( "Epic Stuff and Things" )
print( "By: <NAME>")
name = input("Enter your name: ")
color = input("Enter a color: ")
print("")
print("Welcome to epic stuff an... | |
<gh_stars>0
#!/usr/bin/env python
# Copyright (C) 2015 OpenStack, 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/LICENSE-2.0
#
# Unless required by ap... | |
<gh_stars>10-100
#!/usr/bin/python
import numpy as np
import scipy.special as spc
'''
We have oribtals
Phi_1 = c_a * chi_a + c_b * chi_b
Phi_2 = c_c * chi_c + c_d * chi_d
where chi_i are gaussian type basis functions
and c_i are expansion coefficients
electron density of molecular orbitals Rho_1 = <phi_1|phi_1>... | |
<gh_stars>10-100
# -*- coding: utf-8 -*-
'''
stacking.py raet protocol stacking classes
'''
# pylint: skip-file
# pylint: disable=W0611
# Import python libs
import socket
import binascii
import struct
try:
import simplejson as json
except ImportError:
import json
# Import ioflo libs
from ioflo.aid.odicting import ... | |
to compute the output shape.
Input shape:
This depends on the `layout` parameter. Input is 4D array of shape
(batch_size, channels, height, width) if `layout` is `NCHW`.
Output shape:
This depends on the `layout` parameter. Output is 4D array of shape
(batch_size, channels, out_height, out_width) if `layout` i... | |
def table_slice_2_cc1(table, r2, r_max, c1, c2):
"""
Function to cut a correct slice out of array for CC1 in _find_cc1_cc2().
Cuts out the row header.
"""
# one more row and column index than in the published pseudocode is needed,
# since the a:b notation in python doesn't include b
# contrary to the published p... | |
from datetime import timedelta
from astropy import units as u
import numpy as np
from sunpy.time import parse_time
def get_sky_position(time, offset):
"""Code for converting solar offsets to pointing position.
Parameters
----------
time: Date that is parsable by sunpy.time.parse_time()
i.e.,
time='2016-07-2... | |
<reponame>ActionAnalytics/tfrs
"""
REST API Documentation for the NRS TFRS Credit Trading Application
The Transportation Fuels Reporting System is being designed to streamline
compliance reporting for transportation fuel suppliers in accordance with
the Renewable & Low Carbon Fuel Requirements Regulation.
OpenAP... | |
# -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
#
# Copyright 2019, Battelle Memorial Institute.
#
# 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... | |
'C', 10,'AN'],
['SRT07', 'C', 10,'AN'],
['SRT08', 'C', 2,'AN'],
['SRT09', 'C', 7,'N1'],
['SRT10', 'C', 7,'N1'],
['SRT11', 'C', 3,'R'],
['SRT12', 'C', (3,3),'AN'],
['SRT13', 'C', (2,25),'AN'],
],
'SS': [
['BOTSID', 'M', 3,'AN'],
['SS01', 'M', (6,6),'DT'],
['SS02', 'M', 5,'AN'],
['SS03', 'M', 1,'AN'],
['SS04'... | |
code-block:: python
'''
with fluid.layers.Switch() as switch:
with switch.case(cond1):
i = fluid.layers.fill_constant(shape=[1], dtype='int64', value=1)
with switch.case(cond2):
i = fluid.layers.fill_constant(shape=[1], dtype='int64', value=2)
with switch.default():
i = fluid.layers.fill_constant(shape=[1], dt... | |
<filename>src/classify.py
import csv, os, json, argparse, sys, random
from rdkit import Chem
"""
Load data from directory, classify given molecule or test file
"""
# Walk reverse ontology subgraph (root = hitem) upwards, depth first. If any member of hitemset
# is encountered, add it to minor set. These are later di... | |
"""
Решения задач пробного раунда онлайн-чемпионата по программированию Yandex Сup в категории Алгоритм.
https://contest.yandex.ru/yacup/
"""
from time import time
def A():
"""
На различных мероприятиях команда стажировок регулярно разыгрывает призы в лотерею.
Организаторы выбирают 10 случайных различных чисел от... | |
<reponame>alecomunian/geone<filename>geone/customcolors.py<gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Python module: 'customcolors.py'
author: <NAME>
date: jan-2018
Definition of custom colors and colormap.
"""
import numpy as np
import matplotlib.colors as mcolors
import matplotlib.pyplot as pl... | |
<reponame>Mikehem/tfx<filename>tensorflow_transform/tf_utils.py
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/lic... | |
import random
import pytest
from faker import Faker
from flask import url_for
from .models import Location, Address, Area, Country, AreaSchema, LocationSchema, AddressSchema
from .. import db
from ..images.create_image_data import create_images_locations, create_test_images
from ..images.models import Image, ImageLoc... | |
import * # NOQA
>>> scores, labels = testdata_scores_labels()
>>> self = ConfusionMetrics().fit(scores, labels)
>>> xdata = self.tpr
>>> ydata = self.thresholds
>>> pt = 1.0
>>> #xdata = self.fpr
>>> #ydata = self.thresholds
>>> #pt = 0.0
>>> thresh = interpolate_replbounds(xdata, ydata, pt, maximize=True)
>>... | |
source, destination, extraHopLimit = 0 ):
"""Same as findShortestPaths, but it uses the heuristic path
so it runs much faster. I believe the results should be
the same, but I have not thought about it enough to be able to
be certain about it."""
if not self.neighboursFound:
self.findNeighbours()
if so... | |
/ 2) + 30)
y = 0
while left > 0 :
if getTile(x + dX, y) != Tiles.NOTHING:
setTile(x + dX, y, Tiles.SAND)
left -= 1
y += 1
print("Rocks in dirt")
for i in range(1000):
x = random.randrange(0, WORLD_WIDTH)
y = random.randrange(0, WORLD_HEIGHT // 2.8)
if getTile(x, y) == Tiles.DIRT:
clump(x, y, poisson(10), ... | |
<filename>jiant/tasks/lib/templates/shared.py
import numpy as np
from dataclasses import dataclass
from typing import List, NamedTuple, Tuple
from jiant.tasks.core import FeaturizationSpec
from jiant.tasks.utils import truncate_sequences, pad_to_max_seq_length
from jiant.utils.python.datastructures import BiMap
MAX_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.