from pxr import Gf
import carb
import omni.usd
import omni.ext
import omni.ui as ui
from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription

import asyncio
import gc
import weakref

from omni.isaac.dynamic_control import _dynamic_control
from .utils.simple_robot_controller import RobotController
from omni.isaac.utils.scripts.scene_utils import set_up_z_axis, setup_physics, create_background
from omni.isaac.utils.scripts.nucleus_utils import find_nucleus_server

EXTENSION_NAME = "Robot Navigation"

def create_xyz(init={"X": 100, "Y": 100, "Z": 0}):
    all_axis = ["X", "Y", "Z"]
    colors = {"X": 0xFF5555AA, "Y": 0xFF76A371, "Z": 0xFFA07D4F}
    float_drags = {}
    for axis in all_axis:
        with ui.HStack():
            with ui.ZStack(width=15):
                ui.Rectangle(
                    width=15,
                    height=20,
                    style={"background_color": colors[axis], "border_radius": 3, "corner_flag": ui.CornerFlag.LEFT},
                )
                ui.Label(axis, name="transform_label", alignment=ui.Alignment.CENTER)
            float_drags[axis] = ui.FloatDrag(name="transform", min=-1000000, max=1000000, step=1, width=100)
            float_drags[axis].model.set_value(init[axis])
    return float_drags

class Extension(omni.ext.IExt):
    def on_startup(self):
        self._timeline = omni.timeline.get_timeline_interface()
        self._viewport = omni.kit.viewport.get_default_viewport_window()
        self._usd_context = omni.usd.get_context()
        self._stage = self._usd_context.get_stage()
        self._window = ui.Window(EXTENSION_NAME, width=500, height=175, visible=False)
        self._window.set_visibility_changed_fn(self._on_window)

        menu_items = [
            MenuItemDescription(name=EXTENSION_NAME, onclick_fn=lambda a=weakref.proxy(self): a._menu_callback())
        ]
        self._menu_items = [
            MenuItemDescription(
                name="Controlling", sub_menu=[MenuItemDescription(name="Navigation", sub_menu=menu_items)]
            )
        ]
        add_menu_items(self._menu_items, "Isaac Examples")
        self._dc = _dynamic_control.acquire_dynamic_control_interface()
        self._create_ui()

        self._setup_done = False
        self._rc = None

    def _menu_callback(self):
        self._window.visible = not self._window.visible

    def _on_window(self, visible):
        if self._window.visible:
            self._sub_stage_event = self._usd_context.get_stage_event_stream().create_subscription_to_pop(
                self._on_stage_event
            )
        else:
            self._sub_stage_event = None

    def _create_ui(self):
        with self._window.frame:
            with omni.ui.VStack():
                with ui.HStack(height=5):
                    ui.Spacer(width=7)
                    self._robot_option = ui.ComboBox(0, "Transporter", "Carter", width=125)
                with ui.HStack(height=5):
                    ui.Spacer(width=5)
                    self._load_btn = ui.Button("Load Environment", width=125)
                    self._load_btn.set_clicked_fn(self._on_environment_setup)
                with ui.HStack(height=5):
                    ui.Spacer(width=9)
                    self._motion_label = ui.Label("Primitive Tasks", width=100)
                    self._motion_label.set_tooltip(
                        "Perform simple tasks like moving robot forward or rotating in-place"
                    )
                    self._move_btn = ui.Button("Move Robot", width=100, enabled=False)
                    self._move_btn.set_clicked_fn(self._on_move_fn)
                    self._rotate_btn = ui.Button("Rotate Robot", width=100, enabled=False)
                    self._rotate_btn.set_clicked_fn(self._on_rotate_fn)
                with ui.HStack(height=5):
                    ui.Spacer(width=9)
                    self._goal_label = ui.Label("Set Robot Goal", width=100)
                    self._goal_label.set_tooltip("Set robot target specified as (X, Y, theta)")
                    self.goal_coord = create_xyz(init={"X": -200, "Y": -400, "Z": 0})
                with ui.HStack(height=5):
                    ui.Spacer(width=5)
                    self._navigate_btn = ui.Button("Navigate Robot", width=100, enabled=False)
                    self._navigate_btn.set_clicked_fn(self._on_navigate_fn)
                    self._stop_btn = ui.Button("Stop Robot", width=100, enabled=False)
                    self._stop_btn.set_clicked_fn(self._on_navigate_stop_fn)

    async def _create_robot(self, task):
        done, pending = await asyncio.wait({task})
        if task in done:
            print("Loading Robot Enviornment")
            self._viewport.set_camera_position("/OmniverseKit_Persp", 300, 300, 100, True)
            self._viewport.set_camera_target("/OmniverseKit_Persp", 0, 0, 0, True)
            self._stage = self._usd_context.get_stage()
            result, nucleus_server = find_nucleus_server()
            if result is False:
                carb.log_error("Could not find nucleus server with /Isaac folder")
                return
            self._asset_path = nucleus_server + "/Isaac"

            current_robot_index = self._robot_option.model.get_item_value_model().as_int
            self._robot_prim_path = "/robot"
            if current_robot_index == 0:
                asset_path = self._asset_path + "/Robots/Transporter"
                robot_usd = asset_path + "/transporter.usd"
                self._robot_chassis = self._robot_prim_path + "/chassis"
                self._robot_wheels = ["left_wheel_joint", "right_wheel_joint"]
                self._robot_wheels_speed = [3, 3]
            elif current_robot_index == 1:
                asset_path = self._asset_path + "/Robots/Carter"
                robot_usd = asset_path + "/carter_sphere_wheels_lidar.usd"
                self._robot_chassis = self._robot_prim_path + "/chassis_link"
                self._robot_wheels = ["left_wheel", "right_wheel"]
                self._robot_wheels_speed = [2, 2]

            set_up_z_axis(self._stage)
            setup_physics(self._stage)

            create_background(
                self._stage,
                self._asset_path + "/Environments/Grid/gridroom_curved.usd",
                background_path="/background",
                offset=Gf.Vec3d(0, 0, -9),
            )

            # setup high-level robot prim
            self.prim = self._stage.DefinePrim(self._robot_prim_path, "Xform")
            self.prim.GetReferences().AddReference(robot_usd)

    def _on_stage_event(self, event):
        self.stage = self._usd_context.get_stage()
        if event.type == int(omni.usd.StageEventType.OPENED):
            self._move_btn.enabled = self._setup_done
            self._rotate_btn.enabled = self._setup_done
            self._navigate_btn.enabled = self._setup_done
            self._stop_btn.enabled = self._setup_done
            if self._rc:
                self._rc.enable_navigation(False)
            self._setup_done = False

    async def _play(self, task):
        done, pending = await asyncio.wait({task})
        if task in done:
            self._timeline.play()
            await asyncio.sleep(1)

    async def _on_setup_fn(self, task):
        done, pending = await asyncio.wait({task})
        if task in done:
            self._stage = self._usd_context.get_stage()
            # setup robot controller
            self._rc = RobotController(
                self._stage,
                self._timeline,
                self._dc,
                self._robot_prim_path,
                self._robot_chassis,
                self._robot_wheels,
                self._robot_wheels_speed,
                [1, 0.05],
            )
            self._rc.control_setup()
            # start stepping
            self._editor_event_subscription = (
                omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self._rc.update)
            )

    def _on_environment_setup(self):
        # wait for new stage before creating robot
        task = asyncio.ensure_future(omni.usd.get_context().new_stage_async())
        task1 = asyncio.ensure_future(self._create_robot(task))
        # set editor to play before setting up robot controller
        task2 = asyncio.ensure_future(self._play(task1))
        asyncio.ensure_future(self._on_setup_fn(task2))

        # self._load_btn.enabled=False
        self._move_btn.enabled = True
        self._rotate_btn.enabled = True
        self._navigate_btn.enabled = True
        self._stop_btn.enabled = True
        self._setup_done = True

    def _on_move_fn(self):
        print("Moving forward")
        self._rc.control_command(3, 3)

    def _on_rotate_fn(self):
        print("Rotating in-place")
        self._rc.control_command(3, -3)

    def _on_navigate_fn(self):
        goal_x = self.goal_coord["X"].model.get_value_as_float()
        goal_y = self.goal_coord["Y"].model.get_value_as_float()
        goal_z = self.goal_coord["Z"].model.get_value_as_float()
        print("Navigating to goal ({}, {}, {})".format(goal_x, goal_y, goal_z))
        self._rc.set_goal(goal_x, goal_y, goal_z)
        self._rc.enable_navigation(True)

    def _on_navigate_stop_fn(self):
        print("Navigation Stopped")
        self._rc.enable_navigation(False)
        self._rc.control_command(0, 0)

    def on_shutdown(self):
        self._rc = None
        self._timeline.stop()
        self._editor_event_subscription = None
        remove_menu_items(self._menu_items, "Isaac Examples")
        self._window = None
        gc.collect()


from django.conf.urls import url
from blog import views

urlpatterns = [
    url(r'^getAll/$', views.get_all, name='fetch'),
    url(r'^add/$', views.create_reminder, name='add'),
    url(r'^save/(?P<id>\d+)/$', views.save_reminder, name='create'),
    url(r'^edit/(?P<id>\d+)/$', views.edit_reminder, name='edit'),
    url(r'^delete/(?P<id>\d+)/$', views.delete_reminder, name='delete'),
    url(r'^$', views.index),
]


import requests as req
from multiprocessing import Pool
from lxml import  etree
import re

def geturl():
    url='http://www.sharenice.net/t-6Z+z5LmQ'
    headers={}
    page_text=req.get(url=url,headers=headers).text
    tree=etree.HTML(page_text)
    li_list=tree.xpath('//div[@class="cate-block first-block"]//ul/li')
    #print(li_list)
    video_urls=[]
    for li in li_list:
        try:
            #print(li)
            detial_url=''+li.xpath('./span[@class="cover"]/a/@href')[0]
            #print(detial_url)
            detial_title=li.xpath('./span[@class="cover"]/a/@title')[0]+'.mp4'
            #print(detial_title,detial_url)
            #print(detial_url)
            detial_page_text=req.get(url=detial_url,headers=headers).text
            #print(detial_page_text)
            '''src = "https://video.pearvideo.com/mp4/adshort/20210125/cont-1717851-15586820_adpkg-ad_hd.mp4"'''
            regex='src="(https.*?\.mp4)'
            video_url=re.findall(regex,detial_page_text)[0]
            if video_url=='':
                continue
            #print(video_url)
            dict1= {'name':detial_title,'url':video_url}
            video_urls.append(dict1)
        except BaseException as BE:
            continue
    #print(video_urls)
    return video_urls

def save_video(reponse,name):
    with open(name,'wb') as fw:
        fw.write(reponse)
    fw.close()
    print('%s /保存成功！！' %name)

def getvideo(video_urls):

    #name=li['name']
    url1=video_urls['url']
    #print(url)
    context=req.get(url=url1).content
    print('正在保存：%s' %video_urls['name'])
    #save_video(context,name)
    with open(video_urls['name'], 'wb') as fw:
        fw.write(context)
    fw.close()
    print('%s /保存成功！！' % video_urls['name'])

if __name__ == '__main__':
    videourls=geturl()
    #print(videourls)
    #开启8线程
    pool=Pool(8)
    pool.map(getvideo,videourls)  #传入一个方法和一个可迭代的对象
    pool.close()
    pool.join()

爬虫_多线程_分享短视频.py

