text:
Q: Generate md5 checksum scala js I am trying to calculate hex md5 checksum at in scala js incrementally. The checksum will be verified at server side once file is transferred.
I tried using spark-md5 scala js web jar dependency:

libraryDependencies ++= Seq("org.webjars.npm" % "spark-md5" % "2.0.2")
jsDependencies += "org.webjars.npm" % "spark-md5" % "2.0.2" / "spark-md5.js"

scala js Code:-
val reader =  new FileReader
reader.readAsArrayBuffer(data)  // data is javascript blob object
val spark = scala.scalajs.js.Dynamic.global.SparkMD5.ArrayBuffer
reader.onload = (e: Event) => {
   spark.prototype.append(e.target)
   print("Checksum - > " + spark.end)
}

Error:-

Uncaught TypeError: Cannot read property 'buffer' of undefined
      at Object.SparkMD5.ArrayBuffer.append (sampleapp-jsdeps.js:596)
      at FileReader. (SampleApp.scala:458)

I tried google but most of the help is available are for javascript, couldn't find anything on how to use this library in scala js.
Sorry If I missed something very obvious, I am new to both javascript & scala js.

A: From spark-md5 readme, I read:
var spark = new SparkMD5.ArrayBuffer();
spark.append(e.target.result);
var hexHash = spark.end();

The way you translate that in Scala.js is as follows (assuming you want to do it the dynamically typed way):
import scala.scalajs.js
import scala.scalajs.js.typedarray._
import org.scalajs.dom.{FileReader, Event}

val SparkMD5 = js.Dynamic.global.SparkMD5
val spark = js.Dynamic.newInstance(SparkMD5.ArrayBuffer)()
val fileContent = e.target.asInstanceOf[FileReader].result.asInstanceOf[ArrayBuffer]
spark.append(fileContent)
val hexHashDyn = spark.end()
val hexHash = hexHashDyn.asInstanceOf[String]

Integrating that with your code snippet yields:
val reader =  new FileReader
reader.readAsArrayBuffer(data)  // data is javascript blob object
val SparkMD5 = js.Dynamic.global.SparkMD5
val spark = js.Dynamic.newInstance(SparkMD5)()
reader.onload = (e: Event) => {
   val fileContent = e.target.asInstanceOf[FileReader].result.asInstanceOf[ArrayBuffer]
   spark.append(fileContent)
   print("Checksum - > " + spark.end().asInstanceOf[String])
}

If that's the only use of SparkMD5 in your codebase, you can stop there. If you plan to use it several times, you should probably define a facade type for the APIs you want to use:
import scala.scalajs.js.annotation._

@js.native
object SparkMD5 extends js.Object {
  @js.native
  class ArrayBuffer() extends js.Object {
    def append(chunk: js.typedarray.ArrayBuffer): Unit = js.native
    def end(raw: Boolean = false): String = js.native
  }
}

which you can then use much more naturally as:
val reader =  new FileReader
reader.readAsArrayBuffer(data)  // data is javascript blob object
val spark = new SparkMD5.ArrayBuffer()
reader.onload = (e: Event) => {
   val fileContent = e.target.asInstanceOf[FileReader].result.asInstanceOf[ArrayBuffer]
   spark.append(fileContent)
   print("Checksum - > " + spark.end())
}

Disclaimer: not tested. It might need small adaptations here and there.


text:
Q: In Ruby on Rails, should we use content_for?(:foobar)? This is for Rails 3, almost always I think a content_for?(:foo) is followed by content_for(:foo)  (in haml):
%title= content_for?(:title_for_page) ? "#{content_for(:title_for_page)} - Our great website" : 'Our great website'

So instead of doing 2 lookups, isn't it better to just do 1 lookup and use longer code:
- title_for_page = content_for(:title_for_page)    # is "" when not previously set
%title= title_for_page.blank? ? 'Our great website' : "#{title_for_page} - Our great website"

?  But if content_for? is implemented as a hash, then maybe it is super quick anyway, comparable to the blank? anyways?

A: A one-liner to solve the problem:
- title_for_page = (c = content_for(:title_for_page)).blank? ? 'Our great website' : "#{c} - Our great website"

A: Only way to find out is to test :)
ruby-1.9.2-p136 :001 > h = {:mike => "test"}
 => {:mike=>"test"}

ruby-1.9.2-p136 :004 > Benchmark.ms do
ruby-1.9.2-p136 :005 >     h[:mike].present?
ruby-1.9.2-p136 :006?>   end
 => 0.029087066650390625
ruby-1.9.2-p136 :007 > Benchmark.ms do
ruby-1.9.2-p136 :008 >     h[:mike].blank?
ruby-1.9.2-p136 :009?>   end
 => 0.011205673217773438

I am using present?, as per the source of content_for?
Interesting that blank? is faster than present?, isn't it? Time to explore.
Lets look at the source code for present?:
Woah, it turns out present? just calls blank? and negates it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Getting info without downloading it via the internet" - is 'via' appropriate here? Should it be 'over'? I want to say "without downloading it via the internet" to make clear why a proposed offline alternative is less risky: it does not involve sending secret information (specifically, an encryption key) over an external network.
Related question: Via the Internet - is it correct?

Both on and via have senses for by means of; the Internet is the tool or method you are using to sell.

Therefore I think that via is correct here as well, but to me it sounds uncommon at best.
However, the alternative mentioned in this answer, on, seems to be actually incorrect for my case: "downloading it on the internet" seems like it describes what a person is doing on the internet, but what I want to say rather focuses on the method: via or through or over the internet. (It is also not about a person but about something the system does internally.) At this point, I've overthought the options so much that everything sounds weird to me, but I would guess that over is the least unwieldy-sounding.
Is over indeed the best way to say this? Are via and through also both correct, and neither so weird that you would suggest to change it while proofreading?

A: If you think of the internet as a warehouse, it makes sense to use "from". e.g.

"without downloading it from the internet"

If you think of the internet as a marketplace or bulletin board or TV, you may choose to use "on". e.g.

"videos on the internet"
"selling on the internet" etc.

If you are providing a service using the internet, it is better to use "over". e.g.

"providing service over the internet"

If it is a two-way process, "via" can be used. e.g.

"telelearning via the Internet"

Of course "internet" is a new thing, any preposition can be used as long as it makes sense to the other person.
There were other questions asked on SE as to what prepositions to be used with internet.
Via the Internet - is it correct?
Over the Internet or On the Internet?
https://english.stackexchange.com/questions/4419/in-the-internet-vs-on-the-internet
This is an ngram search showing 4 commonly used prepositions with "internet"

"On the internet" is the most commonly used among the four. The buttons below the graph (ngram) shows the "phrase occurrences" in book search results.

A: Amazingly, both versions of the expression were used with the exact same frequency until 2000, when "over the internet" became slightly more popular, but both are still correct and current.

From Google Ngrams


text:
Q: Integer solutions to fraction equation I am having trouble finding all solutions (or at least proving I have all the solutions already).
The equation is
$$\frac{1}{a}+\frac{1}{b}+\frac{2}{c}=1$$
*a,b,c are positive
I tried to base it on the solutions of a similar equation with the last term a 1 instead of a 2.

A: Let $a\geq b$.
Hence,
$$1=\frac{1}{a}+\frac{1}{b}+\frac{2}{c}\leq\frac{2}{b}+\frac{2}{c},$$
which gives
$$bc\leq2b+2c$$ or
$$(b-2)(c-2)\leq4.$$
Now, if $b\geq3$ we obtain:
$$c-2\leq\frac{4}{b-2}\leq4,$$
which gives
$c\leq6$ and the rest is smooth.
For example, the case $b=1$ is impossible, but for $b=2$ we obtain
$$\frac{1}{2}=\frac{1}{a}+\frac{2}{c}$$ or
$$ac=2c+4a$$ or
$$ac-2c-4a+8=8$$ or
$$(a-2)(c-4)=8$$ and solve some systems:

*

*$a-2=1$ and $c-4=8$ gives $(3,2,12)$;

*$a-2=2$ and $c-4=4$ gives $(4,2,8)$;

*$a-2=4$ and $c-4=2$ gives $(6,2,6)$ and

*$a=2=8$ and $c-4=1$ gives $(10,2,5).$
Now, for $a\geq b\geq3$ we need to check $c\in\{3,4,5,6\}$, which is for you.
For the full ending of the solution it's enough to add triples $(b,a,c)$.

A: Notice each $\frac 1a, \frac 1b, \frac 1c$ average $\frac 13$ but $\frac 1a,\frac 1b$ have a maximum value of $\frac 12$ and $\frac 2c$ has a maximum value of $\frac 23$.
So Case 1:  Each term is equal to the average:
$(a,b,c) = 3,3,6$.
Case 2: $\frac 1a$ or $\frac 1b$ is greater than the average.
Then $a = 2$ or $b = 2$.(wolog $a=2$)
Then $a = 2$ and $\frac 1b + \frac 2c = \frac 12$.
$\frac 2c = \frac 12 - \frac 1b = \frac {b-2}{2b}$
$c = \frac {4b}{b-2}$.  $\gcd(b-2, b) \le 2$ so $b-2|4b$ means $b-2$ is a power of $2$.   $b-2$ is a higher power of $4$ than $2$, then $b= b-2 + 2$ is only divisible by $2$ and not $4$ so $b-2$ may equal $8,4,2$ or $1$.
So $a = 2$ yields $b = 10; c=5$ or $b=6, c= 6$ or $b=4, c = 8$ or $b=3, c= 12$.
That was the hardest case.
Case 3: $\frac 2c$ is greater than the average.
The $c = 3,4$ or $5$
For each of those you get $\frac 1a + \frac 1b = 1-\frac 1c$
You can find the average of $\frac 1a, \frac 1b$. And thus a maximum testing value.  So test each $a= $ minimum value to $a =$ maximum value.
And that will be all possible solutions.


text:
Q: Unknown column 'expiry_date' in 'where clause' my sql query I have multiple tables and I am using the following query to filter records by expiry_date which are not expired yet.
My query:
SELECT

    MT.id,
    CONCAT(MEM.name,' ',MEM.last_name) AS name,
    IFNULL((SELECT MAX(MFT.membership_end_date)
        FROM membership_future_transaction AS MFT
        WHERE MFT.membership_transaction_id = MT.id),MM.end_date) AS expiry_date,
    MEM.phone,
    MEM.email,
    MMST.name AS membership_name,
    MMST.price,
    MMST.session
FROM
    membership_transaction AS MT
    LEFT JOIN member_master AS MEM ON MEM.id = MT.member_id
    LEFT JOIN members_membership AS MM ON MM.membership_transaction_id = MT.id
    LEFT JOIN membership_master AS MMST ON MMST.id = MT.membership_id
