input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
- data1))
"""
def __init__(self, in_dim, cond_dim, n_flow_steps,
wn_num_conv1d, wn_dim_channel, wn_kernel_size,
flag_affine=True,
flag_split = False,
flag_final_block=False,
split_dim = 2,
flag_affine_block_legacy=False):
"""WaveGlowBlock(in_dim, cond_dim, n_flow_steps,
wn_num_conv1d, wn_dim_channel, wn_ke... | |
"ordering": ["name"],
"abstract": False,
},
),
migrations.CreateModel(
name="PlanUnitIntendedUse",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=255, verbose_name="Name")),
],
options={
"verbose_n... | |
import json
import mock
from werkzeug.routing import Rule
from doctor.docs import base
from doctor.resource import ResourceAnnotation
from doctor.response import Response
from .base import TestCase
from .types import (
Age, AgeOrColor, Auth, Color, Colors, ExampleArray, ExampleObject,
ExampleObjects, ExampleObject... | |
# -*- coding: utf-8 -*-
"""Unit test for the actions module.
Copyright (c) 2017 carlosperate https://github.com/carlosperate/
Licensed under the Apache License, Version 2.0 (the "License"):
http://www.apache.org/licenses/LICENSE-2.0
"""
from __future__ import unicode_literals, absolute_import, print_function
... | |
**func_dict['kwargs'])
for it, batch in self.iter_batch(enumerate(train_loader)):
for func_dict in self._schedule[self._begin_iter_].values():
func_dict['func'](*func_dict['args'], **func_dict['kwargs'])
net.train(True)
batch = utils.batch_to_device(batch, device=device)
solver.zero_grad()
loss = net.train_pro... | |
<reponame>deaconjs/SPADE
"""Wrapper for BWidget family of widgets"""
# The authors hereby grant permission to use, copy, modify, distribute,
# and license this software and its documentation for any purpose, provided
# that existing copyright notices are retained in all copies and that this
# notice is included verbati... | |
nearest_stream.get('closest_stream_point')
stream_name = nearest_stream.get('gnis_name', '')
stream_feature_id = nearest_stream.get('linear_feature_id', None)
point_on_stream = shape(nearest_stream_point)
return (stream_feature_id, stream_name, point_on_stream)
def get_watershed_id_at_point(db: Session, point: P... | |
Label(self.matrixOfGraphLabel, text="Matrix Entry", bg=self.color_main_content,
fg=self.color_red,
bd=0, anchor=W)
self.matrixLabel.place(relx=0, rely=0.05, relheight=0.1, relwidth=0.8)
self.matrixLabel['font'] = font1
#self.text_matrix_1 = "Please Enter matrix separated by ','(example: 0010,1101,0101,1111 => 4*4... | |
<reponame>earthlab/firedpy
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
from collections import OrderedDict
import datetime as dt
import gc
import geopandas as gpd
from getpass import getpass
from glob import glob
from io import BytesIO
from multiprocessing import cpu_count, Pool
from netCDF4 import ... | |
<reponame>Flipajs/FERDA
__author__ = 'simon'
import random
import matplotlib.colors as colors
import numpy as np
from PyQt4 import QtGui, QtCore
from skimage.transform import resize
from core.log import LogCategories, ActionNames
from core.region.region import Region
from gui.graph_widget.custom_line_selectable impo... | |
0XF0, 0XC1, 0XE3, 0XF8, 0X70, 0XE1, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF,
0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XF1, 0XE1, 0XE3, 0XF8, 0X70, 0XE1, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF,
0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XF1, 0XE0, 0XC3, 0XF8, 0X70, 0XE1, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF,
0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XF1, 0XE0, 0X03, 0XF8, 0X... | |
import sys
from abc import ABC, abstractmethod
from typing import List, Iterable, Callable, Tuple
from pygame.surface import Surface
from lib.action.event import (
mouse_position, game_event,
pump_event, pressed_mouse,
draw_ellipse, smooth_scale,
init_game
)
from lib.environment.color import GameColor
from lib.envi... | |
<reponame>l2tor/underworlds
import uuid
import time
import logging;logger = logging.getLogger("underworlds.server")
from underworlds.types import *
import underworlds_pb2 as gRPC
from grpc.beta import interfaces as beta_interfaces
class Server(gRPC.BetaUnderworldsServicer):
def __init__(self):
self._worlds = {}... | |
2, so this verifies that reversed() still turns this into an
# iterator.
assert isinstance(act_keys_iter, Iterator)
act_keys = list(act_keys_iter)
assert act_keys == exp_keys
TESTCASES_DICTVIEW_GET = [
# Testcases for DictView.get()
# Each list item is a testcase tuple with these items:
# * desc: Short test... | |
<gh_stars>1-10
"""
This Python script calculates HST ACS WFC photometry.
The class can be used to run calacs for calibrating the raw data.
The class contains also a simple interface for SExtractor that
can be used to find locations of stars in the image.
:depends: PyRAF
:author: <NAME>, for STScI
:history: 02/10/09... | |
""" Broadly applicable NGS processing/analysis functionality """
import os
import re
import subprocess
import errno
from attmap import AttMapEcho
from yacman import load_yaml
from .exceptions import UnsupportedFiletypeException
from .utils import is_fastq, is_gzipped_fastq, is_sam_or_bam
class NGSTk(AttMapEcho):
""... | |
<gh_stars>1-10
from __future__ import print_function, division, absolute_import
import numpy as np
from llvmlite.llvmpy.core import Type, Builder, ICMP_EQ, Constant
from numba import types, cgutils, compiler
from ..caching import make_library_cache, NullCache
def _build_ufunc_loop_body(load, store, context, func, b... | |
<reponame>barentsen/photutils
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import math
import warnings
import numpy as np
from astropy.coordinates import SkyCoord
import astropy.units as u
from astropy.wcs.utils im... | |
import os
import sys
import time
import json
import yaml
import socket
import string
import netaddr
import threading
import constants as const
import subprocess32 as subprocess
from node import Node
from rest import RestLib
from bridge import Bridge
from threading import Lock
from membership_rule import MembershipRule
... | |
}
)
@signin_required()
def get_workflow_logs(workflow_id_or_name, user, **kwargs): # noqa
r"""Get workflow logs.
---
get:
summary: Get workflow logs of a workflow.
description: >-
This resource reports the status of a workflow.
Resource is expecting a workflow UUID.
operationId: get_workflow_logs
produces:
-... | |
import datetime
import pytz
import requests
from unittest.mock import patch
from . import TembaClient
from .types import Broadcast, Group, FlowDefinition
from ..exceptions import TembaException, TembaNoSuchObjectError, TembaMultipleResultsError, TembaBadRequestError
from ..exceptions import TembaConnectionError
from .... | |
<gh_stars>1-10
from pathlib import Path
import numpy as np
from matplotlib import pyplot as plt
from typing import Union, Optional, OrderedDict
Array = Union[list, np.ndarray]
# ref: https://stackoverflow.com/questions/47074423/how-to-get-default-blue-colour-of-matplotlib-pyplot-scatter/47074742
MY_DEFAULT_BLUE: s... | |
<gh_stars>0
import os
import re
import sys
import logging
import warnings
import idlib
from idlib.utils import log as _ilog
from augpathlib.utils import log as _alog
from pyontutils.utils import (makeSimpleLogger,
python_identifier, # FIXME update imports
TZLOCAL,
utcnowtz,
isoformat,
isoformat_safe,
timeformat_f... | |
np.uint64(2)
# feature data
fd = m.create_group('FeatureData')
fd.attrs['AttributeMatrixType'] = np.uint32(7)
fd.attrs['TupleDimensions'] = np.uint64(self.grains.nrows)
Euler = np.array([Orientation.from_rodrigues(g['orientation'])
for g in self.grains], dtype=np.float32)
avg_euler = fd.create_dataset('AvgEulerA... | |
we'll leak memory (hold on to objects in the cache that could have been
# garbage collected).
tracer.log("caller")
self.object_engine.run_sql("SET LOCAL synchronous_commit TO off")
self._release_objects(required_objects)
tracer.log("release_objects")
logging.debug("Releasing %s", pluralise("object", len(required_... | |
corrector.Execute(inputImage, maskImage)
corrected_img = sitk.GetArrayFromImage(corrected_itk_img)
ax[ind, 1].imshow(corrected_img[largest, :, :], cmap='gray')
if not no_masks:
for contour in pancreas_contours:
ax[ind, 1].plot(contour[:, 1], contour[:, 0], linewidth=2, color='r', alpha=0.5)
ax[ind, 1].set_title(... | |
<filename>roombapy/mapping/roomba_mapper.py
import io
import math
import logging
import os
import time
from typing import TYPE_CHECKING, NamedTuple, Tuple
import textwrap
# Import trickery
global HAVE_PIL
HAVE_PIL = False
try:
from PIL import Image, ImageDraw, ImageFont
HAVE_PIL = True
except ImportError:
print("P... | |
"key": "STRING_VARIABLE", "type": "string", "value": "Variation-1 string"},
{"id": 2, "key": "INTEGER_VARIABLE", "type": "integer", "value": 456},
],
"isFeatureEnabled": True,
},
{
"id": "3",
"name": "Variation-2",
"weight": 30,
"variables": [
{"id": 1, "key": "STRING_VARIABLE", "type": "string", "value": "Va... | |
the network depth. The depth is given by the length of the argument
"layers".
'''
def __init__(self, channel, layers, kernel_size=3, in_planes=1, out_planes=1):
'''Initialization
Arguments:
channel: the channel number of the first layer, would also used
as the base of the following channels.
layers: a list of l... | |
<filename>fhir/resources/messageheader.py<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Profile: http://hl7.org/fhir/StructureDefinition/MessageHeader
Release: R4
Version: 4.0.1
Build ID: 9346c8cc45
Last updated: 2019-11-01T09:29:23.356+11:00
"""
from typing import Any, Dict
from typing import List as ListType
from pydant... | |
will generate a packetSent notification with the calllbackId. The application is responsible for constructing a valid 6LoWPAN packet. The packet is sent to the mote best-effort, so the application should deal with responses and timeouts, if any.
#
# The sendIP command should be used by applications that require en... | |
import numpy as np
import sys
import scipy.interpolate as interpolate
import asdf
from .function import *
from .basic_func import Basic
class Func:
'''
The list of (possible) `Func` attributes is given below:
Attributes
----------
'''
def __init__(self, MB, dust_model=0):
'''
Parameters
----------
dust_mo... | |
sum = "h1:3tMoCCfM7ppqsR0ptz/wi1impNpT7/9wQtMZ8lr1mCQ=",
version = "v1.4.0",
)
go_repository(
name = "com_github_gliderlabs_ssh",
importpath = "github.com/gliderlabs/ssh",
sum = "h1:6zsha5zo/TWhRhwqCD3+EarCAgZ2yN28ipRnGPnwkI0=",
version = "v0.2.2",
)
go_repository(
name = "com_github_globalsign_mgo",
import... | |
name was incorrect. Theme was not deleted.'
)
assert Addon.objects.filter(id=theme.id).exists()
self.assert3xx(response, theme.get_dev_url('versions'))
class TestHome(TestCase):
fixtures = ['base/addon_3615', 'base/users']
def setUp(self):
super(TestHome, self).setUp()
assert self.client.login(email='<EMAIL>'... | |
= None
''' '''
id_data = None
''' '''
def append(self, draw_func):
'''
'''
pass
def as_pointer(self):
'''
'''
pass
def bl_rna_get_subclass(self):
'''
'''
pass
def bl_rna_get_subclass_py(self):
'''
'''
pass
def draw(self, context):
'''
'''
pass
def driver_add(self):
'''
'''
... | |
a watershed on the
distance-transformed thresholded image.
- *{WA_PROPAGATE}:* This method uses a propagation algorithm instead
of a watershed. The image is ignored and the pixels are assigned to
the objects by repeatedly adding unassigned pixels to the objects
that are immediately adjacent to them. This method is ... | |
<reponame>vinjn/net-doctor<gh_stars>0
# $Id: dns.py 27 2006-11-21 01:22:52Z dahelder $
# -*- coding: utf-8 -*-
"""Domain Name System."""
from __future__ import print_function
from __future__ import absolute_import
import struct
import codecs
from . import dpkt
from .compat import compat_ord
DNS_Q = 0
DNS_R = 1
# Op... | |
<filename>src/exomole/read_def.py
"""Module grouping some data-classes and the parser for reading and parsing the
ExoMol *.def* files.
"""
import warnings
from pathlib import Path
from pyvalem.formula import Formula, FormulaParseError
from .exceptions import (
LineValueError,
LineCommentError,
LineWarning,
DefPar... | |
#!/bin/env python
# Automatically translated python version of
# OpenSceneGraph example program "osgthreadedterrain"
# !!! This program will need manual tuning before it will work. !!!
import sys
from osgpypp import OpenThreads
from osgpypp import osg
from osgpypp import osgDB
from osgpypp import osgGA
from osgpypp... | |
<reponame>lebarsfa/vpython-wx
from __future__ import division
from .cvisual import vector
from .primitives import (label, curve, faces, points, distant_light)
from .create_display import display
from . import crayola
color = crayola
from numpy import (array, arange, ndarray, zeros, sort, searchsorted,
concate... | |
"",
"chat": "",
"facebook": "",
"forum": "",
"github": "",
"gitter": "",
"instagram": "",
"linkedin": "",
"reddit": "",
"slack": "",
"telegram": "",
"twitter": "",
"youtube": ""
}
},
"PRON": {
"symbol": "PRON",
"address": "0xA3149E0fA0061A9007fAf307074cdCd290f0e2Fd",
"decimals": 8,
"name": "PronCoin"... | |
<gh_stars>10-100
# Copyright (c) 2013. Librato, Inc.
# 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 condi... | |
<filename>xformer/transformer.py
import tensorflow as tf
class BaseModel:
def on_train_start(self): pass
def on_epoch_end(self): pass
def on_fit_end(self): pass
def on_epoch_start(self): pass
def fit(self, dl, n_epochs=1, callbacks=None):
self.dl = dl
self.n_epochs = n_epochs
self.on_train_start()
if... | |
<reponame>Crunch-io/crunch-cube
# encoding: utf-8
"""Provides the Dimension class."""
import copy
from collections.abc import Sequence
from typing import Dict, Iterator, List, Optional, Tuple, Union
import numpy as np
from cr.cube.enums import (
COLLATION_METHOD as CM,
DIMENSION_TYPE as DT,
MARGINAL,
MEASURE,
... | |
from django.shortcuts import render,redirect
from django.http import JsonResponse
from .models import *
from django.views import View
from django.db.models import Q
from django.forms import model_to_dict
from django.contrib.auth import get_user_model
# Create your views here.
from .models import *
from .forms import *
... | |
"""
Routines to load a corpus and perform the necessary pre processing on the audio files and labels.
Contains helper methods to load audio files, too.
"""
import csv
import os
import random
import numpy as np
import python_speech_features as psf
import tensorflow as tf
from scipy.io import wavfile
from asr.dataset.... | |
<reponame>sthagen/thombashi-pytablewriter
"""
.. codeauthor:: <NAME> <<EMAIL>>
"""
import abc
import copy
import math
import warnings
from typing import Any, Dict, List, Mapping, Optional, Sequence, Union, cast
import typepy
from dataproperty import (
ColumnDataProperty,
DataProperty,
DataPropertyExtractor,
Forma... | |
from .BaseStep import BaseStep
from ..data.Posts import Posts
import tomotopy as tp
import pandas as pd
import numpy as np
import json
import csv
import random
import statistics
from collections import Iterable
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from mat... | |
ensure_trailing_sep(start, sep)
if path.startswith(start_with_sep):
return path[len(start_with_sep) :]
raise ValueError(path, start)
def which(cmd):
which_cmd = "where" if get_platform() == "Windows" else "which"
devnull = open(os.devnull, "w")
try:
out = subprocess.check_output([which_cmd, cmd], stderr=devnul... | |
"oso goiz"],
"arratsaldea": ["arratsa", "bazkalostea", "arratsalde", "arrats"],
"gaua": ["iluntzea", "berandu", "gau", "gaba"]}
for syn in synonyms:
for word in synonyms[syn]:
s = s.replace(" " + word + " ", " " + syn + " ")
# relevant plurals
wordlist = ["goizak", "arratsaldeak", "gauak", "egunak", "asteak",
"... | |
"""
Unit tests for EDD's REST API.
Note that tests here purposefully hard-code simple object serialization that's
also coded seperately in EDD's REST API. This should help to detect when REST
API code changes in EDD accidentally affect client code.
"""
import codecs
import csv
import logging
from django.contrib.auth... | |
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import json
import shlex
import unittest.mock
from contextlib import contextmanager
from enum import Enum
from functools import partial
from textwrap im... | |
"""
qzone.items
~~~~~~~~~~~
This module implements the items for qzone scraping.
:copyright: (c) 2017 by <NAME>.
:date: 2017/10/27.
:license: MIT License, see LICENSE.txt for more details.
"""
from lib.basis import SocialMediaItem
class QzoneItem(SocialMediaItem):
pass
class QzoneUserItem(QzoneItem):
def __init... | |
# Copyright 2021 The Kubeflow 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | |
<reponame>zhjpqq/scaledensenet
# -*- coding: utf-8 -*-
__author__ = 'ooo'
__date__ = '2019/6/9 12:17'
"""
Multi-Resolution Net 2019-6-20 20:58
"""
from collections import OrderedDict
import math
import torch
from torch import nn
from torch.nn import functional as F
from xmodules.classifier import AdaPoolView, ReturnX
... | |
import os
import requests
import time
import json
import io
import numpy as np
import pandas as pd
import paavo_queries as paavo_queries
from sklearn.linear_model import LinearRegression
import statsmodels.api as sm
## NOTE: Table 9_koko access is forbidden from the API for some reasons.
# url to the API... | |
relations of the form
# sin(x + y) - sin(x)*cos(y) - sin(y)*cos(x), etc. Geometric primality is
# preserved by the same argument as before.
def parse_hints(hints):
"""Split hints into (n, funcs, iterables, gens)."""
n = 1
funcs, iterables, gens = [], [], []
for e in hints:
if isinstance(e, (SYMPY_INTS, Integer... | |
accept unknown kwargs
expected_kwargs = [
"retry_strategy",
"if_match"
]
extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs]
if extra_kwargs:
raise ValueError(
"remove_user_from_group got unknown kwargs: {!r}".format(extra_kwargs))
path_params = {
"userGroupMembershipId": us... | |
<reponame>mcmasterg/symbiflow-arch-defs<filename>utils/lib/rr_graph/channel.py
#!/usr/bin/env python3
import enum
import io
from collections import namedtuple
from . import Pos
from . import Size
from . import static_property
from ..asserts import assert_type
from ..asserts import assert_len_eq
class ChannelNotStra... | |
with pytest.raises(RSENotFound):
mgr.get_rse_info(rse="TheOnethatshouldnotbehere", **self.vo)
def test_get_protocols_operations(self):
""" RSE (CLIENTS): get protocols for operations of rse."""
protocol_rse = rse_name_generator()
self.client.add_rse(protocol_rse)
protocols = [{'scheme': 'MOCK_READ_WRITE_DELETE',... | |
]
[0. 2.5 5. ]
[0. 2.5 5. ]]
>>> print(north)
[[ 0. 0. 0. ]
[ 2.5 2.5 2.5]
[ 5. 5. 5. ]
[ 7.5 7.5 7.5]
[10. 10. 10. ]]
The spacing can be different for northing and easting, respectively:
>>> east, north = grid_coordinates(region=(-5, 1, 0, 10), spacing=(2.5, 1))
>>> print(east.shape, north.shape)
(5, 7) ... | |
"filename" + ".fits" + recipe.inputdir.upper() (including wildcards)
:param recipe: DrsRecipe instance
:param filename: string, the filename to test
:return cond: bool, if True file is valid, if False file is not valid
:return filelist: list of strings, list of files found
:return error: list of strings, if ther... | |
+= self.copy_from_reg_to_reg(destination=dividend,
source=src)
# mov eax -> edx
src = ProcessorRegister.accumulator
dest = ProcessorRegister.data
value += self.copy_from_reg_to_reg(destination=dest,
source=src)
# shift edx by 31 -> contains the highest bits of the dividend,
# eax the lowest 31 bits
value += ... | |
A value indicating whether an existing NIC is allowed to be reused
during failover subject to availability.
:type reuse_existing_nic: bool
:param tfo_recovery_nic_name: The name of the NIC to be used when creating target NICs in TFO.
:type tfo_recovery_nic_name: str
:param tfo_recovery_nic_resource_group_name: The... | |
<filename>methtuple/funcs.py<gh_stars>1-10
from __future__ import print_function
from .mtuple import *
import re
import csv
import operator
import sys
import itertools
#### Function definitions ####
def make_ignores_list(ic):
"""Make a list from a string of read positions that are to be ignored. Input should be 1-ba... | |
<filename>yinyang/src/parsing/SMTLIBv2Visitor.py
# MIT License
#
# Copyright (c) [2020 - 2021] The yinyang authors
#
# 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, inclu... | |
name.
Args:
file_name: file name for checkpoint
Returns:
None
"""
def _cast(t: torch.Tensor):
if t.dtype == torch.float16:
return t.to(dtype=torch.float32)
else:
return t
checkpoint = {
"state_dict": {
k: _cast(v) for k, v in self.agent.state_dict().items()
},
# FIXME optim state, should I cast it?
"o... | |
# -*- coding: utf-8 -*-
# Copyright 2009-2017 Yelp and Contributors
# Copyright 2018-2019 Yelp
# Copyright 2020 Affirm, Inc.
#
# 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.apa... | |
arrow keys to move.']
while self.opening_scene == True: # while opening scene is True display text and background
self.display.window.blit(Boundary.back_ground, (0,0)) # display background
self.title_text = self.fonts[0].render(self.titles[0], 1, self.color)
self.title_text2 = self.fonts[0].render(self.titles[1], ... | |
= reference_round_df.groupby('barcode_reference_dot_id')
ref_selected_df_no_duplicates = reference_round_df
for brdi, grp in barcoded_round_grouped:
barcode = np.zeros([barcode_length],dtype=np.int8)
barcode[grp.round_num.values.astype(np.int8)-1] = 1
#hamming_dist, index_gene = nn_sklearn.kneighbors(barcode.resh... | |
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json', 'application/x-www-form-urlencoded', 'application/xml', 'text/xml'])
# Authentication setting
auth_settings = ['access_token']
return self.api_client.call_api(resource_path, 'GET',
path... | |
= ['%s=%r' % (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)
all_structs.append(set_silent_use... | |
import os
import requests
MB_PASSWORD = os.getenv("<PASSWORD>")
MB_USERNAME = os.getenv("MB_USERNAME")
MB_DOMAIN = os.getenv("MB_DOMAIN")
MB_BASIC_AUTH_USERNAME = os.getenv("MB_BASIC_AUTH_USERNAME")
MB_BASIC_AUTH_PASSWORD = os.getenv("MB_BASIC_AUTH_PASSWORD")
class Metabase_API():
def __init__(self, domain=MB_DOMA... | |
"""
FindRepoTask
--------------------------------------------------
Run tool to find repos that should be taken down
1. Tool should group repos by owner, if one owner has multiple repos in violation
2. Newly found repos are tagged as “new”
"""
from .BaseTask import BaseTask
from takedown.client.GitHub import GitHubC... | |
# coding: utf-8
import logging
import requests
import mimetypes
from io import BytesIO
from urllib.parse import urlparse
from datetime import datetime, timedelta
from collections import OrderedDict
from flask_babelex import gettext as _
from flask import (
render_template,
abort,
current_app,
request,
session,
r... | |
colg.aggregate(how, _level=(_level or 0) + 1)
def _agg_2dim(name, how):
"""
aggregate a 2-dim with how
"""
colg = self._gotitem(self._selection, ndim=2,
subset=obj)
return colg.aggregate(how, _level=None)
def _agg(arg, func):
"""
run the aggregations over the arg with func
return an OrderedDict
"""
resul... | |
known differences found: 2"
in stdout.getvalue()
)
assert (
"Number of columns compared with all values completely equal: 0"
in stdout.getvalue()
)
def test_column_comparison_outputs_number_of_columns_with_differences_for_custom_known_diffs(
comparison_kd2,
):
stdout = io.StringIO()
comparison_kd2.report(fi... | |
<gh_stars>0
import gc
import os
from itertools import product
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scanpy as sc
import scipy.stats as sts
from tqdm.notebook import tqdm
import triku as tk
from triku.tl._triku_functions import subtract_median
from skle... | |
n n n n n n n n n n n 13 60
38 X monitor_control g 2 1986 semidetached n n h n n n n n n h n h h h n 90 444
39 X monitor_control g 2 1986 semidetached n n h n n n n n n n n n n n n 8 42
40 X monitor_control g 2 1986 semidetached n n h h n n n n n n n n n n n 16 114
41 hst datacapture g 2 1980 semidetached n h h vh h l ... | |
import warnings
import numbers
import numpy as np
import geopandas as gpd
from sklearn.cluster import MiniBatchKMeans
from .base_classes import BaseSpatialCV
from .grid_builder import construct_blocks, assign_pt_to_grid
from .utils import geometry_to_2d, convert_geodataframe, load_custom_polygon
__all__ = [
"HBLOCK"... | |
<reponame>akutta/hercules
#!/usr/bin/env python3
import argparse
from datetime import datetime, timedelta
from importlib import import_module
import io
import json
import os
import re
import shutil
import sys
import tempfile
import threading
import time
import warnings
try:
from clint.textui import progress
except Im... | |
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from enum import Enum
import re
import os
f... | |
+ config['content_type']
base_field_override_response = issue_request(config, 'GET', base_field_override_url, headers)
if base_field_override_response.status_code == 200:
field_config = json.loads(base_field_override_response.text)
for item in field_config['data']:
field_name = item['attributes']['field_name']
re... | |
else 75,
nameScale=0.8 if isFirst else 1.0,
flatness=0.0 if isFirst else 1.0,
shadow=0.5 if isFirst else 1.0,
showDeath=True if isFirst else False,
showLives=False))
x += xOffs * (0.8 if isFirst else 0.56)
isFirst = False
testLives += 1
# non-solo mode
else:
for team in self.teams:
if team.getID() == 0:
x ... | |
<reponame>nukui-s/mlens
"""ML-ENSEMBLE
:author: <NAME>
:copyright: 2017-2018
:licence: MIT
Blend Ensemble class. Fully integrable with Scikit-learn.
"""
from __future__ import division
from .base import BaseEnsemble
from ..index import BlendIndex, FullIndex
class BlendEnsemble(BaseEnsemble):
r"""Blend Ensemble ... | |
<filename>dbca/dbca_splitter.py
from typing import List, Tuple
import logging
import numpy as np
from tqdm import tqdm
import time
import json
from pathlib import Path
import pandas as pd
import matplotlib.pyplot as plt
from dbca.sample import Sample
from dbca.sample_set import SampleSet
from dbca.full_sample_set imp... | |
name_='MyDigiPassEidAddress')
if self.hasContent_():
outfile.write('>%s' % (eol_, ))
self.exportChildren(outfile, level + 1, namespaceprefix_='', name_='MyDigiPassEidAddress', pretty_print=pretty_print)
outfile.write('</%s%s>%s' % (namespaceprefix_, name_, eol_))
else:
outfile.write('/>%s' % (eol_, ))
def export... | |
m21, Tam, Tp, Ts, Q = params
"""
Model with split, ancient migration, heterogenous effective population size (with 2 classes of loci shared by the two populations = Hill-Robertson effects)
nu1: Size of population 1 after split.
nu2: Size of population 2 after split.
b1: Population growth coefficient of populatio... | |
<reponame>cds-snc/notifier-api
import datetime
import uuid
import pytest
from boto3.exceptions import Boto3Error
from freezegun import freeze_time
from notifications_utils.recipients import (
validate_and_format_email_address,
validate_and_format_phone_number,
)
from sqlalchemy.exc import SQLAlchemyError
from app.m... | |
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from builtins import str
from builtins import range
from builtins import object
from copy import copy, deepcopy
import numpy as np
from scipy.optimize import newton
from HARK import AgentType, Solution, NullFunc... | |
2]))
cases[-1]['casedir'] = 'design-48-32a'
cases.append(defaultCase(48, 3, 7, [4, 3, 2, 2, 2, 2, 2]))
cases.append(
defaultCase(48, 3, 14, [4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]))
cases[-1]['casedir'] = 'design-48-42a-t3'
cases.append(defaultCase(48, 3, 25, [
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2... | |
import tensorflow as tf
import numpy as np
import datetime
import pickle
from music_parser import *
def get_time():
return datetime.datetime.now().strftime("%m-%d--%H-%M")
def get_batch(songs_parsed, one_hot_length, num_keys, batch_size, num_timesteps):
# create test data
# loop = np.array([
# [0, 0, 1, 0, 0, 0,... | |
<filename>NitroFE/time_based_features/moving_average_features/moving_average_features.py
import pandas as pd
import numpy as np
from typing import Union, Callable
from NitroFE.time_based_features.weighted_window_features.weighted_window_features import (
weighted_window_features,
)
from NitroFE.time_based_feat... | |
#!/usr/bin/env python3
""" Base class for Face Detector plugins
Plugins should inherit from this class
See the override methods for which methods are
required.
For each source frame, the plugin must pass a dict to finalize containing:
{"filename": <filename of source frame>,
"image": <source image>,
"detected_... | |
do nothing
else:
if not common.isNum(value):
raise MeterException('weight values must be numbers')
try:
totalRatio = self._numerator / self._denominator
except TypeError:
raise MeterException(
'Something wrong with the type of '
+ 'this numerator %s %s or this denominator %s %s' %
(self._numerator, type(self.... | |
import numpy as np
import pandas as pd
import os
def generate_x(x_file):
with open(x_file) as f:
container = f.readlines()
result = []
for line in container:
tmp1 = line.strip()
tmp2 = tmp1.replace(' ', ' ')
# print tmp2
tmp_ary = map(float, tmp2.split(' '))
# nan_count = sum(math.isnan(x) for x in tmp_ary)
... | |
<gh_stars>0
#!/usr/bin/env python
# Copyright (c) 2017,2018, F5 Networks, Inc.
#
# 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 requir... | |
<filename>train.py
import argparse
import os
import shutil
import time
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvision.datasets a... | |
<filename>covid19_stats/engine/viz.py
import os, sys, numpy, titlecase, time, pandas, zipfile, mutagen.mp4
import subprocess, tempfile, shutil, datetime, logging, copy
import pathos.multiprocessing as multiprocessing
from itertools import chain
from multiprocessing import Value, Manager
import cartopy.feature as cfeatu... | |
False
**units**\: byte
"""
_prefix = 'pbr-vservice-mgr-oper'
_revision = '2017-05-01'
def __init__(self):
if sys.version_info > (3,):
super().__init__()
else:
super(GlobalServiceFunctionChaining.ServiceFunction.SfNames.SfName.Data.Sfp.Term, self).__init__()
self.yang_name = "term"
self.yang_parent... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.