爬虫_多线程_分享短视频.py


from module.protocol.network.messages.AbstractTaxCollectorListMessage import AbstractTaxCollectorListMessage

class TaxCollectorListMessage(AbstractTaxCollectorListMessage):
    def __init__(self, buffer_reader, len_type, length, count=None):
        AbstractTaxCollectorListMessage.__init__(self, buffer_reader, len_type, length, count)
        self.id = 1980
        self.nbcollectorMax = {"type": "uint", "value": ""}
        self.fightersInformations = {"type": "Vector.<TaxCollectorFightersInformation>", "value": ""}
        self.infoType = {"type": "uint", "value": ""}


import ast
import os
import sys

from ovn_k8s.common.util import ovs_vsctl
from ovn_k8s.common.util import ovn_nbctl
from ovn_k8s.common import variables

if sys.version_info < (3, 0):
    # python 2
    import ConfigParser
else:
    # python 3
    import configparser as ConfigParser

raw_config_parser = ConfigParser.RawConfigParser()

def init_config():
    config_filename = 'ovn_k8s.conf'
    if sys.platform != 'win32':
        config_path = "/etc/openvswitch"
    else:
        config_path = "C:\\etc"
    config_file = '%s/%s' % (config_path, config_filename)
    # Convert the path to use platform specific path delimitators
    config_file = os.path.abspath(config_file)
    # Return True if the file could be read, otherwise False
    return len(raw_config_parser.read(config_file)) == 1

config_successfully_read = init_config()

def get_default_value(option_name, section_name):
    section_default = {
        "mtu": 1400,
        "conntrack_zone": 64000,
        "ovn_mode": "overlay",
        "log_path": "/var/log/openvswitch/ovn-k8s-cni-overlay.log",
        "unix_socket": "/var/run/openvswitch/ovnnb_db.sock",
        "cni_conf_path": "/etc/cni/net.d",
        "cni_link_path": "/opt/cni/bin/",
        "cni_plugin": "ovn-k8s-cni-overlay",
        "private_key": "/etc/openvswitch/ovncontroller-privkey.pem",
        "certificate": "/etc/openvswitch/ovncontroller-cert.pem",
        "ca_cert": "/etc/openvswitch/ovnnb-ca.cert",
        "k8s_ca_certificate": "/etc/openvswitch/k8s-ca.crt",
        "rundir": "",
        "logdir": ""
    }
    default_config = {'default': section_default}

    section_dict = default_config.get(section_name, {})
    return section_dict.get(option_name, None)

def get_option(option_name, section_name='default'):
    if not config_successfully_read:
        return get_default_value(option_name, section_name)

    try:
        config_string = raw_config_parser.get(section_name, option_name)
    except Exception:
        # Config value could not be found in the file, retrieve the
        # default value
        config_string = get_default_value(option_name, section_name)

    try:
        # Try to evaluate the string which may contain a Python expression
        expr = ast.literal_eval(config_string)
        return expr
    except Exception:
        return config_string

UNIX_SOCKET = get_option('unix_socket')

def ovn_init_overlay():
    if os.path.exists(UNIX_SOCKET):
        OVN_NB = "unix:%s" % UNIX_SOCKET
    else:
        sys.exit("OVN NB database does not have unix socket")
    variables.OVN_NB = OVN_NB

    K8S_API_SERVER = ovs_vsctl("--if-exists", "get", "Open_vSwitch", ".",
                               "external_ids:k8s-api-server").strip('"')
    if not K8S_API_SERVER:
        sys.exit("K8S_API_SERVER not set")
    if not K8S_API_SERVER.startswith("http"):
        variables.K8S_API_SERVER = "http://%s" % K8S_API_SERVER
    else:
        variables.K8S_API_SERVER = K8S_API_SERVER

    K8S_CLUSTER_ROUTER = ovn_nbctl("--data=bare", "--no-heading",
                                   "--columns=_uuid", "find", "logical_router",
                                   "external_ids:k8s-cluster-router=yes")
    if not K8S_CLUSTER_ROUTER:
        sys.exit("K8S_CLUSTER_ROUTER not set")
    variables.K8S_CLUSTER_ROUTER = K8S_CLUSTER_ROUTER

    K8S_CLUSTER_LB_TCP = ovn_nbctl("--data=bare", "--no-heading",
                                   "--columns=_uuid", "find", "load_balancer",
                                   "external_ids:k8s-cluster-lb-tcp=yes")
    if not K8S_CLUSTER_LB_TCP:
        sys.exit("K8S_CLUSTER_LB_TCP not set")
    variables.K8S_CLUSTER_LB_TCP = K8S_CLUSTER_LB_TCP

    K8S_CLUSTER_LB_UDP = ovn_nbctl("--data=bare", "--no-heading",
                                   "--columns=_uuid", "find", "load_balancer",
                                   "external_ids:k8s-cluster-lb-udp=yes")
    if not K8S_CLUSTER_LB_UDP:
        sys.exit("K8S_CLUSTER_LB_UDP not set")
    variables.K8S_CLUSTER_LB_UDP = K8S_CLUSTER_LB_UDP


from collections import deque

def solution(n, wires):
    #연결된 송전탑 수 계산을 위한 bfs
    def bfs(start):
        q = deque()
        q.append(start)
        visited[start] = True
        count = 1
        while q:
            next_node = q.popleft()
            for g in graph[next_node]:
                if visited[g] == False:
                    visited[g] = True
                    q.append(g)
                    count += 1
        return count

    answer = 101
    for i in range(len(wires)):
        graph = [[] for _ in range(n+1)]
        for j in range(len(wires)):
            if i == j: #선택한 부분 연결 끊기
                continue
            graph[wires[j][0]].append(wires[j][1])
            graph[wires[j][1]].append(wires[j][0])

        visited = [False] * (n+1)
        count_network = []
        for j in range(1,n+1):
            if visited[j] == False:
                count_network.append(bfs(j))
        #송전탑 개수 차이 최소값
        answer = min(answer,abs(count_network[0]-count_network[1]))
    return answer

프로그래머스/lv2/86971. 전력망을 둘로 나누기/전력망을 둘로 나누기.py

전력망을 둘로 나누기.py


from rally.common import streaming_algorithms
from rally import consts
from rally.task import sla

@sla.configure(name="outliers")
class Outliers(sla.SLA):
    """Limit the number of outliers (iterations that take too much time).

    The outliers are detected automatically using the computation of the mean
    and standard deviation (std) of the data.
    """
    CONFIG_SCHEMA = {
        "type": "object",
        "$schema": consts.JSON_SCHEMA7,
        "properties": {
            "max": {"type": "integer", "minimum": 0},
            "min_iterations": {"type": "integer", "minimum": 3},
            "sigmas": {"type": "number", "minimum": 0.0,
                       "exclusiveMinimum": 0.0}
        },
        "additionalProperties": False,
    }

    def __init__(self, criterion_value):
        super(Outliers, self).__init__(criterion_value)
        self.max_outliers = self.criterion_value.get("max", 0)
        # NOTE(msdubov): Having 3 as default is reasonable (need enough data).
        self.min_iterations = self.criterion_value.get("min_iterations", 3)
        self.sigmas = self.criterion_value.get("sigmas", 3.0)
        self.iterations = 0
        self.outliers = 0
        self.threshold = None
        self.mean_comp = streaming_algorithms.MeanComputation()
        self.std_comp = streaming_algorithms.StdDevComputation()

    def add_iteration(self, iteration):
        # NOTE(ikhudoshyn): This method can not be implemented properly.
        # After adding a new iteration, both mean and standard deviation
        # may change. Hence threshold will change as well. In this case we
        # should again compare durations of all accounted iterations
        # to the threshold. Unfortunately we can not do it since
        # we do not store durations.
        # Implementation provided here only gives rough approximation
        # of outliers number.
        if not iteration.get("error"):
            duration = iteration["duration"]
            self.iterations += 1

            # NOTE(msdubov): First check if the current iteration is an outlier
            if (self.iterations >= self.min_iterations
                    and self.threshold and duration > self.threshold):
                self.outliers += 1

            # NOTE(msdubov): Then update the threshold value
            self.mean_comp.add(duration)
            self.std_comp.add(duration)
            if self.iterations >= 2:
                mean = self.mean_comp.result()
                std = self.std_comp.result()
                self.threshold = mean + self.sigmas * std

        self.success = self.outliers <= self.max_outliers
        return self.success

    def merge(self, other):
        # NOTE(ikhudoshyn): This method can not be implemented properly.
        # After merge, both mean and standard deviation may change.
        # Hence threshold will change as well. In this case we
        # should again compare durations of all accounted iterations
        # to the threshold. Unfortunately we can not do it since
        # we do not store durations.
        # Implementation provided here only gives rough approximation
        # of outliers number.
        self.iterations += other.iterations
        self.outliers += other.outliers
        self.mean_comp.merge(other.mean_comp)
        self.std_comp.merge(other.std_comp)

        if self.iterations >= 2:
            mean = self.mean_comp.result()
            std = self.std_comp.result()
            self.threshold = mean + self.sigmas * std

        self.success = self.outliers <= self.max_outliers
        return self.success

    def details(self):
        return ("Maximum number of outliers %i <= %i - %s" %
                (self.outliers, self.max_outliers, self.status()))


#! /usr/bin/python3
l1 = [1,2,5,8,9]
l2 = [1,5.6,"hello"]
l1[1] = 100
def raise_exception_msg(message=""):

    try:
        del l[2]
        print(l1)
    except NameError:
        print(message)
    finally:
        return(l1)


"""Functions to convert spiking data to different representations."""

import numpy as np

from spiketools.utils.data import smooth_data
from spiketools.utils.checks import check_time_bins

###################################################################################################
###################################################################################################

def convert_times_to_train(spikes, fs=1000, length=None):
    """Convert spike times into a binary spike train.

    Parameters
    ----------
    spikes : 1d array
        Spike times, in seconds.
    fs : int, optional, default: 1000
        The sampling rate to use for the computed spike train, in Hz.
    length : float, optional
        The total length of the spike train to create, in seconds.
        If not provided, the length is set at the maximum timestamp in the input spike times.

    Returns
    -------
    spike_train : 1d array
        Spike train.

    Examples
    --------
    Convert spike times into a corresponding binary spike train:

    >>> spikes = np.array([0.002, 0.250, 0.500, 0.750, 1.000, 1.250, 1.500])
    >>> convert_times_to_train(spikes)
    array([0, 0, 1, ..., 0, 0, 1])
    """

    if not length:
        length = np.max(spikes)

    spike_train = np.zeros(int(length * fs) + 1).astype(int)
    inds = [int(ind * fs) for ind in spikes if ind * fs <= spike_train.shape[-1]]
    spike_train[inds] = 1

    # Check that the spike times are fully encoded into the spike train
    msg = ("The spike times were not fully encoded into the spike train. " \
           "This probably means the spike sampling rate is too low to encode " \
           "spikes close together in time. Try increasing the sampling rate.")
    if not sum(spike_train) == len(spikes):
        raise ValueError(msg)

    return spike_train

def convert_train_to_times(spike_train, fs=1000):
    """Convert a spike train representation into spike times, in seconds.

    Parameters
    ----------
    spike_train : 1d array
        Spike train.
    fs : int, optional, default: 1000
        The sampling rate of the computed spike train, in Hz.

    Returns
    -------
    spikes : 1d array
        Spike times, in seconds.

    Examples
    --------
    Convert a spike train into spike times:

    >>> spike_train = np.array([0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1])
    >>> convert_train_to_times(spike_train)
    array([0.004, 0.006, 0.009, 0.011, 0.012, 0.014])
    """

    spikes = np.where(spike_train)[0] + 1
    spikes = spikes * (1 / fs)

    return spikes

