content stringlengths 5 1.05M |
|---|
class A:
test = 123
a1 = A()
a2 = A()
print(a1.test)
print(a2.test)
A.test = 321
print(a1.test)
print(a2.test)
|
import os
from keras.applications.inception_v3 import InceptionV3
from keras.applications.mobilenet_v2 import MobileNetV2
from keras.models import Model
from keras.layers import Dense, GlobalAveragePooling2D
from keras.metrics import categorical_accuracy
from keras import backend as K
import keras.optimizers
from metri... |
import cv2
import numpy as np
def read_image(image_path: str) -> np.ndarray:
stream = open(image_path, "rb")
bytes = bytearray(stream.read())
array = np.asarray(bytes, dtype=np.uint8)
image = cv2.imdecode(array, cv2.IMREAD_UNCHANGED)
return image
|
# -*- coding: utf-8 -*-
"""
@Time : 2020/4/13 下午6:07
@File : jqtestbase.py
@author : pchaos
@license : Copyright(C), pchaos
@Contact : p19992003#gmail.com
"""
import unittest
import datetime
import os
from jqdatasdk import *
from dotenv import load_dotenv
from .testbase import TestingBase
def getEnvVar(key)... |
# -*- coding: utf-8 -*-
# Copyright 2019 Spanish National Research Council (CSIC)
#
# 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
#
# Unle... |
#-*- coding: utf-8 -*-
# Creation Date : 2016-10-21
# Created by : Antoine LeBel
import observer
class MailingService(observer.Observer):
MIN_HUMIDITY = 20
def __init__(self):
self.sensor = None
def update(self, HumiditySensor):
self.sensor = HumiditySensor
if HumiditySensor.humid... |
import config_tb
from config_db import config
import requests
from datetime import datetime
from bs4 import BeautifulSoup
import telebot
from db import UseDataBase
from emoji import *
# заглавная страница сервиса Яндекс.Погода с прогнозом
# по текущему месту положения
URL = 'https://yandex.ru/pogoda/'
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class DQN(nn.Module):
def __init__(self, input_dimension, output_dimension):
super(DQN, self).__init__()
self.layer_1 = nn.Linear(
in_features=input_dimension, out_features=64)
self.layer_2 = nn.Linear(in_featu... |
from __future__ import annotations
import pytest
from ufoLib2.objects import Glyph, Layer
def test_init_layer_with_glyphs_dict() -> None:
a = Glyph()
b = Glyph()
layer = Layer("My Layer", {"a": a, "b": b})
assert layer.name == "My Layer"
assert "a" in layer
assert layer["a"] is a
asser... |
from typing import Callable, Union, List
from .errors import CredentialError, TokenExpired, QRExpiredError
from .utils import password_fixer
import json
import os
import threading
import requests
import websocket
class PyTeleBirr:
def __init__(
self,
phone_no: Union[int, str],
... |
# coding=utf-8
"""
"""
import os
import unittest
import shutil
from md_utils.rename_files import main
from md_utils.md_common import (capture_stdout, capture_stderr, silent_remove)
import logging
# logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
DISABLE_REMOVE = logger.isEnabledFor(log... |
"""
Generic templates for different types of Encryption Schemes
"""
__version__ = "2.0.2"
|
def test_epochs_mapping(client):
case_id = 'scoring'
epochs_mapping_json = client.get(f'api/sandbox/epoch/{case_id}').json
assert epochs_mapping_json[0]['epoch_num'] == 1
assert epochs_mapping_json[1]['individual_id'] is not None
assert epochs_mapping_json[1]['epoch_num'] == 2
def test_case_param... |
import numpy as np
import sys
import gc
import chroma.api as api
if api.is_gpu_api_cuda():
import pycuda.driver as cuda
from pycuda import gpuarray as ga
elif api.is_gpu_api_opencl():
import pyopencl as cl
#from pyopencl.array import Array as ga
import pyopencl.array as ga
from chroma.tools import p... |
"""This module finds similar songs based on common adjectives.
Note: This module is based on the module lyrics_topics but is not included
in or combined with lyrics_topics to avoid confusion and to allow the
possibility of working with only one method to find similar lyrics since
they do not lead to equall... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2008-2009 Zuza Software Foundation
#
# This file is part of the Translate Toolkit.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; e... |
# Generated by Django 2.1.7 on 2019-07-30 14:40
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('user', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='subjectinfo',
name='subject_... |
import requests
import base64
serverip = "172.20.10.3"
port = "8080"
router = "detectionMinic"
url = "http://" + serverip + ":" + port + "/" + router
def request(imgFile):
with open(imgFile, 'rb') as f:
rdata = f.read()
e64data = base64.b64encode(rdata)
prm = {'img': e64data}
re... |
import os
import matplotlib.pyplot as plt
import pandas as pd
from lstchain.io.io import dl2_params_lstcam_key
from lstchain.visualization import plot_dl2
def test_plot_disp(simulated_dl2_file):
dl2_df = pd.read_hdf(simulated_dl2_file, key=dl2_params_lstcam_key)
plot_dl2.plot_disp(dl2_df)
def test_directi... |
from dbnd._core.tracking.schemas.base import ApiStrictSchema
from dbnd._vendor.marshmallow import fields
class LogMessageSchema(ApiStrictSchema):
source = fields.String(allow_none=True)
stack_trace = fields.String(allow_none=True)
timestamp = fields.DateTime(allow_none=True)
dbnd_version = fields.Stri... |
# This file is adapted from the perturbseq library by Thomas Norman
# https://github.com/thomasmaxwellnorman/perturbseq_demo/blob/master/perturbseq/cell_cycle.py
import pandas as pd
import numpy as np
from collections import OrderedDict
from scipy.sparse import issparse
from ..tools.utils import einsum_correlation, lo... |
from os import environ
# if you set a property in SESSION_CONFIG_DEFAULTS, it will be inherited by all configs
# in SESSION_CONFIGS, except those that explicitly override it.
# the session config can be accessed from methods in your apps as self.session.config,
# e.g. self.session.config['participation_fee']
SESSION_... |
import tensorflow as tf
# This part can be uncommented if GPU is available in computer system.
#tf.test.is_gpu_available
#from tensorflow.python.client import device_lib
#print(device_lib.list_local_devices())
### Modified on Feb 10 2021 due to tensorflow update
import os
import pandas as pd
import numpy as np
fro... |
from distutils.core import setup
setup(name='pypp',
version='0.0',
description='post-processing eigendecompositions computed with paladin',
url='https://github.com/michael-a-hansen/paladin',
author='Mike Hansen',
author_email='[email protected]',
license='MIT',
packag... |
#!/usr/bin/env python3
import numpy as np
class Car:
"""
Kinematic model of a car-like robot with ref point on front axle
States: x, y, yaw, v
Inputs: a, delta
"""
def __init__(self, x=0, y=0, yaw=0, v=0):
self.x = 0
self.y = 0
self.yaw = 0
self.v = 0
sel... |
import cv2
from matplotlib import pyplot as plt
from os import walk
import os
class LocalDescriptors:
def __init__(self):
pass
def orb_descriptor(self,file, nfeatures=500):
img = cv2.imread(file)
# Initiate STAR detector
orb = cv2.ORB_create(nfeatures=nfeatures)
# f... |
# -*- coding: utf-8 -*-
'文件发送方'
import socket
import threading
import header
import os
import sys
def transfer_file(sock, file_path, print_type):
'发送文件'
# 准备发送文件
sock.send(header.SEND_FILE)
# 打开的文件
fp = None
while True:
data = header.unpack_msg(sock.recv(1024))
if data[0]... |
import urllib2
import re
import slate
import pdfminer
url="http://45.32.111.231:8080/birt/frameset?__report=mydsi/exam/Exam_Result_Sheet_dsce.rptdesign&__format=pdf&USN="
usn = "1DS15IS00"
i=0
def main():
global i,usn
for i in range(1,9):
download_file(url+usn+str(i))
usn = "1DS15IS0"
... |
""" Ex - 047 - Crie um programa que mostre na tela todos os números pares que estão no intervalo de 1 a 50"""
# Como eu Fiz
print(f'{"> Números Pares <":=^40}')
# Criar var:
num_par = []
# Criar laço de repetição:
for count in range(1, 51):
par = count % 2
if par == 0:
num_par.append(coun... |
from flask import Flask, jsonify, request, render_template, redirect
import logging
from enum import Enum
app = Flask(__name__)
BootupStatus = Enum('BootupStatus', ('Initial', 'NeedBootup'))
current_bootup_status = BootupStatus.Initial
@app.route("/")
def index():
return render_template('index.html', current_boot... |
"""Heatmap and dendograms"""
import matplotlib
import pylab
import scipy.cluster.hierarchy as hierarchy
import scipy.spatial.distance as distance
import numpy as np # get rid of this dependence
import easydev
import colormap
from biokit.viz.linkage import Linkage
__all__ = ['Heatmap']
def get_heatmap_df():
"""a... |
from django.http import HttpResponse
from django.views.generic import ListView, TemplateView
from .models import Player
class IndexView(TemplateView):
template_name = 'quarto/index.html'
class BoardView(TemplateView):
template_name = 'quarto/board.html'
context_object_name = 'board'
def get_co... |
# import Python's built-in JSON library
import json, sys
# import the psycopg2 database adapter for PostgreSQL
from psycopg2 import connect, Error
#Get necessary functions
from scryfall_get import *
scry_resp() |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-11-15 19:23
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bruv', '0019_auto_20161025_2316'),
]
operations = [
migrations.RemoveField(
... |
from robocorp_ls_core.python_ls import PythonLanguageServer
from robocorp_ls_core.basic import overrides, log_and_silence_errors
import os
import time
from robotframework_ls.constants import DEFAULT_COMPLETIONS_TIMEOUT
from robocorp_ls_core.robotframework_log import get_logger
from typing import Any, Optional, List, Di... |
#----------------------------------------------------------------------
# Copyright (c) 2014-2016, Persistent Objects Ltd http://p-o.co.uk/
#
# License: BSD
#----------------------------------------------------------------------
"""
WSGI config for mldemo project.
It exposes the WSGI callable as a module-level variabl... |
pattern_zero=[0.0, 0.01586888658, 0.03121748179, 0.03225806452, 0.04604578564, 0.04812695109, 0.06035379813, 0.06347554631, 0.06451612903, 0.07414151925, 0.07830385016, 0.08038501561, 0.08740894901, 0.09261186264, 0.09573361082, 0.09677419355, 0.10015608741, 0.10639958377, 0.11056191467, 0.11238293444, 0.11264308013, 0... |
#!/usr/bin/python
from optparse import OptionParser
import re
import os, sys
def usage(argv):
if len(argv) != 3:
print "Error: \n Usage: " + argv[0] + " wordlist directory \n"
sys.exit(1)
def ReadFromDir(directory):
#for pattern in directory:
listing = []
for fname in os.listdir(directory):
... |
"""MicroESP Errors
"""
__author__ = 'Oleksandr Shepetko'
__email__ = '[email protected]'
__license__ = 'MIT'
class ESP8266Error(Exception):
pass
class DeviceNotConnectedError(ESP8266Error):
pass
class DeviceCodeExecutionError(ESP8266Error):
pass
|
import os
import pytest
from api_flow.config import Config
from api_flow.flow import Flow
from api_flow.step import Step
from unittest.mock import patch
@pytest.fixture(autouse=True)
def setup():
Config.data_path = os.path.join(os.path.dirname(__file__), 'test_data')
@pytest.fixture
def mock_step_execute():
... |
from dataclasses import dataclass
from enum import Enum, auto
from functools import cache
class TokenType(Enum):
# Two or more character tokens and operators
DEFINE = "="
EQUALS = "=="
NOT_EQUALS = "!="
SMALLER_OR_EQUAL_THAN = "<="
GREATER_OR_EQUAL_THAN = ">="
RANGE = ".."
# Single-cha... |
from .callhub import CallHub |
"""Definition of an ElkM1 Area"""
from .const import Max, TextDescriptions
from .elements import Element, Elements
from .message import add_message_handler, as_encode, al_encode, dm_encode
class Area(Element):
"""Class representing an Area"""
def __init__(self, index, elk):
super().__init__(index, el... |
#!/usr/bin/env python
import numpy as np
#############################
## DEFAULT PARAMETER GRIDS ##
#############################
DEFAULT_DIFF_COEFS = np.logspace(-2.0, 2.0, 100)
DEFAULT_LOC_ERRORS = np.arange(0.0, 0.072, 0.002)
DEFAULT_HURST_PARS = np.arange(0.05, 1.0, 0.05)
#######################################... |
from __future__ import unicode_literals
import frappe
def execute():
if frappe.db.exists("DocType", "Membership"):
if 'webhook_payload' in frappe.db.get_table_columns("Membership"):
frappe.db.sql("alter table `tabMembership` drop column webhook_payload") |
# test_getopt.py
# David Goodger <[email protected]> 2000-08-19
import getopt
from getopt import GetoptError
from test_support import verbose
def expectException(teststr, expected, failure=AssertionError):
"""Executes a statement passed in teststr, and raises an exception
(failure) if the expected excep... |
from rlagent.noises.ounoise import OUNoise
|
#!/usr/bin/env python
#pylint: skip-file
# This source code is licensed under the Apache license found in the
# LICENSE file in the root directory of this project.
class PolicyApplication(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and th... |
from django.http import HttpResponse
def index(request):
result = "<h1>welcome to my site</h1>"
return HttpResponse(result)
|
import platform
import os
def mkdir(path):
e = os.path.exists(path)
if not e:
os.makedirs(path)
return True
else:
return False
def mkfile(filePath):
pipfile = "[global]\ntrusted-host=mirrors.aliyun.com\nindex-url=http://mirrors.aliyun.com/pypi/simple/"
if os.path.exists(f... |
from rect import Rect
class Bomb(Rect):
Bombs = []
def __init__(self, x, y):
self.total_frames = 0
super(Bomb, self).__init__(x, y, 32, 32)
Bomb.Bombs.append(self) |
import pytest
@pytest.fixture
def mock_execution_context(mocker):
mock_context = mocker.Mock()
mock_context.parameters.database = "test_database"
mock_context.parameters.model_version_id = 12345
return mock_context
@pytest.fixture
def mock_ezfuncs(mocker):
return mocker.patch("cascade.core.db.ez... |
##############################################################################
# Copyright (c) 2015 Huawei Technologies Co.,Ltd and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, ... |
from unittest import TestCase
from packaging.version import Version
from packaging.specifiers import SpecifierSet
from pyrrot import Pyrrot
class TestIsOld(TestCase):
def setUp(self):
self.l = Version('2.0.0')
def test_equals(self):
specs = SpecifierSet('==1.0.0')
self.assertTrue(Py... |
from abaqusConstants import *
class OdbDataFrame:
"""The OdbDataFrame object.
Notes
-----
This object can be accessed by:
.. code-block:: python
import visualization
session.odbData[name].steps[i].frames[i]
"""
def setValues(self, activateFrame: Boolean, up... |
from fastapi import FastAPI
from routes.student import student_router
import uvicorn
import os
app = FastAPI()
# uvicorn main:app --reload
# Register routes
app.include_router(student_router)
if __name__ == '__main__':
host = "127.0.0.1"
port = 5000
os.system("start \"\" http://" + host + ":" + str(port... |
import pytest
from pyschieber.rules.count_rules import counting_factor
from pyschieber.deck import Deck
from pyschieber.trumpf import Trumpf
from pyschieber.player.random_player import RandomPlayer
from pyschieber.game import Game, get_player_index
from pyschieber.team import Team
@pytest.mark.parametrize("start_... |
import PILasOPENCV as Image
# from PIL import Image
#
img1 = Image.open('Images/cat.jpg')
img2 = Image.open('Images/landscape.jpg').resize(img1.size)
mask = Image.open('Images/mask1.jpg')
mask = mask.resize(img1.size)
#
im_new1 = Image.composite(img1, img2, mask)
im_new1.show()
img1 = Image.open('Images/cat... |
from flask_restplus import Resource, Namespace
from app.extensions import api as app_api
from app.api.utils.access_decorators import requires_role_mine_view, requires_role_mine_create
class DummyResource(Resource):
@requires_role_mine_view
def get(self):
return "Example view method"
@requires_rol... |
#
# @lc app=leetcode id=1178 lang=python3
#
# [1178] Number of Valid Words for Each Puzzle
#
# @lc code=start
class Solution:
def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:
ans = []
freq = dict()
for word in words:
mask = 0
for c ... |
# -*- coding: utf-8 -*-
# Copyright 2015 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 ... |
# Copyright (c) 2020 The FedVision Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... |
# encoding: utf-8
'''
@author: Minghao Guo
@contact: [email protected]
@software: nef
@file: sart.py
@date: 8/28/2019
@desc:
'''
from nefct import nef_class
import numpy as np
from nefct.data.image import Image
from nefct.data.projection import ProjectionSequence
from nefct.functions.project import Project
from nef... |
#!/usr/bin/env python
#
#___INFO__MARK_BEGIN__
##########################################################################
# Copyright 2016,2017 Univa 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 ... |
#!/usr/bin/env python
##############################################################################
#
# diffpy.structure by DANSE Diffraction group
# Simon J. L. Billinge
# (c) 2008 trustees of the Michigan State University.
# All rights reserved.
#
# File coded b... |
import json
import argparse
from deepfrier.Predictor import Predictor
def get_all_labels(annot_file, ont='mf'):
if ont == 'ec':
with open(annot_file, "r") as f:
f.readline()
tasks = f.readline().strip().split("\t")
task_dict = {v: k for k, v in enumerate(tasks)}
... |
"""
The ``serve`` subcommand launches a server
that exposes trained models via a REST API,
and that includes a web interface for exploring
their predictions.
.. code-block:: bash
$ python -m allennlp.run serve --help
usage: run [command] serve [-h] [--port PORT] [--workers WORKERS]
... |
#··················································································#
#··················································································#
# How to run #
# python3 ProtList.py -i ./ScopDatabaseFile.txt -o ScopeN... |
"""Code for flask mongodb extension in scout"""
import os
from scout.adapter.client import get_connection
class MongoDB:
"""Flask interface to mongodb"""
@staticmethod
def init_app(app):
"""Initialize from flask"""
db_name = os.environ.get("MONGO_DBNAME") or app.config.get("MONGO_DBNAME... |
from enum import Enum
class FieldState(Enum):
NONE = " "
BOT = "O"
PLAYER = "X"
|
#!/usr/bin/env python
import asyncio
import json
import threading
import time
import websockets
queue = asyncio.Queue()
new_loop = asyncio.new_event_loop()
def start_loop(loop):
asyncio.set_event_loop(loop)
loop.run_forever()
async def producer():
for i in range(5):
await asyncio.sleep(1)
... |
# Copyright (c) 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 la... |
from rpython.rlib import jit
from . import oop, pretty
class Cont(pretty.PrettyBase):
_immutable_ = True
def to_pretty(self):
return pretty.atom('#<Cont>')
# Not necessarily safe to call this directly.
def plug_reduce(self, w_value, env):
assert isinstance(w_value, oop.W_Value)
... |
# A part of esc2pdf (https://github.com/szihlmann/esc2pdf)
# Copyright (C) 2021 Serge Zihlmann, Bern, Switzerland
# MIT license -- See LICENSE.txt for details
class State(object):
# State object which provides utility functions for the individual state
def __init__(self):
pass
def on_byte(self, b... |
# Data science project config file
import os
# Project name
PROJECT_NAME = 'kaggle-talkingdata2'
# Paths
DATA_BASE_PATH = os.path.expanduser(os.getenv('DATA_BASE_PATH'))
DATA_PATH = os.path.join(DATA_BASE_PATH, PROJECT_NAME)
# Comet
COMET = {
'api_key': os.getenv('COMET_API_KEY'),
'project_name': PROJECT_NAM... |
import pyowm
import json
import requests
from pyowm import timeutils, exceptions
from telegram import Message, Chat, Update, Bot, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import run_async
from emilia import dispatcher, updater, API_WEATHER, API_ACCUWEATHER, spamcheck
from emilia.modules.disable im... |
from django.shortcuts import redirect
def admin_check(user):
if user.is_active and user.is_authenticated:
if user.is_user_admin:
return True
return False
def admin_required(function=None, redirect_field_name=None, login_url='/login/'):
"""
Decorator for views that checks that the user is logged in
and has ... |
"""
demo04_bin.py 二值化
"""
import numpy as np
import sklearn.preprocessing as sp
samples = np.array([[17., 100., 4000.],
[20., 80., 5000.],
[23., 60., 5500.]])
bin = sp.Binarizer(threshold=80)
r_samples = bin.transform(samples)
print(r_samples)
samples[samples<=80] = 0
samples[samples>80] = 1
print(sampl... |
def getStrandPairMethylation(methylationLocationsOneFileName, methylationLocationsTwoFileName, outputFileName):
# Gets the locations of the methylated bases that are in both strands
# Also determines the fraction of methylated bases in each strand that are methylated in the other strand
# ASSUMES THAT LOCATIONS IN F... |
"""
Module to write truth catalogs for AGNs using the AGNs parameters db as input.
"""
import os
import sys
import json
import logging
import sqlite3
import numpy as np
import pandas as pd
from lsst.sims.photUtils import PhotometricParameters
from lsst.sims.utils import angularSeparation
from .synthetic_photometry impo... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
import numpy as np
import tensorflow as tf
import onnx
from onnx_tf.backend import run_node, prepare
from onnx import helper
from onnx.onnx_pb2 import Ten... |
# coding=utf-8
# Copyright 2021
import tensorflow as tf
import numpy as np
import pickle
import re
import os.path
import argparse
import ConfMapper as cm
from pathlib import Path
from datetime import datetime
# Config
# Creat a parser instance as interface for command arguments
parser = argparse.Argume... |
from math import e
import warnings
from typing import Dict, List, Tuple
import numpy as np
import pandas as pd
from ..optimize import Optimizer
from .optimal_scaling_problem import OptimalScalingProblem
from .parameter import InnerParameter
from .problem import InnerProblem
from .solver import InnerSolver
REDUCED = ... |
# -*- coding: utf-8 -*-
"""Settings for when running under docker in development mode."""
from .dev import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(ABS_PATH('./'), 'db.sqlite3'),
},
'backend': {
'ENGINE': 'django.contrib.gis.d... |
import logging
from datetime import timedelta, datetime
import traceback
import time
from django_cronium.models import CronJobLog
from django.utils import timezone
class Schedule(object):
def __init__(self, run_every_mins=None, run_at_times=[], retry_after_failure_mins=None):
self.run_every_mins = run_ev... |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
#!/usr/bin/env python
import torch
import tqdm
import sys
from fairseq.models.bart import BARTModel
if len(sys.argv) < 5:
print("Usage: python bart_infer.py ckp_path bin_path source_file target_file")
sys.exit(0)
ckp_path = sys.argv[1]
bin_path = sys.argv[2]
source_file = sys.argv[3]
target_file = sys.argv[4]... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import numpy as np
from phrun.cache import Cache
from phrun.runner import Runner
Cache.set_root_dir('.')
def test_cache():
cache = Cache.get_cache('test_common')
cache.set('int', 100)
assert cache.get('int') == 100
cache.clean()
def test_runn... |
import xml.etree.ElementTree as ET
from urllib import request, parse
from copy import copy
def soap_request(url, data):
req = request.Request(url, data=data.encode('utf-8'),
headers={'content-type': 'text/xml;charset=utf-8'}, method='POST')
rep = request.urlopen(req)
return xml_t... |
# -*- coding: utf-8 -*-
from .permissions import SignedPermission # noqa
from .signing import sign_filter_permissions # noqa
from .views import SignedViewSetMixin # noqa
|
import numpy as np
import cv2
import sys
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
print (sys.argv[1])
cv2.imwrite("./faces/"+sys.argv[1]+".jpg", frame)
cap.release()
|
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Retrieves a player achievement, earned or unearned.
This is a player facing Lambda function and used in-game.
"""
import botocore
from gamekithelpers import handler_request, handler_response, ddb
i... |
from tkinter import *
from PIL import ImageTk, Image
root = Tk() # Init app
root.title("Images") # Set title here
root.iconbitmap("Images/neon.ico") # Insert icon here
my_img = ImageTk.PhotoImage(Image.open("Images/Burger.jpg").resize((300,400))) # Insert image here
my_label = Label(image=my_img)
my_label.pack()
bu... |
#!/usr/bin/env python
import wx
import images
FRAMETB = True
TBFLAGS = ( wx.TB_HORIZONTAL
| wx.NO_BORDER
| wx.TB_FLAT
#| wx.TB_TEXT
#| wx.TB_HORZ_LAYOUT
)
#---------------------------------------------------------------------------
class TestSearchCtrl(w... |
#!/usr/bin/env python3
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
import pytest
from basecls.layers import NORM_TYPES
from basecls.models.resnet import resnet18
from basecls.solver.optimizer import SGD
from basecls.solver.weight_decay import get_param_groups
@pytest.mark.parametrize("weight_decay", [... |
from logger import Logger
logger = Logger()
logger.log("hello")
logger.log("goodbye")
logger.print_messages()
logger.log("something else")
print("")
logger.print_messages()
|
#!/usr/bin/env python
"""
Copyright 2015 ARC Centre of Excellence for Climate Systems Science
author: Scott Wales <[email protected]>
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
h... |
""" LibMCS2018.py
Module assembling algorithms and data structures
Supplemental Material for the Lecture Notes "Networks - A brief Introduction
using a Paradigmatic Combinatorial Optimization Problem" at the international
summer school "Modern Computational Science 10 - Energy of the Future" held
in Oldenburg, Septem... |
import pytest
from assertions import list_is
dummy_lst = [{"name": "Elmer"}, {"name": "Sam"}]
params = (
("lst", "subset_lst", "expected"),
[
([], [], True),
([{}, {}], [{}, {}, {}], True),
(
[{"id": 1, "name": "Jon", "pets": []}, {"id": 2, "name": "Sam"}],
[{... |
api_key = 'Your API Key goes here'
api_key_secret = 'Your API Secret Key goes here'
access_token = 'Your Access Token goes here'
access_token_secret = 'Your Access Token Secret goes here' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.