问:
Change colors in python dash plotly theme
I am currently creating my first plotly dash app and have a question on graph theming:

I want to use the available plotly_dark theme and only adjust the underlying colors (background and element colors) to custom values. I played around with the ideas provided here: https://plotly.com/python/templates/#saving-and-distributing-custom-themes like this

```<code>import plotly.graph_objects as go
import plotly.io as pio

pio.templates["plotly_dark_custom"] = go.layout.Template(
    ...custom definitions here...
)
pio.templates.default = "plotly_dark_custom"
</code>```

but I was wondering if there is a more intuitive way, e.g. building a child theme from plotly_dark
and only override the colors (providing a palette for the colors and define the new background color) afterwards.

As I am very new to Python my knowledge here is very limited, so I hope you can give me some pointers in the right direction.

Thank you and let me know if I should provide more details on this request.
Stephan

答:
I got an error when running Stephan's answer, so I thought I would post what ended up working for me.</p>

```<code># this helps us get the theme settings
import plotly.io as plt_io

# this is for simple plotting with plotly express
import plotly.express as px

# create our custom_dark theme from the plotly_dark template
plt_io.templates["custom_dark"] = plt_io.templates["plotly_dark"]

# set the paper_bgcolor and the plot_bgcolor to a new color
plt_io.templates["custom_dark"]['layout']['paper_bgcolor'] = '#30404D'
plt_io.templates["custom_dark"]['layout']['plot_bgcolor'] = '#30404D'

# you may also want to change gridline colors if you are modifying background
plt_io.templates['custom_dark']['layout']['yaxis']['gridcolor'] = '#4f687d'
plt_io.templates['custom_dark']['layout']['xaxis']['gridcolor'] = '#4f687d'

# load an example dataset to test
df = px.data.iris()

# create a nice default plotly example figure
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",
                 size='petal_length', hover_data=['petal_width'])

# set the template to our custom_dark template
fig.layout.template = 'custom_dark'

# and voila, we have a modified dark mode figure
fig.show()
</code>```

Body:
I am currently creating my first plotly dash app and have a question on graph theming:

I want to use the available plotly_dark theme and only adjust the underlying colors (background and element colors) to custom values. I played around with the ideas provided here: https://plotly.com/python/templates/#saving-and-distributing-custom-themes like this

import plotly.graph_objects as go
import plotly.io as pio

pio.templates["plotly_dark_custom"] = go.layout.Template(
    ...custom definitions here...
)
pio.templates.default = "plotly_dark_custom"

but I was wondering if there is a more intuitive way, e.g. building a child theme from plotly_dark
and only override the colors (providing a palette for the colors and define the new background color) afterwards.

As I am very new to Python my knowledge here is very limited, so I hope you can give me some pointers in the right direction.

Thank you and let me know if I should provide more details on this request.
Stephan

Body:
I got an error when running Stephan's answer, so I thought I would post what ended up working for me.

# this helps us get the theme settings
import plotly.io as plt_io

# this is for simple plotting with plotly express
import plotly.express as px

# create our custom_dark theme from the plotly_dark template
plt_io.templates["custom_dark"] = plt_io.templates["plotly_dark"]

# set the paper_bgcolor and the plot_bgcolor to a new color
plt_io.templates["custom_dark"]['layout']['paper_bgcolor'] = '#30404D'
plt_io.templates["custom_dark"]['layout']['plot_bgcolor'] = '#30404D'

# you may also want to change gridline colors if you are modifying background
plt_io.templates['custom_dark']['layout']['yaxis']['gridcolor'] = '#4f687d'
plt_io.templates['custom_dark']['layout']['xaxis']['gridcolor'] = '#4f687d'

# load an example dataset to test
df = px.data.iris()

# create a nice default plotly example figure
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",
                 size='petal_length', hover_data=['petal_width'])

# set the template to our custom_dark template
fig.layout.template = 'custom_dark'

# and voila, we have a modified dark mode figure
fig.show()


来源: stackexchange

问:
Change for-loop to while loop
How to change the  for-loop to a while loop?

```<code>for (i = 0; i < arr.length; i++) {
            if (arr[i] == k) {
                found = true;
                break;
            }

        }
</code>```

Code:

```<code>import java.util.Scanner;

class Algorithmus {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("Geben sie den gesuchten Wert ein: ");
        int k = s.nextInt();
        System.out.println("Geben sie die Länge des Arrays ein: ");
        int n = s.nextInt();
        int arr[] = new int[n];
        int i = 0;
        System.out.println("Geben sie die Werte ein:");
        for(i = 0;i<n;i++){
            arr[i] = s.nextInt();
        }
        boolean found = false;
        for (i = 0; i < arr.length; i++) {
            if (arr[i] == k) {
                found = true;
                break;
            }

        }
        if (found==true) {
            System.out.println((i+1));
        } else {
            System.out.println((arr.length + 1));
        }
    }
}
</code>```

The structure should be:

```<code>BEGIN
Input: k1, ..., kn, k;
found := FALSE;
WHILE NOT found AND „not all elements were viewed“ DO
„take the next element ki“;
found := (ki = k)
END (* WHILE *);
IF found THEN
Output: i
ELSE
OUtput: n + 1
END (* IF *)
END
</code>```

答:
Something equivalent would be:</p>

```<code>int i = 0;

while (i < arr.length) {
    if (arr[i] == k) {
        found = true;
        break;
    }
    ++i;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Change for-loop to while loop

Body:
How to change the  for-loop to a while loop?

for (i = 0; i < arr.length; i++) {
            if (arr[i] == k) {
                found = true;
                break;
            }

        }

Code:

import java.util.Scanner;

class Algorithmus {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("Geben sie den gesuchten Wert ein: ");
        int k = s.nextInt();
        System.out.println("Geben sie die Länge des Arrays ein: ");
        int n = s.nextInt();
        int arr[] = new int[n];
        int i = 0;
        System.out.println("Geben sie die Werte ein:");
        for(i = 0;i<n;i++){
            arr[i] = s.nextInt();
        }
        boolean found = false;
        for (i = 0; i < arr.length; i++) {
            if (arr[i] == k) {
                found = true;
                break;
            }

        }
        if (found==true) {
            System.out.println((i+1));
        } else {
            System.out.println((arr.length + 1));
        }
    }
}

The structure should be:

BEGIN
Input: k1, ..., kn, k;
found := FALSE;
WHILE NOT found AND „not all elements were viewed“ DO
„take the next element ki“;
found := (ki = k)
END (* WHILE *);
IF found THEN
Output: i
ELSE
OUtput: n + 1
END (* IF *)
END

Body:
Something equivalent would be:

int i = 0;

while (i < arr.length) {
    if (arr[i] == k) {
        found = true;
        break;
    }
    ++i;
}


答:
You can do something like this:

int idx = 0;
while(idx < arr.length && a[idx] != k) {
    idx++
}

if(idx == arr.length) {
    // element not found, do something
} else {
    // element found
}
```

Title: Change for-loop to while loop


问:
Truncate text for dynamic width (Responsive) through CSS
In the Fiddle link, you can see image with some content. What I want is .g_container li strong should get truncated with dynamic width but now its getting hidden. Its width should stop spreading with image width. now I gets hidden and (3 dots) ... were not visible even if I use text-overflow:ellipsis

```<code>.g_container li strong {
    text-align: center;
    font-size: 13px;
    font-weight: bold;
    padding: 8px 10px 4px !important;
    line-height: 30px;
    color: #000;
    text-transform: uppercase;
    height: 30px;
    overflow: hidden;
    width:100px;
    text-overflow: ellipsis;
    white-space: nowrap;
    background:yellow;
}
</code>```

In bigger resolution, the Lorem ipsum text (ie. with yellow background) looks fine. But for smaller resolutions, text does not get truncated instead getting hidden.

I went through lot of SO questions related to dynamic text truncation, but nothing is related with my requirement.

Edit:

I have images in both landscape and portrait formats and don't know exact dimensions of the images. For ladscape images there is no problem. but for portrait, empty white space is coming according to text width. Can someone help me to solve this issue?

答:
This worked for me

```<code><div style="display: flex; position: absolute; width: 100%;">
  <div style="white-space: nowrap; overflow: hidden;text-overflow: ellipsis;">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi.
  </div>
</div>
</code>```

Adding position:absolute to the parent container made it work.

ContentLicense: CC BY-SA 3.0

Body:
In the Fiddle link, you can see image with some content. What I want is .g_container li strong should get truncated with dynamic width but now its getting hidden. Its width should stop spreading with image width. now I gets hidden and (3 dots) ... were not visible even if I use text-overflow:ellipsis

.g_container li strong {
    text-align: center;
    font-size: 13px;
    font-weight: bold;
    padding: 8px 10px 4px !important;
    line-height: 30px;
    color: #000;
    text-transform: uppercase;
    height: 30px;
    overflow: hidden;
    width:100px;
    text-overflow: ellipsis;
    white-space: nowrap;
    background:yellow;
}

In bigger resolution, the Lorem ipsum text (ie. with yellow background) looks fine. But for smaller resolutions, text does not get truncated instead getting hidden.

I went through lot of SO questions related to dynamic text truncation, but nothing is related with my requirement.

Edit:

I have images in both landscape and portrait formats and don't know exact dimensions of the images. For ladscape images there is no problem. but for portrait, empty white space is coming according to text width. Can someone help me to solve this issue?

Body:
This worked for me

<div style="display: flex; position: absolute; width: 100%;">
  <div style="white-space: nowrap; overflow: hidden;text-overflow: ellipsis;">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi.
  </div>
</div>

Adding position:absolute to the parent container made it work.


问:
How to view dwg in 3D view - customer question
our customer has prblem with view dwg files in 3D: He can see dwg only in 2D, he can't see it in 3d view. His question is how to do it right: Must he use PUT request or translate to SVG ? Or is there any better solution ?

Regards,

Milann

答:
When loading document, mention 'role':'3d' as shown below.

```<code>var viewables = viewerDocument.getRoot().search({'type':'geometry','role':'3d'});
viewer.loadDocumentNode(viewerDocument, viewables[0]);
</code>```

Ref: https://forge.autodesk.com/en/docs/viewer/v7/developers_guide/viewer_basics/load-a-model/#step-2-load-model-in-manifest

Body:
When loading document, mention 'role':'3d' as shown below.

var viewables = viewerDocument.getRoot().search({'type':'geometry','role':'3d'});
viewer.loadDocumentNode(viewerDocument, viewables[0]);

Ref: https://forge.autodesk.com/en/docs/viewer/v7/developers_guide/viewer_basics/load-a-model/#step-2-load-model-in-manifest


问:
Does using a prototype + definition instead of just a definition speed up the program?
Im very new to C programing, but have limited experience with Python, Java, and Perl. I was just wondering what the advantage is of having the prototype of a function above main() and the definition of that function below main() rather than just having the definition of said function above main(). From what I have read, the definition can act as a prototype as well.

