问:
Pivotcache create runtime error mismatch
I have been trying to create a PivotTable using VBA, but it keeps giving me Pan error message in the PivotCache section.

I have three worksheets on a workbook and I intend to use the table in worksheet 1 to create a pivot table and chart on worksheet 3.  But I keep getting an error message.

Here is my vba code:

```<code>    Dim ws As Worksheet
    Dim pc As PivotCaches
    Dim pt As PivotTable
    Dim Rng As Range
    Dim wb As Workbook

    Set ws = Worksheets("Sheet3")
    Set Rng = Worksheets("Sheet3").Range("A58")

    Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Table1", Version:=xlPivotTableVersion14)

    Set pt = pc.CreatePivotTable(TableDestination _
        :=Range("A58"), TableName:="PivotTable5", DefaultVersion:= _
        xlPivotTableVersion14)

    ActiveWorkbook.ShowPivotTableFieldList = True

End Sub
</code>```

Pivot-Table Data screen-shot

答:
Try the code below, explanation inside the code comments:</p>

```<code>Option Explicit

Sub PivotTablefromTable()

Dim wb          As Workbook
Dim ws          As Worksheet
Dim PTbl        As PivotTable
Dim PCache      As PivotCache
Dim WorkTbl     As ListObject
Dim PTblRng     As Range
Dim Rng         As Range

Set ws = Worksheets("Sheet3")
Set Rng = ws.Range("A58")

Set WorkTbl = Worksheets("work").ListObjects("Table1") ' <-- set a variable to the "Table1" in sheet "work"
Set PTblRng = WorkTbl.Range '<-- get the range from "Table1"

' set the Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PTblRng)

' Set the Pivot Table (already created in previous macro run)
On Error Resume Next
Set PTbl = ws.PivotTables("PivotTable5")

On Error GoTo 0
If PTbl Is Nothing Then ' <-- pivot table still doesn't exist >> need to create it
    ' create a new Pivot Table in ws sheet, start from Cell A58
    Set PTbl = ws.PivotTables.Add(PivotCache:=PCache, TableDestination:=Rng, TableName:="PivotTable5")

    ' rest of your code here

Else ' just refresh the Pivot table, with updated Pivot Cache
    PTbl.ChangePivotCache PCache
    PTbl.RefreshTable
End If

ActiveWorkbook.ShowPivotTableFieldList = True

End Sub
</code>```

Body:
I have been trying to create a PivotTable using VBA, but it keeps giving me Pan error message in the PivotCache section.

I have three worksheets on a workbook and I intend to use the table in worksheet 1 to create a pivot table and chart on worksheet 3.  But I keep getting an error message.

Here is my vba code:

    Dim ws As Worksheet
    Dim pc As PivotCaches
    Dim pt As PivotTable
    Dim Rng As Range
    Dim wb As Workbook

    Set ws = Worksheets("Sheet3")
    Set Rng = Worksheets("Sheet3").Range("A58")

    Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Table1", Version:=xlPivotTableVersion14)

    Set pt = pc.CreatePivotTable(TableDestination _
        :=Range("A58"), TableName:="PivotTable5", DefaultVersion:= _
        xlPivotTableVersion14)

    ActiveWorkbook.ShowPivotTableFieldList = True

End Sub

Pivot-Table Data screen-shot

Body:
Try the code below, explanation inside the code comments:

Option Explicit

Sub PivotTablefromTable()

Dim wb          As Workbook
Dim ws          As Worksheet
Dim PTbl        As PivotTable
Dim PCache      As PivotCache
Dim WorkTbl     As ListObject
Dim PTblRng     As Range
Dim Rng         As Range

Set ws = Worksheets("Sheet3")
Set Rng = ws.Range("A58")

Set WorkTbl = Worksheets("work").ListObjects("Table1") ' <-- set a variable to the "Table1" in sheet "work"
Set PTblRng = WorkTbl.Range '<-- get the range from "Table1"

' set the Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PTblRng)

' Set the Pivot Table (already created in previous macro run)
On Error Resume Next
Set PTbl = ws.PivotTables("PivotTable5")

On Error GoTo 0
If PTbl Is Nothing Then ' <-- pivot table still doesn't exist >> need to create it
    ' create a new Pivot Table in ws sheet, start from Cell A58
    Set PTbl = ws.PivotTables.Add(PivotCache:=PCache, TableDestination:=Rng, TableName:="PivotTable5")

    ' rest of your code here

Else ' just refresh the Pivot table, with updated Pivot Cache
    PTbl.ChangePivotCache PCache
    PTbl.RefreshTable
End If

ActiveWorkbook.ShowPivotTableFieldList = True

End Sub


来源: stackexchange

问:
how to open excel on foreground in VBA using powerpoint
i am trying to open an excel file in a powerpoint presentation.
this is my code:

```<code>Sub diversestickersKoole()

Dim xlApp As Object
Dim xlWorkBook As Object

Set xlApp = CreateObject("Excel.Application")

xlApp.Visible = True
Set xlWorkBook = xlApp.Workbooks.Open("V:\Oliedocs\Koole\Stickers Scheepstanks Koole.xltm", True, False)

Set xlApp = Nothing
Set xlWorkBook = Nothing
End Sub
</code>```

the excel file is opening in the background. this must be in the foreground.

can someone help me?

答:
You can use AppActivate.

The code below uses "test.xlsx - Excel as this is the caption of my test workbook.

Stickers Scheepstanks Koole.xltm - Excel should work for you

```<code>Sub diversestickersKoole()

Dim xlApp As Object
Dim xlWorkBook As Object

Set xlApp = CreateObject("Excel.Application")

xlApp.Visible = True
'Set xlWorkBook = xlApp.Workbooks.Open("V:\Oliedocs\Koole\Stickers Scheepstanks Koole.xltm", True, False)
Set xlWorkBook = xlApp.Workbooks.Open("C:\temp\test.xlsx", True, False)
AppActivate "test.xlsx - Excel"

Set xlApp = Nothing

Set xlWorkBook = Nothing

End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i am trying to open an excel file in a powerpoint presentation.
this is my code:

Sub diversestickersKoole()

Dim xlApp As Object
Dim xlWorkBook As Object

Set xlApp = CreateObject("Excel.Application")

xlApp.Visible = True
Set xlWorkBook = xlApp.Workbooks.Open("V:\Oliedocs\Koole\Stickers Scheepstanks Koole.xltm", True, False)

Set xlApp = Nothing
Set xlWorkBook = Nothing
End Sub

the excel file is opening in the background. this must be in the foreground.

can someone help me?

Body:
You can use AppActivate.

The code below uses "test.xlsx - Excel as this is the caption of my test workbook.

Stickers Scheepstanks Koole.xltm - Excel should work for you

Sub diversestickersKoole()

Dim xlApp As Object
Dim xlWorkBook As Object

Set xlApp = CreateObject("Excel.Application")

xlApp.Visible = True
'Set xlWorkBook = xlApp.Workbooks.Open("V:\Oliedocs\Koole\Stickers Scheepstanks Koole.xltm", True, False)
Set xlWorkBook = xlApp.Workbooks.Open("C:\temp\test.xlsx", True, False)
AppActivate "test.xlsx - Excel"

Set xlApp = Nothing

Set xlWorkBook = Nothing

End Sub


问:
How to open a link in chrome from cmd (Windows) without bringing chrome window to foreground?
For example if I click on a link in vscode editor it does not interfere with what I am currently doing - opens it without making chrome window active.

I want to achieve the same from command line from windows using one of: cmd, msys bash, powershell.

There is a similar question answered but without foreground requirement.

答:
You can just Create one text file with .bat extension in windows OS.
Then you can write path where your Chrome is present and then you can write Chrome.exe and then give the link as argument which you want to open.

For Example,
cd C:\Program Files (x86)\Google\Chrome\Application

chrome.exe www.yahoo.com

I hope it will help you.


问:
php 'header' redirect fail due to strange output
Very sorry to have to do this.
I have the following constants DEFINEd in 1 file (constants.php):

```<code>define('ROOTDIR', '/var/www/OrgName');
define('INCLUDESDIR', ROOTDIR.'/ssincludes');
define('CLASSESDIR', ROOTDIR.'/ssincludes/classes');
define('WEBSERVERIP', 'my.very.special.ip');
define('ROOTDIREXT', '/OrgName/html');
define('ROOTSITE', 'http://'.WEBSERVERIP.ROOTDIREXT);
</code>```

then in a php file that simply verifies a user account doesn't already exist, and if not validates the incoming POST data and creates a new user MySQL record for a new user (whichever appropriate), I have this code (stripped non-relevant, I think):

```<code>require('../../ssincludes/constants.php');
require(INCLUDESDIR.'/utilities.php');
require_once(CLASSESDIR.'/clsScout.php');
require_once(CLASSESDIR.'/manager/ClassManager.php');
require_once(CLASSESDIR.'/manager/ClassCode.php');

//Then start - continue the session so PHP knows how to reconstruct the session object
session_start();
SessionCheck();    //A function in utilities.php that just refreshes some $_SESSION[] vars

//Handle the current state of the Authenticator flag
if(!isset($_SESSION['Authenticated'])) {
        $_SESSION['Authenticated']=false;
} else {
    if($_SESSION['Authenticated']==true) {
        $_SESSION['Message'] = "You are already logged in and do not require a new account.";
        header("Location: ".ROOTSITE."/index.php");
    }
}

MakeUser();
header("Location: ".ROOTSITE."/index.php");
exit;

function MakeUser() {
    //Does various things, I have verified no output
    return;
}
</code>```

The header statement is failing from the perspective of the Chrome browser. Inspecting the result from HTML side, I see this:

```<code><html>
    #shadow-root (open)
    <shadow>
        ->head reveal
        ->body reveal
    </shadow>
    <style>
    </style>
    <head>
    </head>
    <body>
    </body>
