content
stringlengths
5
1.05M
import logging from datetime import datetime from normality import stringify from sqlalchemy.dialects.postgresql import JSONB from aleph.core import db from aleph.model import Role, Collection from aleph.model.entityset import EntitySet from aleph.model.common import iso_text, DatedModel, Status from aleph.model.commo...
from croniter import croniter from datetime import datetime from kubernetes import client, config import time import os def get_pod_creation_date(podName, podNamespace): try: config.load_incluster_config() except: config.load_kube_config() v1 = client.CoreV1Api() podStatu...
from __future__ import print_function from __future__ import absolute_import from __future__ import division from itertools import groupby import logging from typing import Any, Dict, Sequence from sciencebeam_utils.utils.collection import flatten from .evaluation.scoring_methods.scoring_methods import ScoringMethod...
from .train_topicbert import *
def add_node(v): global node_count if v in nodes: print("Node already exists") else: node_count+=1 nodes.append(v) for n in graph: n.append(0) temp=[] for i in range(node_count): temp.append(0) graph.append(temp) def ...
from django.contrib.postgres.fields import ArrayField from django.contrib.auth.models import AbstractUser from django.utils.text import slugify from django.db import models import uuid class PushPool(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharF...
from setuptools import setup, find_packages setup(name='vposer', version='0.1.0', packages=['vposer'], include_package_data=True, author='zzilch', author_email='zz@zilch.zone', maintainer='zzilch', maintainer_email='zz@zilch.zone', url='https://github.com/zzilch/vposer', ...
import argparse import os import torch import torch.utils.data import torchvision import matplotlib.pyplot as plt import numpy as np from PIL import Image from PIL import ImageDraw from PIL import ImageFont import tqdm parser = argparse.ArgumentParser() parser.add_argument('--dataset', type=str, default='../../data/v...
#when we get unexpected results try: #to attempt to run something print(a) except: #even though a is not defined print("a is not defined!") try: print(a) except NameError: #when error message shows up print("a is still not defined") except: print("Something else went wrong.") print(a) #...
from constants import * from ZurichInstruments_UHFLI import ZurichInstruments_UHFLI import qt uhf = ZurichInstruments_UHFLI('dev2232') znb = qt.instruments.create('ZNB20', 'RhodeSchwartz_ZNB20', address=ZNB20_ADDRESS, reset=True) # rte = qt.instruments.create('RTE1104', 'RhodeSchwartz_RTE1104', address = 'TC...
from flask_login import UserMixin from app import db, login from werkzeug.security import generate_password_hash, check_password_hash class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(50)) password_hash = db.Column(db.String(250)) roles = db....
import sys from mpplugs.Namespace import Namespace Levels = Namespace(Debug = 0, Info = 1, Note = 2, Warn = 3, Critical = 4) class StreamOutput: def __init__(self, stream, colored=False, minLevel=Levels.Debug, maxLevel=Levels.Critical, enabled=True): self.stream = stream self.colored = colored self.minL...
import os, sys ROOT_PATH = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')) sys.path.append(ROOT_PATH) from memsql_loader.api.caller import ApiCaller api = ApiCaller()
import setuptools with open("readme.md", "r") as fh: long_description = fh.read() setuptools.setup( name="genomicinfo", version="0.0.1", author="Rishab Mallick", author_email="rishabmallick6@gmail.com", description="Extract genomic variants from scientific articles", long_description=long_...
""" program_data.api ~~~~~~~~~~~~ :copyright: (c) 2018 by nyankobass. :license: MIT, see LICENSE for more details. """ import datetime import logging LOGGER = logging.getLogger(__name__) class ProgramData: '''番組データ''' def __init__(self, time: datetime.datetime, title: str, station: str): ''' コンストラク...
from enum import Enum from typing import List, Optional, TypeVar import strawberry from strawberry.field import StrawberryField def test_enum(): @strawberry.enum class Count(Enum): TWO = "two" FOUR = "four" @strawberry.type class Animal: legs: Count # TODO: Remove refere...
# -*- coding: utf-8 -*- """This code is a part of Hydra Toolkit .. module:: hydratk.extensions.testenv.translation.en.help :platform: Unix :synopsis: English language translation for TestEnv extension help generator .. moduleauthor:: Petr Rašek <bowman@hydratk.org> """ language = { 'name': 'English', '...
import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data import matplotlib.pyplot as plt mnist=input_data.read_data_sets("MNIST_data/", one_hot=True) X_train=mnist.train.images Y_train=mnist.train.images X_test=mnist.test.images Y_test=mnist.test.labels dimX=X_train.shape[...
#!/usr/bin/env python # encoding: utf-8 from __future__ import unicode_literals from django.conf.urls import url from rest_framework.authtoken.views import obtain_auth_token from v1.accounts.views import custom_obtain_auth_token urlpatterns = [url(r'^obtain-auth-token/$', custom_obtain_auth_token)]
# Owner(s): ["module: autograd"] import contextlib import gc import io import math import os import random import sys import tempfile import threading import time import unittest import uuid import warnings import operator import subprocess from copy import deepcopy from collections import OrderedDict from itertools i...
#!/usr/bin/env python import re import pandas as pd import numpy as np text = '' with open('output.txt') as f: text = f.read() # Split text by lines lines = text.split('\n') # Remove empty lines lines = [l for l in lines if l.strip() != ''] new_lines = [] # Concatenate the lines because the information of one p...
import logging import time import vim import rpc logger = logging.getLogger(__name__) logger.setLevel(20) #START_TIME = int(time.time()) BASE_ACTIVITY = { 'details': 'Idle', #'timestamps': { # 'start': START_TIME # }, 'assets': { 'large_text': 'Vim', 'large_image': 'vim_logo',...
from gusto import * from firedrake import (IcosahedralSphereMesh, PeriodicIntervalMesh, ExtrudedMesh, SpatialCoordinate, as_vector, VectorFunctionSpace, sin, exp, Function, FunctionSpace) import pytest from math import pi @pytest.fixture def state(tmpdir, geometry): "...
import collections import contextlib import time class Report(object): """A simple way to generate reports.""" def __init__(self, filename): self.filename = filename self._report = collections.OrderedDict() self._start = time.time() def add(self, name, value): self._repor...
# https://docs.python.org/3/library/functions.html#map # -- ================================================== -- # Python map() examples # Its syntax is: map(function, iterable, ...) # -- ================================================== -- # Example 1: Working of map() # ========================...
from django.core.exceptions import PermissionDenied from django.utils.translation import gettext as _, ngettext from rest_framework import serializers from rest_framework.response import Response from ....acl.objectacl import add_acl_to_obj from ....conf import settings from ....core.apipatch import ApiPatch from ...m...
'''Realizar una clase que administre una agenda. Se debe almacenar para cada contacto el nombre, el teléfono y el email. Además deberá mostrar un menú con las siguientes opciones. Añadir contacto Lista de contactos Buscar contacto Editar contacto Cerrar agenda''' import os class Agenda: def __init__(self):...
#!/usr/bin/python # email_url.py # emails the video URL to the presenters from django.core.mail import get_connection, EmailMessage from django.template import Context, Template from process import process from post_yt import post from email_ab import email_ab # from django.conf import settings class email_title(e...
from typing import NamedTuple class GlobalArgs(NamedTuple): config_path: str confirm: bool
DOCUMENTATION = """ --- module: script version_added: "0.9" short_description: Runs a local script on a remote node after transferring it description: - "The M(script) module takes the script name followed by a list of space-delimited arguments. " - "The local script at path will be transferred to the...
import argparse import sys from sudoku import SudokuGenerator def parse_arguments(argv): parser = argparse.ArgumentParser(description="description") parser.add_argument("-s", "--seed", type=str, default=42) parser.add_argument("-l", "--level", type=int, default=50) return parser.parse_args() def...
import unittest import datafilereader class TestImports(unittest.TestCase): @classmethod def setUpClass(cls): cls.project = datafilereader.construct_project(datafilereader.IMPORTS) suite = cls.project.data.suites[1] cls.imports = [i for i in suite.imports] @classmeth...
# Builtins import datetime as dt from typing import Any, Dict, List, Tuple import requests import re from zoneinfo import ZoneInfo # External libraries import tzlocal import pandas as pd import yfinance as yf # Submodule imports from harvest.api._base import API from harvest.utils import * class YahooStreamer(API):...
""" This filter is based on Fast "A Fast Approximation of the Bilateral Filter using a Signal Processing Approach" (Paris & Durand, 2006). For more information please follow references of The Report. Code is highly inspired by 4 codes, 1 C++, 1 Python and 2 MatLab, available on The Internet. For details see references...
import logging from crond import CrondJob from crond.threatpost import TheatPost logging.basicConfig(filename='workers.log', format='%(asctime)s %(levelname)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG) def regist_worker(WorkerClass)...
# Copyright 2020 The universal_double_descent 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 requi...
''' The provided code stub reads and integer, n, from STDIN. For all non-negative integers i<n, print i^2. ''' if __name__ == '__main__': n = int(input()) for i in range(n): print(i**2)
__all__ = ['blocks', 'bp', 'circuit', 'generate_bp_mappings', 'mjp', 'obf', 'rbp', 'timer', 'toposort']
@@ -90,7 +90,7 @@ def get_data(self): def send(self): eccoin.sendpacket(self.packet['_to'], self.packet['_id'], self.packet['_ver'], json.dumps(self.packet)) eccoin.sendpacket(self.packet['_to'], self.packet['_id'], json.dumps(self.packet)) #######################################################################...
from echo.qt.connect import * from echo.qt.connect import _find_combo_data, UserDataWrapper
# module to analyze single cell RNAseq data import numpy as np import matplotlib.pyplot as plt import pandas as pd import polyseq as pseq import umap class Seq_mat(): def __init__(self, gene_path, seq_matrix_path, FB_names=False): if(FB_names==False): self.genes = pd.read_csv(gene_path, delimi...
# Angold4 20200712 class CaesarCipher: """class for doing encryption and decryption using a Caesar cipher""" def __init__(self, shift): """ construct caesar cipher using given integer shift for rotation ensure that every obj has it own decode list """ encoder = [None] * ...
# 2. Load File. data = np.load("File Directory..") files= data.files # 3. The Shape of the Elements. print('Shape - "Image" item: ' + str(data['image'].shape)) print('Shape - "Label" item: ' + str(data['label'].shape)) # 4. Let's Set a Random Index and Visualize it. index = "Give Random Number for Prediction.." plt.i...
# coding: utf-8 from __future__ import annotations from datetime import date, datetime # noqa: F401 import re # noqa: F401 from typing import Any, Dict, List, Optional, Union, Literal # noqa: F401 from pydantic import AnyUrl, BaseModel, EmailStr, validator, Field, Extra # noqa: F401 from aries_cloudcontroller.m...
from sklearn.cluster import KMeans, MiniBatchKMeans import time import numpy as np class Cluster: def __init__(self, embedding_vectors): """ An embeddding space (embedding vectors) should be provided """ self.embedding_vectors = embedding_vectors def kmeans(self, number_of_clu...
from picbackend.views.utils import clean_int_value_from_dict_object from picbackend.views.utils import clean_string_value_from_dict_object def validate_put_rqst_params(rqst_body, rqst_errors): validated_params = { 'rqst_action': clean_string_value_from_dict_object(rqst_body, "root", "db_action", rqst_erro...
from typing import Any, Optional from pydantic import BaseSettings, EmailStr, validator class Settings(BaseSettings): DETA_PROJECT_KEY: str DETA_BASE_NAME: str = "godwit" EMAIL_VERIFICATION: bool = True FROM_EMAIL: EmailStr # SMTP SMTP_TLS: bool = True SMTP_PORT: Optional[int] = None ...
import pytest import subprocess import warnings import conda_remove_envs as cenv VALID_ENV_NAMES = [["test"], ["test", "test2"]] CLI_STR = "python conda_remove_envs.py" def create_env(env: str): subprocess.run(f"conda create --name {env}".split()) @pytest.mark.parametrize("envlist", VALID_ENV_NAMES) def test_...
# -*- coding: utf-8 -*- # @COPYRIGHT_begin # # Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland # # 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.apac...
#!/usr/bin/env python3 """ Author : Ken Youens-Clark <kyclark@gmail.com> Date : 2019-02-07 Purpose: Translate DNA/RNA to proteins """ import argparse import os import sys # -------------------------------------------------- def get_args(): """get command-line arguments""" parser = argparse.ArgumentParser( ...
""" Usage Record splitter to split an UR XML document into one or more sub elements each containing a usage record. Author: Henrik Thostrup Jensen <htj@ndgf.org> Copyright: Nordic Data Grid Facility (2010) """ from xml.etree import cElementTree as ET from sgas.usagerecord import urelements as ur class ParseError...
from datetime import datetime from . import db from ..models import User from flask import current_app def SeedAll(): CreateTables() SeedUsers() def CreateTables(): from sqlalchemy import MetaData metadata = MetaData() metadata.reflect(db.get_engine(bind='default')) if 'user' not in metadata.t...
""" Module to calculate lap times for a given car and racing line. """ from matplotlib import pyplot from constants import AIR_DENSITY, GRAV_ACCELERATION class LapTimeCalculator: """ Class to calculate lap times for a given car and racing line. """ def __init__(self): """ Method to ...
# Copyright 2016-present CERN – European Organization for Nuclear Research # # 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...
""" Test tf utility functions mainly in garage.tf.misc.tensor_utils """ import numpy as np import tensorflow as tf from garage.tf.misc.tensor_utils import compute_advantages, get_target_ops from tests.fixtures import TfGraphTestCase class TestTensorUtil(TfGraphTestCase): """Test class for tf utility functions."...
import torch import torch.nn as nn import torch.nn.functional as F import math from utils.utils import bilinear_sampler, coords_grid # from compute_sparse_correlation import compute_sparse_corr, compute_sparse_corr_torch, compute_sparse_corr_mink from setrans import CrossAttFeatTrans, gen_all_indices, SETransInputFeatE...
""" 2019 (c) piteren some encoders """ from ptools.neuralmess.get_tf import tf from ptools.neuralmess.base_elements import my_initializer, list_of_layers from ptools.neuralmess.layers import zeroes, lay_dense, lay_conv1D, attn, tf_drop # TODO: probably in tf 1.15.2 histogram 'family=' should be replaced with ...
# Generated by Django 2.1.5 on 2019-01-17 17:55 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('grapher', '0002_jasonparser_jasonparseralias'), ] operations = [ migrations.CreateModel( name='...
#!/usr/bin/env python # coding: utf-8 # # Import libraries # In[1]: # Ref: http://puremonkey2010.blogspot.com/2017/06/toolkit-keras-mnist.html # http://yhhuang1966.blogspot.com/2018/03/keras-mlp.html # https://dotblogs.com.tw/greengem/2017/12/17/094023 # https://medium.com/@yehjames/%E8%B3%87%E6%96%9...
############################################################################## # PURPOSE: # (This is a python input file class to set up the general parameters that # describe an Space Reference FOM reference frame object.) # # REFERENCE: # (Trick 16 documentation.) # # ASSUMPTIONS AND LIMITATIONS: # ((Inh...
import argparse import pathlib import sys from dataclasses import dataclass, field from pathlib import Path from typing import List @dataclass class Settings: """ Transfer only dataclass that does not perform any checking on the passed values. The validation is performed by the argparse module. All fields...
from django.urls import path from . import views app_name = 'post' urlpatterns = [ path('user/<str:username>/post/<str:slug>/', views.detail, name='detail'), path('user/<str:username>/post/<str:slug>/edit/', views.edit, name='edit'), path('user/<str:username>/post/<str:slug>/delete/', views.delete, name='...
# Standard library import pathlib # Third-party import astropy.table as at import astropy.units as u import h5py import numpy as np import thejoker as tj from schwimmbad.utils import batch_tasks from scipy.stats import truncnorm as _truncnorm from hq.config import Config from hq.log import logger from hq.physics_help...
from nuaal.connections.api import RestBase from nuaal.definitions import DATA_PATH, TIMESTAMP_FORMAT import requests import json from urllib.parse import quote from threading import Thread from queue import Queue from datetime import datetime class CiscoApiBase(RestBase): def __init__(self, url="https://api.cisc...
import torch import pandas as pd from torch.utils.data import Dataset from transformers import AutoTokenizer class MCOCRDataset(Dataset): def __init__(self, pretrained_model, csv_path, is_train, max_len): self.csv_path = csv_path self.is_train = is_train self.max_len = max_len self...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import six import logging import numpy as np import pandas as pd import utils.boxes as box_utils import utils.keypoints as keypoint_utils from core.config import cfg fro...
from rest_framework import permissions class IsOwnerOrReadOnly(permissions.IsAuthenticated): def has_object_permission(self, request, view, obj): # Non-owners can READ content, but will not be able to UPDATE or DELETE if request.method in permissions.SAFE_METHODS: return True ...
with open('log_dump.txt', 'r') as fp: results = fp.readlines() numbers = [] for idx, r in enumerate(results): split_r = r.split(',')[0].split('(') name = (''.join(split_r[:-1])).split('\\')[-1].split('.jpg')[0][:-1] r_tuple = (idx, name, split_r[-1]) # print(r_tuple) numbers.append(r_tuple) numbers = sorted(num...
import pytest from baby_steps import given, then, when from th import PathHolder from valera import validate from valera.errors import ( MaxValueValidationError, MinValueValidationError, TypeValidationError, ValueValidationError, ) from district42_exp_types.numeric import schema_numeric def test_nume...
from __future__ import division from __future__ import print_function import time from library import factory from library import reset_all_hw import multiprocessing as mp # Standby Mode def standby_func(hw, ns): print("Starting Standby") audio = hw['audio'] audio.speak('start') flash = hw['flashlight'] flash...
import sys from chpass.cli import parse_args from chpass.config import OUTPUT_FILE_PATHS, DB_PROTOCOL from chpass.core.object_factory import ObjectFactory from chpass.dal.chrome_db_adapter import ChromeDBAdapter from chpass.dal.db_connection import DBConnection from chpass.dal.db_adapters.history_db_adapter import His...
"""Module for the Fusion Classifier.""" from typing import List from .set_based_classifier import SetBasedClassifier from variation.schemas.classification_response_schema import ClassificationType class FusionClassifier(SetBasedClassifier): """The Fusion classifier class.""" def classification_type(self) -> ...
"""\ Basis set constructor >>> from pyquante2.geo.samples import h >>> bfs = basisset(h,'sto3g') >>> bfs cgbf((0.0, 0.0, 0.0),(0, 0, 0),[3.42525091, 0.62391373, 0.1688554],[0.1543289707029839, 0.5353281424384733, 0.44463454202535485]) >>> bfs.shells [S shell: [3.42525091, 0.62391373, 0.1688554],[0.15432897, 0.53532814...
import re import json import urllib.parse from requests_oauthlib import OAuth2Session # type: ignore from ..module import Module from ..interfaces import IInterpreter from typing import List, Any, Dict, Optional, Tuple class GsheetError(RuntimeError): pass FORTHIC = ''' ["headers"] VARIABLES : SHEET-ROWS U...
# encoding: utf-8 """ lxml custom element classes for picture-related XML elements. """ from __future__ import ( absolute_import, division, print_function, unicode_literals ) from .. import parse_xml from ..ns import nsdecls from .shared import BaseShapeElement from ..xmlchemy import BaseOxmlElement, OneAndOnlyO...
""" Copyright (C) 2018 Intel Corporation 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 agreed to in writing, softw...
#!/usr/local/bin/python3 # /usr/bin/python3 # Set the path to your python3 above from gtp_connection import GtpConnection from board_util import GoBoardUtil from board import GoBoard class Gomoku(): def __init__(self): """ Gomoku player that selects moves randomly from the set of legal moves. ...
import unittest from elliottlib.cli.find_builds_cli import _filter_out_inviable_builds, _find_shipped_builds from elliottlib.brew import Build import elliottlib from flexmock import flexmock import json import mock class TestFindBuildsCli(unittest.TestCase): """ Test elliott find-builds command and internal f...
def main(request, response): response.status = 302
from graphics import * def main(): win=GraphWin("Click and Type",400,400) for i in range(10): pt=win.getMouse() key=win.getKey() label=Text(pt,key) label.draw(win) win.close() main()
#!/usr/local/bin/python # -*- coding: iso-8859-15 -*- import os.path import sys import getopt from time import gmtime, strftime #decorator for tail recursion class TailRecurseException: def __init__(self, args, kwargs): self.args = args self.kwargs = kwargs def tail_call_optimized(g): def fu...
import sys # for exit import os # for file exist check import cv2 # for image operations, face recognition # Create a CascadeClassifier object. face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") # Get image path from user. # image_path = raw_input("Insert image path: ") # if...
# coding:utf-8 from __future__ import absolute_import, unicode_literals from collections import OrderedDict import graphene from graphene.types.objecttype import ObjectTypeOptions from graphql_relay.node.node import from_global_id from sqlalchemy.exc import SQLAlchemyError from .types import SQLAlchemyObjectTypes, S...
import sys import argparse import imgick.commands as commands if __name__ == '__main__': # parse args parser = argparse.ArgumentParser( description='Create and edit imgick projects from the commandline', usage='imgick <command> [<args>]') parser.add_argument('command', help='Subcommand to ...
# Use the W array and G array to calculate win percentages win_percs_np = calc_win_perc(baseball_df['W'].values, baseball_df['G'].values) # Append a new column to baseball_df that stores all win percentages baseball_df['WP'] = win_percs_np print(baseball_df.head()) %%timeit # Use the W array and G array to calculate...
import random from string import ascii_lowercase from unittest import TestCase from elastic_dql.exceptions import SchemaError from elastic_dql.schema import SchemaFactory class SchemaFactoryTestCase(TestCase): def test_instance_type(self): schema_factory = SchemaFactory.get_instance() self.asser...
from meld.database.classes import Table, Column sets = Table('sets', [ Column('id', int, primary_key=True, autoincrement=True), Column('name', str), Column('year', int), Column('studio', str, default=None) ])
from pythoncom import com_error import time from .tools import _kill_excel, _load_excel def load_addin(excel, addin_str, sleep_time=5): try: _load_addin(excel, addin_str, sleep_time=sleep_time) except com_error: print('Did not start excel correctly') time.sleep(10) print('Killi...
#!/usr/bin/env python import unicodecsv import sys import codecs import json from datetime import datetime, timedelta from openpyxl.utils.datetime import from_excel FIELDNAMES = 'ref_number,amendment_number,amendment_date,agreement_type,recipient_type,recipient_business_number,recipient_legal_name,recipient_operatin...
# This sample tests the ability to detect errant assert calls # that are always true - the "reportAssertAlwaysTrue" option. # This should generate a warning. from typing import Any, Tuple assert (1 != 2, "Error message") a: Tuple[Any, ...] = (2, 3) assert a b = () assert b c = (2, 3) # This should generate a w...
"""\ PEP INFO PEP 349 -- Allow str() to return unicode strings Status: Rejected Created: 2005-08-02 MODULE INFO This module changes str() to allow returning **bytes**. Since all strings are unicode starting from Python 3, the title is changed. Note that str() is made a function, and the three argument form is dis...
import sys import os from common import PostProcess, update_metrics_in_report_json from common import read_limits, check_limits_and_add_to_report_json from common.stability import * def main(): mat_file_name = sys.argv[1] if not os.path.exists(mat_file_name): raise IOError('Given result file does not ...
import argparse import re from itertools import cycle from operator import itemgetter from pathlib import Path import numpy as np import seaborn import torch from matplotlib import pyplot as plt from matplotlib.lines import Line2D seaborn.set() DEF_SIZE = 24 plt.rc('font', size=DEF_SIZE) # controls default text size...
import io import logging import re import time from pathlib import Path import boto3 from ..api import API from ..common import annotation_status_int_to_str, annotation_status_str_to_int from ..exceptions import SABaseException from .images import ( delete_image, get_image_annotations, get_image_bytes, get_image_...
import h5py import numpy as np import pandas as pd imgData = [] row = 0 with open('../data/trainImages.txt', 'r', encoding='utf-8') as source: for line in source: imgData.append(line.strip()) row += 1 # create and write df = pd.read_hdf('../data/cityscapes_paths_train.h5', key='df').sample(frac=1)...
#!/usr/local/env python3 """ Simple k-means clustering example implementation. No optimization attempts have been made, this is pure for example and educational purposes. Data is randomly generated to form three clusters, the k-means is used to learn the centers of these data clusters. """ import math from matplotlib ...
import discord from redbot.core import commands, bot, Config from .eris_event_lib import ErisEventMixin BaseCog = getattr(commands, "Cog", object) class Sudo(BaseCog, ErisEventMixin): def __init__(self, bot_instance: bot): super().__init__() self.bot = bot_instance self.whois = self.bot....
#!/usr/bin/env python import rospy from turtlesim.msg import Pose def callback(data): rospy.loginfo(data) def getposition(): # init ros node rospy.init_node('getposition', anonymous=True) rospy.Subscriber('/turtle1/pose', Pose, callback) rospy.spin() if __name__ == "__main__": getposition...
r""" .. autofunction:: openpnm.models.geometry.throat_perimeter.cylinder .. autofunction:: openpnm.models.geometry.throat_perimeter.cuboid """ import numpy as _np def cylinder(target, throat_diameter='throat.diameter'): r""" Calcuate the throat perimeter assuming a circular cross-section Parameters ...
#!/usr/bin/python3 __author__ = "Kevin GUILLEMOT" __credits__ = [] __license__ = "Apache2.0" __version__ = "1.0.0" __maintainer__ = "" __email__ = "kevin.guillemot2@gmail.com" __doc__ = "Create a pattern for fuzzing" import sys def create_pattern(nb_bytes): alphabet = ["ABCDEFGHIJKLMNOPQRSTUVWXYZ", ...