content
stringlengths
5
1.05M
""" Xarray API for xhistogram. """ import xarray as xr import numpy as np from collections import OrderedDict from .core import histogram as _histogram def histogram(*args, bins=None, dim=None, weights=None, density=False, block_size='auto', bin_dim_suffix='_bin', bin_edge_suffix='_bin_ed...
from .skill import Trello create_skill = Trello
######## # Copyright (c) 2015 GigaSpaces Technologies 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...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 8 11:13:41 2021 @author: dpetrovykh """ from FIAR import FIAR, RepeatMove, OutOfBounds from IPython.display import display #Create a new game game = FIAR(size=13) game.draw_board() #Start making moves game.move(0,0) game.move(1,1) game.move(2,2) g...
# encoding=utf8 from niapy.algorithms.basic import BareBonesFireworksAlgorithm, FireworksAlgorithm, EnhancedFireworksAlgorithm, \ DynamicFireworksAlgorithm, DynamicFireworksAlgorithmGauss from niapy.tests.test_algorithm import AlgorithmTestCase, MyBenchmark class BBFWATestCase(AlgorithmTestCase): def setUp(s...
# coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from ...
#!/usr/bin/env python3 """ Feed parser """ from asyncio import get_event_loop, set_event_loop_policy from config import (DATABASE_NAME, MONGO_SERVER, REDIS_NAMESPACE, get_profile, log) from datetime import datetime from hashlib import sha1 from time import mktime from traceback import format_exc ...
# Generated by Django 3.2 on 2021-05-15 20:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('stats', '0011_country_flag_url_shiny'), ] operations = [ migrations.AddField( model_name='country', name='flag_url_big...
import cgi import codecs from io import BytesIO import logging import types from django.http import HttpRequest, parse_cookie, QueryDict from django.utils.functional import cached_property from django.urls import get_resolver from django.utils.log import log_response from .exception import response_for_exception log...
# Generated by Django 2.1.7 on 2019-03-12 12:03 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('main', '0010_auto_20190312_1152'), ] operations = [ migrations.AlterField( ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import boto3 import json import time from ecs_crd.defaultJSONEncoder import DefaultJSONEncoder from ecs_crd.createStackStep import CreateStackStep from ecs_crd.scaleUpServiceStep import ScaleUpServiceStep from ecs_crd.sendNotificationBySnsStep import SendNotificationBySn...
"""The class for managing basic environment The class requires the follow properties: 'id' (str): the suffix name of resource created 'ec2_params' (dict): the dictionary of the EC2 custom parameters 'lambda_params' (dict): the dictionary of the Lambda custom parameters All properties are mandatory. See th...
import os, sys import winshell shortcuts = {} user_programs = winshell.programs() for dirpath, dirnames, filenames in os.walk(user_programs): relpath = dirpath[1 + len(user_programs):] shortcuts.setdefault( relpath, [] ).extend( [winshell.shortcut(os.path.join(dirpath, f)) for f in filenam...
# coding: utf-8 import re import six from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization class PublicipInstanceResp: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The k...
""" Package name: imagee Version: 1.1 Description: Tool for optimizing image Github repo: https://github/dev-muhammad/imagee Author: Muhammad (https://github/dev-muhammad) """ import os.path import sys from PIL import Image from io import BytesIO import base64 class Imagee(): """ Main Imagee class Attri...
import FWCore.ParameterSet.Config as cms ## test for electronId simpleEleId70cIso = cms.EDProducer( "EleIdCutBasedExtProducer", src = cms.InputTag("gedGsfElectrons"), reducedBarrelRecHitCollection = cms.InputTag("reducedEcalRecHitsEB"), reducedEndcapRecHitCollection = cms.InputTag("reducedEcalRecHitsEE...
from __future__ import absolute_import, division, print_function import stripe TEST_RESOURCE_ID = "po_123" class TestPayout(object): def test_is_listable(self, request_mock): resources = stripe.Payout.list() request_mock.assert_requested("get", "/v1/payouts") assert isinstance(resources...
import datetime import json from secrets import token_hex from typing import List, Dict, Any from flask_login import UserMixin from markupsafe import Markup from passlib.handlers.sha2_crypt import sha512_crypt from passlib.hash import sha256_crypt from peewee import CharField, BooleanField, ForeignKeyField, IntegerFie...
from __future__ import unicode_literals import dataent from dataent.utils import cint, flt def execute(): for doctype in dataent.get_all("DocType", filters={"issingle": 0}): doctype = doctype.name meta = dataent.get_meta(doctype) for column in dataent.db.sql("desc `tab{doctype}`".format(doctype=doctype), as_di...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
from pathlib import Path from typing import List, Any, Dict, Union, Tuple import yaml from genson import SchemaBuilder from .apidoc import Endpoint, APIDoc from .postmanapidoc import PostmanAPIDoc def str_presenter(dumper, data): if len(data.splitlines()) > 1: # check for multiline string return dumper...
from sqlalchemy import MetaData, Table, Column, insert, delete, select from sqlalchemy.dialects.mysql import CHAR from .database import Database from ..utils.verify import uuid_verify metadata = MetaData() subscriptions = Table( "subscriptions", metadata, Column("UserUUID", CHAR(32), nullable=False), ...
# -*- coding: utf-8 -*- from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), ('events', '0001_initial'), ] operations = [ migrations.CreateModel( name='GroupRestriction', fields=[ ...
import sys import re # from Client import * file = open(sys.argv[1],'r') fileName = file.name[:-4] tipos = ['int', 'bool'] tiposEspecias = {} def numBits(numero): if numero > 2: resto = numero % 2 if resto == 0: r = numero/2 return r else: r = (numero/2) + 1 return r else: ...
import re import spacy import statistics import en_core_web_lg from functools import lru_cache #nlp = spacy.load("en_core_web_sm") nlp = en_core_web_lg.load() #text_listใซใƒชใ‚นใƒˆใจใ—ใฆ่ชญใฟ่พผใ‚€ with open('book/book59.txt', 'r') as f: #ๆ”น่กŒ("\n")ใ‚’""ใซๅค‰ๆ› #text_list = f.read().splitlines() text = f.read() #ๆญฃ่ฆ่กจ็พใง"ใ‚’ๅ‰Š้™ค text ...
# -*- coding: utf-8 -*- ''' Dummy Payment Gateway Transaction Untested code is broken code. Testing web services are painful, testing payment gateways are even more painful. This module adds a dummy credit crd processor for unit and integrations tests to use. In production use this payment provid...
# pylint: disable=no-self-use,invalid-name from deep_qa.data.data_indexer import DataIndexer from deep_qa.data.instances.instance import TextInstance from deep_qa.data.tokenizers import tokenizers # pylint: disable=line-too-long from deep_qa.data.instances.text_classification.text_classification_instance import Indexe...
import unittest from name_function import get_formatted_name class NamesTestCase(unittest.TestCase): """Tets for 'name_function.py'""" def test_first_last_name(self): formatted_name = get_formatted_name('seymour', 'skinner') self.assertEqual(formatted_name, 'Seymour Skinner') def test_fi...
import torch import torch.nn.functional as F def slicedWassersteinLoss(x, y, num_projections=1000): '''random projections of 1D features to compute sliced wasserstein distance sliced wasserstein is more memory consuming than PDL loss ''' x = x.reshape(x.shape[0], -1) # B,L y = y.reshape(y.sh...
## User vs Computer #User will be player 1 and Computer will be player 2 import random def checkBoard(board): for player in range(1,3): if player==1: symbol="X" else: symbol="O" for i in range(0,3): if (board[i][0]==symbol) and (board[i][1]==symbol) and (...
"""Base Connection Class.""" # Standard Library from typing import Dict, Union, Sequence # Project from hyperglass.log import log from hyperglass.models.api import Query from hyperglass.parsing.nos import scrape_parsers, structured_parsers from hyperglass.parsing.common import parsers from hyperglass.models.config.de...
import dadi import dadi.DFE as DFE import pickle, glob import numpy as np from src.Models import get_dadi_model_func def generate_cache(model, grids, popt, gamma_bounds, gamma_pts, additional_gammas, output, sample_sizes, mp, cuda, single_gamma): if cuda: dadi.cuda_en...
# Bangla Natural Language Toolkit: Parts of Speech Tagger # # Copyright (C) 2019 BNLTK Project # Author: Ashraf Hossain <asrafhossain197@gmail.com> from keras.models import load_model from string import punctuation import numpy as np from sklearn.feature_extraction import DictVectorizer from sklearn.preprocessing imp...
from plexapi.server import PlexServer from dotenv import load_dotenv import os load_dotenv() PLEX_URL = os.getenv('PLEX_URL') PLEX_TOKEN = os.getenv('PLEX_TOKEN') print("connecting...") plex = PlexServer(PLEX_URL, PLEX_TOKEN) plexacc = plex.myPlexAccount() print("getting users...") users = plexacc.users() user_total...
#!/usr/bin/env python ### IMPORTS ### from utils import makeCelery from math import add_together ### GLOBALS ### ### FUNCTIONS ### ### CLASSES ### ### MAIN ### if __name__ == '__main__': pass
from unittest import TestCase from leetcodepy.binary_tree_preorder_traversal import * from leetcodepy.utils import trees solution1 = Solution1() solution2 = Solution2() root = trees.from_values(1, None, 2, 3) expected = [1, 2, 3] class TestBinaryTreePreorderTraversal(TestCase): def test1(self): self....
from typing import Any, Dict import scanpy as sc from anndata import AnnData def process(adata: AnnData, step: Dict[str, Any], output: Dict[str, Any]): """ Compute a neighborhood graph of observations """ output["neighbors"] = True n_neighbors = step.get("nNeighbors") metric = step.get("metr...
from .parser import Parser from .telemetry import Telemetry from .packet import Packet from .element import Element, UnknownElement from .elements import TimestampElement, DatetimeElement import xml.etree.ElementTree as ET from dateutil import parser as dup import logging # Reference: http://www.topografix.com/GPX/1/...
lista = [1, 10] arquivo = open('teste.txt', 'r') try: texto = arquivo.read() divisao = 10 / 1 numero = lista[1] except ZeroDivisionError: print('Nรฃo รฉ possivel realizar a divisรฃo por 0') except ArithmeticError: print('Houve um erro ao realizar uma operaรงรฃo aritimetica.') except IndexError: pr...
from bs4 import BeautifulSoup import requests # # Run this Second! # # From the get_urls_from_sitemap.py, we get a list of all of the Category Pages. Now we're going to scrape those # pages to get the URL's for any Product Detail Pages.# # # The target's name has been redacted domain = 'http://www.redacted.com' # #...
import unittest from hstest.check_result import correct from hstest.dynamic.dynamic_test import dynamic_test from hstest.stage_test import StageTest class TestRepeatingWrongAmount(StageTest): @dynamic_test(repeat=-1) def test(self, x): return correct() class Test(unittest.TestCase): def test(s...
import os import sys from PIL import Image import numpy as np import matplotlib.image as img import matplotlib.pyplot as plt import cv2 import tqdm def get_labels_from_json(dir_labels, dir_annotated, format="tif", no_label=False): if not os.path.exists(dir_labels): print("New Label Directory:", dir_labels...
""" ## Reference from: Multi-Stage Progressive Image Restoration ## Syed Waqas Zamir, Aditya Arora, Salman Khan, Munawar Hayat, Fahad Shahbaz Khan, Ming-Hsuan Yang, and Ling Shao ## https://arxiv.org/abs/2102.02808 """ import numpy as np import os import argparse from tqdm import tqdm import torch import ...
import numpy as np from .non_uniform_mutation import non_uniform_mutation from .uniform_mutation import uniform_mutation def mutation(pool, area, probability, method, dist="cauchy"): """Apply mutation over the whole pool. Args: pool: (list of) plans to apply mutation over. area: (int) area o...
from disco.test import TestCase, TestJob special = '--special_test_string--' def isspecial(offset__time_node_message): return special in offset__time_node_message[1][2] class DiscoAPIJob(TestJob): @staticmethod def map(e, params): for i in range(3): print(special) yield e.spli...
# coding: utf-8 "" import sys sys.path.append("..") "" from jobtimize.scrapers.scrapmonster import MonsterScrap, scrapMonsterID, dicoFromJson import pytest "" class TestMonster: searchList = ["Data Analyst"] countryList = ["FR"] monsterID = scrapMonsterID(searchList, countryList) scraped = Monst...
#!/usr/bin/env python class Program: @staticmethod def debug(values, log=None): values = [int(x) for x in values.split(",")] variables = {} off = 0 log.show(" Offset Val Op Code 'Description'") while off < len(values): off += Program.debug_line(log,...
def dimensionalIterator(dimensions, maxItems=-1): """ Given a list of n positive integers, return a generator that yields n-tuples of coordinates to 'fill' the dimensions. This is like an odometer in a car, but the dimensions do not each have to be 10. For example: dimensionalIterator((2, 3)) will ...
"""Support for Transports Metropolitans de Barcelona."""
# -*- coding: utf-8 -*- from urlparse import urljoin from flask import Blueprint, render_template, request, flash, abort, redirect, \ g, url_for, jsonify from werkzeug.contrib.atom import AtomFeed from blog.utils import requires_login, requires_admin, \ format_creole, request_wants_json from blog.database imp...
#!/usr/bin/env python3 from itertools import combinations n = int(input()) s = input().split() k = int(input()) total = 0 match = 0 for _ in combinations(s, k): total += 1 if 'a' in _: match += 1 print(match/total)
#!/usr/bin/env python # encoding: utf-8 """ @author: zhanghe @software: PyCharm @file: purchase.py @time: 2018-08-31 15:41 """ from __future__ import unicode_literals from datetime import datetime from flask import ( request, flash, render_template, url_for, redirect, abort, jsonify, ...
from Common.Predictors.AbstractPredictor import AbstractPredictor, abstractmethod class AbstractSvrPredictor(AbstractPredictor): @abstractmethod def _setData(self): pass @abstractmethod def _setForecast(self): pass @abstractmethod def _setIndependent(self): pass ...
# -*- coding: utf-8 -*- ## @package inversetoon.geometry.ellipsoids # # Implementation of 2D ellipsoids. # @author tody # @date 2015/08/13 import math import numpy as np from numpy.linalg import eig, inv ## Ellipsoids class Ellipsoids: ## Constructor def __init__(self, points = []): s...
import asyncore import logging import socket from io import BytesIO from http.server import BaseHTTPRequestHandler from http import HTTPStatus import urllib.parse as urlparse from urllib.parse import parse_qs logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG) log = logging.getLogger(__name__...
# coding: utf-8 """ Automox Console API API for use with the Automox Console # noqa: E501 OpenAPI spec version: 2021-08-10 Contact: support@automox.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import automox_co...
from typing import Type, List, Dict from re import compile from dataclasses import dataclass from py2puml.domain.umlitem import UmlItem from py2puml.domain.umlclass import UmlClass, UmlAttribute from py2puml.domain.umlrelation import UmlRelation, RelType from py2puml.parsing.parseclassconstructor import parse_class_...
import zipfile if __name__ == '__main__': filename = 'data/alphamatting/input_lowres.zip' print('Extracting {}...'.format(filename)) with zipfile.ZipFile(filename, 'r') as zip_ref: zip_ref.extractall('data/alphamatting/') filename = 'data/alphamatting/trimap_lowres.zip' print('Extracting {...
# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use this f...
import sys from optparse import OptionParser from pprint import pprint import yaml import json import wikipedia_ql def run(): # TODO: Link to cheatsheet parser = OptionParser('Usage: %prog [options] query') parser.add_option("-p", "--page", dest="page", help=r'''Wikipedia page name ...
# Generated by Django 3.0.3 on 2020-03-14 19:19 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('common', '0008_remove_su...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSubtree(self, s: TreeNode, t: TreeNode) -> bool: def rec(s,t): if s is No...
"""Module defining UniprotData class.""" # python 2/3 compatibility from __future__ import division, print_function, absolute_import # global imports from collections import Counter, namedtuple import os.path import re import pandas Cofactor = namedtuple('Cofactor', 'chebi name stoichiometry uniprot_note') class U...
# # This is the withhacks setuptools script. # Originally developed by Ryan Kelly, 2009. # # This script is placed in the public domain. # from distutils.core import setup import withhacks VERSION = withhacks.__version__ NAME = "withhacks" DESCRIPTION = "building blocks for with-statement-related hackery" LONG_DE...
from django.db.transaction import atomic from rest_framework import serializers from products.models import Product, Category class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ("id", "sku", "name", "description", "color", "size", "categories", "created_at...
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
import os from porter_stemmer import PorterStemmer import os class Parser: STOP_WORDS_FILE = '%s/../data/english.stop' % os.path.dirname(os.path.realpath(__file__)) stemmer = None stopwords = [] def __init__(self, stopwords_io_stream = None): self.stemmer = PorterStemmer() if(n...
from microbit import * # Please tag us if used! # We'd love to see what you make: # @ScienceOxford ''' This tells us which of the micro:bit's pins is connected to which input on the motor driver (follow the coloured wires!). e.g. FL means that it controls the pin that turns on the left-hand motor in the forward direc...
# -*- coding: utf-8 -*- # vim: set noai syntax=python ts=4 sw=4: # # Copyright (c) 2018-2022 Linh Pham # api.wwdt.me is released under the terms of the Apache License 2.0 """Testing /v2.0/locations routes """ from fastapi.testclient import TestClient import pytest from app.main import app from app.config import API_VE...
FIELDS = { "profile": ["username","age","gender","preferred","address"], #"profile": ["username","age","gender","preferred","address","height","width","avatar"], "schedule": ["schedule_list"], "DELETE": ["_id"], "history": ["history_events","history_partner"], "stats": ["rate","lasttime_login","...
import luigi class ResData(luigi.ExternalTask): """Resistence data""" __version__ = '0.1' def output(self): return luigi.LocalTarget('./data/raw/RES_essential_nonessential_2017-08-17_v5.csv') class FcData(luigi.ExternalTask): """Flow Cytometry Data""" __version__ = '0.1' def output(s...
def maiusculas(string): uppercase_string = '' for letra in string: if letra.isupper(): uppercase_string += letra return uppercase_string maiusculas1 = ('Programamos em python 2?') # deve devolver 'P' maiusculas2 = ('Programamos em Python 3.') # deve devolver 'PP' maiusculas3 = ('PrOg...
import FWCore.ParameterSet.Config as cms from HeavyIonsAnalysis.JetAnalysis.jets.akPu4PFJetSequence_PbPb_mc_cff import * #PU jets with 25 GeV threshold for subtraction akPu4PFmatch25 = akPu4PFmatch.clone(src = cms.InputTag("akPu4PFJets25")) akPu4PFparton25 = akPu4PFparton.clone(src = cms.InputTag("akPu4PFJets25")) ak...
# Generated by Django 3.2.6 on 2021-12-13 23:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('member', '0017_auto_20211213_1658'), ] operations = [ migrations.AddField( model_name='usersns', name='token', ...
# -*- coding: utf-8 -*- # symbology across different markets and vendors # bloomberg bloomberg_symbology = lambda x: str(int(x.split('.')[0])) + ' ' + x.split('.')[1] + ' EQUITY' # bca research bca_symbology = lambda x: x.split(':')[0].zfill(4) + '.' + x.split(':')[1] # hk local local_hk_symbology = lambda x: str(...
''' Module for units and arrays with units. Also doctest other parts of this sub-module: >>> import doctest >>> doctest.testmod(config) TestResults(failed=0, attempted=5) >>> doctest.testmod(units) TestResults(failed=0, attempted=14) >>> doctest.testmod(cosmology) TestResults(failed=0, atte...
import re from PyQt4.QtCore import QDir, QPoint, QTimer, QUrl from PyQt4.QtGui import QDesktopServices from PyQt4.QtWebKit import QWebView, QWebPage import markdown class MikiView(QWebView): def __init__(self, parent=None): super(MikiView, self).__init__(parent) self.parent = parent sel...
""" zoom.collect """ import io import logging import os import zoom from zoom.browse import browse from zoom.buckets import Bucket from zoom.context import context from zoom.alerts import success, error, warning from zoom.fields import ButtonField from zoom.forms import form_for, delete_form from zoom.helpers imp...
from shinytest import ShinyTestCase class TestNpc(ShinyTestCase): def setUp(self): ShinyTestCase.setUp(self) from shinymud.models.player import Player from shinymud.models.npc import Npc from shinymud.models.area import Area from shinymud.models.room import Room ...
import os import cv2 import numpy as np import matplotlib.pyplot as plt def morphology_diff(contrast_green, clahe): #apply open / closing morphology #1st open1 = cv2.morphologyEx(contrast_green, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)), iterations = 1) close1 = cv2.morphologyE...
import matplotlib.pyplot as plt import numpy as np from collections import deque import datetime # Global variables # speed move_speed = 1.0 # mackey glass params gamma = 0.1 beta = 0.2 tau = 17 en = 10. def run(num_data_samples=5000, init_x=1.0, init_x_tau=0.0): x_history = deque(maxlen=tau) x_history.clea...
import h5py import numpy as np from matplotlib import pyplot as plt import seaborn as sns current_palette = sns.color_palette('bright',10) #%% initialization result_path = 'ShapeNet_testing_result.hdf5' class_name = np.genfromtxt('hdf5_data/all_object_categories.txt',dtype='U')[:,0] ####################################...
# SPDX-FileCopyrightText: 2018 Dave Astels for Adafruit Industries # # SPDX-License-Identifier: MIT """ Display code for signal generator. Adafruit invests time and resources providing this open source code. Please support Adafruit and open source hardware by purchasing products from Adafruit! Written by Dave Astels...
# -*- coding:utf-8 -*- __author__ = 'hhstore' ''' ๅŠŸ่ƒฝ: ่ฏปๅ†™officeๆ–‡ๆกฃ,ๆ”ฏๆŒdocx. ไพ่ต–: docxๆจกๅ— ''' from docx import Document def parse_docx(in_file, out_file): doc = Document(in_file) for item in doc.paragraphs: # ้€š่ฟ‡ๆฎต่ฝ่งฃๆžๅ†…ๅฎน. print item.text doc.save(out_file) if __name__ == '__main__': infile = "...
import inspect from pathlib import Path from functools import partial import torch from torch.autograd.profiler import profile import torch.distributed as dist from torch.distributed import ReduceOp from colossalai.utils import get_current_device from .prof_utils import BaseProfiler, _format_time, _format_memor...
from setuptools import setup from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, "README.md"), encoding="utf-8") as f: long_description = f.read() packages = ["appex", "clipboard", "console", "reminders", "sound", "speech"] packages_stubs = [p + "-stubs" for p in packages] p...
import re from decimal import Decimal import datetime import hashlib from app.core.utils import check_datetime_format from app.core.init import SELECT_PARTICIPANT, INSERT_PARTICIPANT, SELECT_TANSACTIONS from .transfer import Transfer class Participant: @classmethod async def get_by_id(cls, app, participant_i...
from twisted.web.client import getPage from phxd.constants import * from phxd.packet import HLPacket from phxd.permissions import PRIV_MODIFY_USERS from phxd.server.utils import certifyIcon def gotIcon(data, user, server): if user and data and len(data) > 0 and certifyIcon(data): user.gif = data ...
# Copyright 2018 Google Inc. # # 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 wr...
""" ไปŽๆŽฅๆ”ถๅˆฐ็š„ๆ•ฐๆฎ่งฃๅŒ… """ import struct class Message: """ โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” โ”ƒ Header โ”ƒ 6้ƒจๅˆ†๏ผŒๅ…ฑ12ๅญ—่Š‚ โ”ƒโ”โ”โ”โ”โ”โ”โ”โ”โ” โ”ƒ โ”ƒ Question โ”ƒ ๆŸฅ่ฏขๅŒบๅŸŸ โ”ƒโ”โ”โ”โ”โ”โ”โ”โ”โ” โ”ƒ โ”ƒ Answer โ”ƒ ๅ›ž็ญ”ๅŒบๅŸŸ โ”ƒโ”โ”โ”โ”โ”โ”โ”โ”โ” โ”ƒ โ”ƒ Authority โ”ƒ ๆŽˆๆƒๅŒบๅŸŸ โ”ƒโ”โ”โ”โ”โ”โ”โ”โ”โ” โ”ƒ โ”ƒ Additional โ”ƒ ้™„ๅŠ ๅŒบๅŸŸ โ”ƒโ”โ”โ”โ”โ”โ”โ”...
import pandas as pd ds1 = pd.Series([12, 14, 16, 18, 20, 24]) ds2= pd.Series([2, 4, 6, 8, 10, 12]) print(ds1+ds2) print(ds1-ds2) print(ds1*ds2) print(ds1==ds2) print(ds1>ds2) print(ds1<ds2)
# 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...
import unicodedata import re import random import torch from torch.autograd import Variable # loading data files # indexing words # ไธ€ไบ›ๆ ‡ๅฟ—็ฌฆๅท(่ฏ) PAD_token = 0 SOS_token = 1 # ๅฅๅญ่ตทๅง‹ EOS_token = 2 # ๅฅๅญ็ป“ๆŸ USE_CUDA = False class Lang: def __init__(self, name): self.name = name self.trimmed = False ...
# -*- coding: utf-8 -*- # snapshottest: v1 - https://goo.gl/zC4yUc from __future__ import unicode_literals from snapshottest import Snapshot snapshots = Snapshot() snapshots['TestEnvironmentBaseImageQueries.test_get_base_image_by_node 1'] = { 'data': { 'node': { 'componentId': 'quickstart-ju...
""" This file contains the Reverse module for the PyADBCXY package. It includes the Reverse class, which implements the reverse mode of automatic differentiation. """ import numpy as np __all__ = ["Reverse"] class Reverse: """ Reverse is the class for implementing the reverse mode auto differentiation inclu...
def my_print(s, *args): #print s, args for i in range(len(args)): s = s.replace('{' + str(i) +'}', args[i]) print s #s = s.replace('{1}', p1) #s = s.replace('{2}', p2) #print s my_print('Salam!') my_print('Salam {0}!', 'ali') my_print('Salam {0}! {1}', 'ali', 'X')
#!/usr/bin/python command = oslc("-d test.osl")
""" *Sound* The sound type. """ from fivear.sampling import Sampling class Sound( Sampled, ): __metaclass__ = ABCMeta # DB_PATH = Path("/home/jed/4ear/fourear/sounds/") # def __init__(self, name: str, sampling_parameters: SamplingParameters): # self.__name = name # self._sa...
from django import template from ..forms import GroupSignupForm from ..models import CollectionGroup, CollectionEvent register = template.Library() @register.simple_tag def get_event_gantt_chart(event, event_members, user): return list( get_gantt_for_member(event, member, user) for member in eve...
import os import cv2 import time import base64 import numpy as np __all__ = ['base64_to_cv2', 'cv2_to_base64', 'Processor'] def check_dir(dir_path): # ็›ฎๅฝ•ๆฃ€ๆŸฅๅ‡ฝๆ•ฐ if not os.path.exists(dir_path): os.makedirs(dir_path) elif os.path.isfile(dir_path): os.remove(dir_path) os.makedirs(dir_p...