text
stringlengths
1
927k
#!/usr/bin/env python # -*- coding: utf-8 -*- from pymisp import PyMISP from keys import misp_url, misp_key import argparse # For python2 & 3 compat, a bit dirty, but it seems to be the least bad one try: input = raw_input except NameError: pass def init(url, key): return PyMISP(url, key, True, 'json', ...
# coding: utf-8 # In[ ]: import pandas as pd import random,time,csv import numpy as np import math,copy,os from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeRegressor from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, confusi...
import tensorflow as tf import numpy as np class TextCNN(object): """ A CNN for text classification. Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer. """ def __init__( self, sequence_length, num_classes, vocab_size, embedding_size, filte...
from envs.common import * if False: MIDDLEWARE_CLASSES = ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) + MIDDLEWARE_CLASSES INSTALLED_APPS += ("debug_toolbar", ) SSLIFY_DISABLE = True INTERNAL_IPS = ('127.0.0.1',) # Uncomment to turn on intercom # ANALYTICAL_INTERNAL_IPS = []
from django.db.models.deletion import DO_NOTHING from django.db.models.fields.related import ForeignKey, ManyToManyField, \ resolve_relation, lazy_related_operation from django.db.models.query_utils import Q from django.db.models.sql.datastructures import Join from django.db.models.sql.where import ExtraWhere, Wher...
from .settings import * DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
import sys if sys.version_info < (3, 7): from ._ysrc import YsrcValidator from ._yperiodalignment import YperiodalignmentValidator from ._yperiod0 import Yperiod0Validator from ._yperiod import YperiodValidator from ._yhoverformat import YhoverformatValidator from ._ycalendar import YcalendarVa...
#! /usr/bin/env python """Author: Scott Staniewicz utils.py: Miscellaneous helper functions Email: scott.stanie@utexas.edu """ from __future__ import division, print_function import contextlib import datetime import copy import errno import sys import os import subprocess import numpy as np import itertools from apert...
#!/usr/bin/env python """Utils common to macOS and Linux.""" import io import logging import os import threading import time from typing import Text import psutil import xattr from google.protobuf import message from grr_response_core import config from grr_response_core.lib import rdfvalue from grr_response_core.li...
# main.py # # Copyright 2020 Ferdinand Macha # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distr...
from typing import Optional, cast from mypy.checker import TypeChecker from mypy.nodes import ListExpr, NameExpr, StrExpr, TupleExpr, TypeInfo, Var from mypy.plugin import FunctionContext from mypy.types import ( AnyType, CallableType, Instance, TupleType, Type, TypeOfAny, UnionType, ) from mypy_django_plugin imp...
#!/usr/bin/env python3 # Copyright (c) 2018 The Motif Project # # 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, th...
# python standard library import unittest # third-party from mock import MagicMock # the ape from optimization.infrastructure.arguments.fetcharguments import Fetch, FetchStrategy from optimization.infrastructure.arguments.basestrategy import BaseStrategy import optimization.infrastructure.arguments.fetcharguments f...
from __future__ import absolute_import, division, print_function, unicode_literals import torch from tests.utils import jitVsGlow import pytest def test_quantized_conv2d(): """Basic test of the PyTorch quantized onv2d Node on Glow.""" def test_f(a, w, b): qu = torch.nn.quantized.Quantize(1/16, 0, t...
class DefaultConfigs(object): # 1.string parameters train_data = "./data/train/" test_data = "./data/test/" test_one_data = "./data/onetest/" val_data = "no" model_name = "resnet50" weights = "./checkpoints/" best_models = weights + "best_model/" submit = "./submit/" logs = "./lo...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # LICENSE file in the root directory of this source tree. # this script is a prototype implementation of transferring H...
from typing import Dict class Average: """Implements a simple running average counter.""" def __init__(self): self.total = 0 self.n_steps = 0 def update(self, value: float) -> None: self.total += value self.n_steps += 1 def compute(self) -> float: return self....
import io from setuptools import setup, find_packages # Read in the README for the long description on PyPI def long_description(): with io.open('README.md', 'r', encoding='utf-8') as f: readme = f.read() return readme setup(name='custom-mathlib', version='0.0.3', url='https://github.com/hy...
"""The tests for the Template fan platform.""" import pytest import voluptuous as vol from homeassistant import setup from homeassistant.components.fan import ( ATTR_DIRECTION, ATTR_OSCILLATING, ATTR_PERCENTAGE, ATTR_PRESET_MODE, DIRECTION_FORWARD, DIRECTION_REVERSE, DOMAIN, SUPPORT_PRE...
# Copyright 2013-2022 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 DingLibs(AutotoolsPackage): """A meta-package that pulls in libcollection, libdhash, libin...
# -*- coding: utf-8 -*- # Copyright (c) 2018-2020 Linh Pham # reports.wwdt.me is relased under the terms of the Apache License 2.0 """WWDTM Panelist vs Panelist Scoring Report Functions""" from collections import OrderedDict from typing import Dict, List import mysql.connector #region Retrieval Functions def retrieve...
from typing import TypeVar, Callable from phi import math from phi.geom import Geometry, Box from phi.math import Shape, Tensor, Extrapolation, channel from phi.math._tensors import Sliceable, BoundDim class Field(Sliceable): """ Base class for all fields. Important implementations: * Cente...
"""CSC110 Fall 2021 Project This module interacts directly with the Twitter API to download tweets and users. It contains functions related scraping users/tweets, including: - getting the tweets of a user - downloading many users by checking their followers and follower's followers, etc. """ import json import math im...
from .bissecao import Bissecao
import asyncio def asyncio_setup(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) return loop
import base64 from io import BytesIO import matplotlib from matplotlib import pyplot as plt import pandas as pd import numpy as np from databricks import koalas from databricks.koalas.config import set_option, reset_option from databricks.koalas.plot import TopNPlot, SampledPlot from databricks.koalas.exceptions impo...
# This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0 # which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 # from typing import Generator, Tuple from volatility.framework import constants from volatility.framework import objects, interfaces...
from warnings import warn import numpy as np import pandas as pd from pandas import DataFrame, Series from shapely.geometry import box from shapely.geometry.base import BaseGeometry from shapely.ops import cascaded_union from .array import GeometryArray, GeometryDtype def is_geometry_type(data): """ Check ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Oct 10 15:03:51 2020 @author: Konstantin Schuckmann """ ############################################################################################# ############################################ DUMMY ########################################## ########...
# Generated by Django 3.2.7 on 2021-09-24 09:50 import django.contrib.postgres.fields from django.db import migrations, models import django_countries.fields import hashid_field.field class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel(...
from decimal import Decimal import pytest from hypothesis import example, given, settings from hypothesis import strategies as st from vyper import ast as vy_ast from vyper.exceptions import TypeMismatch, ZeroDivisionException st_decimals = st.decimals( min_value=-(2 ** 32), max_value=2 ** 32, allow_nan=...
from django.conf import settings from django.db import models from django.utils import timezone class Homework(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, editable=False) subject = models.CharField(max_length=200) task = models.TextField() due_date = mod...
# Generated by Django 2.0.7 on 2018-07-23 09:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0017_auto_20180723_1735'), ] operations = [ migrations.AlterField( model_name='user', name='gender', ...
# richard -- video index system # Copyright (C) 2012, 2013, 2014, 2015 richard contributors. See AUTHORS. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the Licens...
# Time: ctor: O(n), # update: O(logn), # query: O(logn) # Space: O(n) # 307 # Given an integer array nums, find the sum of # the elements between indices i and j (i <= j), inclusive. # # The update(i, val) function modifies nums by # updating the element at index i to val. # Example: # Given nums = [...
from faker.factory import Factory from faker.generator import Generator from faker.proxy import Faker VERSION = '8.2.0' __all__ = ('Factory', 'Generator', 'Faker')
import sst.actions sst.actions.assert_equal(1, 1) sst.actions.assert_equal('foo', 'foo') sst.actions.fails(sst.actions.assert_equal, 1, 2) sst.actions.fails(sst.actions.assert_equal, 'foo', 'bar') sst.actions.assert_not_equal(1, 2) sst.actions.assert_not_equal('foo', 'bar') sst.actions.fails(sst.actions.assert_not...
# Generated by Django 3.1.2 on 2020-10-26 11:50 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Country', fields=[ ...
# # ElementTree # $Id: ElementInclude.py 1862 2004-06-18 07:31:02Z Fredrik $ # # limited xinclude support for element trees # # history: # 2003-08-15 fl created # 2003-11-14 fl fixed default loader # # Copyright (c) 2003-2004 by Fredrik Lundh. All rights reserved. # # fredrik@pythonware.com # http://www.pythonware...
from muwgs import english_dict from itertools import permutations def word_twister(s: str, n: int): arr = [] for x in permutations([s[i] for i in range(len(s))], n): arr.append(''.join([x[i] for i in range(n)])) arr = [x for x in list(set(arr)) if english_dict.check(x)] arr.sort() return a...
# Copyright 2018-2021 Xanadu Quantum Technologies 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...
from rest_framework import viewsets from .serializers import PlaceSerializer, AlternativeNameSerializer from .models import Place, AlternativeName class PlaceViewSet(viewsets.ModelViewSet): queryset = Place.objects.all() serializer_class = PlaceSerializer depth = 2 class AlternativNameViewSet(viewsets.M...
from setuptools import setup, find_packages from os import path, environ cur_dir = path.abspath(path.dirname(__file__)) with open(path.join(cur_dir, 'requirements.txt'), 'r') as f: requirements = f.read().split() setup( name='pmd-beamphysics', version = 'v0.3.0', #packages = ['pmd_beamphysics'], ...
from enum import Enum class ErrorCode(Enum): ErrorOk = 0 Error = 1 ErrorMessage = {ErrorCode.ErrorOk: "", ErrorCode.Error: "is illegal"} class ConnectionErrorMessage: NoHostPort = "connection configuration must contain 'host' and 'port'" HostType = "Type of 'host' must be str!" ...
""" Annotation. Do not edit this file by hand. This is generated by parsing api.html service doc. """ from ambra_sdk.exceptions.service import InvalidJson from ambra_sdk.exceptions.service import MissingFields from ambra_sdk.exceptions.service import NotFound from ambra_sdk.exceptions.service import NotPermitted from ...
# -*- coding: utf-8 -*- # Copyright 2020 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...
#!/usr/bin/python3 ### # # MIT License # # Copyright (c) 2016 Daniela Kilian, Lea Reisinger, Martin Drawitsch # # 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...
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test resendwallettransactions RPC.""" from test_framework.test_framework import HodlCashTestFramework from ...
''' 9-plot_flux.py ========================= AIM: Plot maps of the stray light flux or equivalent magnitude given a particular date INPUT: files: - <orbit_id>_misc/orbits.dat - <orbit_id>_flux/flux_*.dat - resources/moon_*.dat, sun_*.dat, orbits_*.dat variables: see section PARAMETERS (below) OUTPUT: in <orbit_...
# -*- coding: utf-8 -*- """The main Instagram scraping module.""" from app.backend.scraping.instagram._instagram_class import Instagram def caller_instagram(query: str) -> dict: """ Call other Instagram scraping functions to get filtered info about person. Args: `query`: the query to run Instagr...
import sys from itertools import combinations def main(): input = sys.stdin.readline A = list(map(int, input().split())) C = [sum(c) for c in combinations(A, 3)] C = sorted(C, key=lambda x: -x) return C[2] if __name__ == '__main__': print(main())
import random from away_actions.away_actions import AwayAction from careers.career_enums import CareerCategory from careers.career_tuning import Career from drama_scheduler.drama_node_ops import ScheduleDramaNodeLoot from element_utils import build_critical_section_with_finally from event_testing.resolver import Single...
import base64 import io import json import logging from typing import Any, Dict import numpy as np from PIL import Image from src.app.backend.redis_client import redis_client logger = logging.getLogger(__name__) def make_image_key(key: str) -> str: return f"{key}_image" def left_push_queue(queue_name: str, ke...
# -*- coding: utf-8 -*- # MIT License # Copyright (c) 2018-2020 Renondedju # 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...
""" Created on Feb 9, 2016 @author: Chris Smith """ from __future__ import division, print_function, absolute_import, unicode_literals import os import numpy as np from skimage.measure import block_reduce import h5py from .df_utils.dm_utils import read_dm3 from pyUSID.io.image import read_image from pyUSID.io.tran...
# -*- coding: utf-8 -*- """ point ~~~~~ :copyright: (c) 2017 by Tsuyoshi Tokuda :license: MIT, see LICENSE for more details. """ from __future__ import absolute_import __version__ = "0.0.1" __license__ = "MIT"
#!/usr/bin/env python # Retrieved from http://ecdsa.org/ecdsa.py on 2011-10-17. # Thanks to ThomasV. # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, o...
__author__ = 'lorcan' # get int from user # get a base from user to convert int to # get BASE_X string # convert BASE_X string back to integer # get int from user myStr = input("Enter an integer to convert whatever base you want: ") while myStr.isdigit() == False: print( "\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!...
#!/usr/bin/env python3 import sys from conll2t9corpus import mapping def mb_escape(s): if '"' in s or ',' in s: replaced = s.replace('"', '""') return f'"{replaced}"' return s def process(fd): for line in fd: line = line.rstrip('\n\r') if line.startswith("#"): ...
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import logging import os import sys import time from contextlib import contextmanager from threading import Lock from typing import Dict, Tuple from pants.base.exiter import PANTS_FAILED_...
import os from tqdm import tqdm import numpy as np import pandas as pd import cv2 import time import re import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' from deepface import DeepFace from deepface.extendedmodels import Age from deepface.commons import functions, realtime, distance as dst def analysis(db_path = '',...
""" Rewrite of spec/ui_specs/tokens/billing_read_spec.rb """ import pytest from testsuite.ui.views.admin.settings.tokens import Scopes, TokenNewView from testsuite.utils import blame @pytest.fixture(scope="module") def token(custom_admin_login, navigator, request, threescale, permission): """ Create token w...
from django.db import models from .default import AnyFileField __all__ = ('AnyFileField', 'AnyImageField') class AnyImageField(models.ImageField): """ The standard Django `~django.forms.widgets.ImageField` with a preview. """ def formfield(self, **kwargs): from any_imagefield.forms.fields imp...
from __future__ import absolute_import, division, print_function from distutils.version import LooseVersion from matplotlib import __version__ from glue.viewers.common.python_export import code, serialize_options from glue.utils import nanmin, nanmax MATPLOTLIB_GE_30 = LooseVersion(__version__) > '3' def python_e...
# Copyright 2013-2020 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) class PyGoogledrivedownloader(PythonPackage): """Minimal class to download shared files from Google Drive.""" ho...
# Copyright 2019 Huawei Technologies 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 to...
from dataclasses import dataclass from .t_signal_event_definition import TSignalEventDefinition __NAMESPACE__ = "http://www.omg.org/spec/BPMN/20100524/MODEL" @dataclass class SignalEventDefinition(TSignalEventDefinition): class Meta: name = "signalEventDefinition" namespace = "http://www.omg.org/...
#!/usr/bin/python """high-level functions to make relevant plots """ import matplotlib as mpl # we do this because sometimes we run this without an X-server, and this backend doesn't need # one. We set warn=False because the notebook uses a different backend and will spout out a big # warning to that effect; that's unn...
from .orders import OrdersApiWrapper from .products import ProductsApiWrapper
#!/usr/bin/env python # # License: BSD # https://raw.githubusercontent.com/splintered-reality/py_trees/devel/LICENSE # ############################################################################## # Documentation ############################################################################## """ .. argparse:: :mo...
from setuptools import setup setup( name='traf', version='1.0', py_modules=['traf'], install_requires=[ 'Click', 'numpy>=1.19.2', ], tests_requires=[ 'pytest', ], entry_points=''' [console_scripts] traf=traf.main:main ''' )
import dash_bootstrap_components as dbc from dash import html class CreateCard: def __init__(self): self.card = None def get(self): return self.card class CreateProjectCard(CreateCard): def __init__(self, project_name, description): super().__init__() self.card = html....
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "webMatBackEnd.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
from main import app from factory import db from models import Post, User from datetime import datetime with app.app_context(): users = User.query.all() for index, user in enumerate(users): user.password = f"secret{index}" db.session.commit() # for post in user.posts: # print(post....
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Jul 12 11:32:57 2018 @author: ernestmordret """ import argparse from params import * import os parser = argparse.ArgumentParser() parser.add_argument("-d", "--detect", action="store_true", help="run the detect script only.") pa...
from tardis.plasma.base import BasePlasma from tardis.plasma.standard_plasmas import LTEPlasma
from random import random import PIL.Image import PIL.ImageOps import PIL.ImageEnhance import PIL.ImageDraw __all__ = [ 'transform', 'check_augment_min_max', ] def _random_flip(v): return v if random() < 0.5 else -v def _affine(img, matrix, fillcolor): return img.transform(img.size, PIL.Image.AFFIN...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # File : normal_clsf.py # Author : Chi Han, Jiayuan Mao # Email : haanchi@gmail.com, maojiayuan@gmail.com # Date : 13.08.2019 # Last Modified Date: 18.08.2019 # Last Modified By : Chi Han, Jiayuan Mao # # This file is part ...
# 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, ...
""" PyVEX provides an interface that translates binary code into the VEX intermediate represenation (IR). For an introduction to VEX, take a look here: https://docs.angr.io/advanced-topics/ir """ __version__ = (8, 19, 10, 30) if bytes is str: raise Exception("This module is designed for python 3 only. Please inst...
# 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 applic...
# Author: David Goodger # Contact: goodger@users.sourceforge.net # Revision: $Revision: 2224 $ # Date: $Date: 2004-06-05 21:40:46 +0200 (Sat, 05 Jun 2004) $ # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutil...
x, y = 0, 0 current_direction = 0 visited = set() visited_twice = None with open("input.txt") as io: for instruction in io.read().split(", "): direction = instruction[0] if direction == "R": current_direction += 1 elif direction == "L": current_direction -= 1 ...
#!/usr/bin/python3 -i # # Copyright (c) 2015-2020 The Khronos Group Inc. # Copyright (c) 2015-2020 Valve Corporation # Copyright (c) 2015-2020 LunarG, Inc. # Copyright (c) 2015-2020 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the ...
class LinkedList(): """ A Linked List uses nodes and pointers to adjacent nodes to make up the list This allows for easy insertion and deletion, but is a bit inefficient (relatively speaking) This implementation will be a doubly linked list """ def __init__(self): # Just a length that will be incremented upon ...
""" Copyright (c) 2022 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 applicable law or agreed to in writin...
#!/usr/bin/python # -*- coding: utf-8 -*- """ This script can be used to change one image to another or remove an image. Syntax: python pwb.py image image_name [new_image_name] If only one command-line parameter is provided then that image will be removed; if two are provided, then the first image will be replac...
import cv2 import numpy as np from tensorflow.keras.models import load_model from tensorflow.keras.preprocessing.image import img_to_array class OCR(): def __init__(self): self.loaded_model = None self.load_models() def load_models(self): self.loaded_model = load_model("digits.h5") return def predi...
"""Define the acceptable URLs for protocols.""" from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index') ]
#!/usr/bin/env python3 # Copyright (c) 2020, Stanislav Zhelnio # SPDX-License-Identifier: MIT """ Layer management script for github.com/jgraph/drawio Allows to list/show/hide layers on diagram page Tested with draw.io 13.6.2 """ import argparse from os import error import sys import xml.etree.ElementTree as ET from...
class Solution: def singleNumber(self, nums): b1,b2 = 0,0 for n in nums: b1 = (b1 ^ n) & ~ b2 b2 = (b2 ^ n) & ~ b1 return b1 if __name__ == "__main__": solution = Solution() print(solution.singleNumber([1])) print(solution.singleNumber([2,2,1,2])) p...
from snappy import ProductIO, HashMap, GPF import os def apply_orbit_file(product): parameters = HashMap() parameters.put("Apply-Orbit-File", True) operator_name = "Apply-Orbit-File" target_product = GPF.createProduct(operator_name, parameters, product) return target_product def thermal_noise_re...
from .main import Main class CBtcmanager(Main): def __init__(self, link, posts, handbook): Main.__init__(self, link, posts, handbook) self.menu = [ 'Bitcoin', 'Blockchain News', 'Ethereum News', 'Mining News', 'Finance News', 'Business News', 'Technology', 'Comm...
boys = ['John', 'Jack', 'Jeremy'] girls = ['Mary', 'Nancy', 'Joyce'] names = [*boys, *girls]
# -*- coding: utf-8 -*- # Copyright (c) 2019-2020 Christiaan Frans Rademan <chris@fwiw.co.za>. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the ...
from logging.config import fileConfig from sqlalchemy import engine_from_config from sqlalchemy import pool from alembic import context # Add live_api folder to python path in oder to import metadata import sys import os api_path = f'{os.getcwd()}' if "{{cookiecutter.project_name}}" not in api_path: raise Valu...
import numpy as np from .utils import is_scalar def li_ma_significance(n_on, n_off, alpha=0.2): """ Calculate the Li & Ma significance. Formula (17) doi.org/10.1086/161295 This functions returns 0 significance when n_on < alpha * n_off instead of the negative sensitivities that would result fro...
# -*- coding: utf-8 -*- # # scikit-aero documentation build configuration file, created by # sphinx-quickstart on Sun Mar 3 22:33:42 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # #...
# -*- coding: utf-8 -*- import py import sys, random from rpython.rlib import runicode def test_unichr(): assert runicode.UNICHR(0xffff) == u'\uffff' if runicode.MAXUNICODE > 0xffff: if sys.maxunicode < 0x10000: assert runicode.UNICHR(0x10000) == u'\ud800\udc00' else: ...