Thanks in advance,

答: If you write your code in the correct order, i.e. main last, then there is only one definition in your code for each function. This prevents having to change the code in two, or more, places if changes ever need to be made. That prevents errors and reduces the work to maintain it. The principle is called "single source of truth"</p>


答:
Try this</p>

```<code>int i = 0;
while(arr.length > i){
//code
++i;
}
</code>```

Title: Change for-loop to while loop

Body:
Try this

int i = 0;
while(arr.length > i){
//code
++i;
}


问:
Selection sort of singly Linked Lists by swapping nodes(iterative approach)?
I am trying to perform selection sort on singly linked list by swapping the node itself but after all the inputs it looks like my sort() function in not working properly.
What am I missing or did wrong please someone help me with that.

NOTE: Name of all the functions and pointers pretty much tells their task so I thought not to add comments But if anyone wants comment then please let me know.

NOTE: In swap_node(int i, int j),i and j are the positions of the two nodes which needs to be swapped.

#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
    int data;
    struct node *next;
} node;

node *head = NULL, *prev = NULL, *next = NULL;

static int k = 0;//Global variable K which will store the no of nodes created so far.

node *make_node()
{
    k++;
    return ((node *)malloc(sizeof(node)));
}

void push()
{
    if (k == 0)
    {
        next = make_node();
        printf("Enter Data:");
        scanf("%d", &next->data);
        next->next = NULL;
        head = next;
        prev = next;
    }
    else
    {
        next = make_node();
        printf("Enter Data:");
        scanf("%d", &next->data);
        next->next = NULL;
        prev->next = next;
        prev = next;
    }
}

node *x = NULL, *y = NULL;

void swap_node(int i, int j)
{
    node *prevX = NULL, *currX = head, *prevY = NULL, *currY = head;
    if (i == 1)
    {
        for (int l = 1; l < j; l++)
        {
            prevY = currY;
            currY = currY->next;
        }
        head = currY;
        if (j - i == 1)
        {
            currX->next = currY->next;
            currY->next = currX;
        }
        else
        {
            node *temp = currX->next;
            currX->next = currY->next;
            currY->next = temp;
            prevY->next = currX;
        }
    }
    else
    {
        for (int l = 1; l next;
        }
        for (int l = 1; l < j; l++)
        {
            prevY = currY;
            currY = currY->next;
        }
        if (j - i == 1)
        {
            prevX->next = currY;
            currX->next = currY->next;
            currY->next = currX;
        }
        else
        {
            node *temp = currX->next;
            prevX->next = currY;
            prevY->next = currX;
            currX->next = currY->next;
            currY->next = temp;
        }
    }
    x = currX;
    y = currY;
}

void sort()
{
    x = head;
    int i = 0, j = 0;
    for (i = 1; i < k; i++)
    {
        y = x->next;
        for (j = i + 1; j <= k; j++)
        {
            if (x->data > y->data)
            {
                swap_node(i, j);
            }
            y = y->next;
        }
        x = x->next;
    }
}

void print_node()
{
    printf("------------Printing Node--------------\n");
    node *temp = head;
    do
    {
        printf("%d\n", temp->data);
        temp = temp->next;
    } while (temp != NULL);
}

void main(void)
{
    int choice;
    printf("MENU\n1-PUSH\n2-Print node\n");
    do
    {
        printf("Enter Your Choice:");
        scanf("%d", &choice);
        switch (choice)
        {
        case 1:
            push();
            break;
        case 2:
            sort();
            print_node();
            break;
        default:
            printf("Wrong Choice!");
        }

    } while (choice == 1);
}
```

答:
why not just swap the content :  </p>

```<code>void swap_content (node *first, node *second) {
    int med = first->data;
    first->data = second->data;
    second->data = med;
}
</code>```

Body:
why not just swap the content :

void swap_content (node *first, node *second) {
    int med = first->data;
    first->data = second->data;
    second->data = med;
}


答:
int i=0;
while (i < arr.length) {
    if (arr[i] == k) {
        found = true;
        break;
    }
    i++;
}
```

Title: Change for-loop to while loop


问:
IdentityServer 4: No storage mechanism for grants specified - use AddInMemoryStores
I am using Identity Server 4 , ASP.NET Core and trying to replace the IdentityServer developer in Production environment.  But getting the following error:

```<code>No storage mechanism for grants specified. Use the 'AddInMemoryStores' extension method to register a development version.
</code>```

So, I tried to implement the services as mentioned in this answer:

IProfileService

IResourceOwnerPasswordValidator

This is my ConfigureServices Method in Startup class:

```<code>            services.AddMvc();
            var identityBuilder = services.AddIdentityServer();
            identityBuilder.AddInMemoryScopes(identitySrvConfig.GetScopes());
            identityBuilder.AddInMemoryClients(identitySrvConfig.GetClients());
            identityBuilder.AddProfileService<ProfileService>();
            identityBuilder.Services.AddTransient<IResourceOwnerPasswordValidator, ResourceOwnerPasswordValidator>();
</code>```

Taking into consideration that in my case the interface signature is different:

```<code> public class ResourceOwnerPasswordValidator : IdentityServer4.Validation.IResourceOwnerPasswordValidator
{
    public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
    {
        throw new NotImplementedException();
    }
}
</code>```

But I am still getting the same error, what is the problem?

答:
If you are applying custom Identity i.e

```<code>services.AddIdentity<AppUser, UserRole>(options => { options.User.RequireUniqueEmail = true; }).AddEntityFrameworkStores<AbcDbContext>();
</code>```

then in

```<code>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
</code>```

Comment

app.UseIdentityServer();

because we are using custom identity, not default

Body:
I am using Identity Server 4 , ASP.NET Core and trying to replace the IdentityServer developer in Production environment.  But getting the following error:

No storage mechanism for grants specified. Use the 'AddInMemoryStores' extension method to register a development version.

So, I tried to implement the services as mentioned in this answer:

IProfileService

IResourceOwnerPasswordValidator

This is my ConfigureServices Method in Startup class:

            services.AddMvc();
            var identityBuilder = services.AddIdentityServer();
            identityBuilder.AddInMemoryScopes(identitySrvConfig.GetScopes());
            identityBuilder.AddInMemoryClients(identitySrvConfig.GetClients());
            identityBuilder.AddProfileService<ProfileService>();
            identityBuilder.Services.AddTransient<IResourceOwnerPasswordValidator, ResourceOwnerPasswordValidator>();

Taking into consideration that in my case the interface signature is different:

 public class ResourceOwnerPasswordValidator : IdentityServer4.Validation.IResourceOwnerPasswordValidator
{
    public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
    {
        throw new NotImplementedException();
    }
}

But I am still getting the same error, what is the problem?

Body:
If you are applying custom Identity i.e

services.AddIdentity<AppUser, UserRole>(options => { options.User.RequireUniqueEmail = true; }).AddEntityFrameworkStores<AbcDbContext>();

then in

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

Comment

app.UseIdentityServer();

because we are using custom identity, not default


问:
splitting txt based on ':' but excluding the timestamp in python
```<code>05-23 14:14:53.275  A:B:C
</code>```

in the above case i am trying to split the txt based on  : using line.split(':') and following o/p should come as

```<code>['05-23 14:14:53.275','A','B','C']
</code>```

but instead The o/p came is
['05-23 14','14','53.275','A','B','C']

it is also splitting the timestamp.
how do i exclude that from splitting

Body:
05-23 14:14:53.275  A:B:C

in the above case i am trying to split the txt based on  : using line.split(':') and following o/p should come as

['05-23 14:14:53.275','A','B','C']

but instead The o/p came is
['05-23 14','14','53.275','A','B','C']

it is also splitting the timestamp.
how do i exclude that from splitting

Body:
Just for fun of using walrus:

>>> s = '05-23 14:14:53.275  A:B:C'
>>> [(temp := s.rsplit(maxsplit=1))[0], *temp[1].split(':')]
['05-23 14:14:53.275', 'A', 'B', 'C']


问:
python 2.7: cannot pip on windows "bash: pip: command not found"
I am trying to install the SciPy stack located at https://scipy.org/stackspec.html [I am only allowed 2 links; trying to use them wisely].  I realize that there are much easier ways to do this, but I think there is a lot to be learned by doing it manually.  I am relatively new to a lot of this stuff, so I apologize if I sound ignorant at any point.

I am running  Windows 7 Enterprise - 64 bit.  Here is what I have done so far:

Installed python-2.7.8.msi (32-bit) from https://www.python.org/download/releases/2.7.8/

Installed numpy-1.8.1-win32-superpack-python2.7 from
http://sourceforge.net/projects/numpy/files/

Test: import numpy as np ---> no errors

Installed scipy library,

scipy-0.14.0-win32-superpack-python2.7.exe from
(SCIPY DOT ORG LINK REMOVED)
Test: import scipy as sp ---> no errors

Installed matplotlib: matplotlib-1.3.1.win32-py2.7.exe from
(MATPLOTLIB DOT ORG LINK REMOVED)

Installed PIP by running script here:
https://raw.githubusercontent.com/pypa/pip/master/contrib/get-pip.py
I just copied-pasted script to a new file in IDLE,

saved as C:\Python27\Scripts\pip_install.py and clicked Run>module. No errors reported.

Does the path on which I saved
pip_install.py matter?

HERE IS WHERE I FAIL

Attempted to install matlibplot dependency dateutil: Opened a
Cygwin Shell, and typed

```<code>        cd C:\Python27          ! is it necessary to cd to python directtory?
        pip install python-dateutil
</code>```

This results in the error:

```<code>    bash: pip: command not found
</code>```

I get the same error attempting from cmd.

Any help  is appreciated; the closest I found was bash: pip: command not found.  But the OSX nature of it is just enough to confise me further.

UPDATE:

I added the pip-path per Paul H's suggestion below.  It made the error go away, but strangely, nothing I pip actually installs. For example, in Cygwin, I type:

```<code>cbennett2> pip install python-dateutil
cbennett2>
</code>```

You can see that there is no output or feedback from the shell (which I think there should be).  Then when I go to a new python shell:

```<code>>>> from dateutil.parser import parse
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    from dateutil.parser import parse
ImportError: No module named dateutil.parser
>>>>
</code>```

This happens with all of the modules that I thought I had pip'd ... pandas, tornado, etc.

答:
The problem is that your Python version and the library you want to use are not same versionally (Python). Even if you install Python's latest version, your PATH might not change properly and automatically. Thus, you should change it manually.After matching their version, it will work.

Ex: When I tried to install Django3, I got same error. I noticed that my PATH still seems C:\python27\Scripts though I already install Python3.8, so that I manually edited my PATH C:\python38\Scripts and reinstalled pip install Django and everything worked well.

