content
stringlengths
5
1.05M
############################################################################### # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by ...
from PySide2.QtWidgets import QWidget, QVBoxLayout, QLineEdit, QLabel, QScrollArea from PySide2.QtCore import Qt from PySide2.QtGui import QFont from custom_src.global_tools.Debugger import Debugger from custom_src.global_tools.stuff import sort_nodes from custom_src.node_choice_widget.NodeWidget import NodeWidget c...
import numpy as np from PIL import Image import struct import glob class MnistImageManager: #def __init__(self): def getMnistDataFromPng(self, filename): print("### MnistImageManager getMnistDataFromPng") print("filename = " + filename) #file = glob.glob(filename) # make Label Data #lbl = file....
import unittest from sweetcase import switch, case, default class TestComplex(unittest.TestCase): def test_multicase_of_types_with_argument(self): result = None def update_result(new_result): nonlocal result result = new_result data = {"sweet": "case", "git": "hub...
""" Artificial Neuron model class Copyright(c) HiroshiARAKI """ class Neuron(object): def __init__(self, time: int, dt: float): """ Neuron class constructor :param time: :param dt: """ self.time = time self.dt = dt def calc_v(self, data): """ ...
# -*- coding: utf-8 -*- """ Created on Wed Oct 23 10:17:05 2019 @author: lansf """ import os from jl_spectra_2_structure import IR_GEN from jl_spectra_2_structure.plotting_tools import set_figure_settings set_figure_settings('paper') #Folder where figures are to be saved Downloads_folder = os.path.join(os.path.expand...
from grouper import permissions from grouper.fe.forms import PermissionRequestsForm from grouper.fe.util import GrouperHandler from grouper.models import REQUEST_STATUS_CHOICES class PermissionsRequests(GrouperHandler): """Allow a user to review a list of permission requests that they have.""" def get(self): ...
from filament import patcher as _fil_patcher from filament import _util as _fil_util import filament as _fil import _filament.locking as _fil_locking __filament__ = {'patch':'thread'} _fil_thread = _fil_patcher.get_original('thread') class Lock(_fil_locking.Lock): def acquire(self, waitflag=1): blocking ...
"""Convert real number to string with 2 decimal places. Given real number _x, create its string representation _s with 2 decimal digits following the dot. Source: programming-idioms.org """ # Implementation author: nickname # Created on 2016-02-18T16:57:57.897385Z # Last modified on 2016-02-18T16:57:57.897385Z # Ver...
titulo = "Curso de python 3" for caracter in titulo: if caracter == "p": continue # nos mostrara todos los caracteres menos la letra p hace que salte a la siguiente iteracion break # no se visualizaran los caracteres despues de p print(caracter) #imprime todos mis caracteres
"""pytest conftest.""" from pathlib import Path from typing import List import pytest from bs4 import BeautifulSoup, element from sphinx.testing.path import path from sphinx.testing.util import SphinxTestApp pytest_plugins = "sphinx.testing.fixtures" # pylint: disable=invalid-name @pytest.fixture(scope="session") ...
from __future__ import print_function, absolute_import, division from numpy import * from scipy import linalg from scipy import sparse class BuilderAndSolver: use_sparse_matrices = False '''ATTENTION!! this builder and solver assumes elements to be written IN RESIDUAL FORM and hence solves FOR A COR...
from kaggleEuroSoc.helpers.database import Base from sqlalchemy import Column, Integer, Text, ForeignKey class League(Base): __tablename__ = 'League' id = Column(Integer, primary_key=True) country_id = Column(Integer, ForeignKey('Country.id')) name = Column(Text) def __repr__(self): ret...
import tensorflow as tf def create_model(): model = tf.keras.models.Sequential(); model.add(tf.keras.layers.Flatten()) model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) model.add(tf.keras.layers.Dense(512, activation=tf.nn.relu)) model.add(tf.keras.layers.Dense(1024, activation=tf.nn.rel...
class StaticSetpoint: def __init__(self, x, y): self.setpoint = (x, y) def on_start(self, goal, frame): pass def get_setpoint(self): return self.setpoint def is_done(self): return False
try: import os,sys,time,datetime,random,hashlib,re,threading,json,urllib,cookielib,getpass,mechanize,requests,bxin from multiprocessing.pool import ThreadPool from requests.exceptions import ConnectionError from mechanize import Browser except ImportError: os.system('pip2 install requests') ...
# -*- coding: utf8 -*- import pytest from diceroller.tools import ( MAX_SIDES, MAX_DICE_NUMBER, RollParser, BadlyFormedExpression, ) def test_tools(): nb, sides, modifier = RollParser.parse('2d6') assert (nb, sides, modifier) == (2, 6, 0) nb, sides, modifier = RollParser.parse('2d') assert (n...
from typing import Any from cgnal.core.config import BaseConfig, AuthConfig # TODO: Are we sure this is the best place for this class? Wouldn't it be better to place it in the config module? class MongoConfig(BaseConfig): @property def host(self) -> str: return self.getValue("host") @property ...
import PySimpleGUI as gui #Layout primeiro programa em que pegara os valores layout = [[gui.Text("Digite valores para criar sua matriz.")], [gui.Input(size=(10, 1), key='val1'), gui.Text("Valor para Coluna")], [gui.Input(size=(10, 1), key='val2'), gui.Text("Valor para Linha")], [gui.Text(...
# coding=utf-8 """ Copyright 2015 BlazeMeter 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 wr...
from anasymod.templates.templ import JinjaTempl from anasymod.config import EmuConfig from anasymod.generators.gen_api import SVAPI, ModuleInst from anasymod.structures.structure_config import StructureConfig from anasymod.sim_ctrl.datatypes import DigitalSignal class ModuleTimeManager(JinjaTempl): def __...
class ShorturlTarget: def __init__(self, contact_id=None, email=None, number=None): pass
a = "Hello" print("%s: %s %s" % ("Error", a, "World"))
# 2021-01-27 # This code was made for use in the Fu lab # by Christian Zimmermann import matplotlib as mpl import matplotlib.font_manager as fm import matplotlib.patches as patches import matplotlib.pyplot as plt import numpy as np import pandas as pd import scipy.io as spio import scipy.optimize as spo import scipy.s...
import cv2 import numpy as np from matplotlib import pyplot as plt from matplotlib.patches import ConnectionPatch from collections import Counter from scipy.optimize import linear_sum_assignment import math img1 = 'S3_016_02_05.jpg' img2 = 'S3_016_02_06.jpg' images = [] count = [] mode = 0 def det...
# This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import benchexec.util as util import benchexec.tools.template import benchexec.result as r...
#! /usr/bin/python import smtplib email = ""#email for a gmail account here password = ""#password for a gmail account here #to get phone number num = input("What phone number?") #to hard code it #num = ""#put phone number here #to get service provider sp = input("Which service provider \n 1.At&t \n 2.Tmobile \n 3...
""" Minimal code to support ignored makemigrations (like django.db.backends.*.schema) without interaction to SF (without migrate) """ from django.db import NotSupportedError from django.db.backends.base.schema import BaseDatabaseSchemaEditor from salesforce.backend import log class DatabaseSchemaEditor(BaseDatabas...
import nltk from util import adjective_util def do(line): # inspired by the work of Colin Johnson (https://scholar.google.com/citations?hl=en&user=6W7BtygAAAAJ) tokens = nltk.word_tokenize(line) adjacent_adjective_indices = adjective_util.get_indices_of_adjacent_adjectives(line) for adjacent_group in...
# -*- coding: utf-8 -*- """ Package to integrate the DymaxionLabs's funcionality: - Upload images - Predict imagenes based in object detection models - Download results """ import os from pkg_resources import get_distribution, DistributionNotFound from . import files from . import models from . import utils try:...
import pytest from django.core.exceptions import ImproperlyConfigured from mock import patch, call from pylogctx.django import ( ExtractRequestContextMiddleware, OuterMiddleware, context as log_context ) from pylogctx import log_adapter @pytest.fixture() def request(): return {'rid': 42} @pytest...
import re import random import itertools import math from collections import defaultdict from src.utilities import * from src import channels, users, debuglog, errlog, plog from src.functions import get_players, get_all_players, get_main_role, get_reveal_role, get_target from src.decorators import command, event_liste...
# # Copyright 2018 Analytics Zoo 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
from idom import component, html, run @component def Photo(): return html.img( { "src": "https://picsum.photos/id/237/500/300", "style": {"width": "50%"}, "alt": "Puppy", } ) run(Photo)
from flask import Flask from flask_restful import reqparse from mrat_rest import MelanomaRiskAssessmentTool app = Flask('onco_cancer_prognosis') mrat = MelanomaRiskAssessmentTool() @app.route('/skin_cancer_prognosis', methods=['POST']) def skin_cancer_prognosis(): parser = reqparse.RequestParser() parser.add_...
# Copyright 2018 Argo AI, 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 agreed to in writing, sof...
import os from flask import Flask, Response, send_from_directory, request, make_response, jsonify from flask_expects_json import expects_json from apscheduler.schedulers.background import BackgroundScheduler from pytz import utc import json from .countryrepository import CountryRepository from flask_cors import CORS ...
"""Custom layers that constitute building blocks of NN models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from typing import Any import numpy as np import sonnet as snt import tensorflow as tf NONLINEARITIES = { 'relu': tf.nn.relu, 'exp': ...
from urllib.parse import urlparse, parse_qs import re import random import unicodedata import os from tqdm import tqdm from bs4 import BeautifulSoup from common import dir_path, cache_request, re_to_e164 BASE_URL = "https://mvic.sos.state.mi.us/Clerk" # resolved issue with SSL cert chain by fixing intermediate cert #...
# Generated by Django 2.2.4 on 2019-08-13 12:04 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('users', '0002_auto_20190813_1204'), ('neighbour', '0001_initial'), ] operations = [ migrations.Alte...
# Copyright 2015 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...
def func(): print('This is the development version of func().')
from .world import World, NoSuchComponentError, DuplicateComponentError from .entity import Entity, UnregisteredComponentError from .component import Component from .system import System
from venv import logger from django.contrib.auth.hashers import make_password from django.core.management.base import BaseCommand from ...models import User from ...patient import Patient from ...doctor import Doctor from ...license import License from diagnoses.register_status import RegisterStatus from diagnoses.d...
""" .. module:: gui :platform: Windows :synopsis: Main application frame for the entire GUI .. moduleauthor:: Nam Tran <tranngocnam97@gmail.com> """ # Standard Library imports import tkinter as tk from tkinter import ttk import os import sys # Appends the system path to allow absolute path imports due to th...
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2020-08-18 07:56 from __future__ import unicode_literals from django.db import migrations, models from bluebottle.clients import properties from parler.models import TranslatableModelMixin def create_default_impact_types(apps, schema_editor): ImpactType = ...
import sqlite3 x='songs.db' def connect(): conn=sqlite3.connect(x) c=conn.cursor() c.execute(""" CREATE TABLE IF NOT EXISTS playlist ( song_id INTEGER NOT NULL PRIMARY KEY, song text NOT NULL, path text NOT NULL, fav INTEGER ) """) conn.commit() conn.close...
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-06-23 10:05 from __future__ import unicode_literals from django.db import migrations, models from frontend.models import ImportLog from common.utils import under_test def seed_log(apps, schema_editor): if not under_test(): ImportLog.objects.crea...
import unittest import os from programy.braintree import BraintreeManager from programy.config.brain.braintree import BrainBraintreeConfiguration from programytest.client import TestClient class BraintreeManagerTests(unittest.TestCase): def test_dump_no_create(self): config = BrainBraintreeConfiguration(...
import argparse import tensorflow as tf import stupid if __name__ == '__main__': parser = argparse.ArgumentParser(description='Converts H5 to TF lite.') parser.add_argument('keras_model', help='Keras model to load in H5 format.') parser.add_argument('tf_lite_model', help='TF lite model.') args = par...
""" Defines a URL to return a notebook html page to be used in an iframe """ from django.conf.urls import url from xblock_jupyter_graded.rest.views import ( DownloadStudentNBView, DownloadInstructorNBView, DownloadAutogradedNBView ) from django.contrib.auth.decorators import login_required app_name = 'xblock_jupy...
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merg...
# Copyright (c) 2018 Mengye Ren # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distrib...
""" Kivy helpers for orchestrating volume levels for groups of Sounds. """ from __future__ import annotations import os from kivy.core.audio import Sound, SoundLoader class AudioManager: def __init__(self, prefix='./', volume=.5): self._sounds: list[tuple[Sound, float]] = [] self.prefix = prefi...
# Copyright 2016 Nicolas Bessi, Camptocamp SA # Copyright 2018 Tecnativa - Pedro M. Baeza # Copyright 2020 Poonlap V. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, models class ResPartnerTH(models.Model): _inherit = "res.partner" @api.onchange("zip_id", "city_id", "st...
#!/usr/bin/env python3 import os import argparse import re import open3d import prompter import numpy as np import copy import toml from pathlib import Path import mathutils # Global regular expressions index_re = re.compile('(\d+)(?!.*\d)') # Gets last number in a string def get_index(path): m = index_re.sear...
import os from PIL import Image, ImageDraw, ImageFont ##################################################### # parameter setting # ##################################################### row = 2 col = 6 pad = 2 dataset = 'ToS3' seq_num = 3 name = ['bridge'...
# Copyright 2020 The StackStorm Authors. # Copyright 2019 Extreme Networks, 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 ...
import os template_parent = 'default' template_dir = os.path.abspath(os.path.dirname(__file__)) base_fn = 'base.html'
from gym.envs.registration import register # Human Testing register( id='HumanTesting-v0', entry_point='assistive_gym.envs:HumanTestingEnv', max_episode_steps=200, ) # Scratch Itch PR2 register( id='ScratchItchPR2-v0', entry_point='assistive_gym.envs:ScratchItchPR2Env', max_episode_steps=200, ...
# Copyright 2020 Pants project contributors. # Licensed under the Apache License, Version 2.0 (see LICENSE). import pytest from helloworld.util.lang import LanguageTranslator def test_language_translator(): language_translator = LanguageTranslator() assert "hola" == language_translator.translate("es", "hello...
from .projects import start from .forms import addform __all__ = ['start', 'addform']
import numpy import os import scipy.sparse import unittest from afqmctools.hamiltonian.converter import ( read_qmcpack_hamiltonian, read_fcidump, write_fcidump ) from afqmctools.utils.linalg import modified_cholesky_direct from afqmctools.hamiltonian.mol import write_qmcpack_cholesky fro...
""" This library for transformations partly derived and was re-implemented from the following online resources: * http://www.lfd.uci.edu/~gohlke/code/transformations.py.html * http://www.euclideanspace.com/maths/geometry/rotations/ * http://code.activestate.com/recipes/578108-determinant-of-matrix-of-any-o...
# Generated by Django 3.1.7 on 2021-07-27 08:28 import cloudinary.models from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_US...
from django.contrib import admin from .models import Exchange admin.site.register(Exchange)
from django.utils.module_loading import module_has_submodule from collections import namedtuple from importlib import import_module class Fixture(namedtuple("Fixture", "app name export func")): __slots__ = () def __hash__(self): return hash((self.app, self.name)) def __eq__(self, other): ...
from .config import * from .image import * from .tester import * from .util import *
#! /usr/bin/env python import sys import pybindgen from pybindgen import ReturnValue, Parameter, Module, Function, FileCodeSink from pybindgen import CppMethod, CppConstructor, CppClass, Enum from pybindgen.typehandlers.base import ForwardWrapperBase class VisitorParam(Parameter): DIRECTIONS = [Parameter.DIREC...
from django.apps import apps from django.db import models class Item(models.Model): subject = models.ForeignKey( 'Subject', on_delete=models.CASCADE, related_name='items') name = models.CharField(max_length=32) estimated_amount = models.PositiveIntegerField(null=True) memo = models.TextField(...
import sys import pytest from click_testing_utils import clirunner_invoke_piped import clifunzone.txttool as sut from clifunzone import txt_utils def test_none(): expected = 'I was invoked without a subcommand...' clirunner_invoke_piped(sut.cli, [], '', exit_code=0, out_ok=expected) def test_none_debug():...
# package containing kinect specific modules
# TRAIN_PATH = '/Users/roshantirukkonda/Desktop/Kaggle /Pytorch CNN MNIST/Input/MNIST/processed/training.pt' # TEST_PATH = '/Users/roshantirukkonda/Desktop/Kaggle /Pytorch CNN MNIST/Input/MNIST/processed/test.pt' ROOT = '../Input' MODEL_PATH = '../Input/Model' LATEST_MODEL = '/CNN-2021-02-26 02:47:01.247436.pt' TES...
# -*- coding: utf-8 -*- """Copyright 2015 Roger R Labbe Jr. FilterPy library. http://github.com/rlabbe/filterpy Documentation at: https://filterpy.readthedocs.org Supporting book at: https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python This is licensed under an MIT license. See the readme.MD file for mor...
import os import time import torch import torch.nn as nn from torch.autograd import Variable from models import ResNet as resnet_cifar import pandas as pd import argparse import csv from torch.optim.lr_scheduler import MultiStepLR from dataLoader import DataLoader from summaries import TensorboardSummary # parameters...
#!/usr/bin/env python """ This module provides PrimaryDSType.List data access object. """ from WMCore.Database.DBFormatter import DBFormatter from dbs.utils.dbsExceptionHandler import dbsExceptionHandler class List(DBFormatter): """ PrimaryDSType List DAO class. """ def __init__(self, logger, dbi, owne...
#!/usr/bin/env python """Tests for the ee.serializer module.""" import json import unittest import ee from ee import apitestcase from ee import serializer class SerializerTest(apitestcase.ApiTestCase): def testSerialization(self): """Verifies a complex serialization case.""" class ByteString(ee.Encod...
from django.db import models from django.contrib.auth.models import User # Create your models here. class Categorie(models.Model): All_Cat = models.CharField(max_length=20, null=True) def __str__(self): return self.All_Cat class Post(models.Model): Cat = models.ForeignKey(Categorie, on_delete=mo...
import os PROJECT_REPORT_BOILERPLATE_URL = 'https://github.com/cloudblue/connect-report-python-boilerplate.git' PROJECT_REPORT_BOILERPLATE_TAG = os.environ.get('PROJECT_REPORT_BOILERPLATE_TAG')
import json from chargebee.model import Model from chargebee import request from chargebee import APIError class PaymentSource(Model): class Card(Model): fields = ["first_name", "last_name", "iin", "last4", "brand", "funding_type", "expiry_month", "expiry_year", "billing_addr1", "billing_addr2", "billing_cit...
""" A module containing class for map containing all objects """ import config import os from time import sleep class Map: """ A Generalised class for all level maps """ def __init__(self, map_id, columns, rows, map_length): """ Initialises the attributes of map """ se...
import numpy as np import tensorflow as tf from libs.utils.calc_ious import bbox_giou, bbox_iou __all__ = ['get_losses'] def get_losses(pred_raw, pred_decoded, label, bboxes, stride, iou_loss_thr, num_classes): """ Args: pred_decoded: decoded yolo output pred_raw: raw yolo output """ bat...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # License : GPL3 # Author : Jingxin Fu <jingxinfu.tj@gmail.com> # Date : 11/02/2020 # Last Modified Date: 23/05/2020 # Last Modified By : Jingxin Fu <jingxinfu.tj@gmail.com> # -*- coding: utf-8 -*- # Author : Jingxin Fu <jingxi...
from setuptools import setup setup(name='gtab', version='0.8', author="EPFL DLAB", author_email="epfl.dlab@gmail.com", description='gtab (Google Trends Anchor Bank) allows users to obtain precisely calibrated time series of search interest from Google Trends.', long_description='For a pro...
import sys def inc_dict_value(d,k): try: d[k] += 1 except KeyError: d[k] = 1 def update_progress(progress, prefix="Precent", barLength=10) : # copied from https://stackoverflow.com/questions/3160699/python-progress-bar status = "" if isinstance(progress, int): progress = float(progress) if no...
import gooeypie as gp def change_colour(event): # Convert each number value from 0 to 255 to a 2-digit hex code rr = str(hex(red_value.value))[2:].rjust(2, '0') gg = str(hex(green_value.value))[2:].rjust(2, '0') bb = str(hex(blue_value.value))[2:].rjust(2, '0') # Set the background colour col...
print("hello world") #python can do all calculations a=1+1 print(a) print(100**10) #for statement for val in range(5): print(val) #if statement num=5 if num>=0: print('positive') else: print('negative') #string concatenation string="python" string1=" is easy" print(string+string1) #boolea...
#!/usr/bin/python #-*- coding:utf-8 -*- import sys import struct import numpy as np import random import tensorflow as tf def broadcast_to_f32(): para = [] broadcast_shape = [] # init the input data and parameters broadcast_dimcount = int(np.random.randint(1, high=7, size=1)) zero_point = int(np...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Created by Roger on 2019/12/3 doc_tex = """#BeginOfDocument ENG_NW_001278_20130418_F00012ERM rich_ere ENG_NW_001278_20130418_F00012ERM E599 148,156 violence Conflict_Attack Actual rich_ere ENG_NW_001278_20130418_F00012ERM E619 280...
import FWCore.ParameterSet.Config as cms ###OMTF emulator configuration simOmtfDigis = cms.EDProducer("L1TMuonBayesOmtfTrackProducer", srcDTPh = cms.InputTag('simDtTriggerPrimitiveDigis'), srcDTTh = cms.InputTag('simDtTriggerPrimitiveDigis'), srcCSC = cms.InputTag('simCscTriggerPri...
# coding: utf-8 """ OpenAPI Petstore This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech """ ...
import sqlite3 _conn = None _c = None def init(conn): c = conn.cursor() _conn = conn _c = c _c.execute('CREATE TABLE IF NOT EXISTS group (id INTEGER AUTO_INCREMENT, name VARCHAR(200))') _c.execute('CREATE TABLE IF NOT EXISTS perm (id INTEGER AUTO_INCREMENT, group INTEGER, permname VARCHAR(200), pe...
from datetime import timedelta import factory from django.utils import timezone from oauth2_provider.models import AccessToken from sso.oauth2.models import Application from .user import UserFactory class ApplicationFactory(factory.django.DjangoModelFactory): client_type = Application.CLIENT_CONFIDENTIAL a...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import pandas as pd from sklearn.model_selection import KFold from sklearn.linear_model import Lasso import copy, sys, time Times = 10 Fold = 5 ZERO_TOL = 0.000001 ################################################ def read_dataset(data_csv, value_txt):...
# -*- coding: utf-8 -*- import os import sys sys.path.insert(0, os.path.dirname(os.path.abspath('.'))) project = 'test' master_doc = 'index'
from newsblur.celeryapp import app from utils import log as logging @app.task() def IndexSubscriptionsForSearch(user_id): from apps.search.models import MUserSearch user_search = MUserSearch.get_user(user_id) user_search.index_subscriptions_for_search() @app.task() def IndexSubscriptionsChunkForSearc...
# pass list in a function n = int(input("Enter the no. of elements you want in the list: ")) def count(lst): even = 0 odd = 0 for i in lst: if i % 2 == 0: even += 1 print(i, "EVEN") else: odd += 1 print(i, "ODD") return even,odd lst = []...
#!/usr/bin/env python # vim: set filencoding=utf8 """ SnakePlan Setup Script @author: Mike Crute (mcrute@gmail.com) @date: July 09, 2010 """ # 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 # ...
from celery import shared_task from ..core.utils import create_thumbnails from .models import ProductImage, ImageData @shared_task def create_product_thumbnails(image_id): """Takes ProductImage model, and creates thumbnails for it.""" create_thumbnails(pk=image_id, model=ProductImage, size_set='products') @...
import os import pybase64 from telegraph import exceptions, upload_file from telethon.tl.functions.messages import ImportChatInviteRequest as Get from userbot import bot from userbot import CMD_HELP from userbot.utils import admin_cmd from userbot.helpers import * @bot.on(admin_cmd(pattern="lolice(?: |$)(.*)"...