问:
Angular 4 - binding not working when declaring variable as a property of an object
I have a page where I display a list with locations, and clicking on each of them I am displaying assets for that location. I have set up the template like this:

```<code><li
    *ngFor="let location of locations"
    (click)="select(location)"
    droppable
    [dragOverClass]="'drag-target-border'"
    (onDrop)="onItemDrop($event, location)"
    >
      {{ location.name }}
      <ul *ngIf="currentLocation == location && assetsVisible">
        <ng-container *ngIf="currentLocation.assets?.length > 0;else message">
          <li
            *ngFor="let asset of currentLocation.assets"
            class="asset"
            draggable
            [dragData]="asset"
            >
            <p>{{ asset.title }}</p>
            <p>{{ asset.address }}</p>
            <p>{{ asset.value }}</p>
          </li>
        </ng-container>
        <ng-template #message>No assets for {{ location.name }}</ng-template>
      </ul>
  </li>
</code>```

And in the component, I have tried to first set the empty assets array, and an empty currentLocation object with a property assets:

```<code>  locations: any[] = [];
  currentLocation: any = {
    assets: any[] = []
  };
</code>```

And then in the method select I am fetching the assets like this:

```<code>  select(location){

    if (this.currentLocation != location || !this.assetsVisible) {
      this.assetsVisible = true;
    }
    else {
      this.assetsVisible = false;
    }

    this.currentAddress = address;

    this.locationService.getAssets(location.Id)
      .subscribe(
        assets => this.currentLocation.assets = assets
      );
  }
</code>```

What I would like to do is to since I am using the drag and drop plugin for Angular I would like to make it possible for user to drag assets from one location to another. And then just temporarily push that asset to an array of the property currentLocation.assets where the asset was dropped to.
I have made a function for that:

```<code>onItemDrop(e: any, location) {
    this.select(location);
    this.currentLocation.assets.push(e.dragData);
}
</code>```

That drags and drops the asset from one location to another, but I get an error:

ERROR TypeError: Cannot read property 'push' of undefined

I have done console.log(this.currentLocation.assets) in both select and onItemDrop method, and both times I get:

undefined

But, if I do console.log(this.currentLocation) in both functions, I get an object with an empty assets array as a property of it. And I can access every other property of that object, but I can't access assets array.
Also, when I do console.log in ngOnInit I get an empty array back in the console:

```<code>console.log(this.currentLocation.assets);
</code>```

So, I am not sure why do I get this error, why do I get an object with an empty assets array as a property of it, but I can't access directly property of that object, when I can access all other properties of the same object?

This is the whole component:

```<code>import { Component, OnInit } from '@angular/core';
import { LocationService } from '../services/location.service';

@Component({
  moduleId: module.id,
  selector: 'sd-addresses',
  templateUrl: 'location.component.html'
})
export class LocationsComponent implements OnInit {

  errorMessage: string;
  locations: any[] = [];
  currentLocation: any = {
    assets: any[] = []
  };
  assetsVisible: boolean = false;

  constructor(public locationService: LocationService) {}

  ngOnInit() {
    this.getLocations();
  }

  getLocations() {
    this.locationService.get()
      .subscribe(
        locations => this.locations = locations,
        error => this.errorMessage = <any>error
      );
  }

  select(location = {}) {

    if (this.currentLocation != location || !this.assetsVisible) {
      this.assetsVisible = true;
    }
    else {
      this.assetsVisible = false;
    }

    this.currentLocation = location;

    this.locationService.getAssets(location.Id)
      .subscribe(
        assets => this.currentLocation.assets = assets,
      );
  }

  onItemDrop(e: any, location:any = {}) {
    this.currentLocation.assets = [];
    this.currentLocation.assets.push(e.dragData);
    this.select(location);
  }
}
</code>```

答:
In your declaration try this:

```<code>  locations: any[] = [];
  currentLocation: any = {
     assets: []
  };
</code>```

This way you will be declaring currentLocation that is an object type {} and has a property assets that is an array type [].

Body:
I have a page where I display a list with locations, and clicking on each of them I am displaying assets for that location. I have set up the template like this:

      {{ location.name }}

        <ng-container *ngIf="currentLocation.assets?.length > 0;else message">

{{ asset.title }}

{{ asset.address }}

{{ asset.value }}

        </ng-container>
        <ng-template #message>No assets for {{ location.name }}</ng-template>

And in the component, I have tried to first set the empty assets array, and an empty currentLocation object with a property assets:

  locations: any[] = [];
  currentLocation: any = {
    assets: any[] = []
  };

And then in the method select I am fetching the assets like this:

  select(location){

    if (this.currentLocation != location || !this.assetsVisible) {
      this.assetsVisible = true;
    }
    else {
      this.assetsVisible = false;
    }

    this.currentAddress = address;

    this.locationService.getAssets(location.Id)
      .subscribe(
        assets => this.currentLocation.assets = assets
      );
  }

What I would like to do is to since I am using the drag and drop plugin for Angular I would like to make it possible for user to drag assets from one location to another. And then just temporarily push that asset to an array of the property currentLocation.assets where the asset was dropped to.
I have made a function for that:

onItemDrop(e: any, location) {
    this.select(location);
    this.currentLocation.assets.push(e.dragData);
}

That drags and drops the asset from one location to another, but I get an error:

ERROR TypeError: Cannot read property 'push' of undefined

I have done console.log(this.currentLocation.assets) in both select and onItemDrop method, and both times I get:

undefined

But, if I do console.log(this.currentLocation) in both functions, I get an object with an empty assets array as a property of it. And I can access every other property of that object, but I can't access assets array.
Also, when I do console.log in ngOnInit I get an empty array back in the console:

console.log(this.currentLocation.assets);

So, I am not sure why do I get this error, why do I get an object with an empty assets array as a property of it, but I can't access directly property of that object, when I can access all other properties of the same object?

This is the whole component:

import { Component, OnInit } from '@angular/core';
import { LocationService } from '../services/location.service';

@Component({
  moduleId: module.id,
  selector: 'sd-addresses',
  templateUrl: 'location.component.html'
})
export class LocationsComponent implements OnInit {

  errorMessage: string;
  locations: any[] = [];
  currentLocation: any = {
    assets: any[] = []
  };
  assetsVisible: boolean = false;

  constructor(public locationService: LocationService) {}

  ngOnInit() {
    this.getLocations();
  }

  getLocations() {
    this.locationService.get()
      .subscribe(
        locations => this.locations = locations,
        error => this.errorMessage = <any>error
      );
  }

  select(location = {}) {

    if (this.currentLocation != location || !this.assetsVisible) {
      this.assetsVisible = true;
    }
    else {
      this.assetsVisible = false;
    }

    this.currentLocation = location;

    this.locationService.getAssets(location.Id)
      .subscribe(
        assets => this.currentLocation.assets = assets,
      );
  }

  onItemDrop(e: any, location:any = {}) {
    this.currentLocation.assets = [];
    this.currentLocation.assets.push(e.dragData);
    this.select(location);
  }
}

Body:
In your declaration try this:

  locations: any[] = [];
  currentLocation: any = {
     assets: []
  };

This way you will be declaring currentLocation that is an object type {} and has a property assets that is an array type [].


来源: stackexchange

问:
PHP string contains two characters then a slash at the beginning
Imagine the following string

```<code>/en/pages/title-page  or /es/pages/title-page
</code>```

How to determine if the string has a slash then two unknown characters (always two) and then another slash. Then once known, can these be extracted from the string.

答:
The following code will have the language in index 1 of the $matches array. Otherwise, if the pattern does not match, the array will be empty.

```<code>$matches = null;
if (preg_match('/^\/([a-zA-Z]{2})\//', '/en/pages/title-page', $matches) === 1)
    echo $matches[1];
else
    echo 'No language found';
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Imagine the following string

/en/pages/title-page  or /es/pages/title-page

How to determine if the string has a slash then two unknown characters (always two) and then another slash. Then once known, can these be extracted from the string.

Body:
The following code will have the language in index 1 of the $matches array. Otherwise, if the pattern does not match, the array will be empty.

$matches = null;
if (preg_match('/^\/([a-zA-Z]{2})\//', '/en/pages/title-page', $matches) === 1)
    echo $matches[1];
else
    echo 'No language found';


问:
searching a 2d array in python - best method + indentation error
I have created the following 2d array (list of lists) in Python:

```<code>#creating a 2d array (3 rows by 7 columns) and populating it with numbers
matrix=[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]
rows=len(matrix) #finding the max number of rows in the matrix, in this case 3
columns=len(matrix[0]) #finding the max number of columns in each row, 7 in this case
</code>```

I am trying to search for a specific element in the array (say the number 9), and then print "found", if found, and "not found", if not in the array, with the following code:

```<code>number=int(input("What number are you looking for?"))
for i in range(rows):
      for j in range(columns):
        if matrix[i][j]==number:
          print("Found it!")
          break
else:
  print("not found")
</code>```

The output however, is erroneous:

```<code>>>What number are you looking for? 9
>>Found it!
>>not found
</code>```

I have two questions: 1. could someone please explain identatation clearly, with reference to this problem and why the second "not found" always is output.
2. Is there a better more efficient way to do this, without the use of numpy

*note, this is not a duplicate, as I have searched the other entries and they don't quite deal with what I am explicitly asking.

repl.it here:
https://repl.it/IcJ3/3

Someone just suggested an answer as below: (I had already tried this)

https://repl.it/IcJ3/5
Note, it doesn't work at all either:

```<code>number=int(input("What number are you looking for?"))
for i in range(rows):
      for j in range(columns):
        if matrix[i][j]==number:
          print("Found it!")
          break
        else:
          print("not found")
</code>```

Erroneous output, still!

```<code>What number are you looking for? 9
not found
not found
not found
not found
not found
not found
not found
not found
Found it!
not found
not found
not found
not found
not found
not found
not found
</code>```

答:
You seem to be new to Python. In this language, code blocks are identified by the number of indents you have before an instruction. In your case, you have an if statement, but your else is not matching the indentation of that if statement. <br>
You'd want your code to be something like this - </p>

```<code>number=int(input("What number are you looking for?"))
flag = False
for i in range(rows):
      for j in range(columns):
        if matrix[i][j]==number:
          print("Found it!")
          flag = True
          break
if flag == False:
  print ("Not found!")
