问:
Angular/Node/Express/Passport - Issues when connecting to facebook(CORS)
i'm trying to use facebook authentication on my NodeJs server. i came to the tutorial of http://scotch.io/ and have it working locally when using a REST client(Postman, etc).

To improve the UI i used Angular JS as a front end. but when i call a http.get to my specific route given on the NodeJs back-end i get the following error in chome and firefox:

XMLHttpRequest cannot load https://www.facebook.com/dialog/oauth?response_type=code&redirect_uri=http%…0%2Fapi%2Fauth%2Ffacebook%2Fcallback&scope=email&client_id=3000000000006. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:8080' is therefore not allowed access.

i've tried several solutions on StackOverflow but its still not working...
my NodeJs uses Express 4.* and a CORS middleware.
for Angular i found several ways to enable CORS, none working so far.

I hope you can help me:D Thanks in advance!

答:
You can use 'window.location="http://localhost:3000/auth/facebook"'; in your Angular Controller from where you send the request to your Express Server which contains passport.authenticate stuff.

This will stop your angular to call facebook auth dialogue page as AJAX request.

It works for me!


来源: stackexchange

问:
animate addPlotBand Highcharts
Is there a way to add a plotband that has a smooth transition? Before I am using

addPlotLine and
  addPlotBand

```<code>chart.yAxis[0].removePlotBand('plot-band-1');
chart.yAxis[0].removePlotLine('plot-line-1');

var x = (new Date()).getTime(), // current time
    y = Math.round(Math.random() * 100);
series.addPoint([x, y], true, true);

chart.yAxis[0].addPlotBand({
    from: 100000,
    to: y,
    color: {
        linearGradient: { x1: 1, y1: 1, x2: 1, y2: 0 },
        stops: [
            [0, 'rgba(46, 230, 0, 0.22)'],
            [1, 'rgba(46, 230, 0, 0)'] //down
        ]
    },
    id: 'plot-band-1'
 });

chart.yAxis[0].addPlotLine({
    value: y,
    color: 'red',
    width: 2,
    id: 'plot-line-1'
});
</code>```

to plot the point on a dynamic chart, but now I am using animate to make the plotting smoother

```<code>        plotLine = yAxis.plotLinesAndBands[0].svgElem;
        d = plotLine.d.split(' ');

        newY = yAxis.toPixels(y) - d[2];

        plotLine.animate({
          translateY: newY
        }, 300);
</code>```

Also I am trying the solution from this Highcharts plotBand animation. however it seems that I am unable to implement it properly.
For your reference here is the code of where is used addPlotLine and addPlotBand and this is the current code style being used. Appreciate your help with this. Thank you.

答:
If you pass path d attribute as an array, you can animate it as a simple shape.

Add the plotband before setiInterval and animate it as the plotline on every interval.

```<code>const plotbandPath = plotband.svgElem.d.split(' ')
plotbandPath[7] = plotbandPath[9] = newY

plotband.svgElem.animate({
  d: plotbandPath
}, 300)
</code>```

example: http://jsfiddle.net/sqer2x13/

ContentLicense: CC BY-SA 3.0

Title: animate addPlotBand Highcharts

Body:
Is there a way to add a plotband that has a smooth transition? Before I am using

addPlotLine and
  addPlotBand

chart.yAxis[0].removePlotBand('plot-band-1');
chart.yAxis[0].removePlotLine('plot-line-1');

var x = (new Date()).getTime(), // current time
    y = Math.round(Math.random() * 100);
series.addPoint([x, y], true, true);

chart.yAxis[0].addPlotBand({
    from: 100000,
    to: y,
    color: {
        linearGradient: { x1: 1, y1: 1, x2: 1, y2: 0 },
        stops: [
            [0, 'rgba(46, 230, 0, 0.22)'],
            [1, 'rgba(46, 230, 0, 0)'] //down
        ]
    },
    id: 'plot-band-1'
 });

chart.yAxis[0].addPlotLine({
    value: y,
    color: 'red',
    width: 2,
    id: 'plot-line-1'
});

to plot the point on a dynamic chart, but now I am using animate to make the plotting smoother

        plotLine = yAxis.plotLinesAndBands[0].svgElem;
        d = plotLine.d.split(' ');

        newY = yAxis.toPixels(y) - d[2];

        plotLine.animate({
          translateY: newY
        }, 300);

Also I am trying the solution from this Highcharts plotBand animation. however it seems that I am unable to implement it properly.
For your reference here is the code of where is used addPlotLine and addPlotBand and this is the current code style being used. Appreciate your help with this. Thank you.

Body:
If you pass path d attribute as an array, you can animate it as a simple shape.

Add the plotband before setiInterval and animate it as the plotline on every interval.

const plotbandPath = plotband.svgElem.d.split(' ')
plotbandPath[7] = plotbandPath[9] = newY

plotband.svgElem.animate({
  d: plotbandPath
}, 300)

example: http://jsfiddle.net/sqer2x13/


问:
How to loop through csv cells in R?
I have two datasets in R as you can see below, Dataset 1 and Dataset 2. Consider the column 'company' in Dataset 1. I want to iterate through every row in Dataset 2 to find if that company exists, and if it does, then copy the format from Dataset 2 into Dataset 1 format field (currently NA). Thanks.

Dataset 1

Dataset 2

dataset1_updated after implementing Miff's solution

答:
This seems to be a classic case for merge, for example:

```<code>#Get rid of the existing format column
dataset1 <- dataset1[,names(dataset1 != "format")

#merge
dataset1_updated <- merge(dataset1, dataset2[,c("company","format")], all.x=TRUE)
</code>```

Not tested due to the lack of example data

Title: How to loop through csv cells in R?

Body:
This seems to be a classic case for merge, for example:

