content stringlengths 5 1.05M |
|---|
from math import *
from NodeGeneratorBase import *
from Spheral import Vector3d
from Spheral import Tensor3d
from Spheral import SymTensor3d
from Spheral import pair_double_double
from Spheral import vector_of_int, vector_of_double, vector_of_SymTensor3d, vector_of_vector_of_double
from SpheralTestUtilities import *... |
import matplotlib
matplotlib.use('PS')
matplotlib.rc('text', usetex=True)
matplotlib.rcParams['font.size'] = 17
matplotlib.rc('xtick', labelsize=14)
matplotlib.rc('axes', linewidth=1.2)
matplotlib.rcParams['legend.fontsize'] = 12
matplotlib.rcParams['legend.handlelength'] = 5
matplotlib.rcParams['xtick.major.size'] = 5... |
#-*- coding:utf-8 -*-
import os
import sys
import time
import random
import math
import pickle
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import ticker
import scipy.stats as st
from scipy.stats import norm
from scipy.optimize import curve_fit
from datetim... |
#coding: utf-8
#-----------------------------------------------------------
# Um programa que recebe em um dicionário o nome, média e
# situação de um aluno retornando o conteúdo da estrutura.
#-----------------------------------------------------------
# Dicionário em Python - Exercício #090
#---------------------... |
#!/usr/bin/env python3
import ast
def parse_module(f, filename, **kwargs):
contents = f.read()
tree = ast.parse(contents, filename)
dump = ast.dump(tree, indent=4).replace('\n', '\n ')
print(f'AST for {filename!r}:\n {dump}\n')
return tree
|
import libg3n
from libg3n.model.libg3n_class import Libg3nClass
from libg3n.model.libg3n_config_parser_g3n import Libg3nConfigParserG3n
from libg3n.model.libg3n_function import Libg3nFunction
from libg3n.modules.java.java_function import JavaFunction
from libg3n.modules.java.java_class import JavaClass
from libg3n.modu... |
#!/usr/bin/env python
# encoding: utf-8
# Copyright 2013 Herve BREDIN (bredin@limsi.fr)
# This file is part of PyAnnote.
#
# PyAnnote is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either versio... |
from urllib.request import urlopen
import cv2
import numpy as np
def request_image(
url: str = "http://camerapi3.local:8000/image_frame/last_image"):
resp = urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
# width, height = i... |
class Solution:
def twoSumLessThanK(self, A: List[int], K: int) -> int:
A.sort()
res, l, r = -1, 0, len(A) - 1
while l < r:
if A[l] + A[r] >= K:
r -= 1
else:
res = max(res, A[l] + A[r])
l += 1
return res |
#!/usr/bin/python3
import os
import re
import argparse
import os.path
import configparser
import xml.etree.ElementTree as etree
standard_icons_dir = [
'/usr/share/icons',
'/usr/local/share/icons',
'%s/.icons' % os.path.expanduser('~'),
'%s/.local/share/icons' % os.path.expanduser('~'),
]
def collect... |
from app.tasks.recommender import get_item_similarity
from app.sql_models import Rating, User
from app.extensions import cache
from app.utils.redis_utils import get_task_id_from_redis
@cache.cached(60, "recommend-movies-for-user", query_string=True)
def item_cf_recommendation(user_id, k):
w = get_item_similarity.... |
#!/usr/bin/env nix-shell
#!nix-shell -p python3Packages.ipython python3Packages.requests -i python3
import requests
import os
import binascii
import json
api_url_base = os.environ.get("JORMUNGANDR_RESTAPI_URL", "http://localhost:3001/api")
api_url = f"{api_url_base}/v0"
def get_api(path):
resp = requests.get(url... |
"""
Django settings for ecoway project.
Generated by 'django-admin startproject' using Django 3.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Bu... |
"""Advent of Code 2019 Day 14 - Space Stoichiometry"""
from collections import defaultdict
import math
def create_fuel(reactions, fuel_wanted):
"""Create wanted amount of fuel from reactions, return material dict."""
needed = defaultdict(int)
needed['FUEL'] = fuel_wanted
queue = ['FUEL']
while qu... |
"""Db schema definitions and setup routines."""
import sqlalchemy as sa
from sqlalchemy.sql import text as sql_text
from sqlalchemy.types import SMALLINT
from sqlalchemy.types import CHAR
from sqlalchemy.types import VARCHAR
from sqlalchemy.types import TEXT
from sqlalchemy.types import BOOLEAN
#pylint: disable=line-... |
# -*- coding: utf-8 -*-
"""
This module manage interaction between application and
OpenStack cloud infrastructure
"""
import math
from datetime import date
from dateutil.relativedelta import relativedelta
from django.core.cache import cache
from django.utils.dateparse import parse_datetime
from keystoneauth1.identi... |
"""Tests for :mod:`nanoutils.testing_utils`."""
import os
from pathlib import Path
from assertionlib import assertion
from nanoutils import FileNotFoundWarning, delete_finally
PATH = Path('tests') / 'test_files'
DIR1 = PATH / 'tmp_dir'
FILE1 = PATH / 'tmp_file.txt'
def test_warning() -> None:
"""Test :exc:`na... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads/v6/services/remarketing_action_service.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf ... |
import pickle
import time
from typing import Optional
from contextualized_topic_models.models.ctm import ZeroShotTM
from contextualized_topic_models.utils.data_preparation import TopicModelDataPreparation
from contextualized_topic_models.utils.preprocessing import WhiteSpacePreprocessingStopwords
from nltk.corpus impo... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2018-08-11 16:52
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('polls', '0004_poll_open'),
]
operations = [
migrations.AddField(
... |
# 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 json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class GetDir... |
print(2|7)
def comparator(a, b):
ab = str(a) + str(b)
ba = str(b) + str(a)
return ((int(ba) > int(ab)) - (int(ba) < int(ab))) >= 0
def myCompare(mycmp):
class K(object):
def __init__(self, obj):
super().__init__()
self.obj = obj
def __lt__(self, valu... |
from .. import exceptions, native
from .base import Storage
from ..vobject import Item
from functools import partial
import json
class RustStorage(Storage):
_native_storage = None
def _native(self, name):
return partial(
getattr(native.lib, 'vdirsyncer_storage_{}'.format(name)),
... |
def load(h):
return ({'abbr': 'pres', 'code': 1, 'title': 'PRES Pressure Pa'},
{'abbr': 't', 'code': 11, 'title': 'T Temperature K'},
{'abbr': 'q', 'code': 51, 'title': 'Q Specific humidity kg/kg'},
{'abbr': 'pwat', 'code': 54, 'title': 'PWAT Precipitable water kg/m2'},
... |
import requests
from threading import Thread
import queue
import uuid
import time
from os import getcwd
print("\n"*3)
down=[]
stat_time=time.time()
global error
error=""
global img_dimension
img_dimension="1920/1080" ## width/height #width/ for square image
q = queue.Queue()
def urlgen():
global ... |
# ============LICENSE_START=======================================================
# org.onap.dcae
# ================================================================================
# Copyright (c) 2019-2020 AT&T Intellectual Property. All rights reserved.
# Copyright (c) 2020 Pantheon.tech. All rights reserved.
# ====... |
image_width = 256
image_height = 256
image_channels = 3
cnum = 32
|
def issue_new():
import sqlite3
from tabulate import tabulate
import datetime
conn=sqlite3.connect('library.sqlite')
cur=conn.cursor()
cur.executescript('''
DROP TABLE IF EXISTS Issue;
CREATE TABLE Issue (
Issue_id VARCHAR(128) NOT NULL PRIMARY KEY UNIQUE,
Bo... |
def test_success():
assert True
def test_not_failure():
assert not False
|
from cnn_finetune import make_model
from torch import nn
from src.models.head import Head
from src.utils import to_Mish
class MultiHeadNet(nn.Module):
def __init__(self, encoder, pretrained, num_classes, activation):
super().__init__()
self.net = make_model(
model_name=encoder, pretra... |
from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CppExtension
setup(
name='gesvd',
version="0.1",
ext_modules=[
CppExtension('gesvd_cpp', ['gesvd.cpp']),
],
scripts=['gesvd.py', '__init__.py'],
cmdclass={
'build_ext': BuildExtension
})
|
import json
from django.utils.http import is_safe_url
from django.utils.translation import gettext as _
from django.shortcuts import redirect, render
from wagtail.core.models import Site, Page
from wagtail.core import hooks
from wagtail.admin import messages
from wagtail.admin.views.pages import delete
from .models imp... |
# FinMag - a thin layer on top of FEniCS to enable micromagnetic multi-physics simulations
# Copyright (C) 2012 University of Southampton
# Do not distribute
#
# CONTACT: h.fangohr@soton.ac.uk
#
# AUTHOR(S) OF THIS FILE: Dmitri Chernyshenko (d.chernyshenko@soton.ac.uk)
import numpy as np
__all__ = ["Mesh", "MeshField... |
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user_types = (
('Admin', 'Admin'),
('Operator','Operator'),
('Customer', 'Customer'),
)
user = models.OneToOneField(User, on_delete= models.CASCADE)
user_type = models.CharFiel... |
"""
HypermediaHttpSClient uses the HTTPConnection class in httplib to create a dictionary driven interface
to http requesters and response handlers to be used by clients for the HttpHypermediaServer
Requests and their associated responses are exposed in a dictionary interface for processing by proxies and resources
in... |
'''
Created on Jan 9, 2017
@author: User
'''
text = str(input("Enter text: \n"))
def word_counter(text):
# removes starting or trailing spaces also converts all to lower case.
text = text.strip().lower()
#creates a new list with a diff variable
text2 = text.split(' ')
words = 0
... |
import unittest
import dooray
class TestMessengerHookAttachments(unittest.TestCase):
def testCreateAttachment(self):
self.assertEqual(dooray.MessengerHookAttachments._create_attachment(None, None, None, None), None)
self.assertEqual(
dooray.MessengerHookAttachments._create_attachment(... |
from __future__ import absolute_import
from exkaldi.decode import graph
from exkaldi.decode import graph
from exkaldi.decode import score
from exkaldi.decode import e2e
from exkaldi.decode.graph import load_lex
from exkaldi.decode.wfst import load_lat |
# ntrip client launch file
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch_ros.actions import Node
def generate_launch_description():
config = os.path.join(
get_package_share_directory('ntrip_client'),
# 'config',
... |
import FWCore.ParameterSet.Config as cms
# rechit producer
ecalTBSimRecHit = cms.EDProducer("EcalRecHitProducer",
EErechitCollection = cms.string('EcalRecHitsEE'),
EEuncalibRecHitCollection = cms.InputTag("ecalTBSimWeightUncalibRecHit","EcalUncalibRecHitsEE"),
EBuncalibRecHitCollection = cms.InputTag("ecal... |
from ..utils import gen_user_breadcrumb
from ..compatpatch import ClientCompatPatch
class LiveEndpointsMixin(object):
"""For endpoints in ``/live/``."""
def user_broadcast(self, user_id):
"""
Helper method to get a user's broadcast if there is one currently live. Returns none otherwise.
... |
#
# PySNMP MIB module JUNIPER-IPv6-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/JUNIPER-IPv6-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:59:26 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
__author__ = "etseng@pacb.com"
"""
To be used to evaluate phase switching by assuming the genome is already fully "phased".
For example, in Falcon-Unzip, which is pseudo-phased, there could be switching errors.
Since IsoPhase only uses the primary contig (or one of the haplotypes), a switching error shows up
by seein... |
import abc
from lms.lmsdb import models
class BaseNotification(abc.ABC):
def __init__(self, notification: models.Notification):
self.notification = notification
@classmethod
def notification_type(cls) -> str:
return cls.__name__
@staticmethod
@abc.abstractmethod
def build_pa... |
import ardustatlibrary as ard
import time
the_socket = 7777
connresult = ard.connecttosocket(the_socket)
print connresult
socketinstance = connresult["socket"]
print ard.ocv(the_socket)
print ard.socketread(socketinstance)
time.sleep(3)
print ard.potentiostat(2,the_socket)
print ard.socketread(socketinstance)
print... |
#!/usr/bin/python
import os
import sqlite3
class SensorDB():
def __init__(self, path):
path = os.path.join("", path)
self.ClassName = "SensorDB"
self.DB = sqlite3.connect(path, check_same_thread=False)
self.CURS = self.DB.cursor()
self.BuildSchema()
def BuildSchema(self):
self.CURS.execute('''CREAT... |
from .sample import sample
from .params import n, transformers
|
import quantities as pq
def unit(name):
return getattr(pq, name)
|
import operator
import ipaddr
import re
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from django.core.exceptions import ValidationError
from django.db.models import Q
from cyder.core.system.models import System
from cyder.cydhcp.interface.static_intr.models import StaticInterface
fro... |
import numpy as np
import pandas as pd
import tifffile
import pickle
import sys
import seaborn
import matplotlib.pyplot as plt
import os
from tqdm import tqdm
from geo.analysis.data_paths import heatmaps_dir
from geo.data_paths import patch_train
from geo.data_paths import occurrences_train
count_channels = 33
image_... |
'''
def textLines(txt, box):
"""Answers a list of (x,y) positions of all line starts in the box. This
function may become part of standard DrawBot in the near future."""
x, y, w, h = box
attrString = txt.getNSObject()
setter = CoreText.CTFramesetterCreateWithAttributedString(attrString)
path = ... |
import uuid
import requests
from bs4 import BeautifulSoup
import re
import src.models.items.constants as ItemConstants
from src.common.database import Database as db
from src.models.stores.store import Store
class Item(object):
def __init__(self,name,url,price=None,_id=None):
self.name = name
sel... |
from convertme import WriterInterface, Dataset
from mat4py import savemat
from bitarray import bitarray
class MatlabWriter(WriterInterface):
def write(self, dataset, output):
data = {'M': list(map(bitarray.tolist, dataset.bools))}
savemat(output, data)
|
# encoding: utf-8
from __future__ import unicode_literals, division
import math
from Pass.colors import Color
from Pass.units import Pr, unitdispatcher
########################
# Color initialization #
########################
def rgb(r, g, b):
"""Converts an Rgb(r, g, b) triplet into a color."""
return C... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
plt.figure()
sns.set_style("darkgrid")
sns.set_palette("muted")
err_scf = [0.0136, 0.0193, 0.0334]
err_shci = [0, 1e-4, 1e-4]
plt.plot(err_scf, "o-", label="MCSCF")
plt.plot(err_shci, "o-", label="Final SHCI")
plt.title("Energy Error")
plt.yl... |
# VERSION 2
# Add user id as feature
#
#
#
import tensorflow as tf
import tensorflow.contrib as tc
import numpy as np
import tensorflow.contrib.keras as keras
# import tensorflow.contrib as slim
VERSION = "v3"
IS_TRAINING = True
NUM_EPOCHS = 1000000
# IS_TRAINING = False
# NUM_EPOCHS = 1
LEARNING_RATE = 0.01
def re... |
"""Describe group states."""
from homeassistant.components.group import GroupIntegrationRegistry
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.core import callback
from homeassistant.helpers.typing import HomeAssistantType
from . import STATE_CLEANING, STATE_ERROR, STATE_RETURNING
@callbac... |
from django.urls import path
from django.contrib.auth.views import LoginView
from django.contrib.auth import views as auth_views
from core.views import lista_pacientes,home,fomPaciente,cargaPacientes,Editarpaciente,Borrar,Listaestudios,Editaestudio,Borrarestudio
#aca genero las urls que va a tener la app core de n... |
import os
def fix_data_path():
root="/content/ED-MTT/data/OpenFace_features/"
for case in ["Train","validation"]:
for face_feature in os.listdir(root + case):
if "txt" not in face_feature:
os.rename(os.path.join(root + case,face_feature),os.path.join(root + case,face_feature+".txt"))
if __name__ ... |
import workers
from checks import health_task
from polyaxon.settings import HPCeleryTasks
@workers.app.task(name=HPCeleryTasks.HP_HEALTH, ignore_result=False)
def hp_health(x, y):
return health_task.health_task(x, y)
|
import logging
import logging.handlers
import os
import math
import sys
import cv2
import numpy as np
logging.disable(logging.DEBUG)
DISABLE_LOGGING = True
# ============================================================================
CAR_COLOURS = [(0, 0, 255), (0, 106, 255), (0, 216, 255), (0, 255, 182), (0, 255,... |
from model import Net
from tqdm import tqdm
from dataset import train_data, val_data
from dataset import train_data_loader, val_data_loader
import torch
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
matplotlib.style.use('ggplot')
# learning pa... |
#!/local/data/idsbc/idstaff/gladier/miniconda3/envs/gladier/bin/python
import pathlib
import time, argparse, os, re
import numpy as np
#from watchdog.observers import Observer
from watchdog.observers.polling import PollingObserver as Observer
from watchdog.events import FileSystemEventHandler
class KanzusTriggers:
... |
# coding=utf-8
# Copyright (c) 2015 EMC Corporation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#... |
import sys
import os
sys.path.append('/home/td-user/.local/lib/python3.7/site-packages')
os.system(f"{sys.executable} -m pip install requests")
# utilize the pytd to load the data into TD
os.system(f"{sys.executable} -m pip install pytd==0.7.0")
import pytd
import requests
import pandas as pd
import json
print(pytd.... |
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from emmdx import models as emmdxmodels
from extoon import models as exmodels
from core import models
from core.extractor import (
safe_kana,
sa... |
# -*- coding: utf-8 -*-
'''
Preprocessing object for missing data imputation (mean)
@author: Angel Navia Vázquez
'''
__author__ = "Angel Navia Vázquez, UC3M."
import random, string
import time
import numpy as np
class imputation_model_V():
def __init__(self, input_data_description=None):
"... |
import inspect
import sys
import json
import os
import pprint
import runpy
from .log import conf_log
from .registry import PluginBase, reg
from .utils import dict_generator
def print_registry():
# monkey patch sorting
pprint._safe_key.__lt__ = lambda x, y: True
preg = pprint.pformat(reg)
conf_log().... |
import pandas as pd
import numpy as np
import h5py, os, json, sys, shutil
from uuid import uuid4
from pythologist_image_utilities import map_image_ids
from pythologist_reader.qc import QC
from pythologist import CellDataFrame
"""
These are classes to help deal with cell-level image data
"""
class CellFrameGeneric(obj... |
from matplotlib import use
import matplotlib.pyplot as plt
use('Agg')
class ImageMixin(object):
def __init__(self, x, size=(640, 480), color_depth=3):
self.x = x
self.size = size
self.color_depth = color_depth
def transform(self):
raise NotImplementedError()
def save(se... |
# This sample tests the case where a generic type Type[T] is
# instantiated.
from typing import Generic, TypeVar
T = TypeVar("T")
class Foo(Generic[T]):
def __init__(self) -> None:
message_t = self.message_type()
reveal_type(message_t(), expected_text="T@Foo")
def message_type(self) -> type... |
import numpy as np
import scipy as sp
import scipy.ndimage as nd
import keras.models as km
import keras.layers as kl
import keras.regularizers as kr
import keras.utils as ku
import sklearn.model_selection as sm
import sklearn.linear_model as sl
import sklearn.svm as sv
import sklearn.feature_extraction.image as sf
... |
import re
class PlayerParser:
@staticmethod
def parse_player_list(players_properties):
regex = re.compile(r"\(player \"(.+?)\"\)")
player_properties_list = regex.findall(players_properties)
player_list = []
for player_property in player_properties_list:
player_l... |
"""
test_yieldcalculations.py
Note that sone tests are in doctests. Do not replicate them within unitt tests, as we then have to maintain
the same test twice.
"""
from unittest import TestCase
import doctest
import simplepricers.yieldcalculations as yieldcalculations
from simplepricers.bonds_curves import ZeroCurve
... |
"""
@Author:lichunhui
@Time:
@Description: 百度百科爬虫
"""
import re
import copy
from urllib.parse import unquote
from scrapy.spiders import Rule
from scrapy.selector import Selector
from baikeSpider.items import BaiduSpiderItem
from scrapy.linkextractors import LinkExtractor
from .redis_spider import RedisCrawlSpider
f... |
import helper
object=helper.Helper()
object.plot_original()
object.change_basis()
object.show_changed()
object.full_reconstruction()
object.show_full_reconstructed() |
# -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright (c) 2015 Alex Headley <aheadley@waysaboutstuff.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, inclu... |
"""added symbol
Revision ID: a52770687d22
Revises: 7e2a9aed0504
Create Date: 2018-04-04 22:23:11.306246
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a52770687d22'
down_revision = '7e2a9aed0504'
branch_labels = None
depends_on = None
def upgrade():
# #... |
# Copyright 2014 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.
# Invokes gperf for the GN build.
# Usage: gperf.py [--developer_dir PATH_TO_XCODE] gperf ...
# TODO(brettw) this can be removed once the run_executable rule... |
#!/bin/python3
class Request:
def __init__(self, title, description, is_private=False):
self.title = title
self.description = description
self.is_private = is_private
def get_request():
request_data = {
'title': self.title,
'description': self.description,
'is_private': self.is_p... |
from question_generation.pipelines import pipeline
def make_quiz(text_input):
qg = pipeline("question-generation")
return qg(text_input)
|
import psycopg2
import pandas as pd
from sklearn.cross_validation import train_test_split
from sklearn import metrics
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import CountVectorizer
import bills.wrangle.create_corpus
from bills.ingest.setup_database import Subject_Score
from sq... |
import numpy as np
from scipy.optimize import minimize
from functools import reduce
import pandas as pd
from .utils import fn_varml_sandwich_Npsi_NKbeta_Nsgmsq, format_output, fn_mg_est, fn_significance_stars
class RegressionResultsWrapper:
"""
Class that wraps the regression results of the HSAR model.
"""... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#======================================================================
#
# cannon.py
#
# 服务主程序,启动transmod,再根据配置文件启停连接 Channel 0的服务。
#
#======================================================================
import sys, time, struct
import os, errno, socket, mmap
import da... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
import numpy as np
import copy
import random
import platform
import subprocess
import sys
import statistics
from UDFManager import UDFManager
import os
import pickle
from multiprocessing import... |
from CanvasAPI.util import callhelper
from CanvasAPI.courses import settings, users
from CanvasAPI import instance
__all__ = ["get_history", "get_student_history", "get_grader_history"]
def get_course(course_id):
'''Gets a course'''
url_str = "audit/grade_change/courses/{}?include[]=current_grade".f... |
from behave import given, when, then
@given('we have behave installed')
def given_test(context):
pass
@when('we implement a test')
def when_test(context):
context.hello = 'YES'
assert True is not False
@then('behave will test it for us!')
def then_test(context):
assert context.failed is False
|
from nni.assessor import Assessor, AssessResult
import logging
_logger = logging.getLogger(__name__)
class MemoryAssessor(Assessor):
'''评估模型内存是否满足要求
Args:
flash_mem: 闪存可用大小
ram_mem: 运行内存可用大小
'''
def __init__(self, flash_mem, ram_mem, **kwargs):
self.flash_m... |
"""Test sample sync."""
from typing import Optional
from samples.sample_tap_gitlab.gitlab_tap import SampleTapGitlab
from singer_sdk.helpers import _catalog
from singer_sdk.helpers._singer import Catalog
COUNTER = 0
SAMPLE_CONFIG_BAD = {"not": "correct"}
def test_gitlab_sync_all(gitlab_config: Optional[dict]):
... |
from wideryolo.data_utils.data_preprocessing import (
train_file,
val_file,
yolo_image_file,
yolo_label_file,
)
import shutil
train_path = train_file()
val_path = val_file()
image_path = yolo_image_file()
label_path = yolo_label_file()
shutil.rmtree("./wider_data/wider_face_split/")
|
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
def fiftycatGBM():
# Training set has only 45 categories cat1 through cat45
#Log.info("Importing 50_cattest_train.csv data...\n")
train = h2o.import_file(path=pyunit_utils.locate("smalldata/gbm_test/50_cattest_train.csv... |
from TopCompiler import FuncParser
from TopCompiler import Error
from TopCompiler import Parser
from TopCompiler import Scope
from TopCompiler import Types
import AST as Tree
def parseJson(parser):
parse = Tree.Decoder(parser)
parser.currentNode.addNode(parse)
parser.currentNode = parse
parser.nextTok... |
#!/usr/bin/env python
# Import the library
import matplotlib.pyplot as plt
# %matplotlib inline
# Create a class Circle
class Circle(object):
# Constructor
def __init__(self, radius=3, color='blue'):
self.radius = radius
self.color = color
# Method
def add_radius(self, r):
... |
# Copyright (C) 2019 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Modals for create objects."""
from lib import base
class SetValueForAsmtDropdown(base.Modal):
"""Modal for set value for assessment custom attribute."""
def __init__(self, driver):
super(SetVal... |
print("Let's play with some variables!")
food = "myFood"
print(food)
fo0d = "my bad food"
foOd = "another food"
f_00d = "something completely different"
# there is full Unicode support for variables, but lets use English for variable names
ēdiens = "my food" # not a good idea
myFood = "mans ēdiens" # this is completel... |
# coding: utf-8
"""
Licensed to Cloudera, Inc. under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. Cloudera, Inc. licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use thi... |
# Copyright (c) 2013, Frappe and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
from frappe import utils
from frappe.utils import flt
from datetime import datetime,timedelta,date
from f... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import copy
import sys
import threading
import warnings
from typing import Any, Optional, Tuple
import numpy as np
from .. import _core
from .axestuple import AxesTuple
from .axis import Axis
from .deprecated import deprecated
f... |
"""
Setup for different kinds of Tuya climate devices
"""
import logging
from . import DOMAIN
from .const import (
CONF_CLIMATE,
CONF_DEVICE_ID,
CONF_TYPE,
)
from .generic.climate import TuyaLocalClimate
from .helpers.device_config import config_for_legacy_use
_LOGGER = logging.getLogger(__name__)
async... |
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
import os
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
import random
import numpy as np
import cv2
letter_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.