text
stringlengths
38
1.54M
#! /usr/bin/env python3 # Module imageImport.py ################################################# # # # Python functions for importing image files # # # # Author: Robert Thomas # # Username: rjst20 # # # ################################################# # OpenCV used for...
#Boa:Frame:Frame2 import wx import MySQLdb def create(parent): return Frame2(parent) [wxID_FRAME2, wxID_FRAME2BUTTON1, wxID_FRAME2BUTTON2, wxID_FRAME2BUTTON3, wxID_FRAME2BUTTON4, wxID_FRAME2BUTTON5, wxID_FRAME2BUTTON6, wxID_FRAME2BUTTON7, wxID_FRAME2BUTTON8, wxID_FRAME2PANEL1, wxID_FRAME2START, ] = [wx.NewI...
import argparse import logging import apache_beam as beam from apache_beam.io.gcp.internal.clients import bigquery class BigQueryToBigQuery(beam.DoFn): def __init__(self): pass def process(self, element): pass def run(argv=None, save_main_session=True): '''Main run method''' ...
import logging from collections import deque from itertools import permutations import networkx as nx import numpy as np from tqdm import trange from LearningWithExpertKnowledge.expert import * from LearningWithExpertKnowledge.graph import DAG class Estimator: def __init__(self, data: pd.DataFrame, expert: Expe...
# Copyright (c) 2021, Manfred Moitzi # License: MIT License from typing import Union, List, Dict, Tuple import math from matplotlib.textpath import TextPath from matplotlib.font_manager import FontProperties, findfont from ezdxf.entities import Text, Attrib, Hatch from ezdxf.lldxf import const from ezdxf.math import...
import collections class Node(): def __init__(self): self.child = collections.defaultdict(Node) self.isWord = False self.s = "" self.cnt = 0 class WordDictionary: def __init__(self): self.root = Node() def addWord(self, word: str) -> None: cur = sel...
import os path = 'c:\\tmp\\csv' s = '10秒' d = '10s_20180521_20180523' fs = os.listdir(path) for f in fs: os.rename(path + '\\' + f, path + '\\' + f.replace(s, d))
# Basic training configuration file from pathlib import Path from torchvision.transforms import RandomVerticalFlip, RandomHorizontalFlip from torchvision.transforms import RandomResizedCrop from torchvision.transforms import ToTensor, Normalize from common.dataset import get_test_data_loader SEED = 12345 DEBUG = True...
from django.urls import path from . import views urlpatterns = [ path('', views.search, name='search'), path('<str:word>/', views.word_detail, name='wordDetail'), path('wordDetail/pdf/<str:document>/',views.pdf_openner, name='pdfOpenner') ]
import os import cv2 import numpy as np from keras.models import Sequential, load_model from keras.layers import Dropout, Activation, Dense from keras.layers import Flatten, Convolution2D, MaxPooling2D from keras.callbacks import EarlyStopping from sklearn.model_selection import KFold, train_test_split, GridSearchCV im...
q = 0 def endQuestion(): global q q += 1 print("End of question", q) # end of def # 1. Biggie Size - Given a list, write a function that changes all positive numbers in the list to "big". # Example: biggie_size([-1, 3, 5, -5]) returns that same list, but whose values are now [-1, "big", "big", -5] def ...
for i in range(int(input())): s = input() if '1' not in s: print("NO") else: chng = 0 i = 1 while i<len(s) and chng <= 2: if s[i] != s[i-1]: chng += 1 i+=1 if chng == 2 and s[0] == '0': print("YES") elif chng...
from django.db import models from django.contrib.auth.models import User # Create your models here. class user_master(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key = True) username = models.CharField(max_length=50) email = models.EmailField(max_length=50, uni...
""" Write a program that asks the user how many people are in their dinner group. """ seating = input('How many people are in your dinner group?\n') seating = int(seating) if seating > 8: print("You need to wait for a table.") else: print("Table is ready!")
entry = input() while entry != '2002': print('Senha Invalida') entry = input() print('Acesso Permitido')
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). # Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Soft...
import keras from keras.models import Sequential from keras.layers import Dense, Dropout, Activation from keras.optimizers import SGD from keras.datasets import cifar10 # Generate dummy data import numpy as np # x_train = np.random.random((1000, 20)) # y_train = keras.utils.to_categorical(np.random.randint(10, size=(1...
# Register your models here. from django.contrib import admin import models admin.site.register(models.Restaurant)
class instruction: binary = '' def __str__(self): return self.binary def parse(self, line): line = line.strip() line = line.replace('<',';') line = line.replace('>',';') output = line.split(';') return str(output[2]) class a_instruction(instruction): d...
# Databricks notebook source # Set credentials for blob storage spark.conf.set("fs.azure.account.key.databricksstoragedevweu.blob.core.windows.net", "******accesskey******") username = "guido.tournois@icemobile.com" # AAD user with READ permission on database password = dbutils.secrets.get("guido.tournois@icemobile....
# 读取id、姓名、成绩 # aa.xlsx: # id||name||score # 1||mike||88.5 # 2||amy||60.8 # 3||bob||79.6 import xlrd # region (1)将excel内容存于student类型的list class student(): def __init__(self): self.id = 0 self.name = 0 self.age = 0 def read_student(filename): workbook = xlrd.open_work...
import numpy from ltp_core.datamodules.components.srl import Srl from ltp_core.datamodules.utils.datasets import load_dataset def tokenize(examples, tokenizer, max_length): res = tokenizer( examples["form"], is_split_into_words=True, max_length=max_length, truncation=True, ) ...
#-*-coding:UTF_8-*- import re import json sf= input('') sf=sf[:-1]#删去末尾的'.' pf={ '姓名':'', '手机':'', '地址':[], } #提取难度级别并删去 level=sf[0] sf=sf.split(r'!') sf=sf[1] #提取号码并删去 telnum=re.findall("\d{11}",sf) telnum=telnum[0] sf=re.sub(r'\d{11}','',sf) #提取人名并删去 name=re.sub(r',.*$',"",sf) sf=re.sub(name,'',sf...
from datetime import datetime ''' print(datetime.now()) print(datetime.now().day) print(datetime.now().month) print(datetime.now().year) print(datetime.now().time()) # criar data lancamento_ap = datetime(2021,5,6) print(f'Data de Lançamento: {lancamento_ap}') receberdata = datetime.strptime(input("Quando dev...
# Generated by Django 2.2.6 on 2019-12-16 19:52 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='speaker', options={'verbose_name': 'palestrante...
import yaml, os class GetData: def get_yaml_data(self, name): """ 返回yaml文件数据 :param name: 需要读取文件名字 :return: """ #打开文件 with open("./Data" + os.sep + name, "r", encoding="utf-8") as f: #加载文件 return yaml.safe_load(f)
import calendar y = int(input("Enter Year")) m = int(input("Enter month")) c = calendar.TextCalendar(calendar.SUNDAY) str = c.formatmonth(y, m) print(str)
from django.shortcuts import render from django.http import Http404 from django import forms import markdown2 from random import randrange from . import util class SearchForm(forms.Form): # lhs search form search = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder':'Search Encyclopedia'}))...
# -*- coding: utf-8 -*- """ Created on Sun Oct 7 22:42:11 2018 @author: gehui """ even_numbers = list(range(2,11,2)) print(even_numbers)
#!/usr/bin/python '''The third step of metagene_analysis, metagene_plot_only.py uses R to create the metagene plot (as a PDF). Please see README for full details and examples. Requires: python 2 (https://www.python.org/downloads/) R (http://cran.us.r-project.org/) Joy-El R.B. Talbot Copyright (c) 2014 The M...
import os import glob """ train.zipを解凍したtrainから https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html にあるように訓練データを振り分ける """ imgs_path = "./image_dir/*.png" source_dir = "./train" train_dir = "./data/train" valid_dir = "./data/validation" os.makedirs("%s/dogs" % train_dir) os....
input = open('antiqs.in', 'r') output = open('antiqs.out', 'w') n = int(input.readline()) a=list() for i in range(0,n): a.append(i+1) for i in range(0, n): a[i], a[i // 2] = a[i // 2], a[i] for i in range(0, n): output.write(str(a[i])) output.write(' ') input.close() output.close()
rows = 20 cols = 20 size = 18 width = 650 height = 550 outline_gray = "gray" outline_black = "black" fill_empty = "" fill_black = "#000000" fill_white = "#ffffff"
import pandas as pd import cudf, cuml df = pd.read_csv("data/data.csv") columns=['name', 'artists', 'acousticness', 'danceability', 'energy', 'instrumentalness', 'key', 'liveness', 'loudness', 'speechiness', 'tempo', 'valence'] df_mod = df[columns] keys = df_mod.iloc[:,:2].values.tolist() features = df_mod.iloc[:,2:...
import os import json import urllib2 #import jmsCode # JMS STOMP connection wrapper - needs stomp.py import datetime #/////////////////////////////////////////////////////////////////////////////////////////////// # # Set of functions to handle the update payload from an instagram subscription upd...
# 8.3 power set of a set class Solution(object): # Recursive solution, slow def subsets(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ n = len(nums) if n == 0: return nums elif n == 1: return [nums, []] el...
from transformers import TFAlbertForSequenceClassification class NN: def __init__(self): self._nn = self._create_nn() def _create_nn(self) -> TFAlbertForSequenceClassification: return TFAlbertForSequenceClassification.from_pretrained('albert-base-v2', num_labels=1) def get_nn(self): ...
import praw from config_bot import * # Reddit stuff r = praw.Reddit(user_agent = "ARTCbot 1.3.0 by herumph", client_id = ID, client_secret = SECRET, username = REDDIT_USERNAME, password = REDDIT_PASS) submission = r.submission(url='https://www.reddit.com/r/RumphyBot/comments/8gb347/moo...
# Generated by Django 2.2.6 on 2020-05-13 16:52 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('companies', '0008_auto_20200513_0930'), ] operations = [ migrations.AlterField( model_name='eve...
from ..models import Block from ..models import Phase from ..models import DrawingStatus from ..models import Department from ..models import Discipline from ..models import DrawingKind from ..models import Drawing from ..models import Revision from ..models import Comment from ..models import Reply from ..mo...
import sys def get_expression(s): n_chars = len(s) if n_chars == 0: return s exps = [ s[0] ] for char in s[1:]: n_exps = len(exps) j = 0 while j < n_exps: exp = exps[j] exps[j] = exp + '+' + char#+ exps.append(exp + '-' + char)#- ...
import picamera import RPi.GPIO as GPIO import threading import os import time import logging logging.basicConfig(filename='timelapse.log', level=logging.DEBUG, format='%(asctime)s %(message)s') logging.getLogger().addHandler(logging.StreamHandler()) event_start = threading.Event() GPIO_INPUT_BCM = 4 # p...
# -*- coding: utf-8 -*- """ Created on Thu Oct 13 16:57:34 2016 @author: Stanley """ rom_num = (input("Please enter a number in the simplfied Roman System:")) return_num = 0 counter = 0 length = len(rom_num) while (length > 0): if (rom_num[counter] == "M"): return_num += 1000 counter +=1 l...
import numpy as np import cv2 def color_predicts(): ''' 给class图上色 ''' img = cv2.imread("image_3_predict.png",cv2.CAP_MODE_GRAY) color = np.ones([img.shape[0], img.shape[1], 3]) color[img==0] = [0, 0, 0] #其他,黑色,0 color[img==1] = [255,0, 0]#烤烟,红色,1 color[img==2] = [0, 255, 0] #玉米,绿色,2 ...
from .hexutil import long_to_bytes import itertools class StreamReader: def __init__(s, x): s.str = x s.pos = 0 def read(s, length=1): if (s.pos + length) > len(s.str): length = len(s.str) - s.pos res = s.str[s.pos : s.pos + length] s.pos += length ...
import requests from log import * import json def wavySendMessage(data): log('***Invocando API send message de wavy***\n') url = 'https://api-messaging.wavy.global/v1/whatsapp/send' urlHeaders = {'Content-type': 'application/json','UserName': 'wa_telectronicperusac_pe','AuthenticationToken': 'nouxAVNgq...
from django.core.management.base import BaseCommand import requests from mentions.models import Mention class Command(BaseCommand): def handle(self, **options): url = "https://www.electionmentions.com/api/stream?since=2016-01-01" req = requests.get(url) results = req.json() for ...
f = open('text.txt', 'r') text = f.read() f.close text1 = text mas = [] q_mas = [] #task 1 with ' ' ''' abcdefgh a[0:2] + ';' + [2:] ab;cdefgh a[3:5] REPORT4 - bigrams without ' ' | не сквозные pos1 = 0 pos2 = 2 text2 = '' while 1: text2 = text2 + text1[pos1:pos2] + ';' pos1 = pos2 pos2 = pos1 + 2...
# -*- coding: utf-8 -*- import os, time, sys import Tool import random param = {'Capacitance':'pF'} class Instrument(Tool.MeasInstr): def __init__(self, resource_name, debug = False,**keyw): super(Instrument, self).__init__(resource_name,'AH2550A',debug,**keyw) self.identify("Hello, this is ")...
from django.shortcuts import render from django.http import HttpResponse from django.views.generic import TemplateView import contracts from utils import contract from .models import Account # Create your views here. class IndexView(TemplateView): template_name = 'contracts/index.html' def get_context_data(se...
import json import os import tkinter as tk from tkinter import filedialog class ConfigHandler: __CONFIG_FILE = "config.json" __PATH = "path" __LIMIT = "limit" def __init__(self): # TODO: this should be done better, for the moment it will suffice if os.path.isfile(self.__CONFIG_FILE) and os....
import requests from django.db import models from django.contrib.gis.db import models from django.contrib.gis.geos import Point from django.utils.text import slugify class Location(models.Model): address = models.CharField(max_length=200) city = models.CharField(max_length=50) state = models.CharField(max...
#!python3 # SimPy model for a fault_injector. # The fault_injector injects faults into devices # at a predetermined time (via a SimPy interrupt) # # Author: Neha Karanjkar from __future__ import print_function import os, sys import threading from queue import Queue import simpy import time import json import logging...
from flask import Flask, render_template from flask import request import networkx as nx import json import pickle from aminer.graph import setup_graph from aminer.util import get_attached_subgraph, graph_to_d3tree_json, \ graph_to_d3nodelink_json, mst_from_graph, bfs_from_tree, neighborhood, \ deep_subgraph, b...
from Rule import Rule import json class RulesList: def __init__(self, filename : str, rules : list = []): self.filename = filename self.rules = rules def readRules(self) -> None: try: with open(self.filename) as data: self.rules = json.load(data) exc...
import re # import datetime import mdiag # from collections import defaultdict class GroupMdiagTests: # Note the convention: If it passes the test, then it returns True. # Otherwise, it returns false @classmethod def testTransparentHugepages(cls, groupMdiag): # NOTE can also use section trans...
def conRebanadas(c, i, n): n = n + i return c[i:n] def sinRebanadas(c, i, n): n = n + i nueva = "" for i in range(i, n): nueva += c[i] return nueva # PROGRAMA PRINCIPAL c = "Oid mortales el grito sagrado" i = int(input("Índice: ")) n = int(input("Cantidad de caracteres: "...
n = int(input()) a = list(map(int, input().split())) if a.count(0) > 0: ans = 0 else: ans = 1 for i in a: ans *= i if ans > (10 ** 18): break if not ans > (10 ** 18): print(ans) else: print(-1)
import numpy as np import sqlalchemy as sq import bs4 import requests as rq import pandas as pd import time as t import datetime import random print('import successful') nom=900291 while nom<999999: r=random.randrange(1,2) res=rq.get('https://bina.az/items/'+str(nom)) if str(res)!='<Response [200]>': ...
#In the 20x20,grid below, four numbers along a diagonal line have been marked in red. from operator import mul from functools import reduce tab = [[ 8, 2,22,97,38,15, 0,40, 0,75, 4, 5, 7,78,52,12,50,77,91, 8], [ 49,49,99,40,17,81,18,57,60,87,17,40,98,43,69,48, 4,56,62, 0], [ 81,49,31,73,55,79,14,29,93,71,40,67,53,88,...
import cv2 import time import os import HandTrackingModule as htm #webcam setting cap = cv2.VideoCapture(2) hcam, wcam = 480, 640 cap.set(3, wcam) cap.set(4, hcam) #fps parameters curTime = 0 prevTime = 0 #finger Images folderPath = "Finger Images" myList = os.listdir(folderPath) myList.sort() imgList = [] for imPat...
from google.appengine.ext import vendor vendor.add('certifi') vendor.add('chardet') vendor.add('urllib3') vendor.add('requests') vendor.add('requests-toolbelt') vendor.add('prawcore') vendor.add('praw') vendor.add('dateutil') def webapp_add_wsgi_middleware(app): from google.appengine.ext.appstats import recording a...
class HeaderMixin: header_path = '' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['header_path'] = self.header_path return context class SecondHeaderMixin(HeaderMixin): url_name = None menu_title = '' def get_menu_queryset(self...
# Generated by Django 3.1.4 on 2021-02-05 14:57 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('posts', '0001_initial'), ] operations = [ migrations.RenameField( model_name='post', ...
# -*- coding: utf-8 -*- # generated by wxGlade 0.6.3 on Tue May 26 09:15:05 2009 import wx, __builtin__ # begin wxGlade: dependencies # end wxGlade # begin wxGlade: extracode # end wxGlade class AboutDialog(wx.Dialog): def __init__(self, *args, **kwds): # begin wxGlade: AboutDialog.__init__ kwd...
from os.path import dirname, join from pathlib import Path from tokenizers import ByteLevelBPETokenizer from tokenizers.processors import BertProcessing model_name = 'dabert' file_dir = dirname(__file__) data_folder = join(file_dir, 'data') data_paths = [str(x) for x in Path(data_folder).glob("**/*.txt")] output...
from argparse import ArgumentParser, ArgumentTypeError from locale import getdefaultlocale from multiprocessing import Pool from contextlib import redirect_stdout from io import StringIO from zdict import constants, utils, easter_eggs from zdict.api import dump from zdict.completer import DictCompleter from zdict.load...
import ROOT from ROOT import TFile, TTree from ROOT import TCanvas, TGraph from ROOT import gROOT import numpy as np import matplotlib.colors as colors from matplotlib.colors import LogNorm import matplotlib.pyplot as plt from matplotlib.patches import Rectangle import matplotlib.colorbar as cbar from scipy.optimize i...
from typing import List import functools def jump(nums: List[int]) -> int: '''贪心算法,每次找当前能跳到位置中能跳最远的,作为下一个落脚点,当到达边界时,更新边界为最远落脚点,并且steps+1''' maxPos, end, step = 0, 0, 0 for i in range(len(nums)-1): maxPos = max(maxPos, i+nums[i]) # 更新最大值 if i == end: # 该跳了 end = maxPos ...
import hashlib import hmac import json import requests from flask import jsonify import time with open("slack_config.json", "r") as f: data = f.read() config = json.loads(data) #VERIFY SLACK WEBHOOK def verify_signature(request): timestamp = request.headers.get("X-Slack-Request-Timestamp", "") signature...
from sdk.color_print import c_print from tqdm import tqdm def update_login_ips(session, ips, dst_ips, logger): updated = 0 if ips: logger.info(f'Updating Login IPs for tenant: \'{session.tenant}\'') for ip in tqdm(ips, desc='Updating Login IPs', leave=False): name = ip.get('name') ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging from logging.handlers import RotatingFileHandler # création de l'objet logger qui va nous servir à écrire dans les logs logger = logging.getLogger() # on met le niveau du logger à DEBUG, comme ça il écrit tout logger.setLevel(logging.DEBUG) # création d'u...
from shorty.common.exceptions.shorty_exception import ShortyException HTTP_STATUS = 422 class ValidationException(ShortyException): def __init__(self, code: str, detail: str): super().__init__(HTTP_STATUS, code, detail)
import numpy as np from math import pi import math class SwingPendulum(object): min_pos = -pi max_pos = pi umax = 2.0 mass = 1.0 length = 1.0 G = 9.8 timestep = 0.01 required_up_time = 10.0 up_range = pi/4.0 max_speed = (pi/16.0)/timestep pos_start = pi/2....
import time def find(start, end): if start > end: countdownfrom(start, end) elif end > start: countupfrom(start, end) def countdownfrom(start, end): while start >= end: print start start -= 1 def countupfrom(start, end): while start <= end: print start ...
# import the necessary packages from imutils.video import VideoStream from imutils.video import FPS import face_recognition import imutils import pickle import time import cv2 import pandas as pd import paho.mqtt.client as mqtt def messageFunction (client, userdata, message): topic = str(message.topic) messa...
from django.core import serializers from django.shortcuts import render, redirect from django.http import HttpResponse, JsonResponse from django.views.generic import View, CreateView, UpdateView, DeleteView from django.urls import reverse, reverse_lazy from ..models import Driver from ..form import DriverForm from djan...
#!/usr/bin/env python # # Copyright (c) 2015 - 2021, Intel Corporation # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, thi...
# Ported from a Java benchmark whose history is : # This is adapted from a benchmark written by John Ellis and Pete Kovac # of Post Communications. # It was modified by Hans Boehm of Silicon Graphics. # # This is no substitute for real applications. No actual application # is likely to behave in exactl...
import re import numpy as np from scipy.spatial import distance f = open('../sentenceCosinusDistance/sentences.txt', 'r') def split_low(line): return re.split('[^a-z]', line.lower()) not_empty_words = list( filter(lambda word: word, [word for sentence in f.readlines() for word in split_low(sente...
import pytest import cogctl.cli.bundle.enable as bundle # TODO: Eww, this import pytestmark = pytest.mark.usefixtures("mocks") # TODO: What happens when you try to enable a bundle that's already enabled? def test_enable_no_version_enables_latest(cogctl): result = cogctl(bundle.enable, ["disabled_bundle"]) ...
from PIL import Image, ImageFile import torchvision.transforms as transforms import torch.utils.data as data import os Image.MAX_IMAGE_PIXELS = 933120000 ImageFile.LOAD_TRUNCATED_IMAGES = True def is_img_file(filename): return any(filename.lower().endswith(extension) for extension in ('jpg', 'png', 'jpeg')) d...
def get_content_info(file): num_lines = file.count('\n') + 1 num_else = file.count('else') num_char = len(file.replace('\n', '')) return {'lines': num_lines, 'else': num_else, 'characters': num_char} def print_file_info(info): for key, value in info.items(): print(f'number of {key} in file...
import sys DEBUG=True if len(sys.argv) > 1 else False def debug(*texts): if DEBUG: print("[DEBUG]", *texts, flush=True) def solve(senators): sol = "" while True: r = sum(senators.values()) if not r: break k = max(senators, key = senators.get) sol += ...
import numpy as np from pylab import ylim, title, ylabel, xlabel import matplotlib.pyplot as plt from kalman import SingleStateKalmanFilter import pandas as pd from collections import defaultdict import seaborn as sns # ------------------------------------------- Filtering: PARAMETERS : (START) -----------------------...
# Copyright 2014 MongoDB, Inc. # # 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 agreed to in writing, so...
# Author: ambiguoustexture # Date: 2020-03-11 import pickle import numpy as np from scipy import io from similarity_cosine import sim_cos file_context_matrix_X_PC = './context_matrix_X_PC' file_t_index_dict = './t_index_dict' with open(file_t_index_dict, 'rb') as t_index_dict: t_index_dict = pickle.load...
''' 1. Given an NxN matrix, write a function that would rotate it by 90 degrees clock-wise or counter clockwise. ''' # Rotate n clockwise or counter-clockwise # If d == 0, clockwise # If d == 1, counter-clockwise # Else no change def rotate(n, d): m = n if d == 0: m = zip(*m[::-1]) elif d == 1: ...
import argparse import os import cv2 import json from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval from tf_inferencer import TFInferencer # The following variables are used to configure the compression analysis COMPRESSION_LEVELS = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10] ENCODING = "JPG" ...
# coding=utf-8 # 测试command属性绑定事件,测试lambda表达式帮助传参 from tkinter import * root = Tk() root.geometry("270x50") def mouseTest1(): print("command方式,简单情况:不涉及获取event对象,可以使用") def mouseTest2(a,b): print("a={0},b={1}".format(a, b)) Button(root, text="测试command1", command=mouseTest1).pack(side="left") Button(root...
# -*- coding: utf-8 -*- # import numpy import fastfunc import asciiplotlib as apl def print_stats(mesh, extra_cols=None): extra_cols = [] if extra_cols is None else extra_cols angles = mesh.angles / numpy.pi * 180 angles_hist, angles_bin_edges = numpy.histogram( angles, bins=numpy.linspace(0.0, ...
import math ''' ''' s = input('请输入一个数 ') # 这是一个输入语句 s = float(s) if s > 0: s = math.sqrt(s) print(s) else: print('没有平方根') # !/usr/bin/python3 a = 21 b = 10 c = 0 c = a + b print("1 - c 的值为:", c) c = a - b print("2 - c 的值为:", c) c = a * b print("3 - c 的值为:", c) c = a / b print("4 - c 的值为:", c) c =...
pesos = float(input("Ingrese un monto: ")) valor_dolar =3875 dolares = round(pesos / valor_dolar) dolares = str(dolares) print("Tienes "+ " USD$ "+ dolares)
def genWaveHeader(data) : length = len(data); header = "RIFF"; size = 4 + 24 + 8 + length; ch = chr((size & 0x000000FF) >> 0); header += ch; ch = chr((size & 0x0000FF00) >> 8); header += ch; ch = chr((size & 0x00FF0000) >> 16); header += ch; ch = chr((size & 0xFF00000...
# this is the program for socket communication # it can be used both for server and client # python socket_communication.py -server for server # python socket_communication.py -client for client import wx import socket import time import sys sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) port = sys.argv[...
from builtins import range import numpy as np # from skimage.io import imread import tensorflow as tf import sys import cv2 def main(): # Read in image with the shape (rows, cols, channels) im = cv2.imread('./img/face.png') im = np.array(im) / 255. invSpatialStdev = float(1. / 5.) invColorStdev ...
import torch import argparse import docker import os import sys import logging import torchvision.models as models from cloudpickle import CloudPickler import tempfile import tarfile trained_models = ['resnet18', 'densenet201'] logger = logging.getLogger(__name__) class ClipperException(Exception): """A generic ...
""" Stripping Filtering file for B->D*munuX where D0->K3pi @author Philip Hunt @date 2013-07-26 """ from Gaudi.Configuration import * MessageSvc().Format = "% F%60W%S%7W%R%T %0W%M" # # Build the streams and stripping object # from StrippingConf.Configuration import StrippingConf, StrippingStream from StrippingSetti...
##Problem Name : Leetcode Week 2 problem ## Problem Name: Valid Perfect Square ##Time 32 ms class Solution: def isPerfectSquare(self, num: int) -> bool: i = 1 the_sum = 0 while the_sum < num: the_sum += i if the_sum == num: return True ...
import pandas as pd import numpy as np import json import os import re import copy import openpyxl as xl import xlsxwriter from paper_functions import integrated_paper_file_generator from Patent_Functions import integrated_patent_file_generator from typing import List, Dict, Optional, Union, Tuple from pandas.api.types...