text
stringlengths
38
1.54M
import numpy class IndicatorHistoryDataFrameRenderer(object): @staticmethod def render_indicator_data(plots_per_axis, snapshot_data, ymin, ymax, progress_plot, progress_bar_location): # draw individual indicators for indicator_name, plot in plots_per_axis.items(): snapshot_data_per...
# Given an array of ints, return True # if one of the first 4 elements in # the array is a 9. The array length # may be less than 4. from test import Tester def array_front9(nums): num_range = len(nums) if num_range > 4: num_range = 4 for i in range(0,num_range): if nums[i] == 9: ...
# from itertools import chain from notifUpdate import Notification from issues import Issues import time import pandas as pd pd.set_option('display.width', None) issues = Issues() notif = Notification() class gendarmerieUpdate: def __init__(self, connexion, annee_update): self.annee = annee_update ...
# -*- coding: utf-8 -*- """ Created on Wed Jul 8 11:50:03 2020 @author: norma """ import numpy as np import pandas as pd import matplotlib.pyplot as plt import curvefunc import ulxlc data_file = '../data/external/variable_ulxlc/tlag_f0p2_m10_mdot20_test.dat' df = pd.read_csv(data_file, sep=' ', he...
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-06-22 20:12 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('enot_app', '0106_trip_direct'), ('enot_app', '0106_merge_20170611_1250'), ] operati...
import utils import training import numpy as np from random import shuffle if __name__ == '__main__': utils.word_extract() input_nn = [] targets = [] samples_per_category = 5000 a,b = utils.load_inputs("aclImdb/train/neg", 0, samples_per_category, input_nn, targets) input_nn=list(a) targe...
# Esto es un comentario def cuadrado_f(x): """Calcula el numero al cuadrado""" y = x * x return y def cuadrado_p(x): """Imprime el numero al cuadrado""" # return 1000 y = x * x print("El cuadrado es:",y) # a = cuadrado_f(5) # print("el cuadrado de 5 es",a) # b = cuadrado_p(5) # print("e...
# Copyright 2014 Symantec Corporation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
import re import pyfumbbl from . import field import cibblbibbl @cibblbibbl.helper.idkey class Coach(metaclass=cibblbibbl.helper.InstanceRepeater): apiget = field.fumbblapi.CachedFUMBBLAPIGetField( pyfumbbl.coach.get ) def __init__(self, coachId: int, name: str=None): self._name = name if se...
# Copyright 2014 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
def maximum_sum(array, window_size): array_size = len(array) if array_size <= window_size: return -1 window_sum = 0 for i in range(window_size): window_sum += array[i] max_sum = window_sum for i in range(array_size - window_size): window_sum = window_sum - array[i] + a...
from behave import given, when, then from pages.rsi.rsi_date_adjusted_response_validation import RsiDateAdjustedResponseValidation from pages.test_survey.test_survey_contributor_details_page import TestSurveyContributorDetailsPage from pages.rsi.rsi_contributor_details_page import RsiContributorDetailsPage @given(u'...
import cs50 import sys if len(sys.argv) != 2: print("Usage: python caesar.py k") exit(1) else: k = int(sys.argv[1]) #print("{}".format(k)) c=[None] * 100 d=[None] * 100 #print("{}".format(len(d))) print("plaintext: ",end="") p=cs50.get_string() ...
import os import unittest from pyats.topology import loader from genie.libs.sdk.apis.iosxe.snmp.configure import unconfigure_snmp_server_user class TestUnconfigureSnmpServerUser(unittest.TestCase): @classmethod def setUpClass(self): testbed = f""" devices: csr: connectio...
import sqlite3 import ihm.console as ihm def ouvrir_connexion(db_name): """ Connexion à une base de données """ conn = sqlite3.connect(db_name) # création d'un curseur pour accéder à cette base cur = conn.cursor() return conn, cur def executer_requete(cur, req, variables=()...
#!/usr/bin/env python3 import matplotlib.pyplot as plt import sys import pandas as pd import numpy as np file = sys.argv[1] gwas = pd.read_csv(sys.argv[1] , sep = "\s+") gwas['logP'] = -1 * np.log10(gwas['P']) gwas['snp_index'] = range(len(gwas)) df_subset = gwas.query('logP > 5') gwas['snp_index'] = range(len(gw...
import torch.utils.data as data import os import sys import random import numpy as np import cv2 import scipy.io as scio class VideoNet(data.Dataset): def __init__(self, root, source, phase, modality="rbg", name_pattern=None, ...
from django import forms from django.contrib.auth.forms import UserCreationForm from django.forms import ModelForm from django.contrib.auth.models import User from .models import * from accounts.models import * from hoitymoppet.models import * class UserCustomSizeform(forms.ModelForm): class Meta: model =...
from random import shuffle from threading import Thread import irc import irc.bot import util import speech class Carte: VALEURS = ['As', 'Deux', 'Trois', 'Quatre', 'Cinq', 'Six', 'Sept', 'Huit', 'Neuf', 'Dix', 'Valet', 'Dame', 'Roi'] def __init__(self, valeur): self._valeur = valeur def __lt__(self...
#!/usr/bin/env python2 import copy import hashlib import json import os import sys class FileTail(object): def __init__(self, file_name, state_dir='.', debug=False): self._data = None self._debug = debug self._file_object = None self._state = None self._tailed_file = file_...
import cv2 import numpy as np image = cv2.imread('blox.jpg') sift_feature = cv2.xfeatures2d.SIFT_create() surf_feature = cv2.xfeatures2d.SURF_create() orb_feature = cv2.ORB_create() sift_kp = sift_feature.detect(image) surf_kp = surf_feature.detect(image) orb_kp = orb_feature.detect(image) sift_out = cv2.drawKeypo...
import itertools import sys # Reading the file (ToDO: Better way to remove the label spaces) def read_training_file(filename): f = open(filename, 'r') df = f.read() data = [] training_data = [] data = df.split("\n") for row in data: temp_data = [] if(len(row) < 1): ...
# Generated by Django 2.1.4 on 2018-12-18 12:37 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Documento', fields=[ ...
from django.http import HttpResponseRedirect from insight.models import Origin from insight.signals import origin_hit def set_origin_code(request, code): try: origin = Origin.objects.get(code=code) if origin.track_registrations: request.session['insight_code'] = code reque...
import torch as th import torch.nn as nn import torch.nn.functional as F from latent_dialog.enc2dec.base_modules import BaseRNN class EncoderGRUATTN(BaseRNN): def __init__(self, input_dropout_p, rnn_cell, input_size, hidden_size, num_layers, output_dropout_p, bidirectional, variable_lengths): super(Encode...
from django.shortcuts import render from django.contrib.auth.models import User from cars.models import Car # Create your views here. def main(request): br = [] for i in range(1, Car.objects.count()+1): if i % 4 == 0: br.append(i) return render(request, 'cars/cars.html', {'cars': Car....
import requests from bs4 import BeautifulSoup #from .. models import Tournament, Position #from .... apps.players.models import Player import datetime import pdb from models.tournament import Tournament import mongoengine as me me.connect('fg') def tournaments_scrape(): tour_champ_end = datetime.datetime(year=2014,...
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Test module for ErrorMetrics """ import ErrorMetrics as em from collections.abc import Iterable x = [2.7, 3.7, 5.7, 9.1, 2.0] y = [9.0, 9.4, 6.6, 6.3, 0.6] def assert_almost_equal(x, y, th=0.0001): if isinstance(x, Iterable) and isinstance(y, Iterable): ...
class DescendingFrequency: @staticmethod def frequency_sort(input_str: str) -> str: # the smallest character in dataset zero_ord = ord('0') # an array that saves the frequency of each character as it appears. char_frequency = [0] * 75 for current_char in input_str: ...
#!/usr/bin/python import argparse from azure.devops.connection import Connection from msrest.authentication import BasicAuthentication from azure.devops.v6_0.work_item_tracking.models import Wiql def parse_args(): '''Defines cmdline arguments''' parser = argparse.ArgumentParser() parser.add_argument('--ac...
from common.protocolmeta import protocols from itertools import islice def first(iterable): try: return islice(iterable, 1).next() except StopIteration: return None def im_service_compatible(to_service, from_service): ''' Returns True if a buddy on to_service can be IMed from a connect...
import os from os import path as pt from zipfile import ZipFile import numpy as np import pandas as pd import requests import torch import wfdb from tqdm import tqdm import os from tqdm import tqdm import pandas as pd import numpy as np import glob import torch from lib.utils import sample_indices from fbm import fbm...
from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ url('snips/', views.api_snip), url('^snip/(?P<id>\d+)$', views.list_snip), ]
def main(): #image_path = "C:\\Users\\MAHE\\Desktop\\8th Sem Project\\Dicom_to_Image-Python-master\\Dicom_to_Image-Python-master\\Series13_png\\0012.png" image_path = input() numpy_for_image = imgToNumpy(image_path) print(numpy_for_image) transformed_matrix = transformNumpyToMartix(numpy_for_image,poly) #pr...
from controller import Controller import time x = Controller(4) print("\nPut car at stop sign 3") x.new_car(2) print(x.queue) time.sleep(1) print("\nPut car at stop sign 1") x.new_car(0) print(x.queue) print("\nRemove car at front of queue") x.remove_car() print(x.queue) print("\nCheck safety of sign 2") x....
from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('reservation', views.reservation, name='reservation'), ]
#i want see all images and turn them into trainable data import cv2 import os from PIL import Image import numpy as np import pickle BASE_DIR = os.path.dirname(os.path.abspath(__file__)) image_dir = os.path.join(BASE_DIR,'images') faceCascade = cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_...
line = 'Good,100,490.10' field_type = [str, int, float] raw_fields = line.split(',') print(raw_fields) fields = [ty(val) for ty, val in zip(field_type, raw_fields)] print(fields) for i in zip(field_type, raw_fields): print(i,type(i))
b=input() b=int(b) X=[] for i in range(0,b): y=input() X.append(y) C=[] for i in zip(*X): if i.count(i[0])==len(i): C.append(i[0]) else: break print(''.join(C))
import re from solutions import helpers from solutions.day07.file_system import Directory, File def parse_shell_output(filename): strings = helpers.read_each_line_as_string(filename) root_dir = Directory(parent=None, name="/") pwd = root_dir for string in strings: print(string) if s...
COLORS = {"UTILTIES": (127,127,127), "RAILWAY STATIONS":(50,50,50), "INDIGO COLOR":(75,60,130), "LIGHTBLUE COLOR":(128,225,255), "PURPLE COLOR":(170,40,150), "ORANGE COLOR":(250,140,10), "RED COLOR":(250,10,10), "YELLOW COLOR":(240,240,0), ...
from bot_app import api_func import requests import json from bot_app import localization from vedis import Vedis from bot_app import tech_info from logistic_bot import settings # a = api_func.Api() # # a.set_user_id(telegram_id='test', user_id='D87hd487ft4') # a.set_zipcode('test', 33815) # print(a.return_param('test...
""" Classes and functions for interacting with Gen3's Discovery Metadata and configured external sources to obtain DOI metadata and mint real DOIs using Datacite's API. """ import csv from cdislogging import get_logger from gen3.doi import DataCite, DigitalObjectIdentifier from gen3.external.nih.dbgap_doi import dbg...
foo = input() hasDuplicate = 1 for index, letter in enumerate(foo): if foo.index(letter) != index: hasDuplicate = 0 break print(hasDuplicate)
#!、usr/bin/env python #-*- coding:utf-8 -*- from django.forms import ModelForm from .models import Student,State class StudentForm(ModelForm): class Meta: model=Student fields='__all__' class StateForm(ModelForm): class Meta: model=State # field='__all__' exclude=['user...
import unittest import os from essentialdb import PickleSerializer, JSONSerializer class TestSerializers(unittest.TestCase): json_file_path = "test.json" pickle_file_path = "test.pickle" def __get_data(self): return dict({'f1': [1,2,3], 'f2': {'n1':'a', 'n2': 2}}) def test_pickle(self): ...
#!/usr/bin/env python # -*- coding:utf-8 -*- import re import Token as token import sbd.util.Util as util class Tokenizer: def __init__(self): self.tokens = [] self.util = util.Common() def __del__(self): self.clear() def clear(self): del self.tokens[:] def parse(sel...
import configparser _SPORTSBOOK_CONFIG_FILE_ = '/Users/leoshang/workspace/football_data_analysis/asianbookie/' \ 'sportsbook/spiders/premier-league.ini' data_feed_config = configparser.ConfigParser() data_feed_config.read(_SPORTSBOOK_CONFIG_FILE_) class SportsbookConfiguration: def _...
''' python版本:3.6.1 1.对/var/log/nginx/access.log的ip进行分组统计并且排序 2.加入IP地址地理查询及限制输出多少条 使用方法: python count.py python count.py log 1 #输出1条IP对应的地址 python count.py log 2 #输出2条IP对应的地址 python count.py log 3 #输出3条IP对应的地址 ''' import re import sys from fn_get_ip_area import get_ip_area fp = ope...
r"""Efficient implementation of the Gaussian curl-free kernel.""" from time import time from pympler.asizeof import asizeof from numpy.random import rand, seed from numpy import dot, zeros, logspace, log10, matrix, int, float from scipy.sparse.linalg import LinearOperator from sklearn.kernel_approximation import RBF...
from __future__ import unicode_literals import urllib.request, urllib.parse, urllib.error import json import ssl #忽略SSL证书错误 ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE serviceurl = 'https://apis.map.qq.com/ws/geocoder/v1/?' while True: address = input('Enter locat...
# Generated by Django 3.2.13 on 2022-08-18 16:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('action_plans', '0021_auto_20220728_0828'), ] operations = [ migrations.AddField( model_name='actionplan', name='has...
# read files with numbered lines #Autumn (worked with Mandy) counter = 0 infile = open((input("Name of file (include extension): ")),"r") for line in infile.readlines(): print(counter, line) counter = counter + 1
from bean import * from datetime import datetime,timedelta def today_range(): #show the current doing task today = datetime.now() today = datetime(today.year,today.month,today.day) yesterday = today today = datetime(today.year,today.month,today.day) + timedelta(days = 1) return class TaskMa...
from cs50 import get_string from sys import argv if len(argv) != 3: print("Please read documents to follow the format of program") exit(0) csv_file =open(argv[1],"r") groups =[] people= {} for index,row in enumerate(csv_file): if index ==0: groups =[group for group in row.strip().split(",")][1:]...
from lxml import objectify from pandas import DataFrame, Series import pandas as pd from datetime import datetime def read_file(filepath): parse_file = objectify.parse(open(filepath)) root = parse_file.getroot() elt = root.Document flightname = elt.name.text print flightname #get the three placemarks ...
# -*- coding: utf-8 -*- ''' 将n-gram embedding作为lstm的输入 ''' import pickle import numpy as np import keras from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.models import Model from keras.layers import Input, Embedding, AveragePooling1D, Dense, GlobalMax...
from dicom_to_cnn.model.petctviewer.Roi import Roi class RoiNifti(Roi): """Derivated Class for automatic Nifti ROI of PetCtViewer.org Returns: [RoiNifti] -- Nifti ROI """ def __init__(self, roi_number:int, list_point:list, volume_dimension:tuple): """constructor Args: ...
from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: """ https://leetcode.com/problems/binary-tree-postorder-traversal/ Given ...
import dbus import time import json import lxml from lxml import etree from dbus.mainloop.glib import DBusGMainLoop # DBusGMainLoop(set_as_default=True) class BT_Manager: # Open a connection to the SystemBus def __init__(self): self.__bus = dbus.SystemBus() self.__adapter_proxy = self.get_Ada...
#!/usr/bin/env python2 from __future__ import print_function import argparse import collections import ConfigParser import os import subprocess import sys import time from datetime import datetime, timedelta class ExecutionError(Exception): def __init__(self, returncode, output): self.returncode = retur...
class tcp8088(Protocol): def connectionMade(self): logprint("[honeypot.HoneyPotFactory] New connection: %s:%s (%s:%s) [Session: %d]" % \ (self.transport.getPeer().host, self.transport.getPeer().port, self.transport.getHost().host, self.transport.getHost().port, self.transport.sessionno)) def dataReceived(self, da...
#!/usr/bin/env python # Copyright 2019 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# SPDX-License-Identifier: MIT # Copyright (c) 2018-2023 Amano LLC import asyncio from pyrogram import Client, filters from pyrogram.types import ChatPrivileges, Message from config import PREFIXES from eduu.database.admins import check_if_del_service, toggle_del_service from eduu.utils import commands from eduu.uti...
import os import torch import numpy as np from . import img_process def get_real_sketch_batch(batch_size, img_name_list, dataset_filter): img_name_list_all = np.array([x.strip() for x in open(img_name_list).readlines()]) img_name_list = [] for idx, i in enumerate(img_name_list_all): for j in d...
from typing import List, Tuple def cross_add(input_vals: List[int]) -> List[int]: """ Traverses <input_vals> from both directions, adding the ith element to the (n-i)th, and storing the result in the ith element of <result>. Examples: [1, 2, 3] -> [4, 4, 4] [3, 4, 7, 13] ...
import sys def maxSubArraySum(a,size): max_so_far = -sys.maxsize - 1 max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if (max_so_far < max_ending_here): max_so_far = max_ending_here if max_ending_here < 0: m...
#!/usr/bin/env python # coding: utf-8 # In[108]: # Importing the necessary libraries import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn import metrics import matplotlib.pyplot as plt import numpy as np import seaborn as sns im...
import numpy as np from functions import deg2rad, eulermethod from math import sqrt, pi initial_yaw = 40 initial_pitch = 30 initial_roll = 80 initial_angles = [initial_yaw, initial_pitch, initial_roll] initial_angles = deg2rad(initial_angles) tstart = 0.0 tstop = 42.0 step = 0.01 length = int(round(tst...
lista = [20, 10, 5, 4, 6, 8] listb = [3, 8, 15, 6, 12, 9] def add(a, b): return a+b listc = list(map(add, lista, listb)) print(listc)
from __future__ import print_function # Import MNIST data from tensorflow.examples.tutorials.mnist import input_data data = input_data.read_data_sets('/tmp/data/', one_hot=True) import tensorflow as tf # Parameters learning_rate = 0.1 training_epochs = 15 batch_size = 100 # Network Parameters n_hidden = 256 # numb...
""" Solution for Algorithms #21: Merge Two Sorted Lists Runtime: 44 ms, faster than 88.71% of Python3 online submissions for Merge Two Sorted Lists. Memory Usage: 13.2 MB, less than 5.06% of Python3 online submissions for Merge Two Sorted Lists. """ # Definition for singly-linked list. # class ListNode: # def __in...
# 【问题描述】深度优先遍历 # 【输入形式】同上题 # 【输出形式】同上题 # 【样例输入】 # 4 A # A: {B:1, C:1, D:1} # B: {A:1, C:1, D:1} # C: {A:1, B:1, D:1} # D: {A:1, B:1, C:1} # 【样例输出】 # A B C D dic = {0: "A", 1: "B", 2: "C", 3: "D", 4: "E", 5: "F", 6: "G", 7: "H", 8: "I", 9: "J"} ans = [] def travelsal(mat, ver): global ans global n ...
import RPi.GPIO as IO import time as t IN1 = 19 IN2 = 26 def DC_setup(): IO.setmode(IO.BCM) IO.setup(IN1, IO.OUT) IO.setup(IN2, IO.OUT) d1 = IO.PWM(IN1, 50) d2 = IO.PWM(IN2, 50) d1.start(0) d2.start(0) return d1, d2 d1, d2 = DC_setup() while True: d1.ChangeDutyCycl...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^client/$',views.index,name='index'), #url(r'^client/(?P<client_id>[0-9]+)/$',views.client,name='client'), url(r'^client/(?P<client_id>[0-9]+)/$',views.detail,name='detail'), url(r'^client/addclient/$',views.addclient,name='addclient'), ...
# docker container rm spark-submit -f # docker run -it --name spark-submit --network spark-net --volume /home/liming:/home -e HADOOP_USER_NAME=liming -p 4040:4040 mingsqtt/spark_submit:3.0.1 bash # $SPARK_HOME/bin/pyspark --conf spark.executor.memory=14G --conf spark.executor.cores=6 --master spark://spark-master:7077...
//Robot_Arm.ino #include <Servo.h> #include <Wire.h> #include <LCD.h> #include <LiquidCrystal_I2C.h> LiquidCrystal_I2C lcd(0x3F,2,1,0,4,5,6,7); const int arrLen = 20; Servo clawServo, lowerServo, upperServo, baseServo; int claw, lower, upper, base; int clawPot = 3; int lowerPot = 2; int upperPot = 1; int basePot ...
class LRUCacheNode: def __init__(self, key, val, parent=None, child=None): self.key = key self.val = val self.parent = parent self.child = child class LRUCache: def __init__(self, capacity: int): self.head = None self.tail = None self.nums ...
s = 1 n1 = 3 n2 = 2 cont = 0 while n1 < 40: s = s + (n1/n2) n1 += 2 n2 = n2*2 print("%.2f"%s)
class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: for i in range(1, len(coordinates)): xyc = coordinates[i] xyp = coordinates[i-1] print(xyc, xyp) if xyc[0] == xyp[0]: return False pslope = (coordinates[...
import binascii from Crypto.Util.number import bytes_to_long, long_to_bytes # KEY1 = 0xa6c8b6733c9b22de7bc0253266a3867df55acde8635e19c73313 # KEY2 = 0x37dcb292030faa90d07eec17e3b1c6d8daf94c35d4c9191a5e1e ^ KEY1 # KEY3 = 0xc1545756687e7573db23aa1c3452a098b71a7fbf0fddddde5fc1 ^ KEY2 # FLAG = 0x04ee9855208a2cd59091d04767...
__author__ = "Jieshu Wang and Bilal El Uneis" __since__ = "July 2019" __email__ = "foundwonder@gmail.com and bilaleluneis@gmail.com" from unittest import TestCase from abstract_array import * import logging as log class TestArrayListImpl(TestCase): @classmethod def setUpClass(cls): log.basicConfig(l...
from collections import namedtuple MessageSource = namedtuple('MessageSource', 'id type service config')
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # Corrections & modifications by Noviat nv/sa, (http://www.noviat.be): # - VAT listing based upon year...
import data from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D from keras.models import Sequential, load_model model = Sequential() model.add(Conv2D(16, (3, 3))) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(16, (3, 3))) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(D...
import xlrd import sqlite3 as sqlite import itertools def xls2db(infile, outfile): """ Convert an xls file into an sqlite db! """ #Now you can pass in a workbook! if type(infile) == str: wb = xlrd.open_workbook(infile) elif type(infile) == xlrd.Book: wb = infile else: ...
#!/usr/bin/env python3 import argparse import logging import re import os import shutil from os import listdir from os.path import isdir, isfile, join logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO) logger = logging.getLogger() file_path = os.path.dirname(__file__) unsorted_roms_folder =...
#!/bin/python # -*- coding: utf-8 -*- import os as _os import platform as _platform # Setting up the proper libraries and paths, mainly for Windows support _libpath = _os.path.abspath(_os.path.dirname(__file__)) _plat_info = dict(plat=_platform.system()) if _plat_info['plat'] == 'Windows': _plat_info['l...
# coding:utf-8 import socket # from jetbot import Robot import subprocess from multiprocessing import Process def handle_client(client): """ 处理客户端请求 """ request_bytes = client.recv(1024) # data = self.__client.recv(1024) # 判断空 # if data == b"": # print('这里返回二进制空,不知道在哪儿看到的返回None,感觉逻辑合理,浪费...
# mybot/app.py import os from kbbi import KBBI from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity import nltk import random import string import time import _thread from decouple import config from flask import ( Flask, request, abort ) from linebot...
__author__ = 'Danyang' class Solution: def maxKSubArrays(self, nums, k): n = len(nums) f = [[0 for _ in xrange(k+1)] for _ in xrange(n+1)] g = [[0 for _ in xrange(k+1)] for _ in xrange(n+1)] s = [0 for _ in xrange(n+1)] for i in xrange(1, n+1): s[i]...
# euler38 import time t0 = time.time() for n in range(1,60000): val1 = n * 1 val2 = n * 2 val = str(val1) + str(val2) for v in range(3,10): if len(val) >= 9: break valn = n * v val += str(valn) if len(val) == 9: if '1' in val and '2' in val and '3' i...
F1,D2= map(list,input().split()) F1[0] = F1[0].upper() D2[0] = D2[0].upper() fstr = "".join(F1) dstr = "".join(D2) print(fstr,dstr)
from sys import argv import cleanup import tokenize import wordcount import sample def sentance(histogram, total, loop): looper = int(loop) sentance1= [] word_string = " " # loop for i in range(0,looper): weight_word = sample.weighted_random(histogram, total) sentance1.append(weig...
# Generated by Django 3.1.6 on 2021-05-08 11:08 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('teachers', '0008_auto_20210507_2047'), ] operations = [ migrations.RenameModel( old_name='Responses', new_name...
import requests from bs4 import BeautifulSoup import csv from fake_useragent import UserAgent UserAgent().chrome def get_html(url): r = requests.get(url, headers={'User-Agent': UserAgent().chrome}) print(r.text) return r.text def write_csv(data): with open('csvs/Raif.csv', 'a') as f: writer ...
a= float(input("Valor disponivel: ")) b= int(input("Quantidades de tickets do RU: ")) c= float(input("Valor dos tickets: ")) d= int(input("Quantidade de passes de onibus: ")) e= float(input("Valor dos passes: ")) f= ((b * c) + (d * e)) if (a >= f): print("SUFICIENTE") else: print("INSUFICIENTE")
# Created: 12.04.2014, 2018 rewritten for pytest # Copyright (C) 2014-2018, Manfred Moitzi # License: MIT License from __future__ import unicode_literals import pytest from ezdxf.modern.spline import Spline, _SPLINE_TPL from ezdxf.lldxf.extendedtags import ExtendedTags @pytest.fixture def spline(): return Spline(...
# # THIS IS AN IMPLEMENTATION OF THE CLASSIC MEMORY GAME IN 2D # # COPYRIGHT BELONGS TO THE AUTHOR OF THIS CODE # # AUTHOR : LAKSHMAN KUMAR # AFFILIATION : UNIVERSITY OF MARYLAND, MARYLAND ROBOTICS CENTER # EMAIL : LKUMAR93@UMD.EDU # LINKEDIN : WWW.LINKEDIN.COM/IN/LAKSHMANKUMAR1993 # # THE WORK (AS DEFINED BELOW) IS PR...
#!/usr/bin/python #import sys #import json #import subprocess import mechanize import urlparse import urllib,urllib2 from bs4 import BeautifulSoup import multiprocessing class Search: """Search class for new google search""" def __init__(self, keyword): self.keyword = keyword self.crawl_topic = 'escort' self...