content
stringlengths
5
1.05M
# coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
# -*- coding: utf8 -*- from network.manager.networkManager import NetworkCallback class ConvCallback(NetworkCallback): def __init__(self,listP): self.listP = listP def processPacket(self, packet): self.listP.append(packet.readString())
def countingValleys(n, s): height = 0 pre_height = 0 count = 0 for c in s: if c == 'U': height += 1 else: height -= 1 if height == 0 and pre_height < 0: count += 1 pre_height = height return count
# -*- coding: utf-8 -*- """ Created on Wed May 8 10:39:12 2019 @author: dkorff This is the object initialization file for the Li-s model. It imports input values from li_s_battery_inputs.py and initializes the necessary objects to run the simulations """ import numpy as np import cantera as ct import importlib from...
from slim.utils.jsdict import JsDict flag = 'TeSt.' def test_js_dict(): o = JsDict() o.aaa = flag assert o['aaa'] == flag o.aaa = '123' assert o.aaa == '123' assert o['aaa'] == '123' def test_js_dict_repr(): d = {'a': 1} a = JsDict(d) assert repr(a) == "<jsDict {'a': 1}>"
SECOND_PHASE_UPDATE = True AVERAGE_GIVEN_DATA = True REINFORCEMENT_ONLINE = False NUMBER_OF_EPISODES_CONF = 6000 SHOW_EVERY_CONF = 1000 SOLAR_PANEL_INSTANCE_SIZE_CONF = 4 BATTERY_INSTANCE_SIZE_CONF = 3 LEARNING_RATE_SIZE_CONF = 1 DISCOUNT_SIZE_CONF = 1 city_name_list = ['istanbul'] traffic_rate_list = [1] method_list_r...
import json from channels.generic.websocket import WebsocketConsumer import logging import traceback import subprocess import os logger = logging.getLogger("django") class Runcommand: @staticmethod def run(command): if 'cd ' in command or 'cd' == command: if command == 'cd': ...
import sys import numpy as np import pandas as pd from sklearn.model_selection import GridSearchCV from sklearn.neighbors import KernelDensity import utilities.utilities as thex_utils from thex_data.data_consts import TARGET_LABEL, CPU_COUNT, DEFAULT_KERNEL from classifiers.plot_fit import plot_fits class MultiNBKDE...
from gevent import monkey monkey.patch_all() from CTFd import create_app app = create_app() if __name__ == '__main__': app.run()
from django.contrib.auth.backends import ModelBackend from django_auth_ldap.backend import LDAPBackend class AuthBackend(ModelBackend): def authenticate(self, *args, **kwargs): ldap_user = LDAPBackend().authenticate(*args, **kwargs) local_user = super().authenticate(*args, **kwargs) if...
"""Example model definitions for SQLAlchemy's ORM system""" from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, DateTime, Float, Enum from sqlalchemy.orm import relationship from app.core.database import Base class Customer(Base): __tablename__ = "customers" uid = Column(String, primary_key=...
from flask import Flask, request, render_template, flash, redirect from forms import RegistrationForm, AdditionalInformation, MultiStepForm, SomethingElse from wtforms import Form app = Flask(__name__) app.secret_key = 'super secret key' def flash_errors(form: Form): """Flashes form errors""" for field, err...
""" test using logger in pyqt5 modules QUESTION: 1. where does signal.emit() activated? 2. any way to dump logger message into a log file? """ import sys from PyQt5 import QtWidgets import logging class QTextEditLogger(logging.Handler): # what is parent?? def __init__(self, parent): sup...
from src.lib.spaces.vector import Vector class Movable: def getPosition(self) -> Vector: """ Gets the current position of a movable :return: Vector """ pass def getVelocity(self) -> Vector: """ Gets the current velocity :return: """ ...
# _*_ coding: utf-8 _*_ import os from gensim.models.doc2vec import TaggedDocument class SplitSentences(object): def __init__(self, dir_name): self.dir_name = dir_name def __iter__(self): for file_name in os.listdir(self.dir_name): with open(os.path.join(self.dir_name, file_name)...
# -*- coding:utf-8 -*- import sys from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): """ 自定义权限只允许对象的所有者编辑它。 """ def has_object_permission(self, request, view, obj): # 读取权限允许任何请求, # 所以我们总是允许GET,HEAD或OPTIONS请求。 if request.method in permis...
from django.test import TestCase, override_settings from django.core.exceptions import ImproperlyConfigured from logpipe import settings class ProducerTest(TestCase): @override_settings(LOGPIPE={'KAFKA_BOOTSTRAP_SERVERS': ['kafka:9092']}) def test_normal_required_key(self): self.assertEqual(settings.g...
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-08-15 08:08 from django.db import migrations from django.conf import settings from django.utils.timezone import now def add_missing_employee_vouches(apps, schema_editor): UserProfile = apps.get_model('users', 'UserProfile') IdpProfile = apps.get_...
import yaml import project from assets import Asset, Assets from asset_type import AssetType
#!/usr/bin/env python3 import pathlib import os import matplotlib.pyplot as plt from sunburst import SunburstPlot, Path, stringvalues_to_pv fig, ((ax0, ax1), (ax2, ax3)) = plt.subplots(2, 2) axs = [ax0, ax1, ax2, ax3] fig.set_size_inches(10, 10) # set up some random data data = stringvalues_to_pv( { "...
import math from math import atan2, pi class GPSUpdater: @staticmethod def distance_bearing_calculator_using_parameters(destination_x, destination_y, source_x, source_y, image_height, pixel_in_centimeters ): analytical_coordinate_sourceY = image_hei...
# ----------------------------------------------------------------------- # configuration.py # Author: Hari Raval # ----------------------------------------------------------------------- # a Configuration object represents the parameters and settings used to generate an Amber test class Configuration(object): #...
from django.test import TestCase from django_hosts.resolvers import reverse class TestIndexReturns200(TestCase): def test_index_returns_200(self): url = reverse('home') resp = self.client.get(url) self.assertEqual(resp.status_code, 200)
from django.core.management import call_command from django.test.testcases import TestCase from 臺灣言語服務.models import 訓練過渡格式 class 教典音檔試驗(TestCase): @classmethod def setUpClass(cls): call_command('教典音檔0下載', 'dropbox') call_command('教典音檔1轉檔', '--匯入幾筆', '100') call_command('教典音檔2匯入', '--匯...
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Invenio module configuration.""" from __future__ import absolute_import, print_fu...
# Generated by Django 3.1.1 on 2020-10-29 10:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0003_auto_20200930_1454'), ] operations = [ migrations.RenameField( model_name='customuser', old_name='mobi...
TEST = [["a", "b", 1, 2], ["c", "d", 3, 4], ["e", "f", 5, 6]] def dict_list(lst: list[list]): return {tuple(sub[:2]): tuple(sub[2:]) for sub in lst} if __name__ == "__main__": print(f"The original list is : {TEST}") print(f"The mapped Dictionary : {dict_list(TEST)}")
# -------------------------------------------------# # EXERCICIO 11 # # -------------------------------------------------# # Faça um programa que leia a largura e a altura de uma parede # em metros, calcule sua area, e a quantidade de tinta # necessaria para pinta-la, sabendo que cada...
# -*- coding:utf-8 -*- """ @author: Alden @email: sunzhenhy@gmail.com @date: 2018/3/29 @version: 1.0.0.0 """ class Solution(object): def uniqueMorseRepresentations(self, words): """ :type words: List[str] :rtype: int """ tmp_list = [".-", "-...", "-.-.", "-..", ".", "..-.",...
#!/usr/bin/env python """ Crop images with ImageContainer ------------------------------- This example shows how crop images from :class:`squidpy.im.ImageContainer`. Specifically, it shows how to use: - :meth:`squidpy.im.ImageContainer.crop_corner()` - :meth:`squidpy.im.ImageContainer.crop_center()` .. seea...
from __future__ import absolute_import from __future__ import division from __future__ import print_function # stdlib imports import doctest import os import unittest class TestImport(unittest.TestCase): def test_import(self): for name in ('base', 'layers', 'matchers', 'time'): __import__('nt...
# key builder from autologging import logged import re def buildKey(line, keyBuilderConfigs): def getKeyVal(keyBuilderConfig): def getValueFromGroup(result): return result.groups()[keyBuilderConfig.groupNum] def getVal(result): return result.group() @logged def getResult(): result = re.search(keyBuil...
from unittest import TestCase from mock import call, patch, Mock from keteparaha.browser import ( BrowserTestCase, HeadlessBrowserTestCase, snapshot_on_error ) class SubClassed(BrowserTestCase): def do_nothing(self): pass class BrowserTestCaseTest(TestCase): def test_browser_returns...
# This script has to run using the Python executable found in: # /opt/mgmtworker/env/bin/python in order to properly load the manager # blueprints utils.py module. import argparse import logging import utils class CtxWithLogger(object): logger = logging.getLogger('internal-ssl-certs-logger') utils.ctx = CtxWi...
from .SubprocessorBase import Subprocessor from .SubprocessFunctionCaller import SubprocessFunctionCaller
import json import os import re import socket import config from components.telescope.telescope import BaseTelescope from logger import Logger from typing import Dict from status import TelescopeStatus from status import SyncStatus class Telescope(BaseTelescope): def __init__(self): super().__init__() ...
"""Multinet uploader for nested JSON files.""" import json from io import StringIO from flasgger import swag_from from collections import OrderedDict from multinet import util from multinet.db.models.workspace import Workspace from multinet.auth.util import require_writer from multinet.errors import ValidationFailed, ...
from torchvision import models import torch class Model: def __init__(self, path): self.model = models.mobilenet_v2(pretrained=False) self.model.classifier[1] = torch.nn.Linear( in_features=1280, out_features=2, bias=True ) self.model.load_state_dict(torch.load(path, ma...
from _utils import get_production_version __VERSION__ = get_production_version()
#!BPY # -*- coding: UTF-8 -*- # Clone Custome Shape # # 2017.09.10 Natukikazemizo import bpy import os import utils_log import utils_io_csv # Constants WORK_FILE_NAME = "custom_shape_settings.csv" # init logger global logger logger = utils_log.Util_Log(os.path.basename(__file__)) logger.start() header, data = uti...
import string import numpy as np from scipy.constants import codata from scipy.fftpack import fft, ifft eV = codata.value("electron volt") me = codata.value("electron mass") * 1e15 # convert to pico grams hbar = codata.value("Planck constant over 2 pi") * 1e27 # convert to pico-compatible values clas...
from dataclasses import dataclass from github import Repository as GithubRepository from github.PullRequest import PullRequest from sebex.cli import confirm from sebex.config.manifest import Manifest from sebex.log import success, error, log from sebex.release.executor.types import Task, Action from sebex.release.git...
def rescale(value,min,max,omin,omax): print(value,min,max,omin,omax) value = (omax - omin) * (value - min)/(max- min) + omin if value < omin: value = omin if value > omax: value = omax return(int(value)) def print_message(midi, port): if midi.isNoteOn(): print('%s: ON: ' % p...
""" Generate arbitrary FIR , LPF or BPF, Filter Coefficients """ import numpy as np import scipy.signal as spsg def cheby_equi_ripple_filter(samprate, bandwidth, rolloff=1.2, ripple=0.1, stopatt=40, centerfreq=0.0, force_odd_len=False): """ Generate an arbitrary FIR equi-ripple Ch...
from fastapi import Request, Response, Depends, Form, HTTPException from fastapi.templating import Jinja2Templates from fastapi.responses import RedirectResponse, JSONResponse from fastapi.encoders import jsonable_encoder from sqlalchemy.orm import Session from sqlalchemy.exc import IntegrityError from typing import ...
from dakota_driver.driver import pydakdriver import numpy as np from openmdao.main.api import Component, Assembly from openmdao.lib.drivers.api import SLSQPdriver, CONMINdriver, Genetic, COBYLAdriver, NEWSUMTdriver from openmdao.lib.datatypes.api import Float import unittest from pyopt_driver.pyopt_driver import pyOptD...
#!/usr/bin/env python # -*- coding: utf-8 -*- #http://pynote.hatenablog.com/entry/opencv-contour-manipulation import cv2 import numpy as np # 読込 #img = cv2.imread("sample0.jpg") #gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.imread("sample1.jpg") gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #img = cv2.imr...
x = np.arange(30) a = np.arange(30) a[1::2] = -a[1::2] plt.plot(a) plt.plot(x[::2], a[::2], 'x') plt.plot(x[1::2], a[1::2], 'v')
## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Variational Quantum Eigensolver ## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ import projectq as pq from projectq import MainEngine from projectq.ops import QubitOperator, Measure, All, Rx, Ry import numpy as np, cmath from scipy.optimize import minimize class VQE(object): def __init...
import hashlib from datetime import datetime from enum import Enum from typing import Dict, List, Optional, Type, Union from uuid import UUID, uuid4 from pydantic import BaseModel, Field, HttpUrl, conint, validator from ...models.config import BaseConfig from ...models.schemas.files import File from ...models.schemas...
import numpy as np from ..refraction import snell def test_one_plus_one_is_two(): "Check that one and one are indeed two." assert 1 + 1 == 2 def test_perpendicular(): actual = snell(0, 2.0, 3.0) expected = 0 assert actual == expected actual = snell(0, 3.00, 2.00) expected = 0 assert...
import requests as r import json from get_movie_details_from_file import file_movie_name as mov_name from get_movie_details_from_file import file_movie_year as mov_year genre_dictionary = { 12: "Adventure", 14: "Fantasy", 16: "Animation", 18: "Drama", 27: "Horror", 28: "Action", 35: "Come...
# Implementation of CKY, with automatic conversion of a grammar to CNF and weights included. import copy import uuid import numpy as np # =========================================================================== # ============================= CNF Conversion ============================== # ========================...
# Generated by Django 2.0.2 on 2018-08-03 09:31 from django.db import migrations, models import django.db.models.deletion import modelcluster.fields import hypha.public.funds.blocks import wagtail.core.blocks import wagtail.core.fields import wagtail.documents.blocks import wagtail.embeds.blocks import wagtail.images....
import datetime from pathlib import Path from unittest import TestCase from googlegroupexporter.exporters import CsvExporter from googlegroupexporter.pages import IndexPage BASE_DIR = Path(__file__).parent class TestCsvExporter(TestCase): @classmethod def setUpClass(cls): fixture = BASE_DIR / 'index...
from django.contrib import admin # Register your models here. from .models import * admin.site.register(Guardian) admin.site.register(Teacher) admin.site.register(Student) admin.site.register(Subject) admin.site.register(Event) admin.site.register(Assignment) admin.site.register(Attendance) admin.site.register(Grade)...
from api.core import execute_query from traceback import print_stack from os import path import json __author__ = "Ravi Salunkhe" __modified_by__ = "Akshay Deshpande" class NoomPy: def __init__(self, excel_path=None): if excel_path is not None: if path.exists(excel_path): self...
import sys,sce class Yeti_Character_BP(sce.Bosses): def __init__(self): super().__init__(self) name = 'Yeti' blueprintPath = '/Game/PrimalEarth/Dinos/Bigfoot/Yeti_Character_BP.Yeti_Character_BP' fullStatsRaw = [[2000, 0.1, 0.27, 0.5, 0], [300, 0.1, 0.1, 0, 0], [1100, 0.06, 0, 0.5, 0], [15...
# Generated by Django 3.1.7 on 2021-03-31 08:19 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("authentik_policies", "0006_auto_20210329_1334"), ] operations = [ # Create field with default as all for backwards compat migrations...
df.sort_values(by='Age', ascending=False)
from contextlib import contextmanager from typing import Dict, Generator, Optional, Tuple from urllib.parse import urlparse import click import hypothesis def validate_schema(ctx: click.core.Context, param: click.core.Parameter, raw_value: str) -> str: if not urlparse(raw_value).netloc: raise click.Usage...
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **object** utilities. This private submodule implements supplementary object-handling utility functions required by v...
"""Functions to convert between array and block-tree representations of a matrix.""" import numpy as np import pandas as pd from estimagic.parameters.tree_registry import get_registry from pybaum import tree_flatten from pybaum import tree_just_flatten as tree_leaves from pybaum import tree_unflatten def matrix_to_bl...
from channels.auth import AuthMiddlewareStack from channels.db import database_sync_to_async from channels.middleware import BaseMiddleware from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.models import AnonymousUser from django.db import close_old_connections fro...
import logging from itertools import product from force_bdss.api import BaseMCO, DataValue log = logging.getLogger(__name__) class MCO(BaseMCO): def run(self, evaluator): parameters = evaluator.mco_model.parameters log.info("Doing MCO run") for input_parameters in parameter_grid_gene...
#%% ################# # This script takes as input the fish stock trends in Figure 19 # of the FAO STATE OF WORLD FISHERIES AND AQUACULTURE (2020), in .csv format, # and returns a csv file with the processed time series in tidy format. # # Last updated: Feb 2021 # Author: Ignacio Lopez-Gomez # ################# impo...
#!/usr/bin/python3 import socket # used for TCP/IP communication import smtplib # used to send email report import time # used to insert current date in email report import threading class Buzzbox(): # Constructor, saving constants def main(self, _ip: str, _port: int, _light: int, _led: int): self.BUZZ...
# Copyright (c) 1996-2015 PSERC. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. """Checks for dispatchable loads. """ from pypower.idx_gen import PMAX, PMIN def isload(gen): """Checks for dispatchable loads. Returns a column vector...
"""The 'View' Module of the application: The Tree area. This file contains the implementation for the tree area: +------+--------------+ | Tree | HEX | | Area | Area | | | | +------+--------------+ The tree area displays a tree representing the internal structure of the ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from .astm_g_173 import ASTM_G_173_ETR __all__ = ['ASTM_G_173_ETR']
class RandomizedCollection: def __init__(self): self.d = collections.defaultdict(set) self.v = [] def insert(self, val: int) -> bool: self.d[val].add(len(self.v)) self.v.append(val) return True if len(self.d[val]) == 1 else False def remove(self, val: int) -> bool: ...
import random from typing import Dict import fastapi import pytest from fastapi.testclient import TestClient from app.api.api_v1.api import datasets as m from app.config import settings from tests.utils.utils import random_lower_string, random_url @pytest.fixture(scope="function", autouse=True) def patch_prepare_da...
# Top Level Package
import os from fabric.api import env, task from envassert import detect, file, package, port, process, service, user from hot.utils.test import get_artifacts @task def apache(): env.platform_family = detect.detect() apache_config = "/etc/apache2/sites-enabled/wordpress.conf" assert package.installed("ap...
from setuptools import find_packages, setup def get_install_requires(): with open("requirements.txt", "r") as f: return [line.strip() for line in f.readlines() if not line.startswith("-")] def get_install_requires_dev(): with open("requirements_dev.txt", "r") as f: return [line.strip() for l...
from machine import Pin, PWM from time import sleep in1 = PWM(Pin(0)) in2 = PWM(Pin(1)) in3 = PWM(Pin(2)) in4 = PWM(Pin(3)) in1.freq(1000) in2.freq(1000) in3.freq(1000) in4.freq(1000) def drive(left_speed,right_speed) in1.duty_u16(left_speed*(left_speed>0)) in2.duty_u16(-left_speed*(left_speed<0)) in3.duty_u16...
from django import forms from ecs.scratchpad.models import ScratchPad class ScratchPadForm(forms.ModelForm): class Meta: model = ScratchPad fields = ('text',)
# -*- coding: utf-8 -*- # Local data reader and parser to optimize model training. # # Author: Ryan Elliott <ryan.elliott31@gmail.com> # # For license information, see LICENSE import os from typing import List import pandas as pd from neuralcorefres.feature_extraction.stanford_parse_api import ( ConstituencyGram...
from data_wizard import registry from rest_framework import serializers from wq.db.rest.serializers import ModelSerializer from wq.db.patterns import serializers as patterns from .serializers import ReportSerializer from vera.results.serializers import SettableField, ValueValidator import swapper from django.conf impor...
import pandas as pd in_file = "data.csv" out_base = "accessibility" out_ext = "txt" # load data from csv file df = pd.read_csv(in_file) # write data to fast.ai format (separate files for each label and no categories) for l in df.label.unique(): out_file = '.'.join(['_'.join([out_base, str(l)]), out_ext]) df[...
# Quiz01_2.py items = {"콜라":1000,"사이다":900,"씨그램":500,"우유":700,"활명수":800} print("=== 음료 자판기 입니다 ====") print("[콜라][사이다][씨그램][우유][활명수] 중 선택") print("복수 선택 시 --> 예) 사이다,우유 ") # 선택목록 item, 가격 price item = input() # 사이다,우유 items2 = item.strip().split(',') prices = [p for i,p in items.items() if i in items2] price =...
# Copyright (c) 2021 - present, Timur Shenkao # 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 appl...
#!/usr/bin/python # This script unshreds a shredded image (visit http://bit.ly/sCMAD5 for details) # author: Zoreslav Khimich <zoreslav.khimich@gmail.com> from PIL import Image, ImageChops, ImageStat from argparse import ArgumentParser import sys, heapq MAGIC_THRESHOLD = 11 # carefully handpicked to work with your r...
#Cuente e Imprima las ciudades que su pais inicie con la letra E archivo= open("paises.txt", "r") lista= [] paises= [] for i in archivo: e= i.index(":") for r in range(0, e): lista.append(i[r]) e= "".join(lista) paises.append(e) lista= [] for i in paises: if(i[0] == "E"): print(i) lista.append(i...
from keras.models import Sequential from keras.layers import Embedding, Bidirectional, LSTM from keras_contrib.layers import CRF import pickle from data import load_data EMBED_DIM = 40 BIRNN_UNITS = 50 def model(train=True): (train_X, train_Y), (dev_X, dev_Y), (vocab, chunks) = load_data() model ...
import pytest import fv3gfs.util import numpy as np @pytest.fixture def units(): return "m" @pytest.fixture def dims(request): return [fv3gfs.util.X_DIM, fv3gfs.util.Y_DIM] @pytest.fixture def shape(request): return request.param @pytest.fixture def origin(request): return request.param @pytes...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2014 The Plaso Project Authors. # Please see the AUTHORS file for details on individual authors. # # 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 L...
# Generated by Django 2.0.4 on 2018-04-19 12:37 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Task', fields=[ ('id', models.AutoField(pri...
from django.apps import AppConfig class HerosConfigApp(AppConfig): name = 'locfilm.heros' verbose_name = 'Heros'
import pytest from mugen.mixins.Filterable import ContextFilter, Filter, Filterable def is_repeat(x, memory): return True def has_text(x): return True def has_majority_red_color(x): return True def has_majority_green_color(x): return False def has_majority_blue_color(x): return False de...
from anlffr.helper import biosemi2mne as bs import mne import numpy as np from anlffr import spectral from scipy import io import os import fnmatch # Adding Files and locations froot = '/home/hari/Documents/MATLAB/Depth_Clean/' # List of files stems, each will be appended by run number # Could be different for edf, f...
""" This file is for preparing IAM/RIMES word level dataset Please first download IAM word level dataset and extract it in a new folder here named 'IAM' Ensure the following directory structure is followed: ├── data | ├── IAM | └──ascii | └──words.txt | └──words | └──a01 | └─...
"""Quick and dirty markdown to rst converter. This file is here just because I used it when setting up sphinx and someone else might find it useful. """ import glob import re from functools import partial def header(m): n = len(m.group(1)) s = m.group(2) return s + '\n' + '=~'[n-1]*len(s) def fix(s): ...
import numpy as np from numpy.random import randn from pandas import Series, DataFrame import pandas as pd # Sorting by index ser1 = Series(range(3), index=['C', 'A', 'B']) # Now sort_index ser1.sort_index() # Can sort a Series by its values ser1.order() # Lets see how ranking works ser2 = Series(randn(10)) # Thi...
import random # import operator from operator import attrgetter def selRoulette(individuals, k, fit_attr="fitness"): """Select *k* individuals from the input *individuals* using *k* spins of a roulette. The selection is made by looking only at the first objective of each individual. The list returned cont...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "Christian Heider Nielsen" __doc__ = r""" Created on 17/03/2020 """ from itertools import cycle from typing import Iterable def busy_indicator( *, stream: callable = print, indicator_interval: int = 1, phases: Iterabl...
from collections.abc import Hashable import numpy as np from gym import logger, spaces from gym_cellular_automata import Operator def hashable(x): return isinstance(x, Hashable) class Move(Operator): grid_dependant = True # A minor effect because of boundaries action_dependant = True context_dep...
import logging import os import re from datetime import datetime, timedelta from typing import Optional from airflow.models import TaskInstance from util.loader.ingestion_column import _fix_ingestion_column FAILURE_SUBDIRECTORY = "db_loader_failures" STAGING_SUBDIRECTORY = "db_loader_staging" SUPPORTED_MEDIA_TYPES =...
import os, sys here = os.path.realpath('harness') server_hostbase = os.path.realpath(here + '../../../../') sys.path.insert(0,server_hostbase) sys.path.insert(0,server_hostbase + '../') #commented this out, but might be needed for now until the harness is figured out #if so, use your actual path to the Hostbase mod...
import turtle as t pen = t.Turtle() pen.color('cyan') pen.speed(0) screen = t.Screen() screen.bgcolor('black') def draw_square(): for side in range(4): pen.forward(100) pen.right(90) for side in range(4): pen.forward(50) pen.right(90) pen.penup() pen.back(20) pen.p...