content
stringlengths
0
894k
type
stringclasses
2 values
from PyQt5 import QtCore, QtGui, QtWidgets class ROITable(QtWidgets.QWidget): """ GUI element holding information of regions segmented from low resolution image stored in slide scanner image """ def __init__(self, parent=None, table_widget=None): super(ROITable, self).__init__(table_wid...
python
from .lattice import gen_lattice
python
CONFIG_PATH_ENV_KEY='APTIBLE_CONFIG_PATH' ACCESS_TOKEN_ENV_KEY='APTIBLE_ACCESS_TOKEN'
python
from crowdin_api import CrowdinClient from time import sleep import urllib.request import json import re from pathlib import Path class UECrowdinClient(CrowdinClient): def __init__( self, token: str, logger=None, organization: str = None, project_id: int = None, sil...
python
from config.redfish1_0_config import config from config.auth import * from config.settings import * from logger import Log from json import loads, dumps import pexpect import pxssh import subprocess LOG = Log(__name__) class Auth(object): """ Class to abstract python authentication functionality """ @...
python
import sys import igraph as _ig from . import _c_louvain from ._c_louvain import ALL_COMMS from ._c_louvain import ALL_NEIGH_COMMS from ._c_louvain import RAND_COMM from ._c_louvain import RAND_NEIGH_COMM from collections import Counter # Check if working with Python 3 PY3 = (sys.version > '3') def _get_py_capsule(g...
python
# -*- coding: utf-8 -*- import json import unittest from flask import url_for from flask_testing import TestCase from flask_login import login_user from app import create_app, db from app.models import User, Todo, TodoList class TodolistAPITestCase(TestCase): def create_app(self): return create_app('t...
python
#!/usr/bin/env python3 import wdt # Compute cost field from image cost_field = wdt.map_image_to_costs('images/ex2.png') # Plot the cost field wdt.plot(cost_field) # Compute the distance transform from the cost field distance_transform = wdt.get_weighted_distance_transform(cost_field) # Plot the result wdt.plot(distanc...
python
""" Provides a formatter for AoE2 AI rule files (.per) """ from antlr4 import FileStream, InputStream, StdinStream, CommonTokenStream, ParseTreeWalker from .perparse import PERLexer, PERParser from .formatted_per_listener import FormattedPERListener def format_per(*, in_path=None, in_string=None, in_stdin=False, out...
python
# ---------------------------------------------------------------------------- # Copyright (c) 2020, Franck Lejzerowicz. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # -----------------------------------------------------------...
python
from ..token import currency_equals from ..currency import Currency, ETHER from ...constants import SolidityType from ...utils import validate_solidity_type_instance from .fraction import Fraction class CurrencyAmount(Fraction): @property def currency(self): return self._currency @staticmethod ...
python
def _create_ref(ref_type, pkg_name, name): """Creates a reference for the specified type. Args: ref_type: A `string` value. Must be one of the values in `reference_types`. pkg_name: The package name as a `string`. name: The name of the item as a `string`. Returns:...
python
# Imports from sqlalchemy import String, Integer, Float, Boolean, Column, and_, ForeignKey from connection import Connection from datetime import datetime, time, date import time from pytz import timezone import pandas as pd import numpy as np import os from os import listdir from os.path import isfile, join from open...
python
"""20.07.2015 PyOSE: Stacked exomoons with the Orbital Sampling Effect.""" import PyOSE import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib import rc #import xlwt #from tempfile import TemporaryFile from numpy import pi # Set stellar parameters StellarRadius = 0.7 * 696342. # km limb1 = 0.597...
python
# This is similar to test1, but this time B2 also inherits from B1, which allows it to override its config data. # B2 also overrides base1_2, like D1. # The order of inheritace in F is also reversed ([D1, B2] instead of [B2, D1]) # Since the last override of base1_2 in inheritance order is in B2, base1_2 must now # hav...
python
# coding=utf-8 import unittest import requests as req from app.api.base import base_name as names from app.api.base.base_sql import Sql from app.api.src.touches_from_api import add_new_point class TestSetPoint(unittest.TestCase): def test_set_point(self): origin_x = 55.02999 origin_y = 82.921098...
python
from flask import ( redirect, request, url_for, Blueprint, render_template ) from flask_sqlalchemy import model from sqlalchemy.orm import session from . import models todo = Blueprint("todo", __name__) def get_entry(id): return models.Entry.query.filter(models.Entry.id == id).first() def ...
python
# -*- coding=utf-8 -*- # Copyright (c) 2019 Dan Ryan from datetime import datetime, timedelta from typing import List from airflow import DAG from airflow.hooks.S3_hook import S3Hook from airflow.models import Variable from airflow.operators.python_operator import PythonOperator from airflow_salesforce_plugin.hooks i...
python
# Copyright (c) 2020 Simons Observatory. # Full license can be found in the top level "LICENSE" file. import os import sys import numpy as np from scipy.signal import firwin, fftconvolve import toast class Lowpass: """ A callable class that applies the low pass filter """ def __init__(self, wkernel, fmax,...
python
from PIL import Image from random import shuffle import sys from scipy.misc import imread from scipy.linalg import norm from scipy import sum, average import numpy as np def memoize(f): """ Memoization decorator for functions taking one or more arguments. """ class memodict(dict): def __init__(self, f)...
python
# -*- coding: utf-8 -*- import pytest from wemake_python_styleguide.violations.naming import ( PrivateNameViolation, TooShortVariableNameViolation, WrongVariableNameViolation, ) from wemake_python_styleguide.visitors.ast.naming import ( VARIABLE_NAMES_BLACKLIST, WrongNameVisitor, ) function_test ...
python
import unittest from markdown_to_trello.markdown_to_trello import MarkdownToTrello, SaveCards, Card import pytest class ConverterTest(unittest.TestCase): def test_simplest(self): text = 'Do groceries' cards = MarkdownToTrello(text).convert_to_cards() self.assertTrue(len(cards), 1) ...
python
import unittest from data_objects import Rover from services import turn_commands as tc from tests.test_environment import rovers from parameterized import parameterized class TestTurnLeftFromNorthCommand(unittest.TestCase): def test_turn_turns_rover_to_west(self): s = tc.TurnLeftFromNorthCommand() ...
python
# BUG: shift with large periods creates mulfunctioning dtypes with master branch #44978 import numpy as np import pandas as pd print(pd.__version__) df = pd.DataFrame(np.random.rand(5, 3)) result = df.shift(6, axis=1, fill_value=None) print(result) expected = pd.DataFrame(np.full((5, 3), np.nan)) pd.testing.asse...
python
""" Competitive Programming Sanity Checker """ __author__ = 'Kevin Yap' __version__ = '1.0.0' __license__ = 'MIT'
python
import os import datetime as dt from text import * # from IPython.display import clear_output as clear def clear(): os.system('cls' if os.name == 'nt' else 'clear') class Player: def __init__(self, world): self.location = world.start self.items = [] self.maxhealth = 100 self.h...
python
""" config.py List some configuration parameters for training model Modified by: Caleb Harris (caleb.harris94@gatech.edu) on: 4/10/2020 """ import os from os import path as op from hyperopt import hp # Set filepaths pointing to data that will be used in training data_dir = 'imgs//DC_imgs//classify_fixes' t...
python
import os import importlib # automatically infer the user module name (in case there is a change during the development) user_module_name = os.path.split(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))[1] submodule_name = os.path.split(os.path.abspath(os.path.dirname(__file__)))[1] # automatically impo...
python
import math from whylogs.proto import LongsMessage class IntTracker: """ Track statistics for integers Parameters --------- min Current min value max Current max value sum Sum of the numbers count Total count of numbers """ DEFAULTS = { ...
python
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. """ Spark utilities. """ from .spark_net import run_spark_net_from_known_assembly, run_spark_net # noqa: F401
python
import os import sqlite3 from colorama import Fore import re tables_path = os.path.dirname(__file__) + "/tables/" database_name = "elements_limits.db" objects_file = "objects.txt" conn = sqlite3.connect(tables_path + database_name) cursor = conn.cursor() def get_sql(sql): cursor.execute(sql) ...
python
from setuptools import setup import configs try: readme = open('README.rst').read() except: readme = 'Configs: Configuration for Humans. Read the docs at `configs.rtfd.org <http://configs.rtfd.org>`_' setup( name=configs.__title__, version=configs.__version__, author=configs.__author__, descr...
python
from __future__ import absolute_import import torch.nn as nn import torch.nn.functional as F import torch.utils.model_zoo as model_zoo import torchvision as tv from faster_rcnn.faster_rcnn import FasterRCNN import faster_rcnn.network as network """ def get_resnet50_frcnn(): # Create a FasterRCNN with ResNet50 back...
python
class Solution: def XXX(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ ## 旋转题目 找规律 简单的 ## 时间99.5 按层向内旋转 left = 0 right = len(matrix)-1 temp = [0 for i in range(len(matrix))] while left<...
python
#!/usr/bin/env python # Example to solve dense LP problem using (e04mf/lp_solve) # Solve the problem # min cvec^T * x # subject to bl <= A * x <= bu # and if present: blx <= x <= bux from naginterfaces.library import opt from naginterfaces.base import utils import numpy as np print('naginterfaces.l...
python
import fnmatch import glob import io import itertools import logging import os import subprocess from sqlalchemy.orm.exc import NoResultFound from aeromancer.db.models import Project, File, Line from aeromancer import filehandler from aeromancer import utils LOG = logging.getLogger(__name__) def discover(repo_roo...
python
import pygame def load_png(name): """ Load image and return image object """ try: image = pygame.image.load(name) if image.get_alpha() is None: image = image.convert() else: image = image.convert_alpha() except pygame.error: print('Cannot loa...
python
from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from group_norm import * from torch.utils.data import DataLoader, Dataset, TensorDataset from gamm...
python
# -*- coding: utf-8 -*- """Generates summaries of the relation ontology.""" import datetime import os from operator import itemgetter import requests import yaml from tabulate import tabulate from tqdm import tqdm HERE = os.path.abspath(os.path.dirname(__file__)) DIRECTORY = os.path.join(HERE, 'docs', '_data') os.m...
python
import subprocess import os import re import shutil import pytest from test_cookie import basic_project_dict PROJECT_DIRECTORY = os.path.realpath(os.path.curdir) def remove_dir(dirpath): shutil.rmtree(os.path.join(PROJECT_DIRECTORY, dirpath)) def _check_configure(result): try: log_configure = sub...
python
# SPDX-License-Identifier: MIT """ This module contains enumerations for channels of a given monitor mode. """ import enum #=================================================================================================== #===================================================================================...
python
from __future__ import division import numpy as np from photutils.morphology import centroid_com, centroid_1dg, centroid_2dg def recenter(image, pos, window_size = 15, method = "2dg", threshold = 10.): """ Recenter each star in each frame of the image cube before performing aperture photometry to take c...
python
""" DB API中定义了一些数据库操作的错误及异常,下表列出了这些错误和异常: 异常 描述 Warning 当有严重警告时触发,例如插入数据是被截断等等。必须是 StandardError 的子类。 Error 警告以外所有其他错误类。必须是 StandardError 的子类。 InterfaceError 当有数据库接口模块本身的错误(而不是数据库的错误)发生时触发。 必须是Error的子类。 DatabaseError 和数据库有关的错误发生时触发。 必须是Error的子类。 DataError 当有数据处理时的错误发生时触发,例如:除零错误,数据超范围等等。 必须是DatabaseError的子类。 Operationa...
python
import json # Read json def read_json(json_file_path): with open(json_file_path, 'r') as rf: data = rf.read() data_json = json.loads(data) return data_json # Dump json def dump_json(json_file_path, data): with open(json_file_path, 'w') as wf: json.dump(data, wf, indent=4)
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson as json from alipay.aop.api.constant.ParamConstants import * class AlipayCreditAutofinanceLoanCloseModel(object): def __init__(self): self._applyno = None self._orgcode = None self._outorderno = None self._reson = No...
python
from common_grader import CommonGrader import random class RandomPointsGrader(CommonGrader): def __init__(self, *args): super(RandomPointsGrader, self).__init__(*args) def do_grade(self): return random.uniform(0.0, 100.0), random.uniform(0.0, 100.0)
python
import unittest import sys from sqlite.crud_operations import CrudOperations class CrudeOperations(unittest.TestCase): def setUp(self): self.crud = CrudOperations() def test_read_all(self): self.assertIsNotNone(self.crud.read_all()) self.assertIsInstance(self.crud.read_all(),list) ...
python
from django.test import TestCase from app.models import Location, Category, Image # Create your tests here. # location model tests class LocationTestCase(TestCase): def setUp(self): """ Create a location for every test """ Location.objects.create(name="Location 1") def test_l...
python
# Copyright (c) 2005-2009 Jaroslav Gresula # # Distributed under the MIT license (See accompanying file # LICENSE.txt or copy at http://jagpdf.org/LICENSE.txt) # # content: # even if the cid is forced then a simple font is used (if an encoding understood by PDF is used) # if it is not possible to use a simple font ...
python
import datetime import hashlib import http from enum import Enum from typing import Optional, List, Dict from pydantic import ( BaseModel, AnyUrl, constr, conint, HttpUrl, root_validator, validator, ) class AccessMethodType(str, Enum): s3 = "s3" gs = "gs" ftp = "ftp" gsift...
python
from django.db import models from django.db.utils import DatabaseError from django.utils import timezone import logging logger = logging.getLogger('django') class LikeManager(models.Manager): def create(self, creds, **validated_data): try: already_liked = Like.objects.all() \ .fil...
python
from pprint import pprint from functools import reduce from collections import defaultdict data = open("input.txt","r").read() # part 1: 40 times for i in range(50): j = 0 nd = "" while j < len(data): count = 0 curr = data[j] j += 1 count += 1 while j < len(data) an...
python
from .stanzas.action import Action, SYNC_PROTOS from .stanzas.counter import CounterQuery import stanzas.action from peak.util.addons import AddOn from threading import RLock from util.threads.timeout_thread import ResetTimer from collections import defaultdict import warnings import traceback COUNT_TIMEOUT ...
python
"""tests of the AlaskaTemperatureBMI component of permamodel using bmi API""" import datetime import pathlib import pkg_resources from cru_alaska_temperature import AlaskaTemperatureBMI default_config_filename = ( pathlib.Path(pkg_resources.resource_filename("cru_alaska_temperature", "examples")) / "defau...
python
class CostClient(object): CURRENT_COST_URL = '/olap_reports/cost/current' INSTANCE_COST_URL = '/olap_reports/cost/current/instance' HISTORY_COST_URL = '/olap_reports/cost/history' CUSTOM_REPORT_URL = '/olap_reports/custom/' ACCOUNTS_HISTORY_COST_URL = '/olap_reports/custom/893353198679' DAYS_COS...
python
from django.apps import AppConfig class AppointmentsConfig(AppConfig): name = 'appointments' def ready(self): import appointments.signals # register receiver functions for signals
python
import time import numpy as np from scipy.integrate import solve_ivp from scipy.constants import c as c_luz #metros/segundos from scipy.integrate import simps,trapz,cumtrapz c_luz_km = c_luz/1000 import sys import os from os.path import join as osjoin from pc_path import definir_path path_git, path_datos_global = defi...
python
"""Tests related to enriched RichHandler""" import io import logging import re from typing import Tuple, Union import pytest from enrich.console import Console from enrich.logging import RichHandler def strip_ansi_escape(text: Union[str, bytes]) -> str: """Remove all ANSI escapes from string or bytes. If b...
python
class Solution: def alienOrder(self, words: List[str]) -> str: n = len(words) indegrees = [0] * 26 outs = collections.defaultdict(set) for i in range(1, n): w1, w2 = words[i - 1], words[i] for c1, c2 in zip(w1, w2): if c1 != c2: ...
python
import pytest from django.shortcuts import reverse from django.contrib.auth.models import User import json pytestmark = pytest.mark.django_db def test_get_user_return_200(client): url = reverse('users:users') response = client.get(url) assert response.status_code == 200 def test_list_user_return_list_...
python
class Table: def __init__(self, table_file): import collections enc = self.detect_encoding(table_file) val_map = {} char_map = {} err_count = 0 with open(table_file, encoding=enc) as to: line = to.readline() cnt = 1 while line: ...
python
""" TODO """ from selenium.webdriver.common.by import By from .base import BasePageLocators # pylint: disable=too-few-public-methods class CartPageLocators(BasePageLocators): """ TODO """ GO_CHECKOUT = (By.XPATH, '//*[@id="content"]/div[3]/div[2]/a') EMPTY_CART_TEXT = (By.XPATH, '//*[@id="content"...
python
import os import tempfile import pytest from audiomate import corpus from audiomate.corpus import io from audiomate.utils import textfile from tests import resources @pytest.fixture() def writer(): return io.MozillaDeepSpeechWriter() @pytest.fixture() def path(): return tempfile.mkdtemp() class TestMozi...
python
from client import linodeClient import os linode = linodeClient(os.getcwd() + '/../.config') userInput = raw_input("What do you want to do?\n") if userInput == 'create': print(linode.createLinode('3', '1')) if userInput == 'destroy': userInput = raw_input("What do you want to destroy?\n") response = lin...
python
#!/usr/bin/env python #################### # Required Modules # #################### # Generic import json import logging import os import random import subprocess from collections import defaultdict, OrderedDict from glob import glob from pathlib import Path from string import Template # Libs import numpy as np imp...
python
#!/usr/bin/env python3 # Decription: # This program takes user input commands and sends them # to a seperate program that deals with making the motors # on the ROSPerch either turn on or off. # Adapted Sources: # Motor command code is adapted from the UTAP 2020 # code at https://github.com/jdicecco/UTAP/ # ROS talker/l...
python
import serial, keyboard, sys import win32api, win32gui, winsound import time, random, pyautogui import logging, json import cv2, os from datetime import datetime from tkinter import * from PIL import Image, ImageFilter, ImageChops import pytesseract import numpy as np import cv2 import PIL.ImageOps import pyperclip # f...
python
# import numpy as np # import sqlalchemy # from sqlalchemy.ext.automap import automap_base # from sqlalchemy.orm import Session # from sqlalchemy import create_engine, func from flask import Flask, jsonify app = Flask(__name__) @app.route('/api/v1.0/measurement') def api(): data = {"date","prcp" } ...
python
"""Main entrypoint for preprocessor commands.""" import os import argparse import logging import sys import pickle import vectorizer.ast2vec.train as ast2vec from vectorizer.node_map import NODE_LIST from vectorizer.ast2vec import parameters as ast2vec_params LOG_FILE = 'vectorizer/vectorizer.log' def main(): ""...
python
from flask import Flask import youtube_dl app = Flask(__name__) @app.route("/download/<videoId>") def download(videoId): ydl_opts = { "format": "best" } url = "https://www.youtube.com/watch?v=" + videoId with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) return {"s...
python
from flask import Flask, render_template, request, redirect, url_for from flask_sqlalchemy import SQLAlchemy from flask_security import Security, SQLAlchemyUserDatastore, login_required, \ UserMixin, RoleMixin from flask_security.utils import hash_password app = Flask(__name__) app.config['SECRET_KEY'] = 't...
python
''' Setup some basic requirements. Should not be open source due to security problems ''' from app.models import Role # insert roles, User for id=1, Administrator for id=2, Moderator for id=3 Role.insert_roles() # Role.query.all()
python
from django.core.urlresolvers import reverse from menu import Menu from apps.main.menus import ViewMenuItem EducacionMenu = Menu() # Perfil auth_children = ( ViewMenuItem( "Currículo", reverse('curriculo'), weight=30, icon="fa-users"),) Menu.add_item( "educacion", ViewMenu...
python
# ------------------------------------------------------------ # Copyright (c) 2017-present, SeetaTech, Co.,Ltd. # # Licensed under the BSD 2-Clause License. # You should have received a copy of the BSD 2-Clause License # along with the software. If not, See, # # <https://opensource.org/licenses/BSD-2-Clause> # # -...
python
""" Converts RGB and long RGB values to hexadecimal colours Awesome work of Robert Chmielowiec. """ def rgb_to_rgblong(red, green, blue): return red * pow(256, 2) + green * 256 + blue def rgblong_to_rgb(rgb): return rgb // pow(256, 2), (rgb & 65535 ^ 255) // 256, rgb & 255 def rgb_to_hex(red, green, blue)...
python
from common.basedir import BASEDIR is_in_travis = BASEDIR.strip('/').split('/')[0] != 'data'
python
from PyQt5 import QtCore from PyQt5.QtWidgets import QPushButton class DelayPushButton(QPushButton): def __init__(self, text, delay): super().__init__() self._track = -1 self._text = text self._delay = delay self.setText(self._text) self.ani = QtCore.QVariantAnima...
python
import struct import distutils.util import json import warnings import logging logger = logging.getLogger("modbus_server_logger") try: import redis except ImportError: logging.info("Could not import redis, RedisDatastore is not available") class DictDatastore: def __init__(self): self.empty_data...
python
tekst = """Something in the way Ummmmm Something in the way, yeah Ummmmm Something in the way Ummmmm""" print(tekst.count("m"))
python
import os from typing import List from syspass_api_client import api METHODS = { "search": "account/search", "view": "account/view", "view_pass": "account/viewPass", "edit_pass": "account/editPass", "create": "account/create", "edit": "account/edit", "delete": "account/delete", } class A...
python
#MenuTitle: Wrap and Extend Features # -*- coding: utf-8 -*- __doc__=""" Enclose all features with lookups and divide them into sub groups of 3000 lines max. It will also add the useExtension parameter allowing you to have a 32 bits limit insead of the 16 bits. """ import GlyphsApp import string import re # Global va...
python
#%% src 1: https://www.tutorialspoint.com/python_pandas/python_pandas_iteration.htm # In short, basic iteration (for i in object) produces − # Series − values # DataFrame − column labels # Panel − item labels # Note − Do not try to modify any object while iterating. # Iterating is meant for reading and the iterator r...
python
from pyspark.sql import SparkSession def clean_poetry_generated_requirement_file(spark, input_file_path, output_file_path): raw = spark.read.option("delimiter", ";").csv(input_file_path).toDF("dependency", "python-version") # raw.show(5, False) dep = raw.select("dependency") dep.show(50, False) de...
python
# Copyright 2021 The TensorFlow Authors. 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 # # Unless required by applica...
python
import datetime from decimal import Decimal import random from django.utils import unittest from nose.tools import eq_ import amo import amo.tests from market.models import Refund, Price from mkt.stats import tasks from mkt.stats.search import cut, handle_kwargs from mkt.inapp_pay.models import InappConfig, InappPay...
python
from typing import List, Dict, Any, Optional, Text from py2neo import Graph,Node,data,Path, Relationship,NodeMatcher from schema import schema,slot_neo4j_dict class KnowledgeBase(object): def get_entities(self, entity_type:Text, attributes:Optional[List[Dict[Text,Text]]] ...
python
''' Created on Dec 1, 2011 @author: Lukasz Kreczko Email: Lukasz.Kreczko@cern.ch Provides error sources for histograms: - QCD estimation error - QCD shape error - b-tagging error (only for b-tagged hists), flat (in theory only up to 250GeV) - lumi error, flat - JEC error? Flat? '''
python
# This file is part of the bapsflib package, a Python toolkit for the # BaPSF group at UCLA. # # http://plasma.physics.ucla.edu/ # # Copyright 2017-2019 Erik T. Everson and contributors # # License: Standard 3-clause BSD; see "LICENSES/LICENSE.txt" for full # license terms and contributor agreement. # """ Module for ...
python
import rclpy from rclpy.node import Node from threading import Thread, Lock import time import sys import os import os.path from os import path from pathlib import Path import importlib.util from workcell_interfaces.srv import * from workcell_interfaces.msg import * from ot2_workcell_manager_client.retry_api import * f...
python
""" GraphSense API GraphSense API # noqa: E501 The version of the OpenAPI document: 0.4.5 Generated by: https://openapi-generator.tech """ import sys import unittest import graphsense from graphsense.model.address import Address from graphsense.model.entity import Entity from graphsense.model.neig...
python
"""User Model Copyright 2015 Archive Analytics Solutions - University of Liverpool Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by ap...
python
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Count and display statistics of the data. ## Examples ```shell parlai data_stats -t convai2 -dt train:ordered ``` "...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # С клавиатуры вводится цифра (от 1 до 4). # Вывести на экран названия месяцев, соответствующих времени года с номером (считать зиму временем года № 1). if __name__ == '__main__': a = input ('введите число') if a == 1: print ('Зима') elif a == ...
python
import serial from . aiming import GunAngles import time UPDATE_FREQUENCY = 50.0 last_update_time = time.monotonic() ser = None current_gun_angles = GunAngles(pan=0,tilt=0) def get_serial(): global ser # return None #TODO remove # TTY failed, don't retry if ser == -1: return None # Try...
python
from logs import sonarlog import conf_domainsize import conf_nodes import placement_L2 import math import numpy as np # Setup Sonar logging logger = sonarlog.getLogger('placement') class L2Demand(placement_L2.L2): def test_nodes(self, new_domain, nodelist): norms = [] for node in nodelist: ...
python
from sense_hat import SenseHat sense = SenseHat() sense.show_message("Makes sense ;-)")
python
""" Aggregates the data from all databases into one CSV with minimal cutting/processing """ import sqlite3 import csv import pandas as pd HEADERS = list(['track_id', 'title', 'song_id', 'release', 'artist_id', 'artist_mbid', 'artist_name', 'duration', 'artist_familiarity', 'artist_hotttnesss', ...
python
from nipype.interfaces.utility import Function from nipype.pipeline import Node def tsv2subjectinfo(in_file, exclude=None): import pandas as pd from nipype.interfaces.base import Bunch import numpy as np events = pd.read_csv(in_file, sep=str('\t')) if exclude is not None: # not tested ...
python
"""This module defines tests for the user class and its methods""" import unittest from app.models.user import User class UserTests(unittest.TestCase): """Define and setup testing class""" def setUp(self): """ Set up user object before each test""" self.user = User() def test_isuccessful...
python
# (c) Copyright 2020 Hewlett Packard Enterprise Development LP # # @author alok ranjan from tests.nimbleclientbase import SKIPTEST, log_to_file as log '''AlarmsTestCase is not implemented due to external dependency ''' log("**** AlarmsTestCase is not implemented due to external dependency *****'")
python