text stringlengths 3.07k 12.6k |
|---|
import xml.etree.ElementTree as ET
from ..dictionary import Dictionary
from ..constants import SINGLE_AXIS_MINIMUM_SUBNODES
from .register import CanopenRegister, REG_ACCESS, REG_DTYPE
from ingenialink.utils._utils import *
from .._ingenialink import lib
class CanopenCategories:
"""Contains all categories from a ... |
import json
import logging
from agent.config import EMPTY_JSON_DATACITE
logger = logging.getLogger(__name__)
def text_processor(meta, data):
rows = data.split('\n')
adict = dict()
for row in rows:
# print(row)
row = row.strip()
if row.startswith('GROUP'):
continue
... |
from matrix import *
def split(t):
"""
Split a matrix into 4 squares
"""
midRow = int(t.rows/2)
midCol = int(t.cols/2)
topLeft = t.subMatrix(0, 0, midRow - 1, midCol - 1)
topRight = t.subMatrix(0, midCol, midRow - 1, t.cols - 1)
bottomLeft = t.subMatrix(midRow, 0, t.rows - 1, midCol - 1... |
from __future__ import annotations
import enum
from builtins import bool
from typing import NamedTuple
import math
class Line(NamedTuple):
origin: complex
offset: complex
@staticmethod
def from_to(origin: complex, end: complex) -> Line:
return Line(origin, end - origin)
@property
d... |
"""
Module with interface and default configurations for the used clustering algorithms
"""
import os
import subprocess
from warnings import warn
import numpy as np
from sklearn.cluster import KMeans, DBSCAN, SpectralClustering, AgglomerativeClustering
from sklearn.metrics import pairwise_distances
# from excut.mis... |
"""
@Author: <NAME>
Student ID: 692277
Description: Functions in this file will process AURIN data (csv) and save it to CouchDB
"""
import sys
sys.path.append('../')
from couchDbHandler import CouchDB
from api.toolFunc import *
import re
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import TweetTok... |
"""
This script generates anchor boxes for a custom dataset. It will generate:
+ an anchor text file (depending on number of anchors, default = 5)
Example usage:
-------------
python anchor_boxes.py
--path /path/to/dataset.hdf5
--output_dir ./
--num_anchors 5
"""
import os
import csv
import numpy as np
im... |
import json
import re
from operator import itemgetter
from selenium.webdriver.support.ui import Select
# Configuration
verbose = False
delay = 0
last_request = 0
output_filename = 'disciplines.json'
# Regular expression to get course codes and faculties
regex_courses = re.compile(r'<a.*?>([A-Z]{3}[0-9]{4}.*?)<\/a>.*?... |
import torch
import torch.nn.functional as F
from layers import Linear, LayerNorm
from .multi_head_attention import MultiHeadAttention, AttentionMask
from typing import Optional, Callable, Dict
from dataclasses import dataclass
# This file is based on PyTorch's internal implementation
ActivationFunction = Callable[[to... |
import random
import pyglet
from pyglet.window import key, FPSDisplay
from pyglet.resource import image
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
pyglet.resource.path = ['../resources']
pyglet.resource.reindex()
head_image = image('head.png')
body_image = image('body.png')
food_image = image('food.png')
images = [head_... |
import io
import json
import math
import os
import shutil
import tarfile
import tempfile
import time
from falcon import Request
from pathlib import Path
from toolz import curry, do
from toolz import excepts
from typing import Iterator, List, Union
from uuid import UUID
# Converts a string to an int safely, default is ... |
# -*- coding: utf-8 -*-
#------------------------------------------------------------------------------
# file: $Id$
# auth: <NAME> <<EMAIL>>
# date: 2016/10/05
# copy: (C) Copyright 2016-EOT Canary Health, Inc., All Rights Reserved.
#------------------------------------------------------------------------------
impor... |
import os
import pickle
import h5py
import numpy as np
import tensorflow as tf
from scipy.io import loadmat
from lymph.vgg19 import net
def gen_labels(parent_folder: str):
# 生成文件路径
path_1 = os.path.join(parent_folder, "allLabels1.mat")
path_2 = os.path.join(parent_folder, "allLabels2.mat")
out_path ... |
# Copyright 2013 Google Inc. 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 applicable law or ... |
#!/usr/bin/env python
"""Tests for the tulip.spec subpackage."""
from __future__ import print_function
import logging
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('ltl_parser_log').setLevel(logging.ERROR)
import nose.tools as nt
from tulip.spec import ast, lexyacc
from tulip.spec.parser import parse
de... |
#import library
from __future__ import absolute_import, print_function
from http.client import IncompleteRead
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import time
import json
from generate_graph import create_graph
#from window_reservoir_sampling_edges import... |
from tkinter import *
from tkinter.messagebox import *
def label(parent, text_label, x=0, y=0):
label_tables = Label(parent,text=text_label).grid(row=x, column=y)
def text(parent, text, x=0, y=0, height=2, width=30):
text_to_display = Text(parent,height=height, width=width)
text_to_display.insert(... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:
from easyai.base_name.backbone_name import BackboneName
from easyai.base_name.block_name import NormalizationType, ActivationType
from easyai.base_name.block_name import LayerType
from easyai.model.backbone.utility.base_backbone import *
from easyai.model.base_blo... |
# pylint: disable=not-callable
# pylint: disable=no-member
"""
Computes FEP rewards that are environment specific.
"""
import torch
from torch.optim import Adam
import torch.nn as nn
from torch.distributions import Normal
class CondDensityModel(nn.Module):
def __init__(self, node_size, num_states, num_g, act_f... |
#! /usr/bin/env python
import extargsparse
import sys
import os
import zlib
import hashlib
import sha3
import re
from Crypto.Cipher import AES
##importdebugstart
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)),'..','..','src'))
from strparser import *
##importdebugend
def read_bytes(infile):
... |
import numpy as np
import os
import pandas as pd
import tensorflow as tf
import skimage.transform as sktransform
import random
import matplotlib.image as mpimg
import shutil
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Conv2D, Dense, MaxPool2D, Dropout, Flatten, Lambda
fr... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""tools.py
Provides useful functions for the pdp.py script
- config: interact with config files
- prodigal: run prodigal bacterial gene prediction
- eprimer3: predict primers with EMBOSS ePrimer3
- primersearch: run in-silico hybridisation with EMBOSS ... |
from django.contrib import admin
from django.utils.html import format_html, format_html_join
from django.utils.http import urlquote
from bursary.models import Bursary, BursaryReferee
class BursaryRefereeInline(admin.TabularInline):
model = BursaryReferee
class BursaryAdmin(admin.ModelAdmin):
list_display =... |
#!/usr/bin/env python3
import argparse
import json
import os
import logging
from functools import singledispatch
from typing import List
import numpy as np
import pandas as pd
import gensim
import gensim.corpora as corpora
from gensim.models import CoherenceModel
import pyLDAvis.gensim
LOGGER = logging.getLogger(__... |
# Copyright 2011,2012 <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,... |
"""
# http://bookshadow.com/weblog/2017/09/24/leetcode-k-empty-slots/
LeetCode 683. K Empty Slots
There is a garden with N slots. In each slot, there is a flower. The N flowers will bloom one by one in N days. In each day, there will be exactly one flower blooming and it will be in the status of blooming since then.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
from urllib.parse import urlsplit
from urllib.request import urlopen
from urllib.error import HTTPError, URLError
import ssl
import time
from girder import logger
from ..constants import API_VERSION, NotebookStatus, PluginSettings
from girder.constants imp... |
#!/usr/bin/env python
"""Selectively migrate supplier information from a recent framework declaration to new fields on supplier itself
Usage:
scripts/oneoff/migrate-supplier-data-from-declarations.py <stage> <data_api_token> <ch_api_token> <framework_slugs>
[<user>] [--dry-run]
Positional arguments:
<... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Gamut変換の特性を調べる。
"""
# 外部ライブラリのインポート
import os
import numpy as np
import matplotlib.pyplot as plt
# 自作ライブラリのインポート
import test_pattern_generator2 as tpg
import color_space as cs
import transfer_functions as tf
from CalcParameters import CalcParameters
import plot_utili... |
#! -*- coding:utf-8 -*-
# qt sim 任务训练:冻结部分层数,最后做cosin
import sys
import os
import numpy as np
import tensorflow as tf
from bert4keras.backend import keras
from bert4keras.backend import keras, set_gelu, search_layer, K
from bert4keras.tokenizers import Tokenizer
from bert4keras.models import build_transformer_model
fro... |
# -*- coding: utf-8 -*-
"""
Code from https://github.com/LeeJunHyun/Image_Segmentation
@author: jpeeples
"""
import torch
import torch.nn as nn
from .unet_parts import *
import pdb
class Attention_block(nn.Module):
def __init__(self,F_g,F_l,F_int):
super(Attention_block,self).__init__()
self.W_g = ... |
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
''' IMPORTS '''
import urllib3
import csv
# disable insecure warnings
urllib3.disable_warnings()
SOURCE_NAME = 'CSV Feed Integration'
class Client(BaseClient):
def __init__(self, url: str, fieldnames: str, insec... |
from flask_restful import marshal_with, reqparse
from flask import abort, g
from flask import Blueprint as FlaskBlueprint
from flask_restful import fields
from sqlalchemy.orm.session import make_transient
import logging
import uuid
from pebbles.models import db, BlueprintTemplate, Plugin
from pebbles.forms import Blu... |
import os
import json
import time
import threading
import rospy
from std_msgs.msg import String
from lg_msg_defs.msg import WindowGeometry
from appctl_support import ProcController
from lg_msg_defs.msg import ApplicationState
from lg_msg_defs.srv import MediaAppsInfoResponse
from lg_common.helpers import get_app_insta... |
### python >= 3.7
# -*- coding: utf-8 -*-
"""
flask_app/text_cover/text_cover.py
Last updated: 2020-01-26
Flask Blueprint for text report cover sheets
=+LICENCE=============================
Copyright 2019-2020 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file e... |
# Copyright (c) 2020 PaddlePaddle 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 appli... |
#!/usr/bin/env python
"""Inspect plugins, create a JSON describing all the data."""
from __future__ import unicode_literals, print_function
import codecs
from contextlib import contextmanager
import glob
import json
import os
import subprocess
import colorama
import pygments
from pygments.lexers import PythonLexer
f... |
import logging
from json import JSONEncoder
import requests
import urllib3
from requests.exceptions import ConnectionError
logger = logging.getLogger(__name__)
class FeeEstimationResult:
"""A tiny object to pass the Fee Estimation Results around including a list of errors which might have occured"""
def __... |
from flask import Flask, request
import telebot
import os
from telebot import types
import time
#token position and bot declaration
token = 'api_code'
server = Flask(__name__)
bot = telebot.TeleBot(token)
bot.settings = dict()
bot.buffers = dict()
#handlers
@bot.message_handler(commands=['start'])
def start(message)... |
#!/usr/bin/env python
from __future__ import print_function
import sys
import os
import re
import datetime
import hashlib
import random
import numpy as np
import keras
from keras.layers import Input, Embedding, Dense, Dropout
from keras.layers import LSTM, GRU
from keras.optimizers import Adam
from keras.preprocessing... |
import os
import datetime
import json
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, Template
from django.views.decorators.csrf import ensure_csrf_cookie
import pytz
import requests
from geopy.distance import vincenty
# declare global variables
loc... |
import os
import re
import subprocess
import sys
# To use DEFAULT path values:
# Juliet folders' content and info.py location - Goblint/analyzer/tests/juliet
goblint_path = '../../goblint' # DEFAULT
testsupport_path = 'testcasesupport' # DEFAULT
path = './testcases/CWE366_Race_Condition_Within_Thread' # Will be change... |
# flake8: noqa: W503
from __future__ import annotations
import logging
from typing import Any, Dict
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.db.models import Q
from django.http import Ht... |
def _parse_section(text, section, unwrap=True):
"""Extract the content of a section
Args:
text: the text version of the security note
section: the section name to extract
unwrap: defines if we should remove line-wrapping
Returns:
a list of paragraphs within the section
"""
#... |
import math
def STR(a):
# Yes, this is a little bit silly :-)
for i in range(0, len(a) - 1, 2):
print((chr(int(a[i:i+2]))), end=' ')
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, ... |
"""
Copyright (c) 2020 <NAME>. All Rights Reserved.
Released under the MIT license
"""
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import _pair
class ConvLSTMCell(nn.Module):
def __init__(self, in_channels, hidden_channels,
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pygame
from pygame.locals import *
import time
import os
os.environ["SDL_FBDEV"] = "/dev/fb1"
os.environ["SDL_MOUSEDEV"] = "/dev/input/touchscreen"
os.environ["SDL_MOUSEDRV"] = "TSLIB"
hmi_state = 0
HOME_STATE = 0
PRVIEW_STATE = 1
# for GUI from here------
pygame.ini... |
import re
import os
import math
import time
import socket
import tarfile
import requests
import datetime
from pathlib import Path
from contextlib import closing
from lyrebird.log import get_logger
logger = get_logger()
def convert_size(size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "K... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expec... |
#!/usr/bin/env python3
"""
Rescores words-as-classifier scores using sequence prediction
Uses data generated by "structural_model_weighting_trainer.py".
"""
__author__ = "<NAME> <<EMAIL>>"
__copyright__ = "Copyright 2017 <NAME>"
__license__ = "Apache License, Version 2.0"
import argparse
import random
import sys
i... |
import pytest
from lowball_ad_auth_provider import ADAuthProvider, ADAuthPackage
from lowball_ad_auth_provider.auth_provider import Server, Connection, Tls, NTLM
import lowball_ad_auth_provider
from unittest.mock import Mock, PropertyMock
import json
@pytest.fixture
def basic_ad_auth_provider():
authp = ADAuthPro... |
from tensorflow.python.ops import nn_ops, gen_nn_ops
import tensorflow as tf
class MNIST_NN:
def __init__(self, name):
self.name = name
def __call__(self, X, reuse=False):
with tf.variable_scope(self.name) as scope:
if reuse:
scope.reuse_variables()
... |
import numpy as np
import scipy.signal
import tensorflow as tf
import imageio
import os
from ACNetwork import ACNetwork
class Trainer():
def __init__(self, settings, sess, number, coord, globalEpisodes):
self.settings = settings
self.coord = coord
self.sess = sess
self.name = 'tra... |
import os
import datetime
import calendar
import click
import logging
import numpy as np
import xarray as xr
import rioxarray as rioxr
from collections import defaultdict
from glob import glob
import admin.constants as const
from analysis.support import date_fmt
logger = ('snow_mapping')
def get_dates(start_year... |
"""Crawler to collect the papers"""
__author__ = "<NAME>, <NAME>"
from bs4 import BeautifulSoup
from urllib import request
import re
import logging
from confcrawler.util.util import pre_process_types, get_proper_siblings
logger = logging.getLogger("paper_crawler")
def extract_papers(papers_url=None, schedule_url=No... |
import argparse
import os
import re
import time
import numpy as np
from time import sleep
from datasets import audio
import tensorflow as tf
from hparams import hparams, hparams_debug_string
from infolog import log
from tacotron.synthesizer import Synthesizer
from tqdm import tqdm
def generate_fast(model, text):
mod... |
"""A pooled converter that behaves in very similar ways to convert_sub_dirs.py. Lower logging and stat print outs than
convert_sub_dirs.py. Useful for batch converting lower resolution video files that can't fully use all cores. """
import os
import sys
import time
from os import path
from .. import makeMedia... |
import numpy as np
import pytest
from nanomesh import MeshContainer, Mesher3D, TetraMesh, TriangleMesh
from nanomesh.image2mesh._mesher3d import BoundingBox, pad
@pytest.fixture
def image_cube():
from nanomesh import Volume
data = np.ones([10, 10, 10], dtype=int)
data[2:7, 2:7, 2:7] = 0
return Volu... |
def save():
ve = int(input("\nDeseja ver? (1 = SIM / 2 = NÃO): "))
if ve == 1:
print('\n')
ve = open('save.txt', 'r')
txtve = ve.read()
print(txtve)
ve.close()
print("Obrigado por jogar!")
sair1 = int(input("Digite um número menor que 10 para SAIR\n"))
... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 OpenStack 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/... |
from base64 import b64encode
import hashlib
import hmac
import json
from django import forms
from django.conf import settings
from django.contrib import messages
from django.core.exceptions import ImproperlyConfigured
from django.views.generic import TemplateView, View
from django.http import HttpResponse
from django.u... |
# -*- coding: utf-8 -*-
import os
import glob
import argparse
def make_argument_parser():
'''Returns argument parser for this script.
'''
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
description='''
This script adds links to e... |
"""Support for Rointe Climate."""
from __future__ import annotations
from datetime import timedelta
import logging
import async_timeout
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
HVAC_MODE_AUTO,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
PRESE... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
__email__ = "<EMAIL>"
import ddf_library.bases.config as config
from ddf_library.utils import read_stage_file
from pycompss.api.task import task
from pycompss.api.parameter import FILE_IN
from itertools import combinations
from collections import ... |
from dataclasses import dataclass
from typing import List, Union
from typing_extensions import Literal
class Dictable(object):
base = {}
@property
def dictionary(self):
return self.base
class FatherOfAQB(Dictable):
base = {}
def __init__(self, base=None):
if base: self.base = b... |
import random
import os
from PyQt5.QtWidgets import QDockWidget, QGraphicsScene, QGraphicsView, QGraphicsItem, QGraphicsLineItem, \
QGraphicsEllipseItem, QGraphicsTextItem, QLabel, QMessageBox, QGraphicsTextItem
from PyQt5.QtGui import QBrush, QPen, QColor, QFont
from PyQt5.QtCore import Qt, QLineF, QRectF
from ser... |
import logging
import os
from glob import glob
from shutil import copyfile
from subprocess import CalledProcessError, check_output
from tempfile import TemporaryDirectory
from zipfile import ZipFile
import rasterio
import requests
from stactools.nrcan_landcover.constants import (
COLOUR_MAP,
JSONLD_HREF,
... |
import numpy as np
def shift_mutation(perm):
"""
Performs a shift mutation on a permutation
"""
n = len(perm)
i = np.random.choice(n, 2, replace = False)
i = np.sort(i)
i0 = i[0]
i1 = i[1]
perm = np.concatenate((perm[i1:], perm[i0:i1], perm[:i0][::-1]))
return perm
def swap_m... |
import jwt
import json
import base64
import logging
import requests
from authlib.integrations.flask_client import OAuth
from servicelayer.extensions import get_entry_point
from authlib import jose
from aleph import settings
oauth = OAuth()
log = logging.getLogger(__name__)
AZURE_KEYS_URL = "https://login.microsoftonl... |
import numpy as np
import pytest
import math
from sklearn.base import clone
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestRegressor
import doubleml as dml
from ._utils import draw_smpls
from ._utils_irm_manual import fit_irm, boot_irm, tune_nuisance_irm
@pytest.fixtu... |
# Get Python six functionality:
from __future__ import\
absolute_import, print_function, division, unicode_literals
###############################################################################
###############################################################################
######################################... |
"""
author: <NAME>
date: 2019/10/23
des: implement utilities tool help model training
"""
import sys
sys.path.append('../')
import os
import time
import torch
import torch.nn as nn
from torch.optim.lr_scheduler import _LRScheduler
from torch.optim.lr_scheduler import ReduceLROnPlateau
class LabelSmoothSoftmax(nn.Modu... |
# Copyright 2017 Google Inc. 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 applicable law or a... |
"""
Test function to check if the methods declared in helper work as intended
"""
from unittest.mock import patch
import pytest
from gen_release_notes import generate
from gen_release_notes.helper import helper
sample_type_changes = ["env", "packer", "somemysteryvalue"]
sample_string_parsers = [
{
"key"... |
import json
import re
import subprocess
import socket
import contextlib
import io
import sys
import os
import platform
import time
import logging
import urllib.parse
from getpass import getpass
import argparse
# Trying to get this installed on Windows is agnonizing
# This might help: https://github.com/miniupnp/miniup... |
import numpy as np
import pytest
import math
from sklearn.base import clone
from sklearn.linear_model import Lasso, ElasticNet
import doubleml as dml
from ._utils import draw_smpls
from ._utils_plr_manual import fit_plr, boot_plr, tune_nuisance_plr
@pytest.fixture(scope='module',
params=[Lasso(),
... |
import unittest
import numpy as np
import torch
from pytorch_adapt.layers import MMDBatchedLoss, MMDLoss
from pytorch_adapt.layers.utils import get_kernel_scales
from .. import TEST_DEVICE
# from https://github.com/thuml/Xlearn/blob/master/pytorch/src/loss.py
def guassian_kernel(source, target, kernel_mul=2.0, ker... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import datetime
import decimal
import docker
import psycopg2 as py_psql
import psycopg2.extras
import pytest
import os
import sys
import subprocess
import time
import uuid
from helpers.cluster import ClickHouseCluster
psycopg2.extras.register_uuid()
SCR... |
# 唐诗生成
import collections
import os
import sys
import time
import numpy as np
import tensorflow as tf
# 这里引入可能出错
from models.model import rnn_model
# 句子预处理 产生batch函数
from dataset.fiction import process_poems, generate_batch
import heapq
# 后面那个是说明
tf.flags.DEFINE_integer('batch_size', 64, 'batch size.')
tf.flags.DEFINE... |
# Copyright (C) 2011 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and th... |
import os
from typing import Any, Set, Tuple
import logging
from regipy.exceptions import RegistryKeyNotFoundException
from regipy.registry import RegistryHive, NKRecord
from regipy.utils import convert_wintime, calculate_sha1
logger = logging.getLogger(__name__)
def get_subkeys_and_timestamps(registry_hive):
... |
#!/usr/bin/env python
# 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
# "L... |
#!/usr/bin/env python
"""
This script helps upload custom images stored on disk to a public location on imgur.com, and
generates a helpful template to use for the basis of an ESPN fantasy football league note.
"""
import argparse
import base64
import json
import logging
import os
from datetime import datetime
from c... |
"""
refenrence from: https://learnopencv.com/video-stabilization-using-point-feature-matching-in-opencv/
"""
import cv2
import numpy as np
from scipy.signal import savgol_filter
fname = "./deep-stabilization/dvs/video/s_114_outdoor_running_trail_daytime/ControlCam_20200930_104820.mp4"
# fname = "./deep-stabilization/d... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** 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
from ... import _utilities, _tables
from... |
import sys
sys.path.insert(0, '..')
import os
import math
from migen import *
from litex.soc.interconnect.csr import AutoCSR
from tools.common import *
class RAM64(Module, AutoCSR):
def __init__(self, max_words=None,
init=None, endianness="big",
debug=False):
self.init =... |
#!/usr/bin/env python
# TODO nf-core: Update the script to check the samplesheet
# This script is based on the example at: https://raw.githubusercontent.com/nf-core/test-datasets/viralrecon/samplesheet/samplesheet_test_illumina_amplicon.csv
import os
import sys
import errno
import argparse
from itertools import combi... |
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import mmcv
import torch
from mmcv import Config, DictAction
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import get_dist_info, init_dist, load_checkpoint
from mmgen.apis import set_random_seed
from mmgen... |
'''
More factorization code, courtesy of <NAME>.
'''
import numpy as np
import dataclasses
def moments(muhat_row,Sighat_row,muhat_col,Sighat_col,**kwargs):
row_m2 = Sighat_row + np.einsum('ij,ik->ijk',muhat_row,muhat_row)
col_m2 = Sighat_col + np.einsum('ij,ik->ijk',muhat_col,muhat_col)
mn= muhat_row @ mu... |
import os
import fire
import numpy as np
import pandas as pd
import soundfile
from multiprocessing import Pool
from tqdm.auto import tqdm
# split2kaldi = {
# "fine-tune": "fine-tune",
# "dev": "dev",
# "test": "test",
# }
splits = {"fine-tune", "dev", "test"}
def read_utt2xxx(filename):
with open(f... |
import os
import cv2
import dlib
import json
import yaml
import numpy as np
from time import monotonic as now
from datetime import timedelta
from age_gender.preprocess.face_aligner import FaceAligner
from concurrent.futures import ProcessPoolExecutor, as_completed
def get_area(rect):
left = rect.left()
top =... |
import time
import argparse
import traceback
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.web... |
from pathlib import Path
from dateutil.parser import parse
from datetime import timedelta
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from helper_funcs import *
def preprocesamiento_casos():
ts_global = {}
for file in Path('.').glob('*_global.csv'):
ts = ts_since_two_per_co... |
import pandas as pd
import numpy as np
import sys
import time
import matplotlib.pyplot as plt
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
def getData(file):
data = pd.read_csv(file, index_col=None)
x = data.iloc[:,:-1].to_numpy()
y = data.iloc[:,-1].to_numpy(... |
# 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... |
load(":target_recipes.bzl", "TARGET_RECIPES")
load(":repository_locations.bzl", "REPO_LOCATIONS")
def _repository_impl(ctxt):
# Setup the build directory with links to the relevant files.
ctxt.symlink(Label("//bazel:repositories.sh"), "repositories.sh")
ctxt.symlink(Label("//ci/build_container:build_and_in... |
#!/usr/bin/python3.2
# -*- coding: utf-8 -*-
# Differents auth level:
# * master
# * admin
# * known
from functions_core import Function
import functions_core
import hashlib
import auth_core
from core import server_config, write_config, stop, triggers, savetriggers
import sys
import format
@Function('auth', r... |
"""Support for displaying persistent notifications."""
from collections import OrderedDict
import logging
from typing import Awaitable
import voluptuous as vol
from homeassistant.components import websocket_api
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import TemplateError
f... |
# Copyright (c) OpenMMLab. All rights reserved.
import mmcv
import numpy as np
import torch
from mmdet.core import bbox2result
def imrenormalize(img, img_norm_cfg, new_img_norm_cfg):
"""Re-normalize the image.
Args:
img (Tensor | ndarray): Input image. If the input is a Tensor, the
shape ... |
# Package Imports
from ..workspace import Block, Disconnected, Cancelled
# Twisted Imports
from twisted.internet import reactor, defer, task
from twisted.python import log
# Octopus Imports
from octopus import data
from octopus.constants import State
import octopus.transport.basic
# Do not auto-register these classe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.