input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<filename>games/shelf/sawyer_shelf.py
'''
copied and modified from the MELD code
https://github.com/tonyzhaozh/meld
'''
from collections import OrderedDict
import numpy as np
import math
from gym.spaces import Dict, Box
from gym import utils
import os
from gym.envs.mujoco import mujoco_env
SCRIPT_DIR = os.path.dirname... | |
# coding=utf-8
#
# This file is part of Hypothesis (https://github.com/DRMacIver/hypothesis)
#
# Most of this work is copyright (C) 2013-2015 <NAME>
# (<EMAIL>), but it contains contributions by others. See
# https://github.com/DRMacIver/hypothesis/blob/master/CONTRIBUTING.rst for a
# full list of people who may hold c... | |
import argparse
import mock
import requests
from cloud_info_provider.providers import ooi as ooi_provider
from cloud_info_provider.providers import openstack as os_provider
from cloud_info_provider.tests import base, data
from cloud_info_provider.tests import utils as utils
from six.moves.urllib.parse import urljoin
... | |
= StringIO()
geometry.show_sorted(
sites_cart=xrs.sites_cart(),
site_labels=xrs.scatterers().extract_labels(),
f=init_out)
energy_original = geometry.energies_sites(sites_cart=xrs.sites_cart())
t0 = time()
#import code, traceback; code.interact(local=locals(), banner="".join( traceback.format_stack(limit=10) ) )... | |
packet_chunk['HASVALID']:
string = ""
if (configuration['TX_PACKET_ID_WIDTH'] if direction == 'slave' else configuration['RX_PACKET_ID_WIDTH']) == 0:
string += " ((rx_grant_enc_data == {}'d{}) &&".format(1, packet_chunk['LAST_PKT_ENC'])
string += " ({} [{}] == 1'b1))".format("rx_packet_data", packet_chunk['PUSHBIT_... | |
<gh_stars>0
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# File name : controller.py
# Description : Controller PC
# Website : www.adeept.com
# E-mail : <EMAIL>
# Author : William
# Date : 2018/08/22
# Modified : seb3n
# Mod date : 2021/08/15
from socket import *
import time
import threading as thread
impo... | |
duplicate geometries.
Args:
input_path (PathLike): the input file
output_path (PathLike): the file to write the result to
input_layer (str, optional): input layer name. Optional if the input
file only contains one layer.
output_layer (str, optional): input layer name. Optional if the input
file only contains on... | |
chassis_id_mac_address = 4
Chassis ID is a MAC address
.. data:: chassis_id_network_address = 5
Chassis ID is a network address
.. data:: chassis_id_interface_name = 6
Chassis ID is an interface name
.. data:: chassis_id_local = 7
Chassis ID is a local name
.. data:: chassis_id_unknown_type = 8
U... | |
[target]
return df.drop(columns=target), df[target].values.ravel()
def format_cell(bg, t='black'):
return f'background-color: {bg};color: {t};'
def bg(style, subset=None, rev=True, axis=0):
"""Show style with highlights per column"""
if subset is None:
subset = style.data.columns
cmap = _cmap.reversed() if r... | |
import random
import pandas as pd
import pytest
from evalml.preprocessing.data_splitters import BalancedClassificationSampler
@pytest.mark.parametrize("ratio,samples,percentage,seed",
[(1, 1, 0.2, 1),
(3.3, 101, 0.5, 100)])
def test_balanced_classification_init(ratio, samples, percentage, seed):
bcs = BalancedCl... | |
np.linspace(0.0, duration, num=N)
node_map = {}
for func in self.instance_constraint_function_atoms:
time_value = func.args[0]
time_index = np.argmin(np.abs(time_vector - time_value))
free_index = determine_free_index(time_index,
func.__class__(self.time_symbol))
node_map[func] = free_index
self.instance_cons... | |
this round."
if type(prize) == int:
print playerOrder[j + 1] + " now takes possession of The Wheel."
else:
print "Your Free Play spin, however, means that you keep possession of The Wheel."
print ""
if type(prize) == int:
break
if prize == "bankrupt":
print ""
print playerOrder[j], "spun for BANKRUPT, bringi... | |
"""
System tests.
<NAME> <<EMAIL>>
pytest tmpdir docs:
http://doc.pytest.org/en/latest/tmpdir.html#the-tmpdir-fixture
"""
import copy
import shutil
import re
from pathlib import Path
import textwrap
import click.testing
from mailmerge.__main__ import main
from . import utils
def test_no_options(tmpdir):
"""Verify ... | |
import json
import thread
from appscale.tools.agents.base_agent import AgentConfigurationException
from appscale.tools.agents.base_agent import AgentRuntimeException
from appscale.tools.agents.base_agent import BaseAgent
from appscale.tools.agents.factory import InfrastructureAgentFactory
from utils import utils
from... | |
<filename>tests/data23/recipe-577507.py
##
# This module provides a powerful 'switch'-like dispatcher system.
# Values for switch cases can be anything comparable via '==', a string
# for use on the left-hand side of the 'in' operator, or a regular expression.
# Iterables of these types can also be used.
__author__ = ... | |
# from https://github.com/Subaru-PFS/drp_stella/blob/\
# 6cceadfc8721fcb1c7eb1571cf4b9bc8472e983d/src/SpectralPsf.cc
# // Binning by an odd factor requires the centroid at the center of a pixel.
# // Binning by an even factor requires the centroid on the edge of a pixel.
# the definitions used in primary image
# ... | |
import numpy as np
import ctypes as c
import os
# output params :
# 0 objective function
# 1 camber angle down
# 2 up
# 3 toe angle down
# 4 up
# 5 caster angle
# 6 roll centre height
# 7 caster trail
# 8 scrub radius
# 9 kingpin angle
# 10 anti squat / anti dive drive
# 11 anti rise / anti lift brake
# 12 half track ... | |
"""This serves as a main function to run a worker."""
from qip.distributed.proto import *
from qip.distributed.proto.conversion import *
from qip.distributed.worker.worker_backends import SocketServerBackend
from qip.distributed.worker.worker_logger import WorkerLogger, PrintLogger
from qip.distributed.formatsock impor... | |
= active_selection
logging.info('Toolkit: __init__ got active selection: {0}'
''.format(self.active_selection))
super(BaseListItemViewsOperationTool, self).__init__(app=app,
editor_widget=editor_widget,
command_widget=command_widget,
**kwargs)
def create_editor_widgets(self):
editor_widgets = collections.Orde... | |
are ordered by time, with newest backups first. If you do not specify a BackupId or ServerName, the command returns all backups.
This operation is synchronous.
A ``ResourceNotFoundException`` is thrown when the backup does not exist. A ``ValidationException`` is raised when parameters of the request are not valid. ... | |
on devices that directly access hardware, and therefore
# should have their actions simulated.
hardware_access = True
# This is set by NICOS to indicate that do-methods should be intercepted
# and their result simulated. Combines hardware_access and device mode
# at runtime.
_sim_intercept = True
# Autogenerat... | |
<gh_stars>0
# -*- coding:utf-8 -*-
__author__ = 'q00222<EMAIL>'
import os
import aws_util
import json
import log as logger
import aws_access_cloud_data_handler as data_handler
_install_conf = os.path.join("/home/hybrid_cloud/conf",
'aws_access_cloud_install.conf')
def _read_install_conf():
if not os.path.exists(... | |
Filters')
imageFiltersWindow.attributes('-toolwindow', 1) # Makes window framing small, like a toolbox/widget.
# Calculate the spawning position of the new window
rootDistanceFromScreenLeft, rootDistanceFromScreenTop = getWindowGeometry( Gui.root )[2:]
imageFiltersWindow.geometry( '+' + str(rootDistanceFr... | |
disk space.
:param id: tenant id, used for the 'href' link
:type id: ``str``
:return: Returns a flask response with a list of all flavors with additional information.
:rtype: :class:`flask.response`
"""
LOG.debug("API CALL: %s GET" % str(self.__class__.__name__))
try:
resp = dict()
resp['flavors'] = list()
f... | |
'properties.networkAcls', 'type': 'NetworkRuleSet'},
'is_hns_enabled': {'key': 'properties.isHnsEnabled', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(StorageAccount, self).__init__(**kwargs)
self.sku = None
self.kind = None
self.identity = kwargs.get('identity', None)
self.provisioning_state = ... | |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2016-present MagicStack Inc. and the EdgeDB authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://w... | |
= [os.path.splitext(fname)[0] for fname in possibly_encrypted]
if corp_fname in spl1:
ix = spl1.index(corp_fname)
db = opened_db[ix]
print("\n >>>> {} <<<<".format(db.fname()))
for k,v in db.get_all_attr().items():
print " {} = '{}';".format(k,v)
elif corp_fname in spl2:
if not encryption_key:
logger.error("... | |
tvm_out)
def test_where():
condition = np.array([[1, 0], [1, 1]], dtype=np.bool)
x = np.array([[1, 2], [3, 4]], dtype=np.int64)
y = np.array([[9, 8], [7, 6]], dtype=np.int64)
outdata = np.where(condition, x, y)
verify_where(condition, x, y, TensorProto.INT64, outdata)
x = np.array([[1, 2], [3, 4]], dtype=np.fl... | |
# -*- coding: utf-8 -*-
################################################
###### Copyright (c) 2016, <NAME>
###
import numpy as np
import itertools
import time
from .categoryaction import CatObject
class MultQ(object):
def __init__(self,x):
"""Initializes an element of the multiplicative quantale.
Parameters
---... | |
<filename>dim-testsuite/tests/dns_test.py
from dim import db
from dim.dns import get_ip_from_ptr_name
from dim.rrtype import validate_strings
from dim.errors import InvalidParameterError, AlreadyExistsError, InvalidZoneError, DimError
from tests.util import RPCTest, raises
def test_validate_strings():
validate_strin... | |
"""
Copyright thautwarm (c) 2019
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 conditions and the following di... | |
<reponame>OuyangChao/Paddle<filename>python/paddle/fluid/tests/unittests/test_cross_entropy_loss.py<gh_stars>1-10
# 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 m... | |
codomain = FloatDomain()
class BindRoundTo(BindPolyFunction):
call(('round', 2))
signature = RoundToSig
hint = """round(x, n) -> x rounded to a given precision"""
class CorrelateDecimalRoundTo(CorrelateFunction):
match(RoundToSig, (IntegerDomain, IntegerDomain),
(DecimalDomain, IntegerDomain))
signature = R... | |
<filename>bindings/python/capstone/arm64_const.py
# For Capstone Engine. AUTO-GENERATED FILE, DO NOT EDIT [arm64_const.py]
# ARM64 shift type
ARM64_SFT_INVALID = 0
ARM64_SFT_LSL = 1
ARM64_SFT_MSL = 2
ARM64_SFT_LSR = 3
ARM64_SFT_ASR = 4
ARM64_SFT_ROR = 5
# ARM64 extender type
ARM64_EXT_INVALID = 0
ARM64_EXT_UXTB = 1... | |
import math
from math import log2, exp
import numpy as np
import torch
from torch import nn
from torch.nn.functional import softplus
import torch.nn.functional as F
from torch.autograd import grad
from typing import List, Callable, Union, Any, TypeVar, Tuple
# from torch import tensor as Tensor
Tensor = TypeVar('torc... | |
"""The base class for many SciUnit objects."""
import sys
PLATFORM = sys.platform
PYTHON_MAJOR_VERSION = sys.version_info.major
if PYTHON_MAJOR_VERSION < 3: # Python 2
raise Exception('Only Python 3 is supported')
import json, git, pickle, hashlib
import numpy as np
import pandas as pd
from pathlib import Path
fro... | |
# self.widgets['lock'][index].setChecked(channel.lock)
# Set the error boolean (true if the lock is active and we are outside the error threshold)
if channel.lock and np.abs(channel.data[-1] - channel.setpoint) > self.threshold:
self.widgets['error_status'][index].setChecked(True)
else:
self.widgets['error_status... | |
<filename>MsLightweaverManager.py
import pickle
import numpy as np
import matplotlib.pyplot as plt
from lightweaver.rh_atoms import H_6_atom, C_atom, O_atom, OI_ord_atom, Si_atom, Al_atom, Fe_atom, FeI_atom, MgII_atom, N_atom, Na_atom, S_atom, CaII_atom
from lightweaver.atmosphere import Atmosphere, ScaleType
from ligh... | |
<reponame>codacy-badger/vcstools
#!/usr/bin/env python3
import logging
import argparse
logger = logging.getLogger(__name__)
def find_obsids_meta_pages(params=None):
"""
Loops over pages for each page for MWA metadata calls
"""
if params is None:
params = {'mode':'VOLTAGE_START'}
obsid_list = []
temp =[]
page... | |
totale = importo_totale+imposta_totale
# print "DDT NUMERO : {0} TOTALE {1}".format(id_ddt,totale)
return totale
def ritorna_int_calcola_totale_iva_inclusa_da_ddt(id_ddt):
rows = db(db.saved_righe_in_ddt_cliente.saved_ddt_id == id_ddt).select()
# print "DDT ID : ",id_ddt
totale ... | |
<filename>trident/callbacks/lr_schedulers.py
"""Learning Rate Scheduler Callbacks"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import matplotlib.pyplot as plt
import math
import random
import warnings
import types
import numpy as np
from trident.backen... | |
<gh_stars>0
"""Runtime parameters
=====================
Scripting interface for Nek5000 :ref:`parameter file <nek:case_files_par>`.
"""
import json
import logging
import os
import sys
import textwrap
from ast import literal_eval
from configparser import ConfigParser
from io import StringIO
from math import nan
from pa... | |
the LEFT_ARROW emote is pressed,
and which emote should be added.
return: (discord.Message)
msg: (discord.Message) --> old message
start: (int) --> starting index of the results list
results: (list) --> list of videos from json
'''
new_msg = await sendMsg(ctx, str_to_send=to_send(results, start),
title="Search"... | |
self.get_color('node', node_template_type), sep='')
else:
self.generate(uml2_kind, ' "', self.get_label('node', container_name, node_template_type), '" as node_', normalize_name(container_name), self.get_color('node', node_template_type), ' {', sep='')
# Generate a properties map if needed
if properties is not None... | |
<gh_stars>100-1000
import os
import cv2
import glob
import h5py
import math
import torch
import imageio
import numpy as np
from .dataset import PoseRefinedDataset
from .process_spin import process_spin_data, write_to_h5py, read_spin_data
from .load_surreal import dilate_masks
from .utils.skeleton_utils import get_smpl... | |
import gym
import time
import numpy as np
import tensorflow as tf
from overcooked_ai_py.mdp.actions import Direction, Action
from overcooked_ai_py.mdp.overcooked_mdp import OvercookedGridworld
from overcooked_ai_py.mdp.overcooked_env import OvercookedEnv
from overcooked_ai_py.mdp.layout_generator import LayoutGenerato... | |
Exception as e:
# NOTE(Vek): Ignoring exceptions here is safe, because the
# usage resynchronization and the reservation expiration
# mechanisms will resolve the issue. The exception is
# logged, however, because this is less than optimal.
msg = str(e)
LOG.exception(_LE("Failed to roll back reservations"
" %(res... | |
from typing import Dict, List, Optional, Tuple, Union
import typing
import numpy as np
from ConfigSpace.hyperparameters import \
CategoricalHyperparameter, UniformFloatHyperparameter, UniformIntegerHyperparameter,Constant
import sklearn.gaussian_process.kernels
from sklearn.decomposition import PCA
from sklearn.prepro... | |
# Due to a rename, the Episode table is called Event in the database.
IndexedTable(EPISODE, 'ev', read_units=200, write_units=10, name_in_db="Event",
columns=[HashKeyColumn('episode_id', 'ei', 'S'),
Column('parent_ep_id', 'pa', 'S', SecondaryIndexer(), read_only=True),
Column('user_id', 'ui', 'N', SecondaryIndexer(... | |
must not contain -g. This confuses gcc 5.1. (Note that it
# would seem that gcc 5.1 with "-g" does not produce debugging
# info in a format that gdb 4.7.1 can read.)
mk.definition('CFLAGS_AS', '$(patsubst -g,,$(CFLAGS))')
# the rule that transforms %.c into %.o, by compiling it to
# %.s, then applying trackgcroot... | |
#!/usr/bin/env python
#-----------------------------------------------------------------------------
# This file is part of 'SLAC Firmware Standard Library'.
# It is subject to the license terms in the LICENSE.txt file found in the
# top-level directory of this distribution and at:
# https://confluence.slac.stanford.... | |
import os
import sys
import pickle
import numpy as np
import xml.etree.ElementTree as ET
import random
import svgwrite
from IPython.display import SVG, display
import tensorflow as tf
def get_bounds( data, factor ):
min_x = 0
max_x = 0
min_y = 0
max_y = 0
abs_x = 0
abs_y = 0
for i in range( len( data ) ):
x... | |
% (key, value)
for key, value in self.__dict__.items()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
class isInContact_result(object):
"""
Att... | |
from os import system # É importado da biblioteca os a função system que será usado para limpara a tela
from time import sleep # É importado da biblioteca time a função sleep, que serve para p pc "dormir"
from random import randint, choice # É importado da biblioteca random a função randint, que serve para a jogada do ... | |
import asyncio
import pytest
from aioasuswrt.asuswrt import (AsusWrt, _LEASES_CMD, _WL_CMD, _IP_NEIGH_CMD,
_ARP_CMD, Device, _RX_COMMAND, _TX_COMMAND,
_TEMP_CMD, _LOADAVG_CMD, _MEMINFO_CMD,
_NETDEV_CMD)
RX_DATA = ["2703926881", ""]
TX_DATA = ["648110137", ""]
RX = 2703926881
TX = 648110137
TEMP_DATA = [
'59 (0x3... | |
# -*- coding: utf-8 -*-
"""
Copyright (c) 2021 <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 restriction, including without limitation the rights
to use, copy, modify, merge, pub... | |
== len(desc):
return
std = "expected %d warnings, found %d: wlist=%s desc=%r" % \
(len(desc), len(wlist), self._formatWarningList(wlist), desc)
raise self.failureException(self._formatMessage(msg, std))
def consumeWarningList(self, wlist, desc=None, *args, **kwds):
"""[deprecated] assertWarningList() variant tha... | |
import sqlite3
from sqlite3 import Error
import datetime
import csv
import urllib.request as urllib2
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
class BancoDeDados():
def __init__(self, arquivo):
try:
os.makedirs(os.path.join(dir_path, 'log'))
except FileExistsError:
... | |
42)
@parameterized.parameters([
[42, r'\'int\' object is not iterable'],
[[47.11], r'location is not integer-like \(found type: float\)']
])
def test_initializer_locations_type_error(self, locations, message):
focus = (
_random_operation(1, 2),
_random_operation(1)
)
context = transform.TransformationContext... | |
= id_ordine,codice_ordine = codice_ordine, n_riga = n_riga,codice_articolo=codice_articolo,descrizione=descrizione,riferimento_ordine=row["riferimento_ordine"],u_m=row["u_m"],quantita=quantita_prodotta,prezzo=prezzo,evasione=evasione,user_id = auth.user_id,codice_iva=row["codice_iva"])
else:
descrizione =row.descri... | |
# -*- coding: utf-8 -*-
"""This class maintains the internal dfTimewolf state.
Use it to track errors, abort on global failures, clean up after modules, etc.
"""
from dataclasses import dataclass
from concurrent.futures import ThreadPoolExecutor, Future
import importlib
import logging
import threading
import tracebac... | |
options for keys:
id - traffic type id
kvmnetworklabel - The network name label of the physical device
dedicated to this traffic on a KVM host
vmwarenetworklabel - The network name label of the physical device
dedicated to this traffic on a VMware host
xennetworklabel - The network name label of the physical devi... | |
<reponame>anki-code/python-hunter
from __future__ import absolute_import
import linecache
import tokenize
from functools import partial
from os.path import basename
from os.path import exists
from os.path import splitext
from threading import current_thread
from .const import SITE_PACKAGES_PATHS
from .const import SY... | |
All figures in a previous session were dumped to the file, and
all these figures are by this method reloaded and added to the
current set of figures.
"""
# in savefig, self._figs was pickled as one object
handle = open(filename, 'r')
filefigs = pickle.load(handle)
handle.close()
# check that filefigs is a dict... | |
<gh_stars>0
'''
/* ******************* */
/*! \file MarabouNetworkONNX.py
** \verbatim
** Top contributors (to current version):
** <NAME>
** This file is part of the Marabou project.
** Copyright (c) 2017-2019 by the authors listed in the file AUTHORS
** in the top-level source directory) and their institutional... | |
on each item in the batch
_, _, window, _,_,_,_,_,_ = parse_image_meta_graph(image_meta,self.config)
[detections_batch,best_indices] = utils.batch_slice(
[rois]+ robotvqa_class+[mrcnn_bbox, window,robotvqa_poses],
lambda x: refine_detections_graph(x, self.config),
self.config.IMAGES_PER_GPU,parallel_processing=Tru... | |
CC.FLAGS_EXPAND_PERPENDICULAR )
QP.AddToLayout( vbox, self._filter_inbox_and_archive_predicates, CC.FLAGS_EXPAND_PERPENDICULAR )
QP.AddToLayout( vbox, self._file_system_predicate_age, CC.FLAGS_EXPAND_PERPENDICULAR )
QP.AddToLayout( vbox, self._file_system_predicate_duration, CC.FLAGS_EXPAND_PERPENDICULAR )
QP.AddTo... | |
call.return_value = operations_pb2.Operation(name='operations/spam')
response = client.create_backup(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == bigtable_table_admin.CreateBackupRequest()
# Establish tha... | |
<filename>program/diceroll.py
#
# diceroll.py
#
# Written for Classic Python 2.5.4
#
# To use this module: from diceroll import roll
#
# Make a dice roll
#
##########################################################
'''
diecroll module containing roll()
Usage:
from diceroll import roll
print roll('2D6')
Will roll ... | |
currentFltCat in [nextFltCat,prevFltCat]
else:
return currentFltCat == nextFltCat
def _summarizeTAFPrjs(TAFPrjs,TAFData,tafDuration=24):
"""Attempt to group based on previous TAF"""
#
# Initialization
TAFText = []
#
# Save Station Identifier and whether its an amendment
try:
ident=TAFPrjs[0].lampdata['ident... | |
<reponame>ixc/django-compressor
from __future__ import with_statement, unicode_literals
import copy
from contextlib import contextmanager
import io
import os
from importlib import import_module
from mock import patch
from unittest import SkipTest
from django.core.management import call_command
from django.core.manag... | |
<reponame>gifford-lab/seqgra<filename>seqgra/evaluator/gradientbased/gradientbasedevaluator.py
"""Gradient-based Feature Importance Evaluators
"""
from abc import abstractmethod
import math
from typing import Any, List, Optional
import numpy as np
import pandas as pd
import torch
import seqgra.constants as c
from seq... | |
map as a separate .csv file. to be run
after clean() on the ./cleaned directory, also outputs a file
identifying the sizes of structures, so the largest value can be used
with HeaderAsPSaM()
'''
os.makedirs('./Completed', exist_ok=True)
os.makedirs('./Error_NotEqual', exist_ok=True)
os.makedirs('./Error_B... | |
a._collect_garbage()
self.assertEqual(a.statistics['added'], 1)
self.assertEqual(a.statistics.get('aged_out', 0), 0)
self.assertEqual(a.statistics.get('garbage_collected', 0), 0)
self.assertEqual(a.statistics.get('removed', 0), 0)
CUR_LOGICAL_TIME = 3
a._age_out()
self.assertEqual(a.statistics['added'], 1)
sel... | |
<filename>office.py
import pandas as pd
import numpy as np
import math
import re
from pptx import Presentation
from pptx.util import Inches
from pptx.util import Pt
# _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_
class ExcelSPC():
filename = None
sheets = None
valid = F... | |
<reponame>Sohojoe/damon<gh_stars>0
# -*- coding: utf-8 -*-
"""
this module creates functionality to generate unit tests at runtime.
For now it will have very basic functionality, but it will be improving with
time.
"""
import damon1 as dmn
import os
import sys
import inspect
from copy import deepcopy as cp... | |
from __future__ import (absolute_import, division, print_function)
from future.utils import iteritems
from collections import OrderedDict
import xml.etree.ElementTree as xmlET
from pyPRMS.constants import DIMENSION_NAMES
from pyPRMS.prms_helpers import read_xml
def _valid_dimension_name(name):
"""Check if given d... | |
<gh_stars>1-10
from __future__ import print_function
import sys
import os
from flask import Flask, render_template, g, request, make_response, Response
import json
import requests
import slackMessages
import databaseOperations
from datetime import datetime
from apscheduler.schedulers.background import BackgroundSchedul... | |
= py - glareSize
if boundYl < 0: boundYl = 0
boundYu = py + glareSize
if boundYu > rows - 1: boundYu = rows - 1
# the pixel value of the sun position
sunpxl = 125
boundXl = px - glareSize
boundXu = px + glareSize
if boundXl < 0: # too left then part of right
print ('Too left, move to right')
b... | |
None,
modifier_func2 = None,
means = 'geometric')
class MPO_meta:
def __init__(self, means):
'''
target_smiles, fp in ['ECFP4', 'AP', ..., ]
scoring,
modifier,
'''
assert means in ['geometric', 'arithmetic']
self.mean_func = mean2func[means]
def __call__(self, test_smiles):
molecule = smiles_to_rdk... | |
import logging
import os
import pathlib
import sys
import time
from queue import Empty, Queue
from threading import Event
from typing import Optional, Sequence
import numpy as np
import torch
from google.cloud import container_v1 as container
from rich.progress import (
BarColumn,
Progress,
ProgressColumn,
Task,
... | |
<gh_stars>1-10
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""SX1276_77_78_79: 137 MHz to 1020 MHz Low Power Long Range Transceiver featuring the LoRa (TM) long range modem"""
__author__ = "ChISL"
__copyright__ = "TBD"
__credits__ = ["Semtech"]
__license__ = "TBD"
__version__ = "0.1"
__maintainer__ = "https://chisl... | |
import argparse
import datetime
import json
import logging
import math
import os
import re
import time
import numpy as np
import pandas as pd
import requests
import xmltodict
from dateutil.parser import parse
from fvhdms import (
save_df, get_default_argumentparser, parse_args,
user_agent, dataframe_into_influxdb,
... | |
user manual
'''
return c_SetUISlider(clientID, uiHandle, uiButtonID, position, operationMode)
def simxGetUIEventButton(clientID, uiHandle, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
uiEventButtonID = ct.c_int()
auxValues = (ct.c_int*2)()
ret ... | |
<reponame>benw1/WINGS
#!/usr/bin/env python
"""
Contains the DataProduct class definition
Please note that this module is private. The DataProduct class is
available in the main ``wpipe`` namespace - use that instead.
"""
from .core import os, shutil, datetime, si
from .core import return_dict_of_attrs, initialize_arg... | |
None
def read_buffer(self, buf, host_array, blocking=True, size=None, offset=0,
wait_for=None, need_event=False):
"""Copies from device buffer to host buffer.
Parameters:
buf: Buffer object.
host_array: numpy array.
blocking: if the read is blocking.
size: size in bytes to copy (None for entire numpy array).
... | |
import datetime
def now():
return datetime.datetime.utcnow()
print(now(),'Script Start')
import requests
import json
import csv
from bs4 import BeautifulSoup
from html_table_extractor.extractor import Extractor
from html.parser import HTMLParser
import xml.etree.ElementTree as ET
import twython
import os
import colle... | |
= core.Place()
p.set_place(heter_place)
self._default_executor = core.Executor(p)
# TODO(zhangminxu): support heterps pipeline training using exe.run
if "startup_program" in program._heter_pipeline_opt:
#print("get startup_program from _pipeline_opt")
program = program._heter_pipeline_opt["startup_program"]
if ... | |
'fields_difference': fields_difference,
'field_mask': field_mask,
'field_texture': field_texture,
'sigma_zh': sigma_zh,
'stat_test_lag1': stat_test_lag1,
'stat_test_lag2': stat_test_lag2,
'mean_phase': mean_phase,
'differential_phase': differential_phase,
'unfolded_differential_phase': unfolded_differential_pha... | |
import pickle
import time
import os
import shutil
from typing import Dict, List, Tuple, Union, Set
from qanta.guesser.abstract import AbstractGuesser
from qanta.datasets.quiz_bowl import QuizBowlDataset
from qanta.datasets.wikipedia import WikipediaDataset
from qanta.preprocess import preprocess_dataset, tokenize_ques... | |
# File: main.py
# File Created: Tuesday, 7th July 2020 9:43:48 am
# Author: <NAME> (<EMAIL>)
"""
Finite difference solver for wave equation
"""
import abc
import json
import os
from argparse import ArgumentParser
from collections import namedtuple
from time import time
from celluloid import Camera
im... | |
Safari/537.36",
}
params = {
"cb": "datatable1891672",
"type": "GJZB",
"sty": "ZGZB",
"js": "({data:[(x)],pages:(pc)})",
"p": "1",
"ps": "2000",
"mkt": "12",
"pageNo": "1",
"pageNum": "1",
"_": "1603023435552",
}
r = requests.get(url, params=params, headers=headers)
data_text = r.text
data_json = demjso... | |
import argparse
import random
import os
import time
import datetime
import numpy as np
import torch
from torch import nn, autograd, optim
from torch.nn import functional as F
from torch.utils import data
import torch.distributed as dist
from torchvision import transforms, utils
from model import Generat... | |
import unittest
from datetime import timedelta
import rx
from rx import operators as ops
from rx.testing import TestScheduler, ReactiveTest
on_next = ReactiveTest.on_next
on_completed = ReactiveTest.on_completed
on_error = ReactiveTest.on_error
subscribe = ReactiveTest.subscribe
subscribed = ReactiveTest.subscribed
d... | |
scorer=None, ckpt_every=0, printing=False, min_length=0, **kwargs):
assert top_p == 1.0, "For now, the top_p implementation does not work, as the sampling on GPU will crash randomly"
timings = False
T = time.time()
if timings:
print("------------")
force_start_ids = []
if force_start is not None:
force_start... | |
"""Tests the automated search for characteristic over cryptographic primitives."""
import warnings
from datetime import datetime
import collections
import functools
import os
import unittest
from cascada.differential.difference import XorDiff, RXDiff
from cascada.linear.mask import LinearMask
from cascada.algebraic.va... | |
<gh_stars>0
import numpy as np
# Create numpy arrays, list and change elements
a=np.array([1,2,3]) # create a 1D array
print('Dimensions of the array = ',a.ndim) # print the dimensions of the array
print('Shape of the array = ', a.shape) # print the shape of the array
a=np.array([ [1,2,3] ])
print('Dimensions of the ... | |
1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0],
[1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, ... | |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
## \package pts.magic.sources.fi... | |
or filtered through a sum of gaussians as in the original Matlab implementation.
Parameters:
wn: sorted array of wavenumbers (high-to-low or low-to-high)
app: apparent spectrum, shape (pixels, wavenumbers)
ref: reference spectrum; array (wavenumbers)
n_components: number of principal components to be calculated fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.