content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
# coding=utf-8
# aeneas is a Python/C library and a set of tools
# to automagically synchronize audio and text (aka forced alignment)
#
# Copyright (C) 2012-2013, Alberto Pettarin (www.albertopettarin.it)
# Copyright (C) 2013-2015, ReadBeyond Srl (www.readbeyond.it)
# Copyright (C) 2015-2017, A... |
import xml.etree.ElementTree as ET
import os
from dotenv import load_dotenv
load_dotenv('../.env')
bot_word = os.environ["WORD"]
table_word = os.environ["POSTGRES_TABLE_WORD"]
mytree = ET.parse('./kotus-sanalista_v1/kotus-sanalista_v1.xml')
myroot = mytree.getroot()
word_elems = myroot.findall('.//s')
print(len(wor... |
from rasa_addons.core.policies.disambiguation import BotfrontDisambiguationPolicy
from rasa_addons.core.policies.mapping import BotfrontMappingPolicy |
from __future__ import unicode_literals, print_function
import plac
import random
from pathlib import Path
import spacy
from spacy.util import minibatch, compounding
#HELLLO
# new entity label
LABEL = 'ROOM'
LABEL_2 = 'PHONE'
# training data
# Note: If you're using an existing model, make sure to mix in examples o... |
import os
from django.core.files.storage import FileSystemStorage
class DeleteErrorStorage(FileSystemStorage):
def delete(self, name):
''' delete modified to not catch FileNotFoundError
does not support deleting directories
'''
name = self.path(name)
# If the file or d... |
shapefile = {
'area': 'Knightswood',
'input': 'Knightswood_planet_osm_line_lines.shp',
'dotted': 'Knightswood_out.shp'
}
GVIfile = {
'images': './imgs_Knightswood/',
'shapefile': 'GVI_Knightswood.shp',
'data': 'greenViewRes'
}
greenmonth = ['04','05','06','07','08','09']
gcloud_key ... |
# -*- coding: utf-8 -*-
"""
Execution Module Directory
"""
|
# Copyright (c) 2015-2018, Activision Publishing, 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 copyright notice, this
# list of ... |
import sys
from xml.etree.ElementTree import TreeBuilder
import logging
import time
import os
import requests
import json
import datetime
from thingspro.edge.tag_v1 import tag
from opcua import Client
from opcua import ua
from opcua.ua.uatypes import VariantType
from datetime import timezone
_config_fi... |
from typing import List
from kafka import KafkaConsumer, KafkaProducer
from kafka.errors import NoBrokersAvailable
from abstract_translator import MessageTranslator
from messages import CloudEvent
from slip_router import route_message
from json import loads, dumps
from json.decoder import JSONDecodeError
from time impo... |
# Given an array of n integers nums and a target,
# find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition
# nums[i] + nums[j] + nums[k] < target.
# Example:
# Input: nums = [-2,0,1,3], and target = 2
# Output: 2
# Explanation: Because there are two triplets which sums are les... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
if PY2:
text_type = unicode
binary_type = str
else:
text_type = str
binary_type = bytes
def unicode2utf8(arg):
"""Convert strings to UTF8-encoded bytes.
... |
from typing import Union
import dask
from dask.callbacks import Callback
from fungraph.cacheabc import Cache
from fungraph.internal.delayedoptimize import delayedoptimize
from fungraph.internal.lockedcache import LockedCache
DEFAULT_CACHE_PATH = ".fungraphcache"
def cachecontext(cache: Union[str, Cache, None] = DE... |
import sys
import numpy as np
from . import nn_translator
from . import predict
from . import visualizer
inputfile = sys.argv[1]
nn_input, input_mat, empirical \
= nn_translator.nn_translator(inputfile, train=True)
nn_input = np.array(nn_input).reshape((1, predict._N_DIMS_IN))
p = predict.Predictor(net='hyak_l... |
from ..tableau_exceptions import *
class Sort:
def __init__(self, field: str, direction: str):
self.field = field
if direction not in ['asc', 'desc']:
raise InvalidOptionException('Sort direction must be asc or desc')
self.direction = direction
def get_sort_string(self) ->... |
from django.utils.encoding import force_unicode, is_protected_type
from django.utils.functional import Promise
import six
def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with... |
# Copyright (c) OpenMMLab. All rights reserved.
import math
import torch
from mmdet.core.bbox.iou_calculators import bbox_overlaps
from mmdet.core.bbox.transforms import bbox_cxcywh_to_xyxy, bbox_xyxy_to_cxcywh
from .builder import MATCH_COST
@MATCH_COST.register_module()
class BBoxL1Cost:
"""BBoxL1Cost.
A... |
from hearthbreaker.cards.base import MinionCard
from hearthbreaker.cards.heroes import Jaraxxus
from hearthbreaker.cards.weapons.warlock import BloodFury
from hearthbreaker.constants import CHARACTER_CLASS, CARD_RARITY, MINION_TYPE
from hearthbreaker.game_objects import Minion
from hearthbreaker.tags.action import Summ... |
# -*- coding: utf-8 -*-
# This file is part of Kaleidoscope.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... |
#!/usr/bin/env python
"""
BRDF data extraction utilities
------------------------------
The :ref:`nbar-algorithm-label` and :ref:`tc-algorithm-label` algorithms
require estimates of various atmospheric parameters, which are produced using
`MODTRAN <http://modtran5.com/>`_. MODTRAN, in turn, requires `BRDF
<http://en.... |
# -*- coding: utf-8 -*-
"""
Settings and global variables used in the reading and plotting procedures
"""
# todo: reduce dependency on globals (e.g flexible if new datasets/versions are added)
import cartopy.crs as ccrs
# === plot defaults ===
matplotlib_ppi = 72 # Don't change this, it's a matplotlib convention.
in... |
"""
auditor
Usage:
auditor spot [--save_report --dry --verbose ITEM ...]
auditor scheduled
Options:
-h, --help
-r, --save_report Save report to the file specified in the credentials file (will be rotated)
-d, --dry Only run the checks, don't do any fixes [default: False... |
import sys
import logging
import opentracing
import datetime
import time
import json
import traceback as tb
import functools
import socket
from sanic.request import Request
from basictracer.recorder import SpanRecorder
STANDARD_ANNOTATIONS = {
'client': {'cs':[], 'cr':[]},
'server': {'ss':[], 'sr':[]},
}
ST... |
import _plotly_utils.basevalidators
class XbinsValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="xbins", parent_name="histogram2d", **kwargs):
super(XbinsValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
import tensorflow as tf
from kerod.utils.documentation import remove_unwanted_doc
__pdoc__ = {}
class MultiHeadAttention(tf.keras.layers.Layer):
"""Allows the model to jointly attend to information from different representation subspaces.
See reference: [Attention Is All You Need](https://arxiv.org/abs/1706.... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 31 23:29:17 2021
@author: lankuohsing
"""
import tensorflow as tf
from tensorflow.keras.models import load_model
import argparse
import time
import os
import json
import numpy as np
import string
import build_model
import load_data
import vectorize_data
import explore_dat... |
def who_eats_who(zoo_input):
animals = {'antelope': ['grass'], 'big-fish': ['little-fish'], 'bug': ['leaves'],
'bear': ['big-fish', 'bug', 'chicken', 'cow', 'leaves', 'sheep'],
'chicken': ['bug'], 'cow': ['grass'], 'fox': ['chicken', 'sheep'],
'giraffe': ['leaves'], 'lio... |
#! /usr/bin/env python3
import argparse
from pathlib import Path
from Controle_entidade import ControleEntidade
from Controle_csv import ControleCsv
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Processa um dataset e imprime Crs.')
parser.add_argument("caminho", type=Path)
args... |
#! /usr/bin/env python
#This script extracts all front files
# python extract_front_files.py <directory where are front files>
# Example: python count_global_non_dominated_solution.py /home/faccioli/Execute/T0773/
import os
import sys
from shutil import copy
def get_files_front(mypath):
#Obtaing the tar.gz files fr... |
# coding: utf-8
import os
import argparse
import subprocess
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--dir", type=str, default=None)
args = parser.parse_args()
return args
def upload(dir=None):
if dir is None:
photo_dir = os.path.join(os.getcwd()... |
import json
from . import __version__
from .sleeper import SLEEPER_HOME
class BaseConfigDict(dict):
path = SLEEPER_HOME / 'config.json'
def ensure_directory(self):
self.path.parent.mkdir(parents=True, exist_ok=True)
def exists(self):
return not self.path.exists()
def load(self):
... |
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
# -*- coding: utf-8 -*-
import pyRofex
class Market():
def __init__(self, user, password, account=None, environment=pyRofex.Environment.REMARKET):
self.environment = environment
self.account = account
self.is_initialized = False
self.last_message = None # last message received
... |
def rec_a(a: list, i: int, b: list):
if i >= len(a):
return []
else:
# Put result of rb in a list in order to extend it
rb = [rec_b(a[i], b, 0)]
# Get rest of the result
ra = rec_a(a, i+1, b)
# Merge the rest of the result with the current one
rb.extend(ra... |
"""pdata: Simple-to-understand and robust data storage for experimental data.
Storing data sets is handled by pdata.procedural_data
Reading data sets is handled by functions in pdata.analysis
See https://pdata.readthedocs.io/ for documentation and examples.
"""
from pdata._metadata import __version__
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pycocotools.coco as coco
import numpy as np
import json
import os
from progress.bar import Bar
import cv2
import math
import copy
import os
from datasets.dataset.utils import _bbox_overlaps, rotate_bbox... |
#!/usr/bin/env python
"""
Plugin which executes df command and prepares output about mounted storages
Copyright 2017 California Institute of Technology
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 ... |
import sys
import json
import os.path
# definitions
PREFIX = 'prefix'
HOST = 'host'
PORT = 'port'
gDefaultConfig = {}
# functions
def scriptPath():
return os.path.dirname(os.path.abspath(__file__))
def getPort():
global gDefaultConfig
port = gDefaultConfig.get(PORT)
if port == None:
print('... |
#!/usr/bin/env python
# coding:utf8
# Copyright (c) 2018, Tencent. All rights reserved
# Author: Ai Xingsheng (felixai@tencent.com)
# Implement model of
# "Deep Pyramid Convolutional Neural Networks for Text Categorization"
# which can be seen at
# https://ai.tencent.com/ailab/media/publications/ACL3-Brady.pdf
i... |
#IMC
altura = float(input('Digite sua altura: '))
peso = float(input('Digite seu peso: '))
imc = peso/(altura*altura)
print('Seu IMC é {:.2f}'.format(imc))
if imc < 18.5:
print('Status: Abaixo do peso!')
elif imc <= 25:
print('Status: Peso normal!')
elif imc <= 30:
print('Status: Sobrepeso!')
elif imc <= 4... |
## set up logging
import logging, os
logging.basicConfig(level=os.environ.get("LOGLEVEL","INFO"))
log = logging.getLogger("glam_command_line")
import argparse, glob, json, octvi, subprocess, sys
import glam_data_processing.legacy as glam
from getpass import getpass
from datetime import datetime
def getYesNo(message:s... |
import random
from copy import deepcopy
from environment.env import Environment
from environment.mazebase_wrapper import MazebaseWrapper
from environment.observation import ObservationTuple, Observation
from utils.constant import *
class SelfPlay(Environment):
"""
Wrapper class over self play environment
... |
#!/usr/bin/env python3
from ctf_gameserver import checkerlib
import random
import logging
import socket
import utils
from treasurehunt.treasurehunt import *
class TemplateChecker(checkerlib.BaseChecker):
def connect(self):
logging.info(f"default timeout: {socket.getdefaulttimeout()}")
self.sock... |
#!/usr/bin/env python
"""Import Google Cloud Platform projects into an organization."""
import argparse
import re
import sys
from lib.google import Google
def add_project_to_org(admin, project):
"""Add the project to the organization."""
output = []
project_id = project['projectId']
body = project.... |
from __future__ import unicode_literals
import numpy as np
import random
import datetime
import time
import os
from django.conf import settings
from django.db import models
from django.db.models import Count
from django.contrib.auth.models import User
from django.core.cache import cache
import xml.etree.ElementTree as... |
import cv2
import numpy as np
from matplotlib import pyplot as plt
import os
import sys
import_file_path = os.getcwd().split('vision')[0] + 'vision/utilities'
sys.path.append(import_file_path)
from point_manipulation import transform_edge_points
roi_points = []
frame = None
def selectROI(event, x, y, flags, param):
... |
#!/usr/bin/env python3
__author__ = "Emanuel Burgos"
__email__ = "eburgos@wisc.edu" |
"""
Mixins for JWT auth tests.
"""
from time import time
from django.conf import settings
import jwt
JWT_AUTH = 'JWT_AUTH'
class JwtMixin:
""" Mixin with JWT-related helper functions. """
JWT_SECRET_KEY = getattr(settings, JWT_AUTH)['JWT_SECRET_KEY'] if hasattr(settings, JWT_AUTH) else ''
JWT_ISSUER ... |
from PyQt5 import QtWidgets
from PyQt5.QtCore import QSettings
from appGUI.GUIElements import FCDoubleSpinner, FCLabel
from appGUI.preferences.OptionsGroupUI import OptionsGroupUI
import gettext
import appTranslation as fcTranslate
import builtins
fcTranslate.apply_language('strings')
if '_' not in builtins.__dict__... |
# encoding:utf-8
from unittest import TestCase
from statscraper import (BaseScraper, Dataset, Dimension, Result,
DimensionValue, Collection, ROOT, NoSuchItem)
class Scraper(BaseScraper):
"""A scraper with hardcoded yields."""
def _fetch_itemslist(self, item):
yield Dataset("D... |
"""
1. Clarification
2. Possible solutions
- Backtracking brute force
- Backtracking improved
3. Coding
4. Tests
"""
# T=O(n*4^n), S=O(n)
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
self.n = n
self.ans = []
self.backtrack([])
return self.ans
def... |
from django.core.cache import cache
from django.db import models
class FlatContent(models.Model):
slug = models.SlugField(max_length=255, unique=True, help_text='The name by which the template author retrieves this content.')
content = models.TextField()
class Meta:
verbose_name_plural = 'flat con... |
import smtplib, ssl
from email.utils import parseaddr
from email.message import EmailMessage
from MailUtils import MailUtils
from Utilities import Utilities
class MailHandler:
def send_activation_code(self, username, code, receiver_email):
message = EmailMessage()
message.set_content(MailUtils()... |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
"""
Default hyperparameters CartPole-v0
"""
# General hyperparameters
env_name = 'CartPole-v0'
render = False
gamma = 0.99 # discount factor
maxiter = 500 # number of learning iterations
min_trans_per_iter = 1024 # minimum number of transition steps per... |
from abc import abstractmethod
from typing import List
from config import CANNON_STEP_SIZE, CANNON_A_IMG
from model.game_info import AbsGameInfo
from model.game_object import GameObject
from utils.geometry import Position
from visitor import Visitor
from model.missile import AbsMissile
from model.shooting_mode import ... |
"""
:testcase_name while_module
:author Sriteja Kummita
:script_type Module
:description Demonstration of function call inside a while-loop. 'modify_list' calls 'raise_to' for each number of the
received list.
"""
def raise_to(num, power):
return pow(num, power)
def modify_list(num_list, scalar):
l = len(nu... |
# ------------------------------------------------
# instead of slack_bolt in requirements.txt
import sys
sys.path.insert(1, "..")
# ------------------------------------------------
import logging
logging.basicConfig(level=logging.DEBUG)
import os
from slack_sdk.web.async_client import AsyncWebClient
from slack_bol... |
# DomirScire
import time
def elapsed_since(data):
last_time = None
for item in data:
current_time = time.perf_counter()
delta = current_time - (last_time or current_time)
last_time = time.perf_counter()
yield (delta, item)
if __name__ == "__main__":
for t in elapsed_since('... |
import random
howmany = int(input("How many times do you want the coin to be flipped: "))
outcomes = []
while howmany > 0:
num = random.randint(1,2)
outcomes.append(num)
howmany -=1
lis = []
for i in outcomes:
if i == 1:
lis.append("Tails")
if i == 2:
lis.append("Heads")
print (lis)
|
# Copyright 2019 The FastEstimator Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 Radim Rehurek <radim@rare-technologies.com>
# Copyright (C) 2020 Nicolas Mitchell <ncls.mitchell@gmail.com>
#
# This code is distributed under the terms and conditions
# from the MIT License (MIT).
#
import gzip
import io
import logging
import os
import time
import uuid
im... |
from datetime import datetime, date
from django import template
from django.http import Http404
from api.models import S3Upload
from api.utils import get_or_none
from index.models import RouteFreight
from owner.vehicle_util import display_format
from team.models import ManualBooking, OutWardPaymentBill, OutWardPaymen... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from decimal import Decimal
from django.utils.translation import ugettext_lazy as _
from shop.modifiers.base import PaymentModifier
from shop_wspay.payment import WSPayPayment
from shop_wspay.conf import app_settings
try:
from shop.... |
##
# .port
##
"""
Platform specific modules.
The subject of each module should be the feature and the target platform.
This is done to keep modules small and descriptive.
These modules are for internal use only.
"""
__docformat__ = 'reStructuredText'
|
from domain.bag import Bag, InfiniteBag
from reader.fromlist import read_fromlist
from reader.color import ColorReader
from reader.number import read_float
from reader.content import read_content
class BagParser:
def __init__(self, types):
self.types = types
def parse(self, sheet):
bags = []
... |
""" Arquvio auxiliar com função de calcular a distância entre dois textos
"""
from math import sqrt
from math import fsum
def distancia(texto1, texto2):
"""Função auxiliar que calcula a distância euclidiana entre dois textos
Parameters
----------
texto1 : tipo Texto
Primeiro texto a ser compa... |
import argparse
import os
import pathlib
from tabnanny import verbose
from PIL import Image as img
from alive_progress import alive_bar
all_args = argparse.ArgumentParser(
description="Take images from folder and tile them to create a finished tile."
)
all_args.add_argument("-i", "--input", required=False, defau... |
from matplotlib.pyplot import *
from raysect.optical import World, translate, rotate, Point3D, d65_white
from raysect.primitive import Sphere, Box, Cylinder
from raysect.optical.observer import PinholeCamera, RGBPipeline2D, RGBAdaptiveSampler2D
from raysect.optical.material import Lambert, UniformSurfaceEmitter, Blend... |
"""Residences indicators."""
from etl.common import to_json_stat, write_to_file
from etl.config_residences import residences_cfg as cfg
from etlstat.extractor.extractor import xlsx
import json
import pandas as pd
def transform(df, periods, prefix=''):
"""Slice dataframe. Generate time period column.
... |
"""
Various utilitites for working with XML and the lxml library.
"""
import re
from lxml import etree
def format_document(doc, linewidth=72):
"""
Formats a an XML document using the lxml pretty print function and
indenting attributes for long lines.
The ``doc`` parameter has to be an lxml.etree.E... |
from ev3dev2_mock.sensor import lego
INPUT_1 = 'in1'
INPUT_2 = 'in2'
INPUT_3 = 'in3'
INPUT_4 = 'in4'
class Sensor(object):
def __init__(self, address, driver_name):
self.address = address
self.driver_name = driver_name
def list_sensors():
return iter([
Sensor(INPUT_1, 'lego-ev3-touc... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @namespace pyfortified_requests
import sys
# Check Python Version
#
def python_check_version(required_version):
"""Check Python Version
:param: required_version
"""
assert isinstance(required_version, tuple)
current_version = sys.version_info
... |
"""
Test parsers
"""
from __future__ import print_function
import unittest
import filecmp
import sys
import os
from mock import patch, Mock
from pyingest.parsers import atel
from pyingest.serializers import classic
if sys.version_info > (3,):
open_mode = 'rb'
open_mode_u = 'rb'
else:
open_mode = 'r'
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
---------------------------------------------------------------------------------------------
#dir()函数是查看函数或模块内的操作方法都有什么,输出的是方法列表
---------------------------------------------------------------------------------------------
#查看对象内所有的属性及方法
dir([])
x = ['a', 'b']
dir(x)
-... |
"""
Module load handler for execution via:
python -m prtg
"""
from __future__ import absolute_import, division, print_function
import getpass
import click
from six.moves.urllib.parse import urlparse
from .client import PRTGApi
from .version import __version__ as app_version
CONTEXT_SETTINGS = dict(help_option_name... |
# Copyright (c) 2020 Leedehai. All rights reserved.
# Use of this source code is governed under the MIT LICENSE.txt file.
import os
from typing import Any, List, Optional, OrderedDict
INFINITE_TIME = 0 # it means effectively infinite time required by timer
TaskResult = OrderedDict[str, Any] # i.e. collections.Orde... |
# updated by syshin (180825)
# do the following steps before running this script
# (1) run the script 'GenGraph/make_graph_db.py'
# to generate training/test graphs
# (2) place the generated graphs ('.graph_res')
# and cnn results ('_prob.png') in
# a new directory 'args.save_root/graph'
import numpy as np
import os
i... |
import pytest
def test_load_module():
__import__("modules.contrib.amixer")
|
# Space Invaders
# Created by Lee Robinson
# Adapted by Raysa Dutra
# -*- coding: utf-8 -*-
#!/usr/bin/env python
from pygame import *
class Text(object):
def __init__(self, textFont, size, message, color, xpos, ypos):
self.font = font.Font(textFont, size)
self.surface = self.font.render(message, ... |
import os
import shutil
import rfc6266
import requests
from .util import get_safe_filename
def download_to_local(url, dir_name):
"""Downloads remote resource given its URL.
Args:
url: the URL to the resource.
dir_name: the directory on the local filesystem to save the resource.
Returns:... |
"""
Copyright (C) 2022 Martin Ahrnbom
Released under MIT License. See the file LICENSE for details.
SAMHNet: Shape And Middle Height Network
The CNN takes a cropped/scaled instance segmentation mask as well as a
vector with cropping/scaling information and object class and produces
as its out... |
# coding: utf-8
from Component import *
def test(*args):
for arg in args:
print arg
#config.py
class Config(Component):
@RegisterFlow("go")
def Go(self, info, flow):
print "Config Go",info["name"]
return "Config Flow"
@RegiserService("GetConfig")
def co... |
from instance import *
instance = Instance()
# Little-endian
def intToVector(x, size=32):
bits = [False]*size
i = 0
while x > 0:
bits[i] = (x % 2 == 1)
i += 1
x //= 2
return ConstantVector(bits)
# Little-endian bit list to int
def toInt(bits):
val = 0
for b in bits[::-1... |
# Python modules
from math import log2, floor
SECURITY_PARAMETER = 4
N = SECURITY_PARAMETER
P = SECURITY_PARAMETER**2
Q = SECURITY_PARAMETER**5
HINT_SUBSET_SIZE = floor(SECURITY_PARAMETER/log2(SECURITY_PARAMETER)) # ALPHA
HINT_SIZE = 2 * HINT_SUBSET_SIZE
PK_SIZE = 1 # This is the number of encryptions of zero in ... |
from autoarray.mask.mask import Mask as mask
from autoarray.structures.arrays import Array as array
from autoarray.structures.grids import (
Grid as grid,
GridIrregular as grid_irregular,
GridRectangular as grid_rectangular,
GridVoronoi as grid_voronoi,
Coordinates as coordinates,
)
from autoarray.s... |
"""
Celery tasks related to SUSHI fetching
"""
import celery
from core.logic.error_reporting import email_if_fails
from core.task_support import cache_based_lock
from .logic.fetching import retry_queued, fetch_new_sushi_data
from sushi.models import SushiFetchAttempt, SushiCredentials
@celery.shared_task
@email_if_f... |
# Notes:
# - Python is a dynamic language so you don't need to
# define a variable's type
# - Parentheses are often optional
# - Comments start with # and anything in a comment,
# won't be run by the computer
# - Counting starts at 0 not 1
# import will load external modules allowing you to use
# the functions with... |
import sys
import datetime
import basicutil
if len(sys.argv) != 3:
print "usage: ", sys.argv[0], " file1 file2"
exit(1)
fileorig = sys.argv[1]
file = sys.argv[2]
refdates, refvalues = basicutil.read_from_file (fileorig)
dates, values = basicutil.read_from_file (file)
previd = 0
for d in refdates:
if d i... |
#!/usr/bin/python
import unittest
import os
import shutil
import sys
import subprocess
import re
import time
import urllib2
import mechanize
import threading
# --- TESTS
class IamADeveloper(unittest.TestCase):
def testLogLevelsAndLog4jConfig(self):
# Testing job developing
step('Hello, I am... |
import torch
import torchvision
from torch import optim
import torch.nn as nn
from torch.utils.tensorboard import SummaryWriter
from torchvision import datasets, transforms,models
import torch.utils.data
model = models.resnet18(pretrained=True)
device = "cuda:0"
def add_gpu_noise(device, tensor):
a = torch.randn... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# progressbar - Text progress bar library for Python.
# Copyright (c) 2005 Nilton Volpato
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; ei... |
from .util import load_lib
import ctypes
import numpy as np
import logging
logger = logging.getLogger(__name__)
cudaLib = load_lib('libcudaDeconv')
if not cudaLib:
logger.error('Could not load libcudaDeconv!')
else:
try:
# setup
camcor_interface_init = cudaLib.camcor_interface_init
c... |
#!/usr/bin/env python
#
# Copyright 2019 DFKI GmbH.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merg... |
# -*- coding: utf-8 -*-
import os
import pickle
path = './output/'
listing = os.listdir(path)
globalMp = {};
print(listing)
sourceTimeDestination = {}
for infile in listing:
# print(infile)
if infile=='.DS_Store':
continue
file1 = open(path+infile, 'r')
fileData = file1.readlines()
index = 0
for x in range( ... |
from flask import Blueprint, flash, redirect, render_template, request, url_for
from flask_login import current_user, login_required, login_user, logout_user
from werkzeug.security import generate_password_hash, check_password_hash
from . import db
from .models import User
auth = Blueprint("auth", __name__)
@auth.... |
# Copyright 2017, The Johns Hopkins University/Applied Physics Laboratory
# 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... |
'''the main game class has a list of active effects,
it exposes a function to update/check all the effects
the scene is responsible for calling this or not
scene will not call this if you dont want time to pass in that scene
'''
class Effect:
def __init__(self, game, name, target, duration, unique=False):
... |
"""
Parser for Datalog queries
Last modify:
Marcello 24/01/2013
Python Lex & Yacc tutorial:
http://www.dabeaz.com/ply/ply.html
"""
import ply.lex as lex
import ply.yacc as yacc
import os
from dataStructures import *
# Superclass for Datalog parser
class Parser:
tokens = ()
precedence = ()
results = ... |
import json
import torch
from .base import *
class BatchConfig(Config):
""" Batch size related parameters. """
train_batch_size = ConfigArg()
""" The effective training batch size.
This is the number of data samples that leads to one step of model
update. :attr:`train_batch_size` is aggregated ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.