#Get rid of the existing format column
dataset1 <- dataset1[,names(dataset1 != "format")

#merge
dataset1_updated <- merge(dataset1, dataset2[,c("company","format")], all.x=TRUE)

Not tested due to the lack of example data


问:
Airport ticker effect in Adobe trials
When you run an Adobe product in a trial, a window appears each time asking if you have have a serial number yet or if you would like to continue with the trial. Next to that is a lovely 'number ticker', like the ones they used to have at airports (see image).

Does anyone know where I can get one of these, preferably gratis, to use as a component in a flex application?

答:
As promised an version of the flip clock, ready to use on github free of charge. If anyone has request. By all means - ask.

https://github.com/StrangeMother/Flash-AS3-Flip-Clock-display

edit: Sorry aboutt he broken link. Some how the .git at the end of the URL buggered.

I made an app that uses such a feature. Download the air app and take a look. Its just a super simple poker game timer, but it has the feature you require.

if you like it, then I'll sift the code out.

http://pokerblind.strangemother.com/app/data/application/versions/0.1/air/PokerBlind.air

Its a heady mixture of OOP class code and front end. The numerals are a Numeric item in the library of which are managed by a timer class and number counting class. Extendable enough and the graphics should be easy enough to rip apart.

ContentLicense: CC BY-SA 2.5

Title: Airport ticker effect in Adobe trials


问:
List items don't align the same
Hope you guys and girls can help me out here.
I want all the list items align the same at the left side (see image for example)

Example what I want is here

And this is my code

.feature-stack {
  margin: 100px 0 0 0;
  border: solid 3px;
}

.features ul.features-stack {
  margin-top: 50px;
}

.features ul.features-stack ul {}

.features ul.features-stack li:last-child {
  padding-bottom: 0px;
  border-bottom: none;
}

.feature-content ul li {
  list-style-type: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="features-stack">

  <li class="feature-item">
    <div class="feature-content">
      <h5>Polyethene</h5>
      <li>Test Test</li>
      <li>Test Test</li>
      <li>Test Test</li>
      <li>Test Test</li>
    </div>
  </li>

  <li class="feature-item">
    <div class="feature-content">
      <h5>Other virgin plastic</h5>
      <li>Test Test</li>
      <li>Test Test</li>
      <li>Test Test</li>
      <li>Test Test</li>
    </div>
  </li>

  <li class="feature-item">
    <div class="feature-content">
      <h5>Polypropylene</h5>
      <li>Test Test</li>
      <li>Test Test</li>
      <li>Test Test</li>
      <li>Test Test</li>
    </div>
  </li>

</ul></code>```

So I want them to align the same and that the circles are gone.
Hope I have given you guys enough information, otherwise let me know so I can give you more information.

Thanks

答:
Adding ul {list-style-type:none;} does the trick:

ul {
  list-style-type:none;
}

.feature-stack {
  margin: 100px 0 0 0;
  border: solid 3px;
}

.features ul.features-stack {
  margin-top: 50px;
}

.features ul.features-stack ul {}

.features ul.features-stack li:last-child {
  padding-bottom: 0px;
  border-bottom: none;
}

.feature-content ul li {
  list-style-type: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="features-stack">

  <li class="feature-item">
    <div class="feature-content">
      <h5>Polyethene</h5>
      <li>Test Test</li>
      <li>Test Test</li>
      <li>Test Test</li>
      <li>Test Test</li>
    </div>
  </li>

  <li class="feature-item">
    <div class="feature-content">
      <h5>Other virgin plastic</h5>
      <li>Test Test</li>
      <li>Test Test</li>
      <li>Test Test</li>
      <li>Test Test</li>
    </div>
  </li>

  <li class="feature-item">
    <div class="feature-content">
      <h5>Polypropylene</h5>
      <li>Test Test</li>
      <li>Test Test</li>
      <li>Test Test</li>
      <li>Test Test</li>
    </div>
  </li>

</ul></code>```

Title: List items don't align the same

Body:
Hope you guys and girls can help me out here.
I want all the list items align the same at the left side (see image for example)

Example what I want is here

And this is my code

.feature-stack {
  margin: 100px 0 0 0;
  border: solid 3px;
}

.features ul.features-stack {
  margin-top: 50px;
}

.features ul.features-stack ul {}

.features ul.features-stack li:last-child {
  padding-bottom: 0px;
  border-bottom: none;
}

.feature-content ul li {
  list-style-type: none;
}

Polyethene

Test Test

Test Test

Test Test

Test Test

Other virgin plastic

Test Test

Test Test

Test Test

Test Test

Polypropylene

Test Test

Test Test

Test Test

Test Test

So I want them to align the same and that the circles are gone.
Hope I have given you guys enough information, otherwise let me know so I can give you more information.

Thanks

Body:
Adding ul {list-style-type:none;} does the trick:

ul {
  list-style-type:none;
}

.feature-stack {
  margin: 100px 0 0 0;
  border: solid 3px;
}

.features ul.features-stack {
  margin-top: 50px;
}

.features ul.features-stack ul {}

.features ul.features-stack li:last-child {
  padding-bottom: 0px;
  border-bottom: none;
}

.feature-content ul li {
  list-style-type: none;
}

<ul class="features-stack">

  <li class="feature-item">
    <div class="feature-content">
      <h5>Polyethene</h5>
      <li>Test Test</li>
      <li>Test Test</li>
      <li>Test Test</li>
      <li>Test Test</li>
    </div>
  </li>

  <li class="feature-item">
    <div class="feature-content">
      <h5>Other virgin plastic</h5>
      <li>Test Test</li>
      <li>Test Test</li>
      <li>Test Test</li>
      <li>Test Test</li>
    </div>
  </li>

  <li class="feature-item">
    <div class="feature-content">
      <h5>Polypropylene</h5>
      <li>Test Test</li>
      <li>Test Test</li>
      <li>Test Test</li>
      <li>Test Test</li>
    </div>
  </li>

</ul>


问:
Command Manager Create Fact Script not seeing table
I keep getting a message when I try to run the script below in command manager, that the table isn't in the folder.  However when I look in the folder the table is right there, with "logical table" in the details column.  Can anyone see what the issue is with my script?</p>

```<code>Code:

CREATE FACT "TestFact" IN FOLDER "\Schema Objects\Facts\BulkFactTest" EXPRESSION "StuffCount" EXPSOURCETABLES "\SCHEMA OBJECTS\TABLES\TableName" FOR PROJECT "ProjectName";
</code>```

答:
Just checked and it seems you have to omit the base path to the table. Check the outline-example for "Create Fact" of the CommandManager (always helpful).

So this will work:

```<code>CREATE FACT "TestFact" IN FOLDER "\Schema Objects\Facts\BulkFactTest" EXPRESSION "StuffCount" EXPSOURCETABLES "TableName" FOR PROJECT "ProjectName";
</code>```

Note: even when moving tables/table-aliases to subfolders you have to only provide the table-name in EXPSOURCETABLES. Sadly documentation is not the strong suit of MSTR.

Body:
I keep getting a message when I try to run the script below in command manager, that the table isn't in the folder.  However when I look in the folder the table is right there, with "logical table" in the details column.  Can anyone see what the issue is with my script?

Code:

CREATE FACT "TestFact" IN FOLDER "\Schema Objects\Facts\BulkFactTest" EXPRESSION "StuffCount" EXPSOURCETABLES "\SCHEMA OBJECTS\TABLES\TableName" FOR PROJECT "ProjectName";

Body:
Just checked and it seems you have to omit the base path to the table. Check the outline-example for "Create Fact" of the CommandManager (always helpful).

So this will work:

CREATE FACT "TestFact" IN FOLDER "\Schema Objects\Facts\BulkFactTest" EXPRESSION "StuffCount" EXPSOURCETABLES "TableName" FOR PROJECT "ProjectName";

Note: even when moving tables/table-aliases to subfolders you have to only provide the table-name in EXPSOURCETABLES. Sadly documentation is not the strong suit of MSTR.


问:
<userSettings> in app.config Could not find schema information for the element 'userSettings'
Hello when I try to add parameters to the settings table
I get multiple messages for each parameter I add.

e.g.:

Could not find schema information for
the element 'userSettings'

Could not find schema information for
the element 'setting'

Could not find schema information for
the attribute 'serializeAs'

In the app.config I get:

```<code><project1.Properties.Settings>
   <setting name="ccc" serializeAs="String">
      <value>vvv</value>
    </setting>
</project1.Properties.Settings>
</code>```

I can use, edit and save this parameter, but the messages really annoy me.

I use the following schema (and selecting other like 20 and 30 did not help):

C:\Program Files (x86)\Microsoft Visual Studio 9.0\xml\Schemas\DotNetConfig.xsd

Any ideas?

edit:
following Hans post here is my configSections

```<code><configSections>
    <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
      <section name="project1.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
    </sectionGroup>
  </configSections>
</code>```

I don't know what it is for and if I should change it - yet here it is :)

Thanks Asaf

答: I just had this same issue. The fix I came across was to do a 'Clean Solution' followed by a 'Rebuild Solution'. This seems to rebuild the files correctly.</p>

Body:
Hello when I try to add parameters to the settings table
I get multiple messages for each parameter I add.

e.g.:

Could not find schema information for
the element 'userSettings'

Could not find schema information for
the element 'setting'

Could not find schema information for
the attribute 'serializeAs'

In the app.config I get:

<project1.Properties.Settings>
   <setting name="ccc" serializeAs="String">
      <value>vvv</value>
    </setting>
</project1.Properties.Settings>

I can use, edit and save this parameter, but the messages really annoy me.

I use the following schema (and selecting other like 20 and 30 did not help):

C:\Program Files (x86)\Microsoft Visual Studio 9.0\xml\Schemas\DotNetConfig.xsd

Any ideas?

edit:
following Hans post here is my configSections

<configSections>
    <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >

    </sectionGroup>
  </configSections>

I don't know what it is for and if I should change it - yet here it is :)

Thanks Asaf


问:
Install pip without root but with the system's python
I am trying to install pip without sudo.
Reading the Install Docs, it appears to be possible to use --user to have it being installed in my home directory.
After uninstalling pip from the global scope I tried python get-pip.py --user and obtain the following error:

PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.5/dist-packages/wheel-0.29.0.dist-info'

Checking the Install Docs I found the following notice:

Be cautious if you're using a Python install that's managed by your operating system or another package manager. get-pip.py does not coordinate with those tools, and may leave your system in an inconsistent state.

Can I install pip into my home with the casual Ubuntu apt-get python? Or do I also need to build python locally?

答: As phd mentoined in the comment of my question, cloning pip and installing it via python setup.py install --user worked out fine.


问:
Entity Framework ToListAsync() with Select()
I have the following ActionResult in my controller

```<code>public async Task<ActionResult> NewTickets()
{
    // Show tickets for all divisions a agent is in

    var user = "abcdefg";
    var company = "company1";

    var tickets = (from a in db2.Ticket
        join c in db2.Division on a.DivisionId equals c.DivisionId
        join dp in db2.DivisionParticipator on c.DivisionId equals dp.DivisionId
        where c.CompanyId == company.CompanyId && a.Status == "New" && dp.ApplicationUserId == user.Id
        select new
        {
            Id = a.Id,
            DivisionId = a.DivisionId,
            Name = a.Name,
            TicketDate = a.TicketDate,
            NewPosts = a.NewPosts,
            Status = a.Status,
            Type = a.Type
         })
         .ToList().Select(x => new Ticket
         {
             Id = x.Id,
             DivisionId = x.DivisionId,
             Name = x.Name,
             TicketDate = x.TicketDate,
             NewPosts = x.NewPosts,
             Status = x.Status,
             Type = x.Type
          });

    return PartialView(tickets.ToList());
}
</code>```

What i want to achieve is running this async, however if adding the ToListAsync()before Select()the Select() method becomes unavailable. The same goes for the return PartialView(tickets.ToList()).

I'm fairly new to working with async but reading about it's advantages I have been convering regular ActionResult methods with async ones. This has been going fine so far with easier LINQ-based queries. However for this ActionResult-method the query is a bit more advanced and the syntax/way to implement it seems to differ.

Any help to send me in the right direction would be greatly appreciated!

答:
Split in into two statements:

```<code>var tickets0 = await (from ...).ToListAsync();

var tickets = tickets0.Select(...);
</code>```

The .ToListAsync() returns a Task, so it doesn't accept the .Select extension method, which will need some IEnumerable. Only when you await that Task, you will get the List.

Another way (less readable IMO) would be:

```<code> var tickets = (await (from ...).ToListAsync()).Select(...);
</code>```

Note the extra ( ) around the await clause, which mean that the Select will work on the result of the awaited code, instead of the Task.

Body:
I have the following ActionResult in my controller

public async Task<ActionResult> NewTickets()
{
    // Show tickets for all divisions a agent is in

    var user = "abcdefg";
    var company = "company1";

    var tickets = (from a in db2.Ticket
        join c in db2.Division on a.DivisionId equals c.DivisionId
        join dp in db2.DivisionParticipator on c.DivisionId equals dp.DivisionId
        where c.CompanyId == company.CompanyId && a.Status == "New" && dp.ApplicationUserId == user.Id
        select new
        {
            Id = a.Id,
            DivisionId = a.DivisionId,
            Name = a.Name,
            TicketDate = a.TicketDate,
            NewPosts = a.NewPosts,
            Status = a.Status,
            Type = a.Type
         })
         .ToList().Select(x => new Ticket
         {
             Id = x.Id,
             DivisionId = x.DivisionId,
             Name = x.Name,
             TicketDate = x.TicketDate,
             NewPosts = x.NewPosts,
             Status = x.Status,
             Type = x.Type
          });

    return PartialView(tickets.ToList());
}

What i want to achieve is running this async, however if adding the ToListAsync()before Select()the Select() method becomes unavailable. The same goes for the return PartialView(tickets.ToList()).

I'm fairly new to working with async but reading about it's advantages I have been convering regular ActionResult methods with async ones. This has been going fine so far with easier LINQ-based queries. However for this ActionResult-method the query is a bit more advanced and the syntax/way to implement it seems to differ.

Any help to send me in the right direction would be greatly appreciated!

Body:
Split in into two statements:

var tickets0 = await (from ...).ToListAsync();

var tickets = tickets0.Select(...);

The .ToListAsync() returns a Task, so it doesn't accept the .Select extension method, which will need some IEnumerable. Only when you await that Task, you will get the List.

Another way (less readable IMO) would be:

 var tickets = (await (from ...).ToListAsync()).Select(...);

Note the extra ( ) around the await clause, which mean that the Select will work on the result of the awaited code, instead of the Task.


问:
How to bind a function to click event on an embed
I'm trying to bin a function to click event on an embed (flash file). But the problem is the support, so I'm looking for a cross-browser solution. The first thought was add the onclick attribute to the embed element but in Chrome (v. 59.0.3071.115) the click event is never fired, or the onclick is not working...

Code 1:

```<code><embed onclick='myFunction(myOpts)'
       class="item"
       src="/file.swf">

function myFunction(myOpts){
    console.log('is working!!!!');
}
</code>```

The above code is not working on Chrome. So, I was thinking in a new way to call this function on a click event: a parent div with the onclick attribute and fire the embed click with javascript (to play the Flash), this is the code:

Code 2:

```<code><embed onclick='myFunction(myOpts, event)'
       class="item"
       src="/file.swf">

function myFunction(myOpts, event){
    console.log('is working!!!!');
    event.target.getElementsByTagName('embed')[0].click();
}
</code>```

But the embed's click is never fired... So, my question:

Is there a way to call a function with the a click event on an embed? If the answer is yes, which is the best way to call a function without affecting his behavior?

答:
For those looking for an answer, this is what I did:

Now I use an object tag to show the Flash file instead of just the embed tag:

```<code><object id="objectId" classid="clsid:D27CDB6E-AE6D-11cf-96BB-444553540000"  onmouseup="myFunction(myOpts)"
      name="objectName" type="application/x-shockwave-flash" data="flash.swf" width="100%" height="100%">
      <param name="movie" value="flash.swf"/>
      <param name="quality" value="high"/>
      <param name="allowscriptaccess" value="always"/>
      <param name="wmode" value="transparent"/>
      <embed src="flash.swf" wmode="transparent" width="100%" height="100%" allowscriptaccess="always"
      allowfullscreen="true" name="embedName" id="embedId" data="flash.swf">
      </embed>
</object>
</code>```

And to call myFunction() without losing the behaviour of the Flash file I used onmouseup instead of onclick.

Body:
I'm trying to bin a function to click event on an embed (flash file). But the problem is the support, so I'm looking for a cross-browser solution. The first thought was add the onclick attribute to the embed element but in Chrome (v. 59.0.3071.115) the click event is never fired, or the onclick is not working...

Code 1:

<embed onclick='myFunction(myOpts)'
       class="item"
       src="/file.swf">

function myFunction(myOpts){
    console.log('is working!!!!');
}

The above code is not working on Chrome. So, I was thinking in a new way to call this function on a click event: a parent div with the onclick attribute and fire the embed click with javascript (to play the Flash), this is the code:

Code 2:

<embed onclick='myFunction(myOpts, event)'
       class="item"
       src="/file.swf">

function myFunction(myOpts, event){
    console.log('is working!!!!');
    event.target.getElementsByTagName('embed')[0].click();
}

But the embed's click is never fired... So, my question:

Is there a way to call a function with the a click event on an embed? If the answer is yes, which is the best way to call a function without affecting his behavior?

Body:
For those looking for an answer, this is what I did:

Now I use an object tag to show the Flash file instead of just the embed tag:

<object id="objectId" classid="clsid:D27CDB6E-AE6D-11cf-96BB-444553540000"  onmouseup="myFunction(myOpts)"
      name="objectName" type="application/x-shockwave-flash" data="flash.swf" width="100%" height="100%">
      <param name="movie" value="flash.swf"/>
      <param name="quality" value="high"/>
      <param name="allowscriptaccess" value="always"/>
      <param name="wmode" value="transparent"/>
      <embed src="flash.swf" wmode="transparent" width="100%" height="100%" allowscriptaccess="always"
      allowfullscreen="true" name="embedName" id="embedId" data="flash.swf">
      </embed>
</object>

And to call myFunction() without losing the behaviour of the Flash file I used onmouseup instead of onclick.


问:
Is there any way to speed-up python code for downloading tweets using tweepy?
Here is the code that i am using for the purpose .For each user request it's taking too long time to download all the tweets.What are some ways to speed up the execution time.The idea is to use tweet analytics in real time as the user visits the website.I am new to python so any help would be appreciated .</p>

```<code>import tweepy #https://github.com/tweepy/tweepy

#Twitter API credentials
consumer_key = ".."
consumer_secret = ".."
access_key = ".."
access_secret = ".."

def get_all_tweets(screen_name):
    #Twitter only allows access to a users most recent 3240 tweets with this method

    #authorize twitter, initialize tweepy
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_key, access_secret)
    api = tweepy.API(auth)

    #initialize a list to hold all the tweepy Tweets
    alltweets = []

    #make initial request for most recent tweets (200 is the maximum allowed count)
    new_tweets = api.user_timeline(screen_name = screen_name,count=200)

    #save most recent tweets
    alltweets.extend(new_tweets)

    #save the id of the oldest tweet less one
    oldest = alltweets[-1].id - 1

    #keep grabbing tweets until there are no tweets left to grab
    while len(new_tweets) > 0:
        print ("getting tweets before %s".format(oldest))

        #all subsiquent requests use the max_id param to prevent duplicates
        new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest)

        #save most recent tweets
        alltweets.extend(new_tweets)

        #update the id of the oldest tweet less one
        oldest = alltweets[-1].id - 1

        print ("...%s tweets downloaded so far".format(len(alltweets)))

    #transform the tweepy tweets into a 2D array that will populate the csv
    outtweets = [[tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")] for tweet in alltweets]
    return outtweets
</code>```

答:
One way to make your solution faster would be to make some cache.

When you've downloaded all the tweets for a screen name, save them locally, for instance as [twitter_screen_name].json

Then edit your function to check for your cache files. If it doesn't exist, create it empty. Then load it, refresh only what needs to, and save back your json cache file.

This way, when a user visits, you'll download only the diff with twitter. This will be much faster for the regularly consulted screen names.

Then you could add something for auto clearing the cache - a simple CRON that removes files with last-accessed META older than n days for instance.

Body:
Here is the code that i am using for the purpose .For each user request it's taking too long time to download all the tweets.What are some ways to speed up the execution time.The idea is to use tweet analytics in real time as the user visits the website.I am new to python so any help would be appreciated .

import tweepy #https://github.com/tweepy/tweepy

#Twitter API credentials
consumer_key = ".."
consumer_secret = ".."
access_key = ".."
access_secret = ".."

def get_all_tweets(screen_name):
    #Twitter only allows access to a users most recent 3240 tweets with this method

    #authorize twitter, initialize tweepy
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_key, access_secret)
    api = tweepy.API(auth)

    #initialize a list to hold all the tweepy Tweets
    alltweets = []

    #make initial request for most recent tweets (200 is the maximum allowed count)
    new_tweets = api.user_timeline(screen_name = screen_name,count=200)

    #save most recent tweets
    alltweets.extend(new_tweets)

    #save the id of the oldest tweet less one
    oldest = alltweets[-1].id - 1

    #keep grabbing tweets until there are no tweets left to grab
    while len(new_tweets) > 0:
        print ("getting tweets before %s".format(oldest))

        #all subsiquent requests use the max_id param to prevent duplicates
        new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest)

        #save most recent tweets
        alltweets.extend(new_tweets)

        #update the id of the oldest tweet less one
        oldest = alltweets[-1].id - 1

        print ("...%s tweets downloaded so far".format(len(alltweets)))

    #transform the tweepy tweets into a 2D array that will populate the csv
    outtweets = [[tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")] for tweet in alltweets]
    return outtweets


问:
HTML Input: Require URL to end in specific filetype
How can I make a URL Input form require the input to be both a valid URL, and end in a specific filetype.

For example, this is my input:

<input name="bg" placeholder="https://website.com/image" type="url">

As you can see, It is using the URL type, which restricts it to a valid http:// domain, but I would like the input field to only accept .png, .jpg, and .gif files.

Can this be achieved through html or javascript, and if so, how?

Thanks!

答:
Please go through the below code you will get the valid or invalid image url by blur the textbox.

function TextBoxChange()
{
var textboxValue=$("input[name=bg]").val();
var pattern=/https?:\/\/.*\.(?:png|jpg|gif)/i;
//alert(/https?:\/\/.*\.(?:png|jpg|gif)/i.test(textboxValue));
if(pattern.test(textboxValue))
{
$("#errorMsg").text("valid");
}
else
{
$("#errorMsg").text("invalid");
}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="bg" placeholder="https://website.com/image" onblur="TextBoxChange()" type="url" >
<label id="errorMsg"></label></code>```

Body:
Please go through the below code you will get the valid or invalid image url by blur the textbox.

function TextBoxChange()
{
var textboxValue=$("input[name=bg]").val();
var pattern=/https?:\/\/.*\.(?:png|jpg|gif)/i;
//alert(/https?:\/\/.*\.(?:png|jpg|gif)/i.test(textboxValue));
if(pattern.test(textboxValue))
{
$("#errorMsg").text("valid");
}
else
{
$("#errorMsg").text("invalid");
}
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="bg" placeholder="https://website.com/image" onblur="TextBoxChange()" type="url" >
<label id="errorMsg"></label>


问:
Binary coded decimal (BCD) to Hexadecimal conversion
can someone explain to me how to convert BCD to Hexadecimal? For example how can i convert 98(BCD) to Hexadecimal.
Thanks.</p>

答:
Go between different combinations of Hex, Decimal, and Binary.  If you know how binary works then you should easily be able to use BCD:

```<code>Hex  Dec  BCD
0    0    0000
1    1    0001
2    2    0010
3    3    0011
4    4    0100
5    5    0101
6    6    0110
7    7    0111
8    8    1000
9    9    1001
A   10    0001 0000 <-- notice that each digit looks like hex except it can only go to 9.
B   11    0001 0001
C   12    0001 0010
D   13    0001 0011
E   14    0001 0100
F   15    0001 0101
</code>```

Once you got this part of it down, you should be able to use divide by 10 or %10 to find any combination to generate your BCD.  Since it only uses 10 combinations instead of all 16 you will lose some information.

Body:
Go between different combinations of Hex, Decimal, and Binary.  If you know how binary works then you should easily be able to use BCD:

Hex  Dec  BCD
0    0    0000
1    1    0001
2    2    0010
3    3    0011
4    4    0100
5    5    0101
6    6    0110
7    7    0111
8    8    1000
9    9    1001
A   10    0001 0000 <-- notice that each digit looks like hex except it can only go to 9.
B   11    0001 0001
C   12    0001 0010
D   13    0001 0011
E   14    0001 0100
F   15    0001 0101

Once you got this part of it down, you should be able to use divide by 10 or %10 to find any combination to generate your BCD.  Since it only uses 10 combinations instead of all 16 you will lose some information.


问:
Odoo computed field Year from date_invoice
How can I extract only the year from a date field (x_date_invoice) to a new computed odoo field for example x_jaar

I am using Odoo 10.

答:
Hello Pelingier,

Basic Function of Python,

strptime()

Description
The method strptime() parses a string representing a time according to a format. The return value is a struct_time as returned by gmtime() or localtime().

The format parameter uses the same directives as those used by strftime(); it defaults to "%a %b %d %H:%M:%S %Y" which matches the formatting returned by ctime().

If string cannot be parsed according to format, or if it has excess data after parsing, ValueError is raised.

Syntax

Following is the syntax for strptime() method:

```<code>time.strptime(string[, format])
</code>```

Parameters

string -- This is the time in string format which would be parsed based on the given format.

format -- This is the directive which would be used to parse the given string.

strftime()

Description
The method strftime() converts a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument.

If t is not provided, the current time as returned by localtime() is used. format must be a string. An exception ValueError is raised if any field in t is outside of the allowed range.

Syntax

Following is the syntax for strftime() method:

```<code>time.strftime(format[, t])
</code>```

Parameters

t -- This is the time in number of seconds to be formatted.

format -- This is the directive which would be used to format given time. The following directives can be embedded in the format string:

==========================================================================

Your Question Solution

The first import library is from datetime import datetime after use all the functionality of the DateTime.

Try below code,

```<code>for record in self:
    record['x_jaar'] = str(datetime.strptime(record['x_date_invoice'],"%d/%m/%Y %H:%M:%S").strftime("%Y"))
</code>```

I hope my answer is helpful.

If any query so comments, please.

Body:
Hello Pelingier,

Basic Function of Python,

strptime()

Description
The method strptime() parses a string representing a time according to a format. The return value is a struct_time as returned by gmtime() or localtime().

The format parameter uses the same directives as those used by strftime(); it defaults to "%a %b %d %H:%M:%S %Y" which matches the formatting returned by ctime().

If string cannot be parsed according to format, or if it has excess data after parsing, ValueError is raised.

Syntax

Following is the syntax for strptime() method:

time.strptime(string[, format])

Parameters

string -- This is the time in string format which would be parsed based on the given format.

format -- This is the directive which would be used to parse the given string.

strftime()

Description
The method strftime() converts a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument.

If t is not provided, the current time as returned by localtime() is used. format must be a string. An exception ValueError is raised if any field in t is outside of the allowed range.

Syntax

Following is the syntax for strftime() method:

time.strftime(format[, t])

Parameters

t -- This is the time in number of seconds to be formatted.

format -- This is the directive which would be used to format given time. The following directives can be embedded in the format string:

==========================================================================

Your Question Solution

The first import library is from datetime import datetime after use all the functionality of the DateTime.

Try below code,

for record in self:
    record['x_jaar'] = str(datetime.strptime(record['x_date_invoice'],"%d/%m/%Y %H:%M:%S").strftime("%Y"))

I hope my answer is helpful.

If any query so comments, please.


问:
ActionBarCompat: java.lang.IllegalStateException: You need to use a Theme.AppCompat
I am getting a RuntimeException on Android 2.3.5 but I am using Theme.AppCompat (res/values/themes.xml). This is the phone: http://www.gsmarena.com/samsung_galaxy_y_s5360-4117.php

```<code> <!-- res/values/themes.xml -->
 <?xml version="1.0" encoding="utf-8"?>
 <resources>

     <style name="Theme.Styled" parent="@style/Theme.AppCompat">
         <item name="actionBarStyle">@style/QueryActionBar</item>
         <item name="android:actionBarStyle">@style/QueryActionBar</item>
     </style>

     <style name="QueryActionBar" parent="@style/Widget.AppCompat.ActionBar">
         <item name="background">@color/blueback</item>
         <item name="android:background">@color/blueback</item>
         <item name="backgroundSplit">@color/blueback</item>
         <item name="android:backgroundSplit">@color/blueback</item>
     </style>

 </resources>
</code>```

Here is the file for values-v11.

```<code> <!-- res/values-v11/themes.xml -->
 <?xml version="1.0" encoding="utf-8"?>
 <resources>
    <style name="QueryTheme" parent="@android:style/Theme.Holo">
    <!-- Any customizations for your app running on devices with Theme.Holo here -->
    </style>
 </resources>
</code>```

Here is the error.

```<code> java.lang.RuntimeException: Unable to start activity ComponentInfo{com.txt2lrn.www/com.txt2lrn.www.LandingActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
 at android.app.ActivityThread.access$1500(ActivityThread.java:117)
 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
 at android.os.Handler.dispatchMessage(Handler.java:99)
 at android.os.Looper.loop(Looper.java:130)
 at android.app.ActivityThread.main(ActivityThread.java:3687)
 at java.lang.reflect.Method.invokeNative(Native Method)
 at java.lang.reflect.Method.invoke(Method.java:507)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
 at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
 at android.support.v7.app.ActionBarActivityDelegate.onCreate(ActionBarActivityDelegate.java:102)
 at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:98)
 at com.txt2lrn.www.LandingActivity.onCreate(LandingActivity.java:95)
 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
 ... 11 more
</code>```

Sorry folks, I also do have android:theme="@style/Theme.Styled" defined in AndroidManifest.xml.

答:
For my list view am using custom Adapter which extends ArrayAdapter.
in listiview i have 2 buttons one of the buttons as Custom AlertDialogBox.
Ex:
Activity parentActivity;
Constructor for Adapter
`

```<code>public CustomAdapter(ArrayList<Contact> data, Activity parentActivity,Context context) {
        super(context,R.layout.listdummy,data);
        this.mContext   =   context;
        this.parentActivity  =   parentActivity;
    }
</code>```

`
calling Adapter from MainActivty

adapter = new CustomAdapter(dataModels,MainActivity.this,this);```
</div>
</div>
</p>

<p>now write ur alertdialog inside ur button which is in the Adapter class</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>viewHolder.update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View view) {

                AlertDialog.Builder alertDialog =   new AlertDialog.Builder(parentActivity);
                alertDialog.setTitle("Updating");
                alertDialog.setCancelable(false);

                LayoutInflater layoutInflater   = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                 @SuppressLint("InflateParams") final View view1   =   layoutInflater.inflate(R.layout.dialog,null);
                alertDialog.setView(view1);
                alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.cancel();
                    }
                });
                alertDialog.setPositiveButton("Update", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    //ur logic
                            }
                    }
                });
                  alertDialog.create().show();

            }
        });</code>```

Body:
I am getting a RuntimeException on Android 2.3.5 but I am using Theme.AppCompat (res/values/themes.xml). This is the phone: http://www.gsmarena.com/samsung_galaxy_y_s5360-4117.php

 <?xml version="1.0" encoding="utf-8"?>
 <resources>

 </resources>

Here is the file for values-v11.

 <?xml version="1.0" encoding="utf-8"?>
 <resources>

 </resources>

Here is the error.

 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.txt2lrn.www/com.txt2lrn.www.LandingActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
 at android.app.ActivityThread.access$1500(ActivityThread.java:117)
 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
 at android.os.Handler.dispatchMessage(Handler.java:99)
 at android.os.Looper.loop(Looper.java:130)
 at android.app.ActivityThread.main(ActivityThread.java:3687)
 at java.lang.reflect.Method.invokeNative(Native Method)
 at java.lang.reflect.Method.invoke(Method.java:507)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
 at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
 at android.support.v7.app.ActionBarActivityDelegate.onCreate(ActionBarActivityDelegate.java:102)
 at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:98)
 at com.txt2lrn.www.LandingActivity.onCreate(LandingActivity.java:95)
 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
 ... 11 more

Sorry folks, I also do have android:theme="@style/Theme.Styled" defined in AndroidManifest.xml.

Body:
For my list view am using custom Adapter which extends ArrayAdapter.
in listiview i have 2 buttons one of the buttons as Custom AlertDialogBox.
Ex:
Activity parentActivity;
Constructor for Adapter
`

