input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<filename>corehq/apps/reminders/models.py
import pytz
from pytz import timezone
from datetime import timedelta, datetime, date, time
import re
from couchdbkit.ext.django.schema import *
from casexml.apps.case.models import CommCareCase, CommCareCaseGroup
from corehq.apps.sms.models import CommConnectCase
from corehq.ap... | |
<filename>alphaconf/__init__.py
import contextlib
import contextvars
import logging
import os
import re
import sys
import uuid
from typing import Any, Dict, Iterable, List, Union
from omegaconf import DictConfig, MissingMandatoryValue, OmegaConf
from . import arg_parser
__doc__ = """AlphaConf
Based on omegaconf, pr... | |
def __lshift__(self, added_code):
""" implicit code insertion through << operator """
indented_code = self.reindent(added_code)
return self.append_code(indented_code)
def inc_level(self):
""" increase indentation level """
self.tablevel += 1
self.expanded_code += CodeObject.tab
def dec_level(self):
""" decre... | |
# -*- coding: utf-8 -*-
import traceback, logging
from os import path as opath
from functools import partial
import csv
import codecs
from datetime import datetime, timedelta
from .db import db_context, get_db
from . import utils
from . import settings
#from .stats import get_statistic # api xinterface @todo
from .lo... | |
pass
if time_range[0] is None:
# first partition of sequence
DS_t_numtype = traj.indepdomain.type
if isinputcts(traj):
DS_t_typestr = 'continuous'
# continuous time must be float
if not compareNumTypes(DS_t_numtype, _all_float):
raise TypeError('continuous time inconsistent with '
'non-float type')
else:
DS_... | |
r = s.post(url, data=data)
if r.status_code == 401:
r = self.authenticate(data, r, url)
if r.status_code == 201:
constants.MSC_LOGIN_CACHE[self.mscolab_server_url] = (username, password)
if r.status_code == 201:
self.error_dialog = QtWidgets.QErrorMessage()
self.error_dialog.showMessage('You are registered, you ... | |
"""
Phase vocoder.
The phase vocoder is a digital signal processing technique of potentially
great musical significance. It can be used to perform very high fidelity
time scaling, pitch transposition, and myriad other modifications of sounds.
"""
from __future__ import absolute_import
"""
Copyright 2009-2015 <NAME>... | |
"""ResNet v1, v2, and segmentation models for Keras.
# Reference
- [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385)
- [Identity Mappings in Deep Residual Networks](https://arxiv.org/abs/1603.05027)
Reference material for extended functionality:
- [ResNeXt](https://arxiv.org/abs/1611.... | |
<reponame>MrMeeb/qbit_manage
import logging, os, sys
from qbittorrentapi import Client, Version, LoginFailed, APIConnectionError, NotFound404Error, Conflict409Error
from modules import util
from modules.util import Failed, print_line, print_multiline, separator, list_in_text
from datetime import timedelta
from collecti... | |
Type for Variable or Meter 11"+"\n")
lines.append(" WaterSystems:DistrictCooling,!- Variable or Meter 12 Name"+"\n")
lines.append(" ValueWhenMaximumOrMinimum, !- Aggregation Type for Variable or Meter 12"+"\n")
lines.append(" Cogeneration:DistrictCooling,!- Variable or Meter 13 Name"+"\n")
lines.append(" ValueWhenM... | |
"""Script defining SMALMesh, an object capable of rendering a mesh version of the SMAL Model, for optimising the fit to other, existing meshes.
With modifications now to work with:
- newest SMAL Model
- Newly define scale factor parameters"""
from absl import flags
from pytorch3d.structures import Meshes
import sys, ... | |
<gh_stars>1-10
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2016, <NAME> <<EMAIL>>
#
# Permission to use, copy, modify, and/or distribute this software for any purpose
# with or without fee is hereby granted, provided that the above copyright notice
# and this permission notice appear in all copies.
#
# TH... | |
u'z', u'g'] ,
u'㨝' : [u'x'] ,
u'缟' : [u'g'] ,
u'䢦' : [u's'] ,
u'趨' : [u'q', u'c'] ,
u'圯' : [u'y'] ,
u'頱' : [u'l'] ,
u'斸' : [u'z'] ,
u'伿' : [u'y'] ,
u'灁' : [u'y'] ,
u'巈' : [u'j'] ,
u'黊' : [u'x'] ,
u'桑' : [u's'] ,
u'㗘' : [u'b', u'f'] ,
u'盚' : [u'q'] ,
u'蕣' : [u's'] ,
u'滪' : [u'y'] ,
u'鏬' : [u'x'] ,
u'㡱' : [u'j'] ,
u'絳' :... | |
' ' +\
self.x_field('COMMODITY===================',comm_size) + ' ' +\
self.x_field('CURRENT', 10)
#get the extract data
data = ('',)
sql = 'select car.railroad, car.car, place.station, place.code, ' +\
'warehouse.industry, warehouse.destination, warehouse.commodity, commodity.name, car.train, car.station... | |
def run(self) -> None:
await self.manager.run_service(self._body_syncer)
class BodyChainGapSyncer(Service):
"""
A service to sync historical blocks without executing them. This service is meant to be run
in tandem with other operations that sync the state.
"""
_idle_time = BLOCK_BACKFILL_IDLE_TIME
_starting_... | |
from __future__ import print_function
import json
import optparse
import sqlite3
import sys
version = "0.4.0"
gene_count = 0
class Sequence(object):
def __init__(self, header, sequence_parts):
self.header = header
self.sequence_parts = sequence_parts
self._sequence = None
@property
def sequence(self):
if se... | |
#!/usr/bin/python3.8
# -*- coding: utf-8 -*-
# please adjust these two lines if necessary
# multizaehlen.py
# (C) <NAME> 2017-2021
# Programm zum Auswerten der Auszählungen von Textdateien
# =======================================================
# Pickle-Daten (erzeugt durch zaehlen.py) werden ausgewertet und zusam... | |
<filename>code/python/ExchangeDataFeedSnapshotAPISymbolList/v1/fds/sdk/ExchangeDataFeedSnapshotAPISymbolList/model/fields.py<gh_stars>1-10
"""
Exchange DataFeed Snapshot
FactSet’s Exchange DataFeed Snapshot API provides cost-effective access to real-time and delayed global exchange data. Proprietary technology norma... | |
Optional[int] = None,
origin_host_header: Optional[str] = None,
priority: Optional[int] = None,
weight: Optional[int] = None,
shared_private_link_resource: Optional[object] = None,
enabled_state: Optional[Union[str, "EnabledState"]] = None,
**kwargs
):
super(AFDOriginProperties, self).__init__(azure_origin=azur... | |
of the main branch by means of a 1-by-1 convolution,
so that the output tensors of the two branches have the same dimensions. Afterwards the output
tensors of the two branches are added.
Arguments:
input_tensor (4D tensor): The 4D input tensor of the shape (batch, heigh, width, channels).
kernel_size (int): The s... | |
col=1), Player.black): 6893650162163055849,
(Point(row=18, col=12), Player.black): 2623660912777886370,
(Point(row=13, col=17), Player.black): 2459600351157906810,
(Point(row=1, col=19), Player.black): 8151912673468739038,
(Point(row=9, col=3), Player.white): 194307367481754028,
(Point(row=16, col=3), Player.black... | |
<filename>bu.py<gh_stars>0
# std:
import os;
import time;
import json;
import random;
import functools;
# pit-ext:
import bottle;
# pip-int:
import dotsi;
# loc:
import hashUp;
import utils;
request = bottle.request;
response = bottle.response;
redirect = bottle.redirect;
staticFile = bottle.static_file;
#########... | |
<gh_stars>10-100
"""
Implementation slightly modified from [1]_.
References:
..[1] https://github.com/lukemelas/EfficientNet-PyTorch
"""
import torch
from torch import nn
from torch.nn import functional as F
from netharn import layers
import re
import math
import collections
from functools import partial
from torch... | |
<reponame>zenwerk/Pyxif
"""EXIF is a set of several IFDs.
Oth IFD can include "Make", "Model" and more...
Exif IFD can include "ExposureTime", "ISOSpeed" and more...
GPS IFD can include GPS information.
Pass dict(s), that shows several IFD, to "dump" function.
exifbytes = pyxif.dump(0th_dict, exif_dict, gps_dict) # se... | |
#!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
Core iPOPO implementation
:author: <NAME>
:copyright: Copyright 2016, <NAME>
:license: Apache License 2.0
:version: 0.6.4
..
Copyright 2016 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in complian... | |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... | |
<reponame>Fournierp/FPL
import pandas as pd
import numpy as np
import os
import json
def get_raw_data(rank, path='data/fpl_official/2020-21/season/raw/'):
f = os.path.join(path, f"managers_{rank}.json")
chips = pd.DataFrame(
list(pd.read_json(f, orient='index')['chips']),
columns=['wildcard_1', 'freehit', 'bboos... | |
#!/usr/bin/python3
"""
poly MBA generation:
poly = linear * linear * linear ...
add 0-equality:
0-equality = 0 * linear
= (part-term) * (-1*linear)
poly = poly + 0-equality
"""
import argparse
import numpy as np
import os
import random
import re
import sys
sys.setrecursionlimit(30000)
sys.path.append("../tools")
... | |
fp)
fp.write("end Material\n\n")
MapToTypes = {
'use_map_alpha' : 'ALPHA',
'use_map_ambient' : 'AMBIENT',
'use_map_color_diffuse' : 'COLOR',
'use_map_color_emission' : 'COLOR_EMISSION',
'use_map_color_reflection' : 'COLOR_REFLECTION',
'use_map_color_spec' : 'COLOR_SPEC',
'use_map_color_transmission' ... | |
import unittest
import pandas as pd
import numpy as np
from borf.get_orfs import read_fasta
from borf.get_orfs import find_next_stop
from borf.get_orfs import find_max_orf_index
from borf.get_orfs import orf_start_stop_from_aa
from borf.get_orfs import find_longest_orfs
from borf.get_orfs import replace_last_stop
from... | |
3, 4])
self._assert_insert_conversion(obj, False, exp, np.int64)
# int + object -> object
exp = pd.Index([1, 'x', 2, 3, 4])
self._assert_insert_conversion(obj, 'x', exp, np.object)
def test_insert_index_float64(self):
obj = pd.Float64Index([1., 2., 3., 4.])
self.assertEqual(obj.dtype, np.float64)
# float + i... | |
<gh_stars>10-100
"""
Set of classes for dealing with a STAR files (Relion's format)
# Author: <NAME> (Max Planck Institute for Biochemistry)
# Date: 1.06.16
"""
__author__ = '<NAME>'
import gc
import sys
import csv
import copy
import pyto
import errno
from pyseg.globals import *
from pyseg import disperse_io
import ... | |
<filename>experiments/data_source.py
"""
Loading and preparing data for experiments. Some of the datasets are generated using the Matlab
code (see data/matlab_code_data), in order to ensure they are the same training and test points
that were used in the previous paper (Nguyen and Bonilla NIPS (2014)).
The Matlab code ... | |
# -*- coding: utf-8 -*-
import sys, logging
import numpy as np
from math import ceil
from gseapy.stats import multiple_testing_correction
from joblib import delayed, Parallel
def enrichment_score(gene_list, correl_vector, gene_set, weighted_score_type=1,
nperm=1000, seed=None, single=False, scale=False):
"""This ... | |
<gh_stars>100-1000
from libsaas.services import base
from .resource import BitlyResource
class User(BitlyResource):
path = 'user'
@base.apimethod
def info(self, login=None, full_name=None):
"""
Return or update information about a user.
:var login: the bitly login of the user whose info to look up.
If not g... | |
contain a dot.
assert '.' not in produce_method, produce_method
if produce_method not in produce_methods:
produce_methods.append(produce_method)
if self.phase == metadata_base.PipelineRunPhase.FIT:
fit_multi_produce_arguments = self._filter_arguments(step.primitive, 'fit_multi_produce', dict(arguments, produce_me... | |
<reponame>ionos-cloud/ionos-cloud-sdk-python<filename>ionoscloud/api/network_load_balancers_api.py
from __future__ import absolute_import
import re # noqa: F401
import six
from ionoscloud.api_client import ApiClient
from ionoscloud.exceptions import ( # noqa: F401
ApiTypeError,
ApiValueError
)
class NetworkLoadBa... | |
# Copyright (c) Microsoft Corporation
# Copyright (c) Tsinghua University
# Copyright (c) Peng Cheng Laboratory
# All rights reserved.
#
# MIT License
#
# 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 S... | |
requirements.
ResourceRequirement keys that are not present in the dict are not modified.
Args:
name: The name of the resource to set the requirements of (e.g., "cpu" or "memory").
requirements: A dict mapping requirements to target values (e.g., `{ResourceRequirement.request: '500m', ResourceRequirement.limit: '2... | |
<gh_stars>1-10
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pytest
import numpy as np
import pandas as pd
import ray
import ray.dataframe as rdf
@pytest.fixture
def ray_df_equals_pandas(ray_df, pandas_df):
return rdf.to_pandas(ray_df).sort_index... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 15 13:52:36 2018
@author: BallBlueMeercat
"""
import numpy as np
from datasim import magn
#def lnlike(theta, data, sigma, firstderivs_key, ndim):
# '''
# Finding matter density m, interaction gamma.
# '''
# mag = data['mag']
#
# params = {}
# if ... | |
import os
import subprocess
from subprocess import PIPE
from multiprocessing import Pool, cpu_count
import shutil
import re
import pandas as pd
from multiprocessing import Lock
import hashlib
import math
import xarray as xr
import numpy as np
import time
import pickle
class SpiceAnalysis():
def __init__(self):
pass
... | |
# coding: utf-8
"""
3Di API
3Di simulation API (latest stable version: v3) Framework release: 2.9.0 3Di core release: 2.2.2 deployed on: 11:01AM (UTC) on January 11, 2022 # noqa: E501
The version of the OpenAPI document: v3
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
"""
import logging
impor... | |
== state['bots']
assert test_first_round['food'] == list(state['food'][0]) + list(state['food'][1])
assert state['score'] == [0, 0]
for i in range(4):
state = game.play_turn(state)
test_second_round = layout.parse_layout(
""" ######
# . #
#. #
# #
######
######
# 0 #
#21 #
# 3#
###### """)
assert test... | |
+ 0.00793062*m.x249 + 0.00225214*m.x250 + 0.00173381*m.x251
+ 0.0025893*m.x252 + 0.00146414*m.x253 + 0.00619079*m.x254 - 0.000522178*m.x255
+ 0.00121952*m.x256 + 0.000349511*m.x257 + 0.000972283*m.x258 + 0.00145449*m.x259
- 0.000489457*m.x260 + 2.38348E-5*m.x261 + 0.000570035*m.x262 + 0.00228208*m.x263
+ 0.00212064... | |
<filename>src/smexperiments/tracker.py<gh_stars>1-10
# Copyright Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com... | |
<gh_stars>0
#!/usr/bin/env python
from optparse import OptionParser, OptionGroup, SUPPRESS_HELP
import os
import sys
from mapdamage.version import __version__
from mapdamage.rscript import check_R_lib
def file_exist(filename):
if os.path.exists(filename) and not os.path.isdir(filename):
return True
elif filename ... | |
<filename>tests/blackbox/challenge/test_bb_challenge.py
#!/usr/bin/env python3
'''Test scopes with custom rules'''
# ------------------------------------------------------------------------------
# Imports
# ------------------------------------------------------------------------------
import subprocess
import os
impor... | |
as writer:
for Ev, Egrp in sgrp.groupby("E_RHE"):
# sheet_name = Ev
EmV = f"{1E3*Ev:.0f}"
Egrp[["Frequency(Hz)"] + cols].to_excel(
writer, sheet_name=EmV
)
# === plotting
fig, ax = plt.subplots()
Egrp.plot(
x=cols[0],
y=cols[1],
kind="scatter",
ax=ax,
label=cols[1],
)
Egrp.plot(x=cols[2]... | |
"""
Compare with the previous dialog_reader, this dialog_reader removes the token type id
but add padding token and other corresponding special tokens instead.
"""
import os
import json
import pickle
import random
import pprint
import logging
import numpy as np
from tqdm import tqdm
from operator import itemgetter
fro... | |
<gh_stars>0
from _learning import *
from _learning import _lunarySharedFeatFunctionsGen,_lpottsFunctionsGen
import numpy
import struct
from opengm import index_type,value_type, label_type, graphicalModel,gridVis
from opengm import configuration as opengmConfig, LUnaryFunction
from opengm import to_native_boost_python_e... | |
dtype=dtype)
# We are testing correct canonicalization behavior here, so we turn off the
# permissive canonicalization logic in the test harness.
self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker,
canonicalize_dtypes=False)
self._CompileAndCheck(jnp_fun, args_maker)
def testArrayUnsupportedDtypeError(self):
... | |
<filename>airflow/configuration.py
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0... | |
<filename>_build/jupyter_execute/01_linda_soln.py<gh_stars>0
# Bite Size Bayes
Copyright 2020 <NAME>
License: [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](https://creativecommons.org/licenses/by-nc-sa/4.0/)
# Load utils.py
import os
if not os.path.exists('utils.py'):
!wget https://gi... | |
enumeration that specifies
whether the search operation should include only the current directory or
should include all subdirectories.The default value is
System.IO.SearchOption.TopDirectoryOnly.
Returns: An enumerable collection of directory names in the directory specified by path
and that mat... | |
<gh_stars>1000+
import logging
import uuid
from typing import Any
from typing import Dict
from typing import Generator
from typing import List
from typing import Tuple
import neo4j
from azure.core.exceptions import ClientAuthenticationError
from azure.core.exceptions import HttpResponseError
from azure.core.exceptions... | |
with open(filename[0], "w") as log_file:
log_file.write("Indicator Variables\n===========================\n")
for key, val in self.rev_id_conn.iteritems():
log_file.write(val+" = "+key+"\n")
log_file.write("===========================\n\nComposite Index Formula"
"\n===========================\nCI('Region','Year')... | |
group_lens = self.wrapper.grouper.get_group_lens(group_by=group_by)
asset_value = nb.asset_value_grouped_nb(asset_value, group_lens)
else:
asset_value = nb.asset_value_nb(close, assets)
return self.wrapper.wrap(asset_value, group_by=group_by, **merge_dicts({}, wrap_kwargs))
@cached_method
def gross_exposure(self... | |
# Matrix archiver script.
# Copyright (c) <NAME>, 2020. All rights reserved.
# Released under the MIT License (See LICENSE)
# Some portions (namely event retrieval as a batching generator) are taken
# from the MIT Licensed "matrix-archive" project by <NAME>.
import os
import sys
import argparse
import json
import sqli... | |
<reponame>lverdier1/CEASIOMpy
"""
CEASIOMpy: Conceptual Aircraft Design Software
Developed by CFS ENGINEERING, 1015 Lausanne, Switzerland
This programm stors all function needed for stability analysis (dynamic and static)
Python version: >=3.6
| Author: <NAME>
| Creation: 2020-02-24
| Last modifiction: 2020-03-24 (... | |
import distutils.dir_util #for multiple file copy.
import getpass #for username.
import glob #for globbing paths.
import os #fs stat and path check.
import re #regex.
import shutil #move and copy files.
import string #for string replacal.
import StringIO #for redirecting stdout and stderr.
import subprocess #run a subp... | |
<gh_stars>1-10
# -*- coding: utf-8 -*-
from __future__ import division
import collections
import numpy as np
from stingray import Lightcurve
from stingray.events import EventList
import stingray.utils as utils
__all__ = ['Covariancespectrum', 'AveragedCovariancespectrum']
class Covariancespectrum(object):
"""
Co... | |
"v6.0.11": True
}
},
{
"value": "dialup",
"revisions": {
"v6.0.0": True,
"v7.0.0": True,
"v6.0.5": True,
"v6.4.4": True,
"v7.0.1": True,
"v6.4.0": True,
"v6.4.1": True,
"v6.2.0": True,
"v6.2.3": True,
"v6.2.5": True,
"v6.2.7": True,
"v6.0.11": True
}
},
{
"value": "peer",
"revisions": {
"v6.0.0":... | |
import json
import math
from typing import Union, Optional, List
from .core import pack, data as _data, Data, Ref, Expando, expando_to_dict
# TODO add formal parameters for shape functions, including presentation attributes:
# https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/Presentation
def stage(**kwargs... | |
<filename>ChrisFuncs/ChrisFuncs.py<gh_stars>0
# Import smorgasbord
import pdb
import pdb
"""from IPython import get_ipython
get_ipython().run_line_magic('pdb','on')"""
import sys
import os
#sys.path.append( os.path.split( os.path.realpath(__file__) )[:-1][0] )
#sys.path.append( os.path.split( os.path.split( os.path.rea... | |
from datetime import time, date, datetime, timedelta
import pytest
import hallo.modules.dailys.dailys_field
from hallo.events import EventMessage, RawDataTelegram, EventMinute
from hallo.modules.dailys.field_mood import DailysMoodField, MoodTime
from hallo.test.modules.dailys.dailys_spreadsheet_mock import DailysSpre... | |
#
#
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 Google 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:
#
# 1. Redistributions of source code must retain the above ... | |
-2): (0, 1),
(9, 33, 3, -1): (0, 1),
(9, 33, 3, 0): (0, 1),
(9, 33, 3, 1): (0, 1),
(9, 33, 3, 2): (0, 1),
(9, 33, 3, 3): (0, 1),
(9, 33, 3, 4): (0, 1),
(9, 33, 3, 5): (0, 1),
(9, 33, 4, -5): (0, 1),
(9, 33, 4, -4): (0, 0),
(9, 33, 4, -3): (-1, -1),
(9, 33, 4, -2): (0, 1),
(9, 33, 4, -1): (0, 1),
(9, 33, 4,... | |
lock in locks:
loc = self.route.index(origin)
for r in self.route[loc:]:
if 'Line-up area' in self.env.FG.nodes[r].keys():
locks2 = self.env.FG.nodes[r]["Line-up area"]
for r2 in self.route[loc:]:
if 'Lock' in self.env.FG.nodes[r2].keys():
locks3 = self.env.FG.nodes[r2]["Lock"]
break
self.lock_name = []
for ... | |
#!/usr/bin/env python
##
## video.py - recoding VNC to FLV.
##
## Copyright (c) 2009-2010 by <NAME>
##
import sys, zlib, re
from struct import pack, unpack
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from flvscreen import FlvScreen
def str2clip(s):
m = re.match(r'^(\d+)... | |
72335,
-1,
82511906,
72341,
82707708,
81825990,
-1,
82773243,
82672720,
-1,
82838770,
82743422,
-1,
-64271,
82800460,
72281,
-1,
82857207,
72282,
83035380,
82806935,
72275,
-1,
82979679,
72274,
83166454,
82993253,
72277,
-1,
83110751,
72278,
83297529,
83103505,
-1,
-64264,
83265687,
... | |
import copy
import json
from collections.abc import Iterable
from falcon.testing import create_environ
from falcon import Request
from falcon import errors
import falcon
import pytest
from unittest.mock import Mock
from graceful.errors import ValidationError
from graceful.resources.base import BaseResource
from grace... | |
try:
created_at = iso8601.parse_date(created_at)
except iso8601.ParseError as exc:
log.error(str(exc))
return created_at
created_at = pytz.UTC.normalize(created_at)
return created_at
def _list_machines__postparse_machine(self, machine, node_dict):
updated = False
os_type = 'linux'
if 'windows' in str(
node... | |
#!/usr/bin/python
from __future__ import absolute_import, division, print_function
# Copyright 2019-2020 Fortinet, Inc.
#
# 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 3 of the ... | |
import gc
import os, sys
import numpy as np
import tensorflow as tf
import tensorflow.keras as keras
from tensorflow.keras.models import Model
import tensorflow.keras.layers as kl
import tensorflow.keras.models as km
import tensorflow.keras.callbacks as kc
import tensorflow.keras.backend as kb
import tensorflow.keras.r... | |
torch.save(local_rref, fname)
@dist_init
def test_remote_throw(self):
rref = rpc.remote(worker_name((self.rank + 1) % self.world_size),
raise_or_inc,
args=(torch.ones(2),))
with self.assertRaisesRegex(Exception, ".*Expected error.*"):
rref.to_here()
@dist_init
def test_non_cont_tensors(self):
if self.rank =... | |
#!/usr/bin/env python
import csv
import json
from os.path import isfile
from os.path import basename
from os.path import join as pjoin
from pprint import pprint as pp
from typing import Dict, Tuple, List, Union, Any, Optional, IO
import datagristle.common as comm
from datagristle.common import abort
import datagristl... | |
<reponame>YudinYury/Question_by_HackerRank
''' Python question by HackerRank
TODO 1: "Introduction to Regex Module"
You are given a string N.
Your task is to verify that N is a floating point number.
In this task, a valid float number must satisfy all of the following requirements:
Number can start with +, - or . symb... | |
<reponame>tdiprima/code
# Config - reads a configuration file.
#
# This module parses a configuration file using a restricted Python syntax.
# The Python tokenizer/parser is used to read the file, unwanted expressions
# are removed from the parser output before the result is compiled and
# executed. The initialised con... | |
None,
count: Optional[int] = 20,
limit: int = 20,
page_token: Optional[str] = None,
return_json: bool = False,
):
"""
Retrieve authorized user's activities.
Note:
This need you do authorize first.
Args:
parts ((str,list,tuple,set) optional):
The resource parts for activities you want to retrieve.
If not ... | |
<reponame>dylanirion/wildbook-ia
# -*- coding: utf-8 -*-
"""
Dependencies: flask, tornado
"""
import logging
from flask import current_app
from wbia.control import controller_inject
from wbia.web import appfuncs as appf
import utool as ut
from wbia.web import routes
(print, rrr, profile) = ut.inject2(__name__)
logger ... | |
empty initial angles for the circuit. modify later.
self.initial_packed_amps = []
if (strategy == 'UCCSD') and (method != 'linalg'):
# UCCSD circuit strategy preparations
self.ref_state = ref_state_preparation_circuit(
molecule,
ref_type='HF',
cq=self.custom_qubits)
if self.parametric_way:
# in the parametri... | |
<gh_stars>10-100
"""
fuzzyvault.py
This contains my attempt at creating a Python version
of pseudocode for the key recovery project.
There are three functions of interest:
gen_params, gen_secret, gen_keys
"""
# pylint: disable=no-name-in-module, invalid-name
import json
import secrets
import binascii
from typing... | |
print "Possibly,all the result are summarised as follow:"
print len(result)
for item in report:
show(item)
print
print
else:
print len(result)
for item in report:
show(item)
print
print
return;
#########################end show_status###################################
def combine (set,l,pack):
'''
o... | |
KMSEncrypted: bool = None, KMSKey: str = None, Tags: List = None) -> Dict:
"""
Creates a cached volume on a specified cached volume gateway. This operation is only supported in the cached volume gateway type.
.. note::
Cache storage must be allocated to the gateway before you can create a cached volume. Use the Add... | |
# =============================
# > Command implementations
# ============================
import atexit
import dataclasses
import json
import os
import shutil
import subprocess
import sys
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
from tempfile import Tempor... | |
= 'stcTextWidget'
self.widget = w = stc.StyledTextCtrl(parent,*args,**keys)
# Inject the leo_wrapper_class ivar.
self.widget.leo_wrapper_object = self
w.CmdKeyClearAll() # Essential so backspace is handled properly.
# w.Bind(wx.EVT_KEY_DOWN, self.onChar)
wx.EVT_KEY_DOWN(w,self.onChar)
w.Bind(stc.EVT_STC_MARG... | |
# -*- coding: utf-8 -*-
"""Copy of t5-trivia
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1DDn-D-0e57hlfCQIzIT9QVGN9K_5yFqk
<a href="https://colab.research.google.com/github/google-research/text-to-text-transfer-transformer/blob/master/notebooks/t5-tri... | |
yaml.safe_load(
subprocess.Popen(
cmd,
shell=True,
stdout=subprocess.PIPE
).communicate()[0])
if 'environment' in ndata:
env = ndata['environment']
else:
env = 'base'
if 'classes' in ndata:
if isinstance(ndata['classes'], dict):
ret[env] = list(ndata['classes'])
elif isinstance(ndata['classes'], list):
r... | |
<filename>tools/contrail/create_subcluster_environment.py<gh_stars>0
#!/usr/bin/python
import yaml, sys, getopt, json, os
from subprocess import check_output
from string import Template
CONTROL_ONLY_HOSTNAME_PREFIX='ctrlonly'
COMPUTE_HOSTNAME_PREFIX='compute'
DPDK_HOSTNAME_PREFIX='computedpdk'
SRIOV_HOSTNAME_PREFIX='... | |
"""
Implementation of the algorithm that gradually disovers the Pareto front.
"""
import os
import numpy as np
import GPy
from scipy.optimize import minimize
from pyDOE import *
import tqdm
from . import get_idx_of_observed_pareto_front
from . import ehvi_2d_func
from . import DistributedObject
from . import Paralleliz... | |
apply_pass_and_basic_check(
prog, "common::reduce_transposes"
)
self.assertEqual(
get_op_types_in_program(prev_prog),
[
"transpose",
"transpose",
"relu",
"relu",
"concat",
"transpose",
"transpose",
],
)
self.assertEqual(get_op_types_in_program(prog), ["relu", "relu", "concat"])
assert_model_is_valid(
... | |
<reponame>ma-compbio/MATCHA
from pybloom_live import BloomFilter
import multiprocessing
from torch.nn.utils.rnn import pad_sequence
import time
from tqdm import tqdm, trange
import argparse
import warnings
import random
from Modules import *
from utils import *
import datetime
cpu_num = multiprocessing.cpu_count()... | |
<reponame>tomy-0000/pytorch-ssd
import argparse
import os
import logging
import sys
import itertools
import cv2
import datetime
import torch
from torch.utils.data import DataLoader, ConcatDataset
from torch.optim.lr_scheduler import CosineAnnealingLR, MultiStepLR
from torch.utils.tensorboard import SummaryWriter
from... | |
from datetime import date, datetime, timedelta
import asyncio
import cmd
import getpass
import mmlsattendance
import os
import re
PRINT_ATTENDANCE_LIST = False
def print_subjects(SubjectDB_obj):
num_pad = len(str(len(SubjectDB_obj.subjects)))
space = ' '*num_pad + ' '*2
cat_space = space + ' '*3
for... | |
block_id):
locations = self.list_locations()
block = self.connection.request_with_orgId_api_2(
'network/publicIpBlock/%s' % block_id).object
return self._to_ip_block(block, locations)
def ex_delete_public_ip_block(self, block):
delete_node = ET.Element('removePublicIpBlock', {'xmlns': TYPES_URN})
delete_node.se... | |
not None:
self.product_instance_id = m.get('product_instance_id')
if m.get('terminal_identity') is not None:
self.terminal_identity = m.get('terminal_identity')
if m.get('biz_id') is not None:
self.biz_id = m.get('biz_id')
if m.get('data_user_identity') is not None:
self.data_user_identity = m.get('data_user_ide... | |
= []
if lump is None:
return []
pNameLen = int.from_bytes(lump.read(4), "little", signed=True)
for i in range(pNameLen):
patchesNames.append(trailingZeros(
lump.read(8).decode("ISO-8859-1").upper()))
return patchesNames
def getPicture(lump, pallete):
''' Given lump name of a picture, get that pictu... | |
from pylab import *
from matplotlib.collections import LineCollection
from matplotlib.patches import Rectangle
from numpy import nan
import math, time
import numpy as nx
import numpy as np
import flydra_core.reconstruct as reconstruct
import cgtypes # cgkit 1.x
import tables # pytables
import scipy.signal
import sci... | |
or val.lower().endswith('.asd')):
newval=""
#if no search then grab them all else only grab the matches
#seriously speeds things up if skip non-matches
if not session['searchval'] or (session['searchval'] and session['searchval'].lower()
in val.lower()):
newval=os.path.join(root,val)
#blanco match
elif sessio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.