def convert_isis_to_times(isis, offset=0, add_offset=True):
    """Convert a sequence of inter-spike intervals to spike times.

    Parameters
    ----------
    isis : 1d array
        Distribution of interspike intervals, in seconds.
    offset : float, optional
        An offset value to add to generated spike times.
    add_offset : bool, optional, default: True
        Whether to prepend the offset value to the beginning of the spike times.

    Returns
    -------
    spikes : 1d array
        Spike times, in seconds.

    Examples
    --------
    Convert a sequence of inter-spike intervals to their corresponding spike times, in seconds:

    >>> isis = np.array([0.3, 0.6, 0.8, 0.2, 0.7])
    >>> convert_isis_to_times(isis, offset=0, add_offset=True)
    array([0. , 0.3, 0.9, 1.7, 1.9, 2.6])
    """

    spikes = np.cumsum(isis, axis=-1)

    if offset:
        spikes = spikes + offset
    if add_offset:
        spikes = np.concatenate((np.array([offset]), spikes))

    return spikes

def convert_times_to_counts(spikes, bins, time_range=None):
    """Convert spikes times to counts of spikes per time bin.

    Parameters
    ----------
    spikes : 1d array
        Spike times, in seconds.
    bins : float or 1d array
        The binning to apply to the spiking data.
        If float, the time length of each bin.
        If array, precomputed bin definitions.
    time_range : list of [float, float], optional
        Time range, in seconds, to calculate the spike counts across.
        Only used if `bins` is a float.

    Returns
    -------
    spike_bin_counts : 1d array
        Vector of counts of the number of spikes per time bin.

    Examples
    --------
    Convert spike times (in seconds) to counts of spikes per time bin:

    >>> spikes = np.array([0.100, 0.350, 0.450, 0.775, 0.975])
    >>> convert_times_to_counts(spikes, bins=0.250)
    array([1, 2, 0, 2])
    """

    bins = check_time_bins(bins, time_range, spikes)
    spike_bin_counts, _ = np.histogram(spikes, bins)

    return spike_bin_counts

def convert_times_to_rates(spikes, bins, time_range=None, smooth=None):
    """Convert spike times to continuous firing rates.

    Parameters
    ----------
    spikes : 1d array
        Spike times, in seconds.
    bins : float or 1d array
        The binning to apply to the spiking data.
        If float, the time length of each bin.
        If array, precomputed bin definitions.
    time_range : list of [float, float], optional
        Time range, in seconds, to calculate the binned firing rate across.
        Only used if `bins` is a float.
    smooth : float, optional
        If provided, the kernel to use to smooth the continuous firing rate.

    Returns
    -------
    cfr : 1d array
        Continuous firing rate, compute across time bins.

    Examples
    --------
    Convert spike times (in seconds) to continuous firing rate across bins:

    >>> spikes = np.array([0.002, 0.250, 0.450, 0.500, 0.750, 1.000, 1.250, 1.300, 1.400, 1.500])
    >>> convert_times_to_rates(spikes, bins=0.2)
    array([ 5.,  5., 10.,  5.,  0.,  5., 15.,  5.])
    """

    bins = check_time_bins(bins, time_range, spikes)
    bin_counts = convert_times_to_counts(spikes, bins, time_range)

    cfr = bin_counts / np.diff(bins)

    if smooth:
        cfr = smooth_data(cfr, smooth)

    return cfr


import pytesseract
from PIL import Image
from PIL import ImageEnhance

img = Image.open('./code/office.png')
# 转化为灰度图片
img = img.convert('L')

# enhancer = ImageEnhance.Color(img)
# enhancer = enhancer.enhance(0)
# enhancer = ImageEnhance.Brightness(enhancer)
# enhancer = enhancer.enhance(2)
# enhancer = ImageEnhance.Contrast(enhancer)
# enhancer = enhancer.enhance(8)
# enhancer = ImageEnhance.Sharpness(enhancer)
# img = enhancer.enhance(20)

# 二值化处理
# 二值化处理
threshold = 140
table = []
for i in range(256):
    if i < threshold:
        table.append(0)
    else:
        table.append(1)
out = img.point(table, '1')

# out.show()
# 识别图片
img = img.convert('RGB')

print(pytesseract.image_to_string(img))


from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path

from . import views

app_name = 'node'
urlpatterns = [
    # path('node_list/<int:file_Code>', views.CreateTree, name="node_list"),
    path('node_list/<str:proj_Code>', views.node_list, name="node_list"),
    path('node_detail/<str:node_Code>', views.node_detail, name="node_detail"),
    path('create_node/',views.create_node, name='create_node'),
    path('changeNodeInfo/', views.changeNodeInfo, name="changeNodeInfo"),
    path('download/<str:pk>',views.download_view,name='download'),
    path('node_comment_create/<node_Code>',
         views.node_comment_create, name="node_comment_create"),
    path('comment_mention/',views.mentionable_member_json, name='mentionable_member_json'),
    path('submit/', views.comment_submit, name="comment_submit"),
    path('load_comment/', views.load_comment, name="load_comment"),
    path('load_node_data/', views.load_node_data, name="load_node_data"),

]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)


import os
import subprocess
from distutils import dir_util

from testtools.matchers import Equals

from snapcraft.tests import integration
from snapcraft.tests import fixture_setup

class GoTestCase(integration.SnapdIntegrationTestCase):

    def test_install_and_execution(self):
        with fixture_setup.WithoutSnapInstalled('go-hello'):
            # If we just put the source in the temp dir, go will generate
            # the binary with the name of the temp dir, instead of go-hello.
            dir_util.copy_tree(
                os.path.join(self.snaps_dir, 'go-hello'),
                os.path.join(self.path, 'go-hello'),
                preserve_symlinks=True)
            os.chdir('go-hello')

            self.run_snapcraft()
            self.install_snap()
            self.assertThat(
                subprocess.check_output(
                    ['go-hello'], universal_newlines=True),
                Equals('Hello snapcrafter\n'))


from multiprocessing import current_process
import libs.utilities as utilities
import random

def greedypath_RCL(circuit, customers, ALPHA):
    # Constuctive heuristic for Traveling Salesman Problem (TSP).
    # It's a nearest neighbour (NN) algorithm with Restricted Candidate List (RCL).
    # Do hamiltonian circuit with greedy choices in selected subset
    # Selected by clusters function
    # using RCL
    len_circuit = len(circuit)
    obj_BS = float('inf')

    # Constant choices for tests
    # random.seed(4542355562136458828)

    # Change range value to test circuit  starting in dif nodes
    for v in range(1):
        dict_positions = {circuit[i] : circuit[i] for i in range(len_circuit)}
        solution_greedy = [0 for i in range(len_circuit)]
        k = 0
        solution_greedy[k] = dict_positions.pop(v)
        k += 1
        # greedy choices
        while k < len_circuit:
            nearest_value = float('inf')
            farthest_value = 0
            current_node = solution_greedy[k - 1]
            # deciding nearest and farthest customers from  k - 1 customer
            for n in dict_positions:
                length_N = utilities.length(customers[current_node], customers[n])
                if length_N < nearest_value:
                    nearest_value = length_N
                if length_N > farthest_value:
                    farthest_value = length_N
            RCL = []
            # filling in RCL
            for n in dict_positions:
                length_N = utilities.length(customers[current_node], customers[n])
                if length_N <= (nearest_value + (farthest_value - nearest_value)*ALPHA): # Condition to insert neighbours in RCL
                    RCL.append(n)
            solution_greedy[k] = random.choice(RCL)
            dict_positions.pop(solution_greedy[k])
            k += 1
        # Decide best solution found
        curr_obj = utilities.calc_obj(solution_greedy, customers)
        if curr_obj < obj_BS:
            obj_BS = curr_obj
            best_solution = solution_greedy
        dict_positions.clear()
    return best_solution, obj_BS


"""Unit tests for djblets.privacy.templatetags.djblets_privacy."""

from django.template import Context, Template
from django.test.client import RequestFactory
from django.urls import ResolverMatch

from djblets.testing.testcases import TestCase

class PIISafePageURLTemplateTagTests(TestCase):
    """Unit tests for the {% pii_safe_page_url %} template tag."""

    def test_with_pii(self):
        """Testing {% pii_safe_page_url %} with PII in URL"""
        url = self._render_url('/users/test/', kwargs={
            'username': 'test',
        })

        self.assertEqual(url, '/users/<REDACTED>/')

    def test_without_pii(self):
        """Testing {% pii_safe_page_url %} without PII in URL"""
        self.assertEqual(self._render_url('/groups/test/'),
                         '/groups/test/')

    def _render_url(self, path, kwargs={}):
        request = RequestFactory().get(path)
        request.resolver_match = ResolverMatch(func=lambda: None,
                                               args=(),
                                               kwargs=kwargs)

        t = Template('{% load djblets_privacy %}'
                     '{% pii_safe_page_url %}')

        return t.render(Context({
            'request': request,
        }))


# 1
#%matplotlib notebook
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# 2
# Orion
x = [-0.41, 0.57, 0.07, 0.00, -0.29, -0.32,-0.50,-0.23, -0.23]
y = [4.12, 7.71, 2.36, 9.10, 13.35, 8.13, 7.19, 13.25,13.43]
z = [2.06, 0.84, 1.56, 2.07, 2.36, 1.72, 0.66, 1.25,1.38]

# 3
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(x,y, marker = '*')
ax.set_title('2D Constellation View')
ax.set_xlabel('X-Axis')
ax.set_ylabel('Y-Axis')
plt.show()

# 4
fig_3d = plt.figure()
ax = fig_3d.add_subplot(1,1,1, projection='3d')
constellation3d = ax.scatter(x,y,z, marker='*')
ax.set_title('Constellation of Orion', size=('small'), weight=('bold'))
ax.set_xlabel('X_Axis', size=('x-small'), weight=('bold'))
ax.set_ylabel('Y_Axis', size=('x-small'), weight=('bold'))
ax.set_zlabel('Z_Axis', size=('x-small'), weight=('bold'))

plt.show()

# 5
x2 = [22.4, 33.7, 18.4, 24.3]
y2 = [58.3, 55.2, 48.4, 44.4]
z2 = [18.5, 19.3, 26.6, 20.4]

some_stars = plt.figure()
ax = some_stars.add_subplot(1,1,1, projection='3d')
new_constellation3D = ax.scatter(x2,y2,z2, marker='*')
ax.set_title('Aldebaran, Bonner Stars, 39 Tauri', size=('small'), weight=('bold'))
ax.set_xlabel('Celestial X Coordinate', size=('x-small'), fontstyle=('italic'))
ax.set_ylabel('Celestial Y Coordinate', size=('x-small'), fontstyle=('italic'))
ax.set_zlabel('Celestial Z Coordinate', size=('x-small'), fontstyle=('italic'))

plt.show()


import pytest

from pcapi.core.offers import factories as offers_factories
from pcapi.core.testing import assert_num_queries
from pcapi.core.users import factories as users_factories
from pcapi.models import ApiErrors
from pcapi.models import Venue
from pcapi.utils.human_ids import humanize
from pcapi.utils.rest import check_user_has_access_to_offerer
from pcapi.utils.rest import load_or_raise_error

