问:
FragmentManager clean up for .addToBackStack
Is there anyway I can make this a bit cleaner? I know when query = "" I'm at the main menu and therefore back should close the app.</p>

```<code>        if (query == "") {
            fragmentManager.beginTransaction()
                    .replace(containerId, fragment, tag)
                    .commitAllowingStateLoss();
        } else {
            fragmentManager.beginTransaction()
                    .replace(containerId, fragment, tag)
                    .addToBackStack(null)
                    .commitAllowingStateLoss();
        }
</code>```

答:
Yes you can clean-up your fragment from activity one by one, here is the code...</p>

```<code>   public static void clearBackStack() {
        FragmentManager fm = mainActivity.getSupportFragmentManager();
        for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
             fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        }
    }
</code>```

Body:
Is there anyway I can make this a bit cleaner? I know when query = "" I'm at the main menu and therefore back should close the app.

        if (query == "") {
            fragmentManager.beginTransaction()
                    .replace(containerId, fragment, tag)
                    .commitAllowingStateLoss();
        } else {
            fragmentManager.beginTransaction()
                    .replace(containerId, fragment, tag)
                    .addToBackStack(null)
                    .commitAllowingStateLoss();
        }

Body:
Yes you can clean-up your fragment from activity one by one, here is the code...

   public static void clearBackStack() {
        FragmentManager fm = mainActivity.getSupportFragmentManager();
        for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
             fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        }
    }


来源: stackexchange

问:
not like does not apply to string extracted from dropdown menu
The following code should be able to return me some records that doesn't included the following:

```<code> RequestStatus <> 'Submission'
 OR RequestStatus <>'Pre-CRC submission'
 OR RequestStatus <>'CCT Review'
</code>```

Each of the items listed above are menu items coming from a drop down menu.Which should n't be listed in the final results. However, these items are listed in the results. Does anyone know what am I doing wrong here?

```<code>Select

    RequestStatus,
    IncidentID,
    max(LastModifiedDateTimeJ) as 'newfield',
    OwnedByTeamJ,
    DetailsJ,
    Status,
    OwnedByTeam
    from IncidentTicket
where
    CAST(CreatedDateTime as  DATE) >='05-01-2019'
    AND JournalTypeName like '%Journal - Note%'
    And OwnedByTeamJ like '%C - OS Review%'
    AND
       (
        RequestStatus <> 'Submission'
        OR RequestStatus <>'Pre-CRC submission'
        OR RequestStatus <>'CCT Review'
       )

group by  RequestStatus,IncidentID,OwnedByTeamJ
,DetailsJ,Status, OwnedByTeam
</code>```

Thanks,

答:
The condition

```<code>RequestStatus <> 'Submission'
OR RequestStatus <>'Pre-CRC submission'
OR RequestStatus <>'CCT Review'
</code>```

will always be true. You probably meant to use:

```<code>RequestStatus <> 'Submission'
AND RequestStatus <>'Pre-CRC submission'
AND RequestStatus <>'CCT Review'
</code>```

can actually be true if the value is unlike all of the given values.

ContentLicense: CC BY-SA 4.0

Body:
The following code should be able to return me some records that doesn't included the following:

 RequestStatus <> 'Submission'
 OR RequestStatus <>'Pre-CRC submission'
 OR RequestStatus <>'CCT Review'

Each of the items listed above are menu items coming from a drop down menu.Which should n't be listed in the final results. However, these items are listed in the results. Does anyone know what am I doing wrong here?

Select

    RequestStatus,
    IncidentID,
    max(LastModifiedDateTimeJ) as 'newfield',
    OwnedByTeamJ,
    DetailsJ,
    Status,
    OwnedByTeam
    from IncidentTicket
where
    CAST(CreatedDateTime as  DATE) >='05-01-2019'
    AND JournalTypeName like '%Journal - Note%'
    And OwnedByTeamJ like '%C - OS Review%'
    AND
       (
        RequestStatus <> 'Submission'
        OR RequestStatus <>'Pre-CRC submission'
        OR RequestStatus <>'CCT Review'
       )

group by  RequestStatus,IncidentID,OwnedByTeamJ
,DetailsJ,Status, OwnedByTeam

Thanks,

Body:
The condition

RequestStatus <> 'Submission'
OR RequestStatus <>'Pre-CRC submission'
OR RequestStatus <>'CCT Review'

will always be true. You probably meant to use:

RequestStatus <> 'Submission'
AND RequestStatus <>'Pre-CRC submission'
AND RequestStatus <>'CCT Review'

can actually be true if the value is unlike all of the given values.


问:
Convert List of Lists to Dictionary with unique keys and all related values
I'm python newbie and I'am currently struggling with one problem. I have a list of lists:

