content
stringlengths
5
1.05M
import boc a=boc.BOCModel(doc_path="../sample/sample_data/sample_articles.txt") mtx,w2c,idx=a.fit(save_path="./") print(mtx.shape) print(w2c[203]) print(idx[20])
import numpy as np import torch import torchvision import torch.nn.functional as F from torch.utils.data import DataLoader from torchvision import transforms, models, datasets import matplotlib.pyplot as plt %matplotlib inline # Implementation of the ResNet-50 Architecture class ResidualBlock(torch.nn.Modu...
''' Faça um Programa que leia um vetor de 10 caracteres, e diga quantas foram lidas. Imprima as correspondentes. ''' vetor = [] consoantes = 0 vogal = 'aeiou' for x in range(1, 11): letra = input(f'Digite o {x}º caractere: ').lower() if letra not in 'aeiou': consoantes += 1 vetor.append(le...
import functools # Variable name from nurse name, work date, and shift type name # work_date can be either datetime.date or str # shift_type_str is str def GetVariableName(name, work_date, shift_type_str): return 'x_%s_%s_%s' % (name, str(work_date), shift_type_str) # Sum of solver "variables". Works for both ...
"Configuration." import json import os import os.path import flask from datagraphics import constants from datagraphics import utils # Default configurable values; modified by reading a JSON file in 'init'. DEFAULT_SETTINGS = dict( SERVER_NAME = "127.0.0.1:5005", # For URL generation; app.run() in devel. ...
input = """ a1:- not b1. b1:- not a1. a2:- not b2. b2:- not a2. a3:- not b3. b3:- not a3. """ output = """ {a1, a2, a3} {a1, a2, b3} {a1, a3, b2} {a1, b2, b3} {a2, a3, b1} {a2, b1, b3} {a3, b1, b2} {b1, b2, b3} """
import unittest from app.models import News class NewsTest(unittest.TestCase): ''' Test Class to test the behaviour of the News class ''' def setUp(self): ''' Set up method that will run before every Test ''' self.new_news = News('kenya','newsimage','interesting',2020,'...
from datetime import datetime def unix_time(dt): epoch = datetime.utcfromtimestamp(0) delta = dt - epoch return int(round(delta.total_seconds())) def format_time(unix_time): if isinstance(unix_time, str): unix_time = int(unix_time) return datetime.fromtimestamp(unix_time).strftime('%Y-%m-%...
# -*- coding: utf-8 -*- #import cv2 from xml.dom import minidom import subprocess from distutils import spawn import json def anonymize(path, dictionary): if not spawn.find_executable("qpdf"): raise EnvironmentError("qpdf not installed.") dictionary = json.loads(dictionary); #qpdf --s...
import os import csv election_csv = os.path.join('..', 'Resources', 'election_data.csv') total_vote = 0 khan_vote = 0 correy_vote = 0 li_vote = 0 otooley_vote = 0 with open(election_csv, newline="", encoding='utf-8') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') header = next(csvreader) for...
import json import sys import os from tqdm import tqdm from mdf_refinery.validator import Validator from mdf_refinery.parsers.tab_parser import parse_tab # VERSION 0.3.0 # This is the converter for NIST SRD 161 # Arguments: # input_path (string): The file or directory where the data resides. # NOTE: Do not ...
import os, sys, json, re, uuid, time import logging, argparse import requests logging.basicConfig( filename='publish_to_marketplace.log', format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S' ) headers = {'content-type': 'application/json'...
from __future__ import annotations from dataclasses import dataclass, field from typing import Any, Dict, MutableMapping, Union, cast from pyckaxe.lib.nbt import NbtCompound, NbtString from pyckaxe.lib.types import JsonValue from pyckaxe.utils.utils import is_submapping __all__ = ( "BlockStateValue", "Invali...
"""Import the cleaning tasks.""" from typing import List from .gamelog import AddWinPercentage, GamesInLastXDays from .io import ( GenericLoader, FactoryGetter, PlayByPlayLoader, WinProbabilityLoader, GameLogLoader, LineupLoader, RotationLoader, ShotChartLoader, BoxScoreLoader, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Restore unmodified test data to test data location for repeated testing.""" from picasa-cleanup-functions import restore restore() if __name__ == "__main__": print("Executing directly")
# This script contains the validation of the formula given import numpy as np from scipy.io import mmread # Importing matrix coo_matrix = mmread('s12.mtx') # Conver coo to dense np array matrix = coo_matrix.todense() # c3 formula nodes = np.matmul(np.multiply(matrix,np.matmul(matrix,matrix)),np.ones(np.shape(matrix)[1...
#Challenge 4: Take a binary tree and reverse it #I decided to create two classes. One to hold the node, and one to act as the Binary Tree. #Node class #Only contains the information for the node. Val is the value of the node, left is the left most value, and right is the right value class Node: def __init__(self, ...
""" Introduction to most commonly used widgets from PySide2 1. QComboBox 2. QRadioButton 3. QSpinBox 4. QTextEdit """ from PySide2 import QtWidgets from PySide2 import QtCore from shiboken2 import wrapInstance from maya import _OpenMayaUI as omui def maya_main_window(): """ :returns Maya m...
"""Utility functions for Transforms.""" import string import weakref from torch import Tensor, einsum from cockpit.quantities.hooks.base import ParameterExtensionHook def BatchGradTransformsHook_BatchL2Grad(): """Compute individual gradient ℓ₂ norms via individual gradients.""" return BatchGradTransformsHo...
import fileinput def solve(s, d): if (s + d) % 2 != 0: return False a = (s + d) // 2 b = s - a if a >= 0 and b >= 0: r = reversed(sorted((a, b))) # print(*r) return r else: return False assert tuple(solve(40, 20)) == (30,10) assert solve(20, 40) == False...
import collections LogEntry = collections.namedtuple( 'LogEntry', ['level', 'target', 'group', 'message', 'request']) _LEVEL_I18N = { u'warn': u'Warning', u'vuln': u'Vulnerability', u'info': u'Info', } LEVELS = (u'info', u'warn', u'vuln') def entry_str(entry): if entry.request is None: r...
import json from collections import namedtuple import aiohttp METHOD_GET = aiohttp.hdrs.METH_GET METHOD_DELETE = aiohttp.hdrs.METH_DELETE METHOD_POST = aiohttp.hdrs.METH_POST METHOD_PUT = aiohttp.hdrs.METH_PUT METHOD_PATCH = aiohttp.hdrs.METH_PATCH CONTENT_TYPE = aiohttp.hdrs.CONTENT_TYPE JSON_TYPE = 'application/jso...
from user.models import User # WARNING - This will modify user settings in the database # Use with caution and test on your local database first! for user in User.objects.all(): print('Updating settings for user {}'.format(user.id)) user.settings.emails['issuer']['BountyCompleted'] = True # user.settings....
import pymysql import configparser class mysql_operate: def __init__(self): conf = configparser.ConfigParser() conf.read("setting.conf") self.host = conf.get("section", "host") self.user = conf.get("section", "user") self.passwd = conf.get("section", "passwd")...
# -*- coding: utf-8 -*- """ Setup file for pydeequ. Use setup.cfg to configure your project. This file was generated with PyScaffold 3.2.3. PyScaffold helps you to put up the scaffold of your new Python project. Learn more under: https://pyscaffold.org/ """ import sys import os from pkg_resources ...
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score from sklearn.neural_network import MLPClassifier from sklearn.tree import DecisionTreeClassifier # --------------------------------------Data Preprocessing---------------------------------...
# Value of a character in the VIN. # A character not in the map is an invalid character. VIN_VALUE = { "0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "H": 8, "J": 1, "K": 2, "L": 3, "M": 4, "N": 5, "P": 7, "R":...
# -*- coding: utf-8 -*- import flask import os import sys import ast import json import argparse app = flask.Flask(__name__) filename = '' @app.route('/metrics') def get_metrics(): """ Retrieves the last saved avg latency and throughput Args: - Returns: dict: A JSON object ...
# -*- coding: utf-8 -*- import codecs import sys def sort_items(input_filename, output_filename): input_file = codecs.open(input_filename, "r", encoding="utf-8") dic = {} for line in input_file: if len(line) == 0 or line == '\n': continue try: key, value = line.sp...
import os from conans import ConanFile, CMake, tools from conans.errors import ConanInvalidConfiguration class ClhepConan(ConanFile): name = "clhep" description = "Class Library for High Energy Physics." license = "LGPL-3.0-only" topics = ("conan", "clhep", "cern", "hep", "high energy", "physics", "ge...
# Lint as: python2, python3 # Copyright 2020 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 # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law ...
""" This module contains a set of acquisition functions that determine the value of a given query, which is useful for acitive query optimization. """ from typing import List, Dict import numpy as np from aprel.basics import Trajectory from aprel.learning import Belief, SamplingBasedBelief from aprel.learning import Q...
import kafka from kafka import KafkaProducer import json import logging log = logging.getLogger(__name__) class KafkaHandler(object): def __init__(self, address, topic): log.info("Connecting to kafka at %s.." % address) try: self._kafka = KafkaProducer(bootstrap_servers=address) ...
import argparse import numpy as np import fasttext parser = argparse.ArgumentParser() parser.add_argument( "-train", "--train_document", type=str, required=True, help="path to train document" ) parser.add_argument( "-test", "--test_document", type=str, required=True, help="path to test document" ) parser.add_a...
from .json_tools import JSONMixin class View(JSONMixin): """ Represents a "hard configuration" of a camera location Parameters --------- type : str, default "MapView" deck.gl view to display, e.g., MapView controller : bool, default True If enabled, camera becomes interactive. ...
import matplotlib.pyplot as plt import os fn = os.path.join(os.path.dirname(__file__), 'data.csv') f = open(fn, "r") data = f.read() data = data.split('\n') del data[-1] data = map(lambda x: x.split(','), data) data = map(lambda x: map(lambda y: int(y), x), data) g = data plt.plot(1) plt.imshow(g, cmap='...
# Copyright (c) 2016-2019, TDK Electronics # All rights reserved. # # Author: Marek Cieplucha, https://github.com/mciepluc # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met # (The BSD 2-Clause License): # # 1. Redistributi...
class Solution(object): def XXX(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ temp = {} for i in range(len(nums)): num = nums[i] diff = target - num t...
from datetime import datetime, timedelta from itertools import chain from operator import attrgetter from pathlib import Path import click import pytz from git import Repo from tqdm import tqdm @click.command() @click.option( '--path', '-p', type=click.Path(dir_okay=True, file_okay=False), required=True,...
#Artificial Intelligence Homework Assignment 1 #Program by Alex Wilkening #This program finds the best solution to a "gem switcher" problem. #To-Do list: find a way to make sure that the nodes actually go to the right parent def main(StartingNodes): CurrentLayer = [] #A list of all nodes in our current l...
# -*- coding: future_fstrings -*- # # Copyright 2019 Peifeng Yu <peifeng@umich.edu> # # This file is part of Salus # (see https://github.com/SymbioticLab/Salus). # # 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 co...
# TrueType font file parser # Lingdong Huang 2018 # based on js from: http://stevehanov.ca/blog/index.php?id=143 import numpy as np import struct class BinaryReader(): def __init__(this,arrayBuffer): this.pos = 0 this.data = [struct.unpack('B', x)[0] for x in arrayBuffer] def seek(this, pos)...
# This file is part of beets. # Copyright 2014, Adrian Sampson. # # 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, copy, ...
#!/bin/env python import json , sys input_range = [] output_files_list = [] lumi_ranges = sys.argv[1].split(':') for lumi_range in lumi_ranges: input_range.append(tuple(lumi_range.split(','))) jdata = sys.stdin.read() try: lumi_data = json.loads(jdata) except: print jdata exit (1) lumi_data = lumi_data['data...
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import argparse import logging import sys from dataclasses import asdict from pprint import pformat from typing i...
"""Tests for the fixes of CanESM5.""" import iris import numpy as np import pytest from esmvalcore.cmor._fixes.cmip6.canesm5 import Co2, Gpp from esmvalcore.cmor.fix import Fix def test_get_co2_fix(): """Test getting of fix.""" fix = Fix.get_fixes('CMIP6', 'CanESM5', 'Amon', 'co2') assert fix == [Co2(Non...
import requests url = "https://discord.com/api/webhooks/848514072194580511/_7RDKRz4PeX3oPPaRuPsA8P-3287J6uFoUAiXYtA0yygVPOdkLV3HphfLargI1dJ9eJi" def notify(message): data = { "content": "Tweet Posted: "+message, } headers = { "Content-Type": "application/json" } result = reques...
def love6(a, b): if a == 6 or b == 6 or (a-b) == 6 or (b-a) == 6 or (a+b) == 6: return True else: return False result = love6(6, 4) print(result) result = love6(4, 5) print(result) result = love6(1, 5) print(result)
# -*- coding: utf-8 -*- import json import datetime import cPickle as pickle import jsonpickle from infcommon.serializer.exceptions import DeserializeError class JsonSerializer(object): def loads(self, serialized_object, **kwargs): return json.loads(serialized_object, **kwargs) def dumps(self, obj...
from pathlib import Path from PIL import Image import matplotlib.pyplot as plt import numpy as np from wordcloud import WordCloud, ImageColorGenerator, STOPWORDS # 读取文本内容 current_directory = Path.cwd() text = Path.open(current_directory/"4.txt", encoding='utf-8').read() ### 参数配置 ### # 增加词云轮廓模板 cinderella_mask = np.ar...
from tqdm import tqdm from hashlib import md5 from pathlib import Path from src.utils.params import ( Tokens, TokenBasedSpan, CharBasedSpan, Label, ) from typing import Dict, List, Tuple from flashtext import KeywordProcessor from logging import getLogger from .abstract_model import NERModel, NERModelCo...
import numpy as np import math import os import pickle def pick_fz_bpl(bp_norms_go1, bp_symm_grp, symm_grp_ax, x_tol=1e-04): """ Returns an array of unit boundary plane normals lying in the fundamental zone of bicrystal symmetry for an input array containing unit boundary plane normals in po1 reference fr...
N = int(input()) for i in range(N, 0, -1) : star = "" for j in range(0, N-i) : star += " " for k in range(0, 2*i-1) : star += "*" print(star) for i in range(2, N+1) : star = "" for j in range(0, N-i) : star += " " for k in range(0, 2*i-1) : star += "*" p...
# Copyright 2016-2021 The Van Valen Lab at the California Institute of # Technology (Caltech), with support from the Paul Allen Family Foundation, # Google, & National Institutes of Health (NIH) under Grant U24CA224309-01. # All rights reserved. # # Licensed under a modified Apache License, Version 2.0 (the "License");...
import inspect import functools import os import warnings warnings.filterwarnings('ignore', message='numpy.dtype size changed') warnings.filterwarnings('ignore', message='regionprops and image moments') warnings.filterwarnings('ignore', message='non-tuple sequence for multi') warnings.filterwarnings('ignore', message=...
import sys import regex as re from sklearn.cluster import MiniBatchKMeans import numpy as np import cv2 from scipy.ndimage import imread from scipy.misc import imsave import scipy import numpy_indexed as npi def color_region_label(ai, k, log_dir=None, output_file=None, nolonely_file=None): """ Create label image a...
import requests from bs4 import BeautifulSoup import pandas as pd def main(): searchterm = 'zion+williamson++rookie+card' url = f"https://www.ebay.com/sch/i.html?_from=R40&_nkw={searchterm}&_sacat=0&rt=nc&LH_Sold=1&LH_Complete=1" soup = get_data(url) products = parse(soup) export(products, searchte...
class MyShellException(Exception): """ raised when we cannot find a particular key or duplication occurs """ def __init__(self, message, errors=None): # Call the base class constructor with the parameters it needs super().__init__(message) # Now for your custom code... ...
import datetime import json import requests from waste_collection_schedule import Collection # type: ignore[attr-defined] TITLE = "Jumomind" DESCRIPTION = "Source for Jumomind.de waste collection." URL = "https://www.jumomind.de" TEST_CASES = { "ZAW": {"service_id": "zaw", "city_id": 106, "area_id": 94}, "Ba...
import pygame as game import constants import math import random import os class food: def __init__(s, pos): s.pos = pos #s.image = game.image.load(os.getcwd() + '/images/food.png') s.image_rect = [4, 4] s.eaten = 0 s.hitbox = [s.pos[0] + s.image_rect[0] * 0.2, s.pos[1] + s....
#!/usr/bin/env python import pytest """ Test 1985. Find the Kth Largest Integer in the Array """ @pytest.fixture(scope="session") def init_variables_1985(): from src.leetcode_1985_find_the_kth_largest_integer_in_the_array import Solution solution = Solution() def _init_variables_1985(): return...
"""Constants""" import sys FROZEN = getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS') TFLITE_MODEL = "model.tflite" SPINNER = "images/spinner.gif" SMALLSPINNER = "images/small spinner.gif" LOGO_FICH = "images/logo_fich.png" LOGO_SINC = "images/logo_sinc.png" LOGO_UNER = "images/logo_uner.png" LOGO_AGRO = "im...
import logging import subprocess import sys import stardog.cluster.utils as utils def upload_file(ip, upload_file): scp_opts = "-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" cmd = "scp -r %s %s %s:%s" % (scp_opts, upload_file, ip, upload_file) return utils.command(cmd) def refresh_stardo...
##################################### # Temp.py ##################################### # Description: # * Ad-hoc testing ground. from Database.tsql import TSQLInterface from ETL.DataReader import DataReader from ETL.DataComparer import DataComparer from ETL.LocalLargeDataJobPoster import LocalLargeDataJobPoster from Lo...
#Model Evalution import pandas as pd import numpy as np from keras.models import load_model import seaborn as sns import matplotlib.pyplot as plt model = load_model(r'Fashion_Model.hdf5',compile = False) fashion_test_df = pd.read_csv('fashion-mnist_test.csv', sep = ',') testing = np.array(fashion_test_df, dty...
class StreamToLogger: """ Class used to redirect all python errors into the logger. """ def __init__(self, logger, level): self.logger = logger self.level = level self.buffer = [] def write(self, msg): msg = msg.strip() if msg: self.buffer.append...
import unittest from src.homework.h_strings.strings import get_hamming_distance from src.homework.h_strings.strings import get_dna_complement class Test_Config(unittest.TestCase): def test_get_hamming_distance(self): self.assertEqual(7, get_hamming_distance('GAGCCTACTAACGGGAT', 'CATCGTAATGACGGCCT')) ...
import math ################ ROZDIZAł 1 ################ # konwersacja liczby dziesiętnej w binarną # def dec_to_bin (num): # if num > 0: # dec_to_bin(num//2) # print(num%2,end="") # num = int(input()) # dec_to_bin(num) # print() # konwersacja dowolnego systemu liczbowego # OLD # def calc_any_num_...
from sqlite3 import (Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError, IntegrityError, InternalError, ProgrammingError, NotSupportedError)
# Common stuff for social APIs class RateLimitExceeded(Exception): # Constructor accepts anything # Needed to have nice stack traces # (they are displayed with arguments replaced # by their values) def __init__(self, *args, **kwargs): pass
import sys import json import numpy as np from flask import Flask, request, jsonify, make_response # from flask import session from flask import render_template, send_from_directory from flask_cors import CORS import lib.recommender_tools as rec_tools from lib.recommender_data import RECCOMEND_DATA from lib.tools im...
#!/usr/bin/python import os from threading import Thread import chamber import logger import son_of_fermentation MQTT_BROKER_HOST = 'broker.myownbrewery.com' MQTT_BROKER_PORT = 8883 MQTT_BROKER_USERNAME = os.environ.get('MQTT_BROKER_USERNAME', '') MQTT_BROKER_PASSWORD = os.environ.get('MQTT_BROKER_PASSWORD', '') d...
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmseg.models.decode_heads import ANNHead from .utils import to_cuda def test_ann_head(): inputs = [torch.randn(1, 16, 45, 45), torch.randn(1, 32, 21, 21)] head = ANNHead( in_channels=[16, 32], channels=16, num_classes=...
import numpy as np import pandas as pd from numpy import ndarray from pandas import DataFrame from scipy.cluster.hierarchy import linkage from scipy.sparse import csr_matrix from scipy.spatial.distance import squareform def ComputeCooccurrence(k: int) -> DataFrame: data = pd.read_csv('QueriedData.csv', dtype='categor...
import datetime import os import random import re import uuid from decimal import Decimal from io import BytesIO from typing import Dict, Tuple, List from ckeditor.fields import RichTextField from django.conf import settings from django.contrib.auth.models import User from django.core.files import File from django.cor...
# coding: utf-8 # # Creating a feature matrix from a networkx graph # # In this notebook we will look at a few ways to quickly create a feature matrix from a networkx graph. # In[1]: import networkx as nx import pandas as pd G = nx.read_gpickle('major_us_cities') # ## Node based features # In[2]: G.nodes(data...
import sys import logging def duplicate_counter(text): char_dict = {} # Dictionary where we store the characters and their occurrence amount for i in text: if text.count(i) > 1 and i not in char_dict: # If i occurs more than once and hasn't already been done char_dict.update({i:text.coun...
#!/usr/bin/env python3 import numpy as np import cv2 import imutils import numpy import imutils.contours import math tapeAngleDegrees=14.5 tapeAngle = tapeAngleDegrees / 180.0 * math.pi # angle of each piece of tape from verticle tapeGapInches = 8.0 # space between closest point of two pieces of tape tapeWidth...
from django.urls import path from . import views urlpatterns = [ path('', views.datacenter_list, name='datacenters'), path('<int:datacenter_id>/', views.datacenter_view, name='datacenter'), path('<int:datacenter_id>/update/', views.datacenter_update, name='update_datacenter'), path('create/', views.dat...
import os, time from inkplate6_PLUS import Inkplate display = Inkplate(Inkplate.INKPLATE_2BIT) display.begin() # This prints all the files on card print(os.listdir("/sd")) f = open("sd/text.txt", "r") # Print file contents print(f.read()) f.close() time.sleep(5) # Utterly slow, can take minutes :( display.drawIma...
#!/usr/bin/python # -*- coding: utf-8 -*- """Unit tests for botlist.py""" # This test script is intended to be used with mature unittest code. # # This script contains important unittests in order to ensure the function # and stability of core code (for e.g. DrTrigonBot framework) and methods. # You should not chang...
from pyramid_sms.utils import normalize_us_phone_number from pyramid_sms.utils import normalize_international_phone_number def test_normalize_us_phone_number(): assert normalize_us_phone_number("555 123 1234") == "+15551231234" assert normalize_us_phone_number("+1 555 123 1234") == "+15551231234" assert n...
from math import sqrt, exp, pi import pytest from pytest import approx import numpy as np from util.full import Matrix, init, unit, permute, triangular class TestMatrix: def test_diag(self): ref = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] this = Matrix.diag([1, 1, 1]) np.testing.assert_equal(th...
#!/usr/bin/python ''' get a new ami given a running instance ''' import datetime import logging import sys import time import bellatrix from bellatrix.lib.ec2_lib import Ec2lib from bellatrix.lib import bellatrix_util from bellatrix.lib import util class Run(): def __init__(self, key, sec, app_name): s...
import os import yaml import json import argparse import numpy as np from pathlib import Path from datetime import datetime, timedelta from glob import glob import tensorflow as tf from tensorflow.core.framework import summary_pb2 from age_gender.utils.dataloader import init_data_loader from age_gender.utils.config_pa...
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2017-01-14 20:30 from __future__ import unicode_literals from django.db import migrations, models import taggit.managers class Migration(migrations.Migration): dependencies = [ ('adventure', '0027_auto_20170114_1143'), ] operations = [ ...
""" FFG-benchmarks Copyright (c) 2021-present NAVER Corp. MIT license """ from PIL import Image from torch.utils.data import Dataset from .ttf_utils import render from .data_utils import load_ttf_data, load_img_data, sample class BaseDataset(Dataset): def __init__(self, data_dirs, chars, transform=None, extensio...
import numpy as np def _testT3formula(D, tri, key='OI_VIS'): tmp = {} s, t, w0, w1, w2 = D['OI_T3'][tri]['formula'] keys = [k for k in ['OI_VIS', 'OI_VIS2'] if k in D] for key in keys: tmp[key+' mjd0'] = D['OI_T3'][tri]['MJD']-D[key][t[0]]['MJD'][w0] tmp[key+' u0'] = D['OI_T3'][tri]['u1...
from .base import Corpus
from .ginfomax import InfoGraph from .ginfominmax import GInfoMinMax from .gsimclr import GSimCLR
import os import mxnet as mx import numpy as np from tqdm import tqdm from mxnet import autograd, Context from mxnet.gluon import Trainer from typing import List, Any from gluoncv.utils.metrics import SegmentationMetric from gluoncv.utils.parallel import DataParallelCriterion, DataParallelModel from domain.models.p...
#-*-coding:utf-8-*- import futuquant class GetAutypeList(): # 获取复权因子get_autype_list def test1(self): quote_ctx = futuquant.OpenQuoteContext(host='127.0.0.1',port=11111) code_list = ['HK.00700'] ret_code, ret_data = quote_ctx.get_autype_list(code_list) quote_ctx.close() ...
from sagas.nlu.mats import Cats, Mats default = Cats('default') Mats(cat=default) \ .sent(es="Ésta es mi hija.", en="This is my daughter.", zh="这是我的女儿。", ja="これは私の娘です。", v0="Kore wa watashi no musumedesu.", ) \ .sent(es="Él tiene muchos libros de historia.", ...
from scritti.posts.models import Post from django.contrib import admin class PostAdmin(admin.ModelAdmin): fieldsets = [ ('Post', {'fields': ['title', 'body']}), ('Meta', {'fields': ['slug', 'tags', 'author']}), ('Publication', {'fields': ['p...
"""""" import pytest from photoshop.api import Application, EventID, SolidColor class TestApplication: """Test the solidColor.""" # pylint: disable=attribute-defined-outside-init @pytest.fixture(autouse=True) def setup(self): self.app = Application() color = SolidColor() color...
# -*- coding: utf-8 -*- # Time: 2020-05-23 20:23 # Author: Landers1037 # Mail: liaorenj@gmail.com # File: user.py from app import db class User(db.Model): id = db.Column(db.Integer,autoincrement=True,primary_key=True) name = db.Column(db.String(50),nullable=False) password = db.Column(db.String...
import os, sys from matplotlib import pyplot as plt from skimage import feature, color, transform, io import cv2 import numpy as np # why cv2 is giving me fucking read error? # im = cv2.imread('a.png') im = io.imread('a.png') def add_point(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONUP: print...
# -*- coding: utf-8 -*- from .factories import Application as ApplicationFactory __all__ = ['ApplicationFactory']
import numpy as np from SimPEG import ( maps, optimization, inversion, inverse_problem, directives, data_misfit, regularization, ) def run_inversion( m0, simulation, data, actind, mesh, maxIter=15, beta0_ratio=1e0, coolingFactor=5, coolingRate=2, up...