Body:
I am trying to install the SciPy stack located at https://scipy.org/stackspec.html [I am only allowed 2 links; trying to use them wisely].  I realize that there are much easier ways to do this, but I think there is a lot to be learned by doing it manually.  I am relatively new to a lot of this stuff, so I apologize if I sound ignorant at any point.

I am running  Windows 7 Enterprise - 64 bit.  Here is what I have done so far:

Installed python-2.7.8.msi (32-bit) from https://www.python.org/download/releases/2.7.8/

Installed numpy-1.8.1-win32-superpack-python2.7 from
http://sourceforge.net/projects/numpy/files/

Test: import numpy as np ---> no errors

Installed scipy library,

scipy-0.14.0-win32-superpack-python2.7.exe from
(SCIPY DOT ORG LINK REMOVED)
Test: import scipy as sp ---> no errors

Installed matplotlib: matplotlib-1.3.1.win32-py2.7.exe from
(MATPLOTLIB DOT ORG LINK REMOVED)

Installed PIP by running script here:
https://raw.githubusercontent.com/pypa/pip/master/contrib/get-pip.py
I just copied-pasted script to a new file in IDLE,

saved as C:\Python27\Scripts\pip_install.py and clicked Run>module. No errors reported.

Does the path on which I saved
pip_install.py matter?

HERE IS WHERE I FAIL

Attempted to install matlibplot dependency dateutil: Opened a
Cygwin Shell, and typed

        cd C:\Python27          ! is it necessary to cd to python directtory?
        pip install python-dateutil

This results in the error:

    bash: pip: command not found

I get the same error attempting from cmd.

Any help  is appreciated; the closest I found was bash: pip: command not found.  But the OSX nature of it is just enough to confise me further.

UPDATE:

I added the pip-path per Paul H's suggestion below.  It made the error go away, but strangely, nothing I pip actually installs. For example, in Cygwin, I type:

cbennett2> pip install python-dateutil
cbennett2>

You can see that there is no output or feedback from the shell (which I think there should be).  Then when I go to a new python shell:

>>> from dateutil.parser import parse
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    from dateutil.parser import parse
ImportError: No module named dateutil.parser
>>>>

This happens with all of the modules that I thought I had pip'd ... pandas, tornado, etc.


问:
Swift: How to observe if screen is locked in macOS
I want to detect if the user has locked his screen (in macOS) using Swift.

Based on this answer I’ve created the following code:

```<code>import Cocoa
import Quartz

if let dict = Quartz.CGSessionCopyCurrentDictionary() as? [String : Any] {
    let locked = dict["CGSSessionScreenIsLocked"]
    print(locked as? String ?? "")
}
</code>```

...which seems to work fine if I explicitly run the code.

But how is it possible to observe the value so I get notified when the value got changed?

答:
With Combine (available on macOS 10.15+):</p>
```<code>import Combine

var bag = Set<AnyCancellable>()

let dnc = DistributedNotificationCenter.default()

dnc.publisher(for: Notification.Name(rawValue: "com.apple.screenIsLocked"))
    .sink { _ in print("Screen Locked") }
    .store(in: &bag)

dnc.publisher(for: Notification.Name(rawValue: "com.apple.screenIsUnlocked"))
    .sink { _ in print("Screen Unlocked") }
    .store(in: &bag)
</code>```

Body:
I want to detect if the user has locked his screen (in macOS) using Swift.

Based on this answer I’ve created the following code:

import Cocoa
import Quartz

if let dict = Quartz.CGSessionCopyCurrentDictionary() as? [String : Any] {
    let locked = dict["CGSSessionScreenIsLocked"]
    print(locked as? String ?? "")
}

...which seems to work fine if I explicitly run the code.

But how is it possible to observe the value so I get notified when the value got changed?

Body:
With Combine (available on macOS 10.15+):

import Combine

var bag = Set<AnyCancellable>()

let dnc = DistributedNotificationCenter.default()

dnc.publisher(for: Notification.Name(rawValue: "com.apple.screenIsLocked"))
    .sink { _ in print("Screen Locked") }
    .store(in: &bag)

dnc.publisher(for: Notification.Name(rawValue: "com.apple.screenIsUnlocked"))
    .sink { _ in print("Screen Unlocked") }
    .store(in: &bag)


问:
Implementing On Click attribute in XML and pass a method Which takes view as parameter
I have created a variable  inside the data tag of my own custom type in XML file

```<code><data>
        <variable
            name="gameViewModel"
            type="com.example.andriod.splock.screens.game.GameViewModel" />
</data>
</code>```

The variable of this class has a method choicemade(view : View) which takes a  View as parameter

I am unable to pass  it as a reference for my image view

The following code displays  cannot find indentifier method

```<code><imageView
  ...
android:onClick="@{() -> gameViewModel.choicemade(it)}"/>
</code>```

How can I pass the reference for the Image View?

答:
Try this way </p>

```<code><ImageView
...
android:onClick="@{(view) -> gameViewModel.choicemade(view)}"/>
</code>```

Body:
I have created a variable  inside the data tag of my own custom type in XML file

<data>
        <variable
            name="gameViewModel"
            type="com.example.andriod.splock.screens.game.GameViewModel" />
</data>

The variable of this class has a method choicemade(view : View) which takes a  View as parameter

I am unable to pass  it as a reference for my image view

The following code displays  cannot find indentifier method

<imageView
  ...
android:onClick="@{() -> gameViewModel.choicemade(it)}"/>

How can I pass the reference for the Image View?

Body:
Try this way

<ImageView
...
android:onClick="@{(view) -> gameViewModel.choicemade(view)}"/>


问:
Where has this class been used?
For example, I create a UserDataModel class like this:

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

import '../../../../globals/errors/exceptions.dart';
import '../../domain/entities/user_data.dart';
import '../../../../globals/utils/value_checker.dart';

class UserDataModel extends UserData {
  UserDataModel(
      {@required String fullname,
      @required String username,
      @required String token})
      : super(fullname: fullname, username: username, token: token);

  factory UserDataModel.fromJson(Map<String, dynamic> json) {
    return UserDataModel(
        fullname: json['fullname'],
        username: json['username'],
        token: json['token']);
  }

  factory UserDataModel.fromEntity(UserData userData) {
    return UserDataModel(
        fullname: userData.fullname,
        username: userData.username,
        token: userData.token);
  }

  Map<String, dynamic> toJson() {
    Map<String, dynamic> result = new Map<String, dynamic>();
    result = {
      "fullname": fullname,
      "username": username,
      "token": token,
    };

    return result;
  }
}
</code>```

I want to know, which UserDataModel class is initialized in any file? For example, I initialize the UserDataModel class in the repository.dart file or maybe main.dart or something else. How can I know that in VSCode?

答:
Press Ctrl button,

Move your mouse cursor to the Widget(class) you want to locate.

Press left click.

New tab will open containing that Widget/class.

Title: Where has this class been used?

Body:
For example, I create a UserDataModel class like this:

import 'package:meta/meta.dart';

import '../../../../globals/errors/exceptions.dart';
import '../../domain/entities/user_data.dart';
import '../../../../globals/utils/value_checker.dart';

class UserDataModel extends UserData {
  UserDataModel(
      {@required String fullname,
      @required String username,
      @required String token})
      : super(fullname: fullname, username: username, token: token);

  factory UserDataModel.fromJson(Map<String, dynamic> json) {
    return UserDataModel(
        fullname: json['fullname'],
        username: json['username'],
        token: json['token']);
  }

  factory UserDataModel.fromEntity(UserData userData) {
    return UserDataModel(
        fullname: userData.fullname,
        username: userData.username,
        token: userData.token);
  }

  Map<String, dynamic> toJson() {
    Map<String, dynamic> result = new Map<String, dynamic>();
    result = {
      "fullname": fullname,
      "username": username,
      "token": token,
    };

    return result;
  }
}

I want to know, which UserDataModel class is initialized in any file? For example, I initialize the UserDataModel class in the repository.dart file or maybe main.dart or something else. How can I know that in VSCode?


问:
Quicksort function keeps returning "exited, segmentation fault"
I am trying to get this quicksort function to work but it runs into the error "exited, segmentation fault". Can I please get some help? The function stopped working when I combined the while loops using the && Operator.</p>

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

void swap(int a[], int b, int c){
  int temp=a[b];
  a[b]=a[c];
  a[c]=temp;

}

void quicksort_fixed(int *number,int first,int last){
      int pivot=last;
      int smaller_index=first;
      int loop_variable=last;

   if(first<last){

      while((number[smaller_index] <= number[pivot])&&(smaller_index < loop_variable)){
        //printf("smaller index (%d) is less than pivot",smaller_index);
        smaller_index++;
        }
      while((number[loop_variable] > number[pivot])&&(smaller_index < loop_variable)){
        //printf("loop variable (%d) is greater than pivot",loop_variable);
        loop_variable--;
        }
        if(smaller_index < loop_variable){
          swap(number,smaller_index,loop_variable);
        }
    }

      swap(number,last,loop_variable);
      quicksort_fixed(number,first,loop_variable-1);
      quicksort_fixed(number,loop_variable+1,last);

}

void test_quicksort_fixed(){
  printf("\nUnsorted List 1: "); // First Test with small consecutive numbers
  int  a[6] = {5,2,3,1,4,6};
  for (int i=0; i < 6; i++){
    printf("%d, ", a[i]);
  }
  printf("\nSorted List 1: ");
  quicksort_fixed(a,0,5);
  for (int i=0; i < 6; i++){
    printf("%d, ", a[i]);
  }
</code>```

答:
You are missing the base case on your quicksort function. When the recursive calls are outside the if statement, they will keep spawning more recursive calls. Eventually, this will require too many stack frames (you run into a StackOverflow!) and the program will try and access memory it doesn't have (hence the segmentation fault).

Here is a correct implementation:

void quicksort_fixed(int *number, int first, int last) {
  int pivot = first;

  if (first < last) {

    for (int j = first; j < last; j++) {
      if (number[j] < number[last]) {
        swap(number, pivot, j);
        pivot++;
      }
    }
    swap(number, last, pivot);

    quicksort_fixed(number, first, pivot - 1);
    quicksort_fixed(number, pivot + 1, last);
  }
}

