问:
Finding specific elements from an alphanumeric list based on there associated number- python
I have list that contains nested alphanumeric elements. Im looking for a way to find all specific sets in the list that have the same number associated with them. In general the list looks as such [[[a#, b#], [a#, b#]], etc]. The list is as fallows,

```<code>A=[[[a2, b4], [a1, b4]],
   [[a1, b1], [a1, b1]],
   [[a3, b2], [a3, b4]],
   [[a2, b2], [a2, b2]]]
</code>```

I'd like to figure out a way to iterate thru A and find all the sets where the a's and b's in a set are from the same number, like [[ai, bi], [ai, bi]], where the i represent the same number (it can be any number tho, it just has to be the same).
The output would look something like this,

```<code>B=[[[a1, b1], [a1, b1]],
   [[a2, b2], [a2, b2]]
</code>```

So far the code Ive worked out looks like this,

```<code>B=[]
for i in range(len(A)):
    if A[i][0][0]==A[i][1][0]:
        if A[i][0][1]==A[i][1][1]:
            pair=[[A[i][0][0],Ai][0][1]], [A[i][1][0],A[i][1][1]]]
        B.append(pair)
</code>```

But this has its own issues as it doesn't take into account that the number between the a's and the b's also need to be the same (in any one set). I'm wondering how to incorporate that into the code or if theres a simply a better overall approach to this.

Body:
I have list that contains nested alphanumeric elements. Im looking for a way to find all specific sets in the list that have the same number associated with them. In general the list looks as such [[[a#, b#], [a#, b#]], etc]. The list is as fallows,

A=[[[a2, b4], [a1, b4]],
   [[a1, b1], [a1, b1]],
   [[a3, b2], [a3, b4]],
   [[a2, b2], [a2, b2]]]

I'd like to figure out a way to iterate thru A and find all the sets where the a's and b's in a set are from the same number, like [[ai, bi], [ai, bi]], where the i represent the same number (it can be any number tho, it just has to be the same).
The output would look something like this,

B=[[[a1, b1], [a1, b1]],
   [[a2, b2], [a2, b2]]

So far the code Ive worked out looks like this,

B=[]
for i in range(len(A)):
    if A[i][0][0]==A[i][1][0]:
        if A[i][0][1]==A[i][1][1]:
            pair=[[A[i][0][0],Ai][0][1]], [A[i][1][0],A[i][1][1]]]
        B.append(pair)

But this has its own issues as it doesn't take into account that the number between the a's and the b's also need to be the same (in any one set). I'm wondering how to incorporate that into the code or if theres a simply a better overall approach to this.

Body:
Use a simple list comprehension. Iterate through A and check if both elements are same.

In [26]: A=[[['a2', 'b4'], ['a1', 'b4']],
...:    [['a1', 'b1'], ['a1', 'b1']],
...:    [['a3', 'b2'], ['a3', 'b4']],
...:    [['a2', 'b2'], ['a2', 'b2']]]

In [27]: B = [i for i in A if i[0] == i[1]]

In [28]: B
Out[28]: [[['a1', 'b1'], ['a1', 'b1']], [['a2', 'b2'], ['a2', 'b2']]]


来源: stackexchange

问:
Print values from HashMap
Currently, I am trying to write a method to locate the highest value product in my hashmap.

I am looking for a push in the right direction if that is possible. I appreciate any help that might be pointed my way. Thank you.

答:
maxBy returns nullable Map.Entry so you need to handle nullable result. You could for example use safe call with ? following by let as below. </p>

```<code> products.maxBy { it.value.second }?.let {
    val (key, value) = it
    println("The highest priced product is: ")
    println()
    println("Item#    Description      Price")
    println("-----    -------------    -------")
    println("$key ${value.first} ${value.second}")
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Print values from HashMap

Body:
maxBy returns nullable Map.Entry so you need to handle nullable result. You could for example use safe call with ? following by let as below.

 products.maxBy { it.value.second }?.let {
    val (key, value) = it
    println("The highest priced product is: ")
    println()
    println("Item#    Description      Price")
    println("-----    -------------    -------")
    println("$key ${value.first} ${value.second}")
}


问:
Please explain this code
Trying to make sense of the code below, as I want to customise it a bit.
As per the comments, the callback function is passed the last image to load as an argument. Can someone please explain how the callback is passed only to the last image (I understand why, I just don't know how)? From the way I'm reading the code it seems to be passed to all of them.

Cheers.

// $('img.photo',this).imagesLoaded(myFunction)
// execute a callback when all images have loaded.
// needed because .load() doesn't work on cached images

// mit license. paul irish. 2010.
// webkit fix from Oren Solomianik. thx!

// callback function is passed the last image to load
//   as an argument, and the collection as 'this'

$.fn.imagesLoaded = function(callback){
  var elems = this.filter('img'),
      len   = elems.length,
      blank = 'data:image/gif;base64,' +
          'R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';

  elems.bind('load',function(){
      if (--len <= 0 && this.src !== blank){ callback.call(elems,this); }
  }).each(function(){
     // cached images don't fire load sometimes, so we reset src.
     if (this.complete || this.complete === undefined){
        var src = this.src;
        // webkit hack from
        // groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
        // data uri bypasses webkit log warning (thx doug jones)
        this.src = blank;
        this.src = src;
     }
  });

  return this;
};
```

答:
The callback function is only called if len (decremented) is less than or equal to zero.  Since it starts off with the value of the length of the elements (or how many there are), and is decremented when each image is loaded, only the last image will make the expression true.

You can sort of read this part of the code:

```<code>   elems.bind('load',function(){
      if (--len <= 0 && this.src !== blank){ callback.call(elems,this); }
  })
</code>```

as "bind this function to the load method for each element in elems."  So, each element calls the function when it is loaded, so the function () {...} is called.  The first image decrements len and then checks if it is less than or equal to 0, then the next element does the same when its done loading, and so on until the last image decrements len and then checks if it is less than 0.  Since it's the last image, it returns true and if the src is not blank, it runs callback.call().

ContentLicense: CC BY-SA 3.0

Title: Please explain this code

Body:
The callback function is only called if len (decremented) is less than or equal to zero.  Since it starts off with the value of the length of the elements (or how many there are), and is decremented when each image is loaded, only the last image will make the expression true.

You can sort of read this part of the code:

   elems.bind('load',function(){
      if (--len <= 0 && this.src !== blank){ callback.call(elems,this); }
  })

as "bind this function to the load method for each element in elems."  So, each element calls the function when it is loaded, so the function () {...} is called.  The first image decrements len and then checks if it is less than or equal to 0, then the next element does the same when its done loading, and so on until the last image decrements len and then checks if it is less than 0.  Since it's the last image, it returns true and if the src is not blank, it runs callback.call().


问:
How to add a placeholder to my Google Custom Searchbox?
I tried with another codes I found here but nothing worked.

This is my searchbox regular code:

```<code><script async="" src="https://cse.google.com/cse.js?cx=008573911755377469615:xhdlwjbvh7o"></script>
</code>```

答:
Just set the attribute when window load.</p>

```<code>window.onload = myCustomPlaceholder;

function myCustomPlaceholder() {
    document.getElementById("gsc-i-id1").setAttribute("placeholder", "my custom search placeholder")
}
</code>```

Body:
Just set the attribute when window load.

window.onload = myCustomPlaceholder;

function myCustomPlaceholder() {
    document.getElementById("gsc-i-id1").setAttribute("placeholder", "my custom search placeholder")
}


问:
Using C++ objects from C
I would like to use C/C++ mixed code. I also need access to C++ object member variables from C code.

It works (at least in gcc), that I pass pointer to the object and handle it as a struct.

From C++:

```<code>class MyData {
  ...
};
</code>```

From C:

```<code>struct MyData {
  ...
};
</code>```

(Of course, I do not duplicate code in the final header file)

1, I am not sure that this would work using any of the compilers. Is there any reasons why I should not rely on this?

2, If MyData class has virtual member functions, this would not work, but a pointer to the first member variable could solve the problem. Is this safe, or may I get into trouble with this?

答:
The first answer already suggested to define a "glue type" that is legal in both C and C++. It is, however, important to emphasize that it is necessary but not sufficient. A more precise answer would be that you need to define the same type that has the same binary layout.

To clarify:

```<code>struct my_struct {
    int a;
    bool b;
};
</code>```

can have wildly different binary representations depending on the alignment of my_struct (what's the sizeof of my_struct when the alignment 16 bits and 32 bits?). In this case not only the members are important, but what's between the members, i.e., the padding bits.

This is why the pointer to the first member will simply not be enough to have portable code.

The most portable approach would be to define a higher level API, to distill the essence of what you are doing and have functions that can be parameterized via trivial types, i.e., ints, chars, floats.

Title: Using C++ objects from C

Body:
I would like to use C/C++ mixed code. I also need access to C++ object member variables from C code.

It works (at least in gcc), that I pass pointer to the object and handle it as a struct.

From C++:

class MyData {
  ...
};

From C:

struct MyData {
  ...
};

(Of course, I do not duplicate code in the final header file)

1, I am not sure that this would work using any of the compilers. Is there any reasons why I should not rely on this?

2, If MyData class has virtual member functions, this would not work, but a pointer to the first member variable could solve the problem. Is this safe, or may I get into trouble with this?

Body:
The first answer already suggested to define a "glue type" that is legal in both C and C++. It is, however, important to emphasize that it is necessary but not sufficient. A more precise answer would be that you need to define the same type that has the same binary layout.

To clarify:

struct my_struct {
    int a;
    bool b;
};

can have wildly different binary representations depending on the alignment of my_struct (what's the sizeof of my_struct when the alignment 16 bits and 32 bits?). In this case not only the members are important, but what's between the members, i.e., the padding bits.

This is why the pointer to the first member will simply not be enough to have portable code.

The most portable approach would be to define a higher level API, to distill the essence of what you are doing and have functions that can be parameterized via trivial types, i.e., ints, chars, floats.


问:
Breakpoints not hit when using docker-compose for asp.net core project
I am trying to wrap my head around on how to debug an application, when I am using docker. I found this documentation, which does not yield the expected results: https://code.visualstudio.com/docs/containers/docker-compose

What I did was the following:

dotnet new mvc

Inside VS Code ctrl + shift + p --> Add Docker files to Workspace

modify docker-compose.debug.yml to support SSL

```<code>metricdemo:
  image: metricdemo
  build:
    context: .
    dockerfile: Dockerfile
  ports:
    - 80
    - 5000:443
  environment:
    - ASPNETCORE_ENVIRONMENT=Development
    - ASPNETCORE_URLS=http://+:80;https://+:443
    - ASPNETCORE_Kestrel__Certificates__Default__Password=password
    - ASPNETCORE_Kestrel__Certificates__Default__Path=/root/.dotnet/https/aspnetcore-cert.pfx
  volumes:
    - C:\cert\:/root/.dotnet/https
    - ~/.vsdbg:/remote_debugger:rw
</code>```

the next step was to create the launch configuration, so the debugger can get attached:

```<code>{
    "name": "Docker .NET Core Attach (Preview)",
    "type": "docker",
    "request": "attach",
    "platform": "netCore",
    "netCore": {
        "debuggerPath": "/remote_debugger/vsdbg"
    },
    "sourceFileMap": {
        "/src": "${workspaceFolder}"
    }
}
</code>```

I've tried both combinations with and without the debuggerPath set.

After this I fire up docker-compose using

```<code>docker-compose -f "docker-compose.debug.yml" up --build
</code>```

and then I attach the debugger.

Update The reason debugging does not work is actually the Dockerfile itself:

```<code>FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /src
COPY ["MetricDemo.csproj", "./"]
RUN dotnet restore "./MetricDemo.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "MetricDemo.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "MetricDemo.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "MetricDemo.dll"]
</code>```

Both layers, build and publish are built using Release mode. Setting this to Debug, does the trick. This now begs the question: how can I control this variable from docker-compose, so that I can build debug mode from docker-compose.debug.yml and a release configuration from docker-compose.yml? I don't really want to have 2 docker files for a single project.

答:
I've solved my issue by replacing the hardcoded "Release" configuration, which vs code adds, by an ARG:

```<code>FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /src
COPY ["MetricDemo.csproj", "./"]
RUN dotnet restore "./MetricDemo.csproj"
COPY . .
WORKDIR "/src/."
ARG Mode=Debug
RUN echo "$Mode"
RUN dotnet build "MetricDemo.csproj" -c $Mode -o /app/build

FROM build AS publish
ARG Mode=Debug
RUN echo "$Mode"
RUN dotnet publish "MetricDemo.csproj" -c $Mode -o /app/publish
</code>```

I am setting the default value to Debug. This will now enable me to simply override this in my docker-compose.yml, when it is supposed to be published:

```<code>services:
  metricdemo:
    image: metricdemo
    build:
      context: .
      dockerfile: Dockerfile
      args:
        - Mode=Release
</code>```

Body:
I am trying to wrap my head around on how to debug an application, when I am using docker. I found this documentation, which does not yield the expected results: https://code.visualstudio.com/docs/containers/docker-compose

What I did was the following:

dotnet new mvc

Inside VS Code ctrl + shift + p --> Add Docker files to Workspace

modify docker-compose.debug.yml to support SSL

metricdemo:
  image: metricdemo
  build:
    context: .
    dockerfile: Dockerfile
  ports:
    - 80
    - 5000:443
  environment:
    - ASPNETCORE_ENVIRONMENT=Development
    - ASPNETCORE_URLS=http://+:80;https://+:443
    - ASPNETCORE_Kestrel__Certificates__Default__Password=password
    - ASPNETCORE_Kestrel__Certificates__Default__Path=/root/.dotnet/https/aspnetcore-cert.pfx
  volumes:
    - C:\cert\:/root/.dotnet/https
    - ~/.vsdbg:/remote_debugger:rw

the next step was to create the launch configuration, so the debugger can get attached:

{
    "name": "Docker .NET Core Attach (Preview)",
    "type": "docker",
    "request": "attach",
    "platform": "netCore",
    "netCore": {
        "debuggerPath": "/remote_debugger/vsdbg"
    },
    "sourceFileMap": {
        "/src": "${workspaceFolder}"
    }
}

I've tried both combinations with and without the debuggerPath set.

After this I fire up docker-compose using

docker-compose -f "docker-compose.debug.yml" up --build

and then I attach the debugger.

Update The reason debugging does not work is actually the Dockerfile itself:

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /src
COPY ["MetricDemo.csproj", "./"]
RUN dotnet restore "./MetricDemo.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "MetricDemo.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "MetricDemo.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "MetricDemo.dll"]

Both layers, build and publish are built using Release mode. Setting this to Debug, does the trick. This now begs the question: how can I control this variable from docker-compose, so that I can build debug mode from docker-compose.debug.yml and a release configuration from docker-compose.yml? I don't really want to have 2 docker files for a single project.

Body:
I've solved my issue by replacing the hardcoded "Release" configuration, which vs code adds, by an ARG:

FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /src
COPY ["MetricDemo.csproj", "./"]
RUN dotnet restore "./MetricDemo.csproj"
COPY . .
WORKDIR "/src/."
ARG Mode=Debug
RUN echo "$Mode"
RUN dotnet build "MetricDemo.csproj" -c $Mode -o /app/build

FROM build AS publish
ARG Mode=Debug
RUN echo "$Mode"
RUN dotnet publish "MetricDemo.csproj" -c $Mode -o /app/publish

I am setting the default value to Debug. This will now enable me to simply override this in my docker-compose.yml, when it is supposed to be published:

services:
  metricdemo:
    image: metricdemo
    build:
      context: .
      dockerfile: Dockerfile
      args:
        - Mode=Release


问:
ERROR: Error installing rails zeitwerk requires Ruby version >= 2.4.4
I recently changed my laptop and tried installing rails with

```<code>gem install rails
</code>```

and I got this error

```<code>ERROR:  Error installing rails:
    zeitwerk requires Ruby version >= 2.4.4.
</code>```

I have installed ruby version 2.4.4, 2.5.7, and 2.6.5 and I'm still getting the same error.
Any pointers how to resolve this will be greatly appreciated. thanks

答: In directory wanted use rvm use ruby-2.5.7 command line to force the usage of this specific version of ruby and after gem install rails. Just tryed minutes ago and works fine

Body:
I recently changed my laptop and tried installing rails with

gem install rails

and I got this error

ERROR:  Error installing rails:
    zeitwerk requires Ruby version >= 2.4.4.

I have installed ruby version 2.4.4, 2.5.7, and 2.6.5 and I'm still getting the same error.
Any pointers how to resolve this will be greatly appreciated. thanks


问:
Importing from python to html in flask
I am using flask, and I am wondering, how can I get my application variable into my html template without needing to add it when calling the template like in this example:

```<code>render_template('home.html', app=app)
</code>```

Maybe there is a import function I don't know about.

I would like to make it so I can loop through all of my endpoints(app.url_map.iter_rules()) and compare them with the current endpoint( request.endpoint) . My current main problem is getting all of the endpoints into my html file.

My current way of achieving my navigation bar is this:

```<code><header>
   <div class="head" align="center">
       {% if request.endpoint!='users.login' and current_user.is_authenticated!=true %}
           <a  href="{{ url_for('users.login') }}">
               <button class="tablecontent">Login</button>
           </a>
       {% endif %}
       {% if request.endpoint!='users.register' %}
           <a  href="{{ url_for('users.register') }}">
               <button class="tablecontent">Register</button>
           </a>
       {% endif %}
       {% if request.endpoint!='core.home_page' %}
           <a  href="{{ url_for('core.home_page') }}">
               <button class="tablecontent">Home</button>
           </a>
       {% endif %}
       {% if current_user.is_authenticated %}
           {% if request.endpoint!='users.logout' %}
               <a  href="{{ url_for('users.logout') }}">
                   <button class="tablecontent">Logout</button>
               </a>
           {% endif %}
       {% endif %}
       {% if current_user.is_authenticated %}
           {% if request.endpoint!='products.new_product' %}
               <a  href="{{ url_for('products.add_product') }}">
                   <button class="tablecontent">Add Product</button>
               </a>
           {% endif %}
       {% endif %}
   </div>
</header>
</code>```

The import error when I try to use the sitemap from the answer:

```<code>  File "C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\application.py", line 20, in register_applications
    from database_website.applications.core.urls import blueprint as core_blueprint
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\applications\core\urls.py", line 3, in <module>
    from database_website.applications.core import views
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\applications\core\views.py", line 7, in <module>
    from database_website.properties import sitemap
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\properties.py", line 4, in <module>
    from database_website.application import application
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\application.py", line 39, in <module>
    application = Application.create()
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\application.py", line 35, in create
    instance.register_applications()
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\application.py", line 20, in register_applications
    from database_website.applications.core.urls import blueprint as core_blueprint
ImportError: cannot import name 'blueprint' from 'database_website.applications.core.urls' (C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\applications\core\urls.py)
</code>```

My view file:

```<code>from flask import Flask, render_template, url_for, flash, redirect, request
from flask.views import MethodView

from database_website.applications.views import FormViewMixin
from database_website.applications.products.models import Product
from database_website.applications.core import forms
from database_website.application import application

def has_no_empty_params(rule):
    defaults = rule.defaults if rule.defaults is not None else ()
    arguments = rule.arguments if rule.arguments is not None else ()
    return len(defaults) >= len(arguments)

def sitemap():
    links = []
    for rule in application.url_map.iter_rules():
        # Filter out rules we can't navigate to in a browser
        # and rules that require parameters
        if "GET" in rule.methods and has_no_empty_params(rule):
            url = url_for(rule.endpoint, **(rule.defaults or {}))
            links.append((url, rule.endpoint))
    return links

class HomePageView(MethodView, FormViewMixin):

    def get(self):
        form = forms.ProductSearchForm()
        products = Product.query.all()
        return render_template('core/home.html', title='Home',  products=products, form=form)

    def post(self):

        product_search = request.form.get('search_name')

        return redirect(url_for('products.search_product', search_name=product_search))
</code>```

This is when it has sitemap hardoced, it still shows the exact same error because at the time, when the application object gets imported it does not exist yet. I can show the way I initialize my app.

答:
Hopefully this will help :

```<code>def has_no_empty_params(rule):
    defaults = rule.defaults if rule.defaults is not None else ()
    arguments = rule.arguments if rule.arguments is not None else ()
    return len(defaults) >= len(arguments)

def sitemap():
    links = []
    for rule in app.url_map.iter_rules():
        # Filter out rules we can't navigate to in a browser
        # and rules that require parameters
        if "GET" in rule.methods and has_no_empty_params(rule):
            url = url_for(rule.endpoint, **(rule.defaults or {}))
            links.append((url, rule.endpoint))
    return links
</code>```

```<code>render_template('home.html', links=sitemap())
</code>```

```<code>{% for url, endpoint in links %}
    <a href="{{ url }}">{{ endpoint }}</a>
{% endfor %}
</code>```

Title: Importing from python to html in flask

Body:
I am using flask, and I am wondering, how can I get my application variable into my html template without needing to add it when calling the template like in this example:

render_template('home.html', app=app)

Maybe there is a import function I don't know about.

I would like to make it so I can loop through all of my endpoints(app.url_map.iter_rules()) and compare them with the current endpoint( request.endpoint) . My current main problem is getting all of the endpoints into my html file.

My current way of achieving my navigation bar is this:

       {% if request.endpoint!='users.login' and current_user.is_authenticated!=true %}

               <button class="tablecontent">Login</button>

       {% endif %}
       {% if request.endpoint!='users.register' %}

               <button class="tablecontent">Register</button>

       {% endif %}
       {% if request.endpoint!='core.home_page' %}

               <button class="tablecontent">Home</button>

       {% endif %}
       {% if current_user.is_authenticated %}
           {% if request.endpoint!='users.logout' %}

                   <button class="tablecontent">Logout</button>

           {% endif %}
       {% endif %}
       {% if current_user.is_authenticated %}
           {% if request.endpoint!='products.new_product' %}

                   <button class="tablecontent">Add Product</button>

           {% endif %}
       {% endif %}

The import error when I try to use the sitemap from the answer:

  File "C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\application.py", line 20, in register_applications
    from database_website.applications.core.urls import blueprint as core_blueprint
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\applications\core\urls.py", line 3, in <module>
    from database_website.applications.core import views
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\applications\core\views.py", line 7, in <module>
    from database_website.properties import sitemap
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\properties.py", line 4, in <module>
    from database_website.application import application
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\application.py", line 39, in <module>
    application = Application.create()
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\application.py", line 35, in create
    instance.register_applications()
  File "C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\application.py", line 20, in register_applications
    from database_website.applications.core.urls import blueprint as core_blueprint
ImportError: cannot import name 'blueprint' from 'database_website.applications.core.urls' (C:\Users\ulman\PycharmProjects\database_website_optimised\source\database_website\applications\core\urls.py)

My view file:

from flask import Flask, render_template, url_for, flash, redirect, request
from flask.views import MethodView

from database_website.applications.views import FormViewMixin
from database_website.applications.products.models import Product
from database_website.applications.core import forms
from database_website.application import application

def has_no_empty_params(rule):
    defaults = rule.defaults if rule.defaults is not None else ()
    arguments = rule.arguments if rule.arguments is not None else ()
    return len(defaults) >= len(arguments)

def sitemap():
    links = []
    for rule in application.url_map.iter_rules():
        # Filter out rules we can't navigate to in a browser
        # and rules that require parameters
        if "GET" in rule.methods and has_no_empty_params(rule):
            url = url_for(rule.endpoint, **(rule.defaults or {}))
            links.append((url, rule.endpoint))
    return links

class HomePageView(MethodView, FormViewMixin):

    def get(self):
        form = forms.ProductSearchForm()
        products = Product.query.all()
        return render_template('core/home.html', title='Home',  products=products, form=form)

    def post(self):

        product_search = request.form.get('search_name')

        return redirect(url_for('products.search_product', search_name=product_search))

This is when it has sitemap hardoced, it still shows the exact same error because at the time, when the application object gets imported it does not exist yet. I can show the way I initialize my app.

Body:
Hopefully this will help :

def has_no_empty_params(rule):
    defaults = rule.defaults if rule.defaults is not None else ()
    arguments = rule.arguments if rule.arguments is not None else ()
    return len(defaults) >= len(arguments)

def sitemap():
    links = []
    for rule in app.url_map.iter_rules():
        # Filter out rules we can't navigate to in a browser
        # and rules that require parameters
        if "GET" in rule.methods and has_no_empty_params(rule):
            url = url_for(rule.endpoint, **(rule.defaults or {}))
            links.append((url, rule.endpoint))
    return links

render_template('home.html', links=sitemap())

{% for url, endpoint in links %}
    <a href="{{ url }}">{{ endpoint }}</a>
{% endfor %}


答:
The following line does the trick

```<code>if (--len <= 0 && this.src !== blank){ callback.call(elems,this); }
</code>```

Basically, the load event is attached to each img tag, and if load is fired the len variable will be decremented and if len <= 0 the callback will be executed. The load event itself will be triggered by the each() function that replaces the images.

Title: Please explain this code

Body:
Trying to make sense of the code below, as I want to customise it a bit.
As per the comments, the callback function is passed the last image to load as an argument. Can someone please explain how the callback is passed only to the last image (I understand why, I just don't know how)? From the way I'm reading the code it seems to be passed to all of them.

Cheers.

// $('img.photo',this).imagesLoaded(myFunction)
// execute a callback when all images have loaded.
// needed because .load() doesn't work on cached images

// mit license. paul irish. 2010.
// webkit fix from Oren Solomianik. thx!

// callback function is passed the last image to load
//   as an argument, and the collection as 'this'

$.fn.imagesLoaded = function(callback){
  var elems = this.filter('img'),
      len   = elems.length,
      blank = 'data:image/gif;base64,' +
          'R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';

  elems.bind('load',function(){
      if (--len <= 0 && this.src !== blank){ callback.call(elems,this); }
  }).each(function(){
     // cached images don't fire load sometimes, so we reset src.
     if (this.complete || this.complete === undefined){
        var src = this.src;
        // webkit hack from
        // groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
        // data uri bypasses webkit log warning (thx doug jones)
        this.src = blank;
        this.src = src;
     }
  });

  return this;
};

Body:
The following line does the trick

if (--len <= 0 && this.src !== blank){ callback.call(elems,this); }

Basically, the load event is attached to each img tag, and if load is fired the len variable will be decremented and if len <= 0 the callback will be executed. The load event itself will be triggered by the each() function that replaces the images.


问:
How do I fix a node server error, npm ERR! code ELIFECYCLE npm ERR! errno 1?

npm ERR! code ELIFECYCLE
  npm ERR! errno 1
  npm ERR! node-express@1.0.0 start: node server
  npm ERR! Exit status 1
  npm ERR!
  npm ERR! Failed at the node-express@1.0.0 start script.
  npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
  npm ERR!     /Users/teevee/.npm/_logs/2020-05-30T18_42_30_526Z-debug.log

I haven't had any issues until I had to add routes for partners and promotions in my project.  I don't know how to debug this type of error in order to make the needed changes. What can possibly be the issue? I'm still learning.  Here is a link: https://github.com/TanishaV842/node-express/tree/master/routes

答:
One of the issues you have is that it looks like you're including code for your routers in multiple places:

// server.js

app.use("/campsites", campsiteRouter);
app.use("/partners", partnerRouter);
app.use("/promotions", promotionRouter);

campsiteRouter.route("/campsites").all(...);
partnerRouter.route("/partners").all(...);
promotionsRouter.route("/promotions").all(...);
```

<p>There's no need to do that, just do <code>app.use("/campsites", campsiteRouter);</code> and get rid of the router code inside <code>server.js</code>.</p>

<hr>

<p>Second, the code inside of your <code>routers</code> is incorrect in two ways:</p>

<pre class="lang-js prettyprint-override"><code>// these are two different routes, so create a separate
// route for `/campsites/:campsiteId`,
// additionally, you don't want to do `/campsites/:campsiteId`
// because you specified the `/campsite` route/portion inside of
// your `server.js` file when you did
// `app.use("/campsites", campsiteRouter)`, so only use `/:campsiteId`

// WRONG
campsiteRouter
  .route("/campsites")
  .all(...)
  .get("/campsites/:campsiteId", ...)

// CORRECT
campsiteRouter
  .route("/:campsiteId")
  .all(...)
  .get((req, res) => {
    console.log(req.params.campsiteId);
  })
  .post(...);
</code>```

Here's your fixed code:

GitHub

Hope this helps.

Body:
One of the issues you have is that it looks like you're including code for your routers in multiple places:

// server.js

app.use("/campsites", campsiteRouter);
app.use("/partners", partnerRouter);
app.use("/promotions", promotionRouter);

campsiteRouter.route("/campsites").all(...);
partnerRouter.route("/partners").all(...);
promotionsRouter.route("/promotions").all(...);

There's no need to do that, just do app.use("/campsites", campsiteRouter); and get rid of the router code inside server.js.

Second, the code inside of your routers is incorrect in two ways:

// these are two different routes, so create a separate
// route for `/campsites/:campsiteId`,
// additionally, you don't want to do `/campsites/:campsiteId`
// because you specified the `/campsite` route/portion inside of
// your `server.js` file when you did
// `app.use("/campsites", campsiteRouter)`, so only use `/:campsiteId`

// WRONG
campsiteRouter
  .route("/campsites")
  .all(...)
  .get("/campsites/:campsiteId", ...)

// CORRECT
campsiteRouter
  .route("/:campsiteId")
  .all(...)
  .get((req, res) => {
    console.log(req.params.campsiteId);
  })
  .post(...);

Here's your fixed code:

GitHub

Hope this helps.


问:
Does every function get its own stack in c?
I recently learned about stacks, so I was experimenting to see what the stack size is and what happens when it overflows. I found out that on Unix the default stack size is 8 MiB, and that supports my findings since I cannot declare a string having size greater than or equal to 8 MiB in my main function. However, when I declare a variable in main() it affects other functions. For example:

```<code>#include <stdio.h>

void foo(void)
{
    long int size = 1024*1024*2;
    char str[size];
    str[size - 1] = 'a';
    printf("%c\n", str[size - 1]);
}

int main(int argc, char** argv)
{
    long int size = 1024*1024*6;
    char str[size];
    str[size - 1] = 'a';
    printf("%c\n", str[size - 1]);
    foo();
    return 0;
}
</code>```

This code results in segmentation fault but if I make the string size 5 MiB in main() then there is no segmentation fault. Does that mean my C program cannot allocate more than 8 MiB of RAM for local variables (of all functions)? If so, what IS the point of stacks?

答:
C language standard does not know anything about the stack. How function are called, how parameter are passed and where automatic storage objects are stored is up to implementation.

Most of the implementation will actually have only one stack but I will give you some very common exeptions.

RTOSes. Many RTOS-es implement tasks as normal functions. Functions which are separate tasks will have separate stacks.

Many multitasking libraries (like pthread) will give threads (which are functions) separate stacks.

Many hardware designs have more than one stack - for example very popular ARM Cortex uCs - having two separate hardware stacks.

etc etc.

Body:
I recently learned about stacks, so I was experimenting to see what the stack size is and what happens when it overflows. I found out that on Unix the default stack size is 8 MiB, and that supports my findings since I cannot declare a string having size greater than or equal to 8 MiB in my main function. However, when I declare a variable in main() it affects other functions. For example:

#include <stdio.h>

void foo(void)
{
    long int size = 1024*1024*2;
    char str[size];
    str[size - 1] = 'a';
    printf("%c\n", str[size - 1]);
}

int main(int argc, char** argv)
{
    long int size = 1024*1024*6;
    char str[size];
    str[size - 1] = 'a';
    printf("%c\n", str[size - 1]);
    foo();
    return 0;
}

This code results in segmentation fault but if I make the string size 5 MiB in main() then there is no segmentation fault. Does that mean my C program cannot allocate more than 8 MiB of RAM for local variables (of all functions)? If so, what IS the point of stacks?


问:
Only charge Stripe subscription in certain months of the year
I am looking to create a Stripe subscription in line with UK school term times. This means I do not want to charge the user in certain months, such as April or December, but I do want to charge them for the rest of the year.

For example:

```<code>September - charge £10
October - charge £10
November - charge £10
December - charge nothing
January - charge £10
</code>```

etc etc

What would be the best way to implement this?

I have read about subscription phases, and also usage based pricing. Im not sure which one would work best in this scenario.

答: If your Subscription doesn't need to renew after the first year, the best option is to use Subscription Schedules. The idea here is to create a Subscription Schedule and define its phases so that in some cases you charge for the Subscription and in others you don't. When you charge, you define a phase with a Price for the monthly fee. When you don't, you can either change the quantity to 0 or move them to a Price with a £0 amount instead to reflect this.

Body:
I am looking to create a Stripe subscription in line with UK school term times. This means I do not want to charge the user in certain months, such as April or December, but I do want to charge them for the rest of the year.

For example:

September - charge £10
October - charge £10
November - charge £10
December - charge nothing
January - charge £10

etc etc

What would be the best way to implement this?

I have read about subscription phases, and also usage based pricing. Im not sure which one would work best in this scenario.


问:
How to Parameterize beforeEach() in JUnit 5?
I am using JUnit 5 as my Test Runner.

In the setup method, I have hardcoded 3 params (platformName, platformVersion, and deviceName). I have a test method that should test on various combinations... This means, when running my testLogin() test, it should run on multiple platform names, versions, device names...

So, I tried as below...

@BeforeEach
@CsvSource({"IOS,13.0,iPhone X Simulator", "IOS,13.2,iPhone Simulator", "IOS,13.3,iPhone XS Simulator"})
void setUp(String platformName, String platformVersion, String deviceName) throws MalformedURLException {
    ....
    capabilities.setCapability("platformName", platformName);
    capabilities.setCapability("platformVersion", platformVersion);
    capabilities.setCapability("deviceName", deviceName);
    capabilities.setCapability("methodName", testInfo.getDisplayName());
}
```

<p>My question is, how can <code>beforeEach()</code> method can be parameterized? Also, I want to get the test method name... So, if I specify the parameters, then where should I specify TestInfo param. </p>

<p>Please help me. I have also seen the below question...</p>

<p>Parameterized beforeEach/beforeAll in JUnit 5</p>

<p>========</p>

<pre class="lang-java prettyprint-override"><code>public class TestBase {

    @BeforeEach
    void setUp(TestInfo testInfo) throws MalformedURLException {
        MutableCapabilities capabilities = new MutableCapabilities();
        capabilities.setCapability("platformName", "iOS");
        capabilities.setCapability("platformVersion", "13.2");
        capabilities.setCapability("deviceName", "iPhone Simulator");
        capabilities.setCapability("name", testInfo.getDisplayName());
        capabilities.setCapability("app", “/home/my-user/testapp.zip");

        driver = new IOSDriver(
                new URL("https://192.168.1.4:5566/wd/hub"),
                capabilities
        );
    }
}
</code>```

public class LoginTest extends TestBase {

    @Test
    public void testLogin() {
        driver.findElement(By.id("user-name")).sendKeys(“myuser);
        driver.findElement(By.id("password")).sendKeys(“mypassword);
        driver.findElement(By.id(“login_btn”)).click();
        assertTrue(true);
    }
}
```

答:
You can't parameterize @BeforEach method. JUnit5 supports only parameterized tests (test methods).

Parameterized tests are declared just like regular @Test methods but use the @ParameterizedTest annotation instead. In addition, you must declare at least one source (e.g. @CsvSource, @ValueSource, etc.)

For example:

    @ParameterizedTest
    @CsvSource({
        "apple,         1",
        "banana,        2",
        "'lemon, lime', 0xF1"
    })
    void testWithCsvSource(String fruit, int rank) {
        assertNotNull(fruit);
        assertNotEquals(0, rank);
    }
```

Body:
I am using JUnit 5 as my Test Runner.

In the setup method, I have hardcoded 3 params (platformName, platformVersion, and deviceName). I have a test method that should test on various combinations... This means, when running my testLogin() test, it should run on multiple platform names, versions, device names...

So, I tried as below...

@BeforeEach
@CsvSource({"IOS,13.0,iPhone X Simulator", "IOS,13.2,iPhone Simulator", "IOS,13.3,iPhone XS Simulator"})
void setUp(String platformName, String platformVersion, String deviceName) throws MalformedURLException {
    ....
    capabilities.setCapability("platformName", platformName);
    capabilities.setCapability("platformVersion", platformVersion);
    capabilities.setCapability("deviceName", deviceName);
    capabilities.setCapability("methodName", testInfo.getDisplayName());
}

My question is, how can beforeEach() method can be parameterized? Also, I want to get the test method name... So, if I specify the parameters, then where should I specify TestInfo param.

Please help me. I have also seen the below question...

Parameterized beforeEach/beforeAll in JUnit 5

========

public class TestBase {

    @BeforeEach
    void setUp(TestInfo testInfo) throws MalformedURLException {
        MutableCapabilities capabilities = new MutableCapabilities();
        capabilities.setCapability("platformName", "iOS");
        capabilities.setCapability("platformVersion", "13.2");
        capabilities.setCapability("deviceName", "iPhone Simulator");
        capabilities.setCapability("name", testInfo.getDisplayName());
        capabilities.setCapability("app", “/home/my-user/testapp.zip");

        driver = new IOSDriver(
                new URL("https://192.168.1.4:5566/wd/hub"),
                capabilities
        );
    }
}

public class LoginTest extends TestBase {

    @Test
    public void testLogin() {
        driver.findElement(By.id("user-name")).sendKeys(“myuser);
        driver.findElement(By.id("password")).sendKeys(“mypassword);
        driver.findElement(By.id(“login_btn”)).click();
        assertTrue(true);
    }
}


问:
shiny DT::renderdatatable
suppose the columns of a data table  are:  unique-ID, name, salary, position.
I display the table in a shiny application using DT::renderdatatable (DT::dataTableOutput).
I would like to click on a row of the output to display other data of the person belonging to the ID in another output.
what is the solution?
in short, how do I extract the unique-ID from a clicked line item?</p>

答:
You can use the _rows_selected extension coming with DT tables. Here's the list of possible arguments. Several live examples are here or here.

This is a simple example of a plot that updates with the lines selected in the table:

```<code>library(shiny)
library(DT)

ui <- fluidPage(
  DT::dataTableOutput("test_table"),
  plotOutput("test_plot")
)

server <- function(input, output, session) {

  output$test_table <- DT::renderDataTable({
    mtcars
  })

  output$test_plot <- renderPlot({
    s <- input$test_table_rows_selected

    if (!is.null(s)) {
      plot(mtcars[s, "disp"])
    }
  })

}

shinyApp(ui, server)
</code>```

Title: shiny DT::renderdatatable

Body:
You can use the _rows_selected extension coming with DT tables. Here's the list of possible arguments. Several live examples are here or here.

This is a simple example of a plot that updates with the lines selected in the table:

library(shiny)
library(DT)

ui <- fluidPage(
  DT::dataTableOutput("test_table"),
  plotOutput("test_plot")
)

server <- function(input, output, session) {

  output$test_table <- DT::renderDataTable({
    mtcars
  })

  output$test_plot <- renderPlot({
    s <- input$test_table_rows_selected

    if (!is.null(s)) {
      plot(mtcars[s, "disp"])
    }
  })

}

shinyApp(ui, server)


问:
Data files with html content
I'm making a nice simple html page using external data... here's the bit that's causing me grief:

{% for section in faq.sections %}

{{ section.heading }}

    {% for question in section.questions %}

            + {{ question.question }}
            - {{ question.question }}

                {{ question.answer }}

    {% endfor %}

{% endfor %}

```

<p>... and the matching <code>faq.json</code> file:</p>

```{
    "sections" : [
      { "heading" : "Section the first",
        "code" : "gn",
        "questions" : [
                {
                    "question": "What do questions need?",
                    "code" : "1",
                    "answer": "An answer"
                },
                {
                    "question": "Is this also a question?",
                    "code" : "2",
                    "answer": "Yes, it is"
                },
                {
                    "question": "Is this junk data?",
                    "code" : "a",
                    "answer": "Yes"
                },
            ]
        },
        {
            "heading": "Another section",
            "code" : "f",
            "questions": [
                {
                    "question": "Can I have html in my answer?",
                    "code" : "2",
                    "answer": "
\n
First, json needs newlines escaped to be newlines
\\n
Eleventy seems to 'sanitize' the string
\\n
"
                },
                {
                    "question": "question b",
                    "code" : "b",
                    "answer": "answer b"
                },
                {
                    "question": "question c",
                    "code" : "or",
                    "answer": "answer c"
                },
            ]
        }
    ]
}
```

<p>.... and the rendered text for the answer in question is:</p>

```

First, json needs newlines escaped to be newlines
\n
Eleventy seems to 'sanitize' the string

```

Do I have any options here? Is there a way to allow [even a subset of] html elements into the page?

(and yes, the CSS does the clever show/hide descriptions using the '+'/'-' symbols - all that side of things works just lovely)

答:
Change {{ question.answer }} to {{ question.answer | safe }}

(see https://www.11ty.dev/docs/layouts/#prevent-double-escaping-in-layouts - it's clear, once you understand what it's saying :) )

Title: Data files with html content

Body:
I'm making a nice simple html page using external data... here's the bit that's causing me grief:

{% for section in faq.sections %}

{{ section.heading }}

    {% for question in section.questions %}

            + {{ question.question }}
            - {{ question.question }}

                {{ question.answer }}

    {% endfor %}

{% endfor %}

... and the matching faq.json file:

{
    "sections" : [
      { "heading" : "Section the first",
        "code" : "gn",
        "questions" : [
                {
                    "question": "What do questions need?",
                    "code" : "1",
                    "answer": "An answer"
                },
                {
                    "question": "Is this also a question?",
                    "code" : "2",
                    "answer": "Yes, it is"
                },
                {
                    "question": "Is this junk data?",
                    "code" : "a",
                    "answer": "Yes"
                },
            ]
        },
        {
            "heading": "Another section",
            "code" : "f",
            "questions": [
                {
                    "question": "Can I have html in my answer?",
                    "code" : "2",
                    "answer": "
\n
First, json needs newlines escaped to be newlines
\\n
Eleventy seems to 'sanitize' the string
\\n
"
                },
                {
                    "question": "question b",
                    "code" : "b",
                    "answer": "answer b"
                },
                {
                    "question": "question c",
                    "code" : "or",
                    "answer": "answer c"
                },
            ]
        }
    ]
}

.... and the rendered text for the answer in question is:

First, json needs newlines escaped to be newlines
\n
Eleventy seems to 'sanitize' the string

Do I have any options here? Is there a way to allow [even a subset of] html elements into the page?

(and yes, the CSS does the clever show/hide descriptions using the '+'/'-' symbols - all that side of things works just lovely)


问:
Property [Photo] does not exist on this collection instance Laravel
i keep getting an error saying "Property [Photo] does not exist on this collection instance" .
I want to show the name of doctor in the view bienvenu.blade.php with using Session .

This is my doctorcontroller.php :

```<code>public function welcomedoctor (Request $request) {
    $rdv=rendezvous::get();
    $medecin_id=$request->session()->get('doc_id');
      return view ('/bienvenu',['med'=>$medecin_id] ,['pat'=>$rdv] );
}
</code>```

This is the bienvenu.blade.php  :

```<code>  ...
      <img src="{{asset ('assets/img/uploads/'.$med->Photo)}}" class="card-img" alt="...">
      <h1 class="card-title"> Bienvenue Dr. {{$med->Nom}} {{$med->Prénom }} </h1>
      <h3 class="card-text"> <i class='bx bx-plus-medical bx-rotate-270' style='color:#11709d'> </i>
      {{$med->Spécialité}}</h3>
  ...
</code>```

This is web.php :

```<code>Route::get('/bienvenu','doctor@welcomedoctor');
</code>```

Doctor Model :

```<code>class doc extends Model
{
    protected  $table = 'doctor' ;
    protected $fillable = ['ID' , 'Photo' , 'demande'];

    public function article()
    {
        return $this->hasMany('App\blog');
    }
}
</code>```

答:
You have to fetch the data of the doctor's ID from the database first. In your example you're sending the ID of the doctor in the variable $med to your view and not the doctor's data itself.

Here an example since I can only guess your model names based on your question history:

```<code>$doctorId = $request->session()->get('doc_id');
$doctor = doc::where('ID', $doctorId)->first();

return view('bienvenu', ['med' => $doctor, 'pat' => $rdv]);
</code>```

Body:
i keep getting an error saying "Property [Photo] does not exist on this collection instance" .
I want to show the name of doctor in the view bienvenu.blade.php with using Session .

This is my doctorcontroller.php :

public function welcomedoctor (Request $request) {
    $rdv=rendezvous::get();
    $medecin_id=$request->session()->get('doc_id');
      return view ('/bienvenu',['med'=>$medecin_id] ,['pat'=>$rdv] );
}

This is the bienvenu.blade.php  :

  ...
      Photo)}}" class="card-img" alt="...">

 Bienvenue Dr. {{$med->Nom}} {{$med->Prénom }}

      {{$med->Spécialité}}

  ...

This is web.php :

Route::get('/bienvenu','doctor@welcomedoctor');

Doctor Model :

class doc extends Model
{
    protected  $table = 'doctor' ;
    protected $fillable = ['ID' , 'Photo' , 'demande'];

    public function article()
    {
        return $this->hasMany('App\blog');
    }
}

Body:
You have to fetch the data of the doctor's ID from the database first. In your example you're sending the ID of the doctor in the variable $med to your view and not the doctor's data itself.

Here an example since I can only guess your model names based on your question history:

$doctorId = $request->session()->get('doc_id');
$doctor = doc::where('ID', $doctorId)->first();

return view('bienvenu', ['med' => $doctor, 'pat' => $rdv]);


问:
select Value in one listbox should affect all other list boxes
i have three list boxes name as state,District, and college. All list boxes contains a value as "All". if i select all in state list box the other list boxes district and college should change as "All". How to make it? i have done changes for two list boxes. i couldn't make for the third one.

```<code>ex :   1. State -
                a) xxxxxxx
                b) yyyyyyy
                c) zzzzzzz
                d) All

          2. District -
               a) aaaaaaa
               b) bbbbbbb
               c) All

          3. College -
               a) aaaaaaa
               b) All
</code>```

see there, if i click "All" in a state list box the District and College Should come as all.
before that i have done if i click "All" in district list box the college sholud change as "All" . How to write code in onChange??

Thanks in advance.

答:
```<code><select id='selection1'>

....options ...

</select>

var select= document.getElementById('selection1');

select.onchange = function () {
    var index = this.selectedIndex;

    if (index == SomeValue ) {
       // do something

    }
}
</code>```

it makes sense to use a switch statement to do different stuff depending on the item selected.

to access the value of the selected item you can use this inside the onchange:

```<code>...
var selectedValue = this.options[index].value; // index is the selectedIndex;
...
</code>```

Body:
i have three list boxes name as state,District, and college. All list boxes contains a value as "All". if i select all in state list box the other list boxes district and college should change as "All". How to make it? i have done changes for two list boxes. i couldn't make for the third one.

ex :   1. State -
                a) xxxxxxx
                b) yyyyyyy
                c) zzzzzzz
                d) All

          2. District -
               a) aaaaaaa
               b) bbbbbbb
               c) All

          3. College -
               a) aaaaaaa
               b) All

see there, if i click "All" in a state list box the District and College Should come as all.
before that i have done if i click "All" in district list box the college sholud change as "All" . How to write code in onChange??

Thanks in advance.

Body:
<select id='selection1'>

....options ...

</select>

var select= document.getElementById('selection1');

select.onchange = function () {
    var index = this.selectedIndex;

    if (index == SomeValue ) {
       // do something

    }
}

it makes sense to use a switch statement to do different stuff depending on the item selected.

to access the value of the selected item you can use this inside the onchange:

...
var selectedValue = this.options[index].value; // index is the selectedIndex;
...


问:
Create pdf file from multiple models in rails app
In my rails app the user inputs a lot of data in different models. The user should have the possibility to create a pdf file from all the data he inputted in the different models. Which ruby gem does provide this functionality and how can it be used? I already looked into Prawn but couldn‘t figure out, if it provides the functionality to create one pdf with data from different models.</p>

答:
Prawn is a library for generating PDFs from any data. How you create the PDF is up to you. And also where your data comes from. So have a look at the documentation from Prawn on how to do things.

You might also want to check out prawn-table since it provides support for adding tables to a PDF document.

I don't think that you will find any pre-built solution for what you want to do.


问:
Chart Data Not Updating for Both Graphs?
I have two bar graphs that get updated with a function which is called whenever I add an input into the dataset.

```<code>function updateChartData(chart, dataLabels, dataNumbers) {
    chart.data.labels = dataLabels;
    chart.data.datasets[0].data = dataNumbers;
    chart.update();
}
</code>```

Even though both graph's labels are being updated, only one is updating the bars. If I keep adding inputs up to 9 values it'll start updating the bars thereon after.

I tried isolating the graph that's having problems by deleting the second chart but didn't fix. I've tried to use the same datasets for both graphs but it ended up doing this weird thing where if i add an input, the first graph would lag the second graph. For example:

*add 1 input to dataset-

first chart shows nothing, second chart shows 1 input

*add 1 more input to dataset-

first chart shows 1 input, second chart shows 2 inputs.

答: So I actually found the solution but couldn't find it before posting this. The problem was that the API I got the data from was giving me strings of numbers with ","s. Coincidentally  the 9th input I was adding in was less than 1,000 so it could turn the number such as 999 into a number.</p>

Body:
I have two bar graphs that get updated with a function which is called whenever I add an input into the dataset.

function updateChartData(chart, dataLabels, dataNumbers) {
    chart.data.labels = dataLabels;
    chart.data.datasets[0].data = dataNumbers;
    chart.update();
}

Even though both graph's labels are being updated, only one is updating the bars. If I keep adding inputs up to 9 values it'll start updating the bars thereon after.

I tried isolating the graph that's having problems by deleting the second chart but didn't fix. I've tried to use the same datasets for both graphs but it ended up doing this weird thing where if i add an input, the first graph would lag the second graph. For example:

*add 1 input to dataset-

first chart shows nothing, second chart shows 1 input

*add 1 more input to dataset-

first chart shows 1 input, second chart shows 2 inputs.


问:
js datetime regex
I am looking for a js regex for datetime.
The regex should allow:
Only valid (optional, date validity will be checked later as well) date formmated dd/mm/yyyy, or the expressions: today, tomarrow, now, in x days/hours/years/minutes, if date is provided in one of the ways that dosent include "in x hours/minuts" or "now", the the time will be specified as well in the format hh:mm or hh:mm PM/AM or hh or hh PM/AM. If there is a regex that fit some of the rules but not all it will be ok as well.
For example:</p>

```<code> now
 in 5 days 12 AM
 25/6/2020 14:05
 tomorrow 13
</code>```

答:
Did you mean something like?</p>

```<code>let r = /(\d{1,2}\/\d{1,2}\/\d{4})|today|tomorrow|now|(in\s+\d+\s+(days|hours|years|minutes)(\s+\d{1,2}(:\d{2})?\s*(AM|PM))?)|\d{2}(:\d{1,2})?\s*(PM|AM)?/
r.test("please bring it to me tomorrow in 5PM okay?") // true
</code>```

Title: js datetime regex

Body:
I am looking for a js regex for datetime.
The regex should allow:
Only valid (optional, date validity will be checked later as well) date formmated dd/mm/yyyy, or the expressions: today, tomarrow, now, in x days/hours/years/minutes, if date is provided in one of the ways that dosent include "in x hours/minuts" or "now", the the time will be specified as well in the format hh:mm or hh:mm PM/AM or hh or hh PM/AM. If there is a regex that fit some of the rules but not all it will be ok as well.
For example:

 now
 in 5 days 12 AM
 25/6/2020 14:05
 tomorrow 13

Body:
Did you mean something like?

let r = /(\d{1,2}\/\d{1,2}\/\d{4})|today|tomorrow|now|(in\s+\d+\s+(days|hours|years|minutes)(\s+\d{1,2}(:\d{2})?\s*(AM|PM))?)|\d{2}(:\d{1,2})?\s*(PM|AM)?/
r.test("please bring it to me tomorrow in 5PM okay?") // true


问:
Is there a standard library function for binary search on a sorted list in Dart?
Is there a standard library method for binary search on a sorted list in Dart?

I've Googled and there seems to be one in flutter, but I can't find one in dart.

I also found this bug which mentions lowerBound() and binary search. It appears there used to be a collections/algorithms package but this appears deprecated and I can't see a replacement in collections.dart.

It isn't difficult to write one but I prefer to use standard library methods if possible.

答:
The methods are there in the collection.dart package.

They can be a little hard to spot. If you scroll down they are in the Functions section and there is both binarySearch() and lowerBound()

It's important to notice this is package:collection, not dart:collection which also exists. But both are written by the Dart developers.

To import it use:

```<code>import 'package:collection/collection.dart';
</code>```

Body:
The methods are there in the collection.dart package.

They can be a little hard to spot. If you scroll down they are in the Functions section and there is both binarySearch() and lowerBound()

It's important to notice this is package:collection, not dart:collection which also exists. But both are written by the Dart developers.

To import it use:

import 'package:collection/collection.dart';


问:
How do I run a python script that is located on the AWS EC2 server?
I want to use python code on my computer to run a python script that is located on the server (EC2 ubuntu 18). I understand that you can use boto for this, but I didn't find a full-fledged example where it would be written here is the server, we connect to it like this, we execute the script like this.</p>

答:
You can do so by using AWS SSM or lambda function.

Refer to @mokugo-devops 's answer for AWS SSM

or Refer to this for lambda function approach

```<code>#requires paramiko package
#paramiko package is available at:
# https://github.com/pranavmalaviya2/COVID-19-Live-Data-board/tree/master/lambda%20functions/SSH_lambda-Deployment-package

import json
import boto3
import paramiko
import time

def lambda_handler(event, context):
    # boto3 client
    client = boto3.client('ec2')
    s3_client = boto3.client('s3')

    # getting instance information
    describeInstance = client.describe_instances()

    # downloading pem file from S3
    s3_client.download_file('bucket-name','key-name.pem', '/destination/folder/new-key-name.pem')

    # reading pem file and creating key object
    key = paramiko.RSAKey.from_private_key_file("/destination/folder/new-key-name.pem")
    # an instance of the Paramiko.SSHClient
    ssh_client = paramiko.SSHClient()
    # setting policy to connect to unknown host
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    # connect using ec2 instance ID if requires
    ssh_client.connect(hostname="12.12.12.12", username="ubuntu", pkey=key)

    # command list
    commands = [
        "python script.py",
        "python script2.py",
        "aws s3 cp --recursive source/ s3://destination-bucket/",
    ]

    # executing list of commands within server
    print("Starting execution")
    for command in commands:
        print("Executing command: " + command)
        stdin , stdout, stderr = ssh_client.exec_command(command)
        print(stdout.read())
        print(stderr.read())

    print("finished execution")

    return {
        'statusCode': 200,
        'body': json.dumps('Execution Completed')
    }
</code>```

Body:
You can do so by using AWS SSM or lambda function.

Refer to @mokugo-devops 's answer for AWS SSM

or Refer to this for lambda function approach

#requires paramiko package
#paramiko package is available at:
# https://github.com/pranavmalaviya2/COVID-19-Live-Data-board/tree/master/lambda%20functions/SSH_lambda-Deployment-package

import json
import boto3
import paramiko
import time

def lambda_handler(event, context):
    # boto3 client
    client = boto3.client('ec2')
    s3_client = boto3.client('s3')

    # getting instance information
    describeInstance = client.describe_instances()

    # downloading pem file from S3
    s3_client.download_file('bucket-name','key-name.pem', '/destination/folder/new-key-name.pem')

    # reading pem file and creating key object
    key = paramiko.RSAKey.from_private_key_file("/destination/folder/new-key-name.pem")
    # an instance of the Paramiko.SSHClient
    ssh_client = paramiko.SSHClient()
    # setting policy to connect to unknown host
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    # connect using ec2 instance ID if requires
    ssh_client.connect(hostname="12.12.12.12", username="ubuntu", pkey=key)

    # command list
    commands = [
        "python script.py",
        "python script2.py",
        "aws s3 cp --recursive source/ s3://destination-bucket/",
    ]

    # executing list of commands within server
    print("Starting execution")
    for command in commands:
        print("Executing command: " + command)
        stdin , stdout, stderr = ssh_client.exec_command(command)
        print(stdout.read())
        print(stderr.read())

    print("finished execution")

    return {
        'statusCode': 200,
        'body': json.dumps('Execution Completed')
    }


问:
Replacing symbol strange situation
```<code>foreach($ret as $object)
{
    $res = $object->...;
    $img_src = $res[0]->src;
    echo $img_src . '<br />';
    echo str_replace("&size=2", "", $img_src) . '<br /><br />';
}
</code>```

$img_src ~ 'http://site.com/img.jpg&size=2'

And I have to receive same link but without &size=2. Why doesn't work my last line in code. It shows the same url.

答:
Seems to work on this end:

```<code>http://site.com/img.jpg&size=2
http://site.com/img.jpg
</code>```

from

```<code><?php
$img_src = 'http://site.com/img.jpg&size=2';
echo $img_src.'<br />';
echo str_replace("&size=2", "", $img_src).'<br/><br/>';
?>
</code>```

Title: Replacing symbol strange situation

Body:
foreach($ret as $object)
{
    $res = $object->...;
    $img_src = $res[0]->src;
    echo $img_src . '
';
    echo str_replace("&size=2", "", $img_src) . '

';
}

$img_src ~ 'http://site.com/img.jpg&size=2'

And I have to receive same link but without &size=2. Why doesn't work my last line in code. It shows the same url.

Body:
Seems to work on this end:

http://site.com/img.jpg&size=2
http://site.com/img.jpg

from

<?php
$img_src = 'http://site.com/img.jpg&size=2';
echo $img_src.'<br />';
echo str_replace("&size=2", "", $img_src).'<br/><br/>';
?>


问:
Linkedin share doesn't show any info. Just the main URL of our website
If I try to share an article from our website: http://www.acquisitie.org/ to Linkedin, it only shows the main URL from our website. So not the url from the specific article,also no data, image etc. This happens while using the share button and also posting a URL to status update.

This is a Wordpress website and the sharing issue started last month.

What I've tried:
- Disable different plugins that could cause Open Graph conflicts
- Checked Facebook Open Graph debugger for big errors
- Tried different social sharing plugins
- Searching like crazy for a solution

Now unfortunately I'm not the only one with Linkedin share issues as you can see here: http://developer.linkedin.com/forum/attempts-share-url-linkedin-ignore-open-graph-tags, but maybe someone here can help me out. This is driving me crazy.

Thanks in advance!

答:
So not the url from the specific article,also no data, image etc....

So, I looked at your site's code, the current 2020 version and a 2013 version supplied by Archive.org.  Both of them do not contain any og:image tag.  You need to have an og:image tag to specify the image you want to be used when sharing.  You do have some og: tags, but not the og:image one.  Look:

```<code><meta property="og:locale" content="nl_NL"/>
<meta property="og:title" content="Acquisitie » Meer Klanten, Meer Orders, Meer Omzet"/>
<meta property="og:description" content="Verkoop meer!"/>
...
(no og:image tag)
</code>```

Add one, as indicated by the Official LinkedIn Shareable Documentation.  Like this...

```<code><meta property='og:image' content='//media.example.com/ 1234567.jpg"/>
</code>```

Still uncertain that you're doing it incorrectly?  Try the URL you are trying to share (i.e., yoursite.com/pageToShareOnLinkedin) here: Official LinkedIn Post Inspector.  That should be able to tell you exactly why an image isn't being selected.  Of course, for now it will indicate the absence of og: tag.

Body:
So not the url from the specific article,also no data, image etc....

So, I looked at your site's code, the current 2020 version and a 2013 version supplied by Archive.org.  Both of them do not contain any og:image tag.  You need to have an og:image tag to specify the image you want to be used when sharing.  You do have some og: tags, but not the og:image one.  Look:

<meta property="og:locale" content="nl_NL"/>
<meta property="og:title" content="Acquisitie » Meer Klanten, Meer Orders, Meer Omzet"/>
<meta property="og:description" content="Verkoop meer!"/>
...
(no og:image tag)

Add one, as indicated by the Official LinkedIn Shareable Documentation.  Like this...

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

Still uncertain that you're doing it incorrectly?  Try the URL you are trying to share (i.e., yoursite.com/pageToShareOnLinkedin) here: Official LinkedIn Post Inspector.  That should be able to tell you exactly why an image isn't being selected.  Of course, for now it will indicate the absence of og: tag.


问:
Issue requesting token from Sonos api in oauth process
Problem
I am trying to implement the  Sonos Authorization API as I am trying to build a small IoT device I want to use as a remote but I am facing difficulties with the oauth process.

I did the following

Create a Sonos dev-account and create credentials

Open the "Create Authorization Code" in the browser and enter my Sonos credentials. In this step I get redirected to the redirect url as expected (I used requestbin.com and postb.in to get started)

Try to create the token but I get a client_invalid error which is supposed to mean the authorization code is incorrect

What I noticed
As I havent implemented any custom code yet I am not sure what I am doing wrong. I noticed the authorization codes I receive (e.g. ZGyr3PrM) are much shorter in comparison to the examples (e.g. f10072fa6-2134-4fe1-93fd-ca5b9cffa738).

Do you have any ideas how to fix this or did anyone else have the same issues?

Thanks for your support
Felix

答:
I found the solution to my problem:

The example how to add the authorization in the documentation to create the token ist not correct.

It should be

Authorization: Basic {Base64 clientid:secret}

instead of

Authorization: Basic {Base64 clientid and secret}


问:
how to fix progess bar class with problem in ionic 4 and css?
Hello i want to do a progress bar that get the with every time from a ngFor list that why i make this css

```<code>.first{
height: 10px;
width: 100%;
background: #ddd;

}
.second{
height: 10px;
background: #009200;
}
</code>```

and this is my code in html

```<code> <div  *ngFor=" let rec of myComplain">

    <ion-list >

        <ion-item class="box">

          <h2><ion-row ><div class="tile"> Type :   </div> {{rec.type}} </ion-row> </h2>
          <h2 ><ion-row> <div class="tile"> Description:  </div>  {{rec.description}}</ion-row> </h2>
          <h2  *ngIf="rec.avancement === 'Pending Team leader validation'"><ion-row><div class="tile"> Progress :  </div> In progress </ion-row></h2>
          <h2 *ngIf="rec.avancement != 'Pending Team leader validation'" ><ion-row><div class="tile"> Progress :  </div>  {{rec.avancement}}</ion-row></h2>
          <h2><ion-row><div class="tile"> Project:   </div>{{rec.nameProjet}}</ion-row> </h2>
          <h2><ion-row><div class="tile"> Created :  </div> {{ rec.created_at }} </ion-row></h2>
          <h2><ion-row><div class="tile"> Progress:  </div> {{ rec.progress }}% </ion-row></h2>
          <br>

          <div class="first">
            <div class="second" style.width="rec.progress%;"></div>
            </div>

      </ion-item>
      <hr>
    </ion-list>

  </div>
</code>```

the problem is i want to read rec.progress in the style.with every time and dosen't work
any body know how i can do this please ?

答:
The syntax is [style.width.%]="value".

So in your case:

```<code><div class="second" [style.width.%]="rec.progress"></div>
</code>```

Body:
Hello i want to do a progress bar that get the with every time from a ngFor list that why i make this css

.first{
height: 10px;
width: 100%;
background: #ddd;

}
.second{
height: 10px;
background: #009200;
}

and this is my code in html

    <ion-list >

        <ion-item class="box">

<ion-row >
 Type :
 {{rec.type}} </ion-row>

<ion-row>
 Description:
  {{rec.description}}</ion-row>

<ion-row>
 Progress :
 In progress </ion-row>

<ion-row>
 Progress :
  {{rec.avancement}}</ion-row>

<ion-row>
 Project:
{{rec.nameProjet}}</ion-row>

<ion-row>
 Created :
 {{ rec.created_at }} </ion-row>

<ion-row>
 Progress:
 {{ rec.progress }}% </ion-row>

      </ion-item>

    </ion-list>

the problem is i want to read rec.progress in the style.with every time and dosen't work
any body know how i can do this please ?

Body:
The syntax is [style.width.%]="value".

So in your case:

<div class="second" [style.width.%]="rec.progress"></div>


问:
Show/hide password onClick of using Vanilla js
I'm trying to hide/show password using the following codes which works fine if it is for 1 input field. If I have another input field, say for 'verify password', how do I make the other works. I'm kinda stuck here.

Any input is very much appreciated. Thank you.

```<code>    var passwordField = document.querySelector(".password"),
        eyeIcon = document.querySelector(".icon");

    function togglePassword() {
        if (passwordField.type === "password") {
            passwordField.type = "text";
        } else {
            passwordField.type = "password";
        }
    }
    eyeIcon.addEventListener("click", togglePassword);
</code>```

答:
You could just make the listener function generic using this:

```<code> var passwordField = document.querySelector(".password"),
        eyeIcon = document.querySelector(".icon");
  var anotherPassFeild = document.querySelector(".anotherPass")

    function togglePassword() {
        if (this.type === "password") {
            this.type = "text";
        } else {
            this.type = "password";
        }
    }
    passwordField.addEventListener("click", togglePassword);
    anotherPassFeild.addEventListener("click", togglePassword);
</code>```

Or, you can give the same class name password to different inputs, select them all and attach the event listener to each of them like this.

    var passwordField = document.querySelectorAll(".password");
    function togglePassword() {
        if (this.type === "password") {
            this.type = "text";
        } else {
            this.type = "password";
        }
    }
    passwordField.forEach((elem)=>{
      elem.addEventListener("click", togglePassword);
    })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input class ="password something" type="password"/>
<input class ="password icon" type="password"/></code>```

Body:
I'm trying to hide/show password using the following codes which works fine if it is for 1 input field. If I have another input field, say for 'verify password', how do I make the other works. I'm kinda stuck here.

Any input is very much appreciated. Thank you.

    var passwordField = document.querySelector(".password"),
        eyeIcon = document.querySelector(".icon");

    function togglePassword() {
        if (passwordField.type === "password") {
            passwordField.type = "text";
        } else {
            passwordField.type = "password";
        }
    }
    eyeIcon.addEventListener("click", togglePassword);

Body:
You could just make the listener function generic using this:

 var passwordField = document.querySelector(".password"),
        eyeIcon = document.querySelector(".icon");
  var anotherPassFeild = document.querySelector(".anotherPass")

    function togglePassword() {
        if (this.type === "password") {
            this.type = "text";
        } else {
            this.type = "password";
        }
    }
    passwordField.addEventListener("click", togglePassword);
    anotherPassFeild.addEventListener("click", togglePassword);

Or, you can give the same class name password to different inputs, select them all and attach the event listener to each of them like this.

    var passwordField = document.querySelectorAll(".password");
    function togglePassword() {
        if (this.type === "password") {
            this.type = "text";
        } else {
            this.type = "password";
        }
    }
    passwordField.forEach((elem)=>{
      elem.addEventListener("click", togglePassword);
    })

<input class ="password something" type="password"/>
<input class ="password icon" type="password"/>


问:
Dependence incompatible in my flutter project
[source] flutter.bat pub get
Running "flutter pub get" in source...

Because rate_my_app >=0.6.0+3 depends on shared_preferences ^0.5.7 and fstore depends on shared_preferences 0.5.3+4, rate_my_app >=0.6.0+3 is forbidden.

So, because fstore depends on rate_my_app ^0.6.1+2, version solving failed.
pub get failed (1; So, because fstore depends on rate_my_app ^0.6.1+2, version solving failed.)
exit code 1

Here is my pubspec.yaml:

```<code>    name: fstore
description: Mobile commerce app by Flutter

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# `enter code here`https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.3.0+1

environment:
  sdk: ">=2.2.2 <3.0.0"

dependencies:
  logs:
    git: https://github.com/pq/logs
  flutter:
    sdk: flutter
  intl: 0.16.1
  http: 0.12.0+2
  html_unescape: 1.0.1+3
  provider: ^3.0.0+1
  flutter_signin_button: ^0.2.8
  after_layout: 1.0.7+2
  font_awesome_flutter: ^8.5.0
  path: 1.7.0
  flutter_facebook_login: ^2.0.1
  flutter_account_kit: 0.7.0
  vector_math: 2.0.8
  carousel_pro: ^1.0.0
  flutter_widget_from_html_core: ^0.2.2+1
  configurable_expansion_tile: ^1.0.0
  timeago: ^2.0.18
  share: ^0.6.2+1
  validate: ^1.7.0
  country_pickers: ^1.1.0
  shared_preferences: ^0.5.7
  firebase_messaging: 5.1.2
  firebase_analytics: 4.0.2
  transparent_image: 1.0.0
  pull_to_refresh: ^1.5.0
  localstorage: ^2.0.0
  notification_permissions: ^0.4.0
  flare_splash_screen: 2.1.3
  rate_my_app: ^0.6.0+3
  flutter_range_slider: ^1.3.1
  page_indicator: ^0.2.0
  global_configuration: ^1.1.0
  extended_image: 0.5.3
  flutter_screenutil: 0.5.3
  fluttertoast: ^3.1.0
  intro_slider: ^2.2.5
  url_launcher: ^5.1.0
  firebase_core: ^0.4.0+8
  firebase_auth: ^0.11.1+12
  cloud_firestore: ^0.12.7+1
  firestore_ui: ^1.6.0
  flutter_webview_plugin: ^0.3.5
  connectivity: ^0.4.3+6
  random_string: ^1.1.0
  google_maps_flutter: 0.5.19+2
  place_picker: 0.9.8
  cached_network_image: ^2.0.0-rc
  firebase_storage: ^3.0.4
  image_picker: ^0.6.0+17
  fab_circular_menu: 0.1.1
  uuid: ^2.0.2
  flutter_localizations:
    sdk: flutter

dev_dependencies:
  flutter_launcher_icons: ^0.7.2+1
  flutter_test:
    sdk: flutter

# Run this script to generate the app icon: flutter pub pub run flutter_launcher_icons:main
flutter_icons:
  android: "launcher_icon"
  ios: true
  image_path: "assets/images/app_icon.png"

# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  uses-material-design: true
  assets:
    - lib/common/config.json
    - assets/icons/categories/
    - assets/icons/tabs/
    - assets/icons/profile/
    - assets/icons/payment/
    - assets/images/
    - assets/images/country/

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.io/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.io/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  fonts:
    - family: Raleway
      fonts:
        - asset: assets/fonts/Raleway-Regular.ttf
        - asset: assets/fonts/Raleway-Medium.ttf
        - asset: assets/fonts/Raleway-Bold.ttf
        - asset: assets/fonts/Raleway-Light.ttf
        - asset: assets/fonts/Raleway-Thin.ttf
    - family: Roboto
      fonts:
        - asset: assets/fonts/Roboto-Regular.ttf
        - asset: assets/fonts/Roboto-Medium.ttf
        - asset: assets/fonts/Roboto-Bold.ttf
        - asset: assets/fonts/Roboto-Light.ttf
        - asset: assets/fonts/Roboto-Thin.ttf
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.io/custom-fonts/#from-packages
</code>```

I have this problem how can i solve it?

答: I have solved this. You need to update the rate_my_app to 0.6.0+3 and shared_preferences to 0.5.7+3 and then hit packages get.</p>

Body:
[source] flutter.bat pub get
Running "flutter pub get" in source...

Because rate_my_app >=0.6.0+3 depends on shared_preferences ^0.5.7 and fstore depends on shared_preferences 0.5.3+4, rate_my_app >=0.6.0+3 is forbidden.

So, because fstore depends on rate_my_app ^0.6.1+2, version solving failed.
pub get failed (1; So, because fstore depends on rate_my_app ^0.6.1+2, version solving failed.)
exit code 1

Here is my pubspec.yaml:

    name: fstore
description: Mobile commerce app by Flutter

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# `enter code here`https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.3.0+1

environment:
  sdk: ">=2.2.2 <3.0.0"

dependencies:
  logs:
    git: https://github.com/pq/logs
  flutter:
    sdk: flutter
  intl: 0.16.1
  http: 0.12.0+2
  html_unescape: 1.0.1+3
  provider: ^3.0.0+1
  flutter_signin_button: ^0.2.8
  after_layout: 1.0.7+2
  font_awesome_flutter: ^8.5.0
  path: 1.7.0
  flutter_facebook_login: ^2.0.1
  flutter_account_kit: 0.7.0
  vector_math: 2.0.8
  carousel_pro: ^1.0.0
  flutter_widget_from_html_core: ^0.2.2+1
  configurable_expansion_tile: ^1.0.0
  timeago: ^2.0.18
  share: ^0.6.2+1
  validate: ^1.7.0
  country_pickers: ^1.1.0
  shared_preferences: ^0.5.7
  firebase_messaging: 5.1.2
  firebase_analytics: 4.0.2
  transparent_image: 1.0.0
  pull_to_refresh: ^1.5.0
  localstorage: ^2.0.0
  notification_permissions: ^0.4.0
  flare_splash_screen: 2.1.3
  rate_my_app: ^0.6.0+3
  flutter_range_slider: ^1.3.1
  page_indicator: ^0.2.0
  global_configuration: ^1.1.0
  extended_image: 0.5.3
  flutter_screenutil: 0.5.3
  fluttertoast: ^3.1.0
  intro_slider: ^2.2.5
  url_launcher: ^5.1.0
  firebase_core: ^0.4.0+8
  firebase_auth: ^0.11.1+12
  cloud_firestore: ^0.12.7+1
  firestore_ui: ^1.6.0
  flutter_webview_plugin: ^0.3.5
  connectivity: ^0.4.3+6
  random_string: ^1.1.0
  google_maps_flutter: 0.5.19+2
  place_picker: 0.9.8
  cached_network_image: ^2.0.0-rc
  firebase_storage: ^3.0.4
  image_picker: ^0.6.0+17
  fab_circular_menu: 0.1.1
  uuid: ^2.0.2
  flutter_localizations:
    sdk: flutter

dev_dependencies:
  flutter_launcher_icons: ^0.7.2+1
  flutter_test:
    sdk: flutter

# Run this script to generate the app icon: flutter pub pub run flutter_launcher_icons:main
flutter_icons:
  android: "launcher_icon"
  ios: true
  image_path: "assets/images/app_icon.png"

# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  uses-material-design: true
  assets:
    - lib/common/config.json
    - assets/icons/categories/
    - assets/icons/tabs/
    - assets/icons/profile/
    - assets/icons/payment/
    - assets/images/
    - assets/images/country/

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.io/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.io/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  fonts:
    - family: Raleway
      fonts:
        - asset: assets/fonts/Raleway-Regular.ttf
        - asset: assets/fonts/Raleway-Medium.ttf
        - asset: assets/fonts/Raleway-Bold.ttf
        - asset: assets/fonts/Raleway-Light.ttf
        - asset: assets/fonts/Raleway-Thin.ttf
    - family: Roboto
      fonts:
        - asset: assets/fonts/Roboto-Regular.ttf
        - asset: assets/fonts/Roboto-Medium.ttf
        - asset: assets/fonts/Roboto-Bold.ttf
        - asset: assets/fonts/Roboto-Light.ttf
        - asset: assets/fonts/Roboto-Thin.ttf
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.io/custom-fonts/#from-packages

I have this problem how can i solve it?


问:
convenient way to convert seconds into more specific format
Is there any convenient way to convert seconds into more specific format.

For example:

I want to convert

```<code>559 seconds
</code>```

to

```<code>9 min 19 sec
</code>```

答:
The following is a PHP version that I made of some SmallC native code that is shipped with AMX Mod X.</p>

```<code><?php
/**
 * PHPInSimMod - Time Module
 * @package PRISM
 * @subpackage Time
 * @copyright the AMX Mod X Development Team & The PRISM Devlopment Team.
*/

class Time
{
    // Time unit types.
    const UNIT_SECONDS      = 0;
    const UNIT_MINUTES      = 1;
    const UNIT_HOURS        = 2;
    const UNIT_DAYS         = 3;
    const UNIT_WEEKS        = 4;

    // The number of seconds that are in each time unit.
    const SECONDS_IN_MINUTE = 60;
    const SECONDS_IN_HOUR   = 3600;
    const SECONDS_IN_DAY    = 86400;
    const SECONDS_IN_WEEK   = 604800;

    /**
     * @desc: By Brad for AMX Mod X.
     * @param: Unit - The number of time units you want translated into verbose text.
     * @param: Type - The type of unit (i.e. seconds, minutes, hours, days, weeks) that you are passing in.
    */
    static function getLength($unit, $type = Time::UNIT_SECONDS)
    {
        # Ensure the varables are of the correct datatype.
        $unit = (int) $unit;
        $type = (int) $type;

        # If our units happens to equal zero, skip.
        if ($unit == 0)
            return '0 seconds';

        # Determine the number of each time unit there are.
        $weeks = 0; $days = 0; $hours = 0; $minutes = 0; $seconds = 0;

        # Handle the various scales of time.
        switch ($type)
        {
            case Time::UNIT_SECONDS: $seconds = $unit;
            case Time::UNIT_MINUTES: $seconds = $unit * Time::SECONDS_IN_MINUTE;
            case Time::UNIT_HOURS:   $seconds = $unit * Time::SECONDS_IN_HOUR;
            case Time::UNIT_DAYS:    $seconds = $unit * Time::SECONDS_IN_DAY;
            case Time::UNIT_WEEKS:   $seconds = $unit * Time::SECONDS_IN_WEEK;
        }

        # How many weeks left?
        $weeks = $seconds / Time::SECONDS_IN_WEEK;
        $seconds -= ($weeks * Time::SECONDS_IN_WEEK);

        # How many days left?
        $days = $seconds / Time::SECONDS_IN_DAY;
        $seconds -= ($days * Time::SECONDS_IN_DAY);

        # How many hours left?
        $hours = $seconds / Time::SECONDS_IN_HOUR;
        $seconds -= ($hours * Time::SECONDS_IN_HOUR);

        # How many minutes left?
        $minutes = $seconds / Time::SECONDS_IN_MINUTE;
        $seconds -= ($minutes * Time::SECONDS_IN_MINUTE);

        # Seconds are the base unit, so it's handled intrinsically

        // Translate the unit counts into verbose text
        $timeElement = array();

        if ($weeks > 0)
            $timeElement[] = sprintf("%i %s", $weeks, ($weeks == 1) ? "week" : "weeks");
        if ($days > 0)
            $timeElement[] = sprintf("%i %s", $days, ($days == 1) ? "day" : "days");
        if ($hours > 0)
            $timeElement[] = sprintf("%i %s", $hours, ($hours == 1) ? "hour" : "hours");
        if ($minutes > 0)
            $timeElement[] = sprintf("%i %s", $minutes, ($minutes == 1) ? "minute" : "minutes");
        if ($seconds > 0)
            $timeElement[] = sprintf("%i %s", $seconds, ($seconds == 1) ? "second" : "seconds");

        // Outputs are final result in the correct format.
        switch(count($timeElement))
        {
            case 1: return sprintf("%s", $timeElement[0]);
            case 2: return sprintf("%s & %s", $timeElement[0], $timeElement[1]);
            case 3: return sprintf("%s, %s & %s", $timeElement[0], $timeElement[1], $timeElement[2]);
            case 4: return sprintf("%s, %s, %s & %s", $timeElement[0], $timeElement[1], $timeElement[2], $timeElement[3]);
            case 5: return sprintf("%s, %s, %s, %s & %s", $timeElement[0], $timeElement[1], $timeElement[2], $timeElement[3], $timeElement[4]);
        }
    }
}

?>
</code>```

Body:
Is there any convenient way to convert seconds into more specific format.

For example:

I want to convert

559 seconds

to

9 min 19 sec

Body:
The following is a PHP version that I made of some SmallC native code that is shipped with AMX Mod X.

<?php
/**
 * PHPInSimMod - Time Module
 * @package PRISM
 * @subpackage Time
 * @copyright the AMX Mod X Development Team & The PRISM Devlopment Team.
*/

class Time
{
    // Time unit types.
    const UNIT_SECONDS      = 0;
    const UNIT_MINUTES      = 1;
    const UNIT_HOURS        = 2;
    const UNIT_DAYS         = 3;
    const UNIT_WEEKS        = 4;

    // The number of seconds that are in each time unit.
    const SECONDS_IN_MINUTE = 60;
    const SECONDS_IN_HOUR   = 3600;
    const SECONDS_IN_DAY    = 86400;
    const SECONDS_IN_WEEK   = 604800;

    /**
     * @desc: By Brad for AMX Mod X.
     * @param: Unit - The number of time units you want translated into verbose text.
     * @param: Type - The type of unit (i.e. seconds, minutes, hours, days, weeks) that you are passing in.
    */
    static function getLength($unit, $type = Time::UNIT_SECONDS)
    {
        # Ensure the varables are of the correct datatype.
        $unit = (int) $unit;
        $type = (int) $type;

        # If our units happens to equal zero, skip.
        if ($unit == 0)
            return '0 seconds';

        # Determine the number of each time unit there are.
        $weeks = 0; $days = 0; $hours = 0; $minutes = 0; $seconds = 0;

        # Handle the various scales of time.
        switch ($type)
        {
            case Time::UNIT_SECONDS: $seconds = $unit;
            case Time::UNIT_MINUTES: $seconds = $unit * Time::SECONDS_IN_MINUTE;
            case Time::UNIT_HOURS:   $seconds = $unit * Time::SECONDS_IN_HOUR;
            case Time::UNIT_DAYS:    $seconds = $unit * Time::SECONDS_IN_DAY;
            case Time::UNIT_WEEKS:   $seconds = $unit * Time::SECONDS_IN_WEEK;
        }

        # How many weeks left?
        $weeks = $seconds / Time::SECONDS_IN_WEEK;
        $seconds -= ($weeks * Time::SECONDS_IN_WEEK);

        # How many days left?
        $days = $seconds / Time::SECONDS_IN_DAY;
        $seconds -= ($days * Time::SECONDS_IN_DAY);

        # How many hours left?
        $hours = $seconds / Time::SECONDS_IN_HOUR;
        $seconds -= ($hours * Time::SECONDS_IN_HOUR);

        # How many minutes left?
        $minutes = $seconds / Time::SECONDS_IN_MINUTE;
        $seconds -= ($minutes * Time::SECONDS_IN_MINUTE);

        # Seconds are the base unit, so it's handled intrinsically

        // Translate the unit counts into verbose text
        $timeElement = array();

        if ($weeks > 0)
            $timeElement[] = sprintf("%i %s", $weeks, ($weeks == 1) ? "week" : "weeks");
        if ($days > 0)
            $timeElement[] = sprintf("%i %s", $days, ($days == 1) ? "day" : "days");
        if ($hours > 0)
            $timeElement[] = sprintf("%i %s", $hours, ($hours == 1) ? "hour" : "hours");
        if ($minutes > 0)
            $timeElement[] = sprintf("%i %s", $minutes, ($minutes == 1) ? "minute" : "minutes");
        if ($seconds > 0)
            $timeElement[] = sprintf("%i %s", $seconds, ($seconds == 1) ? "second" : "seconds");

        // Outputs are final result in the correct format.
        switch(count($timeElement))
        {
            case 1: return sprintf("%s", $timeElement[0]);
            case 2: return sprintf("%s & %s", $timeElement[0], $timeElement[1]);
            case 3: return sprintf("%s, %s & %s", $timeElement[0], $timeElement[1], $timeElement[2]);
            case 4: return sprintf("%s, %s, %s & %s", $timeElement[0], $timeElement[1], $timeElement[2], $timeElement[3]);
            case 5: return sprintf("%s, %s, %s, %s & %s", $timeElement[0], $timeElement[1], $timeElement[2], $timeElement[3], $timeElement[4]);
        }
    }
}

?>


问:
Confirming or Dismissing Dialog when using Puppeteer
I'm trying to dismiss a dialog within Puppeteer. I tried to convert original Puppeteer instructions, but did not work.

The website I'm crawling throws up the alert from within body onload.

Here is what I have so far with no luck.

```<code>$js_function = JsFunction::createWithAsync()
     ->body('async dialog => {
     await dialog.dismiss();
}');

$this->page->on('dialog', $js_function);

$this->page->goto($this->url);
</code>```

Original puppeteer docs:
https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#class-dialog

答:
You did almost everything right, but there is one small bug.

Here correct code:

```<code>$js_function = JsFunction::createWithAsync()
    ->parameters(['dialog'])
    ->body('await dialog.dismiss();');

$this->page->on('dialog', $js_function);

$this->page->goto($this->url);
</code>```

And here example of code, if you wanna confirm:

```<code>$js_function = JsFunction::createWithAsync()
    ->parameters(['dialog'])
    ->body('await dialog.accept();');

$this->page->on('dialog', $js_function);

$this->page->goto($this->url);
</code>```

Body:
I'm trying to dismiss a dialog within Puppeteer. I tried to convert original Puppeteer instructions, but did not work.

The website I'm crawling throws up the alert from within body onload.

Here is what I have so far with no luck.

$js_function = JsFunction::createWithAsync()
     ->body('async dialog => {
     await dialog.dismiss();
}');

$this->page->on('dialog', $js_function);

$this->page->goto($this->url);

Original puppeteer docs:
https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#class-dialog

Body:
You did almost everything right, but there is one small bug.

Here correct code:

$js_function = JsFunction::createWithAsync()
    ->parameters(['dialog'])
    ->body('await dialog.dismiss();');

$this->page->on('dialog', $js_function);

$this->page->goto($this->url);

And here example of code, if you wanna confirm:

$js_function = JsFunction::createWithAsync()
    ->parameters(['dialog'])
    ->body('await dialog.accept();');

$this->page->on('dialog', $js_function);

$this->page->goto($this->url);