public CustomAdapter(ArrayList<Contact> data, Activity parentActivity,Context context) {
        super(context,R.layout.listdummy,data);
        this.mContext   =   context;
        this.parentActivity  =   parentActivity;
    }

`
calling Adapter from MainActivty

adapter = new CustomAdapter(dataModels,MainActivity.this,this);

now write ur alertdialog inside ur button which is in the Adapter class

viewHolder.update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View view) {

                AlertDialog.Builder alertDialog =   new AlertDialog.Builder(parentActivity);
                alertDialog.setTitle("Updating");
                alertDialog.setCancelable(false);

                LayoutInflater layoutInflater   = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                 @SuppressLint("InflateParams") final View view1   =   layoutInflater.inflate(R.layout.dialog,null);
                alertDialog.setView(view1);
                alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.cancel();
                    }
                });
                alertDialog.setPositiveButton("Update", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    //ur logic
                            }
                    }
                });
                  alertDialog.create().show();

            }
        });


问:
HttpWebResponse hangs/freezes when running in a WebAPI
I am using a C# WebAPI project which would call an external API based on its URL. However, when I am trying to retrieve the data back, it hangs/freezes.

The code where it stops is:

```<code>var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
</code>```

I don't understand why it is stopping though. Could it be interfering with the API request I am also making? When I run this code as part of a unit test, I would get a response back within seconds. I don't think it is the API service itself, I think it is my code. I have already tried various API URLS. None of them work.

My full code is:

```<code>public static async Task<string> CallWebAPi<T>(string url)
{
    string returnValue;

    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    request.ContentType = "application/json";
    request.Method = "GET";

    var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);

    Stream stream = response.GetResponseStream();
    StreamReader strReader = new StreamReader(stream);
    returnValue = await strReader.ReadToEndAsync();

    return returnValue;
}
</code>```

Any help would be appreciated.

答:
you dont need Task.Factory.FromAsync. HttpWebRequest already supports asynchronous operations.

You have defined a generic method CalWebApi<T> but have never used a generic type

if your operation is async, use this.

```<code>    public async Task<T> CalWebApiAsync<T>(string url)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.ContentType = "application/json";
        request.Method = "GET";
        using (var response = await request.GetResponseAsync())
        {
            using (var responseStream = response.GetResponseStream())
            {
                using (var streamReader = new StreamReader(responseStream))
                {
                    var stringResult = await streamReader.ReadToEndAsync();
                    T objectResult = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(stringResult);
                    return objectResult;
                }
            }
        }
    }
