filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_0_663
import cv2 import numpy as np from matplotlib import pyplot as plt from .log import logger MATCHER_DEBUG = False FLANN_INDEX_KDTREE = 0 GOOD_DISTANCE_LIMIT = 0.7 SIFT = cv2.SIFT_create() def is_in_poly(p, poly): """ :param p: [x, y] :param poly: [[], [], [], [], ...] :return: """ px, py = p ...
the-stack_0_664
# -*- coding:utf-8 -*- """ Author: Weichen Shen,wcshen1994@163.com Reference: [1] Guo H, Tang R, Ye Y, et al. Deepfm: a factorization-machine based neural network for ctr prediction[J]. arXiv preprint arXiv:1703.04247, 2017.(https://arxiv.org/abs/1703.04247) """ import tensorflow as tf from ..input_embeddin...
the-stack_0_665
# Copyright 2013-2019 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 PyWidgetsnbextension(PythonPackage): """IPython HTML widgets for Jupyter""" homepage ...
the-stack_0_667
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2012, Jan-Piet Mens <jpmens () gmail.com> # Copyright: (c) 2015, Ales Nosek <anosek.nosek () gmail.com> # Copyright: (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import ...
the-stack_0_670
"""The Spark SQL dialect for ANSI Compliant Spark3. Inherits from ANSI. Spark SQL ANSI Mode is more restrictive regarding keywords than the Default Mode, and still shares some syntax with hive. Based on: - https://spark.apache.org/docs/latest/sql-ref.html - https://spark.apache.org/docs/latest/sql-ref-ansi-compliance...
the-stack_0_671
"""A logging handler that emits to a Discord webhook.""" import requests from logging import Handler class DiscordHandler(Handler): """A logging handler that emits to a Discord webhook.""" def __init__(self, webhook, *args, **kwargs): """Initialize the DiscordHandler class.""" super().__init_...
the-stack_0_673
""" Class to initialize common objects. """ import pickle from pathlib import Path ################################################################ class Init(): #--------------------------------------------------------------- # Constructor #--------------------------------------------------------------- def...
the-stack_0_674
#=============================================================================== # Copyright 2020 Intel Corporation # # 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.o...
the-stack_0_678
#! /usr/bin/env python # Copyright (c) 2014, Dawn Robotics Ltd # 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 # ...
the-stack_0_680
""" ``street.py`` ============= Módulo para o peso de um trecho de rua """ from __future__ import annotations from protocols import Weightable from random import choice from functools import total_ordering from typing import Optional, List, Any, Dict #: Incluir velocidade máxima entre as possibilidades #: de velo...
the-stack_0_683
import pyglet from pyglet.window import key from pyglet.window.key import MOD_SHIFT from CGP import Individual, create_pop, evolve from load import * game_window = pyglet.window.Window(1600, 1000) pyglet.resource.path = ['../assets'] pyglet.resource.reindex() main_batch = pyglet.graphics.Batch() pillar_batch = pygle...
the-stack_0_688
# Copyright 2018-2020 Streamlit 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 wr...
the-stack_0_690
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
the-stack_0_691
"""Various constants and distributions that decribe our dataset. Intended use is normalization of the fields before sending them to a neural net. See notebook distributions-of-parameters.ipynb""" import logging import numpy as np import torch import random import xarray as xr from .util import add_biweekly_dim, obs_...
the-stack_0_694
#! /usr/bin/env python3 # Copyright 2019 Intel Corporation # # 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 applicabl...
the-stack_0_696
import numpy as np import collections import numbers import torch import os from . import joint_network from .summary import LamanClassificationSummary from .. import corruption_dataset, model as mo from .representation import graph_to_rep, combine_graph_reps, encode_action, LamanRep, get_action_offsets from ..molecule...
the-stack_0_698
import numpy as np import matplotlib.pyplot as plt from sympy import solve, Eq, symbols import sys import pandas import math import os def degradeCOP(Tevap, Tcond, Qall, S): degraded = ((Tevap * Tcond)/(Tcond - Tevap)) * (S/Qall) return degraded # This function calculates the reversible COP of a ES refrigera...
the-stack_0_700
# SECUREAUTH LABS. Copyright 2018 SecureAuth Corporation. All rights reserved. # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # Author: Alberto Solino (@agsolino) # # Description: # [MS-VDS]: Virtual D...
the-stack_0_702
import os from unittest import TestCase from configservice import Config, MissingEnviron, ErrorFlagTrue class TestCore(TestCase): def test__load_env(self): # set an env to work with. os.environ['TEST_ME_X'] = '1' c = Config() # Test simple recall. res = c.get_env('TEST...
the-stack_0_705
#!/usr/bin/python3 # -*- coding: utf-8 -*- str = """ACS3004 湖南新永利交通科工贸有限公司 ACS3005 三一帕尔菲格特种车装备有限公司 ACS3006 湖南新永利交通科工贸有限公司""" print(str) items = str.split(sep='\n') for i, e in enumerate(items, 1): print(i, '. ', e.split(sep=' ')[0]) for i in range(1): print(i)
the-stack_0_706
""" Contains abstract functionality for learning locally linear sparse model. """ import numpy as np import scipy as sp from sklearn.linear_model import Ridge, lars_path from sklearn.utils import check_random_state class LimeBase(object): """Class for learning a locally linear sparse model from perturbed data""" ...
the-stack_0_707
# Attempts to verify the solutions of discrete mathematics CW1 import random def listUpTo(num): """ Returns a lists of integers from 1 up to num """ return list(range(1, num + 1)) def countMultiples(dividendList, divisor): """ Returns the total number of multiples of the divisor in dividendLi...
the-stack_0_708
#!/usr/bin/env python3 # Hydrus is released under WTFPL # You just DO WHAT THE FUCK YOU WANT TO. # https://github.com/sirkris/WTFPL/blob/master/WTFPL.md import locale try: locale.setlocale( locale.LC_ALL, '' ) except: pass try: import os import argparse import sys from hydrus.core import H...
the-stack_0_710
print('-*-' * 15) print('SISTEMA CAIXA ELETRONICO') print('-*-' * 15) valor = float(input('Qual será o valor sacado? ')) cedula = 100 qtd = 0 total = valor if valor < 1: print('Saque somente acima de R$1! ') while True: if valor >= cedula: valor = valor - cedula qtd += 1 else: if ...
the-stack_0_711
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. """ Base tests that all storage providers should implement in their own tests. They handle the storage-based assertions, internally. All tests return true if assertions pass to indicate that the code ran to completion, passi...
the-stack_0_714
""" Phong Material For phong shading """ from .material import Material from ..math import Vec3, Ray, HitRecord, dot3, reflect3, normalize3, clamp3 from ..camera import Camera class PhongMaterial(Material): """Base Material Class""" def __init__(self, color: Vec3 = Vec3(1.,1.,1.), shininess: float = 10.0, ...
the-stack_0_715
import numpy as np import os import pickle import tensorflow as tf import matplotlib.pyplot as plt from skimage.transform import rotate, resize from skimage import exposure import skimage.io as io from config import FLAGS def load_facegreyreduxshuffled_set(batch_size, is_training=True): path = os.path.join('da...
the-stack_0_717
import csv from collections import OrderedDict from datetime import datetime from pathlib import Path from typing import Any, List, Mapping from dmutils.formats import DATE_FORMAT, DATETIME_FORMAT from dmutils.s3 import S3 from dmscripts.helpers.s3_helpers import get_bucket_name # This URL is framework agnostic PUBL...
the-stack_0_718
"""Utility functions.""" import logging import numpy as np from scipy.signal import periodogram from tensorpac.methods.meth_pac import _kl_hr from tensorpac.pac import _PacObj, _PacVisual from tensorpac.io import set_log_level from matplotlib.gridspec import GridSpec import matplotlib.pyplot as plt logger = logging...
the-stack_0_719
#-*- coding: utf-8 -*- # pysqlite2/dbapi.py: pysqlite DB-API module # # Copyright (C) 2007-2008 Gerhard Häring <gh@ghaering.de> # # This file is part of pysqlite. # # This software is provided 'as-is', without any express or implied # warranty. In no event will the authors be held liable for any damages # arising from...
the-stack_0_720
# -*- coding: utf-8 -*- from serial.serialutil import SerialException from struct import unpack from .serial_wrapper import SerialPort from .constants import NO_KEY_DETECTED from .internal import XidConnection from .keymaps import (rb_530_keymap, rb_730_keymap, rb_830_keymap, rb_834_keymap, lumin...
the-stack_0_722
# -*- coding: utf-8 -*- # @Author: yulidong # @Date: 2018-07-17 10:44:43 # @Last Modified by: yulidong # @Last Modified time: 2018-08-27 18:45:39 # -*- coding: utf-8 -*- # @Author: lidong # @Date: 2018-03-20 18:01:52 # @Last Modified by: yulidong # @Last Modified time: 2018-07-16 22:16:14 import time import tor...
the-stack_0_723
import pytest import random import tensorflow as tf from run import run from main import main import os import json import shutil cwd = os.path.abspath(os.path.dirname(__file__)) path = os.path.join(cwd, '..', 'cotk') def setup_function(function): import sys sys.argv = ['python3'] random.seed(0) import numpy as np...
the-stack_0_727
__classification__ = 'UNCLASSIFIED' __author__ = "Thomas McCullough" import os import re import logging from typing import List logger = logging.getLogger('validation') _the_directory = os.path.split(__file__)[0] urn_mapping = { 'urn:SIDD:1.0.0': { 'ism_urn': 'urn:us:gov:ic:ism', 'sfa_urn': 'urn...
the-stack_0_728
import math import numbers import random import warnings from collections.abc import Sequence from typing import Tuple, List, Optional import torch from torch import Tensor try: import accimage except ImportError: accimage = None from . import functional as F from .functional import InterpolationMode, _inter...
the-stack_0_730
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/10/04 14:23 # @Author : Iydon # @File : course3.5.py import numpy as np from Poly import * import matplotlib.pyplot as plt def natural_cubic_spline(xs:list, fxs:list, display:bool=False): """ Cubic spline interpolation. """ n = le...
the-stack_0_732
import sys import os.path as op rpws_folder = op.dirname(op.dirname(__file__)) sys.path.append(rpws_folder) print('sys.path + {}'.format(rpws_folder)) from rpws import RevitServer import testconfig as config rs = RevitServer(config.test_server_name, config.test_server_version) for parent, folders, files, models ...
the-stack_0_740
from typing import Sequence, Union, Optional, Callable, Dict, Any, Tuple import torch from ignite.engine.engine import Engine from ignite.engine.events import State, Events, EventEnum, CallableEventWithFilter from ignite.utils import convert_tensor from ignite.metrics import Metric __all__ = [ "State", "creat...
the-stack_0_741
#!/usr/bin/env python # -*- coding: utf-8 -*- from cleave import server class MyServer(server.BaseServer): """ My HTTP Server """ def client_handler(self, client): """ Handles a client connection :param client: server.BaseClient :return: None """ client...
the-stack_0_744
from unittest import TestCase from unittest.mock import patch from pathlib import Path from click.testing import CliRunner from ..management.commands import bump_changelog from hourglass import changelog from hourglass.tests.test_changelog import UtilTests def patch_new_version(version): return patch.object(bump...
the-stack_0_745
import numpy as np def vertex_voronoi(mesh): """ compute vertex voronoi of a mesh as described in Meyer, M., Desbrun, M., Schroder, P., Barr, A. (2002). Discrete differential geometry operators for triangulated 2manifolds. Visualization and Mathematics, 1..26. :param mesh: trimesh object :...
the-stack_0_746
# Copyright (C) 2016 The Android Open Source Project # # 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_0_747
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # (c) Copyright 2013 Hewlett-Packard Development Company, L.P. # 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...
the-stack_0_749
#!/usr/bin/env python import ads1256 import time import rospy from std_msgs.msg import Float32 def ReadValues(): rate = 25 # Frequency in Hz ads1256.start("1",str(rate)) pub = rospy.Publisher('/sen_4/ResVal', Float32, tcp_nodelay=False, queue_size=1) rospy.init_node('Rheostat',anonymous=True) rate=rospy.Rate(10...
the-stack_0_752
""" Utility functions used in the logistic regression classifier. @copyright: The Broad Institute of MIT and Harvard 2015 """ import numpy as np def sigmoid(v): return 1 / (1 + np.exp(-v)) """Computes a prediction (in the form of probabilities) for the given data vector """ def predict(x, theta): p = sigmoi...
the-stack_0_755
import numpy as np import matplotlib.pyplot as plt import sectionproperties.pre.pre as pre import sectionproperties.post.post as post class Geometry: """Parent class for a cross-section geometry input. Provides an interface for the user to specify the geometry defining a cross-section. A method is provid...
the-stack_0_756
#!/usr/bin/env python """ Fetch descriptions from NCBI given file with gene names. Intended to use on genes from Gene2Products.need-curating.txt from funannotate annotate formatted as single column, new line separated text file. Outputs 2 column TSV ready for update-gene2products.py Usage: python grab_gene_descripti...
the-stack_0_757
from pyspark import SparkContext, SparkConf if __name__ == "__main__": conf = SparkConf().setAppName("word count").setMaster("local[3]") # Spark Context sc = SparkContext(conf=conf) sc.setLogLevel("ERROR") # Load input lines = sc.textFile("inputs/word_count.text") # Split the...
the-stack_0_758
import requests from pymongo import MongoClient from datetime import datetime from airflow.providers.mongo.hooks.mongo import MongoHook def get_raw_joke(): """Retrieve a joke from 'jokeapi' and return it in dict format.""" base_url = "https://v2.jokeapi.dev" response = requests.get(f"{base_url}/joke/any")...
the-stack_0_759
from model.group import Group class GroupHelper: def __init__(self, app): self.app = app def open_groups_page(self): wd = self.app.wd if not(wd.current_url.endswith("/group.php") and len(wd.find_elements_by_name("new")) > 0): wd.find_element_by_link_text("groups").click() ...
the-stack_0_762
import os from collections import OrderedDict import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from .building import Building from .datastore.datastore import join_key from .utils import get_datastore from .timeframe import TimeFrame class DataSet(objec...
the-stack_0_766
# 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_0_767
#!/usr/bin/env python #-----------------------------*-python-*----------------------------------------# # file src/cdi_ipcress/python/ipcress_reader.py # author Alex Long <along@lanl.gov> # date Monday, December 15, 2014, 5:44 pm # brief This script has fucntions that parse an IPCRESS file and returns a # d...
the-stack_0_769
import torch import torch.nn as nn import torch.nn.functional as f from torch.nn import init from .submodules import ConvLayer, UpsampleConvLayer, TransposedConvLayer, RecurrentConvLayer, ResidualBlock, ConvLSTM, ConvGRU, RecurrentResidualLayer def skip_concat(x1, x2): return torch.cat([x1, x2], dim=1) def skip...
the-stack_0_774
#!/usr/bin/python3 import os import sys import math sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import data_utils load_fn = data_utils.load_cls_train_val balance_fn = None map_fn = None keep_remainder = True save_ply_fn = None num_class = 40 batch_size = 32 sample_num = 512 num_ep...
the-stack_0_775
from __future__ import print_function, absolute_import, division # makes KratosMultiphysics backward compatible with python 2.6 and 2.7 #import kratos core and applications import KratosMultiphysics import KratosMultiphysics.DelaunayMeshingApplication as KratosDelaunay import KratosMultiphysics.PfemFluidDynamicsApplic...
the-stack_0_776
# # 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 us...
the-stack_0_777
# -*- coding: utf-8 -*- """Implements a class to be used for unit testing. """ import pathlib from tlsmate.workers.eval_cipher_suites import ScanCipherSuites from tlsmate.tlssuite import TlsSuiteTester from tlsmate.tlssuite import TlsLibrary ssl2_ck = [ "SSL_CK_RC4_128_WITH_MD5", "SSL_CK_RC2_128_CBC_WITH_MD5",...
the-stack_0_782
""" [Python scripts for 3DTracker-FAB (www.3dtracker.org)] Example 03: Converting 2D position to 3D This is a script demonstrating how to convert 2D positions in a ROI in a RGB image to 3D. The type of conversion is useful for using 2D image based object detection/tracking algorithms to obtain the corresponding 3D ob...
the-stack_0_784
# Copyright 2017 BrainPad 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_0_785
# coding=utf-8 # Copyright 2018 The Dopamine Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
the-stack_0_790
# Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompa...
the-stack_0_794
import itertools from collections import OrderedDict from rest_framework import filters, exceptions from .mixin import ViewSetMixin def get_sort_order(request, param): args = request.query_params.getlist(param) fields = itertools.chain(*(arg.split(',') for arg in args)) order = tuple(field.strip() for f...
the-stack_0_796
# -*- coding: utf-8 -*- # # Copyright 2015 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...
the-stack_0_798
# uncompyle6 version 3.3.1 # Python bytecode 3.6 (3379) # Decompiled from: Python 3.6.2 (v3.6.2:5fd33b5926, Jul 16 2017, 20:11:06) # [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] # Embedded file name: ../../shared/problems/CR/problem1068_CR.py # Compiled at: 2019-03-13 18:01:49 # Size of source mod 2**32: 1148 bytes __a...
the-stack_0_799
# # Copyright SAS Institute # # 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...
the-stack_0_800
import pandas as pd from pytorch_lightning.loggers import TensorBoardLogger from pytorch_lightning.utilities.cloud_io import load as pl_load import argparse import json import pytorch_lightning as pl import pandas as pd import sklearn from ray import tune import numpy as np import matplotlib.pyplot as plt import seabo...
the-stack_0_802
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Nov 2 23:26:08 2017 @author: Shashwat Sridhar """ # system imports from pyqtgraph.Qt import QtCore, QtGui, QtWidgets from os import sep # swan-specific imports from swan.views.mean_waveforms_view import PgWidget2d from swan.views.virtual_units_view im...
the-stack_0_803
# -*- coding: utf-8 -*- """ Container for building a scene with fluorescent objects (i.e., scene plays a role of background or frame). @author: ssklykov """ # %% Imports import numpy as np import matplotlib.pyplot as plt # from skimage.util import img_as_ubyte import os from skimage.io import imsave from scipy.ndimage...
the-stack_0_804
# Copyright 2019 BlueCat Networks (USA) Inc. and its affiliates # -*- coding: utf-8 -*- # # 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 # # Unle...
the-stack_0_806
import sys import spider from spider_ui import Ui_Dialog, QtWidgets, QtGui class SpiderDialog(QtWidgets.QDialog): def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_Dialog() self.ui.setupUi(self) self.spider = spider.RenrenSpider() self.init_signals() ...
the-stack_0_808
# coding: utf-8 """ DocuSign Click API DocuSign Click lets you capture consent to standard agreement terms with a single click: terms and conditions, terms of service, terms of use, privacy policies, and more. The Click API lets you include this customizable clickwrap solution in your DocuSign integrations. ...
the-stack_0_809
############################################################################### # Copyright Keith Butler(2014) # # # # This file MacroDensity.density_tools.py is free software: you can # ...
the-stack_0_810
import sys sys.path.append("../../") def press(btn): if btn == "SUB": app.showSubWindow("Sub") app.hide() if btn in ["POPUP2", "POPUP"]: app.infoBox("INFO", "INFO") if btn == "MAIN": app.show() app.hideSubWindow("Sub") def closer(btn=None): print("aaa") from a...
the-stack_0_811
from __future__ import print_function, division import os import re import datetime import sys from os.path import join, isdir, isfile, dirname, abspath import pandas as pd import yaml import psycopg2 as db from nilmtk.measurement import measurement_columns from nilmtk.measurement import LEVEL_NAMES from nilmtk.datasto...
the-stack_0_813
#!/usr/bin/env python import urllib from decimal import Decimal from getpass import getpass import click from stellar_base import exceptions from stellar_base.address import Address from stellar_base.builder import Builder from stellar_base.keypair import Keypair from config import configs from validate import valida...
the-stack_0_814
#!/usr/bin/python # Copyright (c) 2012 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Convience file system related operations.""" import os import shutil import sys import tempfile import platform import time ...
the-stack_0_817
"""Command-line tool to find out where a particular chip or board resides. The ``spalloc-where-is`` command allows you to query boards by coordinate, by physical location, by chip or by job. In response to a query, a standard set of information is displayed as shown in the example below:: $ spalloc-where-is --job...
the-stack_0_818
# [1081] 不同字符的最小子序列 # https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters/description/ # * algorithms # * Medium (53.88%) # * Total Accepted: 6.7K # * Total Submissions: 12.5K # * Testcase Example: '"bcabc"' # 返回字符串 text 中按字典序排列最小的子序列,该子序列包含 text 中所有不同字符一次。 # # 示例 1: # 输入:"cdadabcc" #...
the-stack_0_823
numbers = list() while True: num = int(input('Insert a number: ')) numbers.append(num) cont = str(input('Do you want to continue? [y/n]: ')).lower().strip()[0] while cont not in 'yn': cont = str(input('Do you want to continue? [y/n]: ')).lower().strip()[0] if cont == 'n': break print...
the-stack_0_824
# Copyright 2018 The Cirq Developers # # 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 ...
the-stack_0_825
"""Tests related to creating ingest definition""" import json import os import unittest from rf.models import Scene from rf.ingest.landsat8_ingest import get_landsat8_layer class Landsat8LayerTestCase(unittest.TestCase): """Test that we can create a layer from Landsat 8 scenes""" def setUp(self): cw...
the-stack_0_826
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
the-stack_0_829
import argparse import collections import json import os import numpy as np import torch import yaml __all__ = [ "load_config", "save_config", "flatten_dict", "sanitize_dict", "update_namespace", "extract", "s2b", "g", ] # Load config file def load_yaml(f_path): with open(f_path, ...
the-stack_0_830
# -*- coding:utf-8 -*- import unittest class TestZip(unittest.TestCase): TESTDATA = [ ("aabbb" , "a2b3"), ("aaaa", "a4"), ("abc", "abc"), ("abcdd","abcdd") ] def setUp(self): self.judge = Zipper() def testsame(self): for src, exp...
the-stack_0_831
# Copyright (c) 2021 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 app...
the-stack_0_833
# Copyright (c) 2009-2019 The Regents of the University of Michigan # This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. # Maintainer: jglaser / All Developers are free to add commands for new features R""" Potentials between special pairs of particles Special pairs are used to imp...
the-stack_0_834
#!/usr/bin/python3 """ fasttextRun.py: run fasttext via python interface usage: fasttextRun.py -f file [-n N] note: default number of N is 10 (10-fold cross validation) 20180105 erikt(at)xs4all.nl """ import fasttext import os import random import splitFile import sys COMMAND = sys.argv.pop(0) DIM = 3...
the-stack_0_836
# coding: utf8 from .tsv_utils import complementary_list, find_label, baseline_df, chi2 from clinicaaddl.tools.deep_learning.iotools import return_logger from scipy.stats import ttest_ind import shutil import pandas as pd from os import path import numpy as np import os import logging sex_dict = {'M': 0, 'F': 1} de...
the-stack_0_837
# -*- encoding: utf-8 -*- # pylint: disable=E0203,E1101,C0111 """ @file @brief Runtime operator. """ import numpy from ._op import OpRun class ConstantOfShape(OpRun): atts = {'value': numpy.array([0], dtype=numpy.float32)} def __init__(self, onnx_node, desc=None, **options): OpRun.__init__(self, onn...
the-stack_0_838
#!/usr/bin/env python3 import argparse import json import os from patrace import ( InputFile, OutputFile, Call, CreateInt32Value, ) class Arg: def __init__(self, type, name, value): self.type = type self.name = name self.value = value def get(self): arg = self....
the-stack_0_841
import sympy as sym # Computing with Dirichlet conditions: -u''=2 and sines x, L = sym.symbols('x L') e_Galerkin = x*(L-x) - 8*L**2*sym.pi**(-3)*sym.sin(sym.pi*x/L) e_colloc = x*(L-x) - 2*L**2*sym.pi**(-2)*sym.sin(sym.pi*x/L) # Verify max error for x=L/2 dedx_Galerkin = sym.diff(e_Galerkin, x) print((dedx_Galerkin.su...
the-stack_0_842
# -*- coding: utf-8 -*- """ This module exports functions to initialize the Flask application. """ import random from typing import Callable, Dict import flask import flask_babel import orchard.errors import orchard.extensions import orchard.system_status def create_app(config: str = 'Development') -> flask.F...
the-stack_0_843
import functools import re from typing import Any, Dict, Optional, Tuple, Union from urllib.parse import urlsplit from django.apps import apps from django.contrib.auth.models import AnonymousUser from django.http import HttpRequest, JsonResponse from django.utils import timezone from rest_framework import authenticati...
the-stack_0_844
import attr import logging import os from datetime import datetime from feedparser import parse as parse_feed from typing import List, Optional from telegram_rss.config import FeedConfig from telegram_rss.utils import save_as, get_default_directory, load_dict from . import Entry, Channel, Feed class FeedUpdater: ...
the-stack_0_845
#Imports library import socket #Creates instance of 'Socket' s = socket.socket() hostname = 'tutorialspi' #Server IP/Hostname port = 8000 #Server Port s.connect((hostname,port)) #Connects to server while True: x = raw_input("Enter message: ") #Gets the message to be sent s.send(x.encode()) #Encodes and send...
the-stack_0_846
from cs50 import get_string import re def letters_counter(t, a): c = 0 for i in t: if i in a or i in [j.upper() for j in a]: c += 1 return c def words_counter(t): match = re.split(" ", t) return len(match) def sentences_counter(t): match = re.split("[.!?]", t) return l...
the-stack_0_847
import pytest from .common import JSON, Cookies, Headers, Query, Resp, get_paths from .test_plugin_falcon import api as falcon_api from .test_plugin_flask import api as flask_api from .test_plugin_flask_blueprint import api as flask_bp_api from .test_plugin_flask_view import api as flask_view_api from .test_plugin_sta...
the-stack_0_852
from collections import OrderedDict from collections.abc import Iterable from cached_property import cached_property import numpy as np import sympy from devito.finite_differences.finite_difference import (generic_derivative, first_derivative, ...
the-stack_0_853
#!/usr/bin/env python # encoding: utf-8 """ untitled.py Created by Olivier Huin on 2010-02-20. Copyright (c) 2010 Flarebyte.com Limited. All rights reserved. """ import sys import os activitykinds={ ('shortid', 'uuid', 'visiting', 'visiting', ['visiting']), ('shortid', 'uuid', 'booking', 'booking', ['booking']), ('s...