content
stringlengths
5
1.05M
#!/usr/bin/env python import h5py import numpy as np def Kanamori_interaction(l, U_int, J_hund): norb = 2*l + 1 U = np.zeros((norb,norb,norb,norb), dtype=float) for i in range(norb): U[i][i][i][i] = U_int for j in range(norb): if(i != j): U[i][j][i][j] = U_int...
import numpy as np import time import faiss from source import eval_cluster import preprocess def run_kmeans(x, nmb_clusters, verbose=False): """Runs kmeans on 1 GPU. Args: x: data nmb_clusters (int): number of clusters Returns: list: ids of data in each cluster """ n_data, ...
from django.db import models from django.contrib.auth import models as auth_models class Person(models.Model): user = models.OneToOneField(auth_models.User, on_delete=models.CASCADE)
#!/usr/bin/python3 # encoding: utf-8 import socketserver import threading import time import re import ArmController as controller #舵机转动 import LeConf #偏差 from ArmCmd import LeError import ArmCmd import ArmWebServer as web class ServoServer(socketserver.BaseRequestHandler): def handle(self): print("已连接")...
import time import unittest import uuid from decimal import Decimal from typing import List, cast import grpc import petlib.bn import petlib.ec from common.constants import ( CURRENCY_PRECISIONS, SECP256K1_ALTERNATIVE_GENERATOR, SECP256K1_GENERATOR, SECP256K1_GROUP, Blockchain, Currency, ) from...
import fastjsonschema # type: ignore from ...models.meeting import Meeting from ...shared.permissions.meeting import MEETING_CAN_MANAGE from ...shared.schema import schema_version from ..actions import register_action from ..generics import CreateAction create_meeting_schema = fastjsonschema.compile( { "...
from django.shortcuts import render from django.core import serializers from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.conf import settings import json import datetime from registrar.models import Student from regist...
import csv import json from airflow.models import DAG from airflow.operators.dummy import DummyOperator from airflow.operators.python import PythonOperator from airflow.providers.postgres.hooks.postgres import PostgresHook from airflow.utils import timezone import pandas as pd DAGS_FOLDER = '/opt/airflow/dags' de...
import asyncio import contextlib import inspect import io import platform import re import sys import textwrap import traceback from datetime import datetime, timezone from random import randint import math import hikari import lightbulb from lightbulb import commands, plugins, checks from lightbulb.context import Cont...
# -*- coding: utf-8 -*- """ Created on July 11, 2016 @author: bwawok@gmail.com """ from __future__ import absolute_import from django.core.paginator import Paginator from django.test import TestCase from djcompoundqueryset import CompoundQueryset from .testapp.models import FirstModel, SecondModel class LoginLogout...
# emailer.py # # Copyright (c) 2022 John Fritz # MIT License, see license.md for full license text import json import smtplib import ssl from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email import encoders from email.utils impor...
# # Import Django from django.urls import path # # Import views from .api import api_start_timer, api_stop_timer, api_discard_timer, api_get_tasks from .views import projects, project, edit_project, task, edit_task, edit_entry, delete_entry, delete_untracked_entry, track_entry # # Url pattern app_name = 'project...
#!/usr/bin/env python # # Wrapper on pyinotify for running commands # (c) 2009 Peter Bengtsson, peter@fry-it.com # # TODO: Ok, now it does not start a command while another is runnnig # But! then what if you actually wanted to test a modification you # saved while running another test # Yes, we...
import torch import torch.nn as nn import torchvision class AlexNet(nn.Module): def __init__(self,num_classes=1000): super(AlexNet,self).__init__() self.feature_extraction = nn.Sequential( nn.Conv2d(in_channels=3,out_channels=96,kernel_size=11,stride=4,padding=2,bias=False), ...
# SPDX-License-Identifier: BSD-3-Clause # Andrew Piroli 2022 import argparse import time import tracemac_parser from getpass import getpass from netmiko import ConnectHandler from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Union etherchannel_cache_current_device_id: str = "" etherchann...
import sys import os from functools import reduce from datetime import datetime from time import strftime from warnings import warn import numpy as np import pandas as pd from scipy.sparse import issparse, csr_matrix import scanpy as sc import h5py from natsort import natsorted from anndata import AnnData from mudata...
import yaml import os class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self @classmethod def from_nested_dicts(cls, data): """ Construct nested AttrDicts from nested dictionaries. """ if not isinstan...
# -*- coding: utf-8 -*- # # Copyright (C) 2017-2019 KuraLabs S.R.L # # 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...
flag_bits = 2 int_bits = 32 frac_bits = 30 internal_frac_bits = 60 internal_int_bits = 4
from django.conf.urls import url from . import views from django.contrib.auth.views import ( login, logout, # These built in views are for password reset password_reset, password_reset_done, password_reset_confirm, password_reset_complete ) urlpatterns = [ url(r'^register/$', views.reg...
def test_music_genre_object(fake): test_genre_obj = fake.music_genre_object() assert isinstance(test_genre_obj, dict) assert "genre" in test_genre_obj.keys() assert "subgenres" in test_genre_obj.keys() def test_music_genre(fake): test_genre = fake.music_genre() assert isinstance(test_genre, st...
# -*- coding: utf-8 -*- import vim from orgmode._vim import echo, echom, echoe, ORGMODE, apply_count, repeat, insert_at_cursor, indent_orgmode from orgmode.menu import Submenu, Separator, ActionEntry, add_cmd_mapping_menu from orgmode.keybinding import Keybinding, Plug, Command from orgmode.liborgmode.checkboxes impor...
""" Counts number of occurrences of keywords and groups by word. """ from operator import add from defoe import query_utils def do_query(archives, config_file=None, logger=None, context=None): """ Counts number of occurrences of keywords and groups by word. config_file must be the path to a configurati...
#!/usr/bin/env python3 """ BSD 3-Clause License Copyright (c) 2017, SafeBreach Labs 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 noti...
import unittest from parameterized import parameterized_class import gilded_rose_oop import gilded_rose_functional from items.aged_brie import AgedBrie @parameterized_class([ {"gilded_rose_factory": gilded_rose_oop.GildedRose, "name": "OOP"}, {"gilded_rose_factory": gilded_rose_functional.GildedRose, "name"...
""" Usage: plot_per_epoch.py (--model-names=MN)... [--algos=ALGO]... [options] Options: -h --help Show this screen. --algos ALGO Which algorithms to load {BFS, parallel_coloring}. Repeatable parameter. [default: BFS] --has-GRU Does the pro...
import csv import re def getCsv(txtFileName='ninteenth.txt'): with open(txtFileName) as csv_file: csv_reader = csv.reader(csv_file, delimiter=' ') return list(csv_reader) def parseRules(csvFile): rulesDict = {} codes = [] rules = True for row in csvFile: if not row: ...
# Generated by Django 2.0 on 2018-02-21 08:22 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import uuid import web.managers class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0009_alter_user_last_name_max_len...
#! /usr/bin/env python3 # # Copyright 2019 Rolf Michelsen # # 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 appli...
from __future__ import annotations import os import pathlib import typing import services from NeonOcean.S4.Main import Debug, Language, Paths, This from NeonOcean.S4.Main.Saving import Save from NeonOcean.S4.Main.UI import Dialogs from ui import ui_dialog, ui_dialog_picker SelectSaveDialogTitle = Language.String(Th...
import time from robot.utils import timestr_to_secs class Wait: @staticmethod def until_true(condition, timeout, error_msg): """Helper to wait until given condition is met.""" timeout = timestr_to_secs(timeout) max_wait = time.time() + timeout while True: if conditi...
__author__ = 'mnowotka' import datetime from django.db import models from chembl_core_model.models import * from chembl_core_db.db.models.abstractModel import ChemblCoreAbstractModel from chembl_core_db.db.models.abstractModel import ChemblModelMetaClass from django.utils import six # --------------------------------...
'''LINEイベントのハンドラ''' import sys import linebot from django.db.utils import OperationalError from . import line_utilities as line_util from . import line_settings from .. import message_commands as mess_cmd from .. import utilities as util from ..exceptions import GroupNotFoundError, UserNotFoundError CO...
#!/usr/bin/env python import time from pylibftdi import Device, USB_PID_LIST, USB_VID_LIST from ctypes import * import struct from slip import slip, unslip_from STYX_VID = 0x2a19 STYX_PID = 0x1007 USB_VID_LIST.clear() USB_VID_LIST.append(STYX_VID) USB_PID_LIST.clear() USB_PID_LIST.append(STYX_PID) R1 = 21660.0 R2 =...
import sys import copy from parseipl import parseIplInst, parseIplPath def wxyzConjugate(q): return q[0], -q[1], -q[2], -q[3] def quatMultiply(q, p): return q[0]*p[0] - q[1]*p[1] - q[2]*p[2] - q[3]*p[3], \ q[0]*p[1] + q[1]*p[0] + q[2]*p[3] - q[3]*p[2], \ q[0]*p[2] + q[2]*p[0] + q[3]*p[1] - q[1]*p[3], \ q[0]*p[3]...
import logging import logging.handlers import sys def getLogger(logger_name, use_syslog): logger = logging.getLogger(logger_name) logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) cf = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(mess...
import numpy as np import pandas as pd class ElanPortal(): def __init__(self): self.data = {} def add_tier(self, tier_name, type, tier_data): ''' This function add data to portal :param tier_name: :param tier_data: :return: ''' self.data.setdefa...
import numpy as np import pandas as pd from keras.utils import to_categorical from keras import layers, Input, regularizers from keras.models import Model from sklearn import metrics from keras.optimizers import SGD, Adam from keras.callbacks import EarlyStopping import STRING from resources.sampling import un...
from django.contrib import messages from django.contrib.auth import authenticate, login from django.shortcuts import render, redirect from user_access.forms import SignUpForm # Sign Up Functionality def SignUpView(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_v...
import shutil import os import crequests from pathlib import Path cacheDir = "tests/cachedir" def test_cacheDirCreation(): shutil.rmtree( cacheDir, ignore_errors=True ) # Remove the cache dir if it exists... We want to start from fresh crs = crequests.Session(cacheDir) # Create an instance of ...
# Generated by Django 3.1.2 on 2020-11-05 16:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("opcalendar", "0009_auto_20201105_0859"), ] operations = [ migrations.AlterField( model_name="event", name="visibilit...
""" Script to compute partial correlations of various factors with flexibility. """ import numpy as np import pandas as pd from scipy import stats import src.corpus import src.partial LANGS = "en fr zh es de ja la nl ar he id sl ro it pl da".split() for LANG in LANGS: data_file = "data/wiki/processed/%s.pkl" % LA...
from flask import Flask from flask import request from flask import render_template import sys, os sys.path.append('/home/ec2-user/python-image-gallery/gallery/ui') from db_functions import * import secrets app = Flask(__name__) @app.route('/admin') def admin_list(): data = listUsers2() return render_template...
#!/usr/bin/env python2 import sys sys.path.append('../fml/') import os import numpy as np import fml import time import random t_width = np.pi / 4.0 # 0.7853981633974483 d_width = 0.2 cut_distance = 6.0 r_width = 1.0 c_width = 0.5 PTP = {\ 1 :[1,1] ,2: [1,8]#Row1 ,3 :[2,1] ,4: [2,2]#Row...
import gennav import sensor_msgs from gennav_ros import conversions def transform_polygons(polygons, position): """Transforms polygons with respect to some position Args: polygons (list[list[tuple[float, float, float]]]): polygon to be transformed position (gennav.utils.RobotState...
from __future__ import unicode_literals import logging import unittest from six import StringIO class LoggerSetupTest(unittest.TestCase): def _stream(self): return StringIO() def _logger(self, logger_name, stream): logging.getLogger().addHandler(logging.StreamHandler(stream)) return ...
#!/usr/bin/env python # Script to extract "hashes" from Monero databases. # # + Tested with monero-gui-v0.11.1.0 on Fedora 27. # + Tested with monero.linux.x64.v0-9-0-0.tar.bz2 (from Jan, 2016) on Fedora 27. # # This software is Copyright (c) 2017, Dhiru Kholia <dhiru at openwall.com> and # it is hereby released to th...
from typing import Callable, Optional from ._utils.frame_model import FrameType, FrameModel _hook = Callable[[FrameModel], Optional[bool]] class Events: def __init__(self, ws_client): self.__WebSocketClient = ws_client self.__ready_executed = False def on_any(self, func: _hook = None, frame_...
import logging from typing import Any, Dict, Type from uuid import UUID from slack_bolt import App, BoltContext, Ack from teamiclink.slack.middleware import SlackMiddleware from teamiclink.slack.store_goal import GoalStore from slack_sdk import WebClient LOG = logging.getLogger(__name__) def delete_goal( contex...
#!/usr/bin/env python # dCloud Credentials apic = { 'ip': '198.18.133.200', 'url': 'https://198.18.133.200', 'user': 'admin', 'password': 'C1sco12345' } saas = { 'ip': __SAAS_IP__ 'token': __TOKEN___ }
import os import subprocess from collections import OrderedDict from glob import glob from itertools import product from subprocess import Popen, PIPE from warnings import warn from joblib import Parallel, delayed import pandas as pd import shutil # from https://github.com/BIDS-Apps/freesurfer/blob/master/run.py#L11 ...
""" Train the parameters of the simple ADALINE classifier for determining if file has spacing issues. """ import sys import adaline import pandas as pd import numpy as np import matplotlib.pyplot as plt def train_adaline(source_filename="diagnostic_results.csv", plots=False, parameter_filename="adaline_wts.npy")...
from io import BytesIO import html from time import sleep from typing import Optional, List from telegram import TelegramError, Chat, Message from telegram import Update, Bot from telegram.error import BadRequest from telegram import ParseMode from telegram.ext import MessageHandler, Filters, CommandHandler from telegr...
from __future__ import unicode_literals from frappe import _ def get_data(): return [ { "label": _("Documents"), "icon": "icon-star", "items": [ { "type": "doctype", "name": "Assign Tables", "description": _("Assign tables to waiters.") }, { "type": "doctype", "name": "...
from alembic import util from alembic.testing import exclusions from alembic.testing.requirements import SuiteRequirements from alembic.util import sqla_compat class DefaultRequirements(SuiteRequirements): @property def schemas(self): """Target database must support external schemas, and have one ...
"""The sihas_canary integration.""" from __future__ import annotations import logging from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from .const import DOMAIN _LOGGER = logging.getLogger(__name__) PLATFORMS: list[str] = [ "button", "climate", "cover", ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2012-2019 SoftBank Robotics. All rights reserved. # Use of this source code is governed by a BSD-style license (see the COPYING file). """ Convert a binary archive into a qiBuild package and add it to a toolchain. """ from __future__ import absolute_import f...
from . import F90
from django.http import JsonResponse from django.views.decorators.http import require_GET # from apps.fhir.bluebutton.models import Crosswalk from oauth2_provider.decorators import protected_resource from django.contrib.auth.decorators import login_required from collections import OrderedDict from django.conf import se...
from kinorrt.mechanics.mechanics import * from kinorrt.mechanics.stability_margin import * #import wrenchStampingLib as ws smsolver = StabilityMarginSolver() h_modes = np.array([[CONTACT_MODE.STICKING, CONTACT_MODE.STICKING], [CONTACT_MODE.SLIDING_RIGHT, CONTACT_MODE.SLIDING_RIGHT], ...
#!/usr/bin/env python3 """Show modules presence in nginx packages side-by-side in a grid.""" import subprocess from collections import OrderedDict def main(): """Main Function.""" packages_all = ( 'nginx-extras', 'nginx-full', 'nginx-core', 'nginx-light' ) modules = Or...
import random from collections import namedtuple import pytest from patternmatching import bind, bound, group, like, match, padding, repeat Point = namedtuple('Point', 'x y z t') def match_basic(value): if match(value, None): return 'case-1' elif match(value, True): return 'case-2' elif...
# Generated by Django 2.2.16 on 2022-01-12 09:49 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('posts', '0007_auto_20220112_1057'), ] operations = [ migrations.AlterModelOptions( name='follow', options={'ordering': ('us...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.contrib.auth.admin import UserAdmin as AuthUserAdmin from django.template.loader import render_to_string from django.utils.translation import gettext_lazy as _ from hijack_admin.admin import HijackUserAdminMixi...
"""Parsing UsageEvent reasons. Copyright (c) 2016-present, Facebook, Inc. 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. An additional grant of patent rights can be found in the PATENTS file in the same directory. """...
import numpy as np def tsdf_loss(gt, est, norm='L2', mask=None): N = 1 dim = len(gt.shape) for d in range(0, dim): N *= gt.shape[d] diff = gt - est if mask is not None: diff = np.multiply(mask, diff) # compute loss only where tsdf is positive valid = (est > 0).astype(i...
from .surface_plotting import plot_surf, plot_hemispheres __all__ = ['plot_surf', 'plot_hemispheres']
import pytz from aioch import Client from infi.clickhouse_orm.models import ModelBase from infi.clickhouse_orm.database import Database, Page, DatabaseException, ServerError class AsyncDatabase(Database): def __init__(self, db_name='default', db_host='127.0.0.1', db_port='9000', username='defaul...
from collections import OrderedDict import requests import logging import urllib import json import operator from django.conf import settings from .paginator import Paginator API_TYPES = { "events": settings.FDA_DRUG_API_EVENT_URL, "labels": settings.FDA_DRUG_API_LABEL_URL, "enforcements": settings.FDA_D...
# Autogenerated constants for Role Manager service from jacdac.constants import * from jacdac.system.constants import * JD_SERVICE_CLASS_ROLE_MANAGER = const(0x1e4b7e66) JD_ROLE_MANAGER_REG_AUTO_BIND = const(0x80) JD_ROLE_MANAGER_REG_ALL_ROLES_ALLOCATED = const(0x181) JD_ROLE_MANAGER_CMD_SET_ROLE = const(0x81) JD_ROLE_...
from django.db import models from django.urls import reverse from randomslugfield import RandomSlugField # Create your models here. class Shortener(models.Model): slug = RandomSlugField(length=5) link_to = models.URLField() created = models.DateTimeField(auto_now_add=True) def __str__(self): ...
import os import numpy as np import json from io import BytesIO import time import argparse import requests from cli import DefaultArgumentParser from client import Client from s3client import ObjectStorageClient from zounds.persistence import DimensionEncoder, DimensionDecoder import zounds from mp3encoder import enc...
import setuptools with open("README.md", "r") as file_header: long_description = file_header.read() setuptools.setup( name="cppl", version="1.0.0", author="danie_llimas", author_email="amedlimas97@gmail.com", description="Simple OpenCV and Ubidots app to count people in images", long_descr...
import unittest from disctools import AutoShardedBot as _AS from disctools import Bot, Command from .utils import dummy class BotTest(unittest.TestCase): def setUp(self): self.bot = Bot("~") self.ABot = _AS("~") def test_inject(self): class TestCMD(Command): main = dummy...
import pyttsx from gtts import gTTS import vlc import time import wave import contextlib class Mic: def __init__(self): self.engine = pyttsx.init() def say(self, text_to_say): self.engine(text_to_say) self.engine.runAndWait() def stop(self): self.engine.stop() def che...
# -*- coding: utf-8 -*- """ Created on Fri Apr 6 11:23:40 2018 @author: Herbert """ import urllib response_1 = urllib.request.urlopen("http://www.baidu.com") print(response_1.getcode()) cont = response_1.read() print(len(cont)) import http.cookiejar as hc cj = hc.CookieJar() opener = urllib.request.build_opene...
class colorFormat: """Display color format `\033[display mode; font color; background color m String\033[0m` ------------------------------------------------- Font color| background color | color description ------------------------------------------------- 30 | ...
#!/usr/bin/env python3 import os import re LCOV_SF_RE = re.compile(r'^SF:(.*)$') LCOV_DA_RE = re.compile(r'^DA:([0-9]+),([0-9]+)$') # SF:/xxx/yyy/main.cpp # DA:11,0 def uncovered_line_numbers_generator(info_filepath, source_filepath): # NOTE: dummy filepath filename = '' for line in open(info_filepath):...
# encoding=utf8 import jenkins_job_wrecker.modules.base class Buildwrappers(jenkins_job_wrecker.modules.base.Base): component = 'buildwrappers' def gen_yml(self, yml_parent, data): wrappers = [] for child in data: object_name = child.tag.split('.')[-1].lower() self.reg...
import compas from compas.geometry import Point from compas.geometry import Vector from compas.geometry import Frame from compas_nurbs.bspline import BSpline from compas_nurbs.curvature import CurveCurvature if not compas.IPY: from compas_nurbs.evaluators import create_curve from compas_nurbs.evaluators impo...
# -- coding:utf8 -- import argparse #添加子命令函数 def foo(args): print (args.x * args.y) def bar(args): print ('((%s))' %args.z) #创建最上层解析器 parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(title='subcommands', description='valid subcommands', ...
from fastapi import FastAPI, Request, HTTPException from fastapi.responses import RedirectResponse, JSONResponse from fastapi.templating import Jinja2Templates import msal import requests as rq app = FastAPI() templates = Jinja2Templates(directory="templates") #########################################################...
#!/usr/bin/python3 # 文件名:class_complex.py class Complex: def __init__(self, realpart, imagpart): # 构造函数 self指向类实例本身,self不是关键字,可用其他替换(同样表示类实例本身),但只能为第一个参数 self.r = realpart self.i = imagpart x = Complex(3.0,-4.5) print("%.1f+%.1fi" % (x.r,x.i))
# Generated by Django 3.1.2 on 2020-10-20 08:09 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Account', fields=[ ('identity', models.Inte...
import numpy as np from scipy.optimize import root from scipy.sparse import spdiags, kron from scipy.sparse.linalg import spilu, LinearOperator from numpy import cosh, zeros_like, mgrid, zeros, eye # parameters nx, ny = 75, 75 hx, hy = 1./(nx-1), 1./(ny-1) P_left, P_right = 0, 0 P_top, P_bottom = 1, 0 def get_precon...
# -*- coding: utf-8 -*- #!/usr/bin/env python """ Main training workflow """ from __future__ import division import os import sys PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.abspath(os.path.join(PROJECT_ROOT, ".."))) import argparse import glob import os import random impo...
import uuid import boto3 from boto3_type_annotations.kinesis import Client as Kinesis DUMMY_AWS_ENV_VARS = { "AWS_ACCESS_KEY_ID": "anything", "AWS_SECRET_ACCESS_KEY": "anything", } class DockerizedKinesis: region: str endpoint: str kinesis: Kinesis def __init__(self, endpoint: str) -> None:...
import warnings from typing import Optional, Tuple import torch from torch import Tensor from .linear import NonDynamicallyQuantizableLinear from torch.nn.init import constant_, xavier_normal_, xavier_uniform_ from torch.nn.parameter import Parameter from .module import Module from .. import functional as F class Th...
import numpy as np from larcv import larcv from sklearn.decomposition import PCA import time #larcv.test_openmp() # 0. Randomly sample points # 1. Given set of points and subset of points, return list of segments # 2. Given list of segments, compute local PCA # Trivial test here # Given points of coordinates (i, i, ...
# coding=utf-8 # 2019-1-28 # quick_sort def quick_sort(array): less, greater = [], [] if len(array) <=1 : return array # choose a pivot pivot = array.pop() for x in array: if x <= pivot: less.append(x) else: greater.append(x) return quick_sort(less) + [pivot] + quick_sort(greater) if __name__ ...
# ファイル名とデータ filename = "a.bin" data = 100 # 書き込み with open(filename, "wb") as f: f.write(bytearray([data]))
# coding: utf-8 import json import os import boto3 import pandas as pd def main(): price_list = [] pricing = boto3.client('pricing', region_name='us-east-1') paginator = pricing.get_paginator('get_products') response_iterator = paginator.paginate( ServiceCode='AmazonEC2', Filters = [ ...
class StreamHandler(): def open(self, file_path): pass def write(self, file_path, write_object): pass class StreamHandler2019(): def open(self, file_path): with open(file_path, "r") as f: first_line = f.readline().strip() slices_to_order, types_of_pizza = ma...
import numpy as np import os import pyqtgraph as pg import time import csv import sys import msvcrt import matplotlib.pyplot as plt import threading from numpy.fft import fft import matplotlib.animation as anim from scipy.signal import spectrogram, stft # powermatrix = np.genfromtxt('power.csv', delimiter=',') power...
# -*- 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...
"""File parsers for Nets AvtaleGiro and OCR Giro files.""" __version__ = '1.3.0' from netsgiro.constants import * # noqa: Reexport from netsgiro.enums import * # noqa: Reexport from netsgiro.objects import * # noqa: Reexport from netsgiro import constants, enums, objects # noqa: Must come after reexport __a...
from hyde.hyde_instance import HydeInstance, HydeInstanceError from hyde.environment import Environment from hyde.environment import RuntimeError as EnvironmentRuntimeError from hyde.errors import BaseError, Return import hyde.expressions as Expressions from hyde.globals import Globals from hyde.hyde_callable import Hy...
def arg_test(a, b=0, *vargs, **kwargs): return (a, b, vargs, kwargs.items())
import unittest import cupy as np # !! CUPY !! import dezero.layers as L import dezero.functions as F from dezero.utils import gradient_check, array_allclose, array_allclose import chainer.functions as CF class TestConv2d_simple(unittest.TestCase): def test_forward1(self): n, c, h, w = 1, 5, 15, 15 ...
import torch from torch import nn class InstaGAN(object): """ InstaGANの2組のGeneratorとDiscriminatorを保持するためのクラスです。 """ def __init__(self, params): super(InstaGAN, self).__init__() network_params = params["network"] input_nc = network_params["input_channels"] ...