</code>```

var result = await CallWebApiAsync<YourType>("exteranlapiurl");

if your operation is not async, use this..

```<code>     public T CalWebApi<T>(string url)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.ContentType = "application/json";
        request.Method = "GET";
        using (var response = request.GetResponse())
        {
            using (var responseStream = response.GetResponseStream())
            {
                using (var streamReader = new StreamReader(responseStream))
                {
                    var stringResult = streamReader.ReadToEnd();
                    T objectResult = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(stringResult);
                    return objectResult;
                }
            }
        }
    }
</code>```

var result = CallWebApi<YourType>("exteranlapiurl");

Body:
I am using a C# WebAPI project which would call an external API based on its URL. However, when I am trying to retrieve the data back, it hangs/freezes.

The code where it stops is:

var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);

I don't understand why it is stopping though. Could it be interfering with the API request I am also making? When I run this code as part of a unit test, I would get a response back within seconds. I don't think it is the API service itself, I think it is my code. I have already tried various API URLS. None of them work.

My full code is:

public static async Task<string> CallWebAPi<T>(string url)
{
    string returnValue;

    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    request.ContentType = "application/json";
    request.Method = "GET";

    var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);

    Stream stream = response.GetResponseStream();
    StreamReader strReader = new StreamReader(stream);
    returnValue = await strReader.ReadToEndAsync();

    return returnValue;
}

Any help would be appreciated.

Body:
you dont need Task.Factory.FromAsync. HttpWebRequest already supports asynchronous operations.

You have defined a generic method CalWebApi<T> but have never used a generic type

if your operation is async, use this.

    public async Task<T> CalWebApiAsync<T>(string url)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.ContentType = "application/json";
        request.Method = "GET";
        using (var response = await request.GetResponseAsync())
        {
            using (var responseStream = response.GetResponseStream())
            {
                using (var streamReader = new StreamReader(responseStream))
                {
                    var stringResult = await streamReader.ReadToEndAsync();
                    T objectResult = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(stringResult);
                    return objectResult;
                }
            }
        }
    }

var result = await CallWebApiAsync<YourType>("exteranlapiurl");

if your operation is not async, use this..

     public T CalWebApi<T>(string url)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.ContentType = "application/json";
        request.Method = "GET";
        using (var response = request.GetResponse())
        {
            using (var responseStream = response.GetResponseStream())
            {
                using (var streamReader = new StreamReader(responseStream))
                {
                    var stringResult = streamReader.ReadToEnd();
                    T objectResult = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(stringResult);
                    return objectResult;
                }
            }
        }
    }

var result = CallWebApi<YourType>("exteranlapiurl");


问:
Transform instance method to abstract method when overriding
I've read in the Java SE Specification the following and did not fully understand it: link

If, for example, a class declares two public methods with the same name , and a subclass overrides one of them, the subclass still inherits the other method.

And

If the method not inherited is declared in a class, or the method not inherited is declared in an interface and the new declaration is abstract, then the new declaration is said to override it.

Doesn't it match this situation ?

```<code>public class Parent{

    public void method(){
        System.out.println("Call inside parent class");
    }
}
</code>```

and

```<code>public abstract class Child extends Parent{

    public abstract void method();
}
</code>```

Can you please clarify ? Is this an overriding ?

答:
The two sentences aren't particularly related: the first is just giving an example for previous sentence.

This situation matches the second sentences, but not the first, so this would be an example of overriding as opposed to implementing or hiding.

An example for the first sentences would be

```<code>public class Parent {
    public void method() {
        System.out.println("Call inside parent class");
    }

    public void method(int i) {
        System.out.println("Call method(int) inside parent class");
    }
}