pytestmark = pytest.mark.usefixtures("db_session")

class CheckUserHasAccessToOffererTest:
    def test_check_user_has_access_to_offerer(self, app):
        pro = users_factories.UserFactory()
        offerer = offers_factories.OffererFactory()
        offers_factories.UserOffererFactory(user=pro, offerer=offerer)
        # fmt: off
        n_queries = (
            1  # select Offerer
            + 1  # select User
            + 1  # select UserOfferer
        )
        # fmt: on
        with assert_num_queries(n_queries):
            check_user_has_access_to_offerer(pro, offerer.id)

    def test_raises_if_user_cannot_access_offerer(self, app):
        user = users_factories.UserFactory()
        offerer = offers_factories.OffererFactory()
        with pytest.raises(ApiErrors) as error:
            check_user_has_access_to_offerer(user, offerer.id)

        assert error.value.errors["global"] == [
            "Vous n'avez pas les droits d'accès suffisant pour accéder à cette information."
        ]
        assert error.value.status_code == 403

class TestLoadOrRaiseErrorTest:
    def test_returns_object_if_found(self, app):
        with pytest.raises(ApiErrors) as error:
            load_or_raise_error(Venue, humanize(1))

        assert error.value.errors["global"] == [
            "Aucun objet ne correspond à cet identifiant dans notre base de données"
        ]
        assert error.value.status_code == 404

    def test_raises_api_error_if_no_object(self, app):
        venue = offers_factories.VenueFactory()

        load_or_raise_error(Venue, humanize(venue.id))  # should not raise


# Parse vaccination site locations for Mono County

# Run manually: python3 -m location_parsers.mono

import re
import time

from . import County, Location
from . import driver_start, driver_stop

county = County(
    name="Mono", url="https://coronavirus.monocounty.ca.gov/pages/vaccinations"
)

# Returns a list of Location objects
def run():
    driver, display = driver_start()
    driver.get(county.url)

    # Wait for ember.js
    time.sleep(5)

    e = driver.find_element_by_xpath("//strong[contains(., 'Vaccination Locations')]")

    h5 = e.find_element_by_xpath("../..")
    next_h5 = h5.find_element_by_xpath(".//following-sibling::h5")

    ul = next_h5.find_element_by_tag_name("ul")
    ul2 = ul.find_element_by_tag_name("ul")
    items = ul2.find_elements_by_tag_name("li")

    locations = []
    for li in items:
        # split name and address
        m = re.match(r"(.+) \((.+)\)", li.text)
        name = m.group(1)

        address = m.group(2)
        if "," not in address:
            # add town name
            town = name.split()[0]
            address += ", " + town
        address += ", CA"

        locations.append(
            Location(name=name, address=address, county=county.name, url=None)
        )

    driver_stop(driver, display)

    return locations

if __name__ == "__main__":
    locations = run()
    print(locations)


class my_open():
    path = ''
    def __init__(self, x):
        self.path = x
    def content(self):
        file_now = open(self.path)
        content = file_now.readlines()
        count = 0
        con = {}
        for i in content:
            count += 1
            con[count] = i
        return con
    def add(self, *joj):
        file_now = open(self.path)
        content = file_now.readlines()
        for j in joj:
            content.append('{}'.format(j))
        return content
    def __del__(self):
        print('over')
    def addlines(self,*lll):
        file_now = open(self.path)
        content = file_now.readlines()
        k = ['%s, %s' % (n, lll) for n in content]
        return k
f2 = my_open('/mnt/share/p677.py')
print(f2.add('1','3'))
print(f2.addlines('6'))


""" Luta test entry module """
from luta.crawler import Crawler

URL1 = "http://www.sahibinden.com/telli-calgilar-muzik-aletleri?query_text_mf=fender+telecaster&query_text=fender+telecaster"

