text
stringlengths
3.07k
12.6k
__license__ = 'MIT License <http://www.opensource.org/licenses/mit-license.php>' __author__ = '<NAME> <<EMAIL>>' __docformat__ = 'epytext' from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.admin.views.decorators import staff_member_required from django.contr...
"""This module calculates solar system mechanics.""" from dataclasses import dataclass from datetime import datetime, timedelta from typing import List, Tuple from astronomical.model.celestials import Body from astronomical.model.custom_types import angle, real_time from astronomical.model.location import Location fr...
import dash import dash_core_components as dcc import dash_bootstrap_components as dbc from datetime import datetime as dt import dash_html_components as html from dash.dependencies import Output, Input, State from iexfinance.stocks import get_historical_data from dateutil.relativedelta import relativedelta import plot...
from aiohttp import web from examples.logsetup import setup_logging from flaat import AuthWorkflow from flaat.aio import Flaat from flaat.exceptions import FlaatException from flaat.requirements import CheckResult, get_claim_requirement, get_vo_requirement from flaat.user_infos import UserInfos # do some log setup so...
import os import glob import psycopg2 import pandas as pd from io import StringIO from sql_queries import * def get_files(filepath, filemask = '*.*', exclude = ''): ''' Returns the list of files under a given filepath, mask, and excluding specified system subfolders. Parameters: filepath (str): Pa...
#!/usr/local/bin/python # coding: utf-8 from future import standard_library standard_library.install_aliases() import os import re import sys import string import numpy as np from six.moves import urllib from nltk.corpus import stopwords from senpy import EmotionBox, models def ignore(dchars): deletechars = ""...
from math import log2 import itertools import numpy as np import quimb as qu from .tensor_core import rand_uuid, Tensor, TensorNetwork from .tensor_1d import TensorNetwork1D, TensorNetwork1DVector def is_power_of_2(x): return ((x & (x - 1)) == 0) and x > 0 class MERA(TensorNetwork1DVector, TensorNe...
""" Resize specific utilities Future modifications to make: - Add animated gif support through gifsicle - Do test with wand.Image.transform if more correct (current implementation is very brute). - Add test with exif data """ import os import math import tempfile from contextlib import contextmana...
# Copyright 2015 ETH Zurich # # 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, sof...
import base64 import json import os from io import BytesIO from urllib.parse import urlparse import matplotlib import pandas as pd import py4j.java_gateway as status_gateway import pyarrow as pa import pyarrow.parquet as pq import brightics.common.data.table_data_reader as table_reader import brightics.c...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np import argparse import os import inspect import json import random from sharingan_base import * def initRand(): seed = 0 tf.set_random_seed(seed) np.rando...
#!/usr/bin/python3 """ Author: Sy<<EMAIL>> LICENSE: MIT License Copyright (c) 2018 Sy """ from __future__ import print_function from datetime import datetime from functools import partial import getpass import json import os import socket import sys CEND = '\33[0m' F_COLORED = lambda color: lambda str: color + st...
import datetime import time from slackclient import SlackClient from helpers import config_helper from helpers import slack_helper from helpers import utils from helpers import voltdb_helper from helpers import timesten_helper from helpers import altibase_helper from helpers.store import SlackStore from helpers.store...
lower16 = 0xFFFF factor16 = 2 ** 16 def make_recover(index, offset): return int(index + offset * factor16) def recover_index(value): return int(value & lower16) def recover_offset(value): return int((value - (value & lower16)) / factor16) class MapResult: def __init__(self, pos, deleted=False, r...
from ray.rllib.models.tf.tf_modelv2 import TFModelV2 from ray.rllib.utils.framework import try_import_tf from ray.rllib.models import ModelCatalog # import tensorflow_addons as tfa import math tf1,tf,tfv = try_import_tf() def conv(c, k=3, st=1, act=tf.keras.layers.ReLU, name="", gamma_init='ones'): return tf.ker...
#!/usr/bin/env python # Filename: watershed_segment """ introduction: segment a grey image authors: <NAME> email:<EMAIL> add time: 21 February, 2021 """ import os,sys from optparse import OptionParser deeplabforRS = os.path.expanduser('~/codes/PycharmProjects/DeeplabforRS') sys.path.insert(0, deeplabforRS) import ...
import grpc import time import logging from concurrent import futures from multiprocessing import pool from api import core_pb2, core_pb2_grpc from server.messages import Messaging from server.task_manager import TaskManager _ONE_DAY_IN_SECONDS = 60 * 60 * 24 def _unary_unary_interceptor(servicer, method_name, co...
#!/usr/bin/env python # -*- coding=utf-8 -*- import pickle import pandas as pd from pandas import * import numpy as np from nltk import word_tokenize from nltk.util import ngrams import collections from collections import Counter import os import regex as re from make_ngrams import compute_ngrams import math from coll...
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2021 <NAME>. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Access system field.""" from invenio_records.systemfields import SystemField from ....
#!/usr/bin/python import sys import json try: from NaServer import * NASERVER_AVAILABLE = True except ImportError: NASERVER_AVAILABLE = False if not NASERVER_AVAILABLE: module.fail_json(msg="The NetApp Manageability SDK library is not installed") DOCUMENTATTION = ''' --- module: export_rule_create version...
#--coding:utf-8-- import torch.nn as nn import torch import math def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) #import torch.nn.functional as F class Net(nn.Module)...
import hou from assetDB import AssetDBConnection from slice import Slice from fbxUtil import setScaleFactor # import lib.perforce from contextlib import closing from jinja2 import Environment, FileSystemLoader, PackageLoader from itertools import izip import os import random import sys # def getP4Connection(): # ...
from allauth.account.signals import email_confirmed from django.conf import settings from django.contrib.auth.models import Permission from django.contrib.sites.shortcuts import get_current_site from django.core.mail import send_mail from django.db.models.signals import post_save, pre_save from django.dispatch import r...
from unittest import TestCase from mock import Mock, call from ingest.exporter.bundle import Bundle from ingest.exporter.exporter import Exporter, SubmissionEnvelope, SubmissionEnvelopeParseException from ingest.exporter.metadata import MetadataResource, MetadataProvenance from ingest.exporter.staging import StagingI...
from __future__ import absolute_import, division, print_function from cctbx.array_family import flex import sys from cctbx import xray from cctbx import crystal from mmtbx.max_lik import max_like_non_uniform from cctbx.development import random_structure from cctbx.development import debug_utils #--------------------...
import astropy.io.fits as fits import matplotlib.pyplot as plt import matplotlib.tri as tri import numpy as np import os from .parameters import Params, find_parameter_file from .run import run class Disc: def __init__(self, dir=None, **kwargs): # Correct path if needed dir = os.path.normpath(os.p...
import logging import os from typing import Callable, Dict, List, Union import pkg_resources from .options import ( AsideSchemaOption, BibstyleSchemaOption, BooleanSchemaOption, CalloutSchemaOption, CitestyleSchemaOption, CodeSchemaOption, CustomTemplateDefs, HideLinksSchemaOption, ...
import os from collections import defaultdict import urllib from io import open from similar_text import similar_text from zhconv import convert import re NETEASE_LYRIC_SEARCH_API = "http://music.163.com/api/search/get/web?s=%s&offset=0&limit=50&total=true&type=1" NETEASE_LYRIC_DOWNLOAD_API = "http://music.163.com/ap...
# Copyright 2021, The TensorFlow Federated Authors. # # 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...
# Copyright 2021 <NAME> # 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, software...
""" User module to hold accounts related to users (admin or local) in the SMC You can create an Admin User, enable superuser, enable/disable the account, assign local access to engines, and change the account password for SMC or engine access. It is possible to fully provision an Admin User with specific permissions ...
# train.py from datetime import datetime from itertools import cycle import json from pathlib import Path import pickle import sys from typing import Any, Generator, List, Mapping, Optional, Sequence, Tuple, Union import numpy as np from optuna import create_study, Study, Trial import pandas as pd import pytorch_ligh...
# -*- coding: utf-8 -*- # # * Copyright (c) 2009-2015. Authors: see NOTICE file. # * # * 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...
"""Runtime parameters ===================== Scripting interface for Nek5000 :ref:`parameter file <nek:case_files_par>`. """ import textwrap from configparser import ConfigParser from io import StringIO from math import nan from pathlib import Path from sys import stdout from fluidsim_core.params import Parameters as ...
import networkx as nx # Imports networkx package for implementation of graphs import matplotlib.pyplot as plt # Imports matplotlib package for plotting and displaying the graphs node=[] edge=[] # Return a list of nodes of each cycle def cycles(G): l = list(nx.simple_cycles(G)) if len(l) != 0: print...
from datetime import datetime from time import time class Timestamp: def __init__(self, value=None): if value is None: value = time() if value > 9000000000: #the value is in milliseconds value /= 1000 self.value = round(value, 2) def to_str(self)...
from __future__ import unicode_literals, division, absolute_import import sys from argparse import ArgumentParser as ArgParser, Action, ArgumentError, SUPPRESS, _VersionAction import flexget from flexget.utils.tools import console from flexget.utils import requests def required_length(nmin, nmax): """Generates a...
import copy from django.http import Http404 from django.shortcuts import render from django.urls import reverse from django.views.generic import TemplateView from core.builtins.custom_tags import friendly_boolean from caseworker.core.helpers import generate_activity_filters from caseworker.core.services import get_co...
import os import re import json import dimod import embera import tarfile import requests def init_bm(G, RNG_SEED=None): embera.random.seed(RNG_SEED) """ Simulated Ising parameters of initialization of a Boltzmann Machine. """ N = len(G.nodes) node_biases = embera.random.bimodal(N,loc1=.0,scale1=.25,si...
# -*- coding: utf-8 -*- # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
from __future__ import print_function import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import datetime, csv, base64 import psycopg2 DAYS = 30 USER_ID = 'me' CREDENTIALS = 'credentials.js...
""" this module has the layer 2 config components , it has more business logic on the components like : vlan.has_interface --> return true of that particular vlan has an interface interface.is_svi --> return true of that particular interface is an svi interface """ from .base import FeatureSet, Feature from cscmiko.mo...
''' Copyright 2020 Flexera Software LLC See LICENSE.TXT for full license text SPDX-License-Identifier: MIT Author : sgeary Created On : Fri Aug 07 2020 File : create_report.py ''' import sys import logging import argparse import zipfile import os import report_data import report_artifacts import CodeInsight_RESTAP...
#!/usr/bin/python import sys, BenchMarker, Features, SimpleMixer, WeightMixer, \ PerceptronMixer, BucketPerceptronMixer, argparse, Logger, platform, \ datetime, getpass, tarfile, os, TokenCounter, subprocess, \ BayesianModelAvgMixer, NaiveBayesMixer, random from ContextClassifier import ContextClas...
# ejercicio 1 def longitud(cadena): contador = 0 for c in cadena: contador += 1 return contador my_string = input("Ingresar el texto: ") lista_palabras = my_string.split() print("El texto ingresado es: {}".format(my_string)) print(f"La ultima palabra es {lista_palabras[-1]} ...
from __future__ import division, unicode_literals, absolute_import import numpy as np try: import lalsimulation as lalsim except Exception: pass class lal_wrapper(object): def __init__(self, approx, domain): self.approx = lalsim.__dict__[approx] self.domain = domain def __call__...
# Copyright (c) 2013, <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and the followin...
import pandas as pd import datetime import matplotlib.pyplot as plt def calculate_dist_max(av_driving_range): """ function calculating the parameter dist_max based on the average driving range of electric vehicles in the car fleet :param av_driving_range: (km) average driving range :return: """ ...
import json from math import log import re import time import gc import urllib.request import zipfile import os import argparse from sklearn.model_selection import train_test_split import numpy as np np.random.seed(8423) import pandas as pd import xgboost as xgb import average_precision_calculator NUM_PREPROCESS = ...
import numpy as np from numpy import pi from scipy.integrate import simps, quad from .LabFuncs import * from .utils import * from scipy.special import erf from scipy.interpolate import interp1d from verne import MaxwellBoltzmann as MB import argparse import os.path # Exposure in kg days exposure = 0.046e-3 # nucleus...
from metaflow import conda_base, FlowSpec, IncludeFile, Parameter, step, S3 def script_path(filename): """ A convenience function to get the absolute path to a file in this tutorial's directory. This allows the tutorial to be launched from any directory. """ import os filepath = os.path.j...
import csv import glob import io import json import os from time import time import numpy as np import svgwrite from . import visualize_pointcloud as v from .plyutil import read_ply_file def initialize(object_files_path): data = {} for i, path in enumerate(glob.glob(object_files_path)): time_of_pr...
# -*- coding: utf-8 ; test-case-name: bridgedb.test.test_bridgerequest ; -*- #_____________________________________________________________________________ # # This file is part of BridgeDB, a Tor bridge distribution system. # # :authors: <NAME> 0xA3ADB67A2CDB8B35 <<EMAIL>> # please also see AUTHORS file # :c...
import torch from torch import nn from torch.distributions import MultivariateNormal, Normal from model.networks import LargeImpalaCNN from common.arguments import get_parser_rl import numpy as np import torchvision.transforms as transforms import common.const as const from carla_game.carla_gamev09 import CarlaEnv fr...
# Copyright 2015 <NAME> # # 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...
import pygame import sys import random #Initialize pygame pygame.init() WIDTH = 800 HEIGHT = 600 #create the screen screen = pygame.display.set_mode((WIDTH, HEIGHT)) #title and icon pygame.display.set_caption("Pong") icon = pygame.image.load("atari.png") pygame.display.set_icon(icon) #sound e...
# Copyright (c) 2013 Spotify AB # # 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...
""" Copyright 2017-2018 Fizyr (https://fizyr.com) 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 w...
"""Generate Ansible playbook variable reference. * Variables are defined in .yml files which are included in playbook * The variable is described in the precedenting comment * The first variable in a playbook must be ``config_description`` which gives the description of the playbook * Section headers using the form...
# tongue_data.py - Dataloader and image augmentation functions. # Author: hys # Email: <EMAIL> from os.path import join, basename from glob import glob import random import numpy as np import torch import cv2 from torch.utils.data import Dataset from torch.utils.data import DataLoader import albumentations as A fro...
from models import * import matplotlib.pyplot as plt ITER_AMT = 500 DEF_K = 10000 m_arr = [5, 10, 15, 25, 70] def draw_points(m: int) -> (np.array, np.array): """ Given an integer m returns a pair X,y where X is a 2xm matrix where each column represents an i.i.d sample from the distribution ...
import discord from itertools import cycle from discord.ext import tasks, commands from datetime import date from flask import Flask from threading import Thread app = Flask('') today = date.today() # Quote Library quote_library = {} @app.route('/') def main(): return "Your Bot Is Ready" ...
import torch import inspect import functools def check_default_set(split, target_select, dataset_name): # Check whether given object split is either a tuple of strings or string # and represents a valid selection of options given by the tuple of strings # target_select. if isinstance(split, str): ...
# 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. from tqdm import tqdm import nltk import functools import argparse import json from glob import glob import os import time from function import Function import random from function.utils import parse_to_function_tree, make_sampler_from_functio...
import json,ast from django.core import serializers from django.shortcuts import render,HttpResponse,redirect from django.views.generic.edit import FormView from payroll_management.forms import CustomAllowanceForm from payroll_management.views import return_encoded from .forms import * from .builder import...
""" Parse the file containing the list of bonus flying miles. Here is an example: .. code-block:: <NAME> LX326 05.12.2016 ECONOMY LX317 10.01.2017 ECONOMY A3851 12.05.2017 BUSINESS LX8 12.10.2017 FIRST 4433 . <NAME> LX4150 19.10.2017 BUSINESS 6404 . The list consists of blocks. E...
import random from Genes import Genes from DNA import DNA from Biome import Biome # Vision things ID system 2 hex digit long (for now) # 00 - 0A --> Biomes in order ['empty', 'grassland', 'forest', 'jungle', 'savanna', # 'desert', 'wetland', 'tundra', 'artic', 'reef', 'marine', 'ocean'...
import glfw import OpenGL.GL as gl import moderngl_window as mglw from imgui.integrations.glfw import GlfwRenderer import imgui from pathlib import Path from moderngl_window.integrations.imgui import ModernglWindowRenderer from abc import ABC, abstractmethod from .scene_object import SceneObject from .camera import Ort...
# $Filename$ # $Authors$ # Last Changed: $Date$ $Committer$ $Revision-Id$ # Copyright (c) 2003-2011, German Aerospace Center (DLR) # All rights reserved. # # #Redistribution and use in source and binary forms, with or without # #modification, are permitted provided that the following conditions are #met: # ...
# -*- coding: utf-8 -*- # Copyright (c) 2020 <NAME> # # 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, modify...
"""Common functions for genome assembly and annotation data processing. """ import gzip import json import multiprocessing import os import shutil import subprocess import time import urllib.request as request from google.cloud import storage from google.oauth2 import service_account def get_species_list(organisms_p...
""" DFIR Diary The Project shall create an small Programm, to document the information about an security Incident. It may allow you to document an case completely independent to any online tools. If there is no need for a offline usage, this program can send the Logs via syslog for an transperent invest...
import tensorflow as tf import numpy as np import random import gym import gym_gazebo import math import matplotlib.pyplot as plt import matplotlib import matplotlib.pyplot as plt env = None class LivePlot(object): def __init__(self, outdir, data_key='episode_rewards', line_color='blue'): """ Livep...
# main script # various imports import os available_gpus = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # updated this list accordingly str_available_gpus = [str(gpu) for gpu in available_gpus] str_available_gpus = ",".join(str_available_gpus) os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = str...
#this is an adaptation of the anomaly_detection script to also perform PCA #it was proposet to represent events as a point cloud using this technique, but the idea was abandoned for time restrictions #most lines used here are commented in the original script import scipy import stuett from stuett.global_config import ...
#!/usr/bin/env python # coding: utf-8 # In[2]: import os import pandas as pd import json import random import sys import ast import numpy as np import argparse import nltk import pickle import scipy import spacy from sklearn_pandas import DataFrameMapper from sklearn import preprocessing from sklearn.naive_bayes imp...
# -*- coding: utf-8 -*- """Test writing of BGZF files """ import codecs import gzip import io import pytest import vcfpy from vcfpy import parser from vcfpy import writer from vcfpy import record __author__ = "<NAME> <<EMAIL>>" MEDIUM_HEADER = """ ##fileformat=VCFv4.3 ##fileDate=20090805 ##source=myImputationProg...
from PyQt5 import QtCore, QtGui, QtWidgets from database_explorer_plotter.database_ui import database_ui from database_explorer_plotter.load_ui import load_ui from os import path from qt_designer.temporal_backup import temporal_ui from databasemanager import * from custom_plotter.plotter import agplot import sys impor...
import shap import argparse import time import numpy import torch import torch.nn as nn from tqdm import tqdm import gym_minigrid import matplotlib.pyplot as plt import utils # Parse arguments parser = argparse.ArgumentParser() parser.add_argument("--env", required=True, help="name of the env...
# The code to evaluate the predictions given below is adapted from # https://github.com/nianticlabs/monodepth2/blob/master/evaluate_depth.py from __future__ import absolute_import, division, print_function import os import cv2 import numpy as np import time import torch.nn from options.test_options import TestO...
import argparse import datetime import getpass import http.cookies import sys import textwrap import time from logging import getLogger from typing import * import requests import onlinejudge.dispatch as dispatch import onlinejudge_command.utils as utils from onlinejudge.type import LoginError, Service logger = getL...
from random import choice, random, sample import numpy as np import networkx as nx from BanditAlg.BanditAlgorithms import ArmBaseStruct import datetime class LinUCBUserStruct: def __init__(self, featureDimension,lambda_, userID, RankoneInverse = False): self.userID = userID self.d = featureDimension self.A = la...
# python3 # pylint: disable=g-bad-file-header # Copyright 2021 DeepMind Technologies Limited. 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...
class TipoServico: codigo = 0 descricao = '' class TipoServicoPrestado: numeroServico = 0 codigoServico = 0 precoServico = 0.0 codigoCliente = 0 def mostrarRelatorioPorDia(vServicoPrestado, vTipoServico):#5 print('~~Apresentaçao de serviço prestados~~') print(vTipoServico) for i ...
""" This file handles all the community interaction stuff with matrix. It is implemented here and not in the connector because it isn't part of the matrix spec yet and liable to change. """ import logging from functools import wraps from urllib.parse import quote import parse from matrix_client.errors import MatrixRe...
import re import openpyxl from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import Group from django.forms.models import model_to_dict # Create your views here. from django.http import JsonResponse from django.middleware.csrf import get_token from django.shortcuts import HttpR...
import jax from jax import numpy as jnp # import numpy as np from tabcorr.tabcorr import * class JaxTabCorr(TabCorr): def predict(self, model, separate_gal_type=False, **occ_kwargs): """ Predicts the number density and correlation function for a certain model. Parameters -...
"""Helper functions to search class-map configurations""" def search_strings(i): """Search configuration for config k, v's Calls Checks module""" all_matches = [] all_matches.append({'match_what': i.get('prematch')}) if i.get('any') is not None: all_matches.append('Any') for key...
from __future__ import division from fcntl import flock, LOCK_EX, LOCK_UN from contextlib import contextmanager from traceback import format_exc from datetime import timedelta from logging import getLogger from functools import wraps from urllib import urlencode from urlparse import urlparse, urlunparse, parse_qsl from...
load("@bazel_skylib//:lib.bzl", "asserts", "unittest") load("//lib:json_parser.bzl", "json_parse") load(":json_parse_test_data.bzl", "get_pkg_jsons") def _valid_json_parse_test(ctx): env = unittest.begin(ctx) asserts.equals(env, json_parse("[]"), []) asserts.equals( env, json_parse('["x", ...
import django from django.contrib.auth.decorators import user_passes_test from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.shortcuts import render_to_response, redirect from django.template.context import RequestContext from reversion.models import Revision import reversion from .fo...
# Copyright 2017 Neosapience, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
import datetime as dt import json import logging import time from typing import Union, Type, Dict, Tuple, List from uuid import UUID from redis import Redis, ConnectionPool from rq import Queue # type: ignore from rq.command import send_stop_job_command # type: ignore from rq.exceptions import NoSuchJobError # typ...
import asyncio import json from typing import IO, Any, Callable, Dict, List, Optional, Tuple, Type, Union import aiohttp import requests API = 'https://api.zhconvert.org' class FanhuajiEngine(): """繁化姬轉換引擎""" def _request(self, endpoint: str, payload: dict): with requests.get(f'{API}{endpoint}', da...
# following: https://medium.com/ai-society/gans-from-scratch-1-a-deep-introduction-with-code-in-pytorch-and-tensorflow-cb03cdcdba0f import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import torchvision.transforms as transforms import torchvision.datasets as datasets from ...
import sys import nltk nltk.download(['punkt', 'wordnet', 'stopwords']) from sqlalchemy import create_engine import re import numpy as np import pandas as pd import pickle from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from sklearn.featur...
from common import database from common import TaskQueues, get_object_store from common.utils import setup_logging, shell_escape import json import logging import os import shutil import subprocess import tempfile SQLSession = None object_store = None # IP as understood by Docker daemon, not this container DOCKER_R...
# -*- coding:utf-8 -*- # author:平手友梨奈ii # e-mail:<EMAIL> # datetime:1993/12/01 # filename:shufflenet.py # software: PyCharm import tensorflow as tf import tensorflow.keras as keras import tensorflow.keras.layers as layers class ConvBNRelu(keras.Model): def __init__(self, channels, kernel_size, s...
import os import threading import warnings from collections import OrderedDict from io import BytesIO import matplotlib.pyplot as plt import numpy as np from PIL import Image from matplotlib.backends.backend_pdf import PdfPages class Collect(object): """ Collect figures and export to a file Args: ar...