content
stringlengths
5
1.05M
# coding: utf-8 # # Dogs-vs-cats classification with CNNs # # In this script, we'll train a convolutional neural network (CNN, # ConvNet) to classify images of dogs from images of cats using Keras # (version $\ge$ 2 is required). This script is largely based on the # blog post [Building powerful image classification...
import pytest import os from oysterpy import encryption, fileprocessor, datamap from Crypto.Random import get_random_bytes, random from Crypto.Hash import SHA256 import numpy as np def initialize_file(path, sizeinkb=10): testfile_content = get_random_bytes(1024*sizeinkb) f = open(path, "wb") f.write(testf...
import numpy as np import json import sys import os from subprocess import call from config import * usage = 'download_annotation.py [anno_id] [version_id] [model_cat] [model_id] [user_id]' anno_id = sys.argv[1] version_id = sys.argv[2] model_cat = sys.argv[3] model_id = sys.argv[4] user_id = sys.argv[5] original_pa...
from modules import network from modules.components import TCLNET def create_backbone(net_name, init_type, init_gain, gpu_ids): net = None if net_name is 'TCLNET': net = TCLNET.net() else: raise NotImplementedError("model not found") return network.init_net(net, ini...
from tests.unit import MockServiceProviderTestCase from boto.ec2.elb import ELBConnection class TestELBConnectionProviderOverride(MockServiceProviderTestCase): connection_class = ELBConnection def test_provider_override(self): self.assert_alt_provider_used()
from __future__ import print_function from __future__ import division import cv2 as cv import numpy as np from matplotlib import pyplot as plt import argparse import os # BLACK & WHITE IMAGING def black_white(filename): print(filename) image = cv.imread('./static/media/122677.png') image_gray = cv.cvtC...
import numpy as np import cv2 import augmentation from skimage.util import img_as_float def _compute_scale_and_crop(image_size, crop_size, padding, random_crop): padded_size = crop_size[0] + padding[0], crop_size[1] + padding[1] # Compute size ratio from the padded region size to the image_size scale_y = ...
# coding: utf-8 import multiprocessing as mp from os import makedirs from os.path import join, exists from gensim.models.callbacks import CallbackAny2Vec import argparse class EpochLogger(CallbackAny2Vec): """ Callback to log information about training. Not serializable -> remove before saving the model....
from django.shortcuts import render from server.models import Card from app.utils import return_json def card_list(request): cards = [] """ user_id = request.GET.get('uid') user = User.objects.get(pk=int(user_id)) deck = user.decks.all().first() for card in deck.cards.all(): item = c...
#!/usr/bin/env python3 # SPDX-License-Identifier: Apache-2.0 # # Copyright (C) 2021 Micron Technology, Inc. All rights reserved. from contextlib import ExitStack from hse2 import hse from utility import lifecycle, cli hse.init(cli.HOME) try: with ExitStack() as stack: kvdb_ctx = lifecycle.KvdbContext(...
import stacktester.config import stacktester.nova class Manager(object): """Top-level object to access OpenStack resources.""" def __init__(self): self.config = stacktester.config.StackConfig() self.nova = stacktester.nova.API(self.config.nova.host, self.co...
from tkinter import * import requests import json tk = Tk() tk.title('Find Weather') tk.geometry("550x300") def WethData(): city = city_entry.get() state = state_entry.get() api_request = requests.get(f"https://api.hgbrasil.com/weather?key=d08c55d1&city_name={city},{state};locale=en") api = jso...
from aiogram.types import ( KeyboardButton, ReplyKeyboardMarkup ) def cancel_keyboard() -> ReplyKeyboardMarkup: return ReplyKeyboardMarkup([[KeyboardButton('Отменить')]], resize_keyboard=True)
""" sso_tools.catalogs """ from .catalog_utils import * from .alcdef_util import *
from icemet_web.app import app from icemet_web.models.database import database_inst, stats_databases from icemet_web.util import render, api from icemet.db import StatsRow from icemet.ice import Cylinder, Event import flask from datetime import datetime def event2dict(event): duration = event.end.timestamp() - eve...
#!/usr/bin/python """ (C) Copyright 2020-2022 Intel Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent """ from apricot import TestWithServers from daos_perf_utils import DaosPerfCommand from command_utils_base import CommandFailure class DaosPerfBase(TestWithServers): """Base test cases for the daos...
from math import * from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import matplotlib.pyplot as plt import numpy as np import os,sys def mexiHat(sigma, t, parameter = 0.770212): # One-dimensional mexican hat curve. prob = 2....
from collections import defaultdict from urh.awre.components.Component import Component from urh.signalprocessing.FieldType import FieldType from urh.signalprocessing.Message import Message class Preamble(Component): """ Assign Preamble and SoF. """ def __init__(self, fieldtypes, priority=0, predeces...
""" Reports base classes. This reports module tries to provide an ORM agnostic reports engine that will allow nice reports to be generated and exportable in a variety of formats. It seeks to be easy to use with query sets, raw SQL, or pure python. An additional goal is to have the reports be managed by model instances ...
""" Copyright (C) 2022 Red Hat, Inc. (https://github.com/Commonjava/charon) 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 a...
import unittest from pyxlsb2.recordreader import RecordReader class RecordReaderTestCase(unittest.TestCase): def test_read_type(self): reader = RecordReader(b'\xFD\x04\x00') self.assertEqual(reader._read_type(), 637) self.assertEqual(reader._read_type(), 0) self.assertEqual(reader....
try: import requests import logging import json from zcrmsdk.src.com.zoho.crm.api.util.constants import Constants from zcrmsdk.src.com.zoho.crm.api.initializer import Initializer except Exception: from .constants import Constants import requests import logging import json from ....
import unittest import pathlib import shutil from net_models.models.interfaces import * from net_models.inventory import Host, Group, Inventory from net_models.loaders import BaseLoader, ExcelLoader, DirectoryLoader, AnsibleInventoryDumper, NornirInventoryDumper VERBOSITY = 4 class TestBaseLoader(unittest.TestCase)...
# Generated by Django 3.2.6 on 2021-08-12 20:22 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), ('blog', '0017_...
from datetime import datetime from os import getenv from bake import * from scheme import * from lattice.support.buildfile import BuildFile from lattice.tasks.component import ComponentAssembler class AssembleProfile(Task): name = 'lattice.profile.assemble' description = 'assembles a lattice profile' para...
import datetime import os import shutil import torch import torch.nn as nn from omegaconf import OmegaConf from torch.utils.tensorboard import SummaryWriter import argparse from dataloaders.dataset import loaders from trainer.logger import Logger from trainer.util import reproducibility, select_model, select_optimizer...
#!/usr/bin/python3 import time from splinter import Browser def getPrivNoteURL(message): browser = Browser('phantomjs') #ghost.show() browser.visit("https://privnote.com/") command = "document.getElementById('id_body').value='"+message+"';" result = browser.evaluate_script(command) command = "...
import os import json from flask import Flask, request import twilio.twiml from twilio.rest import TwilioRestClient app = Flask(__name__) # Retrieve environment variables set by Heroku account_sid = os.environ['TWILIO_SID'] auth_token = os.environ['TWILIO_TOKEN'] message_target = os.environ['SMS_TO'] cid = os.enviro...
from functools import partial from importlib import import_module from logging import getLogger from math import log2 from pprint import pformat from socket import socket from typing import List, Tuple from PIL import Image, ImageDraw from dcspy import LcdColor, LcdMono, SUPPORTED_CRAFTS, FONT, SEND_ADDR, lcd_sdk fro...
from dataclasses import dataclass from typing import Any, Iterator, List, Type, Union from aiohttp import web from openapi import json from openapi.data.validate import ValidationErrors from openapi.db import CrudDB from openapi.types import Record from sqlalchemy import Table from sqlalchemy.exc import NoResultFound ...
from django.contrib import admin from voucher.models import Voucher, Code, Email # Register your models here. admin.site.register(Voucher) admin.site.register(Code) admin.site.register(Email)
from __future__ import division from six.moves import range import math from rstbx.array_family import flex from rstbx.dps_core import Direction from annlib_ext import AnnAdaptor from rstbx.dps_core import sampling from rstbx.dps_core import Direction, directional_show #from libtbx.development.timers import Timer # va...
import smtplib def send_gmail(gmail_addr, gmail_pwd, to_addrs, msg): smtp_gmail = smtplib.SMTP('smtp.gmail.com', 587) # 建立 SMTP 物件 print(smtp_gmail.ehlo()) # Say Hello print(smtp_gmail.starttls()) # 啟動 TLS 加密模式 print(smtp_gmail.login(gmail_addr, gmail_pwd)) # 登入 status = smtp_gmail.sendma...
from .fetch import download_url, unzip
# -*- coding: utf-8 -*- # (C) Copyright 2020, 2021 IBM. All Rights Reserved. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modificatio...
import os import sys from tree import tree opj = os.path.join mkdir = os.mkdir def mkfile(path, content): with open(path, 'w') as f: f.write(content) class Stdout(object): def __init__(self): self.value = '' def write(self, str_): self.value += str_ def flush(self): ...
# coding: utf-8 from enum import Enum class Mark(Enum): D = "底分型" G = "顶分型" class Direction(Enum): Up = "向上" Down = "向下" class Freq(Enum): F1 = "1分钟" F5 = "5分钟" F15 = "15分钟" F30 = "30分钟" F60 = "60分钟" D = "日线" W = "周线" M = "月线" class FdThree(Enum): """三段形态分类""" ...
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-08-01 07:59 from __future__ import unicode_literals import datetime from django.conf import settings from django.db import migrations, models import django.db.models.deletion import proso.django.models class Migration(migrations.Migration): initial = T...
## Assume you now have a new warped binary image # from the next frame of video (also called "binary_warped") # It's now much easier to find line pixels! nonzero = binary_warped.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) margin = 100 left_lane_inds = ((nonzerox > (left_fit[0]*(nonzeroy*...
"""Tests for cleverhans.experimental.certification.dual_formulation.""" # pylint: disable=missing-docstring from __future__ import absolute_import from __future__ import division from __future__ import print_function import unittest import numpy as np import tensorflow as tf from cleverhans.experimental.certificatio...
""" nn.spiel_problems Base definitions for problems handled by SPieL. Handles interaction with the filesystem. """ import os from shutil import copyfile from pathlib import Path import tarfile import tensorflow as tf from tensor2tensor.data_generators import problem from tensor2tensor.data_generators import text_prob...
# pylint: disable=invalid-name,protected-access from allennlp.common.testing import ModelTestCase class BasicRelationClassifierTest(ModelTestCase): def setUp(self): super(BasicRelationClassifierTest, self).setUp() self.set_up_model( "tests/fixtures/basic_relation_classifier.jsonnet", ...
# Generated by Django 2.2.3 on 2019-07-28 09:14 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import random class Migration(migrations.Migration): dependencies = [ ('account', '0001_initial'), ] operations...
import json import pandas as pd import matplotlib.pyplot as plt class StackedHistogram: def __init__( self, primary_grouping_column, secondary_grouping_column, value_column, df, ): self._max_groupings = 5 self._primary_grouping_column = primary_grouping...
#! /usr/bin/env python # 2014.06.29 S.Rodney __author__ = 'rodney' import hstzpt_apcorr import astropyphot from os import path import sys import numpy as np if sys.version_info <= (3,0): import exceptions # Conversion table from full filter names to single-letter abbreviations # used in STARDUST and other S.Rod...
from pandas import Timestamp from nose_parameterized import parameterized from catalyst.testing import ZiplineTestCase from catalyst.utils.calendars import get_calendar from catalyst.utils.date_utils import compute_date_range_chunks def T(s): """ Helpful function to improve readibility. """ return Ti...
import argparse from cocojson.tools import sample def main(): ap = argparse.ArgumentParser() ap.add_argument('json', help='Path to coco json') ap.add_argument('imgroot', help='Path to img root') ap.add_argument('outdir', help='Path to output dir') ap.add_argument('--k', help='Random k images to ex...
#-*- coding: utf-8 -*- import os import sys import codecs from sem.storage import Document, Annotation from sem.exporters import BratExporter from concatenate_dir import make_data, NUM_NEWLINES def main(indirnames, outfilename, default_shift=0, top_level=False): dirs = [] for indirname in indir...
# -wxPython Imports. import wx from EmbroideryView import EmbroideryView class SimulatorView(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: SimulatorView.__init__ kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds)...
from .rnaseq import *
""" author: Kun Wang (Kenn) e-mail: iskenn7@gmail.com """ from dataset.MNIST import MNIST from model.Model import * def mlp_mnist(): mnist = MNIST(dimension=3) model = Model(name='model', input_dim=[28, 28, 1]) model.initial( [ Flatten(name='flatten'), Dense(n...
""" This playbook assigns the event with the current phase first task in the current phase, close the task as completed and run the next playbook in the next task. """ import phantom.rules as phantom import json from datetime import datetime, timedelta def on_start(container): phantom.debug('on_start() called') ...
import time from UnleashClient import UnleashClient # --- import logging import sys root = logging.getLogger() root.setLevel(logging.DEBUG) handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFor...
#!/usr/bin/env python import os import re from bs4 import BeautifulSoup root = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__), "../build/firefox") ) regex = re.compile("^popup.*\.js$") old_name = "" for root, dirs, files in os.walk(root): for file in files: if regex.match(file):...
import locale import os PROJECT = "djenealog" PROJECT_VERBOSE = PROJECT.capitalize() DOMAIN_NAME = os.environ.get("DOMAIN_NAME", "localhost") ALLOWED_HOSTS = [os.environ.get("ALLOWED_HOST", f"{PROJECT}.{DOMAIN_NAME}")] ALLOWED_HOSTS += [f"www.{host}" for host in ALLOWED_HOSTS] SECRET_KEY = os.environ["SECRET_KEY"] D...
import sys from unittest.mock import patch, MagicMock from aturan_calendar_bot.core import cli @patch('aturan_calendar_bot.core.main') def test_empty(m_main): with patch('sys.argv', ['app']): cli() m_main.assert_called_with([]) @patch('aturan_calendar_bot.core.main') def test_good(m_main): ...
"""Do file io - ORA.""" from __future__ import annotations from ..blend import BlendType from ..layeredimage import LayeredImage from ..layergroup import Group, Layer from .common import blendModeLookup # pylint: disable=invalid-name # pylint: disable=import-outside-toplevel #### ORA #### def openLayer_ORA(file: st...
import os import pytest import yaml from prefect.run_configs import KubernetesRun def test_no_args(): config = KubernetesRun() assert config.job_template_path is None assert config.job_template is None assert config.image is None assert config.env is None assert config.cpu_limit is None ...
from discord.ext import commands import discord import json import asyncpg import asyncio import logging logging.basicConfig(level=logging.WARNING) logging.getLogger("asyncio").setLevel(logging.CRITICAL) with open("data/keys.json", "r") as k: # Loads secret keys keys = json.load(k) # Fetch prefix...
from validation import vworkspace import pypsex #import os with vworkspace() as w: #os.environ['CHAINS_DEBUG_LEVEL']='5' w.props.prettyprint_statement_number=True w.props.must_regions = True w.props.constant_path_effects = False w.props.parallelization_ignore_thread_safe_variables = True w.prop...
import numpy as np def convert_img(img): """Converts (H, W, C) numpy.ndarray to (C, W, H) format """ if len(img.shape) == 3: img = img.transpose(2, 0, 1) if len(img.shape) == 2: img = np.expand_dims(img, 0) return img
#!/usr/bin/env python # --------------------------------------------------------------------------- # Licensing Information: You are free to use or extend these projects for # education or reserach purposes provided that (1) you retain this notice # and (2) you provide clear attribution to UC Berkeley, including a lin...
#!/bin/python # # update_release_notes.py # # This source file is part of the FoundationDB open source project # # Copyright 2015-2018 Apple Inc. and the FoundationDB project authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. #...
from django.db import models from datetime import datetime # Create your models here. class Comment(models.Model): post = models.ForeignKey('comment', on_delete=models.CASCADE, related_name='comments') author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeF...
#class_pupils = input('введите имена учеников через запятую:\n') class_pupils = 'АРина' correct_result = ['Арина'] _result = class_pupils.strip(',') result = [] for item in _result: result.append(item.strip().title()) print(result) assert result == correct_result, 'алгоритм реализован неверно'
import os, term, util, net def list(args, channels, groups, imChannels, users): if len(args) == 2 or args[2] == "users": for channel in imChannels: for user in users: if user['id'] == channel['user']: if 'real_name' in user and user['real_name'] != "": ...
import numpy as np from sklearn.metrics import mean_squared_error from examples.time_series.ts_gapfilling_example import get_array_with_gaps from fedot.utilities.ts_gapfilling import ModelGapFiller, SimpleGapFiller from test.unit.tasks.test_forecasting import get_simple_ts_pipeline def test_get_array_with_gaps(): ...
from ortools.sat.python import cp_model def status_to_message(status) -> str: if status == cp_model.INFEASIBLE: return "INFEASIBLE" elif status == cp_model.MODEL_INVALID: return "MODEL_INVALD" else: return "UNKNOWN"
'''Defines the basic util functions for the API.''' import pandas as pd import numpy as np import requests import json def build_url(category, symbol, meta={}, version=3): '''Creates the url based on the given information. Args: category (str): The category of the information (e.g. 'company/profile' or 'fi...
# pylint: disable=missing-docstring import numpy as np import torch import cleverhans.future.torch.utils as utils from cleverhans.devtools.checks import CleverHansTest class TestOptimizeLinear(CleverHansTest): """ Identical to the TestOptimizeLinear in tests_tf/test_attacks. """ def setUp(self): super(Tes...
# coding=utf-8 from __future__ import unicode_literals import functools from .exception import NeedLoginException, IdMustBeIntException __all__ = ['need_login', 'int_id'] def need_login(func): """ 装饰器。作用于 :class:`.ZhihuClient` 中的某些方法, 强制它们必须在登录状态下才能被使用。 """ @functools.wraps(func) def wrapp...
"""Adds config flow for NWS Alerts.""" from __future__ import annotations import logging from typing import Any import aiohttp import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_NAME from homeassistant.core import callback from homeassistant.data_entry_flow import F...
#!/usr/bin/python3 """SlurmctldCharm.""" from ops.charm import CharmBase from ops.framework import StoredState from ops.main import main from ops.model import ( ActiveStatus, BlockedStatus, ModelError, ) from prometheus_node_exporter import ( PrometheusNodeExporterProvides, ) from prometheus_node_export...
from io import open from setuptools import setup, find_packages # from pip.req import parse_requirements with open('requirements.txt') as f: install_requires = f.read().strip().split('\n') setup(name='fast_bert', version='1.3.6', description='AI Library using BERT', author='Kaushal Trivedi', ...
import numpy from merc.shape import Shape class Sphere(Shape): def __init__(self, center, radius): self.center = center self.radius = radius def intersectsSphere(self, sphere, tolerance=0): p1 = numpy.array(self.center) p2 = numpy.array(sphere.center) dist = numpy.linalg.norm(p1 - p2) return dist <= sel...
from django.test import TestCase class TestModels(TestCase): def setUp(self): pass def test(self): pass
import numpy as np import tensorflow as tf from tensorflow import keras import copy from .other import _set_dimensions class TFBaseFunction(keras.Model): def __init__(self, env, model, optimizer, optim_args={}, trainer_args={}): super().__init__() self.env = env self.model = model ...
from src.url_finder import URLFinder def test_finds_an_url(): result = URLFinder().find_all_inline_urls("hello world [anchor](url.com) some irrelevant text") assert result[0] == "[anchor](url.com)" def test_finds_multiple_urls(): result = URLFinder().find_all_inline_urls("[anchor](url.com) other stuff [...
#!/usr/bin/python """ Copyright (c) 2014 High-Performance Computing and GIS (HPCGIS) Laboratory. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. Authors and contributors: Eric Shook (eshook@kent.edu) """ from pcml import * import os.path as path im...
# coding: utf-8 # ---------------------------------------------------------------------------- # <copyright company="Aspose" file="test_storage_api.py"> # Copyright (c) 2019 Aspose Pty Ltd. All rights reserved. # </copyright> # <summary> # Permission is hereby granted, free of charge, to any person obtaining...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: service.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) ...
from cx_Freeze import setup, Executable file = open("main.py","a",encoding="utf-8") r1 = random.randint(-100000, 100000) file.write("\nvar = " + r1) file.write("\nprint(var)\n") file.close() base = None executables = [Executable("main.py", base=base)] packages = ["idna"] options = { 'build_ex...
import unittest import pyworkout from importlib import util from pyworkout.parsers import tcxtools """ Please note that these tests only work in Python 3.5+ at the moment. """ class TestBasicObject(unittest.TestCase): def test_import_of_module(self): library = util.find_spec("pyworkout") self.asse...
# generate a thumbnail gallery of examples template = """\ {%% extends "layout.html" %%} {%% set title = "Thumbnail gallery" %%} {%% block body %%} <h3>Click on any image to see full size image and source code</h3> <br/> %s {%% endblock %%} """ import os, glob, re multiimage = re.compile('(.*)_\d\d') pwd = os.ge...
""" This module contains utility functions for use with Spell (https://spell.run). """ import logging # Spell is only imported in the Spell python environment. We use it to log metrics to Spell. import os from datetime import datetime from typing import Union, Optional, Any, Dict from torch.utils.tensorboard import Su...
# Generated by Django 4.0.2 on 2022-02-28 21:55 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("triggers", "0004_trigger_name"), ] operations = [ migrations.RenameField( model_name="trigger", old_name="triggered", ...
#!/usr/bin/env python import roslib; roslib.load_manifest('flexbe_mirror') import rospy import smach import threading import zlib from flexbe_core import JumpableStateMachine, LockableStateMachine from flexbe_core.core import PreemptableState from mirror_state import MirrorState from flexbe_core.proxy import ProxyPu...
import pathlib import ed25519 from ed25519.keys import SigningKey import gnupg import os name = 'node' + os.environ['NAME'] path = pathlib.Path("/node") passphrase = 'test' if not path.exists(): path.mkdir() gpg = gnupg.GPG(gnupghome=path) node_id = f'{name}@dothttp.dev' allkeys = gpg.list_keys() if len(all...
from typing import Optional from config.whatsapp_notif import RECIPIENTS from src.api.players_client import PlayersClient from src.senders.whatsapp_sender import send_whatsapp_message from src.utils.players_utils import get_all_player_stats class PlayerStatisticsManager: def __init__( self, season: int, ...
#!/usr/bin/env python3 from functools import reduce from pathlib import Path import operator def intceil(x, y): return -(x // -y) def main(): with Path('input', '13').open() as f: seaport, buses = f seaport = int(seaport) buses = [int(b) for b in buses.split(',') if 'x' != b] print(reduce...
""" File: draw_line.py Name: Jess ------------------------- This file let user draws line(s) depends on those two points user clicked. """ from campy.graphics.gobjects import GOval, GLine from campy.graphics.gwindow import GWindow from campy.gui.events.mouse import onmouseclicked # This constant control t...
# Copyright (C) 2018-2019 Apple Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and ...
# -*- coding: utf-8 -*- from rstobj.directives.codeblock import CodeBlockPython, Code from .gps_cmd import parse_go_command, construct_go_command, is_valid_go_command from ...df_to_list_table import df_to_list_table def remove_go_cmd_construct_teleport(df, gm_cmd_col="gm_cmd"): """ :param gm_cmd_col: the .go...
# Copyright (C) 2019 Verizon. 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 ...
def load(h): return ({'abbr': 'a', 'code': 1, 'title': '70 332.5 40 10'}, {'abbr': 'b', 'code': 2, 'title': '72.5 0 50 45'}, {'abbr': 'c', 'code': 3, 'title': '57.5 345 32.5 17.5'}, {'abbr': 'd', 'code': 4, 'title': '57.5 2.5 32.5 42.5'}, {'abbr': 'e', 'code': 5, 'tit...
import os import re import io from base import IndentXmlBase class TestBasicIndentXml(IndentXmlBase): pass fixtures_path = os.getenv("ST_FIXTURES_PATH") if not fixtures_path: raise Exception("To run the unit test suite set ST_FIXTURES_PATH variable to point to 'fixtures' directory") def setup_all_fixture...
import os, sys sys.path.insert(1, os.path.join(sys.path[0], '..', '..', 'module')) import wiki import pickle, dill import numpy as np import pandas as pd import networkx as nx import scipy as sp import leidenalg as la import igraph as ig def round10(x): return int(round(x / 10.0)) * 10 def networkx_to_igraph(nx_g...
# -*- coding: utf-8 -*- """ @date: 2021/7/6 下午9:48 @file: prune_vggnet_by_channel.py @author: zj @description: Depth Pruning, only one layer pruning operation is performed at a time Firstly, the weight of each Bottleneck is calculated; then the Bottleneck with the smallest value is selected for pruning """ import num...
#!/usr/bin/env python3 # This file is a modified version of the gen_embedded script included in the # scripts directory of seasocks (version 1.1.2). It has been modified to # recursively find the web files itself, which was originally done by piping # in the results from a "find" shell command. # The embedded files i...
#Jonathan McCormick #Outsmart Big Brother (TM) #25 March, 2021 # C Y B E R S E C U R I T Y 4 P O L I T I C A L O R G A N I Z A T I O N S youWantToOutsmartBigBrother = True def useStrongPassphrases(): print("Use long, diverse, original, and well-protected passphrases,") def twoFactorAuth(): print("Use...