[[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]

My aim is to make a dictionary from it with the following format:

{0:[1],1:[2,8],2:[8,1,4,5],3:[4],5:[6,7,2],6:[5,7],7:[5,6],8:[1,2,10,9,11,12],9:[8,10,11,12],10:[8,9,11,12],11:[12,10,9,8],12:[11,9,10,8]}.

In short:

It has to make a dictionary with unique keys from 1 to 12 in this case (all unique numbers in a list), and to each key it assigns a list of values, which is a common subset for this key i.e for key 2 it appears in lists [4,2], [2,5], [1,2,8] so it has to assign to a key 2 a value which is a list of numbers in those 3 lists except 2.

Thus the output for key 2 should be: 2:[8,1,4,5] etc.

I've made some code:

```<code>data = [[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]

graph = {}
for i in range(13):
    graph[i] = 3

numbers = list(range(0,13))
for row in data:
    for i in graph.keys():
        if i in row:
            graph[i] = row

for key,value in graph.items():
    graph[key] = graph[key][1:]

print(graph)
</code>```

Yet, it gives me output:

{0: [1], 1: [2, 8], 2: [5], 3: [4], 4: [2], 5: [6, 7], 6: [6, 7], 7: [6, 7], 8: [9, 10, 11, 12], 9: [9, 10, 11, 12], 10: [9, 10, 11, 12], 11: [9, 10, 11, 12], 12: [9, 10, 11, 12]}

I really don't know how to combine those lists from this in such a way that I will get desired output.

答:
You're assigning graph[i] to only one row, so if you come across another row containing i, the answers from your initial row will get reassigned. Instead you might want to assign an empty list to graph[i] instead of 3 append to graph[i] instead.

```<code>graph = {}
for i in range(13):
  graph[i] = []

for row in data:
  for i in graph.keys():
    if i in row:
      for val in row:
        if val != i:
          graph[i].append(val)
</code>```

Body:
I'm python newbie and I'am currently struggling with one problem. I have a list of lists:

[[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]

My aim is to make a dictionary from it with the following format:

{0:[1],1:[2,8],2:[8,1,4,5],3:[4],5:[6,7,2],6:[5,7],7:[5,6],8:[1,2,10,9,11,12],9:[8,10,11,12],10:[8,9,11,12],11:[12,10,9,8],12:[11,9,10,8]}.

In short:

It has to make a dictionary with unique keys from 1 to 12 in this case (all unique numbers in a list), and to each key it assigns a list of values, which is a common subset for this key i.e for key 2 it appears in lists [4,2], [2,5], [1,2,8] so it has to assign to a key 2 a value which is a list of numbers in those 3 lists except 2.

Thus the output for key 2 should be: 2:[8,1,4,5] etc.

I've made some code:

data = [[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]

graph = {}
for i in range(13):
    graph[i] = 3

numbers = list(range(0,13))
for row in data:
    for i in graph.keys():
        if i in row:
            graph[i] = row

for key,value in graph.items():
    graph[key] = graph[key][1:]

print(graph)

Yet, it gives me output:

{0: [1], 1: [2, 8], 2: [5], 3: [4], 4: [2], 5: [6, 7], 6: [6, 7], 7: [6, 7], 8: [9, 10, 11, 12], 9: [9, 10, 11, 12], 10: [9, 10, 11, 12], 11: [9, 10, 11, 12], 12: [9, 10, 11, 12]}

I really don't know how to combine those lists from this in such a way that I will get desired output.

Body:
You're assigning graph[i] to only one row, so if you come across another row containing i, the answers from your initial row will get reassigned. Instead you might want to assign an empty list to graph[i] instead of 3 append to graph[i] instead.

graph = {}
for i in range(13):
  graph[i] = []

for row in data:
  for i in graph.keys():
    if i in row:
      for val in row:
        if val != i:
          graph[i].append(val)


问:
How to enlarge image without overlapping other elements?
My images in desktop view https://adsler.co.uk/find-an-event/ are flat. Want to increase their height so they look great in desktop too. However, 2 points.

One, can't seem to find the correct css selector.
Two, can't seem to do it without it overlapping other elements.

I just want it to make it taller (proportionally of course)

Html:

```<code><form class "event_filters" id class="event_filters" >....</form>
<div class="event-listing-view-header"></div>
<ul class="event_listings event-listings-table-bordered-change
event-listings-change" id ="event-listing-view">
<div class="line-layout" style="display: none;">
</h4><div class="boxes-view-listing-registered-code"></div></div>
<div class="events-organizer-name">....</div></div>
<div class="col-md-2">....</div>
<div class="col-md-3">....</div>
<div class="col-md-2">....</div>
<div class="col-md-3">....</div>
</div>
</code>```

Tried css:

```<code>@media (min-width: 768px) {.box-layout.event-img img {height: 200px; width: 400px;}}
</code>```

Nothing....

答:
The issue is your selector has a small typo/error. Change this:

```<code>.box-layout.event-img img { ... }
</code>```

to this:

```<code>.box-layout .event-img img { ... }
</code>```

The first one is looking for an image inside an element with class box-layout AND event-img. You want an image inside element with class event-img that is inside element with class box-layout. The space between the selector classes makes all the difference.

Body:
My images in desktop view https://adsler.co.uk/find-an-event/ are flat. Want to increase their height so they look great in desktop too. However, 2 points.

One, can't seem to find the correct css selector.
Two, can't seem to do it without it overlapping other elements.

I just want it to make it taller (proportionally of course)

Html:

<form class "event_filters" id class="event_filters" >....</form>

....

....

....

....

....

Tried css:

@media (min-width: 768px) {.box-layout.event-img img {height: 200px; width: 400px;}}

Nothing....

Body:
The issue is your selector has a small typo/error. Change this:

.box-layout.event-img img { ... }

to this:

.box-layout .event-img img { ... }

The first one is looking for an image inside an element with class box-layout AND event-img. You want an image inside element with class event-img that is inside element with class box-layout. The space between the selector classes makes all the difference.


问:
image.open opens the same image twice and advide for creating loop
I'm basically just starting to write in python, so excuse me if I'm missing something obvious. I'm trying to build a quick and very simple tool that combines two images in one while leaving a blank grey space with the specified color between them. Now, when I run this code, I basically get the result that I want, however, for some reason it doesn't contain the two different images, but the same image, namely the one I called "img", twice. This is what my code looks like:

For the problem:

```<code>img = Image.open("/Users/someone/Documents/Stimuli/1_5_1_n1.bmp")
img = img.resize((1280, 1280))
img1 = Image.open("/Users/someone/Documents/Stimuli/2_7_1_n1.bmp")
img1 = img.resize((1280, 1280))
bi = Image.new("RGBA", (2760, 1280), ("#808080"))
bi.paste(img, (0,0,1280,1280))
bi.paste(img1, (1480,0,2760,1280))
bi.show()
</code>```

答:
```<code>img1 = img.resize((1280, 1280))
</code>```

Presumably you meant img1.resize(...).

Body:
I'm basically just starting to write in python, so excuse me if I'm missing something obvious. I'm trying to build a quick and very simple tool that combines two images in one while leaving a blank grey space with the specified color between them. Now, when I run this code, I basically get the result that I want, however, for some reason it doesn't contain the two different images, but the same image, namely the one I called "img", twice. This is what my code looks like:

For the problem:

img = Image.open("/Users/someone/Documents/Stimuli/1_5_1_n1.bmp")
img = img.resize((1280, 1280))
img1 = Image.open("/Users/someone/Documents/Stimuli/2_7_1_n1.bmp")
img1 = img.resize((1280, 1280))
bi = Image.new("RGBA", (2760, 1280), ("#808080"))
bi.paste(img, (0,0,1280,1280))
bi.paste(img1, (1480,0,2760,1280))
bi.show()

Body:
img1 = img.resize((1280, 1280))

Presumably you meant img1.resize(...).


问:
Make struct Hashable?
I'm trying to create a dictionary of the sort [petInfo : UIImage]() but I'm getting the error Type 'petInfo' does not conform to protocol 'Hashable'. My petInfo struct is this:

```<code>struct petInfo {
    var petName: String
    var dbName: String
}
</code>```

So I want to somehow make it hashable but none of its components are an integer which is what the var hashValue: Int requires. How can I make it conform to the protocol if none of its fields are integers? Can I use the dbName if I know it's going to be unique for all occurrences of this struct?

答:
As of Swift 5 var hashValue:Int has been deprecated in favour of func hash(into hasher: inout Hasher) (introduced in Swift 4.2), so to update the answer @rmaddy gave use:

```<code>func hash(into hasher: inout Hasher) {
    hasher.combine(dbName)
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Make struct Hashable?

Body:
I'm trying to create a dictionary of the sort [petInfo : UIImage]() but I'm getting the error Type 'petInfo' does not conform to protocol 'Hashable'. My petInfo struct is this:

struct petInfo {
    var petName: String
    var dbName: String
}

So I want to somehow make it hashable but none of its components are an integer which is what the var hashValue: Int requires. How can I make it conform to the protocol if none of its fields are integers? Can I use the dbName if I know it's going to be unique for all occurrences of this struct?

Body:
As of Swift 5 var hashValue:Int has been deprecated in favour of func hash(into hasher: inout Hasher) (introduced in Swift 4.2), so to update the answer @rmaddy gave use:

func hash(into hasher: inout Hasher) {
    hasher.combine(dbName)
}


问:
I want to check open applications before turn off my computer through java program
Actually I am working on a java based application which has a functionality to turn off my system on a specific time and it's working fine but, the requirement says that if any application is open then it should not be close before turn off my system must have to close all the open application manually.
I am unable to find out the solution.</p>

答:
Java JNI
https://github.com/twall/jna/

Get the list of all processes via WinAPI and check for user_name in PEB of a process.
Or this http://msdn.microsoft.com/en-us/library/aa390460(v=vs.85).aspx :)


问:
Java scanner to read character frequency from file
I'm trying to get a scanner to read the frequency of characters in the filepath, while using a scanner. What should I add to complete this method to do what I've described. Using a priority Queue.</p>

```<code>public static Huffman build(String filePath) throws IOException {
    if (filePath == null) {
        throw new NullPointerException("File doesn't exist");
    } else {
        try {
            Scanner file = new Scanner(new File(filePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        while (file.hasNextLine()) {
            Scanner s2 = new Scanner(file.nextLine());
            while (s2.hasNext()) {
                String s = s2.next();
                System.out.println(s);
            }
        }
    }
}
</code>```

答:
A priority queue is relatively simple, it's a heap that preserves ordering. While a hashmap would probably be better here, pqueue isn't horrific.

Simply go through the entire character array of the file. Put everything in the priority queue. To get the frequency just pop the pqueue and store it in a map or something similar, or output it to wherever you need to output it.

Map is a lot better, but if you have to use a priority queue it's relatively straightforward

Body:
I'm trying to get a scanner to read the frequency of characters in the filepath, while using a scanner. What should I add to complete this method to do what I've described. Using a priority Queue.

public static Huffman build(String filePath) throws IOException {
    if (filePath == null) {
        throw new NullPointerException("File doesn't exist");
    } else {
        try {
            Scanner file = new Scanner(new File(filePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        while (file.hasNextLine()) {
            Scanner s2 = new Scanner(file.nextLine());
            while (s2.hasNext()) {
                String s = s2.next();
                System.out.println(s);
            }
        }
    }
}


问:
Delphi doesn't recognize that multiple printers are present
I've run into a strange problem.

My program is developped using Delphi7. On a client's computer, who is running Windows 7 64-bit, Printer.Printers.Count returns 0 even though there are multiple printers installed.

MS Word prints without problems and returns the correct list of printers.

Apparently, it used to work before on the same computer then stopped working at one point in the past.

There have been problems with the Spooler and network printers have been installed recently.

Of course it could cause the problem but it still doens't explain why Word sees the printers and Delphi doesn't.

Any ideas?

Thanks!

Edit: Running the program with elevated privileges solved the issue. The point goes to Martijn. Thanks!

答:
This sounds a bit like you’re running the program under elevated privileges (i.e. as administrator), where no printers have been installed, because they’re all under the user’s regular account.

Or vice-versa (printers installed as admin not accessible for program running with limited account privileges).

So I think this belongs on http://superuser.com.


问:
How to remove docker images based on name?
I want to delete all versions of docker images with names that contain a given string (imagename).

I have tried the below, but it doesn't seem to work:

docker images | grep 'imagename' |  xargs -I {} docker rmi

答:
Put together a solution to this question to meet my needs, that wasn't posted previously.

I wanted to match locally built images: library/myapp that I've renamed, tagged, and pushed to a private repo: myrepo.org/library/myapp.  Once they are pushed, I want to clean up the local docker reg.

And I don't care if nothing is found or the command throws an error. Thus added || true at the end for inclusion into scripts.

```<code>docker rmi $(docker image ls */library/myApp --format '{{.Repository}}:{{.Tag}}') || true
</code>```

Body:
Put together a solution to this question to meet my needs, that wasn't posted previously.

I wanted to match locally built images: library/myapp that I've renamed, tagged, and pushed to a private repo: myrepo.org/library/myapp.  Once they are pushed, I want to clean up the local docker reg.

And I don't care if nothing is found or the command throws an error. Thus added || true at the end for inclusion into scripts.

docker rmi $(docker image ls */library/myApp --format '{{.Repository}}:{{.Tag}}') || true


问:
how delete account YouTube for deceased personal
my relative is pass away and I want to delete his account youtube but I don't know his email and password.

答: You can go to Google’s support page, which can be found from a simple search into Google. This will take you to a page in which you will submit information in regards to the deceased person.</p>


问:
Does the Chrome browser development tools respect style changes specifying !important?
I'm doing a bit of CSS troubleshooting and, as you can imagine, I'm having a tough time getting a div to style the way I want it too.  In Chrome, I've opened the development window and I've selected my element to inspect the style settings.

I need to do a quick visual test of some of my changes from within a specific selector.  Note, I'm not looking to declare a temporary, specific value for the element.

I've found the selector, and the respective CSS property and as I knew, it is crossed out because a CSS definition of higher precedence is overriding it.  However, for my test I added !important after the property value but it did not update my element and remained crossed out.

We have some very complex CSS.  There is a chance that it's somehow being overridden but I wanted to be sure-- in Chrome browser, within the development window, if you override a style specified for an object, adding !important should it work?

答:
Does the Chrome browser development tools respect style changes specifying !important?

Yes it does respect the specificity.

You can however test the specificity of your rule before using it in the devtools (or anyplace for that matter) here


问:
Perform LU decomposition without pivoting in MATLAB
How can I implement the function lu(A) in MATLAB so that L*U is directly A and I also get the real L matrix?

When I use [L,U] = lu(A), MATLAB doesn't give me the right L matrix.  When I use [L,U,P] = lu(A), I need to implement P*A = L*U, but I only want to multiply L*U to receive A.

答:
You might want to consider doing LDU decomposition instead of unpivoted LU. See, LU without pivoting is numerically unstable - even for matrices that are full rank and invertible. The simple algorithm provided above shows why - there is division by each diagonal element of the matrix involved. Thus, if there is a zero anywhere on the diagonal, decomposition fails, even though the matrix could still be non-singular.

Wikipedia talks a little about LDU decomposition here:

https://en.wikipedia.org/wiki/LU_decomposition#LDU_decomposition

without citing an algorithm. It cites the following textbook for proof of existence:

Horn, Roger A.; Johnson, Charles R. (1985), Matrix Analysis, Cambridge University Press, ISBN 978-0-521-38632-6. See Section 3.5.

LDU is guaranteed to exist (at least for an invertible matrix), it is numerically stable, and it is also unique (provided that both L and U are constrained to have unit elements on the diagonal).

Then, if for any reason "D" gets in your way, you can absorb the diagonal matrix D into either L (L:=LD) or U (U:=DU), or split it symmetrically between L and U (such as L:=L*sqrt(D) and U:=sqrt(D)*U), or however you want to do it. There is an infinite number of ways to split LDU into LU, and this is why LU decomposition is not unique.


问:
Are blocks and libdispatch available on linux?
I would love to try out grand central dispatch, but all I have to develop on is an Ubuntu workstation. Is libdispatch, and the blocks extension to c/obj-c etc... available on linux? If so, how do I get them?</p>

答:
You may need to use the LLVM Clang (available on Ubuntu) compiler to get blocks at this time (I don't think this is available in gcc yet, but I haven't been keeping up with gcc, so I could be wrong.)

There are efforts underway to port libdispatch (home for the open source libdispatch) to Linux.  Most of the effort seems to be on Debian so far, but some on other distributions, too.  See these discussion threads:

linux + libdispatch + clang + blocks

libdispatch porting status update

Grand Central Dispatch available for Debian (archived link)


问:
Sprite Kit game design for chess game
I am new to Swift and iOS, I am planning to design a chess game (chinese chess) in iOS using Sprite Kit. I've been brainstorming the design strategies.
I have a question regarding creating the chess board and how the pieces move.

Unlike chess, each piece move to an intersection point, I am seeing people who make chess game board by creating each tile as a separate UIview, since the chinese chess board is harder to draw I was planning to just use the board image as one node, and each pieces simply move on top of the board. left right up down by calculating the distance of each square. ( for example, dividing the board width by 8 since there are 8 equal squares a row) Is this a good strategy or is there a better  way of implementing. I find this way not the most efficient since if the device changes, the board and pieces size would stay the same?

I would appreciate it if anyone can give me some advice.

答:
Here is a tutorial using the similar grid.
https://www.raywenderlich.com/55-how-to-make-a-game-like-candy-crush-with-spritekit-and-swift-part-1

First, you should create a helper class Array<2D> for your tiles and chess.

```<code>struct Array2D<T> {
  let columns: Int
  let rows: Int
  private var array: Array<T?>

  init(columns: Int, rows: Int) {
    self.columns = columns
    self.rows = rows
    array = Array<T?>(repeating: nil, count: rows*columns)
  }

  subscript(column: Int, row: Int) -> T? {
    get {
      return array[row*columns + column]
    }
    set {
      array[row*columns + column] = newValue
    }
  }
}
</code>```

You can create a custom class Chess, like this

```<code>import SpriteKit

// MARK: - ChessType
enum ChessType: Int {
  case unknown = 0, Horse, King, etc.
}

// MARK: - Chess
class Chess: CustomStringConvertible, Hashable {

  func hash(into hasher: inout Hasher) {
    hasher.combine(row)
    hasher.combine(column)
  }

  static func ==(lhs: Cookie, rhs: Cookie) -> Bool {
    return lhs.column == rhs.column && lhs.row == rhs.row

  }

  var description: String {
    return "type:\(chessType) square:(\(column),\(row))"
  }

  var column: Int
  var row: Int
  let chessType: ChessType
  var sprite: SKSpriteNode?

  init(column: Int, row: Int, chessType: ChessType) {
    self.column = column
    self.row = row
    self.chessType = chessType
  }
}
</code>```

To find a particular point/tile, you can use these helper methods in your game scene:

```<code>  private func pointFor(column: Int, row: Int) -> CGPoint {
    return CGPoint(x: CGFloat(column) * tileWidth + tileWidth/2,
                   y: CGFloat(row) * tileHeight + tileHeight/2)
  }

  private func convertPoint(_ point: CGPoint) -> (success: Bool, column: Int, row: Int) {
    if point.x >= 0 && point.x < CGFloat(numColumns) * tileWidth {
      if point.y >= 0 && point.y < CGFloat(numRows) * tileHeight {
        return (true, Int(point.x/tileWidth), Int(point.y/tileHeight))
      }
    }
    return (false, 0, 0)
  }
</code>```

Title: Sprite Kit game design for chess game

Body:
Here is a tutorial using the similar grid.
https://www.raywenderlich.com/55-how-to-make-a-game-like-candy-crush-with-spritekit-and-swift-part-1

First, you should create a helper class Array<2D> for your tiles and chess.

struct Array2D<T> {
  let columns: Int
  let rows: Int
  private var array: Array<T?>

  init(columns: Int, rows: Int) {
    self.columns = columns
    self.rows = rows
    array = Array<T?>(repeating: nil, count: rows*columns)
  }

  subscript(column: Int, row: Int) -> T? {
    get {
      return array[row*columns + column]
    }
    set {
      array[row*columns + column] = newValue
    }
  }
}

You can create a custom class Chess, like this

import SpriteKit

// MARK: - ChessType
enum ChessType: Int {
  case unknown = 0, Horse, King, etc.
}

// MARK: - Chess
class Chess: CustomStringConvertible, Hashable {

  func hash(into hasher: inout Hasher) {
    hasher.combine(row)
    hasher.combine(column)
  }

  static func ==(lhs: Cookie, rhs: Cookie) -> Bool {
    return lhs.column == rhs.column && lhs.row == rhs.row

  }

  var description: String {
    return "type:\(chessType) square:(\(column),\(row))"
  }

  var column: Int
  var row: Int
  let chessType: ChessType
  var sprite: SKSpriteNode?

  init(column: Int, row: Int, chessType: ChessType) {
    self.column = column
    self.row = row
    self.chessType = chessType
  }
}

To find a particular point/tile, you can use these helper methods in your game scene:

  private func pointFor(column: Int, row: Int) -> CGPoint {
    return CGPoint(x: CGFloat(column) * tileWidth + tileWidth/2,
                   y: CGFloat(row) * tileHeight + tileHeight/2)
  }

  private func convertPoint(_ point: CGPoint) -> (success: Bool, column: Int, row: Int) {
    if point.x >= 0 && point.x < CGFloat(numColumns) * tileWidth {
      if point.y >= 0 && point.y < CGFloat(numRows) * tileHeight {
        return (true, Int(point.x/tileWidth), Int(point.y/tileHeight))
      }
    }
    return (false, 0, 0)
  }


问:
Chart.js sets canvas dimentions to 0x0 and do not display anything
I got the first char.js example from official docs and tried to implement it with angular. No errors, chart object is created normally but nothing is displayed. When I examine DOM in devtools I see that chart.js set width/height of canvas to 0. What I did wrong?

The code: https://stackblitz.com/edit/angular-chartjs-ex

答:
The chart is not visible because the component host is an inline element. As such, it should not contain block elements like the div wrapper created by the Chart.js library.

Setting the display style attribute of the host to block or inline-block will make the chart visible:

```<code>:host {
  display: inline-block;
}
</code>```

See this stackblitz for a demo.

Body:
The chart is not visible because the component host is an inline element. As such, it should not contain block elements like the div wrapper created by the Chart.js library.

Setting the display style attribute of the host to block or inline-block will make the chart visible:

:host {
  display: inline-block;
}

See this stackblitz for a demo.


问:
MySQL Trigger - AFTER CREATE ON not working
When I try to create a trigger which insert something in the table questiontypes after the creation of a table in USER1 schema I get this error from MySQL (executing it on phpmyadmin) : Sorry an unexpected error happened!

```<code>DELIMITER $$

CREATE OR REPLACE TRIGGER create_table_trigger
AFTER CREATE ON USER1.SCHEMA
BEGIN
    INSERT INTO USER1.questiontypes VALUES('text');
END;

DELIMITER ;
</code>```

Does anyone have a solution ?

答:
It is difficult to find documentation on the non-existence of something; but the absence of any mention of DDL triggers from MYSQL's rather detailed documentation is a big indicator.

Also, the official documentation on CREATE TRIGGER only show INSERT, UPDATE, and DELETE as event types. here

The nearest I could find any official mention was from an unassigned MySql "worklog" entry here, documenting a request for the feature.

Body:
When I try to create a trigger which insert something in the table questiontypes after the creation of a table in USER1 schema I get this error from MySQL (executing it on phpmyadmin) : Sorry an unexpected error happened!

DELIMITER $$

CREATE OR REPLACE TRIGGER create_table_trigger
AFTER CREATE ON USER1.SCHEMA
BEGIN
    INSERT INTO USER1.questiontypes VALUES('text');
END;

DELIMITER ;

Does anyone have a solution ?


问:
How to detect if a web page is running from a website or local file system
I'm a newbie to javascript. How can I detect if my javascript is being run from a web site (http://) vs a local file.</p>

答:
For testing different 'kinds' of local, all at once:

```<code>// Returns the page location type
// 0 (falsey) = Local file, direct from disk (file://path/to/file.html)
// 1 (truthy) = Virtually remote file, from local server (http://localhost)
// 2 (truthy) = Remote file from remote server (http://example.com)

function locationType(){
    if( window.location.protocol == 'file:' ){ return 0; }
    if( !window.location.host.replace( /localhost|127\.0\.0\.1/i, '' ) ){ return 2; }
    return 1;
}
</code>```

Rationale: you may want to test for whether the page is a) on a remote server, or b) on a local server (same computer, for testing, like with AMP), or c) a local file, retrieved directly from disk via the "file://" protocol.

Note that this doesn't handle every possible edge case. For example, you can technically redirect different IPs to "localhost", and other non-"file://" schemes (like "foo://") may in fact represent local access. But it works for most cases and can be otherwise tweaked as needed

Testing only for "http" and "https" is a bit limited, since there are dozens of other LAN and WAN network schemes in use around the world. Whether or not they're local or can even use HTML/JS code may vary, of course (IANA URI Schemes).

ContentLicense: CC BY-SA 2.5

Body:
For testing different 'kinds' of local, all at once:

// Returns the page location type
// 0 (falsey) = Local file, direct from disk (file://path/to/file.html)
// 1 (truthy) = Virtually remote file, from local server (http://localhost)
// 2 (truthy) = Remote file from remote server (http://example.com)

function locationType(){
    if( window.location.protocol == 'file:' ){ return 0; }
    if( !window.location.host.replace( /localhost|127\.0\.0\.1/i, '' ) ){ return 2; }
    return 1;
}

Rationale: you may want to test for whether the page is a) on a remote server, or b) on a local server (same computer, for testing, like with AMP), or c) a local file, retrieved directly from disk via the "file://" protocol.

Note that this doesn't handle every possible edge case. For example, you can technically redirect different IPs to "localhost", and other non-"file://" schemes (like "foo://") may in fact represent local access. But it works for most cases and can be otherwise tweaked as needed

Testing only for "http" and "https" is a bit limited, since there are dozens of other LAN and WAN network schemes in use around the world. Whether or not they're local or can even use HTML/JS code may vary, of course (IANA URI Schemes).


问:
Is there a way to simulate a click on an alert in JavaScript?
I have a page with an iframe whose source page is in a separate domain. From time to time, the source page generates an alert. When it does so, it stops what it is doing until the user clicks OK to the alert.

What I would like to do is programmatically click OK on this alert so the source page can get back to being useful. Is this possible?

答:
You shouldn't have a problem if you know the text of the alert and don't mind getting dirty.

You can override the iframe window's alert with your own and do something to the effect of..

```<code>document.getElementById("InnerFrameName").contentWindow.alert = function(){
    if (arguments[0].toLowerCase() == "innerframe alert text")
        return; //supress
    else
        alert(arguments[0]);
};
</code>```

Edit: I made a little test with a proxy handler (it's in asp.net/c# but you should get the idea)...

The external page in my test is a w3 page with a button that displays an alert, the alert is now passed through the user defined function.

I'm sure this is alot more dirty then you'd like to get.

Page:

```<code><%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Hello From MyPage</title>
    <script type="text/javascript">
        function frameLoaded() {
            document.getElementById("InnerFrameName").contentWindow.alert = function() {
                if (arguments[0].toLowerCase() == "i am an alert box!!") {
                    alert("MESSAGES WOULD BE SUPRESSED: " + arguments[0]);
                    return; //supress
                } else {
                    alert(arguments[0]);
                }
            };
        }
        </script>
</head>
<body onload="alert('Hello from an unsupressed top level frame message!');">
    <form id="form1" runat="server">
            <div>
                <h1>Internal Page (Top Level)</h1>
                <hr />
                <iframe id="InnerFrameName" onload="frameLoaded();" src="PageProxy.ashx?externalURI=http://www.w3schools.com/JS/tryit_view.asp?filename=tryjs_alert"
                    style="width: 800px; height: 600px;">Derp!...</iframe>
            </div>
    </form>
</body>
</html>
</code>```

Proxy Handler:

```<code><%@ WebHandler Language="C#" Class="PageProxy" %>

using System;
using System.Web;

public class PageProxy : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
            byte[] externalPage = new System.Net.WebClient().DownloadData(context.Request["externalURI"]);
            context.Response.OutputStream.Write(externalPage, 0, externalPage.Length);
            context.Response.End();
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
}
</code>```

OwnerDisplayName: moffdub

Body:
You shouldn't have a problem if you know the text of the alert and don't mind getting dirty.

You can override the iframe window's alert with your own and do something to the effect of..

document.getElementById("InnerFrameName").contentWindow.alert = function(){
    if (arguments[0].toLowerCase() == "innerframe alert text")
        return; //supress
    else
        alert(arguments[0]);
};

Edit: I made a little test with a proxy handler (it's in asp.net/c# but you should get the idea)...

The external page in my test is a w3 page with a button that displays an alert, the alert is now passed through the user defined function.

I'm sure this is alot more dirty then you'd like to get.

Page:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Hello From MyPage</title>
    <script type="text/javascript">
        function frameLoaded() {
            document.getElementById("InnerFrameName").contentWindow.alert = function() {
                if (arguments[0].toLowerCase() == "i am an alert box!!") {
                    alert("MESSAGES WOULD BE SUPRESSED: " + arguments[0]);
                    return; //supress
                } else {
                    alert(arguments[0]);
                }
            };
        }
        </script>
</head>
<body onload="alert('Hello from an unsupressed top level frame message!');">
    <form id="form1" runat="server">
            <div>
                <h1>Internal Page (Top Level)</h1>
                <hr />
                <iframe id="InnerFrameName" onload="frameLoaded();" src="PageProxy.ashx?externalURI=http://www.w3schools.com/JS/tryit_view.asp?filename=tryjs_alert"
                    style="width: 800px; height: 600px;">Derp!...</iframe>
            </div>
    </form>
</body>
</html>

Proxy Handler:

<%@ WebHandler Language="C#" Class="PageProxy" %>

using System;
using System.Web;

public class PageProxy : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
            byte[] externalPage = new System.Net.WebClient().DownloadData(context.Request["externalURI"]);
            context.Response.OutputStream.Write(externalPage, 0, externalPage.Length);
            context.Response.End();
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
}

OwnerDisplayName: CQ

LastEditorDisplayName: CQ


问:
Errors: Data path ".builders['app-shell']" should have required property 'class'
I am getting this error while running my application. Here are the details of my application.

```<code>Angular CLI: 7.3.3
Node: 10.15.1
Angular: 7.2.7
@angular-devkit/architect -0.13.3
@angular-devkit/build-angular- 0.800.1
@angular-devkit/build-optimizer - 0.800.1
@angular-devkit/build-webpack - 0.800.1
@angular-devkit/core -7.3.3
@angular-devkit/schematics -7.3.3
@angular/cli -7.3.3
@ngtools/webpack -8.0.1
@schematics/angular -7.3.3
@schematics/update 0.13.3
rxjs 6.3.3
typescript 3.2.4
webpack 4.30.0
</code>```

I have already tried cache clean.

答:
You have incompatibly dependencies  i solved this problem by change the package.json form another project angular and then after change to this packag.json, you change only the dependencies versions you have.

after the change write:

-npm link

-npm serve -o

then it's work :)

```<code>   {
   "name": "angular-jwt-auth",
   "version": "0.0.0",
   "scripts": {
   "ng": "ng",
   "start": "ng serve",
   "build": "ng build",
   "test": "ng test",
   "lint": "ng lint",
   "e2e": "ng e2e"
   },
   "private": true,
   "dependencies": {
   "@angular/animations": "^7.1.4",
   "@angular/cdk": "^7.3.1",
   "@angular/common": "~7.1.0",
   "@angular/compiler": "~7.1.0",
   "@angular/core": "~7.1.0",
   "@angular/forms": "~7.1.0",
   "@angular/http": "^6.1.10",
   "@angular/material": "^7.3.1",
   "@angular/platform-browser": "~7.1.0",
   "@angular/platform-browser-dynamic": "~7.1.0",
   "@angular/router": "~7.1.0",
   "@ng-bootstrap/ng-bootstrap": "^4.2.0",
   "@types/jquery": "^3.3.29",
   "angular-6-datatable": "^0.8.0",
   "bootstrap": "^4.3.1",
   "chart.js": "^2.8.0",
   "core-js": "^2.5.4",
   "jquery": "^3.4.1",
   "rxjs": "~6.3.3",
   "zone.js": "~0.8.26"
    },
   "devDependencies": {
   "@angular-devkit/build-angular": "~0.11.0",
   "@angular/cli": "~7.1.0",
   "@angular/compiler-cli": "~7.1.0",
   "@angular/language-service": "~7.1.0",
   "@types/chart.js": "^2.7.53",
   "@types/jasmine": "^2.8.16",
   "@types/jasminewd2": "^2.0.6",
   "@types/node": "~8.9.4",
   "codelyzer": "~4.2.1",
   "jasmine-core": "~2.99.1",
   "jasmine-spec-reporter": "~4.2.1",
   "karma": "~3.1.1",
   "karma-chrome-launcher": "~2.2.0",
   "karma-coverage-istanbul-reporter": "~2.0.1",
   "karma-jasmine": "~1.1.2",
   "karma-jasmine-html-reporter": "^0.2.2",
   "protractor": "~5.4.0",
   "ts-node": "~7.0.0",
   "tslint": "~5.11.0",
   "typescript": "~3.1.6"
   }
</code>```

Body:
I am getting this error while running my application. Here are the details of my application.

Angular CLI: 7.3.3
Node: 10.15.1
Angular: 7.2.7
@angular-devkit/architect -0.13.3
@angular-devkit/build-angular- 0.800.1
@angular-devkit/build-optimizer - 0.800.1
@angular-devkit/build-webpack - 0.800.1
@angular-devkit/core -7.3.3
@angular-devkit/schematics -7.3.3
@angular/cli -7.3.3
@ngtools/webpack -8.0.1
@schematics/angular -7.3.3
@schematics/update 0.13.3
rxjs 6.3.3
typescript 3.2.4
webpack 4.30.0

I have already tried cache clean.

Body:
You have incompatibly dependencies  i solved this problem by change the package.json form another project angular and then after change to this packag.json, you change only the dependencies versions you have.

after the change write:

-npm link

-npm serve -o

then it's work :)

   {
   "name": "angular-jwt-auth",
   "version": "0.0.0",
   "scripts": {
   "ng": "ng",
   "start": "ng serve",
   "build": "ng build",
   "test": "ng test",
   "lint": "ng lint",
   "e2e": "ng e2e"
   },
   "private": true,
   "dependencies": {
   "@angular/animations": "^7.1.4",
   "@angular/cdk": "^7.3.1",
   "@angular/common": "~7.1.0",
   "@angular/compiler": "~7.1.0",
   "@angular/core": "~7.1.0",
   "@angular/forms": "~7.1.0",
   "@angular/http": "^6.1.10",
   "@angular/material": "^7.3.1",
   "@angular/platform-browser": "~7.1.0",
   "@angular/platform-browser-dynamic": "~7.1.0",
   "@angular/router": "~7.1.0",
   "@ng-bootstrap/ng-bootstrap": "^4.2.0",
   "@types/jquery": "^3.3.29",
   "angular-6-datatable": "^0.8.0",
   "bootstrap": "^4.3.1",
   "chart.js": "^2.8.0",
   "core-js": "^2.5.4",
   "jquery": "^3.4.1",
   "rxjs": "~6.3.3",
   "zone.js": "~0.8.26"
    },
   "devDependencies": {
   "@angular-devkit/build-angular": "~0.11.0",
   "@angular/cli": "~7.1.0",
   "@angular/compiler-cli": "~7.1.0",
   "@angular/language-service": "~7.1.0",
   "@types/chart.js": "^2.7.53",
   "@types/jasmine": "^2.8.16",
   "@types/jasminewd2": "^2.0.6",
   "@types/node": "~8.9.4",
   "codelyzer": "~4.2.1",
   "jasmine-core": "~2.99.1",
   "jasmine-spec-reporter": "~4.2.1",
   "karma": "~3.1.1",
   "karma-chrome-launcher": "~2.2.0",
   "karma-coverage-istanbul-reporter": "~2.0.1",
   "karma-jasmine": "~1.1.2",
   "karma-jasmine-html-reporter": "^0.2.2",
   "protractor": "~5.4.0",
   "ts-node": "~7.0.0",
   "tslint": "~5.11.0",
   "typescript": "~3.1.6"
   }


问:
Is posible on insert query use auto-increment to concatenate with string for column value?
Is posible on insert query use auto-increment to concatenate with string for one column value?

The current AUTO-INCREMENT is = 89 name columns pkey

Example query string:

```<code>INSERT INTO `Tbl` (`ProcessCod`, `ProcessName`, ) VALUES(CONCAT('f-pdf-',AUTO-INCREMENT), 'Text-Description');
</code>```

All in one query???

update i think on a string like this:

```<code>INSERT INTO `Tbl` (
    `ProcessCod`,
    `ProcessName`)
VALUES(
    SELECT CONCAT('f-pdf-',`AUTO_INCREMENT`)
    FROM  INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA = 'INFO'
    AND   TABLE_NAME   = 'Tbl',
    'Text-Description'
);
</code>```

the scope of my question is around the use of auto-increment (no primary key) to fill a column with it and concatenating with a dinamic string not a static prefix.

答:
i have solved with this code:

```<code>INSERT INTO Tbl (
    ProcessCod,
    ProcessName
)VALUES(
    (SELECT CONCAT('f-pdf-',`AUTO_INCREMENT`)
    FROM  INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA = 'INFO'
    AND   TABLE_NAME   = 'Tbl'),
    'Text-Description'
);
</code>```

it was necessary to place the Select in parentheses so that it works correctly.

Body:
Is posible on insert query use auto-increment to concatenate with string for one column value?

The current AUTO-INCREMENT is = 89 name columns pkey

Example query string:

INSERT INTO `Tbl` (`ProcessCod`, `ProcessName`, ) VALUES(CONCAT('f-pdf-',AUTO-INCREMENT), 'Text-Description');

All in one query???

update i think on a string like this:

INSERT INTO `Tbl` (
    `ProcessCod`,
    `ProcessName`)
VALUES(
    SELECT CONCAT('f-pdf-',`AUTO_INCREMENT`)
    FROM  INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA = 'INFO'
    AND   TABLE_NAME   = 'Tbl',
    'Text-Description'
);

the scope of my question is around the use of auto-increment (no primary key) to fill a column with it and concatenating with a dinamic string not a static prefix.

Body:
i have solved with this code:

INSERT INTO Tbl (
    ProcessCod,
    ProcessName
)VALUES(
    (SELECT CONCAT('f-pdf-',`AUTO_INCREMENT`)
    FROM  INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA = 'INFO'
    AND   TABLE_NAME   = 'Tbl'),
    'Text-Description'
);

it was necessary to place the Select in parentheses so that it works correctly.


问:
Evaluating a List of Variables to a List of Their Values in Common Lisp
I am wondering how one can achieve the following. Suppose I have a list of variables that are bound by some let above. I would like to turn this list into a list of the values to which those variables are bound.

That is, suppose we have

```<code>(define make-plist-from-variables (variables)
  (let ((keys variables)
        (values (mapcar #'identity variables)))
    (if (eq (length keys) (length values))
     (make-plist keys values)
     nil))))
</code>```

What can I use in place of #'identity to unpack those values properly?

At the moment, the following call produces the following output.

```<code>CL-USER> (let ((a 2) (b 3)) (make-plist-from-variables '(a b)))
(A A B B)
</code>```

I would like it to be (A 2 B 3)

答:
Functions don't have access to the lexical environment of their callers.
More precisely, during evaluation you cannot access the values of lexical variables knowing only their symbols. Only macros have access to environment objects.

Special variables

You can use dynamic binding:

```<code>(defun foo ()
  (declare (special a))
  (symbol-value 'a))

(let ((a 3))
  (declare (special a))
  (foo))

=> 3
</code>```

In your case, you would collect the symbol along its value, by using SYMBOL-vaLUE on all your symbols.

Related to your question is how to dynamically bind variables to values where the variable names and/or values are known at evaluation time; see special operator PROGV.

Macros

You could obtain e.g. an association list by writing the following code:

```<code>(acons 'a a (acons 'b b nil))
</code>```

Depending on the use case behind your question, you may want to have a macro that expands into such code, that references the variables you want to evaluate.

Body:
I am wondering how one can achieve the following. Suppose I have a list of variables that are bound by some let above. I would like to turn this list into a list of the values to which those variables are bound.

That is, suppose we have

(define make-plist-from-variables (variables)
  (let ((keys variables)
        (values (mapcar #'identity variables)))
    (if (eq (length keys) (length values))
     (make-plist keys values)
     nil))))

What can I use in place of #'identity to unpack those values properly?

At the moment, the following call produces the following output.

CL-USER> (let ((a 2) (b 3)) (make-plist-from-variables '(a b)))
(A A B B)

I would like it to be (A 2 B 3)

Body:
Functions don't have access to the lexical environment of their callers.
More precisely, during evaluation you cannot access the values of lexical variables knowing only their symbols. Only macros have access to environment objects.

Special variables

You can use dynamic binding:

(defun foo ()
  (declare (special a))
  (symbol-value 'a))

(let ((a 3))
  (declare (special a))
  (foo))

=> 3

In your case, you would collect the symbol along its value, by using SYMBOL-vaLUE on all your symbols.

Related to your question is how to dynamically bind variables to values where the variable names and/or values are known at evaluation time; see special operator PROGV.

Macros

You could obtain e.g. an association list by writing the following code:

(acons 'a a (acons 'b b nil))

Depending on the use case behind your question, you may want to have a macro that expands into such code, that references the variables you want to evaluate.


问:
Remove directory from Google Cloud Compute Engine using serial console
The storage on my Google Cloud Compute Engine Instance (inadvertently) got completely used up. I can no longer SSH into my instance. I have increased the space on my instance, but it still will not allow me to SSH. My VM operating system is Ubuntu.

I have tried two things:

1.) I have tried creating a start script to remove a large directory to clear up some space. Under "custom metadata" I have set the key as "startup-script" and the value as

#! /bin/bash
rm /home/myusername/dir-to-rm
```

<p>I save and reset the instance, click "connect to serial console", but I still cannot SSH.</p>

<p>2.) I have tried to use a startup script to set a login username and password for the serial console by using the same method, but with the following script:</p>

<pre class="lang-sh prettyprint-override"><code>#! /bin/bash
sudo useradd tmpuser
echo 'tmpuser:password' | chpasswd
</code>```

答:
I donated my time to help this person since he is a student. Total time to recover was about an hour.

The problem was caused by a corrupted file system. Repairing the file system corrected the problem. I then resized the disk larger to provide more free space.

During startup, the network interfaces failed to load. This, of course, prevents any form of connectivity. This is why SSH did not work.

Body:
The storage on my Google Cloud Compute Engine Instance (inadvertently) got completely used up. I can no longer SSH into my instance. I have increased the space on my instance, but it still will not allow me to SSH. My VM operating system is Ubuntu.

I have tried two things:

1.) I have tried creating a start script to remove a large directory to clear up some space. Under "custom metadata" I have set the key as "startup-script" and the value as

#! /bin/bash
rm /home/myusername/dir-to-rm

I save and reset the instance, click "connect to serial console", but I still cannot SSH.

2.) I have tried to use a startup script to set a login username and password for the serial console by using the same method, but with the following script:

#! /bin/bash
sudo useradd tmpuser
echo 'tmpuser:password' | chpasswd


问:
Converting VB6 varables to C#
I am converting old VB6 code and am having an issue with these constants:

VB6 code:

```<code>Private Const GENERIC_WRITE = &H40000000
Private Const GENERIC_READ = &H80000000
</code>```

C# code:

```<code>private const int GENERIC_WRITE = 0x40000000;
private const uint GENERIC_READ = 0x80000000;
</code>```

Why does the second line have to be uint?
If I do it as int, it gives me an error?

答:
The maximum value of Int32 is 2,147,483,647, and the value of 0x80000000 is 2,147,483,648, or Int32.MaxValue + 1.

Using a uint (or long) gives you a type that's large enough to hold the value you are assigning.

Title: Converting VB6 varables to C#

Body:
I am converting old VB6 code and am having an issue with these constants:

VB6 code:

Private Const GENERIC_WRITE = &H40000000
Private Const GENERIC_READ = &H80000000

C# code:

private const int GENERIC_WRITE = 0x40000000;
private const uint GENERIC_READ = 0x80000000;

Why does the second line have to be uint?
If I do it as int, it gives me an error?


Title: Regex - match up to next match

Body:
I would like to iterate matches over a text, the blocks I want to match start with a number then a tab character.

My beginning match is ^\d+\t, but is there a way to indicate that I want all text including this match up until the next match?

Input data:

1       111.111.111.111
111.111.111.111
                    Host IP     111.111.111.111
111.111.111.111
111.111.111.111         Host IP     TCP             app     11111, 11111, 11111, 11111      Allow
2       111.111.111.111
111.111.111.111
111.111.111.111         Host IP     111.111.111.111
111.111.111.111         Host IP     TCP             app     11111, 11111, 11111, 11111      Allow
3       111.111.111.111
111.111.111.111         Host IP     111.111.111.111
111.111.111.111
111.111.111.111
111.111.111.111         Host IP     TCP             app     11111, 11111, 11111, 11111      Allow
4       111.111.111.111
111.111.111.111
111.111.111.111
111.111.111.111         Host IP     111.111.111.111
111.111.111.111         Host IP     TCP             app     11111, 11111, 11111, 11111      Allow

I'm using Perl.

Body:
while (/
    \G
    ( \d+\t )
    ( (?: (?! \d+\t ) . )* )
/xg) {
    print("match:  $1\n");
    print("buffer: $2\n");
}


问:
In a non-const member function, why is point this non-const, while decltype pointer this is const?
I have a heavily templated class from which I want to use a getter. Following a common convention, I've avoided code duplication like so:

```<code>template< typename Foo, typename... Bars >
class Templated
{
...

  constexpr const Foo& get() const
  {
    return mFoo;
  }

  constexpr Foo& get()
  {
    return const_cast<Foo&>(const_cast<const Templated<Foo, Bars...> *>(this)->get());
  }
</code>```

However it occurred to me that the second definition gets a bit clunky, especially with a class that has many template parameters. Luckily I figured out after a little messing around that I could simplify this for any generic class template to:

```<code>constexpr Foo& get()
{
  return const_cast<Foo&>(const_cast<decltype(this)>(this)->get());
</code>```

This works because, for some reason, decltype(this) resolves to a const pointer to the class object type, whereas just (this) resolves to a non-const pointer to the class object type. Why in the world is this the case?

答:
"const pointer to the class object type" isn't what you want.

this is immutable (this = nullptr; is illegal).  Not *this.

Make your life much easier by just making add_const and remove_const template functions (or use std::as_const if your C++ version is new enough):

```<code>template<typename T>
const T* add_const(T* ptr) { return ptr; } // no cast at all!

template<typename T>
T* remove_const(const T* ptr) { return const_cast<T*>(ptr); }
template<typename T>
T& remove_const(const T& ref) { return const_cast<T&>(ref); }
</code>```

Here add_const(this) correctly results in `non-const pointer to const object type".

For that matter, from inside the class you can just add

```<code>auto cthis() const { return this; }
</code>```

Body:
I have a heavily templated class from which I want to use a getter. Following a common convention, I've avoided code duplication like so:

template< typename Foo, typename... Bars >
class Templated
{
...

  constexpr const Foo& get() const
  {
    return mFoo;
  }

  constexpr Foo& get()
  {
    return const_cast<Foo&>(const_cast<const Templated<Foo, Bars...> *>(this)->get());
  }

However it occurred to me that the second definition gets a bit clunky, especially with a class that has many template parameters. Luckily I figured out after a little messing around that I could simplify this for any generic class template to:

constexpr Foo& get()
{
  return const_cast<Foo&>(const_cast<decltype(this)>(this)->get());

This works because, for some reason, decltype(this) resolves to a const pointer to the class object type, whereas just (this) resolves to a non-const pointer to the class object type. Why in the world is this the case?

Body:
"const pointer to the class object type" isn't what you want.

this is immutable (this = nullptr; is illegal).  Not *this.

Make your life much easier by just making add_const and remove_const template functions (or use std::as_const if your C++ version is new enough):

template<typename T>
const T* add_const(T* ptr) { return ptr; } // no cast at all!

template<typename T>
T* remove_const(const T* ptr) { return const_cast<T*>(ptr); }
template<typename T>
T& remove_const(const T& ref) { return const_cast<T&>(ref); }

Here add_const(this) correctly results in `non-const pointer to const object type".

For that matter, from inside the class you can just add

auto cthis() const { return this; }


问:
Extraction of Data using tbodyclass and Beautifulsoup
Extraction with tbody class using BeautifulSoup and Python 3.

Im trying to extract the table (summary) on top of it. Im using BeautifulSoup for extraction. However I get the following error while using tclass to extract the table containing name,age,info etc

I am aware I can use the previous table{class :datatable} to extract the table .However I want to try extracting using tbody class

How do i extract the table with tbodyclass and what error am i making?
Im bit new to web scraping and any  detailed help would be appreciated

Here is the code

```<code>import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
import requests

urls=['https://www.reuters.com/finance/stocks/company- officers/GOOG.O',
      'https://www.reuters.com/finance/stocks/company- officers/AMZN',
      'https://www.reuters.com/finance/stocks/company- officers/AAPL']

for item in urls:
   response=requests.get(item)
   data=response.content
   soup=BeautifulSoup(data,'html.parser')
   required_data=soup.find_all(class_='moduleBody')
   real_data=required_data.find_all(tbodyclass_='dataSmall')
   print(real_data)
</code>```

Here is the Error

```<code>Traceback (most recent call last):
 File "C:\Users\XXXX\Desktop\scrape.py", line 15, in <module>
real_data=required_data.find_all(tbodyclass_='dataSmall')
 File "C:\Users\XXXX\AppData\Local\Programs\Python\Python37\lib\site-
 packages\bs4\element.py", line 1620, in __getattr__
"ResultSet object has no attribute '%s'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?" % key
AttributeError: ResultSet object has no attribute 'find_all'. You're
probably treating a list of items like a single item. Did you call
find_all() when you meant to call find()?
</code>```

答:
The findall() function returns a set of results. This is useful when more than one occurrence of the tag is present.

You need to iterate over the results, and using findall() on each one separately:

for item in urls:
   response = requests.get(item)
   data = response.content
   soup = BeautifulSoup(data, 'html.parser')
   required_data = soup.find_all(class_='moduleBody')
   for res in required_data:
    real_data = res.find_all(tbodyclass_='dataSmall')
    print(real_data)
```

<p>Edit: One find_all is enough:</p>

<pre class="lang-py prettyprint-override"><code>import requests
from bs4 import BeautifulSoup
url = ["https://www.reuters.com/finance/stocks/company-officers/GOOG.O", "https://www.reuters.com/finance/stocks/company-officers/AMZN.O", "https://www.reuters.com/finance/stocks/company-officers/AAPL.O"]
for URL in url:
    req = requests.get(URL)
    soup = BeautifulSoup(req.content, 'html.parser')
    for i in soup.find_all("tbody", {"class": "dataSmall"}):
        print(i)
</code>```

Body:
Extraction with tbody class using BeautifulSoup and Python 3.

Im trying to extract the table (summary) on top of it. Im using BeautifulSoup for extraction. However I get the following error while using tclass to extract the table containing name,age,info etc

I am aware I can use the previous table{class :datatable} to extract the table .However I want to try extracting using tbody class

How do i extract the table with tbodyclass and what error am i making?
Im bit new to web scraping and any  detailed help would be appreciated

Here is the code

import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
import requests

urls=['https://www.reuters.com/finance/stocks/company- officers/GOOG.O',
      'https://www.reuters.com/finance/stocks/company- officers/AMZN',
      'https://www.reuters.com/finance/stocks/company- officers/AAPL']

for item in urls:
   response=requests.get(item)
   data=response.content
   soup=BeautifulSoup(data,'html.parser')
   required_data=soup.find_all(class_='moduleBody')
   real_data=required_data.find_all(tbodyclass_='dataSmall')
   print(real_data)

Here is the Error

Traceback (most recent call last):
 File "C:\Users\XXXX\Desktop\scrape.py", line 15, in <module>
real_data=required_data.find_all(tbodyclass_='dataSmall')
 File "C:\Users\XXXX\AppData\Local\Programs\Python\Python37\lib\site-
 packages\bs4\element.py", line 1620, in __getattr__
"ResultSet object has no attribute '%s'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?" % key
AttributeError: ResultSet object has no attribute 'find_all'. You're
probably treating a list of items like a single item. Did you call
find_all() when you meant to call find()?

Body:
The findall() function returns a set of results. This is useful when more than one occurrence of the tag is present.

You need to iterate over the results, and using findall() on each one separately:

for item in urls:
   response = requests.get(item)
   data = response.content
   soup = BeautifulSoup(data, 'html.parser')
   required_data = soup.find_all(class_='moduleBody')
   for res in required_data:
    real_data = res.find_all(tbodyclass_='dataSmall')
    print(real_data)

Edit: One find_all is enough:

import requests
from bs4 import BeautifulSoup
url = ["https://www.reuters.com/finance/stocks/company-officers/GOOG.O", "https://www.reuters.com/finance/stocks/company-officers/AMZN.O", "https://www.reuters.com/finance/stocks/company-officers/AAPL.O"]
for URL in url:
    req = requests.get(URL)
    soup = BeautifulSoup(req.content, 'html.parser')
    for i in soup.find_all("tbody", {"class": "dataSmall"}):
        print(i)


问:
How a feature descriptior for traffic sign detection works in opencv
I am trying to understand how Centroid to Contour (CtC) detector works. Here is a sample code that I have found on Github, and I am trying to understand what is the idea behind this. In this sample, the author trying to detect speed sign using CtC. There are just two important functions:

pre_process()

CtC_features

I have understood a part of the code and how it works but I have some problems in understanding how CtC_features function works.
If you can help me I would like to understand the following parts (just 3 points):

Why if centroid.x > curr.x we need to add PI value to the angle result ( if (centroid.x > curr.x) ang += 3.14159;  //PI  )

When we start selecting the features on line 97 we set the start angle ( double ang = - 1.57079;  ). Why is this half the pi value and negative? How was this value chosen?

And a more general question, how can you know that what feature you select are related to speed limit sign? You find the centroid of the image and adjust the angle in the first step, but in the second step how can you know if ( while (feature_v[i].first > ang) ) the current angle is bigger than your hardcode angle ( in first case ang = - 1.57079) then we add that distance as a feature.

I would like to understand the idea behind this code and if someone with more experience and with some knowledge about trigonometry would help me it will be just great.

Thank you.

答:
The code you provided is not the best, but let's see what happens.

I took this starting image of a sign:

Then, pre_process is called, which basically runs a Canny edge detector, along with some tricks which should lead to a better edge detection. I won't look into them, but this is what it returns:

Not the greatest. Maybe some parameter tuning would help.

But now, CtC_features is called, which is the scope of the question. The role of CtC_features is to obtain some features for a machine learning algorithms. This amounts to finding a numerical description of the image which would help the ML algorithm detect the sign. Such a description can be anything. Think about how someone who never saw a STOP sign and does not know how to read would describe it. They would say something like "A red, flat plate, with 8 sides and some white stuff in the middle". Based on this description, someone might be able to tell it's a STOP sign. We want to do the same, but since computers are computers, we look for numerical features. And, with them, some algorithm could be trained to "learn" what features each sign has.

So, let's see what features does CtC_features obtains from the contours.

The first thing it does is to call findContours. This function takes a binary image and returns arrays of points representing the contours of the image. Basically, it takes the edges and puts them into arrays of points. With connectivity, so we basically know which points are connected. If we use the code from here for visualization, we can see what happens:

So, the array contours is a std::vector<std::vector<cv::Point>> and you have in each sub-array a continuous contour, here drawn with a different color.

Next, we compute the number of points (edge pixels), and do an average over their coordinates to find the centroid of the edge image. The centroid is the filled circle:

Then, we iterate over all points, and create a vector of std::pair<double, double>, recording for each point the distance from the centroid and the angle. The angle function is defined at the bottom of the file as

```<code>double angle(Point2f a, Point2f b) {
    return atan((a.y - b.y) / (a.x - b.x));
}
</code>```

It basically computes the angle of the line from a to b with respect to the x axis, using the arctangent function. I'll let you watch a video on arctangent, but tl;dr is that it gives you the angle from a ratio. In radians (a circle is 2 PI radians, half a circle is PI radians). The problem is that the function is periodic, with a period of PI. This means that there are 2 angles on the circle (the circle of all points at the same distance around the centroid) which give you the same value. So, we compute the ratio (the ratio is btw known as the tangent of the angle), apply the inverse function (arctangent) and we get an angle (corresponding to a point). But what if it's the other point? Well, we know that the other point is exactly with PI degrees offset (it is diametrically opposite), so we add PI if we detect that it's the other point.

The picture below also helps understand why there are 2 points:

The tangent of the angle is highlighted vertical distance,. But the angle on the other side of the diagonal line, which intersects the circle in the bottom left, also has the same tangent. The atan function gives the tangents only for angles on the left side of the center. Note that there are no 2 directions with the same tangent.

What the check does is to ask whether the point is on the right of the centroid. This is done in order to be able to add a half a circle (PI radians or 180 degrees) to correct for the result of atan.

Now, we know the distance (a simple formula) and we have found (and corrected) for the angle. We insert this pair into the vector feature_v, and we sort it. The sort function, called like that, sorts after the first element of the pair, so we sort after the angle, then after distance.

The interval variable:

```<code>int degree = 10;
double interval = double((double(degree) / double(360)) * 2 * 3.14159); //5 degrees interval
</code>```

simply is value of degree, converted from degrees into radians. We need radians since the angles have been computed so far in radians, and degrees are more user friendly. Yep, the comment is wrong, the interval is 10 degrees, not 5.

The ang variable defined below it is -PI / 2 (a quarter of a circle):

```<code>double ang = - 1.57079;
</code>```

Now, what it does is to divide the points around the centroid into bins, based on the angle. Each bin is 10 degrees wide. This is done by iterating over the points sorted after angle, all are accumulated until we get to the next bin. We are only interested in the largest distance of a point in each bin. The starting point should be small enough that all the direction (points) are captured.

In order to understand why it starts from -PI/2, we have to get back at the trigonometric function diagram above. What happens if the angle goes like this:

See how the highlighted vertical segment goes "downwards" on the y axis. This means that its length (and implicitly the tangent) is negative here. Also, the angle is considered to be negative (otherwise there would be 2 angles on the same side of the center with the same tangent). Now, we are interested in the range of angles we have. It's all the angles on the right side of the centroid, starting from the bottom at -PI/2 to the top at PI/2. A range of PI radians, or 180 degrees. This is also written in the documentation of atan:

If no errors occur, the arc tangent of arg (arctan(arg)) in the range [-PI/2, +PI/2] radians, is returned.

So, we simply split all the possible directions (360 degrees) into buckets of 10 degrees, and take the distance of the farthest point in each bin. Since the circle has 360 degrees, we'll get 360 / 10 = 36 bins. Then, these are normalized such that the greatest value is 1. This helps a bit with the machine learning algorithm.

How can we know if the point we selected belongs to the sign? We don't. Most computer vision make some assumptions regarding the image in order to simplify the problem. The idea of the algorithm is to determine the shape of the sign by recording the distance from the center to the edges. This makes the assumption that the centroid is roughly in the middle of the sign. Depending on the ML algorithm used, and on the training data, different levels of robustness can be obtained.

Also, it assumes that (some of) the edges can be reliably identified. See how in my image, the algorithm was not able to detect the upper left edge?

The good news is that this doesn't have to be perfect. ML algorithms know how to handle this variation (up to some extent) provided that they are appropriately trained. It doesn't have to be perfect, but it has to be good enough. In order to answer what good enough means, what are the actual limitations of the algorithm, some more testing needs to be done, as well as some understanding of the ML algorithm used. But this is also why ML is so popular in vision: it can handle a lot of variation quite well.

At the end, we basically get an array of 36 numbers, one for each of the 36 bins of 10 degrees, representing the maximum distance of a point in the bin. I assume this is because the developer of the algorithm wanted a way to capture the shape of the sign, by looking at distances from center in various directions. This assumes that no edges are detected in the background, and the sign looks something like:

The max distance is used to pick the border, and not the or other symbols on the sign.

It is not directly used here, but a possibly related reading is the Hough transform, which uses a similar particularization to detect straight lines in an image.

Body:
The code you provided is not the best, but let's see what happens.

I took this starting image of a sign:

Then, pre_process is called, which basically runs a Canny edge detector, along with some tricks which should lead to a better edge detection. I won't look into them, but this is what it returns:

Not the greatest. Maybe some parameter tuning would help.

But now, CtC_features is called, which is the scope of the question. The role of CtC_features is to obtain some features for a machine learning algorithms. This amounts to finding a numerical description of the image which would help the ML algorithm detect the sign. Such a description can be anything. Think about how someone who never saw a STOP sign and does not know how to read would describe it. They would say something like "A red, flat plate, with 8 sides and some white stuff in the middle". Based on this description, someone might be able to tell it's a STOP sign. We want to do the same, but since computers are computers, we look for numerical features. And, with them, some algorithm could be trained to "learn" what features each sign has.

So, let's see what features does CtC_features obtains from the contours.

The first thing it does is to call findContours. This function takes a binary image and returns arrays of points representing the contours of the image. Basically, it takes the edges and puts them into arrays of points. With connectivity, so we basically know which points are connected. If we use the code from here for visualization, we can see what happens:

So, the array contours is a std::vector<std::vector<cv::Point>> and you have in each sub-array a continuous contour, here drawn with a different color.

Next, we compute the number of points (edge pixels), and do an average over their coordinates to find the centroid of the edge image. The centroid is the filled circle:

Then, we iterate over all points, and create a vector of std::pair<double, double>, recording for each point the distance from the centroid and the angle. The angle function is defined at the bottom of the file as

double angle(Point2f a, Point2f b) {
    return atan((a.y - b.y) / (a.x - b.x));
}

It basically computes the angle of the line from a to b with respect to the x axis, using the arctangent function. I'll let you watch a video on arctangent, but tl;dr is that it gives you the angle from a ratio. In radians (a circle is 2 PI radians, half a circle is PI radians). The problem is that the function is periodic, with a period of PI. This means that there are 2 angles on the circle (the circle of all points at the same distance around the centroid) which give you the same value. So, we compute the ratio (the ratio is btw known as the tangent of the angle), apply the inverse function (arctangent) and we get an angle (corresponding to a point). But what if it's the other point? Well, we know that the other point is exactly with PI degrees offset (it is diametrically opposite), so we add PI if we detect that it's the other point.

The picture below also helps understand why there are 2 points:

The tangent of the angle is highlighted vertical distance,. But the angle on the other side of the diagonal line, which intersects the circle in the bottom left, also has the same tangent. The atan function gives the tangents only for angles on the left side of the center. Note that there are no 2 directions with the same tangent.

What the check does is to ask whether the point is on the right of the centroid. This is done in order to be able to add a half a circle (PI radians or 180 degrees) to correct for the result of atan.

Now, we know the distance (a simple formula) and we have found (and corrected) for the angle. We insert this pair into the vector feature_v, and we sort it. The sort function, called like that, sorts after the first element of the pair, so we sort after the angle, then after distance.

The interval variable:

int degree = 10;
double interval = double((double(degree) / double(360)) * 2 * 3.14159); //5 degrees interval

simply is value of degree, converted from degrees into radians. We need radians since the angles have been computed so far in radians, and degrees are more user friendly. Yep, the comment is wrong, the interval is 10 degrees, not 5.

The ang variable defined below it is -PI / 2 (a quarter of a circle):

double ang = - 1.57079;

Now, what it does is to divide the points around the centroid into bins, based on the angle. Each bin is 10 degrees wide. This is done by iterating over the points sorted after angle, all are accumulated until we get to the next bin. We are only interested in the largest distance of a point in each bin. The starting point should be small enough that all the direction (points) are captured.

In order to understand why it starts from -PI/2, we have to get back at the trigonometric function diagram above. What happens if the angle goes like this:

See how the highlighted vertical segment goes "downwards" on the y axis. This means that its length (and implicitly the tangent) is negative here. Also, the angle is considered to be negative (otherwise there would be 2 angles on the same side of the center with the same tangent). Now, we are interested in the range of angles we have. It's all the angles on the right side of the centroid, starting from the bottom at -PI/2 to the top at PI/2. A range of PI radians, or 180 degrees. This is also written in the documentation of atan:

If no errors occur, the arc tangent of arg (arctan(arg)) in the range [-PI/2, +PI/2] radians, is returned.

So, we simply split all the possible directions (360 degrees) into buckets of 10 degrees, and take the distance of the farthest point in each bin. Since the circle has 360 degrees, we'll get 360 / 10 = 36 bins. Then, these are normalized such that the greatest value is 1. This helps a bit with the machine learning algorithm.

How can we know if the point we selected belongs to the sign? We don't. Most computer vision make some assumptions regarding the image in order to simplify the problem. The idea of the algorithm is to determine the shape of the sign by recording the distance from the center to the edges. This makes the assumption that the centroid is roughly in the middle of the sign. Depending on the ML algorithm used, and on the training data, different levels of robustness can be obtained.

Also, it assumes that (some of) the edges can be reliably identified. See how in my image, the algorithm was not able to detect the upper left edge?

The good news is that this doesn't have to be perfect. ML algorithms know how to handle this variation (up to some extent) provided that they are appropriately trained. It doesn't have to be perfect, but it has to be good enough. In order to answer what good enough means, what are the actual limitations of the algorithm, some more testing needs to be done, as well as some understanding of the ML algorithm used. But this is also why ML is so popular in vision: it can handle a lot of variation quite well.

At the end, we basically get an array of 36 numbers, one for each of the 36 bins of 10 degrees, representing the maximum distance of a point in the bin. I assume this is because the developer of the algorithm wanted a way to capture the shape of the sign, by looking at distances from center in various directions. This assumes that no edges are detected in the background, and the sign looks something like:

The max distance is used to pick the border, and not the or other symbols on the sign.

It is not directly used here, but a possibly related reading is the Hough transform, which uses a similar particularization to detect straight lines in an image.


问:
Is there a quick way to close a thread before the main code continues?
I have a students working on a Simon Game for a final project at school and I have tried all day to solve her problem.
She is trying to create the game Simon. The program randomly selects a sequence of colours and highlights those colours by changing the colours of the 4 coloured buttons from the regular colour to white for a few seconds and then back.
Instead of highlighting one colour at a time white, the programming is making all colours appear white at the same time. So users don't know the sequence.

I have been looking up issues with running multiple threads and have tried using the .join() function. However, when that is used no colours turn white.

//highlights the colours that are currently in the array

```<code>
public void play() {

   //loop through the array and look at all the colours so far
   for(int i=0; i<round;i++){

             //red is the position in the array
             if(colours[i]==1){

                  Thread sleep=new Thread(new Runnable(){
                     @Override
                     public void run(){
                         //change the colour of the red button to white
                         redButton.setBackground(Color.WHITE);
                         redButton.setOpaque(true);

                            //wait
                            try {
                                Thread.currentThread().sleep(1000);
                                }
                             catch (InterruptedException e) {
                                e.printStackTrace();
                                }
                            //change the colour back
                        redButton.setBackground(Color.RED);
                         redButton.setOpaque(false);
                     }
                 });

                        sleep.start();

             }

             //yellow
             else if(colours[i]==2){
                 Thread sleep=new Thread(new Runnable(){
                     @Override
                     public void run(){
                         yellowButton.setBackground(Color.WHITE);
                         yellowButton.setOpaque(true);

                            try {
                                Thread.currentThread().sleep(1000);
                                }
                             catch (InterruptedException e) {
                                e.printStackTrace();
                                }
                         yellowButton.setBackground(Color.YELLOW);
                        yellowButton.setOpaque(false);
                     }
                 });
                 sleep.start();

             }
             //green
             else if(colours[i]==3){
                 Thread sleep=new Thread(new Runnable(){
                     @Override
                     public void run(){
                         greenButton.setBackground(Color.WHITE);
                         greenButton.setOpaque(true);

                            try {
                                Thread.currentThread().sleep(1000);
                                }
                             catch (InterruptedException e) {
                                e.printStackTrace();
                                }
                         greenButton.setBackground(Color.GREEN);
                        greenButton.setOpaque(false);

                     }
                 });
                 sleep.start();

             }
             //blue
             else if(colours[i]==4){
                 Thread sleep=new Thread(new Runnable(){
                     @Override
                     public void run(){
                         blueButton.setBackground(Color.WHITE);
                         blueButton.setOpaque(true);

                            try {
                                Thread.currentThread().sleep(1000);
                                }
                             catch (InterruptedException e) {
                                e.printStackTrace();
                                }
                         blueButton.setBackground(Color.CYAN);
                         blueButton.setOpaque(false);

                     }
                 });
                 sleep.start();

             }

   }

}

</code>```

答:
the code there basically says.

for all the steps in the sequence start a thread each.

then each of those threads (all started very soon after each other and not before the previous completes.) set the background to white for 1 second then back.

Usually you want to update the ui in the background so that you can continue to interact, but in this case you are playing a sequence and don't want any input. if updating in the background is required put the whole loop in a  thread and you will want to sleep between iterations of that loop.  otherwise just do it in the main thread.  once the sequence is done playing for the user it will pass control back to the event loop to wait for presses.

also the delay should be .3s < t < .5s 1 second is too long

Body:
I have a students working on a Simon Game for a final project at school and I have tried all day to solve her problem.
She is trying to create the game Simon. The program randomly selects a sequence of colours and highlights those colours by changing the colours of the 4 coloured buttons from the regular colour to white for a few seconds and then back.
Instead of highlighting one colour at a time white, the programming is making all colours appear white at the same time. So users don't know the sequence.

I have been looking up issues with running multiple threads and have tried using the .join() function. However, when that is used no colours turn white.

//highlights the colours that are currently in the array

public void play() {

   //loop through the array and look at all the colours so far
   for(int i=0; i<round;i++){

             //red is the position in the array
             if(colours[i]==1){

                  Thread sleep=new Thread(new Runnable(){
                     @Override
                     public void run(){
                         //change the colour of the red button to white
                         redButton.setBackground(Color.WHITE);
                         redButton.setOpaque(true);

                            //wait
                            try {
                                Thread.currentThread().sleep(1000);
                                }
                             catch (InterruptedException e) {
                                e.printStackTrace();
                                }
                            //change the colour back
                        redButton.setBackground(Color.RED);
                         redButton.setOpaque(false);
                     }
                 });

                        sleep.start();

             }

             //yellow
             else if(colours[i]==2){
                 Thread sleep=new Thread(new Runnable(){
                     @Override
                     public void run(){
                         yellowButton.setBackground(Color.WHITE);
                         yellowButton.setOpaque(true);

                            try {
                                Thread.currentThread().sleep(1000);
                                }
                             catch (InterruptedException e) {
                                e.printStackTrace();
                                }
                         yellowButton.setBackground(Color.YELLOW);
                        yellowButton.setOpaque(false);
                     }
                 });
                 sleep.start();

             }
             //green
             else if(colours[i]==3){
                 Thread sleep=new Thread(new Runnable(){
                     @Override
                     public void run(){
                         greenButton.setBackground(Color.WHITE);
                         greenButton.setOpaque(true);

                            try {
                                Thread.currentThread().sleep(1000);
                                }
                             catch (InterruptedException e) {
                                e.printStackTrace();
                                }
                         greenButton.setBackground(Color.GREEN);
                        greenButton.setOpaque(false);

                     }
                 });
                 sleep.start();

             }
             //blue
             else if(colours[i]==4){
                 Thread sleep=new Thread(new Runnable(){
                     @Override
                     public void run(){
                         blueButton.setBackground(Color.WHITE);
                         blueButton.setOpaque(true);

                            try {
                                Thread.currentThread().sleep(1000);
                                }
                             catch (InterruptedException e) {
                                e.printStackTrace();
                                }
                         blueButton.setBackground(Color.CYAN);
                         blueButton.setOpaque(false);

                     }
                 });
                 sleep.start();

             }

   }

}


问:
How to hide panel and navbar in login page framework7
I'd like to hide correctly the panel and the navbar only in the login page. After login I'd like to show them. I achieve this task partially, because my code has a bad side effect. When I open the app I saw my login page but for few second the navbar appears and then disappears. I'd like to access on login page without this effect. I'd like to see immediatly the login page without them.
How can I solve it?

I declared them in my index.html

```<code> <div id="app">
    <div class="panel panel-left panel-cover">
        <div class="navbar color-theme-green ">
            <div class="navbar-inner sliding">
                <div class="title">Menu</div>
            </div>
        </div>
        <div class="block">
            <div class="list links-list">
                <ul>
                    <li>
                        <a href="/home/" class="panel-close">
                            <div class="item-content">
                                <div class="item-media">
                                    <i class="f7-icons ios-only">graph_square</i>
                                    <i class="material-icons md-only">dashboard</i>
                                </div>
                                <div class="item-inner">
                                    <div class="item-title">Home</div>
                                </div>
                            </div>
                        </a>
                    </li>
                    <li id="company" style="display:none;">
                        <a href="/company/" class="panel-close" >
                            <div class="item-content">
                                <div class="item-media">
                                    <i class="f7-icons ios-only">home</i>
                                    <i class="material-icons md-only">home</i>
                                </div>
                                <div class="item-inner">
                                    <div class="item-title">Company</div>
                                </div>
                            </div>
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <!-- Top Navbar -->
    <div class="navbar color-theme-green">
        <div class="navbar-inner sliding">
            <div class="left">
                <a class="link panel-open">
                    <i class="f7-icons ios-only">menu</i>
                    <i class="material-icons md-only">menu</i>
                    <!--<span class="ios-only">Back</span>-->
                </a>

                <a class="link back">
                    <i class="icon icon-back"></i>
                    <span class="ios-only">Back</span>
                </a>
            </div>
            <div class="title">My app</div>
        </div>
    </div>

    <div class="view view-main"></div>
</code>```

This is my config file app.js where I show and hide the elements on pageInitEvent

```<code>   var $$ = Dom7;

var app = new Framework7({
// App root element
root: '#app',
// App Name
name: 'myApp',
// App id
id: 'it.myapp.myApp',
theme: 'auto',
version: '0.0.1',
cacheDuration: 0,
cache: false,
stackPages: true,
preloadPreviousPage: true,

panel: {
    swipe: 'right',
    swipeNoFollow: true
},
/**
 * Routes
 */
routes: [
    {
        name: 'home',
        path: '/home/',
        url: './pages/home.html',
        on: {
            pageInit:   function(e, page) {

                            app.navbar.show('.navbar');
                            page.router.clearPreviousHistory();
                        }

        },
    },
    {
        name: 'login',
        path: '/login/',
        url: './pages/login.html',
        on:{
                pageInit: function(){
                    app.navbar.hide('.navbar');

                    }
            },
    }

}
</code>```

And finally this is my login.html page where I put no-navbar in orderd to hide it.

```<code><div data-name="login" class="page no-navbar no-toolbar no-swipeback">
<div class="page-content login-screen-content ">
    <!-- Login form -->
    <form id="form-login">
        <div class="row justify-content-center">
            <div class="col-100 tablet-80 desktop-50">
                <div class="card head-card-forest">
                    <div class="card-header">
                        <span></span><h2>Login</h2><span></span>
                    </div>
                    <div class="card-content card-content-padding">
                        <div class="row">
                            <div class="col-100 tablet-auto desktop-auto">
                                <div class="list no-hairlines-md">
                                    <ul>
                                        <li class="item-content item-input">
                                            <div class="item-inner">
                                                <div class="item-title item-label">Email</div>
                                                <div class="item-input-wrap">
                                                    <input type="text" name="username"  placeholder="Username">
                                                    <span class="input-clear-button"></span>
                                                </div>
                                            </div>
                                        </li>

                                        <li class="item-content item-input">
                                            <div class="item-inner">
                                                <div class="item-title item-label">Password</div>
                                                <div class="item-input-wrap">
                                                    <input type="password" name="password"  placeholder="Password">
                                                    <span class="input-clear-button"></span>
                                                </div>
                                            </div>
                                        </li>
                                    </ul>
                                </div>

                                <div class="block">
                                    <div class="row">
                                        <a class="col button button-fill" id="button-login" onclick="getLogin()"> Accedi </a>
                                    </div>
                                </div>
                            </div><!--col-->
                        </div><!--row-->
                    </div><!--card-content-->
                </div><!--.card-->
            </div><!--.col-->
        </div><!--.row-->
    </form>
</div> <!-- ./ page-content -->
</code>```

答:
you can hide the panel in the login page using pageInit event</p>

```<code>pageInit : function (e,p) { p.app.panel.left.hide() }
</code>```

Body:
I'd like to hide correctly the panel and the navbar only in the login page. After login I'd like to show them. I achieve this task partially, because my code has a bad side effect. When I open the app I saw my login page but for few second the navbar appears and then disappears. I'd like to access on login page without this effect. I'd like to see immediatly the login page without them.
How can I solve it?

I declared them in my index.html

Menu

                                    graph_square
                                    dashboard

Home

                                    home
                                    home

Company

                    menu
                    menu

                    Back

My app

This is my config file app.js where I show and hide the elements on pageInitEvent

   var $$ = Dom7;

var app = new Framework7({
// App root element
root: '#app',
// App Name
name: 'myApp',
// App id
id: 'it.myapp.myApp',
theme: 'auto',
version: '0.0.1',
cacheDuration: 0,
cache: false,
stackPages: true,
preloadPreviousPage: true,

panel: {
    swipe: 'right',
    swipeNoFollow: true
},
/**
 * Routes
 */
routes: [
    {
        name: 'home',
        path: '/home/',
        url: './pages/home.html',
        on: {
            pageInit:   function(e, page) {

                            app.navbar.show('.navbar');
                            page.router.clearPreviousHistory();
                        }

        },
    },
    {
        name: 'login',
        path: '/login/',
        url: './pages/login.html',
        on:{
                pageInit: function(){
                    app.navbar.hide('.navbar');

                    }
            },
    }

}

And finally this is my login.html page where I put no-navbar in orderd to hide it.

    <form id="form-login">

Login

Email

                                                    <input type="text" name="username"  placeholder="Username">

Password

                                                    <input type="password" name="password"  placeholder="Password">

                                         Accedi

    </form>

Body:
you can hide the panel in the login page using pageInit event

pageInit : function (e,p) { p.app.panel.left.hide() }