WHERE
    MT.is_casual = 'No'
    AND MT.is_deleted = 'No'
    AND MM.is_cancelled = 'No'
    AND expiry_date >= '2016-01-01'"

But I get Unknown column  'expiry_date' in 'where clause'  error please help me what am I missing here.

A: MySQL has a perhaps nifty feature where you can use having with an alias.  So if you change the where clause to:
WHERE MT.is_casual = 'No' AND
      MT.is_deleted = 'No' AND
      MM.is_cancelled = 'No'
HAVING expiry_date >= '2016-01-01'"

Then it should work.  Of course, this won't work as you expect for a query with a group by.


text:
Q: Sandbox Cookies between environments I have a production environment and a staging environment. I am wondering if I can sandbox cookies between the environments. My setup looks like
Production

*

*domain.com - frontend SPA

*api.domain.com - backend Node

Staging

*

*staging.domain.com - frontend SPA

*api.staging.domain.com - backend Node

My staging cookies use the domain .staging.domain.com so everything is fine there. But my production cookies use the domain .domain.com so these cookies show up in the staging environment.
I've read one possible solution is to use a separate domain for staging like staging-domain.com but I would like to avoid this if possible. Are there any other solutions or am I missing something about how cookies work?

A: There are multiple alternatives:

*

*Set your production domains to be www.domain.com and api.www.domain.com and set your cookie to .www.domain.com

This way, your production cookie will not be seen in the staging environment.
or

*Use .domain.com , but have your backend behave differently depending on which environment they receive the cookie in.

A: One solution would be to change the pass phrase used on staging environment to encrypt cookies.
Doing so will render cookies coming from the production invalid.
The method to do so is web server dependent, for example on Apache HTTP server:
http://httpd.apache.org/docs/current/mod/mod_session_crypto.html
Text from above link:
SessionCryptoPassphrase secret

The session will be encrypted with the given key. Different servers can be configured to share sessions by ensuring the same encryption key is used on each server.
If the encryption key is changed, sessions will be invalidated automatically.

So find how o change the passphrase on your web server on staging environment, and all cookies coming from production, along with all cookies (issued in the past) from staging will be considered invalid on staging.

A: Alternative option if you don't want to use separate domain or www subdomain: you can append staging environment name to the cookie name.
But personally, I would put an API gateway/proxy in front of backend and spa to keep both services under a single domain (domain.com and domain.com/api).
For staging: staging.domain.com and staging.domain.com/api or completely separate domain to avoid exposing a staging address in SSL certificate.
And I would not allow cookie sharing by omitting domain while setting the cookie. Probably, I would set the cookie path to /api.


text:
Q: Test publish permissions for Facebook app I want to test the publish permissions for my facebook app, however when using the graph api(s) to either like or comment, I get an error from the facebook server.
The code being used to post a like is as below:
Bundle params = new Bundle();
        params.putString("url", "http://www.imdb.com/title/tt2015381/");
        new GraphRequest(
                AccessToken.getCurrentAccessToken(),
                "/" + facebookObjectId + "/likes",
                params,
                HttpMethod.POST,
                new GraphRequest.Callback() {
                    public void onCompleted(GraphResponse response) {
                        Log.i(TAG, "FACEBOOK GRAPH RESPONSE FOR POSTING LIKE: " + response);
                    }
                }
        ).executeAsync();