def test_single():
    crw = Crawler(URL1)

    prices = crw.get_values_between('', '
')
    for price in prices:
        print(price)

    next_url = crw.get_last_value_between('<a href="', '" class="prevNextBut" title="Sonraki"')
    print(next_url)

def test_multi():
    loop_pos = 1
    url = URL1
    while True:
        print(f"Loop {str(loop_pos)}")
        crw = Crawler(url)

        prices = crw.get_values_between('', '
')
        for price in prices:
            print(price)

        next_url = crw.get_last_value_between('<a href="', '" class="prevNextBut" title="Sonraki"')
        if next_url == "":
            return
        print(next_url)
        url = f"http://sahibinden.com{next_url}"
        loop_pos += 1

if __name__ == "__main__":
    test_single()


import requests

baseurl = "https://rickandmortyapi.com/api/"
endpoint = "character"

# Retorna la responsejson para una determinada pagina "x"
def main_request(base, endp, x):
    response = requests.get(base+endp + f"?page={x}")
    d = response.json()
    return d

def main_request2(url):
    response = requests.get(url)
    d = response.json()
    return d

# Obtiene el numero de paginas desde la responsejson.

def get_pages(responsejson):
    pages = responsejson["info"]["pages"]
    return pages

# Extrae datos de la response json y los almacena como diccionario dentro de una lista.

def stract_data(responsejson):
    charlist = []
    for char in responsejson["results"]:
        character = {
            "id": char["id"],
            "name": char["name"],
            "episodes": len(char["episode"])
        }
        charlist.append(character)
    return charlist

data = main_request(baseurl, endpoint, 1)
pages = get_pages(data)

# Recorre desde 1 hasta la pagina 34 o hasta pagina que se le indique, realizando la request para obtener la responsejson, extrayendo los datos de la pagina de turno, y extendiendo la lista vacia con esos datos en cada vuelta.

def total_elements(pages):
    new_list = []
    for i in range(1, pages+1):
        data = main_request(baseurl, endpoint, i)
        charxpage = stract_data(data)
        new_list.extend(charxpage)
    return new_list

newlist = total_elements(34)
# print(len(newlist))

url = baseurl+endpoint+f"?page={1}"
# Recorriendo por nextpage.

def total_elements2(url):
    new_list = []

    # Mientras que la url exista:
    while url:
        data = main_request2(url)
        # Actualizar la url con el valor de next en cada vuelta del ciclo while.
        url = data["info"]["next"]
        charxpage = stract_data(data)
        new_list.extend(charxpage)
    return new_list

newlist = total_elements2(url)
print(len(newlist))


from nltk.book import  *
from decimal import *
getcontext().prec= 2

word_lower=[w.lower() for w in text1]
tranning_single_word=[w for w in word_lower if w.isalpha()]
tranning_single_word_dict=dict()
for w in tranning_single_word:
    if w in tranning_single_word_dict:
        tranning_single_word_dict[w]+=1
    else:
        tranning_single_word_dict[w]=1
tranning_single_word_cnt=len(tranning_single_word)
tranning_single_word_prob_dict=dict()
for w in tranning_single_word_dict:
    tranning_single_word_prob_dict[w]=Decimal(Decimal(tranning_single_word_dict[w])/tranning_single_word_cnt)
tranning_pair_word=[(tranning_single_word[i],tranning_single_word[i+1]) for i in range(len(tranning_single_word)-1)]
tranning_pair_word_dict=dict()
for pair in tranning_pair_word:
    key=(pair[0],pair[1])
    if key in tranning_pair_word_dict:
        tranning_pair_word_dict[key]+=1
    else:
        tranning_pair_word_dict[key]=1
tranning_pair_word_cnt=len(tranning_pair_word)
tranning_pair_word_prob=dict()
for pair in tranning_pair_word_dict:
    tranning_pair_word_prob[pair]=Decimal(Decimal(tranning_pair_word_dict[pair])/tranning_pair_word_cnt)
tranning_3_word=[(tranning_single_word[i],tranning_single_word[i+1],tranning_single_word[i+2])
                 for i in range(len(tranning_single_word)-2)]
tranning_3_word_dict=dict()
for triple in tranning_3_word:
    key=(triple[0],triple[1],triple[2])
    if key in tranning_3_word_dict:
        tranning_3_word_dict[key]+=1
    else:
        tranning_3_word_dict[key]=1
tranning_3_word_dict_cnt=len(tranning_3_word)
tranning_3_word_dict_prob=dict()
for t in tranning_3_word_dict:
    tranning_3_word_dict_prob[t]=Decimal(tranning_3_word_dict[t]/tranning_3_word_dict_cnt)
tranning_4_word=[(tranning_single_word[i],tranning_single_word[i+1],tranning_single_word[i+2],tranning_single_word[i+3])
                 for i in range(len(tranning_single_word)-3)]
tranning_4_word_dict=dict()
for w in tranning_4_word:
    if w in tranning_4_word_dict:
        tranning_4_word_dict[w]+=1
    else:
        tranning_4_word_dict[w]=1
tranning_4_word_dict_prob=dict()
tranning_4_word_cnt=len(tranning_4_word)
for w in tranning_4_word_dict:
    tranning_4_word_dict_prob[w]=Decimal(tranning_4_word_dict[w]/tranning_4_word_cnt)
tranning_5_word=[(tranning_single_word[i],tranning_single_word[i+1],tranning_single_word[i+2],tranning_single_word[i+3],tranning_single_word[i+4])
                 for i in range(len(tranning_single_word)-4)]
tranning_5_word_dict=dict()
for w in tranning_5_word:
    if w in tranning_5_word_dict:
        tranning_5_word_dict[w]+=1
    else:
        tranning_5_word_dict[w]=1
tranning_5_word_dict_prob=dict()
tranning_5_word_cnt=len(tranning_5_word)
for w in tranning_5_word_dict:
    tranning_5_word_dict_prob[w]=Decimal(tranning_5_word_dict[w]/tranning_5_word_cnt)
#####################################################################################
def get_text_prob(text):
    text=text.split(' ')
    prob = tranning_single_word_prob_dict[text[0]]
    prob =chec_prob(prob)
    for i in range(len(text)-1):
        n=round(tranning_pair_word_prob[(text[i],text[i+1])],5)
        prob=chec_prob(prob)
        prob=n*prob
        n=chec_prob(round(tranning_single_word_prob_dict[text[-1]],5))
        prob=round(prob*n,5)
        prob=chec_prob(prob)
    return round(prob,5)

def chec_prob(prob):
    if(prob==Decimal(0)):
        return  Decimal(0.0001)
    else:
        return prob
def searach_next_word(word):
    gram2 = sorted(tranning_pair_word_dict.items(), key=lambda item: (item[0], -item[1]))
    #next_wrod=next((element[0][1] for element in gram2 if element[0][0]==word),None)
    next_word=dict()
    for element in  gram2:
        if element[0][0]==word:
            next_word[element[0][1]]=element[1]

    return next_word
def change_dict_value(dict_list):
    for key in dict_list:
        if dict_list[key] is None:
            dict_list[key]=0
    return  dict_list
def get_the_end_word(text):
    text=text.split(' ')
    return  text[-1]
def predicet(text,n):
    next_list=searach_next_word(get_the_end_word(text))
    sentance_dict=dict()
    for w in next_list:
        ntext=text+" "+w
        stext=ntext.split(' ')
        if(n==1):
            sentance_dict[w]=tranning_pair_word_prob.get((stext[0],stext[1]))
        elif(n==2):
            sentance_dict[w]=tranning_3_word_dict_prob.get((stext[0],stext[1],stext[2]))
        elif(n==4):
            sentance_dict[w]=tranning_5_word_dict_prob.get((stext[0],stext[1],stext[2],stext[3],stext[4]))
        elif(n==3):
            sentance_dict[w]=tranning_4_word_dict_prob.get((stext[0],stext[1],stext[2],stext[3]))
        else:
            break
    if(len(sentance_dict)==0):
        print("can't predicate")
        return
    sentance_dict=change_dict_value(sentance_dict)
    sentance_dict=sorted(sentance_dict.items(),key=lambda kv:kv[1],reverse=True)
   # print(text+" "+max(sentance_dict,key=lambda key:sentance_dict.values()))
    frist=True
    for w in sentance_dict:
        if(frist):
            print('the mose predciated one is:')
            print(text+" "+w[0])
            frist=False
            print("others:")
        else:
            print(text+" "+w[0])
    #print(sentance_dict)
   # print(max(sentance_dict,key=lambda key:sentance_dict[key]))

predicet('so am i',3)


import sys
sys.path.append('../..')

import tensorflow as tf
import numpy as np
from stats import Stats
from network import RecurrentNeuralNetwork

# Get MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("../data/MNIST_data/", one_hot=True)

flags = tf.app.flags

# Network
flags.DEFINE_integer('sequence_length', 28, 'Length of each RNN sequence.')
flags.DEFINE_integer('input_size', 28, 'Size of each input.')
flags.DEFINE_integer('hidden_size', 128, 'Number of hidden cells.')
flags.DEFINE_string('cell_type', 'lstm', 'Type of cell to use in the RNN.')

# Optimizer
flags.DEFINE_float('learning_rate', 0.001, 'Learning rate of the optimizer.')
flags.DEFINE_string('optimizer', 'adam', 'Specifices optimizer to use [adam, gradient_descent, rmsprop]. Defaults to gradient descent')

# General
flags.DEFINE_integer('minibatches', 1000, 'Number of minibatches to run the training on.')
flags.DEFINE_integer('minibatch_size', 128, 'Number of samples in each minibatch.')
flags.DEFINE_integer('status_update', 100, 'How often to print an status update.')
flags.DEFINE_integer('random_seed', 123, 'Sets the random seed.')
flags.DEFINE_boolean('run_test', True, 'If the final model should be tested')
flags.DEFINE_boolean('use_gpu', False, 'If it should run the TensorFlow operations on the GPU rather than the CPU.')

settings = flags.FLAGS

print('Starting session with: Minibatches: {} -- Learning Rate: {} -- Optimizer: {}'.format(
    settings.minibatches,
    settings.learning_rate,
    settings.optimizer))

if settings.use_gpu:
    device = '/gpu:0'
else:
    device = '/cpu:0'

network = RecurrentNeuralNetwork(
    device,
    settings.random_seed,
    settings.hidden_size,
    settings.input_size,
    settings.sequence_length,
    settings.cell_type,
    settings.minibatch_size,
    settings.learning_rate,
    settings.optimizer)

# Statistics summary writer
summary_dir = '../../logs/rnn-mnist_hiddensize-{}_celltype-{}_minibatches-{}_minibatchsize-{}_lr-{}_optimizer-{}/'.format(
    settings.hidden_size,
    settings.cell_type,
    settings.minibatches,
    settings.minibatch_size,
    settings.learning_rate,
    settings.optimizer)

summary_writer = tf.summary.FileWriter(summary_dir, network.sess.graph)
stats = Stats(network.sess, summary_writer, 2)

for i in range(settings.minibatches):
    # Get minibatch
    batch_xs, batch_ys = mnist.train.next_batch(settings.minibatch_size)
    # Calculate batch accuracy
    acc = network.get_accuracy(batch_xs, batch_ys)
    # Run training
    loss = network.train(batch_xs, batch_ys)
    # Update stats
    stats.update({'loss': loss, 'accuracy': acc, 'step': i})

    if i % settings.status_update == 0:
        # Print update
        print('Minibatches done: {}, Loss: {}, Accuracy: {}%'.format(max(i, 1), format(loss, '.4f'), format(acc*100, '.2f')))

if settings.run_test:
    print(' --- TESTING MODEL ---')
    x = 0
    accuracy = []
    for n in range(int((len(mnist.test.images)/settings.minibatch_size))):
        # Create batches of size: minibatch_size
        lower_index = settings.minibatch_size * n
        upper_index = (settings.minibatch_size * n) + settings.minibatch_size
        batch_xs = mnist.test.images[lower_index: upper_index]
        batch_ys = mnist.test.labels[lower_index: upper_index]
        # Get accuracy
        acc = network.get_accuracy(batch_xs, batch_ys)
        accuracy.append(acc)

    print('Accuracy on test set: {}%'.format(format(np.average(accuracy)*100, '.2f')))


import os
import allure
import pytest

@pytest.fixture(scope='session')
def login_fixture():
    print("===前置登录===")

@allure.step('步骤一')
def step_1():
    print("操作步骤----------1")

@allure.step('步骤二')
def step_2():
    print("操作步骤----------2")

@allure.step('步骤三')
def step_3():
    print("操作步骤----------3")

@allure.epic('epic 相当于总体描述')
@allure.feature('测试模块')
class TestAllureALL:
    @allure.testcase("https://www.cnblogs.com/poloyy/", '测试用例,点我一下')
    @allure.issue("https://www.cnblogs.com/poloyy/p/12219145.html", 'Bug 链接,点我一下')
    @allure.title("用例的标题")
    @allure.story("story one")
    @allure.severity("critical")
    def test_case_1(self,login_fixture):
        """
        学习-小菠萝测试笔记地址：https://www.cnblogs.com/poloyy/
        """
        print("测试用例1")
        step_1()
        step_2()

    @allure.severity("critical")
    @allure.story("story two")
    def test_case_2(self,login_fixture):
        print("测试用例2")
        step_1()
        step_3()

@allure.epic("另一个 epic")
@allure.feature("查找模块")
class TestAllureALL2:
    @allure.story("story three")
    def test_case_3(self, login_fixture):
        print("测试用例3")
        step_1()

    # @allure.story("story four")
    # def test_case_4(self,login_fixture):
    #     print("测试用例4")
    #     step_3()


# An example of using the compress function inside itertools
# If you do not understand you can check this link as well:
# https://www.novixys.com/blog/python-itertools-compress-dropwhile-takewhile-groupby/

import itertools
import random

names = ["Subhayan", "Shaayan", "Dimpu", "Poulomi", "Rakesh"]

choices = [random.choice([0, 1]) for _ in itertools.repeat(None, 10)]
print(choices)

for item in itertools.compress(names, choices):
    print(item)


import os
from typing import Dict
from flask import Flask

def create_app(config_dict: Dict = {}) -> Flask:
    app = Flask("main")

    DATABASE_URI = os.environ.get('DATABASE_URI')
    BUCKET_NAME = os.environ.get('BUCKET_NAME')
    SQS_URL = os.environ.get('SQS_URL')
    SECRET = os.environ.get('SECRET')
    AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
    AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')

    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['PROPAGATE_EXCEPTIONS'] = True
    app.config['JWT_SECRET_KEY'] = SECRET
    app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URI
    app.config['BUCKET_NAME'] = BUCKET_NAME
    app.config['SQS_URL'] = SQS_URL
    app.config['AWS_ACCESS_KEY_ID'] = AWS_ACCESS_KEY_ID
    app.config['AWS_SECRET_ACCESS_KEY'] = AWS_SECRET_ACCESS_KEY

    return app


import itertools
import numpy as np
from seraphine.agents.common.abstract import AbstractAgent
from seraphine.agents.common.factory import load_agent, safe_deepcopy_env

class RobustEPCAgent(AbstractAgent):
    def __init__(self, env, config):
        super().__init__(config)
        self.A = np.array(self.config["A"])
        self.B = np.array(self.config["B"])
        self.phi = np.array(self.config["phi"])
        self.env = env
        if hasattr(self.env.unwrapped, "automatic_record_callback"):
            self.env.unwrapped.automatic_record_callback = self.record_transition
        self.data = []
        self.robust_env = None
        self.sub_agent = load_agent(self.config["sub_agent_path"], env)
        self.ellipsoids = [self.ellipsoid()]

    @classmethod
    def default_config(cls):
        return {
            "gamma": 0.9,
            "delta": 0.9,
            "lambda": 1e-6,
            "sigma": [[1]],
            "A": [[1]],
            "B": [[1]],
            "D": [[1]],
            "omega": [[0], [0]],
            "phi": [[[1]]],
            "simulation_frequency": 10,
            "policy_frequency": 2,
            "parameter_bound": 1,
            "parameter_box": [[0], [1]],
        }

    def record(self, observation, action, reward, next_observation, done, info):
        """
        the dataset D_[N] should now have a transition.
        the "state" and "deriative" fields of a dict should make up the
        state space. a discrete action could be transformed into a continuous
        by surroundings.
        """
        if hasattr(self.env.unwrapped, "automatic_record_callback"):
            return
        try:
            control = self.env.unwrapped.dynamics.action_to_control(action)
        except AttributeError:
            control = np.array([action])
        state = next_observation["state"]
        deriative = next_observation["deriative"]
        self.record_transition(state, deriative, control)

    def record_transition(self, state, deriative, control):
        """
        a callback that the environment can use in place ``RobustEPCAgent.record()``
        to record a number of transition when it mimics the execution of an action.
        """
        self.data.append((state.copy(), control.copy(), deriative.copy()))
        self.ellipsoids.append(self.ellipsoids())

    def plan(self, observation):
        """
        create an optimistic version of the environment for OPD planning that
        propagates state intervals and computes pessimistic incentives.
        """
        self.robust_env = self.robustify_env()
        self.sub_agent.env = self.robust_env
        return self.sub_agent.plan(observation)

    def ellipsoids(self):
        """
        create an ellipsoid of confidence over the parameter theta, where
        dot{x} = A x + (phi x) theta + B u + D omega
        y = dot{x} + C nu
        """
        d = self.phi.shape[0]
        lambda_ = self.config["lambda"]
        if not self.data:
            g_n_lambda = lambda_ * np.identity(d)
            theta_n_lambda = np.zeros(d)
        else:
            phi = np.array(
                [
                    np.squeeze(self.phi @ state, axis=2).transpose()
                    for state, _, _ in self.data
                ]
            )
            dx = np.array([derivative for _, _, derivative in self.data])
            ax = np.array([self.A @ state for state, _, _ in self.data])
            bu = np.array([self.B @ control for _, control, _ in self.data])
            y = dx - ax - bu

            sigma_inv = np.linalg.inv(self.config["sigma"])
            g_n = np.sum(
                [np.transpose(phi_n) @ sigma_inv @ phi_n for phi_n in phi], axis=0
            )
            g_n_lambda = g_n + lambda_ * np.identity(d)

            theta_n_lambda = (
                np.linalg.inv(g_n_lambda)
                @ np.sum(
                    [
                        np.transpose(phi[n]) @ sigma_inv @ y[n]
                        for n in range(y.shape[0])
                    ],
                    axis=0,
                )
            ).squeeze(axis=1)
            theta_n_lambda = theta_n_lambda.clip(0, 1)
        beta_n = (
            np.sqrt(
                2
                * np.log(
                    np.sqrt(np.linalg.det(g_n_lambda) / lambda_**d)
                    / self.config["delta"]
                )
            )
            + np.sqrt(lambda_ * d) * self.config["parameter_bound"]
        )
        return theta_n_lambda, g_n_lambda, beta_n

    def polytope(self):
        """
        derived from the confidence ellipsoid, the confidence polytope
        """
        theta_n_lambda, g_n_lambda, beta_n = self.ellipsoids[-1]
        d = g_n_lambda.shape[0]
        values, p = np.linalg.eig(g_n_lambda)
        m = beta_n * np.linalg.inv(p) @ np.diag(np.sqrt(1 / values))
        h = np.array(list(itertools.product([-1, 1], repeat=d)))
        d_theta_k = np.clip(
            [m @ h_k for h_k in h],
            -self.config["parameter_bound"],
            self.config["parameter_bound"],
        )
        a0 = self.A + np.tensordot(theta_n_lambda, self.phi, axes=[0, 0])
        da = [np.tensordot(d_theta, self.phi, axes=[0, 0]) for d_theta in d_theta_k]
        return a0, da

    def robustify_env(self):
        """
        create a stable environment version:
            - do the dynamics polytope calculation (A0, dA)
            - make the LVP interval predictor adjustable to the environment by
              setting it
            - when given an interval predictor, the environment has to provide
              negative incentives.
            - since we are not monitoring while we plan, we should prevent the recording
              of environment changes.
        """
        a0, da = self.polytope()
        from highway_env.interval import LPV

        lpv = LPV(
            a0=a0,
            da=da,
            x0=self.env.unwrapped.state.squeeze(-1),
            b=self.B,
            d=self.config["D"],
            omega_i=self.config["omega"],
        )
        robust_env = safe_deepcopy_env(self.env)
        robust_env.unwrapped.lpv = lpv
        robust_env.unwrapped.automatic_record_callback = None
        return robust_env

    def act(self, state):
        return self.plan(state)[0]

    def get_plan(self):
        return self.sub_agent.planner.get_plan()

    def reset(self):
        self.data = []
        self.ellipsoids = [self.ellipsoids()]
        return self.sub_agent.reset()

    def seed(self, seed=None):
        return self.sub_agent.seed(seed)

    def save(self, filename):
        pass

    def load(self, filename):
        pass

class NominalEPCAgent(RobustEPCAgent):
    def __init__(self, env, config):
        super().__init__(env, config)
        self.config["omega"] = np.zeros(np.shape(self.config["omega"])).tolist()

    def polytope(self):
        """
        don't take the calculated dynamics uncertainty into consideration
        """
        a0, da = super().polytope()
        da = [np.zeros(a0.shape)]
        return a0, da


import numpy as np
N = int(input())

graph = [[] for _ in range(N)]
for _ in range(N-1):
    A, B = map(int, input().split())
    A, B = A - 1, B - 1
    graph[A].append(B)
    graph[B].append(A)

def bfs(s):
    visited = [-1] * N
    que = [s]
    visited[s] = 0
    for q in que:
        for v in graph[q]:
            if visited[v] != -1:
                continue
            visited[v] = visited[q] + 1
            que.append(v)
    return visited

print(max(bfs(np.argmax(bfs(0))))+1)


#
# @lc app=leetcode id=349 lang=python3
#
# [349] Intersection of Two Arrays
#

# @lc code=start
from collections import defaultdict

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        # res = []
        # nums1.sort()
        # nums2.sort()
        # n1, n2 = len(nums1), len(nums2)
        # i, j = 0, 0
        # while i<n1 and j<n2:
        #     if nums1[i] < nums2[j]:
        #         i += 1
        #     elif nums1[i] > nums2[j]:
        #         j += 1
        #     else:
        #         if not res or nums1[i] != res[-1]:
        #             res.append(nums1[i])
        #         i += 1
        #         j += 1
        # return res

        res, occur = [], defaultdict(int)
        for num in nums1:
            occur[num] += 1
        for num in nums2:
            if occur[num]:
                res.append(num)
                occur[num] = 0
        return res

# @lc code=end


import sys
import json
import argparse

def check_overlap(set1_path, set2_path, l1):
    """ Checks challenge set overlap. """

    # Read-in sets
    print('Reading-in adversarial samples table ...')
    with open(set1_path, 'r', encoding='utf8') as s1p:
        set1 = json.load(s1p)
    with open(set2_path, 'r', encoding='utf8') as s2p:
        set2 = json.load(s2p)

    overlap = 0

    for term in set1.keys():
        if term not in set2.keys():
            continue
        s1_sents = list()
        s2_sents = list()

        for seed_cluster in set1[term].keys():
            for adv_cluster in set1[term][seed_cluster].keys():
                for seed_sentence in set1[term][seed_cluster][adv_cluster].keys():
                    s1_sents.append(seed_sentence)

        for seed_cluster in set2[term].keys():
            for adv_cluster in set2[term][seed_cluster].keys():
                for seed_sentence in set2[term][seed_cluster][adv_cluster].keys():
                    s2_sents.append(seed_sentence)

        overlap += len(list(set(s1_sents) & set(s2_sents)))

    print('Overlap: {:d} sentences ({:.2f}%)'.format(overlap, (overlap / l1) * 100))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--corpus_path1', type=str, help='path to the first challenge set',
                        required=True)
    parser.add_argument('--corpus_path2', type=str, help='path to the second challenge set',
                        required=True)
    parser.add_argument('--corpus_size', type=int, help='challenge set size (has to be equal for both)',
                        required=True)
    args = parser.parse_args()

    check_overlap(sys.argv[1], sys.argv[2], int(sys.argv[3]))


from datetime import datetime
from typing import Optional, TYPE_CHECKING, Union

from propsd.enums import SourceEvents, SourceState
from propsd.sourcemanager import SourceManager
from propsd.util import dispatch

if TYPE_CHECKING:
    from apscheduler.job import Job

class Schedulable:
    updated: Optional[datetime] = None
    _state: Optional[SourceState] = None

    events: dict = {
        SourceEvents.CREATED: dispatch.Signal(providing_args=['source']),
        SourceEvents.INITIALIZED: dispatch.Signal(providing_args=['source']),
        SourceEvents.NO_UPDATE: dispatch.Signal(providing_args=['source']),
        SourceEvents.ERROR: dispatch.Signal(providing_args=['source', 'error']),
        SourceEvents.UPDATE: dispatch.Signal(providing_args=['source', 'data']),
        SourceEvents.SHUTDOWN: dispatch.Signal(providing_args=['source'])
    }

    def __init__(self):
        self._state = SourceState.CREATED
        self._send_event(SourceEvents.CREATED, source=self)

    def __repr__(self):
        return '{}.{}'.format(self.__class__.__name__, self._state)

    def _pre_get(self):
        if self._state == SourceState.CREATED:
            # First pass
            self._state = SourceState.INITIALIZING
        elif self._state == SourceState.WAITING:
            # Set running state
            self._state = SourceState.RUNNING

    def _post_get(self):
        self.updated = datetime.now()

        if self._state == SourceState.INITIALIZING:
            self._state = SourceState.WAITING
            self._send_event(SourceEvents.INITIALIZED, source=self)
        elif self._state == SourceState.RUNNING:
            # Reset to waiting state on success
            self._state = SourceState.WAITING

    @property
    def job(self) -> 'Job':
        return SourceManager.get_job(str(self))

    @property
    def available(self):
        return self._state in [SourceState.WAITING, SourceState.RUNNING]

    def shutdown(self):
        self._state = SourceState.SHUTDOWN
        self._send_event(SourceEvents.SHUTDOWN, source=self)

    def _send_event(self, event: SourceEvents, **kwargs: Optional[Union['Schedulable', dict]]) -> None:
        self.events[event].send_robust(sender=self.__class__, **kwargs)

def get_event(event: SourceEvents) -> dispatch.Signal:
    return Schedulable.events[event]


import random

from pysc2.agents.myAgent.myAgent_12.config import config, config_for_level_2_build_controller
from pysc2.agents.myAgent.myAgent_12.tools.unit_list import combat_unit, building
from pysc2.lib import features, actions, units
import numpy as np

hard_code = [  # 28种
    0,  # 军械库
    5,  # 兵营
    0,  # 飞行的兵营
    0,  # 重定向兵营
    0,  # 兵营实验室
    0,  # #碉堡
    1,  # 指挥中心
    0,  # 飞行的指挥中心
    0,  # 工程湾
    0,  # 工厂
    0,  # 飞起来的工厂
    0,  # 工厂重定向
    0,  # 工厂实验室
    0,  # 聚变芯体
    0,  # 幽灵军校
    0,  # 导弹塔
    0,  # 轨道指挥中心
    0,  # 飞行的指挥中心
    0,  # 行星要塞
    0,  # 反应堆
    0,  # 感应塔
    0,  # 星港
    0,  # 星港飞起来
    0,  # 星港重定向
    0,  # 星港实验室
    15,  # 补给站
    0,  # 补给站下
    0,  # 科技实验室
]

#######################动作集合
def chooseARandomPlace(input_x, input_y):
    offset = 20
    add_y = random.randint(-offset, offset)
    add_x = random.randint(-offset, offset)

    if input_x + add_x >= config.MAP_SIZE:

        outx = config.MAP_SIZE

    elif input_x + add_x < 0:
        outx = 0

    else:
        outx = input_x + add_x

    if input_y + add_y >= config.MAP_SIZE:

        outy = config.MAP_SIZE

    elif input_y + add_y < 0:
        outy = 0

    else:
        outy = input_y + add_y

    return (outx, outy)

def get_distances(units, xy):
    units_xy = [(unit.x, unit.y) for unit in units]
    return np.linalg.norm(np.array(units_xy) - np.array(xy), axis=1)

def build_supply_depot(obs):
    commandCenters = get_my_units_by_type(obs, units.Terran.CommandCenter)
    if len(commandCenters) > 0:
        commandCenter = commandCenters[random.randint(0, len(commandCenters) - 1)]
        scvs = get_my_units_by_type(obs, units.Terran.SCV)
        if (obs.observation.player.minerals >= 100 and len(scvs) > 0 and obs.observation.player.food_cap < 200):
            supply_depot_xy = chooseARandomPlace(commandCenter.x, commandCenter.y)
            distances = get_distances(scvs, supply_depot_xy)
            scv = scvs[np.argmin(distances)]
            return actions.RAW_FUNCTIONS.Build_SupplyDepot_pt("now", scv.tag, supply_depot_xy)
    return actions.RAW_FUNCTIONS.no_op()

def get_my_completed_units_by_type(obs, unit_type):
    return [unit for unit in obs.observation.raw_units
            if unit.unit_type == unit_type
            and unit.build_progress == 100
            and unit.alliance == features.PlayerRelative.SELF]

def build_barracks(obs):
    commandCenters = get_my_units_by_type(obs, units.Terran.CommandCenter)
    if len(commandCenters) > 0:
        completed_supply_depots = get_my_completed_units_by_type(
            obs, units.Terran.SupplyDepot)

        commandCenter = commandCenters[random.randint(0, len(commandCenters) - 1)]
        scvs = get_my_units_by_type(obs, units.Terran.SCV)
        if (len(completed_supply_depots) > 0 and
                obs.observation.player.minerals >= 150 and len(scvs) > 0):
            barracks_xy = chooseARandomPlace(commandCenter.x, commandCenter.y)
            distances = get_distances(scvs, barracks_xy)
            scv = scvs[np.argmin(distances)]
            return actions.RAW_FUNCTIONS.Build_Barracks_pt(
                "now", scv.tag, barracks_xy)
    return actions.RAW_FUNCTIONS.no_op()

def do_nothing(obs):
    return actions.RAW_FUNCTIONS.no_op()

def assembly_action(obs, action_prob, controller, mark):
    if mark == 'train':
        action_number = np.random.choice(range(config_for_level_2_build_controller.ACTION_DIM), p=action_prob)
    else:
        action_number = np.argmax(action_prob)
    action = controller[action_number](obs)
    return action, action_number

####################################### 观察集合
def get_my_units_by_type(obs, unit_type):
    return [unit for unit in obs.observation.raw_units
            if unit.unit_type == unit_type
            and unit.alliance == features.PlayerRelative.SELF]

def get_enemy_units_by_type(obs, unit_type):
    return [unit for unit in obs.observation.raw_units
            if unit.unit_type == unit_type
            and unit.alliance == features.PlayerRelative.ENEMY]

def get_state(obs):
    state = []  # 52维
    state.append(obs.observation['game_loop'] / 10000)  # step 1
    for unit_type in combat_unit:
        state.append(len(get_my_units_by_type(obs, unit_type)) / 200)  # 18
    for building_type in building:
        state.append(len(get_my_units_by_type(obs, building_type)) / 20)  # 28

    state.append(obs.observation.player.minerals)  # 1
    state.append(obs.observation.player.vespene)  # 1
    state.append(len(get_my_units_by_type(obs, 45)) / 200)  # 1
    state.append(((len(get_enemy_units_by_type(obs, 18))) +  # 敌方指挥中心数量 1
                  len(get_enemy_units_by_type(obs, 36)) +
                  len(get_enemy_units_by_type(obs, 132)) +
                  len(get_enemy_units_by_type(obs, 134)) +
                  len(get_enemy_units_by_type(obs, 130))) / 20
                 )
    state.append(len(get_enemy_units_by_type(obs, 45)) / 200)  # 1

    return np.array(state)

def get_reward(obs):
    building_state = []
    for unit_type in building:
        building_state.append(len(get_my_units_by_type(obs, unit_type)))  # 18

    reward = (200 - np.linalg.norm(np.array(hard_code) - np.array(building_state))) / 200

    return reward


'''
Ask	the	user	to	input	a	positive	integer	n,
and	print	a	textual	image	of	an	hourglass
made	of	2n	lines	with	asterisks.
For	example	if	n=4,	the	program	should	print:
    *******
     *****
      ***
       *
       *
      ***
     *****
    *******
 '''
n = int(input("Please enter a positive integer: "));
num = n
for i in range (0,n):
    line = '*'*((2*n)-1)
    print ((i* ' '+line))
    n -= 1
for j in range (0,num):
    line = '*' * ((j*2) + 1)
    print (((num) * ' ') + line)
    num-=1


# -*- coding:utf-8 -*-

import struct
import socket

class Packet(object):
    def __init__(self, _header, buf):
        hdr_fmt = '>' + ''.join([x[1] for x in _header])  # '>' means the binary data is big-endian
        hdr_fields = [x[0] for x in _header]
        self.__hdr_len__ = struct.calcsize(hdr_fmt)
        i = 0
        for hdr_val in struct.unpack(hdr_fmt, buf[:self.__hdr_len__]):
            setattr(self, hdr_fields[i], hdr_val)  # add header's field-keys to class's attributes
            i += 1

        self.data = buf[self.__hdr_len__:]

# class of Ethernet
# some Ethernet_II payload types
ETH_TYPE_IP = 0x0800  # IP protocol
ETH_TYPE_IP6 = 0x86DD  # IPv6 protocol
_eth_header = (
    ('dst', '6s'),
    ('src', '6s'),
    ('type', 'H')
)

class Ethernet(Packet):
    def __init__(self, buf):
        super(Ethernet, self).__init__(_eth_header, buf)

# class of IP
# some IP protocol
IP_PROTO_TCP = 6  # TCP
IP_PROTO_UDP = 17  # UDP
_ip_header = (
    ('_v_hl', 'B'),  # ip header length(unit: 4 bytes)
    ('type_of_service', 'B'),
    ('len', 'H'),
    ('id', 'H', 0),
    ('flags_offset', 'H'),
    ('ttl', 'B'),
    ('protocol', 'B'),
    ('checksum', 'H'),
    ('_src', '4s'),
    ('_dst', '4s')
)

class IP(Packet):
    def __init__(self, buf):
        super(IP, self).__init__(_ip_header, buf)
        offload = ((self._v_hl & 0xf) << 2) - self.__hdr_len__
        if self.len:
            self.data = buf[self.__hdr_len__ + offload: self.len]
        else:  # might be TCP segmentation offload
            self.data = buf[self.__hdr_len__ + offload:]
        self.src = socket.inet_ntoa(self._src)
        self.dst = socket.inet_ntoa(self._dst)

# class of TCP
# some TCP control flags
TH_FIN = 0x01  # end of data
TH_SYN = 0x02  # synchronize sequence numbers
TH_ACK = 0x10  # acknowledgment number set
TH_PSH = 0X08
# some TCP options
TCP_OPT_MSS = 2  # maximum segment size, len 4
TCP_OPT_WSCALE = 3  # window scale factor, len 3
TCP_OPT_TIMESTAMP = 8  # timestamp, len 10
_tcp_header = (
    ('src_port', 'H'),
    ('dst_port', 'H'),
    ('seq', 'I'),
    ('ack', 'I'),
    ('_offset', 'B'),
    ('flags', 'B'),
    ('win_size', 'H'),
    ('checksum', 'H'),
    ('urgent_ptr', 'H')
)

def parse_opts(buf):
    opts = {}
    while buf:
        o = buf[0]
        if o <= 1:      # EOL or NOP: only has 1 byte of type field and no len/val field
            buf = buf[1:]
        else:
            len = buf[1]    # includes type, len and info
            d, buf = buf[2:len], buf[len:]
            opts[o] = d
    return opts

class TCP(Packet):
    def __init__(self, buf):
        super(TCP, self).__init__(_tcp_header, buf)
        offload = ((self._offset >> 4) << 2) - self.__hdr_len__
        self.data = buf[self.__hdr_len__ + offload:]

        self.opts = parse_opts(buf[self.__hdr_len__:self.__hdr_len__ + offload])
        self.win_scale = None   # range 0-14
        self.tsval = None   # Timestamp Value
        self.tsecr = None   # Timestamp Echo Reply
        self.MSS = None     # Maximum Segment Size
        self.src_ip = None
        self.dst_ip = None
        self.time = None

        if TCP_OPT_WSCALE in self.opts.keys():
            self.win_scale = int.from_bytes(self.opts[TCP_OPT_WSCALE], "big")
        if TCP_OPT_TIMESTAMP in self.opts.keys():
            ts_buf = self.opts[TCP_OPT_TIMESTAMP]
            self.tsval = int.from_bytes(ts_buf[0:4], "big")
            self.tsecr = int.from_bytes(ts_buf[4:8], "big")
        if TCP_OPT_MSS in self.opts.keys():
            self.MSS = int.from_bytes(self.opts[TCP_OPT_MSS], "big")

    def set_ip(self, ip):
        self.src_ip = ip.src
        self.dst_ip = ip.dst

def ip_pkg(buf):
    eth = Ethernet(buf)
    if eth.type == ETH_TYPE_IP or eth.type == ETH_TYPE_IP6:
        return IP(eth.data)
    return None

def tcp_pkg(ip):
    if ip.protocol == IP_PROTO_TCP:
        tcp = TCP(ip.data)
        tcp.set_ip(ip)
        return tcp
    return None


import sys
import traceback
import time

class Robot(object):
    """
    The robot class is an abstract interface to encapsulate how a real robot is implemented.

    The provided functions are designed so that they work on different robot hardware.

    However this robot class is just a super class to more specific robot classes.
    You should NEVER instantiate this class but rather specialised child classes.
    """

    def __init__(self):
        """
        Initializes the robot.

        This also sets up the private variables that have to be populated by child classes.

        Child classes should not overwrite the get_something methods but call the _update methods.

        All set methods have to be implemented by the child classes correctly.
        """
        self._lat = 0
        self._lon = 0
        self._dir_to_north = 0

        self._x = 0
        self._y = 0
        self._heading = 0

        self._buttons = [False, False, False, False]

        self._running = True

        self.on_ultrasonic_reading = None
        self.on_global_position = None
        self.on_local_position = None
        self.on_button_state_changed = None
        self.on_sensor_reading = None

    def wait(self):
        """
        Waits forever or until the user presses CTRL + C.
        """
        print("Press CTRL + C to exit wait.")
        try:
            while self._running:
                time.sleep(1)
        except KeyboardInterrupt:
            print("User pressed CTRL + C")

    def shutdown(self):
        """
        Call this method to ensure that the robot hardware has correctly been stopped.

        This also unregisters all callbacks.
        """
        self.set_speed(0)
        self.set_turn(0)

        self.on_ultrasonic_reading = None
        self.on_global_position = None
        self.on_local_position = None
        self.on_button_state_changed = None
        self.on_sensor_reading = None

    def set_led(self, led_id, status):
        """
        Set the state of an led.

        The state may be on and off.
        True = on
        False = off
        """
        print("Set LED {} to {}".format(led_id, status))

    def set_speed(self, speed):
        """
        Set the speed of the robot in m/s.
        """
        print("Speed was set to {}".format(speed))

    def set_turn(self, turn):
        """
        Set the turn of the robot where 0 means no turn, 1 max turn left and -1 max turn right.
        """
        print("Turn was set to {}".format(turn))

    def set_ultrasonic_direction(self, angle):
        """
        Set the direction in which the ultrasonic sensor looks.
        An angle of 0 means straight ahead, while +pi/2 would mean 90 degree to the left.
        """
        print("Ultrasonic direction was set to {}".format(angle))

    def get_latest_global_position(self):
        """
        Get the latest known global position of the robot.

        The return value is (lat, lon, direction to north)
        """
        return self._lat, self._lon, self._dir_to_north

    def get_latest_local_position(self):
        """
        Get the latest known local position of the robot.

        A local position is the position of the robot relative to the point where it was turned on.

        The return value is (x, y, heading)
        """
        return self._x, self._y, self._heading

    def get_button_state(self, button_id):
        """
        Get the state of a button.

        The button id must be valid otherwise an error is printed and False returned.

        If the id is valid the method returns True if the button is pressed and False otherwise.
        """
        if button_id > len(self._buttons) - 1 or button_id < 0:
            print("ERROR: Invalid button id. Button {} does not exist.".format(button_id))
            return False
        return self._buttons[button_id]

    def _update_button_state(self, button_id, state):
        """
        PRIVATE FUNCTION Do not use!

        The hardware implementation can call this function to update the state of a button.

        This method keeps track of the state of all buttons and invokes the on_button_state changed if availible and nescesarry.
        """
        if button_id > len(self._buttons) - 1 or button_id < 0:
            print("ERROR: Invalid button id. Button {} does not exist.".format(button_id))
            return False
        if self._buttons[button_id] == state:
            return False

        self._buttons[button_id] = state
        if self.on_button_state_changed is not None:
            try:
                self.on_button_state_changed(button_id, state)
            except:
                traceback.print_exc(file=sys.stdout)
                print("Method got automatically unregistered.")
                self.on_button_state_changed = None

    def _update_ultrasonic_reading(self, dist, angle):
        """
        PRIVATE FUNCTION Do not use!

        The hardware implementation can call this function to update an ultrasonic reading.

        This method calls the on_ultrasonic_reading if availible.
        """
        if self.on_ultrasonic_reading is not None:
            try:
                self.on_ultrasonic_reading(dist, angle)
            except:
                traceback.print_exc(file=sys.stdout)
                print("Method got automatically unregistered.")
                self.on_ultrasonic_reading = None

    def _update_sensor_reading(self, sensor, data):
        """
        PRIVATE FUNCTION Do not use!

        The hardware implementation can call this function to update an unspecified sensor reading.

        This method calls the on_sensor_reading if availible.

        sensor is the name of the sensor as a string. (e.g. laser_scanner_1)
        data is the data payload. (e.g. an array containing distances in cm)
        """
        if self.on_sensor_reading is not None:
            try:
                self.on_sensor_reading(sensor, data)
            except:
                traceback.print_exc(file=sys.stdout)
                print("Method got automatically unregistered.")
                self.on_sensor_reading = None

    def _update_global_position(self, lat, lon, dir_to_north, accuracy):
        """
        PRIVATE FUNCTION Do not use!

        The hardware implementation can call this function to update the global position.

        This method keeps track of the global position and invokes the on_global_position changed if availible and nescesarry.
        """
        self._lat = lat
        self._lon = lon
        self._dir_to_north = dir_to_north
        if self.on_global_position is not None:
            try:
                self.on_global_position(lat, lon, dir_to_north, accuracy)
            except:
                traceback.print_exc(file=sys.stdout)
                print("Method got automatically unregistered.")
                self.on_global_position = None

    def _update_local_position(self, x, y, heading, accuracy):
        """
        PRIVATE FUNCTION Do not use!

        The hardware implementation can call this function to update the local position.

        This method keeps track of the local position and invokes the on_local_position changed if availible and nescesarry.
        """
        self._x = x
        self._y = y
        self._heading = heading
        if self.on_local_position is not None:
            try:
                self.on_local_position(x, y, heading, accuracy)
            except:
                traceback.print_exc(file=sys.stdout)
                print("Method got automatically unregistered.")
                self.on_local_position = None


import datetime
import numpy
import tables
import time

import Biclustering.Array
import Biclustering.Bicluster
import Biclustering.Bit
import Biclustering.BitSet
import Biclustering.Combinatorics
import Biclustering.Sizing
import Biclustering.Timing

def fullCoverageData(conditions, minGenes=2):
    """Returns a GEM containing all possible biclusters of [2,conditions]
    conditions with minGenes genes

    @param conditions number of conditions in GEM
    @param minGenes genes in each bicluster of conditions conditions in GEM
    @return data for a GEM
    """
    patterns = Biclustering.Combinatorics.xpermutations(conditions, conditions)

    data = numpy.zeros((2 * patterns.len(), conditions))

    offset = 0
    for p in patterns:
        data[offset : offset + 2] = p
        offset += 2

    return data

def packData(data):
    """Compacts data by converting it to the minimum int size

    @param data data to compact
    @return compacted data
    """

    compact = Biclustering.Sizing.sizeArray(data.shape[1])

    return data.argsort().argsort().astype(compact)

class GeneExpressionMatrix(object):

    FILE_EXTENSION = "gem"
    FILTERS = tables.Filters(complevel = 1, complib= 'lzo')

    def __init__(self, name, data=None, path=None, minGenes=2, filters=None):
        self.name = name

        if path is None:
            # default to PWD
            path = "./"

        fileName = path + name + "." + GeneExpressionMatrix.FILE_EXTENSION

        if filters is None:
            filters = self.FILTERS

        # if creating this GEM
        if data is not None:
            self.file = tables.openFile(fileName, mode = "w",
                                        title = name,
                                        filters = filters)

            group = self.file.createGroup("/", "gem")
            # save raw version in case it's needed for algorithm enhancements
            self.file.createArray(group, "raw", data)
            self.data = packData(data)

            createBiclusters = True
        else:
            self.file = tables.openFile(fileName, mode = "r+",
                                        filters = filters)

            group = self.file.getNode("/", "gem")
            raw = self.file.getNode(group, "raw")
            self.data = packData(raw[:])

            createBiclusters = False

        self.maxConditions = self.data.shape[1]
        self.maxGenes = self.data.shape[0]

        self.biclusters = Biclustering.Bicluster.Group(self.file, "/",
                                                       self.maxConditions,
                                                       self.maxGenes,
                                                       createBiclusters,
                                                       minGenes)

    def splitSubset(self, conditions):
        """Identifies all biclusters with a given subset of 2 conditions

        @param conditions subset of conditions in matrix to search for biclusters
        @return number of valid biclusters found
        """

        if conditions.size != 2:
            raise ValueError("conditions subset can only have 2 conditions for split")

        increasing = numpy.where(self.data[:, conditions[0]] < self.data[:, conditions[1]])
        increasingGenes = Biclustering.BitSet.BitSet(self.data.shape[0], increasing)

        count = 0
        # increasing set
        increasingConditions = Biclustering.Bit.OrderedBitSet(conditions, self.data.shape[1])
        if self.biclusters.pool(increasingConditions, increasingGenes):
            count += 1

        # decreasing set

        decreasingConditions = increasingConditions.reverse()
        if self.biclusters.pool(decreasingConditions, ~increasingGenes):
            count += 1

        return count

    def splitBiclusters(self):
        """Finds all biclusters with 2 conditions"""

        combinations = Biclustering.Combinatorics.xcombinations(self.maxConditions, 2)

        progressBar = \
            Biclustering.Timing.ProgressBar(combinations.len(),
                                                "Splitting")

        count = 0
        for conditions in combinations:
            progressBar.update()

            count += self.splitSubset(conditions)

        progressBar.finish()
        self.file.flush()

        return count

    def indexBiclusters(self, width):
        """Indexes all biclusters

        Indexes are used to speed up chain*() methods
        @param width width of biclusters to index.  chain*(width) cannot be
                     called before calling indexBiclusters(width)
        """
        self.biclusters.index(width)

    def chainBiclusters(self, tailWidth):
        """Chains biclusters into larger biclusters

        Chained biclusters are formed by chaining one bicluster of tailWidth
        with a bicluster of width 2.
        @param tailWidth number of conditions in first array of biclusters
        @return number of biclusters found
        """

        title = "(%d %d) => (%d)" % (2, tailWidth,
                                     tailWidth + 1)
        progressBar = \
            Biclustering.Timing.ProgressBar(self.maxConditions, title)

        count = 0
        for link in xrange(self.maxConditions):
            progressBar.update()

            count += self.biclusters.chain(tailWidth, link)

        progressBar.finish()
        self.file.flush()

        return count

    def chainBiclustersPreCrest(self, headWidth, doubling = False):
        """Chains biclusters into larger biclusters

        Chained biclusters are formed by chaining one bicluster of headWidth
        with a bicluster of width 2.
        @param headWidth number of conditions in first array of biclusters
        @param doubling
        @return number of biclusters found
        """

        if doubling:
            tailWidth = headWidth
        else:
            tailWidth = 2

        title = "(%d %d) => (%d)" % (headWidth, tailWidth,
                                     headWidth + tailWidth - 1)
        progressBar = \
            Biclustering.Timing.ProgressBar(self.maxConditions, title)

        count = 0
        for link in xrange(self.maxConditions):
            progressBar.update()

            count += self.biclusters.chainPreCrest(headWidth, link, doubling)

        progressBar.finish()
        self.file.flush()

        return count

    def pruneBiclusters(self, width):
        """Prunes biclusters of width conditions that are nested

        @param width number of conditions in biclusters to prune
        """

        indexes = xrange(self.biclusters.depth(width))

        title = "(%d not in %d)" % (width, width + 1)
        progressBar = Biclustering.Timing.ProgressBar(len(indexes), title)

        for index in indexes:
            progressBar.update()

            self.biclusters.isNested(width, index)

        progressBar.finish()
        self.file.flush()

    def biclusterCount(self, includeNested=True):
        """Returns total number of biclusters

        @param includeNested True to include nested biclusters.
                             False otherwise.
        @return total number of biclusters
        """

        count = 0
        for i in xrange(2, self.maxConditions + 1):
            count += self.biclusters.depth(i, includeNested)

        return count

    def allBiclusters(self):
        """Finds all biclusters in the GEM"""

        totalStartTime = time.time()

        # seed clusters need 2 conditions so biclusters
        # can be grown by 1 condition if needed
        # 0 biclusters is unlikely, but may occur to too high of minGenes
        if self.splitBiclusters() == 0:
            logging.error("No seed biclusters found.  "
                          "Perhaps minimum genes (%d) is too high?",
                          self.minGenes)

        logging.info("Chaining")

        # search for valid bicluster with most conditions
        maxConditions = self.maxConditions
        # only look for holes above minimum valid bicluster conditions and
        # smaller than the known maxConditions that may still yield genes
        progressBar = \
            Biclustering.Timing.ProgressBar(maxConditions - 2, "Chaining")
        for i in xrange(2, maxConditions + 1):
            progressBar.update()

            self.indexBiclusters(i)
            if self.chainBiclusters(i) == 0:
                maxConditions = i
                break

        progressBar.finish()

        logging.info("Chains constructed. Biclusters: %d Max Conditions: %d",
                     self.biclusterCount(), maxConditions)
        logging.info("Pruning nested Biclusters")

        progressBar = \
            Biclustering.Timing.ProgressBar(maxConditions - 2, "Pruning")

        for i in xrange(2, maxConditions):
            progressBar.update()

            self.pruneBiclusters(i)

        progressBar.finish()

        logging.info("Nested Biclusters pruned.  Biclusters: %s ",
                     self.biclusterCount(False))
        logging.info("Total Time: %s",
                    datetime.timedelta(seconds = time.time() - totalStartTime))

    def stats(self):
        """Prints stats on GEM

        @param includeNested True to count nested (pruned) bicluster.  False to
               ignore them
        """

        lines = list()
        for i in xrange(2, self.maxConditions + 1):
            if i != 2:
                lines.append("\n")
            lines.append("(%d): %d T %d NSUB" %
                         (i, self.biclusters.depth(i),
                          self.biclusters.depth(i, False)))

        lines.append("\n")
        lines.append("Total: %d NSUB: %d" %
                      (self.biclusterCount(), self.biclusterCount(False)))

        return ''.join(lines)

    def annotate(self, annotation, axis="genes"):
        """
        """
        pass

class Annotation(dict):

    def __init__(self, universe=None, file=None, where=None):
        """

        @param universe number of elements being annotated
        @param file file to load Annotation from
        @param where Node in file annotation is on
        """
        super(Annotation, self).__init__()

        if file is not None and where is not None:
            pass
        elif universe is not None:
            self.universe = universe
        else:
            raise ValueError("Could not load or create Annotation with given arguments")

    def __setitem__(self, key, value):
        if not isinstance(value, Biclustering.BitSet.BitSet):
            value = Biclustering.BitSet.BitSet(self.universe, value)

        super(Annotation, self).__setitem__(key, value)

    def categories(self):
        return self.keys()

    def saveTo(self, file, where, name):
        """Creates SetArray which is a pickled version of this annotation
        """

        atom = tables.StringAtom(flavor = 'numpy')
        node = file.createVLArray(where, name, atom)


# 왜 4로하면 안되냐면, 최대공약수가 100이 아니거든

M,N = map(int,input().split(" "))
bd = []
for i in range(M) :
    bd.append(int(input()))

bd.sort(reverse=True)
result = 0

for i in bd :
    if(N >= i) :
        result += int(N/i)
        N  = N%i
    if(N == 0) :
        break

print(result)