input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
import copy,subprocess,os,tempfile,re
import uuid,time,glob,lixtools
import numpy as np
from io import StringIO
import pylab as plt
from dask.distributed import as_completed
def run(cmd, path="", ignoreErrors=True, returnError=False, debug=False):
""" cmd should be a list, e.g. ["ls", "-lh"]
path is for the cmd, not... | |
<filename>plasmapy/utils/decorators/checks.py
"""
Decorator for checking input/output arguments of functions.
"""
__all__ = [
"check_values",
"check_units",
"check_relativistic",
"CheckBase",
"CheckUnits",
"CheckValues",
]
import collections
import functools
import inspect
import numpy as np
import warnings
fro... | |
== "android.intent.action.MAIN":
x.add( item.getAttributeNS(NS_ANDROID_URI, "name" ) )
for sitem in item.getElementsByTagName( "category" ):
val = sitem.getAttributeNS(NS_ANDROID_URI, "name" )
if val == "android.intent.category.LAUNCHER":
y.add( item.getAttributeNS(NS_ANDROID_URI, "name" ) )
z = x.intersection(... | |
"""CardinalityMatching.py
Find maximum cardinality matchings in general undirected graphs.
<NAME>, UC Irvine, September 6, 2003.
"""
import sys
from UnionFind import UnionFind
from Util import arbitrary_item
def matching(G, initialMatching = None):
"""Find a maximum cardinality matching in a graph G.
G is repres... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from abc import ABC, abstractstaticmethod
from typing import Callable, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from torchvision.ops import batched_nms
from combustion.vision import batch_box_targe... | |
parameters - nreal
nreal = int(nreal) # cast to int if needed
if nreal <= 0:
if verbose >= 1:
print('SIMUL_3D: nreal <= 0: nothing to do!')
return None
# --- Fill mpds_geosClassicInput structure (C)
mpds_geosClassicInput, flag = fill_mpds_geosClassicInput(
space_dim,
cov_model,
nx, ny, nz,
sx, sy, sz,
ox,... | |
<reponame>icesat-2UT/PhoREAL
# -*- coding: utf-8 -*-
"""
Script to perform most basic functionalities required to get ATL03 swath
Copyright 2019 Applied Research Laboratories, University of Texas at Austin
This package is free software; the copyright holder gives unlimited
permission to copy and/or distribute,... | |
import enum
import os
from typing import Optional, Union, Tuple, List
from PIL import Image, ImageFont
from platypush.plugins import Plugin, action
class DeviceInterface(enum.Enum):
I2C = 'i2c'
SPI = 'spi'
class DeviceSlot(enum.IntEnum):
BACK = 0
FRONT = 1
class DeviceRotation(enum.IntEnum):
ROTATE_0 = 0
... | |
rusage[6]
self.majflt = rusage[7]
def record_running(self, cur_time):
assert (self.time_start is None), self.time_start
self.time_start = cur_time
self.status = run_status.running
for fd in self.job_output:
self.io[fd] = (cStringIO.StringIO(), None, None)
def add_io(self, fd, payload, eof):
"""
called when ... | |
in indigo.devices.iter()]
# Variables
elif values_dict.get('editSourceFilter', 'A') == "V":
[list_.append(t) for t in [(u"-3", u"%%separator%%"),
(u"-4", u"%%disabled:Variables%%"),
(u"-5", u"%%separator%%")
]
]
[list_.append((var.id, u"{name}".format(name=var.name))) for var in indigo.variables.iter()]
# De... | |
<gh_stars>10-100
# Copyright (c) 2019 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
r"""Submodule containing all standard functions."""
import numpy as np
def exp(q):
r"""Compute the natural exponential function :math:`e^q`.
The expone... | |
t = max(A, B, C)
if t >= p:
a -= 1
B += D[a]
A -= D[a]
break
p = t
ans = min(ans, p)
ans = float(S - ans) / S
print 'Case #%s: %.16f' % (test + 1, ans)
return a
def func_0b1c94ef5ed74644860d862b57fafbea():
infile = open('codejam/test_files/Y14R5P1/A.in')
for test in range(int(infile.readline())):
N, p, q... | |
"""
filebrowser.views
"""
import logging
import re
import json
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.template.loader import get_template
from django.conf import settings
from .utils import get_rucio_file, get_rucio_... | |
anyway be forced later if he attempts virt= or all=.
self.validate_model(loop_type='real_init', stop=False)
# Set where to look for CutTools installation.
# In further versions, it will be set in the same manner as _mgme_dir so that
# the user can chose its own CutTools distribution.
self._cuttools_dir=str(pjoin(s... | |
# Copyright (c) 2021 Institute for Quantum Computing, Baidu 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/licenses/LICENSE-2.0
#
# Unless... | |
= new_masks_softmax.max(dim=1)[0].view(-1).topk(8, largest=False)[0][-1].item()
pending_thresh = max(0.02, max_topk)
new_pos = torch.nonzero(new_masks_softmax[0].max(dim=0)[0] < pending_thresh)
if len(new_pos) > new_pos_limit_2:
# import pdb; pdb.set_trace()
raw_pos = new_masks_softmax.max(dim=1)[0].view(-1).topk(... | |
#master: https://github.com/yagamiraku/tarkov_flea_bot_toTherapis
# └──fork: https://github.com/astron4ik/tarkov_flea_bot_toTherapis
# └──this fork: https://github.com/Avnsx/EFT_Flea_Market_Bot
#Master: yagamiraku | fork: astron4ik | this fork: Avn
import requests,zlib,hashlib,json,configparser,random,os,time,threadi... | |
import os
from enum import IntEnum
from random import uniform
from math import pi
import json
from ipycanvas import MultiCanvas, Canvas, hold_canvas
from ipywidgets import Image
from babyrobot.envs.lib import GridBase
from babyrobot.envs.lib import Arrows
from babyrobot.envs.lib import Direction
class Level(IntEn... | |
The metric dimension name.
:vartype name: str
:ivar display_name: The display name for the dimension.
:vartype display_name: str
:ivar to_be_exported_for_shoebox: Whether to export metric to shoebox.
:vartype to_be_exported_for_shoebox: bool
"""
_validation = {
'name': {'readonly': True},
'display_name': {'re... | |
import os
import sys
import sqlite3
import pandas as pd
from matplotlib import pyplot as plt
from multiprocessing import Process, Queue
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from utility.setting import db_tick, db_backtest
from utility.static import now, strf_time, strp_time, time... | |
range(18):
# angle = i * 20
# _def_lm.append('r{}_90'.format(angle))
def mw_lutmap_is_valid(lutmap: dict) -> bool:
"""
Test if lutmap obeys schema.
Args:
lutmap
Return:
valid (bool):
"""
# FIXME: make this part of the validator for the LutMap parameter.
for key, value in lutmap.items():
if not isinstance(k... | |
j.exceptions.RuntimeError("Not supported on this platform!")
def getVlanTag(self, interface, nicType=None):
"""Get VLan tag on the specified interface and vlan type"""
if nicType is None:
nicType = j.sal.nettools.getNicType(interface)
if nicType == "INFINIBAND" or nicType == "ETHERNET_GB" or nicType == "VIRTUAL":... | |
<gh_stars>1-10
#
# Bindings.py -- Bindings classes for Ginga FITS viewer.
#
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
import math
import os.path
import itertools
import numpy as np
from ginga.misc import Bunch, Settings, Callback
from ginga import trca... | |
import networkx as nx
from math import inf as INFINITY
test_input1 = """#######
#E..G.#
#...#.#
#.G.#G#
#######"""
test_input2 = """#######
#.E...#
#.....#
#...G.#
#######"""
test_move1 = """#########
#G..G..G#
#.......#
#.......#
#G..E..G#
#.......#
#.......#
#G..G..G#
#########"""
test_move2 = """#########
#.G...... | |
<gh_stars>0
import sys
import math
from abc import ABC
from functools import lru_cache
import numpy as np
import quaternion # adds to numpy
from astropy.time import Time
from astropy import constants as const
from astropy import units
from astropy.coordinates import SkyCoord
import configparser
from iotools import ob... | |
0.00435488,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00248228,
'Renaming Unit/Peak Dynamic': 3.58947,
'Renaming Unit/Runtime Dynamic': 0.0982332,
'Renaming Unit/Subthreshold Leakage': 0.0552466,
'Renaming Unit/Subthreshold Leakage with power gating': 0.0276461,
'Runtime Dynamic'... | |
as a 'short text file')
@param fileName
@param obj the file type. Currently we support these file types (as defined
internally by Praat):
- Harmonicity 2
- PitchTier
- Intensity
- SpectrumTier
- Spectrum 2
- Cepstrum 1
@return a two-dimensional array of floats, the first row
(index = 0) repres... | |
self.shared_token_embedder}
else:
self.token_embedder_factory: Callable[[], embedding.Embed]
self.token_embedder = self.token_embedder_factory()
embedders = {'token_ids': self.token_embedder}
if self.position_embedder_factory is not None:
self.position_embedder_factory: Callable[[], embedding.Embed]
self.positio... | |
label_create_button = T("Add New Summary Request Option"),
label_delete_button = T("Delete Summary Request Option"),
msg_record_created = T("Summary Request Option added"),
msg_record_modified = T("Summary Request Option updated"),
msg_record_deleted = T("Summary Request Option deleted"),
msg_no_match = T("No entr... | |
def write_to_out(out, incoming_data, map_out_combined, region):
bires = map_out_combined[0] + region
global_slice = tuple(
[slice(bires[0][x], bires[1][x] + 1) for x in range(bires.shape[1])]
)
local_slice = shardview.slice_to_local(out.subspace, global_slice)
dprint(
2,
"Receiving Data:",
self.worker_num,
ma... | |
"""Plots predictors on full NARR grid."""
import argparse
import numpy
import matplotlib
matplotlib.use('agg')
import matplotlib.colors
import matplotlib.pyplot as pyplot
from gewittergefahr.gg_utils import time_conversion
from gewittergefahr.gg_utils import time_periods
from gewittergefahr.gg_utils import nwp_model_u... | |
<reponame>JinGyeSetBirdsFree/FudanOCR
import os
import cv2
import numpy as np
from math import ceil
import matplotlib.pyplot as plt
from scipy import signal, misc
class BlurImage(object):
def blur_image_path(self, img_path, PSFs=None, part=None, path_to_save=None, show=False):
"""
:param image_path: pa... | |
profile.get('cache-insert-age-header', 'disabled')
if age_header == 'enabled':
cache_config['age_header'] = True
else:
cache_config['age_header'] = False
cache_config['enabled'] = True
cache_config['default_expire'] = \
profile.get('cache-max-age', final.DEFAULT_CACHE_MAX_AGE)
max_entities = profile.get('cache-... | |
import matplotlib.pyplot as plt
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator
from ..configure.default_config import CINRAD_COLORMAP, CINRAD_field_bins, \
CINRAD_field_normvar, CINRAD_field_mapping
import numpy as np
from ..configure.location_config import CN_shp_info
import cart... | |
<reponame>21vcloud/Controller
# -*- coding:utf-8 -*-
from django.db import models
from rest_framework import serializers
from rest_api.models import AccessKey
class ResponseNoneMeta(models.Model):
class Meta:
managed = False
db_table = 'NoneMeta'
class FlavorListInfoResponsesSerializer(serializers.ModelSeriali... | |
<reponame>treymer/openshift-tools
#!/usr/bin/env python
""" Create application check for v3 """
# We just want to see any exception that happens
# don't want the script to die under any cicumstances
# script must try to clean itself up
# pylint: disable=broad-except
# main() function has a lot of setup and error hand... | |
summary."""
if not self.pragma.comp_summary:
return
if len(self.comp_hist.mem_iter) == 0:
print('No computational summary to display')
return
mem = {
'min': Size.bytes2human(min (self.comp_hist.mem_iter)),
'max': Size.bytes2human(max (self.comp_hist.mem_iter)),
'mean': Size.bytes2human(statistics.mean (self... | |
#!/usr/bin/env python
######################################################
# GUI to vizualize ROMS input/output files
# Sep 2021
# <EMAIL>
######################################################
import os
import wx
import datetime as dt
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
f... | |
key = 'scsi{0}.pciSlotNumber'.format(pvscsi.key -
key_offset)
slot = [cfg for cfg in vm.config.extraConfig \
if cfg.key == key]
# If the given controller exists
if slot:
return slot[0].value
else:
return None
def dev_info(unit_number, pci_slot_number):
'''Return a dictionary with Unit/Bus for the vmdk (or er... | |
# Copyright (C) 2019-2020, TomTom (http://tomtom.com).
#
# 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 ... | |
Move the input pointer to the next incoming token. The stream
must become active with LT(1) available. consume() simply
moves the input pointer so that LT(1) points at the next
input symbol. Consume at least one token.
Walk past any token not on the channel the parser is listening to.
"""
if self.p < len(self.t... | |
<gh_stars>1-10
# encoding: utf-8
"""
MIT License
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
... | |
<filename>amd64-linux/lib/python/sun_vtoc_commands.py
from cli import *
#
# VTOC layout: (with unimportant fields removed)
#
# OFFSET SIZE NUM NAME
# 0 128 1 label
VTOC_VERSION = 128 # 128 4 1 version
# 132 8 1 volume name
VTOC_NUMPART = 140 # 140 2 1 number of partitions
VTOC_PART_S2 = 142 # 142 4 8 partition head... | |
<reponame>yujing1997/CTcnn
import matplotlib
matplotlib.use('Agg') #to actually be able to use matplotlib
import numpy as np
from scipy.misc import imsave,imread
import time
from keras import backend as K
from vis.visualization import visualize_activation,visualize_saliency,visualize_cam,get_num_filters
from vis.utils... | |
must be 'same', 'valid' or 'causal'. Got "
+ self.padding
)
wx = self.conv(x)
if self.unsqueeze:
wx = wx.squeeze(1)
if not self.skip_transpose:
wx = wx.transpose(1, -1)
return wx
def _manage_padding(
self, x, kernel_size: int, dilation: int, stride: int,
):
"""This function performs zero-padding on the... | |
= df.groupby(['Date', aggregation]).sum()[columns].reset_index()
df_by_date = df1[(df1['Date'] >= start_date_string) & (df1['Date'] <= end_date_string)].groupby([aggregation]).sum()[columns].reset_index()
df_by_date_prior = df1[(df1['Date'] >= prior_start_date_string) & (df1['Date'] <= prior_end_date_string)].gro... | |
164, 365, 205, 548, 270, 256, 82, 26,
227, 69, 387, 633, 762, 694, 385, 92, 542, 608, 571,
825, 541, 533, 421, 666, 332, 113, 684, 892, 28, 979,
976, 706, 457, 185, 895, 310, 106, 142, 45, 230, 65,
67, 201, 738, 910, 523, 893, 189, 97, 466, 258, 382,
61, 105, 774, 572, 620, 737, 871, 900, 799, 516, 203,
294, 616,... | |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program 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 2
# of the License, or (at your option) any later version.
#
# This program is distributed... | |
<gh_stars>0
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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... | |
from collections import OrderedDict
import numpy as np
import pytorch_lightning as pl
import torch
import torchvision
from nowcasting_utils.models.loss import get_loss
from pl_bolts.optimizers.lr_scheduler import LinearWarmupCosineAnnealingLR
from torch.optim import lr_scheduler
from satflow.models import ConvLSTM, R... | |
lineno = i
break
# Find the line number for functions & methods.
if inspect.ismethod(obj): obj = obj.im_func
if inspect.isfunction(obj): obj = obj.func_code
if inspect.istraceback(obj): obj = obj.tb_frame
if inspect.isframe(obj): obj = obj.f_code
if inspect.iscode(obj):
lineno = getattr(obj, 'co_firstlineno', ... | |
#!/usr/bin/env python3
import json
from pathlib import Path
import platform
import os
import subprocess
from time import time, sleep, monotonic
import cv2
import numpy as np
import depthai
import consts.resource_paths
from depthai_helpers import utils
from depthai_helpers.cli_utils import cli_print, parse_args, Pri... | |
/ 2
ry = mask_diameters * dy / 2
# major and minor ellipse axes with center at (xc, yc)
x = np.array([-rx, rx, 0, 0, 0]) + xc
y = np.array([0, 0, 0, -ry, ry]) + yc
x_rot, y_rot = rotate_points(x, y, xc, yc, phi)
return np.array([x_rot, y_rot])
def beam_size(image, mask_diameters=3, corner_fraction=0.035, nT=... | |
if self.document_isNew[modelType.modelDocument.uri]:
qnamesDerivedFrom = modelType.qnameDerivedFrom
if not isinstance(qnamesDerivedFrom, (list,tuple)): # list if a union
qnamesDerivedFrom = (qnamesDerivedFrom,)
for qnameDerivedFrom in qnamesDerivedFrom:
if modelType.qname in self.type_id and qnameDerivedFrom in se... | |
and skip_no_changes_ is False:
# so we will try to merge it nevertheless
lgr.info("There was nothing to merge but we were instructed to merge due to skip_no_changes=False")
all_to_merge = [branch]
nmerges = 1
plmerges = "s" if nmerges > 1 else ""
lgr.info("Initiating %(nmerges)d merge%(plmerges)s of %(branch)s u... | |
1,
call = lambda z: complex(*z[:2])
),
'ÆĿ': attrdict(
arity = 1,
ldepth = 0,
call = lambda z: int(sympy.functions.combinatorial.numbers.lucas(z))
),
'Æl': attrdict(
arity = 1,
ldepth = 0,
call = lambda z: overload((math.log, cmath.log), z)
),
'Æm': attrdict(
arity = 1,
ldepth = 1,
call = lamb... | |
<reponame>YichenZhou113/Baxter-Teleoperation<gh_stars>0
#!/usr/bin/env python
# -*- coding: utf8 -*-
#
# Hello World client in Python
# Connects REQ socket to tcp://localhost:5555
# Sends "Hello" to server, expects "World" back
#
import sys
import csv
import zmq
import time
from time import sleep
import numpy as np... | |
RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class ModifySubAppIdInfoRequest(AbstractModel):
"""ModifySubAppIdInfo请求参数结构体
"""
def __init__(self):
"""
:param SubAppId: 子应用 ID。
:type SubAppId: int
:param Name: 子应用名称,长度限制:40个字符。
:type N... | |
def __hash__(self):
"""
Calculate a hash considering eventually associated objects.
"""
if self._hash is not None:
return self._hash # Return cached hash.
else:
if self.obj is None: # Anonymous symbol.
myhash = id(self)
else: # Hash of associated object.
myhash = hash(self.obj)
self._hash = myhash
return my... | |
#
# Modified by <NAME>
# Contact: <EMAIL>
#
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import copy
import logging
import numpy as np
import torch
import torchvision.transforms.functional as F
from detectron2.data import detection_utils as utils
from detectron2.data import transforms as T
... | |
search_output['aur'].items():
res.new.append(self.aur_mapper.map_api_data(apidata, None, self.categories))
res.update_total()
return res
def _fill_aur_pkgs(self, aur_pkgs: dict, output: List[ArchPackage], disk_loader: DiskCacheLoader, internet_available: bool,
arch_config: dict, rebuild_check: Optional[Thread], ... | |
from .state import State
from .object import Object, Void
from .listdeforg import ListDefOrigin
from .value import *
from ..error import StoryError
from random import Random
from .container import Container
from .callstack import StackType
from .path import Path
from .tag import Tag
from ..util import Event
from .diver... | |
"""Functionality for generating feature vectors from relational data"""
# Copyright (c) 2018 <NAME>. This is free software released
# under the MIT License. See `LICENSE.txt` for details.
# Features are functions that convert a set of input fields to a value.
# They have input and output types. They have a conversio... | |
import os
import pandas as pd
import arff
import numpy as np
from functools import reduce
import sqlite3
import logging
from libs.planet_kaggle import to_multi_label_dict, get_file_count, enrich_with_feature_encoding, featurise_images, generate_validation_files
import tensorflow as tf
from keras.applications.resnet50 i... | |
<gh_stars>0
import random
from random import shuffle
import numpy as np
from datetime import datetime
import time
import queue
import threading
import logging
from PIL import Image
import itertools
import re
import os
import glob
import shutil
import sys
import copy
import h5py
from netCDF4 import Dataset
import torch
... | |
"true"
else:
#we don't have meta, we delete the resource
resource_node = self.get_resource(res_query)
if isinstance(resource_node, dict) and ''.join(resource_node['path']) in self.resources['children']:
# user wants to delete the entire TB
if ''.join(resource_node['path']) in self.resources['children']:
self.res... | |
t_seq = torch.stack(tmp, 1)
t_seq = t_seq.view(self.num_seq, self.seq_len,
C, H, W).transpose(1, 2)
#print (vpath, vpath.split('/'))
try:
#print ('try', vpath, vpath.split('/'))
vname = vpath.split('/')[-2]
#print (vname)
vid = self.encode_action(int(vname))
except:
#print ('except', vpath)
vname = vpath.sp... | |
#! /bin/python
# jessehogandeliamariahogan
#vim: set ts=4 sw=4 et
import copy
import os
import curses
import time
import sys
false=False
true=True
class char:
def __init__(self, x, y, char):
self.x = x
self.y = y
self.letter = char
def str(self):
return "%s,%s %s" % (self.x, self.y, self.letter)
class board:
d... | |
Approximation([group_1, group_other])
**Summing Up**
When you have created all the groups they need to pass all the groups to :class:`Approximation`.
It does not accept any other parameter rather than `groups`
.. code:: python
>>> approx = Approximation(my_groups)
See Also
--------
:class:`Approximation`
... | |
import StringIO, sys
from xml.dom import Node # MUST be first
from xml.dom import implementation, DOMException
from xml.dom import HIERARCHY_REQUEST_ERR, NOT_FOUND_ERR
from xml.dom import INDEX_SIZE_ERR, INVALID_CHARACTER_ERR, SYNTAX_ERR
from xml.dom.ext.reader.Sax2 import FromXml
from xml.dom.ext import PrettyPrint
#... | |
<reponame>EVS-ATMOS/cmdv-rrm-anl
# This module handles all of the time lookups for soundings and radar
# All of the file_name_str entries will have to be adjusted to fit to
# your radar dataset's naming convention
import glob
import numpy as np
import math
import matplotlib
matplotlib.use('agg')
import pyart
import ti... | |
# coding: utf-8
"""
Copyright 2016 SmartBear Software
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 t... | |
self.get_grid_data(it, v_n_x)
z_arr = self.get_int_data(it, v_n_z)
if mod == 'xy slice':
return np.array(x_arr[:, 0, 0]), np.array(y_arr[0, :, 0]), np.array(z_arr[:, :, 0]),
elif mod == 'integ_over_z':
return np.array(x_arr[:, 0, 0]),np.array(y_arr[0, :, 0]), self.ingeg_over_z(it, z_arr)
elif mod == 'integ_ove... | |
volreg_kws is None else volreg_kws
if not isinstance(template, six.string_types):
if template is None:
# Correct motion: first pass
utils.run(f"3dTcat -prefix {temp_dir}/template.pass1.nii -overwrite {files[0][0]}'[{files[0][1]}]'")
pc(pc.run(correct_motion, f"{temp_dir}/template.pass1.nii", files[k][0], f"{prefix... | |
<gh_stars>1-10
"""
This file provides necessary code to allow boot up of a virtual machine with
the correct program running. This code may provide slightly different environment
when compared to real hardware process, since e.g. external files can be mmap-ed
into VM's memory for writing.
"""
import importlib
import mm... | |
<reponame>iandorsey00/geodata
county_names = [
'Autauga County, Alabama',
'Baldwin County, Alabama',
'Barbour County, Alabama',
'Bibb County, Alabama',
'Blount County, Alabama',
'Bullock County, Alabama',
'Butler County, Alabama',
'Calhoun County, Alabama',
'Chambers County, Alabama',
'Cherokee County, Alabam... | |
"GNX": {
"symbol": "GNX",
"name": "Genaro Network",
"type": "ERC20",
"address": "0x6EC8a24CaBdc339A06a172F8223ea557055aDAa5",
"ens_address": "",
"decimals": 9,
"website": "https://genaro.network",
"logo": {
"src": "",
"width": "",
"height": "",
"ipfs_hash": ""
},
"support": {
"email": "",
"url": ""
},
... | |
held object (pickup_target) on the place_target
return dict(action="PutByType", objectType=self._last_to_interact_object_pose["objectType"])
return dict(action="CloseByType", objectType=self._last_to_interact_object_pose["objectType"])
elif self._last_to_interact_object_pose["objectId"] == place_target["objectId... | |
check3 += 1
continue
elif 'DF-MP2 Energies' in line:
check4 = 1
elif '@DF-RHF Final Energy' in line:
count2 += 1
if chk == 0:
if count2 == 2:
count2 = 0
check5 = 1
elif chk == 1:
if not param.coarse_level == 2:
check5 = 1
else:
if count2 == 2:
check5 = 1
elif chk == 2:
if count2 == 1:
check5 = 1
if c... | |
# -*- coding: utf-8 -*-
"""
Contains functions for generating an SPH glass in a periodic box. To generate
a glass, see glassBox.
This package requires diskpy, ChaNGa, and pynbody.
Created on Wed Mar 16 17:37:10 2016
@author: ibackus
"""
import shutil
import os
import numpy as np
import pynbody
SimArray = pynbody.ar... | |
inner_source ,
OOOoO000 . outer_source )
if ( I1IiiI1ii1i ) :
OoO = OOOoO000 . packet if ( OOO0ooo ) else None
lisp . lisp_glean_map_cache ( OOOoO000 . inner_source , OOOoO000 . outer_source ,
OOOoO000 . udp_sport , OoO )
if ( OOO0ooo ) : return
if 54 - 54: I11i / I1IiiI * oO0o + OoooooooOO - iII111i / OoooooooO... | |
########################################################################################################################
# Module: inference/proposal.py
# Description: Proposal mechanisms to extend particles (series of positions/edges/distances) and re-weight
# in light of a newly received observation.
#
# Web: https:/... | |
0x120
0x10, 0x00, 0x04, 0x03, # 0x124
0x04, 0x01, 0x02, 0x03, # 0x128
0x07, 0x01, 0x24, 0x00, # 0x12c
0x01, 0x00, 0x11, 0x00, # 0x130
0x00, 0x02, None, None, # 0x134
None, None, 0x64, 0x00, # 0x138
0x02, 0x03, 0x00, 0x80, # 0x13c
0x00, 0x00, 0x00, 0x80, # 0x140
None, None, None, None, # 0x144
0x64, 0x00, 0x02... | |
#!usr/bin/env ipython
# Functions related to loading, saving, processing datasets
import tensorflow.keras.datasets as datasets
from tensorflow.keras import Model
import numpy as np
import pandas as pd
import os
from pathlib import Path
from scipy.stats import entropy
from scipy.spatial.distance import cosine
from skle... | |
be patient!'.format(col))
fig = plt.figure(figsize=(20, 15))
sns.distplot(data, bins=bins, kde=False, rug=True)
plt.title('Histograms of {}'.format(col), fontsize=20)
plt.xlabel('{}'.format(col), fontsize=20)
plt.ylabel('number of counts', fontsize=20)
plt.savefig(out_path + '/02-hist/' + "{}.png".format(col))
... | |
"""Derived agent class."""
from swarms.lib.agent import Agent
import numpy as np
from swarms.utils.bt import BTConstruct
# from swarms.utils.results import Results
from py_trees import Behaviour, Blackboard
# import copy
from py_trees.meta import inverter
import py_trees
from py_trees.composites import Sequence, Sele... | |
<filename>egret/model_library/transmission/tx_calc.py<gh_stars>0
# ___________________________________________________________________________
#
# EGRET: Electrical Grid Research and Engineering Tools
# Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC
# (NTESS). Under the terms of Contract DE-N... | |
<gh_stars>0
from __future__ import division
from builtins import range
from future.utils import with_metaclass
import numpy as np
from numpy import newaxis as na
import abc
import copy
from scipy.special import logsumexp
from pyhsmm.util.stats import sample_discrete
try:
from pyhsmm.util.cstats import sample_markov,... | |
<reponame>AndrewSpano/UC_Berkeley_AI_Projects
# search.py
# ---------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, inclu... | |
def winEnumHandler(hwnd, ctx):
if win32gui.IsWindowVisible(hwnd):
print(hex(hwnd), win32gui.GetWindowText(hwnd))
win32gui.EnumWindows(winEnumHandler, None)
def grab_hpbar_locations(gamename=False):
if gamename:
wincap = WindowCapture(gamename, [100, 135, 1223, 688])
original_image = wincap.get_screenshot()
els... | |
error:
# TODO: Do not just catch Exception. Do narrower scope.
if hasattr(error, 'errno'):
log.error('Failed to connect to "%s" due to errno=%d. Exception was %s. Closing connection, '
'will re-attempt', self.__full_address, error.errno, str(error),
error_code='client/requestFailed')
else:
log.exception('Failed ... | |
neighboring bins.
INPUT: drive, single frequency drive signal, sampled with some dt
resp, arbitrary response to be 'binned'
dt, sample spacing in seconds [s]
nbins, number of samples in the final resp(drive)
nharmonics, number of harmonics to include in filter
harms, list of desired harmonics (overrides nh... | |
assert_pint_array_equal(arr1, arr2):
assert_array_equal(arr1.magnitude, arr2.magnitude)
assert str(arr1.units) == str(arr2.units)
if isinstance(_pint.UnitRegistry, NotAModule):
return
ureg = _pint.UnitRegistry()
p_arr = np.arange(10) * ureg.km / ureg.year
yt_arr = unyt_array(np.arange(10), "km/yr")
yt_arr2 = ... | |
# -*- python -*-
import os.path
import identifier
import string
from typeinfo import GetTypeInformation, VoidType, ternary
from omniidl import idlast, idlvisitor, idlutil, idltype, output
# For compatibility with older Pythons...
def zip(a1, a2):
l = min(len(a1), len(a2))
az = []
for i in range(0, l):
az.append((a... | |
0.01960784, 0.03921569,
0.05882353, 0.07843137, 0.09803922, 0.11764706, 0.1372549 ,
0.15686275, 0.17647059, 0.19607843, 0.21568627, 0.23529412,
0.25490196, 0.2745098 , 0.29411765, 0.31372549, 0.33333333,
0.35294118, 0.37254902, 0.39215686, 0.41176471, 0.43137255,
0.45098039, 0.47058824, 0.49019608, 0.50980392, 0.5... | |
<reponame>yarshure/CoreImagePython
"""
pycoreimage
Copyright 2018 Apple Inc. All rights reserved.
# Install
1. pip install pyobjc --ignore-installed --user
2. pip install numpy --ignore-installed --user
3. pip install scikit-image --user
"""
from pycoreimage.pyci import *
def demo_metadata(fpath):
img = cimg.... | |
case with sbml
- could need creating in this local namespace (i.e. internal to the RDF graph),
such as the case with CellML
Users need to know which use case they need for their annotation language.
Args:
about: The string to use as the metaid. When `type` is eUriType.MODEL_URI
then this string must be ... | |
<reponame>joshcoales/pyparsing
#
# test_unit.py
#
# Unit tests for pyparsing module
#
# Copyright 2002-2020, <NAME>
#
#
import contextlib
import datetime
import sys
from io import StringIO
from unittest import TestCase
import pyparsing as pp
from examples.jsonParser import jsonObject
from pyparsing import ParseExcept... | |
<reponame>datosgobar/pydatajson
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
import os
import re
import json
try:
from mock import patch, MagicMock, ANY
except ImportError:
from unittest.mock import patch, MagicMock, ANY
from .context import pydatajson
from pydatajson.federation... | |
<filename>HebbLearn.py<gh_stars>1-10
import sys
import os
import math
import numpy as np
from scipy import misc
import matplotlib.pyplot as plt
try:
import cv2
except:
print('cv2 not available')
pass
# Global parameters
# Nonlinearity options
LINEAR = 1
TANH = 2
DIVTANH = 3
# rgb2gray
# luminance preserving rgb2... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.