The corresponding error that is being generated is:
FACEBOOK GRAPH RESPONSE FOR POSTING LIKE: {Response:  responseCode: 403, graphObject: null, error: {HttpStatus: 403, errorCode: 200, errorType: OAuthException, errorMessage: (#200) App does not have permission to make this call}}

essentially suggesting that App does not have permission to make this call

A: To post custom like:
    Bundle params = new Bundle();
    params.putString("object", linkURL);
    new GraphRequest(
            AccessToken.getCurrentAccessToken(),
            "/" + Profile.getCurrentProfile().getId() + "/og.likes",
            params,
            HttpMethod.POST,
            new GraphRequest.Callback() {
                public void onCompleted(GraphResponse response) {

                    Log.i(TAG, "FACEBOOK GRAPH RESPONSE FOR POSTING LIKE: " + response);
                }
            }
    ).executeAsync();

To delete custom like:
    Bundle params = new Bundle();
    params.putString("object", linkURL);
    new GraphRequest(
            AccessToken.getCurrentAccessToken(),
            "/" + likeActionInstanceId,
            params,
            HttpMethod.DELETE,
            new GraphRequest.Callback() {
                public void onCompleted(GraphResponse response) {
                    Log.i(TAG, "FACEBOOK GRAPH RESPONSE FOR DELETING LIKE: " + response);
                }
            }
    ).executeAsync();

Here the likeActionInstanceId is the id received after submitting the like successfully.
NOTE: Comments can't be added as of now from your own app. Comment Mirroring is in beta phase at Facebook.


text:
Q: What does () mean at the end of Perl subroutine? sub f {
    # some code here
    ()
}

What does () mean in this Perl subroutine?

A: The last expression in a sub will be the return value. This ensures that (assuming no previous return statements) the sub returns an empty list (rather then whatever was on the previous line of code).

A: OK ... so it is perhaps pathological, but this IS Perl we're talking about...
Depending on the actual text of "# some code here", it could conceivably produce a dereferenced CODE reference, in which case the parens would cause the CODE to be invoked with zero arguments, and the return value of that code would be the return value of `f'.
For example, the following will print out a single lowercase "a":
    sub f {
        &{sub { return $_[0] }}
       (@_)
    }

    print f(qw( a b c d e f )), "\n";


text:
Q: Python Anaconda linking I've been trying to install gdal on my Mac, but have been getting errors when running ogr2ogr like so:
dyld: Library not loaded: libcurl.4.dylib
  Referenced from: /usr/local/bin/ogr2ogr
  Reason: Incompatible library version: ogr2ogr requires version 8.0.0 or later,
  but libcurl.4.dylib provides version 7.0.0
Trace/BPT trap: 5

Not being able to find a solution, I had a hunch that Anaconda was part of the problem, since I was getting this:
->which curl
~/anaconda/bin/curl

so, to fix the problem I removed the curl package by running:
conda remove curl

and doing this along with removing the libxml library, I was all set and ogr2ogr was working.
My question is whether or not there was a better way around this than simply removing the packages.  I'm afraid my knowledge of how these dynamic libraries work and how they integrate is lacking, and would appreciate some help.
Thanks!

A: The curl package that comes with Anaconda on Mac is not really needed, since Mac OS X comes with its own curl. So removing it is fine.

A: This is an indirect answer, but I had configuration issues with both Anaconda and Enthought Canopy on my MacBook Air. No trouble at all building out packages using Homebrew. I installed GDAL, shapely, etc. with Homebrew after first following the instructions on this link for general NumPy SciPy ecosystem packages:
http://joernhees.de/blog/2013/06/08/mac-os-x-10-8-scientific-python-with-homebrew/
I think two or three of those packages failed, but I was able to dig out an additional dependency or use pip or setup_tools to grab it instead. I think I used pip to grab gdal, etc. afterwards.


text:
Q: How do I send PHP POST and FILES data to an AJAX URL call when they are not from an HTML form? I have a PHP page with $_POST and $_FILES data filled in. The POST data was obtained not from a traditional HTML form, but between multiple pages.
For example, the POST data is a number of things:
$_POST["username"]
$_POST["password"]
$_FILES
etc.

The question is, how do I send this POST data off to an AJAX call within the page?
I know with a form it's something like this:
$.ajax({
   type: 'post',
   url: 'post.php',
   data: $('form').serialize(),
   success: function () {
     alert('form was submitted');
   }
 });

But what about directly from PHP's POST data?

A:
The question is, how do I send this POST data off to an AJAX call
  within the page?

You can use WebSocket or EventSource and possibly ServiceWorker to stream data from server to client. For example, see How to read and echo file size of uploaded file being written at server in real time without blocking at both server and client? where the requirement is to stream the progress of bytes of uploaded file being written to file at server by php in real time without blocking.


text:
Q: What do two consecutive \usecolortheme statements mean in a beamer theme? I was taking a look at a Beamer theme code in: /usr/local/texlive/2017basic/texmf-dist/tex/latex/beamer/themes/theme/beamerthemeRochester.sty
It contains code like this:
\useoutertheme[width=0pt]{sidebar}
\useinnertheme{rectangles}
\usecolortheme{whale}
\usecolortheme{orchid}

Why are there two consecutive \usecolortheme statements here? Wouldn't the second statement override the first statement anyway?

A: Both orchid and whale are loaded using the same mechanism of \usecolortheme, but they define colors for different instances of a beamer slide. Maybe the order of the lines could have been a bit different:
\useoutertheme[width=0pt]{sidebar}
\usecolortheme{whale}
\useinnertheme{rectangles}
\usecolortheme{orchid}

whale  is an outer color theme, changing the appearance of palette colours. orchid on the other hand, is an inner color theme, most notably changing the color of blocks. The beamer documentation explains this in a little more detail.


text:
Q: Can I replace neodymium magnets with similar-size electromagnets? I am interface designer that occasionally steps out and does some product/concept design. The last one I'm working on is something that would require me to make a matrix of little electromagnets, and i am just starting to inform my self about all that.
For the project I'm playing with right now, I used 1x1x1cm neodymium magnet for experimenting, and it did the job just perfectly. I tried bigger, I tried smaller, but this one is perfect.
The problem is that i need an electromagnet to do the same thing in future. (probably lots of them)
The question is, how large does an electromagnet needs to be in volume to have the same/similar power as neodymium magnet sized 1x1x1cm.
Or even better question, how small can it be, because I really need it small but powerful.
The point of the question is just for me to hear someone experienced on the subject with some theoretical answer (Because i assume it will be enough for this stage of exploration). The real work will be done in collaboration with some professional guy just like you that I will look for if i decide to dive into all this.
Now I am aware of the fact that there are probably different ways you can measure one magnets strength, and that not all neodymium magnets are the same, so it can't be treated as a constant, but I would just like to know in general, is it like 2ccm electromagnet or is it like 20ccm electromagnet.

A: On the one hand, @sai's reasoning seems sound, on the other hand, we should not forget that an electromagnet can have a ferromagnetic core. I cannot offer any specific data right now, but I would suspect that an electromagnet with a suitable core might have comparable strength to that of a permanent magnet. The core can be magnetically soft, so it can have little average permanent magnetization when the electromagnet is switched off.
Using an electromagnet, you need extra power and/or cooling, but you also have extra control (you can vary or switch on/off the magnetic field at will).

A: It's probably very very late and I don't understand why this question has been unanswered for so long but I had a similar issue a while ago, so here goes.
To estimate the field at the surface of the Nd magnet, I used the K&J Magnetics calculator. For a 1 cm x 1 cm x 1 cm block, the surface field is ~0.6 T or 6000 Gauss.
Now let's consider a simple solenoid of outer diameter 1 cm and height 1 cm. If we use 50 µm copper wire, we can make about 200 turns per wind. If we make about 100 windings, we'll have about 20,000 turns, which is crazy. I'd say that you can't put more than 1 mA through a coil like that without any cooling. Let's use the infinite solenoid formula,
$$B=\mu_0 \frac{NI}l,$$
to get an order of magnitude for the field. Our real field is going to be smaller.
I get ~10-3 T or 10 Gauss. So it's pretty much hopeless.. Permanent magnets are way too strong.


text:
Q: Can I remove items from my UITableView data source and have my UITableView animate the row removal without specifying exact index paths? Is such a thing possible?
Basically the data source for my UITableView is a binary tree. I'm going to remove the children of one of the nodes in the tree, and I want the table view to automatically animate the update, which will remove the rows corresponding to these children.
I know I can use beginUpdates(), deleteRowsAtIndexPaths() and endUpdates() but finding all those rows is a computational annoyance (it's far from negligible). Is there any way for the UITableView to just reload with an animation?

A: This answer https://stackoverflow.com/a/13261683/1077601 suggests you can put your [self.tableView reloadData]; inside a UIView animation block.


text:
Q: How to print the map like a template? Here is my code:
To understand the code I have to explain a little. First I am getting student and course data from user in different classes. Then in Schedule class I am trying to create a schedule for student. When user enter a valid student and course name I am inserting these datas to another map.
map< string,map<pair<string,int>,pair<string,Array> > >  courseScList;
map<pair<string,int>,pair<string,Array> > matchMap;

matchMap map has these datas from another class:
course name,course hours,course day,available hours in this day

These 2 are mine maps and I am using these maps in this code:
void Schedule::studentSchedule() {
    string c,s;
    int courseNum;
    list<string>::iterator studentLoc;
    map< string,map<pair<string,int>,pair<string,Array> > >::iterator last;
    map<pair<string,int>,pair<string,Array> >::iterator location;
    map<pair<string,int>,pair<string ,Array> >::iterator match;
    dummy1:
    cout<<"Enter the student name"<<endl;
    cin >> s;
    wrongCourse:
    cout<<"Enter the course names you want"<<endl;
    cin>>c;

    auto predicate = [&](auto& course) { return compareName(course, c); };
    studentLoc = find(getStudentList().begin(),getStudentList().end(),s);
    location = find_if(getMatchMap().begin(), getMatchMap().end(), predicate);
    if(studentLoc != getStudentList().end() || location != getMatchMap().end())
    {
        getCourseScList().insert(make_pair(s,getMatchMap()));
    }
    else
        {
        cout<<"The course or student you wrote isn't available.Please enter existed courses!"<<endl;
        goto wrongCourse;
        }
    cout<<"\n"<<endl;
    char dummy;
    cout<<"\nDo tou want to create a new schedule?Press y or n."<<endl;
    cin>>dummy;
    if(dummy == 'Y' || dummy == 'y')
        goto dummy1;
    else
    {
        location = last->second.begin();
        for(last = getCourseScList().begin();last!=getCourseScList().end();++last)
        {
                cout<<last->first<<"\t"<<(location->first).first<<"\t"<<(location->second).first<<"\t";
                for (const int element : location->second.second)
                    std::cout << element << " ";
                cout<<endl;
            ++location;
        }

    }

I am trying to get student and course name from user and if student name and course name in the map I am inserting this to another map. However when I try to print these student,course,day and day hours data I can't see these in same line. I think the wrong code is this:
 else
            {
            cout<<"The course or student you wrote isn't available.Please enter existed courses!"<<endl;
            goto wrongCourse;
            }
        cout<<"\n"<<endl;
        char dummy;
        cout<<"\nDo tou want to create a new schedule?Press y or n."<<endl;
        cin>>dummy;
        if(dummy == 'Y' || dummy == 'y')
            goto dummy1;
        else
        {
            location = last->second.begin();
            for(last = getCourseScList().begin();last!=getCourseScList().end();++last)
            {
                    cout<<last->first<<"\t"<<(location->first).first<<"\t"<<(location->second).first<<"\t";
                    for (const int element : location->second.second)
                        std::cout << element << " ";
                    cout<<endl;
                ++location;
            }

        }

With this print loop i can't see the template like this;
Studentname1  -- > Coursename1 ----> Courseday1 -->Coursehours1
Studentname1  -- > Coursename2 ----> Courseday2 -->Coursehours1
Studentname2  -- > Coursename1 ----> Courseday1 -->Coursehours1
Studentname3  -- > Coursename2 ----> Courseday2 -->Coursehours

This is just an example what I want to do. How can I organize the code for it?


text:
Q: nice command behavior when only 1 function running I just learned the existence of nice (and ionice) which seems to be really interesting.
I just want to launch a process 'p_low' with less priority than my ususal one 'p_normal'.
What I was able to get from the wiki page (only source which shows me how the resource is distributed), is that:

a process run with nice +15 will receive 25% of the CPU time allocated
  to a normal-priority process: (20 − 15)/(20 − 0) = 0.25

So based on that I can provide 10% of the CPU time to my p_low process if "nice -18 p_low"
This is perfect IF MY 'p_normal' IS RUNING.
So question: is there a way to tell the scheduler to use the default niceness value, and only -18 when there is something else running?
In the worst case I can make a script which check if anything else is running, and "renice" my process, but it doesn't seem to be the best option to me...

EDIT:
ANSWER:
As pointed out by @jilliagre in the comments below his answer:

if nothing else is running the command will get 100% of the CPU
  whatever the niceness given (-18, 0, +18, ...)

A: You are missing how nice works. It is simply a hint to the scheduler for it to prioritize some processes against others when there is a CPU bottleneck.
I there is nothing else running, whatever its niceness, your process will be granted all the CPU power so there is no need to change the niceness in that specific case.


text:
Q: How can I replace an image on a website with a local image in my chrome extension? I have a chrome extension, that changes the appereance of the wikipedia page. Now I want to change the image there. I want to replace it with one stored local in my chrome-extension. I want to change some HTML code to display my image. My manifest.json looks like this
{
    "name" : "name",
    "version": "0.0.1",
    "manifest_version": 2,
    "description" : "some desc",
    "web_accessible_resources" : [
        "images/*.png"
    ],
    "content_scripts" : [
        {
            "css": ["style.css"],
            "js": ["imgreplace.js"],
            "matches" : ["*://www.wikipedia.de/"]
        }
    ]
}

imgreplace.js
document.getElementsByClassName("wikipedia-logo").innerHTML = this.innerHTML + ''

If I refresh the page nothing happens. No Error.
I've also tried it with the function injectAdjacentHTML, but I get the error injectAdjacentHTML is not a function.
How can I replace it?
Tell me, if you need anything of my code.

A: I fixed some bugs.
imgreplace.js
const path = chrome.runtime.getURL("images/wikipedia_logo.png");

document.getElementsByClassName("wikipedia-logo")[0].innerHTML +=
  '';

A: This version does essentially the same thing as @NorioYamamoto's version; it's just a little cleaner.
The original WP logo is briefly visible, I don't know how to prevent that. If you use an SVG instead of a PNG, the change happens so quickly that you can barely see the original logo (YMMV).
manifest.json
{
    "manifest_version": 3,
    "name" : "Replace Wikipedia Logo",
    "version": "0.0.1",
    "content_scripts" : [
        {
            "js": ["imgreplace.js"],
            "matches" : ["*://*.wikipedia.de/*"]
        }
    ],
    "web_accessible_resources" : [
        {
            "resources": ["/images/*.png"],
            "matches": ["*://*.wikipedia.de/*"]
        }
    ]
}

imgreplace.js
try {
    let logo_selector = "#mainbox > div.wikipedia-logo > a > img";
    let logo_imgs = document.querySelectorAll(logo_selector);
    if (logo_imgs.length == 0) {
        throw `The CSS selector "${logo_selector}" didn't find any elements.`;
    }
    else if (logo_imgs.length == 1) {
        logo_imgs[0].src = chrome.runtime.getURL("/images/wikipedia_logo.svg");
    }
    else {
        throw `The CSS selector "${logo_selector}" found more than one element.`;
    }
}
catch(e) {
    console.error(e);
}


text:
Q: How to find all paths in a NxM grid? This is my problem:

A robot is located at the top-left corner of a m x n grid
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid.
How many possible unique paths are there?

This is my code:
def paths(m,n,a,b,memo):

    if(a == 0 or b == 0):
        return 0

    if m>a or n>b:
        return 0

    if m==a and n==b:
        return 1

    if str(m)+str(n) in memo:
        return memo[str(m)+str(n)]
    else:
        memo[str(m)+str(n)] = paths(m+1,n,a,b,memo) + paths(m,n+1,a,b,memo)
        return memo[str(m)+str(n)]

m=23
n=12
memo =  dict()
print(paths(0,0,m-1,n-1,memo))

I am getting correct answer for most of the cases, but for case where m=23 and n=12, my answer is wrong. Correct answer is 193536720 while I am getting 201648450


text:
Q: Reading multiple data values per line using BufferedReader I am making a program that reads data from a file called playoffs.txt. Each line has a team name, score, and division, each separated by colons, like so:
Panthers:0:Atlantic
Lightning:0:Atlantic
Red Wings:0:Atlantic

I want to run a for loop that prints out this for each team:
Team: Panthers
Series Score: 0
Division: Atlantic

However, I'm having trouble figuring out how to separate the values on each line, since readLine seems to print out the entire line. Here's my method:
private static void series(String team1) throws FileNotFoundException, IOException{
    BufferedReader in = new BufferedReader(new FileReader("playoffs.txt"));

    String[] team = new String[0];
    int[] score = new int[0];
    String[] division = new String[0];
    String s;
    int j = 0;
    while((s = in.readLine()) != null){
        String[] var = s.split(":");
        team[j] = in.readLine(var[0]);
        score[j] = in.read();
        division[j] = in.read();
        cout.println(team[j]);
        cout.println(score[j]);
        cout.println(division[j]);
        j++;
    }
}

I'm new to Java and the s.split line I found on another StackOverflow question that was similar to my question, and it runs an error saying "String cannot be converted to boolean." I'm also confused about the difference between readLine() and read(). Any help to point me in the right direction to read each value separately would be appreciated.

A: try
    String[] var = s.split(":");
    team[j] = var[0];
    score[j] = var[1];
    division[j] = var[2];

but you should initialise your team to be big enough to hold your data.
I would personally use an ArrayList
Consider creating a new class called Team which has a team name, a score and a division.  The you can create an ArrayList <Team> = new ArrayList <Team> ();

A: You correctly split on the ':' symbol, which returns a String[].
You don't need to call in.readLIne(var[0]). You already have the values in the String[]. Simply assign them to your variables:
while((s = in.readLine()) != null){
    String[] var = s.split(":");
    team[j] = var[0];
    score[j] = var[1];
    division[j] = var[2]
    cout.println(team[j]);
    cout.println(score[j]);
    cout.println(division[j]);
    j++;
}

This solves one of your issues. However, since you are trying to store multiple values per entry, you are better off with a container class that represents the data you have. You can then create a new instance of the container class and override the toString() method to print the contents of each after all input is received.
Try adding a GameResult class (or call it something else):
public class GameResult{
    String team;
    int score;
    String division;

    public GameResult(String team, int score, String division){
        this.team = team;
        this.score = score;
        this.division = division;
   }

   public String getTeam(){
       return team;
   }

   public int getScore(){
       return score;
   }

   public String getDivision(){
       return division;
   }

   @Override
   public String toString(){
       StringBuilder sb = new StringBuilder();
       sb.append("Team: ").append(team).append("\n");
       sb.append("Score: ").append(score).append("\n");
       sb.append("Division: ").append(division).append("\n");

       return sb.toString();
   }
}

Now you can use the new class and for each line store in a List to later print the results:
private static void series(String team1) throws FileNotFoundException, IOException{
    BufferedReader in = new BufferedReader(new FileReader("playoffs.txt"));
    List<GameResult> results = new ArrayList<>();
    String s;

    while((s = in.readLine()) != null){
        String[] var = s.split(":");
        GameResult result = new GameResult(var[0], var[1], var[2]);

    }

    //Print out the results
    for(GameResult aResult: results){
        System.out.print(aResult);
    }
}


text:
Q: Memory leaking with gsteramer appsink (python bindings) I am trying to build pipeline with appsink and it eats a lot of memory:
#!/usr/bin/env python

import sys

import gi

gi.require_version('Gst', '1.0')
from gi.repository import GObject, Gst

def main():
    GObject.threads_init()
    Gst.init(None)
    # pipeline = Gst.parse_launch('fakesrc ! fakesink')
    pipeline = Gst.parse_launch('fakesrc ! appsink')

    loop = GObject.MainLoop()

    pipeline.set_state(Gst.State.PLAYING)
    try:
        loop.run()
    except:
        pass

    pipeline.set_state(Gst.State.NULL)

if __name__ == '__main__':
    sys.exit(main())

Even without setting connection the memory is constantly increasing. I tried to connect a function using sink.connect("new-sample", handler, sink) - it also leaks memory. Also tried to add handler to bus (read somewhere that gst might enqueue messages that were not delivered to python and keep them forever) - does not help either.
Do I need to release memory somewhere? I have found calls to gst_object_unref in C code, but I am not sure if I should use unref in python code.
Also, simple pipeline 'fakesrc ! fakesink' does not leak memory.
The script is running inside Docker (not sure if this matters, I cannot test outside Docker unfortunately):
FROM python:3.6
ENV PYTHONUNBUFFERED 1
RUN mkdir -p /code
WORKDIR /code
ADD Pipfile Pipfile.lock /code/
RUN apt-get update && apt-get install -y software-properties-common cmake \
    gobject-introspection libgirepository1.0-dev libcairo2-dev \
    libgstreamer1.0-0 gstreamer1.0-plugins-base gstreamer1.0-plugins-good gstreamer1.0-plugins-bad \
    gstreamer1.0-plugins-ugly gstreamer1.0-libav gstreamer1.0-doc gstreamer1.0-tools \
    python-gst-1.0
RUN pip install pipenv && pipenv install --system
ADD . /code/
WORKDIR /code/src
EXPOSE 8181
CMD python main.py

A: Appsink has a queue where it stores incoming samples. By default this size is unlimited. You can control this by the max-buffers and drop properties of appsink so it does not grow infinite.
But what you actually have to do is to actively pull these samples out of the appsink and process them - or at least just drop them.
The new-sample signal is a good start. If that signal is triggered a new sample has arrived and is ready to be processed. I can't recall Python specifically here but you want to call pull_sample method of the appsink object to take ownership of the sample from the appsink to yourself. Once you get out of scope that sample should get released properly - I guess.
EDIT: Make sure the signal is emmitted. There is an appsink property emit-signals which is off by default. But I usually do C stuff so I'm not sure Python does flip some switches sot it works out of the box..

A: Well, the solution (at least hotfix) is simple: manually call gc.collect()
I am not exactly sure why it is not calling (or freeing) automatically, but simple calling gc.collect() on each sink handler solves the issue. This is not super-effective to call gc on each frame and I will definitely do some research on it when I have free time.
The solution was discovered by rewritting to Java (it also eats a lot of memory), but in Java you can specify -Xmx which reduces amount of memory available to JVM


text:
Q: Passing object array to another page i've made a button "checkout" in which when it's pressed it will gather all the data in a html table into an object array. The problem is how do i pass the var arrData data to the next page. New to jquery, thanks in advance.
$("#checkout").on('click',function(){

var arrData=[];
$("#table tr").each(function(){
    var currentRow=$(this);

    var col1_value=currentRow.find("td:eq(0)").text();
    var col2_value=currentRow.find("td:eq(1)").text();
    var col3_value=currentRow.find("td:eq(2)").text();
    var col4_value=currentRow.find("td:eq(3)").text();

    var obj={};
    obj.col1=col1_value;
    obj.col2=col2_value;
    obj.col3=col3_value;
    obj.col4=col4_value;

    arrData.push(obj);
});
console.log(arrData);

});

A: Not to complicate things you can use localStorage to locally store data in browser.
This way you can use the data whenever you want from any page in your website.
Set arrData in local storage from page 1.
localStorage.myArrData=JSON.stringify(arrData);

Get value of arrData in page 2,
var arrData = JSON.parse(localStorage.myArrData);

A: Are you sending this data to a backend? All that this code does is append the details to an object Array.
Typically the data is passed to a backend system and subsequently can be retrieved from the same in any other pages.


text:
Q: Как массово разрешить комментарии для таксономий wordpress? Есть сайт на wordpress на котором для таксономий были отключены комментарии с помощью плагина Disable Comments. Теперь же понадобилось их вернуть, но деактивация плагина к результату не привела. Запрос в базе данных mysql на массовое изменение комментариев работает только для записей
UPDATE wp_posts SET comment_status = 'open', ping_status = 'open';

Как сделать тоже самое для произвольных таксономий?

A: Полностью удалил плагин и потом применил вот эту запись - заработало!
UPDATE wp_posts SET comment_status = 'open', ping_status = 'open'


text:
Q: how to show loader when i select somthing from dropdown ?means while loading data from backend it should show some event like spinner This is my HTML form div

    <select name="limitCount" id="limitCount" ng-model="limitCount"
        class="form-control col-md-2 panel-refresh"
        ng-change="filterChanged()">
        <option value=0>All Records</option>
        <option value="1">1 Record</option>
        <option value=5 selected>5 Records</option>
        <option value=10>10 Records</option>
        <option value=25>25 Records</option>
        <option value=50 selected>50 Records</option>
        <option value=100 selected>100 Records</option>
        <option value=200 selected>200 Records</option>
        <option value=300 selected>300 Records</option>
        <option value=500 selected>500 Records</option>
        <option value=1000 selected>1000 Records</option>
    </select>

and this is my controller for this div
$scope.filterChanged = function () {
    controller.resetGraph = true;
    loadGraphData();
};

Now I want that , when I ever I am selecting from selection dropdown it should show some spinner in the ui(like some loader) until data is fetched from mongodb. please help me as fast as you can . I have to complete this work.write now I am using this, but it is not working at all
$scope.$on('panel-refresh', function (event, id) {
    spinnerId = id;
    $scope.find();
});

A: You have typo in this near   controller.resetGraph = true;$s , like what is $s ?
Here i am going to show you like how you can allow spinner to show and hide after data loaded.

<select name="limitCount" id="limitCount" ng-model="limitCount"
        class="form-control col-md-2 panel-refresh"
        ng-change="filterChanged()">
    <option value=0>All Records</option>
    <option value="1">1 Record</option>
    <option value=5 selected>5 Records</option>
    <option value=10>10 Records</option>
    <option value=25>25 Records</option>
    <option value=50 selected>50 Records</option>
    <option value=100 selected>100 Records</option>
    <option value=200 selected>200 Records</option>
    <option value=300 selected>300 Records</option>
    <option value=500 selected>500 Records</option>
    <option value=1000 selected>1000 Records</option>
</select>

Now in your controller define one variable like :
$scope.loading = false // Initially false to hide spinner

Now when data filter or something you need to just assign Boolean true like this :
$Scope.filterChanged = function () {
    $scope.loading = true// Allow spinner to load
    controller.resetGraph = true;$s
    loadGraphData().then(function(){
    $scope.loading = false// Allow spinner to stop load on finish data lading
     });
};

Let me know if you are not able to get this.


text:
Q: Int to non optional string I have a string 00012. I need to make a string 12 out of it. And load then UIImage by concatenating strings into name.
So I do the following
let myString = "00012"
let myInt = Int(myString)
let imageName = "name_\(myInt)"
let image = UIImage(named: imageName)

The problem is that (myInt) return an optional. I don't get imageName = name_12, I get imageName = name_optional(12)
How can I get rid of optional ?
I can't trim first 3 zeros from initial string, because number can be 00001

A: Use optional bindings:
let myString = "00012"
if let myInt = Int(myString) {
  let imageName = "name_\(myInt)"
  let image = UIImage(named: imageName)
}

alternatively use regular expression:
let myString = "00012"
let myStringWithoutLeadingZeros = myString.replacingOccurrences(of: "^0+", with: "", options: .regularExpression)
let imageName = "name_" + myStringWithoutLeadingZeros
let image = UIImage(named: imageName)

A: You can unwrap the value directly
let myString = "00012"
let myInt = Int(myString)! // unwrapping
let imageName = "name_\(myInt)"
let image = UIImage(named: imageName)

Or you can use optional binding
let myString = "00012"
if let myInt = Int(myString) { // Optional binding
    let imageName = "name_\(myInt)"
    let image = UIImage(named: imageName)
}


text:
Q: Google Cloud Platform Trial I enabled free trial on Google Cloud Platform and added billing account. Now billing account is closed and I have few questions:
1) Will I be able to use Firebase after trial expire without paid account?
2) Is closing billig acoount means I won't be charged for anything?
All projects are unlinked from billing account.

