content
stringlengths
5
1.05M
"""Apply the mask to the nifiti data Usage: roinii_fh roifile """ import re import os import sys import nibabel as nb from roi.pre import join_time from fmrilearn.load import load_roifile from fmrilearn.preprocess.nii import findallnii from fmrilearn.preprocess.nii import masknii def create(args): """Create a r...
""" <name>Raw to Compositional Data</name> <author>By Serge-Etienne Parent, firstly generated using Widget Maker written by Kyle R. Covington</author> <description></description> <RFunctions>compositions</RFunctions> <tags>Compositions</tags> <icon>raw2comp.png</icon> <outputWidgets>plotting_plot, base_rViewer</...
import datetime import hashlib import httplib import types from ..service.jammer import Jammer from ..service.speed import Speed DATE_FMT = '%a, %d %b %Y %H:%M:%S GMT' def _if_modified_since(if_modified_since, last_modified): modified = datetime.datetime.fromtimestamp(last_modified).strftime(DATE_FMT) if mo...
# Write your x_length_words function here: def x_length_words(sentence, x): words = sentence.split(" ") for word in words: if len(word) < x: return False return True # Uncomment these function calls to test your function: print(x_length_words("i like apples", 2)) # should print False print(x_length_wo...
import logging import bspump.ssh import datetime import bspump import bspump.mongodb import bspump.ssh import bspump.common import bspump.file import bspump.trigger ### L = logging.getLogger(__name__) """ Config file for SSH connection should look like this: # SSH Connection [connection:SSHConnection] host=rem...
# Dolares x = int(input()) # Nro de juegos n = int(input()) comprados = 0 # Para cada juego for i in range(0, n): precio = int(input()) # Verificamos si se puede comprar if x >= precio: # Si lo compramos nos queda # menos dinero x = x - precio comprados = comprados + 1 print comprados
from sqlalchemy import ( Boolean, CheckConstraint, Column, Enum, Float, ForeignKey, Integer, MetaData, String, Table, UniqueConstraint, ) from deckman.model.artist import ArtistStatus metadata_obj = MetaData() artists = Table( "artists", metadata_obj, Column(...
# Copyright 2019 The PlaNet 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 applicable...
from sqlalchemy import Column, ForeignKey, Integer, Table, Text from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import backref, relationship Base = declarative_base() metadata = Base.metadata WinesRegion = Table( 'wines_region', metadata, Column('wine_id', Integer, Foreign...
# Festlegen der Abbruchbedingung ungueltige_eingabe = True # Starten der While-Schleife while ungueltige_eingabe: # Versuche Nutzereingabe zu erhalten try: alter = int(input("Bitte geben Sie Ihr Alter ein: ")) if alter >= 18: print("Dein Alter ist", alter, ".") unguelti...
# Helper from bluezero from bluezero import async_tools from queue import Queue from robotpacket import RobotPacket from robotcommand import RobotCommand from robotstate import RobotState import blepy class RobotPeripheral(blepy.Peripheral): # Custom service UUID CPU_TMP_SRVC = '12341000-1234-1234-1234...
""" models module for organising table and validation """ from django.db import models class Contact(models.Model): """ A class for storing instance contact """ contact_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=130, blank=True, null=True) middle_name = mo...
from pymongo import MongoClient from pymongo.errors import PyMongoError from bson.json_util import dumps # client = MongoClient(port=27017) # db = client.STUDENTMDB # collections = db['STUDENT'] # collections.insert_one({"St_id": "21425454", "Name":"Ragul","Email":"ravi@gmail.com","Grade" :"11", "Stream":"Maths"}) ...
#!/bin/python import sys def kangaroo(x1, v1, x2, v2): if x1<x2 and v1<v2: return 'NO' elif x1==x2 and v1>v2: return 'NO' elif x1==x2 and v2>v1: return 'YES' else: if v1!=v2: if (float(x1-x2)/(v2-v1))==(x1-x2)/(v2-v1): return 'YES' ...
from scipy.stats import norm import numpy as np import pandas as pd from . import common_args from ..util import (read_param_file, compute_groups_matrix, ResultDict, extract_group_names, _check_groups) from types import MethodType from multiprocessing import Pool, cpu_count from functools import ...
from ...common_descs import * from ...hek.defs.objs.tag import HekTag from supyr_struct.defs.tag_def import TagDef animation_comment = """ Played immediately after the old unit's transform out animation. The new actor is braindead during the animation, and is invincible until it ends. """ vitality_inheritanc...
""" Reading the leaderboards with :class:`SteamLeaderboard` is as easy as iterating over a list. """ import logging from steam.core.msg import MsgProto from steam.enums import EResult, ELeaderboardDataRequest, ELeaderboardSortMethod, ELeaderboardDisplayType from steam.enums.emsg import EMsg from steam.util import _rang...
import os, argparse, time parser = argparse.ArgumentParser() parser.add_argument('-d','--dork',help="Enter your dork") parser.add_argument('-a','--amount',help="Enter amount of site to printout") arg = parser.parse_args() class Dorker: def __init__(self, dork, amount): self.dork = dork self.amount = amount def ...
# This script's purpose is to train a preliminary CNN for tracking by Keras # Author: Billy Li # Email: li000400@umn.edu # import starts import sys from pathlib import Path import csv import random import pickle import numpy as np import tensorflow as tf from tensorflow.keras import Model, initializers, regularizers...
henn1 = 12 henn2 = 14 henn3 = 124 if henn1 == henn2 and henn2 == henn3: print(1) elif henn1 == henn2 or henn2 == henn3 or henn1 == henn3: print(2) else: print(3)
import importlib.resources as pkg_resources import requests from functools import cache, total_ordering from typing import Any, Callable import adventofcode2021.data session = requests.Session() cookie = pkg_resources.read_text(adventofcode2021.data, "cookie.txt").strip() requests.utils.add_dict_to_cookiejar...
import math import astropy as ast import matplotlib.pyplot as plt import numpy as np import matplotlib as mpl import os from astropy.time import Time from decimal import * from pylab import * from astropy import units as u import warnings from scipy.stats import chi2,chisquare, norm import pandas as pd class Periodic...
from django import forms from .models import AuthUser,Books,Storages,Comments,Reserves class ProfileForm(forms.ModelForm): class Meta: model = AuthUser # fields = [ 'id', 'password','last_login','is_superuser','username', # 'first_name', 'last_name','email','is_staff','is_active'...
import json import re from collections import ChainMap from functools import partial from pathlib import Path from typing import Any, Callable, Dict import yaml from jinja2 import UndefinedError from jinja2.sandbox import SandboxedEnvironment from plumbum.cli.terminal import ask, choose, prompt from plumbum.colors imp...
import matplotlib.pyplot as plt import cv2 import numpy as np def disp_to_color(D, max_disp): D = D.astype(float) D_nml = D.reshape(D.size) / max_disp D_nml[D_nml>1] = 1 I = disp_map(D_nml).reshape(D.shape+(3,)) return I def disp_map(I): map = np.array([[0,0,0,114],[0,0,1,185],[1,0,0,114],[1,0...
#!/usr/bin/env python3 ''' tsacheck - Check intregrity of downloaded files ''' import sys import os import sqlite3 import subprocess import hashlib # --------------------------------------------------------------------------- # def check(argv): '''Check integrity of downloaded files :param argv: The command ...
#!/usr/bin/env python # encoding: utf-8 # # Utility.py # Copyright (c) 2012 Thorsten Philipp <kyrios@kyri0s.de> # # 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, includ...
import os import imutils from flask import Flask, request, render_template, redirect, url_for, jsonify from random import randint import numpy as np import secrets from BGRemoval import * from orientation import * from smile import smile_inference from crop_rotate import * from poseNet import poseNet template_path = ...
from grazyna.utils import register, init_plugin from grazyna.utils.event_loop import loop from grazyna import format from grazyna_rpg.db import get_session, get_engine from grazyna_rpg.randomized_map import RandomMap from grazyna_rpg.world_manager import WorldManager, PathNotFound from grazyna_rpg.enums import Directi...
from __future__ import annotations from discord.ui import View from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from imp.better import BetterBot class BetterView(View): def __init__( self, client: BetterBot, timeout: Optional[int] = None ): super()....
from pathlib import Path import io import sys import os import math import numpy as np import requests import json import kornia.augmentation as K from base64 import b64encode from omegaconf import OmegaConf import imageio from PIL import ImageFile, Image ImageFile.LOAD_TRUNCATED_IMAGES = True from taming.models i...
# SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries # # SPDX-License-Identifier: MIT """Pin definitions for the Khadas VIM3.""" from adafruit_blinka.microcontroller.amlogic.a311d import pin GPIOAO_0 = pin.GPIO496 GPIOAO_1 = pin.GPIO497 GPIOAO_2 = pin.GPIO498 GPIOAO_3 = pin.GPIO499 GPIOAO_4...
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ @File : receive.py @Time : 2019/8/6 10:15 @Author : Crisimple @Github : https://crisimple.github.io/ @Contact : Crisimple@foxmail.com @License : (C)Copyright 2017-2019, Micro-Circle @Desc : None """ import xml.etree.ElementTree as ET def par...
class User: def __init__(self, id, first_name, last_name, email, account_creation_date): self.id = id self.first_name = first_name self.last_name = last_name self.email = email self.account_creation_date = account_creation_date
from typing import Dict, Any import json import datetime import xml.sax.saxutils import re from ask_sdk_model import (RequestEnvelope, Application, Session, Context, Request, User, ...
import pandas as pd import numpy as np import os # ログイン情報を管理する class Management: def __init__(self, user_id, password): self.user = user_id self.password = password self.file_name = './lib/User/userManagement.csv' # 未登録か否かを判断して未登録で未使用のユーザ名なら登録 def signup(self): if os.path.e...
ORDER = ('six', 'five', 'four', 'three', 'two', 'one') YIN_YANG = {'hhh': '----o----', 'hht': '---- ----', 'htt': '---------', 'ttt': '----x----'} def oracle(arr): return '\n'.join(YIN_YANG[''.join(sorted(a[1:]))] for a in sorted(arr, key=lambda b: ORDER.index(b[0])))
# Implementation of Singly Linked list # Class Node: It creates node which is used by Class SinglyLinkedList # # node = Node() is not a member of singlylinkedlist class just because we have to create multiple Node instance per one # singlyLinkedList. Node instance is created only when user enter a data # 3 pointers ...
from datetime import datetime import json from pathlib import Path from datetime import timedelta user_exp_database_filename = Path("database_files/user_exp_database.json") user_exp_database = None addedExp = 100 role_name_list =["goku", "vegeta", "frieza", "cell", "boo", "gohan", "18", "17", ...
mySocialMedia_posts = [ {'Likes': 21, 'Comments': 2}, {'Likes': 13, 'Comments': 2, 'Shares': 1}, {'Likes': 33, 'Comments': 8, 'Shares': 3}, {'Comments': 4, 'Shares': 2}, {'Comments': 1, 'Shares': 1}, {'Likes': 19, 'Comments': 3} ] total_likes = 0 for n,post in enumerate(mySocialMedia_post...
############# Credits and version info ############# # Definition generated from Assembly XML tag def # Date generated: 2018/12/03 04:56 # # revision: 1 author: Assembly # Generated plugin from scratch. # revision: 2 author: -DeToX- # Mapped out the Raw Entry Table struct # revision: 3 author: Lord Zedd ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class LoanPayConsultOrder(object): def __init__(self): self._out_order_no = None self._seller_user_id = None @property def out_order_no(self): return self._out_order_no...
""" Given a set of distinct integers, nums, return all possible subsets (the power set). Note: The solution set must not contain duplicate subsets. """ import itertools def subsets(nums): subsets = [] for i in range(len(nums)): combinations = [list(i) for i in itertools.combinations(nums, i)] ...
#!/usr/bin/env python # pylint: disable=disallowed-name # pylint: disable=missing-class-docstring, # pylint: disable=missing-function-docstring, # pylint: disable=no-self-use import unittest from paramobject import ParametrizedObject, parameter, Parameter class TestParametrizedObject(unittest.TestCase): def te...
from gevent import monkey monkey.patch_all() import click from corgie import scheduling from corgie.log import logger as corgie_logger from corgie.log import configure_logger @click.command() @click.option('--lease_seconds', '-l', nargs=1, type=int, required=True) @click.option('--queue_name', '-q', nargs=1, typ...
# coding: utf-8 # In[1]: # Name: Alex Egg # Email: eggie5@gmail.com # PID: A53112354 from pyspark import SparkContext sc = SparkContext() # In[2]: from pyspark.mllib.linalg import Vectors from pyspark.mllib.regression import LabeledPoint from string import split,strip from pyspark.mllib.tree import GradientB...
################################################################ # Starts a specified WL managed server using the admin server # The Admin server must be running ################################################################ #Functions ################################################################ def getServerStat...
# Python Version: 3.x # -*- coding: utf-8 -*- import json import posixpath import re import urllib.parse from typing import * import bs4 import requests import onlinejudge.dispatch import onlinejudge.implementation.logging as log import onlinejudge.implementation.utils as utils import onlinejudge.type from onlinejudg...
from . import resources, util from .airbase import AirbaseClient, AirbaseRequest __all__ = ["AirbaseClient", "AirbaseRequest", "resources", "util"]
import numpy as np import tensorflow as tf default_path = 'C:/Users/DimKa/Documents/' def data(path=default_path): log_root = path (im_train, y_train), (im_test, y_test) = tf.keras.datasets.cifar10.load_data() # Normalize to 0-1 range and subtract mean of training pixels im_train = im_train / 255 ...
# -*- coding: utf-8 -*- from cleo.commands import Command class Foo5Command(Command): def __init__(self): pass
import gzip import os import json from nltk import sent_tokenize from utils.dataset import * from dataset_loader.base_loader import LoaderBase class Loader(LoaderBase): def __init__(self, cfg): super().__init__(cfg) self.is_dialogue = False def load(self): for data_type in ['train',...
import pytest from .. import * def test_bytes_base32(): expr = Bytes("base32", "7Z5PWO2C6LFNQFGHWKSK5H47IQP5OJW2M3HA2QPXTY3WTNP5NU2MHBW27M") assert expr.type_of() == TealType.bytes expected = TealSimpleBlock([ TealOp(Op.byte, "base32(7Z5PWO2C6LFNQFGHWKSK5H47IQP5OJW2M3HA2QPXTY3WTNP5NU2MHBW27M)") ...
# -*- coding: utf-8 -*- """ .. module:: perform_saob :synopsis: module performing a Systematic Analysis Of Biases .. moduleauthor:: Aurore Bussalb <aurore.bussalb@mensiatech.com> """ import warnings import pandas as pd import numpy as np import random from sklearn.linear_model import LassoCV, LassoLarsIC from s...
# -*- coding: utf-8 -*- # REDIS 配置,请自行替换 REDIS_HOST = 'your_redis_ip' REDIS_PORT = 6379 REDIS_PASSWORD = 'your_redis_password' REDIS_DB = 0 # REDIS KEY的格式,会接收用户的open_id作为变量 REDIS_KEY='wechat-dialog:demo:%(open_id)s' # 初始配置,根据用户信息分配对应的会话处理器 ROUTER = { 'text': [ # 文本消息,用文本内容进行匹配 ('^累加器$', 'accumulator'), # ...
import sys, os, subprocess, json, MySQLdb, time service_root = os.path.dirname(__file__) if service_root != '': service_root = service_root + '/' sys.path.insert(0, os.path.join(service_root, '../httpsqs')) from httpsqs_client import httpsqs converter = "pdf2swf %s -o %s -s /data/xpdf-chinese-simplified/"...
from myutils import * import numpy as np from time import * from pcheck import * import sys from copy import * def filter_data(F, R, variants): m = len(F) n = len(F[0]) F1 = [[zero for _ in range(len(F[0]))] for _ in range(len(F))] R1 = [[zero for _ in range(len(R[0]))] for _ in range(len(R))] for...
##parameters=text_format, text, SafetyBelt='', **kw ## from Products.CMFDefault.exceptions import EditingConflict from Products.CMFDefault.exceptions import ResourceLockedError from Products.CMFDefault.utils import Message as _ if text_format != context.text_format or text != context.EditableBody(): try: c...
version="0.2.2b-dev"
import Orange from Orange.evaluation.testing import CrossValidation from orangecontrib.recommendation import * from sklearn.metrics import mean_squared_error, mean_absolute_error import math import time def test_learners(): start = time.time() # Load data #data = Orange.data.Table('epinions_test.tab') ...
row, col = map(int, input().split()) n, m, d = map(int, input().split()) data = [] dx = [-1, 0, 1, 0] dy = [0, 1, 0, -1] dir_types = [0, 1, 2, 3] #북동남서 for i in range(row): i = list(map(int, input().split())) data.append(i)
from selenium import webdriver if __name__ == "__main__": driver = webdriver.Chrome() base_url = 'https://www.baidu.com' driver.get(base_url)
from django.urls import path from . import views urlpatterns = [ #tarfas path('',views.tarefas,name='tarefas'), path('tarefa/<int:categoria_id>/',views.tarefas_por_categoria,name='tarefas_por_categoria'), path('tarefa/concluir/<int:tarefa_id>/',views.concluir_tarefa,name='concluir_tarefa'), path('...
import os import os.path # import traitlets.config import Config from traitlets import default, Unicode from nbconvert.exporters.html import HTMLExporter from traitlets.log import get_logger class HideCodeHTMLExporter(HTMLExporter): def __init__(self, config=None, **kw): # self.register_preprocessor('hid...
import re import os import shutil import urllib.parse from zlib import compress import base64 import string plantuml_alphabet = string.digits + string.ascii_uppercase + string.ascii_lowercase + '-_' base64_alphabet = string.ascii_uppercase + string.ascii_lowercase + string.digits + '+/' b64_to_plantuml = bytes.maket...
import matplotlib.pyplot as plt import numpy as np import scipy.stats as stats # (a) n = 100 rng = np.random.default_rng(42) mu = 5 data = rng.normal(mu, 1, size=n) # (b) mu_lim = (3, 7) k = 5000 mus = np.linspace(*mu_lim, k) likelihood = np.ones(k) for x in data: likelihood *= stats.norm.pdf(x, loc=mus) mu_den...
from flask import Flask, Reponse, request from flask_sqlalchemy import import mysql.connector
"""This module is the Python part of the CAD Viewer widget""" import base64 import json from textwrap import dedent import numpy as np import ipywidgets as widgets from ipywidgets.embed import embed_minimal_html, dependency_state from traitlets import Unicode, Dict, List, Tuple, Integer, Float, Any, Bool, observe f...
# pylint: disable=consider-using-f-string """Wrapper over the FTrack API to make it more pythonic to use. Supports the querying and creation of objects, and a way to build event listeners. It's designed to hide the SQL-like syntax in favour of an object orientated approach. Inspiration was taken from SQLALchemy. """ ...
#! -*- coding: utf-8 -*- # bert做Seq2Seq任务,采用UNILM方案 # 介绍链接:https://kexue.fm/archives/6933 from bert4torch.models import build_transformer_model from bert4torch.tokenizers import Tokenizer, load_vocab from bert4torch.snippets import sequence_padding, text_segmentate from bert4torch.snippets import AutoRegressiveDecoder...
import toml class TomlError(Exception): pass # Read configuration file def load_config(filename): config = toml.load(filename) # Check the necessary fields are provided in the toml if config.get('contract') is None or config['contract'].get('pricefeeds') is None or config['contract'].get('wrb') is None: ...
def format_error(error_message): return {"err": error_message}
#!/usr/bin/env python """Tests for `pyargcbr` package.""" import os from typing import List, Dict import pytest from pyargcbr.agents.metrics import levenshtein_distance as cmp from pyargcbr.cbrs.domain_cbr import DomainCBR from pyargcbr.knowledge_resources.domain_case import DomainCase from pyargcbr.knowledge_resour...
"""System Module""" from django.test import TestCase class UrlWeatherTest(TestCase): """URL Loading Test""" def test_weather_url(self): """Test to observe if weather page URL is loading correctly""" response = self.client.get('') self.assertEqual(response.status_code, 200)
from pathlib import Path from typing import Iterable import git import pytest from commodore.component import Component def setup_components_upstream(tmp_path: Path, components: Iterable[str]): # Prepare minimum component directories upstream = tmp_path / "upstream" component_urls = {} component_ver...
import numpy as np import matplotlib.pyplot as plt import time import sys sys.path.append('../') from FollyHighLevelControllerV2 import FollyHighLevelControllerV2 # Initialize Molly position molly_position = np.array([-4, -8]) # Initialize Folly position folly_position = np.array([-2, -7.5, 0]) # object length obje...
# Same problem setup as in `dq_darcy_stokes.py` except mixed # formulation is used to solve the Darcy subproblem and thus # we have a Lagrange multiplier on the interface to enforce the # coupling (mass conservation in particular) from utils import rotate import sympy as sp from dolfin import * from xii import * import...
#! python3 # -*- encoding: utf-8 -*- def test_repr_str(): from class_object import Pair p = Pair(3, 4) print(p) print('p is {0!r}'.format(p)) print('p is {0}'.format(p)) def test_custom_date_format(): from class_object import Date from datetime import date d = date.today() d = Date...
# Generated by Django 3.2.9 on 2021-11-24 21:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('SocialLinks', '0005_csseditor_title'), ] operations = [ migrations.AddField( model_name='csseditor', name='link_hove...
"""Test a specific audio driver (either for platform or silent). Only checks the use of the interface. Any playback is silent.""" from __future__ import absolute_import, print_function from tests import mock import queue import pytest import time import pyglet _debug = False pyglet.options['debug_media'] = _debug pyg...
from django.db import models from json import JSONEncoder from django.core.serializers.json import DjangoJSONEncoder import datetime # Create your models here. class Encoder(DjangoJSONEncoder): def default(self, value): if isinstance(value, datetime.date): return DjangoJSONEncoder...
from rply.token import BaseBox from Main.Errors import error, errors import sys class BinaryOp(BaseBox): def __init__(self, left, right): self.left = left self.right = right if self.right.kind == "string" or self.left.kind == "string": self.kind = "string" else: ...
import csv import web import json import datetime import energyServer urls = ("/vehicleData", "vehicles", # "/subwayTotal", "subwayTotal", # "/subwayChanges", "subwayChanges", "/", "check") class check: def GET(self): return "200 OK" def getTime(): web.header('Access-Control-Allow-Origin', '*') web.head...
class TermsOfDeliveryService(object): """ :class:`fortnox.TermsOfDeliveryService` is used by :class:`fortnox.Client` to make actions related to TermsOfDelivery resource. Normally you won't instantiate this class directly. """ """ Allowed attributes for TermsOfDelivery to send to Fortnox ba...
import torch from torch import nn import torch.nn.functional as F import torchvision from torchvision import datasets, transforms, models from collections import OrderedDict from torch import optim from torch.autograd import Variable class PreTrainedCNN: def __init__(self, arch, gpu, hidden_units, pretrained): ...
""" Taylor Polynomial Approximations of 1. SiLU 2. ReLU https://en.wikipedia.org/wiki/Taylor_series#Definition """ import torch import torch.nn as nn class SiLUTaylorApprox(nn.Module): def __init__(self, order=2): super(SiLUTaylorApprox, self).__init__() self.coeffs = torch.tensor([0.0, ...
import json from datetime import datetime from datetime import date from powerbi.enums import DataSourceType from typing import Union from enum import Enum # https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/entity-data-model-primitive-data-types # https://docs.microsoft.com/en-us/power-bi/developer/automa...
# Copyright 2015 NICTA # # 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 wri...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # (c) Copyright 2003-2015 HP Development Company, L.P. # # This program 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 version 2 of the License, or # (at...
from ....extensions import ExtensionMixin from ...flarum.core.forum import Forum class ForumMixin(Forum): @property def markdown_mdarea(self) -> bool: """ Whether or not the MDArea is enabled for markdown. """ return self.attributes.get("flarum-markdown.mdarea", False) ...
from manpy.simulation.applications.MilkPlant.imports import * from manpy.simulation.imports import ExcelHandler, ExitJobShop from manpy.simulation.Globals import runSimulation import time start = time.time() # how many liters is one milk pack milkUnit = 1.0 T1 = MilkTank("T1", "T1", capacity=3200 / float(milkUnit)) T...
# SheetManager Exceptions class GoogleConnectionException(Exception): pass class InitSheetManagerException(Exception): pass class AuthSheetManagerException(Exception): pass class CreateSheetException(Exception): pass class OpenSheetException(Exception): pass class WriteTableException(Excep...
import qrcode location_in = input("Enter Location:") qr=qrcode.QRCode(version=1,box_size=10,border=5) qr.add_data('https://www.google.co.in/maps/place/'+location_in) qr.make(fit=True) img=qr.make_image(fill="black",back_color="white") img.save("1.png")
from django.db import models from home.models import FeatureContent # Create your models here. class ApplContent(FeatureContent): button_text = models.CharField(blank=True, max_length=50) load_file = models.FileField(blank=True, null=True)
from importlib import reload import numpy as np import itertools as it from tumorstoppy import distances, measures, data, knn data_points = 979 Data = data.Data cdr3 = data.CDR3_13 cut_cdr3 = Data( [ Data(['./data/processed_data/TumorCDR3s_test/TumorCDR3s_test_13.txt', './data/pro...
import math import time import torch import torch.nn as nn import torch.nn.functional as F import torch.autograd.profiler as profiler from pykeops.torch import LazyTensor from geometry_processing import ( curvatures, mesh_normals_areas, tangent_vectors, atoms_to_points_normals, ) from helper import sof...
from time import time import jwt from .config import ServiceAccount class JSONWebTokenHandler: """Handles bearer tokens from a service account.""" def __init__(self, service_account: ServiceAccount, audience: str): self._service_account = service_account self._audience = audience s...
import json from rest_framework.views import status from django.urls import reverse # local imports from .base_test import TestBase class TagCreation(TestBase): """Test if a tag list is created""" def test_tag_addition(self): """Test tags addition to article""" self.verify_user() re...
import sys import time from urllib.request import urlopen from .error import OmeError from .util import remove, get_terminal_width, is_terminal def format_size(n): if n < 1024: return '%d B' % n elif n < 1024**2: return '%.1f KB' % (float(n) / 1024) elif n < 1024**3: return '%.1f MB...
def product(*args): """This method returns the product of items passed as arguments Returns product of the arguments passed. If args length is zero then ti will return 0 """ if len(args) == 0: return 0 result = 1 for arg in args: result *= arg return result def convert_cur...