text
stringlengths
8
6.05M
#!/usr/bin/env python # Ver. 1.0.1 import boto3 from pprint import pprint import itertools TAG_KEYS = 'Name', 'Env', 'Appname' # Add credentials below session = boto3.Session() ec2 = session.resource('ec2') instances = [] for instance in ec2.instances.all(): instances.append(instance.tags) clean = filter(None,...
from cycler import cycler import os import argparse import numpy as np import matplotlib.pyplot as plt from dps.hyper import extract_data_from_job from dps.utils import ( process_path, Config, sha_cache, set_clear_cache, confidence_interval, standard_error ) cache_dir = process_path('/home/eric/.cache/dps_pl...
# -*- coding: utf-8 -*- from django.conf.urls import patterns, url, include from core.views import IndexView, PagesView, PageView, ArticleView, ArticlesView urlpatterns = patterns('', url('^$', IndexView.as_view(), name='index'), url(r'pages/', PagesView.as_view(), name='pages'), url(r'page/(?P<slug>[-\w]+...
b = sorted(list(map(int,input().split()))) print('Yes' if b[0]+b[1] == b[2] else 'No')
""" ********************************************************************* This file is part of: The Acorn Project https://wwww.twistedfields.com/research ********************************************************************* Copyright (c) 2019-2021 Taylor Alexande...
from django import forms from . import models class AuthForm(forms.Form): login = forms.CharField(max_length=32) password = forms.CharField(max_length=32) stay_authorized = forms.BooleanField(required=False) class TaskForm(forms.Form): language = forms.ChoiceField(choices=models.Language.choices) ...
n = int(input()) m = [] for i in range(0, n): a, b, c = map(float, input().split(' ')) m.append((a * 2 + b * 3 + c * 5) / 10) for j in m: print('{:.1f}'.format(j))
import dash_bootstrap_components as dbc from dash import Input, Output, State, html collapse = html.Div( [ dbc.Button( "Open collapse", id="collapse-button", className="mb-3", color="primary", n_clicks=0, ), dbc.Collapse( ...
from math import pi import matplotlib.pyplot as plt import numpy as np def relative_error(x0, x): return np.abs(x0 - x) / np.abs(x0) def log_teylor_series(x, N=5): print(N) a = x - 1 a_k = a # x в степени k. Сначала k=1 y = a # Значене логарифма, пока для k=1. for k in range(2, N): # сумма п...
import cv2 import requests import io uri = 'https://node-red-001.au-syd.mybluemix.net/sendImage' cap = cv2.VideoCapture(0) cv2.namedWindow("Camera", cv2.WINDOW_AUTOSIZE) while True: res, frame = cap.read() if res: resized = cv2.resize(frame, (frame.shape[1] // 2, frame.shape[0] // 2)) _, img_encoded = cv2.imen...
"""JSON CLI formatter.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import json def format(obj): # pylint: disable=W0622 """Output object as json.""" return json.dumps(obj)
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> == RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py == 1 2 3 4 >>> == RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\s...
# Author:ambiguoustexture # Date: 2020-03-10 file_shaped = './enwiki-20150112-400-r100-10576_shaped.txt' file_countries = './countries.txt' file_compound_words = './compound_words_process_result.txt' countries_set = set() countries_dict = {} with open(file_countries) as countries: for country in countries: ...
import unittest from katas.beta.beetlejuice_x3_bug_fix import beetle_juice class BeetleJuiceTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(beetle_juice("Harry!"), "Harry! Harry! Harry!") def test_equal_2(self): self.assertEqual(beetle_juice("Hobie!"), "Hobie! Hobie!...
# -*- coding: utf-8 -*- """ Fundamentus Scraper @input: Target Symbol (string) @output: Market Data (DataFrame) Created on Oct 2020 @author: Murilo Fregonesi Falleiros """ def ScrapMarketData(sym, Gui): #%% Fundamentus Access import bs4 as bs from urllib.request import Request, urlopen fun...
__author__ = 'Sebastian Bernasek' import numpy as np import matplotlib.pyplot as plt import seaborn as sns from functools import reduce from operator import add from .base import Base from .settings import * from .palettes import Palette class JointDistribution(Base): """ Object for constructing joint distr...
# -*- coding: utf-8 -*- import ConfigParser from gcloud import storage from gcloud.storage import Blob configfile = ConfigParser.SafeConfigParser() configfile.read("./config/config.ini") UPLOAD_BUCKET = configfile.get("gcs","upload_bucket") PROJECT_ID = configfile.get("gcs","project_id") UPLOAD_FILE = configfile.ge...
#!/usr/bin/env python from __future__ import print_function import fastjet as fj import fjcontrib import fjext import tqdm import argparse import os import pythia8 import pythiaext import pythiafjext from heppy.pythiautils import configuration as pyconf from pyjetty.mputils import mputils import ROOT ROOT.gROOT....
""" Image Data Analysis Using Numpy & OpenCV email: deeptimalhotra27@gmail.com author: Deepti Malhotra """ import numpy as np import parseArgs import cv2 import GrayImageProcessing as gip import sys # start processing if __name__ == '__main__': # load the image args = parseArgs.parseInputArgs() # extrac...
from edges import getSubsetWithEdgeAnalysis from featureDetection import runFeature import numpy as np import glob from matplotlib import pyplot as plt import cv2 as cv i = 5 imDir = "../artSamples/" imnames = glob.glob(imDir + '*.jpg') imnames = sorted(imnames) # descriptors = np.empty((1,159)) # keypoints =...
# 1. How instance methods work? class Test: """Testing how descriptors work.""" def __init__(self, attr=None): self.attr = attr def ret(self): return self # What's wrong here? def show(msg): print(msg) # Depending on how we call the show method # we pass it the instan...
import requests from bs4 import BeautifulSoup import urllib from telegram import ReplyKeyboardMarkup as rkm from activity import Activity from config import APPID class Wolfram(Activity): def __init__(self): self.API = "http://api.wolframalpha.com/v2/query?input={}&appid={}" self.exit = rkm([['Ex...
import csv import numpy as np import math import random, sys class makebins: def __init__(self): self.data=None csvfile1=open('crimesbyday2015.csv', 'w',newline='') self.csvfile=csv.writer(csvfile1,delimiter=',') def drawProgressBar(self,percent, barLen = 50): #just a progress bar so that you dont lose pa...
from tkinter import * root = Tk() root.title("Hello") root.geometry("276x116") text = Label(root, text="請輸入暱稱:", width="30", height="2") text.place(x=0, y=0) name = Entry(root, width="30") name.place(x=0, y=36) button = Button(root, text="執行") button.place(x=0, y=66) result = Label(root, text="", ...
""" Name: HumbleForwarder Author: kjp Humble SES email forwarder. Simple address mapping is supported. Feel free to fork it if you want more configurability. Massively reworked and cleaned up version of https://aws.amazon.com/blogs/messaging-and-targeting/forward-incoming-email-to-an-external-destination/ Setup in...
#!/usr/bin/python3 A={"Age":33 , "Name":"John"} print (A['Age']) print (A['Name'])
from bs4 import BeautifulSoup import urllib3 url = 'your url' http = urllib3.PoolManager() response = http.request('GET', url) soup = BeautifulSoup(response.data) # soup = BeautifulSoup(, 'html.parser') print(soup.prettify())
s=[0,1,2,3,4,5,6,7,8,9] print(s[0:5:1]) print(s[1:-2]) print(s[5:]) print(s[:-1]) print(s[:]) print(s[2:-1:2]) print(s[2:-1:-1]) print(s[-1:2:-1]) print(s[::-1]) a='manikanta' print(a[::-1]) print(a[0:4:1])
import TreeNode def sumNumbers(root):
# -*- coding: utf-8 -*- """ Created on Sat Jun 8 11:05:11 2019 @author: nadolsw Created based on the following tutorial: http://ataspinar.com/2018/04/04/machine-learning-with-signal-processing-techniques/ """ #%% IMPORT NECESSARY PACKAGES #pip install siml #pip install pandas #pip install seaborn i...
import tensorflow as tf import network as nw def MCNN(im_data, bn=False): with tf.variable_scope('MCNN'): x1 = nw.conv2d(im_data, 16, kernel_size=9, padding='same', bn=bn) x1 = tf.layers.max_pooling2d(x1, 2, 2) x1 = nw.conv2d(x1, 32, kernel_size=7, padding='same', bn=bn) x1 = tf.lay...
""" Transform pixel point to object point """ import cv2 import numpy as np import argparse import imutils ap = argparse.ArgumentParser() ap.add_argument("--device","-d",type=int,default=0) args = vars(ap.parse_args()) d = args.get("device") cam = cv2.VideoCapture(d) cam.set(3,1920) cam.set(4,1080) def mouse_callb...
def string_color(name): first_char = length = other_chars = sum_chars = 0 prod_chars = 1 for i, a in enumerate(name): current = ord(a) length += 1 if i == 0: first_char = current else: other_chars += current prod_chars *= current sum_ch...
try: from Tkinter import * except ImportError: from tkinter import * class CollectionNameFrame(Frame): def __init__(self, root): Frame.__init__(self, root) self.grid(row=0, column=2, padx=10, pady=10, sticky=NW) self.collection_name_label = Label(self, text = 'Collection Name:') self.collection_name_label....
from __future__ import division, print_function import unittest import numpy as np from smqtk.representation.descriptor_element.local_elements import \ DescriptorMemoryElement from smqtk.algorithms.relevancy_index.libsvm_hik import LibSvmHikRelevancyIndex if LibSvmHikRelevancyIndex.is_usable(): class TestI...
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'default_installname', 'type': 'shared_library', 'sources': [ 'file.c' ], }, { 'target_name': ...
import mysql.connector import dbconfig as cfg db = mysql.connector.connect( host=cfg.mysql['host'], user=cfg.mysql['user'], password=cfg.mysql['password'], database=cfg.mysql['database'] ) cursor = db.cursor() sql='insert into car (make, model, price) values (%s,%s,%s)' values=("Subaru","Impreza",50000) cu...
# coding: utf-8 """ app.py ~~~~~~ This module implements the App class for main application details and system checks / maintenance. :license: Apache2, see LICENSE for more details """ import os import vikid._version import vikid._conf import logging """ "home_dir", "jobs_dir", "config_filename", "c...
from .DS import DS def start(): ds = DS("set") return ds
from zimsoap import zobjects class MethodMixin: def create_task(self, subject, desc): """Create a task :param subject: the task's subject :param desc: the task's content in plain-text :returns: the task's id """ task = zobjects.Task() task_creator = task.to...
def fun(arr,k): sum = 0 for i in range(len(arr)): if(arr[i]<k): sum = sum+k-arr[i] elif(arr[i]>k): inc = k*(arr[i]//k+1)-arr[i] dec = arr[i]%k sum = sum + inc if inc<=dec else sum + dec return sum arr = [4,9,6] print(fun(arr,5))
import numpy as np from scipy.ndimage.filters import sobel, gaussian_filter from skimage import filter, transform, feature from skimage import img_as_float from coins._hough import hough_circles def compute_center_pdf(image, radius, low_threshold, high_threshold, gradi...
n1 = float(input('Primeira nota: ')) n2 = float(input('Segunda nota: ')) m = (n1 + n2) / 2 print(f'Tirando {n1} e {n2} a média do aluno é {m}') if 7 > m >= 5: print('O aluno está em RECUPERAÇÃO.') elif m < 5: print('O aluno está REPROVADO') else: print('O aluno está APROVADO')
import os from unittest import TestCase from smqtk.utils.file_utils import file_mimetype_filemagic from smqtk.tests import TEST_DATA_DIR try: import magic # We know there are multiple modules named magic. Make sure the function we # expect is there. # noinspection PyStatementEffect magic.detect_fr...
#!/usr/bin/env python3 # # This example first sets up a simple runaway scenario, which is # then passed to a DREAM.ConvergenceScan object. The convergence # scan is configured to apply to the most relevant resolution # parameters for this scenario. We will use the runaway rate as # a measure of convergence, and we will...
from fastapi import FastAPI app = FastAPI() @app.get("/hello") def hello(): return {"msg":"hello world!"}
message = 'gux6Jz!J6rp5r7Jzr66ntrM' SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789 !?.' # Loop through every possible key for key in range(len(SYMBOLS)): # It is importan to set translated to the blank string so that the previous itaration's value sor tranlated is cleared: transla...
print("===문자열 더하기===") head = "python" tail = " is fun" print(head + tail) print("\n===문자열 곱하기(복제)===") everyday = "goodday\n" print(everyday * 3) print("\n===문자열 곱하기 응용===") print("=" * 30) print("\tProgram Start") print("=" * 30)
from .base import * from decouple import config from boto3.session import Session SECRET_KEY = config('SECRET_KEY') DEBUG = False ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS").split(" ") DATABASES = { "default": { "ENGINE": config("SQL_ENGINE"), "NAME": config("SQL_DATABASE"), "...
s = "leetcode" s = list(s) listS = [] for i in range(len(s)): if s[i] not in listS: listS.append([s[i], 1])
# from packaging import version # packaging is not installed in pybites def changed_dependencies(old_reqs: str, new_reqs: str) -> list: """Compare old vs new requirement multiline strings and return a list of dependencies that have been upgraded (have a newer version) """ old = _get_p...
import numpy as np print('Enter n > 0:') n = int(input()) array = np.array([1, 2, 3]) print(np.tile(array, 3*n).reshape(3*n, len(array)))
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from dataclasses import dataclass from pants.engine.engine_aware import EngineAwareParameter LOCAL_ENVIRONMENT_MATCHER = "__local__" @dataclass(froze...
''' The autocomplete function will take in an input string and a dictionary array and return the values from the dictionary that start with the input string. If there are more than 5 matches, restrict your output to the first 5 results. If there are no matches, return an empty array. For this kata, the dictionary will...
import sys import warnings from pathlib import Path from tqdm import tqdm from joblib import Parallel, delayed sys.path.append("/home/herman/git/muspy/") import muspy DATASET_DIR = Path("/data4/herman/muspy-new") TARGET_DIR = DATASET_DIR / "downsampled" DATASET_KEYS = [ "nes", "jsb", "maestro", "hymn...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2015 Open Business Solutions (<http://www.obsdr.com>) # Author: Naresh Soni # Copyright 2015 Cozy Business Solutions Pvt.Ltd(<http://www.cozybiz...
# GitPycharm HW15 print("Hello World 1 in team leader server")
from django.http import HttpRequest from django.test import SimpleTestCase from django.urls import reverse from . import views class HomePageTests(SimpleTestCase): def test_home_page_status_code(self): response = self.client.get('/') self.assertEquals(response.status_code, 200) #============...
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-10-01 21:12 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='post_info...
# using Tkinter's Optionmenu() as a combobox try: # Python2 from vcenter_performance_monitoring import VcenterTest import Tkinter as tk import tkMessageBox vpm = VcenterTest() except ImportError as err: print err def select(): matrick = var.get() vm = var2.get() res=vpm.get_summary(v...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'C:\Users\alvar_000\Documents\registro\dialog.ui' # # Created by: PyQt5 UI code generator 5.8.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(se...
# -*- coding:utf-8 -*- import sqlite3 import re import requests # 创建表 def create_table(cursor1): # PRECAUTIONS TEXT);''') cursor1.execute('''CREATE TABLE CILIN (ID INT PRIMARY KEY NOT NULL, LABELS TEXT NOT NULL, WORD...
import json import os products = [] with open("scans.json", "r") as f: data = json.load(f) for e in data: id = e['id'] name = e['name'] type = e['type'] t = str(e["timestamp"]) l = e["location"] l = [str(i) for i in l] l = ' '.join(l) found = Fals...
# -*- coding: utf-8 -*- """ /*************************************************************************** Node2Link A QGIS plugin Drawing lines with points Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/ ------------------- ...
# -*- coding: utf-8 -*- """ Created on Sat Nov 14 14:30:34 2020 @author: Hal """ from __future__ import print_function import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request def read_respons...
import glob import os from pathlib import Path import joblib import pandas as pd from tqdm import tqdm def save_concat_karte(kartes_path, all_karte_path): kartes = glob.glob(kartes_path) karte_list = list() for karte in kartes: karte_data = pd.read_excel(karte) if len(karte_data.columns) ...
a="jggjkh" print(a)
import cs50 import sys def main(): # checking if command line is acceptable. if len(sys.argv) != 2: print("Missing command-line argument.") exit(1) # Insert Key key = int(sys.argv[1]) print("plaintext: ", end = "") plaintext = cs50.get_string() # Print out cypher-text ...
/Users/samnayrouz/anaconda3/lib/python3.6/base64.py
from collections import defaultdict file = "Day1/frequency.txt" sum = 0 # for storing the frequency changes from the file freqchanges = [] # for keeping track of the current frequency values = defaultdict(lambda:-1) # Reads the file f = open(file,'r') while True: line = f.readline() if not line: break...
from django.contrib import admin from django.urls import reverse from django.utils.safestring import mark_safe from .models import Post, Category, Tag # Register your models here. class PostAdmin(admin.ModelAdmin): list_display = ('get_title', 'get_name', 'publication_date', 'is_published', 'get_categories', 'get_im...
from ..bepasty_xstatic import serve_files from flask import send_from_directory from werkzeug.exceptions import NotFound from . import blueprint @blueprint.route('/xstatic/<name>', defaults=dict(filename='')) @blueprint.route('/xstatic/<name>/<path:filename>') def xstatic(name, filename): """Route to serve the ...
#!/usr/bin/env python from __future__ import print_function import liblo, sys # send all messages to port 4242 on the local machine def oscsend(path,val): port = 4242 target = liblo.Address(port) msg = liblo.Message('/spot'+path) msg.add(val) liblo.send(target,msg)
from django.urls import path, include, re_path from api.endpoint import email_view urlpatterns = [ re_path(r'invitation', email_view.InvitationView.as_view()), ]
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-04-14 22:04:53 # @Author : Fallen (xdd043@qq.com) # @Link : https://github.com/fallencrasher/python-learning # @Version : $Id$ ''' 测试自定义模块的导入 ''' import a
# -*- coding: utf-8 -*- """ Created on Fri Jun 12 17:45:15 2020 @author: Joe """ import wx import ukbiobank class M_AM_B(wx.Frame, ukbiobank.ukbio): pass class SelectIllnessFrame(wx.Frame, ukbiobank.ukbio): __metaclass__ = M_AM_B def __init__(self, parent, ukb): super().__init__(parent=pare...
__author__ = 'Justin' def pathSimilarity(pathA,pathB): num_same_nodes = 0 for node in pathA: if node in pathB: num_same_nodes += 1 percentage = num_same_nodes/max(len(pathA),len(pathB)) return percentage
''' Application wide properties. .. REVIEWED 11 November 2018 This module defines a singleton that hides some application-wide properties. As any singleton, any instantiation returns always the same object. This one specifically re-routes the ``__init__`` method to ensure that all variables are only updated at the fi...
from docxtpl import DocxTemplate,RichText ds = DocxTemplate('word1.docx') context = {'sb' : RichText("林康琪",color='FF0000',bold=True,underline=True,size=40,font="Simson"),"SB":"林son"} ds.render(context) ds.save("SB.docx")
import sys mybook = open("file1.txt") dictionary = {} for lines in mybook: word_list = lines.split() for word in word_list: letter = word[0] letter = letter.upper() if letter in dictionary.keys(): dictionary[letter]+=1 else: dictionary[letter]=1 mybook.clo...
# ====================== # Create annual median composites # ====================== import ee def addDate(image): ''' Function to add date to imagery ''' date = ee.Date(image.get('system:time_start')) dateString = date.format('YYYY-MM-dd') return image.set('date', dateString) def median_comp...
from pathlib import Path import iprPy for name, CalcClass in iprPy.calculation.loaded.items(): calc = CalcClass() print(name) infilename = Path(calc.directory, f'calc_{name}.in') emptydict = {} for key in calc.allkeys: emptydict[key] = '' with open(infilename, 'w') as infile: ...
#!/usr/bin/env python # python3 predict.py # from pathlib import Path # import numpy as np # from PIL import Image # from keras.models import load_model # import sys # sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages') # from __future__ import print_function #Image_checker import roslib # roslib.loa...
from troposphere import ( Parameter, Ref, Template, Condition, Equals, And, Or, Not, If, Sub ) from troposphere.codepipeline import ( Pipeline, Stages, Actions, ActionTypeId, OutputArtifacts, InputArtifacts, ArtifactStore, DisableInboundStageTransi...
from os.path import join as j tmp_dir = "/tmp/mot" project_dir = "/home/mot" data_dir = j(project_dir, "data") experiment_dir = j(data_dir, "experiments") training_dir = j(data_dir, "training") model_dir = j(project_dir, "py", "lib", "models") detection_threshold = 75 CPUs = 16 GPUs = 4 crop_size = 64 use_magic_pi...
import os import yaml # The purpose of this file is to load the yaml file in memory and pass it # around to other module around. config_path = os.environ.get('some shell variable if you want') if config_path is None: config = yaml.load(open(os.path.dirname(__file__) + '/../settings.yaml')) else: config = yaml...
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TP INGE 2 FOR PYTHON ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (Phone Book Project) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ due on March, 25, 2016 ~...
#encoding=utf-8 from appium import webdriver from selenium.webdriver.support.ui import WebDriverWait from appium.webdriver.common.touch_action import TouchAction import base64 import time import os import codecs # 获取手机基本信息 def get_phonemsg(): # 获取设备号 devices = os.system('adb devices') # 获取应用包名及启动名,需事先手工启...
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt df_swing=pd.read_csv('E:\csvdhf5xlsxurlallfiles/2008_swing_states.csv') print(df_swing.columns) _=sns.swarmplot(x='state', y='dem_share', data=df_swing) _=plt.xlabel('state') _=plt.ylabel('percen of vote for obama') plt.show()
#!/usr/bin/env python3 import matplotlib.pyplot as plt import numpy as np import sys sys.path.append('../../py/') from DREAM.DREAMOutput import DREAMOutput plt.rcParams.update({'font.size': 14}) do = DREAMOutput('output.h5') fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(10,4)) # 1.Distribution function evol...
#python2.7, requires torch from __future__ import division from __future__ import print_function import loadModelMNIST import testModel import random import pdb import matplotlib.pyplot as plt import torch from torch.autograd import Variable import torch.optim as optim import torch.nn as nn import torch.nn.functional ...
# Author:ambiguoustexture # Date: 2020-03-04 import gzip import json import pymongo from pymongo import MongoClient file_gz = './artist.json.gz' unit_bulk = 10000 client = MongoClient() db = client.db_MusicBrainz collection = db.artists with gzip.open(file_gz, 'rt') as artists: buf = [] for i, artist in en...
# -*- coding: utf-8 -*- """ Created on Wed Sep 11 19:49:25 2019 @author: Rui Kong """ import numpy as np import math import random import matplotlib.pyplot as plt ''' 差分进化算法:初始化、变异、交叉、边界处理、计算fitness、选择 种群数量一般为4D-10D,必须大于4 变异算子F一般取为0.5 交叉算子CR一般为0.1或0.9 最大进化代数G为100-500 此处为求最小值的问题,若要进行修改,则需要将fitness的地方全部进行修改。 ''' def c...
import pandas as pd TRIPS_DF = {'distance_end': {0: 147.404368166875}, 'distance_start': {0: 318.361754800303}, 'lat_end': {0: 47.050889099999999}, 'lat_start': {0: 47.2013301}, 'lon_end': {0: 8.3093702999999994}, 'lon_start': {0: 7.4539675000000001}, 'mot_segment_id': {0: '86a42e1a-fc08-459f-82e1-2b113d4be97b'}...
# -*- coding: utf-8 -*- # import stdlibs import os import re # import third party libs import pytest # import local libs @pytest.fixture def organization_context(): return { "ansible_role_organization_name": "myorg", } def test_default_configuration(cookies): result = cookies.bake() assert ...
#!/usr/bin/env python # -*- coding: UTF-8 -*- import rospy from math import pow, atan2, sqrt from tf.transformations import * import smach import smach_ros from smach_ros import SimpleActionState from smach_ros import ServiceState import threading import time # Navigation from move_base_msgs.msg import MoveBaseActi...
import requests import os import json import encode_multipart class ActionsManager(): def __init__(self, address): self.address = address def new(self, name, description, language, containerTag, in_out, cloud, timeout, filePath): fields = { "type": "action", ...
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import difflib import json import re import textwrap from itertools import cycle from typing import Callable, Dict, Iterable, List, Optional, Set, Tuple, cast from typing_extensions impor...
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField from wtforms.validators import DataRequired class LoginForm (FlaskForm): pass
#This is Tic Tac Toe by Vanessa Tostado from graphics import * from random import * def grid(win): rect1 = Rectangle(Point(0,700),Point(200, 500))# Rectangle 1 rect1.draw(win) label=Text(Point(100,600), "1") label.draw(win) rect2 = Rectangle(Point(0,500),Point(200, 300))# Rectangle 2 rect...