A: This is how it works:

*

*You have a billing account linked to say 5 projects

*If you want to stop billing on your resources -- you unlink that project

*Now you want to close the Billing account itself -- you will not be charged for any services which fall under free tier of GCP. i.e. Firebase's free tier per month

*One potential issue is that you can not create anything which is charged on the standard rates

*Once you exhaust your $300 free trial subscription (keep in mind that if you cancel the billing account, you will lose access to the $300), you will still be entitled to per month free tier based on the services you are using.

*Without enabling billing for a project, you can not create any resources.

*If you've closed the billing account, you can re-open it. A billing account can cannot be deleted.

Here is a quote from GCP's doc regarding Closure of a Billing account:

Closing an active Cloud Billing account stops all billable services in
  any projects linked to the account, such as running VM instances or
  storage buckets. Projects that are not linked to an active and valid
  Cloud Billing account cannot use Google Cloud or Google Maps Platform
  services that aren't free.

Hope it helps!

A: You don't need to move google account. Your account is type free or not free' as simple as that. Once your 1 year free plan is lapsed you have to upgrade it to normal (non free) billing account.


text:
Q: How to save entries into db on submit button click only I have a code like this
<?php
if ( $thismemberinfo[msurf] >= $msurfclicks ) {
    $sql=$Db1->query("INSERT INTO d_bonus VALUES('$userid','0.02',NOW())");
    echo "success";
} else {
    echo "wrong";
}
?>
<form action="" method="post" name="myform">
  <input type="hidden" value="123" name="match">
  <input type="submit" value="Claim your daily bonus $o.o2" name="submit1">
