问:
How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?
This is running on Windows Server 2008 and used to work several months ago.  I am just now using this server again for some dev work with VS.

This is live web server used to serve up a few test sites as well.

This came up when running Visual Studio, then launching my projects for debugging.

Trying to launch any site through localhost:xxxx when IISExpress has been launched (using actual port #'s in the config to access different sites):

```<code>This webpage is not available

ERR_CONNECTION_REFUSED
</code>```

I have been at this for a few days already, as I have read others have had similar issues, tried most things I have read including changing the managedruntimeversion from "v4.0" to "v4.0.30319" for .net 4.5 (I have never had to do this before) and disabling the logging module (all suggestions found here).

There are only two entries in my hosts file that point to internal server IP addresses.  No localhost related IP's or references.

I have gone as far as re-installing IIS Express, and Visual Studio 2013. I also created a brand new WebApplication site to try to resolve this (simple and no other complicated bindings).

When I spin up Fiddler, I see the following on the page:

```<code>[Fiddler] The socket connection to localhost failed.
ErrorCode: 10061.
No connection could be made because the target machine actively refused it 127.0.0.1:23162
</code>```

I have removed all proxy settings from IE's LAN connection section, where before I was getting a red-x popup in VS indicating something like IISExpress could not launch.

This is not a matter of SSL vs non SSL.

I had TFS Server installed - uninstalled that in case there were some odd bindings that were interfering.

I tried deleting the IISExpress config/settings folder several times.

Current applicationhost.config contains:

```<code><site name="WebApplication1" id="4">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="C:\TFS-WorkRepository\Sandbox\WebApplication1\WebApplication1" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="*:23162:localhost" />
                </bindings>
            </site>
            <siteDefaults>
                <logFile logFormat="W3C" directory="%IIS_USER_HOME%\Logs" />
                <traceFailedRequestsLogging directory="%IIS_USER_HOME%\TraceLogFiles" enabled="true" maxLogFileSizeKB="1024" />
            </siteDefaults>
            <applicationDefaults applicationPool="Clr4IntegratedAppPool" />
</code>```

I wish there was a tag for really-stuck.

Please suggest away, as I don't want to go as far as spinning up a new server.

-- UPDATE --

In the URL bar, when I enter the computer name or IP address :xxxx I get the ERR_CONNECTION_TIMED_OUT rather than ERR_CONNECTION_REFUSED.

答:
This may be relevant to a certain subset of people with this issue...perhaps in a different flavor.

I was forcing an https redirect on RELEASE.

```<code>public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
  filters.Add(new HandleErrorAttribute());
  #if !DEBUG
  filters.Add(new RequireHttpsAttribute());
  #endif
}
</code>```

And there wasn't https enabled on my iis express.
Working correctly on DEBUG

Body:
This is running on Windows Server 2008 and used to work several months ago.  I am just now using this server again for some dev work with VS.

This is live web server used to serve up a few test sites as well.

This came up when running Visual Studio, then launching my projects for debugging.

Trying to launch any site through localhost:xxxx when IISExpress has been launched (using actual port #'s in the config to access different sites):

This webpage is not available

ERR_CONNECTION_REFUSED

I have been at this for a few days already, as I have read others have had similar issues, tried most things I have read including changing the managedruntimeversion from "v4.0" to "v4.0.30319" for .net 4.5 (I have never had to do this before) and disabling the logging module (all suggestions found here).

There are only two entries in my hosts file that point to internal server IP addresses.  No localhost related IP's or references.

I have gone as far as re-installing IIS Express, and Visual Studio 2013. I also created a brand new WebApplication site to try to resolve this (simple and no other complicated bindings).

When I spin up Fiddler, I see the following on the page:

[Fiddler] The socket connection to localhost failed.
ErrorCode: 10061.
No connection could be made because the target machine actively refused it 127.0.0.1:23162

I have removed all proxy settings from IE's LAN connection section, where before I was getting a red-x popup in VS indicating something like IISExpress could not launch.

This is not a matter of SSL vs non SSL.

I had TFS Server installed - uninstalled that in case there were some odd bindings that were interfering.

I tried deleting the IISExpress config/settings folder several times.

Current applicationhost.config contains:

<site name="WebApplication1" id="4">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="C:\TFS-WorkRepository\Sandbox\WebApplication1\WebApplication1" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="*:23162:localhost" />
                </bindings>
            </site>
            <siteDefaults>
                <logFile logFormat="W3C" directory="%IIS_USER_HOME%\Logs" />
                <traceFailedRequestsLogging directory="%IIS_USER_HOME%\TraceLogFiles" enabled="true" maxLogFileSizeKB="1024" />
            </siteDefaults>
            <applicationDefaults applicationPool="Clr4IntegratedAppPool" />

I wish there was a tag for really-stuck.

Please suggest away, as I don't want to go as far as spinning up a new server.

-- UPDATE --

In the URL bar, when I enter the computer name or IP address :xxxx I get the ERR_CONNECTION_TIMED_OUT rather than ERR_CONNECTION_REFUSED.

Body:
This may be relevant to a certain subset of people with this issue...perhaps in a different flavor.

I was forcing an https redirect on RELEASE.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
  filters.Add(new HandleErrorAttribute());
  #if !DEBUG
  filters.Add(new RequireHttpsAttribute());
  #endif
}

And there wasn't https enabled on my iis express.
Working correctly on DEBUG


来源: stackexchange

问:
fminbnd gives a value that is not a minimum seen on the plot
I am trying to find the minimum F and its corresponding x-axis values by using fminbnd. However, when I marked this minimum value on the plot, it is not an minimum at all. The code I used is below:

```<code>T = 726.85;

kB = 8.61e-5;

Fe_energy = 0;

O_energy_Joule = -175.100 + 50.16*T;
O_energy = O_energy_Joule*6.242e18;

syms c;
f = c*O_energy + (1-c)*Fe_energy + kB*T*(c.*log(c) + (1-c).*log(1-c));
F = matlabFunction(f);
x = fminbnd(F, 0, 1)

c = (0:1e-7:1e-4);
R = c*O_energy + (1-c)*Fe_energy + kB*T*(c.*log(c) + (1-c).*log(1-c));
plot(c, R)
hold on
plot(x,F(x),'x')
</code>```

The result of the code is here:
plot and minimum point
Can someone help with answering where the discrepancy comes from? Thanks.

答:
A good thing about matlab optimization functions is that you can set some usefull options and see what the optimizer does.

I don't have the symbolic toolbox, so I put your function into a separate file:

```<code>options = optimset('Display','iter');
x = fminbnd(@myfun, 0, 1, options);
</code>```

Here is the optimizer output:

```<code>   16    0.000453104   1.0262e+20        golden
   17    0.000280034  6.34228e+19        golden
   18     0.00017307  3.91974e+19        golden
   19    0.000106963  2.42254e+19        golden
   20     6.6107e-05  1.49721e+19        golden

Optimization terminated:
 the current x satisfies the termination criteria using OPTIONS.TolX of 1.000000e-04
</code>```

Have a look at the termination criteria.

Now put your own termination criteria into the options and execute the code:

```<code>options = optimset('Display','iter', 'TolX', 1e-7);
x = fminbnd(@myfun, 0, 1, options);
</code>```

The output:

```<code>   31    3.32187e-07  7.52347e+16        golden
   32    2.05303e-07  4.64976e+16        golden
   33    1.26884e-07  2.87371e+16        golden
   34    7.84188e-08  1.77605e+16        golden
   35    4.50855e-08  1.02111e+16        golden

Optimization terminated:
 the current x satisfies the termination criteria using OPTIONS.TolX of 1.000000e-07
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to find the minimum F and its corresponding x-axis values by using fminbnd. However, when I marked this minimum value on the plot, it is not an minimum at all. The code I used is below:

T = 726.85;

kB = 8.61e-5;

Fe_energy = 0;

O_energy_Joule = -175.100 + 50.16*T;
O_energy = O_energy_Joule*6.242e18;

syms c;
f = c*O_energy + (1-c)*Fe_energy + kB*T*(c.*log(c) + (1-c).*log(1-c));
F = matlabFunction(f);
x = fminbnd(F, 0, 1)

c = (0:1e-7:1e-4);
R = c*O_energy + (1-c)*Fe_energy + kB*T*(c.*log(c) + (1-c).*log(1-c));
plot(c, R)
hold on
plot(x,F(x),'x')

The result of the code is here:
plot and minimum point
Can someone help with answering where the discrepancy comes from? Thanks.

Body:
A good thing about matlab optimization functions is that you can set some usefull options and see what the optimizer does.

I don't have the symbolic toolbox, so I put your function into a separate file:

options = optimset('Display','iter');
x = fminbnd(@myfun, 0, 1, options);

Here is the optimizer output:

   16    0.000453104   1.0262e+20        golden
   17    0.000280034  6.34228e+19        golden
   18     0.00017307  3.91974e+19        golden
   19    0.000106963  2.42254e+19        golden
   20     6.6107e-05  1.49721e+19        golden

Optimization terminated:
 the current x satisfies the termination criteria using OPTIONS.TolX of 1.000000e-04

Have a look at the termination criteria.

Now put your own termination criteria into the options and execute the code:

options = optimset('Display','iter', 'TolX', 1e-7);
x = fminbnd(@myfun, 0, 1, options);

The output:

   31    3.32187e-07  7.52347e+16        golden
   32    2.05303e-07  4.64976e+16        golden
   33    1.26884e-07  2.87371e+16        golden
   34    7.84188e-08  1.77605e+16        golden
   35    4.50855e-08  1.02111e+16        golden

Optimization terminated:
 the current x satisfies the termination criteria using OPTIONS.TolX of 1.000000e-07


问:
Keypress event in entry box
I created a calculator using python tkinter , but I want to prevent typing any letters in the entry box that displays the numbers being calculated , I want the input to be only by button press to ensure that input will be numbers and mathematical operators only , this is the code that generates the box

```<code>textbox = Entry(MBC,font=("Helvetica",20,"bold"),text=text_Input,bd=30,
                insertwidth=4,bg="powder blue",justify="right").grid(columnspan=4)
</code>```

if It's a text entry box , how can I make it only display the mathematical operations without accepting keyboard input ?

答:
I guess you can just add a state parameter in your Entry :

myEntry = Entry(myWindow, state=DISABLED)
```

Here is some documentation about Entry widget : https://www.tutorialspoint.com/python/tk_entry.htm

EDIT

As someone in comments said, there is no need to use an Entry widget if you don't want the user to interact directly with. A simple Label would do the job, since you juste need to show the calculations.

Title: Keypress event in entry box

Body:
I created a calculator using python tkinter , but I want to prevent typing any letters in the entry box that displays the numbers being calculated , I want the input to be only by button press to ensure that input will be numbers and mathematical operators only , this is the code that generates the box

textbox = Entry(MBC,font=("Helvetica",20,"bold"),text=text_Input,bd=30,
                insertwidth=4,bg="powder blue",justify="right").grid(columnspan=4)

if It's a text entry box , how can I make it only display the mathematical operations without accepting keyboard input ?

Body:
I guess you can just add a state parameter in your Entry :

myEntry = Entry(myWindow, state=DISABLED)

Here is some documentation about Entry widget : https://www.tutorialspoint.com/python/tk_entry.htm

EDIT

As someone in comments said, there is no need to use an Entry widget if you don't want the user to interact directly with. A simple Label would do the job, since you juste need to show the calculations.


问:
How to get Memory (Private working set) per users in powershell
I'm trying to get the memory usage of process per user (like task manager), that info comes to Memory (Private working set) if we convert that values into MB we should get the memory usage, like in the users view in task manager...

Maybe i missing something, if someone know about this pls tell me.

And this is my script

```<code>Get-WmiObject Win32_Process | Sort-Object -Property privatememorysize -Descending |
Select processname, @{Name="Mem Usage(MB)";Expression={[math]::round($_.privatememorysize/ 1mb,2)}},@{Name="UserID";Expression={$_.getowner().Domain+"\"+$_.getowner().user}} | fl *
</code>```

答:
The issue is that the Win32_Process class doesn't have a property named 'privatememorysize'. Replacing that with 'privatepagecount' instead makes this work as expected.

```<code>Get-WmiObject Win32_Process | Sort-Object -Property privatepagecount -Descending |
    Select processname, @{Name="Mem Usage(MB)";Expression={[math]::round($_.privatepagecount/ 1mb,2)}},@{Name="UserID";Expression={$_.getowner().Domain+"\"+$_.getowner().user}}
</code>```

I see, that is not the same, so we have the issue here where the WMI object doesn't give private working set, and other methods that do include that don't have the user. So what we can do is use Get-Process to get each process and the private working set, and use Get-WMIObject to get the user associated with each object, and then match them up. Probably best to make a hashtable from one to reference, then use that to add the property to the other object. So, let's do that!

```<code>#Get WMI Process objects
$WMIProcs = Get-WmiObject Win32_Process
#Get Get-Process object
$GPProcs = Get-Process
#Convert Get-Process objects to a hashtable for easy lookup
$GPHT = @{}
$GPProcs | ForEach-Object {$GPHT.Add($_.ID.ToString(),$_)}
#Add PrivateWorkingSet and UserID to WMI objects
$WMIProcs|ForEach-Object{
    $_ | Add-Member "Mem Usage(MB)" $([math]::round($GPHT[$_.ProcessId.ToString()].PrivateMemorySize64/1mb,2))
    $_ | Add-Member "UserID" $($_.getowner().Domain+"\"+$_.getowner().user)
}
#Output to screen
$WMIProcs | Format-Table ProcessName, "Mem Usage(MB)", UserID
</code>```

Body:
I'm trying to get the memory usage of process per user (like task manager), that info comes to Memory (Private working set) if we convert that values into MB we should get the memory usage, like in the users view in task manager...

Maybe i missing something, if someone know about this pls tell me.

And this is my script

Get-WmiObject Win32_Process | Sort-Object -Property privatememorysize -Descending |
Select processname, @{Name="Mem Usage(MB)";Expression={[math]::round($_.privatememorysize/ 1mb,2)}},@{Name="UserID";Expression={$_.getowner().Domain+"\"+$_.getowner().user}} | fl *

Body:
The issue is that the Win32_Process class doesn't have a property named 'privatememorysize'. Replacing that with 'privatepagecount' instead makes this work as expected.

Get-WmiObject Win32_Process | Sort-Object -Property privatepagecount -Descending |
    Select processname, @{Name="Mem Usage(MB)";Expression={[math]::round($_.privatepagecount/ 1mb,2)}},@{Name="UserID";Expression={$_.getowner().Domain+"\"+$_.getowner().user}}

I see, that is not the same, so we have the issue here where the WMI object doesn't give private working set, and other methods that do include that don't have the user. So what we can do is use Get-Process to get each process and the private working set, and use Get-WMIObject to get the user associated with each object, and then match them up. Probably best to make a hashtable from one to reference, then use that to add the property to the other object. So, let's do that!

#Get WMI Process objects
$WMIProcs = Get-WmiObject Win32_Process
#Get Get-Process object
$GPProcs = Get-Process
#Convert Get-Process objects to a hashtable for easy lookup
$GPHT = @{}
$GPProcs | ForEach-Object {$GPHT.Add($_.ID.ToString(),$_)}
#Add PrivateWorkingSet and UserID to WMI objects
$WMIProcs|ForEach-Object{
    $_ | Add-Member "Mem Usage(MB)" $([math]::round($GPHT[$_.ProcessId.ToString()].PrivateMemorySize64/1mb,2))
    $_ | Add-Member "UserID" $($_.getowner().Domain+"\"+$_.getowner().user)
}
#Output to screen
$WMIProcs | Format-Table ProcessName, "Mem Usage(MB)", UserID


问:
Getting an index to run one at a time in a for loop
I have a quick question here. Is there a way to stop a for loop and wait for one index to be done before the next one can execute? I'll try to be clear as much as possible so apologize if my question and my code aren't clear enough. Plus, I will give more explanation for whatever clues that you can give me. Much appreciate

So I try to get each id to put on my API, in order to trigger the script to be run. However, the requirement is 1 script has to be done first before the next one can be trigger.

I was messing around with setTimeOut() but looks like it doesn't give me what I need. And sorry guys, my project isn't allowed me to work with any external libraries and either async await

```<code> function sampleScriptRunning(activity){
    var ID = activity.map(function(activity){return activity.ID})
             for(var i = 0; i < ID.length; i++){
                      if(ID[i] === 'undefined'){
                        console.log('No more scripts to run')
                        return;
                            }
       Api.getActivityStatus(ID[i]).then(function(response){
   return $http.post('/proxy/api/nodejsjob/' + response.sample.sample[0].ScriptId + '/run')
       })
</code>```

答:
Here is how you can wrap you work in an async IIFE and then use the await statement to sync your async.

// This is just a dummy Async function, it will randomly return (to simulate true async issues)
function doAsync(i) {
  return new Promise((resolve, reject) => {
    setTimeout(() => { resolve(`here is - ${i}`) }, Math.random()*1000);
  });
}

// This function when called will execute an IIFE to allow us to use await.
function workSyncronously() {
  (async () => {
    for(let i=0; i<10; i++) {
      let message = await doAsync(i);
      console.log(message);
    }
  })();
}

workSyncronously();```
</div>
</div>
</p>

<p>So lets look at something where we need the results of <strong>two functions</strong> before continuing:</p>

<p>Slight tweak to the code, now we are using the result of our first call to drive the second call.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// This is just a dummy Async function, it will randomly return (to simulate true async issues)
function doAsync(i) {
  return new Promise((resolve, reject) => {
    setTimeout(() => { resolve(i*2) }, Math.random()*1000);
  });
}

// This function when called will execute an IIFE to allow us to use await.
function workSyncronously() {
  (async () => {
    for(let i=0; i<10; i++) {
      let timeTwo = await doAsync(i);
      let timeFour = await doAsync(timeTwo);
      console.log(`${i} *2=${timeTwo} *4=${timeFour}`);
    }
  })();
}

workSyncronously();</code>```

So you code might look something like this:

```<code>function sampleScriptRunning(activity) {
  const IDArray = activity.map({
    ID
  } => ID);
  const postResponses = [];

  (asnyc() => {
    for (let id of IDArray) {
      let response = await Api.getActivityStatus(id);
      let postResponse = await $http.post('/proxy/api/nodejsjob/' + response.sample.sample[0].ScriptId + '/run');
      postResponses.push(postResponse);
    }
    return postResponses;
  })();
}
</code>```

Body:
I have a quick question here. Is there a way to stop a for loop and wait for one index to be done before the next one can execute? I'll try to be clear as much as possible so apologize if my question and my code aren't clear enough. Plus, I will give more explanation for whatever clues that you can give me. Much appreciate

So I try to get each id to put on my API, in order to trigger the script to be run. However, the requirement is 1 script has to be done first before the next one can be trigger.

I was messing around with setTimeOut() but looks like it doesn't give me what I need. And sorry guys, my project isn't allowed me to work with any external libraries and either async await

 function sampleScriptRunning(activity){
    var ID = activity.map(function(activity){return activity.ID})
             for(var i = 0; i < ID.length; i++){
                      if(ID[i] === 'undefined'){
                        console.log('No more scripts to run')
                        return;
                            }
       Api.getActivityStatus(ID[i]).then(function(response){
   return $http.post('/proxy/api/nodejsjob/' + response.sample.sample[0].ScriptId + '/run')
       })

Body:
Here is how you can wrap you work in an async IIFE and then use the await statement to sync your async.

// This is just a dummy Async function, it will randomly return (to simulate true async issues)
function doAsync(i) {
  return new Promise((resolve, reject) => {
    setTimeout(() => { resolve(`here is - ${i}`) }, Math.random()*1000);
  });
}

// This function when called will execute an IIFE to allow us to use await.
function workSyncronously() {
  (async () => {
    for(let i=0; i<10; i++) {
      let message = await doAsync(i);
      console.log(message);
    }
  })();
}

workSyncronously();

So lets look at something where we need the results of two functions before continuing:

Slight tweak to the code, now we are using the result of our first call to drive the second call.

// This is just a dummy Async function, it will randomly return (to simulate true async issues)
function doAsync(i) {
  return new Promise((resolve, reject) => {
    setTimeout(() => { resolve(i*2) }, Math.random()*1000);
  });
}

// This function when called will execute an IIFE to allow us to use await.
function workSyncronously() {
  (async () => {
    for(let i=0; i<10; i++) {
      let timeTwo = await doAsync(i);
      let timeFour = await doAsync(timeTwo);
      console.log(`${i} *2=${timeTwo} *4=${timeFour}`);
    }
  })();
}

workSyncronously();

So you code might look something like this:

function sampleScriptRunning(activity) {
  const IDArray = activity.map({
    ID
  } => ID);
  const postResponses = [];

  (asnyc() => {
    for (let id of IDArray) {
      let response = await Api.getActivityStatus(id);
      let postResponse = await $http.post('/proxy/api/nodejsjob/' + response.sample.sample[0].ScriptId + '/run');
      postResponses.push(postResponse);
    }
    return postResponses;
  })();
}


问:
Using Custom font in kivy
I'm trying to create a simple kivy software and I need to use custom Arabic font for button.text.

I've included the custom font in the file and tried but that is how it looks like:

I am not sure if it is an encoding problem or I need to use something different in Kivy

here is my code :

main.py

import kivy
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.core.window import Window

class MyGrid(Widget):
    pass

class BackOffice(App):
    def build(self):
        return MyGrid()

if __name__ == '__main__':
    BackOffice().run()
```

<p><strong>backoffice.kv</strong></p>

```
#:import utils kivy.utils

<MyGrid>
    canvas.before:
        Color:
            rgba: utils.get_color_from_hex('#a1d0f4')
        Rectangle:
            pos: self.pos
            size: self.size

    GridLayout:
        cols: 1
        size: root.width, root.height
        Label:
            text: 'logo here'
        GridLayout:
            cols: 2
            Label:
                text: ' vision logo goes here'
            GridLayout:
                cols:1
                Button:
                    size: 700, 120
                    size_hint: None, None # <---
                    background_color: utils.get_color_from_hex('#0a74c4')
                    font_name: 'fonts/Shoroq-Font.ttf'
                    text: "إعدادت المستخدمين"
                    Image:
                        source: 'images/conference-256.png'
                        y: self.parent.y + 5
                        x: self.parent.x + 70

                Button:
                    text:'button'
                    background_color: utils.get_color_from_hex('#0a74c4')
                Button:
                    text:'button'
                    background_color: utils.get_color_from_hex('#0a74c4')
                Button:
                    text:'button'
                    background_color: utils.get_color_from_hex('#0a74c4')
        GridLayout:
            cols: 3
            Button:
                text: 'button'
                background_color: utils.get_color_from_hex('#ff0000')
            Button:
                text: 'button'
                background_color: utils.get_color_from_hex('#0a74c4')
            Label:
                text: 'some text here'

```

* update *
I also tried to use Arabic reshaper based on This question but it still gives the same result !! as the question was about Textinput, not text viewing in general.

答:
The solution to use arabic.reshaper and bidi.algorithm

Example

main.py

```<code>from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.properties import StringProperty
import arabic_reshaper
from bidi.algorithm import get_display

Builder.load_file("main.kv")

class MyGrid(Widget):
    bidi_text = StringProperty('')

    def __init__(self, **kwargs):
        super(MyGrid, self).__init__(**kwargs)
        reshaped_text = arabic_reshaper.reshape(u"إعدادت المستخدمين")
        self.bidi_text = get_display(reshaped_text)

class BackOffice(App):
    def build(self):
        return MyGrid()

if __name__ == '__main__':
    BackOffice().run()
</code>```

main.kv

```<code>#:import utils kivy.utils

<MyGrid>:
    canvas.before:
        Color:
            rgba: utils.get_color_from_hex('#a1d0f4')
        Rectangle:
            pos: self.pos
            size: self.size

    GridLayout:
        cols: 1
        size: root.width, root.height
        Label:
            text: 'logo here'
        GridLayout:
            cols: 2
            Label:
                text: ' vision logo goes here'
            GridLayout:
                cols:1
                Button:
                    size: 700, 120
                    size_hint: None, None # <---
                    background_color: utils.get_color_from_hex('#0a74c4')
                    font_name: 'fonts/Shoroq-Font.ttf'
                    text: root.bidi_text
                    font_size: sp(20)

                    Image:
                        source: 'images/conference-256.png'
                        y: self.parent.y + 5
                        x: self.parent.x + 70

                Button:
                    text:'button'
                    background_color: utils.get_color_from_hex('#0a74c4')
                Button:
                    text:'button'
                    background_color: utils.get_color_from_hex('#0a74c4')
                Button:
                    text:'button'
                    background_color: utils.get_color_from_hex('#0a74c4')
        GridLayout:
            cols: 3
            Button:
                text: 'button'
                background_color: utils.get_color_from_hex('#ff0000')
            Button:
                text: 'button'
                background_color: utils.get_color_from_hex('#0a74c4')
            Label:
                text: 'some text here'
</code>```

Output

Title: Using Custom font in kivy

Body:
I'm trying to create a simple kivy software and I need to use custom Arabic font for button.text.

I've included the custom font in the file and tried but that is how it looks like:

I am not sure if it is an encoding problem or I need to use something different in Kivy

here is my code :

main.py

import kivy
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.core.window import Window

class MyGrid(Widget):
    pass

class BackOffice(App):
    def build(self):
        return MyGrid()

if __name__ == '__main__':
    BackOffice().run()

backoffice.kv

#:import utils kivy.utils

<MyGrid>
    canvas.before:
        Color:
            rgba: utils.get_color_from_hex('#a1d0f4')
        Rectangle:
            pos: self.pos
            size: self.size

    GridLayout:
        cols: 1
        size: root.width, root.height
        Label:
            text: 'logo here'
        GridLayout:
            cols: 2
            Label:
                text: ' vision logo goes here'
            GridLayout:
                cols:1
                Button:
                    size: 700, 120
                    size_hint: None, None # <---
                    background_color: utils.get_color_from_hex('#0a74c4')
                    font_name: 'fonts/Shoroq-Font.ttf'
                    text: "إعدادت المستخدمين"
                    Image:
                        source: 'images/conference-256.png'
                        y: self.parent.y + 5
                        x: self.parent.x + 70

                Button:
                    text:'button'
                    background_color: utils.get_color_from_hex('#0a74c4')
                Button:
                    text:'button'
                    background_color: utils.get_color_from_hex('#0a74c4')
                Button:
                    text:'button'
                    background_color: utils.get_color_from_hex('#0a74c4')
        GridLayout:
            cols: 3
            Button:
                text: 'button'
                background_color: utils.get_color_from_hex('#ff0000')
            Button:
                text: 'button'
                background_color: utils.get_color_from_hex('#0a74c4')
            Label:
                text: 'some text here'

* update *
I also tried to use Arabic reshaper based on This question but it still gives the same result !! as the question was about Textinput, not text viewing in general.

Body:
The solution to use arabic.reshaper and bidi.algorithm

Example

main.py

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.properties import StringProperty
import arabic_reshaper
from bidi.algorithm import get_display

Builder.load_file("main.kv")

class MyGrid(Widget):
    bidi_text = StringProperty('')

    def __init__(self, **kwargs):
        super(MyGrid, self).__init__(**kwargs)
        reshaped_text = arabic_reshaper.reshape(u"إعدادت المستخدمين")
        self.bidi_text = get_display(reshaped_text)

class BackOffice(App):
    def build(self):
        return MyGrid()

if __name__ == '__main__':
    BackOffice().run()

main.kv

#:import utils kivy.utils

<MyGrid>:
    canvas.before:
        Color:
            rgba: utils.get_color_from_hex('#a1d0f4')
        Rectangle:
            pos: self.pos
            size: self.size

    GridLayout:
        cols: 1
        size: root.width, root.height
        Label:
            text: 'logo here'
        GridLayout:
            cols: 2
            Label:
                text: ' vision logo goes here'
            GridLayout:
                cols:1
                Button:
                    size: 700, 120
                    size_hint: None, None # <---
                    background_color: utils.get_color_from_hex('#0a74c4')
                    font_name: 'fonts/Shoroq-Font.ttf'
                    text: root.bidi_text
                    font_size: sp(20)

                    Image:
                        source: 'images/conference-256.png'
                        y: self.parent.y + 5
                        x: self.parent.x + 70

                Button:
                    text:'button'
                    background_color: utils.get_color_from_hex('#0a74c4')
                Button:
                    text:'button'
                    background_color: utils.get_color_from_hex('#0a74c4')
                Button:
                    text:'button'
                    background_color: utils.get_color_from_hex('#0a74c4')
        GridLayout:
            cols: 3
            Button:
                text: 'button'
                background_color: utils.get_color_from_hex('#ff0000')
            Button:
                text: 'button'
                background_color: utils.get_color_from_hex('#0a74c4')
            Label:
                text: 'some text here'

Output


问:
Pattern matching problem with Prolog
EDIT: See my answer below for why I am a fool. There is still a riddle in this that I would love to have answered though.

I've been stuck on this for far too long. I'm trying to print out a sudoku solution in a nice looking grid.

I think I'm running into problems because I don't understand some key part of how pattern matching works in Prolog.

Without further ado, my code:

```<code>prettier_print([]).
prettier_print([Puzzle]) :- prettier_print(0, [Puzzle]).

prettier_print(0, Puzzle) :-
    writeln('┌───────┬───────┬───────┐'),
    prettier_print(1, Puzzle).
prettier_print(4, Puzzle) :-
    writeln('│───────┼───────┼───────│'),
    prettier_print(5, Puzzle).
prettier_print(8, Puzzle) :-
    writeln('│───────┼───────┼───────│'),
    prettier_print(9, Puzzle).
prettier_print(12, []) :-
    writeln('└───────┴───────┴───────┘').

prettier_print(N, [Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9 | Puzzle]) :-
    member(N, [1,2,3,5,6,7,9,10,11]),  % tried this when the line below did not work
    % N =\= 0, N =\= 4, N =\= 8, N =\= 13,

    format('│ ~d ~d ~d │ ~d ~d ~d │ ~d ~d ~d │~n', [Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9]),
    succ(N, N1),
    prettier_print(N1, Puzzle).
</code>```

Here is the call:

```<code>prettier_print(0, [1,2,3,4,5,6,7,8,9,
                   2,2,3,4,5,6,7,8,9,
                   3,2,3,4,5,6,7,8,9,
                   4,2,3,4,5,6,7,8,9,
                   5,2,3,4,5,6,7,8,9,
                   6,2,3,4,5,6,7,8,9,
                   7,2,3,4,5,6,7,8,9,
                   8,2,3,4,5,6,7,8,9,
                   9,2,3,4,5,6,7,8,9]).
</code>```

And here is the output:

```<code>┌───────┬───────┬───────┐
│ 1 2 3 │ 4 5 6 │ 7 8 9 │
│ 2 2 3 │ 4 5 6 │ 7 8 9 │
│ 3 2 3 │ 4 5 6 │ 7 8 9 │
│───────┼───────┼───────│
│ 4 2 3 │ 4 5 6 │ 7 8 9 │
│ 5 2 3 │ 4 5 6 │ 7 8 9 │
│ 6 2 3 │ 4 5 6 │ 7 8 9 │
│───────┼───────┼───────│
│ 7 2 3 │ 4 5 6 │ 7 8 9 │
│ 8 2 3 │ 4 5 6 │ 7 8 9 │
│ 9 2 3 │ 4 5 6 │ 7 8 9 │
└───────┴───────┴───────┘
true ;
false.
</code>```

The problem is it doesn't JUST return with true, I have to press ;, and then it returns false. This in turn means that my prettier_print/1 rule doesn't work properly.

I think I know enough to figure out that this means:

Prolog is backtracking and trying another interpretation of my rules (seeing if there is anything else it can unify with, if I'm understanding my terms correctly). This finds one other thing to unify with that, but that fails immediately. Is that right?

I want there to be only one possible interpretation. How can I fix my function to mean that?

Thank you for any help, this has me feeling like such a fool!

答:
It is "returning" true, then false, because you are forcing it to backtrack with ;. Since there's only one solution, backtracking fails.

This behavior only occurs in interactive Prolog interpreters; it you were to compile the program or run it in a non-interactive interpreter, it would just print the result and not "return" anything. This is somewhat similar to the behavior of, e.g., the Python interpreter

```<code>>>> 'foo'
'foo'
</code>```

which echoes the value of the last expression entered, but only in interactive mode. A script wouldn't print anything unless you put in print statements.

If you don't want to see the false message then either don't backtrack, i.e. press Enter instead of ;, or use the metapredicate once/1:

```<code>?- member(X,[1,2,3]).
X = 1 ;
X = 2 .    % ENTER pressed here

?- once(member(X,[1,2,3])).
X = 1.

?-
</code>```

but don't just do that anywhere in a program, as it changes the program's semantics.

ContentLicense: CC BY-SA 3.0

Title: Pattern matching problem with Prolog

Body:
EDIT: See my answer below for why I am a fool. There is still a riddle in this that I would love to have answered though.

I've been stuck on this for far too long. I'm trying to print out a sudoku solution in a nice looking grid.

I think I'm running into problems because I don't understand some key part of how pattern matching works in Prolog.

Without further ado, my code:

prettier_print([]).
prettier_print([Puzzle]) :- prettier_print(0, [Puzzle]).

prettier_print(0, Puzzle) :-
    writeln('┌───────┬───────┬───────┐'),
    prettier_print(1, Puzzle).
prettier_print(4, Puzzle) :-
    writeln('│───────┼───────┼───────│'),
    prettier_print(5, Puzzle).
prettier_print(8, Puzzle) :-
    writeln('│───────┼───────┼───────│'),
    prettier_print(9, Puzzle).
prettier_print(12, []) :-
    writeln('└───────┴───────┴───────┘').

prettier_print(N, [Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9 | Puzzle]) :-
    member(N, [1,2,3,5,6,7,9,10,11]),  % tried this when the line below did not work
    % N =\= 0, N =\= 4, N =\= 8, N =\= 13,

    format('│ ~d ~d ~d │ ~d ~d ~d │ ~d ~d ~d │~n', [Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9]),
    succ(N, N1),
    prettier_print(N1, Puzzle).

Here is the call:

prettier_print(0, [1,2,3,4,5,6,7,8,9,
                   2,2,3,4,5,6,7,8,9,
                   3,2,3,4,5,6,7,8,9,
                   4,2,3,4,5,6,7,8,9,
                   5,2,3,4,5,6,7,8,9,
                   6,2,3,4,5,6,7,8,9,
                   7,2,3,4,5,6,7,8,9,
                   8,2,3,4,5,6,7,8,9,
                   9,2,3,4,5,6,7,8,9]).

And here is the output:

┌───────┬───────┬───────┐
│ 1 2 3 │ 4 5 6 │ 7 8 9 │
│ 2 2 3 │ 4 5 6 │ 7 8 9 │
│ 3 2 3 │ 4 5 6 │ 7 8 9 │
│───────┼───────┼───────│
│ 4 2 3 │ 4 5 6 │ 7 8 9 │
│ 5 2 3 │ 4 5 6 │ 7 8 9 │
│ 6 2 3 │ 4 5 6 │ 7 8 9 │
│───────┼───────┼───────│
│ 7 2 3 │ 4 5 6 │ 7 8 9 │
│ 8 2 3 │ 4 5 6 │ 7 8 9 │
│ 9 2 3 │ 4 5 6 │ 7 8 9 │
└───────┴───────┴───────┘
true ;
false.

The problem is it doesn't JUST return with true, I have to press ;, and then it returns false. This in turn means that my prettier_print/1 rule doesn't work properly.

I think I know enough to figure out that this means:

Prolog is backtracking and trying another interpretation of my rules (seeing if there is anything else it can unify with, if I'm understanding my terms correctly). This finds one other thing to unify with that, but that fails immediately. Is that right?

I want there to be only one possible interpretation. How can I fix my function to mean that?

Thank you for any help, this has me feeling like such a fool!

Body:
It is "returning" true, then false, because you are forcing it to backtrack with ;. Since there's only one solution, backtracking fails.

This behavior only occurs in interactive Prolog interpreters; it you were to compile the program or run it in a non-interactive interpreter, it would just print the result and not "return" anything. This is somewhat similar to the behavior of, e.g., the Python interpreter

>>> 'foo'
'foo'

which echoes the value of the last expression entered, but only in interactive mode. A script wouldn't print anything unless you put in print statements.

If you don't want to see the false message then either don't backtrack, i.e. press Enter instead of ;, or use the metapredicate once/1:

?- member(X,[1,2,3]).
X = 1 ;
X = 2 .    % ENTER pressed here

?- once(member(X,[1,2,3])).
X = 1.

?-

but don't just do that anywhere in a program, as it changes the program's semantics.


问:
Apply style with setTimeout()
I created the next code:

  setTimeout(function () {
        var dot = document.querySelectorAll('.dot');
        for (var i=0;i<dot.length;i++) {
            dot[i].style.backgroundColor = 'blue';
        }
    },2000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code> .container{
        display: flex;
        justify-content: space-around;
    }
   .dot{
       background-color: red;
       width: 20px;
       height: 20px;
       border-radius: 50%;
   }</code>```

```

This code apply background-color for each dot at the same time after 2 seconds, but i want to apply the style for each dot separately. Fo example: after 2 seconds to apply the style for first dot, then after 2 seconds to apply the style for second dot, and so on. Who has a solution?

答:
Try using setInterval, seems to be perfect for your case.</p>

```<code>    var dotNumber = 0;
    var myVar = setInterval(() => {
        var dot = document.querySelectorAll('.dot');
        dot[dotNumber].style.backgroundColor = 'blue';

        dotNumber +=1;

        if (dotNumber >= dot.length){
           clearInterval(myVar);
        }
     }, 2000);
</code>```

Title: Apply style with setTimeout()

Body:
I created the next code:

  setTimeout(function () {
        var dot = document.querySelectorAll('.dot');
        for (var i=0;i<dot.length;i++) {
            dot[i].style.backgroundColor = 'blue';
        }
    },2000);

 .container{
        display: flex;
        justify-content: space-around;
    }
   .dot{
       background-color: red;
       width: 20px;
       height: 20px;
       border-radius: 50%;
   }

This code apply background-color for each dot at the same time after 2 seconds, but i want to apply the style for each dot separately. Fo example: after 2 seconds to apply the style for first dot, then after 2 seconds to apply the style for second dot, and so on. Who has a solution?

Body:
Try using setInterval, seems to be perfect for your case.

    var dotNumber = 0;
    var myVar = setInterval(() => {
        var dot = document.querySelectorAll('.dot');
        dot[dotNumber].style.backgroundColor = 'blue';

        dotNumber +=1;

        if (dotNumber >= dot.length){
           clearInterval(myVar);
        }
     }, 2000);


问:
How to add a button to every row in Material-UI?
I'm creating a virtualized table in react using Material-UI. In every last column of every row, there should be a button to extend that particular row. I understand how to do the extending of a row, but I have not managed to figure out how to add the buttons correctly.

I'm trying to integrate this in the example of virtualized tables provided by the documentation, the exact code is given below from: https://material-ui.com/components/tables/. However, as this example provides one generalized function to create all of the data cells and because I don't think I can access the index of a particular row, I cannot figure out how to add the actual buttons.

```<code>import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { withStyles } from '@material-ui/core/styles';
import TableCell from '@material-ui/core/TableCell';
import Paper from '@material-ui/core/Paper';
import { AutoSizer, Column, Table } from 'react-virtualized';

const styles = theme => ({
  flexContainer: {
    display: 'flex',
    alignItems: 'center',
    boxSizing: 'border-box',
  },
  tableRow: {
    cursor: 'pointer',
  },
  tableRowHover: {
    '&:hover': {
      backgroundColor: theme.palette.grey[200],
    },
  },
  tableCell: {
    flex: 1,
  },
  noClick: {
    cursor: 'initial',
  },
});

class MuiVirtualizedTable extends React.PureComponent {
  static defaultProps = {
    headerHeight: 48,
    rowHeight: 48,
  };

  getRowClassName = ({ index }) => {
    const { classes, onRowClick } = this.props;

    return clsx(classes.tableRow, classes.flexContainer, {
      [classes.tableRowHover]: index !== -1 && onRowClick != null,
    });
  };

  cellRenderer = ({ cellData, columnIndex }) => {
    const { columns, classes, rowHeight, onRowClick } = this.props;
    return (
      <TableCell
        component="div"
        className={clsx(classes.tableCell, classes.flexContainer, {
          [classes.noClick]: onRowClick == null,
        })}
        variant="body"
        style={{ height: rowHeight }}
        align={(columnIndex != null && columns[columnIndex].numeric) || false ? 'right' : 'left'}
      >
        {cellData}
      </TableCell>
    );
  };

  headerRenderer = ({ label, columnIndex }) => {
    const { headerHeight, columns, classes } = this.props;

    return (
      <TableCell
        component="div"
        className={clsx(classes.tableCell, classes.flexContainer, classes.noClick)}
        variant="head"
        style={{ height: headerHeight }}
        align={columns[columnIndex].numeric || false ? 'right' : 'left'}
      >
        <span>{label}</span>
      </TableCell>
    );
  };

  render() {
    const { classes, columns, ...tableProps } = this.props;
    return (
      <AutoSizer>
        {({ height, width }) => (
          <Table height={height} width={width} {...tableProps} rowClassName={this.getRowClassName}>
            {columns.map(({ dataKey, ...other }, index) => {
              return (
                <Column
                  key={dataKey}
                  headerRenderer={headerProps =>
                    this.headerRenderer({
                      ...headerProps,
                      columnIndex: index,
                    })
                  }
                  className={classes.flexContainer}
                  cellRenderer={this.cellRenderer}
                  dataKey={dataKey}
                  {...other}
                />
              );
            })}
          </Table>
        )}
      </AutoSizer>
    );
  }
}

MuiVirtualizedTable.propTypes = {
  classes: PropTypes.object.isRequired,
  columns: PropTypes.arrayOf(PropTypes.object).isRequired,
  headerHeight: PropTypes.number,
  onRowClick: PropTypes.func,
  rowHeight: PropTypes.number,
};

const VirtualizedTable = withStyles(styles)(MuiVirtualizedTable);

// ---

const sample = [
  ['Frozen yoghurt', 159, 6.0, 24, 4.0],
  ['Ice cream sandwich', 237, 9.0, 37, 4.3],
  ['Eclair', 262, 16.0, 24, 6.0],
  ['Cupcake', 305, 3.7, 67, 4.3],
  ['Gingerbread', 356, 16.0, 49, 3.9],
];

function createData(id, dessert, calories, fat, carbs, protein) {
  return { id, dessert, calories, fat, carbs, protein };
}

const rows = [];

for (let i = 0; i < 200; i += 1) {
  const randomSelection = sample[Math.floor(Math.random() * sample.length)];
  rows.push(createData(i, ...randomSelection));
}

function ReactVirtualizedTable() {
  return (
    <Paper style={{ height: 400, width: '100%' }}>
      <VirtualizedTable
        rowCount={rows.length}
        rowGetter={({ index }) => rows[index]}
        columns={[
          {
            width: 200,
            label: 'Dessert',
            dataKey: 'dessert',
          },
          {
            width: 120,
            label: 'Calories\u00A0(g)',
            dataKey: 'calories',
            numeric: true,
          },
          {
            width: 120,
            label: 'Fat\u00A0(g)',
            dataKey: 'fat',
            numeric: true,
          },
          {
            width: 120,
            label: 'Carbs\u00A0(g)',
            dataKey: 'carbs',
            numeric: true,
          },
          {
            width: 120,
            label: 'Protein\u00A0(g)',
            dataKey: 'protein',
            numeric: true,
          },
        ]}
      />
    </Paper>
  );
}

export default ReactVirtualizedTable;
</code>```

答: Take a look at react-virtualized tables it supports a rowRenderer prop. You'll probably also need to add in an empty column in the header or it'll be misaligned.</p>

Body:
I'm creating a virtualized table in react using Material-UI. In every last column of every row, there should be a button to extend that particular row. I understand how to do the extending of a row, but I have not managed to figure out how to add the buttons correctly.

I'm trying to integrate this in the example of virtualized tables provided by the documentation, the exact code is given below from: https://material-ui.com/components/tables/. However, as this example provides one generalized function to create all of the data cells and because I don't think I can access the index of a particular row, I cannot figure out how to add the actual buttons.

import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { withStyles } from '@material-ui/core/styles';
import TableCell from '@material-ui/core/TableCell';
import Paper from '@material-ui/core/Paper';
import { AutoSizer, Column, Table } from 'react-virtualized';

const styles = theme => ({
  flexContainer: {
    display: 'flex',
    alignItems: 'center',
    boxSizing: 'border-box',
  },
  tableRow: {
    cursor: 'pointer',
  },
  tableRowHover: {
    '&:hover': {
      backgroundColor: theme.palette.grey[200],
    },
  },
  tableCell: {
    flex: 1,
  },
  noClick: {
    cursor: 'initial',
  },
});

class MuiVirtualizedTable extends React.PureComponent {
  static defaultProps = {
    headerHeight: 48,
    rowHeight: 48,
  };

  getRowClassName = ({ index }) => {
    const { classes, onRowClick } = this.props;

    return clsx(classes.tableRow, classes.flexContainer, {
      [classes.tableRowHover]: index !== -1 && onRowClick != null,
    });
  };

  cellRenderer = ({ cellData, columnIndex }) => {
    const { columns, classes, rowHeight, onRowClick } = this.props;
    return (
      <TableCell
        component="div"
        className={clsx(classes.tableCell, classes.flexContainer, {
          [classes.noClick]: onRowClick == null,
        })}
        variant="body"
        style={{ height: rowHeight }}
        align={(columnIndex != null && columns[columnIndex].numeric) || false ? 'right' : 'left'}
      >
        {cellData}
      </TableCell>
    );
  };

  headerRenderer = ({ label, columnIndex }) => {
    const { headerHeight, columns, classes } = this.props;

    return (
      <TableCell
        component="div"
        className={clsx(classes.tableCell, classes.flexContainer, classes.noClick)}
        variant="head"
        style={{ height: headerHeight }}
        align={columns[columnIndex].numeric || false ? 'right' : 'left'}
      >
        {label}
      </TableCell>
    );
  };

  render() {
    const { classes, columns, ...tableProps } = this.props;
    return (
      <AutoSizer>
        {({ height, width }) => (

            {columns.map(({ dataKey, ...other }, index) => {
              return (
                <Column
                  key={dataKey}
                  headerRenderer={headerProps =>
                    this.headerRenderer({
                      ...headerProps,
                      columnIndex: index,
                    })
                  }
                  className={classes.flexContainer}
                  cellRenderer={this.cellRenderer}
                  dataKey={dataKey}
                  {...other}
                />
              );
            })}

        )}
      </AutoSizer>
    );
  }
}

MuiVirtualizedTable.propTypes = {
  classes: PropTypes.object.isRequired,
  columns: PropTypes.arrayOf(PropTypes.object).isRequired,
  headerHeight: PropTypes.number,
  onRowClick: PropTypes.func,
  rowHeight: PropTypes.number,
};

const VirtualizedTable = withStyles(styles)(MuiVirtualizedTable);

// ---

const sample = [
  ['Frozen yoghurt', 159, 6.0, 24, 4.0],
  ['Ice cream sandwich', 237, 9.0, 37, 4.3],
  ['Eclair', 262, 16.0, 24, 6.0],
  ['Cupcake', 305, 3.7, 67, 4.3],
  ['Gingerbread', 356, 16.0, 49, 3.9],
];

function createData(id, dessert, calories, fat, carbs, protein) {
  return { id, dessert, calories, fat, carbs, protein };
}

const rows = [];

for (let i = 0; i < 200; i += 1) {
  const randomSelection = sample[Math.floor(Math.random() * sample.length)];
  rows.push(createData(i, ...randomSelection));
}

function ReactVirtualizedTable() {
  return (
    <Paper style={{ height: 400, width: '100%' }}>
      <VirtualizedTable
        rowCount={rows.length}
        rowGetter={({ index }) => rows[index]}
        columns={[
          {
            width: 200,
            label: 'Dessert',
            dataKey: 'dessert',
          },
          {
            width: 120,
            label: 'Calories\u00A0(g)',
            dataKey: 'calories',
            numeric: true,
          },
          {
            width: 120,
            label: 'Fat\u00A0(g)',
            dataKey: 'fat',
            numeric: true,
          },
          {
            width: 120,
            label: 'Carbs\u00A0(g)',
            dataKey: 'carbs',
            numeric: true,
          },
          {
            width: 120,
            label: 'Protein\u00A0(g)',
            dataKey: 'protein',
            numeric: true,
          },
        ]}
      />
    </Paper>
  );
}

export default ReactVirtualizedTable;


问:
How to create a model whose ID is the other model's foreign key
I'm new to loopback and as far as I understood from documentations, you can't edit the built-in User model. So to extend that with address and other profile details, I've created a Profile model (based on PersistedModel).

Now I want the id of this model be equal to the foreignKey of User, so when I have the instance of User, I can get the profile simply by id.
This way I don't need to find the Profile instance by querying something like email. hence I don't need to have email in both models.

My question is:
How can I create the Profile model, and create a relation from User to Profile's id.

答:
Extend the user model and add as many properties you wish:

{
  "name": "Profile",
  "plural": "profiles",
  "base": "User",
  ...
}```


问:
How to fetch data after n interval of time
I have data stored of every 1 seconds in sql server, i need to fetch data of every 1 or 2 minute interval not of seconds,how can I get data every 2 minutes based using SQL?

答:
```<code>select *
from
(
    select *,
       datepart(minute, yourDate) mn,
       row_number() over(partition by datepart(minute, yourDate) order by yourDate) rn
    from yourTable
) x
where (mn % 2) = 0
    and rn = 1
</code>```


问:
Line Animation with QPropertyAnimation
Trying to animate a line growing from nothing to a (0,0) to (200, 200) line with PyQt5 and using QPropertyAnimation. I already read a lot of documentation about Qt and tried several samples, but I just cannot get this to work. This is the code I have now:

```<code>from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QPainter, QPixmap, QPainterPath
from PyQt5.QtCore import QObject, QPointF, QPropertyAnimation, pyqtProperty
from PyQt5.QtCore import QLineF
import sys

class Sample(QWidget):

    l1 = QLineF(QPointF(), QPointF())

    def __init__(self):
        super().__init__()

        self.initView()
        self.initAnimation()

    def initView(self):
        self.show()

    def initAnimation(self):
        self.anim = QPropertyAnimation(self.l1, b'geometry')
        self.anim.setDuration(7000)
        self.anim.setStartValue(QPointF(0, 0))
        self.anim.setEndValue(QPointF(200, 200))
        self.anim.start()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Sample()
    sys.exit(app.exec_())
</code>```

Not posting all previous attemps, each one fails with a different error. I got a fade out animation on a widget to work, and a picture following a path, but I can seem to make a simple line drawing work. I was hoping to achieve something like this:

Codepen example

Qt documentation is huge and it seems there are several ways to achieve this, painter and timer, animation, variant animation, but I am not very familiar with C++ and the translation to Python is not always easy. Also samples are not that easy to find.

Am I missing something obvious?

Thanks!

For the record, this is what I achieved so far but as soon as I un-comment the QPropertyAnimation creation, app does not launch. Anyway I was still far from the result in the accepted answer.

```<code>from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys

class MyLine(QGraphicsLineItem, QObject):
    def __init__(self):
        super().__init__()

    def _set_start(self, point):
        self.setLine(point.x(), point.y(), self.line().p2().x(), self.line().p2().y())

    def _set_end(self, point):
        self.setLine(self.line().p1().x(), self.line().p1().y(), point.x(), point.y())

    start = pyqtProperty(QPointF, fset=_set_start)
    end = pyqtProperty(QPointF, fset=_set_end)

class Example(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        hbox = QHBoxLayout(self)

        self.button = QPushButton("Start", self)
        self.button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        hbox.addWidget(self.button)

        hbox.addSpacing(40)

        self.line = MyLine()
        self.line.setLine(0, 0, 10, 10)
        scene = QGraphicsScene()
        scene.addItem(self.line)
        view = QGraphicsView(scene)
        hbox.addWidget(view)

        self.anim = QPropertyAnimation(self.line, b"end") # crash without error here
        # self.anim.setDuration(2500)
        # self.anim.setLoopCount(1)
        # self.anim.setStartValue(QPointF(10, 10))
        # self.anim.setEndValue(QPointF(200, 200))
        # self.button.clicked.connect(self.anim.start)

        self.setGeometry(300, 300, 380, 250)
        self.setWindowTitle('Color anim')
        self.show()

if __name__ == "__main__":

    app = QApplication([])
    ex = Example()
    ex.show()
    app.exec_()
</code>```

答:
You have to use QGraphicsView, QGraphicsScene with QGraphicsLineItem as I show below:

from PyQt5 import QtCore, QtGui, QtWidgets

class LineAnimation(QtCore.QObject):
    def __init__(self, parent=None):
        super(LineAnimation, self).__init__(parent)
        self.m_line = QtCore.QLineF()
        self.m_item = QtWidgets.QGraphicsLineItem()
        self.m_item.setLine(self.m_line)
        self.m_item.setPen(
            QtGui.QPen(
                QtGui.QColor("salmon"),
                10,
                QtCore.Qt.SolidLine,
                QtCore.Qt.SquareCap,
                QtCore.Qt.RoundJoin,
            )
        )

        self.m_animation = QtCore.QPropertyAnimation(
            self,
            b"p2",
            parent=self,
            startValue=QtCore.QPointF(0, 0),
            endValue=QtCore.QPointF(200, 200),
            duration=5 * 1000,
        )
        self.m_animation.start()

    def p1(self):
        return self.m_line.p1()

    def setP1(self, p1):
        self.m_line.setP1(p1)
        self.m_item.setLine(self.m_line)

    def p2(self):
        return self.m_line.p2()

    def setP2(self, p2):
        self.m_line.setP2(p2)
        self.m_item.setLine(self.m_line)

    p1 = QtCore.pyqtProperty(QtCore.QPointF, fget=p1, fset=setP1)
    p2 = QtCore.pyqtProperty(QtCore.QPointF, fget=p2, fset=setP2)

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        scene = QtWidgets.QGraphicsScene(self)
        view = QtWidgets.QGraphicsView(
            scene, alignment=QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop
        )
        self.setCentralWidget(view)

        line_animation = LineAnimation(self)
        scene.addItem(line_animation.m_item)

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())
```

Title: Line Animation with QPropertyAnimation

Body:
Trying to animate a line growing from nothing to a (0,0) to (200, 200) line with PyQt5 and using QPropertyAnimation. I already read a lot of documentation about Qt and tried several samples, but I just cannot get this to work. This is the code I have now:

from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QPainter, QPixmap, QPainterPath
from PyQt5.QtCore import QObject, QPointF, QPropertyAnimation, pyqtProperty
from PyQt5.QtCore import QLineF
import sys

class Sample(QWidget):

    l1 = QLineF(QPointF(), QPointF())

    def __init__(self):
        super().__init__()

        self.initView()
        self.initAnimation()

    def initView(self):
        self.show()

    def initAnimation(self):
        self.anim = QPropertyAnimation(self.l1, b'geometry')
        self.anim.setDuration(7000)
        self.anim.setStartValue(QPointF(0, 0))
        self.anim.setEndValue(QPointF(200, 200))
        self.anim.start()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Sample()
    sys.exit(app.exec_())

Not posting all previous attemps, each one fails with a different error. I got a fade out animation on a widget to work, and a picture following a path, but I can seem to make a simple line drawing work. I was hoping to achieve something like this:

Codepen example

Qt documentation is huge and it seems there are several ways to achieve this, painter and timer, animation, variant animation, but I am not very familiar with C++ and the translation to Python is not always easy. Also samples are not that easy to find.

Am I missing something obvious?

Thanks!

For the record, this is what I achieved so far but as soon as I un-comment the QPropertyAnimation creation, app does not launch. Anyway I was still far from the result in the accepted answer.

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys

class MyLine(QGraphicsLineItem, QObject):
    def __init__(self):
        super().__init__()

    def _set_start(self, point):
        self.setLine(point.x(), point.y(), self.line().p2().x(), self.line().p2().y())

    def _set_end(self, point):
        self.setLine(self.line().p1().x(), self.line().p1().y(), point.x(), point.y())

    start = pyqtProperty(QPointF, fset=_set_start)
    end = pyqtProperty(QPointF, fset=_set_end)

class Example(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        hbox = QHBoxLayout(self)

        self.button = QPushButton("Start", self)
        self.button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        hbox.addWidget(self.button)

        hbox.addSpacing(40)

        self.line = MyLine()
        self.line.setLine(0, 0, 10, 10)
        scene = QGraphicsScene()
        scene.addItem(self.line)
        view = QGraphicsView(scene)
        hbox.addWidget(view)

        self.anim = QPropertyAnimation(self.line, b"end") # crash without error here
        # self.anim.setDuration(2500)
        # self.anim.setLoopCount(1)
        # self.anim.setStartValue(QPointF(10, 10))
        # self.anim.setEndValue(QPointF(200, 200))
        # self.button.clicked.connect(self.anim.start)

        self.setGeometry(300, 300, 380, 250)
        self.setWindowTitle('Color anim')
        self.show()

if __name__ == "__main__":

    app = QApplication([])
    ex = Example()
    ex.show()
    app.exec_()


问:
Error while importing one file into another in Node.JS
I am using import while importing some functions from my practice.js file into different.js file.

```<code>practice.js file:-

function sum(x,y){
    return x+y;
}

const pi = 3.14;

module.exports = {
    sum : sum,
    pi:pi
};
</code>```

different.js file:-

```<code>import {sum,pi} from "./practice.js";

console.log("2 pie: "+sum(pi,pi));
</code>```

Now when I am using require, the output is proper and no error is given.
When I am using import, there is this following error:-

```<code>SyntaxError: Unexpected token {
    at Module._compile (internal/modules/cjs/loader.js:749:23)
    at Object.Module._extensions..js
(internal/modules/cjs/loader.js:816:10)
    at Module.load (internal/modules/cjs/loader.js:672:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:612:12)
    at Function.Module._load (internal/modules/cjs/loader.js:604:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:868:12)
    at internal/main/run_main_module.js:21:11
</code>```

I have asked my colleagues and they told me that this is about ES6 and Babel is not configured in your system.

But I am not sure how to proceed with this. Can anybody please help me how to do it?

答:
Rename your main file (different.js) to different.mjs.
Rename your practice.js file to practice.mjs and make it look like this:

```<code>function sum(x, y) {
    return x + y;
}

const pi = 3.14;

export {sum, pi};
</code>```

Then run node --experimental-modules different.mjs to run Node with it's experimental module loader.

You can read more here

Body:
I am using import while importing some functions from my practice.js file into different.js file.

practice.js file:-

function sum(x,y){
    return x+y;
}

const pi = 3.14;

module.exports = {
    sum : sum,
    pi:pi
};

different.js file:-

import {sum,pi} from "./practice.js";

console.log("2 pie: "+sum(pi,pi));

Now when I am using require, the output is proper and no error is given.
When I am using import, there is this following error:-

SyntaxError: Unexpected token {
    at Module._compile (internal/modules/cjs/loader.js:749:23)
    at Object.Module._extensions..js
(internal/modules/cjs/loader.js:816:10)
    at Module.load (internal/modules/cjs/loader.js:672:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:612:12)
    at Function.Module._load (internal/modules/cjs/loader.js:604:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:868:12)
    at internal/main/run_main_module.js:21:11

I have asked my colleagues and they told me that this is about ES6 and Babel is not configured in your system.

But I am not sure how to proceed with this. Can anybody please help me how to do it?

Body:
Rename your main file (different.js) to different.mjs.
Rename your practice.js file to practice.mjs and make it look like this:

function sum(x, y) {
    return x + y;
}

const pi = 3.14;

export {sum, pi};

Then run node --experimental-modules different.mjs to run Node with it's experimental module loader.

You can read more here


问:
How should I use DispatchGroup for two url requests?
I am using DispatchGroup for two url requests but didn't get any data. I tried each method separately without DispatchGroup, it works fine. So the problem is that I didn't use DispatchGroup correctly. Please help.</p>

```<code>    let buildingManager =  BuildingManager()
    let anaManager = AnalyticsManager()
    let group = DispatchGroup()
    let queue = DispatchQueue.global(qos: .background)

    queue.async(group: group) {
        buildingManager.getBuildingInfos(completion: { [weak self] (buildings, success) in
            guard let self = self else {return}

            if success {
                self.buildings = buildings
                print("success")
            } else {
                print("No building infos")
            }
        })
    }

    queue.async(group: group) {
        anaManager.getAnaData(completion: {[weak self] (anaData, success) in
            guard let self = self else {return}

            if success {
                self.analyticsData = anaData
                print("success")
            } else {
                print("No analytics data")
            }
        })
    }

        group.notify(queue: DispatchQueue.main) { [weak self] in
            self?.dataTableView.reloadData()
        }
</code>```

答:
I would refactor just a bit to explicitly enter and leave your group as needed. The use of queue.async(group:) should only be used when the code in the block is not async already.

```<code>let buildingManager =  BuildingManager()
let anaManager = AnalyticsManager()
let group = DispatchGroup()
let queue = DispatchQueue.global(qos: .background)

queue.async {
    group.enter()
    buildingManager.getBuildingInfos(completion: { [weak self] (buildings, success) in
        defer { group.leave() }

        guard let self = self else {return}

        if success {
            self.buildings = buildings
            print("success")
        } else {
            print("No building infos")
        }
    })

    group.enter()
    anaManager.getAnaData(completion: {[weak self] (anaData, success) in
        defer { group.leave() }

        guard let self = self else {return}

        if success {
            self.analyticsData = anaData
            print("success")
        } else {
            print("No analytics data")
        }
    })

    group.notify(queue: DispatchQueue.main) { [weak self] in
        self?.dataTableView.reloadData()
    }
}
</code>```

Body:
I am using DispatchGroup for two url requests but didn't get any data. I tried each method separately without DispatchGroup, it works fine. So the problem is that I didn't use DispatchGroup correctly. Please help.

    let buildingManager =  BuildingManager()
    let anaManager = AnalyticsManager()
    let group = DispatchGroup()
    let queue = DispatchQueue.global(qos: .background)

    queue.async(group: group) {
        buildingManager.getBuildingInfos(completion: { [weak self] (buildings, success) in
            guard let self = self else {return}

            if success {
                self.buildings = buildings
                print("success")
            } else {
                print("No building infos")
            }
        })
    }

    queue.async(group: group) {
        anaManager.getAnaData(completion: {[weak self] (anaData, success) in
            guard let self = self else {return}

            if success {
                self.analyticsData = anaData
                print("success")
            } else {
                print("No analytics data")
            }
        })
    }

        group.notify(queue: DispatchQueue.main) { [weak self] in
            self?.dataTableView.reloadData()
        }

Body:
I would refactor just a bit to explicitly enter and leave your group as needed. The use of queue.async(group:) should only be used when the code in the block is not async already.

let buildingManager =  BuildingManager()
let anaManager = AnalyticsManager()
let group = DispatchGroup()
let queue = DispatchQueue.global(qos: .background)

queue.async {
    group.enter()
    buildingManager.getBuildingInfos(completion: { [weak self] (buildings, success) in
        defer { group.leave() }

        guard let self = self else {return}

        if success {
            self.buildings = buildings
            print("success")
        } else {
            print("No building infos")
        }
    })

    group.enter()
    anaManager.getAnaData(completion: {[weak self] (anaData, success) in
        defer { group.leave() }

        guard let self = self else {return}

        if success {
            self.analyticsData = anaData
            print("success")
        } else {
            print("No analytics data")
        }
    })

    group.notify(queue: DispatchQueue.main) { [weak self] in
        self?.dataTableView.reloadData()
    }
}


问:
overriding the equals method in java
"Let’s implement the equals method for a Stamp class.
You need to override the equals method of the Object class.
Now you have a slight problem.
The Object class knows nothing about stamps, so
it declares the otherObject
parameter variable of the equals method to have the type
Object. When overriding the method, you are not allowed to change the type of the parameter variable."

Here, it says that we are not allowed to change type of the parameter variable.
However, when I use the below code, it gives me the correct result.

```<code>public class Stamps
{
  private String color;
  private int value;

  public Stamps(String color, int value)
  {
    this.color=color;
    this.value=value;
  }

    public boolean equals(Stamps other)
    {
       return color.equals(other.color)
            && value== other.value;
    }
}

public class Main
{
     public static void main(String[] args)
     {
          Stamps stamp1 = new Stamps("red",10);
          Stamps stamp2 = new Stamps("green",10);

        System.out.println(stamp1.equals(stamp2));
     }
}
</code>```

Here, I'm not overriding the equals() method inherited from Object class since parameter types are different. So, instead of using my code, shouldn't it use the one inherited from Object class ?

答:
When you write a method invocation expression in Java, a complex set of rules is followed to determine which method will be invoked.

Basically, the compiler will search for the most specific method that it can find which matches the types of the parameters you are trying to pass in.

The important thing about these rules is that they make no special provision for methods in Object, or any other class. The methods in Object are treated exactly the same as any method you define yourself.

So, if you are trying to invoke an equals method on an instance of class Stamps, passing in a single instance of Stamps as a parameter, it will find your method:

```<code>boolean equals(Stamps other)
</code>```

This is more specific than the one on Object:

```<code>boolean equals(Object other)
</code>```

("More specific" is informally defined in the spec thus: any parameter you can pass to a "more specific" method can also be passed to a "less specific" method, but not vice versa).

so the Java compiler will choose to invoke the equals(Stamps) method.

However, if you were to change either the first or second (or both) declarations of the variables to be of Object type:

```<code>Object stamp1 = new Stamps("red",10);
</code>```

then the equals(Stamps) method would not be invoked:

For Object stamp1, this would be because Java would search the Object type for matching methods. Since only equals(Object) exists on Object, this is the only possible on to invoke.

For Object stamp2, this would be because the parameter type of equals(Stamps) would not match, so the only possible method to invoke would be equals(Object).

Title: overriding the equals method in java

Body:
"Let’s implement the equals method for a Stamp class.
You need to override the equals method of the Object class.
Now you have a slight problem.
The Object class knows nothing about stamps, so
it declares the otherObject
parameter variable of the equals method to have the type
Object. When overriding the method, you are not allowed to change the type of the parameter variable."

Here, it says that we are not allowed to change type of the parameter variable.
However, when I use the below code, it gives me the correct result.

public class Stamps
{
  private String color;
  private int value;

  public Stamps(String color, int value)
  {
    this.color=color;
    this.value=value;
  }

    public boolean equals(Stamps other)
    {
       return color.equals(other.color)
            && value== other.value;
    }
}

public class Main
{
     public static void main(String[] args)
     {
          Stamps stamp1 = new Stamps("red",10);
          Stamps stamp2 = new Stamps("green",10);

        System.out.println(stamp1.equals(stamp2));
     }
}

Here, I'm not overriding the equals() method inherited from Object class since parameter types are different. So, instead of using my code, shouldn't it use the one inherited from Object class ?

Body:
When you write a method invocation expression in Java, a complex set of rules is followed to determine which method will be invoked.

Basically, the compiler will search for the most specific method that it can find which matches the types of the parameters you are trying to pass in.

The important thing about these rules is that they make no special provision for methods in Object, or any other class. The methods in Object are treated exactly the same as any method you define yourself.

So, if you are trying to invoke an equals method on an instance of class Stamps, passing in a single instance of Stamps as a parameter, it will find your method:

boolean equals(Stamps other)

This is more specific than the one on Object:

boolean equals(Object other)

("More specific" is informally defined in the spec thus: any parameter you can pass to a "more specific" method can also be passed to a "less specific" method, but not vice versa).

so the Java compiler will choose to invoke the equals(Stamps) method.

However, if you were to change either the first or second (or both) declarations of the variables to be of Object type:

Object stamp1 = new Stamps("red",10);

then the equals(Stamps) method would not be invoked:

For Object stamp1, this would be because Java would search the Object type for matching methods. Since only equals(Object) exists on Object, this is the only possible on to invoke.

For Object stamp2, this would be because the parameter type of equals(Stamps) would not match, so the only possible method to invoke would be equals(Object).


问:
using android animation-list
I'm having a little trouble getting an animated loading spinner to work for a splash page. Nothing shows up when I try to run the following code.  Any suggestions?  It seems that quite a few people have issues with this on google but I do not understand why mine is failing to work.  Thanks!

animationloader.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item android:drawable="@drawable/loadingspinner1" android:duration="200" />
<item android:drawable="@drawable/loadingspinner2" android:duration="200" />
<item android:drawable="@drawable/loadingspinner3" android:duration="200" />
<item android:drawable="@drawable/loadingspinner4" android:duration="200" />
<item android:drawable="@drawable/loadingspinner5" android:duration="200" />
<item android:drawable="@drawable/loadingspinner6" android:duration="200" />
<item android:drawable="@drawable/loadingspinner7" android:duration="200" />
<item android:drawable="@drawable/loadingspinner8" android:duration="200" />
<item android:drawable="@drawable/loadingspinner9" android:duration="200" />
<item android:drawable="@drawable/loadingspinner01" android:duration="200" />
<item android:drawable="@drawable/loadingspinner11" android:duration="200" />
<item android:drawable="@drawable/loadingspinner12" android:duration="200" />
</animation-list>
</code>```

SplashScreen.java

```<code>package com.secure.inmatecanteen;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.widget.ImageView;

public class SplashScreen extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splashscreen);

    //Beginning the loading animation as we attempt to verify registration with SIP
    ImageView ivLoader = (ImageView) findViewById(R.id.IVloadinganimation);
    ivLoader.setBackgroundResource(R.anim.animationloader);

    AnimationDrawable frameAnimation = (AnimationDrawable) ivLoader.getBackground();
    frameAnimation.start();
}
}
</code>```

splashscreen.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:background="@android:color/white" >

 <ImageView
android:id="@+id/iclogo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="@drawable/iclogo"
android:adjustViewBounds="true"
/>

 <ImageView
android:id="@+id/IVloadinganimation"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:adjustViewBounds="true"
/>

    </LinearLayout>
</code>```

答:
Check GitHub project here I have implemented: Check here

My MainActivity.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="@color/colorPrimaryDark"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/animation_imageview"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_centerHorizontal="true"
        android:src="@drawable/animation_frame"
        android:scaleType="fitCenter"
        android:layout_marginBottom="50dp"/>

    <TextView
        android:layout_below="@+id/animation_imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:textSize="20sp"
        android:textStyle="bold"
        android:textColor="#fff"
        android:fontFamily="sans-serif-thin"
        android:text="Converting Please wait..."/>

</RelativeLayout>
</code>```

My animation-list in drawable

```<code><?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false">

    <item android:drawable="@drawable/ic_covert_f1" android:duration="90"/>
    <item android:drawable="@drawable/ic_covert_f2" android:duration="90"/>
    <item android:drawable="@drawable/ic_covert_f3" android:duration="90"/>
    <item android:drawable="@drawable/ic_covert_f4" android:duration="90"/>
    <item android:drawable="@drawable/ic_covert_f5" android:duration="90"/>
    <item android:drawable="@drawable/ic_covert_f6" android:duration="90"/>
    <item android:drawable="@drawable/ic_covert_f7" android:duration="90"/>
    <item android:drawable="@drawable/ic_covert_f8" android:duration="90"/>
    <item android:drawable="@drawable/ic_covert_f9" android:duration="90"/>
    <item android:drawable="@drawable/ic_covert_f10" android:duration="90"/>
    <item android:drawable="@drawable/ic_covert_f11" android:duration="90"/>

</animation-list>
</code>```

My MainActivty.java

Always remember to use Runnable to start the animation

```<code>public class MainActivity extends AppCompatActivity {

    AnimationDrawable progressAnimation;
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = (ImageView)findViewById(R.id.animation_imageview);
        progressAnimation =    (AnimationDrawable)imageView.getDrawable();
        progressAnimation.setCallback(imageView);
        progressAnimation.setVisible(true, true);
        imageView.post(new Starter());
    }

    class Starter implements Runnable {
        public void run() {
            progressAnimation.start();
        }
    }
}
</code>```

Works Perfectly Good Luck :)

Title: using android animation-list

Body:
I'm having a little trouble getting an animated loading spinner to work for a splash page. Nothing shows up when I try to run the following code.  Any suggestions?  It seems that quite a few people have issues with this on google but I do not understand why mine is failing to work.  Thanks!

animationloader.xml

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item android:drawable="@drawable/loadingspinner1" android:duration="200" />
<item android:drawable="@drawable/loadingspinner2" android:duration="200" />
<item android:drawable="@drawable/loadingspinner3" android:duration="200" />
<item android:drawable="@drawable/loadingspinner4" android:duration="200" />
<item android:drawable="@drawable/loadingspinner5" android:duration="200" />
<item android:drawable="@drawable/loadingspinner6" android:duration="200" />
<item android:drawable="@drawable/loadingspinner7" android:duration="200" />
<item android:drawable="@drawable/loadingspinner8" android:duration="200" />
<item android:drawable="@drawable/loadingspinner9" android:duration="200" />
<item android:drawable="@drawable/loadingspinner01" android:duration="200" />
<item android:drawable="@drawable/loadingspinner11" android:duration="200" />
<item android:drawable="@drawable/loadingspinner12" android:duration="200" />
</animation-list>

SplashScreen.java

package com.secure.inmatecanteen;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.widget.ImageView;

public class SplashScreen extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splashscreen);

    //Beginning the loading animation as we attempt to verify registration with SIP
    ImageView ivLoader = (ImageView) findViewById(R.id.IVloadinganimation);
    ivLoader.setBackgroundResource(R.anim.animationloader);

    AnimationDrawable frameAnimation = (AnimationDrawable) ivLoader.getBackground();
    frameAnimation.start();
}
}

splashscreen.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:background="@android:color/white" >

 <ImageView
android:id="@+id/iclogo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="@drawable/iclogo"
android:adjustViewBounds="true"
/>

 <ImageView
android:id="@+id/IVloadinganimation"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:adjustViewBounds="true"
/>

    </LinearLayout>

Body:
Check GitHub project here I have implemented: Check here

My MainActivity.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="@color/colorPrimaryDark"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/animation_imageview"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_centerHorizontal="true"
        android:src="@drawable/animation_frame"
        android:scaleType="fitCenter"
        android:layout_marginBottom="50dp"/>

    <TextView
        android:layout_below="@+id/animation_imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:textSize="20sp"
        android:textStyle="bold"
        android:textColor="#fff"
        android:fontFamily="sans-serif-thin"
        android:text="Converting Please wait..."/>

</RelativeLayout>

My animation-list in drawable

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false">

    <item android:drawable="@drawable/ic_covert_f1" android:duration="90"/>
    <item android:drawable="@drawable/ic_covert_f2" android:duration="90"/>
    <item android:drawable="@drawable/ic_covert_f3" android:duration="90"/>
    <item android:drawable="@drawable/ic_covert_f4" android:duration="90"/>
    <item android:drawable="@drawable/ic_covert_f5" android:duration="90"/>
    <item android:drawable="@drawable/ic_covert_f6" android:duration="90"/>
    <item android:drawable="@drawable/ic_covert_f7" android:duration="90"/>
    <item android:drawable="@drawable/ic_covert_f8" android:duration="90"/>
    <item android:drawable="@drawable/ic_covert_f9" android:duration="90"/>
    <item android:drawable="@drawable/ic_covert_f10" android:duration="90"/>
    <item android:drawable="@drawable/ic_covert_f11" android:duration="90"/>

</animation-list>

My MainActivty.java

Always remember to use Runnable to start the animation

public class MainActivity extends AppCompatActivity {

    AnimationDrawable progressAnimation;
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = (ImageView)findViewById(R.id.animation_imageview);
        progressAnimation =    (AnimationDrawable)imageView.getDrawable();
        progressAnimation.setCallback(imageView);
        progressAnimation.setVisible(true, true);
        imageView.post(new Starter());
    }

    class Starter implements Runnable {
        public void run() {
            progressAnimation.start();
        }
    }
}

Works Perfectly Good Luck :)


问:
slider better than jquery ui slider

Possible Duplicate:

  JQuery Slider alternative?

Is there a better slider than jquery UI Slider?

I don't want to add too much files to my js directory for just a single slider.

答:
See this answer

JQuery Slider alternative?

Uses this slider

http://programming.arantius.com/lightweight+javascript+slider+control

Title: slider better than jquery ui slider


问:
How do I list existing subnets in a cloudformation template from Amazon?
I am using the template that makes a Multi-AZ lamp stack.  The only things I am changing are the existing VPC ID, adding the 2 existing subnets, and naming the RDB database, user and pass.  The code validates ok when I click the check button, but when I try to launch the network it fails with the code error,
    "Template contains errors.: Template format error: Every Description member must be a string."

I have been looking for example SIMPLE templates, that do not use any foo-bar type "everybody knows this is to be filled with their own value" stuff.  I have been putting in hours of search and test.  This is the first one I have ever done, and it just cannot be all that hard, right?
I am using the suggested list of AMIs, though in the future I will put in my customized AMI instead.

```<code>"Parameters" : {
    "VpcId" : {
      "Type" : "AWS::EC2::VPC::Id",
      "Description" : "vpc-123456789456",
      "ConstraintDescription" : "must be the VPC Id of an existing Virtual Private Cloud."
},

"Subnets" : {
  "Type" : "List<AWS::EC2::Subnet::Id>",
  "Description" : [
      "subnet-12345621ff4c" ,
      "subnet-1234562188d1"],
</code>```

This is the only one I have found that doesn't throw errors saying "Expecting a ':' instead of a ','"
Should I be listing the name as
"List"

答:
"Description" has to be a string. It's a textual description that shows up in the UI when you create the stack.

I think you're looking for either "Default" or "AllowedValues". The first will set the default value in case your template user doesn't specify anything. To put a list of values, you need to separate them by a comma. For example:

```<code>"Parameters": {
    "VpcId": {
        "Type": "AWS::EC2::VPC::Id",
        "Default": "vpc-123456789456",
        "ConstraintDescription": "must be the VPC Id of an existing Virtual Private Cloud."
    },

    "Subnets": {
        "Type": "List<AWS::EC2::Subnet::Id>",
        "Default": "subnet-12345621ff4c,subnet-1234562188d1"
    }
}
</code>```

The second is a list of allowed values the user can select. That one actually does take a list. For example:

```<code>"Parameters": {
    "VpcId": {
        "Type": "AWS::EC2::VPC::Id",
        "AllowedValues": ["vpc-123456789456", "vpc-xxx"],
        "ConstraintDescription": "must be the VPC Id of an existing Virtual Private Cloud."
    }
}
</code>```

I'm not sure if "ConstraintDescription" will show if the user selects a wrong one. I think that only applies to "AllowedPattern".

Yes, it can be that hard and very frustrating, but it does get easier over time. The learning curve is steep.

Body:
I am using the template that makes a Multi-AZ lamp stack.  The only things I am changing are the existing VPC ID, adding the 2 existing subnets, and naming the RDB database, user and pass.  The code validates ok when I click the check button, but when I try to launch the network it fails with the code error,
    "Template contains errors.: Template format error: Every Description member must be a string."

I have been looking for example SIMPLE templates, that do not use any foo-bar type "everybody knows this is to be filled with their own value" stuff.  I have been putting in hours of search and test.  This is the first one I have ever done, and it just cannot be all that hard, right?
I am using the suggested list of AMIs, though in the future I will put in my customized AMI instead.

"Parameters" : {
    "VpcId" : {
      "Type" : "AWS::EC2::VPC::Id",
      "Description" : "vpc-123456789456",
      "ConstraintDescription" : "must be the VPC Id of an existing Virtual Private Cloud."
},

"Subnets" : {
  "Type" : "List<AWS::EC2::Subnet::Id>",
  "Description" : [
      "subnet-12345621ff4c" ,
      "subnet-1234562188d1"],

This is the only one I have found that doesn't throw errors saying "Expecting a ':' instead of a ','"
Should I be listing the name as
"List"

Body:
"Description" has to be a string. It's a textual description that shows up in the UI when you create the stack.

I think you're looking for either "Default" or "AllowedValues". The first will set the default value in case your template user doesn't specify anything. To put a list of values, you need to separate them by a comma. For example:

"Parameters": {
    "VpcId": {
        "Type": "AWS::EC2::VPC::Id",
        "Default": "vpc-123456789456",
        "ConstraintDescription": "must be the VPC Id of an existing Virtual Private Cloud."
    },

    "Subnets": {
        "Type": "List<AWS::EC2::Subnet::Id>",
        "Default": "subnet-12345621ff4c,subnet-1234562188d1"
    }
}

The second is a list of allowed values the user can select. That one actually does take a list. For example:

"Parameters": {
    "VpcId": {
        "Type": "AWS::EC2::VPC::Id",
        "AllowedValues": ["vpc-123456789456", "vpc-xxx"],
        "ConstraintDescription": "must be the VPC Id of an existing Virtual Private Cloud."
    }
}

I'm not sure if "ConstraintDescription" will show if the user selects a wrong one. I think that only applies to "AllowedPattern".

Yes, it can be that hard and very frustrating, but it does get easier over time. The learning curve is steep.


问:
Issues to space
 elements with pourcentage
I can't space these li elements of my footer with pourcentage on padding left... Otherwise, the inline-block I used don't work anymore...

I already tried to use % but then it stops to be inline...

Can you help me ?

footer {
  position: fixed;
  bottom: 0px;
  left: 0;
  height: 65px;
  width: 100%;
  margin: auto;
  z-index: 99;
}

.footer ul {
  position: absolute;
  display: block;
  text-align: right;
  list-style-type: none;
  bottom: 15px;
  right: 5%;
}

.footer li {
  display: inline-block;
  position: relative;
  padding-left: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
  <div class="footer">

    <ul>
      <li>
        <div id="humidity">15%</div>
      </li>
      <li>
        <div id="temp">15°C</div>
      </li>
      <li>
        <div id="clock">15h15m15s</div>
      </li>
      <li>
        <div id="date" class="date">15.15.15</div>
      </li>
    </ul>

    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1670 97" preserveAspectRatio="none">
<g>
 <path fill="#FE4A11" d="M1669,52.659V97H847.357H0V52.659l122.675-16.814l142.712,3.871c0,0,231.45-27.464,236.787-27.78
  c5.336-0.316,272.148,27.132,272.148,27.132l198.221-14.81l360.398,14.679l231.414-15.818L1669,52.659z"/>
 <path fill="#FE4A11" d="M1669,52.659V97H847.357H0V52.659l122.675-16.814l142.712,3.871c0,0,231.45-27.464,236.787-27.78
  c5.336-0.316,272.148,27.132,272.148,27.132l198.221-14.81l360.398,14.679l231.414-15.818L1669,52.659z"/>
</g>
</svg>

  </div>
</footer></code>```

Title: Issues to space <li> elements with pourcentage

Body:
I can't space these li elements of my footer with pourcentage on padding left... Otherwise, the inline-block I used don't work anymore...

I already tried to use % but then it stops to be inline...

Can you help me ?

footer {
  position: fixed;
  bottom: 0px;
  left: 0;
  height: 65px;
  width: 100%;
  margin: auto;
  z-index: 99;
}

.footer ul {
  position: absolute;
  display: block;
  text-align: right;
  list-style-type: none;
  bottom: 15px;
  right: 5%;
}

.footer li {
  display: inline-block;
  position: relative;
  padding-left: 50px;
}

15%

15°C

15h15m15s

15.15.15

    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1670 97" preserveAspectRatio="none">
<g>
 <path fill="#FE4A11" d="M1669,52.659V97H847.357H0V52.659l122.675-16.814l142.712,3.871c0,0,231.45-27.464,236.787-27.78
  c5.336-0.316,272.148,27.132,272.148,27.132l198.221-14.81l360.398,14.679l231.414-15.818L1669,52.659z"/>
 <path fill="#FE4A11" d="M1669,52.659V97H847.357H0V52.659l122.675-16.814l142.712,3.871c0,0,231.45-27.464,236.787-27.78
  c5.336-0.316,272.148,27.132,272.148,27.132l198.221-14.81l360.398,14.679l231.414-15.818L1669,52.659z"/>
</g>
</svg>

Body:
add width:100% to the UL element

footer {
  position:fixed;
  bottom:0px;
  left:0;
  height: 65px;
  width: 100%;
  margin: auto;
  z-index:99;
}

.footer ul{
    position:absolute;
    display:block;
    text-align:right;
    list-style-type: none;
    bottom:15px;
    right: 5%;
    width:100%;
    }

.footer li {
   display: inline-block;

    padding-left: 5%;
}

<footer>
<div class="footer">

<ul>
    <li><div id="humidity">15%</div></li>
    <li><div id="temp">15°C</div></li>
    <li><div id="clock">15h15m15s</div></li>
    <li><div id="date" class="date">15.15.15</div></li>
  </ul>

    <svg xmlns="http://www.w3.org/2000/svg"  viewBox="0 0 1670 97" preserveAspectRatio="none">
<g>
    <path fill="#FE4A11" d="M1669,52.659V97H847.357H0V52.659l122.675-16.814l142.712,3.871c0,0,231.45-27.464,236.787-27.78
        c5.336-0.316,272.148,27.132,272.148,27.132l198.221-14.81l360.398,14.679l231.414-15.818L1669,52.659z"/>
    <path fill="#FE4A11" d="M1669,52.659V97H847.357H0V52.659l122.675-16.814l142.712,3.871c0,0,231.45-27.464,236.787-27.78
        c5.336-0.316,272.148,27.132,272.148,27.132l198.221-14.81l360.398,14.679l231.414-15.818L1669,52.659z"/>
</g>
</svg>

</div>
</footer>