问:
Makefile compiles all files even if file is not changed when .o files are placed in other floder
I am new to Makefile(Actually to programming). I had following makefile:-

```<code>$ cat Makefile
VER = Debug

main: main.o Time.o
    g++ Object\ Code/main.o Object\ Code/Time.o -o ../$(VER)/main

main.o: main.cpp
    g++ -c main.cpp -o Object\ Code/main.o

Time.o: Time.cpp Time_.h
    g++ -c Time.cpp -o Object\ Code/Time.o

clean:
    rm Object\ Code/*.o
    rm ../$(VER)/main
</code>```

makefile is in src folder

```<code>$ ls && pwd
main.cpp  Makefile  Object Code  Time.cpp  Time_.h
/home/Rahul/Devlopment/WorkSpace/Test C++/src
</code>```

Object code is a Directory in src.

```<code>$ ls ..
Debug  Release  src
</code>```

But whenver I change just one single file and try to use make it compiles all files:-

```<code>$ make
g++ -c main.cpp -o Object\ Code/main.o
g++ -c Time.cpp -o Object\ Code/Time.o
g++ Object\ Code/main.o Object\ Code/Time.o -o ../Debug/main
$ touch Time
Time.cpp     Time_.h
$ touch Time_.h
$ make
g++ -c main.cpp -o Object\ Code/main.o
g++ -c Time.cpp -o Object\ Code/Time.o
g++ Object\ Code/main.o Object\ Code/Time.o -o ../Debug/main
$ make
g++ -c main.cpp -o Object\ Code/main.o
g++ -c Time.cpp -o Object\ Code/Time.o
g++ Object\ Code/main.o Object\ Code/Time.o -o ../Debug/main
</code>```

As a complete noob I have no Idea. Please help me.

答:
When you build a target make requires your recipe to create the same file as the target: else you're lying to make.  A rule like this:

```<code>main.o: main.cpp
        <recipe>
</code>```

is interpreted by make to say, "if you want to build a file main.o and you have a file main.cpp and main.o is out of date, then you can run this recipe <recipe> to do that".  But, your recipe doesn't build main.o, it builds Object code/main.o.  So the next time make goes through, it wants to build main.o and it doesn't exist, so make tries to build it again... etc.

Item #1: it's not possible to use paths containing spaces in makefiles.

Item #2: you should always use automatic variables like $@ etc. to be sure your rules build the same thing that make expects.

Item #3: it's not useful to compile the source code into object files  in a hardcoded directory, then write the executable file to a variable directory (like $(Ver))

Your makefile should look something like this:

```<code>CXX = g++
SOURCES = main.cpp Time.cpp
VER = Debug

$(VER)/main: $(SOURCES:%.cpp=$(VER)/%.o)
        $(CXX) -o $@ $^

$(VER)/%.o : %.cpp
        $(CXX) -o $@ -c $<

clean:
        rm -rf $(VER)
</code>```

See The GNU make manual for details on all these things.

Body:
I am new to Makefile(Actually to programming). I had following makefile:-

$ cat Makefile
VER = Debug

main: main.o Time.o
    g++ Object\ Code/main.o Object\ Code/Time.o -o ../$(VER)/main

main.o: main.cpp
    g++ -c main.cpp -o Object\ Code/main.o

Time.o: Time.cpp Time_.h
    g++ -c Time.cpp -o Object\ Code/Time.o