</form>

I want to save values into db after user clicks the submit button. I have been trying different approaches, but still could not get near to it.
Any ideas/hints what I should do next or doing wrong?
After the given suggesstion below is my code :
<form action="" method="post" name="myform">
<input type="hidden" value="123" name="match">
<input type="submit" value="Claim your daily bonus $o.o2" name="submit1">
</form>
<?php
if(isset($_REQUEST['submit1']))
{
echo "$thismemberinfo[msurf]";
echo " $msurfclicks";
if ( $thismemberinfo[msurf] >= $msurfclicks ) {
      //$sql=$Db1->query("INSERT INTO d_bonus VALUES('$userid','0.02',NOW())");
          echo "success";

}
else
{
echo " not set " ;
}

}

?>

A: you can use isset for checking if button is clicked or not
if(isset($_REQUEST['submit1']))
{

     if ( $thismemberinfo[msurf] >= $msurfclicks ) {
     $sql=$Db1->query("INSERT INTO d_bonus VALUES('$userid','0.02',NOW())");
     echo "success";
     }
     else
     {
        echo "wrong";
     }
 header("location:".$_SERVER['PHP_SELF']);
}

A: Your code is missing a few things..
To insert entries into the database, you should think more about what tasks need to be carried out, I'll give you a list of them, you have probably done some of these.
1) Connect to the database.
2) Obtain the values entered into the form, and store them in local variables, in your case you have used POST on your form and therefore.. here's an example:
$Field1 = mysql_real_escape_string($_POST['match']); // match?? This post data comes from the name field of your form.

3) Create your query... e.g..
$sql = "INSERT INTO table_name (table_heading) VALUES ('$Field1')";

4) Run the query

A: You need to check if the request has come from the post submit i.e. as others pointed check $_POST['submit']
if(isset( $_POST['submit'] ) {
    // your complete rest php code goes here to insert the record
}

On page refresh, it'll see the request is not a post request submitted hence won't execute the php code in the if and will just display the page.


text:
Q: Is it acceptable to lowercase 'google' in all verb forms? Is it acceptable to lowercase 'google' in all verb forms?
For example:

*

*He googled the information.

*He is googling the information.

*He googles the information.

*Please google the information.

Is it now acceptable to lowercase the word 'internet'?

A: Google - verb is usually capitalised, but the lower case is also used,  (see Ngram).

*

*The transitive verb  to google (also spelled Google) means using the Google search engine to obtain information on something or somebody on the World Wide Web. However, in many dictionaries the verb refers to using any web search engine, such as Yahoo!.

Ngram: googling vs Googling
Internet vs internet:

*

*Many American style guides recommend capitalizing the first letter of Internet, and most major American publications (as well as many Canadian ones) do so. Outside North America, internet is rarely capitalized.

*The non-U.S. approach makes more sense. There is no good reason to capitalize internet. The convention in English is to capitalize the first letters of proper nouns, which are the official names of people, places, objects, or events.

*The internet is none of these. It was originally capitalized to differentiate the Internet (the global network that anyone can access) from an internet (any network of interconnected computers), but in common usage this distinction is now irrelevant. Internet is now just a generic term for the communication medium.

(The Grammarist)

A: Yes, having google or googling in lowercase is acceptable. See Merriam-Webster.
Also, for internet, see this Wikipedia article. It has become a generic term and can safely be lowercased.


text:
Q: Conversion of Sql query to linq I am trying to convert sql query for select to linq query using EF in MVC but really got stuck with an error.
In SQL I'm able to get 6 records for my query,similarly when I try to convert this to linq it shows some error.
Following is my query in SQL:
SELECT
   PurchaseOrderMaster.*, PurchaseOrderDetails.*, Vendor.*,
   BusinessUnit.*, InvoiceMaster.*, TenantEmployee.*
FROM
   PurchaseOrderMaster
INNER JOIN
   PurchaseOrderDetails ON PurchaseOrderMaster.TenantID = PurchaseOrderDetails.TenantID
                        AND PurchaseOrderMaster.PurchaseOrderNumber = PurchaseOrderDetails.PurchaseOrderNumber
                        AND PurchaseOrderMaster.PurchaseOrderDate = PurchaseOrderDetails.PurchaseOrderDate
INNER JOIN
   InvoiceMaster ON PurchaseOrderMaster.TenantID = InvoiceMaster.TenantID
                 AND PurchaseOrderMaster.PurchaseOrderNumber = InvoiceMaster.PurchaseOrderNumber
                 AND PurchaseOrderMaster.PurchaseOrderDate = InvoiceMaster.PurchaseOrderDate
INNER JOIN
    BusinessUnit ON PurchaseOrderMaster.TenantID = BusinessUnit.TenantID
                 AND PurchaseOrderMaster.BusinessUnitID = BusinessUnit.BusinessUnitID
INNER JOIN
    TenantEmployee ON PurchaseOrderMaster.TenantID = TenantEmployee.TenantID
INNER JOIN
    Vendor ON PurchaseOrderMaster.TenantID = Vendor.TenantID
           AND PurchaseOrderMaster.VendorID = Vendor.VendorID

For this query I am able to get 6 records .
And my linq query is:
return (from pom in db.PurchaseOrderMaster
                    join pod in db.PurchaseOrderDetails on pom.TenantID equals pod.TenantID
                    where pom.PurchaseOrderNumber == pod.PurchaseOrderNumber && pom.PurchaseOrderDate == pod.PurchaseOrderDate
                    join inv in db.InvoiceMaster on pom.TenantID equals inv.TenantID
                    where pom.PurchaseOrderNumber == inv.PurchaseOrderNumber && pom.PurchaseOrderDate == inv.PurchaseOrderDate
                    join bu in db.BusinessUnit on pom.BusinessUnitID equals bu.BusinessUnitID
                    join te in db.TenantEmployee on pom.TenantID equals te.TenantID
                    join v in db.Vendor on pom.TenantID equals v.TenantID
                    where pom.VendorID == v.VendorID
                    orderby pom.PurchaseOrderNumber ascending, pom.PurchaseOrderDate                   descending
                select new { pom, pod, inv, bu, te, v }).ToList();

At the time of debugging,following is the error that I'm getting:
{"Invalid column name 'invoiceMasterModel_TenantID'.\r\nInvalid column name 'invoiceMasterModel_PurchaseOrderNumber'.\r\nInvalid column name 'invoiceMasterModel_PurchaseOrderDate'.\r\nInvalid column name 'invoiceMasterModel_InvoiceNumber'.\r\nInvalid column name 'invoiceMasterModel_InvoiceDate'.\r\nInvalid column name 'tenantEmployeeModel_TenantID'.\r\nInvalid column name 'tenantEmployeeModel_EmployeeID'."}

Inside Invoice Table it is not able to find some of the columns and hence throwing the error according to me..
I tried with many possible ways but was unable to solve this.
Any ideas..?

A: Problem was with my Entity.
What I did is,I added my entity again and according to that I recreated models for the associated tables removing the earlier ones.
It solved my problem finally .

A: I found this link Entity Framework 5 Invalid Column Name error related to somewhat similar problem.
Here also similar kind of error happened after the date time field. Check if your datetime field PurchaseOrderDate is nullable.

A: Many tools exist that can convert your sql queries to linq, in case you don't wanna write it urself. Try the following sites, works well in my case:
http://www.sqltolinq.com/
http://www.linqpad.net/


text:
Q: app is not showing any layout I am working on this project since months, but at the time of launching I am not getting any kind of elements in my main layout.
Here is the screenshot https://www.dropbox.com/s/99d2lr6ffo4klxc/Screenshot_20180413-064226.png?dl=0
Here is my  build gradle file.
buildscript {

repositories {
    jcenter()
    google()

    mavenCentral()
    maven {
        url "https://maven.google.com"
    }
    maven { url 'https://maven.fabric.io/public' }
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.1.1'
    classpath 'com.google.gms:google-services:3.2.1'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    jcenter()
    google()
    maven {
        url "https://maven.google.com"
    }
    maven { url 'https://maven.fabric.io/public' }
    maven { url "https://jitpack.io" }
    mavenCentral()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

Here is my app gradle
apply plugin: 'com.android.application'

android {
compileSdkVersion 27
defaultConfig {
    applicationId "com.cofoz.cofoz"
    buildToolsVersion '27.0.3'
    minSdkVersion 17
    targetSdkVersion 27
    versionCode 2
    versionName "1.1"
    vectorDrawables.useSupportLibrary = true
    multiDexEnabled true
    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"

}
useLibrary 'org.apache.http.legacy'
dexOptions {
    javaMaxHeapSize "2g"
    preDexLibraries true

    jumboMode true
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
        // Disables PNG crunching for the release build type.
        crunchPngs false

    }
}

sourceSets { main { assets.srcDirs = ['src/main/assets',
'src/main/assets/'] } }
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.0.2'
implementation 'com.android.support:support-v13:27.0.2'
implementation 'com.android.support:animated-vector-drawable:27.0.2'
implementation 'com.android.support:mediarouter-v7:27.0.2'
implementation 'com.android.support:support-compat:27.0.2'
implementation 'com.android.support:support-dynamic-animation:27.0.2'
implementation 'com.android.support:palette-v7:27.0.2'
implementation 'com.android.support:design:27.0.2'
implementation 'com.android.support:animated-vector-drawable:27.0.2'
implementation 'com.android.support:customtabs:27.0.2'
implementation 'com.android.support:cardview-v7:27.0.2'
implementation 'com.android.support:recyclerview-v7:27.0.2'
implementation 'com.android.support.constraint:constraint-
layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.1'

implementation 'com.google.android.gms:play-services-auth:11.8.0'
implementation 'com.google.firebase:firebase-core:11.8.0'

implementation 'com.github.andremion:counterfab:1.0.1'

implementation 'com.firebaseui:firebase-ui-auth:3.2.2'
implementation 'com.google.firebase:firebase-auth:11.8.0'

//implementation 'com.jakewharton:butterknife:8.8.1'

implementation 'com.firebaseui:firebase-ui-firestore:3.2.2'
implementation 'com.google.firebase:firebase-firestore:11.8.0'
implementation 'com.google.firebase:firebase-messaging:11.8.0'

// Required only if Facebook login support is required
//implementation 'com.facebook.android:facebook-android-sdk:4.27.0'

implementation 'com.github.bumptech.glide:glide:4.4.0'
//implementation 'com.github.DanielMartinus:Stepper-Touch:0.6'
//implementation 'com.stone.vega.library:VegaLayoutManager:1.0.6'

implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.squareup.okhttp3:okhttp:3.8.1'
implementation 'com.squareup.okhttp:okhttp:2.5.0'

implementation 'com.google.code.gson:gson:2.8.2'
//implementation'com.google.firebase:firebase-invites:11.8.0'

implementation 'de.hdodenhof:circleimageview:2.1.0'
implementation 'com.airbnb.android:lottie:2.2.5'
implementation 'com.google.android.gms:play-services:11.8.0'

implementation 'com.google.android.gms:play-services-maps:11.8.0'
implementation 'com.google.android.gms:play-services-location:11.8.0'

//implementation 'com.mcxiaoke.volley:library-aar:1.0.0'

implementation 'com.squareup.okhttp:okhttp-urlconnection:2.2.0'

//implementation 'com.github.GrenderG:Toasty:1.2.8'
implementation 'com.github.d-max:spots-dialog:0.4@aar'
implementation 'com.wdullaer:materialdatetimepicker:3.5.0'
//implementation 'com.github.ganfra:material-spinner:2.0.0'
//implementation 'com.google.android.gms:play-services-identity:11.8.0'
//implementation 'com.github.thomper:sweet-alert-dialog:v1.4.0'
// Shimmer
implementation 'com.facebook.shimmer:shimmer:0.1.0@aar'

implementation 'com.karumi:dexter:4.2.0'

implementation 'com.afollestad.material-dialogs:core:0.9.6.0'

}

apply plugin: 'com.google.gms.google-services'

My mainactivity.java goes like this.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        Window window = getWindow();

// clear FLAG_TRANSLUCENT_STATUS flag:
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

// add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

// finally change the color
        window.setStatusBarColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
    }

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
    LinearLayout bottomsheetLayout = (LinearLayout) findViewById(R.id.bottom_sheet);

    counterFab = (CounterFab) findViewById(R.id.counter_fab);
    bottomDishName = (TextView) findViewById(R.id.dishNameBottom);
    dishBottomPrice = (TextView)findViewById(R.id.dishBottomPrice);
    txtIngredients = (TextView) findViewById(R.id.txtIngredients);
    counterFab.setTranslationY(counterFab.getHeight() + 16);
    floatingLay = (CoordinatorLayout) findViewById(R.id.floatingLay);
    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);

    headerName = (TextView)findViewById(R.id.headerName);
    mLogout = (LinearLayout)findViewById(R.id.logout);

    mAuth = FirebaseAuth.getInstance();
    mUser = mAuth.getCurrentUser();
    user_id = mUser.getUid();

    mFirestore = FirebaseFirestore.getInstance();
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

    mDatabaseUser = mFirestore.collection("Users").document(user_id);

    bottomSheetBehavior = BottomSheetBehavior.from(bottomsheetLayout);

    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            counterFab.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();
        }
    }, 100);
    cardLoading = (CardLoading) getApplicationContext();

    counterFab.setCount(cardLoading.getFabCount());
    //gps = new GPSTracker(MainActivity.this);
    //Toast.makeText(this, "Location:"+Double.toString(gps.getLatitude()) + Double.toString(gps.getLongitude()), Toast.LENGTH_SHORT).show();

    //Toast.makeText(this, "FabCount:"+Integer.toString(cardLoading.getFabCount()), Toast.LENGTH_SHORT).show();
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    /*mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            Toast.makeText(MainActivity.this, "Location:" + Double.toString(location.getLatitude()) + "," + Double.toString(location.getLongitude()), Toast.LENGTH_SHORT).show();
        }
    });*/

    //Toast.makeText(this, userName, Toast.LENGTH_SHORT).show();
    //Toast.makeText(this, userEmail, Toast.LENGTH_SHORT).show();

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

    //locationStr = getIntent().getStringExtra("Location");

    sp = getSharedPreferences("profile_data", MODE_PRIVATE);
    spCart = getSharedPreferences("Cart_details", MODE_PRIVATE);

    //String name = sp.getString("Name", "Your Name");

    //String cartCount = spCart.getString("CartCount", "0");
    //Toast.makeText(this, cartCount, Toast.LENGTH_SHORT).show();
    //Integer c = Integer.valueOf(cartCount);
    //counterFab.setCount(c);

    View header=navigationView.getHeaderView(0);
    View view=navigationView.inflateHeaderView(R.layout.nav_header_main);
    headerName = (TextView)header.findViewById(R.id.headerName);
    String userName = getIntent().getStringExtra("name");
   mDatabaseUser.addSnapshotListener(new EventListener<DocumentSnapshot>() {
       @Override
       public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {
           Users users = documentSnapshot.toObject(Users.class);
           headerName.setText(users.getName());
       }
   });
    //Toast.makeText(this, userName, Toast.LENGTH_SHORT).show();
    //headerName.setText(userName);

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    mViewPager.beginFakeDrag();

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    mLogout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mAuth.signOut();
            Intent logoutIntent = new Intent(MainActivity.this, WelcomeActivity.class);
            startActivity(logoutIntent);
        }
    });

}