```

Body:
I am trying to get this quicksort function to work but it runs into the error "exited, segmentation fault". Can I please get some help? The function stopped working when I combined the while loops using the && Operator.

#include <stdio.h>

void swap(int a[], int b, int c){
  int temp=a[b];
  a[b]=a[c];
  a[c]=temp;

}

void quicksort_fixed(int *number,int first,int last){
      int pivot=last;
      int smaller_index=first;
      int loop_variable=last;

   if(first<last){

      while((number[smaller_index] <= number[pivot])&&(smaller_index < loop_variable)){
        //printf("smaller index (%d) is less than pivot",smaller_index);
        smaller_index++;
        }
      while((number[loop_variable] > number[pivot])&&(smaller_index < loop_variable)){
        //printf("loop variable (%d) is greater than pivot",loop_variable);
        loop_variable--;
        }
        if(smaller_index < loop_variable){
          swap(number,smaller_index,loop_variable);
        }
    }

      swap(number,last,loop_variable);
      quicksort_fixed(number,first,loop_variable-1);
      quicksort_fixed(number,loop_variable+1,last);

}

void test_quicksort_fixed(){
  printf("\nUnsorted List 1: "); // First Test with small consecutive numbers
  int  a[6] = {5,2,3,1,4,6};
  for (int i=0; i < 6; i++){
    printf("%d, ", a[i]);
  }
  printf("\nSorted List 1: ");
  quicksort_fixed(a,0,5);
  for (int i=0; i < 6; i++){
    printf("%d, ", a[i]);
  }


问:
How to read the documentation syntaxes?
Can someone explain how I read this syntaxes like the one below. In which I'm picking the MDN reduce method reference. I want to know what the brackets mean, why there's a comma before the words and etc.

arr.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue])

答:
TL;DR: The brackets indicate "optional". The commas exist to show the different function parameters. You can see the "optional" indication in the MDN documentation for each property.

```<code>arr.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue])
</code>```

arr => Reduce is a function on the Array prototype: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

callback: The first parameter of the reduce function is a "reducer function".

This callback has 4 parameters, 2 of them are "optional".

You will accept an accumulator value as the first parameter to the callback

You will accept each array element as currentValue as the second parameter

The index and the array are in [...] to indicate they are "optional". You do not need to worry about them unless you care about the index to implement your reducer.

initialValue is the second "optional" value to the reduce function: A value to use as the first argument to the first call of the callback. If no initialValue is supplied, the first element in the array will be used as the initial accumulator value and skipped as currentValue. Calling reduce() on an empty array without an initialValue will throw a TypeError.

Title: How to read the documentation syntaxes?

Body:
TL;DR: The brackets indicate "optional". The commas exist to show the different function parameters. You can see the "optional" indication in the MDN documentation for each property.

arr.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue])

arr => Reduce is a function on the Array prototype: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

callback: The first parameter of the reduce function is a "reducer function".

This callback has 4 parameters, 2 of them are "optional".

You will accept an accumulator value as the first parameter to the callback

You will accept each array element as currentValue as the second parameter

The index and the array are in [...] to indicate they are "optional". You do not need to worry about them unless you care about the index to implement your reducer.

initialValue is the second "optional" value to the reduce function: A value to use as the first argument to the first call of the callback. If no initialValue is supplied, the first element in the array will be used as the initial accumulator value and skipped as currentValue. Calling reduce() on an empty array without an initialValue will throw a TypeError.


问:
Building a chat app with angular, trying to make it so whenever the @ character is typed a list of the groups users appears above the @ symbol
So say I've got an input as follows:

```<code><input
class="chatInput form-control"
[(ngModel)]="message"
(keydown)="handleSubmit($event)"
/>
</code>```

as well as a list of group members with username attributes.

I want to make it so similar to groupme, every time I type the @ symbol, a list of the groups users pop up above wherever the @ is. I'm able to identify WHEN there is an @ symbold typed with (ngModelChange), however I don't know how to make a pop up at the exact location of the @ symbol. Any ideas?

答:
I would not recommend to go from scratch, because of browser handling, screen sizes keyboard control, debounceTime etc.

Why don't you try it with angular material. This Stackblitz may help you: https://stackblitz.com/edit/angular-4tkhtg-idm9tv?file=src/app/autocomplete-filter-example.ts

Body:
So say I've got an input as follows:

<input
class="chatInput form-control"
[(ngModel)]="message"
(keydown)="handleSubmit($event)"
/>

as well as a list of group members with username attributes.

I want to make it so similar to groupme, every time I type the @ symbol, a list of the groups users pop up above wherever the @ is. I'm able to identify WHEN there is an @ symbold typed with (ngModelChange), however I don't know how to make a pop up at the exact location of the @ symbol. Any ideas?


问:
Application get crashed when taken the picture in iPhone 4G?
I have taken the photo from my device and resize the image and set it to my image view frame. But my apps get crashed some times after taken the photo(Using resize). Now i have taken the photo in iphone 4G. The application get crashed only, when the many application runs in the background(Multitasking). So how could i resolve this issue?, Other than the application doesn't crash at anytime. The only problem is, when many application runs in the background mode, while using the camera mode the apps get crashed. So please Help me out.

Thanks.

答:
I had the same problem with my app.

In my case, I missused dealloc instead of release at some points of my code like this.:

```<code>[label1 release];              // OK
[label2 release];              // OK
[label3 dealloc];              // Not OK

[super dealloc];               // OK
</code>```

Check the code lines concerning with memory leaking.

ContentLicense: CC BY-SA 2.5

Body:
I had the same problem with my app.

In my case, I missused dealloc instead of release at some points of my code like this.:

[label1 release];              // OK
[label2 release];              // OK
[label3 dealloc];              // Not OK

[super dealloc];               // OK

Check the code lines concerning with memory leaking.


问:
Is there a way to read a file in C without a bunch of checks for sscanf and fgets?
In a program I'm writing, I'm currently doing the part of parsing an input file. I have to do input validation (to some degree), checking if sscanf parses the right number of variables and fgets isn't null. But as a result, the main outline looks like this:

```<code>int LINE_LENGTH = 100;
int parseInput(FILE* fp, FILE* output) {
    char* line = calloc(LINE_LENGTH, sizeof(char));
    if (fgets(line, LINE_LENGTH, fp) == NULL) return 1;
    int camFlag, lightFlag;
    if (sscanf(line, "%d %d %d\n", &frames, &camFlag, &lightFlag) != 3) return 1;
    if (camFlag) {
        if (fgets(line, LINE_LENGTH, fp) == NULL) return 1;
        double cx, cy, cz, dx, dy, dz, dt;
        if (sscanf(line, "%f %f %f %f %f %f %f\n", &cx, &cy, &cz, &dx, &dy, &dz, &dt) != 7) return 1;
        // do stuff with input
    }
    if (lightFlag) {
        if (fgets(line, LINE_LENGTH, fp) == NULL) return 1;
        double cx, cy, cz;
        unsigned char r, g, b;
        if (sscanf(line, "%f %f %f %hhu %hhu %hhu\n", &cx, &cy, &cz, &r, &g, &b) != 6) return 1;
        // do stuff with this data
    }
    for (int i = 0; i < frames; i++) {
        if (fgets(line, LINE_LENGTH, fp) == NULL)) return 1;
        int n;
        if (sscanf(line, "%d\n", &n) != 1) return 1;
        // etc...
    }
}
</code>```

and as a result, half the lines are checking input. Is there a good way to avoid this?

答:
One of the good way to get data form the file is fscanf(). There is no need to use fgets or sscanf. You can use while(fgetc(fp) != '\n'); for next line.

fscanf is use as sscanf but for the file. other rules are same.

please check the code I rewrite that.

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

int LINE_LENGTH = 100;
int parseInput(FILE* fp, FILE* output) {
    char* line = calloc(LINE_LENGTH, sizeof(char));
    int camFlag, lightFlag, frames;
    if (fscanf(fp, "%d %d %d", &frames, &camFlag, &lightFlag) != 3) return 1;
    printf("frames - %d, camFlag - %d, lightFlag - %d\n", frames, camFlag, lightFlag);
    while(fgetc(fp) != '\n');
    if (camFlag) {
        double cx, cy, cz, dx, dy, dz, dt;
        if (fscanf(fp, "%lf %lf %lf %lf %lf %lf %lf", &cx, &cy, &cz, &dx, &dy, &dz, &dt) != 7) return 1;
        printf("cx - %lf, cy - %lf, cz - %lf, dx - %lf, dy - %lf, dz - %lf, dt - %lf\n", cx, cy, cz, dx, dy, dz, dt);
        while(fgetc(fp) != '\n');
        // do stuff with input
    }
    if (lightFlag) {
        double cx, cy, cz;
        unsigned char r, g, b;
        if (fscanf(fp, "%lf %lf %lf %hhu %hhu %hhu", &cx, &cy, &cz, &r, &g, &b) != 6) return 1;
        printf("cx - %lf, cy - %lf, cz - %lf, r - %hhu, g - %hhu, b - %hhu\n",cx, cy, cz, r, g, b);
        while(fgetc(fp) != '\n');
        // do stuff with this data
    }
    for (int i = 0; i < frames; i++) {
        int n;
        if (fscanf(fp, "%d", &n) != 1) return 1;
        printf("n - %d\n", n);
        while(fgetc(fp) != '\n');
        // etc...
    }
}

int main(int argc, char ** argv)
{
        FILE * fp1 = NULL , * fp2 = NULL;
        fp1 = fopen(argv[1], "r");
        fp2 = fopen(argv[2], "w");
        parseInput(fp1, fp2);

}
</code>```

```<code>file data:
1 2 3
1.1 2.2 3.3 4.4 5.5 6.6 7.7
1.1 2.2 3.3 4 5 6
1
</code>```

```<code>OUTUPT:

frames - 1, camFlag - 2, lightFlag - 3
cx - 1.100000, cy - 2.200000, cz - 3.300000, dx - 4.400000, dy - 5.500000, dz - 6.600000, dt - 7.700000
cx - 1.100000, cy - 2.200000, cz - 3.300000, r - 4, g - 5, b - 6
n - 1
</code>```

Body:
In a program I'm writing, I'm currently doing the part of parsing an input file. I have to do input validation (to some degree), checking if sscanf parses the right number of variables and fgets isn't null. But as a result, the main outline looks like this:

int LINE_LENGTH = 100;
int parseInput(FILE* fp, FILE* output) {
    char* line = calloc(LINE_LENGTH, sizeof(char));
    if (fgets(line, LINE_LENGTH, fp) == NULL) return 1;
    int camFlag, lightFlag;
    if (sscanf(line, "%d %d %d\n", &frames, &camFlag, &lightFlag) != 3) return 1;
    if (camFlag) {
        if (fgets(line, LINE_LENGTH, fp) == NULL) return 1;
        double cx, cy, cz, dx, dy, dz, dt;
        if (sscanf(line, "%f %f %f %f %f %f %f\n", &cx, &cy, &cz, &dx, &dy, &dz, &dt) != 7) return 1;
        // do stuff with input
    }
    if (lightFlag) {
        if (fgets(line, LINE_LENGTH, fp) == NULL) return 1;
        double cx, cy, cz;
        unsigned char r, g, b;
        if (sscanf(line, "%f %f %f %hhu %hhu %hhu\n", &cx, &cy, &cz, &r, &g, &b) != 6) return 1;
        // do stuff with this data
    }
    for (int i = 0; i < frames; i++) {
        if (fgets(line, LINE_LENGTH, fp) == NULL)) return 1;
        int n;
        if (sscanf(line, "%d\n", &n) != 1) return 1;
        // etc...
    }
}

