text
stringlengths
38
1.54M
from setuptools import setup, find_packages setup( name='Canvas', version='0.1.0', description='', long_description='', author='Robert Cudmore', author_email='robert.cudmore@gmail.com', url='https://github.com/cudmore/bImPy', keywords=['in vivo', 'two photon', 'laser scanning microscopy'], packages=f...
import logging import subprocess logger = logging.getLogger() def compile_video(photos_dir, output_filename, photos_per_second=4, photos_extension=None): photos_extension = 'png' if photos_extension is None else photos_extension logger.info('compiling timelapse (photos per second: {photos_per_second})'.form...
from LinkedList import LinkedList class KthToLastElement: def kthlast(self, k,h): if k > h.length(): return -1 temp = h.head for i in range(h.length()-k): temp = temp.next return temp.data o = LinkedList() o.add(1) o.add(2) o.add(3) o.add(4) o.add(5) o.add...
def main(): num =int(input()) for i in range(2,num+2): for j in range(1,i): print(j,end=" ") print() if (__name__=="__main__"): main()
import tkinter from tkinter import messagebox from tkinter.ttk import Combobox from vanderpolgenerator import VanDerPolGenerator from plot import Plot import re import sys class GUI(tkinter.Tk): def __init__(self,): tkinter.Tk.__init__(self) self.title('Van der Pol Generator Visualizer v1.0') ...
# -*- coding: utf-8 -*- """ lantz.ui.scan ~~~~~~~~~~~~~ A Scan frontend and Backend. Requires scan.ui :copyright: 2015 by Lantz Authors, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import time import math from enum import IntEnum from lantz.utils.qt import QtC...
# -*- coding: utf-8 -*- # Generated by Django 1.11.24 on 2020-01-29 12:51 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('favourites', '0002_auto_20200123_1700'), ] operations = [ migrations.Alter...
# print("Ahmeeada".strip("A")) # imelde="more mayhem","Imelda May","2011",((1,"pulling the Rug"),(2,"psycho"),(3,"mayhem"),(4,"Kentisch town waltz")) # print(imelde) # with open("imelda3txt",'w')as inzwischen: # print(imelde,file=inzwischen) with open("imelda3.txt",'r')as inZwischen: content=inZwischen.readlin...
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import time as tm import datetime as dtm import os mainInDir = "C:/Users/jzhao/Documents/Python Scripts/MS/01_DescriptiveStats/01_Data/" mainTimeStamp = dtm.datetime.fromtimestamp(tm.time()).strftime('%Y.%m.%d.%H.%M.%S') ma...
import json import logging import time from datetime import datetime import requests from influxdb import InfluxDBClient logging.basicConfig(filename="my_app2.log", level=logging.INFO) def return_count(): # Do the request headers = {"Content-Type": "application/json"} url = "https://portal.rockgympro.c...
list1 = [1,2,3,4,5,6] list2 = [9,8,7,6,3,5] len1=len(list1) len2=len(list2) if len1 == len2 : print('both list have equal length') else: print('both list doesnt have equal length')
from math import sqrt def pearson_distance(v1, v2): """ Calculate Pearson Distance between v1 and v2 :param v1: :param v2: :return: float [0,1]. In this case we get close to 0 if items are similar """ # Simple Sums sum1 = sum(v1) sum2 = sum(v2) min_length = min(len(v1), len(v2)...
#!/usr/bin/env python3 """tests for dna.py""" import os import random import re import string from subprocess import getstatusoutput, getoutput prg = './dna.py' # -------------------------------------------------- def test_exists(): """exists""" assert os.path.isfile(prg) # ------------------------------...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import sys import os os.putenv('LANG', 'en_US.UTF-8') os.putenv('LC_ALL', 'en_US.UTF-8') import socket from http.server import BaseHTTPRequestHandler, HTTPServer import time import json import requests import random import cgi from scoreSong import init, scoreMp3 model = i...
from sklearn.tree import DecisionTreeClassifier import numpy as np import tensorflow as tf #내가추가한것 def DecisionTree(csv_path): xy = np.loadtxt(csv_path, delimiter=',', dtype=np.float32) x_train = xy[:, 0:-1] y_train = xy[:, [-1]] x_test = [] x_test.append(x_train[len(x_train) - 1]) x_test ...
import cherrypy from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool from ws4py.websocket import EchoWebSocket import atexit # the following 4 lines are suggested in the cherrypy website: # http://tools.cherrypy.org/wiki/ModWSGI cherrypy.config.update({'environment': 'embedded'}) if cherrypy._...
def print_line(char,time): """打印单行分割线 :param char: 分割字符 :param time: 重复次数 """ print(char * time) def print_lines(char,time): """打印多行分割线 :param char: 分割线使用的分割字符 :param time: 分割线重复的次数 """ row = 0 while row <5: print_line(char,time) row += 1 name = "黑马程序员"
from dialog_api import messaging_pb2 from google.protobuf.wrappers_pb2 import StringValue from dialog_bot_sdk.entities.media.ImageMedia import ImageLocation class WebPageMedia: def __init__(self, url: str, title: str = "", description: str = "", image: ImageLocation = None): self.url = url self.t...
from kivy_soil.kb_system.compat_widgets.popup import AppPopup from utils import get_containing_directory, open_directory from utils import seconds_to_minutes_hours from media_info import cache as media_cache from kivy.properties import StringProperty from kivy.uix.boxlayout import BoxLayout from kivy_soil.kb_system imp...
from App import views from django.urls import path #写上app_name app_name = 'App01' urlpatterns = [ path('login/',views.login,name='login'), path('mark/',views.reply,name='mark'), path('home/',views.index,name='home'), path('logout/',views.logout,name='logout'), ]
import os import matplotlib.pyplot as plt files = os.listdir("../../datasets/UTKFace-curated/") # -curated print("Total files: "+str(len(files))) gender_count = [0, 0] ethnicity_count = [0, 0, 0, 0, 0] age_count = [0 for col in range(120)] for f in files: tmp = f.split("_") if len(tmp)!=4: continue age_count[int(t...
""" 在构建好的规则Trie树中,找出query所有可以匹配的组合 """ import config from items import * from post_handle import apply_post, get_idx_slot, trans_by_post class Searcher: """ rule_trie: 编译好的Trie树类 rule_info: 规则的全局信息,后处理,搜索配置等 ac_machie: 词典和关键字的AC自动机 """ def __init__(self, rule_trie, rule_info, ...
-X FMLP -Q 0 -L 2 97 400 -X FMLP -Q 0 -L 2 95 400 -X FMLP -Q 0 -L 2 89 400 -X FMLP -Q 0 -L 2 82 250 -X FMLP -Q 0 -L 2 56 175 -X FMLP -Q 1 -L 1 45 200 -X FMLP -Q 1 -L 1 42 300 -X FMLP -Q 1 -L 1 39 400 -X FMLP -Q 1 -L 1 36 400 -X FMLP -Q 2 -L 1 32 250 -X FMLP -Q 2 -L 1 31 400 -X FMLP -Q ...
# Write a function solve_3SAT using the search-tree technique outlined # below that takes as its input a 3-SAT instance (see Problem Set 2), # applies pre-processing (see Problem Set 4), and then uses a search tree # to find if the given instance has a satisfying assignment. Your function # should return None if the gi...
''' Author: Jane Wharton Company: Geek Sources, Inc. diction.py: This module is designed to analyze the diction of a text and return a value representing its "uniqueness" or how common the words it contains are when compared against the databases stored in the wordfreq library. Exampl...
# -*- coding: utf-8 -*- """ Created on Tue Jan 12 15:05:57 2021 @author: useren """ import logging from aiogram import Bot, executor, types from aiogram.dispatcher import Dispatcher #from aiogram.dispatcher.webhook import SendMessage from aiogram.contrib.middlewares.logging import LoggingMiddleware from aiogram.utils...
from astropy.io import ascii import numpy as np #rc3=ascii.read("/Users/dhk/work/cat/NGC_IC/myrc3.dat") irac1_gals=[] cnt=0 for x in range(0,14): data=ascii.read("/Users/dhk/work/cat/NGC_IC/SHA_mosaic_quarry_result_%d.tbl" % (x),format='ipac') tmp="" for y in range(0,len(data)): if data[y][10] == 'IRAC1': # if ...
import networkx as nx import community import numpy as np import pyrebase from flask import * import json #import firebase_admin #from firebase_admin import credentials #cred = credentials.Certificate("key.json") #firebase_admin.initialize_app(cred) config = { "apiKey": "AIzaSyA7N3W1eqC00CnLi4KZtIly-z5PD3fWDDo", ...
class MissingColumnAssembler: def populate(self, dto): result = {} for table in dto.sourceTables: if table in dto.excludedTables: continue if table in dto.missingTables: continue sourceColumns = dto.sourceInspector.get_columns...
import time import serial class LockBox(object): def __init__(self,comPort='com13'): try: self.ser = ser = serial.Serial() ser.port = comPort ser.timeout = 5 ser.setDTR(False) ser.open() except serial.serialutil.SerialException: #no serial connection self.ser = None else: ...
import time import math import statistics as stats import market.parser as parser ''' @summary: This method goes through every symbols and obtains the following indicators for the time period and interval: Beta, Sharpe ratio, year low, year high, ... @param symbolsList: An array of symbols i.e. ['BB.TO', 'SIO.V', ...
alpha = 9 print("a= ",alpha) beta = alpha + 10 alpha = 4 charlie = 23 + beta alpha = 70 print("a= ",alpha) print("beta: ", beta) print(charlie) exit
#!/usr/bin/env python # -*- coding: utf-8 -*- """ """ from __future__ import absolute_import import ast import os import subprocess def check_celery_task_func_def_changed(): result = subprocess.run(["git", "diff", "master", "--name-only"], capture_output=True, text=True) filenames = result.stdout.split('\n'...
''' Advanced Security Lab 2 Jonathan Riordan C13432152 Part 1 Key = -3 Message = "And I shall remain satisfied, and proud to have been the first who has ever enjoyed the fruit of his writings as fully as he could desire; for my desire has been no other than to deliver over to the detestation of mankind th...
from time import sleep from picamera import PiCamera from pynput import keyboard from datetime import datetime TIME_LAPSE = 5 # 5 Seconds between shots TIME_LAPSE_PICTURES = 10 # Number of pictures to snap BURST = 5 #set number of pics to take in burst mode PATH = "/home/pi/Desktop/Picamera/captured/" cam = PiCame...
#!/usr/bin/env python import rospy from std_msgs.msg import String, Empty from geometry_msgs.msg import Twist from sensor_msgs.msg import Joy from drone_control.srv import Mode, ModeResponse class control: survey_mode=False def __init__(self): # In ROS, nodes are uniquely named. If two nodes with t...
#!/usr/bin/env python # coding: utf-8 # In[ ]: ## 아래는 실제 트레인 과정 입니다. # In[1]: import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torch.utils.data import Dataset, DataLoader from torchvision import datasets, transforms import numpy as np ...
import openpyxl import pprint # data = {id_: { # "info": (name_, gender_: xxx, age_: xx}, # date_: tx_, # ... # } # } # ... # } data = {} if __name__ == '__main__': wb = openpyxl.load_workbook('D:\\test.xlsx') for sh in wb:...
n = int(input()) m = input().split() for i in range(n): m[i] = int(m[i]) for i in range(n-1,-1,-1): print(m[i],end=' ')
# encoding: utf-8 ''' https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/g3doc/convert/python_api.md ''' import tensorflow as tf pb_file_path = '../caffe2tensorflow/caffe_fcn8s/' with tf.Session(graph=tf.Graph()) as sess: tf.saved_model.loader.load(sess, ['train'], pb_file_path) sess.run(tf...
import astropy import astropy.io.fits as pyfits import matplotlib import matplotlib.pyplot as plt import scipy import scipy.ndimage import showgalaxy import make_color_image import numpy.random as random import gfs_sublink_utils as gsu import numpy as np import congrid ug_g235h=np.linspace(1.75,2.25,int( (2.25-1.75)/(...
import arcpy from arcpy import env from arcpy.sa import * import pandas as pd import numpy as np import os import time import sys arcpy.env.parallelProcessingFactor = "100%" t0 = time.clock() # Set the environment: arcpy.env.overwriteOutput = True scriptPath = arcpy.GetParameter(0) scriptPat...
def calcula_dominator(A): dados = {} for item in A: if item not in dados: dados[item] = 1 else: dados[item] += 1 tamanho = len(A) // 2 for k,v in dados.items(): if v > tamanho: x = k return x def soluti...
# https://www.hackerrank.com/challenges/the-time-in-words import math import os import random import re import sys # Complete the timeInWords function below. def timeInWords(h, m): if m == 00: return (number(h) +' o\' '+'clock' ) elif 1 <= m <= 30: if m == 15: return ('quarter past...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # python 学习笔记 之 面向对象编程(3) # 获取对象信息 import types # 引入oop2_extends文件 from pkg4_oop import oop2_extends # 快速打印 from util import p # -------------------------type()-------------------------- p(type(123)) # type() 判断对象类型 <class 'int'> p(type(p)) # <class 'function'> p(ty...
from werkzeug.exceptions import BadRequest from flask import jsonify def handle_invalid_usage(error): return jsonify(error.to_dict()), error.status_code class ValidationError(BadRequest): """ When invalid data is sent to via POST or PUT, this exception gets raised :param message: The error message ...
#Encrypted By MAFIA-KILLER #WHATSAPP : +92132197796/DON,T TRY TO EDIT THIS TOOL/ import zlib, base64 exec(zlib.decompress(base64.b64decode("eJztXVtv20iWfk6A/IdqBQmpWKKoq29RFrIjd4y2JW+sJNNtu2lKKlmMeFGTVGxndxtudNDTwF5mM2gkWGAWs+jHfdjHfVsMsD/Fj/sy8xO2isUiixQtyxJlOZ6cODZZrDrn1KlzvjokS6X74IVly+37QNH6hmkDw0pZp1bKVjSYass2dA5M...
from rest_framework import serializers from .models import User, Chat, Message class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class ChatSerializer(serializers.ModelSerializer): users = serializers.PrimaryKeyRelatedField(queryset=User.o...
from ariadne import gql type_defs = gql(""" input CozmoSpeakInput { id: ID! sentence: String! } input RandomAnimationInput { id: ID! } type Query { cozmoSpeak(input: CozmoSpeakInput): String, random_animation(input:RandomAnimationInput): [String] } ...
TEST = False #WARNING: Seeing to False will use LIVE DATA that can incur a cost! Please only set to False when live data tests are needed! For testing data, edit the values in sampleresponse.json instead! TESTRESPONSE = "yWait/sampleresponse.json" from django.db import models from django.contrib.auth.models import Use...
n1 = float(input('Digite a primeira nota: ')) n2 = float(input('Digite a segunda nota: ')) m = (n1+n2) / 2 if m >= 6.0: print('Passou') else: print('Reprovou')
import matplotlib.pyplot as plt import numpy as np import cv2 import copy import argparse from scipy.spatial import Delaunay parser=argparse.ArgumentParser(description='Image Morphing') parser.add_argument('--source', dest='source_image', help="Enter Source Image Path", required=True, type=str) parser.add_argument('--...
import cv2 import os def calc_image_hash(filename): image = cv2.imread(filename) resized = cv2.resize(image, (8, 8), interpolation=cv2.INTER_AREA) gray_image = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY) avg = gray_image.mean() ret, threshold_image = cv2.threshold(gray_image, avg, 255, 0) _hash...
class Classroom: def __init__(self, class_id, name, room, owner_id): self.class_id = class_id self.name = name self.room = room self.owner_id = owner_id def from_json(json): return Classroom(json['id'], json['name'], json['room'], json['ownerId'])
from PIL import ImageGrab, Image from utils import start_timeout, timeout, image_in_another from json import load import dhash class TaskIdentifier: with open("tasks.json") as tkjson: tasks = load(tkjson) @staticmethod def dhash(img: Image) -> int: return int(dhash.format_hex(*dhash.dhas...
import demo if __name__ == '__main__': #min_learning_rate = 0.0001 demo.run(0.0001) for i in range(55, 100): demo.run(float(i)/1000000) #new_err = (demo.run(0.0001) #if (float(new_err) < float(min_err)): #min_err = new_err #min_learning_rate = i #print(min_err) #print(...
#!/usr/bin/env python import mcclear as mc import datetime as dt if __name__=="__main__": date = dt.datetime(2011, 12, 31, 23, 45, 0) m = mc.McClear('mcclear-dhhl6-2010-2011.csv') print(m.data) irr = m.get_irradiance(date) print(irr)
import tkinter as tk from math import * from heapq import heappush, heappop import random import time class Para: def __init__(self, dct={}): self.__dict__.update(dct) g = Para() g.size=700 g.sigma = 1 g.eat_efficiency = .5 g.dt = .5 c = tk.Canvas(width=g.size, height=g.size, highlightthickness=0) c.pack(...
''' Skin management ''' from __future__ import with_statement from wx import Image, BITMAP_TYPE_ANY, BitmapFromImage, GetApp, ImageFromString from path import path from logging import getLogger; log = getLogger('skin') from types import FunctionType from util.data_importer import zipopen from util.primitives import ...
from bs4 import BeautifulSoup import requests headers = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Accept-Language": "zh-CN,zh;q=0.8", "Connection": "close", "Cookie": "_gauges_unique_hour=1; _gauges_unique_day=1; _gauges_unique_month=1; _gauges_unique_ye...
import cv2 import numpy as np import os import argparse import logging import zmq from math import sqrt log_format = '%(created)f:%(levelname)s:%(message)s' logging.basicConfig(level=logging.DEBUG, format=log_format) # log to file filename='example.log', TAG = "square-detector-recog:" def angle(pt1, pt2, pt0): ...
#!/usr/bin/env python3 import sys, re from collections import OrderedDict from math import * from optparse import OptionParser from PIL import Image def jisx0208_to_shiftjis(code): if code >= 0x2121: row = (code >> 8 & 0xFF) - 0x21 col = (code & 0xFF) - 0x20 code -= 0x2121 + row * 161 ...
import os import sys import requests from PyQt5 import uic # Импортируем uic from PyQt5.QtGui import QPixmap from PyQt5.QtWidgets import QApplication, QMainWindow, QLineEdit, QRadioButton, QLabel from PyQt5.QtCore import Qt class MyWidget(QMainWindow): def __init__(self): super().__init__() uic....
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('swimming', '0005_auto_20150329_1702'), ] operations = [ migrations.AddField( model_name='athlete', n...
print("Hello World") diva = "jinyc76" print(diva) str_raw = r"'\r\n\t\s\"" print(str_raw) str_multi = """ this is multi\ line\ message line end add \\ \ shows one line """ print(str_multi) str_multi2 = '''this shows also \ mult...
__author__ = 'hodor' import requests import json import constants def UploadDemo(): response = requests.post(constants.server_url + '/api-token-auth/', {'username': 'evan', 'password' : 'password'}) token = response.json()['token'] header = {} header['Authorization']= 'Token '+ token payload = {}...
import itertools import pygame # Custom modules import colors as c COLORDICT = { 'white': c.WHITE } # GUI parameters BACKGROUND = c.BLACK FPS = 60 FONTNAME = 'Arial' FONTSIZE = 40 CAPTION = 'Reaction time experiment' SCREEN_SIZE = (800, 600) # Session parameters DEFAULT_NAME = 'A_girl_has_no_name' DEFAULT_SESSION ...
""" EnsembleStat: Using Python Embedding ============================================================================= met_tool_wrapper/EnsembleStat/EnsembleStat_python _embedding.conf """ ############################################################################ # Scientific Objective # -------------------- # # T...
from django import forms from .models import TenantDetails class DateInput(forms.DateInput): input_type = 'date' class TenantForm(forms.ModelForm): class Meta: model = TenantDetails fields = [ 'first_name', 'last_name', 'pg_name', 'phone_number', 'email', 'address', 'adhar_img', 'pan_img...
import sys import math def main(argv): maximum = int(argv[0]) markers = [True] * (maximum + 1) for i in xrange(2, int(math.sqrt(maximum)) + 1): if markers[i]: for j in xrange(i ** 2, maximum + 1, i): markers[j] = False primes = [p for p in xrange(2, maximum + 1) ...
from django.db import models from django.contrib.auth.models import User from django_extensions.db.fields import CreationDateTimeField, ModificationDateTimeField from deptx.helpers import generateUUID #from mop.trustmanager import tm_getTotalTrust, tm_getCurrentTrust, tm_getCurrentTrustCredit, tm_getCurrentClearance ...
import json if __name__ == "__main__": dest = open('tokens.py', 'a') sushiswapTokenList = open('sushiswapTokenList.txt', 'r') uniswapDefaultList = open('uniswapDefaultList.txt', 'r') uni = json.loads(uniswapDefaultList.read()) sushi = json.loads(sushiswapTokenList.read()) lists = [uni...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if head==None or head.next==None...
#!/usr/bin/env python import sys import jieba from stemming.porter2 import stem from lucene import VERSION, initVM from java.io import File, StringReader from org.apache.lucene.index import DirectoryReader from org.apache.lucene.analysis.core import SimpleAnalyzer from org.apache.lucene.analysis.standard import Standa...
# This script scrapes KBDI data from http://flame.fl-dof.com/cgi-bin/KbdiArchiveListing.py # Specifically, it grabs all archived reports from that site and saves them as # .csv files locally from bs4 import BeautifulSoup import argparse import urllib2 import re import string as str import os # Helper functions, which...
#funkcja rysujaca graf, przyjmuje liste z listami # nalezy zainsatalowac biblioteke Graphviz 2.38 i dodac .../Graphviz 2.38/bin # do zmiennych srodowiskowych from graphviz import Digraph import os def draw_graph(data): graph = Digraph(comment='Program Dependences Diagram') graph.attr('node', shape='box', style='fill...
# -*- coding: utf-8 -*- # Tower / tirs __author__ = 'Quentin' from grille import * from outils import * # Algo # chaque tour gère son rythme de tir # une tour qui tire : # - cherche sa cible (la plus proche, la plus proche de la sortie, ...) # - cree un tir, l'ajoute à la liste des tirs à suivre. class Tir(): ...
from flask import Blueprint, request, render_template, \ flash, g, session, redirect, url_for from flask.ext.user.signals import user_logged_in, user_registered from flask_user import current_user, login_required import app from app import db from models import User mod_user = Blueprint('user', __n...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import sys from curvefit import * class multicurvefit(curvefit): '''The curve in a loglog plane can be decomposed in several picewise . ''' polys=pd.DataFrame() def __init__(self,x=[],y=[]):# *args, **kwargs): #super...
from Include.PytestFrameWorkApproch.BasePkg.DriverClassModule import SelenumDriver SDriver=SelenumDriver("firefox") import time SDriver.Driver.get("https://learn.letskodeit.com/p/practice") ParentHandle=SDriver.Driver.current_window_handle SDriver.clickElementWithResult('xpath', "//button[@id='openwindow']") handles=SD...
# coding: utf-8 """Helper to support writing Unicode CSV files.""" import codecs import cStringIO import csv import six class UnicodeWriter(object): """CSV writer which supports unicode output. Lifted from https://docs.python.org/2/library/csv.html """ def __init__(self, stream, dialect=csv.excel, ...
from hive.data.transformation.utils import relabel_node_ids, generate_adjacency_matrix, generate_ns from datetime import datetime import pandas as pd import numpy as np import networkx as nx import scipy.sparse as sps import random import torch class Compose(object): def __init__(self, dataset_path, dataset_file,...
# -*- coding: utf8 -*- import os import time import string import random import socket import win32api import win32con import base64 from ftplib import FTP userID = ' ' username = 'test' password = 'test' host = '192.168.194.6' path = './media' remotepath = '/' client_keys = ['01TW5JKD','02YUW8B3'...
# Generated by Django 2.0.5 on 2018-05-18 21:16 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='CreateUsr', fields=[ ('id', models.AutoFiel...
#A simple program to resize the Chars74K dataset to 40x40 images and invert the colours import os from PIL import Image, ImageOps os.chdir(os.path.dirname(os.path.realpath(__file__))) #os.mkdir("Chars74KResized") #Creates a new directory for the files for i in os.listdir("Chars74KResized/"): #os.mkdir("Chars74KResi...
import logging from typing import Optional from pygame import Surface from pygame import draw as pygame_draw from base_object import BaseObject from common import RED from common import TILE_SIZE from tile_objects.base_tile_object import BaseTileObject from tile_objects.units.unit import Unit logger = logging.getLog...
#coding=utf-8 # This file contains Att2in2, AdaAtt, AdaAttMO, TopDown model # AdaAtt is from Knowing When to Look: Adaptive Attention via A Visual Sentinel for Image Captioning # https://arxiv.org/abs/1612.01887 # AdaAttMO is a modified version with maxout lstm # Att2in is from Self-critical Sequence Training for Ima...
from django.db import models class Student(models.Model): id=models.AutoField(primary_key=True) name=models.CharField(max_length=255) email=models.CharField(max_length=255) address=models.TextField() gender=models.CharField(max_length=255) password=models.CharField(max_length=255) objects =...
import py from django.conf import settings from .conftest import create_test_module from .db_helpers import mark_exists, mark_database, drop_database, db_exists def test_db_reuse(django_testdir): """ Test the re-use db functionality. This test requires a PostgreSQL server to be available and the environ...
num_grid = [ [1,2,3,4], [5,6,7,8], [22,26,27,28] ] print(num_grid[2][2]) print(num_grid[0][0]) # nasted loop for row in num_grid: for col in row: print(col) #print(num_grid)
from setuptools import setup, find_packages, version setup( name = "interact_fit", version = '0.0.4', packages = find_packages() )
import sqlite3 from tkinter import * """ Classes """ class MenuBtn: def __init__(self, parent,text,command,row,col): self.parent = parent self.text = text self.command = command self.row = row self.col = col Button(self.parent, text = self.text, command = s...
import string import pandas as pd import numpy as np from nltk.corpus import stopwords from nltk import wordpunct_tokenize from nltk import WordNetLemmatizer from nltk import sent_tokenize from nltk import pos_tag from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.naive_bayes im...
def generate_fibonacci(): indx = 1 n_prev = 0 n = 1 yield (indx, n) while True: sum = n + n_prev n_prev = n n = sum indx+=1 yield (indx, sum) def main(): for (i, j) in generate_fibonacci(): if len(str(j)) == 1000: ...
#!/usr/local/bin/python from unittest import TestCase def answer_one(): with open('2020_07_input.txt', 'r') as f: line = f.readline() while line: line = f.readline() def answer_two(): with open('2020_07_input.txt', 'r') as f: line = f.readline() while line: ...
#coding:utf-8 from PyQt4.QtGui import * from PyQt4.QtCore import * import urllib,re,sys doc_version=['11.9.0','11.8.0','11.7.0','11.6.0','11.5.0','11.4.0','11.3.0','11.2.0','11.1.0'] baseurl='http://www.3gpp.org/ftp/Specs/html-info/%s.htm' class StandardDialog(QDialog): def __init__(self,parent=None): ...
# -*- coding: utf-8 -*- """ Created on Thu May 16 12:52:29 2019 @author: walonsor """ import sys #para importar librerias del sistemas print("Hola, bienvenido a tu primer script") print(sys.argv) #esto lo que hace es mostrar los parametros q se reciben ejemplo: ['1_HolaMundo.py', 'Una cadena de texto', '5']
# Author: Azad # Date: 4/5/18 # Desc: Write a program that takes a list of numbers # (for example, a = [5, 10, 15, 20, 25]) # and makes a new list of only the first and last elements of the given list. # For practice, write this code inside a function. #__________________________________________...
# -*- coding: cp949 -*- import time l = range(1000) t = time.mktime(time.localtime()) for i in l: print(i,) t1 = time.mktime(time.localtime()) - t t = time.mktime(time.localtime()) print(", ".join(str(i) for i in l)) t2 = time.mktime(time.localtime()) - t print("for 문으로 각 인자를 출력") print("Take {0} ...
from socket import* from threading import Thread def main(): global udp_socket global dest_ip global dest_port dest_ip = input("ip:") dest_port = int(input("port:")) udp_socket = socket(AF_INET, SOCK_DGRAM) bind_addr = ('10.123.164.100', 8000) udp_socket.bind(bind_addr) recieve = ...