</html>
</code>```

Searches for the text HTML HEAD BODY SHADOW (etc) in the php program file and in all of the included files yields no results.  Clearly (to me anyway), something is injecting the output, maybe PHP via an error, but php.ini is set to display errors (dev site) and it certainly does so for other pages.

Has anybody seen this output? I guess I'm looking for abstract ideas, maybe even Chrome "assuming" something and it's not real output.  The php in question is called via a direct (FORM method='PST' action='thispage.php') submission, so there is no JS lingering either.

Any help or ideas would be appreciated.

--UPDATE--

I never resolved this issue, fortunately for me the server blew up. I'm on a new server and re-launching the code on it. Same issue with new server but this time I was a bit more ready for it. Since this post is getting stale, I thought I would share, maybe somebody has a 'concept' I could pursue.

From a REQUIRE PHP class, browser wasn't getting anything back (except for 200), so I used tattle-tales in the class (class generates HEAD code and farms out some top of body code):

```<code>echo "Seem to not be having any problem here so far<br />";
$this->content = $this->MakeBigFatString();
echo "And we're back, wanna see?<br />";
var_dump($this->content);
return $this->content;
</code>```

I get:

```<code>Seem to not be having any problem here so far
And we're back, wanna see?
string(960) " "
</code>```

I think I'll be looking for "locale" mal-functions or the like.

-- SOLVED --

In a function in an included toolbox:

```<code>(string)$query = "SELECT ContactType FROM contacttype ORDER BY ContactType";
(object)$result = $db->query($query);
if(!$result || $db->errno || $result->num_rows==0) {
    $content .= "</select>\n";
    unset($query);
    echo "This line prints if below exit is used<br />";
    //exit;
    @$result->free();
    //this line is never reached if @result->free() is allowed to execute
    //no 200, no exceptions, no nothing, just blank stares
    //PHP error displays, error logging, html errors -- all turned on
    //just nothing
    $db->close();
    return $content;
}
</code>```

Mildly disturbing.

答:
Change this line

header("Location: ".ROOTSITE."/index.php");

To this

echo ';

Body:
Very sorry to have to do this.
I have the following constants DEFINEd in 1 file (constants.php):

define('ROOTDIR', '/var/www/OrgName');
define('INCLUDESDIR', ROOTDIR.'/ssincludes');
define('CLASSESDIR', ROOTDIR.'/ssincludes/classes');
define('WEBSERVERIP', 'my.very.special.ip');
define('ROOTDIREXT', '/OrgName/html');
define('ROOTSITE', 'http://'.WEBSERVERIP.ROOTDIREXT);

then in a php file that simply verifies a user account doesn't already exist, and if not validates the incoming POST data and creates a new user MySQL record for a new user (whichever appropriate), I have this code (stripped non-relevant, I think):

require('../../ssincludes/constants.php');
require(INCLUDESDIR.'/utilities.php');
require_once(CLASSESDIR.'/clsScout.php');
require_once(CLASSESDIR.'/manager/ClassManager.php');
require_once(CLASSESDIR.'/manager/ClassCode.php');

//Then start - continue the session so PHP knows how to reconstruct the session object
session_start();
SessionCheck();    //A function in utilities.php that just refreshes some $_SESSION[] vars

//Handle the current state of the Authenticator flag
if(!isset($_SESSION['Authenticated'])) {
        $_SESSION['Authenticated']=false;
} else {
    if($_SESSION['Authenticated']==true) {
        $_SESSION['Message'] = "You are already logged in and do not require a new account.";
        header("Location: ".ROOTSITE."/index.php");
    }
}

MakeUser();
header("Location: ".ROOTSITE."/index.php");
exit;

function MakeUser() {
    //Does various things, I have verified no output
    return;
}

The header statement is failing from the perspective of the Chrome browser. Inspecting the result from HTML side, I see this:

    #shadow-root (open)
    <shadow>
        ->head reveal
        ->body reveal
    </shadow>

Searches for the text HTML HEAD BODY SHADOW (etc) in the php program file and in all of the included files yields no results.  Clearly (to me anyway), something is injecting the output, maybe PHP via an error, but php.ini is set to display errors (dev site) and it certainly does so for other pages.

Has anybody seen this output? I guess I'm looking for abstract ideas, maybe even Chrome "assuming" something and it's not real output.  The php in question is called via a direct (FORM method='PST' action='thispage.php') submission, so there is no JS lingering either.

Any help or ideas would be appreciated.

--UPDATE--

I never resolved this issue, fortunately for me the server blew up. I'm on a new server and re-launching the code on it. Same issue with new server but this time I was a bit more ready for it. Since this post is getting stale, I thought I would share, maybe somebody has a 'concept' I could pursue.

From a REQUIRE PHP class, browser wasn't getting anything back (except for 200), so I used tattle-tales in the class (class generates HEAD code and farms out some top of body code):

echo "Seem to not be having any problem here so far
";
$this->content = $this->MakeBigFatString();
echo "And we're back, wanna see?
";
var_dump($this->content);
return $this->content;

I get:

Seem to not be having any problem here so far
And we're back, wanna see?
string(960) " "

I think I'll be looking for "locale" mal-functions or the like.

-- SOLVED --

In a function in an included toolbox:

(string)$query = "SELECT ContactType FROM contacttype ORDER BY ContactType";
(object)$result = $db->query($query);
if(!$result || $db->errno || $result->num_rows==0) {
    $content .= "</select>\n";
    unset($query);
    echo "This line prints if below exit is used
";
    //exit;
    @$result->free();
    //this line is never reached if @result->free() is allowed to execute
    //no 200, no exceptions, no nothing, just blank stares
    //PHP error displays, error logging, html errors -- all turned on
    //just nothing
    $db->close();
    return $content;
}

Mildly disturbing.

Body:
Change this line

header("Location: ".ROOTSITE."/index.php");

To this

echo <script> window.location = "'.ROOTSITE.'/index.php"'.'</script>';


问:
How to delay input
First i got a menu asking what i want to do, the problem is even if i select exit i still have to input the variables from the addEntry function. How do i make it so that only when i call the addEntry function i need to input those variables?</p>

```<code>date=raw_input('date')
amount=raw_input('amount')
desc=raw_input('desc')
account=raw_input('account')
def addEntry(date, amount, desc, account):
        transact=open("transactions.txt", "w")
        print >>transact, date, amount, desc, account
        transact.close()
</code>```

答:
If I understand you correctly, you just want to move the calls to raw_input into addEntry, instead of making them arguments; then they only execute and prompt the user for input when addEntry is called:

```<code>def addEntry():
    date=raw_input('date')
    amount=raw_input('amount')
    desc=raw_input('desc')
    account=raw_input('account')
    transact=open("transactions.txt", "w")
    print >>transact, date, amount, desc, account
    transact.close()
</code>```

You can also change whatever code is calling addEntry so it does the prompts right before the call, instead of doing them at the beginning of your application. For example:

```<code>if userClickedAddEntryButton: # <-- I made this up
    date=raw_input('date')
    amount=raw_input('amount')
    desc=raw_input('desc')
    account=raw_input('account')
    addEntry(date, amount, desc, account)
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to delay input

Body:
First i got a menu asking what i want to do, the problem is even if i select exit i still have to input the variables from the addEntry function. How do i make it so that only when i call the addEntry function i need to input those variables?

date=raw_input('date')
amount=raw_input('amount')
desc=raw_input('desc')
account=raw_input('account')
def addEntry(date, amount, desc, account):
        transact=open("transactions.txt", "w")
        print >>transact, date, amount, desc, account
        transact.close()

Body:
If I understand you correctly, you just want to move the calls to raw_input into addEntry, instead of making them arguments; then they only execute and prompt the user for input when addEntry is called:

def addEntry():
    date=raw_input('date')
    amount=raw_input('amount')
    desc=raw_input('desc')
    account=raw_input('account')
    transact=open("transactions.txt", "w")
    print >>transact, date, amount, desc, account
    transact.close()

You can also change whatever code is calling addEntry so it does the prompts right before the call, instead of doing them at the beginning of your application. For example:

if userClickedAddEntryButton: # <-- I made this up
    date=raw_input('date')
    amount=raw_input('amount')
    desc=raw_input('desc')
    account=raw_input('account')
    addEntry(date, amount, desc, account)


问:
Adding a single character to add keys in Counter
If the type of a Counter object's keys is str, i.e.:

I could do this:

```<code>>>> vocab_counter = Counter("the lazy fox jumps over the brown dog".split())

>>> vocab_counter  = Counter({k+u"\uE000":v for k,v in vocab_counter.items()})
>>> vocab_counter
Counter({'brown\ue000': 1,
         'dog\ue000': 1,
         'fox\ue000': 1,
         'jumps\ue000': 1,
         'lazy\ue000': 1,
         'over\ue000': 1,
         'the\ue000': 2})
</code>```

What would be a quick and/or pythonic way to add a character to all keys?

Is the above method the only way to achieve the final counter with the character appended to all keys? Are there other way(s) to achieve the same goal?

答:
You could do it with string manipulations:</p>

```<code>text = 'the lazy fox jumps over the brown dog'
Counter((text + ' ').replace(' ', '_abc ').strip().split())
</code>```

Body:
If the type of a Counter object's keys is str, i.e.:

I could do this:

>>> vocab_counter = Counter("the lazy fox jumps over the brown dog".split())

>>> vocab_counter  = Counter({k+u"\uE000":v for k,v in vocab_counter.items()})
>>> vocab_counter
Counter({'brown\ue000': 1,
         'dog\ue000': 1,
         'fox\ue000': 1,
         'jumps\ue000': 1,
         'lazy\ue000': 1,
         'over\ue000': 1,
         'the\ue000': 2})

What would be a quick and/or pythonic way to add a character to all keys?

Is the above method the only way to achieve the final counter with the character appended to all keys? Are there other way(s) to achieve the same goal?

Body:
You could do it with string manipulations:

text = 'the lazy fox jumps over the brown dog'
Counter((text + ' ').replace(' ', '_abc ').strip().split())


问:
Adjust width of progress bars dynamically
I am developing a system which have a list of elements, where each of them have a different progress bar.

I would like to include this "Admin dashboard statistics", but the problem is that the values of the 'width' are hardcoded for each component.

How could i pass a specific 'width' which is calculated in the logic of my application?

I am using thymeleaf and spring.

Here is the part of my html:

```<code><div class="progress-bar progress-bar-success"
role="progressbar" aria-valuenow="${proposal.votesInfoRangoEdad.adultgPerNo}"
 aria-valuemin="0" aria-valuemax="100" style="width: 30%"
th:text="${proposal.votesInfoRangoEdad.adultgPerNo}"></div>
</code>```

I need to replace 30% by the value of proposal.votesInfoRangoEdad.adultgPerNo.

答:
We found out a solution doing this:</p>

```<code>th:style="'width:'+ ${proposal.votesInfoGenero.malePerNo}+'%;'"
</code>```

Body:
I am developing a system which have a list of elements, where each of them have a different progress bar.

I would like to include this "Admin dashboard statistics", but the problem is that the values of the 'width' are hardcoded for each component.

How could i pass a specific 'width' which is calculated in the logic of my application?

I am using thymeleaf and spring.

Here is the part of my html:

I need to replace 30% by the value of proposal.votesInfoRangoEdad.adultgPerNo.

Body:
We found out a solution doing this:

th:style="'width:'+ ${proposal.votesInfoGenero.malePerNo}+'%;'"


问:
Pymodm connect to an mlab MongoDB
I have a MongoDB database hosted on mlab and I would like to use PyMODM as my object modeling library.

This is my code so far:

