text
stringlengths
38
1.54M
from collections import defaultdict import numpy as np from math import floor from numpy import random class Rule: def __init__(self, conditions, result): self.conditions = conditions self.result = result self.numerosity = 1 self.__match_count = 0 self.correct_count = 0 ...
from django.conf import settings from django.core.mail import send_mail # 导入Celery类 from celery import Celery # 这两行代码需要的启动worker 的一端打开 # 初始化django所依赖的环境 import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dailyfresh.settings") # 创建一个Celery类的对象 app = Celery('celery_tasks.tasks', broker='redis://127.0.0.1:6379/5...
from . import result from .base import Base from .json_type import JSON from sqlalchemy import Column, UniqueConstraint from sqlalchemy import ForeignKey, Integer, Text from sqlalchemy.orm import relationship, backref from sqlalchemy.orm.session import object_session from sqlalchemy.orm.exc import NoResultFound from .....
# -*- coding:utf-8 -*- import sys from probs import * class losHelper: cookie = "" def prob_choose(self): try: print("문제의 이름을 입력하세요. : ") prob = sys.stdin.readline().split() prob = ''.join(prob) globals()[prob](self.cookie) ex...
import testFIXParser import testFIXSpec import testFields import testFIXSession import testRejects import testIntermittentGaps import unittest def test_suite(): modules = [testFIXParser, testFIXSpec, testFields, testFIXSession, testRejects, ...
try: from StringIO import StringIO except ImportError: from io import StringIO text = StringIO("""Id|Name|Divisor|Description 1|Cognitive|6|NULL 2|Emotional|6|NULL 3|Physical|8|NULL 4|Financial|5|NULL""")
from django.shortcuts import render, redirect from django.core.urlresolvers import reverse from .models import Author, Review, Book from ..login_register .models import User # Create your views here. def index(request): user_obj = User.objects.get(id=request.session['user']) book_obj = Book.objects.all().orde...
# -*- coding: utf-8 -*- """Common PageObject actions.""" import hashlib import io import logging import random import string import sys import time import traceback import uuid from collections import defaultdict, namedtuple from contextlib import contextmanager from io import BytesIO from types import FunctionType, Mo...
from django.contrib import admin from .models import Merchandise # Register your models here. admin.site.register(Merchandise)
from argparse import Namespace import test import numpy as np import torch np.random.seed(42) torch.manual_seed(0) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False opt_v = '01' model = 'm02' epoch = 'latest' epochs_to_test = ['latest', '1', '15', '30', '45', '60', '70'] if opt_v == '0...
from DoubleLinkedList import Node,DoublyLinkedList def palindrome(doublyLinkedList): startPointer = doublyLinkedList.head endPointer = doublyLinkedList.head while endPointer.next is not None: endPointer = endPointer.next while True: if startPointer == endPointer: print("List...
import numpy as np import pandas as pd # # GEOMETRIES # def centroid_3d(arr): length = arr.shape[0] sum_x = np.sum(arr[:, 0]) sum_y = np.sum(arr[:, 1]) sum_z = np.sum(arr[:, 2]) return sum_x / length, sum_y / length, sum_z / length def rescale_3d(X, x_scale, y_scale, z_sca...
from django.contrib.auth.models import User from django.db import models from django.dispatch.dispatcher import receiver class UserInfo(models.Model): """Model for storing extra information related to a user. """ owner = models.OneToOneField(User, related_name='extra_info', primary_key=True, ...
#!/usr/bin/env python # coding: utf-8 # In[22]: import json import pandas as pd import requests import numpy as np from numpy import nan import geopandas import matplotlib.pyplot as plt import folium import seaborn as sns import streamlit as st import plotly.graph_objects as go import folium from streamlit_folium im...
#!/usr/bin/env python import string from collections import OrderedDict START_LETTERS = { 'A': 10, 'B': 2, 'C': 2, 'D': 5, 'E': 12, 'F': 2, 'G': 3, 'H': 3, 'I': 9, 'J': 1, 'K': 1, 'L': 4, 'M': 2, 'N': 6, 'O': 7, 'P': 2, 'Q': 1, 'R': 6, ...
from django.contrib.auth import authenticate, login from django.shortcuts import render, redirect from django.contrib import messages from .forms import RegistrationForm def register(request): if request.method == 'GET': form = RegistrationForm() return render(request, 'registration/register.html',...
ASCII_SIZE = 256 def get_max_occuring_character(str): count=[0]*ASCII_SIZE max = -1 c = '' for i in str: count[ord(i)]+=1 for i in str: if max<count[ord(i)]: max = count[ord(i)] c = i return c str = 'sample striiiiiiiing' print(get_m...
#!/usr/bin/env python __author__ = "Fabio Giuseppe Di Benedetto" import os import os.path import zipfile import glob # folders rcm_folder = "../RCM" firos_folder = ".." rcm_src_folder = os.path.join(rcm_folder, "src") rcm_scripts_folder = os.path.join(rcm_folder, "scripts") rcm_cfg_folder = os.path.join(rcm_folder, ...
import hashlib from django.conf import settings def click_authorization(click_trans_id, amount, action, sign_time, sign_string, merchant_trans_id, merchant_prepare_id=None, *args, **kwargs): """ Authorization :param click_trans_id: :param amount: :param action: :param s...
# Entrada eje_x = int(input("Ingrese la primera cordenada en el eje x\n")) eje_y = int(input("Ingrese la segunda coordenada en el eje y\n")) coordenada = [eje_x,eje_y] distancia = (eje_x - 0)/(eje_y - 0) print("Cordenada: ",coordenada) print("La distancia de la coordenada [0,0] a la coordenada ingresada es: ", dista...
# -*- coding: utf-8 -*- #import visa import random import Tool param={'FLOW':'mbarl/s','P1':'mbar'} class Instrument(Tool.MeasInstr): def __init__(self, resource_name, debug=False): super(Instrument, self).__init__(resource_name,'PL300',debug,baud_rate=19200) def __del_...
ramit = { 'name': 'Ramit', 'email': 'ramit@gmail.com', 'interests': ['movies', 'tennis'], 'friends': [ { 'name': 'Jasmine', 'email': 'jasmine@yahoo.com', 'interests': ['photography', 'tennis'] }, { 'name': 'Jan', 'email': 'jan@hotmail.com', 'interests': ['movies',...
from setuptools import setup, find_packages def do_setup(): setup(name='News_Buddy', version="0.0", author='Lilian Luong, Ameer Syedibrahim, Jaden Tennis', description='News database by topic and named entities', platforms=['Windows', 'Linux', 'Mac OS-X', 'Unix'], ...
from flask import ( Blueprint, flash, g, redirect, render_template, request, url_for ) from werkzeug.exceptions import abort from flaskr.auth import login_required from flaskr.db import get_db bp = Blueprint('blog', __name__) @bp.route('/') def index(): db = get_db() posts = db.execute( 'SELECT ...
from database.utils.JSON import to_json from database.application.function_mapper import get_db_functions from database.utils.answer import Answer def check_super_system_function(name): function_mapper = get_db_functions() function_info = function_mapper[name] if function_info[1].function_type == "system"...
import os.path import random import torchvision.transforms as transforms #import torch from data.base_dataset import BaseDataset from data.image_folder import make_dataset from PIL import Image import mxnet as mx class AlignedDataset(BaseDataset): def initialize(self, opt): # self._provide_data = zip(data...
from __future__ import print_function import pickle from game import Board, Game from mcts_pure import MCTSPlayer as MCTS_Pure from mcts_alphaZero import MCTSPlayer from policy_value_net_pytorch import PolicyValueNet, Net # from policy_value_net_numpy import PolicyValueNetNumpy as PolicyValueNet import sys from collect...
import sys w = [int(x) for x in sys.argv[1].split(',')] s = [int(x) for x in sys.argv[2].split(',')] b = int(sys.argv[3]) assert len(w) == len(s) matrix = [[None for x in range(sum(w))] for y in range(len(w))] def dump_matrix(): elements_width = max(len(str(sum(w))), len(str(len(w)))) for i in range(len(matrix)...
import standard class Hunter(standard.Character): def __init__(self): self.hit_list = [] def on_see_entry(self, char): if char.id in self.hit_list: attack(ch, "backstab") # not implemented
# -*- coding: utf-8 -*- from flask import Flask, render_template from utils import gametype, mapname, colour, geoip, trim import parser import pylibmc from cache import Cache app = Flask(__name__, static_folder="./static") backend = pylibmc.Client(["127.0.0.1"]) cache = Cache(backend) @cache("iw4m-html", time=180) @...
from sqlalchemy.orm.exc import FlushError __author__ = 'ada' import os import sys from sqlalchemy import Column, ForeignKey, Integer, String, Binary from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class La...
def test_47(): assert num_to_english(47) == 'Fourty Seven' def test_27(): assert num_to_english(27) == 'Twenty Seven' def test_7(): assert num_to_english(7) == 'Seven' def test_17(): assert num_to_english(17) == 'Seventeen' def test_33(): assert num_to_english(33) == 'Thirty Three' def test_50(): ...
import tensorflow as tf import numpy as np import os import train import time import cv2 MOVING_AVERAGE_DECAY = 0.99 EVAL_INTERVAL_SECS = 10 image_size = 128 img = cv2.imread("qqq.jpg") img0 = cv2.resize(img, (128, 128)) img2 = tf.cast(img0,tf.float32) img3 = tf.reshape(img2,(1,128,128,3)) y = train.inference(img3) q...
# -*- coding: utf-8 -*- # @Organization : insightface.ai # @Author : Jia Guo # @Time : 2021-05-04 # @Function : from __future__ import division import glob import os.path as osp import numpy as np import onnxruntime from numpy.linalg import norm from ..model_zoo import model_zoo from ..utils...
# -*- coding: utf-8 -*- """ @Time : 2020/6/8 15:44 @Author : QDY @FileName: 234. 回文链表_快慢指针+翻转链表.py 请判断一个链表是否为回文链表。 示例 1: 输入: 1->2 输出: false 示例 2: 输入: 1->2->2->1 输出: true 进阶: 你能否用O(n) 时间复杂度和 O(1) 空间复杂度解决此题? """ # Definition for singly-linked list. # class ListNode: # ...
import pystray from PIL import Image, ImageDraw from pystray import Menu, MenuItem from flask import Flask import threading import signal import os import subprocess app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/shutdown') def shutdown(): subprocess.call('shu...
from app.views import * from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('create/',CreateUser.as_view(),name="create"), path('users/',ListUser.as_view(),name="list"), path('users/delete/<int:pk>',DeleteUser.as_view(),name="delete"), ...
sistema=None class lector: @staticmethod def leer(sistema,queue1, queue3): f = open("example.txt") sistema.makeProcess(f.readlines(),queue1,queue3)
from setuptools import setup, find_packages version = '1.6' setup(name='bhr-client', version=version, description="BHR Client", long_description="Client for the BHR Blackhole Router site", classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords...
""" Neha Bais Calculates gratuity nd total from gratuity rate and subtotal entered by User !!! """ gratuity_rate = eval(input("Enter a gratuity rate in % : ")) subtotal = eval(input("Enter the subtotal : ")) gratuity = (gratuity_rate * subtotal) / 100 total = subtotal + gratuity print ("The gr...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt import netCDF4 as netcdf from matplotlib import dates as mdates import EuroSea_toolbox as to from mpl_toolkits.basemap import Basemap import pickle """ Step 1: ...
import torch import torch.nn as nn import torch.nn.functional as F class AlexNet(nn.Module): def __init__(self): super(AlexNet, self).__init__() # convolution part self.conv1 = nn.Conv2d( in_channels=3, out_channels=96, kernel_size=11, stride=...
from django.shortcuts import render, HttpResponse, redirect from .models import * from django.contrib import messages def index(request): return render(request,'login_app/index.html') def processreg(request): result = User.objects.validate_registration(request.POST) if result['status']: #that means if ...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- mod=1000000007 t=int(input()) for i in range(t): n=int(input()) ans=chk=mod l=[int(i) for i in input().split()] w={} ans=chk=mod for j,k in enumerate(l): if k not in w: w[k]=j else: w[k]=-1 for j in w: ...
# coding= utf-8 import socket info = b'my name is tony' for i in range(256): ip = "192.168.102.101" client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) client.sendto(info, ("192.168.102.101", 8081))
# Problem Source: LeetCode # Given a string, find the first non-repeating # character in it and return it's index. If it doesn't exist, return -1. # Examples: # s = "leetcode" # return 0. # s = "loveleetcode", # return 2. # Note: You may assume the string contain only lowercase letters. ### ### ### def firstUniqCh...
import requests_mock import koji import pytest from koji_builder_kube import cli, errors def test_session_setup_error_type(): with pytest.raises(errors.KojiError): cli.session_setup({}) def test_session_setup_error_auth(fixtures_dir): data = { 'serverca': f'{fixtures_dir}/ca.pem', 'cert': f'{fixtur...
from concurrent.futures import ( ProcessPoolExecutor, ThreadPoolExecutor, ) from time import perf_counter as pc from Crypto.Random import atfork from Crypto.Util.number import getPrime bits = 2 ** 11 count = 40 max_count_workers = 20 def get_prime(count_primes): atfork() return getPrime(bits) exec...
# last element as pivot def quick_sort(array, low, high): #if high == low if low >= high: return pivot = partition(array, low, high) quick_sort(array, low, pivot) quick_sort(array, pivot+1, high) def partition(array, low, high): # i - bound between elements less than pivot and ele...
# Cardinal numbers # Ordinal numbers # Clock time # Digital clock # 24 hr by quarters # Starts at # Dates rod = { 'mz': 'mužské životné', 'mn': 'mužské neživotné', 'f': 'femininum', 'n': 'neutrum' } pád = { 1: 'nominativ', 2: 'genitiv', 3: 'dativ', 4: 'akusativ', 5: 'vokativ'...
from service.Generator import Generator from service.Validator import Validator OUT_FILE_NAME = "out/out.txt" IN_FILE_NAME = "out/in.txt" def main(): test = list(range(50, 501, 50)) # indexy = ['136774', '136785', '136812', '136815', '132336', '136803', '132639', '136814', '136807', '136798', # ...
# -*- coding: utf-8 -*- a = float(raw_input('Informe o valor primeiro lado: ')) b = float(raw_input('Informe o valor segundo lado: ')) c = float(raw_input('Informe o valor terceiro lado: ')) if (a < b + c) and (b < c + a) and (c < b + a): print 'É triângulo' if a == b and b == c and a == c: tipo = 'T...
def add(pieces_dict, p_add, c_add, k_add): if p_add in pieces_dict: print(f"{p_add} is already in the collection!") else: pieces_dict[p_add] = {'composer': c_add, 'key': k_add} print(f"{p_add} by {c_add} in {k_add} added to the collection!") return pieces_dict def remove(pieces_dic...
#!/usr/bin/env python """Train a sentence piece model.""" __author__ = 'Erdene-Ochir Tuguldur' import argparse import sentencepiece as spm parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--vocab-size", type=int, default=32000, help='vo...
# -*- coding:utf-8 -*- """网站导航""" class KgcmsApi(object): """KGCMS框架接口""" kg = db = None def __init__(self): pass def __call__(self): from kyger.kgcms import template from kyger.utility import date, numeric, html_escape, alert, is_format from kyger.upload import Uplo...
from .model import db from .model import Graph, Vertex, Pipeline, Edge, Track from .settings import URL, DATABASE, DATABASE_DEBUG from .model import Database #创建DAG #创建图的函数 def create_graph(name, desc=None): g = Graph() g.name = name g.desc = desc db.session.add(g) try: db.session.comm...
things="Apples Oranges Crows Telephone Light Sugar" stuff=things.split(" ") more=["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] while len(stuff) !=10: next=more.pop() print ("next is %s" % next) stuff.append(next) print (stuff) print (stuff[1]) print (stuff[-1]) print (stuff.pop()) print (...
from sqlalchemy import Column, Integer, String, Boolean, ForeignKey from sqlalchemy.orm import relationship from .declarative_base import Base class Estudiante(Base): __tablename__ = "estudiante" idEstudiante = Column(Integer, primary_key=True) apellidoPaterno = Column(String) apellidoMaterno = Column...
t = int(raw_input()) # read a line with a single integer for p in xrange(1, t + 1): N=int(raw_input()) lines=[] for x in xrange(1,2*N): lines.extend([int(s) for s in raw_input().split(" ")]) solder=[] for i in xrange(len(lines)): if lines[i] in solder: solder.remove(lines[i]) ...
# Copyright (c) James Percent and Unlock contributors. # All rights reserved. # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this l...
import logging import os from pprint import pprint as pp, pformat as pf import click from click_configfile import matches_section, Param, SectionSchema, ConfigFileReader # from click_repl import repl from ubus import Ubus logging.basicConfig(level=logging.INFO) _LOGGER = logging.getLogger(__name__) logging.getLogger...
from scipy import integrate import numpy as np # just a bunch of IMF functions def kroupa(M, alpha_1 = 0.3, alpha_2 = 1.3, alpha_3 = 2.3, xi_o = 1.0): M = np.asarray(M) scalar_input = False if M.ndim == 0: M = M[None] scalar_input = True low_mass = M[ (M <= 0.08) ] mid_mass = M[ ...
import random import time number = random.randint(1, 10) attempt = 0 when_things_went_wrong = time.time() approved_chars = [str(i) for i in range(1, 11)] while True: if attempt == 0: ges = input('Угадай число от 1 до 10: ') elif attempt == 1: print('Да ладно, с кем не бывает') ges = inpu...
# Модуль для проверки ответов к Заданию № 07 from openpyxl import load_workbook from openpyxl.styles import Font import sys import error_rate as er import source_codes as sc import linear_codes as lc from pprint import pprint as pp import numpy as np from random import random import pytils.translit import re def has_n...
import httplib2 from apiclient.discovery import build from oauth2client.file import Storage from oauth2client.client import flow_from_clientsecrets from oauth2client import tools # Define service object as a global variable service = "" def main(): # *** AUTHORIZATION *** global service flow = flow_from...
__all__ = ["Listener"] import logging from select import select from typing import ( Any, Callable, Optional, ) from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT from .base import BaseCommuter from .connector import Connector logger = logging.getLogger("pgcom") class Listener(BaseCommuter): ...
########################################################### # Print student and course information # nathanLanLab1.py # 6.17.2020 ########################################################### print("Hello World!") #assign information to variables last_name = "Lan" g_number = "G01246656" syl_1 = "Assesments are due Tuesd...
from __future__ import print_function import copy import logging import numpy as np import torch import torch.nn.functional as F import torch.nn as nn import torch.utils.data as td from PIL import Image from tqdm import tqdm import trainer import networks class Trainer(trainer.GenericTrainer): def __init__(self...
# -*- coding: utf-8 -*- # Generated by Django 1.11.11 on 2018-03-15 10:21 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cmdb', '0001_initial'), ] operations = [ migrations.AddField( ...
#!/usr/bin/python3 def common_elements(set1, set2): res = [] for i in set1: if i in set2: res.append(i) return res
from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine engine = create_engine('sqlite+pysqlite:///db/blockchaindb.sqlite') Base = declarative_base(bind=engine) Session = sessionmaker(bind=engine)
import json import requests def get_summary(cid): url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%d/description/json" % cid result = requests.get(url) summary = json.loads(result.content) return summary def parse_summary_for_odor(summary): statements = [] # keywords should in...
from django.db import models #add blank=True if not possible - This results in value of 0 #add null=True if may be unknown #use .TextField() for unrestricted length(description) class Order(models.Model): order_create_date = models.DateField() pickup_date = models.DateField() return_date = models.DateField() custo...
from flask import render_template, request, session, redirect from qa327 import app import qa327.backend as bn import re """ This file defines the front-end part of the service. It elaborates how the services should handle different http requests from the client (browser) through templating. The html templates are sto...
""" SYS-611: Buffon's Needle Experiment Example with Antithetic Variables. This example performs a Monte Carlo simulation of Buffon's Needle Experiment to estimate the probability of a needle of certain length crossing lines on a floor with certain spacing. This probability is proportional to the mathematical constant...
from rest_framework import viewsets # from models import from serializers import * class FileViewSet(viewsets.ModelViewSet): serializer_class = FileSerializer # permission_classes = [CustomPermission] # search_fields = ('name', 'description') model = File filter_fields = ('content_type', 'object_i...
import random import string from django.db.models import Q def get_group_members(message, user): members = [] members_qs = message.group.members.filter( ~Q(id=user.id) ) for mem in members_qs: members.append(mem.id) return members def get_message_content(message): details = {...
import pytest @pytest.fixture(name="flask_live_url") def _flask_live_url(live_server): yield live_server.url() @pytest.fixture() def app(): from nexxera.nix.app import create_app config_updates = { "FLASK_TEST": True, "SQLALCHEMY_DATABASE_URI": "sqlite:///:memory:", }...
# -*- coding: utf-8 -*- """ Created on Fri Jun 17 17:09:52 2016 http://stackoverflow.com/questions/9401658/matplotlib-animating-a-scatter-plot """ import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation def main(): numframes = 100 numpoints = 10 color_d...
"""Original source: https://github.com/utkuozbulak/pytorch-cnn-visualizations. Created on Sat Nov 18 23:12:08 2017 @author: Utku Ozbulak - github.com/utkuozbulak """ import logomaker import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import torch from torch.nn import Parameter from tor...
from __future__ import annotations from slay.entity.unit.base import Unit class Peasant(Unit): upkeep = 2
"""The views that takes care of authantication.""" from django.contrib.auth import authenticate, login from django.utils.decorators import method_decorator from django.views.generic.edit import CreateView from buildservice.utils.decorators import anonymous_user_required @method_decorator(anonymous_user_required, nam...
from typing import List from soda.sodacl.check_cfg import CheckCfg class ColumnChecksCfg: def __init__(self, column_name: str): self.column_name = column_name self.check_cfgs: List[CheckCfg] = [] def add_check_cfg(self, check_cfg: CheckCfg): self.check_cfgs.append(check_cfg)
#!/usr/bin/env python3 import sys import time import numpy as np from PyQt6.QtCore import QObject, QThread, pyqtSignal from PyQt6.QtGui import QImage, QPixmap from PyQt6.QtWidgets import (QApplication, QDialog, QLabel, QProgressBar, QPushButton, QVBoxLayout, QWidget) from trainscanner im...
// # nano pythonS1script1 // ---------- import getpass import sys import telnetlib HOST = "192.168.122.71" user = raw_input("Enter your telnet username: ") password = getpass.getpass() tn = telnetlib.Telnet(HOST) tn.read_until("Username: ") //username prompt tn.write (user + "\n") if password: tn.read_until("P...
# https://leetcode.com/problems/climbing-stairs/ from typing import Dict class Solution: def climbStairs(self, n: int) -> int: cache = {1: 1, 2: 2} return self.climbStairsWithCache(n, cache) def climbStairsWithCache(self, n: int, cache: Dict[int, int]) -> int: if n in cache: ...
"""In this experiment instead of training a CTRNN we construct it directly. The goal is to demonstrate, that CTRNN can solve algorithmical problems very efficiently""" from tools.experiment import Experiment from brain_visualizer.brain_visualizer import BrainVisualizerHandler from tools.configurations import Experime...
d = {'a':10, 'b':4, 'e':22, 'd':11, 'c':5} tmp = list() #빈 리스트에 / 위 딕셔너리의 튜플값을 원소를 넣어라 for k,v in d.items() : tmp.append( (v,k) ) tmp = sorted(tmp, reverse=True) print(tmp) #결과값 = [(22, 'e'), (11, 'd'), (10, 'a'), (5, 'c'), (4, 'b')] for a,b in tmp : print(a,b) #결과값 #22 e #11 d #10 a #5 c #4 b
from __future__ import print_function import pytz import dateutil.parser import httplib2 from oauth2client import tools from oauth2client import client import datetime import logging from googleapiclient.discovery import build from oauth2client.file import Storage import Settings import os try: import argparse ...
from parsec import * from datetime import datetime from clize import run from copy import deepcopy import requests import json from bson.json_util import dumps, CANONICAL_JSON_OPTIONS datasource = 'https://discover.data.vic.gov.au/api/3/action/datastore_search?resource_id=afb52611-6061-4a2b-9110-74c920bede77&limit=100...
MOVE_SPEED_CHASE = 15 MOVE_SPEED_RUN = 10 TURN_SPEED = 6 TIME_REFRESH = 0.05 TIME_DURATION = 30 # I need a pull request FAKE_CONSTANT = 20 RULE_LINE = "Space - Start\nW \ I - Up\nS \ K - Down\nA \ J - Left\nD \ L - Right "
""" Ejercicio 1: Hacer un programa que tenga una lista de 8 numeros enteros. Y que haga: -Recorrer la lista y mostrarla. -Hacer una funcion que recorra listas de strings y devuelva un string -Ordenarla y mostrarla -Mostrar su longitud. -Buscar algun eleme...
import numpy as np if __name__ == "__main__": StartTime = '2016-07-26 00:00:00' # setdata_cnn.GetOracleDataSample(109.0, 25.0, '2016-07-26 00:00:00', '2016-07-31 00:00:00', 30, 5, 20, 0.5) predictlabels = np.loadtxt("data_cnn/" + StartTime + "pred_labels.txt") samplelabels = np.loadtxt("data_cnn/" + Sta...
import pymysql def data_stu_Sclass_update(Sno,Sclass): stat = 0 conn = pymysql.connect(host = '192.168.123.209',user = 'root',passwd = '123456',db = 'kaoqinxitong',charset = 'utf8') c = conn.cursor() sql_str = "UPDATE Student SET Sclass = '"+Sclass+"' WHERE Sno ='"+Sno+"'" try: c.execute(s...
import pandas as pd from scipy.stats import ttest_ind data = {'Category': ['cat2','cat1','cat2','cat1','cat2','cat1','cat2','cat1','cat1','cat1','cat2'], 'values': [1,2,3,1,2,3,1,2,3,5,1]} my_data = pd.DataFrame(data) print(f'My_Data:\n{my_data}') print('*************************************************') my_d...
from Testing import ZopeTestCase from Products.Extropy.tests import ExtropyTrackingTestCase from Products.CMFPlone.utils import _createObjectByType from DateTime import DateTime from Products.Extropy.browser.managementreports import WeeklyReport class Dummyhours: """fake worked hours""" def __init__(self, h...
import unittest import import_ipynb import pandas as pd import pandas.testing as pd_testing class Test(unittest.TestCase): def setUp(self): import Calculating_Descriptive_Statistics self.exercise = Calculating_Descriptive_Statistics self.games = self.exercise.games def test_proportion_of_4_5(self): # cover...
#!/usr/bin/env python """Concatenate fasta records in multiple fasta files """ import argparse import logging from Bio import SeqIO from collections import defaultdict __author__ = "Matthew Whiteside" __copyright__ = "Copyright 2015, Public Health Agency of Canada" __license__ = "APL" __version__ = "2.0" __maintai...
import urllib2, socket, getproxylist, json socket.setdefaulttimeout(180) nUsuarios = input("Cuantos usuario deseas crear? ") def is_bad_proxy(pip): try: proxy_handler = urllib2.ProxyHandler({'http': pip}) opener = urllib2.build_opener(proxy_handler) opene...
from time import sleep from page.page_in import PageIn from tools.get_driver import GetDriver import page from tools.get_log import GetLog log = GetLog.get_logger() class TestMisAudit: # 初始化 def setup_class(self): # 获取driver driver = GetDriver.get_driver(page.url_mis) # 获取 统一入口类 ...