clean:
    rm Object\ Code/*.o
    rm ../$(VER)/main

makefile is in src folder

$ ls && pwd
main.cpp  Makefile  Object Code  Time.cpp  Time_.h
/home/Rahul/Devlopment/WorkSpace/Test C++/src

Object code is a Directory in src.

$ ls ..
Debug  Release  src

But whenver I change just one single file and try to use make it compiles all files:-

$ make
g++ -c main.cpp -o Object\ Code/main.o
g++ -c Time.cpp -o Object\ Code/Time.o
g++ Object\ Code/main.o Object\ Code/Time.o -o ../Debug/main
$ touch Time
Time.cpp     Time_.h
$ touch Time_.h
$ make
g++ -c main.cpp -o Object\ Code/main.o
g++ -c Time.cpp -o Object\ Code/Time.o
g++ Object\ Code/main.o Object\ Code/Time.o -o ../Debug/main
$ make
g++ -c main.cpp -o Object\ Code/main.o
g++ -c Time.cpp -o Object\ Code/Time.o
g++ Object\ Code/main.o Object\ Code/Time.o -o ../Debug/main

As a complete noob I have no Idea. Please help me.

Body:
When you build a target make requires your recipe to create the same file as the target: else you're lying to make.  A rule like this:

main.o: main.cpp
        <recipe>

is interpreted by make to say, "if you want to build a file main.o and you have a file main.cpp and main.o is out of date, then you can run this recipe <recipe> to do that".  But, your recipe doesn't build main.o, it builds Object code/main.o.  So the next time make goes through, it wants to build main.o and it doesn't exist, so make tries to build it again... etc.

Item #1: it's not possible to use paths containing spaces in makefiles.

Item #2: you should always use automatic variables like $@ etc. to be sure your rules build the same thing that make expects.

Item #3: it's not useful to compile the source code into object files  in a hardcoded directory, then write the executable file to a variable directory (like $(Ver))

Your makefile should look something like this:

CXX = g++
SOURCES = main.cpp Time.cpp
VER = Debug

$(VER)/main: $(SOURCES:%.cpp=$(VER)/%.o)
        $(CXX) -o $@ $^

$(VER)/%.o : %.cpp
        $(CXX) -o $@ -c $<

clean:
        rm -rf $(VER)

See The GNU make manual for details on all these things.


来源: stackexchange

问:
Swift 4 - How to enable / disable keyboard by using buttons
My tricky problem is :

I've 2 buttons with 2 UITextView.
Like you know, when I push an UITextView, keyboard appear. Well, this is not what I want.

I want to enable / disable the display's keyboard according a specific @IBAction taped.

The scenario is the following:
- First button (Keyboard icon) allow the user to display the keyboard to type something in one of the UITextView, with a FirstResponder init on the top one.

Second button (REC icon) allow the user to speak and display in pre-selected TextView but without displaying keyboard.

I already known that there is :

isUserInteractionEnabled

and

textViewDidBeginEditing

But it doesn't really fit well and/or fix my issue.

Here a screen to be more explicit (don't give a mind about the third green validate button, it's just for the .POST feature) :

Thanks for any help!

答:
Something like this should work:</p>

```<code>class MyViewController: UIViewController, UITextViewDelegate {

    @IBOutlet var yourTextView: UITextView

        override func viewDidLoad() {
            super.viewDidLoad()

            yourTextView.delegate = self
        }

        @IBAction func showKeyboard(_ sender: UIButton) {
        self.yourTextView.becomeFirstResponder()

    }

      @IBAction func hideKeyboard(_ sender: UIButton) {
        self.yourTextView.resignFirstResponder()

    }

    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Something like this should work:

class MyViewController: UIViewController, UITextViewDelegate {

    @IBOutlet var yourTextView: UITextView

        override func viewDidLoad() {
            super.viewDidLoad()

            yourTextView.delegate = self
        }

        @IBAction func showKeyboard(_ sender: UIButton) {
        self.yourTextView.becomeFirstResponder()

    }

      @IBAction func hideKeyboard(_ sender: UIButton) {
        self.yourTextView.resignFirstResponder()

    }

    }


问:
Is there any way I could use Alternate for Lead() and Lag() Functions in SQL Server 2008?
I've table where I need to calculate difference between row to one underneath it and get the resultant to xml. it's daily task so i need it is kind of recursive task.

Structure for my current table is as below :

```<code>CREATE TABLE #Temp
(

    , CurrentDateTime        DateTime
    , ID                     INT
    , ThisYearToDateTotal    INT
    , ThisYearToDateCBT      INT
    , ThisYearToDateManual   INT
    , ThisYearToDateScanned  INT
    , InProcess              INT
    , InputRequired          INT
)`
</code>```

So far I've written the code as below :

```<code>SELECT
  Today_CurrentDateTime
, Today_Total
, Today_CBT
, Today_Manual
, Today_Scanned
, Today_InProcess
, Today_InputRequired
, Yesterday_Total
, Yesterday_CBT
, Yesterday_Manual
, Yesterday_Scanned
, Yesterday_InProcess
, Yesterday_InputRequired
, (TD.Today_Total         - YD.Yesterday_Total)          AS Diff_in_Total
, (TD.Today_CBT           - YD.Yesterday_CBT)            AS Diff_in_CBT
, (TD.Today_Manual        - YD.Yesterday_Manual)         AS Diff_in_Manual
, (TD.Today_Scanned       - YD.Yesterday_Scanned)        AS Diff_in_Scanned
, (TD.Today_InProcess     - YD.Yesterday_InProcess)      AS Diff_in_InProcess
, (TD.Today_InputRequired - YD.Yesterday_InputRequired)  AS Diff_in_InputRequired
 FROM #YesterdayData AS YD
INNER JOIN #TodayData AS TD ON TD.Today_ID = YD.Yesterday_ID
</code>```

and getting the output as below :

Now I've a restriction here that I can't create another permanent table and that's why I can't calculate difference for a each day for throughout a week.

Any Help ?

答:
It's quite easy to mimic LAG and LEAD using sub queries.

For the #Temp table you have in your question, to get ThisYearToDateTotal  value of the previous or next row (order by CurrentDateTime).

Here is a simple example:

```<code>SELECT ID,
       CurrentDateTime,
       ThisYearToDateTotal,
       (
           SELECT TOP 1 ThisYearToDateTotal
           FROM #Temp as tLag
           WHERE tLag.ID = tMain.Id -- partition by
           AND tLag.CurrentDateTime < tMain.CurrentDateTime
           ORDER BY CurrentDateTime DESC
       ) As Lag_ThisYearToDateTotal,
       (
           SELECT TOP 1 ThisYearToDateTotal
           FROM #Temp as tLead
           WHERE tLead.ID = tMain.Id -- partition by
           AND tLead.CurrentDateTime > tMain.CurrentDateTime
           ORDER BY CurrentDateTime
       ) As Lead_ThisYearToDateTotal
 FROM #Temp as tMain
</code>```

Body:
I've table where I need to calculate difference between row to one underneath it and get the resultant to xml. it's daily task so i need it is kind of recursive task.

Structure for my current table is as below :

CREATE TABLE #Temp
(

    , CurrentDateTime        DateTime
    , ID                     INT
    , ThisYearToDateTotal    INT
    , ThisYearToDateCBT      INT
    , ThisYearToDateManual   INT
    , ThisYearToDateScanned  INT
    , InProcess              INT
    , InputRequired          INT
)`

So far I've written the code as below :

SELECT
  Today_CurrentDateTime
, Today_Total
, Today_CBT
, Today_Manual
, Today_Scanned
, Today_InProcess
, Today_InputRequired
, Yesterday_Total
, Yesterday_CBT
, Yesterday_Manual
, Yesterday_Scanned
, Yesterday_InProcess
, Yesterday_InputRequired
, (TD.Today_Total         - YD.Yesterday_Total)          AS Diff_in_Total
, (TD.Today_CBT           - YD.Yesterday_CBT)            AS Diff_in_CBT
, (TD.Today_Manual        - YD.Yesterday_Manual)         AS Diff_in_Manual
, (TD.Today_Scanned       - YD.Yesterday_Scanned)        AS Diff_in_Scanned
, (TD.Today_InProcess     - YD.Yesterday_InProcess)      AS Diff_in_InProcess
, (TD.Today_InputRequired - YD.Yesterday_InputRequired)  AS Diff_in_InputRequired
 FROM #YesterdayData AS YD
INNER JOIN #TodayData AS TD ON TD.Today_ID = YD.Yesterday_ID

and getting the output as below :

Now I've a restriction here that I can't create another permanent table and that's why I can't calculate difference for a each day for throughout a week.

Any Help ?

Body:
It's quite easy to mimic LAG and LEAD using sub queries.

For the #Temp table you have in your question, to get ThisYearToDateTotal  value of the previous or next row (order by CurrentDateTime).

Here is a simple example:

SELECT ID,
       CurrentDateTime,
       ThisYearToDateTotal,
       (
           SELECT TOP 1 ThisYearToDateTotal
           FROM #Temp as tLag
           WHERE tLag.ID = tMain.Id -- partition by
           AND tLag.CurrentDateTime < tMain.CurrentDateTime
           ORDER BY CurrentDateTime DESC
       ) As Lag_ThisYearToDateTotal,
       (
           SELECT TOP 1 ThisYearToDateTotal
           FROM #Temp as tLead
           WHERE tLead.ID = tMain.Id -- partition by
           AND tLead.CurrentDateTime > tMain.CurrentDateTime
           ORDER BY CurrentDateTime
       ) As Lead_ThisYearToDateTotal
 FROM #Temp as tMain


问:
R does not build my project after several weeks with no changes
A bit frustrated right now. I have an R project that I built several weeks ago that I have not touched in those weeks. Come back to R Studio to do some debugging, and it will not rebuild the package. When I run the Check command from within the RStudio UI, the error I get is:

```<code>Error: Check failed: 'P:\MosaicPA\R Packages/Mosaic.VoronoiV2.Rcheck' doesn't exist
Execution halted

Exited with status 1.
</code>```

When I try the Install and Restart option, I get this error:

```<code>==> Rcmd.exe INSTALL --no-multiarch --with-keep.source Mosaic.VoronoiV2

Warning: invalid package 'Mosaic.VoronoiV2'
Error: ERROR: no packages specified

Exited with status 1.
</code>```

I have not seen these messages before, and cannot figure out what I am doing wrong, since nothing has changed.

I am not new to programming, but I am new-ish to the R environment. Cannot figure out what has changed, and I dont know what the .Rcheck file is, and I dont know why R doesnt create it. None of my other projects have a .Rcheck file or directory, and I dont know if this is supposed to be a file or directory. I have tried creating the project from scratch. Same issue.

Using R 3.4.1 and the latest R Studio version.

答: Well, Windows permissions strikes again...personally, I find Windows to be a HUGE POS because of stuff like this. Problem resolved after I reinstalled R under my domain account...I was suspicious of this, but couldn't find a way to confirm. Just reinstalled R and it worked. What I really wish is that when it IS a permissions problem, that Windows would report it as such, so the software can tell the end user this, vs sending us down some rabbit hole, chasing some non-existent problem, which happens too much as it is. Thanks, Redmond! But...I understand...after all, MS is too busy working on the next emoji standard...which is a priority, so who has time to make the OS better. End of rant.</p>

Body:
A bit frustrated right now. I have an R project that I built several weeks ago that I have not touched in those weeks. Come back to R Studio to do some debugging, and it will not rebuild the package. When I run the Check command from within the RStudio UI, the error I get is:

Error: Check failed: 'P:\MosaicPA\R Packages/Mosaic.VoronoiV2.Rcheck' doesn't exist
Execution halted

Exited with status 1.

When I try the Install and Restart option, I get this error:

==> Rcmd.exe INSTALL --no-multiarch --with-keep.source Mosaic.VoronoiV2

Warning: invalid package 'Mosaic.VoronoiV2'
Error: ERROR: no packages specified

Exited with status 1.

I have not seen these messages before, and cannot figure out what I am doing wrong, since nothing has changed.

I am not new to programming, but I am new-ish to the R environment. Cannot figure out what has changed, and I dont know what the .Rcheck file is, and I dont know why R doesnt create it. None of my other projects have a .Rcheck file or directory, and I dont know if this is supposed to be a file or directory. I have tried creating the project from scratch. Same issue.

Using R 3.4.1 and the latest R Studio version.


问:
SQL Query for equal and opposite values
Suppose I have a table with two columns id and val. I wan't to find all the distinct ids where there exist a pair of equal and opposite vals. For example suppose you have the following table

```<code>  id  | val
------+------
   1  |  3
   2  |  5
   2  | -5
   1  |  4
   2  |  6
   3  |  9
   2  | -6
   3  | -9
</code>```

I want the result to be

```<code>result
  2
  3
</code>```

2 in the result set because there are values 5, -5 and 6, -6. 3 is in the result set because of 9, -9.

I can do this by using where exists. Something like

```<code>select distinct tab1.id from tab tab1
where exists (
    select * from tab tab2
    where tab1.id = tab2.id
    and tab1.val = -tab2.val
);
</code>```

However I worry that a query like this has time complexity O(n^2) because it is computed like nested loops (?). However it is possible to compute this in O(n) time by scanning the table (and keeping track of previously seen results in a data structure with O(1) lookup time). What is the optimal way to write such a query?

答:
We should have an explain of your request and how you sets indexes.

May be it could be done like this too :

```<code>WITH pos AS (
  SELECT id, val FROM tab WHERE val > 0),
neg AS (
  SELECT id, val FROM tab WHERE val < 0)
SELECT DISTINCT id
  FROM pos JOIN neg USING (id)
 WHERE pos.val = neg.val;
</code>```

With right indexation, this could be quick. Depend also of the volume of data.

Title: SQL Query for equal and opposite values

Body:
Suppose I have a table with two columns id and val. I wan't to find all the distinct ids where there exist a pair of equal and opposite vals. For example suppose you have the following table

  id  | val
------+------
   1  |  3
   2  |  5
   2  | -5
   1  |  4
   2  |  6
   3  |  9
   2  | -6
   3  | -9

I want the result to be

result
  2
  3

2 in the result set because there are values 5, -5 and 6, -6. 3 is in the result set because of 9, -9.

I can do this by using where exists. Something like

select distinct tab1.id from tab tab1
where exists (
    select * from tab tab2
    where tab1.id = tab2.id
    and tab1.val = -tab2.val
);

However I worry that a query like this has time complexity O(n^2) because it is computed like nested loops (?). However it is possible to compute this in O(n) time by scanning the table (and keeping track of previously seen results in a data structure with O(1) lookup time). What is the optimal way to write such a query?

Body:
We should have an explain of your request and how you sets indexes.

May be it could be done like this too :

WITH pos AS (
  SELECT id, val FROM tab WHERE val > 0),
neg AS (
  SELECT id, val FROM tab WHERE val < 0)
SELECT DISTINCT id
  FROM pos JOIN neg USING (id)
 WHERE pos.val = neg.val;

With right indexation, this could be quick. Depend also of the volume of data.


问:
Event sourcing: non-business important events
This is a general architectural question on ES. The concern is generally about the need to keep a great amount of business non-important events, that affect intermediate state, though we definitely won't care about them (will just ignore them) at the end of the day.

Say we have a User, that has a list of items (i.e Tasks), and the user may quite often add/remove/edit different fields of a task. If we are building ES, we should treat each update as an individual event for example TaskNameChange, TaskCommentChange etc, or we may have one event TaskModified whatever. In our case tasks state changes are actually not important for us, is we don't get much from task change history, from the business standpoint we will ever care about only last ones (for example last TaskNameChange), but we should anyway track and record all the events.

Again my concern is that we should record and keep a great amount of business meaningless events in event store.

Has anyone met such situation and what are ideas about it?

答:
Has anyone met such situation and what are ideas about it?

Horses for courses

If the costs associated with keeping a complete event backed history of your document exceed the business value that you can accrue from that history, then don't design your system to keep all of the history.  Set up a document store, on each save overwrite the previous version of the document, and get on with it.

Greg Young: a whole system based on event sourcing is an anti pattern.


问:
what elements to use for a card inspired layout
I want to achieve the following layout. So in my mockup I used cards as they seemed to be the closest to what I want to create.
Now implementing the layout it seems that cards isn't actually what I should use for this.

What elements should be used instead?

```<code>    @foreach ($foos as $foo)
        <div class="card">
            <div class="card-header">
                {{ $foo->header }}
            </div>
            <div class="card-body">
                <h4 class="card-title">{{ $foo->title }}</h4>
                <p class="card-text">Some text.</p>
            </div>
        </div>
    @endforeach
</code>```

答:
You can do something like this using cards. We have a card with multiple cards inside. Then I've added classes like p-2, to make the padding smaller in the main card.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

Text

Header

Primary card title

Some quick example text to build on the card title and make up the bulk of the card's content.

Header

Primary card title

Some quick example text to build on the card title and make up the bulk of the card's content.

Header

Primary card title

Some quick example text to build on the card title and make up the bulk of the card's content.

```

Body:
I want to achieve the following layout. So in my mockup I used cards as they seemed to be the closest to what I want to create.
Now implementing the layout it seems that cards isn't actually what I should use for this.

What elements should be used instead?

    @foreach ($foos as $foo)

                {{ $foo->header }}

{{ $foo->title }}

Some text.

    @endforeach

Body:
You can do something like this using cards. We have a card with multiple cards inside. Then I've added classes like p-2, to make the padding smaller in the main card.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<div class="card border-primary">
  <div class="card-header bg-primary">Text</div>
  <div class="card-body p-2">
    <div class="card border-success mb-1">
      <div class="card-header bg-success">Header</div>
      <div class="card-body">
        <h4 class="card-title">Primary card title</h4>
        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
      </div>
    </div>
    <div class="card mb-1">
      <div class="card-header">Header</div>
      <div class="card-body">
        <h4 class="card-title">Primary card title</h4>
        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
      </div>
    </div>
    <div class="card">
      <div class="card-header">Header</div>
      <div class="card-body">
        <h4 class="card-title">Primary card title</h4>
        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
      </div>
    </div>
  </div>
</div>


问:
Able to access bucket in gcloud and Python API but not Java API
I'm working on a project that is includes a process to store files into Google Cloud Storage.

The initial prototype was in Python and works fine, however when porting the codebase over to Java I am unable to access the bucket.

The Java project is built with Gradle and development is through NetBeans. The ServiceAccount is a keyfile with restricted access, only allowing for read/write behavior from this particular bucket.

```<code>// The Java code, which should be enough to grab the bucket.
Storage storage = StorageOptions.getDefaultInstance().getService();
Bucket bucket = storage.get(BUCKET_NAME);

// For comparison, the Python setup.
storage_client = storage.Client()
self.bucket = storage_client.bucket(bucket_name)
</code>```

When manually running the project from Gradle the result is,

```<code>Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 403
Forbidden
{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "xxx@xxx.iam.gserviceaccount.com does not have storage.buckets.get access to xxx.",
    "reason" : "forbidden"
  } ],
  "message" : "xxx@xxx.iam.gserviceaccount.com does not have storage.buckets.get access to xxx."
}
</code>```

Slightly different when running from within NetBeans itself:

```<code>Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 401
Unauthorized
{
  "code" : 401,
  "errors" : [ {
    "domain" : "global",
    "location" : "Authorization",
    "locationType" : "header",
    "message" : "Anonymous users does not have storage.buckets.get access to a1s-submissions.",
    "reason" : "required"
  } ],
  "message" : "Anonymous users does not have storage.buckets.get access to a1s-submissions."
}
</code>```

All of these methods are returning the expected results
So I know at least the file is being read.

```<code>StorageOptions.getAppEngineAppId());
StorageOptions.getDefaultProjectId());
StorageOptions.CREDENTIAL_ENV_NAME);GOOGLE_APPLICATION_CREDENTIALS
StorageOptions.getDefaultInstance().getApplicationName());
StorageOptions.getDefaultInstance().getProjectId());
StorageOptions.getDefaultInstance().getCredentials()
    .getAuthenticationType());
StorageOptions.getLibraryName());
</code>```

So given that I can access the bucket via gcloud and python, I know the account has authorization, however I cannot seem to uncover the cause for this error.

答:
Oddly, the solution here was in fact to relax the permissions on the service account. I didn't have access to this at the time but was finally able to check this today.

For whatever reason still unknown to me, Python was able to carry out the same operations with the original service account authorization settings while Java required additional rights granted.

Body:
I'm working on a project that is includes a process to store files into Google Cloud Storage.

The initial prototype was in Python and works fine, however when porting the codebase over to Java I am unable to access the bucket.

The Java project is built with Gradle and development is through NetBeans. The ServiceAccount is a keyfile with restricted access, only allowing for read/write behavior from this particular bucket.

// The Java code, which should be enough to grab the bucket.
Storage storage = StorageOptions.getDefaultInstance().getService();
Bucket bucket = storage.get(BUCKET_NAME);

// For comparison, the Python setup.
storage_client = storage.Client()
self.bucket = storage_client.bucket(bucket_name)

When manually running the project from Gradle the result is,

Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 403
Forbidden
{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "xxx@xxx.iam.gserviceaccount.com does not have storage.buckets.get access to xxx.",
    "reason" : "forbidden"
  } ],
  "message" : "xxx@xxx.iam.gserviceaccount.com does not have storage.buckets.get access to xxx."
}

Slightly different when running from within NetBeans itself:

Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 401
Unauthorized
{
  "code" : 401,
  "errors" : [ {
    "domain" : "global",
    "location" : "Authorization",
    "locationType" : "header",
    "message" : "Anonymous users does not have storage.buckets.get access to a1s-submissions.",
    "reason" : "required"
  } ],
  "message" : "Anonymous users does not have storage.buckets.get access to a1s-submissions."
}

All of these methods are returning the expected results
So I know at least the file is being read.

StorageOptions.getAppEngineAppId());
StorageOptions.getDefaultProjectId());
StorageOptions.CREDENTIAL_ENV_NAME);GOOGLE_APPLICATION_CREDENTIALS
StorageOptions.getDefaultInstance().getApplicationName());
StorageOptions.getDefaultInstance().getProjectId());
StorageOptions.getDefaultInstance().getCredentials()
    .getAuthenticationType());
StorageOptions.getLibraryName());

So given that I can access the bucket via gcloud and python, I know the account has authorization, however I cannot seem to uncover the cause for this error.


问:
google.auth.exceptions.DefaultCredentialsError - not a valid json file
I'mt trying to use goole vision api but i can't run my python script without getting the following error:

```<code>google.auth.exceptions.DefaultCredentialsError: ('File /root/GoogleCloudStaff/apikey.json is not a valid json file.', ValueError('Invalid control character at: line 5 column 37 (char 172)',))
</code>```

My python script:

```<code>import io
from google.cloud import vision

vision_client = vision.Client()
#file_name = "/var/www/FlaskApp/FlaskApp/static/"#'375px-Guido_van_Rossum_OSCON_2006_cropped.png'

file_name = '1200px-Guido_van_Rossum_OSCON_2006.jpg'

#file_name = "/var/www/FlaskApp/FlaskApp/static/cyou_pic_folders/cyou_folder_2017_11_16_10_26_18/pi_pic_lc_2017_11_16_10_26_1800049.png"

with io.open(file_name, 'rb') as image_file:
    content = image_file.read()
    image = vision_client.image(
        content=content, )

labels = image.detect_labels()
for label in labels:
    print(label.description)
</code>```

Thanks very much!

答:
DefaultCredentialsError indicates that you failed acquiring default credentials.Have you done initial set up in a proper manner?
Take a look at vision</p>

Body:
I'mt trying to use goole vision api but i can't run my python script without getting the following error:

google.auth.exceptions.DefaultCredentialsError: ('File /root/GoogleCloudStaff/apikey.json is not a valid json file.', ValueError('Invalid control character at: line 5 column 37 (char 172)',))

My python script:

import io
from google.cloud import vision

vision_client = vision.Client()
#file_name = "/var/www/FlaskApp/FlaskApp/static/"#'375px-Guido_van_Rossum_OSCON_2006_cropped.png'

file_name = '1200px-Guido_van_Rossum_OSCON_2006.jpg'

#file_name = "/var/www/FlaskApp/FlaskApp/static/cyou_pic_folders/cyou_folder_2017_11_16_10_26_18/pi_pic_lc_2017_11_16_10_26_1800049.png"

with io.open(file_name, 'rb') as image_file:
    content = image_file.read()
    image = vision_client.image(
        content=content, )

labels = image.detect_labels()
for label in labels:
    print(label.description)

Thanks very much!


问:
Get WM_LBUTTONDOWN message while ShellExecAndWait?
In the Delphi IDE, create a VCL Forms Application. Then add a TApplicationEvents component and a TButton on the form. Then add these two event-handlers:

```<code>uses
  JclShell;

procedure TForm3.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean);
begin
  if Msg.Message = WM_LBUTTONDOWN then
  begin
    Self.Caption := 'WM_LBUTTONDOWN';
  end
  else if Msg.Message = WM_LBUTTONUP then
  begin
    Self.Caption := 'WM_LBUTTONUP';
  end
end;

procedure TForm3.Button1Click(Sender: TObject);
begin
  JclShell.ShellExecAndWait('C:\Windows\system32\notepad.exe');
  Self.Caption := 'Notepad closed';
end;
</code>```

Now click on the button. The following happens:

"WM_LBUTTONDOWN" appears on the form's title-bar.

"WM_LBUTTONUP" appears on the form's title-bar.

Notepad is executed.

Then click again on the button which starts another instance of Notepad BUT this time without writing anything on the form's title-bar.

Obviously, the program is stuck in JclShell.ShellExecAndWait which returns only when Notepad is closed. So when Notepad is closed any mouse-click again writes to the form's title-bar.

So we can see that while Notepad is running in JclShell.ShellExecAndWait everything in the program works normally: You could even make mathematical calculations while Notepad is running in JclShell.ShellExecAndWait. Only the ApplicationEvents1Message is not triggered while Notepad is running.

So how can I get a WM_LBUTTONDOWN message while Notepad is running in JclShell.ShellExecAndWait?

答:
While JclShell.ShellExecAndWait is waiting for the spawned process to exit it uses following basic message pump:

```<code>while WaitForSingleObject(Sei.hProcess, 10) = WAIT_TIMEOUT do
  repeat
    Msg.hwnd := 0;
    Res := PeekMessage(Msg, Sei.Wnd, 0, 0, PM_REMOVE);
    if Res then
    begin
      TranslateMessage(Msg);
      DispatchMessage(Msg);
    end;
  until not Res;
CloseHandle(Sei.hProcess);
</code>```

I say basic, because the looped part of the VCLs message pump looks like this:

```<code> if PeekMessage(Msg, 0, 0, 0, PM_NOREMOVE) then
  begin
    Unicode := (Msg.hwnd = 0) or IsWindowUnicode(Msg.hwnd);
    if Unicode then
      MsgExists := PeekMessageW(Msg, 0, 0, 0, PM_REMOVE)
    else
      MsgExists := PeekMessageA(Msg, 0, 0, 0, PM_REMOVE);

    if MsgExists then
    begin
      Result := True;
      if Msg.Message <> WM_QUIT then
      begin
        Handled := False;
        if Assigned(FOnMessage) then FOnMessage(Msg, Handled);
        if not IsPreProcessMessage(Msg) and not IsHintMsg(Msg) and
          not Handled and not IsMDIMsg(Msg) and
          not IsKeyMsg(Msg) and not IsDlgMsg(Msg) then
        begin
          TranslateMessage(Msg);
          if Unicode then
            DispatchMessageW(Msg)
          else
            DispatchMessageA(Msg);
        end;
      end
      else
      begin
  {$IF DEFINED(CLR)}
        if Assigned(FOnShutDown) then FOnShutDown(self);
        DoneApplication;
  {$IFEND}
        FTerminate := True;
      end;
    end;
</code>```

The code line

if Assigned(FOnMessage) then FOnMessage(Msg, Handled);

is what will hand the message to your TApplicationEvents.OnMessage via the TMultiCaster that TApplicationEvents has assigned to Application.OnMessage. This is not done in the JCL source.
Additional issues might be that JCL is not UniCode aware regarding messages at this point and there is no handling for WM_QUIT.

What to do about this is depending on what you want to achieve, too. Why do you want to receive this messages in the first place?

I mean it is possible to alter the JCL source - if you are willing to do so - and to add VCL.Forms to the uses, and then call the event handler if assigned like the VCL does:

```<code>while WaitForSingleObject(Sei.hProcess, 10) = WAIT_TIMEOUT do
  repeat
    Msg.hwnd := 0;
    Res := PeekMessage(Msg, Sei.Wnd, 0, 0, PM_REMOVE);
    if Res then
    begin
      Handled := False;
      if Assigned(Application.OnMessage) then
        Application.OnMessage(Msg, Handled);
      if not Handled then
      begin
        TranslateMessage(Msg);
        DispatchMessage(Msg);
      end;
    end;
  until not Res;
CloseHandle(Sei.hProcess);
</code>```

Or even call Application.ProcessMessages, to have the same message processing in place the VCL does:

```<code>while WaitForSingleObject(Sei.hProcess, 10) = WAIT_TIMEOUT do
  Application.ProcessMessages;
CloseHandle(Sei.hProcess);
</code>```

This is working, I could not see any side effects like commenters suggested. But before changing the JCL source in this way I would probably implement my own ShellExecAndWait. Depending on what you would like to achieve, the normal dispatching of messages should still work. So if your TFrom has e.g.

```<code>procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN;
</code>```

implemented, it should be called. This is, however, only the case if the message was directed at your form. If the button is clicked, the resulting messages will be directed to the button itself. You would need to implement your own descendant class then.

Maybe a completely different suggestion?

If your goal is to let certain controls not to be clicked while JclShell.ShellExecAndWait is waiting, and using message handling is your approach to make this possible, there might be other things you can try.

Why not disable them? This will also give the user a visible indication that clicking is a no-go.

```<code>  Button1.Enabled := False;
  try
    JclShell.ShellExecAndWait('C:\Windows\system32\notepad.exe');
    Self.Caption := 'Notepad closed';
  finally
    Button1.Enabled := True;
  end;
</code>```

If you are concerned about multiple controls create a TAction, assign it to every control you want to disable and disable all of them together with the Enabled property of the TAction.

Or, just hide your form while notepad.exe is opened?

```<code>  Hide;
  try
    JclShell.ShellExecAndWait('C:\Windows\system32\notepad.exe');
    Self.Caption := 'Notepad closed';
  finally
    Show;
  end;
</code>```

Or you could remove the event handlers:

```<code>var
  ATmpOnClick: TNotifyEvent;
begin
  ATmpOnClick := Button1.OnClick;
  Button1.OnClick := nil;
  try
    JclShell.ShellExecAndWait('C:\Windows\system32\notepad.exe');
    Self.Caption := 'Notepad closed';
  finally
    Button1.OnClick := ATmpOnClick;
  end;
end;
</code>```

Body:
In the Delphi IDE, create a VCL Forms Application. Then add a TApplicationEvents component and a TButton on the form. Then add these two event-handlers:

uses
  JclShell;

procedure TForm3.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean);
begin
  if Msg.Message = WM_LBUTTONDOWN then
  begin
    Self.Caption := 'WM_LBUTTONDOWN';
  end
  else if Msg.Message = WM_LBUTTONUP then
  begin
    Self.Caption := 'WM_LBUTTONUP';
  end
end;

procedure TForm3.Button1Click(Sender: TObject);
begin
  JclShell.ShellExecAndWait('C:\Windows\system32\notepad.exe');
  Self.Caption := 'Notepad closed';
end;

Now click on the button. The following happens:

"WM_LBUTTONDOWN" appears on the form's title-bar.

"WM_LBUTTONUP" appears on the form's title-bar.

Notepad is executed.

Then click again on the button which starts another instance of Notepad BUT this time without writing anything on the form's title-bar.

Obviously, the program is stuck in JclShell.ShellExecAndWait which returns only when Notepad is closed. So when Notepad is closed any mouse-click again writes to the form's title-bar.

So we can see that while Notepad is running in JclShell.ShellExecAndWait everything in the program works normally: You could even make mathematical calculations while Notepad is running in JclShell.ShellExecAndWait. Only the ApplicationEvents1Message is not triggered while Notepad is running.

So how can I get a WM_LBUTTONDOWN message while Notepad is running in JclShell.ShellExecAndWait?

Body:
While JclShell.ShellExecAndWait is waiting for the spawned process to exit it uses following basic message pump:

while WaitForSingleObject(Sei.hProcess, 10) = WAIT_TIMEOUT do
  repeat
    Msg.hwnd := 0;
    Res := PeekMessage(Msg, Sei.Wnd, 0, 0, PM_REMOVE);
    if Res then
    begin
      TranslateMessage(Msg);
      DispatchMessage(Msg);
    end;
  until not Res;
CloseHandle(Sei.hProcess);

I say basic, because the looped part of the VCLs message pump looks like this:

 if PeekMessage(Msg, 0, 0, 0, PM_NOREMOVE) then
  begin
    Unicode := (Msg.hwnd = 0) or IsWindowUnicode(Msg.hwnd);
    if Unicode then
      MsgExists := PeekMessageW(Msg, 0, 0, 0, PM_REMOVE)
    else
      MsgExists := PeekMessageA(Msg, 0, 0, 0, PM_REMOVE);

    if MsgExists then
    begin
      Result := True;
      if Msg.Message <> WM_QUIT then
      begin
        Handled := False;
        if Assigned(FOnMessage) then FOnMessage(Msg, Handled);
        if not IsPreProcessMessage(Msg) and not IsHintMsg(Msg) and
          not Handled and not IsMDIMsg(Msg) and
          not IsKeyMsg(Msg) and not IsDlgMsg(Msg) then
        begin
          TranslateMessage(Msg);
          if Unicode then
            DispatchMessageW(Msg)
          else
            DispatchMessageA(Msg);
        end;
      end
      else
      begin
  {$IF DEFINED(CLR)}
        if Assigned(FOnShutDown) then FOnShutDown(self);
        DoneApplication;
  {$IFEND}
        FTerminate := True;
      end;
    end;

The code line

if Assigned(FOnMessage) then FOnMessage(Msg, Handled);

is what will hand the message to your TApplicationEvents.OnMessage via the TMultiCaster that TApplicationEvents has assigned to Application.OnMessage. This is not done in the JCL source.
Additional issues might be that JCL is not UniCode aware regarding messages at this point and there is no handling for WM_QUIT.

What to do about this is depending on what you want to achieve, too. Why do you want to receive this messages in the first place?

I mean it is possible to alter the JCL source - if you are willing to do so - and to add VCL.Forms to the uses, and then call the event handler if assigned like the VCL does:

while WaitForSingleObject(Sei.hProcess, 10) = WAIT_TIMEOUT do
  repeat
    Msg.hwnd := 0;
    Res := PeekMessage(Msg, Sei.Wnd, 0, 0, PM_REMOVE);
    if Res then
    begin
      Handled := False;
      if Assigned(Application.OnMessage) then
        Application.OnMessage(Msg, Handled);
      if not Handled then
      begin
        TranslateMessage(Msg);
        DispatchMessage(Msg);
      end;
    end;
  until not Res;
CloseHandle(Sei.hProcess);

Or even call Application.ProcessMessages, to have the same message processing in place the VCL does:

while WaitForSingleObject(Sei.hProcess, 10) = WAIT_TIMEOUT do
  Application.ProcessMessages;
CloseHandle(Sei.hProcess);

This is working, I could not see any side effects like commenters suggested. But before changing the JCL source in this way I would probably implement my own ShellExecAndWait. Depending on what you would like to achieve, the normal dispatching of messages should still work. So if your TFrom has e.g.

procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN;

implemented, it should be called. This is, however, only the case if the message was directed at your form. If the button is clicked, the resulting messages will be directed to the button itself. You would need to implement your own descendant class then.

Maybe a completely different suggestion?

If your goal is to let certain controls not to be clicked while JclShell.ShellExecAndWait is waiting, and using message handling is your approach to make this possible, there might be other things you can try.

Why not disable them? This will also give the user a visible indication that clicking is a no-go.

  Button1.Enabled := False;
  try
    JclShell.ShellExecAndWait('C:\Windows\system32\notepad.exe');
    Self.Caption := 'Notepad closed';
  finally
    Button1.Enabled := True;
  end;

If you are concerned about multiple controls create a TAction, assign it to every control you want to disable and disable all of them together with the Enabled property of the TAction.

Or, just hide your form while notepad.exe is opened?

  Hide;
  try
    JclShell.ShellExecAndWait('C:\Windows\system32\notepad.exe');
    Self.Caption := 'Notepad closed';
  finally
    Show;
  end;

Or you could remove the event handlers:

var
  ATmpOnClick: TNotifyEvent;
begin
  ATmpOnClick := Button1.OnClick;
  Button1.OnClick := nil;
  try
    JclShell.ShellExecAndWait('C:\Windows\system32\notepad.exe');
    Self.Caption := 'Notepad closed';
  finally
    Button1.OnClick := ATmpOnClick;
  end;
end;


问:
How do I add a new state to the Mantis workflow?
Mantis bugtracker have 7 states:

```<code>  New
  Feedback
  Acknowledged
  Confirmed
  Assigned
  Resolved
  Closed
</code>```

I want to add a new state: Suggested. Where in the database do I add this new state?
Do I need to modify any PHP file?

Thanks.

答: This manual entry on status values might help</p>

ContentLicense: CC BY-SA 2.5

Body:
Mantis bugtracker have 7 states:

  New
  Feedback
  Acknowledged
  Confirmed
  Assigned
  Resolved
  Closed

I want to add a new state: Suggested. Where in the database do I add this new state?
Do I need to modify any PHP file?

Thanks.

ContentLicense: CC BY-SA 4.0


问:
if and else statement java
I am literally new at java and struggling with a part
so I am suppose to set an option to set new price in a car rental program </p>

```<code>public class CarToBuy extends CAR {
    private int price;
    private int registration_Year;
    private int milage;
    private boolean sold;

    public CarToBuy(String Description, int cost, int year, int miles) {
        super(Description);
        price = cost;
        registration_Year = year;
        milage = miles;
        sold = false;
    }

    public int getPrice() {
        return price;
    }

    public int getReg() {
        return registration_Year;
    }

    public int getMilage() {
        return milage;
    }

    public void setNewPrice(int newprice) {
        price = newprice;
        if (sold = false) {
            System.out.println("car not in stock");
        } else {
            System.out.println("The New price is" + newprice);
        }
    }

    public void carBuying(String Customer_name) {

        if (sold = false) {
            System.out.println("The Car is not in stock");
        } else {
            System.out.println("Thank you purchasing" + Customer_name);
        }
    }
}
</code>```

<p>even though the user get a display message "the car is not in stock" the price gets updates however what I am trying to do is that the price does not change if the car is not in stock
so if false = price does not changes
if true price changes </p>

答:
The operator = assigns a value to a variable whilst == is used as a conditional operator.

So;

```<code>if(sold){
System.out.println("Thank you purchasing" + Customer_name);
} else {
System.out.println("The Car is not in stock")
}
</code>```

This will execute the first block of code if sold is true and the other block otherwise.

Title: if and else statement java

Body:
I am literally new at java and struggling with a part
so I am suppose to set an option to set new price in a car rental program

public class CarToBuy extends CAR {
    private int price;
    private int registration_Year;
    private int milage;
    private boolean sold;

    public CarToBuy(String Description, int cost, int year, int miles) {
        super(Description);
        price = cost;
        registration_Year = year;
        milage = miles;
        sold = false;
    }

    public int getPrice() {
        return price;
    }

    public int getReg() {
        return registration_Year;
    }

    public int getMilage() {
        return milage;
    }

    public void setNewPrice(int newprice) {
        price = newprice;
        if (sold = false) {
            System.out.println("car not in stock");
        } else {
            System.out.println("The New price is" + newprice);
        }
    }

    public void carBuying(String Customer_name) {

        if (sold = false) {
            System.out.println("The Car is not in stock");
        } else {
            System.out.println("Thank you purchasing" + Customer_name);
        }
    }
}

even though the user get a display message "the car is not in stock" the price gets updates however what I am trying to do is that the price does not change if the car is not in stock
so if false = price does not changes
if true price changes

Body:
The operator = assigns a value to a variable whilst == is used as a conditional operator.

So;

if(sold){
System.out.println("Thank you purchasing" + Customer_name);
} else {
System.out.println("The Car is not in stock")
}

This will execute the first block of code if sold is true and the other block otherwise.


问:
How to connect to laravel forge database via SSH tunnel using HeidiSQL
I'm trying to do the above. HeidiSQL has a load of settings and I have a load of possible values, but I'm not sure exactly what goes where. Here are the different places I can put values

Settings screen

SSH screen

And the values I have are as follows:

The IP address of the database (v)

The port the database uses (w)

The database username and password (x)

My ssh private key (y)

The port I'm going to use on my computer (z)

I've tried many combinations, but generally get the response:

PLink exited unexpected. Command line was: C:\Program Files\PuTTY\plink.exe -ssh [ip address] -P [database port] -i [private key location] -N -L [my port]:[id address]:[database port]

Thank you for your time.

答:
I've now found the answer to this.

The information required was as follows and this is where it goes. Be really careful that you have actually put in all these values.

Settings:

Hostname (A2) - the name of this database It might be fine for this to be 127.0.0.1

User (A5) - Database username

Password (A6) - Database password

Port (A7) - The port the mySQL will be found at (e.g. 3306)

SSH:

SSH Host (B2) + Port (B3) - Your database IP and port number (ie 23.5.4.3 22)

Username (B4) - The username for your SSH login

Plink timeout (B6) - You may need to increase this (to perhaps 15)

Private key - Location of your private key file. Note that sometimes you might have a passphrase. If this is the case you'll probably have to use pageant which is downloaded with Putty

Local port - Which port you want your computer to use for SSH tunnel. eg 3306

These are some articles I found useful.

An article on similar topic

if you are stuck you could try and ssh in without heidi

Info about pageant


问:
Choice parameter or Choice Variable in Bamboo
Currently, I am planning to build an application with all the environments in different plans. But when I see Bamboo it has lot of plans and its kind of confusion. Is there a way to implement all the environments within one plan and before running the plan it should show a drop down  to which environment should run and that will be executed. I have seen this option in Jenkins, I hope there will be plugin added to the Bamboo in implementing this?</p>

答:
I'm not 100% sure what you are doing, but it sounds like you are trying to create a Plan that can deploy your application, and you have multiple environments you want to deploy to.

Bamboo gives you several ways to do this, but none of them are quite perfect in my opinion.  If I'm right about what you are doing, here are your options that I know of:

Create multiple Plans as you are doing.  You can eliminate some of the busy work by creating your first plan (say "Deploy to DEV") and cloning it rather than manually re-typing everything for TEST.

Create a single plan that is designed to use a variable for the environment, and run it manually as a customized build to provide a variable value that designates the environment name.

Create a Deployment Project and Environments instead of a Plan.  This ends up being similar to the first option, you do have to clone the tasks that do the deployment to each environment, but it brings some added advantages of Bamboo being explicitly aware of each environment, which release of your software is currently in each environment, and what the changes are that are inside that release.  Basically this treats environments and releases as first-class citizens in Bamboo that aren't things that exist or happen just behind the scenes of a regular build Plan.

It sounds like the middle option may be closest to what Jenkins allows.

The perfect solution in my mind would allow you to only have a single copy of the parts of tasks to do a deployment that are common to all environments, and a Deployment Project Environment just substitutes in those variables to that singe build execution that are specific to the Environment.


答:
You seem to be missing the authentication config. From Using the client library:

Using the client library

To run the client library, you must first set up authentication.

Title: google.auth.exceptions.DefaultCredentialsError - not a valid json file


问:
How to test the membership of multiple values in a list
I want to test if two or more values have membership on a list, but I'm getting an unexpected result:

```<code>>>> 'a','b' in ['b', 'a', 'foo', 'bar']
('a', True)
</code>```

So, Can Python test the membership of multiple values at once in a list?
What does that result mean?

See also: How to find list intersection?. Checking whether any of the specified values is in the list, is equivalent to checking if the intersection is non-empty. Checking whether all the values are in the list, is equivalent to checking if they are a subset.

答:
```<code>[x for x in ['a','b'] if x in ['b', 'a', 'foo', 'bar']]
</code>```

The reason I think this is better than the chosen answer is that you really don't need to call the 'all()' function. Empty list evaluates to False in IF statements, non-empty list evaluates to True.

```<code>if [x for x in ['a','b'] if x in ['b', 'a', 'foo', 'bar']]:
    ...Do something...
</code>```

Example:

```<code>>>> [x for x in ['a','b'] if x in ['b', 'a', 'foo', 'bar']]
['a', 'b']
>>> [x for x in ['G','F'] if x in ['b', 'a', 'foo', 'bar']]
[]
</code>```

Body:
I want to test if two or more values have membership on a list, but I'm getting an unexpected result:

>>> 'a','b' in ['b', 'a', 'foo', 'bar']
('a', True)

So, Can Python test the membership of multiple values at once in a list?
What does that result mean?

See also: How to find list intersection?. Checking whether any of the specified values is in the list, is equivalent to checking if the intersection is non-empty. Checking whether all the values are in the list, is equivalent to checking if they are a subset.

Body:
[x for x in ['a','b'] if x in ['b', 'a', 'foo', 'bar']]

The reason I think this is better than the chosen answer is that you really don't need to call the 'all()' function. Empty list evaluates to False in IF statements, non-empty list evaluates to True.

if [x for x in ['a','b'] if x in ['b', 'a', 'foo', 'bar']]:
    ...Do something...

Example:

>>> [x for x in ['a','b'] if x in ['b', 'a', 'foo', 'bar']]
['a', 'b']
>>> [x for x in ['G','F'] if x in ['b', 'a', 'foo', 'bar']]
[]


问:
Cannot read property '$pristine' of undefined when string used as input name
In my form I have an ng-repeat and within that ng-repeat I have a bunch of fields. Sometimes there could be 3 fields, sometimes there might just be one.

I have an angular for each to check $pristine for a specific field. The name of the field pretty much stays the same but the field count number changes so I thought I would check it like this:

```<code>var price = "price_" + product.line_no;

console.log($scope.myform.price.$pristine); = console.log($scope.myform."price_1".$pristine);
</code>```

But I am getting this:

```<code>TypeError: Cannot read property '$pristine' of undefined
</code>```

答:
Make sure that you have set unique name attribute in your input field.
Here is a fiddler that can help  https://jsfiddle.net/paka2/n6weLg55/ </p>

```<code><div ng-repeat="product in products">
<input name="price_{{$index}}" type="text" ng-model="productList['price_' + $index]" required/>
</div>
</code>```

Body:
In my form I have an ng-repeat and within that ng-repeat I have a bunch of fields. Sometimes there could be 3 fields, sometimes there might just be one.

I have an angular for each to check $pristine for a specific field. The name of the field pretty much stays the same but the field count number changes so I thought I would check it like this:

var price = "price_" + product.line_no;

console.log($scope.myform.price.$pristine); = console.log($scope.myform."price_1".$pristine);

But I am getting this:

TypeError: Cannot read property '$pristine' of undefined

Body:
Make sure that you have set unique name attribute in your input field.
Here is a fiddler that can help  https://jsfiddle.net/paka2/n6weLg55/

<div ng-repeat="product in products">
<input name="price_{{$index}}" type="text" ng-model="productList['price_' + $index]" required/>
</div>


问:
Saving dataframe as XML in spark sql
```<code>val final_df = sqlContext.sql("select _xmlns, `md:Date`, `md:Creator`, struct(_ngr, _region, SetofValues) as Station from (select _xmlns, `md:Date`, `md:Creator`, _ngr, _region, struct(_dataType, _period, Value) as SetofValues  from (select _xmlns, `md:Date`, `md:Creator`, _ngr, _region, _dataType, _period, struct(_VALUE, _time) as Value from df_h a left outer join df_ds b on a.batchId = b.batchId left outer join df_dsv c on b.batchId = c.batchId left outer join df_nv d on c.batchId = d.batchId))"
final_df.repartition(1).write.format("xml").option("rowTag","NewTag").save(output_path)
</code>```

Schema for above line is as below

```<code>root
 |-- _xmlns: string (nullable = true)
 |-- md:Date: string (nullable = true)
 |-- md:Creator: string (nullable = true)
 |-- Station: struct (nullable = false)
 |    |-- _ngr: string (nullable = true)
 |    |-- _region: string (nullable = true)
 |    |-- SetofValues: struct (nullable = false)
 |    |    |-- _dataType: string (nullable = true)
 |    |    |-- _period: string (nullable = true)
 |    |    |-- Value: struct (nullable = false)
 |    |    |    |-- _VALUE: double (nullable = true)
 |    |    |    |-- _time: string (nullable = true)
</code>```

when I am trying to save dataframe as XML using above command getting XML file as below.

```<code><ROWS>
<NewTag xmlns="testing">
    <md:Date>2016-10-30</md:Date>
    <md:Creator>USER_1</md:Creator>
    <Station ngr="123456" region="North East">
        <SetofValues dataType="Total" period="15 min">
            <Value 3.509" time="05:30:00"></Value>
        </SetofValues>
    </Station>
</NewTag>
<NewTag xmlns="testing">
    <md:Date>2016-10-30</md:Date>
    <md:Creator>USER_1</md:Creator>
    <Station ngr="123456" region="North East">
        <SetofValues dataType="Total" period="15 min">
            <Value 2.6" time="05:45:00"></Value>
        </SetofValues>
    </Station>
</NewTag>
<NewTag xmlns="testing">
    <md:Date>2016-10-30</md:Date>
    <md:Creator>USER_1</md:Creator>
    <Station ngr="123456" region="North East">
        <SetofValues dataType="Total" period="15 min">
            <Value 1.111" time="06:00:00"></Value>
        </SetofValues>
    </Station>
</NewTag>
</ROWS>
</code>```

How to achieve below output. By creating array fro rows..

```<code><NewTag xmlns="testing">
<md:Date>2016-10-30</md:Date>
<md:Creator>USER_1</md:Creator>
<Station ngr="123456" region="North East">
    <SetofValues dataType="Total" period="15 min">
        <Value time="05:30:00">3.509</Value>
        <Value time="05:45:00">2.6</Value>
        <Value time="06:00:00">1.111</Value>
    </SetofValues>
</Station>
</NewTag>
</code>```

I am not able to convert different rows into list of array to achieve array in xml

答:
Late to the party but just in case anyone wonders your schema contains one Value for each Set of Values for each Station for each Root, something like...

```<code>Root  Station  Set  Value
Root  Station  Set  Value
Root  Station  Set  Value
Root  Station  Set  Value
</code>```

If you want to have that output you need to reduce by key and make the "Value" an array.

So after the reduction by the three keys your dataframe would look like...

```<code>Root  Station  Set  [Value, Value, Value, ...]
</code>```

Title: Saving dataframe as XML in spark sql

Body:
val final_df = sqlContext.sql("select _xmlns, `md:Date`, `md:Creator`, struct(_ngr, _region, SetofValues) as Station from (select _xmlns, `md:Date`, `md:Creator`, _ngr, _region, struct(_dataType, _period, Value) as SetofValues  from (select _xmlns, `md:Date`, `md:Creator`, _ngr, _region, _dataType, _period, struct(_VALUE, _time) as Value from df_h a left outer join df_ds b on a.batchId = b.batchId left outer join df_dsv c on b.batchId = c.batchId left outer join df_nv d on c.batchId = d.batchId))"
final_df.repartition(1).write.format("xml").option("rowTag","NewTag").save(output_path)

Schema for above line is as below

root
 |-- _xmlns: string (nullable = true)
 |-- md:Date: string (nullable = true)
 |-- md:Creator: string (nullable = true)
 |-- Station: struct (nullable = false)
 |    |-- _ngr: string (nullable = true)
 |    |-- _region: string (nullable = true)
 |    |-- SetofValues: struct (nullable = false)
 |    |    |-- _dataType: string (nullable = true)
 |    |    |-- _period: string (nullable = true)
 |    |    |-- Value: struct (nullable = false)
 |    |    |    |-- _VALUE: double (nullable = true)
 |    |    |    |-- _time: string (nullable = true)

when I am trying to save dataframe as XML using above command getting XML file as below.

<ROWS>
<NewTag xmlns="testing">
    <md:Date>2016-10-30</md:Date>
    <md:Creator>USER_1</md:Creator>
    <Station ngr="123456" region="North East">
        <SetofValues dataType="Total" period="15 min">
            <Value 3.509" time="05:30:00"></Value>
        </SetofValues>
    </Station>
</NewTag>
<NewTag xmlns="testing">
    <md:Date>2016-10-30</md:Date>
    <md:Creator>USER_1</md:Creator>
    <Station ngr="123456" region="North East">
        <SetofValues dataType="Total" period="15 min">
            <Value 2.6" time="05:45:00"></Value>
        </SetofValues>
    </Station>
</NewTag>
<NewTag xmlns="testing">
    <md:Date>2016-10-30</md:Date>
    <md:Creator>USER_1</md:Creator>
    <Station ngr="123456" region="North East">
        <SetofValues dataType="Total" period="15 min">
            <Value 1.111" time="06:00:00"></Value>
        </SetofValues>
    </Station>
</NewTag>
</ROWS>

How to achieve below output. By creating array fro rows..

<NewTag xmlns="testing">
<md:Date>2016-10-30</md:Date>
<md:Creator>USER_1</md:Creator>
<Station ngr="123456" region="North East">
    <SetofValues dataType="Total" period="15 min">
        <Value time="05:30:00">3.509</Value>
        <Value time="05:45:00">2.6</Value>
        <Value time="06:00:00">1.111</Value>
    </SetofValues>
</Station>
</NewTag>

I am not able to convert different rows into list of array to achieve array in xml

Body:
Late to the party but just in case anyone wonders your schema contains one Value for each Set of Values for each Station for each Root, something like...

Root  Station  Set  Value
Root  Station  Set  Value
Root  Station  Set  Value
Root  Station  Set  Value

If you want to have that output you need to reduce by key and make the "Value" an array.

So after the reduction by the three keys your dataframe would look like...

Root  Station  Set  [Value, Value, Value, ...]


问:
How to add reference to assembly in visual studio mac?
I am sorry. I am newbie in C#. I use Visual Studio Mac. I want to try to connect mysql database.
I have added mysql package. When I run, I get error. The error is :

adding a reference to assembly ‘System.Data, Version-4.0.0.0, Culture=neutral, PublicKeyToken

答: My solution in Visual Studio for Mac 7.3 Preview was to right click on the "Dependencies" node for the project and click "Edit References..."</p>


问:
How can I pop this letter if it exists based on this algorithm?
I'm trying to pop any letters given by the user, for example if they give you a keyword "ROSES" then these letters should be popped out of the list.

Note: I have a lot more explanation after the SOURCE CODE

SOURCE CODE

```<code>  alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
        encrypted_message = []
        key_word = str(input("Please enter a word:"))
        key_word = list(key_word)
        #print(key_word)

        check_for_dup = 0

        for letter in key_word:
            for character in alphabet:
                if letter in character:
                    check_for_dup +=1
                    alphabet.pop(check_for_dup)

        print(alphabet)
        print(encrypted_message)
</code>```

SAMPLE INPUT

Let's say keyword is "Roses"

this what it gives me a list of the following ['A', 'C', 'E', 'G', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

But that's wrong It should of just removed the characters that existed in the keyword given by the user, like the word "Roses" each letter should of been removed and not in the list being popped. as you can see in the list the letters "B","D","F","H",etc were gone. What I'm trying to do is pop the index of the alphabet letters that the keyword exists.

this is what should of happened.

["A","B","C","D","F","G","H","I","J","K","L","M","N","P","Q","T","U","V","W","X","Y","Z"]

The letters of the keyword "ROSES" were deleted of the list

答:
you can directly check with input key

iterate all the letters in data, and check whether or not the letter in the input_key, if yes discard it

```<code>  data = ['A', 'C', 'E', 'G', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  input_key = 'Roses'
  output = [l for l in data if l not in input_key.upper()]
  print output

  ['A', 'C', 'G', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
</code>```

Body:
I'm trying to pop any letters given by the user, for example if they give you a keyword "ROSES" then these letters should be popped out of the list.

Note: I have a lot more explanation after the SOURCE CODE

SOURCE CODE

  alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
        encrypted_message = []
        key_word = str(input("Please enter a word:"))
        key_word = list(key_word)
        #print(key_word)

        check_for_dup = 0

        for letter in key_word:
            for character in alphabet:
                if letter in character:
                    check_for_dup +=1
                    alphabet.pop(check_for_dup)

        print(alphabet)
        print(encrypted_message)

SAMPLE INPUT

Let's say keyword is "Roses"

this what it gives me a list of the following ['A', 'C', 'E', 'G', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

But that's wrong It should of just removed the characters that existed in the keyword given by the user, like the word "Roses" each letter should of been removed and not in the list being popped. as you can see in the list the letters "B","D","F","H",etc were gone. What I'm trying to do is pop the index of the alphabet letters that the keyword exists.

this is what should of happened.

["A","B","C","D","F","G","H","I","J","K","L","M","N","P","Q","T","U","V","W","X","Y","Z"]

The letters of the keyword "ROSES" were deleted of the list

Body:
you can directly check with input key

iterate all the letters in data, and check whether or not the letter in the input_key, if yes discard it

  data = ['A', 'C', 'E', 'G', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  input_key = 'Roses'
  output = [l for l in data if l not in input_key.upper()]
  print output

  ['A', 'C', 'G', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']


问:
Android Studio: Simple BaseAdapter Setup Fail
I would like to create a simple populated GridView using BaseAdapter but I keep getting empty list - application runs but there are no Views displayed.
Below are all files are use for this task:

Main:

```<code>String[] items = {"Some", "items", "to", "display"};

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

    GridView grid = (GridView)findViewById(R.id.grid);
    final TextView text = (TextView)findViewById(R.id.text);

    MyAdapter adapter = new MyAdapter(getApplicationContext(), items);

    grid.setAdapter(adapter);
</code>```

MyAdapter:

LayoutInflater inflater;

```<code>Context context;
String[] myData;

public MyAdapter(Context context, String[] myData) {
    this.context = context;
    this.myData = myData;
}

@Override
public int getCount() {
    return 0;
}

@Override
public Object getItem(int position) {
    return myData[position];
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.grid, parent, false);
    TextView text = (TextView) convertView.findViewById(R.id.textView);
    text.setText(myData[position]);
    return convertView;
}
</code>```

activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.android.random.MainActivity">

    <GridView
        android:id="@+id/grid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:verticalSpacing="40dip"
        android:horizontalSpacing="5dip"
        android:numColumns="auto_fit"
        android:columnWidth="100dip"
        android:stretchMode="columnWidth"
        android:gravity="center"
        />

</android.support.constraint.ConstraintLayout>
</code>```

grid.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        />
</LinearLayout>
</code>```

I have checked in various sources countles times and I did not manage to find an error in my code. It would be amazing if someone would take a look at it and find a reason for empty activity as the reason is probably obvious.

答:
Your getCount method always return 0. Return the number of elements in your myData array instead.</p>

```<code>@Override
public int getCount() {
    return myData.length;
}
</code>```

Body:
I would like to create a simple populated GridView using BaseAdapter but I keep getting empty list - application runs but there are no Views displayed.
Below are all files are use for this task:

Main:

String[] items = {"Some", "items", "to", "display"};

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

    GridView grid = (GridView)findViewById(R.id.grid);
    final TextView text = (TextView)findViewById(R.id.text);

    MyAdapter adapter = new MyAdapter(getApplicationContext(), items);

    grid.setAdapter(adapter);

MyAdapter:

LayoutInflater inflater;

Context context;
String[] myData;

public MyAdapter(Context context, String[] myData) {
    this.context = context;
    this.myData = myData;
}

@Override
public int getCount() {
    return 0;
}

@Override
public Object getItem(int position) {
    return myData[position];
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.grid, parent, false);
    TextView text = (TextView) convertView.findViewById(R.id.textView);
    text.setText(myData[position]);
    return convertView;
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.android.random.MainActivity">

    <GridView
        android:id="@+id/grid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:verticalSpacing="40dip"
        android:horizontalSpacing="5dip"
        android:numColumns="auto_fit"
        android:columnWidth="100dip"
        android:stretchMode="columnWidth"
        android:gravity="center"
        />

</android.support.constraint.ConstraintLayout>

grid.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        />
</LinearLayout>

I have checked in various sources countles times and I did not manage to find an error in my code. It would be amazing if someone would take a look at it and find a reason for empty activity as the reason is probably obvious.

Body:
Your getCount method always return 0. Return the number of elements in your myData array instead.

@Override
public int getCount() {
    return myData.length;
}