```<code>from pymodm import connect, MongoModel, fields

connect = connect('mongodb://user:pass@ds119788.mlab.com/db')

class Test(MongoModel):
    user = fields.CharField()

if __name__ == "__main__":
    test = Test("test")
    test.save()
</code>```

But it gives me this error :

pymongo.errors.ServerSelectionTimeoutError: ds119788.mlab.com:27017: [Errno 61] Connection refused

Am I missing something?

答:
You need to use the MongoDB URI provided by mlab for your account. The URI should contain the port number to connect to.

For example, it should look like :

```<code>connect = connect('mongodb://user:password@ds119788.mlab.com:63123/databaseName')
</code>```

Title: Pymodm connect to an mlab MongoDB

Body:
I have a MongoDB database hosted on mlab and I would like to use PyMODM as my object modeling library.

This is my code so far:

from pymodm import connect, MongoModel, fields

connect = connect('mongodb://user:pass@ds119788.mlab.com/db')

class Test(MongoModel):
    user = fields.CharField()

if __name__ == "__main__":
    test = Test("test")
    test.save()

But it gives me this error :

pymongo.errors.ServerSelectionTimeoutError: ds119788.mlab.com:27017: [Errno 61] Connection refused

Am I missing something?

Body:
You need to use the MongoDB URI provided by mlab for your account. The URI should contain the port number to connect to.

For example, it should look like :

connect = connect('mongodb://user:password@ds119788.mlab.com:63123/databaseName')


问:
Logout link with Spring and Thymeleaf
According with the official example (Secure Web Content), I have to use a form and a button with the aim to perform a logout with Spring Security.
Is there a way to use a link with Thymeleaf instead of a button?</p>

答:
With respect to the context of this question I think vdenotaris wants a link not a submit button for the log out functionality. well I think what you can do is create a hyperlink like this : </p>

```<code><a href="#" th:href="@{/logout}">Log Out</a>
</code>```

<p>and now create a controller with below mapping : </p>

```<code>@RequestMapping(value="/logout", method = RequestMethod.GET)
public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null){
        new SecurityContextLogoutHandler().logout(request, response, auth);
    }
    return "redirect:/login?logout";
}
</code>```

Title: Logout link with Spring and Thymeleaf

Body:
With respect to the context of this question I think vdenotaris wants a link not a submit button for the log out functionality. well I think what you can do is create a hyperlink like this :

<a href="#" th:href="@{/logout}">Log Out</a>

and now create a controller with below mapping :

@RequestMapping(value="/logout", method = RequestMethod.GET)
public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null){
        new SecurityContextLogoutHandler().logout(request, response, auth);
    }
    return "redirect:/login?logout";
}


问:
Build failed with error Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc
I am using Xcode 8.2.1. I am also using CoreData in my project.
When I try to generate a build or when I archive I am seeing the following error. Files mentioned in the error also changes at times.

ERROR:

```<code><unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/BuildingRoofMapping+CoreDataClass.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/BuildingRoofMapping+CoreDataProperties.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/Region+CoreDataClass.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/Region+CoreDataProperties.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/StateRegionMapping+CoreDataProperties.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/WalkingDoors+CoreDataClass.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/WalkingDoors+CoreDataProperties.swift'
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
</code>```

Here is how my CoreData Entities are configured:

Things I have Tried:

Check the location to see if files are actually missing, Files where present exactly at the same path.

I cleaned the build folder and removed derived data and build it again. Nothing helped.

Tried all the answers in this link. Nothing Worked.

Accepted Answer of this question doesn't seem to work either.

I am not sure why this error is coming. Any help is appreciated

EDIT

If I completely remove CoreData from my code then it Archives Successfully.

EDIT 2 :

When I change CodeGen to Manual/None and add files manually as suggested by @Anil . It builds successfully, But when I try to fetch the CoreData entity using :

```<code>let context = appDelegate.persistentContainer.viewContext
let buildingRoofMapping = BuildingRoofMapping(context:context)
</code>```

It gives me run time error.
Error :

```<code>'NSInvalidArgumentException', reason: 'An NSManagedObject of class 'BuildingRoofMapping' must have a valid NSEntityDescription.'
</code>```

EDIT 3:
   Sample Code link. Run it in simulator. It crashes in fetchBasicPrice() of ViewController.swift file

答: First, If you are checking or running the code in simulator and on changes in coreData code you are getting crashed, then you need to delete the app from the simulator and then again install and run. By doing this, changes that are made in your code do not make crash or show error. </p>

Body:
I am using Xcode 8.2.1. I am also using CoreData in my project.
When I try to generate a build or when I archive I am seeing the following error. Files mentioned in the error also changes at times.

ERROR:

<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/BuildingRoofMapping+CoreDataClass.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/BuildingRoofMapping+CoreDataProperties.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/Region+CoreDataClass.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/Region+CoreDataProperties.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/StateRegionMapping+CoreDataProperties.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/WalkingDoors+CoreDataClass.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/WalkingDoors+CoreDataProperties.swift'
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1

Here is how my CoreData Entities are configured:

Things I have Tried:

Check the location to see if files are actually missing, Files where present exactly at the same path.

I cleaned the build folder and removed derived data and build it again. Nothing helped.

Tried all the answers in this link. Nothing Worked.

Accepted Answer of this question doesn't seem to work either.

I am not sure why this error is coming. Any help is appreciated

EDIT

If I completely remove CoreData from my code then it Archives Successfully.

EDIT 2 :

When I change CodeGen to Manual/None and add files manually as suggested by @Anil . It builds successfully, But when I try to fetch the CoreData entity using :

let context = appDelegate.persistentContainer.viewContext
let buildingRoofMapping = BuildingRoofMapping(context:context)

It gives me run time error.
Error :

'NSInvalidArgumentException', reason: 'An NSManagedObject of class 'BuildingRoofMapping' must have a valid NSEntityDescription.'

EDIT 3:
   Sample Code link. Run it in simulator. It crashes in fetchBasicPrice() of ViewController.swift file


问:
yql link list to html
I'm using yql to return a list of links from specific webpages. So far so good, it returns all the links that I pretend, however I don't know how to translate that info into my webpage.

Here's what I'm trying to do:

YQL returns a list of links in the
results

I want those links to appear in my
webpage, inside a table, inside divs,
etc... like if i wrote them there.

I have been trying to find a way to do this but I don't know much of js and json so I'm here trying to achieve some answer from those of you that might know a way.

答:
There are a couple of ways to do this, depending on which approach you want to take.

First, and simplest, is server-side generation.  This is what would result, for example, if a user hits a Submit button on a search form to send you his query, your script receives the query and generates the page, then sends that page to the user.  In this case, your question is largely trivial.  In pseudocode:

```<code>ASSIGN the list of results to list L
FOR EACH ITEM r IN L
    PRINT a string containing an HTML template, substituting the value
          r where appropriate
</code>```

It's trivial enough that I suspect you want to do this via DOM manipulation.  This is what requires JavaScript: you get the query, send the request without refreshing the page, and want to add the results to the DOM.  If you're receiving the list of results, you're already most of the way there.  Using jQuery, you would do the same thing as in the pseudocode above, except that where it has the PRINT statement you would have:

```<code>$(".SearchResults").append("<li>" + r + "</li>");
</code>```

I highly recommend reading through the jQuery tutorial. It's not as hard as you think.

Title: yql link list to html

Body:
There are a couple of ways to do this, depending on which approach you want to take.

First, and simplest, is server-side generation.  This is what would result, for example, if a user hits a Submit button on a search form to send you his query, your script receives the query and generates the page, then sends that page to the user.  In this case, your question is largely trivial.  In pseudocode:

ASSIGN the list of results to list L
FOR EACH ITEM r IN L
    PRINT a string containing an HTML template, substituting the value
          r where appropriate

It's trivial enough that I suspect you want to do this via DOM manipulation.  This is what requires JavaScript: you get the query, send the request without refreshing the page, and want to add the results to the DOM.  If you're receiving the list of results, you're already most of the way there.  Using jQuery, you would do the same thing as in the pseudocode above, except that where it has the PRINT statement you would have:

$(".SearchResults").append("<li>" + r + "</li>");

I highly recommend reading through the jQuery tutorial. It's not as hard as you think.


问:
How to scroll to last element of li in JavaScript?
This is my code. I need help to scroll to the last element of the list in JavaScript.</p>

```<code><ul class="messages" id="chatBox">
  <!-- ngRepeat: message in message -->
  <li ng-repeat="message in message" class="server">
    <div>
      <p class="usrname ng-binding"></p>
      <p class="dataMessage ng-binding">you have connected to angularjs</p>
    </div>
  </li>
  <!-- end ngRepeat: message in message -->
  <li ng-repeat="message in message" class="mymsg">
    <div>
      <p class="usrname ng-binding">ketan</p>
      <p class="dataMessage ng-binding">xcxz</p>
    </div>
  </li>
  <!-- end ngRepeat: message in message -->
  <li ng-repeat="message in message" class="mymsg">
    <div>
      <p class="usrname ng-binding">ketan</p>
      <p class="dataMessage ng-binding">czxc</p>
    </div>
  </li>
  <!-- end ngRepeat: message in message -->
  <li ng-repeat="message in message" class="mymsg">
    <div>
      <p class="usrname ng-binding">ketan</p>
      <p class="dataMessage ng-binding">czxc</p>
    </div>
  </li>
  <!-- end ngRepeat: message in message -->
  <li ng-repeat="message in message" class="mymsg">
    <div>
      <p class="usrname ng-binding">ketan</p>
      <p class="dataMessage ng-binding">cxz</p>
    </div>
  </li>
  <!-- end ngRepeat: message in message -->
  <li ng-repeat="message in message" class="mymsg">
    <div>
      <p class="usrname ng-binding">ketan</p>
      <p class="dataMessage ng-binding">cxzczx</p>
    </div>
  </li>
  <!-- end ngRepeat: message in message -->
</ul>
</code>```

答:
Try using scrollIntoView() method to scroll to last element or any element you want. </p>

<p>$(selector).scrollIntoView();</p>

Body:
This is my code. I need help to scroll to the last element of the list in JavaScript.

you have connected to angularjs

ketan

xcxz

ketan

czxc

ketan

czxc

ketan

cxz

ketan

cxzczx

Body:
Try using scrollIntoView() method to scroll to last element or any element you want.

$(selector).scrollIntoView();


问:
Database ERD, potential loop issues?
Currently working on a CMS for a nature heritage site, just wanted to get some feedback on the database ERD for a particular section that deals with photos.

I have a table called Species which has records of different plant species. Linked to this is populations which basically track the areas a species can be found, then sightings basically records every time someone physically goes out and looks at that population to make notes of health, changes etc.

