text
stringlengths
8
6.05M
import requests import csv from sensetw.core import Mapping def get_mappings(csv_url, agent=None): if agent is None: agent = requests response = agent.get(csv_url) contents = response.text.split("\n") reader = csv.DictReader(contents) return [Mapping(hypothesis_url=row["hypothesis_url"], ...
from Graph import * from GraphWorld import * vs = [Vertex(c) for c in "abcdefgh"] g = Graph(vs) g.add_regular_edges(6) layout = CircleLayout(g) # draw the graph gw = GraphWorld() gw.show_graph(g, layout) gw.mainloop()
#sierpinski_triangle.py """ ------------------------------------------------------------------------------------------- Generates a visualization of the Sierpinski triangle by printing spheres in space in Maya ------------------------------------------------------------------------------------------- One function...
import os from subprocess import call ex = './chemposer' filename = './static/xyz/tmp/C20.xyz' call([ex, filename])
import os import z import fnmatch import csv from collections import defaultdict from sortedcontainers import SortedSet import buy import os from scipy import stats import numpy as np # #x = np.random.random(10) #y = np.random.random(10) #slope, intercept, r_value, p_value, std_err = stats.linregress(x, y) #print("r_va...
### 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; either version 2 of the License, or (at your option) any later ### version. ### This program is distributed in the hope that it will be use...
__author__ = 'apple' from osgeo import ogr import os # Get the input Layer inShapefile = "ne1/ne1.shp" inDriver = ogr.GetDriverByName("ESRI Shapefile") inDataSource = inDriver.Open(inShapefile, 0) inLayer = inDataSource.GetLayer() # Create the output Layer outShapefile = "ne1/ne1_centroids.shp" outDriver = ogr.GetD...
#! env python from boto import ec2 conn = ec2.connect_to_region('us-east-1') vols = conn.get_all_volumes(filters={'status': 'available'}) for vol in vols: #print 'checking vol:', vol.id, 'status:', vol.status, 'attachment_id:', vol.attach_data.status conn.delete_volume(vol.id)
#Leo Li #01/11/19 #Dart simulation #1. The most you can walk is 22 steps. Once you go to twenty, it is highly likely to get a 51% or 52% #2. Monte Carlo simulations are basically simulations that help people to predict something that involves a lot of randomness in it. It is hard to come up with a probablity when rando...
# Python Coroutines and Tasks. # Coroutines declared with async/await syntax is the preferred way of writing asyncio applications. # # To actually run a coroutine, asyncio provides three main mechanisms: # # > The asyncio.run() function to run the top-level entry point “main()” function. # > Awaiting on a corout...
# Generated by Django 2.1.7 on 2019-02-12 14:27 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('tusome', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='author', options={'ordering': ['name']}, ...
# -*- coding: utf-8 -*- from nose.tools import * from mock import patch from picrawler.rt_cores import RTCoreRequest class TestRTCoreRequest(object): @patch('picrawler.rt_cores.cloud') def test_request(self, mock_cloud): req = RTCoreRequest('c1', 10, 1) mock_cloud.realtime.request.return_va...
# incomplete solution n = int(input()) a = [None]*n for x in range(n): a[x] = input() q = int(input()) while q: q -= 1 r, p = input().split() r = int(r) maxmlength = 0 currstring = "" tempstring = "zzzzzzzzzzz" for x in range(r): if(a[x]<tempstring): tempstring ...
import os from subprocess import Popen, PIPE from glob import glob import sys import decimal import ConfigParser def read_meta(): """ Opens up any metadata*.txt files in the local directory or specified directory if there is one. It will search the files for the EPSG code defining the projection as well as the cur...
import torch import numpy as np import pickle sizes = [[1024, 8, 10], [512, 16, 20], [256, 32, 40], [128, 64, 80]] # sizes = [[8, 10], [16, 20], [32, 40], [64, 80], [128, 160]] for id in range(len(sizes)): tmp = np.zeros(sizes[id], dtype=np.int32) for layer in range(sizes[id][0]): id_counter = 0 ...
import io import os import platform import subprocess import zipfile import pandas as pd import requests from powersimdata.network.usa_tamu.constants.zones import abv2state def download_demand_data( es=None, ta=None, fpath="", sz_path="C:/Program Files/7-Zip/7z.exe" ): """Downloads the NREL EFS base demand d...
import json import io import sys import os import time import requests from datetime import datetime from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options def startup_check(file_path): if os.path.isfile(file_path) and os.access(file_path, os.W_OK) and os...
import sys import os import numpy as np from PyQt5.QtCore import QTimer from random import randint from PyQt5 import QtCore, QtGui, QtWidgets from xml.dom.minidom import * from pathlib import Path import queue import copy # block size X_SIZE = 20 Y_SIZE = 20 # player size X_PSIZE = 14 Y_PSIZE = 16 # bot size X_BSIZE ...
import os from celery import Celery from celery.schedules import crontab from django.apps import AppConfig from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'callisto.settings.dev') app = Celery('callisto') class CeleryConfig(AppConfig): name = 'taskapp' verbose_name = 'Cele...
import numpy as np import time np.random.seed(1234) # This class distinguish the cats and elders who were mixed in the # previous representation, and add the ambulance issue. It also represents the reward return as # a vector instead of a scalar because the situation is treated as a multi-objectives problem. class ...
import torch as tc import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy device='cuda'if tc.cuda.is_available() else 'cpu' tc.manual_seed(777) if device=='cuda': tc.cuda.manual_seed_all(777) X=tc.FloatTensor([[0,0],[0,1],[1,0],[1,1]]).to(device) Y=tc.FloatTensor([[0],[1],[...
import posixpath import numpy as np import pandas as pd from wfdb.io import annotation from wfdb.io import download from wfdb.io.record import rdrecord def sigavg( record_name, extension, pn_dir=None, return_df=False, start_range=-0.05, stop_range=0.05, ann_type="all", start_time=0, ...
import os import sys import time import numpy as np import autodisc as ad from autodisc.representations.static.pytorchnnrepresentation.helper import DatasetHDF5 import torch from torch.utils.data import DataLoader from torch.autograd import Variable from torchvision.utils import save_image import configuration ''' ---...
""" This module contains code related to Think Python, 2nd Edition by Allen Downey http://thinkpython2.com This is to complete the exercises in Chapter 11: Dictionaries in Think Python 2 Note: Although this is saved in a .py file, code was run on an interpreter to get results Note: Usi...
from __future__ import absolute_import import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from program_synthesis.algolisp.dataset import data from program_synthesis.algolisp.models import prepare_spec from program_synthesis.common.modules import decoders from progr...
# coding: utf-8 # Standard Python libraries from pathlib import Path from typing import Optional, Union # http://www.numpy.org/ import numpy as np # https://github.com/usnistgov/DataModelDict from DataModelDict import DataModelDict as DM # https://github.com/usnistgov/atomman import atomman as am import atomman.uni...
from flask import Flask, render_template, request,make_response,jsonify from werkzeug.utils import secure_filename from flask_cors import CORS, cross_origin app = Flask(__name__) # CORS(app, support_credentials=True) # cors=CORS(app,resources={ # r"/*":{ # "origins":"*" # } # }) # app.config['CORS_HEAD...
import os from flask import Blueprint, request, flash, Response, jsonify, send_from_directory, g from werkzeug.utils import secure_filename from resourse.models.course import Course from resourse.models.take import Take from resourse.models.student import Student from resourse.models.pdfs import PDF from resourse imp...
def main(): import argparse import re import traceback import requests from dlinkscraper import DLink parser = argparse.ArgumentParser( 'DuckDNS Updater', description= """This script updates your DuckDNS IPv4 address to scraped address from your D-Link router....
from rest_framework import serializers from .models import Person class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = ('identifier', 'name', 'isic_code', 'phone_number', 'address', 'city', 'email', 'website', 'notes')
import re text = input() word = input() pattern = rf"\b{word}\b" # res = re.findall(pattern, text, re.IGNORECASE | re.MULTILINE) res = re.findall(pattern, text, re.IGNORECASE) print(len(res))
''' Created on 2017年1月3日 @author: admin ''' import socket s = socket.socket() host = socket.gethostname() port = 1234 s.bind((host, port)) s.listen(5) while True: c, addr = s.accept() print('Got connection from ', addr) c.send(bytes('Thank you for connecting')) c.close()
#!/usr/bin/env python3 # Advent of code Year 2019 Day 9 solution # Author = seven # Date = December 2019 import enum import sys from os import path sys.path.insert(0, path.dirname(path.dirname(path.abspath(__file__)))) from shared import vm with open((__file__.rstrip("code.py") + "input.txt"), 'r') as input_file: ...
""" Copyright 1999 Illinois Institute of Technology Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publis...
import numpy as np import pandas as pd import matplotlib.pyplot as plt train = pd.read_csv("cheatkey.csv") end_prices = train['종가'] print(type(end_prices)) #normalize window seq_len = 50 sequence_length = seq_len + 1 result = [] for index in range(len(end_prices) - sequence_length + 1): idk = [] idk[:] = ...
def find_all(a_str, sub): start = 0 while True: start = a_str.find(sub, start) if start == -1: return yield start start += 1 def find_all_indexes_substring(a_str, arr): substring_indexes = [] for elem in arr: current_indexes_substring = list(find_all...
#!/usr/bin/python3 # @Author: Safer # @Date: 2016-12-04 17:53:59 # @Last Modified by: Safer # @Last Modified time: 2016-12-04 23:31:25 import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * # * * * * * php /home/www/laravel/artisan schedule:run >> /dev/null 2>&1 class StockDi...
[devicefiles] {{target}}/vendor-boot-ramdisk: vendor-boot-ramdisk [mapping] {{target}}/vendor-boot-ramdisk: vendor-boot-ramdisk
# -*- coding: utf-8 -*- """ Created on Fri Oct 18 19:26:19 2019 @author: Prajwal """ #Euler 17 numbers=[i for i in range(1, 1001)] ones={1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine'} tens={1:'ten', 2:'twenty', 3:'thirty', 4:'forty', 5:'fifty', 6:'sixty', 7:'seventy', 8:'eig...
import django_filters from .models import GTINInformation class GTINFilter(django_filters.FilterSet): class Meta: model = GTINInformation fields = ['gtin_number', 'model_name']
def add(a, b): return a+b def subtract(a, b): return a-b def hello_world(): return "Hello World"
import sys from time import sleep import urllib2 a = 0 b = 1 c = 0 baseURL = "https://api.thingspeak.com/update?api_key=3NR0GTMVEM2R36XX&field1=" while(a < 1000): adc = open("/sys/bus/iio/devices/iio:device0/in_voltage0_raw", "r") value = (adc.read(5)).strip() print value f = urllib2.ur...
from flask import Flask, request, render_template_string # A template string # In a real app, render from a file in the templates directory TEMPLATE = """ <h1>Hello world!</h1> <p>Your IP is {{ip_address}}</p> <img src='static/earth.gif'> """ # Instatiate an app object app = Flask(__name__) @app.route('/') def hello...
import ConfigParser import duo_web as duo from contextlib import closing from flask import Flask, request, session, redirect, url_for, render_template, flash # config DEBUG = True # create flask application app = Flask(__name__) app.config.from_object(__name__) # config parser def grab_keys(filename='duo.conf'): ...
def printSCS (x , y) : global X , Y ,dp for i in range (x + 1) : for j in range (y + 1) : if (i == 0) or ( j == 0 ) : dp[i][j] = 0 else : if (X[i-1] == Y[j-1]) : dp[i][j] = 1 + dp[i-1][j-1] else : a = dp[i-1][j] b = dp[i][j-1] if (a > b) : dp[i][j] = a else : d...
import pyautogui as pag import time import csv scw, sch = pag.size() print("Screen size (" + str(scw) + "," + str(sch) + ")") cx, cy = pag.position() print("Cursor position (" + str(cx) + "," + str(cy) + ")") with open("Files/subjects.csv") as sfile: cread = csv.reader(sfile, delimiter = ",") row...
#!/usr/bin/env python3 import requests import re import time import smtplib import sys import os import json from datetime import datetime from notify_run import Notify import platform if platform.system() == 'Windows': CLEAR_STR = "cls" else: CLEAR_STR = "clear" class Product: def __init__(self, name, l...
from django.conf.urls.defaults import * import os # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() site_media = os.path.join(os.path.dirname(__file__), 'site_media') urlpatterns = patterns('', # Example: # (r'^randompeople/', include('randompeople.foo.urls')...
import django import os import sys path = '/home/teamwork/teamwork' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'teamwork.settings' django.setup() from django.utils import timezone from announcement.models import Announcement, image_path from teamwork import settings def ...
import pickle import fnmatch import os def process_data(d): f1 = open(d,"br") mylist1 = pickle.load(f1) f1.close() return mylist1
list1=[] list2=[] num1=int(input("Enter number of elements for first list:")) for i in range(1,num1+1): b=int(input("Enter element:")) list1.append(b) num2=int(input("Enter number of elements for second list:")) for i in range(1,num2+1): d=int(input("Enter element:")) list2.append(d) list3...
#!/usr/bin/env python # -*- coding: utf-8 -*- import mysql.connector class Price(): def __init__(self,id,priceList): self.idCard=id self.priceList=priceList def update(self,site,price): self.verif() try: conn = mysql.connector.connect(host="localhost",user="root",password="magicpswd", database="magic")...
import sys import rospy import rosbag from matplotlib import pyplot as plt if __name__ == '__main__': # Usage: python bag_graph_z.py inputfile.bag outputfile.png # Topic to find the z data odomTopic = '/A01/odometry' # Vertical limit to calculate time below zlim = 4.0 inputfile = sys.argv[1] ...
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). """Autoformatter to automatically add trailing commas to calls and literals. See https://github.com/asottile/add-trailing-comma for details. """ from pants.backend.python.lint.add_traili...
cards = [ { "spanish": "rojo", "english": "red" }, { "spanish": "verde", "english": "green" }, { "spanish": "azul", "english": "blue" }, { "spanish": "blanco", "english": "white" }, { "spanish": "negro", ...
import turtle paper = turtle.Screen() pen = turtle.Turtle() for i in range(0,500): pen.forward(75) pen.right(95)
"""aospy DataLoader objects""" import logging import os import pprint import numpy as np import xarray as xr from .internal_names import ( ETA_STR, GRID_ATTRS, TIME_STR, ) from .utils import times, io def _preprocess_and_rename_grid_attrs(func, grid_attrs=None, **kwargs): """Call a custom preprocess...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import dataclasses from textwrap import dedent from typing import Sequence import pytest from pants.backend.project_info import peek from pants.backen...
## # Simple dictionairy class that automatically initializes lists if # they are not present in the collection yet. ## class VectorList(dict): def __missing__(self, key): self[key] = [] return self[key]
import torch.nn.functional as F class InputPadder: """Pads images such that dimensions are divisible by 8""" # TODO: Ideally, this should be part of the eval transforms preset, instead # of being part of the validation code. It's not obvious what a good # solution would be, because we need to unpad t...
# Copyright (C) 2021 FireEye, Inc. All Rights Reserved. from speakeasy.struct import EmuStruct, Ptr import ctypes as ct NERR_Success = 0 NetSetupUnknownStatus = 0 NetSetupUnjoined = 1 NetSetupWorkgroupName = 2 NetSetupDomainName = 3 class WKSTA_INFO_100(EmuStruct): def __init__(self, ptr_size): super()...
# -*- coding: utf-8 -*- from socket import * import json import hashlib import datetime import time import random #These are listen request function# def send_shoplist(s,data,address): msg = {} for key in shop_list: if shop_list[key]["state"] == "open": msg[key] = {"name":"","owner":""} ...
import boto3 from botocore.exceptions import ClientError import time import sys bucket_name = sys.argv[1] prefix = sys.argv[2] start = time.time() print('Data prep started...') # Based on model monitor example using CSE-CIC-IDS2018 dataset # see also: https://github.com/aws-samples/reinvent2019-aim362-sagemaker-debu...
import pytest from pyasn1.type.namedtype import NamedType, NamedTypes, DefaultedNamedType, OptionalNamedType from asn1PERser.codec.per.encoder import encode as per_encoder from asn1PERser.classes.data.builtin.OctetStringType import OctetStringType from asn1PERser.classes.types.constraint import ValueSize def SCHEMA_n...
def min_max(*args): the_max = args[0] # 初始化最大值 the_min = args[0] # 初始化最小值 for i in args: if i >the_max: the_max = i elif i<the_min: the_min = i return {"max": the_max, "min:": the_min} print(min_max(1, 2, 4, 6))
from Base import * from Object import * ''' Esta funcao cria um objeto do tipo Ceu e o retorna @PARAMETROS id_tex_livre - primeiro id de textura nao utilizado - passado como lista de tamanho 1 vertices_list - lista de coordenadas de vertices textures_coord_list - lista de coordenadas de textura normals...
# -*- coding: utf-8 -*- # @Author: Fallen # @Date: 2020-04-24 12:55:16 # @Last Modified by: Fallen # @Last Modified time: 2020-04-24 12:55:16 #!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-04-16 14:50:41 # @Author : Fallen (xdd043@qq.com) # @Link : https://github.com/fallencrasher/python-learni...
import time from pyspark.sql import SQLContext from pyspark import SparkContext, SparkConf conf = SparkConf().set('spark.memory.fraction', '1.0').set('spark.memory.storage', '0.0').set('spark.sql.exchange.reuse', False) sc = SparkContext(conf=conf) sqlContext = SQLContext(sc) sqlContext.clearCache() for SF in (100, 3...
def intersection1(list1,list2): """That's shortest and most pratical way for get intersection of two lists.""" return list(set(list1)&set(list2)) def intersection2(list1,list2): """Duplicates elements that's duplicated in list2""" return [x for x in list1 if x in list2] def intersection3(list1,list2): """This is ...
""" MIT License Copyright (c) 2018 Rafael Felix Alves Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, pub...
from otree.api import ( models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer, Currency as c, currency_range, ) import numpy as np import random import json author = 'Ferley Rincón & Cesar Mantilla' doc = """ Informalidad Laboral: Movilidad y Observabilidad Laboral """ ...
""" Tests of the neo.core.segment.Segment class """ from copy import deepcopy from datetime import datetime import unittest import numpy as np import quantities as pq try: from IPython.lib.pretty import pretty except ImportError as err: HAVE_IPYTHON = False else: HAVE_IPYTHON = True from neo.core.segm...
# -*- coding: utf-8 -*- from architect.manager.client import BaseClient import homeassistant.remote as remote from homeassistant.exceptions import HomeAssistantError from celery.utils.log import get_logger logger = get_logger(__name__) DEFAULT_RESOURCES = [ 'ha_entity', ] class HomeAssistantClient(BaseClient): ...
import os from app import db def init_admin(first_name, last_name, email, password): user = User(username=email, password=password) profile = Profile(first_name=first_name, last_name=last_name, user=user, is_admin=True, email=email) db.session.add(user) db.session.add(profile) db.session.commit() def delete_an...
"""task URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/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-based vi...
# -*- encoding:utf-8 -*- # __author__=='Gan' # We are stacking blocks to form a pyramid. Each block has a color which is a one letter string, like `'Z'`. # For every block of color `C` we place not in the bottom row, # we are placing it on top of a left block of color `A` and right block of color `B`. # We are allowed...
import jsonpath from script.base_api.service_profile.students import students_queryById_get from script.default_header import jyy_header def assert_phone_search(student_ids: list, phone): if student_ids: results = [] for student_id in student_ids: params = {"studentId": student_id} ...
import torch.nn as nn import numpy as np class CNNDriver(nn.Module): def __init__(self): super(CNNDriver, self).__init__() self.conv_layers = nn.Sequential( nn.Conv2d(3, 24, kernel_size=5, padding=0, stride=2), nn.BatchNorm2d(24), nn.ReLU(), nn.Conv2...
# https://www.c-sharpcorner.com/article/firebase-crud-operations-using-python/ # https://console.firebase.google.com/u/0/project/led-blink-wifi/database/led-blink-wifi-default-rtdb/data # ============================================== from vicksbase import firebase as vix firebase_obj = vix.FirebaseApplication('htt...
import socketserver import socket import xml.etree.ElementTree as ElementTree import binascii import configparser import threading import datetime import logging import time import queue #Set up the config parser config = configparser.ConfigParser() #Read the config file in. config.read('pi-fighter-s...
from random_stump import RandomStumpInfoGain from decision_tree import DecisionTree import numpy as np class RandomTree(DecisionTree): def __init__(self, max_depth): DecisionTree.__init__(self, max_depth=max_depth, stump_class=RandomStumpInfoGain) def fit(self, X, y): N = X....
T = int(input()) for _ in range(T): n = int(input()) a = list(map(int, input().split())) mid = 0 low = 0 high = n-1 while mid <= high: if a[mid] == 0: a[mid],a[low] = a[low],a[mid] low += 1 mid += 1 elif a[mid] == 1: mid += 1 ...
from flask import Flask, render_template from flask_sqlalchemy import SQLAlchemy import os.path import pymysql app = Flask(__name__) db = SQLAlchemy(app) app.debug = True app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:zhxfei..192@localhost/admin' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.c...
import re from typing import Optional class LockReplacer: def __init__(self, text: str): self.text: str = text self.part: Optional[str] = None self.sha: Optional[str] = None self.time: Optional[str] = None def find_package(self, package: str) -> bool: package = packag...
from django.db import models # Create your models here. class Persona(models.Model): # TODO: Define fields here nombre = models.CharField(blank=True, max_length=100) apellidos = models.CharField(blank=True, max_length=150) edad = models.IntegerField(blank=True, null=True) telefono = models.CharFie...
import time import requests from flask import Flask, render_template, Response, request from modules.CnnModel import CnnModel from modules.Video import Video # %% Parameters camera = 0 resize = False model_name = "model" size = (100, 100, 3) app = Flask(__name__) # %% Création du modèle model = CnnModel(model_name...
# Generated by Django 2.0.4 on 2018-05-12 20:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('music', '0003_auto_20180512_2304'), ] operations = [ migrations.AlterField( model_name='music', name='title', ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> print('train stacked autoencoder stage 1') import os import sys import csv import numpy as np import numpy as np import pickle from PIL import Image import tensorflow as tf import tensorflow_ae_base from tensorflow_ae_base import * import tens...
import json import boto3 oregon = 'us-west-2' frankfurt = 'eu-central-1' singapore = 'ap-southeast-1' tokyo = 'ap-northeast-1' virginia = 'us-east-1' client = boto3.client('ec2', region_name=virginia) response = client.describe_vpcs() print(json.dumps(response, indent=4, sort_keys=True)) response = client.describe...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This script runs consistently some subprocess call """ import subprocess import time class BaseArgs(object): """ Abstract class which split named params """ def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs if...
from django.contrib import admin from .models import Size, PizzaType, PizzaTopping, Pizza, SubExtra, Sub, Pasta, Salad, Platter, Order admin.site.register(Size) admin.site.register(PizzaType) admin.site.register(PizzaTopping) admin.site.register(Pizza) admin.site.register(SubExtra) admin.site.register(Sub) admin.site...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-02-11 18:46 from __future__ import unicode_literals import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('qa', '0007_question_date'), ] operations = [ migrations.AddFi...
x=37 y=73 x,y=y,x print(x) print(y)
# Endi formating string xaqida bu deagni bitta string turidagi o'zgaruvchiga boshqa bitta string turidagi o'rzaruvchini # cancatunation ya'ni qo'shib biriktirib chiqarish degani First_name="Khamzayev" Last_name="Jamshid" masseg=f"{First_name} {Last_name} is a coder!" # bu yerdagi " f " xarfi shu formating deganini bil...
# Number geussing Game. # User can choose a number and let computer try to geuss # Or computer can choose a number and user has to geuss # only bug to fix is if user inputs char for num import random def computer_geuss_number(x): # User has secret number. Computer tries to geuss lower = 1 upper = x while(True): ...
import os import re from pathlib import Path from subprocess import run, PIPE, STDOUT from io import BytesIO from tempfile import TemporaryDirectory, NamedTemporaryFile from PIL import Image PAGE = re.compile(r'page-?(?P<index>\d+).ppm') def _extract_page(file_name: str) -> int: match = PAGE.match(file_name) ...
#!/usr/bin/python3 def square_matrix_simple(matrix=[]): new_mtx = [i[:] for i in matrix] index = 0 for row in new_mtx: for col in row: row[index] = col * col index += 1 index = 0 return new_mtx
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/8/24 14:51 # @Author : liuyb # @Site : # @File : run_this.py # @Software: PyCharm # @Description: A3C运行 Pendulum-v0游戏 import os import numpy as np import gym import tensorflow as tf import multiprocessing import threading import shutil import matp...
from CPUData import * from CSVinfo import * from GPUData import * from MemoryData import * from MotherboardData import * from StorageData import * import csv # Ratio : CPU, GPU, RAM, Storage, Motherboard USE_CSE_RATIO = { 'home' : [0.3,0.1,0.2,0.3,0.1], ...
from dps.config import SystemConfig from dps.vision import LeNet from dps.run import _run import tensorflow as tf import numpy as np class Config(SystemConfig): curriculum = [ dict(T=6, shape=(2, 2), min_digits=2, max_digits=3), dict(T=12, shape=(3, 3), min_digits=2, max_digits=3), dict(T=...