and as a result, half the lines are checking input. Is there a good way to avoid this?

Body:
One of the good way to get data form the file is fscanf(). There is no need to use fgets or sscanf. You can use while(fgetc(fp) != '\n'); for next line.

fscanf is use as sscanf but for the file. other rules are same.

please check the code I rewrite that.

#include <stdio.h>
#include <stdlib.h>

int LINE_LENGTH = 100;
int parseInput(FILE* fp, FILE* output) {
    char* line = calloc(LINE_LENGTH, sizeof(char));
    int camFlag, lightFlag, frames;
    if (fscanf(fp, "%d %d %d", &frames, &camFlag, &lightFlag) != 3) return 1;
    printf("frames - %d, camFlag - %d, lightFlag - %d\n", frames, camFlag, lightFlag);
    while(fgetc(fp) != '\n');
    if (camFlag) {
        double cx, cy, cz, dx, dy, dz, dt;
        if (fscanf(fp, "%lf %lf %lf %lf %lf %lf %lf", &cx, &cy, &cz, &dx, &dy, &dz, &dt) != 7) return 1;
        printf("cx - %lf, cy - %lf, cz - %lf, dx - %lf, dy - %lf, dz - %lf, dt - %lf\n", cx, cy, cz, dx, dy, dz, dt);
        while(fgetc(fp) != '\n');
        // do stuff with input
    }
    if (lightFlag) {
        double cx, cy, cz;
        unsigned char r, g, b;
        if (fscanf(fp, "%lf %lf %lf %hhu %hhu %hhu", &cx, &cy, &cz, &r, &g, &b) != 6) return 1;
        printf("cx - %lf, cy - %lf, cz - %lf, r - %hhu, g - %hhu, b - %hhu\n",cx, cy, cz, r, g, b);
        while(fgetc(fp) != '\n');
        // do stuff with this data
    }
    for (int i = 0; i < frames; i++) {
        int n;
        if (fscanf(fp, "%d", &n) != 1) return 1;
        printf("n - %d\n", n);
        while(fgetc(fp) != '\n');
        // etc...
    }
}

int main(int argc, char ** argv)
{
        FILE * fp1 = NULL , * fp2 = NULL;
        fp1 = fopen(argv[1], "r");
        fp2 = fopen(argv[2], "w");
        parseInput(fp1, fp2);

}

file data:
1 2 3
1.1 2.2 3.3 4.4 5.5 6.6 7.7
1.1 2.2 3.3 4 5 6
1

OUTUPT:

frames - 1, camFlag - 2, lightFlag - 3
cx - 1.100000, cy - 2.200000, cz - 3.300000, dx - 4.400000, dy - 5.500000, dz - 6.600000, dt - 7.700000
cx - 1.100000, cy - 2.200000, cz - 3.300000, r - 4, g - 5, b - 6
n - 1


问:
Where can I find rust test binary for my project?
I'm having problem on a specific function of a test of a specific file:

```<code>mod test {
//...

 #[test]
    #[cfg(feature = "proto-igmp")]
    fn test_handle_igmp() {
</code>```

I've found here https://github.com/rust-lang/cargo/issues/1407 that I can test specific tests by passing its name as an argument to the test binary. But where's such binary? And can I make println work inside tests?

I want to run test_handle_igmp to print some things and see why the error is happening.

答:
You can find it in target/$MODE/$NAME-$hash, e.g. target/debug/example-3beac917983bc7e3.exe. Note that there might be multiple ones, some for doc tests, some for #[test] functions.

That being said if you just want to run test_handle_igmp, you can just use

```<code>cargo test test_handle_igmp -- --nocapture
</code>```

to run your test and see the println outputs. See cargo test --help or the online documentation.

Body:
I'm having problem on a specific function of a test of a specific file:

mod test {
//...

