text
stringlengths
8
6.05M
import xml.dom.minidom DOMTree = xml.dom.minidom.parse("movies.xml") # 打开xml文件 collection = DOMTree.documentElement # 获得文档元素对象 movies = collection.getElementsByTagName("movie") # 获取节点的一组标签,返回的是一个数组 print(movies[0].getAttribute("title")) type = collection.getElementsByTagName("type") item = type[0] print(item.fir...
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: mnist_center.py # Author: Qian Ge <geqian1001@gmail.com> import sys import numpy as np import tensorflow as tf import platform import scipy.misc import argparse sys.path.append('../') from lib.dataflow.mnist import MNISTData from lib.model.ram impor...
import json import logging from datetime import datetime import os from ipaddress import ip_address MAX_ELEMENTS_PER_CASE = 1000 CHUNK_SIZE = 30 # Because 100 is the limit, and some do not finish, 30 are for sure free COST_PER_TRACEROUTE = 20 # Because OneOff = True def template_measurement(): return { ...
nmList=[8,60,43,55,25,134,1] total=0 for i in nmList: total+=i print(total)
import unittest from katas.kyu_6.regexp_basics_parsing_mana_cost import parse_mana_cost class ParseManaCostTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(parse_mana_cost(''), {}) def test_equals_2(self): self.assertEqual(parse_mana_cost('0'), {}) def test_equals_3(...
import logging import pickle import numpy as np import pandas as pd from copulas import EPSILON, get_qualified_name from copulas.multivariate import GaussianMultivariate, TreeTypes from copulas.univariate import GaussianUnivariate from rdt.transformers.positive_number import PositiveNumberTransformer # Configure logg...
#!/usr/bin/env python # # Copyright (c) 2011 Intel, Inc. # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the Free # Software Foundation; version 2 of the License # # This program is distributed in the hope that it will be us...
from math import inf from collections import deque def bfs(nodo, grafo): padri = [-1 for _ in grafo] padri[nodo] = nodo distanze = [inf for _ in grafo] distanze[nodo] = 0 coda = deque([nodo]) while coda: nodo = coda.pop() for adiacente in grafo[nodo]: if padri[adi...
from numpy import argmax # Works out multinomial coefficient nC(k1,k2,...,km) def multiCoeff(n, kList): kMaxFirstPos = argmax(kList) kMax = kList[kMaxFirstPos] coefficient = 1 i = kMax + 1 # Perform repeated multiplication and division # for part of kList up to the maximum for k in kList[:kMaxFirstPos]: for ...
from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager, Group from django.contrib.auth.models import PermissionsMixin from django.utils.translation import ugettext_lazy as _ from movies_app.model.roles import Roles class CustomUserManager(UserManager): d...
import cv2 import imutils import time model_path = "face-detection-adas-0001.xml" pbtxt_path = "face-detection-adas-0001.bin" net = cv2.dnn.readNet(model_path, pbtxt_path) net.setPreferableTarget(cv2.dnn.DNN_TARGET_MYRIAD) camera = cv2.VideoCapture(0) frameID = 0 grabbed = True start_time = time.time() while grabbe...
from django.shortcuts import render from .lookup import perform_lookup from django.http import JsonResponse def search_view(request): q_params = request.GET q = q_params.get('q') context = {} if q is not None: results = perform_lookup(q, internal_sort=True) context['results'] = result...
fildir='D:\SQ\log.txt'#查询某结尾,的数值总和 filer_R=open(fildir,'r') lines=filer_R.read().splitlines()#读取所有信息并去除所以换行符 del lines[0],lines[-1]#去除头和尾 res=[]#保存类型,个数 for line in lines: r_s=line.split('\t') file_Type=r_s[0].split('.')[-1].strip()#获取下标0的元素,在通过.截取,获取最后一个元素,去除空格 file_Size=int(r_s[1].strip())#获取第二个元素去除空格,最后要...
#[1] import the modules and data import pandas as pd import numpy as np import seaborn as sns import matplotlib import matplotlib.pyplot as plt from scipy.stats import skew from scipy.stats.stats import pearsonr ''' %config InlineBackend.figure_format = 'retina' #set 'png' here when working on notebook %matplotlib inli...
from demo.app import app
from flask import Flask, render_template, request, redirect, session, flash import re from mysqlconnection import connectToMySQL from flask_bcrypt import Bcrypt app = Flask(__name__) bcrypt = Bcrypt(app) app.secret_key = '5153fe473438c82c17e638dd778b6b5e' email_regex = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a...
"""Test the analog.renderers module.""" from __future__ import (absolute_import, division, print_function, unicode_literals) import os try: from unittest import mock except ImportError: import mock import pytest from analog import renderers from analog import Report from analog.excepti...
url = 'https://github.com/PDKT-Team/ctf/blob/master/fbctf2019/hr-admin-module/README.md' print 'hr_admin_module'
# Loihi modules import nxsdk.api.n2a as nx # Official modules import numpy as np import logging from copy import deepcopy import os # Pelenet modules from ..system import System from ..system.datalog import Datalog from ..parameters import Parameters from ..utils import Utils from ..plots import Plot from .readout im...
from __future__ import unicode_literals from __future__ import print_function from __future__ import absolute_import from __future__ import division from copy import deepcopy, copy from pickle import HIGHEST_PROTOCOL import six import collections import time import hashlib import os import inspect from functools impo...
import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib import rcParams rcParams["font.size"] = 15 dat = pd.read_json("4d_plot_data.json") xs = dat["n_features"] ys = dat["n_est"] zs = dat["mae"] cs = dat["max_depth"] xs2 = xs.unique() ys2 = ys.unique() xticks = [0.05] + list(np.lin...
from .books.list import book_list from .librarians.list import list_librarians from .libraries.list import list_library from .home import home from .auth.logout import logout_user from .books.form import book_form from .libraries.form import library_form, library_edit_form from .books.details import book_details from ....
from Observation import Observation class SyntheticObservation(Observation): def __init__(self): Observation.__init__(self) self.schema = None self.schema_var = None self.successful_var = None self.successful = False def equals(self, o2): if (type(self) != type(o2)): return False; so2 = Syntheti...
import pickle import numpy as np import tensorflow as tf import tensorflow.keras as kr import Configuration as cfg def load_char_to_index(char_to_index_path): with open(char_to_index_path, 'rb') as char_to_index_file: return pickle.load(char_to_index_file) def save_char_to_index(char_to_index, c...
from __future__ import print_function, division import numpy as np from timeit import default_timer as timer from numbapro import cuda from thread import start_new_thread @cuda.jit('uint64(uint64, uint64, uint64)', inline=True, device=True) def modexp(base, exponent, p): """ iterative modular expoentiation ...
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D #这里设函数为y=3x+2 x_data = [1.0,2.0,3.0] y_data = [5.0,8.0,11.0] def forward(x): return x * w + b def loss(x,y): y_pred = forward(x) return (y_pred-y)*(y_pred-y) mse_list = [] W=np.arange(0.0,4.1,0.1) B=np.arange(0.0,...
from collections.abc import Iterable def _flatten(l,ret): for i in l: if isinstance(i, Iterable) and type(i) is not str: _flatten(i,ret) else: ret.append(i) return ret def flatten(l): ret = [] return list(_flatten(l,ret)) if __name__ == "__main...
#-*- coding: utf-8-*- from __future__ import unicode_literals from django.db import models # Create your models here. #1、图片表 class Image(models.Model): imageId = models.AutoField(primary_key=True) url = models.CharField(max_length=100) img = models.FileField(upload_to="picture") #2、栏目表 class Column(mode...
class Demo4: #static variable name = "Sathya" @classmethod def sample(cls): #Calling static variable using class name print(Demo4.name) #static variable is available for class print(cls.name) @classmethod def sample2(cls): Demo4.name = "Sathya Tech" ...
import os try: from __revision__ import __revision__ except: __revision__ = 'develop' metadata = { 'name': "djopenid", 'version': "1.0", 'release': __revision__, 'url': 'http://www.jollydream.com', 'author': 'hanbox', 'author_email': 'han.mdarien@gmail.com', 'admin': 'han.mdarien@g...
# Generated by Django 2.2.1 on 2019-09-22 14:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0005_auto_20190914_2336'), ] operations = [ migrations.CreateModel( name='Education', fields=[ ...
from flask_script import Manager from movie import app, db, Director, Movie manager = Manager(app) # reset the database and create some initial data @manager.command def deploy(): db.drop_all() db.create_all() StevenSpielberg = Director(name='Steven Spielberg', about='Steven Spielberg is an American film...
# lec4[Multiple feature Linear Regression] import tensorflow as tf import pandas as pd import numpy as np import matplotlib.pyplot as plt ## function ## def standard(x): global memoryList memoryList.append((np.mean(x), np.std(x))) return (x - np.mean(x)) / np.std(x) def rollback(x, num): mean, std = m...
import torch import torch.backends.cudnn as cudnn import torch.nn as nn import torch.optim as optim import argparse import os import numpy as np from tensorboardX import SummaryWriter from Resnet18 import Resnet_18 from Dataloader import Load_Cifar10 from Visualization import Filter_visualization, Featuremap_visualizat...
import gspread from oauth2client.service_account import ServiceAccountCredentials import re class FormReader: def fetch_sheet(self, url): all_list = self.get_data(url) student_links = {} all_list = all_list[1:] for i in range(len(all_list)): if ',' in all_list[i][0]: ...
loop = 5 while(loop <= 10): print(loop) loop += 1 print('Loop Ends') print(loop)
""" Unit tests for the """ from __future__ import absolute_import, division, unicode_literals import json import treq from twisted.trial.unittest import SynchronousTestCase from mimic.canned_responses.loadbalancer import load_balancer_example from mimic.model.clb_errors import ( considered_immutable_error, i...
# 두 자연수 A와 B가 있을 때, A%B는 A를 B로 나눈 나머지이다. # 수 10개를 입력받은 뒤, 이를 42로 나눈 나머지를 구한다. # 그 다음 서로 다른 값이 몇 개 있는지 출력하는 프로그램을 작성하시오. arr = [] new_arr = [] for i in range(10): number = int(input()) arr.append(number%42) for i in arr: if i not in new_arr: new_arr.append(i) print(len(new_arr))
import tkinter as tk import AI TITLE_FONT = ("Helvetica", 24, "bold") class tictactoe_game(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) path = "bg.jpg" container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) con...
""" @author: David inspired by Telmo Menezes's work : telmomenezes.com """ import sys import matplotlib matplotlib.use('Agg') import numpy as np from multiprocessing import Pool import network_evaluation as ne import genetic_algorithm as ga import warnings import os import random np.seterr('ignore') warnings.filterw...
# Generated from ./Java8.g4 by ANTLR 4.7.1 # encoding: utf-8 from __future__ import print_function from antlr4 import * from io import StringIO import sys def serializedATN(): with StringIO() as buf: buf.write(u"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2") buf.write(u"m\u044c\b\1\4\2\t\2...
#!/usr/bin/env python #-*- coding:utf-8 -*- #百个眼镜,摆成一个圈,全部正面向上,第一个人将每个翻动一次,一共翻了100次;第二个人从no.2开始隔一个翻一次,也翻100次;第3个人从no.3开始隔两个翻一次,翻100次,问100个人之后,多少眼镜正面向上 import numpy as np l=[] n=100 a=np.zeros(n) for i in range(1,n+1): for j in range(i,(n+1)*i,i): while(j>n): if(j<=n): if(a[j-1]==0): a[j-1]=1 ...
import threading import sys import hashlib import sqlite3 import hmac import rsa class Customer(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.connection = sqlite3.connect("Customer_Teller_loginInfo.db") self.pubkey, self.privkey = rsa.newkeys(512) self.c...
def meow(): print("Meow!") print("I am imported") # 이 print 함수는 전역 범위
import numpy as np import distance class MultiD(object): """ 不用这个了 直接用numpy的二维矩阵 """ def __init__(self): self.nameList = {} # self.valueList = [] def __getitem__(self, key): if not self.nameList.__contains__(key): print("MultiD don't have t...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jul 5 10:43:31 2018 @author: thomas """ import numpy as np import matplotlib.pyplot as plt def main(): #Color Palette for plotting #Colors are in the following order: Red/Pink, Orange, Green, Blue, Purple R1=[255/255,255/255,153/255,153/2...
# # This file is part of LUNA. # # Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com> # SPDX-License-Identifier: BSD-3-Clause """ Request components shared between USB2 and USB3. """ from amaranth import * from amaranth.hdl.rec import DIR_FANOUT class SetupPacket(Record): """ Record captur...
n1 = int(input('Digite o primeiro termo da PA: ')) r = int(input('Digite a razão da PA: ')) n = n1 aux = 1 while(aux != 11): n = n1 + r*(aux-1) print(n, end=' -> ') aux += 1 print('fim')
import numpy as np import logging from pprint import pformat from keras.models import Model from keras.layers import * from pelesent.models import NeuralNetwork logger = logging.getLogger(__name__) class CNN(NeuralNetwork): def build(self, nb_filter=100, filter_length=3, stride=1, pool_length=3, cnn_activation='r...
from flask import Flask from flask import request import proto.Register_pb2 as Register import proto.Personal_pb2 as Personal import proto.Friend_pb2 as Friend import proto.Basic_pb2 as Basic import proto.Message_pb2 as Message from src.db import Mongo mongo = Mongo() app = Flask("AI ins") # 注册登录相关部分页面与处理函数 @app.rout...
# -*- coding: utf-8 -*- class Solution: DIRECTIONS = [(-1, 0), (0, 1), (1, 0), (0, -1)] def surfaceArea(self, grid): result = 0 for i in range(len(grid)): for j in range(len(grid[0])): result += self.singleSurfaceArea(grid, i, j) return result def s...
try: from cartotools.crs import * # noqa: F401 F403 from cartotools.osm import location except ImportError: # cartotools provides a few more basic projections from cartopy.crs import * # noqa: F401 F403 # Basic version of the complete cached requests included in cartotools from .location impor...
# Open test_list.p with dictionary of dictionaries (d) import pickle filename = "test_lists.p" in_file = open(filename, "rb") d_from_file = pickle.load(in_file) in_file.close() # Designate domains and score types again domains = { 1: "Language", 2: "Spatial", 3: "Motor", 4: "Attention", 5: "...
#!/usr/bin/env python import os import sys import shutil import datetime import pyperclip import subprocess clipboard_copy = pyperclip.clipboards.init_osx_clipboard()[0] STATIC_DIR = os.path.join(os.path.dirname(__file__), "static") if len(sys.argv) == 1: print "Usage: %s file.jpg [file.jpg ...]" % sys.argv[0] ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import time from wgraph.graph import ( load, search, Word, verbose, Graph, draw_graph, add_node, create_graph, apply_styles, ) def distance(graph: Graph, word1: Word, word2: Word) -> int: graph_path = search( gr...
import pytest from django.urls import reverse @pytest.mark.django_db @pytest.mark.parametrize("view", ["inventory:inventory_list"]) def test_view_inventory_list(client, view): url = reverse(view) response = client.get(url) # content = response.content.decode(encoding=response.charset) assert response...
HEX_COLOURS = {"blueviolet": "#8a2be2", "brown": "#a52a2a", "coral": "#ff7f50"} colour_name = input("Enter a colour name: ") while colour_name != "": print("The code for {} is {}".format(colour_name, HEX_COLOURS.get(colour_name))) colour_name = input("Enter a colour name: ")
import RPi.GPIO as GPIO import time sensor = 12 value = 0 GPIO.setmode(GPIO.BOARD) GPIO.setup(sensor, GPIO.IN) while True: print GPIO.input(sensor)
from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse def still_alive(function): def wrap(request, *args, **kwargs): if not request.user.is_authenticated(): #TODO add the 'next': request.GET.get('next', '')} return HttpResponseRedirect(reverse('i...
from __future__ import print_function # import mavutil from pymavlink import mavutil from dronekit import connect, VehicleMode import time # create the connection # From topside computer connection_string = '/dev/ttyACM0' master = mavutil.mavlink_connection(connection_string) master.wait_heartbeat() master.mav.param...
from flask import request, jsonify from ..models import DeviceModel, FlowModel from pa import database as db from sqlalchemy import asc, desc import pa from .summary import get_range_summary from datetime import datetime, timedelta def get_device(): try: devices = db.session.query(FlowModel.mac.label('mac...
from django.db import models from django.contrib.auth import get_user_model class HealthEntry(models.Model): user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, null=True, blank=True ) age = models.IntegerField(default=0) gender = models.CharField( choices=(("M", "Mal...
#!/usr/bin/env python import os import sys import dotenv BASE_DIR = os.path.join(os.path.dirname(__file__), os.pardir) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") os.environ.setdefault("ENV", "default") def run_gunicorn_server(addr, port): """run application use gunicorn http server """ ...
# Copyright 2014 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 a...
"""ChunkedImageLoader class. This is for pre-Octree Image class only. """ import logging from typing import Optional from napari.layers.image._image_loader import ImageLoader from napari.layers.image.experimental._chunked_slice_data import ( ChunkedSliceData, ) from napari.layers.image.experimental._image_locatio...
#!/usr/bin/python # -*- coding: utf-8 -*- variable = 7 if variable > 10: print "La variable es mayor que diez" elif variable < 7: print "La variable es menor que siete" else: print "La variable es siete" print "Esto se muestra siempre"
from bsm.util import ensure_list def _build_steps(cfg): cfg['build'] = ensure_list(cfg['build']) try: make_index = cfg['build'].index('make') except ValueError: return build_step_number = len(cfg['build']) if make_index > 0 and 'configure' not in cfg['install']: cfg['insta...
# if n is a positive integer, n! = n(n-1)(n-2)...(3)(2)(1). The product of all positive integers less than or equal to n # 0! = 1 def factorial(n): if n < 0: return('{} is not a positive integer '.format(n)) elif n >= 1: return(n * factorial(n-1)) else: return(1) print(fac...
# -*- coding: utf-8 -*- """ Main script to train and export GPR Forward models for the Ogden Material """ import numpy as np from random import seed from sklearn.preprocessing import StandardScaler import matplotlib.pyplot as plt from time import time from sklearn.gaussian_process import GaussianProcessRegressor from...
from PyQt5.QtSql import QSqlDatabase, QSqlQueryModel, QSqlQuery from PyQt5.QWidgets import QTableView, QApplication import sys
# as_util_html.py written by Duncan Murray 7/8/2013 (C) Acute Software # utility functions for HTML work, mainly from udacity course import csv try: import urllib.request as request except: import urllib2 as request import getpass import socket def main(): TEST() def TEST(): print(" \n --- Testing Net func...
#!/usr/bin/python """ Starter code for the evaluation mini-project. Start by copying your trained/tested POI identifier from that which you built in the validation mini-project. This is the second step toward building your POI identifier! Start by loading/formatting the data... """ import pickl...
# Generated by Django 2.1.7 on 2019-02-26 13:26 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0005_passenger'), ] operations = [ migrations.RenameField( model_name='passenger', old_name='ticket_class', ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 16-12-4 下午8:52 # @Author : sadscv # @File : chunkFreatures.py def npchunk_features(sentence, i, history): """ 特征抽取器 :param sentence:(word,tag) :param i: int, 当前sentence第i个词 :param history: i前所有的tag(chunk) :return:{"pos":pos} "...
import numpy as np import csv import matplotlib.pyplot as plt path1='./training_log_cnn_pretrain.csv' with open(path1,'r') as f: reader1 = csv.reader(f) datas1 = [[row[0],row[1],row[2],row[3],row[4]] for row in reader1] datas1=np.array(datas1[1:31],dtype=np.float32) path2='./training_log_cnn_custom.csv' wit...
class RaCRohaCentral: president = "Rtr. Akash Rumade" secretary = "Rtr. Satyen Deshpande" treasurer = "Rtr. Yash Shinde" class Avenue(RaCRohaCentral): def display(self): print(f"Roha Central has 4 avenue - PDD, CSD, CMD, ISD, president is {self.president}") president = "Rtr. Yash Shi...
#importation du module socket afin de permetttre une communication réseau #importation d'argparse afin de pouvoir créer des argument #importation de threading, afin d'allouer des processus à différentes action #importation de time afin de créer des pauses lors de certaines action import socket as modSocket import...
import gzip with gzip.open('somefile.gz', 'rt') as f: text = f.read() with gzip.open('somefile.gz', 'wt') as f: f.write('text') import bz2 with bz2.open('somefile.bz2', 'rt') as f: text = f.read() with bz2.open('somefile.bz2', 'wt') as f: f.write('text') with gzip.open('somefile.gz', 'wt', compres...
import os import re import sys import getopt class Greper: """ A greper for any platform. """ params_dict = {} path_list = [] search_pattern = '' search_pattern_cmp = None def __init__(self): """ """ pass def grep(self): """ - 'param...
#!/usr/bin/python3 """interface implemented by all heap variants""" class PairingHeapInterface: def __init__(self): self.count = 0 def make_heap(self): pass def find_min(self): pass def insert(self, node): pass def delete_min(self): pass def merge(self, heap2): pass def delete(self, node): ...
import tensorrt as trt import pycuda.driver as cuda import numpy as np import torch import pycuda.autoinit import dataset import model import time # print(dir(trt)) tensorrt_file_name = 'bert.plan' TRT_LOGGER = trt.Logger(trt.Logger.WARNING) trt_runtime = trt.Runtime(TRT_LOGGER) with open(tensorrt_file_name, 'rb') ...
n=[] k=[] k=int(input()) for i in range(0,k): k=k[0]+k[1]
class node(): """docstring for node.""" def __init__(self,data = None, parent = None): self.data = data self.parent = parent self.child1 = None self.child2 = None class heap(): def __init__(self): self.head = node() self.inser = self.head def add(self, d...
import sys sys.path.append('..') import cards import asyncio from nose.tools import assert_raises import random def test_build_deck(): deck = cards.build_deck("Durak", 1) assert(len(deck) == 36) def test_create_durak_game(): game = cards.create_durak_game(user_id=33, user_name='tobixen', channel_id=34) ...
from __future__ import annotations from Engine.Elements.board import Board from Engine.Elements.center import Center from Engine.Elements.discard import Discard from Engine.Elements.factory import Factory from typing import List, Union class Player: has_starting_marker = False def __init__(self, player_id: i...
from methods import Methods class experiment: def __init__(self): self.method = Methods() def testNB(self): badWords = ['fuck','damn','work','cunt','bitch','whore','asshole'] lines = self.openFile("testing.txt") results_NB = [] results_NB_noC = [] results_NB_...
# -*- encoding: utf-8 -*- import yaml import os.path from .database import * from .exceptions import * class Template(object): """Classe Template - Utilizada para obter e gerenciar a base dos templates. Atributos: - template_list (private:list): Lista de templates - templates ...
''' @Description: @Date: 2020-04-13 20:50:06 @Author: Wong Symbol @LastEditors: Wong Symbol @LastEditTime: 2020-05-30 17:17:50 ''' ''' 双端队列 在队列的两端都可以进行出队和入队 ''' class Node: def __init__(self, data=None): self.data = data self._next = None # 双端队列 class Deque: def __init__(self, _head=None, _tail=None): self....
import logging import auth import json import socket import jwt import argparse import encrypt import json import pre import chain from gmssl import sm2 success_res = json.dumps({ 'status': '200', 'msg': '' }) error_res = lambda msg: json.dumps({ 'status': '401', 'msg': msg }) parser = argparse.Argum...
# -*- coding: utf-8 -*- """ ytelapi This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). """ class Body77(object): """Implementation of the 'body_77' model. TODO: type model description here. Attributes: mfrom (string): A valid Ytel Voice ena...
#!/usr/bin/env python ''' This file is used when you want to control a single robot i.e., the first rover that computer connects to ''' import roslib; roslib.load_manifest('br_swarm_rover') import socket import array class RovCon(): def __init__(self, networkCard): self.nic = networkCard self._r...
import datetime def compare_time(time1, time2): d1 = datetime.datetime.strptime(time1, '%Y-%m-%d %H:%M:%S') d2 = datetime.datetime.strptime(time2, '%Y-%m-%d %H:%M:%S') delta = d1 - d2 print("days is %s"%delta.days) if delta.days >= 30: return True else: return False time1 = dat...
import random, json, os # We are assuming the following moves: # Moves that change your orientation # Up # Down # Left # Right # A move that changes your position # Step # The move that allows you to exit the board # Exit # Other actions that change the world aside from your position # PickUp # Shoot # The functi...
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. Created based on the following tutorial: http://ataspinar.com/2017/08/15/building-convolutional-neural-networks-with-tensorflow/ """ #%% IMPORT NECESSARY PACKAGES # To load the MNIST dataset you will need to install 'python-mnist'...
# -*- coding: utf-8 -*- """ Created on Thu May 6 13:07:33 2021 @author: Vidhi """ import random from string import ascii_uppercase from tkinter import messagebox from tkinter import* root = Tk() root.title("Hangman") root.iconbitmap("icon.ico") root.geometry("670x580+300+70") root.resizable(0,0) root...
def getPawnMoves(pos, board, colour, moveNo): possibleMoves = [] standard = [-1,0] ifOccupied = [[-1,-1], [-1,1]] ifFirst = [-2,0] if colour == "black": standard[0] *= -1 ifOccupied[0][0] *= -1 ifOccupied[1][0] *= -1 ifFirst[0] *= -1 if pos[0] + standard[0] <= 7...
matrix = [[1, 5, 9], [-2, 0, 13], [7, 1, 5]] # for i in range(3): # if i == 0: # sm_1 = min(m[i]) # elif i == 1: # sm_2 = min(m[i]) # else: # sm_3 = min(m[i]) # print(min(sm_1, sm_2, sm_3)) # ########################## """ temp_list =[] m = None n = None for row in matrix: t...
# The following program extracts callback domain names from malware files and then builds a bipartite network of malware samples. # it performs one projection of the network to show which malware samples share common callback servers # it performs another projection to show which callback servers are called by common m...
# Generated by Django 3.2.3 on 2021-06-02 13:57 from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ ("images", "0008_auto_20210602_1557"), ] operations = [ migrations.CreateMode...
import module2 owner = 'module1' module2.show_owner(owner)