content
stringlengths
0
894k
type
stringclasses
2 values
from .caffeNetFaceDetector import CaffeNetFaceDetector
python
__version__ = "4.1" __build__ = "GIT_COMMIT" import logging logger = logging.getLogger(__name__) try: import subprocess import os import platform FNULL = open(os.devnull, 'w') if platform.system() == "Windows": args = ['git', 'describe', '--tags'] else: args = ['git describe --...
python
N = int(input()) A = list(map(int, input().split())) if A.count(0) >= 1: print(0) exit(0) L = 10**18 ans = A[0] for i in range(1, N): ans *= A[i] if ans > L: print(-1) exit(0) print(ans)
python
from django.contrib.auth.models import AbstractUser from django.db.models import IntegerChoices, Model, IntegerField, CharField, TextField, ForeignKey, ManyToManyField, \ FileField, DateTimeField, CASCADE from django.utils.functional import cached_property from martor.models import MartorField class AppUser(Abst...
python
from _thread import RLock from datetime import datetime from io import TextIOWrapper, StringIO from logging import Logger, LogRecord from logging.handlers import MemoryHandler from unittest import TestCase from unittest.mock import patch import pytest from osbot_utils.utils.Json import json_load_file from osbot_utils...
python
import json from dinofw.utils.config import MessageTypes, ErrorCodes, PayloadStatus from test.base import BaseTest from test.functional.base_functional import BaseServerRestApi class TestDeleteAttachments(BaseServerRestApi): def test_payload_status_updated(self): group_message = self.send_1v1_message( ...
python
import os from yaml import ( SafeLoader, load ) from pydantic import ( BaseSettings, BaseModel ) from typing import Any from pathlib import Path def default_yaml_source_settings(settings: BaseSettings): curr_dir = os.path.dirname(os.path.abspath(__file__)) return load( Path(f"{curr_dir}/defaults.yml"...
python
class Solution: def XXX(self, s: str) -> bool: s1='' AZ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' for c in s: if c in AZ : s1+=c.upper() if s1==s1[::-1]: return True else: return False
python
# Copyright 1999-2017 Tencent 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 writ...
python
import time users = {} status = "" def mainMenu(): global status status = input("Do you have an existing account (Y/N)?\nPress Q to quit.\n") if status == "y" or "Y": existingUser() elif status == "n" or "N": newUser() elif status == "q" or "Q": quit() ...
python
class StatsHandler(object): def __init__(self): self._core = {} self.ingredient_num = 0 def add_entry(self, ingredients): self.ingredient_num += len(ingredients) for entry in ingredients: if not entry in self._core.keys(): self._core[entry] = {} for e in ingredients: if entry == e: conti...
python
from collections import Counter ACC = "acc" JMP = "jmp" NOP = "nop" class CycleError(Exception): ... class Computer: def __init__(self, data): self.data = data def load(self): head = acc = 0 while True: op, value = yield head, acc if op == ACC: ...
python
# Copyright (c) 2017 Ansible, Inc. # All Rights Reserved. from django.urls import re_path from awx.api.views import ( AdHocCommandList, AdHocCommandDetail, AdHocCommandCancel, AdHocCommandRelaunch, AdHocCommandAdHocCommandEventsList, AdHocCommandActivityStreamList, AdHocCommandNotification...
python
from buildtest.menu.build import discover_buildspecs tagname = ["tutorials"] print(f"Searching by tagname: {tagname}") included_bp, excluded_bp = discover_buildspecs(tags=tagname) print("\n Discovered buildspecs: \n") [print(f) for f in included_bp]
python
from collections import defaultdict def concept2dict(concepts): d = defaultdict(list) for c in concepts: d[c.index].append(c._asdict()) return d
python
# Copyright 2016-present CERN – European Organization for Nuclear Research # # 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...
python
# GENERATED BY KOMAND SDK - DO NOT EDIT import komand import json class Input: DAYS_BACK = "days_back" EXCLUDE = "exclude" LIMIT = "limit" QUERY = "query" class Output: RESPONSE = "response" class RegistrantMonitorInput(komand.Input): schema = json.loads(""" { "type": "object"...
python
from flask import Flask, render_template, request from models import db, User import psycopg2, logging app = Flask(__name__) output_file = open("query.sql", "w+") output_file.close() POSTGRES = { 'user': 'postgres', 'db': 'airportdb', 'host': 'localhost', 'port': '5432', } app.config['DEBUG'] = True app.config['S...
python
from __future__ import print_function import argparse import torch import torch.utils.data from torch import nn, optim from torch.nn import functional as F from torchvision import datasets, transforms from torch.utils.data import DataLoader from torchvision.utils import save_image from vmodel import * from vdataset imp...
python
dias = int(input('Quantos dia foram alugados? ')) quilometros = float(input('Quantos Km foram rodados?')) total = (dias*60)+(quilometros*0.15) print('O valor a ser pago do aluguel é de R${:.2f}'.format(total))
python
from django.apps import AppConfig class CalorieConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'calorie' def ready(self): #new import calorie.signals #new
python
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str __all__ = ['stmts_from_json', 'stmts_from_json_file', 'stmts_to_json', 'stmts_to_json_file', 'draw_stmt_graph', 'UnresolvedUuidError', 'InputError'] import json import logging from indra.state...
python
#!/usr/bin/env python3 # Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 import argparse import sys from scripts_lib import start_riscv_dv_run_cmd, run_one def main() -> int: parser = argparse.ArgumentParser() ...
python
"""JWT Helper""" import json import time from jose import jwt def create_jwt(config, payload={}): with open(config["AssertionKeyFile"], "r") as f: assertion_key = json.load(f) header = { "alg": "RS256", "typ": "JWT", "kid": assertion_key["kid"], } _payload = { ...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """Script to generate GZIP file specimens.""" from __future__ import print_function from __future__ import unicode_literals import argparse import gzip import os import sys def Main(): """The main program function. Returns: bool: True if successful or False if ...
python
from abc import ABC from typing import Generic, TypeVar from .serializers import serializer from .backends import storage_backend T = TypeVar("T") class KeyValueStore(Generic[T]): """ KeyValueStore ============= Abstract class for a key-value store combining a storage backend with a serializer-d...
python
# AIcells (https://github.com/aicells/aicells) - Copyright 2020 Gergely Szerovay, László Siller # # 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-...
python
# Copyright 2019, A10 Networks # # 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 a...
python
# -*- coding: utf-8 -*- from odoo import models class AccountMoveLine(models.Model): _inherit = "account.move.line" def _stock_account_get_anglo_saxon_price_unit(self): price_unit = super(AccountMoveLine, self)._stock_account_get_anglo_saxon_price_unit() so_line = self.sale_line_ids and sel...
python
import math from seabreeze.pyseabreeze.features._base import SeaBreezeFeature from seabreeze.pyseabreeze.features.fpga import _FPGARegisterFeatureOOI from seabreeze.pyseabreeze.protocol import OOIProtocol # Definition # ========== class SeaBreezeContinuousStrobeFeature(SeaBreezeFeature): identifier = "continuous...
python
from __future__ import print_function, absolute_import, division import pytest from distutils.version import LooseVersion from astropy import units as u from astropy import wcs import numpy as np from . import path from .helpers import assert_allclose, assert_array_equal from .test_spectral_cube import cube_and_raw ...
python
test = {'a': 'dfdf', 'b': 'dfafafa'}
python
from django import forms from django_bootstrap_wysiwyg.widgets import WysiwygInput from .models import Message class MessageForm(forms.ModelForm): class Meta: model = Message widgets = { 'text': WysiwygInput() } class MultipleInputForm(forms.Form): name = forms.CharField(...
python
# -*- coding: utf-8 -*- from .base_settings import * # noqa import os DEBUG = bool(int(os.environ.get("DEBUG", 0))) {%- if cookiecutter.database_type == "mysql" %} DATABASE_VENDOR = os.environ.get("DATABASE_VENDOR", "mysql") {%- elif cookiecutter.database_type == "postgres" %} DATABASE_VENDOR = os.environ.get("DATAB...
python
import os import random import pyfiglet import colorama from colorama import Fore baner = ('''             [...
python
import django_filters from dal import autocomplete from django import forms from django.contrib.auth.models import User from vocabs.models import SkosConcept from vocabs.filters import generous_concept_filter from entities.models import Institution, Person, Place from . models import ArchResource class ArchResource...
python
import data from fastapi import APIRouter, Depends, HTTPException from .dependencies import owner_or_admin from .models import CoinMapping router = APIRouter( prefix="/mappings/coin", tags=["coin"], dependencies=[Depends(owner_or_admin)], responses={404: {"description": "Not found"}}, ) @router.get...
python
import pickle from tqdm import tqdm import numpy as np from polaris2.micro.micro import det from polaris2.geomvis import R3S2toR, R3toR, R3toR3, utilsh, utilmpl, phantoms import logging log = logging.getLogger('log') log.info('Generating phantom.') vox_dims = np.array([.1,.1,.1]) data = np.zeros((3,3,3,6)) data[0,0,0...
python
#!/usr/bin/env python import sys # 2 inputs and 2 outputs class MIMO22: def __init__(self, T=1e3, **kwargs): a = 1 b = 0.1 c = 0.1 d = 1 self.A = np.array([[-a, -b], [-c, -d]], dtype=np.float) self.B = np.array([[a, b], ...
python
import pandas as pd array = {'A' : [1,2,3,4,5,4,3,2,1], 'B' : [5,4,3,2,1,2,3,4,5], 'C' : [2,4,6,8,10,12,14,16,18]} df_array = pd.DataFrame(data=array) print("Arranjo original") print(df_array) print("\n") print("Removendo linhas cuja coluna B tenha valores iguais a 3") df_array_new = df_array[df_array.B != 3] prin...
python
import os from functools import wraps from typing import List, Union import numpy as np if os.getenv("FLEE_TYPE_CHECK") is not None and os.environ["FLEE_TYPE_CHECK"].lower() == "true": from beartype import beartype as check_args_type else: def check_args_type(func): @wraps(func) def wrapper(*...
python
"""Graphs channel signal measurements for a given scan """ import pandas as pd import plotly import plotly.graph_objects as go from db import load class ScanSummary(): def __init__(self): # default scan is latest scan self.scan = None self.labels = None self.default_antenna = lo...
python
from classes.SymEntry import sym_comb_dict # Copyright 2020 Joshua Laniado and Todd O. Yeates. __author__ = "Joshua Laniado and Todd O. Yeates" __copyright__ = "Copyright 2020, Nanohedra" __version__ = "1.0" query_out_format_str = "{:>5s} {:>6s} {:^9s} {:^9s} {:^20s} {:>6s} {:^9s} {:^9s} {:^20s} {:>6s} {:>3s} {:>4s...
python
# Write a program that asks a user to type in two strings and that prints # • the characters that occur in both strings. # • the characters that occur in one string but not the other. # • the letters that don’t occur in either string. # Use the set function to turn a string into a set of characters. # FUNCTI...
python
from sportstrackeranalyzer.plugins.plugin_simple_distances import Plugin_SimpleDistance
python
import numpy as np import random class ALOHA_Q(object): """ ALOHA-Q player as described in Chu et al. """ def __init__(self, N=64, active=True, do_print=False, name=None, t=0, retry_limit=6, ...
python
from django.forms import ModelForm, CharField, CheckboxInput, ChoiceField from .models import Escalamedica, Escalasocial, Escalaenfermagem, Escalafisioterapia from django.contrib.auth.models import User from django import forms from bootstrap4.widgets import RadioSelectButtonGroup class EscalaMedicaForm(ModelForm): ...
python
# -*- coding: utf-8 -*- " Page engine models " import os.path from hashlib import sha1 from django.db import models from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import re...
python
# 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 # distributed under the Li...
python
#! /usr/bin/env python2 import sympy as sy import sympy.physics.mechanics as mech import numpy as np import scipy as sp import matplotlib.pyplot as plt import neuromech as nm """ In this script we analyse the 3D Rossler system (a classic example of chaotic behaviour) using a numerical estimate of maximal Lyapunov c...
python
import os import random import sys import time import joblib import numpy from scenario.example import sc1_simple_lockdown_removal, sc2_yoyo_lockdown_removal, sc0_base_lockdown, \ scx_base_just_a_flu, sc3_loose_lockdown, sc4_rogue_citizen, sc5_rogue_neighborhood, sc6_travelers, \ sc7_nominal_lockdown_removal,...
python
# -*- coding: utf-8 -*- r'''This module contains implementations of common regularizers. In ``theanets`` regularizers are thought of as additional terms that get combined with the :class:`Loss <theanets.losses.Loss>` for a model at optimization time. Regularizer terms in the loss are usually used to "encourage" a mod...
python
#!/usr/bin/python # coding=utf-8 # File Name: 5.SingleNum/single_num.py # Developer: VVgege # Data: Tue Feb 3 22:30:56 2015 ''' Question Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it wi...
python
import multiprocessing as mp import subprocess as sp import os import time import parse import signal from tqdm import tqdm UPDATE = 1 DONE = 2 NEW = 3 queue = mp.Queue() def execute(args): with open('overnight/{0}-{2}-{4} {3}-{5}-{1}.timing'.format(*args), "w+") as timing_file: current = mp.current_pro...
python
from typing import List, Tuple, AsyncGenerator, Optional from unittest.mock import Mock from wcpan.drive.abc import RemoteDriver, ReadableFile, WritableFile, Hasher from wcpan.drive.types import Node, ChangeDict, PrivateDict from wcpan.drive.cache import node_from_dict from .util import create_root class FakeDriver...
python
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'mainui/mainwindow.ui' # # Created: Thu Sep 24 15:01:53 2015 # by: pyside-uic 0.2.15 running on PySide 1.2.2 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui class Ui_MainWindow(object): def...
python
import numpy as np import matplotlib.pyplot as plt from scipy.spatial import distance_matrix from copy import deepcopy from common.utils import RunningMeanStd import gym class Env(): def __init__(self, normalize): #shared parameters self.env = gym.make('Pendulum-v0') self.T = 200 s...
python
# Generated by Django 2.2.6 on 2019-10-29 07:38 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('app', '0002_auto_20191029_0737'), ] operations = [ migrations.RemoveField( model_name='weather', name='dewPointTemperature',...
python
# -*- coding: utf-8 -*- """Concentrate the heavy business logic of the operations of an application. It knows all Models that should be part of the flow and knows the API/services of those models. It also orchestrate all the side-effects and therefore can make the use of other use cases/services. """ from django.utils...
python
# -*- coding: utf-8 -*- ''' @Time : 2021/9/8 @Author : Yanyuxiang @Email : yanyuxiangtoday@163.com @FileName: cprofile_quick_start.py @Software: PyCharm ''' import time def a(): time.sleep(3) def b(): for _ in range(10**6): pass def main(): a() b() print('done') if __name__ == '...
python
import random from .models import MaterialRequestSignature,MaterialRequest,Material,MaterialInStock,MaterialWareHouse, Assignment, Project, Event, OrganizationUnit, Employee, Contractor, ManagerPage, ArchiveDocument from authentication.repo import ProfileRepo from dashboard.models import Icon from dashboard.enums impor...
python
import os from typing import List from dotenv import load_dotenv load_dotenv() commands: List[str] = ['mkdir /home/ubuntu/AOGuildSite/certs/', 'wget {0} -O /home/ubuntu/AOGuildSite/certs/backend_cert.pem'.format(os.getenv('BACKEND_CERT')), 'wget {0} -O /home/ubuntu/AOGui...
python
from flask import abort, Blueprint, render_template, send_from_directory, \ jsonify, request, redirect, url_for, flash, current_app, send_file from flask_login import login_required, current_user import sqlalchemy as sa from spreadsheetcompiler.extensions import login_manager, db from .. import models from .users impo...
python
/home/runner/.cache/pip/pool/47/5c/17/1e750cb5e8e9c342671ff24ef177586ac304eb08d5aa9d733fb4ca2e08
python
from __future__ import print_function, absolute_import, division, generators, nested_scopes import sys import os.path import logging import ply.yacc from jsonpath_ng.jsonpath import * from jsonpath_ng.lexer import JsonPathLexer logger = logging.getLogger(__name__) def parse(string): return JsonPathParser().pars...
python
from .base import BaseMetric import GPUtil class GPUs(BaseMetric): def __init__(self): pass def measure(self): all = [] gpus = GPUtil.getGPUs() for g in gpus: all.append(g.__dict__) return { "gpus_data": all, "gpus_averages": self._...
python
from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend as DjangoModelBackend class ModelBackend(DjangoModelBackend): def authenticate(self, username=None, password=None): """ Case insensitive username """ try: user = User.objects.get(username__...
python
#!/usr/bin/env python3 """ Author: Ken Youens-Clark <kyclark@gmail.com> Purpose: Filter Swissprot file for keywords, taxa """ import argparse import os import sys from Bio import SeqIO # -------------------------------------------------- def get_args(): """get args""" parser = argparse.ArgumentParser( ...
python
import json import logging logging.basicConfig( level=logging.INFO, format="%(asctime)s,%(msecs)d %(levelname)s: %(message)s", datefmt="%H:%M:%S", ) log = logging def write_JSON_file(output_file_name_w_path, arr_of_objs, json_lines=False): with open(output_file_name_w_path, mode="a", encoding='utf8'...
python
import os import pickle import json import numpy as np def main(): artifacts_dir = 'artifacts/filter_experiment/' artifacts_baseline_dir = 'artifacts/filter_baseline_experiment/' epsilons = ['0.001', '0.005', '0.01', '0.05'] use_filters = ['True', 'False'] table = {} table['f'] = [] table[...
python
from django.core.exceptions import ImproperlyConfigured from django.template import engines from django.test import SimpleTestCase, override_settings class TemplateUtilsTests(SimpleTestCase): @override_settings(TEMPLATES=[{'BACKEND': 'raise.import.error'}]) def test_backend_import_error(self): ...
python
from .Adafruit_LSM303 import Adafruit_LSM303
python
from typing import List def strip_punctuation(word: str): res = word.strip(".,;-/!?:\\—()[]{}\"'") return res def strip_punctuation_words(words: List[str]) -> List[str]: # keep res = [strip_punctuation(x) for x in words] res = [x for x in res if x != ""] return res def strip_punctuation_utterance(utte...
python
from django.contrib.auth.models import User from django.db import models from steemconnect.client import Client class SteemConnectUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) refresh_token = models.CharField( max_length=500, help_text="steemconnect user code / to get...
python
# -*- coding: utf-8 -*- # # Copyright (C) 2022 TU Wien. # # Invenio-Users-Resources is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see LICENSE file for more # details. """Definitions that are used by both users and user groups services.""" from invenio_records_resourc...
python
""" The http server implementation """ import BaseHTTPServer import SocketServer import socket #for socket.error import re import os import sys import urlparse import traceback import threading import drapache from drapache import util class DropboxHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """ T...
python
import pandas as pd from matplotlib import pyplot as plt import numpy as np import math from matplotlib import pyplot as plt from sklearn.preprocessing import LabelEncoder feature_dict = {i:label for i,label in zip( range(4), ('sepal length in cm', 'sepal width in c...
python
#!/usr/bin/python # -*- coding: utf-8 -*- """Provide an interface to the Drupal 6 CMS database. This module provides a wrapper to interfacing with the content management system database. Supports Drupal 6 only. """ import MySQLdb as mdb import logging import os, subprocess from phpserialize import unserialize #import ...
python
# plugin to select a new replica based on the "priority" # assigned by users in the server definitions # as with all replica selection, it returns a LIST # of replicas # sorts replicas first by status ( healthy then lagged) # then sorts them by priority from plugins.handyrepplugin import HandyRepPlugin class select_r...
python
# -*- coding: utf-8 -*- from peewee import ForeignKeyField, DateTimeField, TextField, SmallIntegerField from models.base import BaseModel from models.users import Users from models.articles import Articles from datetime import datetime class ArticleComments(BaseModel): owner = ForeignKeyField(Users, related_name...
python
import subprocess import pytest @pytest.fixture def with_packages(capsys, request): with capsys.disabled(): subprocess.run( ["poetry", "add"] + request.param, stdout=subprocess.DEVNULL, ) yield with capsys.disabled(): subprocess.run( ["poetry", ...
python
from __future__ import absolute_import from __future__ import print_function import os import sys import functools import math import numpy as np # the next line can be removed after installation sys.path.insert(0, os.path.dirname(os.path.dirname( os.path.dirname(os.path.abspath(__file__))))) import nngen as ng ...
python
# An indexer using the DIALS methods. import copy import logging import math import os import string import libtbx from cctbx import crystal, sgtbx # wrappers for programs that this needs: DIALS from dials.array_family import flex from xia2.Wrappers.Dials.GenerateMask import GenerateMask as _GenerateMask from xia...
python
""" Metaball Demo Effect by luis2048. (Adapted to Python by Jonathan Feinberg) Organic-looking n-dimensional objects. The technique for rendering metaballs was invented by Jim Blinn in the early 1980s. Each metaball is defined as a function in n-dimensions. """ numBlobs = 3 # Position vector for each blob ...
python
from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from highlight import Highlighter ''' 调用了QCompleter, 不知道有没有起作用。。。。 参考文章地址:http://blog.sina.com.cn/s/blog_a6fb6cc90101gu7w.html 2017年11月17日12点56分 自动补全已经工作了, 是因为文件相对地址打错了。。。。。 2017年11月18日17点18分 @acytoo ''' class TextEdit(QTextEdit): ...
python
import contextlib with contextlib.redirect_stdout(None): import pygame from utils import sin, cos from tiles import Wall def handle_collisions(droid, all_sprites): col_dirs = set() for sprite in all_sprites: if isinstance(sprite, Wall): col_dirs.update(get_collision_directions(droid, sp...
python
# coding=utf-8 class Fake: def __init__(self, d, spec=None): for key, value in d.items(): if isinstance(value, dict): setattr(self, key, Fake(value)) else: setattr(self, key, value) if spec: self.__class__ = spec
python
import os import bpy import time import json import urllib import shutil import pathlib import zipfile import addon_utils from threading import Thread from collections import OrderedDict from bpy.app.handlers import persistent from .translations import t no_ver_check = False fake_update = False is_checking_for_update...
python
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data from tensorbayes.layers import Constant, Placeholder, Dense, GaussianSample from tensorbayes.distributions import log_bernoulli_with_logits, log_normal from tensorbayes.tbutils import cross_entropy_with_logits from tensorbayes.nbutils im...
python
import json, sys, util from xml.dom.minidom import parse dom = parse(sys.argv[1]) imageries = dom.getElementsByTagName('entry') for imagery in imageries: entry = { 'name': util.textelem(imagery, 'name'), 'type': util.textelem(imagery, 'type'), 'url': util.textelem(imagery, 'url'), ...
python
# Numeros favoritos: Modifique o seu programa do Exercicio 02.py para que cada pessoa possa ter mais de um numero favorito. Em seguida, apresente o nome de cada pessoa, juntamente com seus numeros favoritos. favorite_numbers = dict() favorite_numbers["Jaoa"] = [12, 23, 45, 14, 75, 43] favorite_numbers["Alberto"] = [4,...
python
#!/usr/bin/env python # -*- coding:utf-8 -*- """ Time: 2021-02-26 17:17 Author: huayang Subject: Notes: 现象: class C(A, B) C类 继承了 A 和 B, 在此之前,A 和 B 没有任何关系 但在 C 同时继承了 A 和 B 后,A 就能调用 B 中的代码 说明: 1. 先继承 B,此时可以访问 B 的所有成员; 2. 然后继承 A,如果 A 中存在与 B 同名的方法...
python
import pandas as pd import numpy as np import pickle import ast import requests import re import json import warnings import time class recipe_data_class: def __init__(self, raw_recipes_file, pp_recipes_file, ingr_map_file): self.raw_recipes_file = raw_recipes_file self.pp_recipes_file = pp_recipes...
python
from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import Book class BookForm(forms.ModelForm): class Meta: model = Book fields = ('title', 'author', 'pdf', 'cover') class CreateUserForm(UserCreationForm): ...
python
import factory import datetime from django.utils.text import slugify from .constants import * from .models import ( Investor, Shareholder, Security, Addition, Certificate) class InvestorFactory(factory.DjangoModelFactory): FACTORY_FOR = Investor FACTORY_DJANGO_GET_OR_CREATE = ('slug',)...
python
from .return_class import AbstractApiClass class Project(AbstractApiClass): """ A project is a container which holds datasets, models and deployments """ def __init__(self, client, projectId=None, name=None, useCase=None, createdAt=None, featureGroupsEnabled=None): super().__init__(client...
python
''' Author: linghaol Tools package ''' from markdown2 import markdown class FileParser: def parse(fpath=None, ftype=None): ''' File parts are seperated by '//////'. Output is a dictionary. ''' if fpath == None: print('Please specify a file path!') ...
python
from . import subsubpkg21 # noqa: F401 from . import mod # noqa: F401
python
# For image output to bmp file import os # For image operation from library.image_tool_box import * # For math/statistic operation from library.math_tool_box import StatMaker import math ### Prelude: Downlaod and unpack those 4 test data from MNIST database. # train-images-idx3-ubyte.gz: training set images (...
python
#!/usr/bin/env python3 import sys from cx_Freeze import Executable, setup # type: ignore # cx_Freeze options, see documentation: # https://cx-freeze.readthedocs.io/en/latest/distutils.html#build-exe build_exe_options = { "packages": [], "excludes": [ "numpy.core.tests", "numpy.distutils", ...
python