 #[test]
    #[cfg(feature = "proto-igmp")]
    fn test_handle_igmp() {

I've found here https://github.com/rust-lang/cargo/issues/1407 that I can test specific tests by passing its name as an argument to the test binary. But where's such binary? And can I make println work inside tests?

I want to run test_handle_igmp to print some things and see why the error is happening.

Body:
You can find it in target/$MODE/$NAME-$hash, e.g. target/debug/example-3beac917983bc7e3.exe. Note that there might be multiple ones, some for doc tests, some for #[test] functions.

That being said if you just want to run test_handle_igmp, you can just use

cargo test test_handle_igmp -- --nocapture

to run your test and see the println outputs. See cargo test --help or the online documentation.


问:
How to delete data from firebase android
I faced an issue when I had to delete that data which user entered in here this photo. If the user entered enrollment number 60 then I have to delete all data from marks where the enrollment number is 60.

It deletes the data which user entered and it verifies that enrollment from marks and delete all data where enrollment is 66 it means delete that document or node.

I tried the following that did not work.

reff.child("Marks").removeValue().equals(et1);

答:
```<code>
    String et1 =e1.getText().toString().trim();
                    reff.child("Marks").orderByChild("enrollment").equalTo(et1)
                            .addListenerForSingleValueEvent(new ValueEventListener() {
                                @Override
                                public void onDataChange(@NonNull DataSnapshot dataSnapshot)
                                {
                                    for (DataSnapshot ds : dataSnapshot.getChildren())
                                    {
                                        ds.getRef().removeValue();
                                        Toast.makeText(getApplicationContext(), "Deleted", Toast.LENGTH_SHORT).show();
                                    }
                                }

                                @Override
                                public void onCancelled(@NonNull DatabaseError databaseError)
                                {
                                    Toast.makeText(getApplicationContext(), "Failed to delete", Toast.LENGTH_SHORT).show();
                                }
                            });
</code>```


问:
Delete files from HDFS path having date suffixed to the HDFS path older than a given date | unix
I have HDFS path having files as below -

```<code>/test/abc/xyz/2018-01-01
/test/abc/xyz/2019-01-01
/test/abc/xyz/2020-01-01
/test/abc/xyz/2020-02-01
/test/abc/xyz/2020-03-01
</code>```

How can I delete files older than a date  say 2020-01-01 in shell script

Final output -

```<code>/test/abc/xyz/2020-01-01
/test/abc/xyz/2020-02-01
/test/abc/xyz/2020-03-01
</code>```

答:
Try </p>

```<code>
for fn in /test/abc/xyz/*
do
 if [ $(tr -d '-' <<<$fn) -gt 20200101 ]
 then
   echo $fn;
 fi
done

</code>```

Body:
I have HDFS path having files as below -

/test/abc/xyz/2018-01-01
/test/abc/xyz/2019-01-01
/test/abc/xyz/2020-01-01
/test/abc/xyz/2020-02-01
/test/abc/xyz/2020-03-01

How can I delete files older than a date  say 2020-01-01 in shell script

Final output -

/test/abc/xyz/2020-01-01
/test/abc/xyz/2020-02-01
/test/abc/xyz/2020-03-01

Body:
Try

for fn in /test/abc/xyz/*
do
 if [ $(tr -d '-' <<<$fn) -gt 20200101 ]
 then
   echo $fn;
 fi
done


问:
Is there a way to use Google Apps Script to open a document at the last edit?
I have a Google Doc that's getting kind of long. I use it to collect pretty much all my thoughts on different projects, so I'd like it to open back up wherever I left off (not necessarily at the end). - I need it readily accessible on whatever device I'm on, that's why it's a Doc and not a Word file, even though I know how to write the macro there. -

After some digging, it looks like there's an edit trigger for sheets but not for docs, so I've been trying to get a time-based trigger instead as a best approximation of the most recent edit. I wrote the following in the doc's Code.gs, but it doesn't seem to work. Any suggestions?

```<code>function onOpen() {
  deleteTrigger();
  createTrigger();
  DocumentApp.getActiveDocument().setCursor(PropertiesService.getDocumentProperties().getProperty('lastOpen'));
}

function createTrigger() {
  ScriptApp.newTrigger('savePlace')
      .timeBased()
      .everyMinutes(1)
      .create();
}

function savePlace() {
  PropertiesService.getDocumentProperties().setProperty('lastOpen', DocumentApp.getActiveDocument().getCursor());
}

function deleteTrigger() {

  // Loop over all triggers and delete them
  var allTriggers = ScriptApp.getProjectTriggers();

  for (var i = 0; i < allTriggers.length; i++) {
    ScriptApp.deleteTrigger(allTriggers[i]);
  }
}
</code>```

(Also, do I have to specify a script property for lastOpen in the dialog box? And what's the best value to put in there if so. [I'm really, really new to this])

答:
Try this:

Just save your bookmark when you leave.  And the use gotoBookMark when you open up the document.

```<code>function saveBookMark() {
  var doc=DocumentApp.getActiveDocument();
  var cursor=doc.getCursor();
  var bookmark=doc.addBookmark(cursor);
  var ps=PropertiesService.getDocumentProperties();
  ps.setProperty('bookmarkid', bookmark.getId());
}

function gotoBookMark() {
  var doc=DocumentApp.getActiveDocument();
  var bookmarkid=PropertiesService.getDocumentProperties().getProperty('bookmarkid');
  var pos=doc.getBookmark(bookmarkid).getPosition();
  doc.setCursor(pos);
}
</code>```

This will remove all bookmarks:

```<code>function clearBookMarks() {
  var doc=DocumentApp.getActiveDocument();
  var bkmarks=doc.getBookmarks().forEach(function(bm){bm.remove();})
}
</code>```

Here's the menu:

```<code>function menu() {
  DocumentApp.getUi().createMenu('MyMenu')
  .addItem('Save BookMark', 'saveBookMark')
  .addItem('Goto Bookmark', 'gotoBookMark')
  .addItem('Remove All Bookmarks', 'clearBookMarks')
  .addToUi();
}
</code>```

Class Bookmarks

I've never actually used this before but I imagine with a little extra effort one could post an excerpt from each bookmark and provide a checkbox to select them and then only delete the ones you don't want and also provide a button next to each one so you could return to that one whenever you wish.

This was the sample code that got me rolling:

```<code>// Insert a bookmark at the cursor position and log its ID.
var doc = DocumentApp.getActiveDocument();
var cursor = doc.getCursor();
var bookmark = doc.addBookmark(cursor);
Logger.log(bookmark.getId());
</code>```

After that you can use code completion to figure out what methods are available and then refer to the manual when necessary.  It's interest sometimes code completion is updated before the document and sometimes the documentation gets updated first so you sometimes have to willing to wing it on your a bit.

I used the Document Properties Service to save the last bookmark id and so when you open up the document it always goes to the last bookmark.

PropertiesService

Body:
I have a Google Doc that's getting kind of long. I use it to collect pretty much all my thoughts on different projects, so I'd like it to open back up wherever I left off (not necessarily at the end). - I need it readily accessible on whatever device I'm on, that's why it's a Doc and not a Word file, even though I know how to write the macro there. -

After some digging, it looks like there's an edit trigger for sheets but not for docs, so I've been trying to get a time-based trigger instead as a best approximation of the most recent edit. I wrote the following in the doc's Code.gs, but it doesn't seem to work. Any suggestions?

function onOpen() {
  deleteTrigger();
  createTrigger();
  DocumentApp.getActiveDocument().setCursor(PropertiesService.getDocumentProperties().getProperty('lastOpen'));
}

function createTrigger() {
  ScriptApp.newTrigger('savePlace')
      .timeBased()
      .everyMinutes(1)
      .create();
}

function savePlace() {
  PropertiesService.getDocumentProperties().setProperty('lastOpen', DocumentApp.getActiveDocument().getCursor());
}

function deleteTrigger() {

  // Loop over all triggers and delete them
  var allTriggers = ScriptApp.getProjectTriggers();

  for (var i = 0; i < allTriggers.length; i++) {
    ScriptApp.deleteTrigger(allTriggers[i]);
  }
}

(Also, do I have to specify a script property for lastOpen in the dialog box? And what's the best value to put in there if so. [I'm really, really new to this])

Body:
Try this:

Just save your bookmark when you leave.  And the use gotoBookMark when you open up the document.

function saveBookMark() {
  var doc=DocumentApp.getActiveDocument();
  var cursor=doc.getCursor();
  var bookmark=doc.addBookmark(cursor);
  var ps=PropertiesService.getDocumentProperties();
  ps.setProperty('bookmarkid', bookmark.getId());
}

function gotoBookMark() {
  var doc=DocumentApp.getActiveDocument();
  var bookmarkid=PropertiesService.getDocumentProperties().getProperty('bookmarkid');
  var pos=doc.getBookmark(bookmarkid).getPosition();
  doc.setCursor(pos);
}

This will remove all bookmarks:

function clearBookMarks() {
  var doc=DocumentApp.getActiveDocument();
  var bkmarks=doc.getBookmarks().forEach(function(bm){bm.remove();})
}

Here's the menu:

function menu() {
  DocumentApp.getUi().createMenu('MyMenu')
  .addItem('Save BookMark', 'saveBookMark')
  .addItem('Goto Bookmark', 'gotoBookMark')
  .addItem('Remove All Bookmarks', 'clearBookMarks')
  .addToUi();
}

Class Bookmarks

I've never actually used this before but I imagine with a little extra effort one could post an excerpt from each bookmark and provide a checkbox to select them and then only delete the ones you don't want and also provide a button next to each one so you could return to that one whenever you wish.

This was the sample code that got me rolling:

// Insert a bookmark at the cursor position and log its ID.
var doc = DocumentApp.getActiveDocument();
var cursor = doc.getCursor();
var bookmark = doc.addBookmark(cursor);
Logger.log(bookmark.getId());

After that you can use code completion to figure out what methods are available and then refer to the manual when necessary.  It's interest sometimes code completion is updated before the document and sometimes the documentation gets updated first so you sometimes have to willing to wing it on your a bit.

I used the Document Properties Service to save the last bookmark id and so when you open up the document it always goes to the last bookmark.

PropertiesService


问:
Imagemagick jpeg decode delegate missing with OS X Homebrew install
I recently converted from macports to homebrew and my previous macports Imagemagick install was working fine. I followed the homebrew instructions to chown /usr/local (somewhat apprehensively) and remove /usr/local/include and /usr/local/lib. When trying to work with any jpeg images, imagemagick chokes with:

no decode delegate for this image format

Here is a list of some relevant command output. As you can see, no jpeg/jpg delegate can be found.

convert -list configure =>
DELEGATES     bzlib freetype png x11 xml zlib

identify -list configure => DELEGATES     bzlib freetype png x11 xml zlib

However, jpeg lib was installed as part of the Imagemagick dependencies, so I'm not sure what's going on here.

brew list => imagemagick jasper      jpeg        libtiff     little-cms  nginx       pcre

brew doctor => Your OS X is ripe for brewing. Any troubles you may be experiencing are likely purely psychosomatic.

identify --version => Version: ImageMagick 6.6.7-9 2011-04-06 Q16

Any ideas?

答:
I just ran into this issue myself. While investigating I noticed symlinks to the jpeg jib were missing from /usr/local/lib. Can take of this with the following; just be sure to refer to the jpeg lib version in use, at the time of this post I am using 8c:

```<code> ln -s /usr/local/Cellar/jpeg/8c/lib/libjpeg.8.dylib /usr/local/lib/libjpeg.8.dylib

 ln -s /usr/local/Cellar/jpeg/8c/lib/libjpeg.a /usr/local/lib/libjpeg.a
</code>```

Then force homebrew to reinstall imagemagick:

```<code> brew install --force imagemagick
</code>```

Viola! Imagemagick will now show that a jpeg delegate is present.

Body:
I just ran into this issue myself. While investigating I noticed symlinks to the jpeg jib were missing from /usr/local/lib. Can take of this with the following; just be sure to refer to the jpeg lib version in use, at the time of this post I am using 8c:

 ln -s /usr/local/Cellar/jpeg/8c/lib/libjpeg.8.dylib /usr/local/lib/libjpeg.8.dylib

 ln -s /usr/local/Cellar/jpeg/8c/lib/libjpeg.a /usr/local/lib/libjpeg.a

Then force homebrew to reinstall imagemagick:

 brew install --force imagemagick

Viola! Imagemagick will now show that a jpeg delegate is present.


问:
Unusual behavior of this key word in javascript
I have following code snippet which should return all the team names of a agile team. But code returns undefined. I have already tried let _this = this; and replaced this with _this but no result. Can anyone help me with this please.

```<code>let teamSelector = {
  teams: ['Team Alpha', 'Team Beta', 'Team Delta'],
  selectTeam: function(members){
    // let _this = this;
    return members.map((member)=>{
      return `${member} is on ${this.teams[Math.random() * 3]}`;
    });
  }
};

teamSelector.selectTeam(['Anna','Jhon','Kevin','Lesli']);
</code>```

答:
The value generated from Math.random is a float number so it will never reference an array index from this.teams, hence undefined value.

What you need to do is generate a random number using Math.random() * this.teams.length so that it will never generate an index value larger than the array size itself. You then need to use Math.floor to round this down as your Math.random generates a float number.

```<code>let teamSelector = {
  teams: ["Team Alpha", "Team Beta", "Team Delta"],
  selectTeam: function (members) {
    return members.map((member) =>
    `${member} is on ${
        this.teams[Math.floor(Math.random() * this.teams.length)]
      }`
    );
  },
};

teamSelector.selectTeam(["Anna", "John", "Kevin", "Lesli"]);
</code>```

Just a side note too - arrow functions implicitly return so you don't need to return inside the map. However you do need to use return for the map itself to keep the context of this inside the block scope of the object. You will see, if you implicitly return the map then this will reference the window object or a higher up block scope such as the class implementation.

Body:
I have following code snippet which should return all the team names of a agile team. But code returns undefined. I have already tried let _this = this; and replaced this with _this but no result. Can anyone help me with this please.

let teamSelector = {
  teams: ['Team Alpha', 'Team Beta', 'Team Delta'],
  selectTeam: function(members){
    // let _this = this;
    return members.map((member)=>{
      return `${member} is on ${this.teams[Math.random() * 3]}`;
    });
  }
};

teamSelector.selectTeam(['Anna','Jhon','Kevin','Lesli']);

Body:
The value generated from Math.random is a float number so it will never reference an array index from this.teams, hence undefined value.

What you need to do is generate a random number using Math.random() * this.teams.length so that it will never generate an index value larger than the array size itself. You then need to use Math.floor to round this down as your Math.random generates a float number.

let teamSelector = {
  teams: ["Team Alpha", "Team Beta", "Team Delta"],
  selectTeam: function (members) {
    return members.map((member) =>
    `${member} is on ${
        this.teams[Math.floor(Math.random() * this.teams.length)]
      }`
    );
  },
};

teamSelector.selectTeam(["Anna", "John", "Kevin", "Lesli"]);

Just a side note too - arrow functions implicitly return so you don't need to return inside the map. However you do need to use return for the map itself to keep the context of this inside the block scope of the object. You will see, if you implicitly return the map then this will reference the window object or a higher up block scope such as the class implementation.


问:
Why does Scrapy selector only bring the parent element?
I am trying to set a Scrapy selector to fetch some data on a table from Trezor's supported coins page (https://trezor.io/coins/):

```<code>In [1]: import requests
   ...: from scrapy.selector import Selector
   ...: req = requests.get('https://trezor.io/coins/').content
   ...: xs = '//*[@id="content"]/tr'
   ...: sel = Selector(text=req).xpath(xs)

In [2]: sel.extract_first()
Out[2]: '<tr class="coin  " data-href="./#BTC" id="BTC"></tr>'
</code>```

Shouldn't the selector bring the tr element and everything that is inside it (in this case, six td elements with more inner elements? When I try to access the td elements manually (with either xs = '//*[@id="content"]/tr[1]/td' or xs = '//*[@id="content"]/tr[1]/td[1]'), all I get is an empty list. I have also tried getting child nodes, but to no avail.

Cf. extracting on Wikipedia's main page, where you get everything inside the specified container:

```<code>In [3]: req2 = requests.get('https://en.wikipedia.org/wiki/Main_Page').content
   ...: xd = '//*[@id="mp-welcomecount"]'
   ...: sel2 = Selector(text=req2).xpath(xd)

In [4]: sel2.extract_first()
Out[4]: '<div id="mp-welcomecount">\n<div id="mp-welcome">Welcome to <a href="/wiki/Wikipedia" title="Wikipedia">Wikipedia</a>,</div>\n<div id="mp-free">the <a href="/wiki/Free_content" title="Free content">free</a> <a href="/wiki/Encyclopedia" title="Encyclopedia">encyclopedia</a> that <a href="/wiki/Help:Introduction" title="Help:Introduction">anyone can edit</a>.</div>\n<div id="articlecount"><a href="/wiki/Special:Statistics" title="Special:Statistics">6,088,421</a> articles in <a href="/wiki/English_language" title="English language">English</a></div>\n</div>'
</code>```

Why is that on Trezor's case I only get the tr element and how do I correct my code to bring everything that is contained inside it?

答:
Scrapy seems a bit off when it comes to parsing the page (error with tr closing tag). There's no "parent-child" connection between the tr and the td elements. You only have siblings. Structure of the parsed page :

```<code>tr
td
 span
  img
td
 strong
 small
 a
td
 img
td
 img
td
 a
 a
 a
 a
td
 a
 a
tr
...
</code>```

Maybe you can use the following XPath expression to fetch all the data from the table :

```<code>//tr[contains(@class,"coin")][1]/following-sibling::td
</code>```

Output : 8364 nodes

Or look for a magic option in scrapy settings.

Body:
I am trying to set a Scrapy selector to fetch some data on a table from Trezor's supported coins page (https://trezor.io/coins/):

In [1]: import requests
   ...: from scrapy.selector import Selector
   ...: req = requests.get('https://trezor.io/coins/').content
   ...: xs = '//*[@id="content"]/tr'
   ...: sel = Selector(text=req).xpath(xs)

In [2]: sel.extract_first()
Out[2]: '

'

Shouldn't the selector bring the tr element and everything that is inside it (in this case, six td elements with more inner elements? When I try to access the td elements manually (with either xs = '//*[@id="content"]/tr[1]/td' or xs = '//*[@id="content"]/tr[1]/td[1]'), all I get is an empty list. I have also tried getting child nodes, but to no avail.

Cf. extracting on Wikipedia's main page, where you get everything inside the specified container:

In [3]: req2 = requests.get('https://en.wikipedia.org/wiki/Main_Page').content
   ...: xd = '//*[@id="mp-welcomecount"]'
   ...: sel2 = Selector(text=req2).xpath(xd)

In [4]: sel2.extract_first()
Out[4]: '
\n
Welcome to Wikipedia,
\n
the free encyclopedia that anyone can edit.
\n
6,088,421 articles in English
\n
'

Why is that on Trezor's case I only get the tr element and how do I correct my code to bring everything that is contained inside it?

Body:
Scrapy seems a bit off when it comes to parsing the page (error with tr closing tag). There's no "parent-child" connection between the tr and the td elements. You only have siblings. Structure of the parsed page :

tr
td
 span
  img
td
 strong
 small
 a
td
 img
td
 img
td
 a
 a
 a
 a
td
 a
 a
tr
...

Maybe you can use the following XPath expression to fetch all the data from the table :

//tr[contains(@class,"coin")][1]/following-sibling::td

Output : 8364 nodes

Or look for a magic option in scrapy settings.


问:
Convert ISO time Format To local datetime in vb.net
I have issue to convert ISO date time to local datetime.

the flowing code is not work with me and give error

```<code>Dim txt As String = "20200530T015253+08"
Dim output As DateTime = DateTime.ParseExact(txt, "u", System.Globalization.CultureInfo.InvariantCulture)
</code>```

the error is

System.FormatException: 'String was not recognized as a valid DateTime.'

答:
Your date string is not an "ISO date" as far as I can see. ISO 8601 would lay it out like "2020-05-30T01:52:53+08:00" and .net would parse it with "o"

Parse it by specifying the format:

```<code>DateTime.ParseExact("20200530T015253+08", "yyyyMMddTHHmmsszz", Nothing)
</code>```

If your input data will vary its presentation for time zones that have a fractional hours component such as India being 5.5 hours, then you'll need to vary your format string to zzz

Body:
I have issue to convert ISO date time to local datetime.

the flowing code is not work with me and give error

Dim txt As String = "20200530T015253+08"
Dim output As DateTime = DateTime.ParseExact(txt, "u", System.Globalization.CultureInfo.InvariantCulture)

the error is

System.FormatException: 'String was not recognized as a valid DateTime.'

Body:
Your date string is not an "ISO date" as far as I can see. ISO 8601 would lay it out like "2020-05-30T01:52:53+08:00" and .net would parse it with "o"

Parse it by specifying the format:

DateTime.ParseExact("20200530T015253+08", "yyyyMMddTHHmmsszz", Nothing)

If your input data will vary its presentation for time zones that have a fractional hours component such as India being 5.5 hours, then you'll need to vary your format string to zzz


问:
Out of gas while migrating a contract
I have looked at the other "out of gas" SO posts and they haven't solved my problem.
I am using ganache-cli started with

```<code>ganache-cli  --account="0xce2ddf7d4509856c2b7256d002c004db6e34eeb19b37cee04f7b493d2b89306d, 2000000000000000000000000000000"
</code>```

I then execute

```<code>truffle migrate --reset
</code>```

It returns with an error

```<code>Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: VM Exception while processing transaction: out of gas
</code>```

(Full error is at the end)
These are the files involved;

truffle.js

```<code>module.exports = {
   networks: {
   development: {
   host: "localhost",
   port: 8545,
   network_id: "*",
   gas: 470000
  }
 }
};
</code>```

1_initial_migration.js

```<code>var Migrations = artifacts.require("./Migrations.sol");

module.exports = function(deployer) {
  deployer.deploy(Migrations,  {gas: 4500000});
};
</code>```

2_deploy_contracts.js

```<code>var Voting = artifacts.require("./Voting.sol");

module.exports = function(deployer){
    deployer.deploy(Voting, ['Rama', 'Nick', 'Jose'], {gas: 290000});

}
</code>```

Voting.sol

```<code>pragma solidity ^0.4.18;

contract Voting {

  mapping (bytes32 => uint8) public votesReceived;
  bytes32[] public candidateList;

  function Voting(bytes32[] candidateNames) public {
    candidateList = candidateNames;
  }

  function totalVotesFor(bytes32 candidate) view public returns (uint8) {
    require(validCandidate(candidate));
    return votesReceived[candidate];
  }

  function voteForCandidate(bytes32 candidate) public {
    require(validCandidate(candidate));
    votesReceived[candidate]  += 1;
  }

  function validCandidate(bytes32 candidate) view public returns (bool) {
    for(uint i = 0; i < candidateList.length; i++) {
      if (candidateList[i] == candidate) {
        return true;
      }
    }
    return false;
   }
}
</code>```

Full error

```<code>Replacing Migrations...
... 0xaf3b7d40ac17f297a4970b75e1cc55659e86dea3ba7bcf13dd9f82e2b6cf0086
Migrations: 0x1ea6ea9d7528a8ac4b378ae799d2c38fe006b9b6
Saving successful migration to network...
... 0xa8400e873da3cb15719c2c31804ec558e73aa9bfa91c4dc48e922c0ed0db736f
Saving artifacts...
Running migration: 2_deploy_contracts.js
Deploying Voting...
... 0x72947eda435cf854abeeeb5483c9625efad45b664f3bcc7c2085f8aabdbb1076
Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: VM Exception while processing transaction: out of gas
at Object.InvalidResponse (C:\Users\Paul\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\web3\lib\web3\errors.js:38:1)
at C:\Users\Paul\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\web3\lib\web3\requestmanager.js:86:1
at C:\Users\Paul\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\truffle-migrate\index.js:225:1
at C:\Users\Paul\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\truffle-provider\wrapper.js:134:1
at XMLHttpRequest.request.onreadystatechange (C:\Users\Paul\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\web3\lib\web3\httpprovider.js:128:1)
at XMLHttpRequestEventTarget.dispatchEvent (C:\Users\Paul\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\xhr2\lib\xhr2.js:64:1)
at XMLHttpRequest._setReadyState (C:\Users\Paul\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\xhr2\lib\xhr2.js:354:1)
at XMLHttpRequest._onHttpResponseEnd (C:\Users\Paul\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\xhr2\lib\xhr2.js:509:1)
at IncomingMessage.<anonymous> (C:\Users\Paul\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\xhr2\lib\xhr2.js:469:1)
at emitNone (events.js:91:20)
</code>```

答:
I had the same problem and now it's fixed.

Runtime : VM out of gas can occur in two situations -

While using truffle migrate --reset

Make sure to enable optimiser of solidity compiler.

Add -

```<code>solc: {
        optimizer: {
            enabled: true,
            runs: 200
        }
    }
</code>```

in truffle.js in windows and truffle-config.js in mac

Also in networks->development please give high gasPrice and gasLimit and make sure to match it with ganache-cli (if using)

While sending transaction or when connecting with solidity-

This is the most common error faced, when contract runs fine on remix but Runtime on truffle

When using web3 the default gas it uses is 90000 and some calls fail. So whenever you are sending a transaction do remember to give sufficient gas.

Sample

```<code>await this.state.instance.methods.sendingTransactionFunction().send({from : this.state.account, gas : 1000000})
</code>```

Title: Out of gas while migrating a contract

Body:
I have looked at the other "out of gas" SO posts and they haven't solved my problem.
I am using ganache-cli started with

ganache-cli  --account="0xce2ddf7d4509856c2b7256d002c004db6e34eeb19b37cee04f7b493d2b89306d, 2000000000000000000000000000000"

I then execute

truffle migrate --reset

It returns with an error

Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: VM Exception while processing transaction: out of gas

(Full error is at the end)
These are the files involved;

truffle.js

module.exports = {
   networks: {
   development: {
   host: "localhost",
   port: 8545,
   network_id: "*",
   gas: 470000
  }
 }
};

1_initial_migration.js

var Migrations = artifacts.require("./Migrations.sol");

module.exports = function(deployer) {
  deployer.deploy(Migrations,  {gas: 4500000});
};

2_deploy_contracts.js

var Voting = artifacts.require("./Voting.sol");

module.exports = function(deployer){
    deployer.deploy(Voting, ['Rama', 'Nick', 'Jose'], {gas: 290000});

}

Voting.sol

pragma solidity ^0.4.18;

contract Voting {

  mapping (bytes32 => uint8) public votesReceived;
  bytes32[] public candidateList;

  function Voting(bytes32[] candidateNames) public {
    candidateList = candidateNames;
  }

  function totalVotesFor(bytes32 candidate) view public returns (uint8) {
    require(validCandidate(candidate));
    return votesReceived[candidate];
  }

  function voteForCandidate(bytes32 candidate) public {
    require(validCandidate(candidate));
    votesReceived[candidate]  += 1;
  }

  function validCandidate(bytes32 candidate) view public returns (bool) {
    for(uint i = 0; i < candidateList.length; i++) {
      if (candidateList[i] == candidate) {
        return true;
      }
    }
    return false;
   }
}

Full error

Replacing Migrations...
... 0xaf3b7d40ac17f297a4970b75e1cc55659e86dea3ba7bcf13dd9f82e2b6cf0086
Migrations: 0x1ea6ea9d7528a8ac4b378ae799d2c38fe006b9b6
Saving successful migration to network...
... 0xa8400e873da3cb15719c2c31804ec558e73aa9bfa91c4dc48e922c0ed0db736f
Saving artifacts...
Running migration: 2_deploy_contracts.js
Deploying Voting...
... 0x72947eda435cf854abeeeb5483c9625efad45b664f3bcc7c2085f8aabdbb1076
Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: VM Exception while processing transaction: out of gas
at Object.InvalidResponse (C:\Users\Paul\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\web3\lib\web3\errors.js:38:1)
at C:\Users\Paul\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\web3\lib\web3\requestmanager.js:86:1
at C:\Users\Paul\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\truffle-migrate\index.js:225:1
at C:\Users\Paul\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\truffle-provider\wrapper.js:134:1
at XMLHttpRequest.request.onreadystatechange (C:\Users\Paul\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\web3\lib\web3\httpprovider.js:128:1)
at XMLHttpRequestEventTarget.dispatchEvent (C:\Users\Paul\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\xhr2\lib\xhr2.js:64:1)
at XMLHttpRequest._setReadyState (C:\Users\Paul\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\xhr2\lib\xhr2.js:354:1)
at XMLHttpRequest._onHttpResponseEnd (C:\Users\Paul\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\xhr2\lib\xhr2.js:509:1)
at IncomingMessage.<anonymous> (C:\Users\Paul\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\xhr2\lib\xhr2.js:469:1)
at emitNone (events.js:91:20)

Body:
I had the same problem and now it's fixed.

Runtime : VM out of gas can occur in two situations -

While using truffle migrate --reset

Make sure to enable optimiser of solidity compiler.

Add -

solc: {
        optimizer: {
            enabled: true,
            runs: 200
        }
    }

in truffle.js in windows and truffle-config.js in mac

Also in networks->development please give high gasPrice and gasLimit and make sure to match it with ganache-cli (if using)

While sending transaction or when connecting with solidity-

This is the most common error faced, when contract runs fine on remix but Runtime on truffle

When using web3 the default gas it uses is 90000 and some calls fail. So whenever you are sending a transaction do remember to give sufficient gas.

Sample

await this.state.instance.methods.sendingTransactionFunction().send({from : this.state.account, gas : 1000000})


问:
How to upload contacts CSV file to my Gmail account?
Just wondering whether it' s possible to upload a CSV file with contacts information in it to my Gmail account?

I already looked at the Google Data API. it only allows you to add one at a time. Is there a bulk import ?

答: What are you asking exactly? GMail has it right there inside gmail. Must you do it from the data protocol ONLY?


问:
How to avoid plotting certain values of a series with matplotplib
I want to plot a dataframe column with matplotlib, but I don't want to see the trend when the series value is 0 or higher. I also would like to see properly the x axis, without the overlapping. I don't want to remove these values from the series, because of the date it is important to be able to see them as blank space.

Right now, I have the following simple code:

```<code>plt.plot(data, linestyle='dashed')
plt.title('Points')
plt.ylabel('Number')
plt.xlabel('Time (days)')
plt.show(block = True)
</code>```

Where data is the following df:

```<code>Tagname
01/06/2008 00:00   -45.757616
02/06/2008 00:00   -45.990457
03/06/2008 00:00   -45.393121
04/06/2008 00:00   -44.913295
05/06/2008 00:00   -44.705479
                      ...
19/03/2012 00:00   -53.729701
20/03/2012 00:00   -53.453338
21/03/2012 00:00   -52.822274
22/03/2012 00:00   -52.814657
23/03/2012 00:00   -52.900613
Name: points_subs, Length: 3314, dtype: float64
</code>```

How can I do both things???

答:
There's a feature that automatically optimizes the x-axis for you. The matplotlib.dates.AutoDateLocator matplotlib.dates.AutoDateLocatoris used. Does your quality match your intentions?

```<code>import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np

data = (np.random.randint(0, 60, (3314,)) + np.random.rand(3314)) * -1
date = pd.date_range('2008-06-01', '2017-06-27', freq='1D')
df = pd.DataFrame({'data':data}, index=pd.to_datetime(date))

fig = plt.figure(figsize=(16,9),dpi=144)
ax = fig.add_subplot(111)

plt.plot(df.index, df['data'], linestyle='dashed')

plt.title('Points')
plt.ylabel('Number')
plt.xlabel('Time (days)')

locator = mdates.AutoDateLocator()
formatter = mdates.ConciseDateFormatter(locator)

ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)

plt.show(block = True)
</code>```

Body:
I want to plot a dataframe column with matplotlib, but I don't want to see the trend when the series value is 0 or higher. I also would like to see properly the x axis, without the overlapping. I don't want to remove these values from the series, because of the date it is important to be able to see them as blank space.

Right now, I have the following simple code:

plt.plot(data, linestyle='dashed')
plt.title('Points')
plt.ylabel('Number')
plt.xlabel('Time (days)')
plt.show(block = True)

Where data is the following df:

Tagname
01/06/2008 00:00   -45.757616
02/06/2008 00:00   -45.990457
03/06/2008 00:00   -45.393121
04/06/2008 00:00   -44.913295
05/06/2008 00:00   -44.705479
                      ...
19/03/2012 00:00   -53.729701
20/03/2012 00:00   -53.453338
21/03/2012 00:00   -52.822274
22/03/2012 00:00   -52.814657
23/03/2012 00:00   -52.900613
Name: points_subs, Length: 3314, dtype: float64

How can I do both things???

Body:
There's a feature that automatically optimizes the x-axis for you. The matplotlib.dates.AutoDateLocator matplotlib.dates.AutoDateLocatoris used. Does your quality match your intentions?

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np

data = (np.random.randint(0, 60, (3314,)) + np.random.rand(3314)) * -1
date = pd.date_range('2008-06-01', '2017-06-27', freq='1D')
df = pd.DataFrame({'data':data}, index=pd.to_datetime(date))

fig = plt.figure(figsize=(16,9),dpi=144)
ax = fig.add_subplot(111)

plt.plot(df.index, df['data'], linestyle='dashed')

plt.title('Points')
plt.ylabel('Number')
plt.xlabel('Time (days)')

locator = mdates.AutoDateLocator()
formatter = mdates.ConciseDateFormatter(locator)

ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)

plt.show(block = True)


问:
Authenticated Vapor session not preserved inside an XCTest
The application itself works fine, but I can't get a test to work that confirms this.

In Part 1 below, the test checks that the login using email and (correct) password succeeds and the correct URL redirection is returned. In the code immediately before the redirection returns to the test, debug shows that a call to request.auth.require(User.self) succeeds.

In both Parts 2a and 2b, the XCTAssertEqual fails and the log shows that the result of the call to request.auth.require(User.self) has thrown an error saying the user is not authorised.

Part 3 is a double-check that Part 1 is working as it, too, returns the correct URL redirection for an unsuccessful login.

So, it seems that the session data is not being preserved beyond the call to .test(...). Is there a way around this?

```<code>@testable import App
import XCTVapor
final class AppTests: XCTestCase
{
    func test011UserLoginLogout() throws
    {
        func attemptLogin(withPassword password:String, completion:(XCTHTTPResponse) throws -> ()) throws -> Void
        {
            var body = ByteBufferAllocator().buffer(capacity: 0)
            body.writeString(#"{"email":"me@example.com","password":"\#(password)"}"#)
            var headers = HTTPHeaders()
            headers.replaceOrAdd(name: .contentLength, value: body.readableBytes.description)
            headers.contentType = .json
            try app.test(.POST, "/login", headers:headers, body:body) { response in try completion( response ) }
        }

        var app = Application(.testing)
        app.databases.use(.mysql(hostname:DBHost, username:DBAccount, password:DBPassword, database:DBDatabase, tlsConfiguration:.none), as:.mysql)
        app.databases.default(to:.mysql)
        do { try configure(app!) }
        catch { XCTFail("configure(app) failed") }
        //  Part 1 succeeds
        try attemptLogin(withPassword:"goodPassword")
        {
            res in
            XCTAssertEqual(res.status, HTTPResponseStatus.seeOther)
            XCTAssertEqual(res.headers["location"].first,"success")
            try app!.test(.GET, "/success")
            {
                response in
                XCTAssertEqual(response.status, .ok) // <--- Part 2(a) fails
            }
        }

        try app.test(.GET, "/success")
        {
            response in
            XCTAssertEqual(response.status, .ok) // <-- Part 2(b) fails
        }

        // Part 3 succeeds
        try attemptLogin(withPassword:"badPassword")
        {
            response in
            XCTAssertEqual(response.status, .seeOther)
            XCTAssertEqual(response.headers["location"].first,"failed")
        }
    }
}
</code>```

答: I think you're missing the authentication in the request that are failing. You either need to pass the session cookie into the failing request if using sessions or the token if using bearer auth. </p>

Body:
The application itself works fine, but I can't get a test to work that confirms this.

In Part 1 below, the test checks that the login using email and (correct) password succeeds and the correct URL redirection is returned. In the code immediately before the redirection returns to the test, debug shows that a call to request.auth.require(User.self) succeeds.

In both Parts 2a and 2b, the XCTAssertEqual fails and the log shows that the result of the call to request.auth.require(User.self) has thrown an error saying the user is not authorised.

Part 3 is a double-check that Part 1 is working as it, too, returns the correct URL redirection for an unsuccessful login.

So, it seems that the session data is not being preserved beyond the call to .test(...). Is there a way around this?

@testable import App
import XCTVapor
final class AppTests: XCTestCase
{
    func test011UserLoginLogout() throws
    {
        func attemptLogin(withPassword password:String, completion:(XCTHTTPResponse) throws -> ()) throws -> Void
        {
            var body = ByteBufferAllocator().buffer(capacity: 0)
            body.writeString(#"{"email":"me@example.com","password":"\#(password)"}"#)
            var headers = HTTPHeaders()
            headers.replaceOrAdd(name: .contentLength, value: body.readableBytes.description)
            headers.contentType = .json
            try app.test(.POST, "/login", headers:headers, body:body) { response in try completion( response ) }
        }

        var app = Application(.testing)
        app.databases.use(.mysql(hostname:DBHost, username:DBAccount, password:DBPassword, database:DBDatabase, tlsConfiguration:.none), as:.mysql)
        app.databases.default(to:.mysql)
        do { try configure(app!) }
        catch { XCTFail("configure(app) failed") }
        //  Part 1 succeeds
        try attemptLogin(withPassword:"goodPassword")
        {
            res in
            XCTAssertEqual(res.status, HTTPResponseStatus.seeOther)
            XCTAssertEqual(res.headers["location"].first,"success")
            try app!.test(.GET, "/success")
            {
                response in
                XCTAssertEqual(response.status, .ok) // <--- Part 2(a) fails
            }
        }

        try app.test(.GET, "/success")
        {
            response in
            XCTAssertEqual(response.status, .ok) // <-- Part 2(b) fails
        }

        // Part 3 succeeds
        try attemptLogin(withPassword:"badPassword")
        {
            response in
            XCTAssertEqual(response.status, .seeOther)
            XCTAssertEqual(response.headers["location"].first,"failed")
        }
    }
}