content
stringlengths
5
1.05M
""" Created on: 30 June 2019 Investigate stationarity of time series (example of security data), analytics on log-returns Provide summary statistics on the data Introduce tests (such as Augmented Dickey Fuller) to check stationarity of time series Inspiration from: https://www.analyticsvidhya.com/blog/2018/09/non-stat...
import scrapy class ItcastSpider(scrapy.Spider): name = 'itcast' allowed_domains = ['itcast.cn'] start_urls = ['http://www.itcast.cn/channel/teacher.shtml'] def parse(self, response): filename = "teacher.html" open(filename, 'w').write(response.body)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 28 16:14:58 2021 @author: marina """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 2 20:41:01 2021 @author: marina """ # Set absolute package path import sys, os sys.path.append(os.path.abspath("..")) import os import ext...
import pytest from model_mommy import mommy from usaspending_api.common.recipient_lookups import obtain_recipient_uri @pytest.fixture def recipient_lookup(db): parent_recipient_lookup = {"duns": "123", "recipient_hash": "01c03484-d1bd-41cc-2aca-4b427a2d0611"} recipient_lookup = {"duns": "456", "recipient_ha...
"""This module implements the models for the Blog core system.""" from app.models.acl import AccessControlMixin from app.models.patch import CommentMixin, StatusMixin, TagMixin from app.models import db class Post(AccessControlMixin, StatusMixin, CommentMixin, TagMixin, db.Model): """Implements the Post model. ...
# Time Limit Exceeded # class Solution(object): # def threeSum(self, nums): # """ # :type nums: List[int] # :rtype: List[List[int]] # """ # nums.sort() # triplates = [] # for i in range(len(nums) - 2): # if i > 0 and nums[i] == nums[i - 1]: # ...
import matplotlib.pyplot as plt import matplotlib.patches as patches from matplotlib.path import Path import json import numpy as np from pymongo import MongoClient import requests from StringIO import StringIO from PIL import Image zid = 'ARG0001n7u' client = MongoClient('localhost', 27017) db = client['radio'] sub...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Dell EMC OpenManage Ansible Modules # Version 3.0.0 # Copyright (C) 2020-2021 Dell Inc. or its subsidiaries. All Rights Reserved. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # from __future__ import (absolute_import, divi...
from django.db import IntegrityError from Poem.api.views import NotFound from Poem.helpers.history_helpers import create_history from Poem.poem import models as poem_models from rest_framework import status from rest_framework.authentication import SessionAuthentication from rest_framework.response import Response fr...
from operator import mul as _mul from functools import reduce as _reduce def product(iterable): """ Returns the product of an iterable If the list is empty, returns 1 """ return _reduce(_mul, iterable, 1)
#!/usr/bin/env python import argparse parser = argparse.ArgumentParser(description="Go through the chunks.dat file and segment the dataset into chunks.") parser.add_argument("--plot", action="store_true", help="Make plots of the partitioned chunks.") args = parser.parse_args() import os import psoap.constants as C ...
from django import forms from transport.models import Transport from django.utils.translation import gettext_lazy as _ from units.models import Goods class TransportForm(forms.ModelForm): address = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'id':"addressAutocomplete"})) class Meta: ...
import numpy as np import matplotlib.pyplot as plt from jump_reward_inference.state_space_1D import beat_state_space_1D, downbeat_state_space_1D class BDObservationModel: """ Observation model for beat and downbeat tracking with particle filtering. Based on the first character of this parameter, each...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'download_new.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(...
""" Definitions of sections to be used in definitions of input parameters (input files for SPR-KKR tasks) """ from ...common.grammar_types import DefKeyword, SetOf, Flag, energy from ..input_parameters_definitions import \ SectionDefinition as Section, \ ValueDefinition as V def CONTROL(ADSI): """ Crea...
""" isinstance() 函数来判断一个对象是否是一个已知的类型,返回值是True or False 语法格式:isinstance(object, tuple) 参数: object -- 实例对象。 tuple -- 基本类型或者由它们组成的元组,也可以是直接或间接类名。 """ print(isinstance('hello', (int, str))) #注意不是 string # 父类 class Parent(object): pass #子类 class Sub(Parent): pass #实例化 A = Parent() B = Sub() # isinstance() 会认为...
# -*- coding: utf-8 -*- """ Author-related RESTful API module. """ from flask import request from flask_restful import Resource from flask_sqlalchemy import BaseQuery from marshmallow import ValidationError from .. import auth, db from ..models import Author, author_schema, authors_schema from ..utils import paginat...
from datetime import datetime import re import_file_path = "/Users/hewro/Desktop/test.txt" export_file_path = "/Users/hewro/Desktop/dayone_out.txt" # 如果上一行是日期,紧邻的下一行也是日期,并且两个时间戳一致则该行日期不再录用 last_timestamp = 0.0 repeat_time = 0 day_cout = 0 def parse2time(title): global last_timestamp, repeat_time, day_cout ...
from typing import List import stim from ._zx_graph_solver import zx_graph_to_external_stabilizers, text_diagram_to_zx_graph, ExternalStabilizer def test_disconnected(): assert zx_graph_to_external_stabilizers(text_diagram_to_zx_graph(""" in---X X---out """)) == [ ExternalStabilizer(input...
from sklearn.compose import ColumnTransformer from sklearn.linear_model import LogisticRegression from sklearn.ensemble import IsolationForest from sklearn.pipeline import make_pipeline from sklearn.pipeline import FeatureUnion from sklearn.preprocessing import OneHotEncoder from sklearn.svm import LinearSVC from sklea...
import logging from telegram import Update from telegram.ext import Updater from telegram.ext import CallbackContext from telegram.ext import CommandHandler from telegram.ext import MessageHandler from telegram.ext import Filters from Caller import Caller class TelegramInterface: def __init__(self, token, admin_...
import DecisionTree def main(): #Insert input file """ IMPORTANT: Change this file path to change training data """ file = open('SoybeanTraining.csv') """ IMPORTANT: Change this variable too change target attribute """ target = "class" data = [[]] for line in file: ...
# -*- coding: utf-8 -*- # Copyright (c) 2015, seethersan and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from ovenube_peru.ple_peru.utils import Utils, to_file class LibroElectronicoDiarioSimplificado(Utils): def get_account(self, company, yea...
value = float(input()) print('NOTAS:') for cell in [100, 50, 20, 10, 5, 2]: print('{} nota(s) de R$ {},00'.format(int(value/cell), cell)) value = value % cell print('MOEDAS:') for coin in [1, 0.5, 0.25, 0.10, 0.05, 0.01]: print('{} moeda(s) de R$ {:.2f}'.format(int(value/coin), coin).replace('.',',')) v...
from conans import ConanFile, tools import os class GreatestConan(ConanFile): name = "greatest" version = "1.4.1" url = "https://github.com/bincrafters/conan-greatest" homepage = "https://github.com/silentbicycle/greatest" description = "A C testing library in 1 file. No dependencies, no dynamic a...
from pymongo import MongoClient import pandas as pd import json class MongoUtil: def __init__(self, host='localhost', port=27017): #The only fields that are searchabel self.searchableFields = ['website','username'] try: self.client = MongoClient(host, port) self.db =...
from __future__ import unicode_literals import frappe from frappe.model.utils.rename_field import * def execute(): for doctype in ("Purchase Receipt Item", "Delivery Note Item"): frappe.reload_doctype(doctype) table_columns = frappe.db.get_table_columns(doctype) if "qa_no" in table_columns: rename_field(doc...
import tensorflow as tf input_image_size = 28 output_image_size = 24 input_image_channels = 1 num_labels = 10 valid_records = 5000 test_records = 10000 train_records = 55000 batch_size = 100 def read_path_file(image_file): f = open(image_file, 'r') paths = [] labels = [] for line in f: label,...
''' Script to graph various statistics ''' import os from os import path import sys import itertools from statistics import geometric_mean import argparse import numpy as np import matplotlib.pyplot as plt import seaborn as sns apps = ["bt", "cg", "ep", "ft", "lu", "mg", "sp", "ua", "dc"] ''' Graph data as a bar cha...
from selenium import webdriver import unittest class TablesCheck(unittest.TestCase): def setUp(self): # Define driver self.driver = webdriver.Chrome() # Navigate to the url url = 'http://www.w3schools.com/html/html_tables.asp' self.driver.get(url) def test_get_number_...
# Send model regression test results to Segment with a summary # of all test results. import analytics import datetime import json import os from datadog_api_client.v1 import ApiClient, Configuration from datadog_api_client.v1.api.metrics_api import MetricsApi from datadog_api_client.v1.model.metrics_payload import Me...
from lpd8.programs import Programs from lpd8.pads import Pad, Pads from lpd8.knobs import Knobs class Actions: """ Class used to implement main logic related to LPD8 <> SuperCollider interactions """ _pad_to_bank = { # pads to banks translation dict Pads.PAD_6: 0, Pads.PAD_2: 1...
# -*- coding:utf-8 -*- """ Created on 8/20/2018 Author: wbq813 (wbq813@foxmail.com) """ # 字符串预处理模块,为分析器TimeNormalizer提供相应的字符串预处理服务 import re NUM_MAP = {"零": 0, "0": 0, "一": 1, "1": 1, "二": 2, "2": 2, "两": 2, "三": 3, "3": 3, "四": 4, "4": 4, "五": 5, "...
from turtle import fillcolor from manim import * class Amedee(Scene): def construct(self): name=Tex("Amedee", tex_template=TexTemplateLibrary.ctex, font_size=30).to_edge(UL,buff=1) sq=Square( side_length=2, fill_color=GREEN, fill_opacity=0.75 ...
*d,s="""k= I-~)1 H-~S( 3!4-~( C*~U!0-~L3 :&~luos& L+~laets ot evah yam I dna revo gnuh( +,~a m'I laed a & 9+~c em tel( I-~ereht yeH hsu& M,~sekam epat tcud sih dnA hsur a ni slived eht haeYP#V&~H0 [&~esraeh a dna evarg a naht retteb s'taht sseug I krow fo tuo lla er'ew tub ainrofilaC gni& P$~eW tsao& ]#~ot me' evord uo...
from django_celery_beat.admin import PeriodicTaskForm, TaskChoiceField, CrontabSchedule from django.utils.translation import ugettext_lazy as _ from main.fields import SourceChoiceField, DbTypeChoiceField from main.models import BruteConfig, Dictionary, Database from django import forms from typing import Any import js...
from cinto import contas num = int(input('Digite um valor')) fat = contas.fatorial(num) print(f'O fatorial de {num} é {fat}') print(f'O dobro de {num} é {contas.dobro(num)}') print(f'O triplo de {num} é {contas.triplo(num)}')
# Generated by Django 3.2.4 on 2021-06-22 09:03 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("testapp", "0002_alter_blogpage_channel_id"), ] operations = [ migrations.RemoveField( model_name="blogpage", name="last_upda...
import pandas as pd import numpy as np from scipy.io import loadmat from tqdm import tqdm from noiseceiling.utils import _find_repeats mat = loadmat('data/raw/AU_data_for_Lukas.mat') au_names = [n[0] for n in mat['AUnames'][0]] rename_au = {'AU10Open': 'AU10', 'AU10LOpen': 'AU10L', 'AU10ROpen': 'AU10R', 'AU16Open': 'A...
# app/main.py # FastAPI start app # uvicorn app.main:app --reload from typing import Dict from fastapi import FastAPI, Request, status from ai import utils from app.core import auth, nlp, user from app.database import mongodb # Define app app = FastAPI( title="Zero-Shot Classification API", description="Cla...
import enum class logmessage_types(enum.Enum): sent, received, internal = range(3) class internal_submessage_types(enum.Enum): quit, error = range(2) class controlmessage_types(enum.Enum): quit, reconnect, send_line, ping, ping_timeout = range(5) class cronmessage_types(enum.Enum): quit, schedule, delete, resch...
import argparse import os import numpy as np from sklearn.metrics import confusion_matrix, classification_report from pytorch_transformers import BertTokenizer import nemo import nemo_nlp from nemo_nlp.callbacks.joint_intent_slot import \ eval_iter_callback, eval_epochs_done_callback from nemo_nlp.text_data_utils...
#!/usr/bin/env python # -*- coding: utf-8 -*- import random import hashlib import copy from random import randint from random import choice possible_names = ['Carolina', 'Guilherme', 'Daniel', 'Luna', 'Natalie', 'Elaini', 'Eduarda', 'Isabella', 'Júlia', 'André', 'Thiago', 'Sandra', 'Edson', 'Ossian', 'Laura', 'Dante...
# Copyright 2004-2008 Roman Yakovenko. # Distributed under the Boost Software License, Version 1.0. (See # accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) import os from . import algorithm from . import declaration_based from . import registration_based from pygccxml import declara...
'''A Confederação Nacional de Natação precisa de um programa que leia o ano de nascimento de um atleta e mostre sua categoria, de acordo com a idade: - Até 9 anos: Mirim - Até 14 anos: Infantil - Até 18 anos: Junior - Até 20 anos: Sênior - Acima: Master''' from datetime import date ano = int(input('\033[33mDigite o seu...
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
import torch import shutil import unittest from lstm_dna.loader import load_genbank, divide_sequence from .setup_dirs import setup_dirs class TestLoader(unittest.TestCase): def setUp(self): self.indir, self.workdir, self.outdir = setup_dirs(fpath=__file__) def tearDown(self): shutil.rmtree(s...
from request import Request class Event: def __init__(self, data): self.data = data; def request(self): return Request(self.data['Records'][0]['cf']['request'])
from utility import * class Snake(): def __init__(self, snake): #print("~~~~~~Snake Object Created~~~~~~~") self.id = snake['id'] #print(self.id) self.name = snake['name'] #print(self.name) self.health = snake['health'] #print(self.health) self.coordinates = snake['body'] #print(...
from typing import Any, Tuple from Base.bp2DBin import Bin from Base.bp2DBox import Box from Base.bp2DPnt import Point def face_intersection(b1: Box, b2: Box) -> int: '''Check how much overlap the faces of two rectangles have. Return the overlap, as a face, or return None, if there is no face intersection.''...
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import preprocessing from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, confusion_matrix #Definiamo KNN come modello, in particolar...
#!/usr/bin/env python # # Copyright (c) 2015, 2016, 2017, 2018, 2019, Intel Corporation # # 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 above copyright # ...
import socket serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.bind((socket.gethostname(), 25000)) serversocket.listen() print("Server is listening....") connection, address = serversocket.accept() print("Connection has been established") msg = connection.recv(1024) received=msg.dec...
import datetime import random from datetime import datetime from discord.ext import commands class ProgrammCog(commands.Cog): def __init__(self, bot): self.bot = bot self.programm = ("Hier steht ihr programm",) self.password = "5mal4plus5ergibt25" @commands.command(name='new', help=...
class Song(): def __init__(self, title, artist): self.title=title self.artist=artist self.arr=set() def how_many(self, arr): length=len(self.arr) for i in arr: self.arr.add(i.lower()) return len(self.arr)-length
def solution(A): hashMap = {} # Loop for each element of the original array for i in A: # Check if hashMap has the element and invert the value of true, else add it with initial value of true if i in hashMap: hashMap[i] = not hashMap[i] else: hashMap[i] = Tru...
'''OpenGL extension ARB.instanced_arrays This module customises the behaviour of the OpenGL.raw.GL.ARB.instanced_arrays to provide a more Python-friendly API Overview (from the spec) A common use case in GL for some applications is to be able to draw the same object, or groups of similar objects that share ver...
# Standard library imports import sys import warnings # Local imports from uplink import decorators from uplink.converters import keys, interfaces __all__ = ["json", "from_json", "schema"] class _ReturnsBase(decorators.MethodAnnotation): def _get_return_type(self, return_type): # pragma: no cover retur...
from __future__ import print_function from setuptools import setup, find_packages packages = find_packages(include = 'fastml_engine.**', exclude=['fastml_engine.egg-info']) packages.append('fastml_engine.docs') print(packages) setup( name='fastml_engine', version='1.0.6', author="HaiTao Hou", author...
class Rect: def __init__(self, x, y, w, h): self.x1 = x self.y1 = y self.x2 = x + w self.y2 = y + h def center(self): center_x = int((self.x1 + self.x2) / 2) center_y = int((self.y1 + self.y2) / 2) return (center_x, center_y) def intersect(self, othe...
from cs251tk.common import chdir from cs251tk.common import run def reset(student): with chdir(student): run(['git', 'checkout', 'master', '--quiet', '--force'])
import spacy from spacy.language import Language from spacy.lang.tokenizer_exceptions import URL_MATCH #from thinc.api import Config from .stop_words import STOP_WORDS from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .punctuation import TOKENIZER_PREFIXES, TOKENIZER_SUFFIXES, TOKENIZER_INFIXES from .lex_att...
import unittest import trafaret as t import trafaret_schema class TestConstEnumType(unittest.TestCase): def test_const(self): check = trafaret_schema.json_schema({ 'const': 'blabla', }) self.assertEqual(check('blabla'), 'blabla') check = trafaret_schema.json_schema({ ...
# Knapsack algorithm # prints out the value of the optimal solution a = [] with open('knapsack1.txt', 'r') as doc: for line in doc: a.append(list(map(int, line.split()))) kn_size = a[0][0] + 1 n = a[0][1] + 1 del a[0] A = [[]]*n A[0] = [0]*kn_size for i in range(1, n): A[i] = [0]*kn_size for x in...
import pickle from nose.tools import eq_ from ..row_type import RowGenerator def test_row_type(): MyRow = RowGenerator(["foo", "bar", "baz"]) r = MyRow("15\t16\tNULL") eq_(r.foo, "15") eq_(r['foo'], "15") eq_(r[0], "15") eq_(r.bar, "16") eq_(r['bar'], "16") eq_(r[1], "16") eq_(r....
# Copyright The IETF Trust 2007, All Rights Reserved import os from django.shortcuts import get_object_or_404, render import debug # pyflakes:ignore from ietf.doc.models import State, StateType from ietf.name.models import StreamName def state_index(request): types = StateType.object...
# global import abc from typing import Optional, Union # local import ivy class ArrayWithLosses(abc.ABC): def cross_entropy( self: ivy.Array, pred: Union[ivy.Array, ivy.NativeArray], axis: Optional[int] = -1, epsilon: Optional[float] = 1e-7, *, out: Optional[ivy.Ar...
from dmae import dissimilarities, layers, losses, metrics, initializers, normalizers __all__ = [ "dissimilarities", "layers", "losses", "metrics", "initializers", "normalizers" ]
""" Inspired by https://github.com/tkarras/progressive_growing_of_gans/blob/master/tfutil.py """ import tensorflow as tf import numpy as np seed = 1337 np.random.seed(seed) tf.set_random_seed(seed) # --------------------------------------------------------------------------------------------- # For convenience :) ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Sep 18 20:55:41 2017 @author: virilo """ import numpy as np COLOR_DEPTH=255.0 z=[] eps = - 2.0 * 16.0 / COLOR_DEPTH for n in range(256): normalized=(np.float32(n)/ COLOR_DEPTH) * 2.0 - 1.0 # we add eps normalized=normalized...
class Direction: LEFT = 0 RIGHT = 1 UP = 2 DOWN = 3
from django.contrib.auth.decorators import permission_required from django.core.urlresolvers import reverse, reverse_lazy from django.http import JsonResponse, HttpResponseRedirect from django.utils.decorators import method_decorator from django.views.generic import View, DetailView from django.views.generic.detail imp...
from django.db import models from django.conf import settings from django.contrib.auth.models import (AbstractBaseUser, PermissionsMixin, BaseUserManager ) class UserProfilesManager(BaseUserManager): def create_user(self, email,first_name,last_name, passwor...
__author__ = "Max Dippel, Michael Burkart and Matthias Urban" __version__ = "0.0.1" __license__ = "BSD" import numpy as np class LossWeightStrategyWeighted(): def __call__(self, pipeline_config, X, Y): counts = np.sum(Y, axis=0) total_weight = Y.shape[0] if len(Y.shape) > 1: ...
#! /usr/bin/python from setuptools import setup import os.path setup(name='passencode', version='2.0.0', description='passencode', author='Nicolas Vanhoren', author_email='nicolas.vanhoren@unknown.com', url='https://github.com/nicolas-van/passencodeu', py_modules = [], package...
#!/usr/bin/python import sys import json import os from collections import OrderedDict poolInitialSize = sys.argv[1] poolMaxSize=sys.argv[2] appSettingsFilePath = "/usr/lib64/microsoft-r/rserver/o16n/9.1.0/Microsoft.RServer.ComputeNode/appsettings.json" f = open(appSettingsFilePath, "r") jsondata = f.read().decode("...
"""Unittests for crypto challenges set 1.""" import unittest import encode_decode as set_1 class TestChallenges(unittest.TestCase): """Test if the challenges were correctly implemented.""" def test_decode_hex(self): """Test decoding of hex string.""" self.assertEqual(255, list(set_1.decode_...
import json import logging from pathlib import Path from typing import Dict, Text, Union import requests from requests.exceptions import ConnectionError, Timeout, TooManyRedirects from src.coins.base import Coin from src.lib.config import Config MODULE_LOGGER = logging.getLogger(Path(__file__).name) def get_curren...
def divisibleSumPairs(n, k, ar): numPairs = 0 ar = sorted(ar) for i in range(n-1): for j in range(i,n): if ((ar[i]+ar[j]) % k == 0) and i < j: numPairs +=1 return numPairs if __name__ =="__main__": #ar = [43 ,95 ,51 ,55 ,40 ,86 ,65 ,81 ,51 ,20 ,47 ,50 ,65 ,53 ,...
import torch from matplotlib import pyplot as plt import math π = math.pi torch.manual_seed(4) X = torch.randn(2, 2) Y = torch.zeros(2) Y[0] = 1 s1 = 320 s2 = 26000 s1 = 160 s2 = 120 def R(θ): θ = torch.tensor(θ) return torch.tensor([[torch.cos(θ), -torch.sin(θ)], [torch.sin(θ), torc...
# coding: utf-8 from __future__ import unicode_literals import unittest import responses from admitad.items import LinksValidator from admitad.tests.base import BaseTestCase class LinksValidationTestCase(BaseTestCase): def test_link_validation_request(self): with responses.RequestsMock() as resp: ...
from datetime import datetime from vaccineAvailabilityNotifier.client.actionsImpl import ActionsImpl from vaccineAvailabilityNotifier.util import response_processor_utils def get_url(params={}): return 'https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByDistrict?district_id=' + params[ ...
import sys if sys.version_info < (3, 0): sys.stdout.write("Sorry, requires Python 3.x, not Python 2.x\n") sys.exit(1) import random import itertools import copy import matplotlib.pyplot as plt import matplotlib.animation as animation from time import localtime, strftime import signal import sys im...
from clients import installed_games, steamapi if __name__ == '__main__': api = steamapi.SteamApiClient() games = api.get_player_owned_games() for game in games: game['installed'] = installed_games.is_game_in_installed_games_list(game) for game in sorted(games, key=lambda game: game['name']): ...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
import sys import time import json import requests from PyQt5 import QtGui from PyQt5 import QtWidgets from PyQt5 import QtCore from PyQt5.QtCore import QThread, pyqtSignal, pyqtSlot import design class getPostsThread(QThread): add_post_signal = pyqtSignal(str) def __init__(self, subreddits): "...
#!/usr/bin/python # # 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 ag...
import FWCore.ParameterSet.Config as cms import math muonEfficiencyThresholds = [16, 20, 25] # define binning for efficiency plots # pt effVsPtBins = range(0, 50, 2) effVsPtBins += range(50, 70, 5) effVsPtBins += range(70, 100, 10) effVsPtBins += range(100, 200, 25) effVsPtBins += range(200, 300, 50) effVsPtBins += r...
# -*- coding: utf-8 -*- """ author: zengbin93 email: zeng_bin8888@163.com create_dt: 2021/10/30 20:18 describe: A股市场感应器若干,主要作为编写感应器的示例 强势个股传感器 强势板块传感器 强势行业传感器 大盘指数传感器 """ import os.path import traceback from datetime import timedelta, datetime from collections import OrderedDict import pandas as pd from tqdm import t...
import numpy as np import math import random import matplotlib.pyplot as plt from scipy import stats # declare number of particles used for object track estimation particles = 100 # declare arrays likelihood = np.empty(particles) # calculate likelihood of estimate provided by the particle position estimated = np.em...
#!/usr/bin/python import math import numpy as np import pandas as pd # random generators import random from numpy.random import default_rng from scipy.stats import t # student distribution # matplotlib import matplotlib.pyplot as plt #-----------------------------------------------------------------------------...
import cv2 import numpy as np # Load image, create mask, grayscale, and Otsu's threshold image = cv2.imread('2.png') mask = np.zeros(image.shape, dtype=np.uint8) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1] # Perform morph operations o...
import yaml import pandas as pd import numpy as np import os import yaml this_dir, this_filename = os.path.split(os.path.abspath(__file__)) DATA_PATH = os.path.join(this_dir, '..', "data") def load_mismatch_scores(name_or_path): """ Loads a formatted penalty matrix. Parameters ---------- name_or_path...
# Copyright (C) 2015 SlimRoms 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 agreed to in...
# version VERSION_NAME = 'versionName' VERSION_CODE = 'versionCode'
from abc import ABC import gym from gym import spaces from gym.utils import seeding from gym.envs.registration import register import numpy as np import heapq import time import random import json import os import sys import inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))...
import socket import struct import threading import platform msgDecoded = b"" filenameDecoded = "" def send(filepath:str, socket:socket.socket): try: fObj = open(filepath, "rb") except Exception as err: print(err) return f = fObj.read() bLenFilecontents = struct.pack("!I", len...
''' Created on Jun 24, 2017 @author: lawrencezeng ''' def is_goal(position, goal): for i in xrange(0, len(goal)): for j in xrange(0, len(goal[0])): if position[i + 1][j + 1] != goal[i][j]: return False return True def mismatched_tiles(position, goal): """ Ret...
''' Nutanix REST API Bootcamp. Lesson05. Complex sample. Create Image(vDisk or ISO) from NFS Server. ''' import time import json import requests import urllib3 from urllib3.exceptions import InsecureRequestWarning urllib3.disable_warnings(InsecureRequestWarning) IP = '10.149.20.41' USER = 'admin' PASSWORD = 'Nutanix...
"""Test evaluation base.""" # pylint: disable=import-error,protected-access from unittest.mock import AsyncMock from supervisor.coresys import CoreSys from supervisor.resolution.const import ContextType, SuggestionType from supervisor.resolution.data import Suggestion from supervisor.resolution.fixups.create_full_snap...