@Override
public void onResume()
{  // After a pause OR at startup
    super.onResume();
    //Refresh your stuff here
    counterFab.setCount(cardLoading.getFabCount());
    //Toast.makeText(this, "FabCount:"+Integer.toString(cardLoading.getFabCount()), Toast.LENGTH_SHORT).show();
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.

    Fragment fragment = null;

    int id = item.getItemId();

    switch (id){
        case R.id.nav_profile:

            Intent profileIntent = new Intent(MainActivity.this, Profile.class);
            startActivity(profileIntent);
            break;
        case R.id.nav_orders:
            Intent ordersIntent = new Intent(MainActivity.this, Orders.class);
            startActivity(ordersIntent);
            break;

    }

    if (fragment != null) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.content, fragment);
        ft.commit();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

@Override
public void onConnected(@Nullable Bundle bundle) {

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onPointerCaptureChanged(boolean hasCapture) {

}

class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        switch (position){
            case 0:
                OrderNow tabOrdernow = new OrderNow();
                return tabOrdernow;
            case 1:
                MealPlan tabMealPlan = new MealPlan();
                return tabMealPlan;

            default:
                return null;

        }
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Order Now";
            case 1:
                return "Meal Plan";

        }
        return null;
    }
}

}

And Here is my mainactivity.xml file
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:background="@android:color/white"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:itemIconTint="@color/colorPrimary"
    app:itemTextColor="@color/colorPrimary"
    app:menu="@menu/activity_main_drawer">

    <LinearLayout
        android:id="@+id/logout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:layout_marginBottom="30dp"
        android:clickable="true"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.2"
            android:padding="5dp"
            app:srcCompat="@drawable/ic_power_settings_new_black_24dp" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"
            android:gravity="center_vertical"
            android:padding="5dp"
            android:text="Log Out"
            android:textColor="@color/colorPrimary"
            android:textStyle="bold" />
    </LinearLayout>
</android.support.design.widget.NavigationView>

Here is my app_bar_main file
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/floatingLay"
android:layout_height="match_parent"
android:background="@android:color/white"
tools:context="com.cofoz.cofoz.MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="@color/colorPrimary"
        android:elevation="5dp"
        app:popupTheme="@style/AppTheme.PopupOverlay">

        <ImageView
            android:layout_width="69dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:contentDescription="logo"
            android:src="@mipmap/white_text_cofoz" />
    </android.support.v7.widget.Toolbar>

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white"
        app:tabGravity="center"
        app:tabIndicatorColor="@color/colorPrimary"
        app:tabPadding="10dp"
        app:tabSelectedTextColor="@color/colorPrimary"
        app:tabTextColor="@android:color/black" />

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

<include layout="@layout/content_main" />

<include
    layout="@layout/bottom_sheet"
    />

<com.andremion.counterfab.CounterFab
    android:id="@+id/counter_fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    app:backgroundTint="@color/colorPrimary"
    app:borderWidth="0dp"
    app:elevation="11dp"
    app:srcCompat="@drawable/ic_shopping_cart_black_24dp" />

A: Add this in your MainActivity
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

Then i suggest remove the child on your navigationView and add the logout in your activity_main_drawer
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@android:color/white"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:itemIconTint="@color/colorPrimary"
app:itemTextColor="@color/colorPrimary"
app:menu="@menu/activity_main_drawer" /> //This should end here

//activity drawer menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">

<group android:checkableBehavior="single">
    <item
        android:id="@+id/logout"
        android:icon="@drawable/logout_icon"
        android:title="Logout" />
</group>