Linked to all that is media, which will basically be a table containing hashed links to photos stored on the cloud. The photos need to have information on what species has been photographed, but we also want to know when and where that photograph was taken, hence the need to link it back to the sighting event. Here's the subsection of the ERD highlighting the loop.

I just want to know, is this loop going to potentially cause issues? I know I could potentially remove the link from Media to Species and have that reference linked via sightings only, however I want to make this conductive to machine learning later on (basically to analyse a new photo  against the photo repository to identify what species has been photographed). I'm assuming that it would be expensive in terms of processing time if it had to go through 2 other tables to get the entire list of photos for a particular species to then analyse for example.

Is that a valid assumption?

答:
You don't have any loops / cyclic dependencies. What you have is two paths by which Species can be determined from Media. A direct functional dependency:

```<code>mediaID -> speciesID
</code>```

As well as a transitive functional dependency:

```<code>mediaID -> sightID -> popID -> speciesID
</code>```

The risk here is inconsistency. A bug in your program (or an incorrect manual entry) may end up recording different species for a given media via the two paths. Ideally, we would like to record each fact only once and have the DBMS ensure the validity of our data.

Your assumption isn't necessarily correct. Database management systems have numerous mechanisms to speed up joins, like indexes. Exactly how efficient or inefficient a join query would be depends on many factors, like the specific DBMS, the volume of records you expect in your various tables, the indexes you create, and the particular query you use to retrieve the data.

I suggest you remove the redundant attribute for now. It's easy enough to reintroduce it later and populate it via a suitable query, if you see that the join query can't be optimized sufficiently. If you keep (or reintroduce) the redundant attribute, it's possible to enforce consistency using things like triggers or foreign key constraints. Alternatively, a nightly script to update the redundant attribute could help to prevent inconsistencies.

Title: Database ERD, potential loop issues?

Body:
You don't have any loops / cyclic dependencies. What you have is two paths by which Species can be determined from Media. A direct functional dependency:

mediaID -> speciesID

As well as a transitive functional dependency:

mediaID -> sightID -> popID -> speciesID

The risk here is inconsistency. A bug in your program (or an incorrect manual entry) may end up recording different species for a given media via the two paths. Ideally, we would like to record each fact only once and have the DBMS ensure the validity of our data.

Your assumption isn't necessarily correct. Database management systems have numerous mechanisms to speed up joins, like indexes. Exactly how efficient or inefficient a join query would be depends on many factors, like the specific DBMS, the volume of records you expect in your various tables, the indexes you create, and the particular query you use to retrieve the data.

I suggest you remove the redundant attribute for now. It's easy enough to reintroduce it later and populate it via a suitable query, if you see that the join query can't be optimized sufficiently. If you keep (or reintroduce) the redundant attribute, it's possible to enforce consistency using things like triggers or foreign key constraints. Alternatively, a nightly script to update the redundant attribute could help to prevent inconsistencies.


问:
Can't generate allure report from jenkinsfile
I'm trying to generate allure report in jenkins. Allure reports are generated fine when doing it from freestyle project and setting up allure in post build actions - report can be opened from jenkins build page. However when trying to do same in pipeline getting

```<code>java.io.IOException: Can't find allure commandline <null>
</code>```

Tried to use command from Jenkins snippet generator:

```<code>allure([includeProperties: false, jdk: '', properties: [], reportBuildPolicy: 'ALWAYS', results: [[path: 'allure-results']]])
</code>```

could someone advise?

答: Do you use Allure plug-in for Jenkins? If not here is a guide that might help you how to automate testing using selenium, webdriver, jenkins and Allure</p>

Body:
I'm trying to generate allure report in jenkins. Allure reports are generated fine when doing it from freestyle project and setting up allure in post build actions - report can be opened from jenkins build page. However when trying to do same in pipeline getting

java.io.IOException: Can't find allure commandline <null>

Tried to use command from Jenkins snippet generator:

allure([includeProperties: false, jdk: '', properties: [], reportBuildPolicy: 'ALWAYS', results: [[path: 'allure-results']]])

could someone advise?


问:
Drupal 7 cron runs indefinitely
I can't setup drupal's cron to run, because it runs indefinitely. It is strange, before it worked well. Moreover, I installed cron_debug, and with this module it runs in 19 sec and report success for all modules, but if I do 'drush cron' or 'run cron' button in web interface - it never stops.

I have latest drupal 7 updated with bunch of modules, running on nginx and php7-fpm.

I don't understand why cron_debug runs ok, but usual cron is freezing.
I followed most advises from here https://www.drupal.org/docs/7/setting-up-cron/troubleshooting-cron  but they did not helped.

答: I have installed elysia-cron, and it showed, that stuck was with bounce module. I have reinstalled this module and all went fine. I'll keep using this module, because it is awesome. </p>

Title: Drupal 7 cron runs indefinitely


问:
Add pending item to RealmResults with RealmRecyclerViewAdapter
I'm managing my UI list with RealmRecyclerViewAdapter. I'd like to add a "pending" item to the collection that will display immediately while simultaneously posting the new item to the server. In case of failure, I will remove it from the display. Similar to a chat feature; I display the chat when they hit send, and if for some reason the post fails I can remove it and alert the user.

The problem is that with a regular RecyclerView adapter, I can just add one item to the end of the collection without an id, and remove it as needed. But since RealmRecyclerViewAdapter uses managed RealmResults, I can't add a new item without an id.

Can someone suggest a way to handle the situation I'm describing with RealmRecyclerViewAdapter?

答:
Without knowing what your data model looks like. It is hard to give concrete advice, but it sounds like all your have ID's, so something like this should work:

1) It must be possible to generate ID's offline. The standard solution for that is GUIDs: https://en.wikipedia.org/wiki/Universally_unique_identifier
2) Have a boolean on your model class: "syncedWithServer" or something similar. Then you can render all items not yet synced as "pending".

```<code>public class ChatEntry extends RealmObject {
  @PrimaryKey
  private String id = UUID.randomUUID().toString();
  private String entry;
  private boolean syncedWithServer;
}
</code>```

Body:
Without knowing what your data model looks like. It is hard to give concrete advice, but it sounds like all your have ID's, so something like this should work:

1) It must be possible to generate ID's offline. The standard solution for that is GUIDs: https://en.wikipedia.org/wiki/Universally_unique_identifier
2) Have a boolean on your model class: "syncedWithServer" or something similar. Then you can render all items not yet synced as "pending".

public class ChatEntry extends RealmObject {
  @PrimaryKey
  private String id = UUID.randomUUID().toString();
  private String entry;
  private boolean syncedWithServer;
}


问:
MYSQL: select where
let's say I have the following Table:

```<code> ID, Name  ,insurance , per_diem, net_salary, rr, rent, other_allowances
 1, John     1000          0          2000     0    0         0
 2, Jim      1000          0          2000     0    0         0
 3, Steve    500           0          3000     0    0         0
 4, Tom      0             0          0        0    0         0
</code>```

I run the following query

```<code>SELECT Sum((((((applicant.insurance + applicant.per_diem) +
                applicant.net_salary) + applicant.rr) + applicant.rent) +
                applicant.other_allowances)) As available_fund
WHERE applicant.id = id;
From applicant
</code>```

I want to get something like sum for every person

Is it possible?

答:
you must use from first then use where

```<code>     SELECT Sum(applicant.insurance + applicant.per_diem +
              applicant.net_salary + applicant.rr + applicant.rent +
              applicant.other_allowances) As available_fund
     From applicant
     group by  applicant.id
</code>```

it will give all employees sum but if you want to get some particulate employee then put where condition

```<code> WHERE applicant.id = id
</code>```

Title: MYSQL: select where

Body:
let's say I have the following Table:

 ID, Name  ,insurance , per_diem, net_salary, rr, rent, other_allowances
 1, John     1000          0          2000     0    0         0
 2, Jim      1000          0          2000     0    0         0
 3, Steve    500           0          3000     0    0         0
 4, Tom      0             0          0        0    0         0

I run the following query

SELECT Sum((((((applicant.insurance + applicant.per_diem) +
                applicant.net_salary) + applicant.rr) + applicant.rent) +
                applicant.other_allowances)) As available_fund
WHERE applicant.id = id;
From applicant

I want to get something like sum for every person

Is it possible?

Body:
you must use from first then use where

     SELECT Sum(applicant.insurance + applicant.per_diem +
              applicant.net_salary + applicant.rr + applicant.rent +
              applicant.other_allowances) As available_fund
     From applicant
     group by  applicant.id

it will give all employees sum but if you want to get some particulate employee then put where condition

 WHERE applicant.id = id


问:
IntellijIDEA - PluginClassLoader : ClassNotFoundException after moving class to another package
I'm developing a plugin for AndroidStudio .
Assume my package name is com.name.app

I have a class ApiHelper which has a ResponseHandler interface. Another class, ButtonActionHandler (extends AnAction) implements ResponseHandler from ApiHelper.

Everything works fine at this point. But if I move ApiHelper to com.name.app.helpers package I get NoClassDefFoundError &  PluginClassLoader - ClassNotFoundException.

Any idea why this is happening after moving moving file to another package?

答: Invalidate cache and restart. It worked.</p>


问:
When to use UICollectionView instead of UITableView?
I found that UICollectionView is like an upgraded version of UITableView introduced in iOS6, but when should I choose UICollectionView instead of UITableView?

There are still Apps using UITableView, if UICollectionView can do anything UITableView can do , why people still use UITableView? Is there a difference as far as performance is concerned?

Thanks!

答:
Its totally dependent on how your data to be shown.
As mentioned by many above, if you require only single set of data and that too not complex, go for UITableView else use UICollectionView.

UICollectionView is customization friendly.

If you are dealing with multiple cell heights or so, then go for UICollectionView.


问:
How to count how many elements satisfy a condition in an idiomatic way?
Having this data:

```<code>> data
 [1] 1290603356 1290603360 1290603350 1290603344 1290603340 1290603373
 [7] 1290603354 1290603359 1290603345 1290603363 1290603357 1290603354
[13] 1290603364 1290603349 1290603352 1290603365 1290603349 1290603343
[19] 1290603339 1290603343
> offsets <- c(0, 0.5,1,2,4,8,24,4*24,7*24) * 3600)
[1]   1800   3600   7200  14400  28800  86400 345600 604800
> myoffsets <- min(data)+offsets
</code>```

being, a list of UNIX epochs and a list of offsets (0.5 hours, 1h, 2h, 4h...)
I want to be able to graph how many of the epochs are <= than the min(data) + offset

In this example it would be

```<code>1 20 20 20 20 20 20 20
</code>```

I have found how to do this with a for loop:

```<code>for(i in c(1:length(myoffsets))) myres$x[i] <- length(data[data <= myoffsets[i]])
</code>```

But I'm sure there's a more idiomatic way if doing this that is not as convoluted?

