text stringlengths 3.07k 12.6k |
|---|
#!/usr/bin/env python3
import re
from collections import Counter, OrderedDict
from flask import Flask
from flask import render_template
import sys
import os
from functools import wraps
from flask import request, Response
import json
# os.chdir('/path/where/app/is')
app = Flask(__name__)
filename = sys.argv[1]
def ... |
#!/usr/bin/env python
# 2018 / MIT / <NAME> / github.com/misterfifths
# See LICENSE for details
from __future__ import print_function
from sgp30 import SGP30, AirQuality
from threading import Thread, Timer
from smbus import SMBus
from sys import stderr
from os import path
from time import sleep, time
from blinky imp... |
#!/usr/bin/env python3
"""
Aggregate differently spelled entries in a column that represent the same entity
"""
import csv
import numpy as np
import json
import pandas as pd
import pdb
from collections import Counter
import sys
import os
from distances import *
frst_thresh = 0.95
scnd_thresh = 0.75
scnd_gap = 0.9
fr... |
from typing import Iterable, Union, List
from collections import deque
import re
from .utils import (
is_empty,
is_char_hiragana,
is_char_katakana,
is_char_japanese,
is_char_kana,
is_char_kanji,
is_char_romaji,
is_char_english_punctuation,
is_char_japanese_punctuation,
)
def is_hir... |
import os
from flask import Flask, session, render_template, request, flash, redirect, url_for, jsonify
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess secure key'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# setup SQLAlchemy
basedir = os.path.abspath(o... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Normalize effect sizes for ATACseq
Created: 2016-47-26 13:09
Last modified: 2016-09-26 17:45
"""
import os
import sys
import argparse
from time import sleep
from multiprocessing import Pool
import numpy as np
import pandas as pd
import cluster
############... |
#!/usr/bin/env python
# coding: utf-8
# # Stability of Linear Homogeneous ODEs
#
# **<NAME>, PhD**
#
# This demo is based on the original Matlab demo accompanying the <a href="https://mitpress.mit.edu/books/applied-computational-economics-and-finance">Computational Economics and Finance</a> 2001 textbook by <NAME> ... |
# -*- coding: utf-8 -*-
"""
sphinx.ext.errors
~~~~~~~~~~~~~~~~~
Collect all errors
:copyright: Copyright 2007-2009 by the <NAME>, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from docutils import nodes
from sphinx.locale import _
from sphinx.environment import NoUri
from sphinx.util.... |
from codecs import open
from datetime import date
from datetime import datetime
import os
import requests
import sys
import time
import lichess.api
from lichess.format import JSON
CHESSCOM_URL_TEMPLATE = 'https://api.chess.com/{}'
LICHESS_URL_TEMPLATE = 'https://lichess.org/api/{}'
# chess.com
# Helper functions
d... |
import os
import pandas as pd
def analyze_folds(folds: pd.DataFrame, dirty_subset: pd.DataFrame):
unique_items_in_file = []
for i, (_, row) in enumerate(folds.iterrows()):
train_pos, train_neg = row["train_pos"].split(" "), row["train_neg"].split(" ")
test_pos, test_neg = row["test_pos"].spl... |
import sys
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import roc_auc_score
from sklearn.metrics import roc_curve
import... |
import inspect
import os
import sys
def _colored_string(string: str, color: str or int) -> str:
"""在终端中显示一串有颜色的文字
:param string: 在终端中显示的文字
:param color: 文字的颜色
:return:
"""
if isinstance(color, str):
color = {
"black": 30, "Black": 30, "BLACK": 30,
"red": 31, "Re... |
### Copyright (c) 2021-2022, <NAME> ###
import sqlite3
import PySimpleGUI as sg
def imported(filename,namedb):
conn = sqlite3.connect(f"{namedb}")
cursor=conn.cursor()
with open(f"{filename}",encoding="utf8") as infile:
for line in infile:
data = line.split()
... |
# -*- coding: utf-8 -*-
import math
import nltk
import torch
import numpy as np
from nltk.translate.bleu_score import sentence_bleu
from nltk.translate.bleu_score import SmoothingFunction
from torch import cuda
import torch.nn as nn
import torch.nn.functional as F
from classifier.textcnn import collate_fn
device = ... |
#!/usr/bin/env python
import sys
from recorder import SwhRecorder
import signal
import math
import time
try:
from neopixel import Adafruit_NeoPixel, Color
has_pixels = True
except:
has_pixels = False
import pygame
# LED strip configuration:
LED_COUNT = 300 # Number of LED pixels.
LED_PIN ... |
import logging
import os
import re
from django.apps import apps
from django.template import loader
from django.template.loader import render_to_string
from .settings import ScaffoldGeneratorConfig
from .utils import FileTransaction
LOGGER = logging.getLogger(__name__)
def clean_model_fields(model_fields, scaffold_... |
# Author: <NAME> <<EMAIL>>
import copy
import os
from collections import OrderedDict
from typing import Tuple, List, MutableMapping
import joblib
import mne
import numpy as np
from braindecode.datautil.signalproc import exponential_running_standardize
from braindecode.datautil.trial_segment import create_signal_targ... |
'''An asynchronous multi-process `HTTP proxy server`_. It works for both
``http`` and ``https`` (tunneled) requests.
Managing Headers
=====================
It is possible to add middleware to manipulate the original request headers.
If the header middleware is
an empty list, the proxy passes requests and responses un... |
import sys
import json
import math
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
from matplotlib.font_manager import FontProperties
from numpy import arange, meshgrid
_GRAPH_DEFAULTS = {"xlabel":"$x$", "ylabel":"$y$", "num_ticks":5,
"axis_label_fontsize":"x-large", "tick_formats... |
from batou.component import Component
from batou.lib.file import File, Symlink, ensure_path_nonexistent
from io import StringIO
import hashlib
import os.path
import requirements
class VirtualEnv(Component):
namevar = 'python_version'
pip_version = None
def verify(self):
assert os.path.exists(sel... |
#!/usr/bin/env python
import requests
import json
import subprocess
import sys
from faker import Factory
import os
class Kibana(object):
def __init__(self, base_url):
assert base_url.startswith("http")
assert base_url[-1] != "/"
self.base_url = base_url
def _uri(self, path):
... |
#!/usr/bin/env python3
import hashlib
import hmac
import os
import random
import struct
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric.rsa import _modinv as modinv # type: ignore
from cryptography.hazma... |
"""
*****************************************************************************
*
H E A D E R I N F O R M A T I O N *
*
****... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/CommunicationRequest) on 2019-05-07.
# 2019, SMART Health IT.
from . import domainresource
class CommunicationRequest(domainresource.DomainResource):
""" A request for information to ... |
#!/usr/bin/env python
"""Show the content of DeepCpG data files.
Shows the content of ``dcpg_data.py`` output files for a selected region, for
example the methylation state of the target CpG site, neighboring CpG sites, or
the DNA sequence.
Examples
--------
Show the output methylation state of CpG sites on on chrom... |
from urllib.request import urlopen
from statistics import mean
from datetime import date, timedelta
import re
import csv
import os
# Temperature at 900 can contain multiple temperatures, eg -2C rising to 1C
# I want average for the day, so use get ints_from_string() and get_average_int()
def get_ints_from_string(strin... |
'''
Code to dress SMPL with registered garments.
Set the "path" variable in this code to the downloaded Multi-Garment Dataset
If you use this code please cite:
"Multi-Garment Net: Learning to Dress 3D People from Images", ICCV 2019
Code author: Bharat
Shout out to Chaitanya for intersection removal code
'''
from psb... |
from django.contrib.gis.db.models import MultiPolygonField, PointField
from django.db import models
from django.urls import reverse
from bibliography.models import Source
from brit.models import NamedUserObjectModel
TYPES = (
('administrative', 'administrative'),
('custom', 'custom'),
('nuts', 'nuts'),
... |
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from .models import User, Listing, Bid... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
from time import time
import pandas as pd
from numpy import arange
results_df = pd.read_csv('../data/botbrnlys-rand.csv')
def extract_best_vals_index(results_df, df, classifier, hp):
final_df = pd.DataFrame()
temp_df = results_df[results_df.model == classifier]
temp_df_f = temp_df[temp_df.hp.round(3) == ... |
#
# Attempt to analyse a dblatex failure occured on a Debian platform.
#
# Author: <NAME>
#
import subprocess
import sys
import apt
from dbtexmf.core.error import ErrorHandler
from dbtexmf.core.imagedata import ImageConverter
from dbtexmf.core.dbtex import DbTex
class AptSilentProgress(apt.progress.text.OpProgress):
... |
"""
fprime.fbuild.settings:
An implementation used to pull settings into the fprime build. This version uses INI files in order to load the
settings from the settings.default file that is part of the F prime deployment directory.
@author mstarch
"""
import os
import configparser
from typing import Dict, List
from pa... |
"""Code to support homekit_controller tests."""
from datetime import timedelta
import json
import os
from unittest import mock
from aiohomekit.model import Accessories, Accessory
from aiohomekit.model.characteristics import CharacteristicsTypes
from aiohomekit.model.services import ServicesTypes
from aiohomekit.testin... |
import logging
import os
import torch
from tensorboardX import SummaryWriter
import NVLL.argparser
from NVLL.util.gpu_flag import device
def set_seed(args):
torch.manual_seed(args.seed)
if device == torch.device("cuda"):
torch.cuda.manual_seed(args.seed)
def set_save_name_log_nvdm(args):
args.... |
import unittest
from robot.utils.asserts import assert_equal
from robot.utils.misc import printable_name, seq2str, roundup
class TestRoundup(unittest.TestCase):
def test_basics(self):
for number in range(1000):
for extra in range(5):
extra /= 10.0
assert_equal... |
# coding: utf-8
# Code based on https://github.com/keithito/tacotron/blob/master/models/tacotron.py
import tensorflow as tf
from tensorflow.contrib.rnn import GRUCell
from tensorflow.python.layers import core
from tensorflow.contrib.seq2seq.python.ops.attention_wrapper import _bahdanau_score, _BaseAttentionMechanism, ... |
# pip install fhem
# pip install kivy
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from thread import start_new_thread
from kivy.properties import StringProperty
import json
try:
import queue # Python 3.x
except:
import Queue as queue # Py... |
##############################################################################
#
# Copyright (c) 2004 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... |
from __future__ import unicode_literals
import logging
import re
import socket
from mopidy.utils import path
from mopidy.config import validators
def decode(value):
if isinstance(value, unicode):
return value
# TODO: only unescape \n \t and \\?
return value.decode('string-escape').decode('utf-8'... |
import numpy as np
import os
import threading
import gym
if 'MUJOCO_RENDERER' in os.environ:
RENDERER = os.environ['MUJOCO_RENDERER']
else:
RENDERER = 'glfw'
def get_device_id():
return int(os.environ.get('GL_DEVICE_ID', 0))
def set_camera(cam, azimuth=None, elevation=None, distance=None, lookat=None):
""" ... |
import torch
import numpy as np
import torch.nn as nn
'''
The main code is LMC
'''
def normalize_keypoints(kpts, image_shape):
height, width = image_shape[1],image_shape[0]
one = kpts.new_tensor(1)
size = torch.stack([one*width, one*height,one*width, one*height])[None]
center = size / 2
... |
import numpy as np
from optimizers import SGD
class Model(object):
"""
An abstract class that represents a machine learning model.
"""
def __init__(self):
pass
def __call__(self, X, *args, **kwargs):
return self.forward(X, *args, **kwargs)
def forward(self, X, tr... |
import re
import os
import json
import glob
from urllib.parse import quote
from urllib.request import urlopen
import subprocess
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--production', action='store_true')
parsed_args = parser.parse_args()
DEVELOPMENT = not parsed_args.production
F... |
# -*- encoding: utf-8 -*-
"""
GLM solver tests using Kaggle datasets.
:copyright: 2017 H2O.ai, Inc.
:license: Apache License Version 2.0 (see LICENSE for details)
"""
import time
import copy
import sys
import os
import numpy as np
import pandas as pd
import logging
print(sys.path)
from h2o4gpu.util.testing_utils i... |
#@title Imports
import os
from io import BytesIO
import tarfile
import tempfile
from six.moves import urllib
from matplotlib import gridspec
from matplotlib import pyplot as plt
import numpy as np
from PIL import Image
import tensorflow as tf
class DeepLabModel(object):
"""Class to load deeplab model and run infe... |
import featureflow as ff
import zounds
import numpy as np
from torch import nn, optim
from random import choice
import argparse
class Layer(nn.Module):
"""
A single layer of our simple autoencoder
"""
def __init__(self, in_size, out_size):
super(Layer, self).__init__()
self.linear = n... |
import os
import sys
import asyncio
import argparse
import aiohttp
import aiofiles
from typing import List, Tuple, Optional
from timeit import default_timer as timer
from datetime import timedelta
def read_image_ids(image_ids_filepath: str) -> List[int]:
image_ids = []
with open(image_ids_filepath, "r") as ... |
"""Get Sentinel-1 orbit file(s) from ASF or ESA website"""
import argparse
import logging
import os
import re
import sys
from datetime import datetime
import requests
from lxml import html
from requests.adapters import HTTPAdapter
from six.moves.urllib.parse import urlparse
from urllib3.util.retry import Retry
from ... |
# -*- coding: utf-8 -*-
u"""Simulation schema
:copyright: Copyright (c) 2018 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
from pykern import pkcollections
from pykern import pkconfig
from pykern impor... |
import database.paste
import models
import util.cryptography
import util.string
from modern_paste import login_manager
from modern_paste import session
from util.exception import *
def create_new_user(username, password, signup_ip, name=None, email=None):
"""
Creates a new user with the specified username and... |
#/usr/bin/env python
# -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright (c) 2015 <NAME> <<EMAIL>>
#
# 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 ... |
"""This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license.
"""
import os
import io
import sys
import json
import logging
import pandas as pd
import posixpath
import mimetypes
from pathlib import Path
from djan... |
import re
import random
import numpy as np
import os.path
import scipy.misc
import shutil
import zipfile
import time
import tensorflow as tf
from glob import glob
from urllib.request import urlretrieve
from tqdm import tqdm
class DLProgress(tqdm):
last_block = 0
def hook(self, block_num=1, block_size=1, tota... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
# coding=utf-8
# Copyright Huawei Noah's Ark Lab.
# 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/l... |
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn import svm, metrics
from BELM.belm import BELM
def plm_train(data, target, label, n, s1, s2, c, acc=None):
""" Progressive learning implementation"""
gamma = 0.01 + 1 * 0.005
nnet4 = []
var = s2
train_data = []
... |
import json
import hdbscan
import pandas as pd
import joblib
import os
from ad_model.processing import preprocess
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
# Ranges for input features based on excellent, good,... |
import os
import typing as tp
from datetime import datetime
from typing import Any, Generator, Mapping, Tuple
import haiku as hk
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numpy as np
import optax
import typer
from datasets.load import load_dataset
from tensorboardX.writer import Summary... |
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. 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 requir... |
# Copyright 2022 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 or agreed to in writing, sof... |
import torch
from torch import nn, Tensor
from ..._internally_replaced_utils import load_state_dict_from_url
from ...ops.misc import ConvNormActivation, SqueezeExcitation
from ..mobilenetv3 import InvertedResidual, InvertedResidualConfig, MobileNetV3,\
model_urls, _mobilenet_v3_conf
from torch.quantization import Q... |
import pytest
from geomeppy.geom.surfaces import get_adjacencies
from geomeppy.geom.surfaces import set_coords
@pytest.fixture
def shadow_intersecting():
shadow_blocks = [
{
"name": "PN1001_Bld1004_EL24",
"coordinates": [
(-83635.2890999997, -100958.99369999953),
... |
#! /usr/bin/env python
# coding=utf-8
#
# Copyright © 2017 <NAME> <<EMAIL>>
#
# Distributed under terms of the MIT license.
#
# Based on the code of Ulf Astrom (http://www.happyponyland.net)
from camogen.polygon import *
from camogen.pattern import *
from camogen.helpers import *
from PIL import Image, ImageDraw
d... |
#!/usr/bin/python
#
# cachestat Count cache kernel function calls.
# For Linux, uses BCC, eBPF. See .c file.
#
# USAGE: cachestat
# Taken from funccount by <NAME>
# This is a rewrite of cachestat from perf to bcc
# https://github.com/brendangregg/perf-tools/blob/master/fs/cachestat
#
# Copyright (c) 2... |
from ij import IJ, WindowManager
from ij.gui import Toolbar
from time import sleep
w = 40
h = 40
def setColor(color):
IJ.run('Colors...', 'foreground=' + color)
def square(i, j, currentX, currentY):
IJ.runMacro('makeRectangle(' + str(w * i) + ', '
+ str(h * j) + ', '
+ str(w) + ', ' + str(h) + ');')
if i == ... |
import errno
import os
import torch
import tensorflow as tf
def decide_metric(dataset):
if dataset in ['BACE_classification', 'BBBP', 'ClinTox', 'SIDER']:
return 'roc_auc'
elif dataset in ['BACE_regression', 'Delaney', 'HOPV', 'Lipo', 'PDBbind']:
return 'rmse'
else:
return ValueError('Unexpected dat... |
from os import path
from tree_sitter import Language, Parser
from pathlib import Path
import glob, os
import numpy as np
import logging
import platform
import tree_sitter_parsers
import re
import pickle
import json
from tqdm import tqdm
class ASTParser():
import logging
LOGGER = logging.getLogger('ASTParser')... |
import json
import numpy as np
import sys
import matplotlib
from PyQt4 import QtGui, QtCore, Qt
from PyQt4.QtCore import pyqtSignal
matplotlib.use('Qt4Agg')
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as ... |
import numpy as np
def normed_timing_matrix(Mmat):
"""
Normalize the timing design matrix
"""
norm = np.sqrt(np.sum(Mmat ** 2, axis=0))
nmat = Mmat / norm
nmat[:, norm == 0] = 0
return nmat
def power_law(params, freqs, ref_freq=3.168808781402895e-08, repeats=2):
"""
default ref... |
# -*- coding: utf-8 -*-
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2020 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 ARRANTI... |
import cv2
import numpy as np
import copy
import math
#from appscript import app
# Environment:
# OS : Mac OS EL Capitan
# python: 3.5
# opencv: 2.4.13
# parameters
cap_region_x_begin=0.5 # start point/total width
cap_region_y_end=0.8 # start point/total width
threshold = 60 # BINARY threshold
blurValue = 41 ... |
import ast as python_ast
from typing import (
Generator,
)
import asttokens
import vyper.ast as vyper_ast
from vyper.exceptions import (
CompilerPanic,
ParserException,
SyntaxException,
)
from vyper.parser.parser_utils import (
annotate_ast,
)
from vyper.parser.pre_parser import (
pre_parse,
)... |
import warnings
from django.contrib.postgres.indexes import OpClass
from django.db import NotSupportedError
from django.db.backends.ddl_references import Expressions, Statement, Table
from django.db.models import Deferrable, F, Q
from django.db.models.constraints import BaseConstraint
from django.db.models.expressions... |
import json
import os
import re
import socket
import sys
from codecs import encode, decode
from . import shared
dir_path = os.path.dirname(os.path.realpath(__file__))
tlds = None
dble_ext_str = "chirurgiens-dentistes.fr,in-addr.arpa,uk.net,za.org,mod.uk,org.za,za.com,de.com,us.com,hk.org,co.ca," \
"a... |
# coding=utf-8
# Copyright 2019 The Google AI Language Team 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 ... |
# Copyright 2012 OpenStack Foundation
# 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 requ... |
# type: ignore
import io
import logging
import os
import pickle
import torch
from torch._C._distributed_c10d import ProcessGroup
_pickler = pickle.Pickler
_unpickler = pickle.Unpickler
logger = logging.getLogger(__name__)
if torch.distributed.is_available():
from torch.distributed import Backend, broadcast, g... |
from . import assert_match, NamedTensor, contract, build, ntorch
import numpy as np
import torch
from collections import OrderedDict
import torch.nn.functional as F
import pytest
def make_tensors(sizes):
return [build(torch.randn, sizes)]
def test_shift():
for ntensor in make_tensors(dict(alpha=10, beta=2, g... |
#!/usr/bin/env python
#
# SPDX-License-Identifier: MIT
"""
Given a CVAT XML and a directory with the image dataset, this script reads the
CVAT XML and writes the annotations in PASCAL VOC format into a given
directory.
This implementation supports both interpolation tracks from video and
annotated images. If it enco... |
import os
from rpython.rlib.debug import have_debug_prints
from rpython.rlib.debug import debug_start, debug_stop, debug_print
from rpython.rlib.objectmodel import we_are_translated
from rpython.rtyper.lltypesystem import lltype, llmemory, rffi
from rpython.jit.metainterp.resoperation import rop
from rpython.jit.metain... |
import pickle
from .. import turkish
from ...datasources import revision_oriented
from ...dependencies import solve
from .util import compare_extraction
BAD = [
"<NAME>", "<NAME>",
"ahlaksız",
"ahmak",
"allahsız",
"am", "amcık",
"amk", "amq",
"amın oğlu",
"amına", "amına koy", "amına ... |
#!@python36@/bin/python
import tempfile
from contextlib import contextmanager
import subprocess
import os
import stat
import shutil
import argparse
VERSION = "@version@"
TESTING_SYSTEM_TOP_LEVEL = "@testingToplevel@"
DISK = "@disk@"
OVMF = "@ovmf@"
# Tools
BINDFS_BIN = "@bindfs@/bin/bindfs"
QEMU_SYSTEM_X86_64 = "@qe... |
import socket
import struct
import os
# import spidev
from multiprocessing import Process, Value, Array, Lock
from time import perf_counter
# TODO:
# Add support of python-can lib
# Add different hardware devices
# can-hacker
#
# Rename CAN_Bus - to CANSocket
# Implement the object with 5 virtual
# rPyCAN
#
cl... |
# coding: utf8
from __future__ import division, print_function, unicode_literals
from .gold import tags_to_entities, GoldParse
class PRFScore(object):
"""
A precision / recall / F score
"""
def __init__(self):
self.tp = 0
self.fp = 0
self.fn = 0
def score_set(self, cand,... |
from __future__ import unicode_literals
import logging
import os.path
import sys
from pre_commit.util import cmd_output
from pre_commit.util import cmd_output_b
logger = logging.getLogger(__name__)
def zsplit(s):
s = s.strip('\0')
if s:
return s.split('\0')
else:
return []
def no_git... |
import numpy as np
import torch
import torch.nn as nn
from ...builder import SEGMENTAL_CONSENSUSES
def parse_stage_config(stage_cfg):
if isinstance(stage_cfg, int):
return (stage_cfg,), stage_cfg
elif isinstance(stage_cfg, tuple) or isinstance(stage_cfg, list):
return stage_cfg, sum(stage_cfg... |
import pytest
import genet.utils.dict_support as dict_support
from tests.fixtures import assert_semantically_equal
def test_set_nested_value_overwrites_current_value():
d = {'attributes': {'some_osm_tag': 'hello'}}
value = {'attributes': {'some_osm_tag': 'bye'}}
return_d = dict_support.set_nested_value(d,... |
################################################################################
# Copyright (c) 2017-2020, National Research Foundation (Square Kilometre Array)
#
# Licensed under the BSD 3-Clause License (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy
# of the... |
#! /usr/bin/env python
# This file is part of khmer, https://github.com/dib-lab/khmer/, and is
# Copyright (C) 2010-2015, Michigan State University.
# Copyright (C) 2015-2016, The Regents of the University of California.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitte... |
import numpy as np
from numpy.testing import (assert_array_equal, assert_array_almost_equal,
assert_almost_equal, assert_equal)
from nose.tools import assert_raises
from pystruct.models import GraphCRF
from pystruct.inference import get_installed
w = np.array([1, 0, # unary
... |
"""
Fishbone definition module
"""
import math
import fishbone_diagram_generator.const as const
class Rect():
""" Rectangle definition class """
def __init__(self, x, y, w, h):
self.pos = [x, y]
self.size = [w, h]
def get_str(self):
return '(x,y) = (' + str(self.pos[0]) + ',' + st... |
import re
import os
cedict_syntax = re.compile(
r"\A(?P<traditional>\S+)\s+(?P<simplified>\S+)\s*"
r"\[(?P<pinyins>.+?)\]\s*/(?P<translations>.+)/?\Z"
)
accents = list(map(lambda s : s[:-1], ["̄ ", "́ ", "̌ ", "̀ "]))
def accentuate(pinyin):
parts = pinyin.split(" ")
last_accent = ""
for i in ran... |
import configparser
import datetime
import logging
import os
import sys
from py_jama_rest_client.client import JamaClient
logger = logging.getLogger(__name__)
def init_logging():
try:
os.makedirs('logs')
except FileExistsError:
pass
current_date_time = datetime.datetime.now().strftime("%... |
import tensorflow as tf
import os
import time
import math
import pandas as pd
import numpy as np
from ast import literal_eval
from sklearn.utils import shuffle
from sklearn.metrics import *
from tensorflow.keras import Sequential
from tensorflow.keras.layers import *
from tensorflow.keras import backend as K
import sql... |
"""
Function,
Extract detail information of each Movie / TV show by reading the scraped movie/tv show title table.
#########################
routing pattern,
domain: https://reelgood.com
tv shows: /show
movie: /movie
"""
import os, sys
import json
import re
from typing import Iterable
# Helper
from help... |
# -*- coding: utf-8 -*-
"""Methods for writing needed `CalcJob` input files."""
from io import StringIO
from phonopy import Phonopy
from phonopy.structure.cells import get_supercell
from phonopy.structure.dataset import forces_in_dataset
from phonopy.interface.phonopy_yaml import PhonopyYaml
from phonopy.file_IO impor... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import sys
import contextlib
from unittest.mock import patch
import numpy as np
import nevergrad.common.typing as tp
from... |
#! /usr/bin/env python
import rospy
from pkg_vb_sim.srv import conveyorBeltPowerMsg
from pkg_vb_sim.srv import conveyorBeltPowerMsgRequest
from pkg_vb_sim.srv import conveyorBeltPowerMsgResponse
from pkg_vb_sim.srv import ConveyorBeltControl
from pkg_vb_sim.srv import ConveyorBeltControlRequest
from pkg_vb_sim.srv i... |
# -*- coding: utf-8 -*-
# Copyright 2011 OpenStack Foundation.
# 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/LICE... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.