text
stringlengths
38
1.54M
import sys,os,math,itertools, operator sys.path.append('../pythonlib') import basic MAX = 10**6 MAX = 1500000 result = 0 tgt = [x for x in xrange(1, MAX) if x%2 == 0] tgt.reverse() for x in tgt:#[120]: res = 0 for c in xrange(1, x/2): ab = x*(x -2*c)/2 if c**2 != (x - c)**2 - 2*ab: c...
import os import tensorflow as tf import signal from helpers import * #from fc_2 import setup_model # from cnn_2_16 import setup_model #from cnn_2_8 import setup_model from cnn_3_12 import setup_model # from cnn_3 import setup_model IS_TRAINING = True MODEL_STORAGE_PATH = '/etc/bot/predictor/model/' os.makedirs(MODEL...
# Github Login * Navigate to github login page "https://github.com/login" * Verify page heading to be "Sign in to GitHub" ## SignIn to github account * Enter user account creadentials * Click to SignIn * Verify landing page after signIn
from pathlib import Path import unittest import numpy as np from ibllib.pipes import histology import ibllib.atlas as atlas class TestHistology(unittest.TestCase): def setUp(self) -> None: self.brain_atlas = atlas.AllenAtlas(res_um=25) self.path_tracks = Path(__file__).parent.joinpath('fixtures...
def euler635(): # def A3(n): # import itertools # B = range(1,3*n+1) # out = 0 # for i in itertools.combinations(B,n): # if sum(i)%n==0: # out+=1 # return out # import cmath # import mpmath # def f(n): # temp3 = 0 # for ...
n = int(input()) ans = 0 minDistModNot9 = float('inf') minDistModNot9Reserve = float('inf') for _ in range(n): a, b, c = sorted([int(x) for x in input().split()]) ans += a + b if c - b % 9 != 0: minDistModNot9 = min(minDistModNot9, c - b) if c - a % 9 != 0: minDistModNot9Reserve = min(minDistModNot9Reserve, c ...
def margeSort (list): """ This function sorts a list of numbers, and count the number of inversions done by the algorithm. This function sort list of numbers, the function implement the marge sort algorithm, dividing the list to two parts, sending thus lists to be sorted recursively and them mar...
import collections import json import numpy as np import typing from smac.configspace import Configuration from smac.tae.execute_ta_run import StatusType from smac.utils.constants import MAXINT __author__ = "Marius Lindauer" __copyright__ = "Copyright 2015, ML4AAD" __license__ = "3-clause BSD" __maintainer__ = "Mariu...
# Generated by Django 3.1.1 on 2020-09-23 04:28 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Customer', fields=[ ('id', models.AutoField...
""" Minion's bored game =================== There you have it. Yet another pointless "bored" game created by the bored minions of Professor Boolean. The game is a single player game, played on a board with n squares in a horizontal row. The minion places a token on the left-most square and rolls a special three-sided...
import math x=raw_input('enter the coordinate x\n') y=raw_input('enter the coordinate y\n') x=float(x) y=float(y) s=math.atan(y/x)/math.pi*180 print 'the angle in degrees is', s
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-05-11 20:17 from __future__ import unicode_literals import django.contrib.gis.db.models.fields from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencie...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jul 4 11:26:57 2019 @author: oghinde """ import sys home = str(Path.home()) sys.path.append(home + '/Git/Clusterwise_Linear_Model/') sys.path.append(home + '/Git/Utilities/') import numpy as np from normalization.time_series_normalizer import TimeSeri...
from django.db import models # Create your models here. class Patient(models.Model): name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) address = models.CharField(max_length=128) dob = models.DateField(auto_now=False, auto_now_add=False) phone_nu...
#coding=utf-8 import os from mysite.iclock.models import USER_SPEDAY,USER_SPEDAY_DETAILS from django.conf import settings from mysite.utils import getJSResponse from django.utils.translation import ugettext_lazy as _ def fileDelete(request,ModelName): if ModelName=='USER_SPEDAY': keys = request.POST.getlis...
from bs4 import BeautifulSoup import requests import sqlite3 import datetime location = 'atm_numbers.sqlite' table_name = 'currency' conn = sqlite3.connect(location) c = conn.cursor() sql_create = 'create table if not exists ' + table_name + ' (date text, currency text, buy text, sell text, nbu text)' # sql_drop = 'd...
import queue n = int(input()) m = int(input()) graph = [[] for i in range(n+1)] for _ in range(m): node1, node2 = map(int, input().split()) graph[node1].append(node2) graph[node2].append(node1) visited = [False] * (n+1) q = queue.Queue() q.put(1) visited[1] = True count = 0 while q.qsize() > 0: currentNod...
from django.shortcuts import render from flask import request # Create your views here. if request.method == 'POST' and 'run_script' in request.POST: # import function to run from .py_code.hello.py import * # call function def print_some (): # return user to required page return HttpResp...
from django import forms from ticketingApps.models import * from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from datetime import datetime, timedelta from django.utils import timezone class AddMovieForm(ModelFo...
import os import argparse import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence from torchtext import data from torchtext.vocab import pretrained_aliases, Vocab from transformers import (BertConfig, BertForSequence...
""" Generic test data """ from datetime import datetime from uuid import UUID import sqlalchemy from sqlalchemy.orm import Session from sqlalchemy.types import CHAR from pydantic import BaseModel, PositiveInt, constr from fastapi_sqlalchemy import models PEOPLE_DATA = [ {"name": "alice", "order": 1, "gender": "F...
#!/usr/bin/env python """Script to generate NIRISS SIAF content and files using pysiaf and flight-like SIAF reference files Authors ------- Johannes Sahlmann References ---------- Parts of the code were adapted from Colin Cox' makeSIAF.py For a detailed description of the NIRISS SIAF, the underlying r...
#Programmer: Daiwei Li #Date: 2019-04-28 import matplotlib.pyplot as plt import numpy as np #import pandas as pd import csv def read_csv(file_name): with open('data.csv') as f: reader = csv.reader(f) # eliminate blank rows if they exist rows = [row for row in reader if row] h...
from insurance import Client import os def main(): baseURL = "https://sandbox.root.co.za/v1/insurance" appID = os.environ.get('ROOT_APP_ID') appSecret = os.environ.get('ROOT_APP_SECRET') client = Client(baseURL, appID, appSecret) print(client.gadgets.get_phone_value("iPhone 6 Plus 128GB LTE")) if...
import sys sys.stdin = open("test.txt", "r") from collections import deque n, k = map(int, input().split()) a = deque(map(int,input().split())) step = 0 robots = deque([]) #0 카운트 while a.count(0) < k: step += 1 #회전 for i in range(len(robots)): robots[i] += 1 #a.rotate(1) temp = a.pop() ...
import math class LZ77(object): def __init__(self, min_sequence, sequence_length_bits, window_size_bits): self.min_sequence = min_sequence self.sequence_length_bits = sequence_length_bits self.max_sequence = pow(2, sequence_length_bits) + self.min_sequence - 1 self.window_size_bits...
from googleapiclient.discovery import build from google.auth.transport.requests import Request import Sheets.credBuilder as cb import psycopg2 sheetId = 'YOUR-SHEET-ID' dataRange = 'Sheet1!a:z' creds = cb.creds() conn = psycopg2.connect(host='localhost',database='postgres',user='postgres',password='password') ...
# 2018年8月14日 14:36:18 # 作为客户端与HTTP服务交互 # 通过HTTP协议访问多种服务,如下载数据或者与基于REST的API进行交互 # 对于简单的事情,使用urllib.request模块就够了,比如发送一个简单的HTTP GET请求到远程的服务上 ''' from urllib import request,parse # base URL being accessed url = 'http://httpbin.org/get' # Dictionary of query parameters(if any) parms={ 'name1':'value1', 'name2':'va...
# def isim(adi="",soyadi=""): # print("Merhaba",adi,soyadi) # isim(input("Adı:"),input("Soyadı:")) def tip(*args): sayim=0 for item in args: if str(type(item)) == "<class 'str'>": sayim+=1 print("Bu parametre de {} kadar str deger vardır".format(sayim)) tip(1,2,3,"deneme...
from django import template from django.shortcuts import reverse from django.utils.html import format_html from content.models import Participant, Entry, ParticipantAnswer register = template.Library() @register.filter(is_safe=True) def get_challenge_participants(challenge): participants = Participant.objects....
# Definition for a binary tree node. class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution(object): def bstFromPreorder(self, preorder): """ :type preorder: List[int] :rtype: Tre...
#!/usr/bin/python3.4 # coding: utf-8 """ Programme (classe) : CCompteEpargne.py version 1.3 Date : 11-03-2018 Auteur : Hervé Dugast ------- affichage console ----------------------------------------------------------------- *** Création de comptes épargnes ... type compte : EPAR Saisir le solde minimal (supérieu...
#!/usr/bin/env python from cosymlib import Cosymlib, __version__ from cosymlib import file_io from cosymlib.file_io.tools import print_header, print_footer, print_input_info from cosymlib.shape import tools import argparse import os import sys import yaml def write_reference_structures(vertices, central_atom, directo...
# Slow. Horrible. Ugly. Don't try this at home. """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: @staticmethod def computeHeight(root, curHeight=0): if root == None: return curHeigh...
-X FMLP -Q 0 -L 1 52 175 -X FMLP -Q 0 -L 1 49 150 -X FMLP -Q 0 -L 1 43 250 -X FMLP -Q 0 -L 1 41 400 -X FMLP -Q 0 -L 1 41 125 -X FMLP -Q 1 -L 1 39 125 -X FMLP -Q 1 -L 1 36 125 -X FMLP -Q 1 -L 1 35 250 -X FMLP -Q 1 -L 1 30 125 -X FMLP -Q 1 -L 1 30 300 -X FMLP -Q 2 -L 1 27 200 -X FMLP -Q ...
def sol_print(value): sol_print.line_number += 1; print "Case #%d: %s"%(sol_print.line_number, value) sol_print.line_number = 0 T = int(raw_input()) inputs = [] for i in range(T): inputs.append(raw_input()) for stack in inputs: idx = 0 operation = 0 while '-' in stack: countminus = ...
stringVariable = "Hello" integerVariable = 123 decimalVariable = 1.23 print(stringVariable) print(integerVariable) print(decimalVariable)
import pandas from sklearn import model_selection from sklearn.linear_model import LogisticRegression # loading data url = "https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data" filename = '../data/pima-indians-diabetes.data' names =['preg', 'plas', 'pres', 'skin',...
#!/usr/bin/python # Copyright: (c) 2019-2021, DellEMC from __future__ import (absolute_import, division, print_function) __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION =...
from django.db import models from django.utils import timezone # Create your models here. class Mainpage(models.Model): title = models.CharField(max_length=200) text = models.TextField() published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.publishe...
from game import player, resources, map, util import pygame import random import math import sys import os # Resoltuion variables, Display is stretched to match Screen which can be set by user DISPLAY_WIDTH = 640 DISPLAY_HEIGHT = 360 SCREEN_WIDTH = 640 SCREEN_HEIGHT = 360 if os.path.isfile("data/settings.txt"): pr...
''' Напишите программу, которая предлагает ввести пароль и не переходит к выполнению основной части, пока не введён правильный пароль. Основная часть – вывод на экран «секретных сведений». Sample Input 1: 1501 Sample Output 1: Введите пароль: Пароль верный! Секретные сведения: я учусь в IT-классе. Sample Input 2: 0...
from flask import Flask from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy import exc from sqlalchemy import event from sqlalchemy.pool import Pool from flask_cors import CORS app = Flask(__name__) app.config.from_object('chartingperformance.default_settings...
import socket # Create a UDP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) IP = input('Enter a destination IP: ') port = int(input('Enter a port number: ')) while True: print('Enter a message or click Enter to exit:') message = input() if message == '': break else: ...
import cv2 import numpy as np import time def existence_mask(frame, threshhold): resized = cv2.resize(frame, (60,60)) #lur = cv2.GaussianBlur(resized,(21, 21),0) hsv = cv2.cvtColor(resized, cv2.COLOR_RGB2HSV) target = np.uint8([[[25,77,249]]]) hsv_target = cv2.cvtColor(target, cv2.COLOR_BGR2HSV) ...
def verify_arrays_have_same_content(res, expected): _expected = set(expected) assert len(res) == len(expected) for el in res: if el in _expected: _expected.remove(el) else: assert False assert len(_expected) == 0
from django.forms import ModelForm, HiddenInput, NumberInput from user_stats.models import UserStats class UserStatisticForm(ModelForm): '''''' class Meta: model = UserStats fields = ('activity', 'period', 'method', 'user') widgets = { 'user': HiddenInput, 'acti...
# Generated by Django 3.1.1 on 2020-10-17 05:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tobacco', '0005_auto_20201017_1050'), ] operations = [ migrations.AlterField( model_name='board', name='boardid', ...
import string def countFileWords(file_path): f=open(file_path,'r') word_list=f.read().split() total_words=len(word_list) return total_words countFileWords('C:\\Users\\emenya\\Desktop\\smile.txt')
import asyncio import traceback import logging from aiosmb import logger from aiosmb._version import __banner__ from aiosmb.commons.connection.factory import SMBConnectionFactory from aiosmb.dcerpc.v5.interfaces.even6 import Even6RPC """ Query example: "*[System/EventID=5312]" """ async def amain(url, src = "Securi...
# Web flask library url, file upload, bootstrap, csv import os from flask import Flask, flash, render_template, url_for, request, redirect from werkzeug.utils import secure_filename from flask_bootstrap import Bootstrap import csv # machine learning import lib from keras.models import Sequential from keras.layers.cor...
from django.contrib import admin from usuarios.models import * from mensajes.models import * from salas.models import * from usu_salas.models import * admin.site.register(Usuarios.usu_nombre) admin.site.register(Mensajes) admin.site.register(Salas) admin.site.register(Usu_Salas)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.apps import AppConfig class DtrackingConfig(AppConfig): name = 'dtracking' verbose_name = 'Control de Avalúos'
from data_preprocessing import * import torch client_2 = {} n = list(users_split[1]) Load_2 = Data_division(data_file,n) print("***********************************") print("Splitting Data between clients") print("***********************************") client_2['dataset'] = torch.utils.data.DataLoader(Load_2) #read...
class Contact: def __init__(self, name, email, phone): self.name = name self.email = email self.phone = phone def print_contact(self): print("Nombre: {} ; Email: {} ; Phone: {} ".format(self.name, self.email, self.phone))
# Generated by Django 2.2.6 on 2020-01-26 13:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Notes', '0007_auto_20200126_0044'), ] operations = [ migrations.AddField( model_name='semester1subject', name='teach...
import tensorflow as tf from time import time from tensorflow.keras.losses import binary_crossentropy from tensorflow.keras.optimizers import Adam from tensorflow.keras.callbacks import EarlyStopping from tensorflow.keras.metrics import AUC from model_tf2 import DIN from utils_tf2 import * import os import pickle fr...
# Esto me muestra el texto en consola o pantalla print("Hola") print("Mundo") print("!!") """ Esto no se muestra por las comillas print("Hola") print("Mundo") print("!!") """ print("!!")
#%% print('startup') import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, BatchNormalization, Softmax, Flatten #%% (X_train, Y_train), (X_test, Y_test) = mnist.load_data() print(X_train.shape) ...
from django.urls import path, include urlpatterns = [ # path('tst/', include('backend.api.v2.tst.urls')), path('forum/', include('backend.api.v2.forum.urls')), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.contrib.auth.models import AbstractUser from django.db import models class UserWithProfile(AbstractUser): def save(self, *args, **kwargs): if not self.pk: self.profile = UserProfile(...
#!/usr/bin/env python3 import unittest from src.main.python.main import main class TestStringMethods(unittest.TestCase): def test_main_output_value(self): self.assertEqual(main(), "Hello from main!") def test_main_output_type(self): self.assertIsInstance(main(), str) if __name__ == '__ma...
# Generated by Django 3.2.6 on 2021-09-08 02:44 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('courses', '0001_initial'), ] operations = [ migrations.RenameField( model_name='course', old_name='teacher_id'...
#!/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...
from esl.agent import Agent from esl.interaction.header import MessageCode from esl.interaction.message import Message from esl.simulation.identity import Identity from esl.simulation.time import TimePoint class QuoteMessage(Message): def __init__(self, sender: Identity[Agent], recipient: Identity[Agent], sent: ...
import urllib import requests from app import consts def vk_get_name(user_id, access_token): if not user_id: return {} params = { 'user_ids': str(user_id), 'fields': 'photo_50' } user_info = vk_method('users.get', params, access_token) if not user_info or not user_info[0...
import matplotlib matplotlib.use("TkAgg") from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.figure import Figure import matplotlib.animation as animation from matplotlib import style import numpy as np import tkinter as tk from tkinter import ttk # IMPORTS import s...
# -*- coding: utf-8 -*- # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('global_co2.csv') X = dataset.iloc[219:,:1].values Y = dataset.iloc[219:,1:2].values # Splitting the dataset into the Training set and Test ...
import os.path from pathlib import Path from qtpy import QtCore, QtWidgets from qtpy.QtCore import Qt class FilenameModel(QtCore.QStringListModel): """ Model used by QCompleter for file name completions. Constructor options: `filter_` (None, 'dirs') - include all entries or folders only `fs_engine`...
from requests import Session import requests import io headers = {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate, sdch, br', 'Accept-Language': 'en-GB,en-US;q=0.8,en;q=0.6', 'Connection': 'keep-alive', 'Host': 'www1.nseindia.com', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWeb...
"""Mymood URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based ...
#!/usr/bin/python # -*- coding=utf-8 -*- #************************************************************************ # $Id: conjugate.py,v 0.7 2009/06/02 01:10:00 Taha Zerrouki $ # # ------------ # Description: # ------------ # Copyright (c) 2009, Arabtechies, Arabeyes Taha Zerrouki # # This file is the main file to ex...
import common result_file = open("results.json", "a") # OH # micro-snake protection_time = common.measure_protection_time(["../introspection-oblivious-hashing/run-oh.sh", "inputs/snake.bc", "inputs/micro-snake.in"]) print('OH snake protection time ' + str(protection_time)) runtime_overhead = common.measure_runtime_o...
# -*- coding: utf-8 -*- """ Created on Sat Sep 5 22:11:43 2015 @author: lucas """ from negocio.regras_de_negocio import * # from coleta.coleta_tempo_real import ColetaTempoReal from nltk.classify import NaiveBayesClassifier from util.corpus_util import CorpusUtil from datetime import datetime from util.classificador...
from django.contrib.auth.models import User, Group from rest_framework import serializers from .models import Physician class PhysicianSerializer(serializers.ModelSerializer): class Meta: model = Physician fields = ['id', 'firstName', 'lastName', 'maxShiftLoad', 'phoneNumber', 'specialty'] class ...
#coding: utf-8 ''' mbinary ####################################################################### # File : isBipartGraph.py # Author: mbinary # Mail: zhuheqin1@gmail.com # Blog: https://mbinary.xyz # Github: https://github.com/mbinary # Created Time: 2018-12-21 15:00 # Description: Judge if a graph is bipartite ...
# By Hadil Alsudies # !/usr/bin/env python3 import psycopg2 def query1(db): # Runs the first query and prints it c1 = db.cursor() c1.execute("""SELECT A.title AS ArticleName, count(log.logSlug) AS views FROM articles A, (SELECT regexp_replace(log.path, '^.+[/\\\]','') AS logSlug FROM log) AS ...
""" For example, given minion ID n = 1211, k = 4, b = 10, then x = 2111, y = 1112 and z = 2111 - 1112 = 0999. Then the next minion ID will be n = 0999 and the algorithm iterates again: x = 9990, y = 0999 and z = 9990 - 0999 = 8991, and so on. [210111, 122221, 102212] """ number = 210111 count = 0 def answer(n, b): re...
import shutil import sys from flask import Flask, send_from_directory from flask import jsonify from flask import request from flask_cors import CORS from waitress import serve shutil.rmtree('../models/metadata/webdriver/temp') from ModelHandler import ModelHandler from threading import Thread app = Flask(__name__) ...
# -*- coding: UTF-8 -*- # 排序冒泡法https://www.jianshu.com/p/e8ae3a0bc2e4 def main(): li = [10, 8, 4, 7, 5] for i in range(len(li) - 1): for j in range(len(li) - 1 - i): if li[j] > li[j + 1]: # 多元赋值 li[j], li[j + 1] = li[j + 1], li[j] print(j) ...
# -*- coding: utf-8 -*- from __future__ import absolute_import from django.shortcuts import get_object_or_404, render from django.http import HttpResponsePermanentRedirect, Http404 from products.models import Category, Product from shops.models import Delivery from utils.views import handle404 def read(request, pa...
import torch import torch.nn as nn from torch.nn import LSTM class BaseRNNBlock(nn.Module): ''' O bloco impar passa a RNN ao longo da dimensão do tempo, ou seja, ao longo de R chunks de tamanho K ''' def __init__(self, Parameter=128, hidden_size=128, **kwargs): super(BaseRNNBlock, self)._...
import random # 랜덤으로 정답 생성 answer = random.sample(range(1,10),3) print("정답은=", answer) # 초기화 cnt = 0 guess = [] strikecnt = 0 # 게임진행 while strikecnt <3: strikecnt = 0 ballcnt = 0 guess = [] for i in range(3): num = int(input("{}, 1~9까지 숫자를 입력하세요:".format(i))) guess....
""" CI tests for VMware API utility module """ from oslo.vmware import api from oslo.vmware import vim_util import unittest import json class VimUtilCITest(unittest.TestCase): """Test class for utility methods in vim_util.py""" def setUp(self): """Run before each test method to initialize test environ...
### Script to be executed only in Flask shell to use proper App's ENV variables from app import app, db, s3 from app.models import Paper, Tag, File from werkzeug.utils import secure_filename import re import pandas as pd REPO_FOLDER = '/Users/lakshmanan/Downloads/SEGarage final data' excel_file = '/Users/lakshmanan/...
# -*- coding: utf-8 -*- from odoo import models, fields, api class pos_category(models.Model): _inherit = 'pos.category' background_color = fields.Char('Background Color', default='#FFFFFF',)
#!/usr/bin/env python3 # Fibonacci Series: # Implementation (c) 2016,2017 Brig Young (github.com/Sonophoto) # License: BSD-2c, i.e. Cite. # # Reference for this Series: https://oeis.org/search?q=fibonacci # OEIS: Online Encyclopedia of Integer Sequences # F(n) = (F(n-1) + F(n-2) with F(0) == 0 and F(1) == 1 # F(0) = 0...
# Declarando uma variável our_text = 'Python is the best language' # Apresentando o valor na tela do tamanho do texto na variável print(len(our_text)) # Apresentado na Tela partes do texto da variável print(our_text[0]) print(our_text[3]) print(our_text[-1]) print(our_text[0:3]) print(our_text[0:]) print(our_text[:3]...
import numpy as np def generate_ma_part(length = 100): return np.random.normal(size = (length,1)) class TimeSeries(): def __init__(self, a_coef:np.array, b_coef:np.array, ma_part = None, length = 100): self.ar_coef = a_coef self.ma_coef = b_coef self.length = length self.ma_p...
""" @file results.py handler for saving and loading results. """ import os import json import numpy as np class Results(): """ class for easily saving and loading already calculated clustering results<br> <br> every dataset has a folder containing subfolders for every clustering algorithm contain...
from django.contrib import admin from .models import Book,Writer # Register your models here. admin.site.register(Book) admin.site.register(Writer)
#!/usr/bin/env python # calculate the DOS up to a particular band index, default is the last band calculated in vasp from pv_anal_utils import vasp_anal_read_eigen from argparse import ArgumentParser import sys,math import numpy as np import subprocess as sp def gaussian(x_array,bande,sigma): a = 1.0E0/math...
from requests import get from requests.exceptions import RequestException from contextlib import closing from bs4 import BeautifulSoup import re import urllib from urllib.request import urlopen import http.client import string from ast import literal_eval # pip install BeautifulSoup4 class Scraper: def __init__(self...
import os import re import sys import textwrap import time if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest from . import resource_suite from .. import lib from .. import paths from ..core_file import temporary_core_file from ..configuration import IrodsConfig class Test_Quot...
from django.db import models from users import models as user_model from timezone_field import TimeZoneField import pytz from django.utils import timezone class Clients(models.Model): client_name = models.CharField( max_length=50, blank=True, null=True) client_email_id = models.CharField( max_...
''' implements Caesar substitution cipher Author: James Lyons Created: 2012-04-28 ''' from .base import Cipher class Caesar(Cipher): def __init__(self,key=13): ''' key is an integer 0-25 used to encipher characters ''' self.key = key % 26 def encipher(self,string,keep_pu...
import sys from learning_to_learn import train from learning_to_learn.cdqn import create_agent_cdqn ENV_NAME = 'Adam-Polynomial-Continuous-v0' def main(argv): train.main(argv, "output/polynomial-adam-cdqn/cdqn.h5", ENV_NAME, create_agent_cdqn) if __name__ == '__main...
n = int(input("Podaj ilość liczb: ")) liczby = [] for i in range(1 , n+1, 1): print("[",i,"]:" ,end='') liczby.append(input()) for i in range(0 , n, 1): l = int(liczby[i]) ** 2 print(str(liczby[i]),"^2 =",str(l))
# (C) Datadog, Inc. 2018 # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import os from copy import deepcopy import mock import pytest from .common import FIXTURES_PATH from .utils import mocked_perform_request def test_flatten_json(check): check = check({}) with open(os.pa...
""" demo15_vc.py 视频捕获 """ import cv2 as cv # 获取视频捕获设备 video_capture = cv.VideoCapture(0) while True: frame = video_capture.read()[1] cv.imshow('frame', frame) # 每隔33毫秒自动更新图像 if cv.waitKey(33) == 27: break video_capture.release() cv.destroyAllWindows()