text
stringlengths
38
1.54M
# coding=utf-8 import unittest from app.teacher.login.test_data.login_failed_toast import VALID_LOGIN_TOAST from app.teacher.login.object_page.home_page import ThomePage from app.teacher.login.object_page.login_page import TloginPage from app.teacher.user_center.setting_center.object_page.setting_page import SettingPa...
from scipy.stats import beta from scipy.stats import bernoulli as bern import numpy as np import matplotlib.pyplot as plt def main(): # 学習データ生成 batch_number = 4 train_size = 400 batch_size = int(train_size / batch_number) mu = 0.7 # 実際のμの値 X = bern.rvs(mu,size = train_size) X = X.reshape([...
""" Geradores => Generators são na verdade Iterators (Iteradores) OBS.: 1- O contrário não é verdadeiro, ou seja, nem todo iterator é um generator. 2- Uma Generator Function não é um Generator. Ela gera um generator! NOTA: 1- Generators podem ser criados com funções ger...
# # Copyright (c) 2014, Prometheus Research, LLC # from setuptools import setup, find_packages setup( name='rex.sms_demo', version='2.0.1', description='Demo package for testing rex.sms', package_dir={'': 'src'}, packages=find_packages('src'), namespace_packages=['rex'], install_requires...
#对全文的代码做一次依赖树检测 import htmlprocess import re import pdb from collections import Counter from graphviz import Digraph from graphviz import Source import base64 import pandas as pd from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np class DependenceTree_fun(): def __init__(self...
import threading import os import sys import re from ConfigParser import ConfigParser from collections import namedtuple from pynq.providers import IPynqProvider from pynq.enums import Actions import psycopg2 import psycopg2.pool DEFAULT_CONFIG_FILENAME = "pgpynq.cfg" CONFIG_FILE_ENV_VAR = "PGPYNQ_CONFIG_FILE" THRE...
species( label = 'C[CH]CC[CH]CCCC(1420)', structure = SMILES('C[CH]CC[CH]CCCC'), E0 = (125.699,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([2750,2761.11,2772.22,2783.33,2794.44,2805.56,2816.67,2827.78,2838.89,2850,1425,1431.25,1437.5,1443.75,1450,1225,1237.5,1250,1262.5,1275,1270,1287.5...
# -*- coding: utf-8 -*- from openerp import models, fields, api, _ class ActionReason(models.Model): """ Show action reason for action type Action. Default module forgot to include 'action' selection """ _inherit = 'hr.action.reason' action_type = fields.Selection(selection_add=[('action', 'Actio...
#!/usr/bin/env python3 with open('input') as f: stream = f.readline().rstrip() inside_garbage = False nest_level = 0 score = 0 removed_garbage = 0 pending_exclamation_mark = False for c in stream: if pending_exclamation_mark: pending_exclamation_mark = False ...
# 13_frogger.py # # B. Kell 11/2018 update 11/2020 # # Modified by: Ben Goldstone # Date: 11/17/2020 # # This is a game inspired by the old video game "Frogger". In this simplified # version, the player must navigate a frog across six lanes of traffic to # land on one of three lily pads. Player wins if a...
from typing import Optional, List # allows the pulling of data from apis from requests import Session # exceptions for debugging from pulling data from apis from requests.exceptions import ConnectionError, Timeout, TooManyRedirects # allows reading json outputs import json # imports... time stuff from time import s...
from django.core.management.base import BaseCommand from django.contrib.auth.models import User class Command(BaseCommand): def handle(self, *args, **kwargs): for user in User.objects.all(): print(user.id,"\t", end="") print(user.username,"\t", end="") print(user.email)
from django.shortcuts import render # Create your views here. ## 新しく追加 from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from windletterapi.models import User from windletterapi.serializers import MessageSerializer, ChangeDataSerializer ## @a...
# coding: utf-8 # In[ ]: import pandas as pd pd.set_option('precision', 2) from pandas.plotting import scatter_matrix from pandas.plotting import autocorrelation_plot from pandas.plotting import lag_plot from io import StringIO import numpy as np import datetime import matplotlib import matplotlib.pyplot as plt #% ...
import unittest import csv from src.chat import * from src.chat_ops import * from src.swen344_db_utils import connect class TestChat(unittest.TestCase): def test_build_user(self): """rebuild the user table""" conn = connect() cur = conn.cursor() rebuildTables() ...
import rosbag import pickle import numpy as np bag = rosbag.Bag("../dataCollection/12_sept/loop1.bag") data = [[0.,0.,0.,0.,0.,0.,0.]] latestMocap = [0.,0.,0.] latestUwb = [0.,0.,0.,0.] for topic, msg, t in bag.read_messages(topics=["/uwb", "/vrpn_client_node/bot/pose"]): if(topic == "/vrpn_client_node/bot/pose"...
import sys args = sys.argv[::-1] args.pop() text = "" for i in args: i = i[::-1] text += i if i != args[-1] and i != "": text += " " text = text[:-1] string = "" for j in text: if j.isupper() == True: string += j.lower() elif j.islower() == True: string += j.upper() else...
# -*- coding: utf-8 -*- # @Time : 2019/5/3 16:43 # @Author : LegenDong # @User : legendong # @File : dataloaders.py # @Software: PyCharm import torchvision from torch.utils import data from torchvision import transforms __all__ = ['Cifar100DataLoader'] class Cifar100DataLoader(data.DataLoader): MEAN = ...
def greet_user(): # Get the user's name and age name = input("What's your name? ") age = int(input("How old are you? ")) # Print a greeting message print(f"Get off my lawn, {name}!")
import csv import matplotlib.pyplot as plt from evaluationMeasures import * from knn import * from kfold import * import sys if __name__ == '__main__': # Number of fold and number of neighbor (parameters) numberOfFold = 10 numberOfNeighbor = 3 # Input from command line (command prompt or linux shell)...
from xgo_spider_log import spider_start, spider_stop, spider_aborting from xgo_spider_log import spider_node_start, spider_node_stop, spider_node_aborting from xgo_spider_log import queue_remaining, crawl_content, general_log, general_log_info spider_start() crawl_content('酒店详情') crawl_content('酒店详情', 10) queue_rema...
#!/usr/bin/env python import os import sys import commands import time def info(message): print "%s" % message sys.stdout.flush() def error(message): kill() print "ERROR: %s\n" % message sys.stdout.flush() sys.exit(1) def make(): """make sure a make file exists, and m...
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class HotelItem(scrapy.Item): name = scrapy.Field() type = scrapy.Field() region = scrapy.Field() prefecture = scrapy.Field() city...
# coding utf-8 import redis import json import pickle import numpy as np import random import jieba import multiprocessing import sys reload(sys) sys.setdefaultencoding('utf-8') word2idx, idx2word, allwords, corpus = None, None, {}, [] DUMP_FILE = 'data/basic_data_700k_v2.pkl' check_sample_size = 10 TF_THRES = 5 DF_TH...
import os import cv2 import copy import numpy as np import tkinter as tk from tkinter import ttk from PIL import Image, ImageTk import xml.etree.ElementTree as ET # TODO: Allow changing the class when clicking the label. # Todo: Allow preset of labels from where to choose the default. # TODO: Issue with the storing...
#!/opt/scaleavvenv/bin/python3 # EASY-INSTALL-ENTRY-SCRIPT: 'hdmi-matrix-controller==0.0.0','console_scripts','hdmi-mx' __requires__ = 'hdmi-matrix-controller==0.0.0' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys....
from rest_framework.views import exception_handler def custom_exception_handler(exc, context): print("got here") response = exception_handler(exc, context) if response is not None: response.data['message'] = "samuel same" return response
#!/usr/bin/env python # -*- coding:utf-8-*- import csv import chardet import io # csv_file_name="test_utf8.csv" csv_file_name="test_sjis.csv" with open(csv_file_name, "rb") as csv_file: binary = csv_file.read() ret_dict = chardet.detect(binary) # 文字コードを判定 print(ret_dict) # 判定した文字コードなどの情報を出力 reader = ...
import pygame class Images(): """This class is useful to upload images whit some necessary attributess to work in pygame""" def __init__(self, image_file, location, new_size=0): self.image = pygame.image.load(image_file) if new_size: #This allow change the size of the image self.im...
# coding=utf-8 # date: 2018-9-24,18:49:56 # name: smz class Array(object): """实现一个可以保存任何类型的数组 需要使用列表来实现,因为列表可以保存任何对象 基本功能: 1.在给定的位置访问或者替代数组的一个项 [] --> __getitem__(index) \__setitem__(index, newItem) 2.查看数组的长度 len() --> __len__ 3.获取数组的字符串表示 str() --> __str__ 4.使用for循环 fo...
from django.conf.urls import url from django.urls import path,re_path from DataModel import views urlpatterns = [ re_path(r'^test/(?P<m>[0-9]{2})/$', views.testroute), url(r'^uploadfile/',views.testupload), url(r'createtableandaddbasedata',views.CreateTableAndInsertBaseData), url(r'createtableand...
""" A quick script that scans a *.tex file and searches for all of the citations within it. For any citation that is formatted with an ADS-compatible bibstring (i.e. 2013ApJ...768L..14P, or 2011MNRAS.412.1441L), this script will pull the bibtex entry from ADS and will insert them all into a .bib file. -I Shivvers...
my_name = "Sreehari" my_age = 34 # its true my_height = 167 #cms my_weight = 96 #kgs my_eyes = "Black" my_teeth = "Yellowish" my_hair = "gray" print(f"let's talk about {my_name}.") print(f"He's {my_height} centemers tall.") print(f'He\'s {my_weight} pounds heavy.') print("Actually that heavy.") print("H...
from django.contrib import admin from django.urls import path from user import views urlpatterns = [ # path('/', ), ]
# Generated by Django 2.2.2 on 2019-07-10 15:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('jcbose', '0009_auto_20190710_2103'), ] operations = [ migrations.AlterField( model_name='post', name='Mobile_no', ...
import pycodestyle from textwrap import dedent from flake8_print import PrintChecker import pytest from six import PY2, PY3 import sys class CaptureReport(pycodestyle.BaseReport): """Collect the results of the checks.""" def __init__(self, options): self._results = [] super(CaptureReport, ...
#!/usr/bin/env python # coding: utf-8 '''法1:迭代法,写法最简洁,但是效率最低,会出现大量的重复计算,时间复杂度O(1.618^n),而且最深度1000 ''' # In[22]: def fibonacci(n): if n<=1: return n else: return fibonacci(n-1)+fibonacci(n-2) re=[] x=int(input("请输入需要的斐波那契数的项数:")) for i in range(1,x+1): re.append(fibonacci(i)) prin...
import unittest import os import torch from torch.optim import Optimizer import apex from apex.multi_tensor_apply import multi_tensor_applier from itertools import product class RefLAMB(Optimizer): r"""Implements Lamb algorithm. It has been proposed in `Large Batch Optimization for Deep Learning: Training BE...
from django.db import models # Create your models here. class Articles(models.Model): """docstring for Articles""" title = models.CharField(max_length = 120) post = models.TextField() date = models.DateTimeField() def __str__(self): #when we call Articles title it will show title and not something unexpected...
import cv2 import time import imutils cam=cv2.VideoCapture(0) time.sleep(1) firstframe=None area=500 val=0 #process one capture the image while True: _,img=cam.read() #displaying the text inside of the camera feed text="Normal" img=imutils.resize(img,width=300,height=300) grayimage=...
#Faça um programa que pergunte o preço de três produtos e informe qual produto você deve comprar, sabendo que a decisão é sempre pelo mais barato. preco_prod_1 = float(input("Insira o valor do produto 1 R$: ")) preco_prod_2 = float(input("Insira o valor do produto 2 R$: ")) preco_prod_3 = float(input("Insira o valor d...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'c:\Users\dell\Desktop\TD-FALCON\DQN_version\TD_Falcon.ui' # # Created by: PyQt5 UI code generator 5.13.0 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtGui import ...
class TestInitException(BaseException): 'Test init exception => Unresolved test' pass class TestRunException(BaseException): 'Test run exception => Failed test' pass class TestValidateException(BaseException): 'Test validation exception => Failed test' pass class TestCleanupExcept...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Data pre-processing: build vocabularies and binarize training data. """ import argparse import glob import os impor...
# -*- coding: utf-8 -*- """ Name create_MESH_drainage_database. previously called lc_vectorbased Purpose The purpose of this script is to calculate land cover fractions for each subbasin of interest. Then the landcover is converted the (subbasin*lc_types) it is adhered to the driange database. Progra...
import matplotlib.pyplot as plt """ Function to draw a rectangle in matplotlib """ def draw_rectangle(y_min, y_max, x_min, x_max): plt.hlines(y_min, x_min, x_max) plt.hlines(y_max, x_min, x_max) plt.vlines(x_min, y_min, y_max) plt.vlines(x_max, y_min, y_max) """ Training Data for the learner """ train...
# -*- coding:utf-8 -*- ''' Created on 2013-3-9 @author: sunlzx ''' import sys import locale if __name__ == '__main__': pass #如果不换行,需要添加","号 print("line"), ; print("newline"); print "line", "newline"; print; print "=========" ''' 格式化输出 ''' count = 10; name = "总问" print locale.getdefaultlocale() print sys.get...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 2 11:12:06 2019 @author: lxu """ import numpy as np import sklearn as sklearn import itertools class IRTprob(object): def __init__(self, epsilon=1, _lambda=0.1, momentum=0.8, maxepoch=20, num_batches=300, batch_size=1000): self.eps...
# -*- coding: utf-8 -*- import scrapy import os,json,HTMLParser import time import MySQLdb from scrapy.selector import Selector from zhihu.items import UserItem from zhihu.myconfig import UsersConfig from zhihu.myconfig import DbConfig class UsersSpider(scrapy.Spider): name = 'users' domain = 'https://www.zhih...
#-*- coding:utf8 -*- import yaml from sqlalchemy.sql import select from sqlalchemy import and_ from core.models import session,HostUser,User,Group,Host,User2Group,HostUser2Group from bin.yunserver import start from core.models import Base,engine def format_yaml(yfile): try: f = open(yfile,'r') d ...
# O(2^n) because it ends up looking like a binary search tree def fib(n): if n == 0 or n == 1: return n return fib(n - 1) + fib(n - 2) # O(n), O(1) space fibs = {} # if the fibonacci number of a given number n has been computed # before return it # otherwise recurse => find fib of n - 1 and fib of n ...
#!/usr/bin/python3 # SORAY CENGİZ ELM 463 PROJECT # 03.01.2021 17:40 # Kodu çalıştırabilmek ilgili modüllerin yüklü olduğundan emin olunuz import plotly.express as px import plotly.graph_objects as go from skimage import data, filters, measure, morphology import sys import numpy as np import cv2 as cv import matplo...
class Solution: """ @param: s: A string @param: wordDict: A set of words. @return: All possible sentences. """ def wordBreak(self, s, wordDict): # write your code here return self.dfs(s, wordDict, {}) def dfs(self, s, wordDict, mem): if s in mem: return m...
from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import * from devices_ui import Ui_Form import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'vm')) from device import Device class DevDockWidget(QDockWidget, Ui_Form): def __init__(self, parent = None): QDockWidg...
import os import shutil import time class Storage(dict): """ Storage is just a special dict. :key: should be a string key :value: should be a stream of bytes """ def PACKAGES(self): raise NotImplementedError class InMemoryStorage(Storage): pass class FileStorage(Storage): ...
"Constants\n\nThis module contains constants used in the Cognite Python SDK.\n\nThis module is protected and should not used by end-users.\n\nAttributes:\n BASE_URL (str): Base url for Cognite API. Should have correct version number.\n LIMIT (int): Limit on how many datapoints should be returned from the...
# coding=utf-8 import traceback import mysql.connector import xlwt import setting import json def execute_query(sql, args): host, port, user, password, database = get_mysql_props() conn = mysql.connector.connect(host=host, port=port, user=user, password=password, database=database) cursor = conn.cursor(...
from django.views.generic import DetailView, ListView, UpdateView, CreateView from .models import City, Country, Address, Province from .forms import CityForm, CountryForm, AddressForm, ProvinceForm class CityListView(ListView): model = City class CityCreateView(CreateView): model = City form_class = Ci...
def makeArrayConsecutive2(statues): # > HINT! Before solving any problem first of all try to # > solve it in your mind and then try to write code. # In this case the amount of statues needed will be the max # height minus the minimum height. Then in order to understand # the amount of statues needed...
import torch import numpy as np from torchvision import datasets from data import data_transforms import numpy as np import matplotlib.pyplot as plt import cv2 from model import Net state_dict = torch.load('experiment/model_7.pth') model = Net() model.load_state_dict(state_dict) features_blobs = [] def hook_feature(m...
from __future__ import division import numpy as np import matplotlib.pyplot as plt import csv import pandas as pd from random import sample def change(a): if a == "yes": return 1 return 0 filename = "housing.csv" raw_data = open(filename, 'rt') df = pd.read_csv(filename) df.drop("Unnamed: 0",axis...
# Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com> # # This file is part of paramiko. # # Paramiko is free software; you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (a...
""" """ # Standard Library import inspect # Third Party # Local def dump_args(frame): # frame = inspect.currentframe() args, _, _, values = inspect.getargvalues(frame) print('function name "%s"' % inspect.getframeinfo(frame)[2]) for i in args: print(" %s = %s" % (i, values[i])) return...
# coding: utf-8 import os from sanic import Sanic from sanic.response import json from sanic_jinja2 import SanicJinja2 from jinja2 import FileSystemLoader from sanic_plugin_toolkit import SanicPluginRealm from sanic_oauthlib.provider import oauth1provider import sqlalchemy as sa from sqlalchemy.ext.declarative import d...
import numpy as np import gzip import cPickle import sys import random from getAttrfromSeq import * import seqVectorizer as sv class dataProssesor(object): """ This class can read specific data files and unpak its content it can process data vectors format and pack them into the the type used by dbm.py ...
################## # Allison and Pan (Group 4) # Step 3 of Project 1 # This file receives the accelerometer data from the logger microbit # and converts it into a tuple that can be graphed ################# import microbit as mb import radio radio.on() # Turn on radio radio.config(channel=4, length =100) print('Pro...
#!/usr/bin/env python3 """ This script is used to monitor the contents of the two grading queues (interactive & batch). USAGE: ./grading_done.py [or] ./grading_done.py --continuous """ import argparse import os from pathlib import Path import subprocess import time import psutil import json import time import da...
from capabilities.capability import capability # Used for bash commands (when required), unix-only import subprocess # used to sanitize bash input when complex commands are required, unix-only from pipes import quote import glob from enum import Enum from collections import OrderedDict class tasks(capability): ...
import datetime import string from django.middleware import transaction from django.utils import timezone from django.shortcuts import render,get_object_or_404,render_to_response from django.views.decorators.http import require_http_methods from django.http import HttpResponseRedirect,HttpResponse from django.core.url...
import httplib2 import json from INFaaS import settings """ App for Human Activity Recognition """ def request(): # Prepare connection to INFaaS conn = httplib2.HTTPConnection(settings.SERVER_HOST, settings.SERVER_PORT) # Prepare contexts for testing context_query = {} context_query["source"] = 2 ...
import falcon import logging from certidude import authority from certidude.auth import login_required, authorize_admin from certidude.decorators import serialize, csrf_protection logger = logging.getLogger("api") class SignedCertificateListResource(object): @serialize @login_required @authorize_admin ...
from otQuery import otQuery from ot_field import ObjectId, StringVal, ReferenceVal, DateTimeVal,\ ReferenceToUserVal class user(object): def __init__(self): self.folder = r"00. MasterData\05. People\05.1 Persons\User Accounts" self._id = ObjectId('objectId') self._firstname = ...
from django.core import mail from rest_framework import status from rest_framework.test import APITestCase from ..models import Course class CoursesGet(APITestCase): def setUp(self): Course.objects.create( title="Rust", description="Uma linguagem capacitando todos a construir sof...
import numpy as np import torch def benchmark(net,num_clust,dataloaders_,epochs,cluster_nets): """ A function that allows you to train a model for each cluster, print results and store the best performing epoch's mape result. It decides the best epoch using the mape score. params: - net (nn.Module): model. - n...
numero = int(input('Digite um número inteiro: ')) soma = 0 i = 1 while i <= numero: soma += i i += 1 print(f'A soma dos números de 1 até {numero} = {soma}')
#!/usr/local/bin/python3 print("knuth") # i = i + m - (l-1) # data = "abacbbababcabcabbab" pattern = "ababc" # build table of shift amounts shifts = [0] * (len(pattern) + 1) shift = 0 for pos in range(len(pattern)): while shift <= pos and pattern[pos] != pattern[pos-shift]: shift += shifts[pos-shift] s...
n=int(input()) a=[int(i) for i in input().split()] maximum=max(a) count=0 for i in a: if i==maximum: count+=1 print(count)
# encoding: utf-8 """ learning """ x = 3 print x x += 2 print x x -= 1 print x x,y=99,3 print x,y my_list = [] my_list.append(1) my_list.append(2) my_list2 = [55.55,"Hi",3,99,222,222] my_list2[0]=333.333 print len(my_list),sum(my_list),my_list2.count(222) print my_list2[1] print my_list2[0],my_list[1:3]...
from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from ping_pong.serializers import PingPongSerializer from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema # Create your views here. class PingPongView(APIView): @swagge...
# File: pruebas.py # Del capítulo 15 de _Algoritmos Genéticos con Python_ # # Author: Clinton Sheppard <fluentcoder@gmail.com> # Copyright (c) 2017 Clinton Sheppard # # 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 ...
from ..cw_controller import CWController # Class for /sales/orders from . import order class OrderAPI(CWController): def __init__(self, **kwargs): self.module_url = 'sales' self.module = 'orders' self._class = order.Order super().__init__(**kwargs) # instance gets passed to parent...
from flask import Flask, render_template, request, redirect, flash, session import re app = Flask(__name__) app.secret_key = 'lol' @app.route("/") def main(): return render_template("index.html") @app.route("/result", methods=["post"]) def result(): if len(request.form['name']) < 1 or len(request.form['comme...
# -*- coding: utf-8 -*- __all__ = ["unit_vector", "unit_disk", "angle", "periodic"] import aesara_theano_fallback.tensor as tt import numpy as np import pymc3.distributions.transforms as tr class AbsoluteValueTransform(tr.Transform): """ """ name = "absolutevalue" def backward(self, y): u = 2 ...
# Generated by Django 3.0.4 on 2020-03-25 21:28 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('isp', '0020_auto_20200326_0327'), ] operations = [ migrations.AlterField( ...
from selenium.webdriver.common import keys from selenium.webdriver.common.by import By from utils.miscellaneous import months from time import sleep class SkipLaggedHomeFlightSearchPage: _home_header = (By.ID, "home-container") _trip_type = (By.XPATH, "//div[@class='skip-select passengers-input-container trip...
import os #from google.cloud import bigquery from google.oauth2 import service_account def test(): print("test succeeded") class Access(object): """ Instantiate environment variables """ def __init__(self): self.app_id = os.environ['FACEBOOK_APP_ID'] self.app_google_cloud_service_accoun...
import sys sys.setrecursionlimit(1 << 20) INF = float('inf') def read_int_list(): return list(map(int, input().split())) def read_ints(): return map(int, input().split()) def f(v): v = list(str(v)) v.sort() return int(''.join(v[::-1])) - int(''.join(v)) def main(): N, K = read_ints() ...
# We will read content from the file and then we will print it with open('test_files/file_for_reading.txt') as fr: file_contents = fr.read() print("File contents are", file_contents) # Now we will write some random number import random with open('test_files/file_for_writing.txt', 'w') as fw: fw.write(rando...
#!/usr/bin/env python import os import sys import argparse import pysam def break_count(bamfn, chrom, poslist, minpad=5, flex=1): bam = pysam.AlignmentFile(bamfn, 'rb') altcount = 0 refcount = 0 discards = 0 tsd_start = min(poslist) tsd_end = max(poslist) tsd_len = tsd_end - tsd_sta...
import requests from datetime import datetime from bs4 import BeautifulSoup """현재 날짜""" year = datetime.today().year month = datetime.today().month day = datetime.today().day """웹페이지 크롤링""" webpage = requests.get(f"https://search.naver.com/search.naver?where=news&sm=tab_jum&query={day}%EC%9D%BC").text soup = Beautifu...
from InProjectComboBox import * class StratigraphicUnitComboBox(InProjectComboBox): def __init__(self, parent, managementDialogClass, finderClass): DataSelectionComboBox.__init__(self, parent, StratigraphicUnitManagementDialog,...
#!/usr/bin/env python # coding: utf-8 # In[ ]: def single_gradient(x_train,y_train, learning_rate,m): m_slope = [0 for i in range(x_train.shape[1])] M = x_train.shape[0] N = x_train.shape[1] for j in range(N): for i in range(M): x = x_train[i] y = y_train[i] ...
import redis from hashlib import md5 import random import requests import json class chat_cache: def __init__(self): pool = redis.ConnectionPool(host='chat-redis.izdgsg.ng.0001.apse1.cache.amazonaws.com', port=6379, decode_responses=True) self.r = redis.Redis(connection_pool=pool) self.url = "http://cognitiv...
# -*- coding: utf-8 -*- import os import sys import json import string import random import requests import subprocess import urllib.request # ディレクトリを作成する def mkdir(dirpath): try: print("%s %s %s start" % (__file__, sys._getframe().f_code.co_name, ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import time import signal import argparse import asyncio import pygazebo import numpy as np from PIL import Image from pynput import keyboard ''' gz topic -l gz joint -m 'simple_diff' -j right_wheel_hinge --vel-t 0 gz world --reset-all renice -n 15 ...
# coding:utf-8 import unittest,time import requests import re host = "http://127.0.0.1:81" class FaTie(): def __init__(self, s): self.s = s # 初始化 def fatie(self): url = "" body = {} r = self.s.post(url, data=body) return r.content def is_fatie_sucess(self): ...
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def printLeaves(root): if root: printLeaves(root.left) if not root.left and not root.right: print(root.data,end=" ") printLeaves(root.right) def printBoun...
# -*- coding: utf-8 -*- """ Created on Wed Oct 14 22:22:33 2020 @author: lenovo """ import os import pandas as pd data_location = "excelfile/" if os.path.exists(data_location) and os.path.exists("mainfile.xlsx"): for file in os.listdir(data_location): print("...Merging file "+file) df= pd.read_exc...
import codecs import time from six.moves.urllib.parse import urlencode, urlsplit, parse_qs from django.conf import settings from django.core.cache import cache from graphite.http_pool import http from graphite.intervals import Interval, IntervalSet from graphite.logger import log from graphite.node import LeafNode, ...
#recommendation engine #item similarity based recommendation #importing libs import pandas as pd import numpy as np from scipy.sparse import csr_matrix books = pd.read_csv('finalData.csv') #create a pivot table books_pivot = books.pivot(index='bookTitle',columns = 'userID', values = 'bookRating').fillna(0) books_m...