text
stringlengths
38
1.54M
""" 案例1 #导入相关的包、 import re #查找相关的数字 #r表示字符串不转义 pattern=re.compile(r'\d+') #在字符串"123one789two"中按照pattern指定的正则进行查找 match=pattern.match("123one789two") print(match) """ """ #案例2 #导入相关的包、 import re #查找相关的数字 #r表示字符串不转义 pattern=re.compile(r'\d+') #在字符串"123one789two"中按照pattern指定的正则进行查找 #后边的...
import os import sys import unittest from pkg_resources import resource_string from scoville.circuit import Circuit from scoville.eagleSchematic import EagleSchematic from scoville.parts import GenericVoltageSource from unitTests import test_AND, test_OR, test_NAND, test_NOT, test_XOR, test_OneBitSelect, test_ThreeBi...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'petro-ew' """ 35. Написать функцию, получающую в качестве аргумента целое число x, и возвращающую строковое представление x в двоичной системе счисления. """ x = 56 def funcz(x): return "{0:b}".format(x) print(funcz(x))#!/usr/bin/env python3 # -*- coding...
import os from global_settings import * try: from local_settings import * from local_settings_secret import * except ImportError: import warnings warnings.warn('Local settings have not been found (src.conf.local_settings). Trying to import Heroku config...') try: from local_settings_heroku...
from utils import json_serialize from flask_restful import Resource, reqparse from app import db from models import Bank, BankBranch, Staff, User _bank_parser = reqparse.RequestParser() _bank_parser.add_argument(name="name", type=str, required=True, help="No Bank Name Provided", location="json") class BankListApi(...
""" Customer Name Contact ID Date Days room rent =1000 tot =rent*days*rooms 0 - 5 = 5% 5 - 10 = 10% 10 - 15 = 15% more than 15 = 20% """ name = input("Enter Customer Name : ") contact = input("Enter Contact Number : ") Id = input("Enter ID Number : ") date = input("Enter Date of Booking : ") days = ...
#!/usr/bin/env python # coding: utf-8 # In[2]: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns get_ipython().run_line_magic('matplotlib', 'inline') # In[3]: df=pd.read_csv('loan_data.csv') # In[4]: df.head() # In[5]: fig=sns.pairplot(df) # In[9]: fig.savef...
import FWCore.ParameterSet.Config as cms from EventFilter.CSCRawToDigi.cscDigiFilterDef_cfi import cscDigiFilterDef def appendCSCChamberMaskerAtUnpacking(process): if hasattr(process,'muonCSCDigis') : # clone the original producer process.preCSCDigis = process.muonCSCDigis.clone() # now a...
# Tuples su coleciton data tipovi koji su ordered i immutable, mogu duplikati elemenata # slicno listi ali ne moze da se menja nakon sto se napravi # ne moze sort, reverse # cesto se koristi za objekte koji pripadaju zajedno # () # zagrade nisu obavezne mytuple = ("Vika", 28, "Beograd") print(mytuple) # ako ima samo ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Text-to-Image module import os, sys, time from PIL import Image, ImageDraw, ImageFont from random import * from util import * from title.titletemplates import * from title.bgprofiles import * from title.generators import Generator import title.util as titutil COVER_PA...
#!/usr/bin/python -tt def count(m): if m == 0: return "INSOMNIA" a = [False, False, False, False, False, False, False, False, False, False] filled = 10 mmm = m while filled > 0 and m < 10**100: mm = m while mm > 10: last_dig = mm % 10 if not a[last_dig]: a[last_dig] = True ...
"""'Administrator's SQLAlchemy model""" from flask_login import UserMixin from sqlalchemy import ForeignKey, UniqueConstraint from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.orm import relationship from JDISCTF.app import DB from JDISCTF.models.role import Role class Administrator(User...
import numpy as np import scipy.io class Sigmoid(object): def __init__(self, x): self.x = x def f(self): return 1.0 / (1.0 + np.exp(-self.x)) def df(self): f = self.f() return np.multiply(f, 1.0-f) def d2f(self): f = self.f() return np.multiply(np.mul...
""" Program to calculate tip total amount is the addition of total bill and amount of the tip that needs to be given tip is calculated by multiplying total bill with tip percentage and dividing by 100 each person expense is total amount divided by total number of people and round the expense upto two decimal points """...
import csv import numpy as np x1 = [] x2 = [] x = [] with open('Data/Output/Data1.csv') as csvfile1: read_position = csv.reader(csvfile1, delimiter = ',') for row in read_position: x1.append(row) with open('Data/Output/Data2.csv') as csvfile2: read_position = csv.reader(csvfile2, delimiter = ',') for ...
__version__ = "$Id$" # Clipboard module. # # There is one *global* clipboard object, but it is implemented as a class, # so you can create multiple instances if you wish. # # Unfortunately, there is no link with the X clipboard facility (yet). # # The clipboard node typed: you always specify a list of objects. # the t...
import pytest from .pages.pages import MapPage, LandingPage, ListPage from .base import FunctionalTestCase @pytest.mark.usefixtures('activity_changeset') class ListTests(FunctionalTestCase): def test_list_filter(self): # Test that the list can be filtered by attributes. a_id_1 = self.create_item...
import numpy as np import lasagne from lasagne.updates import sgd from gmllib.helpers import progress_bar from rllib.environment import Environment from rllib.agent import Agent from rllib.space import FiniteStateSpace, FiniteActionSpace from rllib.parameter_schedule import GreedyEpsilonLinearSchedule from rllib.q_le...
#!/usr/bin/env python2 import sys grafo = open(sys.argv[1], 'w+') grafo.write('digraph {\n') temp = dict() for line in sys.stdin: values = line.strip().split() if values[0] == 'eth': key = values[1]+'-'+values[2] if int(values[3]) == 34525: key = key+'-'+'IPv6' if not key in temp.keys(): temp[key] =...
from django.core.exceptions import ValidationError from rest_framework import viewsets, status, permissions from rest_framework.decorators import action from rest_framework.response import Response from rest_framework_extensions.mixins import NestedViewSetMixin from apps.recipes.models import Recipe, Step from apps.re...
# coding: utf8 from django.shortcuts import get_object_or_404, redirect from django.views.generic.list import ListView from django.views.generic.base import View from django.views.generic.edit import DeleteView, CreateView, UpdateView from braces.views import LoginRequiredMixin, JSONResponseMixin from forum.models impo...
from conans import ConanFile, tools, CMake from conans.errors import ConanInvalidConfiguration, ConanException import os class Sol2Conan(ConanFile): name = "sol2" url = "https://github.com/conan-io/conan-center-index" homepage = "https://github.com/ThePhD/sol2" description = "C++17 Lua bindings" t...
import matplotlib.pyplot as plt import numpy as np import os import math as math import wavelet path = "Medicoes ponte dia 07-02-2019/" files_in_dir = [] wav_levels = 2 n_cortes = 3 fator = 4 ocorrencias = [] for file_ in os.listdir(path): file_str = str(file_) if(file_str.endswith(".txt") or file_str.endsw...
import numpy as np import matplotlib.pyplot as plt import math from scipy.special import comb #Apolarity condition for P(x) and Q(x) def apolarity(p, q): sum=0 for i in range(p.order+1): sum+=((-1)**i)*(p[i]*q[p.order-i])/(comb(p.order,i)) if sum==0: return(sum) else: retur...
import db_helper def main(): run = 1 db_helper.create_table() while run: print("\n") print('1. Insert new task in todo list \n' '2. View the todo list \n' '3. Delete the task \n' '4. exit \n') x = input("Choose any of above option: ") ...
import sqlite3 db_name = 'entreprise-sqlite.db' # This function will connect to the sqlite3 database and then execute the sql script string use the cursor.executescript() function. def execute_sql_script(sql_script_string): # Connect to sqlite3 database. conn = sqlite3.connect(db_name) # Open the cursor...
from rdflib import Namespace, Graph, Literal, RDF, URIRef from rdfalchemy.rdfSubject import rdfSubject from rdfalchemy import rdfSingle, rdfMultiple, rdfList from brick.brickschema.org.schema._1_0_2.Brick.Average_Discharge_Air_Flow_Sensor import Average_Discharge_Air_Flow_Sensor from brick.brickschema.org.schema._1_0_...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by hubiao on 2017/5/12 from __future__ import unicode_literals import logging,os,time from logging.handlers import TimedRotatingFileHandler import re class Log(object): def __init__(self): self.ResultRoot= './TestResult' if not os.path.exi...
# -*- coding: cp1252 -*- import random import pandas as pd import matplotlib.pyplot as plt def correl(df): corr = df.corr() t = 0.4 print "Matriz de Correlação\n\n",corr.iloc[-1].round(2) listacolunas = list(corr.columns.values) yx = len(listacolunas) -1 ...
# -*- coding: utf-8 -*- import Pyro4 import sys import importlib.util import os # reload(sys) # sys.setdefaultencoding('utf-8') class Unbuffered(object): def __init__(self, stream): self.stream = stream def write(self, data): self.stream.write(data) self.stream.flush() def write...
import gzip import numpy as np import os.path import scipy.sparse from scipy.sparse import csr_matrix from sklearn.preprocessing import normalize import sys from scanorama import merge_datasets MIN_TRANSCRIPTS = 600 def load_tab(fname, max_genes=40000): if fname.endswith('.gz'): opener = gzip.open el...
from flask import Flask, render_template, url_for, request import requests import math import ktrain import numpy as np #from sklearn.metrics import confusion_matrix #from sklearn.metrics import f1_score #from sklearn.metrics import accuracy_score from ktrain import text from tensorflow import keras #import pickle imp...
l=10 # Global variables means anyone can use this m=20 # Global variables means anyone can use this def function1(): l=5 #local varialbe means only this function can use this n=10 #local varialbe means only this function can use this print(l,m,n) '''here l is 5 so it can not take the value of global va...
from nine import str from PyFlow.UI.Tool.Tool import ShelfTool from PyFlow.Packages.Maya.Tools import RESOURCES_DIR from Qt import QtGui class RunScriptTool(ShelfTool): """docstring for RunScriptTool.""" def __init__(self): super(RunScriptTool, self).__init__() @staticmethod def toolTip(): ...
from helper import build_tree from helper import print_tree def mirror_tree(root): # post order swap def swap_node(root): if not root: return swap_node(root.left) swap_node(root.right) root.left, root.right = root.right, root.left return swap_node(root) if __n...
from django.urls import path from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth import views #from django.contrib.auth.views import login from . import views urlpatterns = [ #path('', views.index, name='index'), path('review/', views.ReviewView.as_view(), name='...
import json from datetime import datetime class BECS: possibleDonors = { 'A+': ['A+', 'A-', 'O+', 'O-'], 'O+': ['O+', 'O-'], 'B+': ['B+', 'B-', 'O+', 'O-'], 'AB+': ['O+', 'A+', 'B+', 'AB+', 'O-', 'A-', 'B-', 'AB-'], 'A-': ['A-', 'O-'], 'O-': ['O-'], 'B-': ['B...
from base import JiraBaseAction class JiraDeactivateUser(JiraBaseAction): def _run(self, username): return self.jira.deactivate_user(username)
from dateutil import parser class Condition(object): """ The current weather conditions. Attributes: code: The condition code for the forecast. The possible values for the code are described at the following URL (integer). http://developer.yahoo.com/weather/#codes ...
import config import transformers import torch.nn as nn import config_file from transformers import (BertConfig, BertForQuestionAnswering, BertTokenizer,XLNetConfig, XLNetForQuestionAnsweringSimple, XLNetTokenizer,XLMConfig, XLMForQuestionAnswering, XLMTokenizer, RobertaConfig, RobertaForQuestionAnswering, RobertaTo...
#!/usr/bin/env python """Delete login user events older than a given number of days. :Copyright: 2006-2020 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import datetime, timedelta import click from byceps.database import db from byceps.services.user.models.event impo...
from django.contrib import admin, messages from django.db import IntegrityError from requests import HTTPError from .api import ( make_import_language_list, ) from .models import ( ListLanguagesModel, TranslatedTextModel, ) class LanguageListAdmin(admin.ModelAdmin): list_display = [ 'code', ...
from tensorflow.keras.layers import * from tensorflow.keras.models import Model import os import numpy as np import tensorflow.keras.backend as K import unicodedata #text = [l.strip().split('\t') for l in open('corrected_forms.tsv','r') for i in range(10)]+[l.strip().split('\t') for l in open('training_data.tsv','r')...
from django import forms from .models import Comments class CommentsForm(forms.ModelForm): class Meta: model = Comments exclude = ['is_delete', 'create_time', 'update_time'] error_messages = { 'author': { 'max_length': '亲, 名字长度不能超过10位数哦', 'requi...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 12 14:43:23 2017 @author: jjcao """ import torch import torch.nn as nn import functools # class ResUnetGenerator(nn.Module): def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=Fals...
import logging log = logging.getLogger(__name__) import itertools import importlib from functools import partial from collections import defaultdict import numpy as np import pandas as pd import pyqtgraph as pg from atom.api import (Unicode, Float, Tuple, Int, Typed, Property, Atom, Bool, Enum...
#!/usr/bin/env python import click from lib.python.stream_crawler.stream_crawler import StreamCrawler class BloodhoundCLI: @click.group() def bloodhound_cli(): pass @bloodhound_cli.command() @click.option('--site', type=click.Choice(['youtube', 'twitch']), required=True) def crawl(site):...
import requests import json api_request = requests.get("https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=5&convert=USD&CMC_PRO_API_KEY=3889ce63-c733-403d-8b7d-c41a2438b4ea") api = json.loads(api_request.content) print("----------------") print("----------------") coins = [ { "...
import math a,b=raw_input().split() x=float(a) y=float(b) print round(math.sqrt(x*x+y*y),1) print round(x*y/2,1)
from flask import Blueprint courses = Blueprint('courses',__name__,url_prefix='/courses') from app.courses import routes
import time initial = time.time() #print(initial) k = 0 while(k<10): print("This is sandy program") time.sleep(2) k+=1 print("while loop execution time: ", time.time() - initial, "Seconds")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 6 13:54:26 2020 @author: petrapoklukar """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import app from absl import flags import sys sys.path.append('..') from dis...
# ***************************************************************************** # # 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 # # ...
from socket import socket, AF_INET, SOCK_STREAM class TCPClient(): def __init__(self, ip, port, bufsize=1024): self.ip = ip self.port = port self.bufsize = bufsize self.client = socket(AF_INET, SOCK_STREAM) self.RUN = True def start(self): self.client.connect((...
import warnings warnings.filterwarnings('ignore') import sys import random import numpy as np from sklearn import linear_model, cross_validation, metrics, svm from sklearn.metrics import confusion_matrix, precision_recall_fscore_support, accuracy_score from sklearn.ensemble import RandomForestClassifier from sklearn....
import numpy as np class FaceData: def __init__(self): self.detection_data = self.DetectionData() self.recognition_data = self.RecognitionData() self.results_data = self.ResultData() class DetectionData(): def __init__(self): self.tracker_ids = np.asarray([]) ...
def gree(name): print(f"hello {name}") ''' we have to types of functions 1. preform a task (e.g., greet and print are functions which are preforming a task) 2. return a value (e.g., round(1.9) is a function which returns a value) if put a print(preform a task fucntion) the result will be NONE but, if put a prin...
from flask_wtf import FlaskForm from wtforms import StringField, IntegerField from wtforms import validators from wtforms.fields.core import BooleanField from wtforms.validators import InputRequired, Optional, URL class AddPetForm(FlaskForm): '''Form for adding a new furry little friend, or maybe a reptile friend ...
from datetime import datetime from model_mommy.recipe import Recipe from django.contrib.gis.geos import Point, Polygon from catamidb.models import AUVDeployment, DOVDeployment, BRUVDeployment, TVDeployment, TIDeployment, Pose pose1 = Recipe( Pose, position=Point(12.4604, 43.9420), depth=27.5, date_time...
#!/usr/bin/env python import h5py import numpy as np import sys file = h5py.File("out.heat") # print file.keys() counts = file['0.counts'][...] expected_counts = file['0.expected'][...] positions = file['0.positions'][...] regions = file['regions'][...] start = regions[0][4] end = regions[0][5] peak_list = [] for ...
from datetimewidget.widgets import DateTimeWidget from django import forms # class UserRegistrationForm(forms.Form): # phone_number = forms.CharField( # required = True, # label = '', # max_length = 32 # ) # first_name = forms.CharField( # required = True, # label = '...
__author__ = 'izaac' import validictory import json import requests # Validator following the http://json-schema.org guidelines using the python validictory library # This is for integration and acceptance test schema_following = { "type": "object", "properties": { "user_is_following": { ...
""" https://www.hackerrank.com/challenges/reduced-string/problem string s: a string to reduce """ def superReducedString(s): s = list(s) i = 0 while i < len(s) - 1: if s[i] == s[i+1]: del s[i] del s[i] i = 0 if len(s) == 0: r...
# coding: utf-8 # # EC2 # # * EC2 stands for Elastic Compute Cloud # # * web service that provides resizable compute compute capacity in cloud. # * reduce time req to obtain, boot new server to minutes # * allows quick scale in capacity both up and down and requirements change. # # * what is it? It is a virtual l...
# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use ...
import argparse import logging import math import os import pathlib import shutil import subprocess def app_path_arg_validate(path): path = os.path.abspath(str(path)) if not os.access(path, os.F_OK | os.R_OK | os.X_OK): raise argparse.ArgumentTypeError( f"Specified application could no...
import abc from chess import coords from chess import move BISHOP_DIRS = {(1, 1), (1, -1), (-1, 1), (-1, -1)} ROOK_DIRS = {(0, 1), (0, -1), (-1, 0), (1, 0)} KNIGHT_DIRS = {(2, 1), (2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2), (-2, 1), (-2, -1)} class Piece(abc.ABC): def __init__(self, pos: coords.Coords, col: bo...
import pygame, time, random, settings,model car_exit=pygame.image.load('cartinki/EXIT.png') car_exit=pygame.transform.scale(car_exit,[100,50]) exit_rect=pygame.Rect(900,0,100,50) def paint(screen): # рисуем кадр pygame.draw.rect(screen, [100, 250, 200], [0, 0, 1300, 700], 0) for security in m...
# -*- coding: utf-8 -*- __author__ = 'Jonathan Mulle & Austin Hurst' from sdl2 import SDL_GetPerformanceCounter, SDL_GetPerformanceFrequency # TODO: Clean up the docs and code here def precise_time(): """Returns the time (in seconds) since the task was launched. The time returned has sub-millisecond pr...
# -*- coding: utf-8 -*- # Jogo da forca # POO # importar arquivos # import random # Criar tabuleiro usando LISTA tabuleiro=[''' +----+ | | | | | | ==========''', ''' +----+ | | O | | | | ==========''',''' +----+ | | O | | | | | ========...
base = [3,7,20,2,11,19,96,35,15,64] mark = False false_index = -1 loop = True Guess = int(input("Enter a number : ")) for i in range(len(base)): if Guess == base[i]: false_index = i+1; mark=True break if not mark: print("Not found") else: print("Found {0} at index {1}".format(Guess,f...
""" Copyright (c) 2020 R. Ian Etheredge All rights reserved. This work is licensed under the terms of the MIT license. For a copy, see <https://opensource.org/licenses/MIT>. """ from VisionEngine.base.base_trainer import BaseTrain import tensorflow as tf import numpy as np import os class KLWarmUp(tf.keras.callback...
from .random_variable import RandomVariable, TensorLike from tensorflow_probability import distributions as tfd import pymc4 as pm from typing import List class Mixture(RandomVariable): r""" Mixture random variable. Often used to model subpopulation heterogeneity .. math:: f(x \mid w, \theta) = \sum...
from django.shortcuts import render,redirect from .models import Products,Category,Tags from django.http import HttpResponse from .forms import ProductForm # Create your views here. def home(request): products=Products.objects.all() #tags=products.pop('tags') return render(request,'home.html',{'products...
from textblob import TextBlob from plotly.offline import plot import plotly.graph_objs as go import random user1 = "Bob" user2 = 'Alice' with open('chat_sample.txt', 'r+') as f: samples = f.readlines() d = {user1:[], user2:[]} for line in samples: time, *text = line.split('-') text = ''.join...
# -*- coding: utf-8 -*- import pandas as pd ## create empty df df = pd.DataFrame() # create a column df['name'] = ['Adam', 'Xavier', 'Ada'] df['employed'] = ['Yes', 'Yes', 'No'] df['age'] = [32,32,21] ## create a function def mean_age_by_group(dataframe,col): #groups the data by a column and return mean ag...
import sqlite3 import pandas as pd conn = sqlite3.connect('tweets.db') c = conn.cursor() c.execute(''' SELECT * FROM normal_tweets ''') rows = c.fetchall() df = pd.DataFrame(rows, columns=['id', 'datetime', 'tweet']) sample = df.sample(len(df)) sample['tweet'].to_csv('data_labeling/FULL_label_data.txt')
import FWCore.ParameterSet.Config as cms process = cms.Process("Demo") process.Timing = cms.Service("Timing") process.ana_PbPb = cms.EDAnalyzer('singleTrackAnalyzer', vertexSrc = cms.string('hiSelectedVertex'), trackSrc = cms.InputTag('hiGeneralTracks'),...
import sys import numpy as np seed = 1 np.random.seed(seed) #pfam_id = 'PF00008' #ipdb = 0 pfam_id = sys.argv[1] ipdb = sys.argv[2] ipdb = int(ipdb) ext_name = '%s/%02d'%(pfam_id,ipdb) try: ct = np.loadtxt('%s_ct.dat'%ext_name) except: pass #==============================================================...
# Generated by Django 3.1.5 on 2021-01-29 17:05 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('films', '0006_film_creat...
class Node: def __init__(self, id: int, tag: bool = False, weight: int = 0.0, color: str = "white", nodesIn: dict = None, nodesOut: dict = None, position: tuple = None, parent=None): self.id = id self.tag = tag self.weight = weight self.color = color if node...
#!/usr/bin/python """ This program will search "pycon" keyword on provided site and validate test as per search result. """ import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keys class pythonorgserach(unittest.TestCase): def setUp(self): """set geckodriver bin file path...
import tensorflow as tf x1 = tf.add(4,8,) x2 = tf.multiply(x1,5) x3 = tf.add(12,6,) x4 = tf.multiply(x3,x2) x5 = tf.div(x4,2) with tf.Session() as sess: output = sess.run(x5) print(output) with tf.Session() as sess: outnew=tf.summary.FileWriter("./logs/add",sess.graph) #tensorboard --logdir=logs...
from unittest import TestCase from django.conf import settings from django_dynamic_fixture import decorators class SkipForDatabaseTest(TestCase): def setUp(self): self.it_was_executed = False def tearDown(self): # It is important to do not break others tests: global and shared variable ...
#!/usr/bin/python # -*- coding: utf-8 -*- #****************************************************************# # ScriptName: test.py # Author: # Create Date: 2014-03-07 # Modify Author: # Modify Date: 2014-03-07 # Function: #***************************************************************# import execs import random de...
from .auth import require from .common import CommonController import cherrypy import simplejson class Table(CommonController): _cp_config = { 'tools.sessions.on': True, 'tools.auth.on': True } @cherrypy.expose @require() def list(self): table=self.model.get_list() data=dict(module_tem...
""" This script is used to test the performance between DES and AES. The requirement library includes numpy, pycrypto, and matplotlib """ import os import time import numpy as np import matplotlib.pyplot as plt from Crypto.Cipher import AES from Crypto.Cipher import DES from des_algorithm import * # import my des alg...
from django.db import models from accounts.models import User from cmdb.models.base import IDC from cmdb.models.asset import Server, NetDevice class CPU(models.Model): # Intel(R) Xeon(R) Gold 5118 CPU @ 2.30GHz version = models.CharField('型号版本', max_length=100, unique=True) speed = models.PositiveSmallInt...
# -*- coding: utf-8 -*- import serial import time ser = serial.Serial('/dev/ttyUSB1', 9600) def SringRead(): string=ser.readline() return string def StringWrite(string): ser.write(string) def main(): while(1): var = input("Enter string: ") if not var: continue StringWrite(var) ...
from psychopy import parallel, core, event import os, sys, inspect import GlobalVariables try{ import readPort } except { try{ # use this if you want to include modules from a subfolder cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"sub...
#!/usr/bin/python3 # -*- coding:utf-8 -*- """ @author: tianwen @file: 累加.py @time: 2020/8/14 9:06 @desc: """ # 第一种算法,运算速度慢于第二种,特别是在运行大量运算时 def func(n): thesum = 0 for i in range(n + 1): thesum += i return thesum print(func(100)) # 第二种算法,比第一种运算速度快 def fun(n): for x in range(n + 1): ...
def move( n, x, y, z): #将n个盘子从x借助y移动到z if 1 == n : print(x,"-->",z) else : mo...
import requests import os import json from py2neo import authenticate, Graph import sys if __name__ == "__main__": # member_id = "19057581" member_id = sys.argv[1] key = os.environ['MEETUP_API_KEY'] uri = "https://api.meetup.com/2/groups?lat=51.5072&lon=0.1275&member_id={0}&key={1}".format(member_id,...
import json from django.contrib.auth import authenticate from django.core.exceptions import ObjectDoesNotExist from django.http import HttpResponse from django.utils import timezone from rest_framework import permissions, status, generics from rest_framework.response import Response from rest_framework.views import AP...
from credentials import mongodb_key from pymongo import MongoClient from datetime import datetime, timedelta import pandas as pd # Set db access db_client = MongoClient(f"mongodb+srv://{mongodb_key.username}:{mongodb_key.password}@clusterk.su3fg.azure.mongodb.net/<dbname>?ssl=true&ssl_cert_reqs=CERT_NONE&retryWrites=...
#!/usr/bin/python3 -u import argparse import os import numpy as np import os.path as op import pandas as pd from utils_wgbs import validate_files_list from multiprocessing import Pool from os.path import splitext, basename import sys from utils_wgbs import load_beta_data, trim_to_uint8, default_blocks_path, eprint d...
from pwn import * context.log_level = 'debug' #p = process('./bjdctf_2020_babystack') p = remote('node3.buuoj.cn',27983) backdoor_addr = 0x4006e6 ret_addr = 0x400561 p.recvuntil('name:\n') payload = b'a' * ( 0x10 + 8 ) + p64(ret_addr) + p64(backdoor_addr) p.sendline(str(len(payload))) p.recvuntil('name?\n') p.se...
# Adapted for numpy/ma/cdms2 by convertcdms.py import cdms2 as cdms, MV2 as MV, genutil import sys import cdat_info pth=cdat_info.get_prefix()+'/sample_data/' files = [ pth+'u_2000.nc', pth+'u_2001.nc', pth+'u_2002.nc', ] for file in files: f=cdms.open(file) u=f('u') if...
numero = int(input("Dígame cuántas palabras tiene la primera lista: ")) if numero < 1: print("¡Imposible!") else: primera = [] for i in range(numero): print("Dígame la palabra", str(i + 1) + ": ", end="") palabra = input() primera += [palabra] print("La primera lista es:", prime...
from graphframes import GraphFrame # Need a dataset of edges and nodes def get_graph(orig_df, predictions, orig_df_id_col="row_id", predictions_id_col="id"): predictions_nodes = orig_df.withColumnRenamed(orig_df_id_col, "id") predictions_edges = predictions.withColumnRenamed(f"{predictions_id_col}_l", "src"...