text
stringlengths
38
1.54M
import graphene from graphene_django.types import DjangoObjectType from graphene.types.generic import GenericScalar from django.utils import timezone import datetime import pytz from django.db.models import Q from backend.utils import HelperClass from functools import reduce from collections import Counter import datet...
import os import pickle import os.path import datetime from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from googleapiclient.http import MediaFileUpload class GDrive(): def __init__(self): scopes = ['https:...
print("start of program") x = input("enter first number: ") x = int(x) y = input("enter second number: ") y = int(y) w = input("do you want to + - * /") if(w == "+"): answer = x+y print(x,"+",y,"=", answer ) elif(w == "-"): answer = x-y print(x,"-",y,"=", answer) elif(w == "*"): answer = x...
''' start = 2 stop = 21 - 1 = 20 step = 2 ''' ''' for i in range(2,21,2): print(i) ''' for i in range(10,1,-1): print(i)
from django.shortcuts import redirect def check_have_blog(func): def inner(request, *args, **kwargs): user = request.user if user.blog: return func(request, *args, **kwargs) else: return redirect('/backend/index.html') return inner
from django.shortcuts import render, render_to_response, redirect from .forms import UserCreationForm from django.contrib.auth.models import User from django.http import HttpResponseRedirect from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.decorators import login_required from django.u...
## A simple script that calculates the complex roots of a given quadratic equation, by taking as inputs the coefficients of the equation ## from cmath import sqrt print('\nFor the equation in form:\na*x^2+b*x+c=0\n') a=float(input("Enter the value of a: ")) b=float(input("Enter the value of b: ")) c=float(in...
import sys import collections import string import ROOT from gdata.youtube import service from random_video import GenerateVideo from gdata.service import RequestError #--------------------------------------------------------------------- def comments_generator(client, video_id): """ Returns the list of video...
''' 3 2 2 1 1 3 # 2 1 3 4 3 1 4 2 3 4 2 # 1 4 2 3 5 4 2 4 3 5 2 3 1 2 # 1 2 3 5 4 ''' for t in range(1, 11): start, end = map(int, input().split()) data = list(map(int, input().split())) adj = [[] for i in range(start + 1)] visit = [None] + [0] * start for i in range(0, len(data), 2): ...
from django.shortcuts import render from models import * from django.http import HttpResponse, JsonResponse import requests import json # Create your views here. def music(request): context = {} if request.method == 'POST': key_word = request.POST.get('name') page = request.POST.get('page', '1...
import pytorch_pretrained_bert import math def bert_optimizer(model, config, data_loader): # # build optimizer, learning rate scheduler. delete every lines containing lr_scheduler for disabling scheduler num_train_optimization_steps = int(math.ceil(data_loader.n_samples / data_loader.batch_size + 0.5) / config...
# coding: utf-8 from model.yolo_v3 import YOLO_V3 import config as cfg from data import Data import tensorflow as tf import numpy as np import os import argparse class YoloTrain(object): def __init__(self): self.__anchor_per_scale = cfg.ANCHOR_PER_SCALE self.__classes = cfg.CLASSES self._...
#!/usr/bin/env python3 import sys import math import time train = [] test = [] for lines in sys.stdin: lines = lines.strip() features = [float(x) for x in lines.split(',')] if features[-1]!=-1.0: train.append(features) continue else: test.append(features[:-1]) for test_value, values in enumerate(test): s...
import json import datetime from models.patient import Patient from models.database import DataAccess def initiate_archiving(): print("Beginning archiving records") patient_ids = DataAccess("patients").db.find({"selector": {"_id": {"$gt": None}}, "fields": ["_id"], "limit": 9000}) # get all patient ids ...
from django.shortcuts import render from django.shortcuts import redirect from django.http import HttpResponseRedirect from django.http import Http404 from django.template.response import TemplateResponse from django.urls import reverse from django.db import models from django.db.models import Sum from school_system.fo...
from __future__ import print_function import numpy as np import os.path as osp from robolearn_envs.pybullet.core.bullet_utils import Link from robolearn_envs.pybullet.core.bullet_sensors import Camera from robolearn_envs.pybullet.core.bullet_multibody import BulletMultibody class BulletObject(BulletMultibody): de...
import sys import time import numpy as np import torch import torch.nn as nn from torch.autograd import Variable from classifier import FCClassifier class NLIModel(nn.Module): """ Main model class for the NLI task calling SentenceEmbedding and Classifier classes """ def __init__(self, config): ...
from random import randint import random from CX import crossoverOperator from CX import crossoverOperator2 population = [] # list that holds paths population_size = 10 # max 120 combinations mutate_prob = 0.1 n_generations = 1 routes_length = [0]*population_size fitness = [0]*population_size best_path = 1000 citie...
#Exercício Python 29: Escreva um programa que leia a velocidade de um carro. Se ele ultrapassar 80Km/h, mostre uma mensagem dizendo que ele foi multado. A multa vai custar R$7,00 por cada Km acima do limite. v = int(input('Digite sua velocidade: ')) if v <= 80: print('Você está na velocidade correta.') else: m ...
from app import db '''Make clases declared here to be available on make_shell_context in Manager.py''' class Category(db.Model): __tablename__ = 'inv_categories' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique = True) description = db.Column(db.String(128)) ...
''' Disjoint Sets support the following operations: make_set(x): creates a singleton set {x} find(x): returns ID of the set containing x union(x, y): merges two sets containing x and y,respectively. ''' class Disjoint_Sets_Element: def __init__(self, _parent = -1, _rank = 0): self.parent = _par...
#!/usr/bin/env python """ Runner class of Dotmanager. Run configuration scripts. """ import os import subprocess __author__ = "Romain Ducout" class Runner(): """Applies the runs of a configuration""" def __init__(self, config, config_root): self.config = config self.config_root = config_root ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals from datetime import date today = date.today() AUTHOR = "Leonardo Giordani" SITENAME = "The Digital Cat" SITESUBTITLE = "Adventures of a curious cat in the land of programming" SITEURL = "" DEBUG = True # WEBASSETS_DEBUG = True #...
from client_chuli import * class Gui: def __init__(self, connfd): self.connfd = connfd self.state = 0 # 创建注册窗口(在登录窗口的基础上创建) def client_signgui(self, t, v): # 重置登录窗口提示语 # v.set('') # 创建注册窗口 top2 = Toplevel(t) top2.title("注册") top2.geometry("4...
from django.db import models # Create your models here. class Author(models.Model): name = models.CharField(max_length=50) birth_date = models.DateField(null=True) def __str__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=50) def __str__(self): ...
x = 1 apartments = [] sum_ap = 0 while x > 0: x = int(input("Apartment price: ")) if x > 0: sum_ap = sum_ap + 1 apartments.append(x) print("Apartment", sum_ap, "price:", x) else: print("Try again!") break sum_price = 0 k = 0 for k in range(len(apartments)): sum_p...
import Quartz from Foundation import NSMutableData from PyObjCTools.TestSupport import TestCase, min_os_level class TestCGPDFContext(TestCase): def testFunctions(self): data = NSMutableData.data() self.assertIsInstance(data, Quartz.CFMutableDataRef) consumer = Quartz.CGDataConsumerCreateW...
import unittest from tests.unit_test_helper.console_test_helper import * class TestOutput(unittest.TestCase): def test(self): temp_globals, temp_locals, content, output = execfile("lab16/ch016_t17_list_slicing.py") self.assertEqual("!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI", temp_locals['g...
#!/usr/bin/env python import platform from itertools import product from egcg_core.config import cfg from pyclarity_lims.entities import Sample, Container, Step from EPPs.common import StepEPP, get_workflow_stage, InvalidStepError, finish_step class CopySamples(StepEPP): """Creates duplicate submitted samples w...
def decorator_func(say_hello_func): def wrapper_func(hello_var, world_var): hello = "Hello, " world = "World" if not hello_var: hello_var = hello if not world_var: world_var = world return say_hello_func(hello_var, world_var) return wrapper_func @decorator_func d...
# https://leetcode.com/problems/longest-common-subsequence/ # 2021/10 # 638 ms class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: L1, L2 = len(text1), len(text2) dp = [[0] * (L1 + 1) for _ in range(0, L2 + 1)] for j in range(0, L2): for i in range...
import torch from torch import nn import sys from src import models from src import ctc from src.utils import * import torch.optim as optim import numpy as np import time from torch.optim.lr_scheduler import ReduceLROnPlateau import os import pickle from sklearn.metrics import classification_report from sklearn.metric...
from django.db import models from django.core.exceptions import ValidationError from lis.specimen.lab_aliquot.models import BaseAliquot from edc_base.model.models import BaseUuidModel from .aliquot_condition import AliquotCondition from .aliquot_type import AliquotType from .receive import Receive class Aliquot(Ba...
from pathlib import Path from collections import namedtuple, Counter def flatten(l): flat = [] for el in l: if type(el) is list: flat.extend(el) else: flat.append(el) return flat class IncludeFile(Path): _flavour = Path('.')._flavour class SourceFile(Path)...
class GenericPipelineTask: def __init__(self): pass def run(self): pass class DataPreparationTask: def __init__(self): self.name = 'data_preparation' def run(self): pass class FeatureEngineeringTask: def __init__(self): self.name = 'feature_engineering...
import pyttsx3 import datetime import speech_recognition as sr import wikipedia import webbrowser engine = pyttsx3.init('sapi5') voices = engine.getProperty('voices') engine.setProperty('voices', voices[0].id) def speak(audio): engine.say(audio) engine.runAndWait() def wishme(): hour = i...
# -*- coding: utf-8 -*- """ Created on Thu Dec 19 08:59:42 2019 @author: SNR """ from selenium import webdriver from BeautifulSoup import BeautifulSoup import pandas as pd driver = webdriver.chrome('N:\GitHub\PythonCorseJohn') DateAndTime = [] News = [] TypeOfNews = [] driver.get('https://www.bseindia.com/corporate...
# encoding= utf-8 # @Time : 2020/5/11 9:25 # @Author : Yao # @File : vector.py # @Software: PyCharm from math import hypot class Vector: def __init__(self, x=0, y=0): self.x = x self.y = y #字符串表达式 def __repr__(self): return 'Vector(%r, %r)' %(self.x,self.y) def __abs__(s...
from flask import Flask, flash from config import config from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_pagedown import PageDown from flask_moment import Moment from flask_bootstrap import Bootstrap from faker import Faker db = SQLAlchemy() login_manager = LoginManager() pagedo...
# Generated by Django 2.0.5 on 2018-09-03 12:01 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django_jalali.db.models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
def PatternToNumber(pattern): if pattern == "" : return 0 lastSymbol = pattern[-1] restOfPattern = pattern[0:-1] return (4*PatternToNumber(restOfPattern)+SymbolToNumber(lastSymbol)) def SymbolToNumber(symbol): if symbol == 'A': return 0 elif symbol == 'C': ...
__author__ = 'mactep' import argparse from extra.share import igblastp_tools def printRegionLabels( dom ): for i in [1,2,3]: FR_S = "FR" CDR_S = "CDR" if len(dom.getFR(i)) > 0: FR_S = FR_S[:(len(dom.getFR(i))-1)] if len(dom.getCDR(i)) > 0: CDR_S = CDR_S[:(...
import sys import os import requests import json def results(ipaddr): r = requests.get( f'http://ip-api.com/json/{str(ipaddr)}?fields=status,country,countryCode,reverse,query' ) return json.dumps(r.json(), indent=4) def main(argv): ipaddr = "ipaddr.txt" if os.path.exists(ipaddr) and os....
#!/usr/bin/env python3 # CAUTION this script doesn't check for Remote File Inclusion (RFI) # DISCLAIMER # ONLY test this in a server you have permission to do it!!!!!!! from ArgumentHandler import ArgumentHandler from termcolor import colored import PayloadManager import sys from pyfiglet import Figlet from proxies_...
# # Copyright (c) 2018 Intel Corporation # # 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...
import logging import numpy as np import scipy.stats from anndata import AnnData _default_filters = ( 'filter_quality', 'filter_reads', 'filter_copy_state_diff', 'filter_is_s_phase', ) def calculate_filter_metrics( adata: AnnData, quality_score_threshold=0.75, read_count_thr...
from rest_framework import pagination from rest_framework.views import Response class CustomPageNumberPagination(pagination.PageNumberPagination): page_size = 15 def get_paginated_response(self, data): return Response({ 'links': { 'next': self.get_next_link(), ...
# Copyright 2015 Google Inc. 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 law or ag...
""" Given an array of integers a and an integer sum, find all of the unique combinations in a that add up to sum. The same number from a can be used an unlimited number of times in a combination. Elements in a combination (a1 a2 … ak) must be sorted in non-descending order, while the combinations themselves must be sor...
#!/usr/bin/env python import argparse import os import os.path import shutil import re def ParseArgs() : parser = argparse.ArgumentParser(description='Delete folders based on a regular expression.') parser.add_argument('-q', '--quiet', action="store_true", help="Delete folders without confirmation.") parser.add_a...
import numpy as np import csv import keras import random import utm import math import keras.optimizers as op from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten, Activation, Reshape from keras.layers import Conv2D, MaxPooling2D, LSTM from keras.optimizers import SGD, Adam from keras.ut...
from os.path import join import redis from catcher.core.runner import Runner from catcher.utils.misc import try_get_object from test.abs_test_class import TestClass class RedisTest(TestClass): def __init__(self, method_name): super().__init__('redis', method_name) def test_set(self): self.p...
import numpy as np b = np.arange(24).reshape(2, 12) print(b) print(b.ndim) print('*' * 30) b = np.arange(24).reshape(2, 12) print(b) print(b.size) print('*' * 30) b = np.arange(24).reshape(2, 12) print(b) print(b.itemsize) print('*' * 30) b = np.arange(24).reshape(2, 12) print(b) print(b.nbytes) print('*' * 30)...
# -*- coding:utf-8 -*- # author: bcabezas@apsl.net from django.db import models from cms.models.fields import PlaceholderField from cms.models import CMSPlugin from easy_thumbnails.files import get_thumbnailer from django.conf import settings from django.contrib.staticfiles.finders import find as staticfiles_find imp...
"""Utilities used by the SpikeGLX interfaces.""" import json from datetime import datetime from pathlib import Path from ....utils import FilePathType def get_session_start_time(recording_metadata: dict) -> datetime: """ Fetches the session start time from the recording_metadata dictionary. Parameters ...
from webapp import create_app from webapp.hh_2 import hh_parse from flask import current_app app = create_app() with app.app_context(): hh_parse(current_app.config['BASE_URL'], current_app.config['HEADERS'])
cislo = int(input("Zadajte číslo: ")) def najdiDelitele(x): delitele = [] for i in range(x): if x % (i+1) == 0: delitele.append(i+1) return (delitele) def jePrvocislo(y): l = najdiDelitele(y) if(len(l) == 2): return 1 else: return 0 def najdiPrvocisla(z): ...
# 题目:有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。问第三个人,又说比第2人大两岁。问第2个人,说比第一个人大两岁。最后问第一个人,他说是10岁。请问第五个人多大? a = 10 for i in range(2, 6): # 后面的人比前面的人大两岁 a = a + 2 print("第%d个人%d岁!" % (i, a)) # def age(n, a): # if n == 1: # return a # else: # return age(n - 1, a) + 2 # ...
"""Module with functions for making forecast scenarios.""" from __future__ import division from collections import namedtuple import logging from frozendict import frozendict import numpy as np import xarray as xr from fbd_core.etl.computation import weighted_mean, weighted_quantile from fbd_core.etl.transformation i...
import sys import subprocess as sp if(len(sys.argv) != 2): print("Incorrect Usage") print("Usage: python3 click.py <file containing subdomains>") sys.exit() sp.run("mkdir poc", shell=True) inputFile = open(sys.argv[1],"r") i=1 for line in inputFile: line=line.rstrip("\n") content="<html>\n<...
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: (r'^$', 'bicalca.monitor.views.show'), (r'^monitor/add', 'bicalca.monitor.views.add'), (r'^monitor/save', 'bicalca.mon...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Nov 17 16:07:56 2016 @author: ibackus """ import numpy as np import cPickle as pickle import okcupidio import pandas as pd # RUN FLAGS do_make_features = True do_filter_features = True do_pca = True # SETTINGS savename = 'features.p' minResponseRate ...
import numpy as np def score_game(game_core): '''Запускаем игру 1000 раз, чтобы узнать, как быстро игра угадывает число''' count_ls = [] # фиксируем RANDOM SEED, чтобы ваш эксперимент был воспроизводим! np.random.seed(1) random_array = np.random.randint(1, 101, size=(1000)) for number in rando...
def make_incrementor (n): return lambda x: x + n f = make_incrementor(2) g = make_incrementor(6) print f(42), g(42) if 0: print("yes") else: print("no") if "a" in "there" or 6 % 2: print('true') else: print('false') print(6 % 2) my_list = [ "cat", 2, "dog", 4] x = 5 in my_list print(x) if x: p...
#输出打印涉及变量的句子 special_number=3 message=str(special_number)+"是33最喜欢的数字!" print(message)
from django.urls import path from .views import upload_csv, download_csv, pause_task, resume_task, cancel_task urlpatterns = [ path('task/<int:task_id>/pause/', pause_task, name="pause_task"), path('task/<int:task_id>/resume/', resume_task, name="resume_task"), path('task/<int:task_id>/cancel/', cancel_ta...
# -*- coding: utf-8 -*- from odoo import models, fields, api from odoo.exceptions import ValidationError import logging _logger = logging.getLogger(__name__) class routeusers(models.Model): _name = 'routeusers' _rec_name = 'name' _description = 'routeusers' _parent_store = True name = fi...
import numpy as np import cv2 #put these files on the desktop face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') img = cv2.imread('face.png') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1....
''' Created on Mar 10, 2015 @author: puneeth ''' import pandas, csv, time from collections import Counter from astropy.table.row import Row start = time.time() print(str(start)) ifname = 'train.csv' ofname = 'train_data.csv' print('Read train.csv') df_train = pandas.read_csv(ifname) print('Consolidate 40 Soil Ty...
''' Created on Dec 26, 2017 @author: Mark ''' from _collections import defaultdict comps = [] hiscore = None longest = defaultdict(list) with open("data/Day24") as f: for l in f: comp = l.strip().split("/") comps.append((int(comp[0]), int(comp[1]))) def solve(bridge, used): global comps global hiscore glob...
#import libraries from sklearn import datasets import numpy as np import matplotlib.pyplot as plt import math #Import the Boston Dataset and differentiate Features(data) and Targets print 'Loading Boston Dataset.....' boston = datasets.load_boston() data=boston.data target=boston.target tr=data.shape[0] ...
from django.urls import path from . import views app_name = 'hello' urlpatterns = [ #path('<int:id>/<nickname>/', views.index, name='index'), path('my_name_is_<nickname>.I_am_<int:age>_years_old.', views.index, name='index'), ]
""" Globals (mainly constants) """ # Colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) BLUE = (0, 0, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) ALL_LAYERS = ["bg1", "bg2", "cache", "obstacle", "dessinable","ramassable", "actionnable", "personnage", "joueur" ] assert all(s[-1]!='s' for s in ALL_LAYERS),"layername s...
# # The Python Imaging Library. # $Id$ # # macOS icns file decoder, based on icns.py by Bob Ippolito. # # history: # 2004-10-09 fl Turned into a PIL plugin; removed 2.3 dependencies. # 2020-04-04 Allow saving on all operating systems. # # Copyright (c) 2004 by Bob Ippolito. # Copyright (c) 2004 by Secret Labs. #...
import requests as rq from bs4 import BeautifulSoup import vpn_connect as vc import json import time import re def retry(file): def inner(func): def wrapper(): ret = True while ret: ret = False try: data = func() except Exception as e: print(e) change_country() ret = True ...
suites_menu = ('link_text', 'Suites', 'Suites menu') tests_menu = ('link_text', 'Tests', 'Tests menu') pages_menu = ('link_text', 'Pages', 'Pages menu') reports_menu = ('link_text', 'Reports', 'Reports menu') project_settings_menu = ('link_text', 'Settings', 'Settings menu') environments_menu = ('link_text', 'Environm...
from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import ( detail, edit, list as _list, ) from django.urls import reverse_lazy from ..models import ( Contact, ContactEmail ) __all__ = ( 'ContactEmailView', 'ContactEmailListView', 'ContactEmailCreateView...
import numpy as np import cv2 from remove import median_filter cap = cv2.VideoCapture('./green.mov') allFrames = [] frames = np.arange(0, 10700, 15) ret = True WINDOW_SIZE = 40 while(cap.isOpened() and ret): ret, frame = cap.read() if ret: allFrames.append(np.array(frame)) allFrames = np.array(allFr...
#coding=UTF-8 ''' Created on Jan 7, 2011 @author: elvin ''' import settings import urllib from google.appengine.ext import blobstore from google.appengine.ext.webapp import blobstore_handlers from google.appengine.ext.webapp import util from google.appengine.ext import db from google.appengine.ext import webapp from ...
from django.conf import settings from django.contrib.postgres.fields import HStoreField from django.db import models from s3direct.fields import S3DirectField class Gallery(models.Model): title = models.CharField(max_length=55) description = models.TextField(blank=True) owner = models.ForeignKey(settings...
months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def days(y, m): if m != 1: return months[m] if y % 4 != 0: return 28 if y % 100 != 0: return 29 if y % 400 != 0: return 28 return 29 sun = 0 day = 0 for year in range(1900, 2001): for month in range(0, 1...
import FWCore.ParameterSet.Config as cms import copy process = cms.Process('runZtoMuTau') # import of standard configurations for RECOnstruction # of electrons, muons and tau-jets with non-standard isolation cones process.load('Configuration/StandardSequences/Services_cff') process.load('FWCore/MessageService/Message...
"""유저의 회원가입, 로그인, 로그아웃, 내 정보 확인, 내 정보 수정 뷰들이 담겨있습니다.""" import json import bcrypt import jwt from django.shortcuts import render from django.views import View from django.http import HttpResponse, JsonResponse from django.db import IntegrityError from eatexpress.settings import SECRET_KEY, HASH from user.models impor...
#! /usr/bin/env python # -*- coding: utf-8 -*- import sys from PySide6.QtWidgets import QApplication, QMainWindow, QDialog from PySide6 import QtCore # импортируем связанный py файл с нашим ui файлом from design_calculator import Ui_MainWindow class MainWindow(QMainWindow): def __init__(self): # вызовем метод ...
# Eu estou usando o exercício 4 da lista de programação 5 para executar este exercício. def main(): arquivo = open('texto.txt', 'r') conteudo = arquivo.read() lista_palavras = conteudo.split() acronimo = '' for palavra in lista_palavras: acronimo = acronimo + palavra[0] acronimo = a...
#!/usr/bin/env python import subprocess from wrappers_settings import * import sys if len(sys.argv) > 3: path = check_username(sys.argv[1]) size = sys.argv[2] lvm_name = sys.argv[3] run_command(["lvcreate", "-n", path, "-L%sG" % size, lvm_name]) sys.exit(0) sys.exit(255)
import Gato def alimentar(Animales.Animal): if(tipoalimento=tipoalimento): self.tipoalimento+="Dogui" self.cantidadalimento=cantidadalimento else: print("El gato tiene hambre") def TomarAgua(Animales.Animal): if(self.CantidadAgua.CantidadAgua): self.cantidadaliment...
import abc import inspect import json import os import multiprocessing import time import numpy as np import tensorflow as tf2 from ..utils.misc import time_block, colorize from ..utils.exception import NotSamplingError tf = tf2.compat.v1 tf.disable_v2_behavior() class Base(abc.ABC): """Base class for all recomme...
# # A number of functions which can be used to add various types of noise to # exact simulations to create fake data # # This file is part of PINTS. # Copyright (c) 2017, University of Oxford. # For licensing information, see the LICENSE file distributed with the PINTS # software package. # # import numpy as np de...
#!/usr/bin/env python # coding: utf-8 # In[2]: import sys from time import sleep plot_mode = False n_epoch_scale = 1 if(len(sys.argv) > 1): if sys.argv[1][0] == 'p': print("executing: "+sys.argv[1]+" -> "+str(len(sys.argv[1]))+" Plot mode enabled") plot_mode = True if sys.argv[1][0] == 'h': print("executing:...
from weakref import WeakKeyDictionary import pytest from mock import Mock, patch from nameko.containers import ServiceContainer, WorkerContext from nameko.testing.services import dummy, entrypoint_hook from nameko_sqlalchemy.database import ( DB_URIS_KEY, Database, Session, ) from sqlalchemy import Column,...
from django.urls import path from . import views from .views import HouseListView, HouseDetailView, HouseCreateView, HouseUpdateView, HouseDeleteView urlpatterns = [ path('', HouseListView.as_view(), name='home'), path('<int:pk>/', HouseDetailView.as_view(), name='detail'), path('new/', HouseCreateView.as...
def main(): try: import math import numpy as np filein = open("billboard.in", "r") file = open("billboard.out", "w") print("files opened") nums = np.zeros((2,4)) print("matrix created") for i in range(0,2): parts = filein.readline().split('...
import imdb_crawler as ic if __name__ == "__main__": generos = ['adventure', 'documentary', 'reality_tv', 'game_show'] pag = 1 url = 'http://www.imdb.com/search/title/?genres={}&title_type=' \ 'tv_series,mini_series&page={}&ref_=adv_nxt'.format(generos[0], 1) ic.crawler_tvseries(tipo="adventur...
''' Nalu Zou, Yuming Tsang, Jerome Orille 3/13/20 Project Part 2 - Crew Member Data Wrangling This is a test file used for testing similar code in 'dept_info.py' and 'crew_info.py.' ''' from test_util import assert_equals from crew_dept_info import populate_department, total_department import pandas as pd from ast imp...
import os DB_HOST = os.environ.get('DB_HOST') DB_PORT = int(os.environ.get('DB_PORT')) DB_USER = os.environ.get('DB_USER') DB_PASSWORD = os.environ.get('DB_PASSWORD') DB_DATABASE = os.environ.get('DB_DATABASE') DB_TABLE = os.environ.get('DB_TABLE')
import numpy def take_input(): #Taking input from the user. message = 'Please enter the number of type of stylization you want:\n'+'1)normal stylization\n'+'2)black and white\n'+'3)line stylization \n' typeI = int(input(message)) filename = str(input('Enter filename with extension :')) N = int...
import numpy as np import matplotlib.pyplot as plt # Create red points centered at (-2, -2) red_points = np.random.randn(50, 2) - 2 * np.ones((50, 2)) # Create blue points centered at (2, 2) blue_points = np.random.randn(50, 2) + 2 * np.ones((50, 2)) # plt.interactive(False) # Plot the red and blue points plt.scatt...
import random from corpustools.corpus.classes.lexicon import Corpus, Inventory, Segment, FeatureMatrix, Word from corpustools import __version__ as currentPCTversion def force_update2(corpus): corpus = Corpus(None, update=corpus) for word in [x for x in corpus]: word2 = Word(update=word) corpus...
import sys from androguard.core.bytecodes import apk from androguard.core.bytecodes import dvm import pandas as pd import serial import time dataset_perm_list = ["android.permission.BIND_WALLPAPER", "android.permission.FORCE_BACK", "android.permission.READ_CALENDAR", "android.permission.BODY_SENSORS", "android.permiss...