input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<reponame>nrccua/aioradio
"""Generic functions related to working with files or the file system."""
# pylint: disable=broad-except
# pylint: disable=consider-using-enumerate
# pylint: disable=invalid-name
# pylint: disable=logging-fstring-interpolation
# pylint: disable=too-many-arguments
# pylint: disable=too-many-bo... | |
at most
a single -1 which indicates a dimension that should be
derived from the input shape.
# Returns
The new output shape with a -1 replaced with its computed value.
Raises a ValueError if the total array size of the output_shape is
different then the input_shape, or more then one unknown dimension
is specif... | |
######################################################################
######################################################################
# Copyright <NAME>, Cambridge Dialogue Systems Group, 2017 #
######################################################################
##############################################... | |
layer
d_model = long_cart_embs.shape[-1]
long_cart_padding_mask_list = padding_mask(long_cart)
long_buy_padding_mask_list = padding_mask(long_buy)
long_cart_transformer = Encoder(1, d_model, 4, 256, cfg.long_seq_len, True)
long_buy_transformer = Encoder(1, d_model, 4, 256, cfg.long_seq_len, True)
long_cart_outp... | |
<gh_stars>0
# Copyright 2015-2016 Palo Alto 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 required by applicable law ... | |
import os,shutil,sys
try:
from scenegraphUSD.Utility import queue
from scenegraphUSD import Logging
from scenegraphUSD.Setting import *
except ImportError:
## Developling envrionment
sys.path.append("/home/xukai/Git/git_repo/scenegraphUSD/python")
from scenegraphUSD.Utility import queue
from scenegraphUSD impor... | |
plt.savefig(savepath+".jpg")
def sample_data_from_total(total_data,total_label,sample_rate=0.5):
# total_data : numpy ndarray
# total_label: numpy ndarray
idx = list(range(total_data.shape[0]))
sample_len=int(len(idx) * sample_rate)
sample_idx=np.random.choice(idx,size=sample_len,replace=False)
return total_da... | |
--*
The amount of time an in-progress restore has been running, or the amount of time it took a completed restore to finish.
- **EstimatedTimeToCompletionInSeconds** *(integer) --*
The estimate of the time remaining before the restore will complete. Returns 0 for a completed restore.
- **DataTransferProgress** *(... | |
<reponame>vjFaLk/shipstation-client
list_tags = '[{"color": "#FFFFFF", "name": "Amazon Prime Order", "tagId": 12345}]'
list_marketplaces = """
[
{
"canConfirmShipments":true,
"canRefresh":true,
"marketplaceId":23,
"name":"3dcart",
"supportsCustomMappings":true,
"supportsCustomStatuses":false
},
{
"canConfir... | |
"""
A module for finding instantons between vacua in multiple field dimensions.
The basic strategy is an iterative process:
1. Make an ansatz for the path along which the field will travel.
2. Split up the equations of motion into components that are parallel and
perpendicular to the direction of travel along the ... | |
# -*- coding: utf-8 -*-
'''
Author: <NAME> <<EMAIL>>
Date: 2012-08-25
This example file implements 5 variations of the negative binomial regression
model for count data: NB-P, NB-1, NB-2, geometric and left-truncated.
The NBin class inherits from the GenericMaximumLikelihood statsmodels class
which provides automatic... | |
else:
flux = self['flux']
""" Check linetype """
if linetype == 'abs':
pm = -1.
labva = 'top'
elif linetype == 'em' or linetype == 'strongem':
pm = 1.
labva = 'bottom'
else:
print('')
print("ERROR: linetype must be either 'abs', 'em', or 'strongem'")
print('')
return None, None
""" Set up the tick param... | |
<reponame>anthem-ai/fhir-types
from typing import Any, List, Literal, TypedDict
from .FHIR_boolean import FHIR_boolean
from .FHIR_canonical import FHIR_canonical
from .FHIR_code import FHIR_code
from .FHIR_CodeableConcept import FHIR_CodeableConcept
from .FHIR_ContactDetail import FHIR_ContactDetail
from .FHIR_date im... | |
<filename>mvpa2/mappers/fx.py
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the PyMVPA package for the
# copyright and license te... | |
duration, reason))
if response: self.out_SERVERMSG(client, '%s' % response)
def in_BANSPECIFIC(self, client, arg, duration, reason):
# arg might be a username(->user_id), ip, or email; ban it
good, response = self.bandb.ban_specific(client, duration, reason, arg)
if good: self.broadcast_Moderator("%s banned-s... | |
<filename>glasses/models/classification/resnet/__init__.py
from __future__ import annotations
from torch import nn
from torch import Tensor
from glasses.nn.blocks.residuals import ResidualAdd
from glasses.nn.blocks import Conv2dPad, BnActConv, ConvBnAct
from collections import OrderedDict
from typing import List
from f... | |
from __future__ import division
import json
from collections import OrderedDict
from datetime import timedelta
from decimal import Decimal, ROUND_UP
import numpy as np
from django.conf import settings
from django.contrib.auth.models import User
from django.db import connection, transaction
from django.db.models impor... | |
# Force any command line keys and values that are bytes to unicode.
k = k.decode() if isinstance(k, bytes) else k
v = v.decode() if isinstance(v, bytes) else v
self._flag_values.setdefault(k, v)
@staticmethod
def _is_valid_key(key):
"""Return True if key is a valid configuration key."""
return key and key[0].i... | |
# 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... | |
import random
import shutil
import itertools
import colorsys
from PIL import Image, ImageDraw
__all__ = [
"STANDARD_MODES",
"SPECIAL_MODES",
"ALL_MODES",
"hex_to_rgb",
"hex_to_rgba",
"rgb_to_hex",
"rgba_to_hex",
"random_color",
"iter_pixels",
"color_distance",
"rough_color_distance",
"eval_pixel",
"mix",
... | |
"""The prompt_toolkit based xonsh shell."""
import os
import re
import sys
from functools import wraps
from types import MethodType
from prompt_toolkit import ANSI
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.cursor_shapes import ModalCursorShapeConfig
from prompt_toolkit.enums im... | |
self.status == 6:
return "killing"
elif self.status == 7:
return "butchering"
elif self.status == 8:
return "assassinating"
elif self.status == 9:
return "executing"
elif self.status == 10:
self.gold += random.choice(range(0,20))
return "selling loot..."
else:
return "deleting enemies from existence..."
d... | |
from torch_rgcn.utils import *
from torch.nn.modules.module import Module
from torch.nn.parameter import Parameter
from torch import nn
import math
import torch
class DistMult(Module):
""" DistMult scoring function (from https://arxiv.org/pdf/1412.6575.pdf) """
def __init__(self,
indim,
outdim,
num_nodes,
num_r... | |
list of futures
self.tag_map = defaultdict(list)
# request_obj -> list of (tag, future)
self.request_map = defaultdict(list)
def clean_timeout_futures(self, request):
'''
Remove all futures that were waiting for request `request` since it is done waiting
'''
if request not in self.request_map:
return
for ta... | |
== "variant" and n1!=n2:
sb.append("\t\t\t\t<y:ArcEdge>\n")
else:
sb.append("\t\t\t\t<y:PolyLineEdge>\n")
sb.append("\t\t\t\t\t<y:LineStyle ")
if not dashed:
sb.append("type=\"line\"")
else:
sb.append("type=\"dashed\"")
#sb.append(" width=\"2.0\" ")
sb.append(" width=\"5.0\" ")
sb.append("color=\"... | |
""" bgasync.api - BGAPI classes, constants, and utility functions. """
# This file is auto-generated. Edit at your own risk!
from struct import Struct
from collections import namedtuple
from enum import Enum
from .apibase import *
class event_system_boot(Decodable):
decoded_type = namedtuple('event_system_boot_type',... | |
the indexes.
'''
f = open(file_name, encoding='utf-8')
for line in f:
# This is effectively the documentation for the file format of the file
values = line.rstrip('\n').split('\t')
(pubchemid, CAS, formula, MW, smiles, InChI, InChI_key, iupac_name, common_name) = values[0:9]
CAS = int(CAS.replace('-', '')) # Sto... | |
<filename>Diagnostify.py
#! /bin/usr/python
# Import all neccessary modules
import os
import ctypes
import pyttsx3
import speech_recognition as sr
import math
import traceback
from pyttsx3.drivers import sapi5
import random
import threading
import datetime
import PySimpleGUI as sg
from stat import S_IWUSR,... | |
import collections
import weakref
from lxml import etree
import six
def split_elem_def(path):
"""Get the element name and attribute selectors from an XPath path."""
path_parts = path.rpartition('/')
elem_spec_parts = path_parts[2].rsplit('[')
# chop off the other ']' before we return
return (elem_spec_parts[0],... | |
Constraint(expr= -m.b1049 - m.b1050 + m.b1051 - m.b1179 <= 0)
m.e2036 = Constraint(expr= -m.b1049 - m.b1050 - m.b1051 + m.b1052 - m.b1180
<= 0)
m.e2037 = Constraint(expr= m.b1057 - m.b1185 <= 0)
m.e2038 = Constraint(expr= -m.b1057 + m.b1058 - m.b1186 <= 0)
m.e2039 = Constraint(expr= -m.b1057 - m.b1058 + m.b1059 - m.b1... | |
# coding=utf-8
# Copyright (C) 2019 ATHENA AUTHORS; <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... | |
import numpy as np
TOTAL_NUMBER_OF_TAILES = 60
DICE_MOVE_OUT_OF_HOME = 6
NO_ENEMY = -1
# This roule is that if, there are two pieces on the field, the last one has to return is to start
PLAY_WITH_RULE_A = True
TAILE_FREE = 0
TAILE_HOME = 1
TAILE_START = 2
TAILE_GLOB = 3
TAILE_GOAL_AREAL = 4
TAILE_STAR = 5
TAILE_GOAL... | |
= StringResources.SuccessText()
# ้่ฏฏ็
ErrorCode = 0
# ่ฟๅๆพ็คบ็ๆๆฌ
def ToMessageShowString( self ):
'''่ทๅ้่ฏฏไปฃๅทๅๆๆฌๆ่ฟฐ'''
return StringResources.ErrorCode() + ":" + str(self.ErrorCode) + "\r\n" + StringResources.TextDescription() + ":" + self.Message
def CopyErrorFromOther(self, result):
'''ไปๅฆไธไธช็ปๆ็ฑปไธญๆท่ด้่ฏฏไฟกๆฏ'''
if res... | |
<filename>assignments/ps05/experiment.py
"""Problem Set 5: Object Tracking and Pedestrian Detection"""
import cv2
import ps5
import os
import numpy as np
# I/O directories
input_dir = "input_images"
output_dir = "output"
NOISE_1 = {'x': 2.5, 'y': 2.5}
NOISE_2 = {'x': 7.5, 'y': 7.5}
# Helper code
def run_particle_f... | |
the geottansform data of
the bottom left corner
Parameters
----------
nc : [netcdf object]
netcdf object .
Var : [string], optional
the variable you want to read from the netcdf file if None is given the
last variable in the file will be read. The default is None.
Returns
-------
1-geo : [tuple]
geotransf... | |
"""
Testing using the Test Client
The test client is a class that can act like a simple
browser for testing purposes.
It allows the user to compose GET and POST requests, and
obtain the response that the server gave to those requests.
The server Response objects are annotated with the details
of the contexts and temp... | |
## @ PatchFv.py
#
# Copyright (c) 2014 - 2015, Intel Corporation. All rights reserved.<BR>
# This program and the accompanying materials are licensed and made available under
# the terms and conditions of the BSD License that accompanies this distribution.
# The full text of the license may be found at
# http://opensou... | |
--------
data :: dictionary
data dictionary with cases in cases list updated or added
'''
data_hist_arrs = ['NDump','time(mins)', 'time(secs)']
for case in cases:
data[case] = {}
data[case]['path'] = dir+case+'/prfs'
data[case]['rp'] = RprofSet(data[case]['path'])
data[case]['rph'] = data[case]['rp'].get_hi... | |
then please use Rational."%(row_sum))
def _work_out_state_index(self, state_index, given_condition, trans_probs):
"""
Helper function to extract state space if there
is a random symbol in the given condition.
"""
# if given condition is None, then there is no need to work out
# state_space from random variables... | |
cidx)) for cidx in idx_chunks]
res_cnt = 0
while result:
tmp = result.pop(0).get()
for i, j in enumerate(tmp[1]):
if options.verbose:
log_progress(res_cnt, gene_counts.shape[0])
res_cnt += 1
pval[j] = tmp[0][i]
if options.verbose:
log_progress(gene_counts.shape[0], gene_counts.shape[0])
print('')
pool.termi... | |
stock in cip_df have a sector? ie. ETF?
return None
assert set(df.columns) == set(["sum", "asx_code", "sector_name"])
df["increasing"] = df.apply(
lambda row: "up" if row["sum"] >= 0.0 else "down", axis=1
)
sector_names = (
df["sector_name"].value_counts().index.tolist()
) # sort bars by value count (ascending... | |
#!/usr/bin/python
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-
"""
Role
====
The ``PluginManager`` loads plugins that enforce the `Plugin
Description Policy`_, and offers the most simple methods to activate
and deactivate the plugins once they are loaded.
.. note:: It may also classify the plugins in ... | |
title = self.tr("Recent Workflows")
dialog.setWindowTitle(title)
template = (
'<h3 style="font-size: 26px">\n'
#'<img height="26" src="canvas_icons:Recent.svg">\n'
"{0}\n"
"</h3>"
)
dialog.setHeading(template.format(title))
dialog.setModel(model)
model.delayedScanUpdate()
status = dialog.exec_()
index = ... | |
category=entity.category,
subcategory=entity.subcategory,
length=entity.length,
offset=entity.offset,
confidence_score=entity.confidence_score,
)
def __repr__(self):
return (
"PiiEntity(text={}, category={}, subcategory={}, length={}, "
"offset={}, confidence_score={})".format(
self.text,
self.category,
se... | |
<filename>library/service_element.py
#!/usr/bin/python
# Copyright (c) 2017-2019 Forcepoint
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: service_element
short_description: Create, modify or delete service elements
descriptio... | |
storage_name
kwargs['dataset_group'] = 'scene'
kwargs['dataset_meta'] = {
'authors': '<NAME>, <NAME>, and <NAME>',
'title': 'TUT Urban Acoustic Scenes 2018 Mobile, public leaderboard dataset',
'url': None,
'audio_source': 'Field recording',
'audio_type': 'Natural',
'audio_recording_device_model': 'Various',
'm... | |
Checking if the direction of the move is correct
full_rec_payable = full_rec_move.line_ids.filtered(lambda l: l.account_id == self.account_rsa)
self.assertEqual(full_rec_payable.balance, 18.75)
def test_unreconcile(self):
# Use case:
# 2 invoices paid with a single payment. Unreconcile the payment with one invoic... | |
<filename>appdotnet/api.py
from __future__ import print_function
import os
import sys
import requests
import json
import endpoints
from datetime import datetime
import dateutil
from exceptions import APIException, HTTPException
from util import is_sequence
USER_AGENT = 'appdotnet/0.1.3 (Python/%s)' % '.'.join([str(x) ... | |
<gh_stars>0
# Copyright 2019-2022 Cambridge Quantum Computing
#
# 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 ... | |
#!/usr/bin/env python
#
# Copyright 2007 Google 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 required by applicable law or ag... | |
B : B's minOccurs=4, B's maxOccurs=4, R has 2 groups, each has
one child with minOccurs as 2
"""
assert_bindings(
schema="msData/particles/particlesQ013.xsd",
instance="msData/particles/particlesQ013.xml",
class_name="Doc",
version="1.1",
mode=mode,
save_output=save_output,
output_format=output_format,
struc... | |
args.IsSpecified('node_version') and args.enable_autoupgrade:
log.warning(util.WARN_NODE_VERSION_WITH_AUTOUPGRADE_ENABLED)
def AddMachineTypeFlag(parser):
"""Adds --machine-type flag to the parser.
Args:
parser: A given parser.
"""
help_text = """\
The type of machine to use for nodes. Defaults to e2-medium.
... | |
only data field.
_preload_content (bool, optional):
Response is converted into objects.
_request_timeout (int, optional):
Total request timeout in seconds.
Returns:
ValidResponse: If the call was successful.
ErrorResponse: If the call was not successful.
Raises:
PureError: If calling the API fails.
ValueErr... | |
import inspect
from typing import List, Union, Set, Any
import numpy as np
from fruits.cache import Cache, CoquantileCache
from fruits.scope import force_input_shape, FitTransform
from fruits.core.callback import AbstractCallback
from fruits.signature.iss import SignatureCalculator, CachePlan
from fruits.words.word i... | |
' ').replace('\r', ' ')
body = '<!doctype html>' + \
'<html lang="en">' + \
'<head>' + \
'<meta charset="utf-8">' + \
'<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">' + \
'<link rel="stylesheet"' + \
'href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css... | |
from __future__ import print_function
import bz2
from ftplib import FTP
import gzip
import hashlib
import logging
import os
import pickle
import re
from subprocess import Popen, STDOUT, PIPE
import sys
import time
import urllib
import yaml
class MirrorException(Exception):
def __init__(self, val):
self.val = val
d... | |
<reponame>lzkelley/bhem
"""
"""
import logging
# import warnings
import numpy as np
import scipy as sp
from . import radiation, utils
from . constants import MELC, MPRT, SPLC, K_BLTZ, H_PLNK
class Mahadevan96:
def __init__(self, adaf, freqs, log=30, backup_temp=None, quiet=True):
"""
"""
if not isinstance(log,... | |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.nn.init import xavier_uniform, _calculate_correct_fan, \
calculate_gain, dirac
class InitialConv(nn.Module):
def __init__(self, in_channels, n_filters, filter_size, n_init_conv,
subsample=... | |
<gh_stars>10-100
import random
import math
import pygame
from pygame.color import THECOLORS
import pymunk
from entities.agent import Agent
from entities.edible import Edible
from entities.obstacle import Obstacle
from PIL import Image
from maps.map import Dungeons
import numpy as np
class Env(object):
def __init... | |
<reponame>jwfromm/relax<filename>tests/python/unittest/test_tir_schedule_cache_read_write.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 license... | |
#!/usr/bin/env python
import os
import glob
import shutil
import pytest
import hypothesis.strategies as st
from hypothesis import given, settings
from radical.entk import Task
from radical.entk import states
import radical.entk.exceptions as ree
# Hypothesis settings
settings.register_profile("travis", max_exampl... | |
* _mass)
else:
h = min(100, cone_height)
r = min(100., d / (d**2+7.) * 0.9 *_mass) # kegel_radius; er ist beschrรคnkt
if size < 0.6:
r = 2 * r
if not tube_radius:
tr = None
else:
tr = d/50. * _mass
# Ermittlung der Lage der Spitze aus lรคnge(a(P2-P1)) = h
a = h / 2. / ll
kegel_pos = [x2-a*vv[0], y2-a*vv[... | |
<filename>demisto_sdk/tests/integration_tests/update_release_notes_integration_test.py<gh_stars>10-100
import os
from os.path import join
import pytest
from click.testing import CliRunner
import conftest # noqa: F401
from demisto_sdk.__main__ import main
from demisto_sdk.commands.common.git_util import GitUtil
from d... | |
myParameters["lExcludeTotalsFromCSV"] = lExcludeTotalsFromCSV
myParameters["lIncludeFutureBalances_SG2020"] = lIncludeFutureBalances_SG2020
myParameters["lDontRoundPrice"] = lRoundPrice
myParameters["lStripASCII"] = lStripASCII
myParameters["csvDelimiter"] = csvDelimiter
myParameters["_column_widths_SG2020"] = _co... | |
filename:
slope_suffix = '{}.fits'.format(suffix)
jump_file = filename.replace(slope_suffix, '_jump.fits')
break
if jump_file is None:
raise ValueError("ERROR: Unrecognized slope filename suffix.")
if not os.path.isfile(jump_file):
raise FileNotFoundError("ERROR: Jump file {} not found.".format(jump_file))
pri... | |
# ExportSQLite: SQLite export plugin for MySQL Workbench
#
# Copyright (C) 2015 <NAME> (Python version)
# Copyright (C) 2009 <NAME> (Original Lua version)
#
# 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 F... | |
transformations that occur *within* block-level
# tags like paragraphs, headers, and list items.
text = self._do_code_spans(text)
text = self._escape_special_chars(text)
# Process anchor and image tags.
text = self._do_links(text)
# Make links out of things like `<http://example.com/>`
# Must come after ... | |
<reponame>bencrabbe/npdependency
import argparse
import math
import os.path
import pathlib
import random
import shutil
import sys
import tempfile
import warnings
from typing import (
Any,
BinaryIO,
Callable,
Dict,
IO,
Iterable,
List,
NamedTuple,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
cast,
overload,
... | |
#!/usr/bin/env python
"""
Based on http://groups.google.com/group/dropio-api/web/full-api-documentation
"""
__version__ = '0.1.1'
import httplib
import logging
import mimetypes
import mimetools
import os.path
import sys
import urllib
import urllib2
import uuid
from optparse import OptionParser
from... | |
from django.contrib.gis.db import models
from django.db import connection, transaction
from django.db.models import Max
from django.utils.translation import pgettext_lazy
from django.utils.translation import ugettext_lazy as _
from enumfields import EnumField
from sequences import get_next_value
from leasing.enums imp... | |
<reponame>yanyongyu/FlappyBird<filename>src/main.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This is the main program of the game.
@Author: yanyongyu
"""
__author__ = "yanyongyu"
__all__ = ["Game"]
import sys
import time
import random
import traceback
import pygame
import pygame.locals as gloc
import bird
... | |
header[kw].strip("-SIP")
header[kw] = val
else:
continue
return header
def to_header_string(self, relax=None):
"""
Identical to `to_header`, but returns a string containing the
header cards.
"""
return str(self.to_header(relax))
def footprint_to_file(self, filename='footprint.reg', color='green',
width=2,... | |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT
import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
from . import BigGAN_layers as layers
from networks.utils import init_weights, _len2mask, make_one_hot
# Architectures for G
# Atten... | |
<filename>python/Labyrinth.py
#!/usr/bin/python3
# This was: #! /usr/bin/env python
# The labyrinthine abbey library in Python - October 3, 2013
import random
#import sys
import VersionSpecificUtilities
class RoomInfo:
def __init__(self, level, room):
self.levelNumber = level
self.roomNumber = room
... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Functional tests for `copra.rest.Client` class.
Without any additional user input, this module will test all of the
unauthenticated methods of the copra.rest.Client.
An API key for the Coinbase Pro sandbox is required to test the authenticated
methods. The key informa... | |
from __future__ import absolute_import, division, print_function, unicode_literals
import copy
import json
import logging
import math
import os
import shutil
import tarfile
import tempfile
import sys
from io import open
import torch
from torch import nn
from torch.nn import CrossEntropyLoss
from torch.utils import c... | |
res = str(v.strip('"\''))
return res
def _decode_attribute(self, s):
'''(INTERNAL) Decodes an attribute line.
The attribute is the most complex declaration in an arff file. All
attributes must follow the template::
@attribute <attribute-name> <datatype>
where ``attribute-name`` is a string, quoted if the nam... | |
<gh_stars>0
import uuid
import os
import datetime
import csv
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.decorators import login_required
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts impo... | |
<gh_stars>0
from django import http
from django.core.exceptions import PermissionDenied
from django.db.models import Prefetch, Q
from django.db.transaction import non_atomic_requests
from django.shortcuts import get_object_or_404, redirect
from django.utils.encoding import force_text
from django.utils.translation impor... | |
import warnings
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule, xavier_init
from mmcv.runner import auto_fp16, BaseModule
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
from ..builder import NECKS
class GroupAttention(BaseModule):
def __init__(s... | |
<filename>threeML/utils/data_download/Fermi_LAT/download_LAT_data.py
from __future__ import print_function
import glob
import html.parser
import os
import re
import socket
import time
import urllib.error
import urllib.parse
import urllib.request
from builtins import str
from pathlib import Path
import astropy.io.fits... | |
import math
import operator
from functools import reduce
import numpy as np
import gym
from gym import error, spaces, utils
from .minigrid import OBJECT_TO_IDX, COLOR_TO_IDX, STATE_TO_IDX
class ReseedWrapper(gym.core.Wrapper):
"""
Wrapper to always regenerate an environment with the same set of seeds.
This can be ... | |
# DISABLE SELECT PYLINT TESTS
# pylint: disable=bad-continuation, no-member, broad-except, no-name-in-module
# pylint: disable=arguments-differ
"""
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โโโโฆโโโโโโโโโฆ โฆโโโโโโโโโ โโฆโโโโโโฆโโโโโโโโโโโโฆโโโโ โ
โ โ โฆโ โฆโโ โโฃโ โโโ โโฃโโฃ โโโโโฃ โโโโโฃ โ โ โโฃโโโโ โ โโโโฃ โ
โ โโโโฉโโ... | |
range(order + 1):
for j in range(i + 1):
XL1[k1] = square[i - j, j]
k1 += 1
return (XL0, XL1)
def reorder(pcfName, verbose=False):
'''Use pcf files
'''
# order = 5
print ('\n =============================================%\n')
print (pcfName)
xForward = []
yForward = []
xBackward = []
yBackward = []
pc... | |
<reponame>tomar27/pipelines<gh_stars>1-10
"""Module for input and output processing for Cloud AI Metrics."""
import copy
import dataclasses
import json
import numbers
from typing import Any, Dict, List, Optional, Tuple, Type, Union
import tensorflow.compat.v2 as tf
from lib import column_spec, constants, evaluation_c... | |
"""
spark-submit task2.py <filter threshold> <support> <input_file_path> <output_file_path>
spark-submit task2.py 70 50 "file:///Users/markduan/duan/USC_course/USC_APDS/INF553/homework/hw2/dataset/task2_data.csv" "task2_output.txt"
"""
import sys
import time
from pyspark import SparkConf, SparkContext
# import os
# ... | |
"""
T_zero = {"p0": SE3.identity()}
ang_lims_map = {}
old_to_new_names = {
"p0": "p0"
} # Returned for user of the method (to map old joint names to new ones)
ub, lb = spherical_angle_bounds_to_revolute(self.ub, self.lb)
count = 1
joint_prev = "p0"
for (
joint
) in self.d: # Assumes the dictionary is in chai... | |
segments from Hierarchy pickle.
Arguments:
"""
# read threshold and connectivity
pickled_obj = common.read_pickle(file_name=name)
if isinstance(pickled_obj, pyto.segmentation.Labels):
segments = pickled_obj
elif isinstance(pickled_obj, pyto.scene.SegmentationAnalysis):
segments = pickled_obj.labels
else:
... | |
'rider_position',
'field_type': 'rider_position_type',
'ref_field_name': 'event',
'ref_field_value': { 'rider_position_change'}},
'speed_high_alert': { 'example': 1.0,
'field_name': 'speed_high_alert',
'field_type': 'uint32',
'ref_field_name': 'event',
'ref_field_value': { 'speed_high_alert'},
'scale': 1000.0,... | |
"""
tasks service
Provides a management API for tasks in the system.
"""
import enum
from datetime import datetime
import six
from clearml.backend_api.session import (
Request,
BatchRequest,
Response,
NonStrictDataModel,
schema_property,
StringEnum,
)
from dateutil.parser import parse as parse_datetime
class ... | |
# -*- coding: utf-8 -*-
# Copyright 2013 Mirantis, 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 required by applicable law o... | |
<filename>third_party/fonts.bzl
# Copyright 2017 The TensorFlow 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
#
... | |
= np.array([1, 0, 2])
idx = 3
y = 0
x = [-1, 0, 1]
res = n_box - 3
while res > 0:
y += 1
if res == 3:
i_list = [0, 1, 2]
else:
i_list = [0, 2]
material = [0, 1][int(np.random.rand() < 0.5 and res > 3)]
for i in i_list:
init_p[idx, :] = np.array([x[i], y, material])
idx += 1
res -= 1
elif shape_type == ... | |
#-------------------------------------------------------------------------------
# Copyright 2017 Cognizant Technology Solutions
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://w... | |
import torch
import pretty_midi
import os
import numpy as np
import matplotlib.pyplot as plt
from attn_ecvae_mq import VAE
from utils import *
import glob
def load_model(VAE, model_path):
model = VAE(130, 2048, 3, 12, 128, 128, 32)
model.eval()
dic = torch.load(model_path)
for name in list(dic.keys()):
dic[name.r... | |
# Actions
self.actions_input = dict()
for name, action in self.actions_spec.items():
self.actions_input[name] = tf.placeholder(
dtype=util.tf_dtype(action['type']),
shape=(None,) + tuple(action['shape']),
name=name
)
# Explorations
self.explorations = dict()
if self.explorations_spec is None:
pass
elif isi... | |
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2021 Beartype authors.
# See "LICENSE" for further details.
'''
**Beartype decorator.**
This private submodule implements the core :func:`beartype` decorator as well
as ancillary functions called by that decorator. The :... | |
0x05492141, 0xfdadf7ff, 0x28009806, 0x6006d000, 0xe7cb2000, 0x00000515,
0x460bb510, 0x7b1c3320, 0xd00c2c01, 0x600c6814, 0x604c6854, 0x608a6852, 0x73192101, 0xf7ff05c9,
0x2000fd94, 0x4801bd10, 0x0000bd10, 0x00000514, 0xb084b5f7, 0xd00d000f, 0x90012000, 0x97002404,
0x46399002, 0x98064361, 0xffe2f7fe, 0x0c2d0405, 0xe00... | |
import numpy as np
import pandas as pd
import math
import tensorflow as tf
from tensorflow.keras.utils import Sequence
from tensorflow.keras.wrappers.scikit_learn import KerasRegressor
from tensorflow.keras.models import Sequential
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
import aux.conf... | |
<reponame>craigmaloney/eeweather
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2018 Open Energy Efficiency, 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.apach... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.