public class Child extends Parent{
    public void method() {
    }
}
</code>```

Here, Child overrides method() and inherits method(int i), so if you call new Child().method(0), the string will get printed.

Body:
I've read in the Java SE Specification the following and did not fully understand it: link

If, for example, a class declares two public methods with the same name , and a subclass overrides one of them, the subclass still inherits the other method.

And

If the method not inherited is declared in a class, or the method not inherited is declared in an interface and the new declaration is abstract, then the new declaration is said to override it.

Doesn't it match this situation ?

public class Parent{

    public void method(){
        System.out.println("Call inside parent class");
    }
}

and

public abstract class Child extends Parent{

    public abstract void method();
}

Can you please clarify ? Is this an overriding ?

Body:
The two sentences aren't particularly related: the first is just giving an example for previous sentence.

This situation matches the second sentences, but not the first, so this would be an example of overriding as opposed to implementing or hiding.

An example for the first sentences would be

public class Parent {
    public void method() {
        System.out.println("Call inside parent class");
    }

    public void method(int i) {
        System.out.println("Call method(int) inside parent class");
    }
}

public class Child extends Parent{
    public void method() {
    }
}

Here, Child overrides method() and inherits method(int i), so if you call new Child().method(0), the string will get printed.


问:
Cannot read functions from external javascript file used by html file
I have an index.html file:

```<code><head>
    <title>Jiggle Into JavaScript</title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>

    <p>Press the buttons to change the box!</p>

    <div id="box" style="height:150px; width:150px; background-color:darkorange; margin:25px"></div>

    <button type="button1" onclick="growFunc()">Grow</button>
    <button type="button2" onclick="blueFunc()">Blue</button>
    <button type="button3" onclick="fadeFunc()">Fade</button>
    <button type="button4" onclick="resetFunc()">Reset</button>
    <script type="text/javascript" src="javascript.js"></script>
</body>
</code>```

My javascript.js file looks like this:

```<code>function growFunc() {
    document.getElementById("button1").addEventListener("click",
        function(){document.getElementById("box").style.height = "250px";
    });
}

function blueFunc() {
    document.getElementById("button2").addEventListener("click",
      function(){document.getElementById("box").style.backgroundColor = "blue";
    });
}

function fadeFunc() {

    document.getElementById("button3").addEventListener("click", function(){

        document.getElementById("box").style.backgroundColor = "orange";

    });

}

function resetFunc() {
    document.getElementById("button4").addEventListener("click",
       function(){
        document.getElementById("box").style.height = "150px";
        document.getElementById("box").style.backgroundColor = "darkorange";
       });
}
</code>```

Both files are in the same directory. When I try to run index.html in Firefox, for example, nothing happens when I click on the buttons. But if I have the functions all in the index.html file(see below), it works. I can't seem to find what's wrong with my code(I'm new at this). Thank you for your help.

```<code><head>
<title>Jiggle Into JavaScript</title>
</code>```

```<code><p>Press the buttons to move the box!</p>

<div id="box" style="height:150px; width:150px; background-color:darkorange; margin:25px"></div>

<button id="growBtn">Grow</button>
<button id="blueBtn">Blue</button>
<button id="fadeBtn">Fade</button>
<button id="resetBtn">Reset</button>

<script type="text/javascript">

    document.getElementById("growBtn").addEventListener("click", function(){
        document.getElementById("box").style.height = "250px";
    });

    document.getElementById("blueBtn").addEventListener("click", function(){
         document.getElementById("box").style.backgroundColor = "blue";
    });

    document.getElementById("fadeBtn").addEventListener("click", function(){
        document.getElementById("box").style.backgroundColor = "orange";
    });

    document.getElementById("resetBtn").addEventListener("click", function()
        document.getElementById("box").style.height = "150px";
        document.getElementById("box").style.backgroundColor = "darkorange";
    });
</script>

