text stringlengths 3.07k 12.6k |
|---|
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.cache import cache_page
from .forms import CommentForm, PostForm
from .models import Comment, Follow, Group, Post, User
@... |
r"""
Calculates the scattering for a generalized Guinier/power law object. This is
an empirical model that can be used to determine the size and dimensionality
of scattering objects, including asymmetric objects such as rods or
platelets, and shapes intermediate between spheres and rods or between rods
and platelets, a... |
import asyncio
import traceback
from typing import List, Any, Dict
from tartiflette.executors.types import Info, ExecutionContext
from tartiflette.schema import GraphQLSchema
from tartiflette.types.exceptions.tartiflette import InvalidValue
from tartiflette.types.field import GraphQLField
from tartiflette.types.locati... |
import numpy as np
import matplotlib.pyplot as plt
from numpy.linalg import inv
N = 25
X = np.reshape(np.linspace(0, 0.9, N), (N, 1))
Y_train = np.cos(10*X**2) + 0.1 * np.sin(100*X)
#K = 12 # order of the func
listTrainning = []
for i in np.linspace(0, 0.9, N):
listTrainning.append(np.cos(10*i**2) + 0.1 * np.sin(... |
import pytest
import re
import pandas as pd
from requests.exceptions import HTTPError
from solarforecastarbiter.datamodel import Site, Observation
from solarforecastarbiter.io import api
from solarforecastarbiter.io.reference_observations import eia
@pytest.fixture
def session(requests_mock):
return api.APISessi... |
import json
import os
import requests
from datetime import datetime, timedelta
def get_account_stats(addr):
os.environ["EXPLORER_API"] = "https://explorer.thetatoken.org:8443/api"
uri = os.getenv("EXPLORER_API") + f"/account/{addr}"
headers = {"x-api-key": os.getenv("EDGESTATS_API_KEY")}
req = reques... |
import typing as T
import datetime
import os
import shutil
import logging
from . import utils, ffmpeg, types, exceptions
from .exif_write import ExifEdit
TIME_FORMAT = "%Y-%m-%d %H:%M:%S"
TIME_FORMAT_2 = "%Y-%m-%dT%H:%M:%S.000000Z"
LOG = logging.getLogger(__name__)
def sample_video(
video_import_path: str,
... |
"""Individual methods for assessing ERPAC."""
import numpy as np
from scipy.stats import chi2
from joblib import Parallel, delayed
from tensorpac.gcmi import nd_mi_gg
from tensorpac.config import CONFIG
def pearson(x, y, st='i...j, k...j->ik...'):
"""Pearson correlation for multi-dimensional arrays.
Parame... |
from os import stat
from grammar import Grammar, Rule, check_can_be_terminal
from typing import List, Set
from dataclasses import dataclass
from queue import Queue
import copy # For making clones
# A class that has a rule and some extra things
class AutomataRule(Rule):
"""
This class represents a rule but with ad... |
import cv2
import numpy as np
from typing import Union, List, Tuple
from os import path, listdir
def check_file_res(fpath: str) -> Tuple[int, int, int]:
''' return Tuple(height, width, channel) '''
if path.exists(fpath):
img = cv2.imread(fpath)
return img.shape
else:
raise Exceptio... |
"""Support for functionality to interact with Android TV/Fire TV devices."""
import logging
import os
from adb_shell.auth.keygen import keygen
from androidtv.adb_manager.adb_manager_sync import ADBPythonSync
from androidtv.setup_async import setup
from homeassistant.components.media_player import DOMAIN as MP_DOMAIN
... |
import concurrent.futures
import logging
import os
from threading import Lock
from time import sleep
import numpy as np
import pycurl
from notetool.tool import delete_file, exists_file, path_parse
from requests import Session
from tqdm import tqdm
class BaseDownLoad:
def __init__(self, session=None):
s... |
from typing import Dict, Tuple
import numpy as np
import pandas as pd
import statsmodels.api as sm
from matplotlib import pyplot as plt, gridspec
import seaborn as sns
from sklearn import metrics
from data.visualisation import apply_style
def plot_rf_feature_importances(importances: np.ndarray) -> None:
plt.tit... |
import os
import re
from pathlib import Path
from typing import Iterable, Tuple, Union, List
from torch.utils.data import Dataset
from torchaudio.datasets.utils import download_url
_CHECKSUMS = {
"http://svn.code.sf.net/p/cmusphinx/code/trunk/cmudict/cmudict-0.7b":
"825f4ebd9183f2417df9f067a9cabe86",
"htt... |
import os
import sys
import ffmpeg
from termcolor import colored
def print_message(msg_type, **kwargs):
""""""
if msg_type == 'options':
print(
colored("\t{}) {}".format(kwargs['key'], kwargs['value']),
'green')
)
elif msg_type == 'choose':
print(... |
import csv
import lib_data_structures
import lib_doctest_pycharm
import logging
from fp_conf import fp_diff_files_conf, fp_conf
logger = logging.getLogger()
lib_doctest_pycharm.setup_doctest_logger_for_pycharm()
class FileDiff(object):
def __init__(self):
pass
def __enter__(self):
return self... |
"""Method implementations for the Elpy JSON-RPC server.
This file implements the methods exported by the JSON-RPC server. It
handles backend selection and passes methods on to the selected
backend.
"""
import io
import os
import pydoc
from elpy.pydocutils import get_pydoc_completions
from elpy.rpc import JSONRPCServ... |
"""Implement the Model class in the MVC pattern for AkeyaaPy.
This modules contains the working functions that perform the Akeyaa analysis
across a venue.
Notes
-----
*Akeyaa analysis* entails the fitting of the conic potential model at
many target locations within the `venue`. The target locations are selected
as t... |
import re
import tempfile
from cgi import FieldStorage
from datetime import datetime
from gzip import GzipFile
from io import BytesIO
from onegov.core.utils import Bunch
from onegov.core.utils import dictionary_to_binary
from onegov.form import Form
from onegov.form.fields import ChosenSelectField
from onegov.form.fie... |
#! /usr/bin/env python3
import os
import sys
import unittest
import click
try:
from enjoliver import configs, gunicorn_conf
from enjoliver.model import Base
except ModuleNotFoundError:
click.echo('please install enjoliver first: cd enjoliver-api && pip install -e .')
sys.exit(255)
PROJECT_PATH = os.p... |
import sys
import click
import numpy as np
import pandas as pd
import re
SOL_NEW_BEST = 'new best energy'
SOL_NEW = 'new energy'
SOL_DUPLICATE_BEST = 'best energy (dup)'
SOL_DUPLICATE = 'duplicate energy'
SOL_NOTHING = ''
sol_types = dict(
NOTHING=0, # nothing new, do nothing
NEW_HIGH_ENERGY_SOL=1, # ADDED... |
#!/usr/bin/env python
# ===============================================================================
# Copyright (c) 2014 Geoscience Australia
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
... |
from allennlp.data import Instance
from allennlp.data.dataset_readers import DatasetReader
from allennlp.data.fields import TextField, SequenceLabelField, MetadataField
from allennlp.data.token_indexers import TokenIndexer, SingleIdTokenIndexer
from allennlp.data.tokenizers import Token
import spacy
from spacy.tokenize... |
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry import story
from telemetry import page
from contrib.vr_benchmarks import (shared_android_vr_page_state as vr_state)
from contrib.vr_benchmark... |
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY ... |
"""
Processing example using a Mahr file format (txt).
The code loads a file, builds the q-spectrum and displays the image.
Note that invalids are replaced with NAN.
"""
import sys
import time
import getopt
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1 import mak... |
import bs4
import chromedriver_binary
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import sys
import time... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import sys
from text.compat import basestring, implements_to_string, PY2, binary_type
class ComparableMixin(object):
'''Implements rich operators for an object.'''
def _compare(self, other, method):
try:
return method(self._c... |
# Copyright 2020 Broadband Forum
#
# 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 writi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Simulate linearized benchmark bicycle given a test file from the Unity3d
bicycle simulator. Apply the torque input specified in the test file and
compare bicycle states.
"""
import os
import sys
import numpy as np
from numpy import linalg as la
from scipy import signal... |
import time, sys
import os
import json
import copy
from fsop_counters import FSOPCounters
from common import FsDriftException, OK
from common import KiB_PER_GiB, BYTES_PER_KiB, MiB_PER_GiB, BYTES_PER_MiB
def output_thread_counters(outfile, start_time, total_errors, fsop_ctrs):
jsondict = fsop_ctrs.json_dict()
... |
"""User sessions for aiohttp.web."""
import abc
import json
import time
from collections.abc import MutableMapping
from aiohttp import web
__version__ = '2.8.0'
class Session(MutableMapping):
"""Session dict-like object."""
def __init__(self, identity, *, data, new, max_age=None):
self._change... |
# -*- coding: utf-8 -*-
# Grid CSV dumper
# See the accompanying LICENSE file.
# (C) 2021 Engie Digital
#
# vim: set ts=4 sts=4 et tw=78 sw=4 si:
"""
Save a `Grid` in CSV file, conform with the specification describe
here (https://www.project-haystack.org/doc/Csv)
"""
from __future__ import unicode_literals
import dat... |
from sympy import (
Add, collect, Dummy, cos, cosh, sin, sinh, exp, factorial, I, Mul, Pow,
simplify
)
from sympy.physics.quantum.operatorordering import normal_ordered_form
from .commutators import recursive_commutator
from .operator_utilities import extract_operator_products, split_coeff_operator
from .qsimpl... |
from typing import Optional, Any
from functools import reduce
from pyscf import __config__
from pyscf.cc import ccsd
from pyscf.mp.mp2 import _mo_without_core
from pyscfad import lib
from pyscfad.lib import numpy as jnp
from pyscfad.gto import mole
from pyscfad.scf import hf
def amplitudes_to_vector(t1, t2, out=None):... |
# from datetime import datetime
import os
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class TinyWebDB(db.Model):
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import framework.configbase
import math
import time
import numpy as np
from modules.transformer_encoder import Encoder
from modules.transformer_decoder import Decoder
decay1 = [(i+1)*20**(-1) for i in range(20)]
deca... |
#!/usr/bin/env python
"""
Add docstring
"""
from datetime import datetime
from protorpc import messages
from google.appengine.ext import ndb
# Define game objects
class Game(ndb.Model):
"""Game object"""
deck = ndb.StringProperty(repeated=True)
disp_deck = ndb.StringProperty(repeated=True)
attemp... |
# coding=utf-8
import os
import time
import json
from django.shortcuts import render, get_object_or_404
from django.views.generic import View
from django.db.models import ObjectDoesNotExist
from pics.utils import _ajax_error, _ajax_success, _is_doubtful
from . import models as spider_models
# Create your views here... |
# Author Melody
# Data 2021-06-03 16:27:40
import pandas as pd
import geopy.distance
# Pytest is an automated testing module on Python,Use Pytest to test the legitimacy on Bikeshare Data
# import pytest as pt
# Coords is a data structures to save How Bikeshare Date,Coord just like a List
def getStartEndCoords():
... |
"""Plugwise platform for Home Assistant Core."""
import asyncio
from datetime import timedelta
import logging
from typing import Dict
from Plugwise_Smile.Smile import Smile
import async_timeout
import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, CO... |
import torch
import numpy as np
from torch import nn
from torch.autograd import Variable
from pdb import set_trace as bp
from operations import *
def _concat(xs):
return torch.cat([x.view(-1) for x in xs])
class Architect(object):
def __init__(self, model, args, distill=False):
self.network_momentu... |
# 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
# "License"); you may not u... |
import asyncio
import random
import time
from asyncio import TimeoutError, sleep
from random import choice
from string import ascii_letters
import async_cleverbot as ac
import discord
from discord.ext import commands
from discord.ext.commands.cooldowns import BucketType
from ...lib import Embed, ErrorEmbed, Tokens, g... |
#!/usr/bin/env python3
# Copyright 2018-present, HKUST-KnowComp.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Machine Comprehension predictor"""
import logging
from multiprocessing import Pool as ProcessPool
from mu... |
from PyQt5.QtWidgets import QFileDialog, QMessageBox
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap, QImage, QPainter, QIcon, QColor
import os
from app.constants import TILEWIDTH, TILEHEIGHT
from app.resources.resources import RESOURCES
from app.resources.tiles import TileSet, TileMapPrefab
fr... |
import logging
from datetime import datetime, timedelta
from functools import partial
import dateutil.parser
from sqlalchemy import create_engine
from sqlalchemy import func, Table, Column, Boolean, Integer, String, MetaData
from sqlalchemy.pool import StaticPool
from sqlalchemy.sql import select, update
from haikubo... |
# Copyright (c) 2017, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated Thu Apr 11 15:07:49 2013 by generateDS.py version 2.9a.
#
import sys
from mixbox.binding_utils import *
from stix.bindings import register_extension
im... |
# -*- coding:utf-8 -*-
"""
Trader Module.
Author: Moseszhang
Date: 2019/10/31
Email: <EMAIL>
"""
import copy
from quant import const
from quant.error import Error
from quant.utils import logger
from quant.tasks import SingleTask
from quant.order import Order, ORDER_TYPE_LIMIT
from quant.position import Position
... |
"""Manage Series of experimental data in potentially several folders."""
import os
from pathlib import Path
import datetime
import pandas as pd
from .general import make_iterable, list_files
# ================================= Classes ==================================
class File:
"""Individual file among the... |
#!/usr/bin/env python
"""
From a set of regions and two sets of intervals inside those regions
compute (for each region separately) the overlap between the two sets
of intervals and the overlap in `nsamples` random coverings of the
regions with intervals having the same lengths. Prints the z-score relative
to the mean... |
import math
import multiprocessing.pool
import numpy as np
import pyhf
signal_region = 'A'
control_regions = ['B', 'C', 'D']
all_regions = [signal_region] + control_regions
poi_name = 'mu'
signal_uncertainty_name = 'systematic_uncertainty'
bkg_normalization_name = 'mu_b'
bkg_scale_factor_1_name = 'tau_B'
bkg_scal... |
import time
from braze.client import _wait_random_exp_or_rate_limit
from braze.client import BrazeClient
from braze.client import BrazeClientError
from braze.client import BrazeInternalServerError
from braze.client import BrazeRateLimitError
from braze.client import MAX_RETRIES
from braze.client import MAX_WAIT_SECOND... |
"""A collection of metrics for evaluation xG models."""
import numpy as np
from scipy import integrate
from sklearn.neighbors import KernelDensity
def expected_calibration_error(y_true, y_prob, n_bins=5, strategy='uniform'):
"""Compute the Expected Calibration Error (ECE).
This method implements equation (3)... |
import uuid as _uuid
from copy import copy as _copy
from Acquire.Crypto import PrivateKey as _PrivateKey
from Acquire.Crypto import PublicKey as _PublicKey
from Acquire.Crypto import OTP as _OTP
from Acquire.ObjectStore import bytes_to_string as _bytes_to_string
from Acquire.ObjectStore import string_to_bytes as _st... |
# SPDX-License-Identifier: MIT
# Copyright (c) 2018-2022 Amano Team
import glob
import importlib
import json
import os
import re
from typing import Dict, List
import pyrogram
import yaml
from langs import Langs
from pyrogram import Client, filters
from pyrogram.helpers import bki
from rich import print
from userlixo... |
import datetime
import os
import string
import numpy
from scipy.io import netcdf
from inqbus.lidar.scc_gui.log import logger
NC_FILL_INT = -2147483647
NC_FILL_FLOAT = 9.9692099683868690e+36
NC_FILL_DOUBLE = 9.9692099683868690e+36
def ncname(measurement):
datestr = measurement['header']['start'].strftime('%Y%m%... |
# Copyright 2015 gRPC 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 or agreed to in writing... |
"""TODO."""
import os
import uuid
from testplan import Testplan, TestplanResult
from testplan.common.entity import (
Resource,
ResourceStatus,
Runnable,
RunnableResult,
)
from testplan.common.utils.exceptions import should_raise
from testplan.common.utils.path import default_runpath
from testplan.comm... |
# 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.\n",
# 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 writ... |
#!/usr/bin/python
import sys
from klampt import *
from klampt import vis
from klampt.vis import editors
from klampt.io import resource
from klampt.model import ik,coordinates,config,cartesian_trajectory
from klampt.math import vectorops,so3,se3
from klampt.model import trajectory
import time
import math
class InterpK... |
import os
from pathlib import Path
import subprocess
import numpy as np
import cv2
from videokf.utils.all_utils import make_dir, make_frames_list
from videokf.keyframe_manager.frame_manager import Frame, calculate_stillness
def extract_frames(ffmpeg_exe, video_file, frames_selected=None, output_dir="frames", frame_q... |
import numpy as np
import pandas as pd
import scipy.sparse as sp
import sklearn.preprocessing as pp
from math import exp
from heapq import heappush, heappop
# conventional i2i
class CosineSimilarity():
# expects DataFrame, loaded from ratings.csv
def __init__(self, df, limit=20):
self.limit = limit
... |
import logging
from flask import flash
from flask_login import current_user
from scout.build import build_managed_variant
from scout.constants import CHROMOSOMES, CHROMOSOMES_38
from scout.parse.variant.managed_variant import parse_managed_variant_lines
from scout.server.extensions import store
from scout.server.util... |
# Copyright 2020-present Kensho Technologies, LLC.
"""Code for loading descriptor and symbol databases from grpc reflection service
This is Leonid's personal take on clean room implementation of
https://github.com/grpc/grpc/blob/master/test/cpp/util/proto_reflection_descriptor_database.cc
but with less bells and whist... |
# Copyright 2017 The TensorFlow 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 applica... |
import json
from collections import defaultdict
class Deque:
def __init__(self,lista=None):
self.lista=lista or []
def setLista(self,lista):
self.lista=lista
def addRight(self,item):
self.lista.append(item)
def addLeft(self,item):
self.lista.insert(0,item)
def remover... |
"""
Computing the robot forword kinematics in tensorflow
"""
from rmp2.utils.tf_transform_utils import T_prismatic, T_revolute, T_rpy
from urdf_parser_py.urdf import URDF
import tensorflow as tf
import os
class Joint:
"""
tensorflow module for joint
"""
def __init__(self, urdf_joint, dtype=tf.float32... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @namespace pyfortified_requests
import re
import ujson as json
import urllib.parse
from .constants import (__USER_AGENT__)
from base64 import b64encode
import requests
import shlex
import argparse
from pyfortified_requests.support.utils import urlencode_dict
# from ppr... |
"""
Low-level Skype API definitions.
This subpackage imports one of the:
- `Skype4Py.api.darwin`
- `Skype4Py.api.posix`
- `Skype4Py.api.windows`
modules based on the current platform.
Name of the imported module in available in the `platform` variable.
The modules implement the low-level Skype API and define optio... |
# -*- coding: utf-8 -*-
## \package command_line
# MIT licensing
# See: docs/LICENSE.txt
import sys
from startup.tests import available_tests
from startup.tests import test_list
## Solo args
#
# -h or --help
# Display usage information in the command line.
# -v or --version
# Display Debreate version in the co... |
from dataclasses import dataclass
import json
import logging
import datetime
import pytz
from fitparse import FitFile
from django.conf import settings
from wizer.file_helper.lib.parser import Parser
from wizer.tools.utils import remove_nones_from_list
log = logging.getLogger(__name__)
class FITParser(Parser):
... |
import torch
from torch.utils.data import Dataset
import string
translator = str.maketrans('', '', string.punctuation)
import random
import glob
from PIL import Image
import numpy as np
from torch.nn.utils.rnn import pad_sequence
import pickle
DATA_DIR = '../../data/'
FRAMES_DIR = '../../data/processed-frames/'
ENVS_D... |
import logging
from django import forms
from django.contrib.auth import authenticate
from django.contrib.auth.forms import AuthenticationForm
from django.core.validators import validate_email
from django.utils.translation import ugettext_lazy as _
from .models import CalendallUser
from . import utils
log = logging.... |
#!/usr/bin/env python3
"""
Panopticon by <NAME>
Copyright 2016, <NAME>
This file is licensed under the BSD 3-clause License
Upgraded to support discord.py 1.0.0a1540 by PikalaxALT
"""
# Imports from stdlib
import asyncio
import base64
from datetime import datetime, timezone
import time
import os
import re
import sign... |
"""LightGBM関連。"""
from __future__ import annotations
import logging
import pathlib
import typing
import numpy as np
import pandas as pd
import sklearn.metrics
import tqdm
if typing.TYPE_CHECKING:
import lightgbm as lgb
logger = logging.getLogger(__name__)
def cv(
models_dir: str | pathlib.Path,
feats_... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
"""This module corresponds to the goddard/astro directory in idlutils.
"""
from __future__ import print_function
def airtovac(air):
"""Convert air wavelengths to wavelengths in vacuum.
Parameters
----------
air : ... |
import os
import re
from typing import Dict, List, Set, Tuple, Type
from ..casing import safe_snake_case
from ..lib.google import protobuf as google_protobuf
from .naming import pythonize_class_name
WRAPPER_TYPES: Dict[str, Type] = {
".google.protobuf.DoubleValue": google_protobuf.DoubleValue,
".google.protob... |
"""
Copyright 2015 Rackspace
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
dist... |
"""
REST-API wrapper for Link Grammar parser. Uses Falcon framework along with Gunicorn WSGI server
(can be any WSGI server).
Request:
http://<server ip>:<server port>/linkparser?lang=<language>&text=<sentence>&mode=<mode>&limit=<limit>
<language> - short name of the dictionary supp... |
from builtins import open as builtin_open
import importlib
import os
import sys
from contextlib import contextmanager, _GeneratorContextManager as GCM
import threading
from funcy import wrap_with
import ruamel.yaml
from voluptuous import Schema, Required, Invalid
from dvc.repo import Repo
from dvc.exceptions import D... |
import re
from fetcher.helpers import instantiate_aspace, list_chunks
from pisces import settings
class MissingArchivalObjectError(Exception):
pass
def indicator_to_integer(indicator):
"""Converts an instance indicator to an integer.
An indicator can be an integer (23) a combination of integers and le... |
import math
import shutil
import faiss
import numpy as np
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
from tqdm import tqdm
def compute_features(eval_loader, model, args):
print('Comput... |
# -*- coding: utf-8 -*-
from pysignfe.xml_sped import *
from pysignfe.nfe.manual_300 import ESQUEMA_ATUAL
import os
DIRNAME = os.path.dirname(__file__)
class ConsSitNFe(XMLNFe):
def __init__(self):
super(ConsSitNFe, self).__init__()
self.versao = TagDecimal(nome=u'consSitNFe', codigo=u'EP01', pro... |
from tweepy import Stream
from tweepy.auth import OAuthHandler
from tweepy.streaming import StreamListener
import csv
import signal
from time import sleep
from threading import Thread
import os
import onedrivesdk
Place = ["Delhi","Noida","Gurgaon","Gaziabad"]
Resource = ["bed"]#["bed","oxygen","medicine","remdecivir",... |
# modified from https://github.com/goberoi/cloudy_vision
import cv2
from jinja2 import FileSystemLoader, Environment
import json
import numpy
import time
import os
import pprint
import shutil
import time
import vendors.google
import vendors.microsoft
import vendors.clarifai_
import vendors.ibm
import vendors.cloudsigh... |
import os
import numpy as np
import pandas as pd
from sklearn.utils import shuffle
column_names = ['treat', 'age', 'educ', 'black', 'hisp', 'married', 'nodegr', 're75', 're78']
column_types = {
'treat': 'int32',
'age': 'int32',
'educ': 'int32',
'black': 'int32',
'hisp': 'int32',
'married': 'in... |
# -*- coding: utf-8 -*-
import os
import io
import unittest
from testfixtures import TempDirectory
from .. import fs
from .. import localfs
from ..utils import TemporaryFilename
class test_localfs(unittest.TestCase):
def setUp(self):
self.dir = TempDirectory()
def tearDown(self):
self.dir.c... |
import os
from time import sleep
from vmaf.core.mixin import H5pyMixin
from vmaf.tools.reader import YuvReader
from vmaf.core.executor import Executor
from vmaf.core.result import RawResult
__copyright__ = "Copyright 2016-2017, Netflix, Inc."
__license__ = "Apache, Version 2.0"
class RawExtractor(Executor):
def... |
import logging
import json
import os
import random
import string
import sys
import pprint
import threading
import tempfile
import modules.urllib3 as urllib3
from urllib.parse import parse_qs
from typing import Dict, List
from http.server import HTTPServer, BaseHTTPRequestHandler
from enum import Enum
modules = os.pa... |
"""
Contours shape recognition mainly based on cv2.approxPolyDP() function
"""
# Import required packages:
import numpy as np
import cv2
from matplotlib import pyplot as plt
def get_position_to_draw(text, point, font_face, font_scale, thickness):
"""Gives the coordinates to draw centered"""
text_size = cv2.... |
#!/usr/bin/env python3
#############################################################################
##
## Copyright (C) 2018 The Qt Company Ltd.
## Contact: https://www.qt.io/licensing/
##
## This file is part of the plugins of the Qt Toolkit.
##
## $QT_BEGIN_LICENSE:GPL-EXCEPT$
## Commercial License Usage
## Licensee... |
import torch
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
__all__ = ['resnet']
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)
class... |
#!/usr/bin/env python3
# Copyright (c) the JPEG XL Project Authors. All rights reserved.
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
"""Produces demos for how progressive-saliency encoding would look like.
As long as we do not have a progressive decoder tha... |
"""
Contains Analyzer class responsible for the Analysis phase.
Contains CSPAnalyzer class, an implementation of Analyzer that uses constraint satisfaction problem to find a desired state.
"""
import logging
from typing import Optional, List
from multiprocessing import Pool
from multiprocessing.pool import AsyncResul... |
from aiotfm.errors import PacketError, PacketTooLarge, XXTEAInvalidPacket, XXTEAInvalidKeys
class Packet:
def __init__(self, buffer=None):
if buffer is None:
buffer = bytearray()
elif not isinstance(buffer, bytearray):
buffer = bytearray(buffer)
self.buffer = buffer
self.pos = 0
self.exported = Fals... |
from __future__ import division, print_function, unicode_literals
import six
import pyglet
from pyglet.gl import *
from cocos.director import director
from cocos.menu import *
from cocos.scene import Scene
from cocos.layer import MultiplexLayer, Layer
from cocos.actions import *
from cocos.sprite import Sprite
impor... |
### python lib
import os, sys, math, random, glob, cv2
import numpy as np
### torch lib
import torch
import torch.utils.data as data
### custom lib
import utils
class RandomCrop(object):
def __init__(self, image_size, crop_size):
self.ch, self.cw = crop_size
ih, iw = image_size
self.h1 =... |
import pandas as pd
import cv2
import os
from lxml.etree import Element, SubElement, ElementTree
from multiprocessing import Pool, cpu_count
image_source = '/kaggle/input/siim-covid19-resized-to-1024px-jpg'
def create_ann(ele):
ann_path = '../../dataset/siim-covid19-detection/labels/train/{}.xml'.format(ele.image... |
from datetime import datetime, timezone
from time import time
from flask import current_app, g
from flask.sessions import SecureCookieSessionInterface
from flask_ldap3_login import AuthenticationResponseStatus
from flask_login import login_user, logout_user
from itsdangerous import (TimedJSONWebSignatureSerializer
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.