content stringlengths 5 1.05M |
|---|
def task_report_deps():
"""report dependencies and changed dependencies to a file
"""
return {
'file_dep': ['req.in', 'req-dev.in'],
'actions': ['echo D: %(dependencies)s, CH: %(changed)s > %(targets)s'],
'targets': ['report.txt'],
}
|
def binary_search(ds, low, high, key):
print('ds:',ds)
print('low:', low)
print('high:', high)
mid = (high + low) // 2
if low > high:
return None
elif key == ds[mid]:
return mid
elif key < ds[mid]:
return binary_search(ds, low, mid - 1, key)
else:
return ... |
import unittest
from kubernetes.client import V1APIResource
from k8s_handle.exceptions import ProvisioningError
from k8s_handle.transforms import split_str_by_capital_letters
from .adapters import Adapter, AdapterBuiltinKind, AdapterCustomKind
from .mocks import K8sClientMock, CustomObjectsAPIMock, ResourcesAPIMock
... |
from nose.tools import assert_equals, assert_true, assert_false
from ..mdp import MDP
class TestMDP:
def test_mdp_solver_value_iteration_linear_mdp(self):
"""
Value iteration should find optimal V(s) for a simple linear MDP
"""
m = MDP()
a_forward = m.add_action('forward')
m.add_transition('s0', a_forwa... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import MySQLdb
import conf
class MySqlHelper(object):
def __init__(self):
self.conn_dict = dict(conf.conn_dict) #导入链接数据库字符串
#{host:'192.168.75.133',user:'zhangyage',passwd:'zhangyage',db:'oldboy'}
def Get_Dict(self,sql,params): ... |
from enum import Enum
from enum import auto
from typing import Optional
from typing import Mapping
from typing import Sequence
import forsyde.io.python.core as core
class VertexTrait(core.Trait, Enum):
{%- for type_name, type_data in vertexTraitSuper.items() %}
{{type_name}} = auto()
{%- endfor %}
@classmeth... |
import sys
from itertools import chain
import pathlib
from wheel.bdist_wheel import (
get_abi_tag,
get_platform as get_platform_tag,
)
from wheel.wheelfile import WheelFile
def remove_source_files(input_folder):
in_fd = pathlib.Path(input_folder)
if not in_fd.is_dir():
raise RuntimeError(f'in... |
import numpy as np
import pandas as pd
from flask_cors import cross_origin
from flask import Flask, request, render_template
import pickle
app = Flask(__name__)
@cross_origin()
@app.route('/')
def home():
return render_template('index.html')
@cross_origin()
@app.route('/predict',methods=['POST'])
d... |
#!/usr/bin/env python3
import sys
from jinja2 import Environment, FileSystemLoader
from pprint import pprint
from webob import Request, Response
dispatch = {
'/': 'index.html',
'/index.html': 'index.html',
'/about/aboutme.html': 'about/aboutme.html',
'/github.css': ... |
import frappe
from frappe import _
@frappe.whitelist()
def add_bill_amount(item):
r = frappe.db.get_value("Food Item",item,["name","subsidy_rate","original_rate","limit"])
return r |
#!/usr/bin/env python3
import os
import sys
import logging
from p1204_3.generic import VIDEOPARSER_REPO
def __video_parser_dir():
this_path = os.path.dirname(os.path.realpath(__file__))
return os.path.join(
this_path,
"bitstream_mode3_videoparser",
)
def run_videoparser(video_segment_fi... |
#!/bin/env python
"""
Copyright 2010-2019 University Of Southern California
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 applicabl... |
from mxnet.gluon.loss import Loss
from mxnet.gluon.loss import _reshape_like
from mxnet.gluon.loss import _apply_weighting
class MeanSquareLoss(Loss):
def __init__(self, weight=1., batch_axis=0, **kwargs):
super(MeanSquareLoss, self).__init__(weight, batch_axis, **kwargs)
def hybrid_forward(self, F, p... |
import os
import zipfile
#Check root user
if os.geteuid() != 0:
exit("You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'. Exiting.\nExample : sudo python <filename>.py")
#Store all file name in array
Mylist = os.listdir('.')
#Get the number size of array
tfile = int(len... |
from __future__ import annotations
import cmath
from typing import Optional
import numpy as np
import psutil
import ray
import scipy.special as ssp
from pymwm.utils import coax_utils
from pymwm.waveguide import Database, Sampling, Waveguide
from .samples import Samples, SamplesForRay, SamplesLowLoss, SamplesLowLoss... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""ConvNeXt models.
"""
from __future__ import annotations
from functools import partial
from typing import Optional
from typing import Union
import torch
import torch.nn.functional as F
from torch import nn
from torch import Size
from torch import Tensor
from torch.nn.... |
# -*- coding: utf-8 -*-
"""Neural_Machine_Translation_Attention.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1f7uW5_n27jMXhZBpwll0eyHF543SVmRm
# Neural Machine Translation with Attention
- This uses seq2seq model.
- RNN based encoder. Again ... |
"""
Module:
unicon.plugins.generic
Authors:
pyATS TEAM (pyats-support@cisco.com, pyats-support-ext@cisco.com)
Description:
Module for defining all the Statements and callback required for the
Current implementation
"""
import re
from time import sleep
from unicon.eal.dialogs import Statement
from unic... |
# -*- coding: utf-8 -*-
import warnings
from .helper import Helper
from .table import Table
from ..outputs import NullOutput
class TableHelper(Helper):
"""
Provides helpers to display table output.
"""
LAYOUT_DEFAULT = 0
LAYOUT_BORDERLESS = 1
LAYOUT_COMPACT = 2
def __init__(self):
... |
from output.models.nist_data.atomic.g_month_day.schema_instance.nistschema_sv_iv_atomic_g_month_day_max_exclusive_5_xsd.nistschema_sv_iv_atomic_g_month_day_max_exclusive_5 import NistschemaSvIvAtomicGMonthDayMaxExclusive5
__all__ = [
"NistschemaSvIvAtomicGMonthDayMaxExclusive5",
]
|
#!/usr/bin/python3
import sqlite3
import cgi, cgitb
import json
from urllib.request import urlopen
print("Content-Type: text/html")
print()
conf = {}
with open("../admin/qsdb.conf", mode="rt") as fl:
for line in fl:
line = line.strip().strip(" ")
if len(line) < 1 or line[0] == "#": continue
... |
def order_search(item, items: list):
if not isinstance(items, list):
print(f'The items {items} MUST be of type list')
return
items.sort()
size = len(items) - 1
lower = 0
upper = size
while lower <= upper:
mid = (upper + lower) // 2
if item == items[mid]:
... |
def main():
# input
n = int(input())
# cmpute
ans, i = [], 1
while i+1 <= n:
i += 1
x = i
if x%3==0 or x%10==3:
ans.append(i)
while x:
x //= 10
# output
for i in range(len(ans)):
print(f' {ans[i]}', end='')
if __name__ == '__main__':
main()
|
from pexels_api import API
import os
# Init api object with your Pexels API key
API_KEY = os.environ.get("PEXELS_API_KEY")
api = API(API_KEY)
# Search 'koala' photos
api.search("koala")
print("Total results: ", api.total_results)
# Loop all the pages
while True:
# Get all photos in the page
photos = api.get_ent... |
#/ Type: UI
#/ Name: Channel Calculator
#/ Authors: Joe Petrus and Bence Paul
#/ Description: This is an example that lets you create a channel from existing channels
#/ References: None
#/ Version: 1.0
#/ Contact: support@iolite-software.com
from iolite.QtGui import QAction, QLabel, QLineEdit, QCompleter, QDialog, QH... |
# See pybullet quickstart guide here:
# https://docs.google.com/document/d/10sXEhzFRSnvFcl3XxNGhnD4N2SedqwdAvK3dsihxVUA/edit#
# Create a Tiltbrush-like app, drawing lines using any controller
# Line width can be changed
import pybullet as p
CONTROLLER_ID = 0
POSITION = 1
ORIENTATION = 2
BUTTONS = 6
#assume that the ... |
from werkzeug.serving import run_simple
# from inquire_sql_backend.server_annoy import app
from inquire_sql_backend.server_nms import app
if __name__ == '__main__':
run_simple("0.0.0.0", port=9000, application=app)
|
# -*- coding: utf-8 -*-
import unittest
from openprocurement.auctions.core.tests.base import snitch
from openprocurement.auctions.geb.tests.base import (
BaseWebDocsTest
)
from openprocurement.auctions.geb.tests.blanks.create import (
create_auction_dump
)
from openprocurement.auctions.geb.tests.blanks.draft ... |
from typing import Dict
from requests.exceptions import RequestException
import requests, json
class AirbyteApiCallerException(Exception):
pass
class AirbyteApiCaller:
def api_call(self, endpoint: str, body: Dict[str, str] = None):
"""
Generic `api caller` for contacting Airbyte
"""... |
import torch
from data import TestDataset
import numpy as np
from network import Discriminator,Generator
from torch.autograd import Variable
import time
from utils import *
import importlib
import argparse
test_time = False
def parse_args():
parser = argparse.ArgumentParser( description = "bicubic" )
pa... |
# coding=utf-8
# --------------------------------------------------------------------------
# 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 ... |
import os
import numpy as np
from numpy.lib.function_base import disp
import torch
import decord
from PIL import Image
from torchvision import transforms
from random_erasing import RandomErasing
import warnings
from decord import VideoReader, cpu
from torch.utils.data import Dataset
import video_transforms as video_tra... |
def exec_proj(name):
__import__(name)
|
# Scrapy settings for SWE_Project project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://docs.scrapy.org/en/latest/topics/settings.html
# https://docs.scrapy.org/en/latest/topics/downloader-middle... |
#!/usr/bin/env python
from AudioPython import *
from AudioPython.dsp import *
import sys
def test_pink_noise():
channels = ((pink_noise(amplitude=0.01),),)
samples = compute_samples(channels)
for i in range(1000):
yield_raw(samples)
if __name__ == "__main__":
test_pink_noise()
|
data_dir = '/home/cn/data/sample_tick/'
import os
import shutil # higher level file operations - more choices for error handling
os.path.join('usr', 'bin', 'spam') # join path
cur_dir = os.getcwd() # current working dir
os.chdir('/tmp'); os.getcwd() # move around
os.chdir('/home/cn/program/python/sandbox');
os.ge... |
# -*- coding: utf-8 -*-
# @Time : 2018/11/4 15:32
# @Author : QuietWoods
# @FileName: evaluate.py
# @Software: PyCharm
""" evaluation scripts"""
import re
import os
from os.path import join
import logging
import tempfile
import subprocess as sp
from cytoolz import curry
from pyrouge import Rouge155
from pyrouge.... |
import requests
import config
import re
def login_to_vk(username, password):
session = requests.Session()
first_page = session.get(config.VK_MAIN_PAGE).text
ip_h = re.compile(r'ip_h=(.+?)&').search(first_page).group(1)
lg_h = re.compile(r'lg_h=(.+?)&').search(first_page).group(1)
data_to_send = config.VK_POST... |
"""using the different database object in the settings.
So the Spanglish app uses a different database / server
than other apps.
"""
import logging
logger = logging.getLogger('spanglish')
APP_LABEL = 'spanglish'
DB = 'spanglish'
class DBRouter(object):
"""A router to control Q and Devops db operations."""
... |
import os
import re
from loguru import logger
from flexget import plugin
from flexget.event import event
logger = logger.bind(name='rtorrent_magnet')
pat = re.compile('xt=urn:btih:([^&/]+)')
class PluginRtorrentMagnet:
"""
Process Magnet URI's into rtorrent compatible torrent files
Magnet URI's will l... |
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 13 02:12:00 2021
@author: J
"""
import time
import cv2
import numpy as np
class ObjectDetection:
def __init__(self):
self.MODEL = cv2.dnn.readNet(
'models/yolov3-tiny.weights',
'models/yolov3-tiny.cfg'
)
self.CLASSES =... |
"""
Implement weak defense model for Athena on top of IBM ART.
It wraps a keras model to a weak defense in Athena ensemble.
@author: Ying Meng (y(dot)meng201011(at)gmail(dot)com)
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import numpy as np
import six
from ar... |
import os
from flask import send_file
from slerp.logger import logging
from slerp.validator import Number, Blank
from entity.models import Document
log = logging.getLogger(__name__)
class DocumentService(object):
def __init__(self):
super(DocumentService, self).__init__()
@Blank(['filename', 'mimetype', 'fol... |
#pylint: disable=W0703, R0912,W0105
'''
Copyright 2014 eBay Software Foundation
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 ap... |
""" main
This module contains a collection of YANG definitions
for sanity package.
This module contains definitions
for the following management objects\:
Copyright (c) 2013\-2014 by Cisco Systems, Inc.
All rights reserved.
"""
import re
import collections
from enum import Enum
from ydk.types import Empty, YL... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from datetime import datetime
import click
from loguru import logger
from colorama import init, Fore
VERSION = Fore.YELLOW + "2.0.0" + Fore.RESET
VERSION_NAME = Fore.GREEN + "Brazen Beaver" + Fore.RESET
VERSION_ART = f"""
___
.=" "=... |
import sys
import hashtable
# defaults
N = 1000
m = 10
func = "f2"
filename = "plot.png"
if len(sys.argv) == 5:
N = int(sys.argv[1])
m = int(sys.argv[2])
func = sys.argv[3]
filename = sys.argv[4]
# get our hashfunc
if func == "f1":
h = hashtable.h_mod(m)
elif func == "f2":
h = hashtable.h_mul(... |
__version__ = '1.0.1'
from platformer import PlatformerApp
if __name__ == "__main__":
PlatformerApp().run()
|
# -*- coding: utf-8 -*-
from django.contrib import admin
from library.models import PressReview, PressReviewForm
class PressReviewAdmin(admin.ModelAdmin):
form = PressReviewForm
list_display = ('date', 'link',)
search_fields = ('date',)
admin.site.register(PressReview, PressReviewAdmin)
|
# ===============================================================================
# Copyright 2011 Jake Ross
#
# 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/licens... |
# --------------------------
# UFSC - CTC - INE - INE5603
# Exercício calculos
# --------------------------
# Classe responsável pela interação com o usuário
from view.menu import Menu
from view.paineis.painel_media3 import PainelMedia3
from view.paineis.painel_soma3 import PainelSoma3
from view.paineis.painel_par imp... |
import sys
print("example_venv_base_simple.py", "execution")
path = sys.base_prefix if hasattr(sys, "base_prefix") else sys.prefix
print(path, sys.prefix)
|
"""
Создать класс TrafficLight (светофор).
определить у него один атрибут color (цвет) и метод running (запуск);
атрибут реализовать как приватный;
в рамках метода реализовать переключение светофора в режимы: красный, жёлтый, зелёный;
продолжительность первого состояния (красный) составляет 7 секунд, второго (жёлтый) —... |
# --------------------------------------------------------
# Deep Iterative Matching Network
# Licensed under The Apache-2.0 License [see LICENSE for details]
# Written by Gu Wang, Yi Li
# --------------------------------------------------------
"""
generate rendered from rendered poses
generate (observed rendered) pai... |
# -*- coding: UTF-8 -*-
class PandasticSearchException(RuntimeError):
def __init__(self, msg):
super(PandasticSearchException, self).__init__(msg)
class NoSuchDependencyException(PandasticSearchException):
pass
class ServerDefinedException(PandasticSearchException):
pass
class ParseResultExc... |
import debug_toolbar
from django.conf.urls import url, include
urlpatterns = [url(r"^", include(debug_toolbar.urls))]
|
kgVegetable = float(input())
kgFruit = float(input())
sumVegetable = int(input())
sumFruit = int(input())
priceVegetable = kgVegetable * sumVegetable
priceFruit = kgFruit * sumFruit
bgl = priceVegetable + priceFruit
eur = bgl / 1.94
print(priceVegetable)
print(priceFruit)
print(eur) |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-24 18:11
from __future__ import unicode_literals
from __future__ import absolute_import
from django.core.management import call_command
from django.db import migrations
from corehq.privileges import REPORT_BUILDER_5
def _grandfather_reportbuilder_5_pr... |
import unittest
import test_utils
from gcp_census.bigquery.bigquery_table_metadata import BigQueryTableMetadata
from gcp_census.bigquery.transformers.partition_metadata_v1_0 import \
PartitionMetadataV1_0
class TestPartitionMetadataV1_0(unittest.TestCase):
def test_transforming_table_without_labels(self):
... |
'''Trains a simple sentiment analysis model.
'''
from __future__ import print_function
import numpy as np
np.random.seed(42)
import tensorflow as tf
tf.set_random_seed(42)
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers i... |
# Copyright 2021, Mycroft AI 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 agreed to in writi... |
from model import Igra, bazen_besed
import random
def izpis_igre(igra):
if not igra.zmaga() and not igra.poraz():
return "Nadaljujmo z igro."
return None
def izpis_zmage(igra):
if igra.zmaga():
return "Zmagali ste!"
return None
def izpis_poraza(igra):
if igra.poraz():
ret... |
from dataclasses import replace
from decimal import Decimal
import pytest
from pricehist.price import Price
from pricehist.series import Series
@pytest.fixture
def series():
return Series(
"BASE",
"QUOTE",
"type",
"2021-01-01",
"2021-06-30",
[
Price("2... |
import z3
from variable import Var
from valuation import Valuation
class Formula:
def __init__(self, valuation=None, disabled=None):
self._domain = set()
self._assertions = []
if valuation is not None:
self.assert_valuation(valuation)
if disabled is not None:
... |
import logging
import fnmatch
from typing import Set, Optional, Union, List
from checkov.common.util.consts import DEFAULT_EXTERNAL_MODULES_DIR
class RunnerFilter(object):
# NOTE: This needs to be static because different filters may be used at load time versus runtime
# (see note in BaseCheckRegistery... |
# http://adventofcode.com/2016/day/11
import copy
import itertools
import re
POSSIBLE_ITEMS_IN_ELEVATOR = [1, 2]
ALL_SEEN_STATES = set()
class Generator(object):
def __init__(self, t):
self.type = t
def __repr__(self):
return "%s generator" % self.type
def __eq__(self, other):
... |
# Software License Agreement (BSD License)
#
# Copyright (c) 2012, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above... |
"""Main module."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Union
@dataclass
class Img:
name: str
size: int = 0
@dataclass
class ImgNode:
img: Img
prev: Union[ImgNode, None] = None
next: Union[ImgNode, None] = None
def chain_prev(self, ... |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Provides the web interface for displaying an overview of Pinpoint."""
from dashboard.pinpoint import request_handler
class MainHandler(request_handler.... |
# coding=utf-8
# --------------------------------------------------------------------------
# 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 ... |
import collections
from typing import List, Tuple
class Report:
"""
A column-based report outputing data from the system.
Composed of a ReportHeader and ReportBody, which in turn
contains multiple ReturnLine objects.
"""
def __init__(self, data: List[Tuple], titles: List) -> None:
sel... |
import sys
sys.path.append("../")
from ucsdpcb import PcbPlacer, PcbRouter, PcbDB
db = PcbDB.kicadPcbDataBase('../module/PCBBenchmarks/bm9/bm9.routed.kicad_pcb')
db.printNodes()
placer = PcbPlacer.GridBasedPlacer(db)
placer.set_num_iterations(1)
placer.set_iterations_moves(1)
placer.test_placer_flow()
db.printNodes()
... |
from common import config
from common import util
class entityObject(object):
"""Read YAML config file to get access info
(device ip, tcp port, user name, keys, etc)
"""
def __init__(self, entities_yml_file=config.cfg.entities_yml_file, *args, **kwargs):
self.entities_yml_file = entities_yml_... |
# -*- coding: utf-8 -*-
import numpy as np
import copy
from pyJaya.consts import minimaxType
from pyJaya.population import Population
class JayaBase(object):
"""Jaya base class
Args:
numSolutions (int): Number of solutions of population.
listVars (list): Range list.
functionToEvaluat... |
import torch
def gather_elementwise(tensor, idx_tensor):
'''
For `tensor.shape = tensor_shape + (K,)`
and `idx_tensor.shape = tensor_shape` with elements in {0,1,...,K-1}
'''
return tensor.gather(-1, idx_tensor[..., None])[..., 0]
|
# -*- 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... |
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import random
import caffe
from lib import run_net
from lib import score_util
from datasets.cityscapes import cityscapes
net = caffe.Net('../nets/stage-cityscapes-fcn8s.prototxt',
'../nets/cityscapes-fcn8s-heavy.caffemodel',
... |
from XiguaUser_pb2 import User as UserPb
class User:
def __init__(self, json=None):
self.ID = 0
self.name = ""
self.brand = ""
self.level = 0
self.type = 0
self.block = False
self.mute = False
if json:
if type(json) == bytes:
... |
from arena import Arena
from agent import HAgent, AAgent
from helper import *
from trainer import qtrainer
from environment import Env
import random
import numpy as np
import matplotlib.pyplot as plt
if __name__ == '__main__':
# init size, num_humans, num_targets, amount of half cover
# np.random.seed(1234)
... |
'''
General information for compound and reaction naming and formatting.
'''
from pathlib import Path
# get the path of the project folder
# (one directory above that of this script)
path = Path(__file__)
script_dir = path.parent
parent = script_dir.parents[1]
# to be implemented
# import pandas as pd
# compound_info... |
from typing import Type
from unittest import mock
import copy
from src.database import settings
from pytest import raises
def generate_setting_cls(validate_return: bool) -> Type[settings.Setting]:
class Foo(settings.Setting):
set_was_called = False
@staticmethod
def _validate_input(*arg... |
# Copyright (c) 2012, Willow Garage, Inc.
# All rights reserved.
#
# Software License Agreement (BSD License 2.0)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the a... |
# Generated by Django 3.2 on 2022-03-11 15:44
import datetime
import django.db.models.deletion
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
("workspaces", "0002_alter_notionworkspace_icon_url"),
("tasks", ... |
import Python_API #Initializes Runtime
from jnius import autoclass
from Python_API.DataTypes.LongType import LongType
input_handler_send_proxy = autoclass("org.wso2.siddhi.InputHandlerSendProxy")
class InputHandler(object):
def __init__(self):
raise NotImplementedError("Initialize InputHandler using Exec... |
"""
Helper functions for working with the NGA flatfile.
"""
# stdlib imports
import os
import pkg_resources
import logging
# third party imports
import numpy as np
import pandas as pd
from obspy.geodetics.base import gps2dist_azimuth
def get_nga_record_sequence_no(st, eq_name, distance_tolerance=50):
"""
Re... |
print("""
089) Crie um programa que leia nome e duas notas de vários alunos e guarde
tudo em uma lista composta. No final, mostre um boletim contendo a média de
cada um e permita que o usuário possa mostrar as notas de cada aluno
individualmente.
""")
alunos = []
indice = 0
titulo = ' Sistema de Cadastro e Visualizaçã... |
import warnings
from itertools import chain
from typing import Tuple, List, Dict, Set
from .model import CleanAccount
from ...load.balances import Account, Snapshot
from ...load.transactions import Transaction
from ...log import logger
try:
# private configuration
# default_account is just a string with mat... |
from __future__ import annotations
from typing import List, Union, TYPE_CHECKING, Optional, Callable, Coroutine, Any, Dict
from pydantic import constr, conint
if TYPE_CHECKING:
from roid import CommandType
from roid.app import SlashCommands
from roid.components import Component, ButtonStyle, SelectOption,... |
from .. import base
def getname(obj):
try:
return obj.name
except AttributeError:
return obj
class User(base.Resource):
HUMAN_ID = True
def __repr__(self):
return '<User: %s>' % getattr(self, 'name', 'unknown-name')
def delete(self):
self.manager.delete(self)
... |
from yattag import Doc
class MessageFormatter:
def __init__(self):
pass
def format_message(self, message):
"""
appends messageML tags to plain text and returns a dictionary:
{message : messageML object}
"""
doc,tag,text,line = Doc().ttl()
with tag('mes... |
from dict_hash import sha256
from .utils import create_dict
import os
def test_dict_hash():
path = sha256(create_dict())
assert os.path.exists(path)
os.remove(path) |
from .transformer import Transformer
from .captioning_model import CaptioningModel
|
# Copyright (c) 2015, 2016, 2020 Florian Wagner
#
# This file is part of Monet.
"""Module containing the `GeneSet` class."""
import hashlib
from typing import List, Iterable
class GeneSet:
"""A gene set.
A gene set is just what the name implies: A set of genes. Usually, gene
sets are used to group gene... |
from acrolib.cost_functions import ( # pylint: disable=no-name-in-module
norm_l1,
norm_l2,
sum_squared,
norm_infinity,
weighted_sum_squared,
)
import numpy as np
from numpy.testing import assert_almost_equal
from .slow_cost_functions import (
cost_function_l1_norm,
cost_function_l2_norm,
... |
import numpy; from numpy import sin,cos; from taylorpoly import UTPS
def f(x):
return sin(x[0] + cos(x[1])*x[0]) + x[1]*x[0]
x = [UTPS([3,1,0],P=2), UTPS([7,0,1],P=2)]
y = f(x)
print('normal function evaluation y_0 = f(x_0) = ', y.data[0])
print('gradient evaluation g(x_0) = ', y.data[1:])
|
"""Test functions for pem.fluid.ecl module
"""
import pytest
from pytest import approx
import numpy as np
import digirock.fluids.ecl as fluid_ecl
from inspect import getmembers, isfunction
@pytest.fixture
def tol():
return {
"rel": 0.05, # relative testing tolerance in percent
"abs... |
# -------------------------------------------------------------------------------------------------
# system
import time
import sys
# -------------------------------------------------------------------------------------------------
# Common
from PyQuantum.Common.Assert import *
# ---------------------------------------... |
__title__ = "simulation"
__author__ = "murlux"
__copyright__ = "Copyright 2019, " + __author__
__credits__ = (__author__, )
__license__ = "MIT"
__email__ = "murlux@protonmail.com"
import copy
import math
from datetime import datetime as dt
class OpenedTrade():
"""An object representing an open trade."""
def ... |
import Config as cfg
import utils.AlphaVantageUtils as av
import utils.PostgresUtils as pg
def update_price(ticker, interval, size):
count_duplicate = 0
count_create = 0
df_prices = av.get_prices(cfg.AV_APIKEY, ticker, interval, size)
for i in range(0, len(df_prices)):
if not pg.is_price_... |
# matrix sparseness judgment, convergence judgment, distance product by matrix multiplication, association law for distance product,
# scale-free characteristics of the social networks degrees and the precision limit of floating point operations on the modern hardware.
# 1. DPMM: distance product by MM
# 2. Associati... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.