</body>
</code>```

答:
You are binding event handler in the inline click handler, thus its having no effect when you click once.

In your javascript file use DOMContentLoaded event to wait for DOM to be loaded completely then bind event handlers

```<code>document.addEventListener("DOMContentLoaded", function(event) {
    //Bind event handlers
    document.getElementById("button1").addEventListener("click", function(){
        .....
    });
});
</code>```

And Get rid of ugly inline event handlers.

Body:
I have an index.html file:

    <title>Jiggle Into JavaScript</title>

Press the buttons to change the box!

    <button type="button1" onclick="growFunc()">Grow</button>
    <button type="button2" onclick="blueFunc()">Blue</button>
    <button type="button3" onclick="fadeFunc()">Fade</button>
    <button type="button4" onclick="resetFunc()">Reset</button>

My javascript.js file looks like this:

function growFunc() {
    document.getElementById("button1").addEventListener("click",
        function(){document.getElementById("box").style.height = "250px";
    });
}

function blueFunc() {
    document.getElementById("button2").addEventListener("click",
      function(){document.getElementById("box").style.backgroundColor = "blue";
    });
}

function fadeFunc() {

    document.getElementById("button3").addEventListener("click", function(){

        document.getElementById("box").style.backgroundColor = "orange";

    });

}

function resetFunc() {
    document.getElementById("button4").addEventListener("click",
       function(){
        document.getElementById("box").style.height = "150px";
        document.getElementById("box").style.backgroundColor = "darkorange";
       });
}

Both files are in the same directory. When I try to run index.html in Firefox, for example, nothing happens when I click on the buttons. But if I have the functions all in the index.html file(see below), it works. I can't seem to find what's wrong with my code(I'm new at this). Thank you for your help.

<title>Jiggle Into JavaScript</title>

Press the buttons to move the box!

<button id="growBtn">Grow</button>
<button id="blueBtn">Blue</button>
<button id="fadeBtn">Fade</button>
<button id="resetBtn">Reset</button>

Body:
You are binding event handler in the inline click handler, thus its having no effect when you click once.

In your javascript file use DOMContentLoaded event to wait for DOM to be loaded completely then bind event handlers

document.addEventListener("DOMContentLoaded", function(event) {
    //Bind event handlers
    document.getElementById("button1").addEventListener("click", function(){
        .....
    });
});

And Get rid of ugly inline event handlers.


答:
This is how i do my Request. Each Part is in an own Function. Its create the Request and you can get the Response synchronous.

public HttpWebRequest CreateRequest(string Url, string Method, string ContentType, object Content, List<RequestHeader> headers)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);

    request.Method = Method;

    if (!string.IsNullOrWhiteSpace(ContentType)) request.ContentType = ContentType;
    else if(Content != null) request.ContentType = "application/json";

    if (Content != null)
    {
        var postData = Newtonsoft.Json.JsonConvert.SerializeObject(Content);
        var data = Encoding.ASCII.GetBytes(postData);
        request.ContentLength = data.Length;
        using (var stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }
    }

    foreach(RequestHeader header in Headers)
    {
        request.Headers.Add(header.Type, header.Value);
    } //class at the end.

    return request;
}

public string GetResponse(HttpWebRequest request)
{
    var retval = "";
    try
    {
        var response = (HttpWebResponse)request.GetResponse();
        retval = ReadResponse(response);
        response.Close();
    }
    catch (Exception ex)
    {
        resolveException(ex.Message);
    }
    return retval;
}

public string ReadResponse(HttpWebResponse response)
{
    var retval = "";
    try
    {
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            var responseText = reader.ReadToEnd();
            retval = responseText;
        }
    }
    catch (Exception ex)
    {
        resolveException(ex.Message);
    }

    return retval;
}

public class RequestHeader
{
    public HttpRequestHeader Type { get; set; }
    public string Value { get; set; }
}```

Title: HttpWebResponse hangs/freezes when running in a WebAPI


问:
Tracking "Windows Search" Queries
I can enable logging for Windows Search through the registry (see below), but this only captures queries sent through the default user-interface for Windows Search. I want to capture queries used by Outlook 2003, Outlook 2007, OneNote 2007 or any other application that accesses the SystemIndex.

```<code>HKEY_CURRENT_USER\Software\Microsoft\Windows Desktop Search\DS\WriteLog[DWORD]0|1
</code>```

What I want to do is analyze these queries in order get a better understanding on how to build queries for my personal search utility (WinForms/WPF/ADO.NET/OleDb) that I use to search my code library (physical file system).

How would I track any and all queries performed on the SystemIndex of Windows Search?

答:
I believe the answer is here, but have not had time to try it out.

Troubleshooting Windows DAC/MDAC
http://msdn.microsoft.com/en-us/library/ms693114(VS.85).aspx

Data Access Tracing in SQL Server 2008
http://msdn.microsoft.com/en-us/library/cc765421.aspx

Title: Tracking "Windows Search" Queries

Body:
I can enable logging for Windows Search through the registry (see below), but this only captures queries sent through the default user-interface for Windows Search. I want to capture queries used by Outlook 2003, Outlook 2007, OneNote 2007 or any other application that accesses the SystemIndex.

HKEY_CURRENT_USER\Software\Microsoft\Windows Desktop Search\DS\WriteLog[DWORD]0|1

What I want to do is analyze these queries in order get a better understanding on how to build queries for my personal search utility (WinForms/WPF/ADO.NET/OleDb) that I use to search my code library (physical file system).

How would I track any and all queries performed on the SystemIndex of Windows Search?


答:
You will need to await the query before calling select, but given that the query is simply selecting a model out of the query you can create the model within the query and just await that.</p>

```<code>public async Task<ActionResult> NewTickets()
{
    // Show tickets for all divisions a agent is in

    var user = "abcdefg";
    var company = "company1";

    var tickets = await (from a in db2.Ticket
        join c in db2.Division on a.DivisionId equals c.DivisionId
        join dp in db2.DivisionParticipator on c.DivisionId equals dp.DivisionId
        where c.CompanyId == company.CompanyId && a.Status == "New" && dp.ApplicationUserId == user.Id
        select new Ticket
        {
            Id = a.Id,
            DivisionId = a.DivisionId,
            Name = a.Name,
            TicketDate = a.TicketDate,
            NewPosts = a.NewPosts,
            Status = a.Status,
            Type = a.Type
         })
         .ToListAsync();

    return PartialView(tickets);
}
</code>```

Title: Entity Framework ToListAsync() with Select()

Body:
I have the following ActionResult in my controller

public async Task<ActionResult> NewTickets()
{
    // Show tickets for all divisions a agent is in

    var user = "abcdefg";
    var company = "company1";

    var tickets = (from a in db2.Ticket
        join c in db2.Division on a.DivisionId equals c.DivisionId
        join dp in db2.DivisionParticipator on c.DivisionId equals dp.DivisionId
        where c.CompanyId == company.CompanyId && a.Status == "New" && dp.ApplicationUserId == user.Id
        select new
        {
            Id = a.Id,
            DivisionId = a.DivisionId,
            Name = a.Name,
            TicketDate = a.TicketDate,
            NewPosts = a.NewPosts,
            Status = a.Status,
            Type = a.Type
         })
         .ToList().Select(x => new Ticket
         {
             Id = x.Id,
             DivisionId = x.DivisionId,
             Name = x.Name,
             TicketDate = x.TicketDate,
             NewPosts = x.NewPosts,
             Status = x.Status,
             Type = x.Type
          });

    return PartialView(tickets.ToList());
}

What i want to achieve is running this async, however if adding the ToListAsync()before Select()the Select() method becomes unavailable. The same goes for the return PartialView(tickets.ToList()).

I'm fairly new to working with async but reading about it's advantages I have been convering regular ActionResult methods with async ones. This has been going fine so far with easier LINQ-based queries. However for this ActionResult-method the query is a bit more advanced and the syntax/way to implement it seems to differ.

Any help to send me in the right direction would be greatly appreciated!

Body:
You will need to await the query before calling select, but given that the query is simply selecting a model out of the query you can create the model within the query and just await that.

public async Task<ActionResult> NewTickets()
{
    // Show tickets for all divisions a agent is in

    var user = "abcdefg";
    var company = "company1";

    var tickets = await (from a in db2.Ticket
        join c in db2.Division on a.DivisionId equals c.DivisionId
        join dp in db2.DivisionParticipator on c.DivisionId equals dp.DivisionId
        where c.CompanyId == company.CompanyId && a.Status == "New" && dp.ApplicationUserId == user.Id
        select new Ticket
        {
            Id = a.Id,
            DivisionId = a.DivisionId,
            Name = a.Name,
            TicketDate = a.TicketDate,
            NewPosts = a.NewPosts,
            Status = a.Status,
            Type = a.Type
         })
         .ToListAsync();

    return PartialView(tickets);
}


问:
Create stored procedure in DocumentDB Emulator
Update:  I downloaded the emulator again and did a repair and the options show up again.  Resolved.

can anyone please tell me if it is possible to create stored procedures in DocumentDB emulator?  I know I can do it in the real DocumentDB on Azure.  However, I can't seem to be able to find the script panel anywhere in the emulator.  I google around and I can't find any answer either. According to the website, I should be able to create stored procs using the emulator.  Very strange.

答: You can create Stored procedures, User Defined Functions & Triggers from the Cosmos DB Emulator UI. Just click on the ... dots that appear when you hover over the collection to open the context menu or right click over it.


问:
Trigger needs to fire only when column value is today's date
I want to apply the trigger in database when column_value match the particular scenario like

In goal table there are fields like goal, status, start_Date, end_Date

Now I want to change the status of goal. When user enter his/her goal, he/she filled end_Date. Now I want to change the status of goal when end_Date matched to current Date

Example:-

```<code>+------+--------+--------------+-------------+
| GOAL | STATUS | START_DATE   | END_DATE    |
+------+--------+--------------+-------------+
|    1 | Active | 2017-07-03   | 2017-07-09  |
+------+--------+------------+---------------+
</code>```

When END_DATE equals to current Date, then I want to change status 'Active' to 'Finished'

I hope I am able to understand my question.

Thanks in advance!

答:
The logic for this is </p>

```<code>DROP TRIGGER IF EXISTS TB;
DELIMITER //
CREATE TRIGGER TB BEFORE INSERT ON T
FOR EACH ROW
BEGIN

 IF NEW.START_DT = DATE(NOW()) THEN
    SET NEW.STATUS = 'YES' ;
 end if;
END //
DELIMITER ;

  use sandbox;
DROP TABLE IF EXISTS T;
CREATE TABLE T(GOAL INT, STATUS VARCHAR(3), START_DT DATE,END_DATE DATE);
mysql> TRUNCATE TABLE T;INSERT INTO T VALUES(1,NULL,'2017-07-06','2017-07-06');SELECT * FROM T;
Query OK, 0 rows affected (0.73 sec)

Query OK, 1 row affected (0.06 sec)

+------+--------+------------+------------+
| GOAL | STATUS | START_DT   | END_DATE   |
+------+--------+------------+------------+
|    1 | YES    | 2017-07-06 | 2017-07-06 |
+------+--------+------------+------------+
1 row in set (0.00 sec)
</code>```

Body:
I want to apply the trigger in database when column_value match the particular scenario like