答:
```<code>plot(subset(data, data <= min(data+offset)))
</code>```

Body:
Having this data:

> data
 [1] 1290603356 1290603360 1290603350 1290603344 1290603340 1290603373
 [7] 1290603354 1290603359 1290603345 1290603363 1290603357 1290603354
[13] 1290603364 1290603349 1290603352 1290603365 1290603349 1290603343
[19] 1290603339 1290603343
> offsets <- c(0, 0.5,1,2,4,8,24,4*24,7*24) * 3600)
[1]   1800   3600   7200  14400  28800  86400 345600 604800
> myoffsets <- min(data)+offsets

being, a list of UNIX epochs and a list of offsets (0.5 hours, 1h, 2h, 4h...)
I want to be able to graph how many of the epochs are <= than the min(data) + offset

In this example it would be

1 20 20 20 20 20 20 20

I have found how to do this with a for loop:

for(i in c(1:length(myoffsets))) myres$x[i] <- length(data[data <= myoffsets[i]])

But I'm sure there's a more idiomatic way if doing this that is not as convoluted?


问:
Show bigger version of actor while actor is tapped libgdx
Let's say I have an actor foo and an actor bar which is the bigger version of the foo actor. How can I show bar next to foo while foo is tapped and then have have it disappear when foo is no longer being tapped (kind of like a tooltip)? Foo is in a stage2d table.
How can I show a bigger, more complete version of the actor while it is tapped?

Rough idea of what I want:

```<code>    Actor foo = new Actor();
    foo.addListener(new ActorGestureListener() {

        public void touchDown (InputEvent event, float x, float y, int pointer, int button) {
            // show bar next to foo (like a tooltip)
        }

        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
            // make bar dissapear
        }
    });
</code>```

Code that kind of does what I want:
In this case toolTipCard is the actor I want to display when I touch one of the Strings from selectedDeck.

```<code>Stage collectionStage;
List<String> selectedDeck;
TestCard tooltipCard;
Vector3 touch = new Vector3();

            selectedDeck.addListener(new ActorGestureListener() {

                public void touchDown(InputEvent event, float x, float y, int count, int button) {
                    if (selectedDeck.getItems().size > 0) {
                        tooltipCard = new TestCard(game.cardFont, cardNameToCard.get(selectedDeck.getSelected()));
                        tooltipCard.setWidth(Gdx.graphics.getWidth() / (7 * scale));
                        tooltipCard.setHeight(Gdx.graphics.getHeight() / (3.3f * scale));
                        touch = viewport.unproject(touch.set(Gdx.input.getX(), Gdx.input.getY(), 0));
                        tooltipCard.setPosition(touch.x - tooltipCard.getWidth(), touch.y - tooltipCard.getHeight());
                        collectionStage.addActor(tooltipCard);
                    }
                }

                public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
                    tooltipCard.remove();
                }
            });
</code>```

答:
As described in the comments there are 2 options:

edit the draw method of an actor (if you need to show a very simple tooltip use this).

If you want to show a more advanced actor which can have it's own actions. You can get the foo's global coordinates and add an actor directly to the stage which you set visible/invisible (or fade in/out for a nicer look/feel).

To get the coordinates you can use: localToStageCoordinates

```<code>Vector2 v = foo.localToStageCoordinates(new Vector2());
</code>```

or relative to its center:

```<code>Vector2 v = foo.localToStageCoordinates(new Vector2(foo.getWidth()/2,foo.getHeight()/2));
</code>```

then use for instance: bar.addAction(Actions.fadeIn(0.5f)); and bar.addAction(Actions.fadeOut(0.5f)); to show/hide the tooltip

For optimization purposes you can reuse the bar actor for all foo instances on the screen and just repurpose it on every click. It is probably cheaper than creating a full actor for every one of them. However, if you can probably even create and destroy it on touch down/up without any problems.

Body:
Let's say I have an actor foo and an actor bar which is the bigger version of the foo actor. How can I show bar next to foo while foo is tapped and then have have it disappear when foo is no longer being tapped (kind of like a tooltip)? Foo is in a stage2d table.
How can I show a bigger, more complete version of the actor while it is tapped?

Rough idea of what I want:

    Actor foo = new Actor();
    foo.addListener(new ActorGestureListener() {

        public void touchDown (InputEvent event, float x, float y, int pointer, int button) {
            // show bar next to foo (like a tooltip)
        }

        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
            // make bar dissapear
        }
    });

Code that kind of does what I want:
In this case toolTipCard is the actor I want to display when I touch one of the Strings from selectedDeck.

Stage collectionStage;
List<String> selectedDeck;
TestCard tooltipCard;
Vector3 touch = new Vector3();

            selectedDeck.addListener(new ActorGestureListener() {

                public void touchDown(InputEvent event, float x, float y, int count, int button) {
                    if (selectedDeck.getItems().size > 0) {
                        tooltipCard = new TestCard(game.cardFont, cardNameToCard.get(selectedDeck.getSelected()));
                        tooltipCard.setWidth(Gdx.graphics.getWidth() / (7 * scale));
                        tooltipCard.setHeight(Gdx.graphics.getHeight() / (3.3f * scale));
                        touch = viewport.unproject(touch.set(Gdx.input.getX(), Gdx.input.getY(), 0));
                        tooltipCard.setPosition(touch.x - tooltipCard.getWidth(), touch.y - tooltipCard.getHeight());
                        collectionStage.addActor(tooltipCard);
                    }
                }

                public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
                    tooltipCard.remove();
                }
            });

Body:
As described in the comments there are 2 options:

edit the draw method of an actor (if you need to show a very simple tooltip use this).

If you want to show a more advanced actor which can have it's own actions. You can get the foo's global coordinates and add an actor directly to the stage which you set visible/invisible (or fade in/out for a nicer look/feel).

To get the coordinates you can use: localToStageCoordinates

Vector2 v = foo.localToStageCoordinates(new Vector2());

or relative to its center:

Vector2 v = foo.localToStageCoordinates(new Vector2(foo.getWidth()/2,foo.getHeight()/2));

then use for instance: bar.addAction(Actions.fadeIn(0.5f)); and bar.addAction(Actions.fadeOut(0.5f)); to show/hide the tooltip

For optimization purposes you can reuse the bar actor for all foo instances on the screen and just repurpose it on every click. It is probably cheaper than creating a full actor for every one of them. However, if you can probably even create and destroy it on touch down/up without any problems.


问:
Python: Why it always asks to install pyparsing whenever I want install something?
I'm not sure why pip always throw the exception that 'can not find pyparsing'.
even When I try to download pyparsing i get:

```<code>pip install pyparsing
Traceback (most recent call last):
  File "/usr/bin/pip", line 5, in <module>
    from pkg_resources import load_entry_point
  File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 72, in <module>
    import packaging.requirements
  File "/usr/local/lib/python2.7/dist-packages/packaging/requirements.py", line 9, in <module>
    from pyparsing import stringStart, stringEnd, originalTextFor, ParseException
ImportError: No module named pyparsing
</code>```

It doesn't make sense?!

答:
Try Downloading the wheel file and install

```<code>wget https://pypi.python.org/packages/6a/8a/718fd7d3458f9fab8e67186b00abdd345b639976bc7fb3ae722e1b026a50/pyparsing-2.2.0-py2.py3-none-any.whl#md5=7247e7896688eff4bc8c7fc5d0cdd2b0
pip install pyparsing-2.2.0-py2.py3-none-any.whl
</code>```

In case you face any issue with wget command download , you can get the wheel file from the following link

https://pypi.python.org/pypi/pyparsing/2.2.0#downloads

Body:
I'm not sure why pip always throw the exception that 'can not find pyparsing'.
even When I try to download pyparsing i get:

pip install pyparsing
Traceback (most recent call last):
  File "/usr/bin/pip", line 5, in <module>
    from pkg_resources import load_entry_point
  File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 72, in <module>
    import packaging.requirements
  File "/usr/local/lib/python2.7/dist-packages/packaging/requirements.py", line 9, in <module>
    from pyparsing import stringStart, stringEnd, originalTextFor, ParseException
ImportError: No module named pyparsing

It doesn't make sense?!

Body:
Try Downloading the wheel file and install

wget https://pypi.python.org/packages/6a/8a/718fd7d3458f9fab8e67186b00abdd345b639976bc7fb3ae722e1b026a50/pyparsing-2.2.0-py2.py3-none-any.whl#md5=7247e7896688eff4bc8c7fc5d0cdd2b0
pip install pyparsing-2.2.0-py2.py3-none-any.whl

In case you face any issue with wget command download , you can get the wheel file from the following link

https://pypi.python.org/pypi/pyparsing/2.2.0#downloads


问:
listview to string exception thrown
What I have going on is i am using

```<code>string proj = listView2.SelectedItems[0].ToString();
</code>```

to capture the item of my selected listview item, this works fine the first around, when i click on another listview item it throw the exception of

InvalidArgument=Value of '0' is not valid for 'index'.
  Parameter name: index

Any thoughts?

```<code>    private void listView2_SelectedIndexChanged(object sender, EventArgs e)
    {
       string proj = listView2.SelectedItems[0].ToString();
    }
</code>```

working:

```<code>        string proj ="";
        ListView.SelectedListViewItemCollection lv2si =
        this.listView2.SelectedItems;

        foreach (ListViewItem item in lv2si)
        {
            proj = item.ToString();
        }
</code>```

答:
What if no item is selected in listview ? The collection will contain zero items and it will throw this exception.

Instead, obtain ListViewItemCollection and use foreach to iterate over it. As described in MSDN example:
ListView.SelectedListViewItemCollection breakfast =
            this.ListView1.SelectedItems;

```<code>    double price = 0.0;
    foreach ( ListViewItem item in breakfast )
    {
        price += Double.Parse(item.SubItems[1].Text);
    }
</code>```

http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.selecteditems.aspx

Title: listview to string exception thrown

Body:
What I have going on is i am using

string proj = listView2.SelectedItems[0].ToString();

to capture the item of my selected listview item, this works fine the first around, when i click on another listview item it throw the exception of

InvalidArgument=Value of '0' is not valid for 'index'.
  Parameter name: index

Any thoughts?

    private void listView2_SelectedIndexChanged(object sender, EventArgs e)
    {
       string proj = listView2.SelectedItems[0].ToString();
    }

working:

        string proj ="";
        ListView.SelectedListViewItemCollection lv2si =
        this.listView2.SelectedItems;

        foreach (ListViewItem item in lv2si)
        {
            proj = item.ToString();
        }

Body:
What if no item is selected in listview ? The collection will contain zero items and it will throw this exception.

