filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_106_15771
# Copyright 2014 The LibYuv 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 in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All contributing project authors...
the-stack_106_15772
import logging import os import time import timeit import numpy as np import matplotlib.pyplot as plt from argparse import ArgumentParser import paddle import paddle.nn as nn # user from builders.model_builder import build_model from builders.dataset_builder import build_dataset_train from utils.utils import setup_s...
the-stack_106_15773
import dragonfly as df import title_menu, menu_utils, server, df_utils, game, letters, items, server from game_menu import game_menu inventory_wrapper = menu_utils.InventoryMenuWrapper() def get_inventory_page(menu): page = game_menu.get_page_by_name(menu, 'inventoryPage') return page async def focus_item(pa...
the-stack_106_15774
from unittest import TestCase from unittest import main import mock import sys from masking_api_60.api.application_api import ApplicationApi from masking_api_60.models.application import Application from masking_api_60.models.application_list import ApplicationList from masking_api_60.models.page_info import Pag...
the-stack_106_15776
# Copyright 2021 SpinQ Technology Co., Ltd. # # 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 ...
the-stack_106_15777
# Copyright 2017 The Sonnet 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 applicable l...
the-stack_106_15780
import numpy as np import matplotlib.pyplot as plt import sys def format_number(x): return 255 - x.reshape((28,28)) def main(path="means.csv"): means = np.genfromtxt(path, delimiter=',',dtype=np.uint8)[:,:-1] print(means.shape) for i in range(20): plt.subplot(4,5,i+1) plt.imshow(forma...
the-stack_106_15782
from collections import OrderedDict, MutableMapping from copy import deepcopy from django.db.models import F def delete_keys_from_dict(dictionary): """ Recursive function to remove all keys from a dictionary/OrderedDict which start with an underscore: "_" parameters: - dictionary: dictionary...
the-stack_106_15783
""" This module helps you understand: -- UNIT TESTING. -- the difference between PRINT and RETURN Authors: David Mutchler, Dave Fisher, Vibha Alangar, Mark Hays, Amanda Stouder, their colleagues and Owen Land. """ ############################################################################### # # DONE: 1....
the-stack_106_15785
# coding: utf-8 # import uiautomator2 as u2 import pytest import logging import time def test_set_xpath_debug(sess): with pytest.raises(TypeError): sess.settings['xpath_debug'] = 1 sess.settings['xpath_debug'] = True assert sess.settings['xpath_debug'] == True assert sess.xpath.logger.le...
the-stack_106_15789
import os import numpy as np import torch import cv2 import argparse from tqdm import tqdm from detectron2 import model_zoo from detectron2.config import CfgNode import detectron2.data.transforms as T from detectron2.config import get_cfg from detectron2.checkpoint import DetectionCheckpointer from detectron2.modeling...
the-stack_106_15790
""" Defines Layout classes which may be used to arrange panes and widgets in flexible ways to build complex dashboards. """ from __future__ import absolute_import, division, unicode_literals from collections import OrderedDict import param import numpy as np from bokeh.models import (Column as BkColumn, Row as BkRow...
the-stack_106_15793
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals # Standard library modules import unittest # Third-party modules import boto3 from botocore.exceptions import ClientError # Package modules from moto import mock_cloudformation AWS_REGION = 'us-west-1' SG_STA...
the-stack_106_15796
import sqlite3 from .fixtures import * def test_update_status_invalid(tmp_path, process, disable_extractors_dict): subprocess.run(['archivebox', 'add', 'http://127.0.0.1:8080/static/example.com.html'], capture_output=True, env=disable_extractors_dict) assert list((tmp_path / "archive").iterdir()) != [] a...
the-stack_106_15797
def event_handler(obj, event): if event == lv.EVENT.CLICKED: date = obj.get_pressed_date() if date is not None: obj.set_today_date(date) calendar = lv.calendar(lv.scr_act()) calendar.set_size(230, 230) calendar.align(None, lv.ALIGN.CENTER, 0, 0) calendar.set_event_cb(event_handler) # S...
the-stack_106_15799
# -*- coding: utf-8 -*- """ Copyright 2020 Giuliano Franca 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 agree...
the-stack_106_15801
# # Copyright (c) 2019 ISP RAS (http://www.ispras.ru) # Ivannikov Institute for System Programming of the Russian Academy of Sciences # # 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 # # h...
the-stack_106_15804
import mxnet as mx import mxnet.ndarray as nd from utils.math import Distances from utils.converters import Converters from tensorboardX import SummaryWriter from dataProcessor.tiffReader import GEOMAP from networkProcessor.trainer import Trainer from network.resnext import resnext50_32x4d from dataProcessor.imagePro...
the-stack_106_15805
import hmac import hashlib from itertools import count import struct import time from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from cryptography.hazmat.backends import default_backend from scapy.automaton import ATMT, Automaton from scapy.base_class...
the-stack_106_15808
#pylint: disable-all """ Test a final model with distance attacks """ import os import copy import argparse import subprocess import yaml if __name__ == "__main__": TEST_TYPES = { "BIM_L2": { "adversary_type": "L2BasicIterativeAttack", "distance_type": "MeanSquaredDistance" ...
the-stack_106_15809
import numpy as np from multiphenotype_utils import (get_continuous_features_as_matrix, add_id, remove_id_and_get_mat, partition_dataframe_into_binary_and_continuous, divide_idxs_into_batches) import pandas as pd import tensorflow as tf from dimreducer import DimReducer from general_autoencoder import GeneralAuto...
the-stack_106_15812
#!/usr/bin/env python # plot already normalized data # first column is time stamp #plot-normalized.py taken from PMU-tools import csv import matplotlib.pyplot as plt import sys import argparse ap = argparse.ArgumentParser(usage='Plot already normalized CSV data') ap.add_argument('--output', '-o', help='Output to file....
the-stack_106_15815
# -*- coding: utf-8 -*- # Copyright 2016 OpenMarket Ltd # # 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 la...
the-stack_106_15816
""" Testing of callbacks in non-Python Alert snippets. """ from pathlib import Path import dash.testing.wait as wait from .helpers import load_jl_app, load_r_app HERE = Path(__file__).parent def test_r_dismiss(dashr): r_app = load_r_app((HERE.parent / "alert" / "dismiss.R"), "alert") dashr.start_server(r_a...
the-stack_106_15818
from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import logging import pytest import ray import ray.services as services from ray.test.cluster_utils import Cluster logger = logging.getLogger(__name__) @pytest.fixture def start_connected_cluste...
the-stack_106_15819
import numpy as np class LOWESS: def __init__(self, sigma=1., frac=1., eps=1e-8): self.sigma = sigma self.frac = frac self.eps = eps self.X_ = None self.y_ = None def _compute_weights(self, x): distances = np.linalg.norm(self.X_ - x[:, None], axis=-1) ...
the-stack_106_15820
# coding: utf-8 """ CLOUD API An enterprise-grade Infrastructure is provided as a Service (IaaS) solution that can be managed through a browser-based \"Data Center Designer\" (DCD) tool or via an easy to use API. The API allows you to perform a variety of management tasks such as spinning up additional serv...
the-stack_106_15821
import math import copy from contextlib import contextmanager from functools import partial import torch import torch.nn.functional as F from torch import nn, einsum from einops import rearrange, repeat, reduce from einops.layers.torch import Rearrange from x_clip.mlm import MLM from x_clip.visual_ssl import SimSiam,...
the-stack_106_15823
""" Defines the Card class which models a Magic: the Gathering card's behaviour. Currently, the following actions are supported: to gain mana instanteneously as well as according to a pattern every turn, to create gold/create gold/draw Cards immediately as well as according to a pattern every turn. Additionally, a card...
the-stack_106_15828
# Copyright (c) 2020, Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can be # found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause import six from coremltools import TensorType import pytest tf = pytest.importorskip("tensorflow", m...
the-stack_106_15829
import os from robolearn.old_utils.plots.specific_cost import plot_specific_cost method = 'gps' # 'gps' or 'trajopt' gps_directory_names = ['gps_log1'] gps_models_labels = ['gps_log1'] itr_to_load = None # list(range(8)) block = False specific_costs = None #[4] # None for all costs dir_names = [os.path.dirname(os...
the-stack_106_15830
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyRequestsOauthlib(PythonPackage): """This project provides first-class OAuth library supp...
the-stack_106_15831
## @package Rve # This module contains classes (Rve Modelers) that are used # to handle the generation, assignment and tracking of # RveConstitutiveLaws. # # More details from __future__ import print_function, absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and 2.7 i...
the-stack_106_15832
from setuptools import setup, find_packages requirements = ['Flask', 'werkzeug', 'jinja2', 'peewee>=3.0.0', 'wtforms', 'wtf-peewee'] setup( name='flask-peewee', version='3.0.4-propel', url='http://github.com/coleifer/flask-peewee/', license='MIT', author='Charles Leifer', author_email='coleifer...
the-stack_106_15834
""" Copyright 2017-present Airbnb, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
the-stack_106_15835
"""A demo for object detection or image classification using CORAL TPU. This example is intended to run later in a raspberry PI, but for now, is running on a Linux machine The only pending thing to make it run on the raspberry, since capturing frames require a different method through the picamera python library See:...
the-stack_106_15837
import argparse import scipy from scipy import ndimage import numpy as np import sys from packaging import version from multiprocessing import Pool import torch from torch.autograd import Variable import torchvision.models as models import torch.nn.functional as F from torch.utils import data, model_zoo from model.deep...
the-stack_106_15839
import unittest from datetime import datetime from django.utils import http from django.utils.datastructures import MultiValueDict class TestUtilsHttp(unittest.TestCase): def test_urlencode(self): # 2-tuples (the norm) result = http.urlencode((('a', 1), ('b', 2), ('c', 3))) self.assertEq...
the-stack_106_15841
import numpy as np import pandas as pd from copy import copy, deepcopy from matplotlib import pyplot as plt from datetime import datetime, timedelta from matplotlib.backends.backend_pdf import PdfPages dfheight=pd.read_csv('../data/raw/Results from Val_Roseg_Timelapse in µm per sec.csv') dfdates=pd.read_csv('../data/r...
the-stack_106_15844
import select import socket import threading try: import SocketServer except ImportError: import socketserver as SocketServer def check_if_ipv6(ip): try: socket.inet_pton(socket.AF_INET6, ip) return True except socket.error: return False class LocalPortForwarding: def __...
the-stack_106_15845
import random import pytest from aiohttp_apiset.jinja2 import template @template('fake.html') def handler(request): return {'req': request} @template('fake.html') async def handler2(request): return {'req': request} @pytest.mark.parametrize('handler', [ handler, handler2 ]) async def test_with_req(s...
the-stack_106_15847
# import os # import cv2 # import numpy as np # # INPUT_VIDEO = 'test.mp4' # OUTPUT_IMG = 'out_my_video' # os.makedirs(OUTPUT_IMG, exist_ok=True) # # # def print_image(img, frame_diff): # """ # Place images side-by-side # """ # new_img = np.zeros([img.shape[0], img.shape[1] * 2, img.shape[2]]) # [heigh...
the-stack_106_15851
"""Utility methods for Mycroft Precise.""" class TriggerDetector: """ Reads predictions and detects activations This prevents multiple close activations from occurring when the predictions look like ...!!!..!!... NOTE: Taken from precise-runner source code """ def __init__(self, chunk_si...
the-stack_106_15852
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
the-stack_106_15853
class Solution: # @param s, a string # @return a string def reverseWords(self, s): if s is None: return s = s.strip() words = s.split() words.reverse() s = " ".join(words) return s
the-stack_106_15854
""" To understand why this file is here, please read: http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django """ from django.conf import settings from django.db import migrations def update_site_forward(apps, schema_editor): """Set site d...
the-stack_106_15856
from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve import numpy as np from federatedml.util import consts import logging from federatedml.util import LOGGER from federatedml.evaluation.metrics import classification_metric from federatedml.evaluation.metrics import regression_metric from fe...
the-stack_106_15858
# -*- coding: utf-8 -*- """ pygments.styles ~~~~~~~~~~~~~~~ Contains built-in styles. :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.plugin import find_plugin_styles from pygments.util import ClassNotFound #: Maps sty...
the-stack_106_15859
# Copyright 2016 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 ...
the-stack_106_15860
import numpy as np import torch from matplotlib import pyplot as plt from matplotlib.lines import Line2D from sinkhorn_barycenters import barycenter from utils import gengaussians params = {"legend.fontsize": 18, "axes.titlesize": 16, "axes.labelsize": 16, "xtick.labelsize": 13, ...
the-stack_106_15862
import os import shutil import textwrap import unittest import subprocess import click.testing import mkcodes class TestBase(unittest.TestCase): outputfile = 'tests/output/output.py' def tearDown(self): shutil.rmtree('tests/output', ignore_errors=True) @classmethod def call(cls, *flags, in...
the-stack_106_15864
""" * Created with PyCharm. * User: 彭诗杰 * Date: 2018/5/3 * Time: 11:25 * Description: main handler for backend system * one remote object one server, not many options onfiguration Parameters: * { * local_sign: false, // default sign tx in jingtumd * } """ import json import math from numbers import Number f...
the-stack_106_15866
import torch import torch.nn as nn import numpy as np import math from time import time from .kernels import MaxSimCUDA from .kernels import ComputeCentroidsCUDA from ..CustomModule import CustomModule class MultiKMeans(CustomModule): """ Run multiple independent K-means algorithms in parallel. Parameters: ...
the-stack_106_15868
"""The LBFGS attack """ import numpy as np import tensorflow as tf from cleverhans.attacks.attack import Attack from cleverhans.compat import reduce_sum, softmax_cross_entropy_with_logits from cleverhans.model import CallableModelWrapper, Model, wrapper_warning from cleverhans import utils from cleverhans import util...
the-stack_106_15869
import json import datetime import random from picklefield import PickledObjectField from django.shortcuts import render from django.http import HttpResponse from django_q.tasks import Async, schedule from django_q.models import Schedule, Task # Create your views here. class CJsonEncoder(json.JSONEncoder): def...
the-stack_106_15872
# # UAVCAN DSDL compiler for libuavcan # # Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com> # ''' This module implements the core functionality of the UAVCAN DSDL compiler for libuavcan. Supported Python versions: 3.2+, 2.7. It accepts a list of root namespaces and produces the set of C++ header files for ...
the-stack_106_15873
from setuptools import find_packages from setuptools import setup package_name = 'ros2component' setup( name=package_name, version='0.12.0', packages=find_packages(exclude=['test']), data_files=[ ('share/' + package_name, ['package.xml']), ('share/ament_index/resource_index/packages', ...
the-stack_106_15874
import numpy as np import pandas as pd __all__ = ( "one_ns_timedelta", "one_s_timedelta", "unix_begin_time" ) one_ns_timedelta = pd.Timedelta(1) one_s_timedelta = np.timedelta64(1, 's') unix_begin_time = pd.Timestamp(0, unit='s')
the-stack_106_15875
import numpy as np import scipy.stats as sps import torch import models.dataset as md import models.model as mm import utils.smiles as chem_smiles from running_modes.configurations.general_configuration_envelope import GeneralConfigurationEnvelope from running_modes.configurations.transfer_learning.adaptive_learning_r...
the-stack_106_15876
""" The MIT License (MIT) Copyright (c) 2020 James Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publis...
the-stack_106_15877
import base64 import datetime import json import os import uuid from collections import defaultdict import flask.views from datastore_viewer.infrastructure import DatastoreViewerRepository from datastore_viewer.infrastructure import get_client from datastore_viewer.presentation.ui.api.encoder import DataStoreEntityJS...
the-stack_106_15878
from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.db import transaction from rest_framework import serializers from .models import * from Users.serializers import UserSerializer from core.views import get_userData class OrganizationSerializer(serializers.Mod...
the-stack_106_15879
import argparse import logging from dvc.command.base import append_doc_link from dvc.command.base import CmdBase from dvc.command.base import fix_subparsers from dvc.exceptions import BadMetricError from dvc.exceptions import DvcException logger = logging.getLogger(__name__) def show_metrics(metrics, all_branches=...
the-stack_106_15880
""" Num params: 122790952 Run it as: mpiexec -n {num_processes} python3.6 -m flows_celeba.launchers.celeba128_5bit_official from the flows master directory of the git repo. num_processes=8 was used for this launcher on a 8-GPU (1080 Ti) machine with 40 GB RAM. If you want to use python3.5, remove the f str...
the-stack_106_15882
""" This example script download a test raster, caculates and plot normalised channel steepness (ksn). Read the comments to understand each steps. Copy and adapt this script to learn. If any questions: b.gailleton@sms.ed.ac.uk B.G. """ # If you are facing a common matplotlib issue, uncomment that: #####################...
the-stack_106_15883
"""distutils.command.check Implements the Distutils 'check' command. """ from distutils.core import Command from distutils.errors import DistutilsSetupError try: # docutils is installed from docutils.utils import Reporter from docutils.parsers.rst import Parser from docutils import frontend from d...
the-stack_106_15886
from __future__ import annotations import typing from typing import Any, Optional, Dict, List, Union, Optional from dataclasses import asdict try: from typing import Literal except ImportError: from typing_extensions import Literal # type: ignore if typing.TYPE_CHECKING: from dataclasses import dataclas...
the-stack_106_15887
import csv import logging import psutil from intelligence import intelligence class processlist( intelligence ): def __init__( self, output_type='csv' ): super(processlist, self).__init__( output_type='csv' ) self.default_headers = None def run( self ): self.logger.info( 'run...
the-stack_106_15888
# ********************************************************************************************************************** # # brief: simple script to plot runtimes # # author: Lukas Reithmeier # date: 16.08.2020 # # ************************************************************************************************...
the-stack_106_15891
#copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. # #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 l...
the-stack_106_15892
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains th...
the-stack_106_15893
''' Manage ruby gems. ''' # Import python libs import re def _gem(command, ruby=None, runas=None): cmdline = 'gem {command}'.format(command=command) if __salt__['rvm.is_installed'](): return __salt__['rvm.do'](ruby, cmdline, runas=runas) ret = __salt__['cmd.run_all']( cmdline, ru...
the-stack_106_15894
import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils from h2o.estimators.gbm import H2OGradientBoostingEstimator def distribution_behavior_gbm(): eco = h2o.import_file(path=pyunit_utils.locate("smalldata/gbm_test/ecology_model.csv")) # 0/1 response: expect gaussian eco_model = H2...
the-stack_106_15895
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import init from models.generators.resblocks import Block class ResNetGenerator(nn.Module): """Generator generates 64x64.""" def __init__(self, num_features=64, dim_z=128, bottom_width=4, activation=F.relu, num...
the-stack_106_15896
# Copyright 2016 Red Hat, 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 ...
the-stack_106_15899
import os from instauto.api.client import ApiClient from instauto.api.actions import post as ps from instauto.api.actions import search as se if __name__ == '__main__': if os.path.isfile('./.instauto.save'): client = ApiClient.initiate_from_file('./.instauto.save') else: client = ApiClient(use...
the-stack_106_15900
import sys import traceback from typing import Any import discord from discord.ext import commands from discord.ext.commands import errors import bot_config import errors as cerrors import functions class Logging(commands.Cog): """Handle logging stuff""" def __init__( self, bot: commands.Bo...
the-stack_106_15904
import os.path import logging import socket from base64 import b64encode from urllib3 import PoolManager, ProxyManager, proxy_from_url, Timeout from urllib3.util.retry import Retry from urllib3.util.ssl_ import ( ssl, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION, DEFAULT_CIPHERS, ) from urllib3.exceptions import SS...
the-stack_106_15905
# 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. # 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, ...
the-stack_106_15906
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "...
the-stack_106_15912
""" Groups a batch_size block of worlds together; can run act, reset etc on entire batch """ import torch import numpy as np from ulfs import alive_sieve from ulfs.rl_common import cudarize class WorldsContainer(object): """ Contains a bunch of worlds, runs action tensor against them, and returns rewards...
the-stack_106_15913
# Copyright 2019 MilaGraph. 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 ag...
the-stack_106_15915
import numpy as np try: # use scipy if available: it's faster from scipy.fftpack import fft, ifft, fftshift except ImportError: from numpy.fft import fft, ifft, fftshift def FT_continuous(t, h, axis=-1, method=1): r"""Approximate a continuous 1D Fourier Transform with sampled data. This function...
the-stack_106_15916
from z3 import * import jry2.translator as translator import random def getId(type, id): return type + str(id) def declareVar(type, id, VarTable): newVar = translator.DeclareVar(type, id) # print "declareVar", id, newVar, type VarTable[str(newVar)] = newVar return newVar def replaceFunctionCall...
the-stack_106_15917
#!/usr/bin/env python3 # # Consolidate all the raw Blogger JSON files into a single, simplified JSON file. # from collections import OrderedDict import html import io import json import sys import lxml.etree as ET import lxml.html import re import feeds import util posts = feeds.json_post_entries_list() output = []...
the-stack_106_15918
import numpy as py print("Input: ",end="") arr = py.array(input().split()).astype(int) def count(arr, low, high): while high >= low: mid = (high + low)//2 if (arr[mid] == 1 and (mid == 0 or arr[mid - 1] == 0)): return mid if arr[mid]==1: high...
the-stack_106_15922
# coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
the-stack_106_15924
# --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- import os import json import hashlib from datetime import datetime from os import listdir from os.path import isfile, join from c...
the-stack_106_15929
# !/usr/bin/env python3 import jieba from gensim import corpora, models, similarities # choice_item = [ # '不方便,在工作,稍等一会, 我不是很感兴趣, 能不能等会再打','方便, 好,可以聊一下,方便,感兴趣,挺好的,有什么事','不知道你说的啥'] choice_item = ['不方便','在工作','稍等一会','我不是很感兴趣', '能不能等会再打','方便', '好','可以聊一下','方便','感兴趣','挺好的','有什么事','不知道你说的啥'] choice_cut = ...
the-stack_106_15931
from unittest import mock import os import pytest import tomlfmt here = os.path.dirname(__file__) pyproject_toml = os.path.join(os.path.dirname(here), "pyproject.toml") @pytest.fixture def no_write(): """utility for verifying that no files are written""" def open_no_write(path, mode="r"): assert m...
the-stack_106_15932
import numpy as np from matplotlib import pyplot as plt import EmotionUtils import tensorflow as tf FLAGS = tf.flags.FLAGS tf.flags.DEFINE_string("data_dir",\ "EmotionDetector/",\ "Path to data files") images = [] images = EmotionUtils.read_data(FLAGS.data_dir) train_im...
the-stack_106_15933
# -*- coding: UTF-8 -*- import numpy as np import sys def readPFM(fpath, expected_identifier="Pf"): # PFM format definition: http://netpbm.sourceforge.net/doc/pfm.html def _get_next_line(f): next_line = f.readline().decode('utf-8').rstrip() # ignore comments while next_line.startswith(...
the-stack_106_15935
from __future__ import print_function, division import cv2 import numpy as np from numba import jit @jit def copy_with_resize(src, dest, size): ''' Copy an image with resizing Parameters: src - source dest - destination size - (width, height) tuple ''' img = cv2.imread...
the-stack_106_15940
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- import os import numpy as np from distutils.core import setup from dist...
the-stack_106_15941
import sys import pathlib field_type_mapping = {'CHAR': 'TEXT', 'INTEGER': 'INTEGER', 'TIMESTAMP': 'TEXT', 'VARCHAR': 'TEXT', 'DATE': 'TEXT'} filename = pathlib.Path(sys.argv[1]) table_name = filename.stem....
the-stack_106_15942
import csv import os import re def translate(file, path): csv_file = open(file, 'r') csv_reader = csv.reader(csv_file, delimiter=',') locales = [ {'identifier' : 'fr', 'column' : 3}, {'identifier' : 'en', 'column' : 5} ] for aLocale in locales: if not os.path.e...
the-stack_106_15943
import random import os, codecs import Hex from binascii import hexlify as hx, unhexlify as uhx import Keys import re from hashlib import sha256 from struct import pack as pk, unpack as upk import Fs import aes128 import sq_tools import io import Print indent = 1 tabs = '\t' * indent ''' versions = ...
the-stack_106_15944
import os import requests import six import logging from wandb.docker import auth from wandb.docker import www_authenticate import subprocess entrypoint = os.path.join(os.path.dirname( os.path.abspath(__file__)), "wandb-entrypoint.sh") auth_config = auth.load_config() log = logging.getLogger(__name__) def shell(c...
the-stack_106_15945
from django.conf import settings from django.db import migrations from django.db.backends.base.schema import BaseDatabaseSchemaEditor from django.db.migrations.state import StateApps def update_default_site(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor): Site = apps.get_model('sites', 'Site') # noqa: ...
the-stack_106_15946
#!/usr/bin/env python # pylint: disable=R0902, R0903, C0103 """ Gantt.py is a simple class to render Gantt charts, as commonly used in """ import os import json import platform from operator import sub import numpy as np import matplotlib.pyplot as plt from matplotlib import rc # TeX support: on Linux assume TeX in ...