content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python -tt
from collections import Counter
import unicodedata
words = []
with open("./all-verbs.txt", "rb") as fh:
words = fh.readlines()
words = [unicodedata.normalize("NFC", item.decode("utf-8").rstrip()) for item in words]
cnt = Counter()
for word in words:
cnt[word] += 1
for item in cnt... |
import matplotlib.pyplot as plt
import numpy as np
from numpy.linalg import norm
import re
import os
import torch
import torchvision.transforms as transforms
import os.path as osp
from torch.utils.data import Dataset
from os import listdir
from os.path import isfile, join
#from Bio.PDB import PDBParser
from src.dataloa... |
"""Methods for saving/loading checkpoints"""
import logging
import typing
from dataclasses import dataclass
from pathlib import Path
import torch
import torch.optim
from vits_train import setup_discriminator, setup_model
from vits_train.config import TrainingConfig
from vits_train.models import MultiPeriodDiscriminat... |
import numpy
from shadow4.syned.shape import Rectangle
from shadow4.syned.element_coordinates import ElementCoordinates
from shadow4.syned.refractors.interface import Interface
from shadow4.physical_models.prerefl.prerefl import PreRefl
from shadow4.beamline.s4_beamline_element import S4BeamlineElement
class S4In... |
from time import sleep
import struct
import hid
FRAME_HEADER = 0x55
CMD_SERVO_MOVE = 0x03
CMD_MULT_SERVO_UNLOAD = 0x14
CMD_MULT_SERVO_POS_READ = 0x15
device = hid.device()
device.open(0x0483, 0x5750) # LOBOT VendorID/ProductID
print(f"Manufacturer: {device.get_manufacturer_string()}")
print(f"Product: {device.ge... |
from abc import ABCMeta, abstractmethod
from typing import Optional
from categories.models import Category
from features.models import SourceType, Tag
class FeatureImporterBase(metaclass=ABCMeta):
@property
@abstractmethod
def source_system(self):
pass
@property
@abstractmethod
def s... |
import argparse
import ConfigParser
import cPickle
import mysql.connector
import time
import sys, os, re
from context import diana
import diana.classes.drug as diana_drug
def main():
options = parse_user_arguments()
design_experiment_dcdb(options)
def parse_user_arguments(*args, **kwds):
"""
Parses... |
from .LetterGrade import LetterGrade
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @FileName: WEWORK_ops.py
# @Software:
# @Author: Leven Xiang
# @Mail: xiangle0109@outlook.com
# @Date: 2021/5/18 16:55
from __future__ import absolute_import, unicode_literals
import os
from pwdselfservice import cache_storage
from ... |
# flake8: noqa
import supriya.synthdefs
import supriya.ugens
def test_SynthDefCompiler_rngs_01():
sc_synthdef = supriya.synthdefs.SuperColliderSynthDef(
"seedednoise",
r"""
arg rand_id=0, seed=0;
RandID.ir(rand_id);
RandSeed.ir(1, seed);
Out.ar(0, WhiteNoise.ar());... |
# -*- coding: utf-8 -*-
"""Make database connection and set Table objects"""
from sqlalchemy import create_engine, Table, MetaData
import config
metadata = MetaData()
def engine():
engine = create_engine('mysql+pymysql://{username}:{password}@{host}/{database}'.format(
username=config.MySQL_DB['username... |
import subprocess
def subprocess_cmd(command, DEBUG=False):
"""execute a bash command and return output"""
if DEBUG:
print "command: " + command
process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
proc_stdout = process.communicate()[0].strip()
if DEBUG:
print "o... |
class CPT:
def __init__(self):
self.name = 'CPT'
def __str__(self):
return self.name |
#! /usr/bin/env python
import os
import numpy as np
import scipy
from astropy.io import fits
from astropy import units as u
import sys
import string
import nrm_analysis
from nrm_analysis.fringefitting.LG_Model import NRM_Model
from nrm_analysis.misctools import utils
from nrm_analysis import nrm_core, InstrumentData... |
import os
from urllib.parse import urlparse
from http.server import BaseHTTPRequestHandler
from .constants import *
from .routes import routes
class Server(BaseHTTPRequestHandler):
def do_GET(self):
for route, filename in routes.items():
if urlparse(self.path).path.lstrip("/") == route.lstrip("... |
from .models import Location, Pokemon, Area, PokemonUser, Region
from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework.validators import UniqueValidator
from django.contrib.auth.password_validation import validate_password
class PokemonSerializer(serializers.ModelSerial... |
import numpy as np
import os
import tensorflow as tf
from matplotlib import pyplot as plt
plt.ioff()
from keras import backend as K
from keras.models import load_model, Model
from keras.layers import Input, Dense, Flatten
from keras.constraints import UnitNorm
from keras.applications import VGG16
from aux_masks imp... |
from django.core import management
from django.test import TestCase
from django.utils import six
class ModelValidationTest(TestCase):
def test_models_validate(self):
# All our models should validate properly
# Validation Tests:
# * choices= Iterable of Iterables
# See: htt... |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# Level | Level for Humans | Level Description
# -------|------------------|------------------------------------
# 0 | DEBUG | [Default] Print all messages
# 1 | INFO | Filter out INFO messages
# 2 ... |
# -*- coding: utf-8 -*-
"""
Created on Dec 20, 2011
@author: Tyranic-Moron
"""
from twisted.plugin import IPlugin
from pymoronbot.moduleinterface import IModule
from pymoronbot.modules.commandinterface import BotCommand, admin
from zope.interface import implementer
from pymoronbot.message import IRCMessage
from pymor... |
#!/usr/bin/env python
# ROS python API
import rospy
import numpy as np
import set_point
import time
import scipy.linalg
import control
from tf.transformations import euler_from_quaternion
# 3D point & Stamped Pose msgs
from geometry_msgs.msg import Point, PoseStamped
from gazebo_msgs.msg import LinkStates
# import all... |
from __future__ import print_function
import tensorflow as tf
from sklearn.neighbors import NearestNeighbors
import numpy as np
from tqdm import tqdm
import time
def nn_dist(train_set, query_set, exclude_self):
# Flatten
train_set = np.reshape(train_set, [train_set.shape[0], -1])
query_set = np.reshape(query_se... |
"""
https://docs.microsoft.com/en-us/graph/api/resources/identityset
"""
from .base_data import BaseData
from .identity import Identity
import attr
@attr.s(auto_attribs=True)
class IdentitySet(BaseData):
"""
The IdentitySet resource is a keyed collection of identity resources.
It is used to represent a s... |
#!/usr/bin/env python
#
#
# 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 (the
#... |
__version__ = '1.0.0b11'
from .performance_list import PerformanceList
from .entity import Entity
from .meet import Meet
from .race import Race
from .runner import Runner
from .horse import Horse
from .jockey import Jockey
from .trainer import Trainer
from .performance import Performance
from .provider import Provider... |
# Copyright European Organization for Nuclear Research (CERN)
#
# 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
#
# Authors:
# - Vincent Garonne, <... |
'''
Description:
Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
Example 1:
Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Example 2:
Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]
Note:
1 <= A.length <= 10000
-1... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import hparams as hp
class StepwiseMonotonicMultiheadAttention(nn.Module):
""" Stepwise Monotonic Multihead Attention
args:
n_heads (int): number of monotonic attention heads
d_model (int): dimension of model... |
# Copyright 2019 DeepMind Technologies Ltd. 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... |
from collections import namedtuple
import numpy as np
import torch
fields = ('state', 'action', 'next_state', 'reward', 'done', 'weight', 'index')
Transition = namedtuple('Transition', fields)
Transition.__new__.__defaults__ = (None,) * len(Transition._fields)
def to_tensor(ndarray, requires_grad=False):
return... |
"""Errors
CarpetBag Errors that might be thrown when problems happen.
"""
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class EmptyProxyBag(Error):
"""Raised when the ProxyBag is empty as we request from it."""
pass
class InvalidContinent(Error):
"""Raised when ... |
import re
from sdmx.model import PACKAGE, MaintainableArtefact
# Regular expression for URNs
URN = re.compile(
r"urn:sdmx:org\.sdmx\.infomodel"
r"\.(?P<package>[^\.]*)"
r"\.(?P<class>[^=]*)=((?P<agency>[^:]*):)?"
r"(?P<id>[^\(\.]*)(\((?P<version>[\d\.]*)\))?"
r"(\.(?P<item_id>.*))?"
)
_BASE = (
... |
# coding: utf-8
# Aluno: Misael Augusto
# Matrícula: 117110525
# Problema: Custo Empregado
salario_base = float(raw_input())
dias_trabalhados = int(raw_input())
transporte_diario = float(raw_input())
custo_transporte = dias_trabalhados * transporte_diario
if salario_base <= 1317.07:
INSS = 0.08 * salario_base
elif 1... |
import datetime
from decimal import Decimal
from textwrap import dedent
from beancount.core.data import Amount, Balance
import pytest
from beancount_dkb import CreditImporter
from beancount_dkb.credit import FIELDS
CARD_NUMBER = '1234********5678'
HEADER = ';'.join('"{}"'.format(field) for field in FIELDS)
def _f... |
# -*- coding: utf-8 -*-
import math
import logging
import numpy as np
import phandim
EPS = 1.0e-4
def invariant(shot, the_range, steps, nr):
"""
Check phantom parameters
Parameters
----------
shot: float
shot position, mm
the_range: (float,float)
... |
from __future__ import absolute_import
from __future__ import print_function
from tqdm import tqdm
import pickle as pkl
import hashlib
import os
import argparse
import pandas as pd
def formatter(x):
try:
x = float(x)
return '{:.1f}'.format(x)
except:
return x
def main():
parser... |
from flask import current_app as app
import random
class Product:
def __init__(
self,
id,
name,
description,
category,
price,
is_available,
creator_id,
image
):
self.id = id
self.name = n... |
# Default Python Libraries
import asyncio
from asyncio.base_events import BaseEventLoop
from multiprocessing.pool import ThreadPool
from .client_service import AristaFlowClientService
from .configuration import Configuration
from .rest_helper import RestPackageRegistry
from .service_provider import ServiceProvider
c... |
# ---------------------------------------------------------------------------
# Unified Panoptic Segmentation Network
#
# Copyright (c) 2018-2019 Uber Technologies, Inc.
#
# Licensed under the Uber Non-Commercial License (the "License");
# you may not use this file except in compliance with the License.
# You may obtai... |
#!/usr/bin/python3
import os
import sys
import csv
import pickle
## Need this line so Atom can run it
os.chdir('/home/andres/Programs/python/covid/scripts')
#print(os.getcwdb())
def load_obj(name):
with open('obj/' + name + '.pkl', 'rb') as f:
return pickle.load(f)
def get_coords(country):
if country... |
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
from torch.autograd import Variable
import numpy as np
import torchvision
from torchvision import datasets, models, transforms
imp... |
x_axis = 0
y_axis = 0
z_axis = 0
f_option = 0
w_option = 0
k_option = 0
m_option = 0
s_option = 0
str_option = 0
slh_option = 0
dis_option = 0
Weapon = []
Jennifer_Dead = False
Jennifer_Body = False
Goblin_Village = True
GoblinK_Maim = False
GoblinP_Maim = False
GoblinP_Dead = False
GoblinK_Dead = False
room2 = False
D... |
import json
import numpy as np
import pandas as pd
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
from sklearn.metrics import mean_absolute_error
from statsmodels.tsa.stattools import adfuller
from scipy import stats
from scipy.stats import normaltest
import statsmodels.api as sm... |
from csv import reader
from requests import get, exceptions
from datetime import datetime
import pandas as pd
# Todo import
from .constantes import *
from .excepciones import *
class Codavi:
"""
Codavi ofrece datos y estadísticas sobre el COVID-19 en toda la Argentina.
"""
def __fecha_actual(self, for... |
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth import views as auth_views
from homes.views import HomePageView, CustomRegistrationView
from homes.forms import CustomAuthenticationForm
admin.site.site_header = 'Django Property'
urlpatterns = [
url(r'^admin/', a... |
print("hello world")
print("helo mans")
print("i guess its working") |
from yt.testing import \
fake_random_ds, \
assert_equal
from yt.units.yt_array import \
uconcatenate
def _get_dobjs(c):
dobjs = [("sphere", ("center", (1.0, "unitary"))),
("sphere", ("center", (0.1, "unitary"))),
("ortho_ray", (0, (c[1], c[2]))),
("slice", (0, c[0... |
#!/usr/bin/env python
# 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
# (the "Licen... |
#!/usr/bin/env python
'''
given two groups of samples, assess their ability to be correctly classified using MS loci
'''
import argparse
import logging
import sys
import cyvcf2
import intervaltree
REMOVE_CHR=True
def populate_intervals(panels, vdx, vcf, name, group, pass_only, loci):
logging.info('processing %s... |
from typing import List, Union, Tuple
from darts.commands import AddScore, ScoreValue
class ScoreTextInput:
"""This will handle the logic behind the text entry for scores."""
def __init__(self):
self.scores: List[Union[str, Tuple[str, str]]] = ['']
def __str__(self):
return ' + '.join(f... |
#!/usr/bin/env python3
import base64
import hashlib
import os
import sys
def main(*filenames: str):
for filename in filenames:
with open(filename, 'rb') as f:
h = hashlib.sha3_384(f.read())
new_name = base64.urlsafe_b64encode(h.digest()).decode('utf-8')
print(f"{filename} -> {... |
#!/usr/bin/env python
from azure_storage.methods import copy_blob, create_parent_parser, delete_container, delete_file, delete_folder, \
extract_common_path, move_prep, setup_arguments
from argparse import ArgumentParser, RawTextHelpFormatter
import coloredlogs
import logging
import sys
import os
clas... |
print('Valores de b:')
print('-------------')
print('1) b = 7')
print('2) b = 7')
print('3) b = 00000000000000000007')
print('4) b = 7 ')
print('5) b = 7%')
print()
print('Valores de d:')
print('-------------')
print('1) d = 2.208000')
print('2) d = 2')
print('3) d = 2.2')
print('4)... |
import os
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('source_path', help="Path to the video or audio file")
parser.add_argument('-o', '--output',
help="Output path for subtitles (by default, subtitles are saved in \
the same directory and name as... |
from ._registry import DATALOADERS
from torch.utils.data import DataLoader
@DATALOADERS.register
class DataListLoader(DataLoader):
r"""Data loader which merges data objects from a
:class:`torch_geometric.data.dataset` to a python list.
.. note::
This data loader should be used for multi-gpu suppo... |
#=======================================================================
# Title: Python script to compare diBELLA and BELLA (alignment) output
# Author: G. Guidi
# Date: 11 Feb 2019
#=======================================================================
# Run: python3 checkOutput.py <file1> <file2>
# file1 is sup... |
# coding: utf-8
# pip3 install spidev
# AI開始ボタン
import os
_FILE_DIR=os.path.abspath(os.path.dirname(__file__))
import spidev
import time
import sys
import subprocess
from subprocess import Popen
from lib.led import LED
from lib.spi import SPI
# 開始ボタンのSPI接続コネクタ番号
A1 = 1
A2 = 2
START_BUTTON_SPI_PIN = A1
TEST_BUTTON_SP... |
from .Peer import Peer
from .PeerNetwork import PeerNetwork
from .NetworkHandler import NetworkHandler
|
from django.test import TestCase
from .views import get_dog
class DogTestCase(TestCase):
def test_get_dog(self):
self.assertNotEqual(get_dog(), None)
|
import time
import board
import busio
import adafruit_character_lcd.character_lcd_rgb_i2c as character_lcd
lcd_columns = 16
lcd_rows = 2
i2c = busio.I2C(board.SCL, board.SDA)
lcd = character_lcd.Character_LCD_RGB_I2C(i2c, lcd_columns, lcd_rows)
#lcd.color = [100, 0 , 0]
lcd.message = " Hello!"
time.sleep (1)
lcd.cle... |
import os
import sys
import shutil
from distutils.dir_util import copy_tree
from zipfile import ZipFile
def removeDirectory(filePath):
if os.path.isdir(filePath):
t = shutil.rmtree(filePath)
def copyFile(src, dest):
srcPath, ext = os.path.splitext(src)
# zipが放り込まれたら解凍してからファイル移動する
if ext == '... |
__all__ = [ 'x', 'y', 'z']
w = 'w'
x = 'x'
y = 'y'
z = 'z'
|
from PIL import Image
import numpy as np
from configuration import *
val_percentage = 0.05
img_list = os.listdir(train_dir)
img_list = np.random.permutation(img_list)
val_data_num = int(len(img_list) * val_percentage)
train_data = img_list[val_data_num:]
val_data = img_list[:val_data_num]
for i, t in enumerate(tr... |
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incor... |
#
# Copyright 2016 The BigDL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
# app.py
from flask import Flask, jsonify, request, render_template
app = Flask(__name__)
######## Example data, in sets of 3 ############
data = list(range(1,300,3))
print (data)
######## HOME ############
@app.route('/')
def test_page():
example_embed='Sending data... [this is text from python]'
# look in... |
from flask import Flask, Blueprint
from flask_sockets import Sockets
html = Blueprint(r'html', __name__)
ws = Blueprint(r'ws', __name__)
@html.route('/')
def hello():
return 'Hello World!'
@ws.route('/echo')
def echo_socket(socket):
while not socket.closed:
message = socket.receive()
socket... |
# explorer_panels.py
#
# This file is part of scqubits.
#
# Copyright (c) 2019 and later, Jens Koch and Peter Groszkowski
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
###############################... |
import time
from pycompss.api.api import compss_barrier
def measure(name, dataset_name, model, x, y=None):
print("==== STARTING ====", name)
compss_barrier()
s_time = time.time()
model.fit(x, y)
compss_barrier()
print("==== OUTPUT ==== ", dataset_name, time.time() - s_time)
|
import sys
sys.path.insert(0, '/srv/wcdo/src_viz')
from dash_apps import *
#### DATA ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
dash_app1 = Dash(__name__, server = app, url_base_pathname= webtype + '/language_territories_mapping/', external_stylesheets=external_stylesheets, external_scripts... |
print('=-='*20)
print('Analisador de Triângulo')
print('=-='*20)
a = float(input('Informe o primeiro lado :'))
b = float(input('Informe o segundo lado: '))
c = float(input('Informe o terceiro lado: '))
if a < b + c and b < a + c and c < a + b:
print('Pode ser um triângulo')
else:
print('Não pode ser um triângu... |
from . import *
from bfg9000.tools.doppel import Doppel
class TestDoppel(ToolTestCase):
tool_type = Doppel
def test_env(self):
with mock.patch('bfg9000.shell.which', return_value=['command']):
self.assertIsInstance(self.env.tool('doppel'), Doppel)
def test_kind_args(self):
s... |
from autokeras.image.image_supervised import ImageClassifier, ImageRegressor
from autokeras.text.text_supervised import TextClassifier, TextRegressor
from autokeras.net_module import CnnGenerator, MlpModule |
from dynamic_fixtures.fixtures.basefixture import BaseFixture
class Fixture(BaseFixture):
pass
|
import os
TITLE = "epg-grabber"
EPG_XMLTV_TIMEFORMAT = "%Y%m%d%H%M%S"
CONFIG_REGEX = r"^[-\w\s]+(?:;[-.&\w\s]*)$"
PERIOD = "."
SITES_DIR = "sites"
METADATA_DIR = os.path.join(SITES_DIR, "channels_metadata")
CONFIG_DIR = os.path.join(SITES_DIR, "channels_config")
EMPTY_CONFIG_ERROR_MESSAGE = """
The URL {config_url} d... |
##########################################################################################
# Wislight lightbulb commands
##########################################################################################
import pexpect, time, argparse
class BulbWislight():
DEVICE = "98:7B:F3:6C:0E:09"
color = [0,0,0... |
from unittest import TestCase
from esrally import exceptions
from esrally.utils import versions
class VersionsTests(TestCase):
def test_is_version_identifier(self):
self.assertFalse(versions.is_version_identifier(None))
self.assertFalse(versions.is_version_identifier(""))
self.assertFalse... |
#coding: utf-8
'''
Machinery needed to register 'UCS' encoding as a valid python encoding.
To use UCS encoding, `ucs_codec.register_UCS()`
Created on Feb 4, 2016
@author: mike
'''
from __future__ import print_function, unicode_literals
import codecs
from cslavonic.ucs_decode import ucs_encode, ucs_decode
### Codec ... |
import pytest
from tests.mocks import MockOktaClient
from okta.models import DomainResponse
class TestDomainResource:
"""
Integration Tests for the Domain Resource
"""
@pytest.mark.vcr()
@pytest.mark.asyncio
async def test_list_domains(self, fs):
client = MockOktaClient(fs)
do... |
"""
Database Input / Output functions
"""
import pandas as pd
import pymysql
import IEDC_pass
def db_conn(fn):
"""
Decorator function to provide a connection to a function. This was originally inspired by
http://initd.org/psycopg/articles/2010/10/22/passing-connections-functions-using-decorator/
T... |
"""Pytest conftest fixtures."""
import os
import sys
import pytest
from prometheuspvesd.utils import Singleton
@pytest.fixture(autouse=True)
def reset_singletons():
Singleton._instances = {}
@pytest.fixture(autouse=True)
def reset_os_environment():
os.environ = {}
@pytest.fixture(autouse=True)
def reset... |
import numpy as np
import pandas as pd
from scipy.spatial.transform import Rotation
g = 9.80665 # m per sec^2
### Utilities functions ###
# check for axis of specified length and return its position
def matchAxis(shape,l=3):
if l not in shape:
print("No axis of length ",l)
return None
# find... |
from django.urls import path
# Create your views here.
from . import views
urlpatterns = [
path("signup/", views.SignUpView.as_view(), name="signup"),
]
|
# coding:utf-8
import json
import pandas as pd
import time
def read_acc_value(f) :
data = open(f).read()
accValues = json.loads(data)['accValues']
X = []
Y = []
for x, y in accValues:
t = time.localtime(x / 1000)
x = time.strftime("%Y-%m-%d", t)
X.append(x)
Y.append... |
# https://leetcode.com/problems/sort-colors/
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
# for i in range(0,len(nums)):
i = 0
iterator = 0
while it... |
''' orchestration module '''
''' imports '''
# functions
#from .funcs import func
import numpy as np
'''
'''
''' orchestration functions '''
def func(var):
''' var
Args:
var (np.array): track buffer
Returns:
(np.array): var
'''
# return
return var
|
import numpy as np
import awkward
from awkward import JaggedArray
#for later
#func = numbaize(formula,['p%i'%i for i in range(nParms)]+[varnames[i] for i in range(nEvalVars)])
def convert_jec_txt_file(jecFilePath):
jec_f = open(jecFilePath,'r')
layoutstr = jec_f.readline().strip().strip('{}')
jec_f.close(... |
import types
__docformat__ = "restructuredtext"
def walk_recursive_generators(generator):
"""Walk a tree of generators without yielding things recursively.
Let's suppose you have this:
>>> def generator0():
... yield 3
... yield 4
...
>>> def generator1():
... yield 2
... |
import os
import random
import itertools
import numpy as np
import torch
import torch.nn as nn
import torch.utils.data
import torchvision.transforms as transforms
from torchvision.utils import make_grid
from torch.autograd import Variable
from PIL import Image
import matplotlib.pyplot as plt
from tensorboardX import Su... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2018 all rights reserved
#
"""
Exercise building subvectors out of existing vectors
"""
def test():
# package access
import gsl
# pick a size
n = 20
# make one
v = gsl.vector(shape=n)
# fill... |
import argparse
import json
from pathlib import Path
from PIL import Image
INFO = {
"contributor": "",
"date_created": "",
"description": "",
"url": "",
"version": "",
"year": ""
}
LICENSES = [
{
"name": "",
"id": 0,
"url": ""
}
]
CATEGORIES = [
{
'id': 1,
'na... |
# SPDX-License-Identifier: Apache-2.0
from io import BytesIO
import numpy as np
import onnx # noqa
from onnx import shape_inference, TensorProto
from onnx.numpy_helper import from_array, to_array
from onnx.helper import make_tensor
from ..proto.onnx_helper_modified import (
make_node, make_tensor_value_info, mak... |
import glob
import os
import shutil
target_path = "/observations/solarnet-campaign/homogenization/catania"
os.makedirs(target_path, exist_ok=True)
for f in glob.glob("/observations/solarnet-campaign/ftp.oact.inaf.it/Romano/SOLARNET_SPRING/**/*.fts", recursive=True):
shutil.move(f, os.path.join(target_path, os.pat... |
# 也是二分法
class Solution:
def mySqrt(self, x: int) -> int:
if x < 2:
return x
left, right = 2, x // 2 + 1
while left <= right:
mid = left + (right - left) // 2
if mid * mid > x:
right = mid - 1
elif mid * mid < x:
... |
```You are given a data structure of employee information, which includes the employee's unique id, their importance value and their direct subordinates' id.
For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then empl... |
"""
Move data from ingestion to production
"""
import requests
from b2stage.endpoints.commons.b2handle import B2HandleEndpoint
from restapi import decorators
from restapi.connectors import celery
from restapi.utilities.logs import log
from seadata.endpoints.commons.cluster import ClusterContainerEndpoint
from seadata.e... |
#!/usr/bin/env python
"""
Copyright (c) 2006-2021 sqlmap developers (http://sqlmap.org/)
See the file 'LICENSE' for copying permission
"""
try:
import mimerpy
except:
pass
import logging
from lib.core.common import getSafeExString
from lib.core.data import conf
from lib.core.data import logger
from lib.core... |
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import argparse
from datetime import datetime
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
from torch.autograd import Variable
from torchvision import datasets, transforms
import matplotlib
m... |
'''
Rolien e Naej são os desenvolvedores de um grande portal de programação. Para ajudar no novo sistema de cadastro do site, eles requisitaram a sua ajuda. Seu trabalho é fazer um código que valide as senhas que são cadastradas no portal, para isso você deve atentar aos requisitos a seguir:
A senha deve conter, no mí... |
"""Db tools."""
import csv
import json
import os
from datetime import datetime
from typing import Dict, List
import boto3
from botocore import config
from covid_api.core.config import DT_FORMAT, INDICATOR_BUCKET
from covid_api.models.static import IndicatorObservation
s3_params = dict(service_name="s3")
lambda_para... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.