Instead, obtain ListViewItemCollection and use foreach to iterate over it. As described in MSDN example:
ListView.SelectedListViewItemCollection breakfast =
            this.ListView1.SelectedItems;

    double price = 0.0;
    foreach ( ListViewItem item in breakfast )
    {
        price += Double.Parse(item.SubItems[1].Text);
    }

http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.selecteditems.aspx


问:
Alarm is ringing continously?
i'm new to android ,this is my code,and i'm stored alarm values in sqlite ,Alarm got ringing correct time but i get my alarm is ringing continously...

```<code>     private void night() {
    DatabaseHelper db = new DatabaseHelper(getContext());
    ls = db.getAllinfo();
    for (int i = 0; i < ls.size(); i++) {
        Calendar c = Calendar.getInstance();
            int hour = Integer.parseInt(ls.get(i).getSch_night_hour());
            int mins = Integer.parseInt(ls.get(i).getSch_night_mins());
        //int hour=20;
        //int mins=06;
            int cr_hour = c.get(Calendar.HOUR_OF_DAY);
            int cr_mins = c.get(Calendar.MINUTE);
            if (cr_hour >= hour) {

                if (cr_mins == mins) {
                    try {
                        new AlarmReceiver(cr_hour,mins,10).setAlarm(getActivity());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return;
                } else {

                    Log.e("night", "for hr waiting");

                }
            } else {
                Log.e("night", "for mins waiting");
            }
      }

  return;
}
</code>```

AlarmReciver.class

```<code>   public void setAlarm(Context context) {
        pf=new PrimaryFragment();
        alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, Alarmclass.class);
        alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, hour);
    calendar.set(Calendar.MINUTE, min);
    calendar.set(Calendar.SECOND, sec);
       // alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
             //   calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);
        alarmMgr.set(AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(), alarmIntent);
        Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);

        vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(800);
        ringtone = RingtoneManager.getRingtone(context, alarmUri);
        ringtone.play();
      //  pf.showstatus();
        //notification
        ComponentName comp = new ComponentName(context.getPackageName(),
                Alarmclass.class.getName());
        startWakefulService(context, (intent.setComponent(comp)));
    alarmMgr.cancel(alarmIntent);
}
</code>```

please any one clear my doubt...waiting for your positive response...

答: You need to stop the alarm . Try ringtone.stop() after you play it.

Title: Alarm is ringing continously?

Body:
i'm new to android ,this is my code,and i'm stored alarm values in sqlite ,Alarm got ringing correct time but i get my alarm is ringing continously...

     private void night() {
    DatabaseHelper db = new DatabaseHelper(getContext());
    ls = db.getAllinfo();
    for (int i = 0; i < ls.size(); i++) {
        Calendar c = Calendar.getInstance();
            int hour = Integer.parseInt(ls.get(i).getSch_night_hour());
            int mins = Integer.parseInt(ls.get(i).getSch_night_mins());
        //int hour=20;
        //int mins=06;
            int cr_hour = c.get(Calendar.HOUR_OF_DAY);
            int cr_mins = c.get(Calendar.MINUTE);
            if (cr_hour >= hour) {

                if (cr_mins == mins) {
                    try {
                        new AlarmReceiver(cr_hour,mins,10).setAlarm(getActivity());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return;
                } else {

                    Log.e("night", "for hr waiting");

                }
            } else {
                Log.e("night", "for mins waiting");
            }
      }

  return;
}

AlarmReciver.class

   public void setAlarm(Context context) {
        pf=new PrimaryFragment();
        alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, Alarmclass.class);
        alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, hour);
    calendar.set(Calendar.MINUTE, min);
    calendar.set(Calendar.SECOND, sec);
       // alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
             //   calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);
        alarmMgr.set(AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(), alarmIntent);
        Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);

        vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(800);
        ringtone = RingtoneManager.getRingtone(context, alarmUri);
        ringtone.play();
      //  pf.showstatus();
        //notification
        ComponentName comp = new ComponentName(context.getPackageName(),
                Alarmclass.class.getName());
        startWakefulService(context, (intent.setComponent(comp)));
    alarmMgr.cancel(alarmIntent);
}

please any one clear my doubt...waiting for your positive response...


问:
Copy a file by ANT from a folder in workspace to a folder in the project
I have a file which i need to copy from workspace/dir1 to the current project[workspace/dir2]

My ANT build file is in dir2

答:
Use the following code to copy workspace

```<code><project name="ant_workspace_demo">
    <target name="copy_workspace">
        <copy todir="../New_files">
            <fileset dir="AntWorkspace"/>
        </copy>
    </target>
</project>
</code>```

Then, in command prompt(windows) enter "ant copy_workspace".

Body:
Use the following code to copy workspace

<project name="ant_workspace_demo">
    <target name="copy_workspace">
        <copy todir="../New_files">
            <fileset dir="AntWorkspace"/>
        </copy>
    </target>
</project>

Then, in command prompt(windows) enter "ant copy_workspace".


问:
How to use a recursive function to count the sum of the positive elements of a list?
How to use a recursive function to count the sum of the positive elements of a list?

I'm not sure how to go about it? I know how to do it without using a recursive function:

```<code>sum=0
for i in range(len(List)):
    if List[i]>0:
        sum=sum+List[i]
</code>```

答:
You need to divide the problem, into a 'current' step and the remainder to be handled by recursion. You also need to determine when to end the recursion.

The current step is determining what to sum in this step. That's the current value, or 0 if the value is smaller than 0.

The remainder is summing the current value to the recursive call for the rest of the list.

You end the recursion when an empty list is passed in; the sum of an empty list is always 0.

In the end, that gives:

```<code>def recursive_positive_sum(l):
    # end recursion for an empty list
    if not l:
        return 0
    # get a value
    value = l[0]
    if value < 0:
        value = 0
    # recurse, sum the value with the remainder
    return value + recursive_positive_sum(l[1:])
</code>```

We can use a max() to get the value or 0 and inline that:

```<code>def recursive_positive_sum(l):
    if not l:
        return 0
    return max(l[0], 0) + recursive_positive_sum(l[1:])
</code>```

Demo:

```<code>>>> def recursive_positive_sum(l):
...     if not l:
...         return 0
...     return max(l[0], 0) + recursive_positive_sum(l[1:])
...
>>> recursive_positive_sum([])
0
>>> recursive_positive_sum([-42])
0
>>> recursive_positive_sum([-42, 10, -81, 100])
110
</code>```

Body:
How to use a recursive function to count the sum of the positive elements of a list?

I'm not sure how to go about it? I know how to do it without using a recursive function:

sum=0
for i in range(len(List)):
    if List[i]>0:
        sum=sum+List[i]

Body:
You need to divide the problem, into a 'current' step and the remainder to be handled by recursion. You also need to determine when to end the recursion.

The current step is determining what to sum in this step. That's the current value, or 0 if the value is smaller than 0.

The remainder is summing the current value to the recursive call for the rest of the list.

You end the recursion when an empty list is passed in; the sum of an empty list is always 0.

In the end, that gives:

def recursive_positive_sum(l):
    # end recursion for an empty list
    if not l:
        return 0
    # get a value
    value = l[0]
    if value < 0:
        value = 0
    # recurse, sum the value with the remainder
    return value + recursive_positive_sum(l[1:])

We can use a max() to get the value or 0 and inline that:

def recursive_positive_sum(l):
    if not l:
        return 0
    return max(l[0], 0) + recursive_positive_sum(l[1:])

Demo:

>>> def recursive_positive_sum(l):
...     if not l:
...         return 0
...     return max(l[0], 0) + recursive_positive_sum(l[1:])
...
>>> recursive_positive_sum([])
0
>>> recursive_positive_sum([-42])
0
>>> recursive_positive_sum([-42, 10, -81, 100])
110


问:
Excel Combine two columns in call to function?
My spreadsheet looks like this:

I have two lists of dates, I want to get all unique dates between Dates1 and Dates2 and put them in column C.

I can get unique dates in column A with UNIQUE(A2:A4), but I want all unique dates between both columnms. When I try to do =UNIQUE(A2:A4,B2:B5) I get the error:

Wrong number of arguments to UNIQUE. Expected 1 arguments, but got 2 arguments.

How can I get all unique dates between both? I've also tried concatenate, but that just gives me a huge number, not a row of dates.

Thanks!

答:
unique formula can only work with single column. Try this formula:

=UNIQUE({A2:A4;B2:B5})

{ } will convert 2 columns into one: {A2:A4;B2:B5}

See more info here:
https://support.google.com/docs/answer/6208276?hl=en


问:
runas command in windows 7
I'm trying to run a batch file as admin. I found that I can use runas command which corresponds sudo command in Linux I think.

I tried

runas /noprofile /user:computername\adminuser "blah.bat start"

But it gives an error, saying :