Then to handle click event implement OnNavigationItemSelectedListener in your mainActivity
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.logout) {
        //Do something
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

Hope this helps
EDIT:
If you really want to add custom view in your navigationView, you need to create an instance of that view then add an onclicklistener


text:
Q: Asymptotic with respect to Poisson I encounter two problems in my assignment.
The first one is :
Suppose $X_1,X_2...X_n$ are i.n.d random variable with Poisson ($\lambda^{i}$).(a) Find the MLE 0f $\lambda$. (b) What is the Asymptotic distribution?
For (a) I find the Mle  is the root of $\lambda +2\lambda^{2}+3\lambda^{3}+...n\lambda^{n}=\Sigma_{i=1}^{n}ix_i$. It seems to no way to work out the closed form. Thus I don't know how to do (b).
The second is
Suppose $X_1,X_2...X_n$ are i.i.d random variable with Poisson ($\lambda$), $\lambda$ is an integer. (a) Find MLE (b) Find $lim_{n \to \infty}Var(\lambda^{MLE})$.
For (a) I use $\frac{L(\lambda)}{L(\lambda-1)}\geq1$, L is Likelihood function to derive a strange interval. $\lambda^{MLE}$ is the only integer in the interval. Then I have no idea about the (b). please give me a hint or some solutions.Thanks a lot


text:
Q: Using a Capture like a Slurpy I've been reading about Captures and this paragraph intrigued me:

Inside a Signature, a Capture may be created by prefixing a sigilless
  parameter with a vertical bar |. This packs the remainder of the
  argument list into that parameter.

This sounds a lot like a **@ (non flattening) slurpy, so this concocted this test code:
my $limit=1_000_000;
my @a=1 xx 10000;
my @b=-1 xx 10000;

sub test1(|c){
    1;
};

sub test2(**@c){
    1;
};
{
    for ^$limit {
        test1(@b,@a);
    }
    say now - ENTER now;
}
{
    for ^$limit {
        test2(@b,@a);
    }
    say now - ENTER now;
}

A sample run gives durations of each test block:
0.82560328
2.6650674

The Capture certainly seems to have the performance advantage. Is there a down side to using a Capture as a slurpy in this fashion? Have I over simplified the comparison?

A: A Capture has two slots, holding a VM-level array (positional arguments) and hash (named arguments). It is quite cheaply constructed, and - since |c style arguments are quite common in various bits of the internals - has been well optimized. Since a capture parameter slurps up both positional and named arguments, any named arguments will be silently ignored. That's probably not much of an issue for methods, where unrequired named arguments will be silently placed into %_ anyway, but might be a consideration if using this construct on a sub, since it's not a pure optimization: it changes behavior.
The **@c case allocates an Array, and then allocates a Scalar container for each of the passed values, placing them into the Scalar containers and those Scalar containers into the Array. That's a reasonable amount of extra work.
There's another case not considered here, which is this one:
sub test3(**@c is raw){
    1;
}

That places a List in @c, and sets its elements to refer directly to the things that were passed. This is a bit cheaper than the case without is raw. In theory, it could probably perform as well as - if not better than - a capture parameter like |c; it probably just needs somebody working on the compiler to have a dig into why it doesn't yet.
In summary, if not caring about enforcing itemization and/or having a mutable Array of incoming arguments, then adding is raw is probably a better optimization bet than picking a capture parameter: the argument processing semantics are closer, it's already a bit faster, will allow for more natural code, and has future potential to be every bit as fast as, if not faster, than |c.


text:
Q: How to stop GameObject duplications when reloading a scene? I'm making a game where the player can switch back and forth between levels. I use "DontDestroyOnLoad" to bring my player between them, but whenever I reload a scene, it duplicates the player, as well as everything else I want to keep loaded. Does anyone know any easy fix to this? I'm new to programming so keep it simple please.

A: probably you need to write something like this:
public static <TypeName> instance = null;
void Awake() {
  if (instance != null) {
    Destroy(gameObject);
  } else {
    instance = this;
    DontDestroyOnLoad(gameObject);
  }
}


text:
Q: Puzzled about for loops in C Just to be clear, I understand how for loops work. However, the different syntax causes me problems... Let me give you an example:
I was looking up a recursive sorting algorithm (insertion sort).  The code went like this:
void insertion_recursive(int array[],int size){
int i;

if (size<=1) return;

insertion_recursive(array,size-1);

for(i=size-1;i;i--)
   if(array[i]<array[i-1])
       swap(&array[i],&array[i-1]);
   else
       break;
}

I understand how the code works, but the condition for the loop is confusing me:
for(i=size-1 ; i ; i--)

What does it mean?  Just leaving 'i' without specifying a condition?

A: An expression represents a single data item--usually a number. The expression may consist of a single entity, such as a constant or variable, or it may consist of some combination of such entities, interconnected by one or more operators. Expressions can also represent logical conditions which are either true or false. However, in C, the conditions true and false are represented by the non-zero integer values and zero integer value, respectively. Several simple expressions are given below:
a + b
x = y
t = u + v
x <= y
++j

In your example, i is an expression whose value is expression's l-value which is in this case, it is the value of variable i.
The expression will evaluate to true for non-zero i values and false if value of i is zero.
So, for(i=(size-1); i ; i--) is equivalent to for(i=(size-1); i != 0; i--).

A: In C when trying to evaluate a condition, everything that is 0 is false, and everything else is true.
Even pointers are treated the same way. The constant NULL is actually defined as 0. In C++11 we finally have the null_ptr for type safety.
In C there is no bool type, and in C++ if you cast true to integer you get 1, and false casts to 0.

A: i by itself is converted to a boolean, similar to if (i) {...} or if (! i) {...}; integers are considered true when nonzero and false when zero.
So, for(i=size-1 ; i ; i--) is equivalent to for(i=size-1 ; i != 0; i--).


text:
Q: Issues in loading LayoutManager using requirejs I'm new to require js and i'm using backbone with layout manager. I've pasted my code below and i'm not able to get the layout manager to work and i get this error :
 "Uncaught TypeError: Cannot call method 'extend' of undefined"

in line where layoutmanager is used (Backbone.LayoutView.extend)
Main.js

require.config({
paths: {
    jquery: 'lib/jquery-1.9.1.min',
    underscore: 'lib/underscore-min',
    backbone: 'lib/backbone-min',
    handlebars: 'lib/handlebars',
    layoutManager : 'lib/backbone.layoutmanager'
    mousewheel : 'lib/jquery.mousewheel.min'
},
shim : {
    'backbone' : {
        deps: ['jquery', 'underscore' ],
        exports: 'Backbone'
    },
    'layoutManager' : {
        deps: ['jquery', 'underscore', 'backbone'],
        exports: 'LayoutManager'
    },
    'mousewheel' : ['jquery']
}

});
require(["jquery", "underscore", "backbone", "layoutManager", "handlebars","mousewheel", "common"],function($, _, Backbone, LayoutManager, Handlebars,mousewheel, App) {

App.Views.HelloView = Backbone.LayoutView.extend({
    template : '#hello_tmpl1',
});

App.Layouts.AppLayout = new BackBone.Layout({

    template : '#layout',
    views : {
        ".helloView" : new App.Views.HelloView()
    }
});

$('body').empty().append(App.Layouts.AppLayout.el.render());

});

Common.js
  define(function(){
    var App = null;
    App = { Models:{}, Views:{}, Collections:{}, Templates:{}, Router:{}, Layouts:{}};

   return App;
});

A: function($, _, Backbone, LayoutManager

Here you name it LayoutManager.
App.Views.HelloView = Backbone.LayoutView.extend({

Here you try to use it as Backbone.LayoutView... which doesn't exist (thus the undefined). Try
App.Views.HelloView = LayoutView.extend({

The Backbone var you have here is different from the global one, think requirejs :)

A: New version of layoutmanager doesn't use 'LayoutView' to create views. Use Backbone.Layout.extend({ ...}) to create your views ... have fun .. ;)


text:
Q: No such module 'GoogleMobileAds' in Swift 3
I did every solution from web search..
As you see the image, GoogleMobileAds.framework is included well.
But I can't build project with 'No such module 'GoogleMobileAds'' error
What should I try?
p.s. what I did additionally
Build Settings

*

*Other Linker Flags : $(OTHER_LDFLAGS) -ObjC

*Always Search User Paths : YES

*Framework Search Paths : $(inherited)

Add import AppDelegate

*

*import Firebase

p.s. I'm trying to integrate without CocoaPods

A: I have faced the exact same issue. Running the following command in Terminal solved it for me:
pod install --repo-update

A: Actually, you don't need CocoaPods.

*

*Just remove the framework from your project's hierarchy.

*Find the GoogleMobileAds.framework file you just unzipped and simply drag and drop it into the navigator (the view on the left that shows you all the files in your project)

*Make sure to check "Copy items if needed" and select the "Create groups" option when prompted.

Works like a charm to me.

A: If installed with "pod 'Google-Mobile-Ads-SDK'", remove it from pod file, run pod install, then add it back, run pod install again. :)

A: You need to make sure the framework is included in your targets Build Phases. Target>Build Phases>Link Binary With Libraries. If it is not there click the "+" sign to add it.

A: Make sure your Podfile file contains the following libs
  pod 'Firebase/Core'
  pod 'Firebase/AdMob'

Maybe it helps someone.

A: I ran into the same issue. I would suggest using the cocoapods. If you want to integrate the SDK manually, copy the framework to the root directory and then move it to the Frameworks folder later. It seemed to resolve my issue.

A: Open application prefenences and link this framework into your project. check'embedded framworks' and framework path too.
https://developers.google.com/admob/ios/quick-start
read this manual

A: I find the solution
just add "GoogleMobileAds" to your project holder
then open Build Phases choose Link Binary With Libraries and press + and choose "Add other..." find in your project holder "GoogleMobileAds" and ad it
enter image description here

A: Remember there are two places to update when you add/replace/move a framework:

*

*Under build phases be sure to add the framework to the list of libraries to link with

*For the target (not the project) add the directory containing the framework to the "Framework Search Paths" list of directories if it is not already present (for example, if you placed the framework in a path not previously containing frameworks)

A: You need to use the xcworkspace file. You are using the regular xcodeproj file:


text:
Q: SQL - How to return a set of numbers after a specific word In SQL i'm trying to return the first set of numerical values after a specific word. I only want the numbers from the string after the specific word.
eg:  ' hello : '
for example:
hello : 123            should return 123
hello : x123           should return 123
hello : 123 456        should return 123
cake : 10              should not return anything

So far I've worked out i need to do something like -
Declare @sInitialString varchar(max)
@sInitialString = " hello hello : 123 456"
--FIND ' hello : ' within @sInitialString
-- possibly save this a new substring or string?
-- find the first numerical value after this has been found

Seems simple but from previous posts it seems more complex.
I've managed to get all numerical values to return
DECLARE @sInitialString VARCHAR(MAX)

SET @sInitialString = (SELECT UPPER(' hello hello : 123 '))
select substring(@sInitialString,patindex('%[0-9]%',@sInitialString),100)

I just seem to be missing something either in my approach or the solution. Has anyone managed to achieve this?

A: Assuming your code works to find the relevant string, you can get the first value using outer apply:
select x.nums
from (select substring(@sInitialString, patindex('%[0-9]%', @sInitialString), 100) s
     ) s outer apply
     (select (case when s.s like '% %'
                   then left(s.s, charindex(' ', s.s)
                   else s.s
              end) as nums
     ) x

I don't think your logic actually works, though, because it is not looking for hello.  So, you might be looking for something more like:
select x.nums
from (select (case when @sInitialString like 'hello%[0-9]%'
                   then substring(@sInitialString, patindex('%[0-9]%', @sInitialString), 100)
              end) s
     ) s outer apply
     (select (case when s.s like '% %'
                   then left(s.s, charindex(' ', s.s))
                   else s.s
              end) as nums
     ) x;

A: Try solution below. To make last PATINDEX search work I had to add a space symbol at the end. I use 2 step to make code readable, but you can convert it into single statement to use in SELECT or use CTE to achieve multiple steps.
DECLARE @sInitialString VARCHAR(MAX) = ' hello hello : retert 123'
DECLARE @sToken VARCHAR(MAX) = 'hello :'

-- Add a character at the to make search of the numeric string end work
SELECT @sInitialString += @sInitialString  + ' '
-- Find String token and save the rest of the string to the variable
SELECT @sInitialString = SUBSTRING(@sInitialString, PATINDEX('%' + @sToken + '%', @sInitialString) + LEN(@sToken), 10000)
-- The extract string from first numeric character unitl last numeric
SELECT @sInitialString = SUBSTRING(@sInitialString, PATINDEX('%[0-9]%', @sInitialString), PATINDEX('%[0-9][a-z !@#$%^&*(()_]%', @sInitialString) - PATINDEX('%[0-9]%', @sInitialString) + 1)
SELECT @sInitialString


text:
Q: mongodb query findById() and month and year I've searched for an answer on how to solve my problem but found nothing, so I am very sorry if I am repeating a question that has been asked before.
i'm trying to find a results for a specific userId by month and year.
the dates has been stored in db in this format : yyyy-mm-dd.
I'm trying the following query with Mongo v3.6.8:
db.collection.find({
  $and: [
    {
      $expr: {
        $eq: [
          {
            $month: {
              $dateFromString: {
                dateString: "$Ntry.BookgDt",
                format: "%Y-%m-%d"
              }
            }
          },
          12
        ]
      }
    },
    {
      $expr: {
        $eq: [
          {
            $year: {
              $dateFromString: {
                dateString: "$Ntry.BookgDt",
                format: "%Y-%m-%d"
              }
            }
          },
          2020
        ]
      }
    },
    {
      $expr: {
        $eq: [
          "id",
          "5fab9a66c493dc4a3c49a7a3"
        ]
      }
    }
  ]
})

Sample data:
[
  {
    "userid": "5fab9a66c493dc4a3c49a7a3",
    "name": "user name",
    "acc": "admin",
    "Blas": "00.00",
    "Ntry": [
      {
        "Amt": "11.72",
        "BookgDt": "2020-08-16",

      },
      {
        "Amt": "16.72",
        "BookgDt": "2020-06-23",

      }
    ]
  },
  {
    "userid": "5fab9a77c493dc4a3c49a7a3",
    "name": "user name",
    "acc": "user",
    "Blas": "00.00",
    "Ntry": [
      {
        "Amt": "11.72",
        "BookgDt": "2020-08-23",

      },
      {
        "Amt": "16.72",
        "BookgDt": "2020-07-23",

      }
    ]
  }
]

so my query is to find all Ntry for UserId 5fab9a66c493dc4a3c49a7a3 in month 8 and year 2020, but I got this erorr:
query failed: (ConversionFailure) $dateFromString requires that 'dateString' be a string, found: array with value ["2020-08-16", "2020-06-23"]
can you please help me to find the suitable query, and thank you in advance.
here is also a mongo play ground link, It's the best for quick editing:

A: This pipeline should work:
db.foo.aggregate([
// Top level match
{$match: {userid: "5fab9a66c493dc4a3c49a7a3"}}

// Next, only keep entries in the Ntry array with month 8 and year 2020.
// addFields: {"Ntry": {$filter: {input: "$Ntry"}}} means overwrite the
// original Ntry array.
,{$addFields: {"Ntry": {$filter: {
                input: "$Ntry",
                as: "zz",
                cond: { $and: [
{$eq: [{$month:{$dateFromString:{dateString:"$$zz.BookgDt",format: "%Y-%m-%d"}}}\
, 8] },
{$eq: [{$year: {$dateFromString:{dateString:"$$zz.BookgDt",format: "%Y-%m-%d"}}}\
, 2020] }
                               ]}
            }}
    }}

// It is possible everything got filtered out of the Ntry array, leaving
// an empty (size 0) array.  We likely do not want that, so further
// cut down the output material.  You can comment this out to see what
// changes, especially if you change the month and year targets above.
,{$match: {$expr: {$ne: [ {$size: "$Ntry"}, 0] } }}

]);

It's probably simpler to call $dateFromString twice but if you are feeling adventurous, then use $let inside the cond to convert the date just once:
db.foo.aggregate([
{$match: {userid: "5fab9a66c493dc4a3c49a7a3"}}

,{$addFields: {"Ntry": {$filter: {
        input: "$Ntry",
        as: "zz",
        cond: {
           $let: {
                vars: {dd: {$dateFromString:{dateString:"$$zz.BookgDt",format: "%Y-%m-%d"}}},
                in: {
                    $and: [
                      {$eq: [{$month: "$$dd"}, 8] },
                      {$eq: [{$year:  "$$dd"}, 2020] }
                    ]
                }
           }
        }
    }}
}}
,{$match: {$expr: {$ne: [ {$size: "$Ntry"}, 0] } }}
]);


text:
Q: How to to get hiddenfield value in ItemTemplate Just want to ask how can I find hiddenfield in repeater because my problem I have button and I want to get the associate hiddenfield  inside ItemTemplate because I get null value when I try to get hiddenfield value
  <asp:Repeater ID="rp_resList" runat="server" OnItemDataBound="rp_resList_ItemDataBound">
            <ItemTemplate>

                    <asp:HiddenField ID="hf_resID" runat="server" Value='<%#  Eval("Id") %>' />
                    <a href='<%#  Eval("pageID") %>'><%#  Eval("name") %>

                    <asp:Literal ID="litSummary" runat="server" Text='<%#  Eval("summary") %>'></asp:Literal>

 <%--                   <asp:Repeater ID="rp_tagsSkill" runat="server">
                        <ItemTemplate>

                                <%#  Eval("Description") %>

                        </ItemTemplate>
                    </asp:Repeater>--%>
                    <asp:Repeater ID="rp_tagsTopics" runat="server">
                        <ItemTemplate>

                                <%#  Eval("Description") %>

                        </ItemTemplate>
                    </asp:Repeater>

                        <asp:ImageButton ID="imgbtnBookmark" runat="server"   OnClick="imgbtnBookmark_Click" />
                        <asp:DropDownList ID="ddlGroup" runat="server" DataSourceID="SqlDS_Groups" DataTextField="name" DataValueField="id" AppendDataBoundItems="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" >
<asp:ListItem Value="-1">Select Group</asp:ListItem>

protected void imgbtnBookmark_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
    Bookmark bm = new Bookmark();
    HiddenField hiddenField = rptGroup.FindControl("hf_resID") as HiddenField;
    bm.UserID =
    Guid.Parse(Membership.GetUser(HttpContext.Current.User.Identity.Name).ProviderUserKey.ToString());
    bm.Resoursce.ResourceID = Convert.ToInt32(hiddenField.Value);
    Bookmark.Insert(bm);
}

A: Try this, change you button tag to pass id as CommandArgument value
<asp:ImageButton ID="imgbtnBookmark" runat="server"
    OnClick="imgbtnBookmark_Click"
    CommandArgument='<%#  Eval("Id") %>'/>

in your button click event you can access id using
bm.Resoursce.ResourceID = Convert.ToInt32(e.CommandArgument.ToString());

A: Change rptGroup.FindControl("hf_resID") as HiddenField; to
        e.Item.FindControl("hf_resID")....
I hope this link will help you .

A: jquery
 function showid(dllval) {
            var ID = $(dllval).parent().parent().find('[id*="hiddenID"]').val();
alert(ID)
}

asp.net
<asp:DropDownList ID="ddl" runat="server" onclick="showid(this);" >
 </asp:DropDownList>
<asp:HiddenField ID="hiddenID" runat="server" Value='<%#Eval("ID")%>' />


text:
Q: My Windows Service setup.exe doesn't work on Windows Server 2016 machine i created an Windows Service application on .Net Framework 4.6 and an installation setup of this project. When i compile my project in release mode, it creates setup.exe and my .msi file. Normally, in Windows 10, my setup.exe and windows service works perfectly. But when i try to run the setup.exe in Windows Server 2016, this image is emerging:

When i click "Accept" button, ofcourse, it cannot download the .net framework 4.7.2 on windows server 2016.
My project doesn't have any dependecies with .net framework 4.7.2 as far as i know. And i have installed first versions of nugets that i used. Can you help me?

A: Finally I fix the problem! Setup Project prerequisites was the problem. In my prerequisites
net framework 4.7.2 version is selected and somehow i couldn't see this! All my solution work perfectly when I changed target .net framework in there.
For more information:
https://www.gonnalearn.com/target-version-net-framework-launch-condition-version/
The last thing "Check the prerequisites" in this website was my solution :)


text:
Q: Apache won't start in VirtualBox I'm running VirtualBox with a Windows XP SP 2 system (my native OS is Windows XP, too). I tried to install XAMPP, WAMP or EasyPHP but with all of them Apache won't start.
XAMPP says that port 80 is busy, but I'm not running any program since the VM is empty and I've just installed the OS and Firefox. I tried to edit the httpd.conf file anyway, setting another port but it gives me the same error.
I tried to start Apache manually by executing the httpd.conf file and I get an error like

Unable to start the application. The application configuration is not correct. Removing and installing the application again may solve the problem.

(I'm using Windows XP in another language so I don't know the exact error message in English)
Any help would be greatly appreciated!

A: Error message you posted is related to MSVCRT libraries.
This is due to manifest information inside httpd.exe or underlaying DLLs.
You need to install correct version of MSVCRT redistributable runtime on your virtual machine.
Which exact version of apache you are running? Or better say, provide download link, I can check version of MSVCRT lib for you.
Try this for fisrt or nay previous version if not succeeded :http://www.microsoft.com/download/en/details.aspx?id=5555
More info here