content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
"""
@package mi.dataset.parser.test
@file marine-integrations/mi/dataset/parser/test/test_adcpt_m_log9.py
@author Tapana Gupta
@brief Test code for adcpt_m_log9 data parser
Files used for testing:
ADCPT_M_LOG9_simple.txt
File contains 25 valid data records
ADCPT_M_LOG9_large.txt
File conta... |
# Inspired by ABingo: www.bingocardcreator.com/abingo
HANDY_Z_SCORE_CHEATSHEET = (
(1, float('-Inf')),
(0.10, 1.29),
(0.05, 1.65),
(0.025, 1.96),
(0.01, 2.33),
(0.001, 3.08))[::-1]
PERCENTAGES = {0.10: '90%', 0.05: '95%', 0.01: '99%', 0.001: '99.9%'}
DESCRIPTION_IN_WORDS = {0.10: 'fairly conf... |
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from past.utils import old_div
import rlpy
import numpy as np
from hyperopt import hp
param_space =... |
import os
from jobControl import jobControl
from pyspark.sql import SparkSession
from pyspark.sql import functions as f
from pyspark.sql.types import IntegerType, StringType
from utils import arg_utils, dataframe_utils
job_args = arg_utils.get_job_args()
job_name = os.path.basename(__file__).split(".")[0]
num_partiti... |
from fontbakery.checkrunner import Section
from fontbakery.fonts_spec import spec_factory
def check_filter(item_type, item_id, item):
# Filter out external tool checks for testing purposes.
if item_type == "check" and item_id in (
"com.google.fonts/check/035", # ftxvalidator
"com.google.fonts/check/0... |
# Generated by Django 3.2.5 on 2021-07-18 12:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('src', '0006_auto_20210718_1014'),
]
operations = [
migrations.AddField(
model_name='job',
name='delivery_address',
... |
"""fix Contact's name constraint
Revision ID: 41414dd03c5e
Revises: 508756c1b8b3
Create Date: 2021-11-26 20:42:31.599524
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '41414dd03c5e'
down_revision = '508756c1b8b3'
branch_labels = None
depends_on = None
def u... |
#/usr/bin/env python
import sys
import logging
logger = logging.getLogger('utility_to_osm.ssr2.git_diff')
import utility_to_osm.file_util as file_util
from osmapis_stedsnr import OSMstedsnr
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
# diff is called by git with 7 parameters:
... |
# THIS FILE IS GENERATED FROM SIGPROFILEMATRIXGENERATOR SETUP.PY
short_version = '1.1.0'
version = '1.1.0'
|
from gym_minigrid.minigrid import *
from gym_minigrid.register import register
class WarehouseSortEnv(MiniGridEnv):
"""
Environment with a door and key, sparse reward
"""
def __init__(self, size=8):
super().__init__(
grid_size=size,
max_steps=10*size*size
)
... |
"""Plot road network
"""
import os
import cartopy.crs as ccrs
import geopandas
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
from atra.utils import load_config, get_axes, plot_basemap, scale_bar, plot_basemap_labels, save_fig
def main(config):
"""Read shapes, plot map
"""
data_p... |
import torch
import torch.nn as nn
from utils.util import count_parameters
class Embedding(nn.Module):
"""A conditional RNN decoder with attention."""
def __init__(self, input_size, emb_size, dropout=0.0, norm=False):
super(Embedding, self).__init__()
self.embedding = nn.Embedding(input_s... |
class FileReader(object):
def read(self, file):
with open(file) as f:
return f.read()
def read_lines(self, file):
lines = []
with open(file) as f:
for line in f:
lines.append(line)
return lines
|
from locust import HttpUser, task
from locust import User
import tensorflow as tf
from locust.contrib.fasthttp import FastHttpUser
def read_image(file_name, resize=True):
img = tf.io.read_file(filename=file_name)
img = tf.io.decode_image(img)
if resize:
img = tf.image.resize(img, [224, 224])
r... |
# coding=utf-8
import unittest
import urllib2
import zipfile
import random
from tempfile import NamedTemporaryFile
from StringIO import StringIO
from . import EPUB
try:
import lxml.etree as ET
except ImportError:
import xml.etree.ElementTree as ET
class EpubTests(unittest.TestCase):
def setUp(self):
... |
"""Collection of Object."""
import sqlite3
class Connection(sqlite3.Connection):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.execute('pragma foreign_keys=1')
class CustomCommand:
"""Object for custom command."""
__slots__ = (
"id",
"type... |
import networkx as nx
import numpy as np
import sys
from scipy.io import mmread
from scipy.sparse import coo_matrix
np.set_printoptions(threshold=sys.maxsize)
if len(sys.argv) != 2:
print("Usage: python3 ./hits.py <file.mtx>")
exit()
graph_coo = mmread(sys.argv[1])
print("Loading COO matrix")
print(graph_coo.... |
import pickle
from typing import Any, Union
from datetime import datetime
class DataStorage:
_DataStorageObj = None
def __new__(cls, *args, **kwargs):
if cls._DataStorageObj is None:
cls._DataStorageObj = super().__new__(cls)
return cls._DataStorageObj
def __init__(self):
... |
class discord:
Colour = None
class datetime:
datetime = None
|
import math
import os
def activator(data, train_x, sigma): #data = [p, q] #train_x = [3, 5]
distance = 0
for i in range(len(data)): #0 -> 1
distance += math.pow(data[i] - train_x[i], 2) # 計算 D() 函式
return math.exp(- distance / (math.pow(sigma, 2))) # 最後返回 W() 函式
def grnn(data, train_x, train_y, ... |
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring,line-too-long
from unittest import mock
import os
import pytest
from eze.plugins.tools.checkmarx_kics import KicsTool
from eze.utils.io import create_tempfile_path
from tests.plugins.tools.tool_helper import ToolMetaTestBase
... |
"""Simple templating engine. See `TemplateEngine` class."""
import os
import re
import inspect
__all__ = ['TemplateEngine', 'TemplateSyntaxError', 'annotate_block']
class TemplateEngine:
"""Simple templating engine.
WARNING: do NOT use this engine with templates from untrusted sources.
Expressions in th... |
from rdkit import Chem
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit.Chem import Descriptors
from padelpy import from_smiles
import re
import time
nms=[x[0] for x in Descriptors._descList]
print('\n')
calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms)
f=open('/scratch/woon/b3lyp_2017/datas... |
from torch import randn
from torch.nn import Linear
from backpack import extend
def data_linear(device="cpu"):
N, D1, D2 = 100, 64, 256
X = randn(N, D1, requires_grad=True, device=device)
linear = extend(Linear(D1, D2).to(device=device))
out = linear(X)
vin = randn(N, D2, device=device)
vou... |
# -*- coding: utf-8 -*-
import logging
from pathlib import Path
import yaml
logger = logging.getLogger(__name__)
def recursive_update(original_dict: dict, new_dict: dict) -> dict:
"""Recursively update original_dict with new_dict"""
for new_key, new_value in new_dict.items():
if isinstance(new_valu... |
# Generated by Django 3.2.6 on 2021-11-29 00:15
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('kube', '0003_auto_20210917_0032'),
]
operations = [
migrations.RemoveField(
model_name='kubecluster',
name='type',
)... |
import json
from flask import make_response
from marshmallow import fields, Schema, post_load, EXCLUDE
from flask_apispec.utils import Ref
from flask_apispec.views import MethodResource
from flask_apispec import doc, use_kwargs, marshal_with
# All the following schemas are set with unknown = EXCLUDE
# because part ... |
from abc import ABC, abstractmethod
import itertools
import numpy as np
import matplotlib.pyplot as plt
import tqdm
from . import _heatmap
from . import preprocessing
class Regressor(ABC):
'''
Mix-in class for Regression models.
'''
@abstractmethod
def get_output(self):
'''
Retu... |
from __future__ import absolute_import, print_function
import pytest
from steam_friends import app
from steam_friends.views import api, auth, main
def test_app(flask_app):
assert flask_app.debug is False # todo: should this be True?
assert flask_app.secret_key
assert flask_app.testing is True
asser... |
# from classify.data.loaders.snli import SNLIDataLoader
# __all__ = ["SNLIDataLoader"]
|
import numpy as np
class InvertedPendulum:
def __init__(self, length, mass, gravity=9.81):
self.length = length
self.mass = mass
self.gravity = gravity
# matrices of the linearized system
self.A = np.array([[0, 1, 0, 0],
[gravity/length, 0, 0, 0]... |
class Base:
@property
def id(self):
return self._id
def __repr__(self):
return '({} {})'.format(self.__class__.__name__, self.id)
def __unicode__(self):
return u'({} {})'.format(self.__class__.__name__, self.id)
def __eq__(self, other):
return self.id == other.id
... |
# from DETR main.py with modifications.
import argparse
import datetime
import json
import random
import time
from pathlib import Path
import math
import sys
from PIL import Image
import requests
import matplotlib.pyplot as plt
import numpy as np
from torch.utils.data import DataLoader, DistributedSampler
import torc... |
# Generated by Django 2.1.2 on 2018-12-05 14:28
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("barriers", "0020_auto_20181025_1545")]
operations = [
migrations.RemoveField(model_name="barriercontributor", name="barr... |
#special thanks to this solution from:
#https://stackoverflow.com/questions/40237952/get-scrapy-crawler-output-results-in-script-file-function
#https://stackoverflow.com/questions/41495052/scrapy-reactor-not-restartable
from scrapy import signals
from scrapy.signalmanager import dispatcher
from twisted.internet import... |
# -*- coding: utf-8 -*-
"""Helper module to work with files."""
import fnmatch
import logging
import os
import re
from stat import S_IRGRP, S_IROTH, S_IRUSR, S_IWGRP, S_IWOTH, S_IWUSR
# pylint: disable=redefined-builtin
from ._exceptions import FileNotFoundError
MAXLEN = 120
ILEGAL = r'<>:"/\|?*'
LOGGER = logging.ge... |
from numpy import dtype
db_spec = True
try:
import sqlalchemy.types as sqlt
except:
db_spec = False
return_keys = [
'id',
'created_at',
'number',
'total_price',
'subtotal_price',
'total_weight',
'total_tax',
'total_discounts',
'total_line_items_price',
'name',
'tota... |
from setuptools import find_packages, setup
setup(
name='serverlessworkflow_sdk',
packages=find_packages(include=['serverlessworkflow_sdk']),
version='0.1.0',
description='Serverless Workflow Specification - Python SDK',
author='Serverless Workflow Contributors',
license='http://www.apache.org/l... |
#!/usr/bin/env python3
# coding: utf-8
# PSMN: $Id: 02.py 1.3 $
# SPDX-License-Identifier: CECILL-B OR BSD-2-Clause
""" https://github.com/OpenClassrooms-Student-Center/demarrez_votre_projet_avec_python/
Bonus 1, json
"""
import json
import random
def read_values_from_json(fichier, key):
""" create an new em... |
# encoding: utf8
from pygubu import BuilderObject, register_custom_property, register_widget
from pygubu.widgets.pathchooserinput import PathChooserInput
class PathChooserInputBuilder(BuilderObject):
class_ = PathChooserInput
OPTIONS_CUSTOM = ('type', 'path', 'image', 'textvariable', 'state',
... |
"""
Anserini: A toolkit for reproducible information retrieval research built on Lucene
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 a... |
from picamera import PiCamera
from time import sleep
def record_video(sec):
pi_cam = PiCamera()
pi_cam.start_preview()
pi_cam.start_recording('./video.mp4')
sleep(sec)
pi_cam.stop_recording()
pi_cam.stop_preview()
record_video(5)
|
import logging
from hearthstone.enums import CardType, Zone, GameTag
from hslog import LogParser, packets
from hslog.export import EntityTreeExporter
from entity.game_entity import GameEntity
from entity.hero_entity import HeroEntity
from entity.spell_entity import SpellEntity
# import entity.cards as ecards
logger =... |
''' Train all cort models
Usage:
train_all.py [--num_processes=<n>] --type=<t> <consolidated_conll_dir> <out_dir>
'''
import os
from cort.core.corpora import Corpus
import codecs
import random
import subprocess
from cort_driver import train
from joblib import Parallel, delayed
import sys
import itertools
from doco... |
""" Yoga style module """
from enum import Enum
from typing import List
class YogaStyle(Enum):
""" Yoga style enum """
undefined = 0
hatha = 1
yin = 2
chair = 3
def get_all_yoga_styles() -> List[YogaStyle]:
""" Returns a list of all yoga styles in the enum """
return [YogaStyle.hatha, Yo... |
#!/usr/bin/python
import os
import sys
import argparse
from collections import defaultdict
import re
import fileUtils
def isBegining(line):
m = re.match(r'^[A-Za-z]+.*', line)
return True if m else False
def isEnd(line):
return True if line.startswith('#end') else False
def getItem(item):
m = re... |
import speech_recognition as sr
import pyaudio #optional
# get audio from the microphone
while True: #this loop runs the below code infinite times until any inturrupt is generated
r = sr.Recognizer()
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source)
print... |
from django.conf.urls import url
from django.urls import path
from . import views
from . import dal_views
from .models import *
app_name = 'vocabs'
urlpatterns = [
url(
r'^altname-autocomplete/$', dal_views.AlternativeNameAC.as_view(
model=AlternativeName,),
name='altname-autocomplete'... |
from dancerl.models.base import CreateCNN,CreateMLP
import torch.nn as nn
if __name__ == '__main__':
mlp=CreateMLP(model_config=[[4,32,nn.ReLU()],
[32,64,nn.ReLU()],
[64,3,nn.Identity()]])
print(mlp)
cnn=CreateCNN(model_config=[[4,32,3,2,1,n... |
from DB import Database
db = Database("db")
MENU = range(1)
def reminder_handler(user_id, obj):
date, type, name = obj
db.add_event(user_id, date, "birthday" if type == "Birthday" else "regular", name)
if type == "Birthday":
db.add_reminder(user_id, date - 7 * 24 * 60 * 60, "birthday" if type ==... |
import glob
import os
import sys
import argparse
import time
from datetime import datetime
import random
import numpy as np
import copy
from matplotlib import cm
import open3d as o3d
VIRIDIS = np.array(cm.get_cmap('plasma').colors)
VID_RANGE = np.linspace(0.0, 1.0, VIRIDIS.shape[0])
LABEL_COLORS = np.array([
(255,... |
from __future__ import absolute_import, division, print_function
from distutils.version import LooseVersion
import pickle
import numpy as np
import pytest
import xarray as xr
import xarray.ufuncs as xu
from . import (
assert_array_equal, assert_identical as assert_identical_, mock,
raises_regex,
)
require... |
from .utils import *
from .ps.dist_model import DistModel
from .ps import ps_util
def evaluate_ps(gpu_available, options):
model_path = os.path.join(options.model_path, 'alex.pth')
model = DistModel()
model.initialize(model='net-lin', net='alex', model_path=model_path, use_gpu=gpu_available)
dist_sta... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Cisco-IOS-XR-Get-Full-ClearText-Running-Config Console Script.
Copyright (c) 2021 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
... |
#Uses Money Flow Index to determine when to buy and sell stock
import numpy as np
import pandas as pd
#import warnings
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
#warnings.filterwarnings('ignore')
df = pd.read_csv('StockTickers/JPM.csv',nrows=200)
df.set_index(pd.DatetimeIndex(df['Date'].values),... |
from synapse import Synapse
from timemodule import Clock
from neuron import *
import random
clock = Clock()
neurons = []
for i in range(20):
neurons.append(Neuron(clock.get_time(),7/10))
for i in range(30):
connect(neurons[random.randrange(20)],neurons[random.randrange(20)]
,random.randrange(2),1)... |
#!/usr/bin/env python3
import logging
import os
import yaml
from jinja2 import Environment, FileSystemLoader
logging.getLogger().setLevel(logging.DEBUG)
def main(template_name, vars_file):
logging.info("Enter main.")
with open(vars_file, 'r') as yaml_vars:
variables = yaml.load(yaml_vars)
thes... |
from status import Status
import errors
from unittest import TestCase
class TestStatus(TestCase):
def test_ok(self):
try:
Status.divide(Status.OK.value, None)
self.assertTrue(True)
except errors.JstageError:
self.assertTrue(False)
def test_no_results(self):... |
# -*- coding: utf-8 -*-
# file: train_atepc_english.py
# time: 2021/6/8 0008
# author: yangheng <yangheng@m.scnu.edu.cn>
# github: https://github.com/yangheng95
# Copyright (C) 2021. All Rights Reserved.
###################################################################################################################... |
#!env python3
import pyd4
import sys
file = pyd4.D4File(sys.argv[1])
chrom = sys.argv[2]
begin = int(sys.argv[3])
end = int(sys.argv[4])
for (chrom, pos, value) in pyd4.enumerate_values(file, chrom, begin, end):
print(chrom, pos, value)
|
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXX XXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXX XXXXXXXX XXXXXXX XXXXXXXXXXXX
XXX XXXXXXXXXXXX XXXXXXXXXX XXX XXXXXXXXXX XXXXXXX XXXXXXXXXXX XXXXXXXXXX
XXXXXXX XXXXXXXXXXXXXXXX XXXX XXXX XX XXXXXX XXXXXX XXXX X XXXXXXXXX XXXX
XXXXXX X... |
import datetime
model_date_to_read = '20200125'
model_version_to_read = '2.0'
model_date_to_write = datetime.datetime.today().strftime('%Y%m%d')
model_version_to_write = '2.0'
|
# -*- coding: utf-8 -*-
"""
Created on 2017-8-23
@author: cheng.li
"""
import numpy as np
import pandas as pd
from PyFin.api import *
from alphamind.api import *
from matplotlib import pyplot as plt
plt.style.use('ggplot')
import datetime as dt
start = dt.datetime.now()
universe = Universe('custom', ['zz800'])
f... |
# Other imports
import numpy as np
import torch
# DeepCASE Imports
from deepcase.preprocessing import Preprocessor
from deepcase import DeepCASE
if __name__ == "__main__":
########################################################################
# Loading data ... |
"""
[summary]
[extended_summary]
"""
# region [Imports]
# * Standard Library Imports ------------------------------------------------------------------------------------------------------------------------------------>
import os
from datetime import datetime
import re
# * Third Party Imports -----------------------... |
import math
import sys
import time
import numpy as np
import owl
from net import Net
import net
from net_helper import CaffeNetBuilder
from caffe import *
from PIL import Image
class NetTrainer:
''' Class for training neural network
Allows user to train using Caffe's network configure format but on multiple G... |
import numpy as np
import torch
import torch.nn.functional as F
import os, copy, time
#from tqdm import tqdm
import pandas as pd
from ipdb import set_trace
path = '/home/vasu/Desktop/project/'
### helper functions
def to_np(t):
return np.array(t.cpu())
### Losses
def calc_class_weight(x, fac=2):
... |
# Copyright Jetstack Ltd. See LICENSE for details.
# Generates kube-oidc-proxy Changelog
# Call from the branch with 3 parameters:
# 1. Date from which to start looking
# 2. Github Token
# requires python-dateutil and requests from pip
from subprocess import *
import re
from datetime import datetime
import dateutil.... |
from PIL import Image
import numpy as np
from matplotlib import pylab as plt
img = np.array(Image.new("RGB", (28, 28)))
img[:,:,:] = 255
img[2,2,:] = 0
img[2,5,:] = 0
img[2,6,:] = 0
img[2,10,:] = 0
img[2,11,:] = 0
img[3,10,:] = 0
img[3,11,:] = 0
plt.imshow(img)
plt.imsave("p.png", img)
np.save('p,npy', img, allo... |
""" Hyperparameters for MJC peg insertion trajectory optimization. """
from __future__ import division
from datetime import datetime
import os.path
import numpy as np
from gps import __file__ as gps_filepath
from gps.agent.mjc.agent_mjc import AgentMuJoCo
from gps.algorithm.algorithm_traj_opt import AlgorithmTrajOpt
... |
import os
import sys
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(os.path.join(PROJECT_ROOT, 'vendor', 'pyyaml', 'lib'))
import yaml
from git import apply as git_apply
class Patch:
def __init__(self, file_path, repo_path):
self.file_path = file_pa... |
# vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:
# See LICENSE comming with the source of python-quilt for details.
import runpy
import sys
from unittest import TestCase
from six.moves import cStringIO
from helpers import tmp_mapping
class Test(TestCase):
def test_registration(self):
with tmp_mapping(v... |
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from rest_framework.test import APIClient
import json
from django.utils import timezone
from datetime import timedelta
# Create your tests here.
from .models import Contact
from .serializers import ContactSerializer
from agape.people.... |
#!/usr/bin/python
import sys
def __test1__(__host__):
import pylibmc
print 'Testing <pylibmc> ... %s' % (__host__)
mc = pylibmc.Client([__host__], binary=True, behaviors={"tcp_nodelay": True,"ketama": True})
print mc
mc["some_key"] = "Some value"
print mc["some_key"]
assert(mc["some_key"... |
import json
import argparse
import requests
parser = argparse.ArgumentParser()
parser.add_argument("--extension-uuid", dest="extension_uuid", type=str)
parser.add_argument("--gnome-version", dest="gnome_version", type=str)
args = parser.parse_args()
def get_extension_url(extension_uuid, gnome_version):
base_url ... |
# -*- coding: utf-8 -*-
import re, kim, dinle, islem, muhabbet
def __init__(giris):
pattern_kim = re.match('(.+) ((kim(dir)?)|nedir)(\?)?$', giris, re.IGNORECASE)
pattern_dinle = re.match('(.+) dinle$', giris, re.IGNORECASE)
pattern_islem = re.match('^([\d\(\)\-]+(\+|\-|\*|\/)[\d\(\)\+\-\*\/\.]+)(=)?(\?)?... |
from pirates.minigame import CannonDefenseGlobals
from pirates.pirate.CannonCamera import CannonCamera
from pirates.util.PythonUtilPOD import ParamObj
class CannonDefenseCamera(CannonCamera):
class ParamSet(CannonCamera.ParamSet):
Params = {
'minH': -60.0,
'maxH': 60.0,
... |
class Tweet:
def __repr__(self):
return self.id
def __init__(self, _id, text, created_at, hashtags, retweet_count, favorite_count, username, user_location):
self.id = _id
self.text = text
self.created_at = created_at
self.hashtags = hashtags
self.retweet_count = ... |
class DimensionError(Exception):
def __init__(self, message="Dimension mismatch"):
super(DimensionError, self).__init__(message)
|
import numpy as np
from task.Schema import Schema
# import pdb
class StimSampler():
'''
a sampler of sequences
'''
def __init__(
self,
n_param,
n_branch,
pad_len=0,
max_pad_len=None,
def_path=None,
def_prob=None,
... |
from mwcleric.auth_credentials import AuthCredentials
class AuthCredentials(AuthCredentials):
"""Wrapper class just to make imports nicer to work with"""
pass
|
import tkinter as tk
import view_calc as vc
import model_calc as mc
class CalcController:
def __init__(self):
self.root = tk.Tk()
self.calc = vc.ViewCalc(self.root, self)
self.moc = mc.ModelCalc()
def start(self):
self.root.mainloop()
def operacao(self, op, n1, n2):
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: robot_behavior.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as... |
import six
import itertools
import numpy as np
from chainer import serializers
import nutszebra_log2
# import nutszebra_slack
import nutszebra_utility
import nutszebra_log_model
import nutszebra_sampling
import nutszebra_download_cifar100
import nutszebra_preprocess_picture
import nutszebra_basic_print
import nutszebra... |
import torch
import wandb
import numpy as np
from mlearn import base
from tqdm import tqdm, trange
from collections import defaultdict
from mlearn.utils.metrics import Metrics
from mlearn.utils.early_stopping import EarlyStopping
from mlearn.utils.evaluate import eval_torch_model, eval_sklearn_model
from sklearn.model_... |
# Software License Agreement (BSD License)
#
# Copyright (c) 2012, Fraunhofer FKIE/US, Alexander Tiderko
# 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 mus... |
import bpy
from bpy.props import *
from .. events import propertyChanged
from .. base_types import AnimationNodeSocket, PythonListSocket
class ColorSocket(bpy.types.NodeSocket, AnimationNodeSocket):
bl_idname = "an_ColorSocket"
bl_label = "Color Socket"
dataType = "Color"
drawColor = (0.8, 0.8, 0.2, 1)... |
import pytest
from src.xmlToData.regexExtractors.parametersExtractor import ParametersExtractor
@pytest.mark.parametrize("xml_string", ["+ get_age(): int",
"# add_weight( ): int",
"- set_height( ): int"])
def test_extract_empty_pa... |
#
# 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 "License"); you may not us... |
# coding: utf-8
"""
nlpapiv2
The powerful Natural Language Processing APIs (v2) let you perform part of speech tagging, entity identification, sentence parsing, and much more to help you understand the meaning of unstructured text. # noqa: E501
OpenAPI spec version: v1
Generated by: https://git... |
import torch
from nff.utils.scatter import compute_grad
from nff.utils import batch_to
from torch.nn import ModuleDict
from ase import Atoms
from ase import units
import numpy as np
from torchmd.topology import generate_nbr_list, get_offsets, generate_angle_list
def check_system(object):
import torchmd
if o... |
#!/usr/bin/env python3.8
from passlocker import User, user_details
def create_new_user(fisrtname, lastname ,password):
'''
Function to create a new user with a username and password
'''
new_user = User(fisrtname, lastname ,password)
return new_user
def save_user(user):
'''
Function to save... |
import mdk
import requests
class MockRequest(object):
def __init__(self):
self.data = None
self.get = self.repeater
self.post = self.repeater
self.put = self.repeater
self.delete = self.repeater
self.status = 200
def repeater(self, url, params=None, headers=No... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
class PropertyAuthInfo(object):
def __init__(self):
self._area = None
self._city = None
self._community = None
self._data_id = None
self._latitude ... |
def queryUser(feature_names):
print "Please enter changes to features in the format:\n(feature 1 number) (+ for increase, - for decrease)\n(feature 2 number) (+/-)\n...\n(enter -1 -1 to stop)"
for i in range(len(feature_names)):
print str(i+1)+": "+feature_names[i]
print "-------------------------------------"
in... |
from ..profiles import models
def user_display(user):
try:
profile = user.profile
except models.Profile.DoesNotExist:
return user.email
return profile.name
|
"""
Contains the CNOT gate
"""
from .quantum_gate import QuantumGate
import numpy as np
class CNOT(QuantumGate):
""" Implements the CNOT gate
Parameters
------------
target : 0 or 1, optional
Specifies the target qubit, default is 0.
"""
def __init__(... |
import sys
from daqhats import hat_list, HatIDs, mcc152
# get hat list of MCC daqhat boards
board_list = hat_list(filter_by_id = HatIDs.ANY)
if not board_list:
print("No boards found")
sys.exit()
# Read and display every channel
for entry in board_list:
if entry.id == HatIDs.MCC_152:
print("Board... |
"""Calculates the new ROM checksum and writes it back to the binary
"""
from binaryninja import BackgroundTaskThread, BinaryReader, show_message_box
import struct
class GenesisChecksum(BackgroundTaskThread):
def __init__(self, bv):
BackgroundTaskThread.__init__(self, "", True)
self.progress = 'ge... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.