Logon failure: user account restriction.. (msdos window doesn't allow me to copy anything) is there any way I can run this batch file as admin? Right click doesn't work because I can't include any parameters.

答:
I believe that you can allow or disallow the RunAs command with the registry.

```<code>HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer
"HideRunAsVerb"= 1
</code>```

See Disabling the RunAs Command

Title: runas command in windows 7

Body:
I believe that you can allow or disallow the RunAs command with the registry.

HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer
"HideRunAsVerb"= 1

See Disabling the RunAs Command


问:
How to find what version of EclipseLink my Eclipse Project is using?
I have a Maven jersey-quickstart-webapp Project I am developing in Eclipse. The project is a JERSEY REST backend with angularjs javascript frontend.

I would like to know how to check what version of EclipseLink my project is using.

Where can I find this property? I've searched high and low but I can't find it - I know that I did stumble across it before, so it definitely exists....

This question is trying to get to the bottom of the following question I posed months ago about a problem with eclipselink and Jersey REST, that still hasn't been fixed: Class not found when using JAX-RS with Eclipse and Glassfish
This should be fixed with jersey 2.22.1 and eclipselink 2.6.1, but I think somewhere in my setup, eclipselink 2.6.0 is still hanging around and screwing the whole thing up. Highly frustrating!

I know that eclipselink is being used in this project, because the following code returns 2.6.1 when the project is running. However, previously I saw that even though this was saying 2.6.1, that the eclipselink configuration somewhere(I can't remember where - doh!) was still saying version 2.6.0.

```<code>//This helps us tell what version of eclipse link we are using
Class<?> myClass = Class.forName("org.eclipse.persistence.Version");
Method myMethod = myClass.getMethod("getVersion");
String version = myMethod.invoke(null).toString();
System.out.println("version = " + version);
</code>```

Here is what the Maven dependency hierarchy looks like - as you can see it has no eclipselink stuff in there:

All help highly appreciated...

答:
Duplicated! Refer this

There is a static class and static method to get this information.
  Example: How to print in java code

```<code>AbstractSessionLog.getLog().log(SessionLog.INFO, DatabaseLogin.getVersion());
</code>```

Body:
I have a Maven jersey-quickstart-webapp Project I am developing in Eclipse. The project is a JERSEY REST backend with angularjs javascript frontend.

I would like to know how to check what version of EclipseLink my project is using.

Where can I find this property? I've searched high and low but I can't find it - I know that I did stumble across it before, so it definitely exists....

This question is trying to get to the bottom of the following question I posed months ago about a problem with eclipselink and Jersey REST, that still hasn't been fixed: Class not found when using JAX-RS with Eclipse and Glassfish
This should be fixed with jersey 2.22.1 and eclipselink 2.6.1, but I think somewhere in my setup, eclipselink 2.6.0 is still hanging around and screwing the whole thing up. Highly frustrating!

I know that eclipselink is being used in this project, because the following code returns 2.6.1 when the project is running. However, previously I saw that even though this was saying 2.6.1, that the eclipselink configuration somewhere(I can't remember where - doh!) was still saying version 2.6.0.

//This helps us tell what version of eclipse link we are using
Class<?> myClass = Class.forName("org.eclipse.persistence.Version");
Method myMethod = myClass.getMethod("getVersion");
String version = myMethod.invoke(null).toString();
System.out.println("version = " + version);

Here is what the Maven dependency hierarchy looks like - as you can see it has no eclipselink stuff in there:

All help highly appreciated...

Body:
Duplicated! Refer this

There is a static class and static method to get this information.
  Example: How to print in java code

AbstractSessionLog.getLog().log(SessionLog.INFO, DatabaseLogin.getVersion());


问:
SELECT COUNT Per Date and Type SQL Server 2012
I have an SQL Query below.

```<code>SELECT sched_date, sched_name, employee_name from tbl_schedule
</code>```

It returns this result:

```<code>    sched_date    sched_name              employee_name

    2017-04-01    09:00 AM - 06:00 PM     M.G.Cave
    2017-04-01    09:00 AM - 06:00 PM     L.C.Manalo
    2017-04-01    11:00 AM - 8:00 PM      R.M.Jakosalem
    2017-04-01    11:00 AM - 8:00 PM      S.D.Dela Cruz
    2017-04-02    Rest Day                M.G.Cave
    2017-04-02    Rest Day                L.C.Manalo
    2017-04-02    Rest Day                R.M.Jakosalem
    2017-04-02    Rest Day                S.D.Dela Cruz
</code>```

I want the employees to be counted per date and per schedule. My desired result is:

```<code>    2017-04-01    09:00 AM - 06:00 PM     2 employees
    2017-04-01    11:00 AM - 8:00 PM      2 employees
    2017-04-02    Rest Day                4 employees
</code>```

Thank you in advance.

答:
A GROUP BY on the sched_date, sched_name and a COUNT(*) will get you your desired result:

```<code>SELECT
   sched_date,
   sched_name,
   COUNT(*) AS employees
from
   tbl_schedule
GROUP BY
   sched_date,
   sched_name
</code>```

Body:
I have an SQL Query below.

SELECT sched_date, sched_name, employee_name from tbl_schedule

It returns this result:

    sched_date    sched_name              employee_name

    2017-04-01    09:00 AM - 06:00 PM     M.G.Cave
    2017-04-01    09:00 AM - 06:00 PM     L.C.Manalo
    2017-04-01    11:00 AM - 8:00 PM      R.M.Jakosalem
    2017-04-01    11:00 AM - 8:00 PM      S.D.Dela Cruz
    2017-04-02    Rest Day                M.G.Cave
    2017-04-02    Rest Day                L.C.Manalo
    2017-04-02    Rest Day                R.M.Jakosalem
    2017-04-02    Rest Day                S.D.Dela Cruz

I want the employees to be counted per date and per schedule. My desired result is:

    2017-04-01    09:00 AM - 06:00 PM     2 employees
    2017-04-01    11:00 AM - 8:00 PM      2 employees
    2017-04-02    Rest Day                4 employees

Thank you in advance.

Body:
A GROUP BY on the sched_date, sched_name and a COUNT(*) will get you your desired result:

SELECT
   sched_date,
   sched_name,
   COUNT(*) AS employees
from
   tbl_schedule
GROUP BY
   sched_date,
   sched_name


问:
Is __exit__ called when using in parameter?
In this single line code, When call a method as parameter, but not release resource, __exit__ is called when method is finished ?

```<code>hashlib.md5(open("PATH", 'rb').read()).hexdigest()
</code>```

It can be issued about 'improper resource release' ?

答:
You can find a comprehensive explanations regard this in python data models documentation:

Some objects contain references to “external” resources such as open files or windows. It is understood that these resources are freed when the object is garbage-collected, but since garbage collection is not guaranteed to happen, such objects also provide an explicit way to release the external resource, usually a close() method. Programs are strongly recommended to explicitly close such objects. The try...finally statement and the with statement provide convenient ways to do this.

That said your opened object will not be closed since you're not calling the close attribute of the opened object. If you don't call the close explicitly you should wrap your code within a with statement:

```<code>with open("PATH", 'rb') as f:
    hashlib.md5(f.read()).hexdigest()
</code>```

By doing the context manager will call __exit__ method automatically at the end of the block which it will call the close method of your file object consequently.

Body:
In this single line code, When call a method as parameter, but not release resource, __exit__ is called when method is finished ?

hashlib.md5(open("PATH", 'rb').read()).hexdigest()

It can be issued about 'improper resource release' ?

Body:
You can find a comprehensive explanations regard this in python data models documentation:

Some objects contain references to “external” resources such as open files or windows. It is understood that these resources are freed when the object is garbage-collected, but since garbage collection is not guaranteed to happen, such objects also provide an explicit way to release the external resource, usually a close() method. Programs are strongly recommended to explicitly close such objects. The try...finally statement and the with statement provide convenient ways to do this.

That said your opened object will not be closed since you're not calling the close attribute of the opened object. If you don't call the close explicitly you should wrap your code within a with statement:

with open("PATH", 'rb') as f:
    hashlib.md5(f.read()).hexdigest()

By doing the context manager will call __exit__ method automatically at the end of the block which it will call the close method of your file object consequently.


问:
Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)
App Dies On Startup (connection to the server was unsuccessful)

I have an Android application that I'm writing using PhoneGap BUILD. The app was working fine earlier, but now it seems I am getting this error after refining my app (some UI changes only)

1) When I start the app I (usually) get:

Application Error - The connection to the server was unsuccessful.
(file:///android_asset/www/index.html)

Sorry if this is duplication of any question. I have seen some similar questions here, but i couldn't find a perfect answer or solution. As in my case it was working fine until my last changes.

答:
If you are using visual studio. After changing config.xml sometimes you need this

clean build solution
  rebuild your app

It is working for me.


问:
Array pointer outside of main function
Here is another total-beginner-noob question of me: when putting the lines

```<code>double w[1];
double *l;
l = w;
</code>```

into the main() function, everything works perfectly well when compiling, however, when putting it before the main() (as declared variables), then the error

expected ',' or ';' before '=' token

appears for the last line.

Also, putting the former two before main() and only l = w; into the main() will work fine. Why is that so? Does it have something to do with compile/runtime? Can I not assign values outside main() when having them declared before? If so, why?

答:
For why it works, declarations can be made outside a function - however, by doing so, you are declaring it as a global variable.

C++ can initialize a variable after you declare it, however, it will not run anything else other than that. So in this case, the expression

```<code>l = w;
</code>```

will not run because it is not inside a method.

Title: Array pointer outside of main function

Body:
Here is another total-beginner-noob question of me: when putting the lines

double w[1];
double *l;
l = w;

into the main() function, everything works perfectly well when compiling, however, when putting it before the main() (as declared variables), then the error

expected ',' or ';' before '=' token

appears for the last line.

Also, putting the former two before main() and only l = w; into the main() will work fine. Why is that so? Does it have something to do with compile/runtime? Can I not assign values outside main() when having them declared before? If so, why?

Body:
For why it works, declarations can be made outside a function - however, by doing so, you are declaring it as a global variable.

C++ can initialize a variable after you declare it, however, it will not run anything else other than that. So in this case, the expression

l = w;

will not run because it is not inside a method.


问:
Why is the formatting in my ftplugin applying to all files in every format?
I'm created a custom file format, .cheat, for my cheat sheets, and in that format only I am highlighting alternating rows to make it easy to see which keystroke combo triggers each command. Why is the formatting in my ftplugin applying to all files in every format?

Key lines from ~/.vim/vimrc:

```<code>set nocompatible
au BufNewFile,BufRead *.cheat set filetype=cheat
filetype off
" vundle stuff
filetype on
nmap <leader>? :75vsp ~/.vim/my.cheat
</code>```

(Full vimrc below for reference.)

Full ~/.vim/ftdetect/cheat.vim:

```<code>if exists("b:did_load_filetypes") | finish | endif
let b:did_ftplugin = 1
au BufNewFile,BufRead *.cheat set filetype=cheat

syn match Oddlines "^.*$" contains=ALL nextgroup=Evenlines skipnl
syn match Evenlines "^.*$" contains=ALL nextgroup=Oddlines skipnl
hi Oddlines ctermbg=DarkGray ctermfg=White
hi Evenlines ctermbg=LightGray ctermfg=White
</code>```

Full ~/.vim/vimrc:

```<code>set nocompatible
au BufNewFile,BufRead *.cheat set filetype=cheat
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
  Plugin 'VundleVim/Vundle.vim'
  Plugin 'dracula/vim'
  Plugin 'vim-airline/vim-airline'
  Plugin 'tpope/vim-commentary'
  Plugin 'neilagabriel/vim-geeknote'
  Plugin 'tpope/vim-fugitive'
  Plugin 'moll/vim-node'
  Plugin 'danro/rename.vim'
  Plugin 'vim-syntastic/syntastic'
  set statusline+=%#warningmsg#
  set statusline+=%{SyntasticStatuslineFlag()}
  set statusline+=%*
  let g:syntastic_always_populate_loc_list=1
  let g:syntastic_auto_loc_list=1
  let g:syntastic_check_on_open=1
  let g:syntastic_check_on_wq=0
call vundle#end()
filetype plugin indent on
set number
set wrap
set breakindent
set autoindent
set shiftwidth=2
set linebreak
set nolist
set cursorline
set cursorcolumn
set ruler
set laststatus=2
set timeoutlen=1000 ttimeoutlen=0
set splitright
hi CursorLine  cterm=NONE ctermbg=Black ctermfg=None
hi CursorColumn cterm=NONE ctermbg=Black ctermfg=None
set updatetime=200
au CursorHold * silent! update
nmap <CR> o<Esc>
nmap <leader>? :75vsp ~/.vim/my.cheat
</code>```

答:
Your ftdetect/cheat.vim should only contain the following :

```<code>au BufNewFile,BufRead *.cheat set filetype=cheat
</code>```

While the remaining configurations you should place in a ftplugin/cheat.vim :

```<code>if exists("b:did_ftplugin") | finish | endif
let b:did_ftplugin = 1

syn match Oddlines "^.$" contains=ALL nextgroup=Evenlines skipnl
syn match Evenlines "^.$" contains=ALL nextgroup=Oddlines skipnl
hi Oddlines ctermbg=DarkGray ctermfg=White
hi Evenlines ctermbg=LightGray ctermfg=White
</code>```

Body:
I'm created a custom file format, .cheat, for my cheat sheets, and in that format only I am highlighting alternating rows to make it easy to see which keystroke combo triggers each command. Why is the formatting in my ftplugin applying to all files in every format?

Key lines from ~/.vim/vimrc:

set nocompatible
au BufNewFile,BufRead *.cheat set filetype=cheat
filetype off
" vundle stuff
filetype on
nmap <leader>? :75vsp ~/.vim/my.cheat

(Full vimrc below for reference.)

Full ~/.vim/ftdetect/cheat.vim:

if exists("b:did_load_filetypes") | finish | endif
let b:did_ftplugin = 1
au BufNewFile,BufRead *.cheat set filetype=cheat

syn match Oddlines "^.*$" contains=ALL nextgroup=Evenlines skipnl
syn match Evenlines "^.*$" contains=ALL nextgroup=Oddlines skipnl
hi Oddlines ctermbg=DarkGray ctermfg=White
hi Evenlines ctermbg=LightGray ctermfg=White

Full ~/.vim/vimrc:

set nocompatible
au BufNewFile,BufRead *.cheat set filetype=cheat
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
  Plugin 'VundleVim/Vundle.vim'
  Plugin 'dracula/vim'
  Plugin 'vim-airline/vim-airline'
  Plugin 'tpope/vim-commentary'
  Plugin 'neilagabriel/vim-geeknote'
  Plugin 'tpope/vim-fugitive'
  Plugin 'moll/vim-node'
  Plugin 'danro/rename.vim'
  Plugin 'vim-syntastic/syntastic'
  set statusline+=%#warningmsg#
  set statusline+=%{SyntasticStatuslineFlag()}
  set statusline+=%*
  let g:syntastic_always_populate_loc_list=1
  let g:syntastic_auto_loc_list=1
  let g:syntastic_check_on_open=1
  let g:syntastic_check_on_wq=0
call vundle#end()
filetype plugin indent on
set number
set wrap
set breakindent
set autoindent
set shiftwidth=2
set linebreak
set nolist
set cursorline
set cursorcolumn
set ruler
set laststatus=2
set timeoutlen=1000 ttimeoutlen=0
set splitright
hi CursorLine  cterm=NONE ctermbg=Black ctermfg=None
hi CursorColumn cterm=NONE ctermbg=Black ctermfg=None
set updatetime=200
au CursorHold * silent! update
nmap <CR> o<Esc>
nmap <leader>? :75vsp ~/.vim/my.cheat

Body:
Your ftdetect/cheat.vim should only contain the following :

au BufNewFile,BufRead *.cheat set filetype=cheat

While the remaining configurations you should place in a ftplugin/cheat.vim :

if exists("b:did_ftplugin") | finish | endif
let b:did_ftplugin = 1

syn match Oddlines "^.$" contains=ALL nextgroup=Evenlines skipnl
syn match Evenlines "^.$" contains=ALL nextgroup=Oddlines skipnl
hi Oddlines ctermbg=DarkGray ctermfg=White
hi Evenlines ctermbg=LightGray ctermfg=White


问:
ilmerge error "Unresolved assembly reference not allowed: xxxxxxx"
I am trying to merge two assemblies using ilmerge with the method described here:

http://www.hanselman.com/blog/MixingLanguagesInASingleAssemblyInVisualStudioSeamlesslyWithILMergeAndMSBuild.aspx

however, I am getting an error with a project reference I don't want merged...so, of three referenced assemblies, I just want one merged, but the ilmerge doesn't seem to work with the project references.

I know there is a /lib: option, but how can I automate that in the Ilmerge.CSharp.targets so it works with any project?

答: I've had this problem for dll's I wasn't merging with ILMerge (I was merging others). It was solved by copying them to the directory <project>\obj\<configuration>\, because that's where ILMerge was looking for them and caused the error Unresolved assembly reference not allowed.


问:
Magento Theme's key does not correspond to required format
I am creating a new theme from scratch for magento 2, I have created the necessary files for it. but when i open the admin pannel it gives error, and the error log show the following error "Theme's key does not correspond to required format"

my theme.xml code:

```<code><theme xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/theme.xsd">
 <title>WPIINC</title> <!-- your theme's name -->
 <media>
     <preview_image>media/preview.jpg</preview_image> <!-- the path to your theme's preview image -->
 </media>
</theme>
</code>```

composer.json code:

```<code>{
"name": "wpiinc/wpiinc",
"description": "N/A",
"require": {
    "php": "~5.5.0|~5.6.0|~7.0.0",
    "magento/theme-frontend-blank": "100.0.*",
    "magento/framework": "100.0.*"
},
"type": "magento2-theme",
"version": "100.0.1",
"license": [
    "OSL-3.0",
    "AFL-3.0"
],
"autoload": {
    "files": [
        "registration.php"
    ]
}
}
</code>```

registration.php code:

```<code><?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::THEME,
'wpiinc/wpiinc',
__DIR__
);
</code>```

folder structure is app->design->frontend->wpiinc->wpiinc

how can i solve this error?
when i run php bin/magento setup:static-content:deploy this command i get following error in cmd prompt
"Theme's key does not correspond to required format 'area/vendor/name'"

Please help

答:
Please replace registration.php Code with</p>

```<code><?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::THEME,
'frontend/wpiinc/wpiinc',
__DIR__
);
</code>```

Body:
I am creating a new theme from scratch for magento 2, I have created the necessary files for it. but when i open the admin pannel it gives error, and the error log show the following error "Theme's key does not correspond to required format"

my theme.xml code:

<theme xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/theme.xsd">
 <title>WPIINC</title>
 <media>
     <preview_image>media/preview.jpg</preview_image>
 </media>
</theme>

composer.json code:

{
"name": "wpiinc/wpiinc",
"description": "N/A",
"require": {
    "php": "~5.5.0|~5.6.0|~7.0.0",
    "magento/theme-frontend-blank": "100.0.*",
    "magento/framework": "100.0.*"
},
"type": "magento2-theme",
"version": "100.0.1",
"license": [
    "OSL-3.0",
    "AFL-3.0"
],
"autoload": {
    "files": [
        "registration.php"
    ]
}
}

registration.php code:

<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::THEME,
'wpiinc/wpiinc',
__DIR__
);

folder structure is app->design->frontend->wpiinc->wpiinc

how can i solve this error?
when i run php bin/magento setup:static-content:deploy this command i get following error in cmd prompt
"Theme's key does not correspond to required format 'area/vendor/name'"

Please help

Body:
Please replace registration.php Code with

<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::THEME,
'frontend/wpiinc/wpiinc',
__DIR__
);


