input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
import pickle
import random
import logging
import cv2
import torch
import numpy as np
from tqdm import tqdm, trange
from imgaug.augmenters import Resize
import os
from natsort import natsorted
import re
import imgaug.augmenters as iaa
from imgaug.augmentables.lines import LineString, LineStringsOnImage
from torchvisio... | |
= []
for s in cvarstore:
ts.append(TupleVariation(s[0], s[1]))
fo['cvar'] = ttFont.newTable('cvar')
fo['cvar'].variations = ts
def make_coordinate_index(glist, fo):
""" glyph list, the font object. """
coordinateIndex = {}
for gn in glist:
currentGlyph = fo['glyf'][gn]
if not currentGlyph.isComposite():
c = ... | |
parent master.
STANDARD OPTIONS
class, compound, cursor, image, state, style, takefocus,
text, textvariable, underline, width
WIDGET-SPECIFIC OPTIONS
command, offvalue, onvalue, variable
"""
Widget.__init__(self, master, "ttk::checkbutton", kw)
def invoke(self):
"""Toggles between the sele... | |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 21 12:11:36 2019
@author: keelin
"""
import numpy as np
import opencxr.utils
import skimage.feature
from opencxr.utils.resize_rescale import rescale_to_min_max
from scipy import ndimage
from scipy.ndimage import binary_dilation, find_objects
from skimage import measure
"... | |
}),
.M_REGIONS(M_REGIONS),
.M_BASE_ADDR({ {% for p in range(n-1,-1,-1) %}w_a_r(M{{'%02d'%p}}_BASE_ADDR){% if not loop.last %}, {% endif %}{% endfor %} }),
.M_ADDR_WIDTH({ {% for p in range(n-1,-1,-1) %}w_32_r(M{{'%02d'%p}}_ADDR_WIDTH){% if not loop.last %}, {% endif %}{% endfor %} }),
.M_CONNECT_READ({ {% for p in ... | |
<reponame>os-climate/sostrades-core
'''
Copyright 2022 Airbus SAS
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 a... | |
import networkx as nx
import random
import matplotlib.pyplot as plt
import os
import ast
import re
import sys
import time
import joblib
import numpy as np
from copy import deepcopy
import pandas as pd
from Features.Feature_env import Features
memodict = {}
##########################################################... | |
to extension-specific structure
("onSubdevice", ze_bool_t), ## [out] True if the resource is located on a sub-device; false means
## that the resource is on the device of the calling Sysman handle
("subdeviceId", c_ulong), ## [out] If onSubdevice is true, this gives the ID of the sub-device
("haveFan", ze_bool_t), ... | |
<filename>src/view/views/console/worksheet/ResultGrid.py
'''
Created on 17-Feb-2017
@author: vijay
'''
import wx
import wx.dataview as dv
from wx import ListCtrl
from src.view.constants import ID_COPY_COLUMN_HEADER
import string
import wx.grid as gridlib
import logging.config
from src.view.constants impo... | |
<reponame>JulyKikuAkita/PythonPrac<gh_stars>1-10
__source__ = 'https://github.com/kamyu104/LeetCode/blob/master/Python/arithmetic-slices-ii-subsequence.py'
# https://leetcode.com/problems/arithmetic-slices-ii-subsequence/
# Time: O(n^2)
# Space: O(n * d)
#
# # Description: Leetcode # 413. Arithmetic Slices
#
# A sequen... | |
import json
import logging.config
import sys
from json import JSONEncoder
from stn.utils.uuid import generate_uuid
import networkx as nx
from networkx.readwrite import json_graph
from stn.node import Node
from uuid import UUID
import copy
import math
from stn.task import Timepoint
MAX_FLOAT = sys.float_info.max
cl... | |
<filename>website/views.py
import functools
import json
import string
from random import choice
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core import serializers
from django.core.cache i... | |
<gh_stars>1-10
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
# Copyright (C) 2016-2020 German Aerospace Center (DLR) and others.
# SUMOPy module
# Copyright (C) 2012-2017 University of Bologna - DICAM
# This program and the accompanying materials are made available under the
# terms of the ... | |
<reponame>Moldovandreii/RepetitionCount<gh_stars>1000+
"""Use pika with the Gevent IOLoop."""
import functools
import logging
import os
import threading
import weakref
try:
import queue
except ImportError: # Python <= v2.7
import Queue as queue
import gevent
import gevent.hub
import gevent.socket
import pika.comp... | |
<gh_stars>0
#!/usr/bin/env python
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import json
import os
import shutil
import anndata
import numpy as np
from sklearn.metrics import roc_auc_score, roc_curve
from scipy.sparse import issparse
from collections import defaultdict
import scvi
from scvi.da... | |
<reponame>BenTenmann/scirpy<gh_stars>0
import pandas as pd
import json
from anndata import AnnData
from ._datastructures import AirrCell
from typing import (
Iterable,
Mapping,
MutableMapping,
Sequence,
Union,
Collection,
Optional,
)
import numpy as np
from glob import iglob
import pickle
import os.path
from . i... | |
# coding: utf-8
"""
Hydrogen Nucleus API
The Hydrogen Nucleus API # noqa: E501
OpenAPI spec version: 1.9.5
Contact: <EMAIL>
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from nucleus_api.configuration import Configuration
class Budget(... | |
<reponame>berkalpay/EVcouplings
"""
Functions for handling evolutionary couplings data.
.. todo::
1. clean up
2. add Pompom score
3. add mapping tools (multidomain, complexes)
4. ECs to matrix
5. APC on subsets of positions (e.g. for complexes)
Authors:
<NAME>
<NAME> (original mixture model code)
<NAME> (ske... | |
<reponame>vishalbelsare/synapse<gh_stars>0
import os
import asyncio
import synapse.exc as s_exc
import synapse.common as s_common
import synapse.lib.cell as s_cell
import synapse.lib.base as s_base
import synapse.lib.nexus as s_nexus
import synapse.lib.msgpack as s_msgpack
import synapse.lib.lmdbslab as s_lmdbslab
... | |
<gh_stars>0
from django import forms
from django.apps import apps
from django.core.exceptions import PermissionDenied
from django.urls import reverse, NoReverseMatch
from django.template.context_processors import csrf
from django.db.models.base import ModelBase
from django.forms.forms import DeclarativeFieldsMetaclass
... | |
small security factor for worst case:
Vcellrhomax = V_cell * rho_T.max()
vN_dm_max = np.abs(dm_io).max() * timestep / Vcellrhomax
# get maximum von Neumann stability condition values:
# get dividers for maximum stable timestep to increase or decrease
# stepsize:
vN_diff_mult = vN_diff_max / 0.5
vN_dm_mult = vN_... | |
<reponame>mak-ov/dlcourse_ai-master
import numpy as np
from numpy.core.numeric import zeros_like
def l2_regularization(W, reg_strength):
'''
Computes L2 regularization loss on weights and its gradient
Arguments:
W, np array - weights
reg_strength - float value
Returns:
loss, single value - l2 regularization ... | |
[('ydk.models.cisco_ios_xr.Cisco_IOS_XR_call_home_cfg', 'CallHomeTransMethod', '')])),
('destination_addr', (YLeaf(YType.str, 'destination-addr'), ['str'])),
('enable', (YLeaf(YType.boolean, 'enable'), ['bool'])),
])
self.method = None
self.destination_addr = None
self.enable = None
self._segment_path = lambda: ... | |
import numpy as np
import matplotlib.pyplot as plt
from os import makedirs
from os.path import isfile, exists
from scipy.constants import mu_0
# from numba import njit
def calcDipolMomentAnalytical(remanence, volume):
""" Calculating the magnetic moment from the remanence in T and the volume in m^3"""
m = remanence... | |
= histogram.Histogram1D(bin_edges=bin_edges, y=y, errors_squared=errors_squared)
if access_attributes_which_are_stored:
# This attribute will be stored (but under "_x"), so we want to make sure that it
# doesn't disrupt the equality comparison.
h1.x
if not test_equality:
h1.bin_edges = np.array([5, 6, 7, 8, 9])... | |
<filename>silx/gui/icons.py<gh_stars>10-100
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2016 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated doc... | |
import json
import logging
import re
from typing import Iterable, List, Optional, Type, TypeVar
from bs4 import BeautifulSoup
from sqlalchemy.orm import Session
from fallen_london_chronicler.images import get_or_cache_image, ImageType
from fallen_london_chronicler.model import Area, AreaType, Storylet, \
StoryletCat... | |
source_1)
source_2 = _AppendType(add_type, source_2)
if _UnsignedType(add_type):
self.EmitOp3('uaddw', destination, source_1, source_2)
else:
self.EmitOp3('saddw', destination, source_1, source_2)
def EmitVCvt(self, cvt_to, cvt_from, destination, source):
if cvt_to == 'f32' and cvt_from == 's32':
self.EmitOp2(... | |
%(veqinstr)s(compslice, datasliceright);
// Compare the results of the SIMD operation.
if ((__builtin_ia32_pmovmskb128((v16qi) resultslice) != 0xffff)) {
return 0;
}''',
'lt' : '''// Make sure they're not equal.
resultslice = %(veqinstr)s(datasliceleft, datasliceright);
if (!(__builtin_ia32_pmovmskb128((v1... | |
"""
Module that contains many useful utilities
for validating data or function arguments
"""
from typing import Iterable, Union
import warnings
import numpy as np
from my_happy_pandas.core.dtypes.common import is_bool
def _check_arg_length(fname, args, max_fname_arg_count, compat_args):
"""
Checks whether 'args' ... | |
<filename>datastore_utils.py
#Copyright July 2021 Ontocord LLC. Licensed under Apache v2 https://www.apache.org/licenses/LICENSE-2.0
#datastore_utils.py
from collections.abc import Iterable
from dataclasses import dataclass, field, fields
from typing import Any, ClassVar, Dict, List, Optional, Sequence, Tuple, Union
f... | |
<reponame>ElvisNguyen/Hoshii-kun
import discord
import asyncio
import dateparser
import datetime
import math
import json
import pytz
import apscheduler
import pymongo
import dns
import requests
import arrow
import csv
import random
from difflib import SequenceMatcher
from discord.ext import commands,... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Bioindustrial-Park: BioSTEAM's Premier Biorefinery Models and Results
# Copyright (C) 2020-, <NAME> <<EMAIL>>
#
# This module is under the UIUC open-source license. See
# github.com/BioSTEAMDevelopmentGroup/biosteam/blob/master/LICENSE.txt
# for license details.
'''
Re... | |
= set()
for m in self._current_media:
locations_manager = m.GetLocationsManager()
if url in locations_manager.GetURLs():
removee_media.add( m )
if len( removee_media ) > 0:
removee_hashes = { m.GetHash() for m in removee_media }
content_update = HydrusData.ContentUpdate( HC.CONTENT_TYPE_URLS, H... | |
(lnext[0] - lower[li][0])
ylower = lower[li][1] + frac * (lnext[1] - lower[li][1])
return xnext
def func_78cafb3f55af4821b4ab185596e77daf(li, unext, lnext, lower):
xnext = unext[0]
frac = 1.0 * (xnext - lower[li][0]) / (lnext[0] - lower[li][0])
ylower = lower[li][1] + frac * (lnext[1] - lower[li][1])
return fra... | |
}
},
TaskInvocationParameters={
'RunCommand': {
'Comment': 'string',
'DocumentHash': 'string',
'DocumentHashType': 'Sha256'|'Sha1',
'NotificationConfig': {
'NotificationArn': 'string',
'NotificationEvents': [
'All'|'InProgress'|'Success'|'TimedOut'|'Cancelled'|'Failed',
],
'NotificationType': 'Command'|'Inv... | |
<reponame>davidgcameron/arc
from __future__ import print_function
from __future__ import absolute_import
from .ControlCommon import *
import subprocess
import sys
import re
import pickle
import time
import pwd
import signal
try:
input = raw_input # Redefine for Python 2
except NameError:
pass
def complete_job_own... | |
"""
Coupling
********
Functions to estimate coupling from twiss dataframes and different methods to calculate the closest tune
approach from the calculated coupling RDTs.
"""
import logging
from contextlib import suppress
from typing import Sequence, Tuple
import numpy as np
from pandas import DataFrame, Series
from ... | |
`{name}` is not valid")
if name in main_args:
Manager.exit(1, f"[{error_msg_name_part}] Configuration name `{name}` cannot be changed")
if not value:
removed_args.add(name)
elif ELIF_THEN_RE.search(name) or VAR_RE.search(value):
# if the value contains a variable, we only check the name
# same if it's a "elif" ... | |
is used
result = torch.linalg.matrix_rank(a, atol=tol_value, rtol=tol_value)
self.assertEqual(result, 2) # there are 2 singular values above max(0.81, 1.5*0.81)
# CUDA 11.6 issue failure https://github.com/pytorch/pytorch/issues/75391
@skipCUDAIf(torch.version.cuda is not None
and torch.version.cuda.split(".") ==... | |
by using deploy_id and its stage (hostStage = 0 ~ 8)
def get_hosts_by_deploy(request, name, stage, deploy_id):
hostStageString = request.GET.get('hostStage')
if hostStageString is None:
hostStage = TOTAL_ALIVE_HOST_REPORT
else:
hostStage = hostStageString
envs = environs_helper.get_all_env_stages(request, name)
... | |
which="psf", index=None, **kwargs):
""" kwargs goes to get_keys()
Parameters
----------
which: [string] -optional-
Source of magnitude measurements
- 'psf'
- 'ap'
- 'apbig'
"""
extra = "g" if which != "psf" else "" # strange ipac structure
return self.get_keys(["jd",f"mag{which}",f"sigma{extra}{which}","fi... | |
<filename>modules/embedding.py
#!/usr/bin/env python
# -*- coding=utf-8 -*-
###########################################################################
# Copyright (C) 2013-2021 by Caspar. All rights reserved.
# File Name: embedding.py
# Author: <NAME>
# E-mail: <EMAIL>
# Created Time: 2021-03-29 17:19:30
#############... | |
import unittest
from conda_build_all.conda_interface import MatchSpec
from conda_build_all.version_matrix import (parse_specifications,
special_case_version_matrix,
filter_cases,
keep_top_n_major_versions,
keep_top_n_minor_versions)
from conda_build_all.tests.unit.dummy_index import DummyPackage, DummyIndex
cla... | |
run.
# - For building cross compilation tools: Where the cross compiler will run.
os:
Windows:
subsystem: [None, cygwin, msys, msys2, wsl]
WindowsStore:
version: ["8.1", "10.0"]
WindowsCE:
platform: ANY
version: ["5.0", "6.0", "7.0", "8.0"]
Linux:
Macos:
version: [None, "10.6", "10.7", "10.8", "10.9", "10.10"... | |
returns a random hash function which returns hash values from 0..N-1.
"""
if not isinstance(keys, (list, tuple)):
raise TypeError("list or tuple expected")
NK = len(keys)
if NK != len(set(keys)):
raise ValueError("duplicate keys")
for key in keys:
if not isinstance(key, str):
raise TypeError("key a not string:... | |
<filename>project_6_starter.py
#!/usr/bin/env python
# coding: utf-8
# # Project 6: Analyzing Stock Sentiment from Twits
# ## Instructions
# Each problem consists of a function to implement and instructions on how to implement the function. The parts of the function that need to be implemented are marked with a `# TOD... | |
<reponame>dianshao-embedded/dianshao
from datetime import datetime
import os
import socket
import json
from sqlite3 import Timestamp
from celery import shared_task
from progressui.backend import ProgressSend
from git.repo.base import Repo
from tools import shell, git, bbcommand, patch, bbfile, dishes
from tools import ... | |
<gh_stars>0
'''
Neural networks for standard systems
'''
import numpy as np
import collections
import tensorflow as tf
from tensorflow import math as tfm
from tensorflow import linalg as tfl
from tools import vae_utils
from neural_networks import layers
from neural_networks import NN_utils
class Classifier(object):
... | |
"""
This Is My Deeeep.io Version Using Pymunk
So That The Collision And Stuff Like That Is Not Crappy.
"""
# Import Librarys And Modules
import arcade
import random
import math
import pymunk
from typing import Optional
from Pymunk_Helping_Code import follow_sprite
from arcade.pymunk_physics_engine import PymunkPhys... | |
<gh_stars>1-10
""" Lazy-CSeq Sequentialization module
(swarm version of the corresponding name)
maintained by <NAME>, University of Southampton.
"""
VERSION = 'lazyseqnewscheduleswarm-0.1-2016.09.14'
"""
Transformation:
implements the lazy sequentialization schema
(see Inverso, Tomasco, Fischer, <NAME>, Parlato, ... | |
<filename>self_play.py<gh_stars>0
import time
import math
import numpy
import ray
import torch
import models
@ray.remote
class SelfPlay:
"""
Class which runs in a dedicated thread to play games and save them to the replay buffer.
"""
def __init__(self, initial_checkpoint, Game, config, seed):
self.config = co... | |
# Copyright 2013 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... | |
<reponame>EmPlatts/FRB
""" Module for IGM calculations
"""
from __future__ import print_function, absolute_import, division, unicode_literals
import numpy as np
import os
from IPython import embed
from pkg_resources import resource_filename
from scipy.interpolate import interp1d
from scipy.interpolate import Interpo... | |
- NON-SKILLED", max_length=2)
SKILLED = models.CharField("TYPE OF HLTH CARE WRKR - SKILLED", max_length=2)
SKILLWOS = models.CharField("SPECIFY TYPE OF SKILLED WORKER", max_length=25)
OTHCW = models.CharField("TYPE OF HLTH CARE WRKR - SOME OTHER", max_length=2)
OTHCWOS = models.CharField("SPECIFY OTHER TYPE HEALTH ... | |
else:
c = nv.quantil(1-Rational(alpha, 2))
krit1 = p0 - c*sqrt(p0*(1-p0)/n)
krit2 = p0 + c*sqrt(p0*(1-p0)/n)
krit1 = ceiling(n*krit1) - 1
krit2 = floor(n*krit2) + 1
ab= {i for i in range(krit1+1)}.union({i for i in range(krit2, n+1)})
return ab
def ab_ber_(self, **kwargs):
"""ebenso; zugehörige Methode... | |
import csv
import cv2
import numpy as np
import pandas as pd
import sys
from datetime import datetime
from numpy.random import RandomState
import keras
import tensorflow as tf
from keras.models import Sequential
from keras.callbacks import ModelCheckpoint
from keras.layers import Flatten, Dense, Lambda, Cropping2D, C... | |
: "uk.gov.gchq.gaffer.operation.impl.export.set.ExportToSet"
}, {
"class" : "uk.gov.gchq.gaffer.operation.impl.DiscardOutput"
}, {
"class" : "uk.gov.gchq.gaffer.operation.impl.export.set.GetSetExport",
"start" : 2,
"end" : 4
} ]
}
''',
g.OperationChain(
operations=[
g.GetAllElements(),
g.ExportToSet(),
g.... | |
<reponame>yisibl/picosvg
# Copyright 2020 Google 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 applicable law or ag... | |
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | |
board
Attributes
----------
map : list
a 2d list that is the game board
currentShips : dict
A dictionary of all ships currently on the board and how many
hits they have recived
hits : list
A list of coordinates that have been engaged
sunkShips : list
A list of ships that have been sunk
Methods
-------
g... | |
"""Exit context manager.
.. versionchanged:: 1.0.0 disconnect enforced on close
.. versionchanged:: 1.1.0 release lock on exit
.. versionchanged:: 1.2.1 disconnect enforced on close only not in keepalive mode
"""
if not self.__keepalive_period:
self.close()
super().__exit__(exc_type, exc_val, exc_tb)
@propert... | |
the variable
"""
if not self._bound_target:
self._metadata_buffer[name] = value
else:
self._bound_target.setncattr(name, value)
def _dump_metadata_buffer(self):
"""
Dump the metadata buffer to file
"""
if self._bound_target is None:
raise UnboundLocalError("Cannot dump the metadata buffer to target since no... | |
"dtype"):
rhs_dtype = rhs.dtype
else:
try:
rhs_dtype = np.dtype(rhs)
except:
rhs_dtype = None
if dtype is None:
dtype = np.result_type(self.dtype, rhs_dtype)
elif dtype == "float":
dtype = (
np.float32
if rhs_dtype == np.float32 and self.dtype == np.float32
else np.float64
)
if isinstance(new_array_size... | |
7.25162339277303*(1.27323954473516*m.x117)**2.435*(m.x14 - m.x21) == 0)
m.c60 = Constraint(expr=SignPower(m.x60,1.852) - 2.58578563053754*(1.27323954473516*m.x118)**2.435*(m.x15 - m.x16) == 0)
m.c61 = Constraint(expr=SignPower(m.x61,1.852) - 5.84921218726644*(1.27323954473516*m.x119)**2.435*(m.x15 - m.x22) == 0)
m.c... | |
input climate data
###Convert thiessen polygons to raster by group
arcpy.PolygonToRaster_conversion(outFspPoly,"SS_GROUP",spgpMASK,"CELL_CENTER","NONE","#")
###Clip theissen groups by bias file, then save to ascii
arcpy.gp.Times_sa(BiFiIn,spgpMASK,BiFiOut)
gp.AddMessage("Generating regional bias files for spatial ... | |
self.btn_execution.setMinimumSize(QSize(0, 45))
self.btn_execution.setFont(font)
self.btn_execution.setCursor(QCursor(Qt.PointingHandCursor))
self.btn_execution.setLayoutDirection(Qt.LeftToRight)
self.btn_execution.setStyleSheet(u"background-image: url(:/icons/images/icons/cil-terminal.png);")
self.verticalLayout... | |
heapq.heappop(lNodes)
lVisitedNodes.append((h, tNode))
for plot in plots.surrounding(tNode):
if plotFunction(location(plot)):
if plot in targets: return True
tTuple = (targets.closest_distance(plot), location(plot))
if not tTuple in lVisitedNodes and not tTuple in lNodes:
heapq.... | |
the serial port
:rtype: str
**Command**
+----------+------------+------------+----------------------------------------------------------------------------------+
| Byte 1 | Byte 2-3 | Byte 4-5 | Byte 6 | Byte 7 |
+==========+============+============+==============================================================... | |
The video is not in VAL so in contexts that do and don't allow cache misses we should always get a fallback
result = self.get_result(allow_cache_miss)
self.verify_result_with_fallback_and_youtube(result)
@ddt.data(
({}, '', [], ['en']),
({}, '', ['de'], ['de']),
({}, '', ['en', 'de'], ['en', 'de']),
({}, 'en-su... | |
with different weights. Conceptually it
computes:
output= [f(theta[i], input[i]) for i in range(p.repeat)]
where f is the fprop function of the sublayer, theta[i] and input[i] are
the weights and inputs of the i-th sublayer.
"""
def _InferOutShapes(self, args):
input_shapes = [
None if arg is None else tshap... | |
# program to extract data from FITS files into files to repressent a box of the stellar atmosphere, including turbulent velocity.
import pyfits
import numpy as np
import os.path
import os
# Currently using Slice_rot_3D, set vbswitch to 0 if v and B files are not required.
def Slice(locin, locout, star, mag, num, dz):... | |
atol=1e-14)
np.testing.assert_allclose(np.diff(grid1.x)[nx-1], -dx*(nx-1))
np.testing.assert_allclose(np.diff(grid1.y)[nx-1], dx)
# Another set, but with odd nx
for _ in range(10):
backDist = rng.uniform(9.0, 11.0)
wavelength = rng.uniform(300e-9, 1100e-9)
while (nx%2) == 0:
nx = rng.integers(10, 21)
lx = rng... | |
<gh_stars>10-100
#!/usr/bin/python3
# COPYRIGHT 2021 BY EXTRAHOP NETWORKS, INC.
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE', which is part of this source code package.
import json
import boto3
import os
from netaddr import IPNetwork, IPAddress
EC2_CLIENT = boto3.client("ec2")
# T... | |
88
new_vm.memory[11] = 88
new_vm.memory[12] = 88
new_vm.memory[13] = 88
new_vm.memory[14] = 88
new_vm.memory[15] = 88
new_vm.memory[16] = 88
new_vm.memory[17] = 88
new_vm.memory[18] = 88
new_vm.memory[19] = 88
new_vm.memory[20] = 88
new_vm.memory[21] = 88
new_vm.memory[22] = 88
new_vm.memory[23] = 88
new_... | |
namespace_, name_='grid')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='t:', name_='grid'):
if self.dist... | |
n)
if hash in _dict_conjugate:
return _dict_conjugate[hash].copy()
cc = np.zeros(n, dtype = np.int)
if n > 0:
for j, k in enumerate(c):
if k >= n:
cc[n-1] += 1
elif k >= 1:
cc[k-1] += 1
s = cc[n-1]
for j in xrange(n-2, -1, -1):
s += cc[j]
cc[j] = s
_dict_conjugate[hash] = cc
return cc
# Eliminate ex... | |
if we should use homosapiens dataset on gene dates
mindistance: int the minimal phylogenetic distance between in average in this homology to consider it
highly conserved
preserved: bool to true if we should find highly preserved genes or not
size: the average size of the datapoints in the pointcloud representation ... | |
"""Functions for builtin CherryPy tools."""
import logging
import re
from hashlib import md5
import six
from six.moves import urllib
import cherrypy
from cherrypy._cpcompat import text_or_bytes
from cherrypy.lib import httputil as _httputil
from cherrypy.lib import is_iterator
# Conditional HTTP request support #
... | |
"""
Author: <NAME>
BSD 3-Clause License
Copyright (c) 2019, The Regents of the University of Minnesota
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... | |
2.2 and 3.0 compat
self.assertTrue(
'File extension “” is not allowed' in res['error']['image'][0]
or 'File extension \'\' is not allowed' in res['error']['image'][0])
@override_settings(MEDIA_ROOT=os.path.join(settings.BASE_DIR, 'media_test'))
def test_comment_image_upload_unique_bad_name(self):
utils.login(sel... | |
top genotype
top_genotype = self._to_top(i, genotype, coding, location)
# replace alleles in ped lines only if necessary
new_line[6+i*2], new_line[6+i*2+1] = top_genotype
return new_line
def _check_file_sizes(self, line):
# check genotypes size 2*mapdata (diploidy) + 6 extra columns:
if len(line) != len(self.... | |
22.5056461813379*m.x3335
+ 22.1617279110058*m.x3336 + 29.6585391439873*m.x3337 + 22.8299755509779*m.x3338
+ 20.8671488680664*m.x3339 + 10.1010293848718*m.x3340 + 23.9887690242752*m.x3341
+ 26.3362278937491*m.x3342 + 13.5190583563331*m.x3343 + 26.6306210689289*m.x3344
+ 17.350679114*m.x3345 + 27.7508454104506*m.x334... | |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-12-22 14:18
from __future__ import unicode_literals
import django.db.models.deletion
import django.utils.timezone
import djgeojson.fields
from django.conf import settings
from django.conf import settings
from django.contrib.sites.models import Site
from djan... | |
row['ctl_rules'].split(';')
else:
rs = [row['ctl_rules']]
for r in rs:
operator = False
if ('>=' in r):
operator = '>='
action = 'greater_than_or_equal_to'
elif ('<=' in r):
operator = '<='
action = 'less_than_or_equal_to'
... | |
<filename>blackswan/visualisation.py
# encoding: utf8
import os
from os.path import join
from tempfile import mkstemp
from netCDF4 import Dataset
from datetime import datetime, date
import numpy as np
import logging
from matplotlib import use
use('Agg') # use this if no xserver is available
from matplotlib import pypl... | |
###########################################
# VCZ calibration (coarse landscape) FLUX dance 1
###########################################
file_cfg = gc.generate_config(in_filename=input_file,
out_filename=config_fn,
mw_pulse_duration=20,
ro_duration=2200,
flux_pulse_duration=60,
init_duration=200000)
# set CZ par... | |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance w... | |
<reponame>Excalibur95/eneticAlgorithmsWithPython
# File: ticTacToe.py
# Del capítulo 18 de _Algoritmos Genéticos con Python_
#
# Author: <NAME> <<EMAIL>>
# Copyright (c) 2017 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# Y... | |
a discrete intensity grid
:param xy: observed spatial locations as a two-column vector
:param w: observation window, i.e. discrete grid to be mapped to, [xmin xmax ymin ymax]
:param nt: two-element vector defining number of bins in both directions
"""
# Make grid
x = nnp.linspace(w[0], w[1], nt[0] + 1)
y = nnp.l... | |
the encoder.
mean = np.array(transform['mean']).reshape(3, 1, 1)
std = np.array(transform['std']).reshape(3, 1, 1)
image = (image - mean) / std
image = image.astype(np.float32)
return image, gt_image, load_dict
def resize_label_image(self, image, gt_image):
size = self.conf['transform']['patch_size']
# https... | |
#!/usr/bin/env python3
# Copyright 2018 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Utility to manipulate Chrome OS disk & firmware images for manufacturing.
Run "image_tool help" for more info and a list of sub... | |
rights.
Source: https://core.telegram.org/bots/api#exportchatinvitelink
:param chat_id: Unique identifier for the target chat or username of the target channel
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:return: Returns exported invite link as String on success.
:rtype: :obj:`base.String`
"""... | |
<filename>thermo/equilibrium.py
# -*- coding: utf-8 -*-
'''Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2019, 2020 <NAME> <<EMAIL>>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Softwa... | |
# Shim file to support IDA 6.x-7.3 and 7.5+
# Documentation provided by Hex-Rays:
# https://hex-rays.com/products/ida/support/ida74_idapython_no_bc695_porting_guide.html
import idc
import idaapi
try:
import ida_bytes
except ImportError:
ida_bytes = None
try:
import ida_name
except ImportError:
ida_name = None
t... | |
is successfully stopped: FAILED", tid)
output = runr(self, 'cat /var/log/respawner.log| grep "Child exited: 15 /usr/local/bin/unitcomm">/dev/null; echo $?', tid)
if output == '0':
log_green("Verify that unitcom process is successfully exited: PASSED", tid)
else:
log_red("Verify that unitcom process is successfull... | |
# report.py
# Copyright 2008 <NAME>
# Licence: See LICENCE (BSD licence)
"""Generate a report comparing results with schedule.
"""
import re
from solentware_misc.core import utilities
from solentware_misc.core.null import Null
from .gameobjects import (
MatchReport,
MatchGame,
Section,
Game,
Player,
Unfinished... | |
# Importar librerías/modulos
import arcade
import time
import webbrowser
# Versión del juego
version = "Alpha"
# Tamaño de la ventana (ancho y alto)
s_width = 800
s_height = 600
# Parámetro relacionado a la velocidad del personaje
MOVEMENT_SPEED = 5
# Margen de pixeles Jugador - Pantalla
LEFT_VIEWPORT_MARGIN = 400
... | |
<reponame>kalaspuff/stockholm<filename>stockholm/money.py
from __future__ import annotations
import decimal
import json
import re
from decimal import ROUND_HALF_UP, Decimal
from functools import reduce
from typing import Any, Dict, Generic, Iterable, List, Optional, Tuple, Type, TypeVar, Union, cast
from .currency im... | |
<path i\
d=\x22path4496\x22 d=\x22\
m1410.8-552.18-2\
.6811-0.78534v-1\
.6593-1.6593l2.6\
172-2.8863c1.439\
4-1.5875 2.6774-\
2.9468 2.7509-3.\
0206 0.1162-0.11\
664 0.1338 0.583\
79 0.1338 5.3399\
0 3.0108 0.1003\
5.5024 0.061 5.\
4976-0.039 0-1.4\
08-0.39464-2.882\
4-0.82659z\x22/>\x0a \
<path id=\x22path4\
494\x2... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.