content
stringlengths
5
1.05M
class BitSet: def __init__(self, size): self.bits = (1 << size) - 1 def get(self, index): return (self.bits >> index) & 1 def set(self, index, value): mask = 1 << index self.bits &= ~mask if value: self.bits |= mask def flip(self, index): ...
import datetime from django.test import TestCase from custom.icds_reports.reports.bihar_api import get_mother_details from custom.icds_reports.tasks import update_bihar_api_table from datetime import date from mock import patch @patch('custom.icds_reports.utils.aggregation_helpers.distributed.bihar_api_demographics...
from django.urls import path from .consumers import StudentWaitingConsumer, WorkshopControlConsumer, StudentWorkshopConsumer """ Websocket Session UrlPatterns are used for websocket connections for users which do not have a user e.g. a student which is using a code to access """ websocket_urlpatterns = [ path("wai...
# -*- coding: utf-8 -*- """ .. module:: skimpy :platform: Unix, Windows :synopsis: Simple Kinetic Models in Python .. moduleauthor:: SKiMPy team [---------] Copyright 2017 Laboratory of Computational Systems Biotechnology (LCSB), Ecole Polytechnique Federale de Lausanne (EPFL), Switzerland Licensed under the ...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: mindinsight_summary.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from go...
from PyQt4.QtGui import * class _ListItem(QListWidgetItem): def __init__(self, value): super(_ListItem, self).__init__() self._value = value def get_value(self): return self._value class BaseListWidget(QListWidget): def __init__(self, parent=None): super(BaseListWidget...
from flask import Flask, render_template, flash, url_for, redirect, request, session from wtforms import Form, BooleanField, TextField, PasswordField, validators from passlib.hash import sha256_crypt from MySQLdb import escape_string as thwart import gc from functools import wraps from content_management import Content...
#!/usr/bin/env python # -*- coding: utf-8 -*- import configparser class Config: config_parser = configparser.ConfigParser() default_config_path = 'config/config.ini' def __init__(self, config_path = default_config_path): """ Constructor for Config :param config_path: ...
print(f"Loading {__file__}...") import numpy as np from ophyd import ( EpicsSignal, EpicsSignalRO, EpicsMotor, Device, Signal, PseudoPositioner, PseudoSingle, ) from ophyd.utils.epics_pvs import set_and_wait from ophyd.pseudopos import pseudo_position_argument, real_position_argument from o...
# # File: # labelbar.py # # Synopsis: # Demonstrates labelbars and labelbar resource settings. # # Category: # Labelbar # # Author: # Mary Haley # # Date of initial publication: # March, 2005 # # Description: # This example illustrates the effects of setting values # for various labelbar re...
import os import re _shaders_dir = os.path.dirname(os.path.realpath(__file__)) # from opengl language specification: # "Each number sign (#) can be preceded in its line only by spaces or horizontal tabs. # It may also be followed by spaces and horizontal tabs, preceding the directive. # Each directive is terminated b...
#!/usr/bin/python # -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # /******************************************************* # * Copyright (C) 2013-2014 CloudRunner.io <info@cloudrunner.io> # * # * Proprietary and confidential # * This file is part of CloudRunner Server. # * # * CloudRunner S...
from django.apps import AppConfig from django.utils.translation import ugettext_lazy class AccountsAppConfig(AppConfig): name = 'learningprogress.accounts' verbose_name = ugettext_lazy('Accounts')
""" Standard definitions that don't change. """ ESI_KEY_DELETED_BY_EVEOAUTH = 0 ESI_KEY_REPLACED_BY_OWNER = 1 ESI_KEY_DELETED_BY_SYSADMIN = 2 ESI_KEY_REMOVAL_REASON = ( (ESI_KEY_DELETED_BY_EVEOAUTH, "The Test Auth app was deleted by the user on the eve website."), (ESI_KEY_REPLACED_BY_OWNER,"The character's o...
import cp2110 import threading import time import json d = cp2110.CP2110Device() d.set_uart_config(cp2110.UARTConfig( baud=9600, parity=cp2110.PARITY.NONE, flow_control=cp2110.FLOW_CONTROL.DISABLED, data_bits=cp2110.DATA_BITS.EIGHT, stop_bits=cp2110.STOP_BITS.SHORT)) d.enable_uart() last_p = "" ...
# Copyright (c) 2011-2013 Kunal Mehta. All rights reserved. # Use of this source code is governed by a BSD License found in README.md. from django.test import TestCase from huxley.accounts.constants import * from huxley.accounts.models import * class HuxleyUserTest(TestCase): def test_authenticate(self): ...
item = float(input('Digite o Preço do produto: ')) desc = int(input('Digite o Valor do desconto: ')) preco = float(item - (item * desc / 100)) print('O produto com {}% de desconto, custara R${:.2f}!'.format(desc, preco))
# -*- coding: utf-8 -*- import shutil from oss2 import defaults, exceptions, models, utils, xml_utils from oss2.compat import to_string, to_unicode, urlparse, urlquote from . import http class _Base(object): def __init__(self, auth, endpoint, is_cname, session, connect_timeout, app_name='', ena...
def test_login(app): x = 0 pass
#!/usr/bin/env python # -*- coding: utf-8 -*- from torch import cat, Tensor from torch.nn import Module, GRU, Dropout, LayerNorm __author__ = 'An Tran' __docformat__ = 'reStructuredText' __all__ = ['SublayerConnection'] class SublayerConnection(Module): def __init__(self, size: int, ...
# Copyright (c) 2018, NVIDIA CORPORATION. """ Helper functions for parameterized docstring """ import functools import string import re _regex_whitespaces = re.compile(r'^\s+$') def _only_spaces(s): return bool(_regex_whitespaces.match(s)) _wrapopts = { 'width': 78, 'replace_whitespace': False, } de...
from .jobManager import JobManager class ClusterJobManager(JobManager): """ Helper class to enqueue and dequeue jobs to the cluster job queue. """ def __init__(self): JobManager.__init__(self, 'CLUSTER_JOBSQUEUE_CONNECTIONSTRING')
# -*- coding: utf-8 -*- """ @FileName: model_test.py @author: Meihua Peng @time: $(2018.5.30) $(10:00) """ import numpy as np import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1' import tensorflow as tf import pandas as pd # tf.cond = tf import keras from keras import optimizers, backend from keras.models import Sequ...
""" Implementation of Adaptive Embedding from :cite:https://arxiv.org/abs/1809.10853 Based on https://github.com/kimiyoung/transformer-xl/blob/master/pytorch/mem_transformer.py """ import torch import torch.nn as nn class AdaptiveEmbedding(nn.Module): def __init__(self, n_token, d_embed, d_proj, cutoffs,...
from .. import _image_size import numpy as np from scipy.spatial.distance import cdist, pdist class ImageCrop(): """ """ def __init__(self, ndim, crop_array=None, single_im_size=_image_size, ): _shape = (ndim, 2) self.ndim = ...
# # This file is part of pyasn1-modules software. # # Created by Russ Housley # Copyright (c) 2019, Vigil Security, LLC # License: http://snmplabs.com/pyasn1/license.html # import sys from pyasn1.codec.der.decoder import decode as der_decode from pyasn1.codec.der.encoder import encode as der_encode from pyasn1_modul...
# Created by Jennifer Langford on 3/24/22 for CMIT235 - Week 1 Assignment # This is an ongoing effort weekly for the duration of this course. # The program will be complete at the end of the course. mySubList1 = [[1, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6], [2, 8, 4, 6, 7, 8, 9, 10, 11, 12, 12, 13]] mySubList2 = [[0, -1, 3, ...
#!/usr/bin/env python import xml.etree.ElementTree as XET ''' Author: Pengjia Zhu (zhupengjia@gmail.com) ''' class odsread: ''' read ods file Input: - filename: ods filepath ''' def __init__(self,filename): from zipfile import ZipFile ziparchive = ZipFile(f...
# Copyright 2013-2018 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 * # Although this looks like an Autotools package, it's not one. Refer to: # https://github.com/flame/b...
# -*- coding: utf-8 -*- import logging from abc import ABCMeta from abc import abstractmethod from copy import deepcopy from random import getrandbits from sklearn.base import BaseEstimator from pipesnake.base.utils import _check_input from pipesnake.base.utils import _check_transformer_type from pipesnake.utils imp...
#!/usr/bin/env python # Copyright (c) 2014, Stanford University # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this list ...
import dash import dash_core_components as dcc import dash_html_components as html import pandas as pd from textwrap import dedent from reusable_components import Section, Chapter from tutorial import styles from tutorial import tools examples = { example: tools.load_example('tutorial/examples/table/{}'.format(e...
#!/usr/bin/env python3 import sys import time import random from optparse import OptionParser from rgbmatrix import RGBMatrix, RGBMatrixOptions from matrixdemos.scripts.utils import * description = "A simple demo of twinkling stars" parser = OptionParser(description=description) parser.add_option("-s", "--speed", h...
#!/usr/bin/env python """ Create release notes for a new release of this GitHub repository. """ # Requires: # # * assumes current directory is within a repository clone # * pyGithub (conda or pip install) - https://pygithub.readthedocs.io/ # * Github personal access token (https://github.com/settings/tokens) # # Git...
#!/usr/bin/env python3 # Small GUI program using GUIZero to change the # brightness of a Pi-top/CEED if using Jessie and not pi-topOS # to use this program you first have to install the code from # https://github.com/rricharz/pi-top-install # to get the brightness command # while there it's worth installing ...
#!/usr/bin/env python import sys from fetch_data import FetchData from markov_python.cc_markov import MarkovChain """ Goofy first attempt at a Python application that uses the Codecademy markov_python module to create fun/dumb/whatever responses based on data pulled from various web locations. Pretty lame, but ...
#!/home/tortes/anaconda3/envs/ts/bin/python """ Change list: - Remove past action - adjust step output: remove arrived - Change python version to 3 - Add action space, observation space 8.17 - Change action space to discrete action """ import os import rospy import numpy as np import math from math import pi import ran...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import os import pickle import yaml import pathlib import pandas as pd import shutil from qlib.contrib.backtest.account import Account from qlib.contrib.backtest.exchange import Exchange from qlib.contrib.online.user import User from qlib.contrib...
def addition(a, b): return int(a) + int(b) def subtraction(a, b): return int(a) - int(b) def multiplication(a, b): return int(a) * int(b) def division(a, b): return round((int(a) / int(b)),9) def squaring(a): return int(a)**2 def squarerooting(a): return round((int(a)**.5),8) class Calcula...
from django.conf.urls import url, include from django.contrib import admin from books.views import Mainpage urlpatterns = [ url(r'^$', Mainpage.as_view(), name='mainpage'), # 主页 ]
# -*- coding: utf-8 -*- """ Pytesting/test/test_worker.py Generative test cases for the data processing Worker object @author: Rupert.Thomas Created 22/11/2019 Run tests (from the root folder using): pytest """ import datetime from string import printable # digits + ascii_letters + punctuation + whitespace from ...
""" This holds functionality to get commands, and parse commands """ from quick_netmiko import QuickNetmiko from pyats_genie_command_parse import GenieCommandParse def command_parse(python_dict, fifo_queue, thread_lock): # pylint: disable=inconsistent-return-statements """Function to get and parse commands from...
r"""Implementation of the Dijkstra algorithm for finding shortest paths. The algorithm is implemented using a priority queue (in particular heapq that is provided in python). This should provide a complexity of :math:`O(E \\cdot log(V))`, while many other implementations have the complexity :math:`O(V \\cdot E)`. .. ...
import notebooks import os.path tracking_uri = r'file:///' + os.path.join(os.path.dirname(notebooks.__file__),'model_simulate','mlruns') import mlflow mlflow.set_tracking_uri(tracking_uri)
"""Command line tool to handle Postgresql WAL archiving on Rackspace's cloudfiles. pg_raxarchive ============= ``pg_raxarchive`` is a command line tool to handle Postgresql WAL archiving on Rackspace's cloudfiles. Quick help ---------- Install using pip then: - Create a file ``/etc/pg_raxarchive.ini`` with racksp...
import pathlib from typing import Union from configparser import ConfigParser from azure.identity import DefaultAzureCredential class TradingCredentials(): def __init__(self, config_file: Union[str, pathlib.Path] = None) -> None: """Initializes the `TradingCredentials` object. ### Overview ...
# encoding: utf-8 # # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Author: Kyle Lahnakoski (kyle@lahnakoski.com) # from __future__ import absolute_import, divisio...
"""Checks to ensure the individual issues toml have all the required fields.""" import os import sys import tomlkit as toml SEVERITIES = ("major", "minor", "critical") CATEGORIES = ( "bug-risk", "doc", "style", "antipattern", "coverage", "security", "performance", "typecheck", ) GITH...
import pandas as pd from sklearn.gaussian_process.kernels import Matern from sklearn.gaussian_process import GaussianProcessRegressor as GPR from PyALE import ale import matplotlib.pyplot as plt import seaborn as sns def plot_ale(log_name=None): if log_name == 'Baseline': iters = pd.read_csv('./logs/mbo/'...
print('\033[0;30;41mComo você está? ') print('\033[4;33;44mComo você está?') print('\033[1;35;43mComo você está?') print('\033[30;42mComo você está?') print('\033[mComo você está?') print('\033[7;30mComo você está?')
# Copyright (c) 2013, omar jaber and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ def execute(filters=None): columns, data = get_columns(), get_data() return columns, data def get_columns(): return [ _("Code/Re...
import json, time start = time.time() # Translate avro message to NGSI def to_ngsi(ms): # msg_time = time.ctime(ms["header"]["time"]) id_string = "hmod.itcrowd.predator.uav.2:"+str(ms["header"]["time"]) entity = { "id": id_string, "type":"UAV_simple", #"time" : str(msg_time), } value = dict() # The mo...
# Copyright (c) 2017 Weitian LI <liweitianux@live.com> # MIT license """ Wrapper function to view FITS files using DS9. """ import subprocess def ds9_view(filename, regfile=None, regformat="ciao", regsystem="physical", cmap="he", binfactor=2, scale="linear", smooth=None): """ Wrapper function t...
import sys import re ## Need to convert asxxxx syntax to rgbds syntax module = sys.argv[1] class Token: def __init__(self, kind, value, line_nr): self.kind = kind self.value = value self.line_nr = line_nr def isA(self, kind, value=None): return self.kind == kind and (value is...
import sqlite3 from datetime import date class TalkThread(object): def __init__(self, id, cmts): self.id = id self.comments = cmts def add_comments(self, cmts): self.comments.append(cmts) class Comment(object): def __init__(self, cmt): self.comment_id = cmt[0] se...
import sqlite3 from .db import DB class CaseInfoTable(DB): def __init__(self): self.table_name = 'PB_case_details' self.table_desc = 'Punjab patients discharged, ventilators, icu and death details. Table page 1 or 2' self.cols = self.getcolumns() def getcolumns(self): cols = ...
# pure_collector.py # import Python modules import urllib3 # import third party modules from prometheus_client.core import GaugeMetricFamily # disable ceritificate warnings urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) class PurestorageCollector: """ Class that instantiate the collector's ...
""" EmailAlert - send alerts via email """ from __future__ import division from builtins import str, object import smtplib import logging class EmailAlert(object): """ A simple class to send alerts via email """ EMAIL_HEADER = "From: %s\r\nSubject: %s\r\nTo: %s\r\n\r\n" def __init__(self, confi...
#!/usr/bin/env python # # Copyright 2007 Google 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 o...
def simple_gem5(data): s = "" s += "from __future__ import print_function\n" s += "from __future__ import absolute_import\n" s += "import m5\n" s += "from m5.objects import *\n" s += "system = System()\n" # Set the clock fequency of the system (and all of its children) s += "system.clk_domain = SrcClockDoma...
import argparse import torch from rlkit.core import logger from rlkit.samplers.rollout_functions import multitask_rollout from rlkit.torch import pytorch_util as ptu from rlkit.envs.vae_wrapper import VAEWrappedEnv def simulate_policy(args): data = torch.load(args.file) policy = data['evaluation/policy'] ...
from damage_detector.detector import Detector if __name__ == '__main__': print("Enter image path: ") image_path = input() Detector.detect_scratches(image_path)
"""See :ref:`specs.projects.actors`. """
import sys from datetime import datetime, timedelta, timezone, time from django.conf import settings from django.utils.translation import ugettext as _ from .models import InfusionChanged, SensorChanged, LastTriggerSet, TriggerTime def process_nightscouts_api_response(response): """ process nightscout`s res...
""" Read a fastq file and a time file and split based on the time time stamp Our time stamp file should have the following information: sample ID\tStart Time We assume that all times are contiguous, so if you want to include a gap you'll need to add that with a name Time should be in one of the formats supported by...
from colloidoscope.hoomd_sim_positions import convert_hoomd_positions, hooomd_sim_positions from colloidoscope import DeepColloid from colloidoscope.simulator import simulate from colloidoscope.hoomd_sim_positions import read_gsd import numpy as np from magicgui import magicgui from napari.layers import Image import na...
# -*- coding: utf-8 -*- # Update by: https://github.com/CokeMine/ServerStatus-Hotaru # 依赖于psutil跨平台库: # 支持Python版本:2.6 to 3.7 # 支持操作系统: Linux, Windows, OSX, Sun Solaris, FreeBSD, OpenBSD and NetBSD, both 32-bit and 64-bit architectures import socket import time import json import psutil from collections import deque ...
# Config homeserver_url = "matrix.example.com" access_token = "" # # Import modules import json import requests import sys if __name__ == "__main__": room_id = sys.argv[1].replace("!", "%21").strip() url = "https://%s/_matrix/client/r0/rooms/%s/send/m.room.message" %(homeserver_url, room_id) headers = { ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Machine translation using Microsoft Translator API """ import sys import os import argparse import uuid import json import requests from requests.packages.urllib3.util.retry import Retry from requests.adapters import HTTPAdapter from logging import getLogger, StreamHand...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import common, Form from odoo.tools import mute_logger class TestDropship(common.TransactionCase): def test_change_qty(self): # enable the dropship and MTO route on the product prod ...
"""Request handler classes for the extension""" import base64 import json import tornado.gen as gen from notebook.base.handlers import APIHandler, app_log from jupyterlab_ucaip.service import UCAIPService, ManagementService handlers = {} def _create_handler(req_type, handler): class Handler(APIHandler): ""...
# This file is managed by the 'airflow' file bundle and updated automatically when `meltano upgrade` is run. # To prevent any manual changes from being overwritten, remove the file bundle from `meltano.yml` or disable automatic updates: # meltano config --plugin-type=files airflow set _update orchestrate/dags/melta...
# Generated by Django 2.0.4 on 2018-05-05 11:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('source', '0005_auto_20180505_0833'), ] operations = [ migrations.AlterField( model_name='source', name='jnl_cidade',...
from pydgn.training.event.state import State class EventHandler: r""" Interface that adheres to the publisher/subscribe pattern for training. It defines the main methods that a subscriber should implement. Each subscriber can make use of the :class:`~training.event.state.State` object that is passed t...
import ksl_env import os import pandas as pd from Climate_Shocks.get_past_record import get_vcsn_record, event_def_path import matplotlib.pyplot as plt ksl_env.add_basgra_nz_path() from basgra_python import run_basgra_nz from supporting_functions.plotting import plot_multiple_results from supporting_functions.woodward...
"""CLI to get data from a MetaGenScope Server.""" from sys import stderr import click from requests.exceptions import HTTPError from .utils import add_authorization @click.group() def get(): """Get data from the server.""" pass @get.command(name='orgs') @add_authorization() def get_orgs(uploader): ""...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from .card_dialog import CardDialog from .card_options import CardOptions from .card_sample_helper import CardSampleHelper from .channel_supported_cards import ChannelSupportedCards __all__ = ["CardDialog", "CardOptions", "C...
# 1 DOF SYSTEM import numpy as np import matplotlib.pyplot as plt import libraryTugas as lib # 1. SYSTEMS PARAMETERS #================ # a. Initial condition x_init1, xDot_init1 = 0.1, 0 # [m], [m/s] # b. System parameters mass1, damp1, spring1 = 1, 1, 10 # [kg], [Ns/m], [N/m] omega, forceMagnit = 2, 0.5 # [rad/s]...
# -*- coding: utf-8 -*- """ /*************************************************************************** Name : DB Manager Description : Database manager plugin for QGIS Date : May 23, 2011 copyright : (C) 2011 by Giuseppe Sucameli email : brush.tyler@...
from fastapi import HTTPException, status InvalidCredentials = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail='Incorrect username or password', headers={'WWW-Authenticate': 'Basic'}, ) UserAlreadyExists = HTTPException( status_code=status.HTTP_409_CONFLICT, detail='User already ex...
#!/usr/bin/env python3 import os import pandas as pd import argparse def get_tag(x, tag): try: return x[tag] except: return False def main(): parser = argparse.ArgumentParser( prog="check_argparse.py", formatter_class=argparse.RawTextHelpFormatter, description=''...
from setuptools import setup setup( name='bt_futu_store', version='1.0', description='Futu API store for backtrader', url='', author='Damon Yuan', author_email='damon.yuan.dev@gmail.com', license='MIT', packages=['btfutu'], install_requires=['backtrader', 'futu-api'], )
import torch import torch.nn as nn class VGGishish(nn.Module): def __init__(self, conv_layers, use_bn, num_classes): ''' Mostly from https://pytorch.org/vision/0.8/_modules/torchvision/models/vgg.html ''' super().__init__() layers = [] in_channels = 1 ...
# Generated by the protocol buffer compiler. DO NOT EDIT! # sources: proto/messages.proto # plugin: python-betterproto from dataclasses import dataclass import betterproto class Target(betterproto.Enum): UNKNOWN = 0 DOCKER_IMAGE = 1 USER_BACKGROUND_IMAGE = 2 DATA = 3 BASH_SCRIPT = 4 ANSIBLE_...
#!/usr/bin/env python """Tests for `sentency` package.""" from sentency.regex import regexize_keywords def test_regexize_keywords(): keywords = "abdominal aortic aneurysm\naneurysm abdominal aorta" actual = regexize_keywords(keywords) expected = "(?i)((abdominal.*aortic.*aneurysm)|(aneurysm.*abdominal.*...
import csv produceFile = open("produceSalesAltered.csv") csvReader = csv.reader(produceFile) produceData = list(csvReader) # Get a list of lists produceTotals = {} for csvLine in produceData[1:]: # Extract data from current line # [produceType, _, _, total] = csvLine produceType = csvLine[0] # produce t...
import os import unittest from recipe_scrapers.hundredandonecookbooks import HundredAndOneCookbooks class TestHundredAndOneCookbooksScraper(unittest.TestCase): def setUp(self): # tests are run from tests.py with open(os.path.join( os.getcwd(), 'recipe_scrapers', ...
from django.db import models from django.contrib.auth.models import User # Create your models here. # one off?, daily, weekly, monthly class TaskType(models.Model): typename=models.CharField(max_length=255) typedescription=models.CharField(max_length=255, null=True, blank=True) def __str__(self): ...
from dask.distributed import Client, progress from dask import delayed import dask.bag as db import pandas as pd from time import sleep import json import os # create 8 parallel workers client = Client(n_workers=8) def computeIDF(documents): import math N = len(documents) idfDict = dict.fromkeys(docu...
""" Hacemos lo mismo que en el 9, pero en vez de sumar, multiplicamos. """ total = 1 input_values_correct = False """ Aquí vamos a controlar que introducimos el número de elementos correcto, para luego pedir las veces especificadas para la multiplicación total de lo que queremos conseguir """ while(input_values_correct...
from django.contrib import admin from mysite.bridie.models import User, Post, Comment # Register your models here. class UserAdmin(admin.ModelAdmin): pass class PostAdmin(admin.ModelAdmin): pass class CommentAdmin(admin.ModelAdmin): pass admin.site.register(User, UserAdmin) admin.site.register(Post, PostAdmin) admi...
''' Created on Sep 6, 2015 @author: ace ''' import argparse import re from django.core.management.base import BaseCommand, CommandError from openpyxl import load_workbook from account.models import Profile from account.utils import format_phonenumber from friend.models import PhoneContactRecord class Command(BaseC...
class Solution: def maxProfit(self, prices: List[int]) -> int: dp_i_0, dp_i_1 = 0, float('-inf') for i in range(len(prices)): dp_i_0 = max(dp_i_0, dp_i_1 + prices[i]) dp_i_1 = max(dp_i_1, -prices[i]) return dp_i_0
import future import builtins import past import six import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.autograd import components as comp from torch.distributions import multinomial, categorical import math import numpy as np try: from . import helpers as...
# 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 ap...
def f(x,y): x = [1] z = x+y a = [1,2] b = a print(f(a,b)) print(a) print(b)
from __future__ import absolute_import from __future__ import division from __future__ import print_function from lib.rpn.generate_anchors import generate_anchors import numpy as np def generate_anchors_global(feat_stride, height, width, anchor_scales=(8,16,32), anchor_ratios=(0.5,1,2)): anchors = generate_anchors(...
import pandas as pd import sklearn from sklearn.dummy import DummyClassifier, DummyRegressor from sklearn.linear_model import LinearRegression, LogisticRegression from sklearn.model_selection import cross_validate def baseline_fun( X_train, y_train, type="regression", metrics_1="accuracy", metrics_2="r2" ): "...
#!/usr/bin/env python3 import json import sys CHUNK_SIZE = 50 FILENAME_PREFIX = 'circles' class Worker(object): def __init__(self, src: list, destdir: str): self.src = src self.destdir = destdir def save_file(self, counter: int): filename = '%s-%d.json' % (FILENAME_PREFIX, counter) ...
# -*- coding: utf-8 -*- """ :author: Grey Li (李辉) :url: http://greyli.com :copyright: © 2018 Grey Li :license: MIT, see LICENSE for more details. """ import os import sys import click from flask import Flask, request, g, session, redirect, url_for, render_template, jsonify, flash from flask_github impo...