content stringlengths 5 1.05M |
|---|
import pymysql.cursors
from fixture.orm import ORMFixture
from model.group import Group
db = ORMFixture(host = "127.0.0.1", name="addressbook", user="root", password="")
try:
L = db.get_contacts_not_in_group(Group(id="40"))
for item in L:
print(L)
finally:
pass |
"""obfuscate tweet data for tests"""
from datetime import datetime
import json
import time
tdict = str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
"WWWWWWWWWWWWWWWWWWWWWWWWWWwwwwwwwwwwwwwwwwwwwwwwwwww")
def obfuscate(data, key=None):
if isinstance(data, list):
... |
import utils
from .linear_classifier import LinearClassifierMethod
from .linear_classifier import LinearClassifierMethodParams
from .moco import MoCoMethod
from .moco import MoCoMethodParams
__all__ = ["MoCoMethod", "MoCoMethodParams", "LinearClassifierMethod", "LinearClassifierMethodParams", "utils"]
|
var1 = 100
if var1:
print("1 - if 表达式条件为 true")
print(var1)
var2 = 0
if var2:
print("2 - if 表达式条件为 true")
print(var2)
print("Good bye!")
n = 100
sum = 0
counter = 1
while counter <= n:
sum = sum + counter
counter += 1
print("1 到 %d 之和为: %d" % (n, sum)) |
import glob
from itertools import chain
import nbformat
from toolz import curry, compose
import logging
import sys
import json
def _read_notebook(filename):
return nbformat.read(filename, as_version=4)
@curry
def _strip_sensitive(cell, strip_tag="stripout"):
if "tags" in cell["metadata"].keys() and strip_t... |
from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("The Tic Tac Toe Game")
clicked = True
count = 0
def disable_buttons():
b00['state'] = 'disable'
b01['state'] = 'disable'
b02['state'] = 'disable'
b10['state'] = 'disable'
b11['state'] = 'disable'
b12['state'] = 'di... |
import sys
import pytest
from parcyl import Requirement, parseVersion
def test_Req_parse():
r = Requirement.parse("eyeD3_extra")
assert r.name == "eyeD3_extra"
assert r.project_name == "eyeD3-extra"
assert r.key == "eyed3-extra"
assert r.specs == []
assert r.marker is None
r = Requirement... |
def longest_consec(strarr, k):
if len(strarr) == 0 or k > len(strarr) or k <= 0:
return ""
num = 0
string = ""
for i in range(len(strarr) - k + 1):
leng = len("".join(strarr[j] for j in range(i, i + k)))
if num < leng:
num = leng
string = "".join(strarr[j] for j in range(i, i + k))
return string
|
import glob
from os import path
import unittest
import deltalanguage as dl
from test.execution.base import TestExecutionBaseDS
class TestExecutionUnsorted(TestExecutionBaseDS):
"""These are the original tests difined in Deltasimulator which haven't
been moved to any categories yet.
TODO there 2 options... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
import modelcluster.fields
import wagtail.core.fields
import modelcluster.tags
class Migration(migrations.Migration):
dependencies = [
('wagtailimages', '0002_initial... |
# -*- coding: utf-8 -*-
import os
import shutil
import urllib.request
from urllib.error import HTTPError, URLError
from autoselenium.utils import *
__all__ = ['download_driver', 'download_default_driver', 'get_version']
def download_driver(driver, version='current', root='.'):
if not os.path.exists(root):
... |
import logging
from memosa import context, memoize2
logging.basicConfig(level=logging.INFO)
@memoize2
def add(x, y):
yield f'{x}+{y}'
yield x + y
with context():
for i in range(3):
print(add(1, 2))
|
from pyliticamemes import bolsonaro, cabodaciolo, ciro, dilma
dilma.mandioca()
|
import csv
import numpy as np
import pyquaternion
from trajectory.trajectory import Trajectory
from trajectory.trajectory_node import TrajectoryNode
class CameraTrajectory(Trajectory):
def load(self, file_path: str):
with open(file_path, 'r') as f:
csv_rows = csv.reader(f)
for... |
"""Used for rendering frames as png files."""
import sys
import os
import numpy as np
import pyvista as pv
import nibabel as nb
FILENAME = "/home/faruk/data2/DATA_MRI_NIFTI/derived/sub-demo_flatten/sub-04_ses-T2s_segm_rim_HG_RH_v02_borderized_multilaterate_perimeter_chunk_curvature_binned_flat_400x400_voronoi_median_... |
import os
import glob
import shutil
import random
import torch
import torch.nn as nn
from model import ShuffleNetV2
import torchvision.transforms as transforms
from PIL import Image
import time
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# device = torch.device("cpu")
model_path = './mode... |
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
|
import torch
from torch import Tensor
import torch.nn as nn
import torch.nn.functional as F
from aw_nas.ops import register_primitive
# Operations of two dimensional UNet
# ---------------------------------------------------------------------------------------
class DownBlock2D(nn.Module):
def __init__(self, C_... |
import requests
import json
import os
from pathlib import Path
def _detect_artifact(artifact_id):
"""Detects type of artifact based on artifact URL.
Parameters
----------
artifact_id : str
String in form of resolvable URL
Returns
-------
artifact_type : str
String represe... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
"""
Minimal Atom feed writer.
"""
from __future__ import absolute_import, division, unicode_literals, print_function
import sys
import datetime
import hashlib
import xml.etree.ElementTree as etree
from . import util
__all__ = ['F... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A reproduction of Figure 5.6 from Rasmussen & Williams (2006).
http://www.gaussianprocess.org/gpml/
"""
from __future__ import division, print_function
import sys
import time
import emcee
import numpy as np
import cPickle as pickle
import statsmodels.api as sm
import... |
import tkinter as tk
from tkinter import ttk
def main():
root=tk.Tk()
root.title("Feet to Meters")
mainframe=ttk.Frame(root,padding="3 3 12 12")
mainframe.grid(column=0,row=0,sticky=(tk.N,tk.W,tk.E,tk.S))
mainframe.columnconfigure(0,weight=1)
mainframe.rowconfigure(0,weight=1)
feet=tk.S... |
#!/usr/bin/python
import sys
cnt_map = dict()
for line in sys.stdin:
path = line.strip()
cnt_map[path] = cnt_map.get(path, 0) + 1
max_path = max(cnt_map, key=cnt_map.get)
max_cnt = cnt_map.get(max_path, 0)
print "{0}\t{1}".format(max_path, max_cnt)
|
import discord, os, english_words, random
class o:
mode = 'discord'
message_volume = 10000
locs = ['452565980745433117', '368951504578543627', '451093718574039050']
creds = ['usr', 'pss']
corploc = '1'
names = ['roh', 'baht', 'aadi']
bye = ['Bye!', 'Hasta la vista', 'i gtg nao', 'i... |
from .mappers import (
DotNetSphinxMapper,
PythonSphinxMapper,
GoSphinxMapper,
JavaScriptSphinxMapper,
)
DEFAULT_FILE_PATTERNS = {
"python": ["*.py", "*.pyi"],
"dotnet": ["project.json", "*.csproj", "*.vbproj"],
"go": ["*.go"],
"javascript": ["*.js"],
}
DEFAULT_IGNORE_PATTERNS = {
... |
default_app_config = "ddrr.apps.DDRRConfig"
|
from django.core.exceptions import ValidationError
from web3 import Web3
def validate_checksumed_address(address):
try:
if not Web3.isChecksumAddress(address):
raise ValidationError(
"%(address)s has an invalid checksum",
params={"address": address},
... |
import utils.env_loader as env_loader
env = env_loader.load()
from flask import Flask
if env.get("FLASK_ENV") == "production":
app = Flask("app", template_folder="templates_production")
from app import configs
app.config.from_object(configs.Production)
socketio_kwargs = {
"async_mode": "geve... |
# associate two results by comparing their coordinates |
def __del__(self):
try:
if self.cb:
libvirtmod.virStreamEventRemoveCallback(self._o)
except AttributeError:
pass
if self._o is not None:
libvirtmod.virStreamFree(self._o)
self._o = None
def _dispatchStreamEventCallback(self, ev... |
import os
import gevent.monkey
gevent.monkey.patch_all()
# import logging
import multiprocessing
#debug = True
dirs="./logs"
if not os.path.exists(dirs):
os.makedirs(dirs)
# loglevel = 'info'
bind = '0.0.0.0:5000'
pidfile = r'./logs/gunicorn.pid'
accesslog = r"./logs/micro_access.log"
errorlog = r"./... |
import skiff
import os
import pytest
import time
# XXX: according to https://developers.digitalocean.com/#links
# XXX: the per page default is 25, but from my testing it's actually 20
DEFAULT_RESULTS_PER_PAGE = 20
token = os.getenv("DO_TOKEN")
assert token is not None
test_domain = os.getenv("DO_TEST_DOMAIN")
assert... |
# Copyright (C) 2013 eNovance SAS <licensing@enovance.com>
#
# 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... |
# MySQL Connector/Python - MySQL driver written in Python.
# Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
# MySQL Connector/Python is licensed under the terms of the GPLv2
# <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
# MySQL Connectors. There are special exceptio... |
import asyncio
import websockets
import pyroboy
import redis
import struct
from pyroboy.face_recognition import FaceRec
ENCONDING_LENGTH = 128
class FaceOracle:
def __init__(self):
self.r = redis.Redis(host='172.17.0.1', port=6379, db=0)
self.start_server = websockets.serve(self.recognize, 'localh... |
from django.core.exceptions import ValidationError
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.contrib import messages
from .models import *
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, Row, Column, HTML,... |
import attr
import jax.numpy as jnp
import jax.random
from qml.finance.deccumulation.market_state.market_state_types import MarketStateUpdater
from qml.tools.jax_util.types import Array
from qml.tools.monte_carlo.brownian_motion import vector_geometric_brownian_motion
@attr.s(frozen=True, auto_attribs=True)
class GB... |
# Улитка ползет по вертикальному шесту высотой H метров, поднимаясь за день на A метров, а за ночь спускаясь на B
# метров. На какой день улитка доползет до вершины шеста?
h = int(input())
a = int(input())
b = int(input())
increase = a - b
d = ((h - a) + increase - 1) // increase + 1
print(d)
|
# pylint: skip-file
from sorter.lib.first_run import init
class fake_db(object):
def __init__(self):
self.query = ""
def create_connection(self):
pass
def execute(self, foo):
self.query = foo
def close_connection(self):
pass
def get_qry(self):
return ... |
#!/usr/bin/env python3
import argparse
import bagit
import os
import shutil
class BagInfo:
def __init__(self, path = None):
self.path = os.path.abspath(path)
try:
self.bag = bagit.Bag(path)
except:
print("not bag")
self.check_baginfo()
def check_bagin... |
"""CLI parser."""
import collections
import inspect
import sys
import typing as t
from .exceptions import CLError
from .infer_params import infer_params_from_signature
from .normalize import UnknownOption, normalize
from .params import Param
ExceptionHandler = t.Callable[["Genbu", CLError], t.NoReturn]
def defaul... |
from JumpScale import j
import JumpScale.baselib.redis
redis=j.clients.redis.getRedisClient("localhost",9999)
import JumpScale.lib.ms1
ms1=j.tools.ms1
def main():
#check if secret key is already known
if not redis.exists("ms1:secret") or redis.get("ms1:secret")=="":
import config
secret=redis.g... |
import yaml
import torch
import torch.nn as nn
import argparse
import pprint
from pathlib import Path
from tqdm import tqdm
from typing import List, Dict
from torch.utils.data import DataLoader
from model import Generator, Discriminator
from dataset import IllustDataset
from visualize import Visualizer
from loss impo... |
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import unittest
from extensions.front.mxnet.gluoncv_ssd_anchors import SsdAnchorsReplacer
from mo.front.common.partial_infer.utils import int64_array
from mo.utils.ir_engine.compare_graphs import compare_graphs
from m... |
from requests import HTTPError
def requests_http_error_handler(exc: HTTPError):
try:
response_body = exc.response.json()
except ValueError:
response_body = exc.response.text
status_code = exc.response.status_code if exc.response.status_code < 500 else 503
return {
"statusCode"... |
from sklearn.decomposition import PCA
from numpy.lib.function_base import disp
from sklearn.preprocessing import OneHotEncoder
from typing import Dict, List, Sequence, Tuple
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.figure_factory as ff
import plotly.grap... |
# run black box attack on models
import numpy as np
import tensorflow as tf
import random
# construct graph for testing on original examples
def build_test(discriminator, test_image_placeholder, test_label_placeholder, config):
x = test_image_placeholder
x = 2.0*x - 1.0
y = test_label_placeholder
d_o... |
from django.http import HttpResponse
from django.shortcuts import render
from .tasks import first_task, send_email
from .models import Poetry
from .my_singal import action
# Create your views here.
def first_celery(req):
# 任务函数的异步调用
first_task.delay(4)
send_email.delay("liuda@1000phone.com")
return Ht... |
import sys
import AnchorLayout
from PyQt5.QtWidgets import *
class Form1 (QWidget):
def __init__ (self, parent = None):
super().__init__(parent)
self.setWindowTitle('Anchor Demo')
self.resize(400, 310)
self.layout = AnchorLayout.AnchorLayout(self)
self.initUI()
... |
from escalonator import Escalonator
from process import Process
from ioqueue import IO
from cpu import CPU
from mmu import MMU, VirtualMemory
import random
import time
from Gantt import Window_Gantt
class main():
def __init__(self, processes, quantum, override, type, typeMMU):
super().__init__()
se... |
import torch
import numbers
from vel.api.metrics.averaging_metric import AveragingNamedMetric
from vel.rl.api.base import OptimizerAlgoBase
from vel.math.functions import explained_variance
from vel.schedules.constant import ConstantSchedule
class PpoPolicyGradient(OptimizerAlgoBase):
""" Proximal Policy Optimi... |
from .viz import charts
from .modeling import *
from .stats import *
|
class Solution(object):
def minScoreTriangulation(self, values):
N = len(values)
dp = [[float('inf')]*N for _ in xrange(N)]
for i in xrange(N-1):
dp[i][i+1] = 0
for l in xrange(3, N+1):
for i in xrange(N-l+1):
j = i+l-1
... |
'''
File: HAPT_Dataset.py
Author: Federico Cruciani
Date: 03/10/2019
Version: 1.0
Description:
utility functions to load the
Human Activities and Postural Transitions (HAPT) dataset
'''
import numpy as np
import pandas as pd
from os.path import expanduser
from keras.utils import to_categorical
from multiprocessi... |
from typing import Dict
from tabledbmapper.engine import QueryResult, CountResult
from tabledbmapper.logger import Logger
from tabledbmapper.manager.manager import Manager
class DAO:
"""
Dao layer
"""
# Database manager
_manager = None
# Statement constants
_get_list = "GetList"
_ge... |
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.urls import fetch_url
import json
DOCUMENTATION = r'''
---
module: web_module
short_description: A small module to retrieve all orgs from the meraki API.
version_added: "1.0.0."
description: Retrieve all organizations the user has access to... |
from typing import List
from dict_typer import get_type_definitions
def test_convert_with_empty_list() -> None:
source = {"items": []} # type: ignore
# fmt: off
expected = "\n".join([
"from typing import List",
"",
"from typing_extensions import TypedDict",
"",
"... |
def update_relation_index(search_manager, parent_pk, delete):
search_manager.update_relation_index(parent_pk, delete) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 5 09:20:45 2020
@author: bressler
"""
import SBCcode as sbc
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter
import runlistscatalogue as rlc
from PICOcode.REFPROP.SeitzModel import SeitzModel
import pulse_integrat... |
import sys
import os
# local path to the code
local_path = "/Users/zhengz11/myscripts/git_clone/pn_kc/pn_kc/"
sys.path.append(local_path)
# exec(open(local_path + "/connectivity/startup.py").read())
import mushroom_2to3.connect as cc
import mushroom_2to3.analysis_routine as ar
from mushroom_2to3.shuffle import *
fr... |
import os
import sys
import json
import requests
import codecs
HOST=os.environ["CONTAINER"]
if HOST == "":
HOST = "localhost"
DEST="http://%s:8080/run" % HOST
def content_from_args(args):
if len(args) == 0:
return {}
if len(args) == 1 and os.path.exists(args[0]):
with open(args[0]) as fp... |
import time
import math
import sys
sys.setrecursionlimit(100000)
with open("number3.txt", "r") as f:
nums = f.read()
num_list = nums.split(",")
del num_list[-1]
num_list = list(map(int, num_list))
def heap_sort(num_list):
length = len(num_list)
#長さが1になったらそのまま返す
if length == 1:
... |
import os
from django.conf import settings
from ietf.meeting.models import Meeting, Session
def get_current_meeting():
'''Returns the most recent IETF meeting'''
return Meeting.objects.filter(type='ietf').order_by('-number')[0]
def get_materials(group,meeting):
'''
Returns the materials as a dic... |
n1=float(input('insira um dos catetos: '))
n2=float(input('insira o outo cateto: '))
n3=(n1 ** 2 + n2 ** 2)**(1/2)
print('a hipotenusa de um triangulo com {} por {} é de {}.'.format(n1,n2,n3)) |
"""
stitchr_extensions tests
"""
import unittest
from resources import data
from pyspark.sql.functions import when, col
from pystitchr.base.df_columns import *
class TestColumnMethods(unittest.TestCase):
def test_get_valid_numeric(self):
test_df: DataFrame = data.test_df_float
df, cnt, _ = get_va... |
"""
actam:
python data_download.py smiles -p data/datasetName
Downloading QM9/ DECAGON data to args.path (set by default to be "./data/")
command: python data_download QM9 DECAGON -p path
"""
import argparse
import os
import wget
import zipfile
import tarfile
from utils.file_utils import *
def download_smiles_d... |
# Copyright 2019-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" fil... |
import json
import logging
import random
import sys
from types import SimpleNamespace
import click
from jade.loggers import setup_logging
from disco.enums import Placement
from disco.sources.base import DEFAULT_PV_DEPLOYMENTS_DIRNAME
from disco.sources.source_tree_1.pv_deployments import (
DeploymentHierarchy,
... |
NETWORK_NAME = 'testnet'
LEDGER_DIR = '/home/indy/ledger'
LOG_DIR = '/home/indy/log'
KEYS_DIR = LEDGER_DIR
GENESIS_DIR = LEDGER_DIR
BACKUP_DIR = '/home/indy/backup'
PLUGINS_DIR = '/home/indy/plugins'
NODE_INFO_DIR = LEDGER_DIR
CLI_BASE_DIR = '/home/indy/.indy-cli/'
CLI_NETWORK_DIR = '/home/indy/.indy-cli/networks'
|
# Copyright (c) 2013 Mark D. Hill and David A. Wood
# 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 copyright
# notice, this list of conditio... |
# -*- coding: utf-8
from __future__ import unicode_literals, absolute_import
import os
DEBUG = True
USE_TZ = True
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'
INSTALLED_APPS = [
'django.contrib.admin',
'django.cont... |
import datetime
import time
import json
import requests
import pandas as pd
import os
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from airflow.models import Variable
args = {
'owner': 'airflow',
'start_date': dt.datetime(2021, 10, 14),
'retries': 1,
... |
"""
Decorator is a structural pattern that allows
adding new behaviors to objects dynamically by
placing them inside special wrapper objects.
Using decorator you can wrap objects countless
number of times since both target objects and
decorators follow the same interface. The resulting
object will get a stacking behav... |
"""
At the onset of the Great Recession, there was a large drop (6.32%, according to FRED) in consumer
spending on non-durables. Some economists have proffered that this could be attributed to precautionary
motives-- a perceived increase in household income uncertainty induces more saving (less consumption)
to prote... |
#!/usr/bin/env python
##################################################
# Gnuradio Python Flow Graph
# Title: Top Block
# Generated: Mon Oct 13 13:03:15 2014
##################################################
from PyQt4 import Qt
from PyQt4.QtCore import QObject, pyqtSlot
from gnuradio import blocks
from gnuradio imp... |
# todo: add hash sum to judge solution file name on web-app side cuz it can break everything
import os
import shutil
import subprocess
from typing import List
import source.models
from .service import sequence_to_dict
from .static import *
from .config import BUILD_SOURCE_MAX_TIME, SQL_GET_TASK_ATTRIBUTE, SQL_GET_C... |
#!/usr/bin/env python3
print(type("My Name is Ahmed"))
print(type(3))
print(type(9.8))
####### Type conversion #######
print(3.5 ,int(3.5)) # "float to int) you notice in this example it only removes the values after int even if they shoule be rounded up
print("1998" , int("1998")) #"str to int"
print("1998" , in... |
# coding=utf-8
from __future__ import print_function
import json
from watson_developer_cloud import TextToSpeechV1
import text_scraper
text_to_speech = TextToSpeechV1(
username='7d084eb0-c888-4d0d-b0cf-1220faa2114a',
password='IYlMgOjMZEHk')
# print(json.dumps(text_to_speech.list_voices(), indent=2))
def te... |
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you ma... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .encoder import Normalization
class DecoderLayer(nn.Module):
def __init__(
self,
global_self_attention,
local_self_attention,
global_cross_attention,
local_cross_attention,
d_mode... |
#!/usr/bin/env python
#coding:utf-8
# Author: mozman --<mozman@gmx.at>
# Purpose: test SVGAttribute
# Created: 12.10.2010
# Copyright (C) 2010, Manfred Moitzi
# License: GPLv3
import sys
import unittest
from svgwrite.data.types import SVGAttribute, SVGMultiAttribute
class TestSVGMultiAttribute(unittest... |
"""Functions for common view actions, such as lists.
---
Copyright (c) 2013, University Radio York.
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 abo... |
from abc import ABC, abstractmethod
from typing import Type
from .entities import Client
# yapf: disable
class AuthStrategy(ABC):
@abstractmethod
def get_client(self, request: 'falcon.Request', **static_client_params) -> Client: ...
class ClientFactory(ABC):
@abstractmethod
def get_client_cls(self... |
import pytest
from base58 import b58encode_check
from sovtoken.constants import OUTPUTS, ADDRESS, AMOUNT, INPUTS, SEQNO
from plenum.common.exceptions import InvalidClientRequest, UnknownIdentifier
from plenum.common.util import randomString
def test_xfer_handler_static_validation_valid(xfer_handler, xfer_request):
... |
import numpy as np
import json
def main():
from matplotlib import pyplot as plt
fname = "data/pair_corrfuncs_tempdependent_gsAl7200Mg800.json"
with open(fname,'r') as infile:
data = json.load(infile)
print ("here")
T = data["temperature"]
fig = plt.figure()
ax = fig.add_subplot(1,1... |
# included from snippets/main.py
def debug(*x, msg=""):
import sys
print(msg, *x, file=sys.stderr)
def solve(N, edges):
global cost
ccs = [[1]] # Connected Components
ret = 18
cost = 0
def visit(pos):
nonlocal ret
global cost
if pos == N + 1:
if len(cc... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class RealObject(object):
def __init__(self):
self._real = True
def was_faked(self):
return False
@property
def real(self):
return self._real
@real.setter
def real(self, value):
self._real = value |
import pytest
import os
from collections import OrderedDict
import pypospack.utils
from pypospack.pyposmat.data import PyposmatBadParametersFile
def get_testing_set():
pypospack_root_dir = pypospack.utils.get_pypospack_root_directory()
testing_set = OrderedDict()
testing_set['data_directory'] = os.path.jo... |
import torch
import torch.nn as nn
kl_loss = nn.KLDivLoss(reduction='batchmean').cuda()
def knowledge_distill_loss(outputs, outputs_student):
T = 3.0
P = nn.functional.softmax(outputs_student / T, dim=1)
Q = nn.functional.softmax(outputs / T, dim=1)
M = 0.5 * (P + Q)
P = torch.clamp(P, 0.01, 0.99... |
import warnings
warnings.filterwarnings("ignore")
import pandas as pd
import numpy as np
from features.building_features import manual_features, segmentation_text, clean_regex
from data.utils import split
np.random.seed(0)
def prepare_input(dataset='MultiSourceFake', segments_number=10, n_jobs=-1, emo_re... |
# coding=utf-8
# author uguisu
import numpy as np
import tensorflow as tf
from tensorflow.python.framework.errors_impl import InvalidArgumentError
def matrix_001():
print('\n- 矩阵转置 ------------------------')
# 矩阵转置
np_array = np.array([[1., 2., 3.], [4., 5., 6.]])
tensor_a = tf.constant(np_array, dty... |
n = 0
for c in range(0, 26):
print(n)
n += 2 |
import torch
def format_attention(attention, layers=None, heads=None):
if layers:
attention = [attention[layer_index] for layer_index in layers]
squeezed = []
for layer_attention in attention:
# 1 x num_heads x seq_len x seq_len
if len(layer_attention.shape) != 4:
raise... |
#!/usr/bin/env python
"""
2016.12.10 CKS
Loops indefinitely, recording from the microphone, sending short segments of speech to Google for recognition.
Seems to work ok.
I tested this on a laptop and I found the amplification setting on my built-in microphone drastically effected results.
At first, it was set to 100... |
import argparse
import os
import os.path as osp
import shutil
import tempfile
import cv2
import mmcv
import numpy as np
import torch
import torch.distributed as dist
import tqdm
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import get_dist_info, load_checkpoint
from mmdet.apis i... |
from functools import singledispatch
import torch as th
import numpy as np
@singledispatch
def swapaxes(data, dim0, dim1):
raise TypeError('swapaxes function does not support this data type')
@swapaxes.register(np.ndarray)
def _(array, dim0, dim1):
return np.swapaxes(array, dim0, dim1)
@swapaxes.register... |
import pprint
class MetricDefinition():
def __init__(self):
print("init")
if __name__ == "__main__":
print("foo")
|
import streamlit as st
import json
import requests
import matplotlib.pyplot as plt
import numpy as np
URI='http://127.0.0.1:5000'
st.title('Neural Network Visualizer')
st.sidebar.markdown('## Input Image')
if st.button('Get Random Prediction'):
response=requests.post(URI, data={})
response=json.loads(response.t... |
import numpy as np
from skimage import io, transform
def PreprocessImage(img):
img = np.array(img)
print("Original Image Shape: ", img.shape)
# we crop image from center
short_egde = min(img.shape[:2])
yy = int((img.shape[0] - short_egde) / 2)
xx = int((img.shape[1] - short_egde) / 2)
crop_... |
from typing import List, Type, Dict
from labext.module import Module
class JQuery(Module):
@classmethod
def id(cls) -> str:
return 'jquery'
@classmethod
def css(cls) -> List[str]:
return []
@classmethod
def js(cls) -> Dict[str, str]:
return {cls.id(): '//code.jquery... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.