content
stringlengths
5
1.05M
from sqlalchemy.orm import Session import random from . import models, schemas def get_corpse(db: Session, corpse_name: str): return (db.query(models.Corpse) .filter(models.Corpse.corpse_name == corpse_name) .first()) def create_corpse(db: Session, corpse_name: str, img: bytes): db_c...
#!python # Author: Thomas Berg <merlin66b@gmail.com> # License: BSD import os import shutil # For this script to run, scons must be installed (http://www.scons.org), # and Microsoft VS2008. # Purpose of this program: Generate all files needed for a C++ build, compile # it with scons, and demonstrate a crash...
# -*- coding: utf-8 -*- import time def generate_sdp(self, ip, audio_port, rtp_profiles, session_description=" "): sdp = "" #Protocol Version ("v=") https://tools.ietf.org/html/rfc4566#section-5.1 (always 0 for us) sdp += "v=0\r\n" #Origin ("o=") https://tools.ietf.org/html/rfc4566#section-5...
class CuboidParams(): def __init__(self): # TODO: put all the relevant parameters at this single place here! # PARAMS FOR THE APROACH PRIMITIVE self.approach_grasp_xy = [0.1, 0.1, 0.09, 0.036195386201143265] self.approach_grasp_h = [0.1, 0.0, 0.0, 0.0] self.approach_duration...
from collections import defaultdict def profile(count_matrix: Dict) -> Dict: """Generate the profile matrix of the given count matrix Arguments: count_matrix {Dict} -- motif count matrix Returns: Dict -- profile matrix of the counts matrix Example: >>> count_matrix =...
"""Models for ripper app.""" import urllib.parse import urllib.request from bs4 import BeautifulSoup from bs4.dammit import EncodingDetector import requests import re from dateutil.parser import parse from dateutil.tz import gettz from django.db import models from django.urls import reverse as reverse_url from djan...
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # 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...
from enum import Enum from random import choices import numpy as np import matplotlib.pyplot as plt from matplotlib import gridspec from mpl_toolkits.axes_grid1 import make_axes_locatable class Direction(Enum): Up = 1 Right = 2 Down = 3 Left = 4 class Position(): x = 0 y = 0 direction = ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Mar 31 21:42:33 2019 @author: george """ import sys import numpy as np from sklearn.linear_model import LogisticRegressionCV from sklearn.model_selection import GridSearchCV from sklearn.ensemble import RandomForestClassifier from sklearn.neural_netwo...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django.contrib.postgres.fields import django.contrib.postgres.fields.hstore from django import VERSION as django_version from django.contrib.postgres.operations import HStoreExtension from django.db import migrations, models try: from django....
"""Tests of session module""" import pytest try: from unittest import mock except ImportError: import mock from rasterio.session import DummySession, AWSSession, Session, OSSSession, GSSession, SwiftSession def test_base_session_hascreds_notimpl(): """Session.hascreds must be overridden""" assert S...
# coding=utf-8 # Copyright 2020 The TF-Agents 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
# -*- coding: utf-8 -*- import uuid import domain_model from domain_model import DomainModel from domain_model import DomainModelWithUuid from misc_test_utils import copy_dict_with_key_removed from misc_test_utils import domain_model_validate_internals_test from misc_test_utils import domain_model_validation_test from...
frase = str(input('Digite uma frase: ')).strip().upper() cont = frase.count('A') pos1 = (frase.find('A')+1) print('A letra A aparece {} vezes na frase.'.format(cont)) print('A primeira letra A apareceu na posição {}.'.format(pos1)) print('A última letra A apareceu na posição {}.'.format(frase.rfind('A')+1))
import torch class OTR(): def __init__(self): self.name = "name" class NormalisedRatio(OTR): def __init__(self): super(NormalisedRatio, self).__init__() def __call__(self, y_1, y_0): ratio = (y_1 - y_0) / y_0 return torch.sigmoid(ratio, 2)
#!/usr/bin/env python """ * ******************************************************* * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved. * SPDX-License-Identifier: MIT * ******************************************************* * * DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT * WARRANTIES OR CONDI...
# cluster from AttentionXML import os import tqdm import joblib import numpy as np from scipy.sparse import csr_matrix, csc_matrix from sklearn.preprocessing import normalize from sklearn.datasets import load_svmlight_file from sklearn.preprocessing import MultiLabelBinarizer def get_sparse_feature(feature...
"""LogTools Log viewer application By BigBird who like to Code https://github.com/bigbirdcode/logtools """ import argparse import io import os import pathlib import sys from textwrap import dedent from typing import Any, NoReturn import wx # Python has 2 types of calls: # - direct call, like: python main.py # - ...
import os import shutil from pathlib import Path from pprint import pprint import csv import time from PIL import Image from datetime import datetime import re import numpy as np from typing import List import cv2 import torch from pytube import YouTube from facenet_pytorch import MTCNN from utils import ( varian...
from rest_framework import status from lego.apps.notifications import constants from lego.apps.notifications.models import Announcement from lego.apps.users.models import AbakusGroup, User from lego.utils.test_utils import BaseAPITestCase class NotificationSettingsViewSetTestCase(BaseAPITestCase): fixtures = [ ...
# This source code is licensed under the license found in the # LICENSE file in the {root}/privgem/tabular/ppgm directory of this source tree. # # This code has been modified from the version at # https://github.com/BorealisAI/private-data-generation/tree/master/models/Private_PGM/mbi # Modifications copyright (C) 2021...
# Demonstrate the use of acceleration test import sys import os import numpy as np from fastsim import simdrive, vehicle, cycle def create_accel_cyc(length_in_seconds=300, spd_mph=89.48, grade=0.0, hz=10): """ Create a synthetic Drive Cycle for acceleration targeting. Defaults to a 15 second acceleration...
#!/usr/bin/env python # Wenchang Yang (wenchang@princeton.edu) # Wed Aug 7 12:49:43 EDT 2019 from .accessor import LinearRegressAccessor
# -*- coding: utf-8 -*- """ Anki Add-on: HTML Cleaner Entry point for the add-on into Anki Please don't edit this if you don't know what you're doing. Copyright: (c) Glutanimate 2017 License: GNU AGPL, version 3 or later; http://www.gnu.org/copyleft/gpl.html """ from .html_cleaner import editor, browser
import abc import asyncio import threading __all__ = () class Wait(abc.ABC): __slots__ = () @abc.abstractmethod def _make_event(self): raise NotImplementedError() @abc.abstractmethod def _make(self, event): raise NotImplementedError() def __call__(self, manage, event = ...
import pytest from vidispine.errors import NotFound def test_delete(vidispine, cassette, collection): vidispine.collection.delete(collection) assert cassette.all_played def test_non_existent_collection(vidispine, cassette): with pytest.raises(NotFound) as err: vidispine.collection.delete('VX-1...
import torch from torch_geometric.utils import contains_isolated_nodes def test_contains_isolated_nodes(): row = torch.tensor([0, 1, 0]) col = torch.tensor([1, 0, 0]) assert not contains_isolated_nodes(torch.stack([row, col], dim=0)) assert contains_isolated_nodes(torch.stack([row, col], dim=0), num_...
# -*- coding: utf-8 -*- from twisted.internet import reactor, protocol, ssl from twisted.mail import imap4 # from twisted.internet import defer # from twisted.python import log # log.startLogging(open("/tmp/twisted.log","w")) # defer.setDebugging(True) from . import debug #@UnresolvedImport # pylint: disable-msg=F0401...
# subsystem mem # memory layout: # 0, value0, 0, value1, ..., value(N-1), 0, 0, 0, 0 # init imm # initialize imm bytes of random-access memory. imm <= 256. # memory should be cleared before loading. # clean # works only after init. clean random-access memory area. # clean fast # doesnt clear values. works on...
""" Plotting Data Module Contains the general class definition and the subclasses of the Clawpack data objects specific to plotting. """ from __future__ import absolute_import from __future__ import print_function import os import copy import numpy as np import re import logging import clawpack.clawutil.data as clawda...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf.urls import patterns, url urlpatterns = patterns( 'pagseguro.views', url( r'^$', 'receive_notification', name='pagseguro_receive_notification' ), )
from collections import abc from pathlib import Path import time import re from threading import Thread from api import audio from api import gui from init_phase import init_phase from viability_phase import viability_phase from evaluation_phase import create_datetime_subdir, evaluation_phase from evaluation_phase im...
import cv2 import numpy as np from matplotlib import pyplot as plt I = cv2.imread('masoleh.jpg') # notice that OpenCV uses BGR instead of RGB! B = I.copy() B[:, :, 1:] = 0 G = I.copy() G[:, :, ::2] = 0 R = I.copy() R[:, :, :2] = 0 cv2.imshow('win1', I) while 1: k = cv2.waitKey() if k == ord('o'): ...
# Standard libraries import os from datetime import datetime as dt from datetime import timedelta # External libraries import pandas as pd class LoadProfileData: def __init__(self,settings, logger): self.logger = logger self.settings = settings # Read all csv files self.read_fil...
from setuptools import setup, find_packages from os.path import join, dirname setup( name='smartRM', version='1.0', author='Andrew Denisevich', author_email='andrew.denisevich@gmail.com', packages=find_packages(), long_description=open(join(dirname(__file__), 'README')).read() } )
import os import time from dataclasses import dataclass from datetime import datetime from typing import Annotated from apischema import deserialize, serialize from apischema.metadata import conversion # Set UTC timezone for example os.environ["TZ"] = "UTC" time.tzset() def datetime_from_timestamp(timestamp: int) -...
''' This file contains the important function that is imported within the module ''' import numpy as np import matplotlib.pyplot as plt from time import time import os import glob from astropy.io import fits from functools import reduce from scipy.interpolate import LSQUnivariateSpline as spline from scipy.interpolat...
# coding: utf-8 # Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. # This product includes software developed at Datadog (https://www.datadoghq.com/). # Copyright 2019-Present Datadog, Inc. from __future__ import absolute_import import sys import unittest im...
# -*- coding: utf-8 -*- # pragma pylint: disable=unused-argument, no-self-use """Function implementation""" import logging from resilient_circuits import ResilientComponent, function, handler, StatusMessage, FunctionResult, FunctionError from fn_ldap_multidomain_utilities.util.helper import LDAPUtilitiesHelper from as...
strIN = input("String to calculate the lenght: ") print(f'Length: {len(strIN)}')
""" <<<<<<<<<<Base Class Initializers>>>>>>>>>>> -> Unlike C++ and Java, Python doesn't automatically call base class initializers. -> __init__ is treated just like any other method. -> If a subclass defines __init__, it must explicitly call the base class implementation for it to be run. """ """ <<<<<<<<<Type Inspect...
import re import stanza import deplacy config = { 'processors': 'tokenize,pos,lemma,depparse', 'lang': 'en', } nlp = stanza.Pipeline(**config) string = "The Old Kingdom is the period in the third millennium also known as the 'Age of the Pyramids' or 'Age of the Pyramid Builders' as it includes the great 4th D...
# -*- coding: utf-8 -*- """ Created on Sun Jun 10 18:05:15 2018 @author: LocalAdmin """ import numpy as np import cv2 from matplotlib import pyplot as plt def read_stereo_image(im="stereo_image_explorer.bmp"): cv_im = cv2.imread(im); imgL = cv_im[0:96, 126:252, :]; imgR = cv_im[0:96, 0:126, :]; retur...
""" Networks used in the main paper """ from mixmo.utils.logger import get_logger from mixmo.networks import resnet, wrn LOGGER = get_logger(__name__, level="DEBUG") def get_network(config_network, config_args): """ Return a new instance of network """ # Available networks for tiny if conf...
""" Application module does all REST API operations on application endpoint """ import random import urllib from common import assert_status_code, assert_content_type_json, \ load_json_schema, assert_valid_schema, assert_valid_schema_error from httpstatus import HTTP_OK, HTTP_NOT_FOUND, HTTP_CREATED...
import logging import time as timer import angr lw = logging.getLogger("CustomSimProcedureWindows") class GetTempFileNameA(angr.SimProcedure): def decodeString(self, ptr): fileName = self.state.mem[ptr].string.concrete return fileName def run(self, lpPathName, lpPrefixString, uUnique, lpTemp...
#!/usr/bin/env python import rospy from std_msgs.msg import UInt16, String from sensor_msgs.msg import Joy from math import atan2 import numpy as np import time class RobotArmControl(object): def __init__(self): self.msg = Joy() self.torso_pos = 90 self.shoulder_pos = 45 self.elbow_pos = ...
import datetime from docx.shared import Cm from docxtpl import DocxTemplate, InlineImage """"" Работа с текстами """"" def get_context(company, result_sku_list): # возвращает словарь аргуменов return { 'retailer': company, 'sku_list': result_sku_list, } def from_template(company, result_s...
import os from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError from werkzeug.security import check_password_hash, generate_password_hash import time import datetime as dt import secrets import random ## TODO check in requirements from flask import Flask, flash, jsonify, redirect, ren...
# Copyright 2018 Luddite Labs 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...
#!/usr/bin/env python """ Load API client for a Tool Registry Service (TRS) endpoint based either on the GA4GH specification or an existing client library. """ import logging from bravado.requests_client import RequestsClient from ga4ghtest.core.config import trs_config from .client import TRSClient logger = logging...
# Copyright 2019 The PlaNet 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...
from typing import List, Optional, Tuple from pydantic import BaseModel class DMInputParams(BaseModel): scale: float size: Tuple[int, int] mean: Optional[Tuple[float, ...]] swapRB: Optional[bool] crop: Optional[bool] class Config: allow_population_by_field_name = True fields ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_mldmp ---------------------------------- Tests for `maximum likelihood MDP` module. """ import random import unittest2 from tests.test_learner import TestLearner from rltools.learners import MLMDP from rltools.strategies import Strategy from rltools.domains imp...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # File : dimension.py # Author : Honghua Dong # Email : dhh19951@gmail.com # Date : 04/20/2018 # # This file is part of TextualReasoning-PyTorch. # Distributed under terms of the MIT license. import itertools import torch import torch.nn as nn from jactorch.functi...
import logging import utils import constants logging.basicConfig( level=logging.DEBUG, format=constants.logfmt, handlers=[logging.StreamHandler(), logging.FileHandler('../../data/logs/make_station_tree.log', 'w')], ) logging.debug("started") stations = utils.load_stations() tree, node_station = utils.make_...
# Copyright (C) 2020 NTT DATA # 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 ...
""" This package contains support code to package Salt with PyInstaller. """
from django import http from django.shortcuts import render from django.views import View from address.models import Area from utils.response_code import RET class Areas(View): # get /api/v1.0/areas/ def get(self, request): """展示区域数据""" try: areas = Area.objects.all()...
import os import requests with open('raw.csv') as f: lis=[line.split(',') for line in f] for i, person in enumerate(lis): person[0] = person[0].replace(' ', '_') person[1] = person[1].strip('\n') print("Will create dir {0}, and store image from {1}".format(person[0], person[1])) ...
from . import BaseHandler, apply_request_schema, apply_response_schema from .exceptions import NotFoundError, ValidationError from ..aliases import AliasNotFound, AliasStoreType from ..aliases.manager import redact, reveal from ..schemas.aliases import ( AliasResponseSchema, AliasesResponseSchema, RedactReq...
#! /usr/bin/env python # -*- coding: iso-8859-15 -*- ############################################################################## # Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II # Copyright 2009 & onward LRI UMR 8623 CNRS/Univ Paris Sud XI # # Distributed under the Boost ...
# coding=utf-8 # Licensed Materials - Property of IBM # Copyright IBM Corp. 2020 from streamsx.topology.schema import StreamSchema # # Defines Message types with default attribute names and types. _SPL_SCHEMA_ACCESS_TOKEN = 'tuple<rstring access_token, rstring refresh_token, rstring scope, int64 expiration, rstring t...
# Copyright 2013 Rackspace, 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...
from flask_sqlalchemy import SQLAlchemy import json db = SQLAlchemy() class Interface(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, unique=True) url = db.Column(db.String) query_string = db.Column(db.String) active = db.Column(db.Boolean, index=True) defa...
# -*- coding: utf-8 -*- """ Created on Tue Oct 28 15:08:20 2014 @author: aitor """ import datetime import json import gzip import time import sys import tweepy from tweepy import StreamListener, Stream credentials = json.load(open('credentials.json', 'r')) CONSUMER_KEY = credentials['consumer_key'] CONSUMER_SECRET =...
"""Copyright © 2020-present, Swisscom (Schweiz) AG. All rights reserved. AnalyticalSolver, used to solve the Quadratic Constrained Optimization Problem for 2 gradients analytically. The AnalyticalSolver class contains the implementation of the analytical QCOP Solver for 2 gradients. """ from copsolver.copsolver impor...
# !/usr/bin/env python3 # -*-coding:utf-8-*- # @file: attenStereoNet_embed_sga_11.py # @brief: # @author: Changjiang Cai, ccai1@stevens.edu, caicj5351@gmail.com # @version: 0.0.1 # @creation date: 16-10-2019 # @last modified: Mon 11 May 2020 01:02:03 AM EDT import torch import torch.nn as nn import torch.nn.functional...
""" Receives a command with search table results from search engine and calls filer and utils modules to handle the command. """ class CommandHandler: """ Handles commands from searchengine. """ pass
from output.models.nist_data.atomic.non_negative_integer.schema_instance.nistschema_sv_iv_atomic_non_negative_integer_min_inclusive_2_xsd.nistschema_sv_iv_atomic_non_negative_integer_min_inclusive_2 import NistschemaSvIvAtomicNonNegativeIntegerMinInclusive2 __all__ = [ "NistschemaSvIvAtomicNonNegativeIntegerMinInc...
""" This packages implements tomography algorithms and utilities in python. It is made of several modules, as follows: - siddon: The core of the package, with a fast C/OpenMP implementation of the Siddon algorithm. See: http://adsabs.harvard.edu/abs/1985MedPh..12..252S - simu: Implements some utilities to perform...
"""Defines various distribution models.""" import numpy as np import numpy.random as rnd import scipy.stats as stats from warnings import warn import serums.enums as enums class BaseSingleModel: """Generic base class for distribution models. This defines the required functions and provides their recommended...
import time import usb.core, usb.util # generateWords from random import choice from wordlist import wordlist # detectHuman import pygame def generateWords(): return " ".join([choice(wordlist) for x in range(4)]) def detectHuman(): pygame.init() pygame.event.set_grab(True) screen = pygame.display.se...
# Copyright 2020 Canonical 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 in writing, s...
import sys import pytest @pytest.mark.parametrize("mode", ["normal", "xdist"]) class TestFixture: """ Tests for ``subtests`` fixture. """ @pytest.fixture def simple_script(self, testdir): testdir.makepyfile( """ def test_foo(subtests): for i in ran...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('api', '0084_auto_20151125_2051'), ] operations = [ migrations.AddField( model_name='activity', name=...
import glob import os import random import re import cv2 import numpy as np import pandas as pd import tensorflow as tf from sklearn.model_selection import train_test_split from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau from .data_generator import DataGenerator from .losses i...
# -*- coding: utf-8 -*- import mysql.connector def store_mysql(filepath): conn = mysql.connector.connect(user = 'root', password = '1207', database = 'ShowMeTheCode') cursor = conn.cursor() # 判断表是否已经存在 cursor.execute('show tables in ShowMeTheCode;') tables = cursor.fetchall() findtables = Fal...
from api import app from api import database from flask import jsonify from flask import request @app.route('/companies', methods=['POST']) def create_company(): company = request.get_json() db = database() db.update(company) return jsonify(company), 201
import unittest from Familytree.individual import Person from Familytree.relations import Relations from Familytree import variables from unittest.mock import patch, Mock from tests import mock_member_creation class MyTestCase(unittest.TestCase): def setUp(self): self.member = Person(1, "Hubby", "Male") ...
name = 'stemplar' __version__ = '0.0.1'
from __future__ import unicode_literals from redis.exceptions import DataError, ResponseError from limpyd import fields from limpyd.exceptions import UniquenessError from ..base import LimpydBaseTest from ..model import TestRedisModel class HMTest(LimpydBaseTest): """ Test behavior of hmset and hmget "...
''' Faça um Programa que pergunte em que turno você estuda. Peça para digitar M-matutino ou V-Vespertino ou N- Noturno. Imprima a mensagem "Bom Dia!", "Boa Tarde!" ou "Boa Noite!" ou "Valor Inválido!", conforme o caso. ''' print('Em que turno voce estuda:') turno = str(input(''' M-matutino V-vesperino N-noturn...
import socket import struct def quad2int(ip): return struct.unpack("!L", socket.inet_aton(ip))[0] def int2quad(ip): return socket.inet_ntoa(struct.pack('!L', ip))
import logging from bson.errors import InvalidId from django.http import JsonResponse, HttpResponseNotFound, HttpResponseBadRequest, HttpResponse from django.views.decorators.csrf import csrf_exempt from api.models import db_model from bson import ObjectId from api.models.auth import RequireLogin from api.models import...
from .__about__ import __version__ from .riak_repl import RiakReplCheck __all__ = ['__version__', 'RiakReplCheck']
""" @Author: huuuuusy @GitHub: https://github.com/huuuuusy 系统: Ubuntu 18.04 IDE: VS Code 1.36 工具: python == 3.7.3 """ """ 思路: 类似斐波那契数列,动态规划 结果: 执行用时 : 48 ms, 在所有 Python3 提交中击败了68.02%的用户 内存消耗 : 13.8 MB, 在所有 Python3 提交中击败了5.22%的用户 """ class Solution: def climbStairs(self, n): # 类似斐波那契数列的解法 ...
# The MIT License (MIT) # # Copyright (c) 2019 Scott Shawcroft for Adafruit Industries LLC # # 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 ...
import pandas as pd import pytest from pyspark.sql import DataFrame from sparkypandy import Columny, DataFramy from sparkypandy.testing import assert_series_equal from tests.conftest import ALL_COLUMN_NAMES, NUMERIC_COLUMN_NAMES class TestColumny: @pytest.mark.parametrize("col_name", ALL_COLUMN_NAMES) # type: i...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser import datetime import os import pkg_resources import sphinx.cmd.quickstart as sphinx_quickstart from sphinx.util.console import bold from hieroglyph import version def ask_user(d): """Wrap sphinx.c...
#!/usr/bin/env python3 import os from setuptools import setup about = {} # type: ignore here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, "url_hostname", "__version__.py")) as f: exec(f.read(), about) setup( name=about["__title__"], description=about["__description__"], ...
from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import * import time class Worker(QRunnable): ''' Worker thread ''' @pyqtSlot() def run(self): ''' Your code goes in this function ''' print("Thread start") time.sleep(5) prin...
from codewars.decode_morse_adv import decode_bits, decode_morse def test_simple_messages() -> None: assert decode_bits('111') == '.' assert decode_bits('111000111') == '..' assert decode_bits('111000111000111') == '...' assert decode_bits('10001') == '. .' assert decode_bits('111000000000111') == ...
from django.contrib import admin from profiles_api import models ## Models need to be defined to be later used for Admin. admin.site.register(models.UserProfile) admin.site.register(models.ProfileFeedItem)
from django.urls import path, include from rest_framework.routers import DefaultRouter from .views import ( UserRegisterAPIView, UserLoginAPIView, UserLogoutAPIView, PasswordChangeAPIView, DepartamentViewSet, UserViewSet) app_name = 'accounts' router = DefaultRouter() router.register(r'departaments', Departa...
import twitter import mysql.connector import json import os def collect_data_about(name, twitter_api, cursor): MAX_ENTRY_PER_PERSON = 1000 print(f'Quering twitter API for: {name}') search_results = twitter_api.search.tweets(q=name, count=100, lang='en') processStatusCounter = 0 while True: try: ...
from argparse import ArgumentParser class ModelTrainingArgs(ArgumentParser): def __init__(self): super().__init__() self.add_argument("-d", "--dataset", help="Dataset name") self.add_argument("-c", "--config", help="Config file path") self.add_argument( "--debug", actio...
from sklearn import tree from dataset import TransDataset import numpy as np trans_dataset = TransDataset() X, y = trans_dataset.get_x_y() print(np.array(X).shape) print(np.array(y).shape) regressor = tree.DecisionTreeRegressor() regressor = regressor.fit(X, y) test_dataset = TransDataset("test") test_x, test_y = t...
URL = "https://www.omdbapi.com/"