text
stringlengths
8
6.05M
# Create your views here. from django.template import RequestContext from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User, Group, Pe...
import numpy as np #import theano #import theano.Tensor as T import time th_zero = [0, 90, -90, 0, 180, -180] L = [10.0, 105.0, -28.0, 110.0, -20.0, 28.0, 150.0] #th = [-10, -27, 47, 63, -20, 5] #th = [0,-20,0,30,0,90] #th = [ -96, -75, -34, -27, 21, 206] #th = [ -96.07351766, -74.89197776, -34....
from django.db import models from django.contrib.auth import authenticate,login,logout from django.contrib.auth.models import AbstractUser # Create your models here. class UserProfile(AbstractUser): nick_name = models.CharField(max_length=20,null=True) mobile =models.CharField(max_length=11,unique=True) ...
import dash_bootstrap_components as dbc from dash import html nav_contents = [ dbc.NavItem(dbc.NavLink("Active", href="#", active=True)), dbc.NavItem(dbc.NavLink("A much longer link label", href="#")), dbc.NavItem(dbc.NavLink("Link", href="#")), ] nav1 = dbc.Nav(nav_contents, pills=True, fill=True) nav2 ...
import os import shutil import unittest from pathlib import Path from patchworkdocker.modifiers import copy_file, apply_patch from patchworkdocker.tests._common import TestWithTempFiles _RESOURCES_LOCATION = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources") _EXAMPLE_FILE_NAME = "test-file" _EXAMP...
### This middleware will set a variable, request.site ### to reference the current Site for the given request. from django.contrib.sites.models import Site, SiteManager from django.conf import settings import re ignore_www_zone = getattr(settings, 'IGNORE_WWW_ZONE', True) ignore_server_port = getattr(settings, 'IGNOR...
def carpIkiEkle(x, y): sonuc = x * y + 2 return sonuc def carpUcEkle(x, y): sonuc = x * y + 3 return sonuc sayi = carpIkiEkle(3, 5) print(sayi) print(carpUcEkle(3, 5))
import pymysql import os MONKEYPATCH_PYMYSQL_CONNECTION = True def monkeypatch_pymysql_connection(): Connection = pymysql.connections.Connection def enter_patch(self): return self def exit_patch(self, exc, value, traceback): try: self.rollback() # Implicit rollback when co...
""" CCT 建模优化代码 A21 Baseutils 示例 作者:赵润晓 日期:2021年5月2日 """ from os import error, path import sys sys.path.append(path.dirname(path.abspath(path.dirname(__file__)))) from cctpy import * # Baseutils 工具类,提供了很多实用的方法 # 函数 equal() # 可以用来判断两个数是否相等 print(BaseUtils.equal(1, 1)) # True print(BaseUtils.equal(1, 2)) # False ...
from django.conf.urls import patterns, url from views import delete, index urlpatterns = patterns('boxer.views', url(r'^delete/$', delete, name="delete"), url(r'^$', index, name="index"), )
from twisted.internet.defer import inlineCallbacks from autobahn.twisted.wamp import ApplicationSession from autobahn import wamp from model.serializer.ditesiSerializer import JSONSerializable #from model.serializer import ditesiSerializer #ditesiSerializer.register() class TestSer(JSONSerializable): def __init...
#!/usr/bin/python __author__ = 'Elisabetta Ronchieri' import sys import unittest import getopt from tstorm.utils import report_file from tstorm.utils import settings from tstorm.utils import sequence from tstorm.utils import release from tstorm.utils import range from tstorm.utils import limit from tstorm.utils im...
# A friendly note from the author: # # I wrote this implementation of merge sort as an # exercise. Please use a library function for your # real-world sorting needs. def merge(left, right): leftlen = len(left) rightlen = len(right) iLeft = 0 iRight = 0 result = [0 for i in range(0,leftlen+rightlen...
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-07-07 18:34 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mealplanner', '0006_auto_20160606_1911'), ] operations = [ migrations.AlterF...
import re from collections import Counter file = open('URL_String.txt', "r") Url_text = file.readlines() text_blob = [] for i in range(len(Url_text)): if 1==1: text_blob = text_blob +re.split(r'[^a-zA-Z]+', Url_text[i].strip().lower()) print i #print text_blob text_file = open("URL_String_Freq.txt", "w") w...
'''' 面向对象 程序 现实中 对象 具体的事务 现实中的实物---转化为程序 ====面向对象 好处: 面向对象: 类 对象 属性 方法 对象: 小明的手机 小红的手机 小妹的手机 。。。 对象的集合 ---共同的特征:品牌, 颜色,大小,价格 动作:打电话, 发短信,上网 类别:手机类 对象里面包含属性(特征)和方法(动作) 多个对象----提取共同的属性和方法---封装成一个类 ''' # 所有的类名首字母大写,多个单词使用驼峰命名法 # 所有的类都默认继承object ...
import json import datetime from .types import Artifact, Publication, Collection, Universe # serialization # -------------------------------------------------------------------------------------- def serialize(node): """Serialize the universe/collection/publication/artifact to JSON. Parameters -------...
import pandas as pd def function_Save_Data_Matrix_into_CSV(data_matrix, Path): data_matrix_df = pd.DataFrame(data_matrix) data_matrix_df.to_csv(Path, header=False, index=False) return
import re rawdata = [] with open("input.txt") as f: rawdata = f.readlines() rawdata = [n.strip() for n in rawdata] data = {} for line in rawdata: newline = line.split(" contain ") newline = [re.sub(" *bags* *", "", n).strip(".") for n in newline] # Make this a dictionary data[newline[0]] = [n.stri...
import queue pages = int(input()) graph = {} for p in range(pages): root = input() buffer = [] while True: l = input() if l == '</HTML>': break while '<A HREF=' in l: url = l[l.index('<A HREF=') + 9: l.index('<A HREF=') + l[l.index('<A HREF='):].index('">')] print('Link from %s to %s' % (root,...
""" QS 硬边磁铁 """ from typing import List, Tuple import numpy as np from cctpy.abstract_classes import Magnet, Plotable, LocalCoordinateSystem from cctpy.constant import ZERO3 class QsHardEdgeMagnet(Magnet, Plotable): """ 硬边 QS 磁铁,由以下参数完全确定: length 磁铁长度 / m gradient 四极场梯度 / Tm-1 second_gradient 六...
import requests from urllib.request import urlopen from bs4 import BeautifulSoup from pymongo import MongoClient client = MongoClient('localhost', 27017) db = client.dbsparta def get_detail_info(url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko...
matriz = [] for i in range(3): linha = [] for j in range(3): linha.append(int(input('Digite a nota ['+ str(i) + ',' + str(j) + ']: '))) matriz.append(linha) #contar pares pares = 0 for linha in matriz: for valor in linha: if valor % 2 == 0: pares = pares + 1 #imprimir em form...
from simpleparse.common import numbers, strings, comments from simpleparse import generator from simpleparse.parser import Parser from simpleparse.dispatchprocessor import * import collections, re from .Factor import Factor from .Faresystem import Faresystem from .Linki import Linki from .Logger import WranglerLogger f...
import cgi import os import wsgiref.handlers import os from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db from google.appengine.api import mail #Go...
import boto3 def get_bucket_list(): """ returns the buckets names """ regions = 0 client = boto3.client('s3') # get bucket names from list bucket_list_full_info = client.list_buckets() bucket_list_dict = bucket_list_full_info['Buckets'] bucket_list = [] for i in bucket_list_dic...
from sys import stdin def main(): case = 1 while True: n, m = map(lambda x: int(x), stdin.readline().split()) if n == 0: break names = [] distance = [[1000 for j in range(n)] for i in range(n)] for x in range(n): distance[x][x] = 0 for x in range(n): names.append(stdin.readline().strip()) for ...
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pants.backend.codegen.protobuf.protoc import Protoc from pants.engine.rules import collect_rules, rule from pants.engine.target import ( COMMON_TARGET_FIELDS, AllTargets, ...
'''' George Alromhin gr.858301 example of deep learning with a library Keras.. https://keras.com/ Documentation library for charting Matplotlib.. https://matplotlib.org/ Documentation of tensorflow https://www.tensorflow.org/install/pip OF. PIP site .. https://pypi.org/project/pip/ ''' import tensorflow as tf im...
#!/usr/bin/env python # # Copyright (c) 2019 Opticks Team. All Rights Reserved. # # This file is part of Opticks # (see https://bitbucket.org/simoncblyth/opticks). # # 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...
# Generated by Django 3.0.7 on 2020-08-17 18:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('staff', '0002_staff_status'), ] operations = [ migrations.AddField( model_name='staff', name='comment', ...
from enum import Enum from warnings import warn import torch from ..extension import _load_library from ..utils import _log_api_usage_once try: _load_library("image") except (ImportError, OSError) as e: warn( f"Failed to load image Python extension: '{e}'" f"If you don't plan on using image ...
import plotly.express as px dark_blue = "rgb(40, 60, 70)" light_blue = "rgb(200, 230, 250)" plot_background_blue = "rgb(240, 250, 255)" transparent = "rgba(255, 255, 255, 0)" def get_rubicon_colorscale(num_colors, low=0.33): if num_colors < 2: num_colors = 2 return px.colors.sample_colorscale( ...
#! /usr/bin/env/python3 """A simple script used to detect the presence of an ARP spoofing attack. Uses Python 3""" import scapy.all as scapy def get_mac(ip): """Returns target MAC address""" arp_request = scapy.ARP(pdst=ip) broadcast = scapy.Ether(dst='ff:ff:ff:ff:ff:ff') arp_request_broadcast = b...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import torch from torch.jit import script, trace import torch.nn as nn from torch import optim import torch.nn.functional as F import csv import random import...
# Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. # This file contains a set of utilities functions used by other Python-based # scripts. from __future__ i...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-04-11 15:49:07 # @Author : Fallen (xdd043@qq.com) # @Link : https://github.com/fallencrasher/python-learning # @Version : $Id$ data_list = [] def func(arg): return data_list.insert(0,arg) data = func("hhhh") print(data) print(data_list) def func...
import sys import os import warnings import pandas as pd import numpy as np from datetime import datetime from datetime import date from datetime import timedelta import math import copy from scipy.optimize import minimize sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) warnings.f...
import os import numpy as np import pandas as pd from modisco.hit_scoring import densityadapted_hitscoring from modisco.util import compute_per_position_ic import chrombpnet.evaluation.invivo_footprints.run_tfmodisco as run_tfmodisco import click def import_tfmodisco_hits(hits_bed): """ Imports the TF-MoDISco ...
from django.db import models class Player(models.Model): cID = models.CharField(max_length = 20) password = models.CharField(max_length = 20) Room = models.IntegerField (default = 0) class Room(models.Model): num = models.AutoField(primary_key =True) User0 = models.CharField(max_length = 20, defau...
import numpy as np from matplotlib import pyplot as plt # This generates 100 variables that could possibly be assigned to 5 clusters n_variables = 100 n_clusters = 5 n_samples = 1000 # To keep this example simple, each cluster will have a fixed size cluster_size = n_variables / n_clusters # Assign each variable to a...
import csv import time import mandb ''' CREATE TABLE timu_1( temp_id INT UNSIGNED AUTO_INCREMENT,/* 主(不可重复) 临时id */ njtype varchar(50) NOT NULL,/* 年级类型 */ tmtype varchar(500) NOT NULL,/* 题目类型 */ urls varchar(500) NOT NULL,/* 数据源链接 */ tmdata TEXT NOT NULL,/* 题目文本 */ daandata TEXT NOT NULL,/* 题目答案 */ jiexi TEXT...
import os import dmenu import pyimgur def upload(): client_id = "8e98531fa1631f6" PATH = "/tmp/screenshot.png" im = pyimgur.Imgur(client_id) uploaded_image = im.upload_image(PATH, title="Uploaded with PyImgur") print(uploaded_image.link) os.system("rm /tmp/screenshot.png") def save_local(): save_name = dmenu.s...
__author__ = 'tyerq' def schema(): return """ posts: permalink == _id author == nickname posted topic text comments == [ comment: author == nickname posted text ... ] tags == [ tag ... ] users: use...
# coding:utf-8 # 面向对象编程 # 定义一个Student类,这个类拥有name和score两个属性Property。 class Student(object): def __init__(self, name, score): self.name = name self.score = score def print_score(self): """打印一个学生的成绩""" print("%s: %s" % (self.name, self.score)) Tom = Student("Tom", 85) Jim = St...
def introduce(): print("Hello, I'm Attila!") def add(a, b): return a + b def joke(): print("LOL") def shout(): print("KEK")
# # @lc app=leetcode.cn id=102 lang=python3 # # [102] 二叉树的层序遍历 # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def levelOrder(self, root...
# -*- coding: utf-8 -*- """ Created on Thu Jan 25 14:28:12 2018 @author: XuL """ import random from pathlib import Path import spacy import en_core_web_md as spacyEn TRAIN_DATA = [ ('Choudries Inc. Super Seven Food Mart filed for Chapter 11 bankruptcy protection Bankr. M.D. Pa. Case No. 16-02475 on June 13, 20...
from django.db import models class QuestionBank(models.Model): bank_name = models.CharField(max_length=20, verbose_name='题库名') question_num = models.IntegerField(verbose_name='题号') question_name = models.CharField(max_length=300, verbose_name='题目') @staticmethod def get_question(bank_name, qu...
import os import sys sys.path.insert(0, 'tools/msa_edition') import remove_empty_sequences is_dna = True def extract_msa(s, curs, max_curs, writer): while (curs < max_curs and curs != 0): end_species = s.find("\t", curs) species = s[curs: end_species] curs_seq = end_species + 1 end_seq = s.find("\n...
nums = sorted(list(map(int,input().split()))) ans = 0 if (nums[1] - nums[0]) % 2 == 1: nums[0] += 1 nums[2] += 1 ans += 1 while nums[0] != nums[1]: nums[0] += 2 ans += 1 while nums[0] != nums[2]: nums[0] += 1 nums[1] += 1 ans += 1 print(ans)
""" -- Refactor the dataloader for Squirrel """ import math import random import numpy as np import torch from torchtext.data.batch import Batch # from squirrel.data.noise import merged_noisy_generator class DistributedBatch(Batch): def __init__(self, data=None, dataset=None, ...
# Generated by Django 2.2 on 2020-10-23 18:36 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Profile', fields=[ ('id', models.AutoField(au...
from ixnetwork_restpy import SessionAssistant from ixnetwork_restpy import TestPlatform import time import pprint #sw-ixia3.insieme.local is 172.31.194.141 session_assistant = SessionAssistant(IpAddress='172.31.194.141', LogLevel=SessionAssistant.LOGLEVEL_INFO, ClearConfig=True) ixnetwork = session_assista...
#!/usr/bin/env python3 import argparse import serial import time from time import sleep import datetime from tqdm import tqdm import os parser = argparse.ArgumentParser() parser.add_argument('port') parser.add_argument('--clear', type=int, default=1) args = parser.parse_args() class Controller: def __init__(self,...
from traceback import format_exc import click from lib import Validator, RuleDoesNotExist, RuleCannotBeParsed, FileNewLineError @click.group(invoke_without_command=True) @click.option('--rules', type=click.Path(exists=True), default='rules.json') @click.option('--rules-string', type=click.STRING) @click.argument('c...
from django.shortcuts import render, HttpResponse,redirect from django.http import JsonResponse def root(request): return redirect("/blog") #/blogs - display the string "placeholder to later display a list of all blogs" with a method named "index" def index(request): return HttpResponse("placeholder to la...
from pymol import cmd cmd.load("1r_final.pdb") cmd.hide("lines") cmd.show("cartoon") cmd.set("cartoon_fancy_helices", 1) cmd.set("ray_trace_mode", 1) cmd.set("two_sided_lighting", "on") cmd.set("reflect", 0) cmd.set("ambient", 0.5) cmd.set("ray_trace_mode", 0) cmd.set('''ray_opaque_background''', '''off''') inFile ...
def omit_hashtag(message, hashtag): return message.replace(hashtag, "", 1) ''' The local transport authority is organizing an online picture contest. Participants must take pictures of transport means in an original way, and then post the picture on Instagram using a specific hashtag. The local transport authorit...
#Program to calculate the exponentials. base=input("Enter the base value : ") ex=input("Enter exponent : ") p=1 for i in range(1,ex+1,1): p=p*base print base,"raised to exponent",ex," = ",p
''' The application. ''' import os from flask import Flask ASYNC_MODE = 'threading' PING_INTERVAL = 59 # Create and configure application app = Flask(__name__) app.config['SECRET_KEY'] = os.getenv('FLASK_SECRET_KEY') app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('SQLALCHEMY_DATABASE_URI') app.config['SQLALCHEMY...
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: Stephanie # # Created: 08/03/2015 # Copyright: (c) Stephanie 2015 # Licence: <your licence> #------------------------------------------------------------------------------- impor...
import types from openerp import models, fields, api, _ class DocumentTemplateFunctionJinja(models.Model): _inherit = 'document.template.function' is_filter = fields.Boolean('Is Filter') is_test = fields.Boolean('Is Test') is_function = fields.Boolean('Is Function') @api.one @api.constrains(...
import RPi.GPIO as GPIO from influxdb import InfluxDBClient from datetime import datetime,time from time import sleep from pytz import timezone import logging,pdb '''initial var''' RELAIS_4_GPIO = 22 sleep_time = 600 influxdb_user = 'pippo' influxdb_password = 'pippopassword' influxdb_db = 'LIGHT' influxdb_host = 'loc...
""" leg @ rig """ import maya.cmds as mc from .. base import module from .. base import control from ..utils import joint from ..utils import name from cmath import polar def build( legJoints, topToeJoints, pvLocator, scapJoint = '', prefix = 'lf_leg', rigScale = 1.0, ...
import sys sys.path.insert(1, '/home/jimmy/ctf/tools') from base64 import b64encode, b64decode from cryptotools import * # token we want to forge: king-horse-5diuoe7tpxjen8xu0n7 print(len('king-horse-5diuoe7tpxjen8xu0n7')) # need something of length 30 then we need something close so we can flip the right area # t...
from tkinter import * from tasks import * import json f=open("tasks.json","w") f.write("") f.close() window = Tk() window.title("Welcome to Repl.it") window.geometry('350x200') lbl = Label(window, text="Empty") lbl.grid(column=0, row=1) txt = Entry(window,width=10) txt.grid(column=1, row=0) def clicked(): creat...
from unittest import test from notes import * test(29, greet("Jeremy"))
# Generated by Django 2.1.5 on 2019-02-08 04:20 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('books', '0010_auto_20190202_2240'), ('orders', '0003_offer'), ] operations = [ migrations.RenameMod...
import fournisseur class Concessionnaire: def __init__(self, lieu, nbEmployes, nbVoiture, voitureDispo): self.adresse = lieu self.nombreEmployes = nbEmployes self.nombreVoiture = nbVoiture self.voitureDisponible = voitureDispo concessionnaire = Concessionnaire("France", 10, 30, fourn...
import _thread import time def fun1(tread_name,delay): print('开始运行fun1,线程的名字:',tread_name) time.sleep(delay) print('fun1结束运行') def fun2(tread_name,delay): print('开始运行fun2,线程的名字:',tread_name) time.sleep(delay) print('fun2结束运行') if __name__=='__main__': print('开始运行') _thread.start_new_thre...
import seaborn as sns import matplotlib.pyplot as plt iris=sns.load_dataset("iris") print(iris.head()) print(iris.shape) print(iris.describe()) print(sns.jointplot(x="sepal_length", y="sepal_width",data=iris)) plt.show() print(sns.pairplot(iris)) plt.show(0)
#Program to print the longest string def longest_string(s): a = s.split(" ") max=0 for i in a: l = len(i) if l > max: max = l for i in a: if len(i) == max: print(i) longest_string ("Shape of you Xp")
#!/usr/bin/python import os import sys sys.path.append("/home/penguinofdoom") sys.path.append("/home/penguinofdoom/Projects") sys.path.append("/home/penguinofdoom/Projects/Retina") import time import random as rnd import commands as comm import itertools import numpy as np import MultiNEAT as NEAT import multiprocessi...
# 232. Implement Queue using Stacks class MyQueue: def __init__(self): """ Initialize your data structure here. """ self.__queue1 = [] self.__queue2 = [] def push(self, x): """ Push element x to the back of queue. :type x: int :rtype: vo...
import random from collections import defaultdict import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages import numpy as np from keras import backend as K from keras.models import Model from scipy.misc import imsave # util function to convert a tensor into a valid image def deprocess_ima...
import tokens # ############### from telegram.ext import Updater, MessageHandler, Filters def messageFilter(update, context):#This can filter messages print("Hi") def send_message(my_text): dp.bot.send_message(chat_id=my_telegram_id, text=my_text) my_telegram_id = tokens.get_my_telegram_id() telegram_token ...
""" Для чисел в пределах от 20 до 240 найти числа, кратные 20 или 21. Необходимо решить задание в одну строку. """ result = [itm for itm in range(20,240) if itm % 20 == 0 or itm % 21 == 0] print(result)
def print_sub(): print("Printed form sub script folder")
#!/usr/bin/env python import unittest from useless.decorators import nocase __author__ = 'Ronie Martinez' class NoCaseTest(unittest.TestCase): def test_call_inexistent_snake_case(self): @nocase class MyClass(object): def myMethod(self): return "myMethod" a = ...
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> #I pledge my honor that I have abided by the Stevens Honor System >>> #this code gives the uder a list of menus to choose from >>> def main(): firs...
import json import yaml import re PEERPEM = "crypto-config/peerOrganizations/org%d.example.com/tlsca/tlsca.org%d.example.com-cert.pem" CAPEM="crypto-config/peerOrganizations/org%d.example.com/ca/ca.org%d.example.com-cert.pem" class JSONObject: def toJSON(self): return json.dumps(self, default=l...
n=2 primo=1 while primo!=10002: for i in range(2,n): if n%i==0: break else: print(n) primo+=1 n+=1
# 这一节我们使用tfrecord来实现读取数据 import tensorflow as tf tfrecord_dir = "./Dataset/tfrecord/" IMAGENET_MEAN = tf.constant([123.68, 116.779, 103.939], dtype=tf.float32) NUM_CLASSES = 9 # 数据集类别数用于生成one_hot数据 #########生成feature方法########## def _tf_record_parser(record): keys_to_features = { 'data': tf.Fix...
#!/usr/bin/python import random maxNum = 1000000 # The array that is to be sorted arr = [int(maxNum * random.random()) for i in range(10000)] def merge(listA, listB): listReturn = [] while len(listA) > 0 or len(listB) > 0: if len(listA) == 0: listReturn.extend(listB) listB.cle...
import pandas as pd import os import numpy import csv import pycountry import re import time from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By def close_overlay(...
from cs_plone3_theme import Plone3Theme class BootstrapTheme(Plone3Theme): _template_dir = 'templates/bootstrap_theme' summary = 'A Theme for Plone 3/4 based on Twitter Bootstrap' skinbase = 'Bootstrap Theme' use_local_commands = True def post(self, command, output_dir, vars): print "-----...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sqlite3, os from PyQt5.QtCore import pyqtSignal from shutil import copyfile from io import StringIO from progressWidget import * class database(): ''' Do the SQL things ''' def __init__(self): self.dataPath = "./data/pyzik.db" ...
import cv2 img=cv2.imread("/home/anshul/Desktop/obama.jpg") #resized=cv2.resize(img, (600,600)) resized=cv2.resize(img,(int(img.shape[1]*5),int(img.shape[0]*2))) cv2.imshow("legend",resized) cv2.waitKey(2000) cv2.destroyAllWindows()
import liblo, sys class Manta(object): def __init__(self, receive_port=8000, send_port=8001, send_address='127.0.0.1'): self.osc_server = liblo.Server(receive_port) self.osc_target = liblo.Address(send_port) def send_osc(self, path, *args): #liblo.send(self.osc_target, *args) ...
#!/usr/bin/env python def inventory_mikrotik_system_health(info): if info: return [('', None)] else: return None def check_mikrotik_system_health(item, _no_params, info): for voltage, temp, cputemp, powercons, current, cpufreq in info: perfdata = [] summary = '' i...
from .test_thoriumcorp_lab import suite
# Unordered Unique Items numbers1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 9} numbers2 = {1, 5, 9} numbers3 = {1, 2, 3, 4, 5} numbers1_bkp = numbers1.copy() print(numbers1) # Methods # clear() numbers3.clear() # Clear the sets print(numbers3) # difference() result = numbers1.difference(numbers2) # Difference from set1 to...
from flask import Flask, render_template, request from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression from sklearn.externals import joblib import re import string app = Flask(__name__) @app.route("/",...
from __future__ import division import iotbx.pdb import sys import os import itertools def get_prev_rsd_flip_occs(rg): co_angles = [] o_occs = {} altlocs = set() for ag in rg.atom_groups(): altlocs.add(ag.altloc) for altloc_pair in itertools.combinations(altlocs, 2): if " " in altloc_pair or "" ...
class Queue: def __init__(self): self.queue = [] def enqueue(self,value): self.queue.append(value) def dequeue(self): self.queue.pop() def display(self): print(self.queue) a = Queue() a.enqueue(5) a.enqueue(10) a.enqueue(15) a.display() a.dequeue() a.disp...
# -*- coding: utf-8 -*- from datetime import datetime try: # noinspection PyUnresolvedReferences from django.core.exceptions import ImproperlyConfigured # noinspection PyUnresolvedReferences from django.utils import timezone def now(): try: return timezone.now() except...
# -*- coding: utf-8 -*- ############################################################################# # Copyright Vlad Popovici <popovici@bioxlab.org> # # 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 ...
import Adafruit_DHT import time import datetime # Example using a Raspberry Pi with DHT sensor # connected to GPIO23. pin = 4 sensor = Adafruit_DHT.DHT22 def get_date_time(): v = datetime.datetime.now() my_date='{}/{}/{}'.format(v.month,v.day,v.year) my_time = '{}:{}:{}'.format(v.hour,v.minute,v.secon...
import telebot import datetime bot = telebot.TeleBot('830999920:AAFyyAO5ZIJ7sYQFJGQA9QmF201KWnObHNc') global_bots = 0 TIMES_WAKE_UP = 2 @bot.message_handler(content_types=['text']) def get_text_messages(message): global global_bots global TIMES_WAKE_UP global_bots +=1 now = datetime.datetime.now() ...