text
stringlengths
8
6.05M
#!/usr/bin/env python3 # # This is the output that I will get from my mycalendar1.py program. # Day Time Subject Monday 9:10 AM - 10:15 AM LA 10:35 AM - 11:40 AM SS 12:10 PM - 1:15 PM ...
class Node: def __init__(self, key, value): self.key = key self.value = value self.prev = None self.next = None class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.hashmap = {} # Initialize dummy nodes self.head = Nod...
from django.shortcuts import render from .forms import ContactForm def contact(request): human = False if request.POST: form = ContactForm(request.POST) if form.is_valid(): human = True else: form = ContactForm() return render(request, 'contact.html', { 'fo...
from django.urls import path, include from . import views from rest_framework import routers import sys router = routers.DefaultRouter() router.register('employer', views.EmployerView) router.register('contacts', views.ContactsView) urlpatterns = [ path('', include(router.urls)), path(r'xls/', views.export_xl...
arr = [3,5,1,7,8,12,9,2,2,0] def mergesort(arr): n=len(arr) if n==1: return mid=n//2 left = arr[:mid] right = arr[mid:] mergesort(left) mergesort(right) l=0 m=0 p=0 nl=len(left) nr=len(right) while l < nl and m < nr : if left[l] <= right[m]: arr[p]=left[l] l += 1 else: arr[p]=right[m] ...
from django.test import TestCase from django.contrib.auth.models import User from django.contrib import messages class TestViews(TestCase): def test_registration_new_user(self): page = self.client.post('/accounts/registration/', { 'username':'test_us...
from seat.applications.TeacherApplication import TeacherApplication from seat.applications.CourseApplication import CourseApplication from seat.applications.ExamApplication import ExamApplication from django.http import JsonResponse from api.helpers import endpoint_checks from django.core.urlresolvers import reverse im...
#ATUL_KONAJE 5198 #CSE6331 ATUL.KONAJE@mavs.uta.edu import pymongo from pymongo import MongoClient import hashlib from bson.binary import Binary from datetime import datetime import base64 #Get MongoDB instance mClient =MongoClient() #Create/Get existing DB mDB=mClient.Photobook_db def enc_pwd(passwd): return has...
#!/usr/bin/python # -*- coding: UTF-8 -*- """" набор Pytest тестов для тестирования restfull версии приложения geo_map """ import pytest from fastapi.testclient import TestClient from app_fast_api import app client = TestClient(app) def test_read_root(): response = client.get("/", headers={"X-Token": "coneofs...
from piece import * from board import Board from player import Player """ RUNS BY CYCLES >Each cycle is when both White and Black make a move. >Stars the game by a White Move. >Every move, checks if the game is finished, prints board, and prints the last move of the game. >For each move: >1. Ask the position of the p...
import sys __all__ = ['apply_all_config', 'apply_config', 'get_config', 'load_module'] def apply_all_config(config_module): keys = dir(config_module) for k in keys: if k[:2] == '__' or type(getattr(config_module, k, None)) == 'function': continue apply_config(k, getattr(config_mo...
from django.shortcuts import render # Create your views here. def home(request): return render(request,'newsApp/index.html') def sportsnews(request): head_msg='Sports news' msg1='No T20 world cup this year' msg2='IPL postponed' msg3='Paskitan players test positive for covid19' my_dict={'head_ms...
# -*- coding: utf-8 -*- import numpy as np import tensorflow as tf from vgg19_v26 import vgg19 import os from PIL import Image from PIL import ImageEnhance import matplotlib.pyplot as plt from tqdm import tqdm img_H,img_W,img_C = 500, 800, 3 vgg19net = vgg19(trainable=False) img = tf.get_variable(name='wanted', shape...
# -*- coding: utf-8 -*- """Tests for API renderers.""" from __future__ import unicode_literals from django.test import RequestFactory from rest_framework.serializers import ListSerializer from rest_framework.utils.serializer_helpers import ReturnDict, ReturnList import mock from .base import TestCase from webplatform...
class Merge_sort: ''' 归并排序 ''' def sort(self, nums): ''' : type nums: List[int] 要排序的数组 ''' self.merge_sort(nums, 0, len(nums)-1) def merge_sort(self, nums, left, right): if left < right: mid = (left + right)//2 self.merge_sort(nums, l...
import time import sys import dask.dataframe as dd import pandas as pd #from memory_profiler import profile def timefunc(f): def f_timer(*args, **kwargs): start = time.time() result = f(*args, **kwargs) end = time.time() print ('... Time run ==>' ,f.__name__, 'took', rou...
from roboclaw import * M1Forward(128,16) M2Forward(128,16) M2Forward(129,16)
import numpy as np import torch import torch.nn as nn import torch.nn.init as init import torch.nn.functional as F from torch.autograd import Variable def l2norm2d(inputs, k): # k dimension to normalize norm = torch.sqrt(torch.sum(inputs * inputs, k)) + 1e-12 return inputs / norm.expand_as(inputs) class ...
from flask import render_template,request from DCapi import app from DCapi.humanresource.data.user import users @app.route('/',methods=['get','post']) def index(): return '11' #return render_template('test.html',url='/login',form=True) @app.route('/login',methods=['get','post']) def login(): formdata=requ...
""" Example script using PyOpenPose. """ import argparse from libs import pyopenpose as op import time import cv2 import os OPENPOSE_ROOT = os.environ["OPENPOSE_ROOT"] def run(): cap = cv2.VideoCapture(args.filename) params = dict() params["model_folder"] = OPENPOSE_ROOT + os.sep + "models" + os.sep p...
"""undeadthread URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-...
# -*- coding: utf-8 -*- # @Time : 2019/5/16 2:29 PM # @Author : Shande # @Email : seventhedog@163.com # @File : db_config.py # @Software: PyCharm class DBConfig(object): """redis的db配置: db=1:用户登陆 """ _redis_conf = { 'host': '101.132.186.25', # 'host': '47.100.63.158', # ...
""" Dash port of Shiny faithful example: https://shiny.rstudio.com/gallery/faithful.html Note: the shiny version includes a slider for adjusting the bandwidth of the density approximation curve, which is not easily adjusted when using plotly.figure_factory.create_distplot, so it doesn't feature in this example. """ i...
class PriorityQueue(Queue): def __init__(self, list = [], _ascending = True, _sortFunc = None): super().__init__(*list) self.ascending = _ascending if(_sortFunc is None): _sortFunc = self.defaultSortFunc def defaultSortFunc(self): pass def enqueue(self, item): ...
import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SQLITE = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } POSTGRESQL = { 'default' : { '...
#!/usr/bin/env python3 import os import csv def main(): masterfile = open("graph.csv",'w') writer = csv.writer(masterfile) writer.writerow(["Node", "Connected","Local","Remote"]) row = [] remote = False aruba = False for line in open("CDP-neighbors.txt","r"): #initialize every row o...
from django.shortcuts import render from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.authtoken.models import Token from django.shortcuts import get_object_or_404 from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from res...
# Generated by Django 2.2.6 on 2019-10-02 18:40 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('qrCodeApp', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='qrcodeurldata', options={'verbose_...
#!/usr/bin/env python import pygame import mimo import enum from utils import utils from utils import neopixelmatrix as graphics from utils import ringpixel as ring from utils.NeoSprite import NeoSprite, AnimatedNeoSprite, TextNeoSprite, SpriteFromFrames from utils import constants from scenes.BaseScene import Scene...
import numpy as np import lasagne from braindecode.experiments.experiment import create_experiment def load_model(basename): """Load model with params from .yaml and .npy files.""" exp = create_experiment(basename + '.yaml') params = np.load(basename + '.npy') model = exp.final_layer set_param_valu...
#!/usr/bin/env python # -*- coding:utf-8 -*- # ------------------------------------------------------------------ # -------------------- 实现switch类似功能 -------------------- # ------------------------------------------------------------------ # 实例1 choice = 'ham' print({'spam': 1, 'ham': 1.99, 'eggs': 3, 'bacon': 1...
# 2017-03-11 jkang # practice tf.cond # ref: http://web.stanford.edu/class/cs20si import tensorflow as tf x = tf.random_uniform([], -1, 1) # random value from -1 ~ 1 y = tf.random_uniform([], -1, 1) # random value from -1 ~ 1 out = tf.cond(tf.less(x, y), lambda: tf.add(x, y), lambda: tf.sub(x, y)) ''' if 1st arg of...
# Code by Daniel Kukiela (https://twitter.com/daniel_kukiela) # Originally acquired from the repository by sentdex (https://github.com/Sentdex/pygta5) import ctypes from threading import Thread from time import time, sleep from queue import Queue # main keys class class Keys(object): common = None standalon...
# -*- encoding:utf-8 -*- # __author__=='Gan' # # A self-dividing number is a number that is divisible by every digit it contains. # For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. # Also, a self-dividing number is not allowed to contain the digit zero. # Given a lower an...
#!/usr/bin/env python # -*- coding:utf-8 -*- s = 'spam' # -------------------- 索引和分片 -------------------- # 索引 s[i] 获取指定偏移的元素 # 第一个元素偏移为0 # 最后一个元素偏移为-1 print('-' * 20, ' 索引和分片 ', '-' * 20) print('索引s[1]:\n\t%s' % s[1]) print('索引s[2]:\n\t%s' % s[2]) print('索引s[-2]:\n\t%s' % s[-2]) print('负数索引+字符串长度=索引位置!...
import logging logger = logging.getLogger(__name__) def grab_largest_image(url): import asyncio from pyppeteer import launch async def main(): browser = None try: browser = await launch() page = await browser.newPage() logger.info(f"Opening page {url}"...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Solution(object): def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ if len(s) != len(t): return False a = list(s) a.sort() b = list(t) ...
import functools import itertools import numpy as np import PIL.Image import pytest import torch.testing import torchvision.ops import torchvision.transforms.v2.functional as F from torchvision import tv_tensors from torchvision.transforms._functional_tensor import _max_value as get_max_value, _parse_pad_padding from ...
if __name__ == '__main__': s = "chris alan" a = s.split(' ') r = '' for p in a: r += ' ' + p.capitalize() print(r[1:])
#coding:gb2312 #切片练习题和for循环温习 fruits=['banana','watermelon','apple','strawberry','orange'] friend_fruits=fruits[:]#切片复制列表 fruits.append('litchi') friend_fruits.append('peach')#各自添加 print("My favorite fruits are :") for items in fruits: print(items) print(fruits) print("\nMy friend favorite fruits are :") for items in...
#!/usr/bin/python # -*- coding: UTF-8 -*- """ 题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。 例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。 程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。。 """ print for i in range(100, 1000, 1): x = i / 100 y = i / 10 % 10 z = i % 10 # print z, y, z, i if i == x**3 + y**3 + z...
import sys def tokenize(file_name): """Converts text file to list of tokens Params: file_name - file to tokenized str -> list """ tokens = [] with open(file_name) as file: words = file.read().split(" ") for word in words: tokens.append(word) tokens.pop() re...
import numpy as np A = np.array([[4,-1,-1,0], [-1,4,0,-1], [-1,0,4,-1], [0,-1,-1,4]]) B = np.array([[30], [60], [40], [70]]) casicero = 1e-15 # Evitar truncamiento A = np.array(A, dtype=float) AB = np.concatenate((A,...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2017-12-08 # @Author : ${author} (${email}) # @Link : ${link} # @Version : $Id$ 计算机管理 compmgmt.msc 计算机服务 services.msc 管理员启动命令行 runas /user:administrator cmd 设置任务计划模块自动运行 sc config schedule start= auto 启动任务计划程序 taskschd.msc /s pip install -U pip pip list -...
#!/usr/bin/python -tt # # Copyright (c) 2011 Intel, Inc. # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the Free # Software Foundation; version 2 of the License # # This program is distributed in the hope that it will be us...
import matplotlib.pyplot as plt import test_dev.data as data_collection max_batch_sizes = [] time_commit = [] num_tran = 0 time_ = 0 for data in data_collection.data: tran = data.get("num_transactions") time = data.get("commit_time") max_batch_size = data.get("max_batch_size") max_batch_sizes.append(m...
#coding:utf-8 template_variables = dict( title=u'Docker管理平台', name =u'Docker管理平台', username="", ) DATABASES = dict( DB='shipman', USERNAME='root', PASSWORD='oldboy@123', HOST='192.168.11.122', PORT=3306, ) NODE_LIST = ['node_ip', 'port'] COOKIE_NAME = "user_id"
from django.core.cache import cache from django.core.urlresolvers import reverse from django.db.models import Q, Avg from django.http import HttpResponse, HttpResponseNotFound, Http404 from django.template import RequestContext, loader import json from web.models import Category, Submission, VoteCategory def category(...
from django.db import migrations election_title_map = { "mayor.bedford.2019-05-02": "Mayor of Bedford", "mayor.bedford.2021-01-01": "Mayor of Bedford", "mayor.bristol.2016-05-05": "Mayor of Bristol", "mayor.bristol.2020-05-07": "Mayor of Bristol", "mayor.bristol.2021-01-01": "Mayor of Bristol", ...
from pydantic import BaseModel class UserCreateResponse(BaseModel): code: str = None # data: dict = {"Oauth-Token": str, "expire": 86400*7} data: dict msg: str = None class Config: orm_mode = True class UserCurrentResponse(BaseModel): code: str = None # data: dict = {"nickname": ...
from setuptools import setup def readme(): with open('README.md') as f: return f.read() setup( name = 'ryser', version = '0.0.12', packages = ['ryser',], description = "Latin squares and related designs.", author = "Matthew Henderson", author_email = "matthew.james.henderson@gmail....
import sys import time import threading import logging from library.vpm import BinaryOut logger = logging.getLogger(__name__) class vdm(threading.Thread): def __init__(self, config,callback): threading.Thread.__init__(self) self._config = config self._callback = callback self....
el_before = 2 el = 1 ans = 1 for i in range(2,int(input())+1): ans = el + el_before el_before = el el = ans print(ans)
from rest_framework import serializers from . import models class ChoiceSerializer(serializers.ModelSerializer): class Meta: model = models.Choice fields = ('id', 'description', ) class PollSerializer(serializers.ModelSerializer): choices = ChoiceSerializer(many=True, read_only=True) cl...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2019-05-21 07:08 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('edu', '0009_auto_20190519_2222'), ] operations = [ ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Sep 8 17:44:53 2019 @author: Zackerman24 """ """For checking correct coord entry, could make sure entry is in A - F and 1-6""" """Shave off extra space on any user input""" """Make sure coordinate entries are unique, not duplicative""" import numpy a...
import sys sys.path.append('C:\\Users\\nikit\\AppData\\Local\\Programs\\Python\\python38\\lib\\site-packages') import NBodyPlotter as nbp from NBodyPlotter import NBodySolver from NBodyPlotter import Body import matplotlib.pyplot as plt import numpy as np #Define scale values to keep close to unity mass_scale = 1e30 #...
from src.entity.article import Article from src.configure import environment, runTime import json def orgnizeJson2ArticleList(jsonStrs): jsonDataList = json.loads(jsonStrs.decode('utf8')) articleList = [] for jsonData in jsonDataList: article = Article() article.title = jsonData.get('title'...
#!/usr/bin/python3 class Edureka: empcount=0 '''Explaining Edureka Class''' print("Edureka. __dict__:",Edureka.__dict__) print("Edureka. __dict__:",Edureka.__name__)
# This is where the answers to Chapter 9 questions for the BSS Dev RampUp go # Name:
import re from django.db import models import bcrypt # Create your models here. class Dog(models.Model): name = models.CharField(max_length=10) is_good = models.BooleanField(default=True) img_url = models.CharField(max_length=255) bio = models.TextField() breed = models.CharField(max_length=15) ...
import socket import time from threading import Thread def make_request(): start_time = time.time() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', 8000)) sock.send(b'GET /\n\n') resp = sock.recv(100) sock.close() end_time = time.time() print(time.str...
#! /usr/bin/env python """ Program FMC and FTD using YAML file for user data. """ import fmcapi import logging from ruamel.yaml import YAML from pathlib import Path import argparse def main(datafile): """Grab the data from the yaml file and send it to program_fmc().""" yaml = YAML(typ="safe") path = Path(...
# Generated by Django 2.1.5 on 2019-02-26 10:20 from django.db import migrations, models import jsonfield.fields class Migration(migrations.Migration): dependencies = [ ('loader', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='missingobse...
from .vec3 import Vec3 class BlockEvent: """An Event related to blocks (e.g. placed, removed, hit)""" HIT = 0 def __init__(self, type, x, y, z, face, entityId): self.type = type self.pos = Vec3(x, y, z) self.face = face self.entityId = entityId def __repr__(self): ...
import base64 from subprocess import Popen, PIPE import threading import os from time import time from hashlib import sha256 _author__ = 'Ritwik' def thread_create(pr_func): import Queue def func_wrapper(pr_queue, *args): func_result = pr_func(*args) pr_queue.put(func_result) ...
from redis import Redis redis_connection = Redis(db=1, decode_responses=True) list_key = "example-list" redis_connection.rpush(list_key, 1, 2, 3, 4, 5) print(redis_connection.lrange(list_key, 0, -1))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Feb 15 12:14:45 2020 @author: adeela """ ''' https://opensource.com/article/18/3/loop-better-deeper-look-iteration-python https://nedbatchelder.com/blog/201608/breaking_out_of_two_loops.html https://www.youtube.com/watch?v=u8g9scXeAcI ''' # =======...
import pygame from pygame.locals import * import pygame.mixer import serial import time #portStr = '\dev\ttyACM0' #arduino = serial.Serial('/dev/ttyACM0', 9600) pygame.display.set_mode((120, 120), DOUBLEBUF | HWSURFACE) pygame.init() pygame.mixer.init() snare = pygame.mixer.Sound('snare.wav') crash = pygame.mixer.S...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSymmetric(self, root: TreeNode) -> bool: return self.isMirror(root, root) def isMirror(self, t1: TreeNode, t2: TreeNode): ...
default_config = { # buffer bounds for first cull of objects not on chip # in arcsec 'bounds_buffer_uv': 16.0, # allowed values in the bitmask image 'bitmask_allowed': 0, # cutout types in addition to 'image'. Allowed values are # ['weight','seg','bmask'] 'cutout_types': [], # de...
# -*- coding: utf-8 -*- import os os.getcwd() #获取当前工作目录 os.chdir('D:\python_learning') #修改当前工作目录 import pandas as pd from pandas import Series,DataFrame import matplotlib.pyplot as plt #字符串处理 import re text = "foo bar\t baz \tqux" re.split('\s+',text) #列出字符串中包含了某些字符的项目 #flmData[flmData['rflfln'].str.contains(...
# -*- coding: utf-8 -*- ''' HTTP base handlers. ''' # This file is part of citadel. # Distributed under the terms of the last AGPL License. # The full license is in the file LICENCE, distributed as part of this software. __author__ = 'Team Machine' from tornado import web class BaseHandler(web.RequestHandle...
from django.urls import path from ebooks.api.views import (EbookDetailAPIView, EbookListCreateAPIView, ReviewCreateAPIView, ReviewDetailAPIView) urlpatterns = [ path("ebooks/", EbookListCreateAPIView.as_view(), name="ebook-list"), path("ebooks/<int:pk>/", ...
from matplotlib.pyplot import * from glob import glob from datetime import datetime import matplotlib.pyplot as plt from numpy.random import randn from os import path import pandas as pd import numpy as np def file_search_glob(inpath, condition): return glob(inpath + '\\'+condition) def Get_rtrs(xlspath): a...
# -*- coding: utf-8 -*- # # Copyright (c) 2012, Clément MATHIEU # All rights reserved. # # 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...
class Solution: def findLongestWord(self, s: str, d: List[str]) -> str: def is_subseq(main: str, sub: str) -> bool: i, j, m, n = 0, 0, len(main), len(sub) while i < m and j < n and n - j >= m - i: if main[i] == sub[j]: i += 1 j += 1...
import pickle path = "../models/%s/svhn/num_clusters_100/cluster_%u/record.pkl" clusters = 100 names = ["einet_0_0", "einet_0_1"] c_idx = [i for i in range(clusters)] for name in names: avg_best = 0.0 for c in c_idx: try: f = path % (name, c) l = pickle.load(open(f, 'rb')) ...
with open('input_xr.txt') as f: data_list = f.read().splitlines() data_list = [int(i) for i in data_list] for i in range(len(data_list)): for j in range(i, len(data_list)): for k in range(j, len(data_list)): if(data_list[i] + data_list[j] + data_list[k] == 2020): result...
from os import environ from os.path import join as path_join if "ISISROOT" not in environ.keys(): environ["ISISROOT"] = environ["CONDA_PREFIX"] if "ISISDATA" not in environ.keys(): environ["ISISDATA"] = path_join(environ["ISISROOT"], "data")
import re email_address = 'Please contact us at: support@datacamp.com' match = re.search(r'([\w\.-]+)@([\w\.-]+)', email_address) if match: print(match.group()) # The whole matched text print(match.group(1)) # The username (group 1) print(match.group(2)) # The host (group 2)
# Created by Luis A. Sanchez-Perez (alejand@umich.edu). # Copyright © Do not distribute or use without authorization from author import tensorflow as tf class SpectrogamSequencer(tf.keras.layers.Layer): """ A non-trainable layer to generate a sequence of potentially overlapping window from an input spectrogram...
from celery.decorators import periodic_task from celery.schedules import crontab from django.conf import settings from django.template.loader import get_template from django.template import Context from django.core.mail import EmailMultiAlternatives import redis import json @periodic_task(run_every=(crontab(minute=...
class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ # at the beginnning set it to empty list combinations = [] self.helper(digits, combinations.append, 0, []) return combinations def helper(s...
import re from emailReceive import EmailReceive from emailSend import EmailSend class EmailUtil(object): @staticmethod def getLink(address,password,title=('title',),regular=r'http',findAll=False,debug=0): print('Getting into EmailReceive............') allRes = EmailReceive(address, password).ge...
#!/usr/bin/env python # coding: utf-8 # In[ ]: # 查看当前挂载的数据集目录, 该目录下的变更重启环境后会自动还原 # View dataset directory. This directory will be recovered automatically after resetting environment. get_ipython().system('ls /home/aistudio/data') # In[ ]: # 查看工作区文件, 该目录下的变更将会持久保存. 请及时清理不必要的文件, 避免加载过慢. # View personal work direc...
from sklearn.linear_model import LinearRegression import statsmodels.api as sm import pandas as pd import numpy as np import matplotlib.pyplot as plt #분석할 데이터 불러오기 data = pd.read_csv("./regressionData(2019).csv", na_values=[999]) df = pd.DataFrame(data, columns = ['학업스트레스', '가족스트레스', '우울', '스마트폰중독']) # 상관 분석을 하고자 하는 컬...
import os import pandas as pd from openpyxl import load_workbook name = input("Enter your name - ") df = pd.DataFrame({'Name' : [name]}) writer = pd.ExcelWriter('new.xlsx', engine='openpyxl') writer.book = load_workbook('new.xlsx') writer.sheets = dict((ws.title, ws) for ws in writer.book.worksheets) reader = pd.read_e...
# -*- coding: utf-8 -*- import factory from factory.django import DjangoModelFactory from ralph.accounts.tests.factories import UserFactory from ralph.operations.models import ( Change, Failure, Incident, Operation, OperationStatus, OperationType, Problem ) def get_operation_type(name): ...
import time import winsound from multiprocessing import Process, Event, Lock from pyemotiv import Epoc from pyfob import Fob WINL = 300 def emotiv(e): epoc = Epoc() fid = open('emotiv.dat', 'w') e.wait() t0 = time.time() tp = time.time() while tp - t0 < WINL: tp = time.time() ...
import mechanize def readFile(path): file = open(path,'r') content = file.read() return content arrayLogins = readFile('logins_gmail.txt').split('\n') url = "https://accounts.google.com/ServiceLoginAuth" browser = mechanize.Browser() browser.set_handle_equiv(True) browser.set_handle_redirect(True) browse...
# Given a m * n matrix of distinct numbers, return all lucky numbers # in the matrix in any order. # # A lucky number is an element of the matrix such that it is the # minimum element in its row and maximum in its column. class Solution: def luckyNumbers(self, matrix): return set(min(row) for ...
from datetime import datetime # 1. "{:04d}" now = datetime.now() cur_year = now.year cur_month = now.month cur_day = now.day date_str = "{:04d}-{:02d}-{:02d}".format(cur_year, cur_month, cur_day) print(date_str) # 2. "{:.2f}" value = "{:.2f}".format(3.1415926) print(value) ''' [result] 3.14 ''' value = "{:+.2f}".f...
import requests import time from bs4 import BeautifulSoup from recipes.models import Recipe class BudgetByteScraper: """ Scrapes recipe data from budgetbytes.com and loads it into app database """ def __init__(self): self.recipe_list = [] self.count = 0 def populate_recipe_list(...
#!/usr/bin/python3 ''' 0x0A-python-inheritance module ''' def is_same_class(obj, a_class): ''' Returns True if the object is exactly an instance of the specified class; otherwise False. ''' return type(obj) is a_class
import discord from discord.ext import commands import wolframalpha import aiohttp, io, asyncio import requests, json import shutil, os import time import tokens from bs4 import BeautifulSoup as soup from urllib.request import urlopen as uReq # globals TOKEN = tokens.DISCORD_TOKEN WOLFRAM_ID = tokens.WOLFRAM_TOKEN cl...
import threading import time import logging logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-10s) %(message)s') def daemon(): logging.debug('Starting') time.sleep(2) logging.debug('Exiting') d = threading.Thread(name='daemon', target=daemon) d.setDaemon(True) def non_daemon(): ...
# coding: utf-8 import MeCab f = open("../Rakuten-real-/userID150-165.csv") li = [] for id in f: li.append(id[:-1]) parse = MeCab.Tagger("mecabrc") for user in range(397,400): g = open("../rakutendb/150-165/"+li[user]+".csv") bg = open("../rakutendb/150-165lda/"+li[user]+".csv","w") hhh = 0 fo...
import time import requests import json from spotibot.core.objects import Time as spottime, User as user from spotibot.core.utils import Hasher as hasher from spotibot.mongo.utils.Handlers import get_serializable # TODO: Need to have something here that indicates downstream actions to not # even attempt to execute...
import sys import os import gitlab # TODO setup a test to make sure everything is working # TODO add support for multi-line comments accepted_file_types = {'.py': ['#todo', '# todo'], '.c': ['//todo', '// todo'], '.cpp': ['//todo', '// todo'], '.js': ...