问:
TrueCaller SDK into iOS
I have to intrgate truecalled SDK into my app,
which will authenticate user and I will get response from truecaller which I have to use throughout the app.

I have downloaded the SDK from

```<code>https://developer.truecaller.com/
</code>```

and integrated into my code.
I am able to login using truecaller and It ask for permission.
If I click OK,
it opens the browser and shows some JSON,

like this

```<code>{"code":404, "message":"HTTP 404 not found"}
</code>```

I have used same URL provided by SDK,

```<code>https://si568c53146f0a4130bf723b62d52361b6.truecallerdevs.com
</code>```

Following are the screen shots shows the flow

答:
Did you follow this steps:

Add the entry truesdk under LSApplicationQueriesSchemes in into your Info.plist file

```<code><key>LSApplicationQueriesSchemes</key>
<array>
<string>truesdk</string>
</array>
</code>```

Add the associated domain provided by Truecaller (for example applinks:si44524554ef8e45b5aa83ced4e96d5xxx.truecallerdevs.com) in Your project -> Capabilities > Associated Domains. The prefix 'applinks:' is needed for universal links to function properly.

Important: Replace the 'https://' part from the provided app link with "applinks:". ie https://si44524554ef8e45b5aa83ced4e96d5xxx.truecallerdevs.com should become applinks:si44524554ef8e45b5aa83ced4e96d5xxx.truecallerdevs.com while adding to entitlements.

(Note that there is no http:// or https:// prefix when setting up the applinks:)

Title: TrueCaller SDK into iOS

Body:
I have to intrgate truecalled SDK into my app,
which will authenticate user and I will get response from truecaller which I have to use throughout the app.

I have downloaded the SDK from

https://developer.truecaller.com/

and integrated into my code.
I am able to login using truecaller and It ask for permission.
If I click OK,
it opens the browser and shows some JSON,

like this

{"code":404, "message":"HTTP 404 not found"}

I have used same URL provided by SDK,

https://si568c53146f0a4130bf723b62d52361b6.truecallerdevs.com

Following are the screen shots shows the flow

Body:
Did you follow this steps:

Add the entry truesdk under LSApplicationQueriesSchemes in into your Info.plist file

<key>LSApplicationQueriesSchemes</key>
<array>
<string>truesdk</string>
</array>

Add the associated domain provided by Truecaller (for example applinks:si44524554ef8e45b5aa83ced4e96d5xxx.truecallerdevs.com) in Your project -> Capabilities > Associated Domains. The prefix 'applinks:' is needed for universal links to function properly.

Important: Replace the 'https://' part from the provided app link with "applinks:". ie https://si44524554ef8e45b5aa83ced4e96d5xxx.truecallerdevs.com should become applinks:si44524554ef8e45b5aa83ced4e96d5xxx.truecallerdevs.com while adding to entitlements.

(Note that there is no http:// or https:// prefix when setting up the applinks:)


答:
The __exit__ won't be called, __exit__ is triggered at the end of with-statement.

In CPython __del__ will get triggered eventually as there are no reference to this file object anymore and it will close the file.

But it's recommended to use with-statement to make sure the close() call is explicit not implicit and in this way you're not relying on implementation details.

```<code>with open("PATH", 'rb') as f:
    hash = hashlib.md5(f.read()).hexdigest()
</code>```

Title: Is __exit__ called when using in parameter?

Body:
The __exit__ won't be called, __exit__ is triggered at the end of with-statement.

In CPython __del__ will get triggered eventually as there are no reference to this file object anymore and it will close the file.

But it's recommended to use with-statement to make sure the close() call is explicit not implicit and in this way you're not relying on implementation details.

with open("PATH", 'rb') as f:
    hash = hashlib.md5(f.read()).hexdigest()