</code>```

Body:
I have created the following 2d array (list of lists) in Python:

#creating a 2d array (3 rows by 7 columns) and populating it with numbers
matrix=[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]
rows=len(matrix) #finding the max number of rows in the matrix, in this case 3
columns=len(matrix[0]) #finding the max number of columns in each row, 7 in this case

I am trying to search for a specific element in the array (say the number 9), and then print "found", if found, and "not found", if not in the array, with the following code:

number=int(input("What number are you looking for?"))
for i in range(rows):
      for j in range(columns):
        if matrix[i][j]==number:
          print("Found it!")
          break
else:
  print("not found")

The output however, is erroneous:

>>What number are you looking for? 9
>>Found it!
>>not found

I have two questions: 1. could someone please explain identatation clearly, with reference to this problem and why the second "not found" always is output.
2. Is there a better more efficient way to do this, without the use of numpy

*note, this is not a duplicate, as I have searched the other entries and they don't quite deal with what I am explicitly asking.

repl.it here:
https://repl.it/IcJ3/3

Someone just suggested an answer as below: (I had already tried this)

https://repl.it/IcJ3/5
Note, it doesn't work at all either:

number=int(input("What number are you looking for?"))
for i in range(rows):
      for j in range(columns):
        if matrix[i][j]==number:
          print("Found it!")
          break
        else:
          print("not found")

Erroneous output, still!

What number are you looking for? 9
not found
not found
not found
not found
not found
not found
not found
not found
Found it!
not found
not found
not found
not found
not found
not found
not found

Body:
You seem to be new to Python. In this language, code blocks are identified by the number of indents you have before an instruction. In your case, you have an if statement, but your else is not matching the indentation of that if statement.

You'd want your code to be something like this -

number=int(input("What number are you looking for?"))
flag = False
for i in range(rows):
      for j in range(columns):
        if matrix[i][j]==number:
          print("Found it!")
          flag = True
          break
if flag == False:
  print ("Not found!")


问:
How to prevent Sql-Injection on User-Generated Sql Queries
I have a project (private, ASP.net website, password protected with https) where one of the requirements is that the user be able to enter Sql queries that will directly query the database. I need to be able to allow these queries, while preventing them from doing damage to the database itself, and from accessing or updating data that they shouldn't be able to access/update.

I have come up with the following rules for implementation:

Use a db user that only has permission for Select Table/View and Update Table (thus any other commands like drop/alter/truncate/insert/delete will just not run).

Verify that the statement begins with the words "Select" or "Update"

Verify (using Regex) that there are no instances of semi-colons in the statement that are not surrounded by single-quotes, white space and letters. (The thought here is that the only way that they could include a second query would be to end the first with a semi-colon that is not part of an input string).

Verify (using Regex) that the user has permission to access the tables being queried/updated, included in joins, etc. This includes any subqueries. (Part of the way that this will be accomplished is that the user will be using a set of table names that do not actually exist in the database, part of the query parsing will be to substitute in the correct corresponding table names into the query).

Am I missing anything?

The goal is that the users be able to query/update tables to which they have access in any way that they see fit, and to prevent any accidental or malicious attempts to damage the db. (And since a requirement is that the user generate the sql, I have no way to parametrize the query or sanitize it using any built-in tools that I know of).

答:
My gut reaction is that you should focus on setting the account privileges and grants as tightly as possible.  Look at your RDBMS security documentation thoroughly, there may well be features you are not familiar with that would prove helpful (e.g. Oracle's Virtual Private Database, I believe, may be useful in this kind of scenario).

In particular, your idea to "Verify (using Regex) that the user has permission to access the tables being queried/updated, included in joins, etc." sounds like you would be trying to re-implement security functionality already built into the database.

OwnerDisplayName: Yaakov Ellis

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Yaakov Ellis

OwnerDisplayName: Dave Costa


问:
Is importing a file good in Python
I have around 80 lines of a function in a file. I need the same functionality in another file so I am currently importing the other file for the function.

My question is that in terms of running time on a machine which technique would be better :- importing the complete file and running the function or copying the function as it is and run it from same package.

I know it won't matter in a large sense but I want to learn it in the sense that if we are making a large project is it better to import a complete file in Python or just add the function in the current namespace.....

答:
The whole point of importing is to allow code reuse and organization.

Remember too that you can do either

```<code>import MyModule
</code>```

to get the whole file or

```<code>from MyModule import MyFunction
</code>```

for when you only need to reference that one part of the module.

Title: Is importing a file good in Python

Body:
The whole point of importing is to allow code reuse and organization.

Remember too that you can do either

import MyModule

to get the whole file or

from MyModule import MyFunction

for when you only need to reference that one part of the module.


问:
Find Chrome is running igntion or crankshaft
Is there any way to find chrome is running ignition or crankshaft V8 Engine?

As per https://v8project.blogspot.in/2017/05/launching-ignition-and-turbofan.html, chrome uses V8 ignition engine by default from version 59. I am looking for a way to enable ignition in chrome version#57 (in CEF environment).

When i use --js-flags="--ignition --turbo" in chrome 57, i am not finding much difference in js execution speed through chrome's performance inspect tools. So, i am looking for a way to query running v8 engine so that i will be sure enough to carry out my test on crankshaft or ignition; also, please do share any guidelines for performing JS load and execution performance.

Thanks!!!

答:
Using Ignition in Chrome M57 is not officially supported. You can play with it if you like; it may or may not work; you're on your own.

Ignition does not replace Crankshaft. It replaces "full codegen", the old non-optimizing compiler. Ignition is not faster than full-codegen, but it saves memory (and has other, mostly internal/architectural, benefits).

There is no way to find out from JavaScript which compiler is being used. From the command line, you can use --js-flags="--trace-opt" to trace which functions are getting optimized by which compiler.


问:
Form submit to get clean url
I don't know if I asked it right. I am a beginner.
I am building a website where items can be searched. There is a form in the website and the value is searched using php get method. And the url after form submit is something like this.

example.com/?q=item

I modified the htaccess file so that I can use example.com/item/ to get the same result, Which works.

What I need to do is redirect to example.com/item/ after user submits the form . How can I achieve this? Should I use javascript or php or which is better?

答:
Why not both. Javascript for users who have it enabled. PHP as a fallback for those that don't.

PHP

```<code>if (!empty($_GET['q']))
{
    $redirecturl = $domainname . "/search/" . $_GET['q'];
    $redirecturl = str_replace(" ", "-", $redirecturl);
    header('Location: ' . $redirecturl, true, 303);
    die();
}
</code>```

Javascript

See: How to submit form using JavaScript and redirect to a URL?

Title: Form submit to get clean url

Body:
Why not both. Javascript for users who have it enabled. PHP as a fallback for those that don't.

PHP

if (!empty($_GET['q']))
{
    $redirecturl = $domainname . "/search/" . $_GET['q'];
    $redirecturl = str_replace(" ", "-", $redirecturl);
    header('Location: ' . $redirecturl, true, 303);
    die();
}

Javascript

See: How to submit form using JavaScript and redirect to a URL?


问:
How to make getopt_long() print nothing when there is error command-line arguments?
I have a program use getopt_get() to parse command line arguments.
My code is like this :

```<code>int opt;
int optionIndex;
static struct option longOptions[] = {
    {"help", no_argument, NULL, 'h'},
    {"test", no_argument, NULL, 't'},
    {0, 0, 0, 0}
};
while ((opt = getopt_long(argc, argv, "ht", longOptions, &optionIndex)) != -1) {
    switch (opt) {
        case 'h':
            help();
            return 0;
            break;
        case 't':
            init();
            test();
            return 0;
            break;
        case '?':
            help();
            return 1;
            break;
        default:
            printf("default.\n");
    }
</code>```

When I pass correct command line arguments to program, it works wells.
But when wrong arguments are passed to program, it will print annoying and superfluous words like this.

For example, i pass wrong argument 'q' to program

```<code>$ ./program -q
./program: invalid option -- 'q'
Usage: -h -t
</code>```

When there are wrong arguments, I just want it run my function help() without printing any word.

```<code>./program: invalid option -- 'q'
</code>```

How can I stop getopt_long to print this annoying word and just print nothing?

答:
Read the fine manual...

If getopt() does not recognize an option character, it prints an error
  message to stderr, stores the character in optopt, and returns '?'.
  The calling program may prevent the error message by setting opterr to
  0.

So, try this before calling getopt_long:

```<code>opterr = 0;
</code>```

Body:
I have a program use getopt_get() to parse command line arguments.
My code is like this :

int opt;
int optionIndex;
static struct option longOptions[] = {
    {"help", no_argument, NULL, 'h'},
    {"test", no_argument, NULL, 't'},
    {0, 0, 0, 0}
};
while ((opt = getopt_long(argc, argv, "ht", longOptions, &optionIndex)) != -1) {
    switch (opt) {
        case 'h':
            help();
            return 0;
            break;
        case 't':
            init();
            test();
            return 0;
            break;
        case '?':
            help();
            return 1;
            break;
        default:
            printf("default.\n");
    }

When I pass correct command line arguments to program, it works wells.
But when wrong arguments are passed to program, it will print annoying and superfluous words like this.

For example, i pass wrong argument 'q' to program

$ ./program -q
./program: invalid option -- 'q'
Usage: -h -t

When there are wrong arguments, I just want it run my function help() without printing any word.

./program: invalid option -- 'q'

How can I stop getopt_long to print this annoying word and just print nothing?

Body:
Read the fine manual...

If getopt() does not recognize an option character, it prints an error
  message to stderr, stores the character in optopt, and returns '?'.
  The calling program may prevent the error message by setting opterr to
  0.

So, try this before calling getopt_long:

opterr = 0;


问:
How can I map a "root" Servlet so that other scripts are still runnable?
I'm trying to build a Servlet that calls a JSP page similar to the following:

```<code>public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws IOException, ServletException {
    req.getRequestDispatcher("/WEB-INF/main.jsp").forward(req, resp);
}
</code>```

I need this Servlet to respond to the domain's root (eg: http://example.com/) so I'm using the following mapping in the web.xml:

```<code><servlet-mapping>
    <servlet-name>MainServlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>
</code>```

The problem I'm having is that this matches EVERYTHING, so when the dispatcher forwards to "/WEB-INF/main.jsp" this matches the url-pattern so the Servlet gets run again. This results in a loop that runs until it dies with a java.lang.StackOverflowError.

How can I match the root without preventing other scripts from being runnable?

答:
Using the welcome-file element of web.xml worked for me, on app engine. Here's mine:

```<code><web-app>
    <servlet>
        <servlet-name>RootServlet</servlet-name>
        <servlet-class>com.foo.RootServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>RootServlet</servlet-name>
        <url-pattern>/foo</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>foo</welcome-file>
    </welcome-file-list>
</web-app>
</code>```

Body:
I'm trying to build a Servlet that calls a JSP page similar to the following:

public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws IOException, ServletException {
    req.getRequestDispatcher("/WEB-INF/main.jsp").forward(req, resp);
}

I need this Servlet to respond to the domain's root (eg: http://example.com/) so I'm using the following mapping in the web.xml:

<servlet-mapping>
    <servlet-name>MainServlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

The problem I'm having is that this matches EVERYTHING, so when the dispatcher forwards to "/WEB-INF/main.jsp" this matches the url-pattern so the Servlet gets run again. This results in a loop that runs until it dies with a java.lang.StackOverflowError.

How can I match the root without preventing other scripts from being runnable?

Body:
Using the welcome-file element of web.xml worked for me, on app engine. Here's mine:

<web-app>
    <servlet>
        <servlet-name>RootServlet</servlet-name>
        <servlet-class>com.foo.RootServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>RootServlet</servlet-name>
        <url-pattern>/foo</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>foo</welcome-file>
    </welcome-file-list>
</web-app>


问:
rendered block refreshed at 16 rows while BufferedRenderer view size is 46
I have this snippet code

Ext.define('FieldGrid', {
    alias: 'fieldGrid',
    extend: 'Ext.grid.Panel',
    dock: 'left',
    selModel: {
        mode: 'SIMPLE'
    },
    columns: [
        {
            text: 'TODO Sites',
            dataIndex: 'text',
            flex: 1
        }
    ],
    bodyStyle: {
        background: '#FFFFFF'
    },
    filterOn: true,
    hideHeaders: true,
    width: 400,
    maxHeight: 400,
    baseStore: store,
    selectedIds: Ext.flatten(selectedIds),
    fieldGridConfig: {
                    plugins: 'bufferedrenderer',
                    height: 400
                }
})```

When I have some rows selected initially then I filter the grid, this ends with the error below

Uncaught Error: rendered block refreshed at 16 rows while   BufferedRenderer view size is 46

Any help we will be appreciated

答:
Had a similar problem with refreshing a grid with locked columns. So instead of just doing grid.getStore().reload(); you need to do:

```<code>            grid.suspendLayouts();
            grid.getStore().reload();
            grid.getView().refresh();
            grid.resumeLayouts();
</code>```

If you have a similar problem ExtJS will crash in syncRowHeightFinish function.

You might want to use this patch to avoid crashes in other cases (tested for ExtJS 6.2.1):

```<code>Ext.define('Ext.ux.view.TableSyncPatch', {
    override: 'Ext.view.Table',
    syncRowHeightFinish: function(synchronizer, otherSynchronizer) {
        var ln = synchronizer.length,
            bufferedRenderer = this.bufferedRenderer,
            i;
        if (ln > otherSynchronizer.length){
            ln = otherSynchronizer.length;
            console.warn('[TableSyncPatch] synchronizer.length!=otherSynchronizer.length');
        }
        for (i = 0; i < ln; i++) {
            synchronizer[i].finish(otherSynchronizer[i]);
        }
        // Ensure that both BufferedRenderers have the same idea about scroll range and row height
        if (bufferedRenderer) {
            bufferedRenderer.syncRowHeightsFinish();
        }
    },
}
// Warn if un-tested for specific version.
, function() {
    if (!Ext.getVersion().match('6.2.1')) {
        Ext.log({
            msg: 'This patch has not been tested with this version of ExtJS',
            level: 'warn'
        });
    }
});
</code>```

Body:
I have this snippet code

Ext.define('FieldGrid', {
    alias: 'fieldGrid',
    extend: 'Ext.grid.Panel',
    dock: 'left',
    selModel: {
        mode: 'SIMPLE'
    },
    columns: [
        {
            text: 'TODO Sites',
            dataIndex: 'text',
            flex: 1
        }
    ],
    bodyStyle: {
        background: '#FFFFFF'
    },
    filterOn: true,
    hideHeaders: true,
    width: 400,
    maxHeight: 400,
    baseStore: store,
    selectedIds: Ext.flatten(selectedIds),
    fieldGridConfig: {
                    plugins: 'bufferedrenderer',
                    height: 400
                }
})

When I have some rows selected initially then I filter the grid, this ends with the error below

Uncaught Error: rendered block refreshed at 16 rows while   BufferedRenderer view size is 46

Any help we will be appreciated

Body:
Had a similar problem with refreshing a grid with locked columns. So instead of just doing grid.getStore().reload(); you need to do:

            grid.suspendLayouts();
            grid.getStore().reload();
            grid.getView().refresh();
            grid.resumeLayouts();

If you have a similar problem ExtJS will crash in syncRowHeightFinish function.

You might want to use this patch to avoid crashes in other cases (tested for ExtJS 6.2.1):

Ext.define('Ext.ux.view.TableSyncPatch', {
    override: 'Ext.view.Table',
    syncRowHeightFinish: function(synchronizer, otherSynchronizer) {
        var ln = synchronizer.length,
            bufferedRenderer = this.bufferedRenderer,
            i;
        if (ln > otherSynchronizer.length){
            ln = otherSynchronizer.length;
            console.warn('[TableSyncPatch] synchronizer.length!=otherSynchronizer.length');
        }
        for (i = 0; i < ln; i++) {
            synchronizer[i].finish(otherSynchronizer[i]);
        }
        // Ensure that both BufferedRenderers have the same idea about scroll range and row height
        if (bufferedRenderer) {
            bufferedRenderer.syncRowHeightsFinish();
        }
    },
}
// Warn if un-tested for specific version.
, function() {
    if (!Ext.getVersion().match('6.2.1')) {
        Ext.log({
            msg: 'This patch has not been tested with this version of ExtJS',
            level: 'warn'
        });
    }
});


问:
Primefaces tree dynamic contextmenu
I need a dynamic context menu for a tree (different on each node based on some permissions, so I cannot use a different menu for each node's type).

I have implemented it using a backing bean model and I update it on every selection's change. Everything works fine, except that if the user right click an unselected node the following happens:

context menu (of previously selected node) is showed

context menu is updated (triggered by select event) and than hidden again

right click again shows the updated context menu

I have found I workaround for treetable
https://dnhome.wordpress.com/2013/10/07 ... e-of-tree/

but it doesn't work for a tree.

Any hint is welcome

PF 6.1.2, WF 10.0.0

答:
I think I have found a working solution. I have built an example based on the primeface's showcase

BasicView.java

```<code>package example;

import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;

import org.primefaces.context.RequestContext;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;

@ManagedBean(name="treeBasicView")
@ViewScoped
public class BasicView implements Serializable {

    private TreeNode root;

    @ManagedProperty(value="#{selectionView}")
    SelectionView selectionView;

    @PostConstruct
    public void init() {
        root = new DefaultTreeNode("Root", null);
        TreeNode node0 = new DefaultTreeNode("Node 0", root);
        TreeNode node1 = new DefaultTreeNode("Node 1", root);

        TreeNode node00 = new DefaultTreeNode("Node 0.0", node0);
        TreeNode node01 = new DefaultTreeNode("Node 0.1", node0);

        TreeNode node10 = new DefaultTreeNode("Node 1.0", node1);

        node1.getChildren().add(new DefaultTreeNode("Node 1.1"));
        node00.getChildren().add(new DefaultTreeNode("Node 0.0.0"));
        node00.getChildren().add(new DefaultTreeNode("Node 0.0.1"));
        node01.getChildren().add(new DefaultTreeNode("Node 0.1.0"));
        node10.getChildren().add(new DefaultTreeNode("Node 1.0.0"));
        root.getChildren().add(new DefaultTreeNode("Node 2"));
    }

    public TreeNode getRoot() {
        return root;
    }

    public void onNodeSelect(NodeSelectEvent event){
        checkSelectionChanged();
    }

    public void onRightClickSelectListener(NodeSelectEvent e) {
            checkSelectionChanged();
        }

/* Update the contextMenu only if the selection has changed */
        private void checkSelectionChanged(){
            if(this.getSelectionView().getSelectedNode()!=this.getSelectionView().getPrevSelectedNode()){
            RequestContext.getCurrentInstance().update("treeform:mytreeContexMenu");
        }
    }

    public SelectionView getSelectionView(){
        return selectionView;
    }

    public void setSelectionView(SelectionView selectionView){
        this.selectionView=selectionView;
    }
}
</code>```

MenuView.java

```<code>package example;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import org.primefaces.model.menu.*;

@ManagedBean
@RequestScoped
public class MenuView {

    private MenuModel model;

    @ManagedProperty(value="#{selectionView}")
    SelectionView selectionView;

    public void init() {
        model = new DefaultMenuModel();

        //First submenu
        DefaultSubMenu firstSubmenu = new DefaultSubMenu("Dynamic Submenu");

        DefaultMenuItem item = new DefaultMenuItem("External");
        item.setUrl("http://www.primefaces.org");
        item.setIcon("ui-icon-home");
        firstSubmenu.addElement(item);

        model.addElement(firstSubmenu);

        //Second submenu
        DefaultSubMenu secondSubmenu = new DefaultSubMenu("Dynamic Actions");

        this.getTreeSelectionView().getSelectedNode();
        if(this.getTreeSelectionView().getSelectedNode()==null){
            return;
        }
        String nodeText = this.getTreeSelectionView().getSelectedNode().getData().toString();

        if(nodeText.contains("0")){ //just a condition
            item=new DefaultMenuItem("Action for 0");
            item.setIcon("ui-icon-disk");
            item.setCommand("#{menuView.save}");
            secondSubmenu.addElement(item);
        }

        if(nodeText.contains("1")){ //just a condition
            item=new DefaultMenuItem("Action for 1");
            item.setIcon("ui-icon-close");
            item.setCommand("#{menuView.delete}");
            item.setAjax(false);
            secondSubmenu.addElement(item);
        }

        if(nodeText.contains("2")){ //just a condition
            item=new DefaultMenuItem("Action for 2");
            item.setIcon("ui-icon-search");
            item.setCommand("#{menuView.redirect}");
            secondSubmenu.addElement(item);
        }

        model.addElement(secondSubmenu);
    }

    public MenuModel getModel() {
        if(model==null){
            this.init();
        }
        return model;
    }

    public void save() {}

    public void update() {}

    public void delete() {}

    public SelectionView getTreeSelectionView(){
        return selectionView;
    }

    public void setSelectionView(SelectionView selectionView){
        this.selectionView=selectionView;
    }
}
</code>```

SelectionView.java

```<code>package example;

import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.model.TreeNode;

@ManagedBean(name="selectionView")
@ViewScoped
public class SelectionView implements Serializable {

    private TreeNode selectedNode;
    private TreeNode prevSelectedNode;

    public TreeNode getSelectedNode() {
        return selectedNode;
    }

    public void setSelectedNode(TreeNode selectedNode) {
        this.setPrevSelectedNode(this.selectedNode);
        this.selectedNode = selectedNode;
    }

    public TreeNode getPrevSelectedNode(){
        return prevSelectedNode;
    }

    public void setPrevSelectedNode(TreeNode prevSelectedNode){
        this.prevSelectedNode=prevSelectedNode;
    }
}
</code>```

tree.xhtml

```<code><!DOCTYPE html>
        <html
                xmlns="http://www.w3.org/1999/xhtml"
                xmlns:ui="http://java.sun.com/jsf/facelets"
                xmlns:f="http://java.sun.com/jsf/core"
                xmlns:h="http://java.sun.com/jsf/html"
                xmlns:p="http://primefaces.org/ui">

        <h:head>
            <title><h:outputText value="Test tree"/></title>
            <h:outputScript library="scripts" name="navigator.js"/>

        </h:head>
        <h:body>

            <h:form id="treeform">

            <p:tree value="#{treeBasicView.root}" var="node" dynamic="true" id="mytree" selectionMode="single" selection="#{selectionView.selectedNode}">
                <p:ajax event="select" listener="#{treeBasicView.onNodeSelect}"/>
                <p:ajax event="contextMenu" listener="#{treeBasicView.onRightClickSelectListener}" oncomplete="PF('mytreeContexMenuVar').show()"/>

                <p:treeNode>
                    <h:outputText value="#{node}" />
                </p:treeNode>
            </p:tree>

            <p:contextMenu for="mytree" id="mytreeContexMenu" model="#{menuView.model}" widgetVar="mytreeContexMenuVar">

            </p:contextMenu>
            </h:form>
        </h:body>
</html>
</code>```

mytree.js
The contextMenu should be updated and than showed
(based on the example found here: https://dnhome.wordpress.com/2013/10/07)

```<code>    var siteFunctions = {
        //patch to fix a problem that the context menu disappears after update
        //delay the show to occure after the update
        patchContextMenuShow: function() {
            'use strict';
            var protShow = PrimeFaces.widget.ContextMenu.prototype.show;
            siteFunctions.patchContextMenuShow.lastEvent = null;
            PrimeFaces.widget.ContextMenu.prototype.show = function(e) {
                var ret;
                if (e) {
                    siteFunctions.patchContextMenuShow.lastEvent = e;
                    siteFunctions.patchContextMenuShow.lastEventArg = arguments;

                     siteFunctions.patchContextMenuShow.lastEventContext = this;
                    //prevent default browser context menu
                     e.preventDefault();
                    e.stopPropagation();
                } else if (siteFunctions.patchContextMenuShow.lastEvent) {

                    ret = protShow.apply(siteFunctions.patchContextMenuShow.lastEventContext, siteFunctions.patchContextMenuShow.lastEventArg);
                    siteFunctions.patchContextMenuShow.lastEvent = null;
                }
                return ret;
            };
        }
    };

    $(document).ready(function() {
        'use strict';
        try {
            siteFunctions.patchContextMenuShow();
        } catch (e) {
            console.error(e);
        }
    });
</code>```

Title: Primefaces tree dynamic contextmenu

Body:
I think I have found a working solution. I have built an example based on the primeface's showcase

BasicView.java

package example;

import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;

import org.primefaces.context.RequestContext;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;

@ManagedBean(name="treeBasicView")
@ViewScoped
public class BasicView implements Serializable {

    private TreeNode root;

    @ManagedProperty(value="#{selectionView}")
    SelectionView selectionView;

    @PostConstruct
    public void init() {
        root = new DefaultTreeNode("Root", null);
        TreeNode node0 = new DefaultTreeNode("Node 0", root);
        TreeNode node1 = new DefaultTreeNode("Node 1", root);

        TreeNode node00 = new DefaultTreeNode("Node 0.0", node0);
        TreeNode node01 = new DefaultTreeNode("Node 0.1", node0);

        TreeNode node10 = new DefaultTreeNode("Node 1.0", node1);

        node1.getChildren().add(new DefaultTreeNode("Node 1.1"));
        node00.getChildren().add(new DefaultTreeNode("Node 0.0.0"));
        node00.getChildren().add(new DefaultTreeNode("Node 0.0.1"));
        node01.getChildren().add(new DefaultTreeNode("Node 0.1.0"));
        node10.getChildren().add(new DefaultTreeNode("Node 1.0.0"));
        root.getChildren().add(new DefaultTreeNode("Node 2"));
    }

    public TreeNode getRoot() {
        return root;
    }

    public void onNodeSelect(NodeSelectEvent event){
        checkSelectionChanged();
    }

    public void onRightClickSelectListener(NodeSelectEvent e) {
            checkSelectionChanged();
        }

/* Update the contextMenu only if the selection has changed */
        private void checkSelectionChanged(){
            if(this.getSelectionView().getSelectedNode()!=this.getSelectionView().getPrevSelectedNode()){
            RequestContext.getCurrentInstance().update("treeform:mytreeContexMenu");
        }
    }

    public SelectionView getSelectionView(){
        return selectionView;
    }

    public void setSelectionView(SelectionView selectionView){
        this.selectionView=selectionView;
    }
}

MenuView.java

package example;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import org.primefaces.model.menu.*;

@ManagedBean
@RequestScoped
public class MenuView {

    private MenuModel model;

    @ManagedProperty(value="#{selectionView}")
    SelectionView selectionView;

    public void init() {
        model = new DefaultMenuModel();

        //First submenu
        DefaultSubMenu firstSubmenu = new DefaultSubMenu("Dynamic Submenu");

        DefaultMenuItem item = new DefaultMenuItem("External");
        item.setUrl("http://www.primefaces.org");
        item.setIcon("ui-icon-home");
        firstSubmenu.addElement(item);

        model.addElement(firstSubmenu);

        //Second submenu
        DefaultSubMenu secondSubmenu = new DefaultSubMenu("Dynamic Actions");

        this.getTreeSelectionView().getSelectedNode();
        if(this.getTreeSelectionView().getSelectedNode()==null){
            return;
        }
        String nodeText = this.getTreeSelectionView().getSelectedNode().getData().toString();

        if(nodeText.contains("0")){ //just a condition
            item=new DefaultMenuItem("Action for 0");
            item.setIcon("ui-icon-disk");
            item.setCommand("#{menuView.save}");
            secondSubmenu.addElement(item);
        }

        if(nodeText.contains("1")){ //just a condition
            item=new DefaultMenuItem("Action for 1");
            item.setIcon("ui-icon-close");
            item.setCommand("#{menuView.delete}");
            item.setAjax(false);
            secondSubmenu.addElement(item);
        }

        if(nodeText.contains("2")){ //just a condition
            item=new DefaultMenuItem("Action for 2");
            item.setIcon("ui-icon-search");
            item.setCommand("#{menuView.redirect}");
            secondSubmenu.addElement(item);
        }

        model.addElement(secondSubmenu);
    }

    public MenuModel getModel() {
        if(model==null){
            this.init();
        }
        return model;
    }

    public void save() {}

    public void update() {}

    public void delete() {}

    public SelectionView getTreeSelectionView(){
        return selectionView;
    }

    public void setSelectionView(SelectionView selectionView){
        this.selectionView=selectionView;
    }
}

SelectionView.java

package example;

import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.model.TreeNode;

@ManagedBean(name="selectionView")
@ViewScoped
public class SelectionView implements Serializable {

    private TreeNode selectedNode;
    private TreeNode prevSelectedNode;

    public TreeNode getSelectedNode() {
        return selectedNode;
    }

    public void setSelectedNode(TreeNode selectedNode) {
        this.setPrevSelectedNode(this.selectedNode);
        this.selectedNode = selectedNode;
    }

    public TreeNode getPrevSelectedNode(){
        return prevSelectedNode;
    }

    public void setPrevSelectedNode(TreeNode prevSelectedNode){
        this.prevSelectedNode=prevSelectedNode;
    }
}

tree.xhtml

<!DOCTYPE html>
        <html
                xmlns="http://www.w3.org/1999/xhtml"
                xmlns:ui="http://java.sun.com/jsf/facelets"
                xmlns:f="http://java.sun.com/jsf/core"
                xmlns:h="http://java.sun.com/jsf/html"
                xmlns:p="http://primefaces.org/ui">

        <h:head>
            <title><h:outputText value="Test tree"/></title>
            <h:outputScript library="scripts" name="navigator.js"/>

        </h:head>
        <h:body>

            <h:form id="treeform">

            <p:tree value="#{treeBasicView.root}" var="node" dynamic="true" id="mytree" selectionMode="single" selection="#{selectionView.selectedNode}">
                <p:ajax event="select" listener="#{treeBasicView.onNodeSelect}"/>
                <p:ajax event="contextMenu" listener="#{treeBasicView.onRightClickSelectListener}" oncomplete="PF('mytreeContexMenuVar').show()"/>

                <p:treeNode>
                    <h:outputText value="#{node}" />
                </p:treeNode>
            </p:tree>

            <p:contextMenu for="mytree" id="mytreeContexMenu" model="#{menuView.model}" widgetVar="mytreeContexMenuVar">

            </p:contextMenu>
            </h:form>
        </h:body>
</html>

mytree.js
The contextMenu should be updated and than showed
(based on the example found here: https://dnhome.wordpress.com/2013/10/07)

    var siteFunctions = {
        //patch to fix a problem that the context menu disappears after update
        //delay the show to occure after the update
        patchContextMenuShow: function() {
            'use strict';
            var protShow = PrimeFaces.widget.ContextMenu.prototype.show;
            siteFunctions.patchContextMenuShow.lastEvent = null;
            PrimeFaces.widget.ContextMenu.prototype.show = function(e) {
                var ret;
                if (e) {
                    siteFunctions.patchContextMenuShow.lastEvent = e;
                    siteFunctions.patchContextMenuShow.lastEventArg = arguments;

                     siteFunctions.patchContextMenuShow.lastEventContext = this;
                    //prevent default browser context menu
                     e.preventDefault();
                    e.stopPropagation();
                } else if (siteFunctions.patchContextMenuShow.lastEvent) {

                    ret = protShow.apply(siteFunctions.patchContextMenuShow.lastEventContext, siteFunctions.patchContextMenuShow.lastEventArg);
                    siteFunctions.patchContextMenuShow.lastEvent = null;
                }
                return ret;
            };
        }
    };

    $(document).ready(function() {
        'use strict';
        try {
            siteFunctions.patchContextMenuShow();
        } catch (e) {
            console.error(e);
        }
    });


问:
How to detect if the user doesn't allow Apple Health Kit Authorisation?
I am using AppleHealthKit in my application. Everything is working correctly. The problem is that I am not able to detect if the user taps "Don't Allow" button when asking for permission.

With this method, my application uses HealthKit, even though the user doesn't allow this.

```<code>requestAuthorizationToShareTypes(healthKitTypesToWrite, readTypes: healthKitTypesToRead) { (success, error) -> Void in
        if( completion != nil ) {
            completion(success:success,error:error)
        }
</code>```

Apple Documentation:

So basically my question is how to detect this?

答:
You can do this but only for one specific type and only for write data(u can do the same with other type too if u have to check them)</p>

```<code>HKHealthStore *_healthStore;
HKQuantityType *stepsType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

HKAuthorizationStatus status = [_healthStore authorizationStatusForType:stepsType];

BOOL isActive;
switch (status) {
    case HKAuthorizationStatusSharingAuthorized:
        isActive = YES;
        break;
    case HKAuthorizationStatusSharingDenied:
        isActive = NO;
        break;
    case HKAuthorizationStatusNotDetermined:
        isActive = NO;
        break;

    default:
        break;
}

NSLog(@"STATUS-------%@", isActive ? @"yes" : @"no");
</code>```

Body:
I am using AppleHealthKit in my application. Everything is working correctly. The problem is that I am not able to detect if the user taps "Don't Allow" button when asking for permission.

With this method, my application uses HealthKit, even though the user doesn't allow this.

requestAuthorizationToShareTypes(healthKitTypesToWrite, readTypes: healthKitTypesToRead) { (success, error) -> Void in
        if( completion != nil ) {
            completion(success:success,error:error)
        }

Apple Documentation:

So basically my question is how to detect this?

Body:
You can do this but only for one specific type and only for write data(u can do the same with other type too if u have to check them)

HKHealthStore *_healthStore;
HKQuantityType *stepsType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

HKAuthorizationStatus status = [_healthStore authorizationStatusForType:stepsType];

BOOL isActive;
switch (status) {
    case HKAuthorizationStatusSharingAuthorized:
        isActive = YES;
        break;
    case HKAuthorizationStatusSharingDenied:
        isActive = NO;
        break;
    case HKAuthorizationStatusNotDetermined:
        isActive = NO;
        break;

    default:
        break;
}

NSLog(@"STATUS-------%@", isActive ? @"yes" : @"no");


问:
Django wsgi Apache2: 'AH01630: client denied by server configuration'
I've followed this tutorial to deploy my django project : https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-debian-8

Why the static files can't be loaded from apache?

I am using Debian9, Python3.5 and Django 1.11

This is my virtual host configuration:

```<code><VirtualHost *:80>

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    Alias /static /home/alex/djangoproject/static
    <Directory /home/alex/djangoproject/static>
        Require all granted
    </Directory>

    <Directory /home/alex/djangoproject/cpanel>
        <Files wsgi.py>
            Require all granted
        </Files>
    </Directory>

    WSGIDaemonProcess djangoproject python-home=/home/alex/djangoproject/djangoprojectenv python-path=/home/alex/djangoproject
    WSGIProcessGroup djangoproject
    WSGIScriptAlias / /home/alex/djangoproject/cpanel/wsgi.py

</VirtualHost>
</code>```

`

And the apache error from error.log:

AH01630: client denied by server configuration /home/alex/djangoproject/static

And my settings.py config related to static foder

STATIC_URL = '/static/'
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')

答:
Solved this by adding the django project name directory before static
so this :

```<code>Alias /static /home/alex/djangoproject/static
<Directory /home/alex/djangoproject/static>
    Require all granted
</Directory>
</code>```

Will become this:

```<code>Alias /static /home/alex/djangoproject/"django-project-name(in mycase: cpanel)"/static
<Directory /home/alex/djangoproject/"django-project-name(in mycase: cpanel)"/static>
    Require all granted
</Directory>
</code>```

Performed ./migrate.py collectstatic , restart apache and all running smoothly.

Body:
I've followed this tutorial to deploy my django project : https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-debian-8

Why the static files can't be loaded from apache?

I am using Debian9, Python3.5 and Django 1.11

This is my virtual host configuration:

<VirtualHost *:80>

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    Alias /static /home/alex/djangoproject/static
    <Directory /home/alex/djangoproject/static>
        Require all granted
    </Directory>

    <Directory /home/alex/djangoproject/cpanel>
        <Files wsgi.py>
            Require all granted
        </Files>
    </Directory>

    WSGIDaemonProcess djangoproject python-home=/home/alex/djangoproject/djangoprojectenv python-path=/home/alex/djangoproject
    WSGIProcessGroup djangoproject
    WSGIScriptAlias / /home/alex/djangoproject/cpanel/wsgi.py

</VirtualHost>

`

And the apache error from error.log:

AH01630: client denied by server configuration /home/alex/djangoproject/static

And my settings.py config related to static foder

STATIC_URL = '/static/'
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')

Body:
Solved this by adding the django project name directory before static
so this :

Alias /static /home/alex/djangoproject/static
<Directory /home/alex/djangoproject/static>
    Require all granted
</Directory>

Will become this:

Alias /static /home/alex/djangoproject/"django-project-name(in mycase: cpanel)"/static
<Directory /home/alex/djangoproject/"django-project-name(in mycase: cpanel)"/static>
    Require all granted
</Directory>

Performed ./migrate.py collectstatic , restart apache and all running smoothly.


问:
Unexpected result in Java (floating to integer)
I have a problem with this

```<code>System.out.print((9/5) * 3);
</code>```

I expects the result 5.4 but it returns 3. Why is this happening?

答:
All the numbers are integer there so it will give integer result you may make 9.0 or 5.0 to get that answer...
As given below..</p>

```<code>System.out.print((9.0/5) * 3); OR
System.out.print((9/5.0) * 3);
</code>```

Body:
I have a problem with this

System.out.print((9/5) * 3);

I expects the result 5.4 but it returns 3. Why is this happening?

Body:
All the numbers are integer there so it will give integer result you may make 9.0 or 5.0 to get that answer...
As given below..

System.out.print((9.0/5) * 3); OR
System.out.print((9/5.0) * 3);


问:
Task Scheduler is not supporting option "Run with highest Privilege" and "Run weather user is logged on or not"
I am trying to schedule Task on Task Scheduler, every thing is working fine unless I tick "Run with Highest privileges" or "Run weather user is logged on or not"

As soon as I tick this, scheduler stop triggering my Script.

Script- .Bat file using Power Shell command.

Can any one figure out what went wrong?

Edited- ( Changed file location from drive to network drive)

```<code>@Echo Off

:: SDate=DAYMONTHYEAR FORMAT of Systemdate
::set SDate=%date:~7,2%%date:~4,2%%date:~10,4%

::Variable for folder path
for /D %%d in ("\\Server\Schd File\AA\*") do (
for %%a in ("%%d\*.*") do (SET "FPath=%%~dpa"
Set "FName=%%~na" )
)

For /F "Tokens=4-9 Delims=-" %%A In ("%FName%") Do (
    Set "Freq=%%B"
    Set "ADate=%%F%%E%%D"
)

Set "DFormat=ddMMyyyy"

IF %Freq% == Daily (
For /F UseBackQ %%A In (
    `Powershell "([datetime]::ParseExact('%ADate%','%DFormat%',[System.Globalization.CultureInfo]::CurrentCulture)).AddDays(-1).ToString('ddMMyyyy')"`
) Do Set "DateF=%%A"
)

IF %Freq% == Weekly (
For /F UseBackQ %%A In (
    `Powershell "([datetime]::ParseExact('%ADate%','%DFormat%', [System.Globalization.CultureInfo]::CurrentCulture)).AddDays(-7).ToString('ddMMyyyy')"`
) Do Set "DateF=%%A"
)

IF %Freq% == Monthly (
For /F UseBackQ %%A In (
    `Powershell "([datetime]::ParseExact('%ADate%','%DFormat%', [System.Globalization.CultureInfo]::CurrentCulture)).AddMonths(-1).ToString('MMMyyyy')"`
) Do Set "DateF=%%A"
)

mkdir "%FPath%%Freq%\%DateF%"
move "%FPath%\%FName%.*" "%FPath%%Freq%\%DateF%\"

GoTo :EOF
</code>```

答:
There was a major overhaul of Scheduled Tasks security in Vista and later to prevent hackers from installing a scheduled task that could access network resources.

When you set the task to run whether or not a user is logged on you must set the user credentials to a user with the permissions needed to run the task. That user must also have the local policy set to allow the user to run batch files.

Additionally, when a user is not logged on, task scheduler uses “Service-for-User” (S4U) authentication which denies the user access to any network functionality. Assuming your "D:\AA*" path is a local drive this may not be a problem but if it is a mapped network drive it will be a problem.

"Run with Highest privileges" does not grant higher privileges to the specified user but runs under a completely separate security token for the system Administrator account that is created when Windows is installed.

https://technet.microsoft.com/en-us/library/cc722152(v=ws.11).aspx

https://technet.microsoft.com/en-us/library/cc732613(v=ws.10).aspx

https://technet.microsoft.com/en-us/library/ee844140(v=ws.10).aspx

https://superuser.com/questions/640962/why-cant-a-task-scheduler-job-access-a-mapped-network-drive/782836#782836

The only solution I found to run a task overnight that needs network access was to leave the machine running and the user logged on.

Body:
I am trying to schedule Task on Task Scheduler, every thing is working fine unless I tick "Run with Highest privileges" or "Run weather user is logged on or not"

As soon as I tick this, scheduler stop triggering my Script.

Script- .Bat file using Power Shell command.

Can any one figure out what went wrong?

Edited- ( Changed file location from drive to network drive)

@Echo Off

:: SDate=DAYMONTHYEAR FORMAT of Systemdate
::set SDate=%date:~7,2%%date:~4,2%%date:~10,4%

::Variable for folder path
for /D %%d in ("\\Server\Schd File\AA\*") do (
for %%a in ("%%d\*.*") do (SET "FPath=%%~dpa"
Set "FName=%%~na" )
)

For /F "Tokens=4-9 Delims=-" %%A In ("%FName%") Do (
    Set "Freq=%%B"
    Set "ADate=%%F%%E%%D"
)

Set "DFormat=ddMMyyyy"

IF %Freq% == Daily (
For /F UseBackQ %%A In (
    `Powershell "([datetime]::ParseExact('%ADate%','%DFormat%',[System.Globalization.CultureInfo]::CurrentCulture)).AddDays(-1).ToString('ddMMyyyy')"`
) Do Set "DateF=%%A"
)

IF %Freq% == Weekly (
For /F UseBackQ %%A In (
    `Powershell "([datetime]::ParseExact('%ADate%','%DFormat%', [System.Globalization.CultureInfo]::CurrentCulture)).AddDays(-7).ToString('ddMMyyyy')"`
) Do Set "DateF=%%A"
)

IF %Freq% == Monthly (
For /F UseBackQ %%A In (
    `Powershell "([datetime]::ParseExact('%ADate%','%DFormat%', [System.Globalization.CultureInfo]::CurrentCulture)).AddMonths(-1).ToString('MMMyyyy')"`
) Do Set "DateF=%%A"
)

mkdir "%FPath%%Freq%\%DateF%"
move "%FPath%\%FName%.*" "%FPath%%Freq%\%DateF%\"

GoTo :EOF


问:
Set the Startpoint and End point of a Connector in Enterprise Architect through C# add-ins
I am working in Enterprise Architect C# add-ins. I need to arrange the elements and connectors through code such that there is no overlapping of connectors. I have set the Line Style as Auto Routing for the diagram links.

Is there a API available in EA for setting the starting point/ending point of connector as source element's dimension value such that the connector starts from the top of the element.

Kindly Help. Thanks in advance.

Edit:I have tried updating through API as follows but am not able to see change in connector starting position:

```<code>            for (short i = 0; i < Diagram.DiagramLinks.Count; i++)
            {

                    EA.DiagramLink dl = Diagram.DiagramLinks.GetAt(i);
                    //set the line style and update
                    dl.LineStyle = EA.LinkLineStyle.LineStyleAutoRouting;
                    dl.Geometry = "EDGE=4;";
                    dl.Update();
                    Diagram.Update();
            }
</code>```

答:
This is possible, but tricky. DiagramLinks have an attribute Geometry which holds a csv styled list. A detailed description can be found in my Inside book, but you can simply look for parameters SX and SY which specify the relative X and Y positions and they can vary +- half width/height of the start object. Analogously EXand EY for the end. Finally the EDGE parameter specifies the edge from where the connector starts at the start object: 1=bottom; 2=left; 3=top; 4=right

Edit1: I fiddled around a bit, but I have no open mind at the moment. What you should do is to create an empty EAP and place two two elements on a diagram and connect these. Now run SELECT geometry FROM t_diagramlinks in the SQL scratch pad. Move the connector/elements around, save the diagram (or the changes will not be written to the database) and re-issue the SQL to see the effect on SX etc.

Also, you can update Geometry via the API which is what I'd recommend. Further you need to reload the diagram to see the updates reflected in the graphics.

Edit2: Probably the answer to your issue. The Edge attribute is just a r/o attribute. Important are the coordinate parameters. So if you want to have the connector start at the middle top edge you need to set SX=0;SY=<halfheight>; where <halfheight> is half of the element height. Also note that you can provide values which are out of bounds and EA will just render funny results (means they do not check the validity of the attribute on Update()).

This has been my test code (sorry for the Perl ;-):

```<code>my $d = $rep->GetCurrentDiagram();
for my $dl (in $d->DiagramLinks) {
  print $dl->Geometry . "\n";
  $dl->{Geometry} = 'SX=0;SY=10;EX=0;EY=0;';
  $dl->Update();
}
$rep->ReloadDiagram($d->DiagramId);
</code>```

P.S. The edge is always determined upon the relative positioning of the connected elements (unless connector ends are pinned).

Body:
I am working in Enterprise Architect C# add-ins. I need to arrange the elements and connectors through code such that there is no overlapping of connectors. I have set the Line Style as Auto Routing for the diagram links.

Is there a API available in EA for setting the starting point/ending point of connector as source element's dimension value such that the connector starts from the top of the element.

Kindly Help. Thanks in advance.

Edit:I have tried updating through API as follows but am not able to see change in connector starting position:

            for (short i = 0; i < Diagram.DiagramLinks.Count; i++)
            {

                    EA.DiagramLink dl = Diagram.DiagramLinks.GetAt(i);
                    //set the line style and update
                    dl.LineStyle = EA.LinkLineStyle.LineStyleAutoRouting;
                    dl.Geometry = "EDGE=4;";
                    dl.Update();
                    Diagram.Update();
            }

Body:
This is possible, but tricky. DiagramLinks have an attribute Geometry which holds a csv styled list. A detailed description can be found in my Inside book, but you can simply look for parameters SX and SY which specify the relative X and Y positions and they can vary +- half width/height of the start object. Analogously EXand EY for the end. Finally the EDGE parameter specifies the edge from where the connector starts at the start object: 1=bottom; 2=left; 3=top; 4=right

Edit1: I fiddled around a bit, but I have no open mind at the moment. What you should do is to create an empty EAP and place two two elements on a diagram and connect these. Now run SELECT geometry FROM t_diagramlinks in the SQL scratch pad. Move the connector/elements around, save the diagram (or the changes will not be written to the database) and re-issue the SQL to see the effect on SX etc.

Also, you can update Geometry via the API which is what I'd recommend. Further you need to reload the diagram to see the updates reflected in the graphics.

Edit2: Probably the answer to your issue. The Edge attribute is just a r/o attribute. Important are the coordinate parameters. So if you want to have the connector start at the middle top edge you need to set SX=0;SY=<halfheight>; where <halfheight> is half of the element height. Also note that you can provide values which are out of bounds and EA will just render funny results (means they do not check the validity of the attribute on Update()).

This has been my test code (sorry for the Perl ;-):

my $d = $rep->GetCurrentDiagram();
for my $dl (in $d->DiagramLinks) {
  print $dl->Geometry . "\n";
  $dl->{Geometry} = 'SX=0;SY=10;EX=0;EY=0;';
  $dl->Update();
}
$rep->ReloadDiagram($d->DiagramId);

P.S. The edge is always determined upon the relative positioning of the connected elements (unless connector ends are pinned).


问:
Should the password field be unique?
In light of the recent Gawker Media password leak, I've realized that many users share the same passwords. To help encourage stronger passwords, would it be helpful if passwords are constrained to be unique among all users?

One immediate downside I could think of (besides account creation performance?) is being able to know that someone is using a given string as a password. This knowledge, combined with a list of users, could be quite dangerous.

Is there a way to mitigate that downside while retaining the alleged benefits of not allowing repeat passwords?

It's kind of like the XKCD kick bot where you aren't allowed to repeat short, unoriginal sentences like "yah" or "lol".

Edit^2: I thought you could unique-ify against a hash, but as someone pointed out, with varying salts, this would not have the intended effect. Good eye!

答:
I would suggest the follwing as you have already mentioned the disadvantage of using "unique@ passwords for all

Educate the user's about strong password.

Ask user's to change password regularly.

Keep a "Password strength" meter while they type in the password.

Title: Should the password field be unique?


问:
What is the gold standard for creating a main() loop that waits for a Thread in Java
I was tasked to write a small server application. It is supposed to be started via the console and then run in the background, processing some network traffic and calculating stuff locally until it receives a shutdown signal. I am pretty sure i can handle all of that - except the very basic application architecture. I am super unsure how to bring my main loop to wait for the application to finish. So here is my current code, cleaned up and omitting unnecessary parts.

```<code>public class TestServer {

public static Logger logger;
private static Boolean abortStartup = false;
private static ServerModule server;

public static void main(String[] args) {
    System.out.println("Starting Server...");
        initializeServer(); //this function reads config file, and initializes all variables and stuff. If anything goes wrong, abortStartup is set to true

        if (!abortStartup) {
            runMainLoop();
        }

        if (!abortStartup) {
            cleanup(); //clean up all initialized variables and objects
        }

    System.out.println("Goodbye.");
}

private static void runMainLoop() {
    //This is the main loop. Run this until application terminates.
    logger.log(null, "Starting main loop...", Logger.LOGLEVEL_NOTE);
        server.run();
        while (server.isAlive()) {
            //wait until server dies.
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                logger.log(null, "Interrupted during wait for main thread.", Logger.LOGLEVEL_ERROR);
            }
        }
    logger.log(null, "Done.", Logger.LOGLEVEL_NOTE);
}
</code>```

ServerModule looks like this:

```<code>public class ServerModule{

public Boolean shutdown = false;
private Boolean stayAlive = true;

public ServerModule(){
    //setup everything
}

public void run() {
    //initalize timers, instantiate objects etc.. add listeners and everything. At some point, a network message will set stayAlive to false;
}

public Boolean isAlive() {
    return stayAlive;
}
</code>```

Now for the actual question: is there a more elegant or more efficient way to go about this? i am talking about this part specifically:

```<code>while (server.isAlive()) {
            //wait until server dies.
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                logger.log(null, "Interrupted during wait for main thread.", Logger.LOGLEVEL_ERROR);
            }
</code>```

Is thread.sleep okay here? Could or should i even omit it? I want to wait here at this very point of my code, so i can clean up after execution stops.

答:
You can make your server something runnable, pack that into a Thread and join!

Example

```<code>public static void main(String[] args) throws InterruptedException {
    Thread t = new Thread(() -> {
        try {
            Thread.sleep(5000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    System.out.println("Starting Server!");
    t.start();
    t.join();
    System.out.println("Server is done!");

}
</code>```

Body:
I was tasked to write a small server application. It is supposed to be started via the console and then run in the background, processing some network traffic and calculating stuff locally until it receives a shutdown signal. I am pretty sure i can handle all of that - except the very basic application architecture. I am super unsure how to bring my main loop to wait for the application to finish. So here is my current code, cleaned up and omitting unnecessary parts.

public class TestServer {

public static Logger logger;
private static Boolean abortStartup = false;
private static ServerModule server;

public static void main(String[] args) {
    System.out.println("Starting Server...");
        initializeServer(); //this function reads config file, and initializes all variables and stuff. If anything goes wrong, abortStartup is set to true

        if (!abortStartup) {
            runMainLoop();
        }

        if (!abortStartup) {
            cleanup(); //clean up all initialized variables and objects
        }

    System.out.println("Goodbye.");
}

private static void runMainLoop() {
    //This is the main loop. Run this until application terminates.
    logger.log(null, "Starting main loop...", Logger.LOGLEVEL_NOTE);
        server.run();
        while (server.isAlive()) {
            //wait until server dies.
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                logger.log(null, "Interrupted during wait for main thread.", Logger.LOGLEVEL_ERROR);
            }
        }
    logger.log(null, "Done.", Logger.LOGLEVEL_NOTE);
}

ServerModule looks like this:

public class ServerModule{

public Boolean shutdown = false;
private Boolean stayAlive = true;

public ServerModule(){
    //setup everything
}

public void run() {
    //initalize timers, instantiate objects etc.. add listeners and everything. At some point, a network message will set stayAlive to false;
}

public Boolean isAlive() {
    return stayAlive;
}

Now for the actual question: is there a more elegant or more efficient way to go about this? i am talking about this part specifically:

while (server.isAlive()) {
            //wait until server dies.
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                logger.log(null, "Interrupted during wait for main thread.", Logger.LOGLEVEL_ERROR);
            }

Is thread.sleep okay here? Could or should i even omit it? I want to wait here at this very point of my code, so i can clean up after execution stops.

Body:
You can make your server something runnable, pack that into a Thread and join!

Example

public static void main(String[] args) throws InterruptedException {
    Thread t = new Thread(() -> {
        try {
            Thread.sleep(5000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    System.out.println("Starting Server!");
    t.start();
    t.join();
    System.out.println("Server is done!");

}


问:
bug in the SQL parser
hello could somebody please tell me what should I do about this:

```<code> Error
 There is a chance that you may have found a bug in the SQL parser. Please
 examine your query closely, and check that the quotes are correct and not mis-matched.
 Other possible  failure causes may be that you are uploading a file with binary
 outside
 of a quoted text area. You can also try your query on the MySQL command line
 interface.
 The MySQL server error output below, if there is any, may also help you in diagnosing
 the problem. If you still have problems or if the parser fails where the command line
 interface succeeds, please reduce your SQL query input to the single query that causes
 problems, and submit a bug report with the data chunk in the CUT section below:

 ----BEGIN CUT----
 eNodzUsKwyAYBOBFdv8p5gBW1DQE3AWRZOGrmrYHCF0EgrtCe/ua7obhY8bmHLOGkTAKzgYNCQVF
 ZW1tR+S/5eY0Bi75KC7bcdC9ZMTCMM02rAwP2+BzrzBLjt42KXgvKPlJ49ryQGlJp2KxnDs9lyPc
 Xt8fclOYNV6V/hfU/QAEiiEJ
 ----END CUT----
 ----BEGIN RAW----
 ERROR: C1 C2 LEN: 1 2 2
 STR:

 MySQL: 5.1.70-cll
 USR OS, AGENT, VER: Win CHROME 5.0.30
 PMA: 4.0.5
 PHP VER,OS: 5.3.17 Linux
 LANG: en
 SQL:

 ----END RAW----

 SQL query:

 MySQL said: Documentation

 #1064 - You have an error in your SQL syntax; check the manual that corresponds to
  your MySQL server version for the right syntax to use near '' at line 1
</code>```

I've exported my Database as a backup and now when I import that I get this Error !! what's that? please tell me by the way I have some Arabic texts in my tables ...??

答:
Open the SQL document with any text editor and at the very end of the file, remove the blank lines (null characters). Save the file and you're good to go.

Source: https://sourceforge.net/p/phpmyadmin/bugs/4095/

Title: bug in the SQL parser

Body:
hello could somebody please tell me what should I do about this:

 Error
 There is a chance that you may have found a bug in the SQL parser. Please
 examine your query closely, and check that the quotes are correct and not mis-matched.
 Other possible  failure causes may be that you are uploading a file with binary
 outside
 of a quoted text area. You can also try your query on the MySQL command line
 interface.
 The MySQL server error output below, if there is any, may also help you in diagnosing
 the problem. If you still have problems or if the parser fails where the command line
 interface succeeds, please reduce your SQL query input to the single query that causes
 problems, and submit a bug report with the data chunk in the CUT section below:

 ----BEGIN CUT----
 eNodzUsKwyAYBOBFdv8p5gBW1DQE3AWRZOGrmrYHCF0EgrtCe/ua7obhY8bmHLOGkTAKzgYNCQVF
 ZW1tR+S/5eY0Bi75KC7bcdC9ZMTCMM02rAwP2+BzrzBLjt42KXgvKPlJ49ryQGlJp2KxnDs9lyPc
 Xt8fclOYNV6V/hfU/QAEiiEJ
 ----END CUT----
 ----BEGIN RAW----
 ERROR: C1 C2 LEN: 1 2 2
 STR:

 MySQL: 5.1.70-cll
 USR OS, AGENT, VER: Win CHROME 5.0.30
 PMA: 4.0.5
 PHP VER,OS: 5.3.17 Linux
 LANG: en
 SQL:

 ----END RAW----

 SQL query:

 MySQL said: Documentation

 #1064 - You have an error in your SQL syntax; check the manual that corresponds to
  your MySQL server version for the right syntax to use near '' at line 1

I've exported my Database as a backup and now when I import that I get this Error !! what's that? please tell me by the way I have some Arabic texts in my tables ...??


问:
Active redshift user count for specific time period
I need Active redshift user count for specific time period (say 20th Apr to 25th May).

I know PG_user table, but know luck with what i am looking for.
All on all i need a report with active user count for specific time period (20th Apr to 25th May).

Thanks a lot in advance.

答:
Do you need to know how many user where logged in that time period?
to get the list day by day

```<code> select  starttime, process, user_name
 from stl_sessions where starttime>='2017-04-20' starttime <'2017-05-26'
</code>```

to count users in total during that period:

```<code> select  count(*)
 from stl_sessions where starttime>='2017-04-20' starttime <'2017-05-26'
</code>```

Body:
Do you need to know how many user where logged in that time period?
to get the list day by day

 select  starttime, process, user_name
 from stl_sessions where starttime>='2017-04-20' starttime <'2017-05-26'

to count users in total during that period:

 select  count(*)
 from stl_sessions where starttime>='2017-04-20' starttime <'2017-05-26'


问:
How to use conditional arguments while plotting in R?
I have a dataframe of which two columns are of date and sales. date column varies from 2012-10-22 to 2016-09-22. I want to plot the graph of sales in jan 2013 by day without creating any subset.

I have used this-
ggplot(subsales,aes(Date,spdby))+geom_line()

Is it possible by using ggplot()?

I have plotted the sales per day and look like this-

I want to zoom in, to January 2013 and want to extract that part as a new plot.

答:
yes, in ggplot:

library(ggplot2)

subsales <- data.frame(
  date = seq(as.Date("2013-1-1"), as.Date("2017-1-1"), by = "day"),
  spdby = runif(1462, 2000, 6000)
)

ggplot(subsales, aes(date, spdby)) +
  geom_line()
```

<p><img src="https://i.imgur.com/FpyVsQS.png" alt=""></p>

<pre class="lang-r prettyprint-override"><code>ggplot(subsales, aes(date, spdby)) + geom_line() +
  scale_x_date(limits = c(as.Date("2013-1-1"), as.Date("2013-1-31")))
#> Warning: Removed 1431 rows containing missing values (geom_path).
</code>```

Body:
yes, in ggplot:

library(ggplot2)

subsales <- data.frame(
  date = seq(as.Date("2013-1-1"), as.Date("2017-1-1"), by = "day"),
  spdby = runif(1462, 2000, 6000)
)

ggplot(subsales, aes(date, spdby)) +
  geom_line()

ggplot(subsales, aes(date, spdby)) + geom_line() +
  scale_x_date(limits = c(as.Date("2013-1-1"), as.Date("2013-1-31")))
#> Warning: Removed 1431 rows containing missing values (geom_path).


问:
Tic Tac Toe how to tell user there is no winner?
I'm working in this project for 3 days and i can not figure out where I'm doing wrong if you can help me with i really appreciate your help.I'm trying to create a tic tac toe game .When I'm running the game if the player X or O  wins a message will pop up saying that X or O win .But if the a non of users win a message should pop up and saying there is no winner . the pop up for the winner is working perfectly but the pop up for no one win does not work.if you can help me to fix it you are really making my day.</p>

```<code>public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;

int activePlayer = 0; // for x player

int[] gameState ={2,2,2,2,2,2,2,2,2}; // 2 means unplayed.

int[][] winningLocation ={{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
boolean gameover =false;

public void gameLogic(View view){

    ImageView tappedView =(ImageView) view;

    int tappedLocation = Integer.parseInt(view.getTag().toString());

    if(gameState[tappedLocation]==2 && !gameover) {
        gameState[tappedLocation]=activePlayer;

        tappedView.setTranslationY(-3000f);

        if (activePlayer == 0) {

            tappedView.setImageResource(R.drawable.x);

            activePlayer = 1;

        } else if (activePlayer == 1) {
            tappedView.setImageResource(R.drawable.o);
            activePlayer = 0;
        }
        tappedView.animate().translationYBy(3000f).setDuration(500);
    }
  String mesg ="";

    for(int[]winningPostion :winningLocation){

        if(gameState[winningPostion[0]] == gameState [winningPostion[1]]
                && gameState[winningPostion[1]]== gameState [winningPostion[2]]
                && gameState[winningPostion[0]]!=2){

            if (activePlayer ==0)

                mesg = "O is the winner!";

            if(activePlayer==1)

                mesg = "X is the winner!";

            else
                gameover=true;
            mesg="there is no winner ";

            LinearLayout winnerLayout =(LinearLayout)findViewById (R.id.winnerLayout);
            winnerLayout.setVisibility(View .VISIBLE);

            TextView winnermesg = (TextView) findViewById(R.id.editText);
            winnermesg.setText(mesg);

            gameover=true;
        }
    }

}

// a method that let the players play again

public void playagain(View view){
    LinearLayout winnerLayout = (LinearLayout) findViewById(R.id.winnerLayout);
    winnerLayout.setVisibility(View.INVISIBLE);
    gameover=false;
    activePlayer=0;

    for (int i =0; i < gameState.length;i++)
        gameState[i]=2;

    GridLayout gridlayout = (GridLayout) findViewById(R.id.gridlayout);
    for(int i =0 ; i < gridlayout.getChildCount(); i++)
        ((ImageView)gridlayout.getChildAt(i)).setImageResource(0);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

 // to play the song
      mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.song);
      mediaPlayer.start();

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // to show and hide the playing again button

   LinearLayout winnerLayout = ( LinearLayout) findViewById(R.id.winnerLayout);
    winnerLayout.setVisibility(View.INVISIBLE);

   FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

// pause and play the song when the user leaving annd returning the game
@Override
protected void onPause(){
    super.onPause();
    mediaPlayer.stop();
    mediaPlayer.release();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}
</code>```

答:
Enclose the block with braces { }</p>

```<code>else {
    gameover=true;
    mesg="there is no winner ";
}
</code>```

Body:
I'm working in this project for 3 days and i can not figure out where I'm doing wrong if you can help me with i really appreciate your help.I'm trying to create a tic tac toe game .When I'm running the game if the player X or O  wins a message will pop up saying that X or O win .But if the a non of users win a message should pop up and saying there is no winner . the pop up for the winner is working perfectly but the pop up for no one win does not work.if you can help me to fix it you are really making my day.

public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;

int activePlayer = 0; // for x player

int[] gameState ={2,2,2,2,2,2,2,2,2}; // 2 means unplayed.

int[][] winningLocation ={{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
boolean gameover =false;

public void gameLogic(View view){

    ImageView tappedView =(ImageView) view;

    int tappedLocation = Integer.parseInt(view.getTag().toString());

    if(gameState[tappedLocation]==2 && !gameover) {
        gameState[tappedLocation]=activePlayer;

        tappedView.setTranslationY(-3000f);

        if (activePlayer == 0) {

            tappedView.setImageResource(R.drawable.x);

            activePlayer = 1;

        } else if (activePlayer == 1) {
            tappedView.setImageResource(R.drawable.o);
            activePlayer = 0;
        }
        tappedView.animate().translationYBy(3000f).setDuration(500);
    }
  String mesg ="";

    for(int[]winningPostion :winningLocation){

        if(gameState[winningPostion[0]] == gameState [winningPostion[1]]
                && gameState[winningPostion[1]]== gameState [winningPostion[2]]
                && gameState[winningPostion[0]]!=2){

            if (activePlayer ==0)

                mesg = "O is the winner!";

            if(activePlayer==1)

                mesg = "X is the winner!";

            else
                gameover=true;
            mesg="there is no winner ";

            LinearLayout winnerLayout =(LinearLayout)findViewById (R.id.winnerLayout);
            winnerLayout.setVisibility(View .VISIBLE);

            TextView winnermesg = (TextView) findViewById(R.id.editText);
            winnermesg.setText(mesg);

            gameover=true;
        }
    }

}

// a method that let the players play again

public void playagain(View view){
    LinearLayout winnerLayout = (LinearLayout) findViewById(R.id.winnerLayout);
    winnerLayout.setVisibility(View.INVISIBLE);
    gameover=false;
    activePlayer=0;

    for (int i =0; i < gameState.length;i++)
        gameState[i]=2;

    GridLayout gridlayout = (GridLayout) findViewById(R.id.gridlayout);
    for(int i =0 ; i < gridlayout.getChildCount(); i++)
        ((ImageView)gridlayout.getChildAt(i)).setImageResource(0);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

 // to play the song
      mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.song);
      mediaPlayer.start();

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // to show and hide the playing again button

   LinearLayout winnerLayout = ( LinearLayout) findViewById(R.id.winnerLayout);
    winnerLayout.setVisibility(View.INVISIBLE);

   FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

// pause and play the song when the user leaving annd returning the game
@Override
protected void onPause(){
    super.onPause();
    mediaPlayer.stop();
    mediaPlayer.release();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

Body:
Enclose the block with braces { }

else {
    gameover=true;
    mesg="there is no winner ";
}


问:
Patch becoming empty when running with packer build. How to fix this
I have automated a image build process in a cloud environment using packer tool.

It installs lot of tools and applies lot of patches using linux path tool.

Everything is working as expected when doing manually. But with packer automation I'm facing one issue with apllying patch.

There is a config file at /etc/myprogram/myconfig.cfg.

I'm running patch like this.

pushd /etc/myprogram
patch -p 0 < myconfig.cfg.patch

Patch is applying successfully when running manually. But with packer that target file is becoming empty.

But in stdout of packer build i can see output like 2 hunks applied.

What cloud be the issue ? Please some suggestions to debug this.

packer build base.json

base.json

```<code>{
    "builders": [
        {
            "flavor": "general1-8",
            "image_name": "Havell Build {{ timestamp }}",
            "source_image": "d944e490-f615-49a5-97f7-b80a8b0398d4",
            "ssh_keypair_name": "packer-manual",
            "ssh_private_key_file": "packer-manual.key",
            "ssh_username": "root",
            "type": "openstack"
        }
    ],
    "provisioners": [
        {   "type": "shell",
            "inline": "mkdir -p /tmp/patches/"
        },
        {
            "type": "file",
            "source": "patches/",
            "destination": "/tmp/patches/"
        },
        {
            "script": "apply_patches.sh",
            "type": "shell"
        }
    ]
}
</code>```

apply_patches.sh

```<code>#!/bin/bash
set -ex

echo "*********************before************************"
echo "***************************************************"
cat /etc/myprogram/myconfig.cfg
echo "***************************************************"
echo "***************************************************"
pushd /etc/myprogram
patch -p 0 < myconfig.cfg.patch

echo "***********************after***********************"
echo "***************************************************"
cat /etc/myprogram/myconfig.cfg
echo "***************************************************"
echo "***************************************************"

exit 0
</code>```

答:
Change your script to read:</p>

```<code>pushd /etc/myprogram
patch -p 0 < /tmp/patches/myconfig.cfg.patch
</code>```

Body:
I have automated a image build process in a cloud environment using packer tool.

It installs lot of tools and applies lot of patches using linux path tool.

Everything is working as expected when doing manually. But with packer automation I'm facing one issue with apllying patch.

There is a config file at /etc/myprogram/myconfig.cfg.

I'm running patch like this.

pushd /etc/myprogram
patch -p 0 < myconfig.cfg.patch

Patch is applying successfully when running manually. But with packer that target file is becoming empty.

But in stdout of packer build i can see output like 2 hunks applied.

What cloud be the issue ? Please some suggestions to debug this.

packer build base.json

base.json

{
    "builders": [
        {
            "flavor": "general1-8",
            "image_name": "Havell Build {{ timestamp }}",
            "source_image": "d944e490-f615-49a5-97f7-b80a8b0398d4",
            "ssh_keypair_name": "packer-manual",
            "ssh_private_key_file": "packer-manual.key",
            "ssh_username": "root",
            "type": "openstack"
        }
    ],
    "provisioners": [
        {   "type": "shell",
            "inline": "mkdir -p /tmp/patches/"
        },
        {
            "type": "file",
            "source": "patches/",
            "destination": "/tmp/patches/"
        },
        {
            "script": "apply_patches.sh",
            "type": "shell"
        }
    ]
}

apply_patches.sh

#!/bin/bash
set -ex

echo "*********************before************************"
echo "***************************************************"
cat /etc/myprogram/myconfig.cfg
echo "***************************************************"
echo "***************************************************"
pushd /etc/myprogram
patch -p 0 < myconfig.cfg.patch

echo "***********************after***********************"
echo "***************************************************"
cat /etc/myprogram/myconfig.cfg
echo "***************************************************"
echo "***************************************************"

exit 0

Body:
Change your script to read:

pushd /etc/myprogram
patch -p 0 < /tmp/patches/myconfig.cfg.patch


问:
How to combine stdin and file for formatted output in sed or awk?
I need to find a single line of code, I think SED or AWK would be the best tools, to take two inputs (one stdin, one file) and combine them to output one formatted line to stdout.

stdin data: 20170607233000 wind0 180 1 2 3

file data: 270

output needed: 270 1 2 3
(replace the 180 with 270 from file, drop the timestamp and wind0 "name")

I have this line of code:

```<code>awk ‘ { printf "%d %d %d %d", $7, $4, $5, $6 }’ - heading.txt
</code>```

but it processes stdin and heading.txt and independent inputs and provides two outputs.

I also found this example of code, and it gets close to what I want but I don't understand how to format/reorder the output:

```<code>awk ’FNR==NR { a[FNR""] = $0; next } { print a[FNR""], $0 }'
</code>```

Here's the context in case you care: This is for a weather station sitting on a (large) boat. The wind direction always reports relative to the boat, typically reporting North, but that's not accurate. The boat pivots on a single anchor point and always faces in to the wind. I have a magnetometer (compass) hooked to the RaspberryPi that is the weather station and reads the heading the boat is facing and writes it to a file via cron. This makes the boat in to a giant wind vane. I need to take the heading data from the file and replace the wind direction with the "real" value. The weather station code is nice enough to allow me to create a "virtual" gauge based on other gauges and insert code via a cgi script. The limitation is that the code has to be a single line that can be executed in the linux shell and return data via stdout.

Body:
I need to find a single line of code, I think SED or AWK would be the best tools, to take two inputs (one stdin, one file) and combine them to output one formatted line to stdout.

stdin data: 20170607233000 wind0 180 1 2 3

file data: 270

output needed: 270 1 2 3
(replace the 180 with 270 from file, drop the timestamp and wind0 "name")

I have this line of code:

awk ‘ { printf "%d %d %d %d", $7, $4, $5, $6 }’ - heading.txt

but it processes stdin and heading.txt and independent inputs and provides two outputs.

I also found this example of code, and it gets close to what I want but I don't understand how to format/reorder the output:

awk ’FNR==NR { a[FNR""] = $0; next } { print a[FNR""], $0 }'

Here's the context in case you care: This is for a weather station sitting on a (large) boat. The wind direction always reports relative to the boat, typically reporting North, but that's not accurate. The boat pivots on a single anchor point and always faces in to the wind. I have a magnetometer (compass) hooked to the RaspberryPi that is the weather station and reads the heading the boat is facing and writes it to a file via cron. This makes the boat in to a giant wind vane. I need to take the heading data from the file and replace the wind direction with the "real" value. The weather station code is nice enough to allow me to create a "virtual" gauge based on other gauges and insert code via a cgi script. The limitation is that the code has to be a single line that can be executed in the linux shell and return data via stdout.

Body:
A simple solution using sed:

echo "20170607233000 wind0 180 1 2 3" | sed 'N;s/\n.*180//;' file -