text
stringlengths
38
1.54M
from . import ffi as ffi from typing import Any def address_of_symbol(name: Any): ... def add_symbol(name: Any, address: Any) -> None: ... def load_library_permanently(filename: Any) -> None: ...
''' Created on Jul 3, 2015 @author: kieran ''' from spectral_tools import Sav_Template,apply_window from functions import log_n from echo_tools import * import pylab as p from general_tools import progress_bar,pload,pdump from time import time import pickle as pkl T=2009. d0=11000.#distance to Cas a (=3.4kpc mag_base...
#!/usr/bin/python3 #-- coding: utf-8 -- import time import subprocess import os import telebot import urllib #modulo tratamento urls import emoji from emoji import emojize API_TOKEN= '<TOKEN DO SEU BOT>' #Bot gerado pelo BOTFATHER bot = telebot.TeleBot(API_TOKEN, threaded=False) #Sumario do telebot funcao que aplica...
from django.core import serializers from django.core.paginator import Paginator from django.shortcuts import render, redirect, get_object_or_404 from django.template import loader from django.utils import timezone from django.http import JsonResponse from django.db.models import Count from .forms import GrupoForm, Musi...
from abc import ABC, abstractmethod class Invader: INVADER_TYPES = {'goblin': 'green', 'troll': 'grey', 'orc': 'green', 'ogre': 'tan', 'dragon': 'red'} def __init__(self, canvas, path): self._canv = canvas self._path = path self._health = 100 self._size = 4 # radius of circ...
#!/usr/bin/python # -*- coding:UTF-8 -*- ''' // H_FILE_PART1 #ifndef SRC_FILETEXTGENERATOR_HFILEGENERATOR_H_ #define SRC_FILETEXTGENERATOR_HFILEGENERATOR_H_ #include <string> #include "h_file_text_generator.h" using namespace std; class HFileTextGenerator { // H_FILE_PART2 private: int _size; string _fileTex...
""" Created on Mon July 10, 2017 @author: Ruchika Chhabra """ from ConfigParser import ConfigParser class ConfigParse(): ''' DESCRIPTION: ------------ This class reads config.ini file and sets the required user inputs in the class attributes. ATTRIBUTES: ---------- 1...
#!/user/bin/env python # -*- coding: utf-8 -*- # fib def fib(max): n,a,b=0,0,1 while n<max: print b a,b = b,a+b n = n+1 fib(100)
import numpy as np from collections import deque from rdpg_constants import * class ReplayMemory: def __init__(self, state_dim, action_dim): self.index = 0 self.histories = np.zeros((MAX_CAPACITY, LENGTH, state_dim + action_dim)) self.states = np.zeros((MAX_CAPACITY, LENGTH, state_dim)) ...
# Generated by Django 2.2.6 on 2019-12-07 14:46 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('work', '0059_resolutionlink'), ] operations = [ migrations.AlterField( model_name='resolutionli...
from rest_framework.parsers \ import MultiPartParser, \ FormParser, \ FileUploadParser from rest_framework.response import Response from . import models, serializers from rest_framework import generics, status from django.utils.translation import ugettext_lazy as _ from apiNomad.setup import service_init_d...
from pandas import read_csv import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn import preprocessing from sklearn.preprocessing import scale from sklearn.model_selection import train_test_split from sklearn import metrics from sklearn.model...
# -*- coding: utf-8 -*- """ Created on Thu Jan 21 12:53:10 2021 Programme to select all kinematic and kinetic data from a trial, read it in from for single cycle on each side, normalise to gait cycle, plot kinematic and kinetic graph @author: snbar """ import c3dreader import ezc3d import matplotlib.pyplo...
from sqlalchemy import ( Column, String, create_engine, BigInteger, Integer, DateTime) from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import as_declarative, declared_attr from datetime import datetime import functools from blog import app rw_engine = create_engine(app.config['MYSQL_RW'])...
import pybullet_envs import gym import torch import numpy as np from agent import Agent from pybullet_wrappers import RealerWalkerWrapper import argparse import torch torch.autograd.set_detect_anomaly(True) if __name__ == '__main__': parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpForm...
import datetime import json import uuid from django.core.paginator import Paginator from django.http import HttpResponse, JsonResponse from django.shortcuts import render # Create your views here. from django.views.decorators.csrf import csrf_exempt from article.models import Carousel def query_carousel(request): ...
#!/usr/bin/python3 #Run make to update import os import sys import argparse import shutil sys.path.insert(0, "/home/pi/Documents/ScanningSystem/atlundiumberry/") import stepper_helpers as sh #directory in which this file exists #dir_path = os.path.dirname(os.path.realpath(__file__))+"/" dir_path = "/home/pi/Documen...
from urllib import request import os import re def download_file(url, dest_dir): dst_fname = url.split('/')[-1] dst_fname = os.path.join(dest_dir, dst_fname) html = request.urlopen(url) with open(dst_fname, 'wb') as fobj: while True: data = html.read(4096) if not data: ...
""" #冒泡排序 def bubble_sort(alist): n=len(alist) for j in range(0,n-1): count=0 for i in range(0,n-1-j): if alist[i]>alist[i+1]: alist[i],alist[i+1]=alist[i+1],alist[i] count+=1 if count==0: return if __name__=="__main__": alist=[...
import os, sys import glob import pandas as pd import numpy as np import scipy.special import operator from collections import Counter, defaultdict from time import time import datetime import matplotlib.pyplot as plt import matplotlib from Upload_BodyGuardz import * font = {'family' : 'monospace', 'weigh...
import numpy as np from numpy.testing import assert_array_equal from pystruct.inference import inference_lp def test_chain(): # test LP, AD3, AD3-BB and JT on a chain. # they should all be exact rnd = np.random.RandomState(0) for i in xrange(10): forward = np.c_[np.arange(9), np.arange(1, 10)...
# -*- coding: utf-8 -*- """ Created on Mon Oct 3 08:30:22 2016 @author: chris """ import random guesses=0 lownumber =0 highnumber=100 number=random.randint(lownumber,highnumber) print("Is the number ", number, "?") response=input("Respond 'Yes','Higher', or 'Lower':") while response != "Yes": ...
from typing import List import collections class Solution: def maxDistance(self, colors: List[int]) -> int: # min_colors = collections.defaultdict(lambda: 1000) # max_colors = collections.defaultdict(int) # max_distance = 0 # for index, val in enumerate(colors): # min_c...
from Parser import * from ListCreator import * import os import cProfile test = PlayList('https://www.youtube.com/playlist?list=PLMC1lL-g1-zajmJpSneZcXCB-dVpMwbcB','Test Playlist') s = "test = PlayList('https://www.youtube.com/playlist?list=PLMC1lL-g1-zajmJpSneZcXCB-dVpMwbcB','Test Playlist')" print("Tests For %s" % t...
import sqlite3 import sys conn = sqlite3.connect('mollys_mansion.db') c = conn.cursor() name = ("offscreen",) c.execute("select desc from object where name=?", name) p=''.join(c.fetchone()) print(p) running=1 currLocation=" " player=("player",) c.execute("SELECT holder from object where name=?",player) holder ...
def even_or_odd(n): if n % 2 == 0: print("even") return print("odd") # w = even_or_odd(31) #Assigning result of a function call, where the function returns None # odd # print(w) # None
from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return "Hello World!" @app.route('/<userinput>') def hellodojo(userinput): return userinput.title() @app.route('/say/<userinput>') def helloinput(userinput): return "Hi " + userinput.title() + "!" @app.route('/repeat/<num>/<user...
import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) ds = pd.read_csv("./csv-data/site-content.csv", index_col="site_host") # intとobjectの clolumnsを取得する int_cols = [col for col in ds.columns if ds[col].dtype in ["int64", "float64"]] obj_cols = [col for col...
from django.test import TestCase from django.forms.models import model_to_dict from .factories import DemandFactory from ..serializers import DemandSerializer from nose.tools import eq_, ok_ import pytest pytestmark = pytest.mark.django_db class TestCreateDemandSerializer(TestCase): def setUp(self): se...
from flask import ( Blueprint, abort, flash, g, redirect, render_template, request, url_for ) from datetime import datetime from kittycount.db import get_db bp = Blueprint('visits', __name__) @bp.route('/') def index(): db = get_db() visits = db.execute( """ SELECT visits,...
import numpy import sys print(sys.argv) i = int(sys.argv[1]) j = int(sys.argv[2]) a = numpy.random.normal(size=i * j) print("output_%d_%d.txt" % (i, j)) print("output_{}_{}.txt".format(i, j)) info = { "firstvalue": i, "secondvalue": j, } print(info) #print("output_%(firstvalue)d_%(secondvalue)d_%(firstvalue).5...
from flask import Flask, render_template,request,send_from_directory from flask_sqlalchemy import SQLAlchemy from flask_security import Security,SQLAlchemyUserDatastore,UserMixin, RoleMixin, login_required from flask_security.utils import hash_password import json import os file_path = os.path.abspath(os.getcwd())+"\m...
from _utils.pathfinder import get_repo_path import pickle import os class TrainedModelLoader: def __init__(self, experiment): self.experiment = experiment self.xgboost = self._load('xgboost') self.lr = self._load('lr') self.svm = self._load('svm') def _load(self, model_name): ...
#!/bin/python3 # https://www.hackerrank.com/challenges/py-if-else/problem import math import os import random import re import sys def py_if_else(n): if N % 2 > 0: print('Weird') elif 2 <= N <= 5: print('Not Weird') elif 6 <= N <= 20: print('Weird') elif N >= 20: prin...
A=str(input("Numbers:")) a=len(A) b=[] for i in range(0,a): x=A[i] b.append(x) b.sort() print(min(b))
class MyHashTable: def __init__(self, size): self.size = size self.capacity = self.size self.slots = [None] * self.size self.data = [None] * self.size def __setitem__(self, key, value): self.put(key, value) def __getitem__(self, key): try: h = se...
import webapp2 import jinja2 from main import template_dir class Handler(webapp2.RequestHandler): """ Base class handler """ # environment is common for all jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True) def write(self, *a, **kw): self.response.w...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import wx class PlayerInteraction(object): def install(self, controller, pres): self.controller = controller self.presentation = pres pres.Bind(wx.EVT_BUTTON, self.on_button) def on_button(self, evt): btn = evt....
import random import time import allure from allure import description, epic, feature, severity, story from allure_commons.types import Severity from service.macro.define import MacroDefine @epic("TMS-流程引擎") @feature("流程配置") @story("宏定义") @severity(Severity.NORMAL) @description("新建宏定义") def test_create(session): ...
# -*- coding: utf-8 -*- """ Created on Thu Mar 22 12:42:33 2018 @author: Ledicia Díaz """ import numpy as np import matplotlib.pyplot as plt delta_t=0.01 t=0 x=1 y=1 w0=1 b=0 w=1 F=0 x0=1 y0=1 for i in range(1000): x=x0+delta_t*y0 y=y0+delta_t*(-b*y0-w0**2*x0+F*np.cos(w*t)) t=delta_t+t x0=x y0=y ...
# Generated by Django 2.2.2 on 2019-06-27 05:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('images', '0003_auto_20190627_1436'), ] operations = [ migrations.CreateModel( name='Franchise', fields=[ ...
# CMPT 145: Assignment 5 Question 1 # test script import a5q1 as a5q1 import node as N #### UNIT TEST CASES test_item = 'to_string()' data_in = None expected = 'EMPTY' reason = 'Empty node chain' result = a5q1.to_string(data_in) if result != expected: print('Test failed: {}: got "{}" expected "{}" ...
import wx import pymouse import time LIST_COLORS = ['#F7F7F7', '#FFFFFF', '#FCF8E3'] #73879C def hexToColour(value): value = value.lstrip('#') lv = len(value) t = tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3)) return wx.Colour(t[0],t[1],t[2]) class CategoryListPage(wx.Panel): def __init_...
import io import sys import json from datetime import date from bot.data import Gender, Request, Response, parse_request from bot.logger import logger from bot.mood_analyzer import analyze from bot.pattern_recognizer import answer_for_pattern from bot.text_processor.generator import generate_answer def handle_reques...
""" OCAPI Data Endpoints """ from .code_versions import CodeVersions from .custom_objects import CustomObjects from .customer_lists import CustomerLists from .customer_objects_search import CustomObjectsSearch from .global_jobs import GlobalJobs from .job_execution_search import JobExecutionSearch from .jobs import Job...
#Simple Calculator #By Yasmine Lopes ################## ##Ask which operation the user is going to do ##Ask for the first number ##Ask for the second number ##Calculate the operation ##Print the result #Return to the calculator while True: operation = input('Which of these operations you want to? \n(+, ...
from django.contrib import admin from .models import * admin.site.register(Game) admin.site.register(Card) admin.site.register(CardSet)
import datetime from eppy.doc import EppUpdateCommand from registrobrepp.ipnetwork.addipnetwork import AddIpNetwork from registrobrepp.ipnetwork.aggripnetwork import AggrIpNetwork from registrobrepp.ipnetwork.chgipnetwork import ChgIpNetwork from registrobrepp.ipnetwork.remipnetwork import RemIpNetwork class BrEppU...
__author__ = 'Thierry Schellenbach' __copyright__ = 'Copyright 2010, Thierry Schellenbach' __credits__ = ['Thierry Schellenbach'] __license__ = 'BSD' __version__ = '1.1' __maintainer__ = 'Thierry Schellenbach' __email__ = 'thierryschellenbach@gmail.com' __status__ = 'Production'
""" net_surgery.py VGG16 Transfer Learning After 3-to-4-Channel Input Conversion Written by Phil Ferriere Licensed under the MIT License (see LICENSE for details) Based on: - https://github.com/minhnhat93/tf_object_detection_multi_channels/blob/master/edit_checkpoint.py Written by SNhat M. Nguyen Unknown ...
#!/usr/bin/env python import requests from bs4 import BeautifulSoup import sys from twython import Twython import numpy as np apiKey = '...' apiSecret = '...' accessToken = '...' accessTokenSecret = '...' #BeautifulSoup scraping algorythm url = 'https://coinmarketcap.com' soup = BeautifulSoup(requests.get(url).text, ...
##### from model.Data import UsFo import re class UserHelper: def __init__(self, app): self.app = app def Open_home_page(self): wd = self.app.wd if not (wd.current_url.endswith("/") and len(wd.find_elements_by_name("searchform")) > 0): wd.get("http://localhost/addressbook/"...
from classes.aux_code_thread import Thread from utils import logger from utils import RunShellFunc import os def create_logger(log_file): print(f"Creating log file") logger.setup_logger(log_file) def aux_analysis(Thread: Thread, aux_analysis_dir): create_logger(os.path.join(aux_analysis_dir, Thread.log_fil...
#!/usr/bin/env python # -*- coding: utf-8 -*- r"""pprint_dir_magic -- DESCRIPTION """ from IPython.core.magic import Magics, magics_class, line_magic from IPython.core.magic import register_line_magic from IPython.core.magic_arguments import (argument, magic_arguments, parse_a...
#! /usr/bin/env python import cherrypy.daemon if __name__ == '__main__': cherrypy.daemon.run()
#!/usr/bin/env python3 # Created by: Christina Ngwa # Created on: October 2019 # This program uses a nested if statement def main(): # this function uses a nested if statement # output print("Is the year a leap year? Find out.") print("") # input year = int(input("Enter a year: ")) prin...
# -*- coding: utf-8 -*- # Copyright (C) 2012 Rosen Diankov <rosen.diankov@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
import os import imp """ This script allows creating a directory structure that corresponds to the parameterized inputs present in the file test/integration/test_display_callback.py Run this from the root of the ansible-runner directory It will write these files to a folder named "callback-testing-playbooks" """ ca...
"""Math functions for calculator allowing for multiple inputs""" def add(array): return reduce(lambda x,y: x+y, array) def subtract(array): return reduce(lambda x,y: x-y, array) def multiply(array): return reduce(lambda x,y: x*y, array) def divide(array): return reduce(lambda x,y: x/y, array) def p...
my_dict = {'a':645, 'b':3987, 'c': 93,'d': 111, 'e': 646, 'f': 20} print("Словарик: ", my_dict) max_keys = sorted(my_dict, key = my_dict.get, reverse = True) print('Наибольшое значение в ключе: ', max_keys[0]) print('2-е наибольшое значение в ключе: ', max_keys[1]) print('3-е наибольшое значение в ключе: ', max_keys[...
""" Calculates cohen kappa for the coding in this study """ from sklearn.metrics import cohen_kappa_score import pandas as pd def labels_to_numbers(labels1, labels2): """ Turn labels, eg. [tfoj, tfoz] into numbers, e.g [0, 1] """ uniques = list(set(labels1 + labels2)) mapping = {} for i, l...
import uuid import requests from flask import Flask, render_template, session, request, redirect, url_for, jsonify from flask_session import Session # https://pythonhosted.org/Flask-Session from services.user import UserService from services.outlook import OutlookService from services.auth import AuthService from load...
from rest_framework import generics from django.contrib.auth.models import User from rest_framework import permissions from rest_framework.response import Response from django.db.models import Count, Avg from buses.models import Driver from buses.api.serializers.driver_serializer import DriverSerializer class DriverLi...
""" Problem 22 Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. ...
#!/usr/bin/env python def predict(RD, RIA, RIS, RRV, RWR, num_courses): from sklearn.model_selection import GridSearchCV from sklearn.model_selection import StratifiedShuffleSplit from sklearn.model_selection import train_test_split from sklearn.svm import SVC import pandas as pd import numpy as np mod...
from typing import List class Solution1: def largestRectangleArea(self, heights: List[int]) -> int: if not heights: return 0 length = len(heights) less_to_left = [-1] * length less_to_right = [length] * length for i in range(1, length): p = i - 1 ...
# -*- coding: utf-8 -*- """ Created on Wed Mar 4 19:26:07 2020 @author: Utilisateur """ from copy import deepcopy import autograd.numpy as np from autograd.numpy.linalg import pinv from autograd.numpy import newaxis as n_axis from autograd.numpy import transpose as t ###############################...
def funcion1(): x = 5 + funcion2() #L2 print("ingreso por el método 1") return x def funcion2(): x = 3 + funcion3() #L3 print("Ingreso por el método 2") return x def funcion3(): print("Ingreso por el método 3") x = 7 return x x = funcion1() #L1 print (x) #Recur...
import cv2 import json import math import numpy as np from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval import torch from opendr.perception.pose_estimation.lightweight_open_pose.algorithm.datasets.coco import CocoValDataset from opendr.perception.pose_estimation.lightweight_open_pose.algorit...
import sys import platform import os from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from gui.mainWindow import helpform, newimagedlg import gui.mainWindow.qrc_resources from gui.mainWindow.exercise import resizedlg __version__ = "1.0.1" class MainWindow(QMainWindow): def __in...
import sys import os from subprocess import check_output from subprocess import call from subprocess import Popen from multiprocessing import Pool import math import numpy as np import pandas as pd from collections import OrderedDict import csv script_path = os.path.dirname(os.path.realpath(__file__))+'/' sys.path.app...
import yaml import shutil import os def main(): with open("scores.yml") as f: res = yaml.load(f, Loader=yaml.BaseLoader) for score, files in res.items(): dirpath = f"scored/{score}/" print(dirpath) if not os.path.isdir(dirpath): os.makedirs(dirpath) for f...
__version__ = "$Id$" import windowinterface, WMEVENTS from usercmd import * from wndusercmd import * # @win32doc|TopLevelDialog # There is one to one corespondance between a TopLevelDialog # instance and a document, and a TopLevelDialog # instance with an MDIFrameWnd. The document level commands # are enabled. This ...
# Copyright (c) 2020 DDN. All rights reserved. # Use of this source code is governed by a MIT-style # license that can be found in the LICENSE file. """RPC facility for use in ChromaService services. The outward facing parts of this module are the `ServiceRpc` class and the RpcWaiter.initialize/shutdown methods. Co...
# this file interact with the remote/local object detector and # and collect the detection results by feeding them with one synthesized image import requests import time from PIL import Image, ImageDraw,ImageColor,ExifTags from io import BytesIO def localize_objects(path): """Localize objects in the local image...
import bpy import os os.system('cls' if os.name == 'nt' else 'clear') for texture in bpy.data.images: flag = False for mat in bpy.data.materials: if mat.node_tree is not None: for node in mat.node_tree.nodes: if node.type == 'TEX_IMAGE': if node.image ==...
def compare(s,a): for word in a: if s.find(word) == 0 and iseither(s,len(word)) : return 1 else : return 0 def iseither(s,i): #문자열 s의 i번째 이후의 문자열이 문제 조건을 만족하는지 안하는지를 반환 global A if i==len(s): return 1 if compare(s[i:],A) == 0: return 0 else: re...
from django.core.management import base class Command(base.NoArgsCommand): help = "Recalculates March Madness scores." def handle_noargs(self, verbosity=0, **options): from marchmadness.models import recalculate_all_scores recalculate_all_scores() # vi: set sw=4 ts=4 sts=4 tw=79 ai et nocinden...
import numpy as np class Uni: """ 1D uniform grid """ def __init__(self,args): self.l = args['l'] self.R = args['R'] self.N = args['N'] self.A = np.pi*self.R**2. def __call__(self): l,A,N = self.l,self.A,self.N z = np.linspace(0.,l,N) dz = np.diff(z) A0 = np.ones(N)*A return [z,dz,A0] clas...
#!/usr/bin/env python """Fetcher of curriculum for UIUC.""" import json import requests import _common # TODO: complete the license and version info __author__ = 'Pengyu CHEN' __copyright__ = '2014 Deal College Inc.' __credits__ = ['Pengyu CHEN'] __license__ = '' __version__ = '' __maintainer__ = 'Pengyu CHEN' __ema...
#!/usr/bin/env python import sys import socket pattern = ''.join(chr(_) for _ in range(0,256) if chr(_).isalpha()) for sizes in ( [str(_) for _ in range(1,10)], [str(1) for _ in range(0,0xff)], ['ffff',], ['20000',], (), ): for te_key in ('Transfer-Encoding', 'TE'): for te_value in ('chunked', 'chunked, trai...
#PortiCode def toplamAl(liste): if type(liste) == list or type(liste) == tuple: toplam = 0 for i in liste: toplam +=i return toplam else: raise ValueError("Girilen parametre liste veya tuple bekleniyordu") """ a = toplamAl([1,2,3,4,5,6]) b = toplamAl((1,2...
from django.shortcuts import render, get_object_or_404 from django.views.generic.base import TemplateView from django.views.generic import ListView from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.models import User from django.contrib.auth import logout, login, authenticate from djang...
# -*- coding: utf-8 -*- """ Created on Mon Jul 10 19:11:01 2017 @author: Luis """ import pygame,sys from pygame.locals import * from random import randint # crear numeros aleatorios ancho = 800 alto = 600 posX = 0 posY = 520 class Bola(pygame.sprite.Sprite): # heredar de pygame.Sprite.. """"Clase para la nave...
''' 1 - Faça um programa que peça dois números e imprima o maior deles ''' print("Informe o primeiro numero") num1 = int(input()) print("Informe o segundo numero") num2 = int(input()) if (num1 > num2): print(f'O maior número é o {num1}') elif (num2 > num1): print(f'O maio número é o {num2}') else: print(...
time_24 = int(input("Enter the time: ")) hours = time_24 // 100 minutes = time_24 % 100 am_pm = "am" if hours == 12: am_pm = "pm" if hours % 12 == 0: hours = 12 elif hours % 12 != hours: hours = hours % 12 am_pm = "pm" if minutes < 10: min_str = "0" + str(minutes) else: min_str = str(minutes) ...
__author__ = 'kattaguy' a = 1; b = 1; c = 1; for a in range (1, 500): for b in range(1, 500): for c in range(1,500): if (a ** 2 + b ** 2 == c ** 2) & (a+b+c == 1000): product = a*b*c print(product)
# author:lzt # date: 2019/12/4 15:44 # file_name: dict_test # 字典的生成 import random dict1 = {1: 2, 2: 3, 3: 4, 5: "005", None: "6", "7": None} print(dict1) # 用字典类生成字典:字典参数!!! dict2 = dict(张三=1, 李四=2, 王五=5) print(dict2) # 用字典创建字典 dict3_1 = {"1": 1, "2": 2} dict3 = dict(**dict3_1) print(dict3) # 带字典参数的函数 def test_dic...
# Generated by Django 3.0.2 on 2020-04-13 04:42 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('apis', '0008_auto_20200401_0847'), ] operations = [ migrations.CreateModel( name='RelPostShapeC...
'''Trains an GRU model on the IMDB sentiment classification task. The dataset is actually too small for LSTM to be of any advantage compared to simpler, much faster methods such as TF-IDF + LogReg. # Notes - RNNs are tricky. Choice of batch size is important, choice of loss and optimizer is critical, etc. Some configur...
# -*- coding: utf-8 -*- import math print(math.floor(34.9)) print(math.tan(3)) from math import log, ceil print(log(2)) print(ceil(34.3)) import math as m print(m.floor(34.9))
from __future__ import annotations from typing import TypedDict __all__ = ( "Permission", "Role", ) Permission = tuple[int, int] class _RoleOptional(TypedDict, total=False): colour: str hoist: bool rank: int class Role(_RoleOptional): name: str permissions: Permission
#Mostrar por la pantalla la suma de los multiplos de 3 y 5 entre 10 #entre 100 y entre 1000. print('--------RETO 1-------'); sumMul = 0; print('Multiplos de 3 y 5 del 1 al 10'); for x in range(1,10): if x % 3 == 0 or x % 5 == 0: sumMul = sumMul + x; print x; #Los imprime dando saltos...
username = 'max' password = 'JQP' user = input('username : ') user_pass = input('password : ') if(user == username and user_pass == password): print("Welcome admin") else: print("password is not collage \n Get out Now!!!")
import infoEt import local class ControlInfo: """ Clase para el control de las etiquetas. """ def __init__(self): """ Constructor. """ self.__listaD=[] self.__listaL=[] def separar(self,cad): """ Función separa las cadenas de etiquetas y las tran...
import functools import re def read_passports() -> list[dict]: with open('input.txt') as file: lines = file.read().split('\n\n') file.close() raw_passports = [re.split('\s', re.sub('\n', ' ', line.strip())) for line in lines] return list(map( lambda raw_passport: dict(functools.reduc...
from django.urls import path from django.views.decorators.cache import cache_page from .views import * urlpatterns = [ path('', ForumHome.as_view(), name='home'), path('archieve/<int:year>/', archieve), path('about/', AboutForum.as_view(), name='about'), path('addbike/', AddBike.as_view(), name='add_b...
from __future__ import absolute_import import threading import time from grid import CozGrid from particle import Particle, Robot from setting import * from particle_filter import * from utils import * # map file Map_filename = "map_test.json" """ Autograder rubric Total score = 100, two stage: 1. Build ...
import multiprocessing as mp from functools import partial import numpy as np from recresid import recresid def ssr_triang(n, h, X, y, k, intercept_only, use_mp=False): """ Calculates the upper triangular matrix of squared residuals """ fun = ssr_triang_par if use_mp else ssr_triang_seq return f...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^login/$', views.login_view, name='login_view'), url(r'^logout/$', views.logout_view, name='logout_view'), ]