In goal table there are fields like goal, status, start_Date, end_Date

Now I want to change the status of goal. When user enter his/her goal, he/she filled end_Date. Now I want to change the status of goal when end_Date matched to current Date

Example:-

+------+--------+--------------+-------------+
| GOAL | STATUS | START_DATE   | END_DATE    |
+------+--------+--------------+-------------+
|    1 | Active | 2017-07-03   | 2017-07-09  |
+------+--------+------------+---------------+

When END_DATE equals to current Date, then I want to change status 'Active' to 'Finished'

I hope I am able to understand my question.

Thanks in advance!

Body:
The logic for this is

DROP TRIGGER IF EXISTS TB;
DELIMITER //
CREATE TRIGGER TB BEFORE INSERT ON T
FOR EACH ROW
BEGIN

 IF NEW.START_DT = DATE(NOW()) THEN
    SET NEW.STATUS = 'YES' ;
 end if;
END //
DELIMITER ;

  use sandbox;
DROP TABLE IF EXISTS T;
CREATE TABLE T(GOAL INT, STATUS VARCHAR(3), START_DT DATE,END_DATE DATE);
mysql> TRUNCATE TABLE T;INSERT INTO T VALUES(1,NULL,'2017-07-06','2017-07-06');SELECT * FROM T;
Query OK, 0 rows affected (0.73 sec)

Query OK, 1 row affected (0.06 sec)

+------+--------+------------+------------+
| GOAL | STATUS | START_DT   | END_DATE   |
+------+--------+------------+------------+
|    1 | YES    | 2017-07-06 | 2017-07-06 |
+------+--------+------------+------------+
1 row in set (0.00 sec)


问:
How to loop through csv cells in R?
I have two datasets in R as you can see below, Dataset 1 and Dataset 2. Consider the column 'company' in Dataset 1. I want to iterate through every row in Dataset 2 to find if that company exists, and if it does, then copy the format from Dataset 2 into Dataset 1 format field (currently NA). Thanks.

Dataset 1

Dataset 2

dataset1_updated after implementing Miff's solution

答:
You want to join these two datasets together. data.table is really good at this.

```<code>library(data.table)

setDT(dataset1)
setDT(dataset2)

setkey(dataset1, company)
setkey(dataset2, company)

dataset2[dataset1[, .(fname, lname, email, company)]]
</code>```

Left joins

Left outer join

The result of a left outer join (or simply left
  join) for tables A and B always contains all rows of the "left" table
  (A), even if the join-condition does not find any matching row in the
  "right" table (B). This means that if the ON clause matches 0 (zero)
  rows in B (for a given row in A), the join will still return a row in
  the result (for that row)—but with NULL in each column from B. A left
  outer join returns all the values from an inner join plus all values
  in the left table that do not match to the right table, including rows
  with NULL (empty) values in the link column.

Wikipedia.

Here we are left joining dataset2 on dataset1. We keep all rows from dataset1, and join dataset2 if company from dataset1 matches company from dataset2. If it matches, we keep dataset2's row and add it, including the format field. If it doesn't match, we get NA.

Title: How to loop through csv cells in R?

Body:
You want to join these two datasets together. data.table is really good at this.

library(data.table)

setDT(dataset1)
setDT(dataset2)

setkey(dataset1, company)
setkey(dataset2, company)

dataset2[dataset1[, .(fname, lname, email, company)]]

Left joins

Left outer join

The result of a left outer join (or simply left
  join) for tables A and B always contains all rows of the "left" table
  (A), even if the join-condition does not find any matching row in the
  "right" table (B). This means that if the ON clause matches 0 (zero)
  rows in B (for a given row in A), the join will still return a row in
  the result (for that row)—but with NULL in each column from B. A left
  outer join returns all the values from an inner join plus all values
  in the left table that do not match to the right table, including rows
  with NULL (empty) values in the link column.

Wikipedia.

Here we are left joining dataset2 on dataset1. We keep all rows from dataset1, and join dataset2 if company from dataset1 matches company from dataset2. If it matches, we keep dataset2's row and add it, including the format field. If it doesn't match, we get NA.


问:
Display loader before whole page gets load
Code is simple but page gets load along with loader.</p>

```<code><script>
$(window).load(function() {
$(".loader").delay(2000).fadeOut("slow");
})
</script>

<body>
<header>
<div class="loader"><img src="img/loader.gif"></div>
</header>
</body>
</code>```

答:
Prefer using document.ready like below.

$(document).ready(function() {
$(".loader").delay(2000).fadeOut("slow");
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <script  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
 <header><div class="loader"><img src="img/loader.gif" alt="loading............."/></div> </header></code>```

Body:
Prefer using document.ready like below.

$(document).ready(function() {
$(".loader").delay(2000).fadeOut("slow");
})

 <script  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
 <header><div class="loader"><img src="img/loader.gif" alt="loading............."/></div> </header>


问:
Compress Png Files missing from build settings
I am building an app which has quite a few images in, therefore I have crushed them all using ImageOptim to help decrease the size of my .IPA. How ever the size of my app has not changed at all.

I have looked on their website and they say to turn off Compress Png Files in the Build Settings under Packaging. However that option is not there. I have tried manually adding it into my project.pbxproj but it gets listed under the User Defined section and does not turn it off.

I have also tried searching in the Build settings (My main target is selected).

So my question is... how can I add Compress Png Files into my build settings?

答: If you change the format of the file to png, the error shows up all the time for the assets when you try to use it. It's better to find the original png file or save the file as a png file with an image editor. </p>


问:
Is there a way to clear the variables read using source < (grep = ...)?
It's possible to read variables from the .ini file with source <(grep = test.ini):

```<code>$ cat test.ini
[head]
  shoulders=/hahaha/
  knees=/lololol/
  toes=/kekeke/

$ source <(grep = test.ini)

$ echo $shoulders
/hahaha/

$ echo $knees
/lololol/

$ echo $toes
/kekeke/
</code>```

I can manually clear variables read from the source <(grep = ...) command, e.g.

```<code>$ unset toes
$ echo toes
</code>```

But is there a way to automatically track which variables are added from the source command and unset them all together?

答:
Typically, this sort of thing is terribly unreliable.  But you could do something like:

```<code>set | grep -v ^_ > /tmp/original-vars  # record variables
source <(grep = test.ini)              # read from init file

# now, compare current variables assigned with the original and unset
# those that were not originally assigned while attempting
# to mask out some common internal variables that bash sets but making
# no claims at robustness or safety:
set | grep -v ^_ | diff -u - /tmp/original-vars \
  | awk '/^-/ && NR>1{print $2}' FS=[=-] \
  | while read var; do unset $var; done
</code>```

YMMV, reader beware, etc.

Body:
It's possible to read variables from the .ini file with source <(grep = test.ini):

$ cat test.ini
[head]
  shoulders=/hahaha/
  knees=/lololol/
  toes=/kekeke/

$ source <(grep = test.ini)

$ echo $shoulders
/hahaha/

$ echo $knees
/lololol/

$ echo $toes
/kekeke/

I can manually clear variables read from the source <(grep = ...) command, e.g.

$ unset toes
$ echo toes

But is there a way to automatically track which variables are added from the source command and unset them all together?

Body:
Typically, this sort of thing is terribly unreliable.  But you could do something like:

set | grep -v ^_ > /tmp/original-vars  # record variables
source <(grep = test.ini)              # read from init file

# now, compare current variables assigned with the original and unset
# those that were not originally assigned while attempting
# to mask out some common internal variables that bash sets but making
# no claims at robustness or safety:
set | grep -v ^_ | diff -u - /tmp/original-vars \
  | awk '/^-/ && NR>1{print $2}' FS=[=-] \
  | while read var; do unset $var; done

YMMV, reader beware, etc.


问:
Test for expected failure in Mocha
Using Mocha, I am attempting to test whether a constructor throws an error. I haven't been able to do this using the expect syntax, so I'd like to do the following:

```<code>it('should throw exception when instantiated', function() {
  try {
    new ErrorThrowingObject();
    // Force the test to fail since error wasn't thrown
  }
  catch (error) {
   // Constructor threw Error, so test succeeded.
  }
}
</code>```

Is this possible?

答:
2017 answer if you need to do this with async code: using await and not needing any other libraries.

```<code>it('Returns a correct error response when making a broken order', async function(){
  this.timeout(5 * 1000);
  var badOrder = {}
  try {
    var result = await foo.newOrder(badOrder)
    // The line will only be hit if no error is thrown above!
    throw new Error(`Expected an error and didn't get one!`)
  } catch(err) {
    var expected = `Missing required field`
    assert.equal(err.message, expected)
  }
});
</code>```

Note the poster was only doing sync code, but I expect a lot of people using async were led here by the question title!

Title: Test for expected failure in Mocha

Body:
Using Mocha, I am attempting to test whether a constructor throws an error. I haven't been able to do this using the expect syntax, so I'd like to do the following:

it('should throw exception when instantiated', function() {
  try {
    new ErrorThrowingObject();
    // Force the test to fail since error wasn't thrown
  }
  catch (error) {
   // Constructor threw Error, so test succeeded.
  }
}

Is this possible?

Body:
2017 answer if you need to do this with async code: using await and not needing any other libraries.

it('Returns a correct error response when making a broken order', async function(){
  this.timeout(5 * 1000);
  var badOrder = {}
  try {
    var result = await foo.newOrder(badOrder)
    // The line will only be hit if no error is thrown above!
    throw new Error(`Expected an error and didn't get one!`)
  } catch(err) {
    var expected = `Missing required field`
    assert.equal(err.message, expected)
  }
});

Note the poster was only doing sync code, but I expect a lot of people using async were led here by the question title!

ContentLicense: CC BY-SA 4.0


问:
Why aren't options being overridden?
In my module pattern, options are 'undefined' for some reason.. does anyone see why they aren't being passed in properly?

