content
stringlengths
0
894k
type
stringclasses
2 values
# Generated by Django 3.1.2 on 2020-10-29 00:29 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('categories', '0001_initial'), ] operations = [ migrations.CreateModel( name...
python
#!/usr/bin/python2 import argparse import traceback from os.path import exists from selenium import webdriver from selenium.webdriver.common.by import By import ipdb from time import sleep from random import random from telegram_send import send import re from datetime import datetime import pickle def update_price_h...
python
#!/usr/bin/env python # Copyright 2013 Brett Slatkin # # 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 o...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright(c) 2020 De Montfort University. All rights reserved. # # """ Find all solutions script. Written for use with the Gunport Problem solving scripts. """ import numpy as np import common as cmn # Common defines and functions __author__ = 'David Kind...
python
from django.shortcuts import render from django.http import HttpResponse from django.contrib import messages from test1.player_performance import player_stats # Create your views here. def home(Request): # Go to Homepage return render(Request, 'homepage.html') def search(Request): # If users enter correct player ...
python
#!/usr/bin/env python import argparse, grp, pwd, os, sys, tarfile def main(argv): parser = argparse.ArgumentParser(description='Extract a tar archive using simple I/O.', add_help = False) parser.add_argument('-?', '-h', '--help', help='Display this message and exit', action='store_true', dest='help') pars...
python
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.11.3 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" ...
python
from itertools import chain, repeat from six.moves import cStringIO as StringIO from . import builtin from .file_types import source_file from .. import safe_str from .. import shell from ..backends.make import writer as make from ..backends.ninja import writer as ninja from ..build_inputs import Edge from ..file_type...
python
import os import yaml filepath = os.path.join(os.path.curdir, "config", "settings.yml") def __get_setting(): with open(filepath, encoding="utf-8")as f: return yaml.load(f) def app_id(): return __get_setting()["YOLP"]["appid"] def coordinates(): return __get_setting()["coordinates"] def sla...
python
import datetime import os import sys import quickfix as fix sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) import app.pricefeed import app.pxm44 as pxm44 DATA_DICTIONARY = fix.DataDictionary() DATA_DICTIONARY.readFromURL('spec/pxm44.xml') # 20 level book MSG = fix.Message('8=FIX.4...
python
import pandas as pd from ml2_mini_project.dataPrep.apply_moving_average import apply_moving_average from ml2_mini_project.dataPrep.apply_pct_change import apply_pct_change from ml2_mini_project.dataPrep.collapse_dataframe_into_new import \ collapse_dataframe_into_new from ml2_mini_project.dataPrep.normalize_by_col...
python
# SPDX-License-Identifier: MIT # Copyright (c) 2022 MBition GmbH from typing import Any, Dict, List, Optional, Union, Type from ..odxtypes import DataType from ..utils import read_description_from_odx from ..globals import logger from .compumethodbase import CompuMethod from .compuscale import CompuScale from .iden...
python
import unittest import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MCwebDjango.settings') import django django.setup() from django.utils import timezone from mcwebapp.models import * from django.contrib.auth.models import User def populate(): curr_time = timezone.now() # Create superuser. ...
python
import anki_vector import time def main(): args = anki_vector.util.parse_command_args() with anki_vector.Robot() as robot: for _ in range(10): if robot.proximity.last_sensor_reading: distance = robot.proximity.last_sensor_reading.distance print("====...
python
import datetime from enum import Enum class Escape(Enum): BEGIN = '\033\033[92m' END = '\033[0m' _dayName = {1:'Mo',2:'Tu',3:'We',4:'Th',5:'Fr',6:'Sa',7:'Su'} def _title(year,month): date = datetime.date(year,month,1) return '{0:^21}'.format(date.strftime('%B')) def _dayHead(nday=37): out = ''...
python
import torch import torchvision from torch.utils.data import DataLoader, Subset import pytorch_lightning as pl import torchvision.transforms as transforms from torchvision.datasets import ImageFolder import os, sys from glob import glob import cv2 from PIL import Image sys.path.append('../') from celeba.dataset impor...
python
from enum import Enum from typing import Optional, List from happy_config.typechecking.types import Type, StructuralType, PrimitiveType from happy_config.typechecking.typecheck_error import TypeCheckError, TypeMismatch, InvalidField, InvalidEnumValue def check_type(x, tp: Type) -> Optional[TypeCheckError]: def co...
python
""" Example: Solving nonsmooth problem #K|x1| + |x2| -> min #x0 = [10^4, 10] x_opt = all-zeros f_opt = 0 """ from numpy import * from openopt import NSP K = 10**3 f = lambda x: abs(x[0]) + abs(x[1])*K + abs(x[2]) * K**2 x0 = [1000, 0.011, 0.01] #OPTIONAL: user-supplied gradient/subgradient df = lambda x: [sign(x[0...
python
from part1 import ( gamma_board, gamma_busy_fields, gamma_delete, gamma_free_fields, gamma_golden_move, gamma_golden_possible, gamma_move, gamma_new, ) """ scenario: test_random_actions uuid: 522367919 """ """ random actions, total chaos """ board = gamma_new(5, 4, 3, 2) assert board is...
python
import name_lib_main my_name = "Fred" my_length = name_lib_main.name_length(my_name) my_lower_case = name_lib_main.lower_case_name(my_name) print(f"In my code, my length is {my_length} and my lower case name is: {my_lower_case}")
python
# -*- coding: utf-8 -*- """ @Time : 2018/1/25 14:04 @Author : Elvis zsl_resnet.py for m in self.fc1: if hasattr(m, 'weight'): orthogonal(m.weight) """ import numpy as np import torch from torch import nn import torch.nn.functional as F from torch.autograd import Variable from torchvision.models import ...
python
#!/usr/bin/env python """ Usage: explain_lm FST STR Explain the cost assigned to a string STR by the fst FST. """ def main(fst_path, string): fst = FST(fst_path) s = string.replace('<noise>', '%') subst = {'^': '<bol>', '$': '<eol>', ' ': '<spc>', '%': '<noise>'} fst.explain([subst.get(c, c) for c in...
python
from __future__ import division import random import os import numpy as np import pickle import datetime import json class Decision(object): def __init__(self, pair, result, reviewer, time): self.pair = pair self.result = result self.reviewer = reviewer self.time = time def dic...
python
from setuptools import setup, find_packages setup( name = 'aes', version = '1.0.0', description = 'AES(Advanced Encryption Standard) in Python', author = 'Donggeun Kwon', author_email = 'donggeun.kwon@gmail.com', url = 'https://github.com/Don...
python
from typing import NamedTuple, Optional, Tuple import numpy as np from cgtasknet.tasks.reduce.reduce_task import ( _generate_random_intervals, ReduceTaskCognitive, ReduceTaskParameters, ) class RomoTaskParameters(NamedTuple): dt: float = ReduceTaskParameters().dt trial_time: float = 0.25 ans...
python
# -*- coding: utf-8 -*- """ Created on Fri May 10 09:24:08 2019 @author: zjrobbin """ w_dir='E:/Maca_Climate_Files_Sapps/' ## Librarys from datetime import datetime, timedelta from netCDF4 import num2date, date2num import matplotlib.pyplot as plt import geopandas import rasterio as rt import numpy as n...
python
from tortoise import fields from tortoise.models import Model from app.db.base import ModelTimeMixin __all__ = ['Store'] class Store(Model, ModelTimeMixin): """店铺""" id = fields.IntField(pk=True) name = fields.CharField(unique=True, max_length=64, description='店铺名称') desc = fields.CharField(null=T...
python
import numpy as np from pymoo.algorithms.soo.nonconvex.es import ES from pymoo.docs import parse_doc_string from pymoo.core.survival import Survival from pymoo.util.function_loader import load_function class StochasticRankingSurvival(Survival): def __init__(self, PR): super().__init__(filter_infeasible=...
python
from ismo.ensemble import run_all_configurations import json import git if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description=""" Runs the ensemble for M different runs (to get some statistics). """) parser.add_argument('--script_name', type=str, required=True, ...
python
"""This module contains helper functions to use the Paho MQTT library with the MQTT broker defined in a :class:`.MQTTConfig` object. """ import json from paho.mqtt.publish import single def auth_params(mqtt_config): """Return the authentication parameters from a :class:`.MQTTConfig` object. Args: ...
python
import logging as log import imp from imagebot import pysix class MonitorException(Exception): pass def start_tk_monitor(outpipe): from imagebot.monitor_tk import Monitor #Tkinter will have to be imported in its own process for Tk to work mon = Monitor(outpipe) mon.start() def start_gtk_monitor(outpipe): f...
python
# -*- coding: utf-8 -*- # @Time : 2020/3/7 10:39 PM # @Author : zyk # @Email : zhangyongke1105@163.com # @File : my_test.py # @Software : PyCharm # 在列表之间移动元素 # 首先,创建一个待验证码用户列表,和一个用于存储已验证用户的空列表 unconfirmed_users = ['alic', 'brian', 'candace'] confirmed_users = [] # 验证每个用户,直到没有未验证的用户为止,并将每个验证过的用户都添加到已验证用户列表中 w...
python
from sklearn.preprocessing import StandardScaler as StdScaler from niaaml.preprocessing.feature_transform.feature_transform_algorithm import ( FeatureTransformAlgorithm, ) __all__ = ["StandardScaler"] class StandardScaler(FeatureTransformAlgorithm): r"""Implementation of feature standard scaling algorithm. ...
python
import cairosvg import cv2 import numpy as np import sys from PIL import Image # board = 'stm32tiny' board = 'HermitL' board = 'HermitR' board = 'ZoeaR' layer = 'F_Paste' layer = 'B_Paste' root = '/Users/akihiro/repos/Hermit/{}/'.format( board ) path_png = root + 'layer/{}-{}.png'.format( board, layer ) path_bmp = roo...
python
import sys import optparse from .generate_pyt_meta import meta_toolbox def parse_options(args=None, values=None): """ Define and parse `optparse` options for command-line usage. """ usage = """%prog [options] [TOOLBOX_PATH]""" desc = "Generate ArcGIS Metadata from markdown'd toolbox code. " ...
python
class readInfo:
python
# -*- coding: utf-8 -*- """ Created on Fri Jul 23 17:47:14 2021 @author: keikei """ """ Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must...
python
class Supplier: def __init__(self, location, frequency): self.location = location self.frequency = frequency
python
import pstat import copy import support from typed_math import pow, sqrt, exp, abs, fabs, log, round, pi #################################### ####### FREQUENCY STATS ########## #################################### def itemfreq(inlist:List(float))->List(List(float)): """ Returns a list of pairs. Each pair consi...
python
from app_base import * from app_data import * import etk_helper @api.route('/projects/<project_name>/actions/project_config') class ActionProjectConfig(Resource): @requires_auth def post(self, project_name): # frontend needs to fresh to get all configs again if project_name not in data: ...
python
import json from ..customlogging import CustomLog class Tradier(object): def __init__(self, httpclient, httpclient_streaming, token): self.httpclient_streaming = httpclient_streaming self.streams = Tradier.Streams(self) self.httpclient = httpclient self.token = token self....
python
r""" Core collapse supernova explosion engines: explodability as a function of progenitor mass in solar masses as reported by the Sukhbold et al. (2016) [1]_ models. **Signature**: from vice.yields.ccsne.engines import S16 .. versionadded:: 1.2.0 .. tip:: Instances of the ``engine`` class can be passed the keyword a...
python
#!/usr/bin/env python # this script should work with almost any python version, I think import argparse import glob import json def get_replacement_lines(): replacements = [] for file in glob.glob('./json/*.json'): with open(file) as fp: data = json.load(fp) value = list(data.val...
python
from .models import Category def common(request): category=Category.objects.all() context={ 'category':category } return context
python
#!/usr/bin/env python import time import argparse import hashlib,binascii import krbKeyCrack import krbKeyGenerate if __name__ == '__main__': # Command line arguments parser = argparse.ArgumentParser(description="Kerberos POC Benchmark") parser.add_argument('wordlist', nargs='?', default = "/usr/share/wor...
python
default_app_config = "BICAPweb.apps.BICAPwebConfig"
python
import torch import torch.nn as nn import torch.nn.functional as F class DQNetwork(nn.Module): """My Deep Q Network""" # Go for an architecture that worked for the lunar lander mini project # Had a simple architecture with two dropout layers. def __init__( self, state_size, action_size, seed, fc_u...
python
from __future__ import print_function, division import numpy as np import pandas as pd import datetime NAN = object() def add_dal_fields(in_path, out_path): ra = np.load(in_path)['x'] names = ra.dtype.names columns = {nm : ra[nm] for nm in names} df = pd.DataFrame(columns) dates = [] dates = [...
python
from django import forms from django.forms import formset_factory class UserRegistrationForm(forms.Form): username = forms.CharField( required = True, label = 'Username', max_length = 32 ) email = forms.CharField( required = True, label = 'Email', max_length ...
python
""" Static Data extractor extract_human_gene_orthologues: extract_phenotyping_centres: extract_ontology_terms: """ import os from typing import List from pyspark.sql import DataFrame, SparkSession from pyspark.sql.types import StructType, StructField, StringType, ArrayType from owlready2 import get_ontology...
python
# Generated by Django 3.2.7 on 2021-10-28 15:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("kite_runner", "0003_article_tag"), ] operations = [ migrations.AddField( model_name="profile", name="favourites", ...
python
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def maxAncestorDiff(self, root: TreeNode) -> int: ans = [0] def dfs(node, a, b): if node: a, ...
python
import tensorflow.compat.v1 as tf tf.disable_v2_behavior() import libs.model_common # X:(M,T,N,N)=>(M*N,T,N), Y:(M,N,N)=>(M*N,N) def placeholder(T, F_in, F_out): samples = tf.compat.v1.placeholder(shape = (None,T, F_in), dtype = tf.float32,name="samples") labels = tf.compat.v1.placeholder(shape = (None, F_out...
python
import os import sys import glob import math import collections import itertools import torch from abc import ABC, abstractproperty from deepsplines.datasets import init_dataset from deepsplines.dataloader import DataLoader from deepsplines.ds_utils import size_str from deepsplines.ds_utils import dict_recursive_merge...
python
""" Let's get the relationships yo """ import numpy as np import torch import torch.nn as nn import torch.nn.parallel from torch.autograd import Variable from torch.nn import functional as F from torch.nn.utils.rnn import PackedSequence from lib.resnet import resnet_l4 from config import BATCHNORM_MOMENTUM, IM_SCALE f...
python
import codecs import re import string from markdown import markdown from django.utils.safestring import mark_safe bracket_extract = re.compile(r"<.*?>(.*?)<\/.*?>") class MarkDownView(object): """ allows for a basic view where a markdown files is read in and rendered Give the class a markdown_loc v...
python
# # PySNMP MIB module ONEACCESS-ACL-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ONEACCESS-ACL-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:24:52 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
python
from __future__ import absolute_import import logging from flask import Blueprint, request, g, abort from huskar_api import settings from huskar_api.extras.concurrent_limiter import ( check_new_request, release_request, ConcurrencyExceededError) from huskar_api.switch import switch, SWITCH_ENABLE_CONCURRENT_LIMI...
python
import bmtrain as bmt def main(): bmt.init_distributed() bmt.print_rank("======= All Gather =======") bmt.benchmark.all_gather() bmt.print_rank("===== Reduce Scatter =====") bmt.benchmark.reduce_scatter() if __name__ == '__main__': main()
python
from django.db import models # Create your models here. # a cleaned up version of the old comments model, django-ready. class Comment(models.Model): CID = models.IntegerField(primary_key=True,unique=True,editable=False,) requestTime = models.DateTimeField() name = models.CharField(max_length=120,null=True...
python
"""Example demonstrating a basic usage of choke package.""" from time import sleep from redis import StrictRedis from choke import RedisChokeManager, CallLimitExceededError REDIS = StrictRedis() # Tweak this to reflect your setup CHOKE_MANAGER = RedisChokeManager(redis=REDIS) # Example configuration: enforce limit o...
python
# -*- coding: utf-8 -*- # from __future__ import absolute_import, unicode_literals import uuid import pytest import mock import avalon.cache import avalon.models def test_get_frozen_mapping(): mapping = {'foo': set(['zing', 'zam', 'zowey'])} frozen = avalon.cache.get_frozen_mapping(mapping) assert 'foo...
python
from pythonforandroid.recipe import Recipe from pythonforandroid.logger import shprint from pythonforandroid.util import current_directory from os.path import join import sh class SnappyRecipe(Recipe): version = '1.1.7' url = 'https://github.com/google/snappy/archive/{version}.tar.gz' built_libraries = {'...
python
import os os.system("cls") def both(): folder = input("Enter path to directory: ") os.system("cls") print(f"WARNING, this will rename every file in the directory: {folder}!") name = input(f"Enter new name for files: ") os.system("cls") print("WARNING, this could cause problems if file extention...
python
import sys import unittest from unittest import mock from unittest.mock import MagicMock, Mock sys.modules['w1thermsensor'] = MagicMock() from sensors.ground_temperature_sensor import GroundTemperatureSensor class TestGroundTemperatureSensor(unittest.TestCase): @mock.patch('sensors.ground_temperature_sensor.Sens...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/11/23 下午3:09 from api.channel import channel from util.data_util import data_pool from util.faker_util import fakerist # 创建报名活动并开启 def add_channel_random(): kwargs = data_pool.supply('channel.yml', 'add_channel')[0] fake = "Asctrio" + fakerist.m...
python
import hashlib from Crypto.Cipher import AES class Crypto: SALT = "@uhooinc.com" def __init__(self, clientCode): self.key = hashlib.md5( clientCode.encode("utf-8") ).digest() # initialization key self.length = AES.block_size # Initialize the block size self.aes =...
python
#!/usr/bin/env python3 import shlex import shutil import pwncat from pwncat.modules import Bool, List, Status, Argument, BaseModule, ModuleFailed from pwncat.platform.windows import Windows, PowershellError class Module(BaseModule): """ Load the Invoke-BloodHound cmdlet and execute it. Automatically download...
python
import Cptool.config from Cptool.gaMavlink import GaMavlink if __name__ == '__main__': GaMavlink.extract_from_log_path(f"./log/{Cptool.config.MODE}")
python
from __future__ import print_function import os, sys import numpy as np np.random.seed(1234) # for reproducibility? import warnings with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) import lasagne os.environ["THEANO_FLAGS"] = "cuda.root=/usr/local/cuda,device=gpu,fl...
python
# -* encoding: utf-8 *- import logging from collections import OrderedDict from typing import Tuple, Dict, Optional from django.contrib.auth import hashers from django.core.exceptions import ValidationError from django.http import HttpRequest from django.utils.translation import ugettext_lazy as _ from typing import U...
python
import torch import numpy as np import random import torch.utils.data as data import sys sys.path.append("../../../") """ Dataset class for creating the shuffling dataset. """ class SetShufflingDataset(data.Dataset): def __init__(self, set_size, train=True, val=False, test=False, **kwargs): self.set_size = s...
python
from flask_restful import Resource, reqparse from models import hotel from models.hotel import HotelModel hoteis = [ { 'hotel_id': 'alpha', 'nome': 'Alpha Hotel', 'estrelas': 4.3, 'diaria': 420.34, 'cidade': 'Rio de Janeiro' }, { 'hotel_id': 'bravo', ...
python
#!/usr/bin/env python3 # coding=utf-8 """ Benchmark helper for triggers. Each benchmark is linked to a trigger class from lib.trigger """ from abc import abstractmethod, ABCMeta from contextlib import suppress import logging import multiprocessing import os import subprocess import timeit import time from lib.helper...
python
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
python
def convert(pth_path, wts_path, device_type='cuda'): import struct import torch from viclassifier.utils import dev_opt device = dev_opt.usingDevice(device_type) model = torch.load(pth_path, map_location=device) model.to(device) # 测试时不启用 BatchNormalization 和 Dropout model.eval() # p...
python
import sys,time,os,random,fonction,string from pystyle import * listbye = [""" ___ _ _ | _ )_ _ ___ ______ ___ _ _ ___ _ _ | |__ _| |_ ___ _ _ | _ \ || / -_)_ (_-< -_) -_) | || / _ \ || | | / _` | _/ -_) '_| |___/\_, \___( ) /__|___\___|...
python
from setuptools import setup setup( name='alpha_vantage_proxy', version='0.0.4', description='A plugin to interface with alphavantage api', url='https://github.com/kburd/alpha-vantage-proxy', author='Kaleb Burd', author_email='kalebmburd@gmail.com', license='MIT', packages=['alpha_vant...
python
import torch import numpy as np from torch import nn from torch import optim from torch.nn import functional as F from cl_gym.algorithms import ContinualAlgorithm from cl_gym.algorithms.utils import flatten_grads, assign_grads from cl_gym.algorithms.utils import flatten_weights, assign_weights class MCSGD(ContinualAl...
python
import json import requests from kivy.core.audio import SoundLoader from secret import WATSON_USERNAME from secret import WATSON_PASSWORD class watson_voice(): def __init__(self, voice_record): self.name = voice_record['name'] self.language = voice_record['language'] self.gender = voice_...
python
import math import torch import copy import torch.nn as nn import torch.nn.functional as F from transformers import BertTokenizer, BertModel def linear_block(input_dim, hidden_dim): linear = nn.Sequential( nn.Linear(input_dim, hidden_dim), nn.LeakyReLU(0.5)) return linear class MLP(...
python
# Imitando o comportamento de números numa classe class Coordenada(): def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return "<Coordenada x:{0},y:{1}>".format(self.x, self.y) # TODO: Implemente adição def __add__(self, other): pass # TODO: Imp...
python
# -*- coding: utf-8 -*- """ Copyright (c) 2019-2021 Tomasz Łuczak, TeaM-TL 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 limitation the rights to use, cop...
python
import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset from torch.utils.data import DataLoader import numpy as np import os import h5py import subprocess import shlex import json import glob from .. ops import transform_functions, se3 from sklearn.neighbors import Neare...
python
import os from unittest import TestCase from healthtools.scrapers.base_scraper import Scraper from healthtools.scrapers.doctors import DoctorsScraper from healthtools.scrapers.foreign_doctors import ForeignDoctorsScraper from healthtools.scrapers.health_facilities import HealthFacilitiesScraper from healthtools.scrap...
python
""" .. _model-rgcn: Relational graph convolutional network ================================================ **Author:** Lingfan Yu, Mufei Li, Zheng Zhang In this tutorial, you learn how to implement a relational graph convolutional network (R-GCN). This type of network is one effort to generalize GCN to h...
python
""" The type of race condition that this class is designed to prevent is somewhat difficult to write unit tests for. My apologies for the abysmal coverage. T """ from google.appengine.ext import db from catnado.testing.testcase import SimpleAppEngineTestCase from catnado.unique_property_record import ( UniqueProp...
python
from PIL import Image def parse_photo(file_path): """Open image(s), remove Alpha Channel if image has it and store image(s).""" images = [] for file_name in file_path: try: # Open file img = Image.open(file_name) # If image has Alpha Channel, remove it ...
python
# # Copyright (c) 2019 Juniper Networks, Inc. All rights reserved. # """ Telemetry feature implementation. This file contains implementation of abstract config generation for telemetry feature """ from collections import OrderedDict from abstract_device_api.abstract_device_xsd import ( CollectorParams, EnabledI...
python
""" This evaluation script modifies code for the official Quoref evaluator (``allennlp/tools/quoref_eval.py``) to deal with evaluating on contrast sets. """ import json from typing import Dict, Tuple, List, Any, Set import argparse from collections import defaultdict import numpy as np from allennlp.tools import drop_...
python
try: from django.conf.urls import * except ImportError: # django < 1.4 from django.conf.urls.defaults import * # place app url patterns here
python
import os from flask import Flask, request, jsonify, make_response from flask_cors import CORS from joinnector import SDK # through the custom helperclient from src.client.nector_client import NectorClient client_sdk = NectorClient(os.environ.get("API_KEY"), os.environ.get( "API_SECRET"), os.environ.get("API_MODE"...
python
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np class Net(nn.Module): def __init__(self, num_class=1024): super(Net, self).__init__() num_output_hidden = int(np.log2(num_class - 1)) + 1 self.fc1 = nn.Linear(nu...
python
import numpy as np from scipy.interpolate import UnivariateSpline import seaborn as sns import matplotlib.pyplot as plt import matplotlib.mlab as mlab import scipy.stats as st import TransitionMatrix as TM from TransitionMatrix import SetTransitionMatrix_NULL def configuration(m,spaces): if m == 1: if sp...
python
Import jogovelha import sys erroInicializar = False jogo = jogovelha.inicializar() if len(jogo) != 3: erroInicializar = True else: for linha in jogo: if len(linha) != 3: erroInicializar = True else: for elemento in linha: if elemento != '.': erroInicializar = if erroInicializar: sys.exit(1) else: sys.exit(0)
python
#!/usr/bin/python from re import findall from collections import defaultdict from itertools import combinations def sortSides(triangles): for i in range(len(triangles)): triangles[i] = sorted(triangles[i]) def part1(numbers): sortSides(numbers) isTriangle = 0 for t in numbers: if t[0]...
python
from aoc20191215a import discover_map, move, draw def aoc(data): seen = discover_map(data) step = 0 while 1 in seen.values(): prev = seen.copy() for (x, y), value in prev.items(): if value == 2: for xx, yy, _ in move(x, y): if prev[(xx, yy)] ...
python
from tkinter import * from tkinter import messagebox from dao.book_repository_json import BookRepositoryJson from model.book import Book from presentation.add_edit_book_dialog import AddEditBookDialog from presentation.app_main_window import AppMainWindow from presentation.show_items_view import ShowItemsView from uti...
python
from utils.qSLP import qSLP from qiskit.utils import QuantumInstance from qiskit import Aer, QuantumCircuit from utils.data_visualization import * from utils.Utils_pad import padding from utils.import_data import get_dataset from qiskit.circuit.library import ZZFeatureMap, ZFeatureMap from qiskit.circuit.library import...
python
# OP_RETURN.py # # Python script to generate and retrieve OP_RETURN bitcore transactions # # Copyright (c) Coin Sciences Ltd # # 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 restrict...
python