text
stringlengths
8
6.05M
import sys import getopt import os import os.path import weakref import gc import time import numpy from PyQt4.QtCore import Qt from PyQt4.QtGui import QApplication, QCursor from application.lib.helper_classes import HelperGUI # HelperGUI from application.ide.widgets.observerwidget import ObserverWidget from appli...
import mpmath as mp from math import pi, exp, cos def do_integ( scal=0.5 ): L = 10.0 c1 = L*scal f = lambda x: exp( 1.5*cos(2.0*pi/L *(x - c1) ) ) print('mpmath = %18.10f' % mp.quad( f, [0,L] ) ) do_integ( scal=0.1 ) do_integ( scal=0.5 ) do_integ( scal=0.9 )
import json files = [ "bolsavalores20191001.json", "bolsavalores20191008.json", "bolsavalores20191014.json", "bolsavalores20191015.json", "bolsavalores20191020.json", "ibovespa20191001.json", "ibovespa20191008.json", "ibovespa20191014.json", "ibovespa20191015.json", "ibovespa201...
"""Tests for the baseline_model functions.""" import pytest from src.models.baseline_model.baseline_model import read_data from src.models.baseline_model.baseline_model import create_datasets from src.models.baseline_model.baseline_model import create_model from src.models.baseline_model.baseline_model import train_mo...
import pytest from django.core.exceptions import ImproperlyConfigured from django.http import Http404 from django.test import RequestFactory from restdoctor.rest_framework.resources import ( get_queryset_model_map, ResourceViewSet, ResourceView, ) from tests.test_unit.stubs import ( ModelA, ModelAViewSet, Mode...
#!/usr/bin/python3 """This module prints people's names""" def say_my_name(first_name, last_name=""): """This function will print names Args: first_name (str): The person's first name last_name (str): The person's last name """ if not isinstance(first_name, str): raise TypeErr...
from pyspark.sql import SparkSession from pyspark.sql.functions import avg, format_number cluster_seeds = ['cass1:9042','cass2:9043','cass3:9044'] spark_session = SparkSession \ .builder \ .appName("Year Most-Polluted City") \ .config("spark.cassandra.connection.host", ','.join(cluster_seeds)) \ .confi...
import datetime import calendar import csv import sys def row_as_dict(data, columns): result = {} for row in data: i=0 items = {} for col in row: #skip first column for key of dictionary if (i > 0): column_name = columns[i] items[...
import pandas as pd def add_month_yr(x): ''' :param x: dataframe :type x: pd.DataFrame :return: dataframe ''' assert isinstance(x, pd.DataFrame) # ID column is index for x month_dict = {'1': 'Jan', '2': 'Feb', '3': 'Mar', '4': 'Apr', '5': 'May', '6': 'Jun'...
# ----------------------------------------------------------------------------- # Copyright (c) 2014--, The Qiita Development Team. # # Distributed under the terms of the BSD 3-clause License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
from bs4 import BeautifulSoup import requests import json def getMatchups(date): url = 'https://www.mlb.com/scores/{}'.format(date) page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') teams = soup(class_="sc-pbIaG fCAMpt") for i in range(len(teams)): teams[i] = team...
import attr from attr.validators import instance_of import numpy as np import pandas as pd @attr.s(slots=True) class Deinterleave: """ **HIGHLY EXPERIMENTAL** This class can differentiate the data recorded in PMT1 into two distinct channels by observing the time that has passed between the laser ...
# -*- coding: utf-8 -*- import codecs import os import csv #1. 读取文件 #['aa', 'aaa-bbb-sss'] => ['aa','aaa','bbb','sss'] def word_split(words): new_list = [] for word in words: if '-' not in word: new_list.append(word) else: lst = word.split('-') new_list.extend(lst) return new_list def read_file(file_...
token = '829114388:AAGz4YoeVDx8xtRN11efRmtevg848ZOiH2g'
import os import cgi import json import six import hashlib import uuid import fs.move import fs.subfs import fs.tempfs import fs.path import fs.errors from . import config, util DEFAULT_HASH_ALG = 'sha384' class FileProcessor(object): def __init__(self, presistent_fs, local_tmp_fs=False, tempdir_name=None): ...
from unittest import TestCase from src.d3_network.command import Command from src.d3_network.encoder import DictionaryEncoder from src.d3_network.network_exception import MessageNotReceivedYet class TestDictionaryEncoder(TestCase): def test_when_encode_then_return_byte_string(self): message = {'command'...
import unittest import functools import numpy import cupy from cupy import testing from cupyx import fallback_mode @testing.gpu class TestFallbackMode(unittest.TestCase): def numpy_fallback_equal(name='xp'): """ Decorator that checks fallback_mode results are equal to NumPy ones. Args:...
# !/usr/bin/python # # main.py # Reads sensor values and sends them to a server through LoRa # Requires LoPy with CoZIR CO2, Temperature and Humidity sensor attached # Version 0.11.02 # Author R. Puthli, Itude Mobile # # import TTN import time import pycom from AirSensor import AirSensor from CoZIR import CoZ...
from random import choice class RandomWalk: """ A class to generate random walks """ def __init__(self,num_points = 5000): """ Initialize the attributes of the walk """ self.num_points = num_points #all walk starts at (0,0) self.x_value = [0] self.y_value = [0] de...
#import pygrend from scenegraph import * from darect import * from pygrend import * from widgets import * from view import * renderer = Renderer() vTop = BaseView('vTop') r = DaRect() r.pos = (0, 0) r.dims = (800, 600) vTop.rect = r SCENEGRAPH.add(vTop) splitViewInX(vTop, 30) #splitViewInY(vTop, 10) # run main lo...
from django.contrib import admin from .models import ImageModel admin.site.register(ImageModel)
from abc import abstractmethod, ABC class TreeABC(ABC): @abstractmethod def is_empty(self): raise NotImplementedError @abstractmethod def num_nodes(self): raise NotImplementedError @abstractmethod def data(self): raise NotImplementedError @abstractmethod def...
# File: configure.py # Aim: Provide tools for setting and getting environ variables # %% import os # %% ---------------------------------- # Set and get local configures through environments class Configure(): def __init__(self, prefix='_MEG_RSVP_'): self.prefix = prefix def unique(self, key): ...
import os path = '/Users/jakesorensen/Desktop/' images = [] others = [] count = 0 for list in os.listdir(path): if list.endswith('.jpg'): print(list) count += 1 print(count)
import datetime import email.message import math import logging import unittest.mock as mock from typing import Callable, Any import pytest from pytest import LogCaptureFixture from pysimplesoap.simplexml import SimpleXMLElement import debianbts as bts from debianbts import Bugreport logger = logging.getLogger(__nam...
''' Library containing functions and information to run an oven simulation''' import matplotlib.pyplot as plt import numpy as np class Body(object): def __init__(self, T0, volume, mat, debug): self.temp = T0 self.mat = mat self.volume = volume self.step_heat = 0 self.debug ...
# primes.py def is_prime(n): """ Returns True if n is a prime number, and False otherwise. >>> is_prime(-7) False >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(25) False >>> is_prime(31) Tr...
#!/usr/bin/env python3 # # Development Order #5: # # This is the meat and bones of the tool, where the actual desired # commands or operation will be run. The results are then recorded # and added to the 'results' JSON data, which will then be sent # back to the test. Both system and api are able to be used here. # im...
#!/usr/bin/env python # -*- coding: UTF-8 -*- a,b=map(int,raw_input().split()) ans=[str(b)] while 1: if b%10==1: ans.append(str(b/10)) b/=10 elif b%2==0: ans.append(str(b/2)) b/=2 else: print 'NO' break if b==a: print 'YES' print len(ans) ...
import operator from collections import OrderedDict from collections.abc import MutableSequence from functools import reduce import pandas def is_outlier(deviation=3): """Build a callable taking a `Series` as argument, and returning a new `Series` of booleans indicating whether values are in a specific SD ra...
# 147. Insertion Sort List # # Sort a linked list using insertion sort. class ListNode(object): def __init__(self, x): self.val = x self.next = None def __iter__(self): item = self while item is not None: yield item.val item = item.next class Soluti...
#!/usr/bin/python RED = True BLACK = False class Node: def __init__(self, key=None, val=None, color=None): self.key = key self.val = val self.left = None self.right = None self.color = color class RedBlackBST: def __init__(self): self.root = None def put(...
# import unittest from unittest import TestLoader, TestSuite, TextTestRunner import sys sys.path.append('..') # Importing the modules #from Test_UI.K8s_Parallel_MultiUser_SingleGpu.test_01_singleGpu_pgan_mnist_manual import Kubernetes_Ui_Parallel_Pgan_Mnist_01 #------------ Rapt UI Screens -------------------------...
import tensorflow as tf import numpy as np import sys def create_model(input_node): layer1 = tf.layers.conv2d( input_node, 16, (3, 3), padding="SAME", activation=tf.nn.relu, kernel_initializer=tf.keras.initializers.he_normal() ) layer2 = tf.layers.conv2d( ...
'''30. Write a Python script to check whether a given key already exists in a dictionary. ''' d = {1: 0, 2: 20, 3: 90, 4: 4, 5: 50, 11: 66} def is_key(x): if x in d: print('Key is already exists in a dictionary ') else: print('Key is not exists in a dictionary') is_key(11) is_key(0)
import os import torch import torch.nn as nn from cleanfid.downloads_helper import * import contextlib @contextlib.contextmanager def disable_gpu_fuser_on_pt19(): # On PyTorch 1.9 a CUDA fuser bug prevents the Inception JIT model to run. See # https://github.com/GaParmar/clean-fid/issues/5 # https://g...
from distutils.core import setup setup( name='usi_st_robotframework_commonlibrary', packages=['usi_st_commonlibrary'], version='0.1', author='Jerry Huang', url='', author_email='Jerry_Huang@ms.usi.com.tw', license='MIT', platforms='any', description='USI RobotFramework library for s...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.core.validators from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations...
nums = list(map(int, input().split())) n = len(nums) ans = [] for i in range(0, n, 2): a = nums[i] b = nums[i + 1] if a * b != 0 and b > 0: ans.append(str(a * b)) ans.append(str(b - 1)) if len(ans) == 0: print('0 0') else: print(' '.join(ans))
"""empty message Revision ID: 905ba9f6d23d Revises: 13b0fec5b6ac Create Date: 2020-11-10 11:51:48.775036 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '905ba9f6d23d' down_revision = '13b0fec5b6ac' branch_labels = None depends_on = None def upgrade(): # ...
from __future__ import print_function import numpy as np from ase.units import Bohr, Ry import sys import os def read_etot(logfile): f = open(logfile, 'r') while True: line = f.readline() if not line: break if 'Total =' in line: Etot = float( line.split()[2] )...
from serial import Serial, EIGHTBITS, PARITY_NONE, STOPBITS_ONE from pymongo import MongoClient from json import loads myclient = MongoClient("mongodb://localhost:27017/") mydb = myclient["database"] col_temp = mydb["temp"] col_light = mydb["light"] col_press = mydb["press"]
import urllib.request def download_web_image(url): urllib.request.urlretrieve(url, "messi.jpg") download_web_image('https://media-public.fcbarcelona.com/20157/0/document_thumbnail/20197/11/31/187/45817611/1.0-10/45817611.jpg?t=1493315026000')
# question https://www.hackerrank.com/challenges/python-loops/problem # solution if __name__ == '__main__': n = int(input()) for i in range(n): print(f"{i*i}")
from pylons import url
"""Vistas del módulo erp """ # Librerias Django from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.shortcuts import render # Librerias en carpetas locales from ..base.models import PyPartner, PyProduct from .subviews.logoutmodal import LogOutModalView @l...
from keras.models import Sequential from keras.layers import LSTM from keras.layers import Dense #for reporting errors import matplotlib.pyplot as plt from pylab import figure from sklearn.metrics import mean_squared_error from math import sqrt from utils import * def lstm_model(neurons, batch_input_shape, stateful=...
from project_module_installation_and_file_creation import * if os.path.isfile(os.getcwd() + '/csv and text files/execution_value.txt') == False: make_folder() from project_mysql_execution import * execute_commands() else: from project_objects import * cur.execute('USE project') from tkin...
from sklearn.metrics import precision_recall_curve import pickle import numpy as np import matplotlib.pyplot as plt import itertools def plot_precision_recall_curve(dst_lst_address): with open(dst_lst_address, "rb+") as f: dis_total = pickle.load(f) print(len(dis_total)) with open("pos_samples.txt...
"""Add user_linkedin_info. Revision ID: 41c4d0ca1619 Revises: 1520c933a172 Create Date: 2016-02-08 10:38:57.384355 """ # revision identifiers, used by Alembic. revision = '41c4d0ca1619' down_revision = '1520c933a172' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgr...
#!/usr/bin/env python3 import sys from _constants import * def checkSexDigit(sexStrDigit): try: if sexStrDigit == "" or sexStrDigit == " ": sexStrDigit = "0" sexDigit = int(sexStrDigit) if sexDigit > 59: raise ValueError("Digit above 59.") if sexDigit < 0: ...
from ED6ScenarioHelper import * def main(): # 格兰赛尔 CreateScenaFile( FileName = 'T4104 ._SN', MapName = 'Grancel', Location = 'T4104.x', MapIndex = 1, MapDefaultBGM = "ed60018", Flags = 0, ...
#!/usr/bin/env python3 # Solution to Python Challenge Part 0: http://www.pythonchallenge.com/pc/def/0.html def exponentiate(a,b): """ Exponentiate a with be, i.e. a^b inputs: a,b : Integers Outputs: int : Exponentiated value Failure: Exception """ return(a**b) if __na...
# -*- coding: utf-8 -*- # script predict with test dataset # basic library import pandas as pd, numpy as np import calendar import pickle from sklearn.model_selection import cross_val_score, train_test_split from sklearn.metrics import mean_squared_error, r2_score, explained_variance_score, mean_absolute_error fr...
from django.contrib.auth.models import User from django.db import models from .api.APIFactory import APIFactory from .api.CoinMarketCap import CoinMarketCap class Crypto(models.Model): """Defines cryptocurrencies which can be used in tracker""" symbol = models.CharField(max_length=10, primary_key=True) n...
# Bootstrap confidence intervals # To "pull yourself up by your bootstraps" is a classic idiom meaning that you achieve a difficult task by yourself with no help at all. In statistical inference, you want to know what would happen if you could repeat your data acquisition an infinite number of times. This task is impos...
#!/usr/bin/env python """ @Author: Anshul Paigwar @email: p.anshul6@gmail.com For more information on python-pcl check following links: Git Hub repository: https://github.com/strawlab/python-pcl Check the examples and tests folder for sample coordinates API documentation: http://nlesc.github.io/python-pcl/ document...
#!/usr/bin/python3 def best_score(a_dictionary): if a_dictionary is None or a_dictionary == {}: return (None) best = max(list(sorted(a_dictionary.values()))) for key in a_dictionary: if best == a_dictionary[key]: return (key) return (None)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('clinic', '0004_auto_20150921_1318'), ] operations = [ migrations.AddField( model_name='clinic', name...
from scrapy.exporters import CsvItemExporter from scrapy.conf import settings class SlybotCSVItemExporter(CsvItemExporter): def __init__(self, *args, **kwargs): kwargs['fields_to_export'] = settings.getlist('CSV_EXPORT_FIELDS') or None super(SlybotCSVItemExporter, self).__init__(*args, **kwargs)
from rest_framework.response import Response from rest_framework.views import APIView from .models import Category from .serializers import CategoriesSerializer, CategorySerializer class CategoriesView(APIView): """Categories list output""" def get(self, request): categories = Category.objects.all() ...
""" Specifies routing for the application""" from flask import render_template, request, jsonify, session from flask_mysqldb import MySQL from app import app, mysql, id_dict from app import database as db_helper team_map = None @app.route("/teams/delete/<int:team_id>", methods=['POST']) def delete(team_id): """ r...
import cgi from classes.pythonSqlConnect import PythonSqlConnect form = cgi.FieldStorage() #print(form.getvalue("name")) # Encoding import sys sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf8', buffering = 1) print("Content-type: text/html; charset=utf-8\n") # Query and Fetch the students con = Python...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/mainwindow.ui' # # Created by: PyQt5 UI code generator 5.5.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): Mai...
n=int(input('Enter the number of nodes:- ')) l=[] print('\nPlease enter time in HH:MM format.\nEnter the time for:-') for i in range(n): print("Node",i+1,": ",end='') l.append(input()) s=input('\nEnter the agreed upon time (in HH:MM format):- ') time=s[:3] s=int(s[3:]) l1=[] for i in l: l1.append(in...
# -*-coding:utf-8 -*- from datetime import date from django.db.models import Q, F from django.shortcuts import get_object_or_404, render from django.views.generic import ListView, DetailView from django.core.cache import cache from config.models import SideBar, Link from .models import Tag, Category, Post # Create ...
import numpy as np import matplotlib.pyplot as plt import csv import cv2 as cv from PIL import Image ############################### ##### PARAMETER VALUES ###### BOOL_LEFT = True SIZE_ = 7 RANGE_ = 90 THRESH_ = 750 ############################### #### Mapping function #### def right_map(i,j): global l...
# 33. Search in Rotated Sorted Array ''' Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplica...
d={} with open('poem.txt','r') as f: for line in f: for word in line.split(): if word in d: d[word]+=1 else: d[word]=1 print(d)
#import sys #input = sys.stdin.readline def main(): N = int( input()) t = N//2 print((N-t)/N) if __name__ == '__main__': main()
from django.db import models class Allergen(models.Model): name = models.CharField('Название', max_length=50) class Meta: verbose_name = 'аллерген' verbose_name_plural = 'аллергены' def __str__(self): return self.name class Dish(models.Model): allergens = models.ManyToManyF...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 12 14:45:41 2020 @author: pedro """ def solution(src, dest): def getRowCol(x): return x//8, x%8 def isValid(r, c): return r >= 0 and r <= 7 and c >= 0 and c <= 7 # get initial and final rows and columns oro...
# Generated by Django 3.2 on 2021-05-13 04:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.AddField( model_name='accounts', name='user_type', ...
# # list_test.py # python script to provide list of unit tests to cmake # # Copyright (c) 2018 Wesley Reinhart. # This file is part of the crayon project, released under the Modified BSD License. import os test_path = os.path.abspath(os.path.dirname(__file__)) import glob for test in glob.glob(test_path + "/test_*.py"...
from .base_multilingual_model import MultilingualSummModel, fasttext_predict from summertime.model.base_model import SummModel from summertime.model.single_doc import BartModel from easynmt import EasyNMT class TranslationPipelineModel(MultilingualSummModel): """ A class for multilingual summarization perfor...
''' Dropbox holds a competition between schools called CampusCup. If you verify an email address from a college, university, or higher education institution, you earn 20 points toward your school's overall ranking. When a school receives at least 100 points, all of its registered members receive an additional 3 Gb of b...
from setuptools import setup, find_packages __version__ = "0.1.0" setup( name='mitsuki', packages=find_packages(), version=__version__, description='A simple MAME frontend', install_requires=[ "pygame", "pyyaml", "docopt", "lxml", "pillow", "context....
import binascii import logging from hexbytes import HexBytes from web3 import Web3 from web3.datastructures import AttributeDict from typing import Dict def check_web3(ethereum_rpc_url: str) -> bool: try: w3: Web3 = Web3(Web3.HTTPProvider(ethereum_rpc_url, request_kwargs={"timeout": 2.0})) ret = w...
from django.apps import AppConfig class CountryDataConfig(AppConfig): name = 'country_data'
import pytest from lxml import etree from onegov.core.widgets import inject_variables from onegov.core.widgets import parse_structure from onegov.core.widgets import transform_structure from wtforms.validators import ValidationError class TextWidget: tag = 'text' template = """ <xsl:template match="t...
import sys from collections import OrderedDict from numpy import random sys.path.insert(0, '/home/machen/face_expr') from chainer.datasets import TransformDataset from time_axis_rcnn.extensions.special_converter import concat_examples_not_string from chainer.iterators import SerialIterator, MultiprocessIterator f...
# recursion, find max value among a list with n entries def find_max(data): """ linear recursion: time O(n), space O(n) """ if len(data) == 1: return data[0] else: return max(data[0], find_max(data[1:])) def find_max2(data, left, right): """ recursion, idea from binary sea...
''' 우선 해야할 것이 1. genres_original 에 있는 1000개 wav 파일 load 해서 data화 2. fma_small 에 있는 mp3 파일 genre 매칭해서 data화 이것들이 끝나고 나면 pytube.py 파일을 이용해 새로운 genre mp3 파일 100개 수집 해당 mp3 파일을 30초로 자르는 방법이 있을까 체크하기 ''' import os import numpy as np import pandas as pd import matplotlib.pyplot as plt import librosa import librosa.display...
''' author: juzicode address: www.juzicode.com 公众号: juzicode/桔子code date: 2020.6.26 ''' print('\n') print('-----欢迎来到www.juzicode.com') print('-----公众号: juzicode/桔子code\n') with open('example-a3.txt','a+',encoding='utf8') as fileobj: posi = fileobj.tell() #获取当前文件指针位置 print('tell():',posi) fileobj.seek(0...
#!/usr/bin/env python import mechanize import time import argparse parser = argparse.ArgumentParser(description='Upload zip files to Purdue DB') parser.add_argument("-i", "--inputFiles", dest="inputFiles", nargs='+', help="Files to upload") parser.add_argument("-u", "--user", dest="user", help="Name of user upl...
from django.contrib import admin # Register your models here. from weather.models import AirPollution, AirPollutionData admin.site.register([AirPollution, AirPollutionData])
#!/usr/bin/python def nested_list(l): if type(l) == int: print(l), return l for elem in l: nested_list(elem) nested_list([1,[4,3],6,[5,[1,0]]])
#Credits - https://discuss.pytorch.org/t/convert-int-into-one-hot-format/507/3 import torch batch_size = 5 nb_digits = 10 # Dummy input that HAS to be 2D for the scatter (you can use view(-1,1) if needed) y = torch.LongTensor(batch_size,1).random_() % nb_digits # One hot encoding buffer that you create out of the loo...
import face_recognition import os import sys import re from PIL import Image import PIL data = "./data" unknown_image = face_recognition.load_image_file("./photos/jobi.jpg") unknown_encoding = face_recognition.face_encodings(unknown_image)[0] for filename in os.listdir(data): if filename.endswith(".jpg"): ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' 1.设定一个用户名和密码,输入正确提示登录成功,否则失败,但是失败次数最多3次,否则退出程序(可以使用for或者while 循环) ''' # 1.次数 import sys username = 'dapeng' password = 'test123' #for 循环 # for i in range(3): # if username == input("输入你的用户名:") and password == input("输入你的密码:"): # print("Login Successful!") # break...
# Bubble Sort Algorithm - V 1.0.0 # Author: Dena, Rene # Last Modified: 5/26/17 ## Misc. import sys ## Functions def Main(): nums = [] while True: try: one = int(input("Please enter first integer: ")) break except ValueError: print("Not a valid integer! Please try again ....
_running = True _database = None def run_console(database): global _database _database = database while _running: query = input(" > ") command, args = parse_query(query) execute(command, args) def parse_query(query): parts = query.split(' ') command = parts[0].lower() ...
""" """ # Copyright 2019 CNRS # 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 # Unless required by applicable law or agreed to in writing,...
import pandas as pd import matplotlib.pyplot as plt import random import numpy as np #read dataset df = pd.read_csv('perceptron_data.csv', delimiter = ',', names = ['x_1', 'x_2', 'Result']) #tiny step eta eta = 0.001 #pick random a,b between (-1,0) and random c between (0,1) a = random.uniform(-1,0) b = random.unifor...
#!/usr/bin/python #\file sub_realtime1.py #\brief certain python script #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Oct.28, 2021 import numpy as np import matplotlib.pyplot as plt if __name__=='__main__': #plt.rcParams['figure.figsize']= 10,5 fig, (ax1,ax2) = plt.subplots(1,2,figsiz...
""" 给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。 示例 1 : 输入:nums = [1,1,1], k = 2 输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。 说明 : 数组的长度为 [1, 20,000]。 数组中元素的范围是 [-1000, 1000] ,且整数 k 的范围是 [-1e7, 1e7]。 Related Topics 数组 哈希表 👍 895 👎 0 """ """ 解题思路: 前缀和,保存一个数组的前缀和,然后利用差分法得出任意区间段的和 """ def subarray_sum(nums, k): dic =...
from django.db import models from rest_framework.authtoken.views import ObtainAuthToken # class
import numpy as np from sklearn import linear_model import matplotlib.pyplot as plt # 训练集 X = [0, 1, 2, 3, 0, 1, 2, 3] Y = [1, 2, 3, 4, -1, 0, 1, 2] arr = np.array([1, 2, 3, 4]).reshape((4, 1)) print(arr) # 测试集 X_TEST = [0.5, 1.5, 2.5] Y_TEST = [1.5, 2.5, 3.5] plt.figure() plt.scatter(X, Y, color='red') plt.title('...
import sc2 from sc2.constants import * #our own classes from probe import Probe as pbControl from zealot import Zealot as zlControl from cannon import Cannon as cnControl class UnitList(): def __init__(self): self.unit_objects = {} def make_decisions(self, game): self.game = game for unit in self.game.unit...
from flask import Flask, render_template, redirect # Import scrape_mars import scrape_mars # Import our pymongo library, which lets us connect our Flask app to our Mongo database. import pymongo # Create an instance of our Flask app. app = Flask(__name__) # Create connection variable conn = 'mongodb://localhost:2701...