```<code>Framework.MyModule = (function(options) {
    var defaults = {
        someOption : 1,
        stuff      : 2
    };
    if (!options) {
        var options = defaults;
    } else {
        for (var index in defaults) {
            if (typeof options[index] == 'undefined')
                options[index] = defaults[index];
        }
    }
    var module = {};

    // Initialize
    _something();

    // Private Methods
    function _something() {}

    // Public Methods
    module.click = function() {};

    return module;
})();

... docready function ...

var options = {
  someOption : 9,
  stuff      : 10
};

Framework.MyModule(options);

... end doc ready ...
</code>```

Please see the fiddle: http://jsfiddle.net/kWHEZ/1/

答:
You're not passing in any options to the anonymous function call.

your call would have to end with })(options); if you want it to use custom options.

Title: Why aren't options being overridden?

Body:
In my module pattern, options are 'undefined' for some reason.. does anyone see why they aren't being passed in properly?

Framework.MyModule = (function(options) {
    var defaults = {
        someOption : 1,
        stuff      : 2
    };
    if (!options) {
        var options = defaults;
    } else {
        for (var index in defaults) {
            if (typeof options[index] == 'undefined')
                options[index] = defaults[index];
        }
    }
    var module = {};

    // Initialize
    _something();

    // Private Methods
    function _something() {}

    // Public Methods
    module.click = function() {};

    return module;
})();

... docready function ...

var options = {
  someOption : 9,
  stuff      : 10
};

Framework.MyModule(options);

... end doc ready ...

Please see the fiddle: http://jsfiddle.net/kWHEZ/1/


问:
What is the difference between a "function" and a "procedure"?
Generally speaking, we all hear about the functions or procedures in programming languages. However, I just found out that I use these terms almost interchangeably (which is probably very wrong).

So, my question is:

What is the difference in terms of their functionality, their purpose and use?

An example would be appreciated.

答:
In terms of С#/Java, function is the block of code, which return particular value, but procedure is the block of code which return void (nothing). In C#/Java both functions and procedures more often called just methods.

```<code>    //This is a function
    public DateTime GetCurrentDate()
    {
        return DateTime.Now.Date;
    }

    //This is a procedure(always return void)
    public void LogMessage()
    {
        Console.WriteLine("Just an example message.");
    }
</code>```

Body:
In terms of С#/Java, function is the block of code, which return particular value, but procedure is the block of code which return void (nothing). In C#/Java both functions and procedures more often called just methods.

    //This is a function
    public DateTime GetCurrentDate()
    {
        return DateTime.Now.Date;
    }

    //This is a procedure(always return void)
    public void LogMessage()
    {
        Console.WriteLine("Just an example message.");
    }


问:
How to save a trained tensorflow model for later use for application?
I am a bit of a beginner with tensorflow so please excuse if this is a stupid question and the answer is obvious.

I have created a Tensorflow graph where starting with placeholders for X and y I have optimized some tensors which represent my model. Part of the graph is something where a vector of predictions can be calculated, e.g. for linear regression something like

y_model = tf.add(tf.mul(X,w),d)
y_vals = sess.run(y_model,feed_dict={....})
```

<p>After training has been completed I have acceptable values for w and d and now I want to save my model for later. Then, in a different python session I want to restore the model so that I can again run</p>

<pre class="lang-py prettyprint-override"><code>## Starting brand new python session
import tensorflow as tf
## somehow restor the graph and the values here: how????
## so that I can run this:
y_vals = sess.run(y_model,feed_dict={....})
</code>```

for some different data and get back the y-values.

I want this to work in a way where the graph for calculating the y-values from the placeholders is also stored and restored - as long as the placeholders get fed the correct data, this should work transparently without the user (the one who applies the model) needing to know what the graph looks like).

As far as I understand tf.train.Saver().save(..) only saves the variables but I also want to save the graph. I think that tf.train.export_meta_graph could be relevant here but I do not understand how to use it correctly, the documentation is a bit cryptic to me and the examples do not even use export_meta_graph anywhere.

答:
In order to save the graph, you need to freeze the graph.
Here is the python script for freezing the graph : https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py

Here is a code snippet for freezing graph:

from tensorflow.python.tools import freeze_graph
freeze_graph.freeze_graph(input_graph_path, input_saver_def_path,
                            input_binary, checkpoint_path,  output_node
                            restore_op_name, filename_tensor_name,
                            output_frozen_graph_name, True, "")
```

<p>where output node corresponds to output tensor variable.</p>

<pre class="lang-py prettyprint-override"><code>output = tf.nn.softmax(outer_layer_name,name="output")
</code>```

Body:
I am a bit of a beginner with tensorflow so please excuse if this is a stupid question and the answer is obvious.

I have created a Tensorflow graph where starting with placeholders for X and y I have optimized some tensors which represent my model. Part of the graph is something where a vector of predictions can be calculated, e.g. for linear regression something like

y_model = tf.add(tf.mul(X,w),d)
y_vals = sess.run(y_model,feed_dict={....})

After training has been completed I have acceptable values for w and d and now I want to save my model for later. Then, in a different python session I want to restore the model so that I can again run

## Starting brand new python session
import tensorflow as tf
## somehow restor the graph and the values here: how????
## so that I can run this:
y_vals = sess.run(y_model,feed_dict={....})

for some different data and get back the y-values.

I want this to work in a way where the graph for calculating the y-values from the placeholders is also stored and restored - as long as the placeholders get fed the correct data, this should work transparently without the user (the one who applies the model) needing to know what the graph looks like).

As far as I understand tf.train.Saver().save(..) only saves the variables but I also want to save the graph. I think that tf.train.export_meta_graph could be relevant here but I do not understand how to use it correctly, the documentation is a bit cryptic to me and the examples do not even use export_meta_graph anywhere.

Body:
In order to save the graph, you need to freeze the graph.
Here is the python script for freezing the graph : https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py

Here is a code snippet for freezing graph:

from tensorflow.python.tools import freeze_graph
freeze_graph.freeze_graph(input_graph_path, input_saver_def_path,
                            input_binary, checkpoint_path,  output_node
                            restore_op_name, filename_tensor_name,
                            output_frozen_graph_name, True, "")

where output node corresponds to output tensor variable.

output = tf.nn.softmax(outer_layer_name,name="output")


问:
How to get details of all the child at same time in single list view from real-time database firebase
i am able to retrieve details of a single child on the list view but not all the child from firebase database. I want to access the child directly.

Here is my code

database pic

emulator pic

```<code> public class ViewDatabase extends AppCompatActivity {
 private static final String TAG = "ViewDatabase";
 private DatabaseReference databaseReference;
 private ListView mListView;
 @Override
 protected void onCreate(@Nullable Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
    setContentView(R.layout.view_database_layout);
 mListView = (ListView) findViewById(R.id.listview);
   databaseReference =
 FirebaseDatabase.getInstance().getReference().child("hello");
 databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            showData(dataSnapshot);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

  }
 private void showData(DataSnapshot dataSnapshot) {
    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {

        userinfo user = snapshot.getValue(userinfo.class);

        Log.d(TAG, "showData: name: " + user.getName());
        Log.d(TAG, "showData: Mobile: " + user.getMob());
        Log.d(TAG, "showData: Vehicle: " + user.getVehicle());
        Log.d(TAG, "showData: Address: " + user.getaddress());

        ArrayList<String> array = new ArrayList<>();
        array.add(user.getName());
        array.add(user.getMob());
        array.add(user.getVehicle());
        array.add(user.getaddress());
        ArrayAdapter adapter = new ArrayAdapter(this,
    android.R.layout.simple_list_item_1, array);
        mListView.setAdapter(adapter);
    }

   }
 }
</code>```

答:
Please use this code:</p>

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference helloRef = rootRef.child("hello");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        ArrayList<String> array = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String address = ds.child("address").getValue(String.class);
            String mob = ds.child("mob").getValue(String.class);
            String name = ds.child("name").getValue(String.class);
            String vehicle = ds.child("vehicle").getValue(String.class);
            array.add(address + " / " + mob + " / " + name + " / " + vehicle);
            Log.d("TAG", address + " / " + mob + " / " + name + " / " + vehicle);
        }
        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array);
        mListView.setAdapter(adapter);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
helloRef.addListenerForSingleValueEvent(eventListener);
</code>```

Body:
i am able to retrieve details of a single child on the list view but not all the child from firebase database. I want to access the child directly.

Here is my code

database pic

emulator pic

 public class ViewDatabase extends AppCompatActivity {
 private static final String TAG = "ViewDatabase";
 private DatabaseReference databaseReference;
 private ListView mListView;
 @Override
 protected void onCreate(@Nullable Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
    setContentView(R.layout.view_database_layout);
 mListView = (ListView) findViewById(R.id.listview);
   databaseReference =
 FirebaseDatabase.getInstance().getReference().child("hello");
 databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            showData(dataSnapshot);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

  }
 private void showData(DataSnapshot dataSnapshot) {
    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {

        userinfo user = snapshot.getValue(userinfo.class);

        Log.d(TAG, "showData: name: " + user.getName());
        Log.d(TAG, "showData: Mobile: " + user.getMob());
        Log.d(TAG, "showData: Vehicle: " + user.getVehicle());
        Log.d(TAG, "showData: Address: " + user.getaddress());

        ArrayList<String> array = new ArrayList<>();
        array.add(user.getName());
        array.add(user.getMob());
        array.add(user.getVehicle());
        array.add(user.getaddress());
        ArrayAdapter adapter = new ArrayAdapter(this,
    android.R.layout.simple_list_item_1, array);
        mListView.setAdapter(adapter);
    }

   }
 }

Body:
Please use this code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference helloRef = rootRef.child("hello");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        ArrayList<String> array = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String address = ds.child("address").getValue(String.class);
            String mob = ds.child("mob").getValue(String.class);
            String name = ds.child("name").getValue(String.class);
            String vehicle = ds.child("vehicle").getValue(String.class);
            array.add(address + " / " + mob + " / " + name + " / " + vehicle);
            Log.d("TAG", address + " / " + mob + " / " + name + " / " + vehicle);
        }
        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array);
        mListView.setAdapter(adapter);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
helloRef.addListenerForSingleValueEvent(eventListener);