text
stringlengths
38
1.54M
from django.contrib.auth.models import User from django.db import models from django.forms import ModelForm from django.contrib.auth.signals import user_logged_in, user_logged_out class MyCircle(models.Model): userC = models.ForeignKey(User) username = models.CharField(max_length=30) Uname = models.CharFi...
import numpy as np import matplotlib.pyplot as plt def twoPtForwardDiff(x,y): """Function that takes two arrays as inputs and returns the approximate derivative from 2 points, x and x+h. df/dx = lim h->0[f(x+h)-f(x)/h]""" dy = np.diff(y) dx = np.diff(x) dydx = np.zeros(y.shape, float) ...
#!/usr/bin/env python import sys import datetime if len(sys.argv) != 4: print "%s YEAR COPYYEAR NUMDAYS" % sys.argv[0] sys.exit(0) YEAR = int(sys.argv[1]) COPYYEAR = int(sys.argv[2]) DAY_COUNT = int(sys.argv[3]) description = """abcdefghijklmnopqrstuvwqyz.?{}-abcdefghijklmnopqrstuvwqyz.?{}abcdefghijklmnopqrs...
''' Convert prefix to postfix ''' ''' Read exp from right to left push operand to stack if operator is encountered, then pop 2 operands from stack. Concatenate the 2 operands with the operator in between and push it to stack Repeat process until end of expression ''' # IMPORTANT NOTE: # EXPRESSION = OP1...
import logging import os import timeit import unittest import pandas as pd import yaml from mimesis.enums import Gender from mimesis.schema import Field, Schema from odoo.tests.common import TransactionCase from odoo.tools.config import config from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive ...
import numpy as np from dashboard.bokeh.helper import get_palette from bokeh.models import LinearColorMapper, ColorBar from bokeh.models import HoverTool, PrintfTickFormatter, ColumnDataSource from bokeh.plotting import Figure class Patch: def set_amp(self, z_value): ''' Setup for AMP plots ''' ...
import json from copy import copy import numpy as np from batch_generator.utils import get_random_paths from train_utils.utils import read_json class DirIterator: def __init__(self, fnames, reader=read_json, shuffle=True): self.fnames = fnames self.reader = reader self.gen = None ...
# A - 添字 # https://atcoder.jp/contests/abc041/tasks/abc041_a string = input() n = int(input()) print(string[n-1])
from datetime import datetime from django.contrib.auth.models import User from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required from django.template import RequestContext from django.http import HttpResponse from casetracker.models import Filter, Category, Status, Pr...
"""The iotawatt integration.""" from datetime import timedelta import logging from typing import Dict, List from httpx import AsyncClient from iotawattpy.iotawatt import Iotawatt import voluptuous as vol from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from...
class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ pt = 0 size = len(nums) while pt < size - 1: if nums[pt] > nums[pt+1]: nums[pt], nums[pt+1] = nums[pt+1], nums[pt...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import os import re import util import random import embeddings_util import nltk import random import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim torch.manual_seed(1) device = torch.device("cuda" if torc...
class IRespond: pass class Kline(IRespond): def __init__(self,open_time, close_time, open_dt, close_dt, open, close, high, low, vol, instrument): self.open_time = open_time self.close_time = close_time self.open_dt = open_dt self.close_dt = close_dt self.open = ...
#!/usr/bin/env python # # This code was created by Richard Campbell '99 (ported to Python/PyOpenGL by John Ferguson 2000) # # The port was based on the PyOpenGL tutorial module: dots.py # # If you've found this code useful, please let me know (email John Ferguson at hakuin@voicenet.com). # # See original so...
t = input() for ti in range(t): n = input() stocks = map(int, raw_input().split(' ')) transactions = [0 for x in range(n)] stocks.reverse() max_so_far = 0 for i in range(n): if stocks[i] > max_so_far: transactions[i] = 0 #sell max_so_far = stocks[i] else: ...
""" @author Mateus Paiva Matiazzi """ import time class PID: def __init__(self, kp=1.0, ki=0.0, kd=0.0, maxIntegral=1000.0, maxDerivative=1000.0, target=0.0): # Constants self.kp = kp self.ki = ki self.kd = kd # Max integral and derivative value self.maxIntegral...
# -*- coding: UTF-8 -*- from user import User from attack import Attacker from box import Box from equip import Equip from item import Item from shop import Shop from growup import Growup from card import Card from req import KfReq from log import Logging import time import datetime class UserTask(object): run = T...
from django.contrib import admin from .models import Person # Register your models here. class PersonAdmin(admin.ModelAdmin): list_display = ('id', 'first_name', 'last_name', 'email') list_filter = ('is_verify',) admin.site.register(Person, PersonAdmin)
import configparser import time from paho34 import Paho34 import argparse import os import sys parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('--config', type=str, help='set config path') args = parser.parse_args() if not os.path.isfile(args.config): print("config file...
import argparse import gym import numpy as np from gym.envs.registration import register from gym.spaces import Discrete from gym.utils import seeding from tensorboardX import SummaryWriter register( id="FrozenLakeNotSlippery-v0", entry_point="gym.envs.toy_text:FrozenLakeEnv", kwargs={"map_name": "4x4", "...
"""Assorted utility functions and values. safe_plt: A Pyplot that won't attempt to open a display if not available iso639_3: A mapping of Norwegian language names (as used in the data) to ISO639_3 codes. """ import datetime as dt import itertools import os from pathlib import Path import pickle import random impor...
import fresh_tomatoes import media # Creating Different Movie Object and proving the values as per the constructor toy_story = media.Movie("Toy Story", "A Story of a boy and his toy that comes to life", "https://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg", # ...
#Embedded file name: ACEStream\Core\Overlay\OverlayApps.pyo from MetadataHandler import MetadataHandler from threading import Lock from threading import currentThread from time import time from traceback import print_exc import sys from ACEStream.Core.BitTornado.BT1.MessageID import * from ACEStream.Core.BuddyCast.budd...
import os import time import subprocess from mininet.node import Host from mininet_test.pendingresult import PendingResult from mininet_test.runresult import RunResult from mininet_test.errors import RunResultError class TestMonitorHost(Host): def __init__(self, *args, **kwargs): """ Host wrapper to int...
# -*- coding: utf-8 -*- from odoo import api, fields, models, _ from ...wxwork_api.helper.common import * from odoo.exceptions import UserError class Users(models.Model): _inherit = "res.users" _description = "Enterprise WeChat system users" _order = "wxwork_user_order" notification_type = fields.Se...
#!/usr/bin/env python """ 'Triangle'-button on controller to start the mission 'publish setpoints to '/set_point', Twist' """ import rospy import numpy as np from geometry_msgs.msg import Twist from std_msgs.msg import Empty, Bool import time est_relative_position = None # States of the quadcopter S_INIT ...
aa = [] bb = [] value = 0 for i in range(0,100): aa.append(value) value += 2 for i in range(0, 100): bb.append(aa[99 - i]) print(f"bb[0]에는 {bb[0]}이, bb[99]에는 {bb[99]}값이 입력됩니다.")
from django_tablib import Field, ModelDataset from api.export import PublicMetricDatasetMixin from ..export import MetricDatasetMixin from .models import YumYuck class YumYuckDatasetMixin(object): recorded = Field(header='recorded') crop = Field(header='crop') yum_before = Field(header='yum before') ...
# This method takes in a string name and returns a string # saying goodbye to that name ##### SOLUTION 1 # def goodbye(name): # # using concatenation # # return ("Goodbye " + name) # # using arguments by position # # return ('Goodbye {personName}'.format(personName=name)) # # using F-Strings ...
from csv import reader counter_t = 0 counter_f = 0 with open(f'media/results/result_HFK_Export_Prosperus_V1_KWVLybf.csv', 'r') as read_obj: csv_reader = reader(read_obj) for line in read_obj.readlines(): array = line.split(',') item = array[2] if item == 'True': counter_t +...
#! /usr/bin/python import sys import signal import commands import os import time import string import logging import traceback from Exceptions import * import Test_utils def main(): fails=0 utils = Test_utils.Test_utils(sys.argv[0],"test glite-wms-job-submit commmad") utils.prepare(sys.argv[1:]) ...
# Generated by Django 2.1.7 on 2019-03-20 06:51 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('homedetail', '0011_auto_20190316_2138'), ('payment', '0003_auto_20190319_2151'), ] operations = [ m...
# Generated by Django 3.0.7 on 2020-06-24 19:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('articles', '0008_auto_20200624_2251'), ] operations = [ migrations.AlterField( model_name='article', name='field_nam...
import threading import time import ex import servo import Motor_contorol global command import Camera def e(): while True: ex.main() def s(): servo.main() def mc(): Motor_contorol def c(): Camera.get_image() def command(co): while True: co[0]=input() if __name__=="__main__...
#!/usr/bin/env python # Copyright 2021 University of Chicago # # 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 applicab...
r"""http://codeforces.com/contest/474/problem/A """ import fileinput inp = fileinput.input() kb = r'''qwertyuiopasdfghjkl;zxcvbnm,./''' def solve(): direction = {'R': -1, 'L': 1}[next(inp).strip()] keys = next(inp).strip() sol = ''.join([kb[kb.find(k) + direction] for k in keys]) print(sol) if __n...
import os import csv import random import re f_train = open("train_ori.csv", "r", encoding='utf-8') freader = csv.reader(f_train, dialect='excel') train_header = next(freader) out_data = [] for i, rowlist in enumerate(freader): out_data.append([re.sub(r"[^a-zA-Z0-9?.!,']+", " ", rowlist[-2]).lower(), rowlist[-1]...
#!/usr/bin/python3 """ Michael duPont - sumvals.py Example file using the begin(s) library Usage: python3 sumvals.py [-h] [other args...] Demo example: invoke makerand | cut -f1 -d- | xargs python3 sumvals.py """ #library import begin @begin.start #Parameter descriptions read from annotations #begin.start can only...
# open("file pass", opening mode like "r", buffering, encoding, errors) # Режимы отркывания: # "r" = открыть только для чтения # "w" = открыть для записи, если файл не существует то он его создаст, все что было в файле удалится # "x" = создание эксклюзивного файла, если файл существует то выдасться ошибка # "a...
#programmer : Prasath Ram R new_cipher = input() replacement = "PER" replacementIndex = 0 count = 0 for index in range(len(new_cipher)): if(cipher[index] != replacement[replacementIndex]): count+=1 replacementIndex = (replacementIndex + 1) % 3 print(count)
# Generated by Django 3.1.7 on 2021-06-22 10:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('hospital_app', '0004_auto_20210617_1613'), ] operations = [ migrations.CreateModel( name='User', fields=[ ...
import pygame pygame.init() # 초기화 # 화면크기 설정 screen_width = 480 # 가로 screen_hight = 640 # 세로 screen = pygame.display.set_mode((screen_width, screen_hight)) # 화면 타이틀 pygame.display.set_caption("GS game") # 이벤트 루프 running = True while running: for event in pygame.event.get(): # 어떤 이벤트가 발생하는가? if event.typ...
#!/usr/bin/python # coding: utf8 import os import json import datetime import time import smtplib import subprocess from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import Encoders from openpyxl import Workbook from openpyxl.styles imp...
#!/usr/bin/python3 #tests camera input for the presence of a QR code #3 QR codes need to be present in the image #if the final stitched to the concatenated QR-codes #an output is updated to be displayed #works with FlaskScope from PIL import Image from time import sleep from pyzbar.pyzbar import decode #import picame...
from django.core.exceptions import ObjectDoesNotExist from django.core.serializers import json from django.shortcuts import render,render_to_response from django.http import HttpResponse from account.forms import RegisterForm,LoginForm from account.models import Users def getid(request): name="" try: ...
lines = open('resume.tex').read().splitlines() result = [] should_keep = False for line in lines: if line.find('{document}') > -1: should_keep = not should_keep continue if should_keep: result.append(line) open('resume.tex', 'w').write(("\n".join(result))) # pandoc resume.md -o resume.tex --template=foo.tex...
#!/usr/bin/env python # encoding: utf-8 class postag(object): # ref: http://universaldependencies.org/u/pos/index.html # Open class words ADJ = "ADJ" ADV = "ADV" INTJ = "INTJ" NOUN = "NOUN" PROPN = "PROPN" VERB = "VERB" # Closed class words ADP = "ADP" AUX ="AUX" CCON...
# import context import unittest import numpy as np from minesweeper.internal.ms_board import ms_board # TODO in wherever the gameplay section is, make sure 0 mines ends in one click # and width * height mines ends in 0 clicks (without making the board visible?) def count_mines(ms_board): return np.count_nonzero...
import sys import os import json #path = "/Users/micha/Google Drive/WORKSPACE/travaille/side projects/Python/2013_UWash_IntroDataScience/datasci_course_materials/assignment1" #os.chdir(path) def createSentimentDict(afinnfile): scores = {} # initialize an empty dictionary for line in afinnfile: ...
'''1º Contar el número de productos que hay en la home.''' import unittest from selenium import webdriver from selenium.webdriver.chrome.options import Options class CountElementsHome(unittest.TestCase): def setUp(self) -> None: options = Options() options.add_argument('--headless') optio...
import powers # write a recursive function that takes as input a nested list of strings, and returns #a single string with each word separated by a space. ## ##def nested_build(nested_list:[str or [str]]) ->str: ## ## ## unpacked = '' ## for element in nested_list: ## if type(element) == str: ## ...
from __future__ import unicode_literals from django.db import models import json from wagtail.wagtailcore.models import Page from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel, MultiFieldPanel from wagtail.wagtailimages.edit_handlers import ImageChooserPane...
import os import multiprocessing as mp def multicore(func, args, num_cores = os.cpu_count()): """ This function triggers a parallel processing of specified functions on each element of the args. Params: func -- (function) args -- (list) arguments for specified functions num_cores ...
import sys input = sys.stdin.readline total_invitees = int(input()) n = int(input()) list_multiples = [] for j in range(n): multiple = int(input()) list_multiples.append(multiple) list_invitees = [] for integer in range(1, total_invitees + 1): list_invitees.append(integer) for r in range(n): current_m...
import unittest import cnn_framework from .predictor import Predictor from .input import * from .layers import MoleculeConv from keras.layers.core import Dense class Test_Input(unittest.TestCase): def test_read_input_file(self): predictor_test = Predictor() path = os.path.join(os.path.dirname(cnn_framework.__...
#. try & except x=3 y='bob' try: print(x+y) except: print('dont add string with numbers') # quit() #. right dangerous code in try indent. it would be safe factor #. too much code in try could make you hard to find where the traceback happened #. we can use quit() in except indent to not make more traceback...
import time from selenium import webdriver # 创建浏览器驱动对象 from selenium.webdriver.common.by import By driver = webdriver.Chrome() # 窗口最大化 driver.maximize_window() # 打开测试网站 driver.get("file:///D:/software/UI%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95%E5%B7%A5%E5%85%B7/web%E8%87%AA%E5%8A%A8%E5%8C%96%E5%B7%A5%E5%85%B7%E9...
# Data 생성 from scipy.stats import norm x = [norm.rvs() * 5 + 170. for _ in range(10)] x_1 = x x_2 = x # 정렬 함수 def sort_function (X) : # 주어진 데이터의 길이를 구한다. N = len(X) # 0부터 주어진 길이-1 까지 반복한다. for i in range(N-1): # 스위칭을 하기 위해 임시로 k라는 변수를 만든다. k = i # 위에 반복문에 해당하는 기준 숫자와 그 뒷숫자와 1대1로...
release_major = 1 release_minor = 11 release_patch = 33 release_so_abi_rev = release_patch # These are set by the distribution script release_vc_rev = None release_datestamp = 0 release_type = 'unreleased'
"""Python Cookbook 2nd ed. Tests for ch12_r06_server """ import base64 import json from unittest.mock import Mock import Chapter_12.ch12_r06_server import Chapter_12.ch12_r06_user from pytest import * # type: ignore @fixture # type: ignore def fixed_salt(monkeypatch): mocked_os = Mock(urandom=Mock(return_value...
#!/usr/bin/python # # Copyright (C) 2007 Saket Sathe # # 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 applic...
from .helpers import is_valid_email def email(email_str): """Return email_str if valid, raise an exception in other case.""" if is_valid_email(email_str): return email_str else: raise ValueError('{} is not a valid email'.format(email_str))
""" Script reads LENS data for selected variables Notes ----- Author : Zachary Labe Date : 28 November 2016 Usage ----- lats,lons,var = readLENS(directory,varq) """ def readLENSEnsemble(directory,varq): """ Function reads LENS ensembles netCDF4 data array Parameters ----------...
import jprops def Property(key_file,properties_file): if not properties_file.startswith("/"): properties_file = "/var/www/goblin/current/etc/" + properties_file with open(properties_file) as fp: properties = jprops.load_properties(fp) return properties
"""This module contains update handlers""" import logging from abc import ABC, abstractmethod from typing import Callable, Optional, Type from celery import group from shaman.forms import Form from shaman.models import Update log = logging.getLogger(__name__) class Handler(ABC): """The base class for all upda...
import numpy as np from scipy import sparse from scipy.sparse import linalg as splinalg import sklearn.linear_model as sklin import sklearn.decomposition def learn(X_train, y_train, mode='lsmr', reduction=None, n_components=10, alphas=[0.1, 1., 10.], normalize=False): def ridge(): model = sklin.Ridge(norm...
from typing import List class Solution: def maxProfit(self, prices: List[int]) -> int: if not prices: return 0 firstProfit = [0 for _ in range(len(prices))] cost = prices[0] for i in range(1, len(prices)): firstProfit[i] = max(firstProfit[i - 1], prices[i] -...
import numpy as np import refltool as rt from os import chdir from pylab import * ############ ##import current data #this one is half-sapph-no-ito chdir("../data/expt2") data_new=rt.reflm_std("mirror_VNATrc.001","mirror_VNATrc.002","half-sapph-no-ito_VNATrc.001","half-sapph-no-ito_VNATrc.002") ########### ##impor...
from behave import * from behave.model import Table, Row import copy from test_project.test_utils.dbt_test_utils import DBTVAULTGenerator use_step_matcher("parse") dbtvault_generator = DBTVAULTGenerator() def set_stage_metadata(context, model_name) -> dict: """ Setup the context to include required sta...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2019-02-28 15:47:20 # @Author : cdl (1217096231@qq.com) # @Link : https://github.com/cdlwhm1217096231/python3_spider # @Version : $Id$ import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.autograd import...
# coding=utf-8 from flask import request, render_template, jsonify, make_response, url_for from peewee import create_model_tables import simplejson as json from werkzeug.exceptions import abort from app import app from models import User, WXUser, Group, Product, Purchase, WxJsapiTicket from auth import auth from admin...
from code.data_structures.linkedlist.singly_linkedlist import LinkedList ''' Time efficiency: O(1) ''' def deleteMiddleNode(linkedlist, node): linkedlist.deleteMiddleNode(node) return linkedlist
#-*-coding:utf-8-*- print "pyhon中返回函数的说明" print "高阶函数不仅可以把函数作为参数,也可以把函数作为返回值" ''' 普通的求和函数 ''' def calc_sum(*args): ax = 0 for n in args: ax += n return ax """ 但是当我们不想要立即求和,而是在后面的代码中,根据 需要再计算怎么办?不返回求和的结果,只是返回求和的函数 """ def lazy_sum(*args): def sum(): ax = 0 for n in args: ax = ax + n return ax return ...
"""empty message Revision ID: b83831b4b242 Revises: 21166afba474 Create Date: 2016-03-14 00:49:43.914692 """ # revision identifiers, used by Alembic. revision = 'b83831b4b242' down_revision = '21166afba474' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql def upgrade(): ### ...
"""Human readable quantities of some units. This modules provides subclasses of :class:`int` or :class:`float` to denote particular quantities such as time intervalls or amounts of memory. The classes provide string representations in a more human readable form and constructors that accept these string representation...
""" An operator is a callable object representing an operation that when applied to a puzzle state, produces a generator of possible next states. This file defines the abstract base class for operators and the operators used in the peg puzzle """ from typing import Generator, Tuple, Callable from state import PuzzleSta...
from __future__ import unicode_literals from django.contrib import admin from models import * admin.site.register(Group) admin.site.register(Card)
import os def main(): n = int(input()) nums = list( map( int, input().split() ) ) nums.sort() #print( nums ) # Get median element if len( nums ) % 2 == 0: median = ( nums[ int(len(nums) / 2) ] + nums[ int(len(nums) / 2) - 1 ] ) / 2 else: median = nums[ int(len(nums) / 2) ]...
from functools import wraps import contextlib import shutil import tempfile from nose import SkipTest def build_po_string(data): return ( '#, fuzzy\n' 'msgid ""\n' 'msgstr ""\n' '"Project-Id-Version: foo\\n"\n' '"POT-Creation-Date: 2013-06-05 14:16-0700\\n"\n' '"PO...
from django.db import models from apps.registro.models.Region import Region from apps.seguridad.models import Ambito class Jurisdiccion(models.Model): prefijo = models.CharField(null = True, max_length = 3) region = models.ForeignKey(Region) nombre = models.CharField(max_length = 50) ambito = models.F...
chassis_511 = '192.168.65.24' server_511 = 'localhost:8888' server_properties = {'windows_511': {'server': server_511, 'locations': [f'{chassis_511}/1/1', f'{chassis_511}/1/2'], 'install_dir': 'C:/Program Files/Spirent Communications/Spirent Te...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @CreateTime: 2018-10-10T18:36:20+09:00 @Email: guozhilingty@gmail.com @Copyright: Shiba-lab @License: MIT """ import numpy as np import torch import torch.nn as nn class VDSR(nn.Module): """ Superresolution using Very Deep Convolutional Networks The net...
print('学习:Python-dict') #定义字典列表 d = {'Bob':95,'Lisa':96,'Luncode':100} #修改key的值 d['Bob'] = 99 #检查key是否在列表中 print('Lisa' in d) #输出对应key的value print(d['Bob']) #删除列表中的key和value d.pop('Lisa') #输出列表 print(d) #小结 d = {'Michael': 95,'Bob': 75,'Tracy': 85} print('d[\'Michael\'] =', d['Michael']) print('d[\'Bob\'] =', d['Bob'...
import json from terminaltables import SingleTable import os import io sensors_dictionary = {} def parse_json(received_bytes): # Convert received bytes to a string json_string = received_bytes.decode("utf-8") # Use json library to convert the json string into a python dictionary sensor_dictionary = ...
# Napisz algorytm, który na wejście przyjmie listę zawierającą tylko stringi i integery. # Zwróci listą zawierającą tylko powtarzające się wartości, nie zmieniając ich kolejności. # Przykład: [1, 2, 3, 1, 3] 1 i 3 nie są unikalne, więc wynikiem będzie [1, 3, 1, 3]. def notunique(my_list): unique_list = [] non...
secrets = { 'ssid' : '[Wifi SSID]', 'password' : '[Wifi Password]', 'public_key' : '[Bayou Public Key]', 'private_key' : '[Bayou Private Key', 'base_url': 'http://192.168.1.163:5000/data/' }
''' Created on 6 Jul 2015 @author: leo ''' from fractions import Fraction class F(Fraction): ''' Classe que representa um numero fracionario, extendendo fractions.Fraction ''' def __init__(self,n,m=Fraction(0)): self.fraction = Fraction(n) self.m = Fraction(m) d...
import os import numpy as numpy import pandas as pd from StringIO import StringIO class DataHandler: def __init__(self): print "starting to load data" data = pd.read_csv(os.path.realpath('Data/train.csv'), delimiter=",").values self.trainLabels=data[:,0] self.trainFeatures=data[:,1:...
import exlotto def output(m, n): nums = exlotto.lotto(m, n) snums = sorted(nums) return snums #跑一萬次出現最多的數字六個 if __name__ == '__main__': import operator lilotto = list() dictlotto = {} for i in range(10000): #將新的list加入 lilotto.extend(output(48,6)) #統計每個數字出現的次數 ...
list = [] def add_item(name): list.append(name) def remove_item(name): list.remove(name) def print_list(): print(list) def print_inst(): print("1. print Instruction\n2. Add Item\n3. Remove Item\n4.Quit\n5.Print List") print("1. print Instruction\n2. Add Item\n3. Remove Item\n4.Quit\n5.Print List") ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import unittest class TestB(unittest.TestCase): def setUp(self): print('test TestB start') def test_1(self): print('test TestB test_1') def test_cc(self): print('test TestB test_cc') def test_aa(self): print('test TestB ...
import os bash_scrapy = 'scrapy crawl jobs -o test.json' def main(): os.system(bash_scrapy) if __name__ == '__main__': main()
# 클래스 기반 메소드 심화 class Car: """ Car class Author: jinsuSang Date: 2021.07.17 """ # 클래스 변수 # del 사용시 클래스 변수에 접근하는 것은 좋지 못하다고 생각함 # 클래스 변수는 read only 형식을 사용하는 것을 개인적으로 추천 __price_per_raise = 1.0 def __init__(self, company, details): self.__company = company self._...
# -*- coding: utf-8 -*- """ Create Second Defect on DAGM Images @author: josemiguelarrieta """ #Load libraries import os import cv2 os.chdir('Documents/SIVA') from utils_dagm import load_image_dagm, load_labels_dagm,write_labels_defectA,rectangle_expanded_roi from utils_dagm import write_labels_expROI, defect_B_rect_...
import numpy as np import matplotlib.pyplot as plt import networkx as nx if __name__ == '__main__': from vnf_metrics import VNFMetrics else: from nfvmaddpg.model.gan.utils.vnf_metrics import VNFMetrics def topos2grid_image(topos, vnf_decoder): # topos = [e if e is not None else Chem.RWMol() for e in topo...
import pandas as pd import time import calendar from datetime import datetime, timedelta # Filenames (Files are in same folder as the python script) chicago = 'chicago.csv' new_york_city = 'new_york_city.csv' washington = 'washington.csv' def get_city(): '''Asks the user for a city and returns the filename for t...
# 平均拆單 N張 拆M次 import sys def order_split(number, count, max_split): """ input: number 量 input: count 次 output: array """ print(f"input: number:{number} count: {count}") ret = [] # sum = 0 # 前序 sum = count / 2 # 中序 # sum = count - 1 # 後序 nn = 0 ...
# Generated by Django 2.0.6 on 2019-12-10 14:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('web', '0001_initial'), ] operations = [ migrations.AlterField( model_name='account', name='is_staff', fi...
import json import pymysql import redis import schedule from pymongo import MongoClient from utils.wirte_logs import Logger from config import environments r_2 = redis.StrictRedis(host='192.168.1.180', port=30378) env_dict = environments.get('dev') client = MongoClient(env_dict.get('mongodb_host'), env_dict.get('mongod...
def plot_var_contours_with_distance(df, mask, var, dist=100, bins=5, wd=12, ht=5, varmin=33, varmax=35, nlevs=10, colorunit=' ', save=False, savename="Untitled.png", zbin=10, xbin=10, zmin=0, nmin=0): zlowest = df.loc[mask, 'DEPTH'].min() ...