text
stringlengths
38
1.54M
import csv import time from googleapiclient.discovery import build from setup import Setup from data import Data class Update: """ Update the existing spreadsheets with the latest grade reports. """ def __init__(self, d): self.credentials = d.credentials self.date = d.date sel...
#! /usr/bin/env python import time import rospy from std_msgs.msg import * from geometry_msgs.msg import * from mavros_msgs.msg import * from mavros_msgs.srv import * from geographic_msgs.msg import * from trajectory_msgs.msg import * from nav_msgs.msg import Odometry import math trans = Transform() cmd_vel = Twist() ...
# uncompyle6 version 3.2.3 # Python bytecode 3.6 (3379) # Decompiled from: Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] # Embedded file name: C:\Users\ZHANGDorisXStudent\Desktop\LightBlue_NLTK\src\ChatBotDesign\chatbot.py # Compiled at: 2018-10-09 06:51:54 from memory import Memory f...
import pandas as pd import numpy as np def load_landsat_data(filename): ''' Utility function to load Landsat dataset. https://github.com/abarthakur/trepan_python/blob/master/run.py Landsat dataset : https://archive.ics.uci.edu/ml/datasets/Statlog+(Landsat+Satellite) num_classes= 7, but 6th is empty. ...
import collections import os import pickle import shutil import numpy from pwdmodels.semantic_word2vec_optimal import SemanticModel, Struct def combine_semantic_to_word2vec(semantic_model_dir, word2vec_model_dir, combine_model_dir): word2vec_cluster = {} shutil.copy(os.path.join(word2vec_model_dir, "seg.txt...
#-*- coding: utf-8 -*- def printn(n): if n<0: return num=[0]*n for i in range(10): num[0]=str(i) printrec(num) def printrec(num,idx=0): if idx==len(num)-1: print(''.join(num)) return for i in range(10): num[idx+1]=str(i) printrec(num,idx+1) ...
from flask import Flask from flask_sqlalchemy import SQLAlchemy from config import config from flask_bootstrap import Bootstrap from flask_moment import Moment from flask_login import LoginManager, current_user import flask_whooshalchemyplus login_manager = LoginManager() login_manager.login_view = 'auth.login' login_...
from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.contrib.messages.views import SuccessMessageMixin from django.contrib import message...
import collections, gzip, time import numpy as np import tensorflow as tf import utils import sys OPTIMIZERS = ['sgd', 'adam', 'sgd_momentum'] class MediumConfig(object): """Medium config.""" init_scale = 0.05 learning_rate = 0.25 max_grad_norm = 20 num_layers = 3 num_steps = 50 hidden_size = 1500 ma...
#!/usr/bin/env python import sys, os, random file_dir="video_list" random.seed(0) with open(file_dir + "/video_esea_2019-0409.txt") as f: for line in f: line = line.strip() if line: print(line + "#video_downsample/esea/") MAX_ALL_QTY=5000 arr = [] with open(file_dir + "/video_all_2019-0409.txt") as...
from flask import Flask, request from processing import calculate app = Flask(__name__) app.config["DEBUG"] = True @app.route("/", methods=["GET", "POST"]) def adder_page(): errors = "" if request.method == "POST": number1 = None number2 = None number3 = None number4 = None ...
import libreria def pedir_habitacion(): libreria.pedir_nombre("ingrese matrimonial") print("se agrega matrimonial") def pedir_suite(): print("se agrega suite") def pedir_doble(): print("se agrega doble") def pedir_presidencial(): print("se agrega presidencial") def pedir_extra(): li...
import pytest from django.urls import NoReverseMatch from django.urls.base import reverse from model_bakery import baker from bpp.models import Autor, Jednostka, Praca_Doktorska, Praca_Habilitacyjna, Zrodlo from bpp.models.cache import Autorzy, Rekord from bpp.models.patent import Patent, Patent_Autor from bpp.models....
# 50명 승객과 매칭 기회, 총 탑승 승객 수를 구하는 프로그램 작성 # 조건1 : 승객별 운행 소요 시간 5~50 사이의 난수 # 조건2 : 소요시간 5~15분 사이의 승객만 매칭 # #출력문 예제 # [0] 1번째 손님 (소요시간 : 15분) # [ ] 2번째 손님 (소요시간 : 50분) # [0] 3번째 손님 (소요시간 : 5분) # ... # [ ] 50번재 손님 (소요시간 : 16분) # #총 탑승 승객 : 2분 from random import * cnt = 0 # 총 탑승 승객수 for i in range(1, 51): #1~50이라는 수 (승객)...
password = "pass" password_input = input("Introduzca su contraseña: ") if password_input.lower() == password.lower(): print(":)") else: print(":(")
class Solution(object): def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ rowset=[] colset=[] gridset=[] digit=set() for i in range(9): rowset.append(set()) colset.append(set()) ...
import torch import torch.nn as nn from torch.autograd.function import Function from torch.utils.checkpoint import get_device_states, set_device_states # helpers def map_values(fn, x): out = {} for (k, v) in x.items(): out[k] = fn(v) return out def dict_chunk(x, chunks, dim): out1 = {} ou...
#!/bin/python3 import math import os import random import re import sys # Complete the countSort function below. def countSort(arr): arrlen=len(arr) firsthalf=int(arrlen/2) countingArray=list() j=0 for i in range(0,100): countingArray.append(list()) for i in arr: index=int(i[0]...
#Codechef #https://www.codechef.com/ICL2019/problems/ICL1901 t=int(input()) while t>0: k,n=list(map(int,input().split())) k=str(k) k=set(k) if len(k)==3: print(27) elif len(k)==2: print(8) else: print(1) t-=1
import requests import simplejson class TagMe: """ A Python wrapper for the TagMe REST API, which provides a text annotation service: https://tagme.d4science.org/tagme/ It is able to identify on-the-fly meaningful short-phrases (called "spots") in an unstructured text and link them to a pertinent ...
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # 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://w...
# Generated by Django 2.2.3 on 2021-10-20 12:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('superSu', '0010_auto_20211020_0743'), ] operations = [ migrations.AddField( model_name='prueba', name='apellido', ...
#!/usr/bin/env python import argparse import sys def _lines(stream): l = stream.readline() while l != "": yield l l = stream.readline() def main(argv): parser = argparse.ArgumentParser( description=("Add a value in every line so that you add a column in " "t...
import os.path import json import jsonpickle data_path = "data/roomdata.json" class Data(object): def __init__(self): self.main_channel_id = -1 self.inventory = [] self.state = 0 self.map_msg_id = -1 self.progress_msg_id = {} self.cooldown = {} self.light_l...
# -*- coding: utf-8 -*- """ Tests for all number generators """ from fauxfactory import FauxFactory import sys import unittest class TestNumbers(unittest.TestCase): """ Test number generators """ @classmethod def setUpClass(cls): """ Instantiate our factory object """ ...
#!/usr/bin/env python # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0. import codecs import re import os from setuptools import setup, find_packages VERSION_RE = re.compile(r""".*__version__ = ["'](.*?)['"]""", re.S) PROJECT_DIR = os.path.dirname(os.path.rea...
from collections import Counter class Solution: def longestPalindrome(self, s: str) -> int: odd = sum(val & 1 for key, val in Counter(s).items()) return len(s) - odd + 1 if odd > 1 else len(s) def longestPalindrome(self, s): odds = sum(v & 1 for v in collections.Counter(s).values()) ...
from __future__ import unicode_literals from django.db import models from django.contrib import messages from django.contrib.messages import get_messages import re EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-copyZ0-9._-]+\.[a-zA-Z]+$') class UserManager(models.Manager): def login(self,request): if...
import argparse import hashlib import inspect import os import time from typing import Callable, List import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import h5py from matplotlib.backends.backend_pdf import PdfPages import crack_detection as crack_detection import crack_metrics as crack_met...
import argparse parser = argparse.ArgumentParser() parser.add_argument("--job_name", help="target job name") # noqa: E501 parser.add_argument( "--job_list", help="list of existing jobs from databricks cli" ) # noqa: E501 args = parser.parse_args() job_name = args.job_name.lower() jobs = args.job_list.splitline...
import numpy as np from three_wolves.deep_whole_body_controller.utility import trajectory, reward_utils, pc_reward CUBE_MASS = 0.094 CUBE_INERTIA = np.array([[0.00006619, 0, 0], [0, 0.00006619, 0], [0, 0, 0.00006619]]) class PositionController: def __init__(self...
from utils import load_pickle import glob import numpy as np from sklearn.utils import shuffle from preprocess import W2VTransformer from utils import pad_with_vectors from keras.utils.np_utils import to_categorical from preprocess import get_int_representation_from_vocab from utils import get_imdb_vocab def load_imdb...
"""The "Ikeda map" is a discrete-time dynamical system of size 2. Source: [Wiki](https://en.wikipedia.org/wiki/Ikeda_map) and Colin Grudzien. See `demo` for more info. """ import numpy as np from numpy import cos, sin import dapper.mods as modelling import dapper.tools.liveplotting as LP # Constant 0.6 <= u <= 1....
# Generated by Django 3.1.7 on 2021-04-20 00:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Job', '0016_auto_20210420_0845'), ] operations = [ migrations.AddField( model_name='resume', name='practice', ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-11-05 19:26 from __future__ import unicode_literals from django.db import migrations, models import documents.models class Migration(migrations.Migration): dependencies = [ ('documents', '0012_auto_20160212_2053'), ] operations = [ ...
import numpy as np import matplotlib.pyplot as plt for person in [30, 60]: for sav_name in ['3layerAE', '3layerVAE']: orig_ts = np.load(f'encoder_comparisons/{sav_name}_1_0_{person}_orig.npy') recons_ts = np.load(f'encoder_comparisons/{sav_name}_1_0_{person}_recons.npy') for i in range(50):...
#!/bin/env python # coding: utf-8 """ asyncio support sqlite """ import os import re import sys from setuptools import setup, find_packages PY_VER = sys.version_info INSTALL_REQUIRES = [] if PY_VER >= (3, 4): pass elif PY_VER >= (3, 3): INSTALL_REQUIRES.append('asyncio') else: raise RuntimeError("aiomy...
import re from django import template from django.template import Context, Template from django.core.urlresolvers import resolve, Resolver404 from datetime import datetime from datetime import datetime_delta register = template.Library() @register.simple_tag def expires_in(item): # a datetime object is constructe...
def workbook(n, k, arr): # n - num of chapters(len(arr)) # k - max-prob on page can contain pageNo = 1 speProbs = 0 for idx in range(n): if k >= arr[idx]: if pageNo in range(arr[idx] + 1): speProbs += 1 pageNo += 1 else: ...
# Generated by Django 3.0.8 on 2020-08-27 07:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('frontend', '0007_auto_20200711_1042'), ] operations = [ migrations.CreateModel( name='Team', fields=[ ...
import sys import logging from .sentry import get_client as get_sentry_client from .job_status import set_status from .misc import get_http_log_path from .config import config as teuth_config from .exceptions import ConnectionLostError from copy import deepcopy log = logging.getLogger(__name__) def import_task(name)...
# Generated by Django 3.2.8 on 2021-10-12 04:58 import datetime from decimal import Decimal from django.conf import settings import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ...
import pulp from LineupGenerator import LineupGenerator class Nhl(LineupGenerator): def __init__(self, sport, num_lineups, overlap, player_limit, teams_limit, stack, solver, correlation_file, players_file, defenses_goalies_file, output_file): super().__init__(sport, num_lineups, overlap, player_limit, teams_limit, ...
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return '<h3> Go to /[number] to see the number squared</h3>' @app.route('/<int:number>') def squared(number): return '<h1>' + str(number*number) + '</h1>' if __name__ == "__main__": app.run(host='0.0.0.0', debug=True)
from sklearn.base import BaseEstimator import config class DistanceModel(BaseEstimator): """ This models predicts always the class from which the anchor point is the closest to the cursor. """ def __init__(self): pass def predict(self, X): y_pred = [] for x in X: x_ = list(x[:7]) min_val = min(x_) ...
start = int(input("Enter lower bound = ")) end = int(input("Enter upper bound = ")) for val in range(start,end+1): if str(val) == str(val)[::-1]: print(val,end=" ") print()
#!/usr/bin/env python3 """ 2D Controller Class to be used for the CARLA waypoint follower demo. """ import cutils import numpy as np from matplotlib import pyplot as plt from NavigationLibrary.controllers.LongitudinalPID import LongitudinalPID class Controller2D(object): def __init__(self, waypoint...
import FWCore.ParameterSet.Config as cms process = cms.Process("runRivetAnalysis") process.options = cms.untracked.PSet( allowUnscheduled = cms.untracked.bool(False) ) process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(10) ) process.source = cms.Source("PoolSource", ...
import json from autoprotocol.protocol import Protocol from autoprotocol.container import WellGroup from autoprotocol_utilities.resource_helpers import ref_kit_container p = Protocol() #wells 1-4: pglo + bacteria + ara + lb amp #well 5-8: same but no ara (control) #well 9-12: no bactera, no ara (control) num_picks =...
# 生成两端点所连直线上的点的坐标 from skimage.draw import line import numpy as np img = np.zeros((10, 10), dtype=np.uint8) rr, cc = line(1, 1, 8, 8) img[rr, cc] = 1 print(img)
from __future__ import annotations from typing import TYPE_CHECKING from flowchem.devices.flowchem_device import FlowchemDevice from ...components.technical.power import PowerSwitch if TYPE_CHECKING: from .bubble_sensor import PhidgetBubbleSensor, PhidgetPowerSource5V from flowchem.components.sensors.base_senso...
import ConfigParser, os, inspect class Config: def __init__(self, section="main"): self.section = section self.parser = ConfigParser.ConfigParser() base_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) local_config_path = os.path.join(base_path,'mount.cfg') for config_path i...
import cv2 from classes.PlateFinder import PlateFinder from classes.NeuralNetwork import NeuralNetwork if __name__ == '__main__': findPlate = PlateFinder() # Initialize the Neural Network model = NeuralNetwork() cap = cv2.VideoCapture('test/video.MOV') # while cap.isOpened(): # ret, img ...
clk_src.count = 29 sbclk_src.count = 27 clk_div.count = 0 clk_dfs_mode.count = 1 clk_dll_mode.count = 0 clk_mul.count = 7 clk_shift_stepsize = 8.594e-12 clock_period_external = 2.841441861258077e-09 clock_period_internal = 2.857142857142857e-09 p0_div_1kHz.count = 275 clk_88Hz_div_1kHz.count = 89100 hlc_div = 12 nsl_di...
# pylint # {{{ # vim: tw=100 foldmethod=indent # pylint: disable=bad-continuation, invalid-name, superfluous-parens # pylint: disable=bad-whitespace, mixed-indentation # pylint: disable=redefined-outer-name # pylint: disable=missing-docstring, trailing-whitespace, trailing-newlines, too-few-public-methods # pylint: dis...
import random import sys import time from cache import * from cpath import data_path from data_generator import tokenizer_wo_tf as tokenization from misc_lib import TimeEstimator from job_manager.marked_task_manager import MarkedTaskManager from tlm.wiki import bert_training_data as btd working_path ="/mnt/nfs/work3/...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('students', '0003_auto_20150324_2059'), ] operations = [ migrations.CreateModel( name='Exam', fields=...
import time from twilio.rest import Client from random import * def sleep(): time.sleep(randint(3, 6)) def text_me(message): twilio_number = '+19562720613' jamie_number = '+19568214550' valeria_number = '+19564370322' #phone_number = '+1%s' % input('What is your phone number?') client.messag...
from common.until import printf, logging_except, logging_sql from db.DB_Redis import RedisClient from project.Jijinwang import Spider_basic_list as MS, Spider_List class Schedule(object): def __init__(self): self.main = self.main_spider self.spider_list = Spider_List def main_spider(self): ...
# # Copyright (c) 2017-2023 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # import abc import keyring import six from sqlalchemy.orm.exc import NoResultFound from sysinv.common import constants from sysinv.common import utils from sysinv.common import exception from sysinv.helm import common as hel...
from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import smtplib import pandas as pd import argparse def mail_to_list(email_list, info_list, gmail, password, subject, test_only=False): """Send an email to everyone in the provided csv.""" server = smtplib.SMTP('smtp.gmail.com...
test_data=""" insert into graphs values (1, 1, 0); insert into nodes values (1, 1, "A"); insert into nodes values (1, 2, "B"); insert into nodes values (1, 3, "C"); insert into nodes values (1, -3, "D"); insert into edges values (1, 2, NULL); insert into edges values (1, 3, NULL); insert into edges values (3, -3, NULL)...
import unittest import pytest import json from app.api.v1 import views from app.api.app import create_app class BaseTest(unittest.TestCase): def setUp(self): self.app = create_app(config_name="testing") self.client = self.app.test_client self.client1 = self.app.test_client() ...
from statistics import mean from math import sin, cos, atan, pi def add_tuple(t1, t2): a = t1[0] + t2[0] b = t1[1] + t2[1] return (a, b) def sub_tuple(t1, t2): a = t1[0] - t2[0] b = t1[1] - t2[1] return (a, b) def taxi_distance(coord1, coord2): return (abs(coord1[0] - coord2[0]) + abs(...
import math import backtrader as bt class GoldenCrossStrategy(bt.Strategy): params = (('fast', 7), ('slow', 21), ('order_percentage', 0.80), ('ticker', 'AAPL')) def log(self, txt, dt=None): dt = dt or self.datas[0].datetime.date(0) print('%s, %s' % (dt.isoformat(), txt)) def __init__(s...
from typing import List, Optional from fibonacci.services import ( fibonacci_recursive_with_database, fibonacci_up_to_index, fibonacci_up_to_value, ) def up_to_including_index(n: int) -> List[int]: """ This function calls the fibonacci_up_to_including_index_database function using the given n (Fibona...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'login_window.ui' # # Created by: PyQt5 UI code generator 5.15.0 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. import re from PyQt5 impor...
#Given a 32-bit signed integer, reverse digits of an integer. # Example 1: # Input: 123 # Output: 321 class Solution: def reverse(self, num): revd = int(str(num)[::-1]) if num>= 0 else -int(str(num)[1:][::-1]) if revd > 2**31 or revd < -2**31: return 0 else: return r...
import pickle as pkl import numpy as np import json from collections import Counter import csv import random import matplotlib.pyplot as plt # from nltk.twitter import Query, Streamer, Twitter, TweetViewer, TweetWriter, credsfromfile #vector helpers #note this code is adapted from Joel Grus's Excellent Data Science fr...
def iterator(): # 迭代器 test = [1, 2, 3, 4] test = iter(test) # 使test成为迭代器 print(next(test)) # 结果为1 print(next(test)) # 结果为2 class TestIter: def __init__(self, value): self._value = value self._children = [] def __repr__(self): # TestIter的返回值,__str__则为pri...
from django.contrib import admin from django.urls import path,include from . import views from django.views.generic.base import RedirectView urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('delete/<int:id>/',views.delete_data , name="deletestudent"), path('upd...
# python has 3 control state ments # pass: it can be used in conditionaln stmts loos functions # break: it is exit the loop in a condition when the condition is true # continue: it is exits the the loop at a condition if the the condition is true and return backs the loop after the condititon is exititue # collecti...
from django.contrib.auth.backends import ModelBackend import re from .models import User def get_user_by_accoutn(account): try: if re.match('^1[3-9]\d{9}$', account): # 手机号登录 user = User.objects.get(mobile=account) else: # 用户名登录 user = User.objects.ge...
import sonnet as snt import tensorflow as tf a = snt._resampler(tf.constant([0.]),tf.constant([0.])) print(a)
import re import numpy as np import pandas as pd import operator # This is used in able to coalesce all the listings that # are not in a cluster, into one. # It does this by going through all clusters, then # finding out combined_listings = pd.read_csv("current_target_out.csv") df = pd.DataFrame(columns=['clus...
from rest_framework import serializers from person.models import Permission class PermissionSerializer(serializers.ModelSerializer): object_id = serializers.SerializerMethodField() def get_object_id(self, obj): """ Delete course run :param obj: :return: """ re...
# Generated by Django 3.0.3 on 2020-02-11 20:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('runner', '0009_auto_20200211_2104'), ] operations = [ migrations.RenameField( model_name='viewable', o...
# -*- coding: utf-8 -*- import tensorflow as tf from datetime import datetime as dt # Key of the flags to ingore ignore_keys = set(["h", "help", "helpfull", "helpshort"]) def get_options(): tf.app.flags.DEFINE_string("save_dir", "saved", "checkpoints,log,options save directory") ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [('auvsi_suas', '0001_initial'), ] operations = [ migrations.RemoveField(model_name='missionconfig', name='ir...
import mnist_input # import mnist_model # reload(mnist_model) import numpy as np import tensorflow as tf mnist = mnist_input.read_data_sets('MNIST_data', one_hot=True) import mnist_noise_model from importlib import reload reload(mnist_noise_model) # checkpoint_path = "save_models/baseline_40epochs.ckpt" checkpoint_p...
import numpy as np import cPickle as pickle from scipy import ndimage age = 1E8 # --- duration of constant SF / yr n = 100000 # --- number of star particles Z = 0.001 # --- metallicity ages = age*np.random.random(n) # --- assume ages are uniformly spread over the age of the galaxy metallicities = Z*np.ones(n) # --...
from typing import Set, List import numpy as np import pandas from Siamese.data_types import PatchDesc, TupleInt from Siamese.feature_processing import EnsembleFeatureMetadata def compute_query_ranking_metrics(supportFeatureNames: Set[str], patchesSorted: List[PatchDesc], metadataF...
## Two trees are considered "leaf-similar" if the order of their leaves is the same from left to right. ## This function uses DFS to check if two given trees are "leaf-similar". class Node: def __init__(self, val, visited): self.val = val self.visited = visited self.left = None self...
import pickle import sys from src.configuration import Configuration def pack_args(population, server_id, config: Configuration): """ Compiles a list of arguments for parallel training """ config_str = pickle.dumps(config) # Each server gets a portion of the jobs: server_job_args = [[] for _ in range...
a = [10,9,8,7,6,5,4,3,2,1] def merge(l, m, r): global a x = a[l:m+1] y = a[m+1:r+1] i = l while x and y: if x[0] < y[0]: a[i] = x.pop(0) else: a[i] = y.pop(0) i += 1 while x: a[i] = x.pop(0) i += 1 while y: a[i] = y.pop(0) i += 1 print a def merge_sort(l, r): global a if l >= r: retu...
# File Name: dog_cat.py # 此类是狗的集合,此类的实例是具体的某一只狗 class Dog(object): def __init__(self, name): # Python 的私有属性用一个或两个下划线开头表示 # 一个下划线开头的私有属性表示外部调用者不应该直接调用这个属性,但还是可以调用 # 两个下划线外部就不能直接调用了,但也有办法 self._name = name # 私有属性 _name 不可以被直接调用 # 因此需要定义两个方法来修改和获取该属性值 # get_name 用来获取属性值,s...
from scipy import integrate, interpolate, fftpack import numpy as np import matplotlib.pyplot as plt import pandas import csv class YAGTS_DataBrowser: def __init__(self, date, shotNo, shotSt): self.date = date self.shotNo = shotNo self.shotSt = shotSt #self.filepath = '/Volumes/shar...
import matplotlib.pyplot as plt import numpy x = numpy.arange(0,10,0.1) s = numpy.sim(x) print(s) plt.plot(s) plt.show()
# -*-coding:Latin-1 -* class TableauNoir: objets_crees= 0 #attribut de classe, identique a tout les objets de la classe def __init__(self): #Constructeur: il n'est pas vraiment obligatoire. #chaque fonction speciale a deux tiret bas, celle ci sert a definir les attributs """À chaque fois qu'on crée un objet, ...
# test_util.py """Module to provide testing utility functions, objects, etc.""" from unittest.mock import MagicMock class AsyncMock(MagicMock): """ AsyncMock is the async version of a MagicMock. We use this class in place of MagicMock when we want to mock asynchronous callables. Source: https:/...
# perform face detection # display detected face frame # display FPS info in webcam video feed # This is the official sample demo file desribed in the installer documentation # Date: 2020 01 26 # Install OpenVINO™ toolkit for Raspbian* OS # http://docs.openvinotoolkit.org/2019_R1/_docs_install_guides_installing_ope...
import os import numpy as np import matplotlib.pyplot as plt import matplotlib.patches import skimage import skimage.measure import skimage.color import skimage.restoration import skimage.io import skimage.filters import skimage.morphology import skimage.segmentation from nn import * from q4 import * # do not include...
from .deck import Deck from .comp_dealer import CompDealer class BlackJackGame: def __init__(self, player1): self.player1 = player1 self.dealer = CompDealer() self.player1.current_score = 0 # setting human player's score to zero self.bet_amount = 0 self.deck = Deck() ...
import pymysql db = pymysql.connect("localhost","root","12343249","sparsh" ) cursor = db.cursor() sql = """INSERT INTO vidhi(ID,Name) VALUES (1,'I love you')""" try: cursor.execute(sql) db.commit() except: db.rollback() db.close()
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-25 15:53 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('filters', '0003_filteredresource_status'), ] operations = [ migrations.Alte...
#!/usr/bin/env python # encoding: utf-8 import os.path from datetime import timedelta from decimal import Decimal import flask from flask.ext.script import Manager from jinja2 import Markup, escape import yaml pages = flask.Blueprint('pages', __name__) missing = object() def q(value, places): return value.quan...
from rest_framework import serializers from Offers.models import Offers class OfferSerializer(serializers.ModelSerializer): class Meta: model = Offers fields = ('url',) #url = serializers.URLField()
from django.contrib import admin from .models import Cliente class ClienteAdmin(admin.ModelAdmin): list_display = ["nome", "sobrenome", "cpf", "telefone", "email"] admin.site.register(Cliente, ClienteAdmin)
from domain.square import Square class UI: def __init__(self, g): self._game = g def _readMove(self): while True: try: tokens = input("Enter move >> ").split(' ') if len(tokens) != 2: raise ValueError ...
# Created by MechAviv # Quest ID :: 17613 # [Commerci Republic] The Minister's Son sm.setNpcOverrideBoxChat(9390241) sm.sendNext("I'm... fine, you... meddling dumb-dumb!") sm.setSpeakerID(9390241) sm.flipSpeaker() sm.flipDialoguePlayerAsSpeaker() sm.setBoxChat() sm.setColor(1) sm.sendSay("#b(He's not very polite...)#...