text:
Q: How to get Line exception The question is pretty clear.
And it should work with
StackTrace st = new StackTrace(exc, true);

//Get the first stack frame
StackFrame frame = st.GetFrame(0);

//Get the file name
//string fileName = frame.GetFileName();

//Get the line number from the stack frame
int line = frame.GetFileLineNumber();

the problem is that if I launch my application in debug mode it works always.
When I launch it in Release mode it seems it need the pdb files to get this information. So what are the drawbacks of keeping the pdb files (I thought they were needed only in debug mode). Viceversa is this the only way to get the exception line information?

A:
So what are the drawbacks of keeping the pdb files (I thought they were needed only in debug mode)

Mostly the fact that it makes for a bigger deployment. Apparently it doesn't affect performance.

Viceversa is this the only way to get the exception line information?

Yes, only the pdb contains the line information. But as mentioned in the comments, the line numbers may not be completely accurate in release mode.

A: In addition to the trick you're doing with the pdb files, you need to disable the "Optimize code" options for your project if you need to preserve the lines numbers (Not 100 %). But this is not recommended by anyway as it might make your program slower.
You can find that in the build options in the Project properties.
Optimize code rearranges your code removing, moving and adding lines to optimize it.


text:
Q: How to disable/block Node from requiring Addons? I'm using vm2 sandbox to only allow requiring some internal modules but how do you block requiring the Node Addons? The Addons might as well be doing the same things like disallowed modules. Do I strip it in /node/src/ or is there some other way? I can't find any Node arguments nor vm2 options.
My vm2 config is:
  new NodeVM({
    require: {
        external: true,
        builtin: [x,y,z],
        mock: {..},
        context: 'sandbox'
    }..

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python subprocess behaves different when called from Django vs unit test My first time posting - please go easy on me. I could not come up with a succinct title that summarizes this issue. I seem to have a codec problem.
My django-based website calls a subprocess (soffice) to convert uploaded documents to basic text files, to then go on to do some processing of the text from the doc. This was working beautifully for a time. On my local dev machine, the unit tests for file conversion still work perfect as does the complete django app, end-to-end. On the production server, where it all used to work, the file conversion call no longer works the same from within the django app, while it does work properly when run from the test code. This change in behavior appears to be the result of running general server updates.
args = ['soffice',
        '--headless',
        '--convert-to',
        'txt:Text',
        '--outdir',
        outDir,
        filePath]

subprocess.call(args)

fo = open(textFilePath, "r")

try:
    docText = fo.read()
except:
    print("Failed to read", textFilePath)
    docText = None

I removed some of the error checking to simplify a bit.
When I run the file conversion code as part of the complete django application on the production server, I can see that certain special characters such as symbol § are turned into garbage. But if I run the same file conversion code on its own, outside of django, on the same machine, those symbols are not corrupted. As mentioned, on my dev machine, it works both standalone and within django. The one difference between the two machines is how I run django. Locally, it's run using django's runserver command. On the production machine, it's using mod_wsgi with apache. I don't see how it's possible for django or mod_wsgi to interfere with what soffice is doing in the subprocess, but it does appear that way. I have opened a python shell on the problem server and run essentially the same code as above, getting clean text back, plus running the unit tests against it works too.
Any help is sincerely appreciated!

A: If you are using mod_wsgi daemon mode, ensure you are setting lang/locale as otherwise you are going to inherit a default encoding of ASCII from the operating system.

*

*http://blog.dscpl.com.au/2014/09/setting-lang-and-lcall-when-using.html
This would propagate through to sub processes as well.
if not using daemon mode, you really should be looking at doing so as it is preferred over embedded mode of mod_wsgi. If using embedded mode it is somewhat harder to change the lang/locale as must be done in Apache startup scripts and how you do that depends on the platform and distro.

A: The solution was to upgrade mod_wsgi using:
pip install mod_wsgi --upgrade


text:
Q: PDO PHP prepared and execute with UNIX_TIMESTAMP() I'm having problems with my execution for inserting item into MYSQL
I currently have this code
$save = $dbh->prepare("INSERT INTO tables(id,id2,datetime) VALUES(?,?,?)");
$save -> execute($id,$id2, "UNIX_TIMESTAMP()");

This gives me problems
PDOStatement::execute() expects at most 1 parameter, 3 given

A: You just can't use a function as param with execute.
Moreover, execute expects only one parameter : an array, you gave 3 parameters.
UNIX_TIMESTAMP() has to be written directly into the query and $id1,$id2 have to be put in an array
$save = $dbh->prepare("INSERT INTO tables(id,id2,datetime) VALUES(?,?,UNIX_TIMESTAMP())");
$save -> execute(array($id,$id2));

A: Matter not about function as param, the same problem I had
I just forgot to show data as array() items...
Either, you may use timestamp.
Instead of this:
$sec->execute($v,time(),$student_id);

One should be like this:
$sec->execute(array($v,time(),$student_id));


text:
Q: can't add an expression for a subfield in MongoDB Here is my code.
   Cart
        .aggregate()
        .match(where)
        .lookup({
            from: "product_catelogs",
            foreignField: "_id",
            localField: "product_id",
            as: "product"
        })
        .project({
          product: {
            $arrayElemAt: ["$product", 0]
          },
          "product.custom_field": {
            $add: [1, 1]
          },
          product_quantity: 1,
          product_variant: 1,
          guest_token: 1,
          user_id: 1,
          product_id: 1,
        })

In this I want to add a custom field with product object. but when I am trying to do so, I am facing this kind of error,

can't add an expression for a subfield of product because there is
  already an expression that applies to the whole field

Please help me out.

A: I'm afraid the only way you could go about this is to add another project pipeline that has projections of the product embedded fields individually together with the new field. An example follows:
Cart.aggregate()
    .match(where)
    .lookup({
        "from": "product_catelogs",
        "foreignField": "_id",
        "localField": "product_id",
        "as": "product"
    })
    .project({
        "product": { "$arrayElemAt": ["$product", 0] },
        "product_quantity": 1,
        "product_variant": 1,
        "guest_token": 1,
        "user_id": 1,
        "product_id": 1,
    })
    .project({
        "product.field1": "$product.field1", // <-- change to suit your actual schema
        "product.field2": "$product.field2",
        "product.field3": "$product.field3",
        "product.field4": "$product.field4",
        "product.custom_field": { "$add": ["$product.field4", "$product.field5"] },
        "product_quantity": 1,
        "product_variant": 1,
        "guest_token": 1,
        "user_id": 1,
        "product_id": 1,
    })


text:
Q: Crystal report pro 11 crashes when linking tables I have a series problem with Crystal report pro version 11.5.11.1470 SP 5. When i make a new report and add multiple tables and just press on link tab to make links between tables, it crashes and closes. I uninstalled the program so many times and installed it again but in vain. I googled this issue the whole day but with no luck at all. the technical issue log showes the following:
Problem Event Name: APPCRASH
  Application Name: crw32.exe
  Application Version:  11.5.11.1470
  Application Timestamp:    492e9155
  Fault Module Name:    MFC71U.DLL
  Fault Module Version: 7.10.3077.0
  Fault Module Timestamp:   3e77fc29
  Exception Code:   c0000005
  Exception Offset: 00032e72
  OS Version:   6.1.7601.2.1.0.256.4
  Locale ID:    1033
  Additional Information 1: 1fc1
  Additional Information 2: 1fc163a1c57ae45571bce37d539b233f
  Additional Information 3: 12a3
  Additional Information 4: 12a3f41f6385dcf1330ec81c9df2618c


text:
Q: How manage camera shutter speed and aperture in Android? I would like to manage camera shutter speed or aperture in Android
but I have not found nothing about that.
The problem is this one: I have to take a picture in macro mode with
flash but with newer smartphones the flash light is too strong and
the pictures are almost over exposed. I have tried exposure
compensation calls but it is not enough.
By using the Camera software I notice that the app manages the
camera aperture, and it is able to take good macro pictures even
though the flash is forced to on, so I think there is a way to do
that, can you help me?
I'm using both Samsung Nexus S and Samsung Galaxy W. The white
picture problems does not exist with Samusng Galaxy ACE: in this
case seems that there is a kind of an hardware light power
calibration before shooting.
Thank so much!

A: Sorry to bring that to you but this feature is simply not supported and no release date is planned.
See feature/bug report :
Modify Shutter speed and aperture of camera

A: Via the Camera 1 API on the Android side it isn't possible to manually set one of the two mentioned parameters directly. Neither the characteristics can be queried via a standardized method, because it isn't supported.
Of course there is a way around, to query or to set such properties via special methods:
// query all the settings you camera support (API 1)
mCamera.getParameters().flatten();
// set parameters - e.g. aperture
mCamera.getParameters().set("aperture", "80");

But the next thing is, that the specific device must support such a setting, which vary from device to device. On some devices there can be set certain values and with other you can't and can only use the ''auto'' mode.
Additionally the configuration strings (e.g. ''aperture'') and the range of the possible values are different on the devices. For this reason they developed the  Camera 2 API, which is more standardized and supports such functionalities. Additionally it is much easier to set or to query special configurations.
Exposure
Commonly all mobile devices have a built-in Exposure control and is called Auto Exposure (AE) control. With the AE, the device controls automatically the exposure of the image by default and equalize over or under exposed images.
The Metering Area (MA) and the Exposure Value (EV) - Compensation could help.
// Android (API 1)
mCamera.getParameters().setMeteringAreas(List<Camera.Area> meteringAreas);
mCamera.getParameters().setExposureCompensation(int value);

A: Sorry it's late but might be helpful for others
To set aperture:

Camera.Parameters params = camera.getParameters();
params.set("mode", "m");
params.set("aperture", "28"); //can be 28 32 35 40 45 50 56 63 71 80 on default zoom


text:
Q: differs between/among cultures Some say "among" is used in reference to vague entities, whereas "between" is used for specific entities, regardless of how many are involved. Also, "between" is used for multiple one-to-one relationships. What about the following? "cultures" seems vague as it does not pick out specific cultures, yet when we compare tea-drinking practice, we are comparing one culture with another at a time. So these seem to be conflicting considerations.

People all around the world drink tea, but the way they do so differs between/among cultures.

A:
...but the way they do so differs between/among cultures.

Both versions are valid.
If the same question had been  asked back before the 1950s, a grammarian would probably have insisted on using among because there are more than two tea-drinking cultures.
In the debate between vs among, Merriam-Webster says

We use between when we want to express a relation to things and have them considered as individual and usually equal entities: between the devil and the deep blue sea; the restaurant between my house and my work; a treaty between nations. This connotation stems from an earlier use of between that referred to a point between two places, or travel between two specific points. Among, on the other hand is the best word to use when referring to things collectively and imprecisely: for this reason, among many others; no honor among thieves.

In the OP's example, one could argue that among is preferable because the names of the tea-drinking cultures are not specified, unlike in this following example:

The differences between English, Chinese, and Arabic are significant

whereas no university is mentioned except in the subordinate clause

Among all the universities in the UK, Cambridge and Oxford are the oldest and most prestigious.

Although the names of the countries, in Merriam-Webster's example, are not mentioned–"a treaty between nations"– it is appropriate because of each nation has a one-to-one relationship regardless of the unspecified number.


text:
Q: Is Ra's al Ghul really immortal? I am a fan of Batman and justice league. I know the history of Ra' al Ghul, and that he restores his power from the Lazarus Pit.
My Question is: Does it make him immortal like Vandal Savage ? Or does he require the pit every time to restore his power?
If one time bath makes him immortal, then - since in Batman: Red-Hood Robin also took a bath in it - Robin should also be a immortal, shouldn't he?
If he is not immortal, then why does he say he is in Batman Begins?

A: No he is not immortal. He requires the Lazarus Pit in order to restore himself to his prime. This enables him to cheat death but can still die, unlike Vandal Savage. He can technically come back from the dead if placed in the Lazarus Pit, such as Jason Todd, the Red Hood.
In the Batman Begins movie, he was merely referring to what Ra's al Ghul represents to being immortal. Not himself. The idea that the need for justice against corruption, to do what is right at any price, will forever exist. At least to my understanding.


text:
Q: Codeigniter 3 - fetch data from another table where current ID I'm working on helpdesk system.
I created two tables contacts and contacts_comments.
Now I fetch contacts details by contact ID in view page - this working correct.
and now from view page I insert comments to second table contacts_comments.
To contacts_comments I insert message and current contact(ticket) ID.
And now I try display all this comments for current ticket ID.
<?php foreach ($comments as $comment): ?>

                                                <img src="<?php echo base_url(); ?>assets/c_admin/assets/images/users/avatar-8.jpg" alt="" class="avatar-xs rounded-circle" />

<?php echo $comment->ticket_client; ?> <?php echo $comment->created_at; ?>

<?php echo $comment->comments_message; ?>

                                                 Reply

                                        <?php endforeach; ?>

But this function display for me all comments from  table contacts_comments.
I try build function:
    //get comments by id
public function get_comments_by_id($id)
{
    $id = clean_number($id);
    $this->db->where('ticket_id', $id);
    $query = $this->db->get('contacts_comments');
    return $query->row();
}

Can anyone help me how to add to this query in CI3 with result somelike:
DB WHERE  contacts.id == contacts_comments.ticket_id


text:
Q: Switch login between normal user and admin user Hi i want to develop an app where the user can choose to login into a normal user account or an admin account. So basically, when he launch the app, he will be asked to click on 2 buttons, one user normal and one admin. How can i manage that in swift ?
Thanks

A: First create a Navigation Controller,then create a viewController Add 2 buttons in it. Create a segue for both buttons to the next viewController i.e your actual loginPage.(drag from the first icon to your actual login page)

Click on the segue and click 4th icon on the attribute inspector (top right side)
On textfield next to identifier , name it (eg : AdminLogin)
Click on the other segue and do the same  and name it UserLogin.
Create actions for each button on your viewController class
    @IBAction func ActionLoginAdmin(_ sender: Any) {

performSegue(withIdentifier: "AdminLogin", sender: nil)
}

    @IBAction func ActionuserAdmin(_ sender: Any) {

performSegue(withIdentifier: "UserLogin", sender: nil)
}

This is the basic. Please don't post questions like this. Learn something and post what you have tried.


text:
Q: How to fetch properties value in JSP as Boolean value for conditional check using Spring PropertyPlaceholderConfigurerconfiguration In my project we are using below configuration to the load configuration file in spring context.
<!-- Configuration property files -->
<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="systemPropertiesModeName">
        <value>SYSTEM_PROPERTIES_MODE_OVERRIDE</value>
    </property>
    <property name="locations">
        <list>
            <value>jdbc.properties</value>
            <value>jms.properties</value>
            <value>config.properties</value>
            <value>override.properties</value>
        </list>
    </property>
</bean>

Later I want read config.properties as Boolean value in JSP Page. then based on conditions I want to rendered some comment box in UI.
Do have any work around on this. Please help me with your suggestion, Thanks in advance


text:
Q: Can a hovering helicopter travel half the globe in 12 hours? Suppose we have a helicopter that is able to stay stationary in flight for extended periods of time.  If such a helicopter stayed at point A in the sky for 12 hours straight, would it reach the other side of the globe?

A: No. A helicopter that "stays stationary" does so in relation to the atmosphere around it and the atmosphere pretty much follows the ground underneath it. The atmosphere does not stand still while the earth rotates. If it did, we would experience constant winds on the order of 1000 km/h. That would not be pleasant.


text:
Q: Finding Orthogonal Vectors in a Plane How can I find orthogonal vectors in $\mathbb{R}^3$ that lie in a plane created by the equation below:
$$x_1-2x_2+4x_3=0$$
Thanks,

A: A plane has the equation
$$a x_1+b x_2+c x_3=d$$
The normal to this plane is $n=[a,b,c]$.
So you want two vectors perpendicular to each other, and perpendicular to $n$.
Pick any vector $v_0$ not parallel to $n$. Then $v_1=n\times v_0$ and $v_2=n\times v_1$ are the sought-after vectors. (see cross product)

A: From the equation of the plane, we find that the vector $\mathbf n=(1,-2,4)^T$ is normal to the plane. Every vector that's orthogonal to $\mathbf n$ lies in the plane. Three obvious choices are $(2,1,0)^T$, $(4,0,-1)^T$ and $(0,4,2)^T$. (In general, given a non-zero vector $(a,b,c)^T$, at least two of $(0,c,-b)^T$, $(-c,0,a)^T$ and $(b,-a,0)^T$ are non-zero and orthogonal to the original vector.) Choose any one of these for your first vector and the cross product of $\mathbf n$ with the chosen vector for the other.
Essentially, you've being asked to find an orthogonal basis of $\mathbf R^3$ such that two of the basis vectors span the given plane. In $\mathbb R^3$ you can take advantage of cross products to do this. In higher-dimensional spaces, you'll have to do something a little different. In this answer, Marc van Leeuwen describes an easy way to construct such a basis for a hyperplane in $\mathbb R^n$.


text:
Q: sending an http request over ssh server i have my data residing on an SSH server and i want to inquire and retrieve the data via HTTP POST and GET requests. i have been trying to do that using the simple url's http://127.0.0.1:9200/_search? but it gives me an empty response. What is the correct way to send requests over ssh server through http? my http post function looks something like this:
function spatialsearch(coordinates_selected) {
  var coords = coordinates_selected.geometry.coordinates;
  console.log('c',JSON.stringify(coordinates_selected.geometry.coordinates));
  var _url = 'http://127.0.0.1:9200/_search?';

  var b = {
    "query": {
      "bool": {
        "must": {
          "match_all": {}
        },
        "filter": {
          "geo_shape": {
            "metadata.o2r.spatial.geometry": {
              "shape": {
                "type": "polygon",
                "coordinates":
                coords

                /* [
                //     [-22.0, 76.0],
                //     [-27.0, 65.0],
                //     [-57.0, 65.0],
                //     [-59.0, 76.0],
                //     [-22.0, 76.0]
                ]*/

              },
              "relation": "within"
            }}}}}
  };

  console.log(b,'http sending request');
  return $http.post(_url,b);
}

i tried SSH tunneling using ssh -L9201:sshserver:9200 r_chau02@sshserver but i am still not getting any response.
update
i updated the port in my code to 9201 but still the result was same. The error in console is net::ERR_EMPTY_RESPONSE while the terminal generates channel 3: open failed: connect failed: Connection refused.

A: You are looking in the right direction, with a minor error. The HTTP request and forwarding port don't match (9200 and 9201).
You can either update your code to query on port 9201, or change the ssh tunnel to:
ssh -L9201:127.0.0.1:9200 r_chau02@sshserver

This will make ES available on localhost:9200 (assuming tunneling is enabled on the server, and ES is listening on the sshserver address).


text:
Q: how to loop through column names in R genres=c("Action","Adventure","Animation","Biography","Comedy","Crime",
 "Documentary","Drama","Family","Game.Show","Horror","Music","Musical",
 "Mystery","Romance","Sci.Fi","Short","Thriller","War","Western")

This is my vector of genres.
Another data set has the same column names.
This is the data set column names
"Title"        "Genre"        "imdbRating"   "Release_Year"
"Action"       "Adventure"    "Animation"    "Biography"    "Comedy"
"Crime"        "Documentary"  "Drama"        "Family"
"Fantasy"      "Game.Show"    "Horror"       "Music"
"Musical"      "Mystery"      "N.A"          "Romance"
"Sci.Fi"       "Short"        "Sport"        "Thriller"
"War"          "Western"

I want to run this command for all genres replacing each genre with the value.
     data_predict$genres[grepl("*genres*", data_predict$Genre)]=1

Orignal Data set

        data_predict<-structure(list(Genre = structure(c(3L, 1L, 2L), .Label = c("Action, Adventure, Sci-Fi",
"Action, Drama, War", "Sci-Fi"), class = "factor"), Action = c(0,
0, 0), Adventure = c(0, 0, 0), Animation = c(0, 0, 0), Biography = c(0,
0, 0), Comedy = c(0, 0, 0), Crime = c(0, 0, 0), Documentary = c(0,
0, 0), Drama = c(0, 0, 0), Family = c(0, 0, 0), Game.Show = c(0,
0, 0), Horror = c(0, 0, 0), Music = c(0, 0, 0), Musical = c(0,
0, 0), Mystery = c(0, 0, 0), Romance = c(0, 0, 0), Sci.Fi = c(0,
0, 0), Short = c(0, 0, 0), Thriller = c(0, 0, 0), War = c(0,
0, 0), Western = c(0, 0, 0)), .Names = c("Genre", "Action", "Adventure",
"Animation", "Biography", "Comedy", "Crime", "Documentary", "Drama",
"Family", "Game.Show", "Horror", "Music", "Musical", "Mystery",
"Romance", "Sci.Fi", "Short", "Thriller", "War", "Western"), row.names = c(NA,
3L), class = "data.frame")

Expected result
data_predicted<-structure(list(Genre = structure(c(3L, 1L, 2L), .Label = c("Action, Adventure, Sci-Fi",
    "Action, Drama, War", "Sci-Fi"), class = "factor"), Action = c(0,
    1, 1), Adventure = c(0, 1, 0), Animation = c(0, 0, 0), Biography = c(0,
    0, 0), Comedy = c(0, 0, 0), Crime = c(0, 0, 0), Documentary = c(0,
    0, 0), Drama = c(0, 0, 1), Family = c(0, 0, 0), Game.Show = c(0,
    0, 0), Horror = c(0, 0, 0), Music = c(0, 0, 0), Musical = c(0,
    0, 0), Mystery = c(0, 0, 0), Romance = c(0, 0, 0), Sci.Fi = c(0,
    0, 0), Short = c(0, 0, 0), Thriller = c(0, 0, 0), War = c(0,
    0, 1), Western = c(0, 0, 0)), .Names = c("Genre", "Action", "Adventure",
    "Animation", "Biography", "Comedy", "Crime", "Documentary", "Drama",
    "Family", "Game.Show", "Horror", "Music", "Musical", "Mystery",
    "Romance", "Sci.Fi", "Short", "Thriller", "War", "Western"), row.names = c(NA,
    3L), class = "data.frame")

A: Try
library(qdapTools)
mtabulate(strsplit(as.character(data_predict$Genre), ', '))

Or
 data_predict[-1] <- lapply(names(data_predict)[-1],
      function(x) as.numeric(grepl(x, data_predict$Genre)))


text:
Q: Python FTP (from ftplib module) fails on login to SFTP server I am doing the following
>> from ftplib import FTP
>> s = FTP('host','user','password') # Connect

and it fails giving the following
Traceback (most recent call last):   File "<stdin>", line 1, in  <module>
   File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ftplib.py", line 117, in __init__
     self.connect(host)
   File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ftplib.py", line 132, in connect
     self.sock = socket.create_connection((self.host, self.port), self.timeout)
   File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 571, in create_connection
     raise err socket.error: [Errno 60] Operation timed out

*

*I know that host, user, passwd are correct

*How do I debug/fix this error?

A: WinSCP (which you've otherwise been using to connect to the same server) supports SFTP and SCP, not FTP.
To write a Python program using SFTP, you should be using the Paramiko library.

A: Try doing it like this:
try:
    s = FTP(host)
    s.login(user, password)
except Exception, e:
    print "The error was:", str(e)


text:
Q: AS400 sql clear screen I am new to working with an AS400 green screen terminal and I am running some queries through the STRSQL command.
However, I cannot figure out how to clear the terminal screen to get rid of the past queries that were run.
An analogy; if im running command prompt and the screen gets too cluttered, i can run 'cls' to clear the screen. Is there a simular command on AS400?

A: You can press Shift-F1 (F13) and select option 3 "Remove all entries from current session".  Then press Enter to confirm.

A: EDIT: Short answer: No. <- This is incorrect.
Long answer: you probably don't want to use STRSQL anyway.  Use iNavigator (also on its way out) or IBM i Access for Web, which has a database interface.  Another IBM offering is Data Studio.  Alternatively, you could use any number of third party database tools like SQuirreL to do design work or for ad hoc queries.  Basically, anything that uses ODBC / JDBC will work.
As a side note, the platform hasn't been called AS/400 for 20 years.  Google searches for AS/400 are increasingly returning worse and worse results.  A more modern name (only 10 years defunct) is iSeries.  The current operating system is called IBM i, and the IBM web site is called the Knowledge Center.  It's true that 'IBM i' doesn't yield the best search results, but that will never change unless we start using the term on the internet :-)

A: I use STRSQL all the time to prove an SQL statement either in my RPG or Web-based pgm.
I don't like clearing the historical statements because sometimes I find a hint, or a technique that I may need to reference again at some point.
With all that being said...
If your screen is "crowded" and you just want a brand new screen - simply page-down.


text:
Q: Power BI Gantt Chart Can someone enlighten me on how to create a visual like this? Visual that show how long the business proposal has been and if they are still in negotiating phase or closing deals already.
I tried searching all over the internet for a week now, but until now I can't find any answer. Hope someone higher knowledge than me help me. Thank you in Advance

A: You can use Deneb and the VL template here to create this chart in PowerBI.

https://deneb-viz.github.io/
https://vega.github.io/vega-lite/examples/bar_gantt.html

A: This looks like it should work.
https://www.youtube.com/watch?v=9rBU7Xp1xYA
I have PBI on my work laptop, but I am not on that machine now. I don't have PBI installed on my personal laptop, so I can't try it out right now.


text:
Q: Inheriting from Window in WPF MVVM I'm trying to implement the following solution: https://stackoverflow.com/a/1486481/154439.  In the author's solution he writes,

I created an abstract ApplicationWindowBase class that inherits from Window.

I am not sure what he means here.  I tried changing my XAML from <Window ... to <ApplicationWindowBase ....  No luck.
The designer-generated file for the window inherits from System.Windows.Window, but as that file is designer-generated, making changes to it does me no good.  I've tried various other approaches with no success.
I am very new to both WPF and MVVM.  Am I missing something obvious?

A: Code to go along with Kevin's comment:
Code Behind
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : ApplicationWindowBase
{
    public MainWindow()
    {
        InitializeComponent();
    }
}

XAML
<myPrefix:ApplicationWindowBase x:Class="StackOverflow.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:myPrefix="clr-namespace:StackOverflow"
        Title="TestWindow" Height="300" Width="300">
    <Grid>

    </Grid>
</myPrefix:ApplicationWindowBase>

Just make sure you use the correct namespace, mine happens to be StackOverflow.

A: First, xaml or not, these are all classes.  Therefore, anything inheriting from another class (i.e., Window), must do so as any other class.
namespace SomeNamespace
{
    public sealed class MyWindow : Window
    {
        public object SomeNewProperty {get;set;}
    }
}

xaml is just a different type of serialization with its own set of rules.  But it's still serialized XML, and as such everything must be traceable back to its original type.
How xaml does this is through a facility in XML called "namespaces".  They fit well with our understanding of namespaces as C# developers, as we must map an XML namespace to a namespace in our application so that the xaml serializer can match an XML element with a CLR type.
Xaml uses a couple different ways of matching these namespaces.  One looks like a URL and is defined by an assembly attribute (e.g., "xmlns="http://microsoft.com/whatevs").  This works when the assembly is external to the one you are writing in.  In your case, you'll have to use the other method of identifying your namespace.  This specialized XML namespace is parsed by the xaml serializer in order to identify the namespace and containing assembly of your classes.  It goes by the form "clr-namespace:SomeNamespace;assembly=SomeAssembly".  You can omit the assembly bit if the type is in the current assembly.
To put it all together with the above example, you would create an instance of your new window like this:
<t:MyWindow
    xmlns:t="clr-namespace:SomeNamespace"
    xmlns="the standard microsoft namespace here"
    t:OmitOtherStuffBecauseThisIsAnExampleLol="true">


text:
Q: Comparing two Resizable Array Sets I am trying to find the union and intersection of two ResizableArraySet objects I made using a modified Set Interface that has a few methods taken away. I am having a tough time passing both sets and processing them both. I know that's not what exactly happens, but here is some code to better explain what I am trying to do. Here is the call in my tester.
System.out.println(Arrays.toString((set.union(set2)).toArray()));

So set is an object I made in the tester, and set2 is another ResizableArraySet object that I made to compare to set. When I print that, I just get an array of set2.
Here are the constructors and instance variables.
public class ResizableArraySet<T> implements Set<T> {

private int numberOfEntries;
private int size;
T[] array;

/**
 * Constructor for Set without size variable (Default size is 10)
 */
@SuppressWarnings({ "unchecked" })
public ResizableArraySet() {
    array = (T[]) new Object[10];
}

/**
 * Constructor for the Set with size variable
 *
 * @param size
 */
@SuppressWarnings({ "unchecked" })
public ResizableArraySet(int size) {
    this.size = size;
    array = (T[]) new Object[size];
}

Here is relevant code for my union method. If the intersection method is necessary, I can provide that in an edit, but I think the problem is the same in both methods.
@SuppressWarnings({ "unchecked", "unused" })
@Override
public Set<T> union(Set<T> anotherSet) {
    T[] newArray = (T[]) new Object[anotherSet.getSize()];
    int entries = this.size;
    System.out.println(entries); //Get 0, when the size is not 0
    for (int x = 0; x < entries; x++) {
        if (anotherSet.contains(array[x]) == false) {
            anotherSet.add(array[x]);
        }
    }
    return anotherSet;
}

Here are my add, remove, and contains methods
    @Override
public boolean add(T newEntry) {
    if (contains(newEntry)) {
        return false;
    } else if (array.length > numberOfEntries) {
        array[numberOfEntries] = newEntry;
        numberOfEntries++;
        return true;
    } else {
        array = Arrays.copyOf(array, (array.length * 2));
        array[numberOfEntries] = newEntry;
        numberOfEntries++;
        return true;
    }
}

@Override
public boolean remove(T anEntry) {
    if (contains(anEntry) != true) {
        return false;
    }
    for (int x = 0; x < numberOfEntries; x++) {
        if (array[x].equals(anEntry)) {
            // Loop to move the values down one index in the main array
            for (int a = x; a < numberOfEntries; a++) {
                array[a] = array[a + 1];
            }
            numberOfEntries--;
        }
    }
    return true;
}

@Override
public boolean contains(T anEntry) {
    for (int x = 0; x < numberOfEntries; x++) {
        if (array[x].equals(anEntry)) {
            return true;
        }
    }
    return false;
}

So to sum up my problem. I'm having trouble comparing both objects, because they both have to use the same methods [contains(anEntry), add(anEntry), getSize()]
Let me know if I'm missing any helpful code.
Does anyone have a solution to my problem

A: Here's how your union should look like.  It uses an iterator, which you'll need to implement.  This is because your otherSet variable is of type Set<T>, not ResizableArraySet<T>, so you don't have access to its array directly.
public Set<T> union(Set<T> anotherSet) {
    ResizableArraySet<T> newSet = new ResizableArraySet<>();
    for (int i = 0; i < numberOfEntries; i++) {
        newSet.add(array[i]);
    }
    Iterator<T> it = anotherSet.iterator();
    while (it.hasNext()) {
        T el = it.next();
        if (!newSet.contains(el)) {
            newSet.add(el);
        }
    }
    return newSet;
}


text:
Q: How to convert Map to Map in java? I have the Map of type Object, i need to convert this map into the type String.
Map<String, String> map = new HashMap<String, String>();
Properties properties = new Properties();
properties.load(instream);

Can any body please tell me, how to assign the properties to above map?
Thanks & Regards,
Msnaidu

A: Map<String, String> properties2Map(Properties p) {
            Map<String, String> map = new HashMap<String, String>();
            for(Map.Entry<Object, Object> entry : p.entrySet()) {
                String key = (String) entry.getKey(); //not really unsafe, since you just loaded the properties
                map.put(key, p.getProperty(key));
            }
            return map;
}

I also like to use utility methods with type arguments to walk around generic type invariance and do some "downcasting" or "upcasting" (when I KNOW it is safe to do so). In this case:
@SuppressWarnings("unchecked")
<A, B extends A> Map<B, B> downCastMap(Map<A,A> map) {
    return (Map<B, B>)map;
}

Then you can write
Properties p = ...
Map<String, String> map = downCastMap(p);

A: The cleanest way to add the properties to the map would be (following on from your example):
for (String propName : properties.stringPropertyNames()) {
    map.put(propName, properties.getProperty(propName));
}

This works nicely in this particular case, because the Properties object is really a map containing String keys and values, as the getProperty method makes clear.  It's only declared as Map<Object, Object> for horrible backwards-compatibility reasons.
By using the Properties-specific methods, rather than treating this as just a Map<Object, Object>, you can populate your Map<String, String> with perfect type-safety (rather than having to cast).

A: You can directly convert:
Properties properties = new Properties();
Map<String, String> map = new HashMap<String, String>((Map)properties);

A: Because we know that the Properties are a String-to-String mapping already, it's save to do it with rawtype and unchecked conversion. Just leave a comment:
    Properties properties = new Properties();
    properties.load(instream);

    @SuppressWarnings({ "rawtypes", "unchecked" })
    // this is save because Properties have a String to String mapping
    Map<String, String> map = new HashMap(properties);

A: With Java 8 and the addition of Streams, I would suggest you to use the APIs Steam provides
Here, we assuming that each of the values actually are String objects, the cast to String should be safe:
Map<String,Object> map = new HashMap<>();

Map<String,String> stringifiedMapSafe = map.entrySet().stream()
     .collect(Collectors.toMap(Map.Entry::getKey, e -> (String)e.getValue()));

Now, in case we not sure that all the element are String, and we want to filter the key/values with null:
Map<String,Object> map = new HashMap<>();

Map<String,String> stringifiedMapNotSafe = map.entrySet().stream()
             .filter(m -> m.getKey() != null && m.getValue() !=null)
             .collect(Collectors.toMap(Map.Entry::getKey, e -> (String)e.getValue()));

A: Map<String,String> getPropInMap(Properties prop){
    Map<String, String> myMap = new HashMap<String, String>();
    for (Object key : prop .keySet()) {
        myMap.put(key.toString(), prop .get(key).toString());
    }
    return myMap;
}

A: Iterate over Map Object, take k v, make them string and put it to a Map String.
Map<Object,Object> map1; // with object k,v
Map<String, String> mapString = new HashMap<String, String>();
for (Object key : map1.keySet()) {
                String k = key.toString();
                String v = mmap1.get(key).toString();
                mapString.put(k, v);
            }


text:
Q: What's the difference between Abstract Algebra and Group Theory? I'm slowly beginning a student of certain higher mathematics.
I'm trying to see if I would prefer to study Group Theory or Abstract Algebra.
I know that Abstract Algebra seems to "come before" Group Theory, in the sence that one usually learns the terminology of GT through AA.
Am I correct in thinking that AA is essentially a broader version of GT, whereas GT seems to just focus on rings and fields?
I'm basically trying to learn one of the two that will best lead to lie algebra(s), and get a pure math balance to differential geometry that I'm trying to learn now.

A: No-one can give you useful advice on what courses to take without knowing the actual content of those courses. Your best bet is to ask someone at your institution, who'll know best what's involved.


text:
Q: jQuery save state for a div after refresh

 <button class="hide">Hide/show</button>

    Data here

 <button class="hide">Hide/show</button>

    Data2 here

So I have this code, and i got it to work thanks to stackoverflow answerers, but I have a question about saving the state. I tried a cookie method, but I can't seem to figure out how to save state and load the saved value for each individual div from cookies.

A: Use class in place of id. Change your html like,

    <button class="hide">Hide/show</button>

Data here

    <button class="hide">Hide/show</button>

Data2 here

Live Demo
To save state try to use localStorage()
$(document).ready(function(){
    if(localStorage && localStorage.getItem('activeComm')){
        comm=localStorage.getItem('activeComm');
        $('#'+comm).slideToggle("fast");
    }
    $(".hide").click(function(){
       $comm=$(this).next(".comm");
       $comm.slideToggle("fast");
       localStorage.setItem('activeComm',$comm.attr('id'));
       return false;
    });
});

HTML

    <button class="hide">Hide/show</button>

Data here

    <button class="hide">Hide/show</button>

Data2 here


text:
Q: Custom JSON struct Unmarshal I'm using an API that returns the result as the name of the object and I am trying to unmarshal just the fields of the struct. Here is an example of the JSON:
{
  "AAPL": {
   "symbol": "AAPL",
    "description": "Apple Inc. - Common Stock",
    "lastPrice": 284.45,
    "openPrice": 284.69,
    "highPrice": 284.89,
    "lowPrice": 282.9197,
  }
}

You can see it is using "AAPL" as the name of the struct and I'm not sure how to unmarshal it. I'm looking to unmarshal into this struct:
type Quote struct {
    Symbol                    string  `json:"symbol"`
    Description               string  `json:"description"`
    LastPrice                 float64 `json:"lastPrice"`
    OpenPrice                 int     `json:"openPrice"`
    HighPrice                 int     `json:"highPrice"`
    LowPrice                  int     `json:"lowPrice"`
}

I assume I need to write a custom unmarshal func
func (q *Quote) UnmarshalJSON(b []byte) error {
...
}

I'm not sure of the contents. Any assistance is appreciated!

A: I think  you  are looking for json:"-".
https://golang.org/pkg/encoding/json/#Marshal
As a special case, if the field tag is "-", the field is always omitted. Note that a field with name "-" can still be generated using the tag "-,".


text:
Q: OS X El Capitan mail folder issue I upgraded my Macbook Pro this morning to Version 10.11, and all my personal mail folders disappeared with up to 24 months of archived and must needed emails.  They still show up on my iPhone 6...and I'm getting iCloud flow between the two.  How do I get them to reappear on my Mac?  Help?

A: It is a common issue, your data did not disappear. Just go to the tab "Mailbox" in Apple mail and than click "Synchronize". All your mails will be downloaded from the servers they were on.


text:
Q: graph isomorphism neural network I am trying to understand graph isomorphism network and graph attention network through PyTorch (GIN) and GAT for some classification tasks.
however, I can't find already implemented projects to read and understand as hints.
there are some for GCN and they are ok.
I wanted to know if anyone can suggest any kind of material except raw theoretical papers so I can refer to.

A: Graph Isomorphism networks (GIN) can be built using Tensorflow and spektral libraries.
Here is an example of GIN network built using above mentioned libraries:
class GIN0(Model):
    def __init__(self, channels, n_layers):
        super().__init__()
        self.conv1 = GINConv(channels, epsilon=0, mlp_hidden=[channels, channels])
        self.convs = []
        for _ in range(1, n_layers):
            self.convs.append(
                GINConv(channels, epsilon=0, mlp_hidden=[channels, channels])
            )
        self.pool = GlobalAvgPool()
        self.dense1 = Dense(channels, activation="relu")

    def call(self, inputs):
        x, a, i = inputs
        x = self.conv1([x, a])
        for conv in self.convs:
            x = conv([x, a])
        x = self.pool([x, i])
        return self.dense1(x)

You can use this model for training and testing just like any other tensorflow model with some limitations.


text:
Q: ArcGIS JavaScript API find the polygon a point belongs I have a shapefile containing polygons and whenever a user searches an address I store latitude and longitude of the location. I want to know which polygon this address belongs and I have id assigned for each polygon in the shapefile. But I am new to ArcGIS API I couldn't figure it out. I tried this:
var queryCitiesTask = new QueryTask({
    url: "https://****/gridpointspolygon/MapServer/1"
});
var query = new Query();
query.geometry = new Point(long, lat); //
query.spatialRelationship = Query.SPATIAL_REL_INTERSECTS;
query.outFields = ["pt_v03_ind"];
query.returnGeometry = false;
queryCitiesTask.execute(query, function (result) {
    console.log("test");
});


text:
Q: caja and QT applications - how to set QT_SCALE_FACTOR On this system (19.04 MATE with latest NVIDIA)  QT applications play with oversized menus and window decorations. To correct I set
QT_SCALE_FACTOR=1

into my .bashrc and this works when I call up an application from the command line.
However when caja calls an associated QT application, this environment variable is not being set. I have tried adding it to
~/.config/caja/desktop-metadata

and to
/etc/environment

but it has no effect.
Where can I set this?


text:
Q: Associating an attribute to an object I have the following program. I discovered the maximum age but how can I associate that age in my function with the respective person object I've created ?
class Info :

  def __init__ (self, first, last, height) :

    self.first = first
    self.last = last
    self.height = height

  def fullname (self) :

    return self.first + ' ' + self.last

person1 = Info ("A", "B", 178)
person2 = Info ("C", "D", 161)
person3 = Info ("E", "F", 170)
heights = [person1.height, person2.height, person3.height]

def highest_height (heights) :

  return max (heights)

print ("Displaying full names:", person1.fullname (), person2.fullname (), person3.fullname ())
print ("The highest height is {} cm.".format (highest_ (heights)))

Instead of printing the highest age is {} cm...
I want the highest person is ... with {} cm..

A: tallest = max([person1, person2, person3], key=lambda p: p.height)

will return you the tallest person because the max function takes a key that it uses to calculate that max.

From O/Ps comment:
You can avoid using lambda by making the key a standard python function
def metric(person):
    return person.height

max([person1, person2, person3], key=metric)

Or more simply - keep track of the person and the height in a loop,
tallest_p, tallest_h = None, -1  # assuming people can not be negitive height ;)
for person in [person1, person2, person3]:
    if person.height > tallest_h:
        tallest_p, tallest_h = person, person.height

A: Since you mentioned in a comment that you're wondering if there's a non-lambda way of doing this:
class Info :

  def __init__(self, first, last, height) :

    self.first = first
    self.last = last
    self.height = height

  def fullname(self) :

    return self.first + ' ' + self.last

person1 = Info ("A", "B", 178)
person2 = Info ("C", "D", 161)
person3 = Info ("E", "F", 170)
persons = [person1, person2, person3]
heights = [person1.height, person2.height, person3.height]

def highest_height(heights) :
  return max(heights)

def highest_person(persons):
    highest = max([p.height for p in persons])
    highest_persons = []
    for person in persons:
        if person.height == highest:
            highest_persons.append(person)
    return highest_persons

print ("Displaying full names:", person1.fullname(), person2.fullname(), person3.fullname())
print ("The highest height is {} cm.".format(highest_height(heights)))
print ("The highest person is {} with height {} cm.".format(highest_person(persons)[0].fullname(), highest_height(heights)))

Notice that highest_person() returns a list of all persons that have the highest size (this is because you could have multiple people who are the tallest if they are the same length)


text:
Q: sql server 2005 database password recovery i have one database in ms sql server 2005.
i create this long time back, now want to modify it but i lost the password, i remember the user name for that database, is there any way to recover the password for that database or
change its password ?
Thanks

A: Databases don't have passwords. You may be talking about:

*

*the password of a database master key, certificate or other cryptographic key encrypted by password

*the password of a SQL Server login

*the password of database backup media

None of these can be recovered if lost. The only one that can be brute forced is if you lost access to a SQL instance, see How to add a Windows user to the sysadmin fixed server role in SQL Server 2005 as a failure recovery mechanism


text:
Q: Are arrays treated like pointers when passed to subroutines in Fortran? I am trying to understand some Fortran code. There is a subroutine which takes a 2D array as input. Then this subroutine is called from somewhere else, but is passed the first element of a 2D array instead of the array itself. However, the subroutine seems to treat this input as if it were just the 2D array itself and is able to access all of its elements. This makes it seem like the subroutine actually accepts a pointer to a scalar, like how you can pass arrays in C/C++.
I have made a small example that demonstrates what I mean:
program main
    dimension k(2, 2);
    k(1, 1) = 1; k(1, 2) = 2
    k(2, 1) = 4; k(2, 2) = 3
    call test(2, k(1, 1))
end program

subroutine test(n, k)
    dimension k(n, n)
    do i=1, n
        write(*, '(2(I1 X))') (k(i,j), j=1,n)
    end do
end subroutine test

This program outputs the following:
1 2
3 4

Can someone explain this to me?

A: This seems to be a hack on the compiler, as you pass actually the array as a 2D (1,1) element (see http://astroa.physics.metu.edu.tr/MANUALS/intel_ifc/mergedProjects/optaps_for/fortran/optaps_prg_arrs_f.htm Intel seems to have changed their links...). As you can see at the bottom, you pass a fixed-shape array.
Then in the function itself, you hack the compiler and set the size of the array dimension k(n, n), so that's a different value than what you specified.
This is probably Fortran 77 code, in Fortran 90 and upwards, you would not do something as bad as this, as you can and should pass the array with the sizes directly to the function and it uses them directly.


text:
Q: Qt application different icon theme I've developed a text editor using Java and the QtJambi (Qt 4.6.3) library. The application has a QToolBar with some QActions with icons. My text editor can switch between two themes (dark and light). If i use black icons, the dark theme looks terrible, and if I use white icons, the light theme looks terrible too. I want to change the icons when I press the switch theme button.
The icons are declared like this:
private String inir = "classpath:/ico/";
private QIcon iconodeshacer = new QIcon(inir+"deshacer.png");

And I set them to the QActions this way:
private QToolBar herramientas = new QToolBar();
herramientas.addAction(iconodeshacer, "Deshacer", this, "deshacer()");

I've tried to change the inir String and apply:
herramientas.update();
herramientas.repaint();

I can't find a solution for QtJambi or regular Qt (from which I can translate).
I would like to declare both icon themes and apply them without having to declare each QAction outside the configuration and manually change the icon with setIcon();

A: You can implement a switchTheme function and call it each time when you want to change your theme. In this fuction you should load necessary icons.
class ActionManager : public QObject // Singleton
{
//...
QMap< QAction *, QString > allActions;

public:

  void registerAction( const QString& key, QAction *action )
  {
    allActions[action] = key;
    connect( action, &QObject::destroyed, this, &ActionManager::onActionDelete );
  }

  void switchTheme( const QString& themeName )
  {
    for ( QMap< QAction *, QString >::iterator i = allActions.begin(); i != allActions.end(); i++ )
    {
      const QString iconPath = QString( ":/icons/theme_%1/%2.ico").arg( themeName ).arg( i.value() );
      i.key()->setIcon( iconPath );
    }
  }

private slots:
  void onActionDelete()
  {
    QAction *act = qobject_cast<QAction *>( sender() );
    allActions.remove( act );
  }

};

//Usage:
QAction *saveAction = new QAction();
ActionManager::instance()->registerAction( act, "saveicon" );

//On applying theme:
ActionManager::instance()->switchTheme( "light ");
// Will load ":/icons/theme_light/saveicon.ico" for saveAction

A: Thanks to Dmitry Sazonov for giving me an idea. As I'm programming on java, not c++, its code is difficult to apply on my application. But I understood the idea. What I've done its storing the icon names on an String array and resetting the icons of the elements every time i switch the theme.
private String[] nombreiconoseditar = {"copiar.png", "cortar.png", "pegar.png", "", "deshacer.png", "rehacer.png", "", "buscar.png", "buscareemplazar.png"};

And I change the route to the icon folder and set the icon one by one in the element I want, in this example, I change all the icons on the QMenu editar.
inir="classpath:/ico/claro/";

List ed = editar.actions();
    for(int i=0; i<ed.size(); i++)
    {
        QAction tmp = (QAction) ed.get(i);
        tmp.setIcon(new QPixmap(inir+nombreiconoseditar[i]));
    }

Hope this can help someone with the same problem!


text:
Q: sylius: site not deploying correctly in production I've developed a sylius based site and all is working fine in development environment, but some problems have arisen when deploying it on the  production environment:
In Frontend: compiled frontend.js return an error:

(function ($) { Uncaught TypeError: undefined is not a function frontend.js:27
  (anonymous function)

jquery 1.8.0 is included before the line that produces the error.
In Backend: no errors seems to arise but select widgets doesn't render (none of them).
The steps done to deploy the site in prod were:

*

*Migrated the database.

*Installed in production environmnet:
php app/console sylius:install -e prod

*Cleared and warmed up the cache:
php app/console cache:clear --env=prod --no-debug
php app/console cache:warmup --env=prod --no-debug

*Dumped assets:
php app/console assetic:dump --env=prod

Curiously, when debug parameter is set to true in app.php none of these errors arise.
Thank you very much for your help!

A: You should run Assetic dump command with the no-debug option. php app/console assetic:dump --env=prod --no-debug.


text:
Q: Python - Print multiple functions in one line So when searching on google, the only think I found was printing print() functions all in one line. What I want to do is print multiple functions (like the def function1():) type of function.
if choice == "y":
      dice = input("What are the face values of the dice?")
      for c in dice:
        if c == "1":
          dot1()

I want to be able to print a possible dot2(), or dot3() if the choice is 2, or 3 on that same line. Is that possible? Right now dot1(), 2, and 3 looks like:
def dot1():
  print()
  print(" * ")
  print()
  return()

def dot2():
  print("*")
  print()
  print("  *")
  return()

def dot3():
  print("*")
  print(" *")
  print("  *")
  return()

If so please let me know! Also if you would like more code as an example let me know. This is really bugging me haha

A: Maybe you are trying to print the dot patterns of the dice faces?
def dot_pattern(c):
    dice_repr = {1: '\n *\n\n',
             2: '*\n\n  *',
             3: '*\n *\n  *',
             4: '* *\n\n* *',
             5: '* *\n *\n* *',
             6: '* *\n* *\n* *'}
    return dice_repr[c]

for c in range(1, 7):
    print(dot_pattern(c))
    print()

output:
Output
 *

*

  *

*
 *
  *

* *

* *

* *
 *
* *

* *
* *
* *

A: dice_dict = {
        1: dot1,
        2: dot2,
        3: dot3
}

dice_dict[1]() # loads function dot1.


text:
Q: How JavaScript's (0 == "") === true agrees with ECMA-262 type conversion rules? I've already seen several questions explaining why 0 == "" is true in JavaScript, but i have a bit deeper question.
So the answer to why is 0 == "" is true in JavaScript is that string "" gets converted to number, zero-length string is converted to zero number, but how this agrees with [9.3.1 paragraph of ECMA-262](http://www.ecma-international.org/ecma-262/5.1/#sec-9.3.1) which says that string should be parsed using given formal grammar and if it fails, then such string is converted to NaN. When i looked on this spec i thought that "" is not a string numeric literal and it should be parsed as NaN and NaN is not equal to 0.0.
So why above speculation isn't correct and 0 == "" is actually true?
Thanks in advance.

A: The grammar allows for StringNumericLiteral to be empty:

StringNumericLiteral :::
      StrWhiteSpaceopt
      StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt

A few lines down, it says:

A StringNumericLiteral that is empty or contains only white space is converted to +0.

and:

The MV of StringNumericLiteral ::: [empty] is 0.

So I'm afraid you simply didn't fully read the standard passage you're looking at. :)


text:
Q: Issue with composer update I've tried to run "php composer.phar update" but I got this error:
Key extra is a duplicate in ./composer.json at line 94
ComposerHookHandler::onPreUpdate
Deprecation Notice: The Composer\Package\LinkConstraint\VersionConstraint class is deprecated, use Composer\Semver\Constraint\Constraint instead. in phar:///home/budrysl2/domains/westeros.com.pl/public_html/composer.phar/src/Composer/Package/LinkConstraint/VersionConstraint.php:17

Deprecation Notice: The Composer\Package\LinkConstraint\LinkConstraintInterface interface is deprecated, use Composer\Semver\Constraint\ConstraintInterface instead. in phar:///home/budrysl2/domains/westeros.com.pl/public_html/composer.phar/src/Composer/Package/LinkConstraint/LinkConstraintInterface.php:17

Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- The requested package mediawiki/mediawiki-codesniffer 0.5.0 is satisfiable by mediawiki/mediawiki-codesniffer[v0.5.0] but these conflict with your requirements or minimum-stability.
Problem 2
- The requested package mediawiki/mediawiki-codesniffer 0.5.0 is satisfiable by mediawiki/mediawiki-codesniffer[v0.5.0] but these conflict with your requirements or minimum-stability.
Problem 3
- The requested package mediawiki/mediawiki-codesniffer 0.4.0 is satisfiable by mediawiki/mediawiki-codesniffer[v0.4.0] but these conflict with your requirements or minimum-stability.
Problem 4
- The requested package mediawiki/mediawiki-codesniffer 0.4.0 is satisfiable by mediawiki/mediawiki-codesniffer[v0.4.0] but these conflict with your requirements or minimum-stability.

I use it on my MediaWiki page on westeros.com.pl
Could anybody help me?

A: Except for the duplicate "merge-plugin" key, your composer.json is correct and installs fine on my setup :
Generating optimized autoload files
Key merge-plugin is a duplicate in ./composer.json at line 92
Class ComposerHookHandler is not autoloadable, can not call pre-update-cmd script
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating optimized autoload files
$

Maybe there was a problem in one of the package dependencies before ?


text:
Q: Help with Complex integration I have to calculate the following integral
$$\int_{-\infty}^{\infty} \frac{\cos(x)}{e^x+e^{-x}} dx$$
Anyone can give me an idea about what complex function or what path I should choose to calculate the integral?

A: By following the Daniel Fischer's suggestion, consider the integration path $\gamma=\partial D$ (with counter-clockwise orientation) where $D$ that is the rectangle with vertices in $R,R+i\pi,-R+i\pi,-R$. Since the zero set of $e^x+e^{-x}=2\cosh x$ is $\frac{\pi}{2}i+\pi i\mathbb{Z}$, by the residue theorem:
$$\int_{\gamma}\frac{\cos z}{e^z+e^{-z}}dz = 2\pi i\cdot\operatorname{Res}\left(\frac{\cos z}{e^z+e^{-z}},z=\frac{\pi}{2}i\right)=\pi \cosh\frac{\pi}{2}.$$
Since $\cos(z+\pi i)=\cos(z)\cosh(\pi)-i\sin(z)\sinh(\pi)$ and $\cosh(z+\pi i)=-\cosh(z)$, the contribute given by integrating $\frac{\cos z}{e^z+e^{-z}}$ along the horizontal sides the rectangle equals:
$$(1+\cosh\pi)\int_{-R}^{R}\frac{\cos z}{e^z+e^{-z}}dz,$$
because $\sin(z)$ is an odd function while $\cos(z)$ and $\cosh(z)$ are even functions.
When $|\Re z|=R$ we have:
$$|\cos z|\leq\sqrt{\cosh^2(|\Im z|)+\sinh^2(|\Im z|)}\leq \cosh(\Im z)$$
$$|2\cosh z|\geq 2\sinh(|\Re z|),$$
hence the contribute given by the vertical sides of the rectangle is negligible when $R\to +\infty$, and:
$$\int_{-\infty}^{+\infty}\frac{\cos z}{e^z+e^{-z}}\,dz = \frac{\pi}{2\cosh(\pi/2)}=\frac{\pi}{e^{\pi/2}+e^{-\pi/2}}.$$

A: $\newcommand{\+}{^{\dagger}}
 \newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\down}{\downarrow}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\isdiv}{\,\left.\right\vert\,}
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}
 \newcommand{\wt}[1]{\widetilde{#1}}$
\begin{align}&\color{#c00000}{%
\int_{-\infty}^{\infty}{\cos\pars{x} \over \expo{x} + \expo{-x}}\,\dd x}
=\Re\ \overbrace{%
\int_{-\infty}^{\infty}{\expo{\ic x} \over \expo{x} + \expo{-x}}\,\dd x}
^{\ds{\mbox{Set}\ \expo{x} \equiv t\ \imp\ x = \ln\pars{t}}}\ =\
\Re\int_{0}^{\infty}{t^{\ic} \over t + 1/t}\,{\dd t \over t}
\\[3mm]&=\color{#00f}{\Re\int_{0}^{\infty}{t^{\ic} \over t^{2} + 1}\,\dd t}
=\Re\bracks{2\pi\ic\,{\pars{\expo{\pi\ic/2}}^{\ic} \over 2\ic}
+2\pi\ic\,{\pars{\expo{3\pi\ic/2}}^{\ic} \over -2\ic}
-\int_{\infty}^{0}{t^{\ic}\pars{\expo{2\pi\ic}}^{\ic} \over t^{2} + 1}\,\dd t}
\\[3mm]&=\pi\expo{-\pi/2} - \pi\expo{-3\pi/2}
+\expo{-2\pi}\,\color{#00f}{\Re\int_{0}^{\infty}{t^{\ic} \over t^{2} + 1}\,\dd t}
\end{align}

From here we can get an expression for
  $\ds{\color{#c00000}{%
\int_{-\infty}^{\infty}{\cos\pars{x} \over \expo{x} + \expo{-x}}\,\dd x}
=\color{#00f}{\Re\int_{0}^{\infty}{t^{\ic} \over t^{2} + 1}\,\dd t}}\,$:
  \begin{align}&\color{#66f}{\large%
\int_{-\infty}^{\infty}{\cos\pars{x} \over \expo{x} + \expo{-x}}\,\dd x}
={\pi\expo{-\pi/2} - \pi\expo{-3\pi/2} \over 1 - \expo{-2\pi}}
=\pi\,{\expo{\pi/2} - \expo{-\pi/2} \over \expo{\pi} - \expo{-\pi}}
=\pi\,{\sinh\pars{\pi/2} \over \sinh\pars{\pi}}
\\[3mm]&=\pi\,{\sinh\pars{\pi/2} \over 2\sinh\pars{\pi/2}\cosh\pars{\pi/2}}
=\color{#66f}{\large\half\,\pi\,\sech\pars{\pi \over 2}}
\approx {\tt 0.6260}
\end{align}

We used the contour
There are two simple poles at $\ds{i = \expo{\pi\ic/2}}$ and at
$\ds{-i = \expo{3\pi\ic/2}}$ since the branch cut of $\ds{t^{\ic}}$ is given by:
$$
t^{\ic} \equiv \exp\pars{\ic\ln\pars{\verts{t}} - {\rm Arg}\pars{t}}\,,\qquad
t \not= 0\,,\quad 0 < {\rm Arg}\pars{t} < 2\pi
$$

A: Hint: You should find the solutions of
$$e^z+e^{-z}=0 ~~(*), $$
with $z=x+iy$. As
$$e^z+e^{-z}=(e^x+e^{-x})\cos y+i(e^{x}-e^{-x})\sin y,  $$
$(*)$ gives
$$\cos y = \sin y = 0$$ or $$\cos y= 0 \cap x = 0. $$
In summary $e^z+e^{-z}=0 \Leftrightarrow x= 0,~ y= \frac{\pi}{2}+k\pi, $ with $k\in\mathbb Z$: the poles of the function $f(z)=\frac{\cos z}{e^z+e^{-z}}$ lie on the imaginary axis.
Now you can use @DanielFischer comment.

A: You can use this way to do. Clearly
\begin{eqnarray}
I&=&\int_{-\infty}^{\infty} \frac{\cos(x)}{e^x+e^{-x}}dx=2\int_{0}^{\infty} \frac{\cos(x)}{e^x+e^{-x}}dx\\
&=&2\int_{0}^{\infty} \frac{e^{-x}\cos(x)}{1+e^{-2x}}dx=2\text{Re}\int_{0}^{\infty} \frac{e^{-x}e^{-ix}}{1+e^{-2x}}dx\\
&=&2\text{Re}\int_{0}^{\infty} \frac{e^{-(1+i)x}}{1+e^{-2x}}dx=2\text{Re}\int_{0}^{\infty} \sum_{n=0}^\infty e^{-(1+i)x}(-1)^ne^{-2nx}\\
&=&2\text{Re}\int_{0}^{\infty} \sum_{n=0}^\infty(-1)^n e^{-(2n+1+i)x}dx\\
&=&2\text{Re}\int_{0}^{\infty} \sum_{n=0}^\infty(-1)^n e^{-(2n+1+i)x}dx\\
&=&2\text{Re}\sum_{n=0}^\infty(-1)^n \frac{1}{2n+1+i}=2\sum_{n=0}^\infty(-1)^n \frac{2n+1}{(2n+1)^2+1}\\
&=&\sum_{n=0}^\infty(-1)^n \frac{2n+1}{2n^2+2n+1}=\frac{1}{2}\sum_{n=-\infty}^\infty(-1)^n \frac{2n+1}{2n^2+2n+1}\\
&=&\frac{\pi\sinh\frac{\pi}{2}}{\sinh\pi}=\frac{\pi}{2\cosh\frac{\pi}{2}}.
\end{eqnarray}
Here we used
$$ \sum_{n=-\infty}^\infty(-1)^n f(n)=-\pi \sum_{k=1}^m\text{Res}(\frac{f(z)}{\sin(\pi z)},a_k) $$
where $a_1,a_2,\cdots,a_m$ are poles of $f(z)$.


text:
Q: error:no match for 'operator ==',what should I do? I wanna create a function that receive 3 string-type parameters s,oldval,newval,using iterator,insert and erase to replace the oldval in s by newval.
When I compiler it,comes the error :no match for the operator == in....
string &foo(string &s,string &oldval,string &newval)
{
    string::iterator it=s.begin();
    while(it!=s.end())
    {
        if(*it==oldval)
        {
            it=s.erase(it);
            it=s.insert(it,newval);
        }
        ++it;
    }
    return &s;
}

A: it is iterating over the characters of the string; *it is a single character. You can compare that with another character, but not with a string.
Either oldval and newval should have type char, not string; or you need more complicated logic to look for and replace substrings, rather than single characters, in the input. The member functions find and replace might be helpful for that.
Note that replacing a single character is as simple as *it = newval;, with no need to mess around erasing and inserting characters.

A: A string iterator "points" to a type of char (the template parameter for std::basic_string that makes up the std::string type), but you're comparing that character to a string (oldval) using ==.
std::string doesn't have an overload comparison operator for char.

A: Viktor,
I have seen your question.
"s" is a string. Wenn you use pointer,pointer only points a character. That means, just one character is selected. How can you compare a character with a string? Compiler will tell you,
"no match for the operator == in..." .
You need to view the website:
http://www.cplusplus.com/reference/string/string/find/
Best regards
Dehlen Zhang


text:
Q: How we can define Early Stopping for Keras to check after each batch (not entire epoch) Normally Early stopping for Keras can be defined to check if it reaches a limit (loss, accuracy) after each epoch. But in mini batch method each epoch contains multiple loss, acc for training and validation phase. How we can tell Keras to check every acc or loss in an epoch for early stopping?
filepath="weights.best.hdf5"

checkpoint = ModelCheckpoint(filepath, monitor='acc', verbose=1, save_best_only=True)

early_stop = EarlyStopping(monitor='acc', patience=5)

callbacks_list = [checkpoint, early_stop]

history = model.fit(x, y, validation_data=(x_test, y_test), epochs=1, callbacks=callbacks_list)

A: Copy the code for EarlyStopping from the source and change on_epoch_end with on_batch_end. Update a few other things that talks about epoch and it's ready:
from tensorflow.python.platform import tf_logging as logging
import numpy as np
from keras.utils import io_utils
from tensorflow import keras

class BatchEarlyStopping(keras.callbacks.Callback):
    """Stop training when a monitored metric has stopped improving.
    Assuming the goal of a training is to minimize the loss. With this, the
    metric to be monitored would be `'loss'`, and mode would be `'min'`. A
    `model.fit()` training loop will check at end of every batch whether
    the loss is no longer decreasing, considering the `min_delta` and
    `patience` if applicable. Once it's found no longer decreasing,
    `model.stop_training` is marked True and the training terminates.
    The quantity to be monitored needs to be available in `logs` dict.
    To make it so, pass the loss or metrics at `model.compile()`.
    Args:
      monitor: Quantity to be monitored.
      min_delta: Minimum change in the monitored quantity
          to qualify as an improvement, i.e. an absolute
          change of less than min_delta, will count as no
          improvement.
      patience: Number of batches with no improvement
          after which training will be stopped.
      verbose: Verbosity mode, 0 or 1. Mode 0 is silent, and mode 1
          displays messages when the callback takes an action.
      mode: One of `{"auto", "min", "max"}`. In `min` mode,
          training will stop when the quantity
          monitored has stopped decreasing; in `"max"`
          mode it will stop when the quantity
          monitored has stopped increasing; in `"auto"`
          mode, the direction is automatically inferred
          from the name of the monitored quantity.
      baseline: Baseline value for the monitored quantity.
          Training will stop if the model doesn't show improvement over the
          baseline.
      restore_best_weights: Whether to restore model weights from
          the batch with the best value of the monitored quantity.
          If False, the model weights obtained at the last step of
          training are used. An batch will be restored regardless
          of the performance relative to the `baseline`. If no batch
          improves on `baseline`, training will run for `patience`
          batches and restore weights from the best batch in that set.
      start_from_batch: Number of batches to wait before starting
          to monitor improvement. This allows for a warm-up period in which
          no improvement is expected and thus training will not be stopped.
    Example:
    >>> callback = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=3)
    >>> # This callback will stop the training when there is no improvement in
    >>> # the loss for three consecutive batches.
    >>> model = tf.keras.models.Sequential([tf.keras.layers.Dense(10)])
    >>> model.compile(tf.keras.optimizers.SGD(), loss='mse')
    >>> history = model.fit(np.arange(100).reshape(5, 20), np.zeros(5),
    ...                     batches=10, batch_size=1, callbacks=[callback],
    ...                     verbose=0)
    >>> len(history.history['loss'])  # Only 4 batches are run.
    4
    """

    def __init__(
        self,
        monitor="val_loss",
        min_delta=0,
        patience=0,
        verbose=0,
        mode="auto",
        baseline=None,
        restore_best_weights=False,
        start_from_batch=0,
    ):
        super().__init__()

        self.monitor = monitor
        self.patience = patience
        self.verbose = verbose
        self.baseline = baseline
        self.min_delta = abs(min_delta)
        self.wait = 0
        self.stopped_batch = 0
        self.restore_best_weights = restore_best_weights
        self.best_weights = None
        self.start_from_batch = start_from_batch

        if mode not in ["auto", "min", "max"]:
            logging.warning(
                "EarlyStopping mode %s is unknown, fallback to auto mode.",
                mode,
            )
            mode = "auto"

        if mode == "min":
            self.monitor_op = np.less
        elif mode == "max":
            self.monitor_op = np.greater
        else:
            if (
                self.monitor.endswith("acc")
                or self.monitor.endswith("accuracy")
                or self.monitor.endswith("auc")
            ):
                self.monitor_op = np.greater
            else:
                self.monitor_op = np.less

        if self.monitor_op == np.greater:
            self.min_delta *= 1
        else:
            self.min_delta *= -1

    def on_train_begin(self, logs=None):
        # Allow instances to be re-used
        self.wait = 0
        self.stopped_batch = 0
        self.best = np.Inf if self.monitor_op == np.less else -np.Inf
        self.best_weights = None
        self.best_batch = 0

    def on_batch_end(self, batch, logs=None):
        current = self.get_monitor_value(logs)
        if current is None or batch < self.start_from_batch:
            # If no monitor value exists or still in initial warm-up stage.
            return
        if self.restore_best_weights and self.best_weights is None:
            # Restore the weights after first batch if no progress is ever made.
            self.best_weights = self.model.get_weights()

        self.wait += 1
        if self._is_improvement(current, self.best):
            self.best = current
            self.best_batch = batch
            if self.restore_best_weights:
                self.best_weights = self.model.get_weights()
            # Only restart wait if we beat both the baseline and our previous
            # best.
            if self.baseline is None or self._is_improvement(
                current, self.baseline
            ):
                self.wait = 0

        # Only check after the first batch.
        if self.wait >= self.patience and batch > 0:
            self.stopped_batch = batch
            self.model.stop_training = True
            if self.restore_best_weights and self.best_weights is not None:
                if self.verbose > 0:
                    io_utils.print_msg(
                        "Restoring model weights from "
                        "the end of the best batch: "
                        f"{self.best_batch + 1}."
                    )
                self.model.set_weights(self.best_weights)

    def on_train_end(self, logs=None):
        if self.stopped_batch > 0 and self.verbose > 0:
            io_utils.print_msg(
                f"Batch {self.stopped_batch + 1}: early stopping"
            )

    def get_monitor_value(self, logs):
        logs = logs or {}
        monitor_value = logs.get(self.monitor)
        if monitor_value is None:
            logging.warning(
                "Early stopping conditioned on metric `%s` "
                "which is not available. Available metrics are: %s",
                self.monitor,
                ",".join(list(logs.keys())),
            )
        return monitor_value

    def _is_improvement(self, monitor_value, reference_value):
        return self.monitor_op(monitor_value - self.min_delta, reference_value)

Note:
This is based off of the current implementation of EarlyStopping at this time. If you are reading this in the far future, you should probably check out the current source for the new version and modify it accordingly.


text:
Q: Rounding in Python round(1.4 999 999 999 999 999) (without the spaces) gets rounded to 2
but
round(1.4  99 999 999 999 999) (without the spaces) gets rounded to 1.
I suppose this has to do with imprecise floating point representations, but fail to understand how does it come that the first representation is interpreted as closer to 2 than to 1.

A: Because 1.4 999 999 999 999 999 when parsed is exactly 1.5, the difference between them is too small to represent at that magnitude.
But 1.4  99 999 999 999 999 is low enough to parse to "less than 1.5", actually 1.4999999999999988897769753748434595763683319091796875, which is clearly less than 1.5


text:
Q: List of @ContentChild() angular2 I have one component that has this template:
    <div class="col-md-12 navbar navbar-fixed-bottom navbar-light bg-faded noselect">
    <ng-content></ng-content>
</div>

If i need get the childs inside <ng-content> i use @ContentChild(), but i need get a list of components that are inside a <ng-content>. How do this ?


text:
Q: Windows VSS service I am a newbie and I am working on a driver that tracks creation/write/modification on files. Now I have been told to work on Volume snapshot. I have seen the code of VSS that comes with Windows SDK.
 But I have been informed to work on VSS at the kernel level, means I have to find out how I can use or communicate Windows Volume snapshot service through my driver. Please can someone give some inputs on this and try to help me because i googled a lot for Volume snapshot but did not get much help from there. Should I implement VSS Writer at the kernel level or something else to use the feature of Windows VSS service. Thanks in advance.

A: I think you should implement the VSS Hardware Provider.

*

*Get the development document
http://msdn.microsoft.com/en-us/library/windows/desktop/aa381601(v=vs.85).aspx

*Get the Sample Code

*

*You need to install the Microsoft SDK--for example--7.1

*Assumed that the SDK is installed under default path, access the path C:\Program Files\Microsoft SDKs\Windows\v7.1\Samples\winbase\vss\vsssampleprovider
Here you can find the sample codes.
Good Luck!

A: Should I develop a VSS writer or VSS provider : Neither. Incremental block level backup of files would require a FS mini-filter driver approach which, for the incremental time range Tn to Tn+1, should track block level writes happening on the live file. At time Tn+1, when the vss snapshot is taken, this minifilter should additionally track writes happening on the "file's view" sitting on the snapshot block device. The snap is not always read-only from birth. There is a brief time window in the VSS state machine during which the snapshot is actually writable so that various writers could do their thing (writes, updates, rollbacks etc). You could, in principle, also delete files from the snapshot while executing the onpostsnapshot callback (if you have a custom writer i.e.) The exact point in time when you'd need to stop live file tracking and start snapshot view tracking can be managed based on the completion of flush and hold writes IOCTL. So basically, at the end of snapshot, you'd have 2 change bitmaps : one that describes the writes on the live file and the other describing the writes on the snapshot view of the file. Merge these 2 bitmaps and then backup the changed blocks (based on the merged bitmap), off the snapshot block device. More or less similar scheme can also be applied for taking incremental block level backups of volumes.


text:
Q: Does ASP.NET MVC AntiCrsf token relies on machinekey We are using the asp.net MVC out of box AntiCSRF for security. We have lots of form which uses AJAX POST with JSON.
The application will be hosted in Azure using 3 Web Servers load balanced.
Can someone please clarify below:

*

*How does ASP.NET Generates the Csrf Token?

*If it uses Machine Key, do I need to configure anything to make sure the request works on Azure non sticky load balance?
Thanks.

A: Based on the source code of the Antiforgery class I can conclude that it does use the MachineKey to derive the tokens:

Though best practices in ASP.NET farm deployment use the same machine key for other reasons as well (authentication cookies when using Forms authentication, Viewstate signing and other security related items). I'd opt to sync them across the farm regardless of the Anti forgery token. This would be yet another reason to do so :).

A: It is send as a cookie and in a hidden HTML form field, both must be the same when submitted.
The idea is it that the cookie cannot be set by an outside attacker.
http://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-(csrf)-attacks


text:
Q: Why does the queue size remain zero? I am using multiprocessing to process my records.
queue = Queue()

def produce(i, item):
    data = process(i, item)
    queue.put(data)

def process(i, item):
    data = do_processing(i, item)
    return data

if __name__ == '__main__':
    records = load_records()

    with ProcessPoolExecutor(max_workers=os.cpu_count()) as executor:
        print('produce items')
        for i, item in ennumerate(records.items()):
            executor.submit(produce, i, item)

    print('queue size:{}'.format(queue.qsize()))
    while not queue.empty():
        save(queue.get())

Here I put records in a queue from produce as that step is time-consuming. After processing the records, I save them. As the consume step is not time consuming, I don't bother to run it in a separate thread.
Here after I execute the code, the queue remains empty. What is going on here?

A: I think this is how to do what you want. As mentioned in a comment, each process runs in its own memory space so global variables like the queue can't be simply shared and you can't pass it as an argument to each process.
When using a ProcessPoolExecutor, you can effectively do what's needed—sharing the queue—by defining an initializer function that will be called at the beginning of each process that will create a global for that process and pass the queue as an argument to it.
Here's something that closely resembles your code and is actually runnable illustrating what I mean:
from concurrent.futures import ProcessPoolExecutor
from multiprocessing import Queue
import os

MAX_RECORDS = 10

def load_records():
    return dict.fromkeys(range(MAX_RECORDS), 0)

def do_processing(item):
    return item

def init_queue(queue):
    globals()['queue'] = queue  # Makes queue a global in each process.

def produce(i, item):
    data = process(i, item)
    queue.put(data)

def process(i, item):
    data = do_processing(item)
    return data

if __name__ == '__main__':
    records = load_records()

    queue = Queue()
    with ProcessPoolExecutor(max_workers=os.cpu_count(),
                             initializer=init_queue, initargs=(queue,)) as executor:
        print('producing items')
        for i, item in enumerate(records.items()):
            future = executor.submit(produce, i, item)
        print('done producing items')

    print('queue size: {}'.format(queue.qsize()))
    while not queue.empty():
        print(queue.get())

Output:
producing items
done producing items
queue size: 10
(0, 0)
(1, 0)
(2, 0)
(3, 0)
(4, 0)
(5, 0)
(6, 0)
(7, 0)
(8, 0)
(9, 0)

A: Use multiprocessing.Queue() for handling multiprocessing.
queue = multiprocessing.Queue()

def produce(item):
    data = process(item)
    queue.put(data)

def process(item):
    data = do_processing(item)
    return data

if __name__ == '__main__':
    records = load_records()

    with ProcessPoolExecutor(max_workers=os.cpu_count()) as executor:
        print('produce items')
        for item in records.items():
            executor.submit(produce, item)

    print('queue size:{}'.format(queue.qsize()))
    while not queue.empty():
        save(queue.get())

A: def process(item):
    data = do_processing(item)
    return data

queue = Queue() # not a multiprocessing queue

with multiprocessing.Pool(processes=os.cpu_count()) as pool:
    for result in pool.imap(process, records):
        queue.put(result)

while not queue.empty():
    save(queue.get())


text:
Q: brew path didn't cover sbin I have problem when I used brew to install aircrack-ng. I found out that it cover path
/usr/local/Cellar/aircrack-ng/1.1/bin

but it couldn't find commands after I tried tab-completion in path
/usr/local/Cellar/aircrack-ng/1.1/sbin

What should I do? Do I need to add another path?

A: The sbin directory, which some admin tools like dsniff and aircrack install to, is not on the path by default, and it's not in Homebrew's initial setup instructions, which tell you to get /usr/local/bin on your path. This is because, traditionally, sbin/ is for administrative tools that only root would expect to run.
Tab completion is picking up the files in /usr/local/Cellar/aircrack-ng/1.1/bin because they are symlinked in to /usr/local/bin, which is on your PATH. It does not find the files in /usr/local/Cellar/aircrack-ng/1.1/sbin, because they are symlinked in to /usr/local/sbin, which is not on your PATH. Your current working directory does not matter for tab-completion, because . (the current directory) is not on the PATH.
If you want to see those other programs on your path, where tab-completion can pick them up, add /usr/local/sbin to your PATH in the same place you added /usr/local/bin - probably your ~/.bashrc file.
In general, if you want to use tab-completion on programs in the current directory, you need to call them with a ./ prefix. For example, cd /usr/local/sbin and then type ./air and hit tab, and you'll get some choices.

A: By convention, .../bin directories are for all users, .../sbin directories are for usage by root only. I don't know the setup if homebrew, but maybe /usr/local/Cellar/aircrack-ng/1.1/sbin is on the path if you are root?


text:
Q: Which one is more grammatical and idiomatic, "view something is" or "view something as"? The lecturer is saying

Something hits you really hard and then goes away, and then
  nothing happens for a very long period of time.
  And you'll learn this in the future, you can kind of view
  this is an impulse.

Is it more grammatical to rewrite the last part "you can kind of view
this is an impulse" as "you can kind of view this as an impulse"?

A: What are you trying to say here? "Something hits you really hard and then goes away, and then nothing happens for a very long period of time. And you'll learn this in the future, you can kind of view this is an impulse." I am unsure of the context.
'View this is' is not grammatically correct, as far as I know. Perhaps you could say 'see this is', if this is what you are trying to say.
If you are trying to say 'this can be seen as an impulse', you should use 'view this as'.

A: "View this as" is a phrase meaning to look at something from another perspective, usually as a way to recharacterize an action or an argument.
For example:

The child complained of a stomach ache.  I view this as a way to stay home from school.
I didn't want to go out with my coworkers for lunch because I brought my own lunch.  My coworkers view this as me not wanting to spend time with outside the office.


text:
Q: Can racerJS use native mongo ObjectIDs? I noticed that the latest commit to Racer's Mongo DB driver has to do with casting Racer's ids to Mongo ObjectIDs, any idea how to get that to work?

A: This driver is for Racer 0.3. Current version is 0.5. A lot of things have been changed: Share.js added, LiveDB, Redis, etc. You should use this driver now: https://github.com/share/livedb-mongo


text:
Q: Access Global .resx file in ASP.Net View Page I am currently building in Version 3.5 of the .Net framework and I have a resource (.resx) file that I am trying to access in a web application.  I have exposed the .resx properties as public access modifiers and am able to access these properties in the controller files or other .cs files in the web app.  My question is this: Is it possible to access the name/value pairs within my view page?  I'd like to do something like this...
text="<%$ Resources: Namespace.ResourceFileName, NAME %>"

or some other similar method in the view page.

A: <%= Resources.<ResourceName>.<Property> %>

A: Expose the resource property you want to consume in the page as a protected page property.  Then you can just do use "this.ResourceName"

A: If you are using ASP.NET 2.0 or higher, after you compile with the resource file, you can reference it through the Resources namespace:
text = Resources.YourResourceFilename.YourProperty;

You even get Intellisense on the filenames and properties.


text:
Q: How to make retina ready image that can be used on retina and non retina devices This is a follow up to the link below
Preparing the images for retina-ready (web)
This is clarification, because so many words mean different things to different people. It appears that to have one image that looks good on both retina and non-retina device:
if the image on the screen should be max-width of 400 and max-height of 300, then the image itself should be 800 x 600, with a ppi of 144. Then the file should be highly compressed to minimize its download time.
When you display the image, you force it to its max-width and max-height using css/html code like this:
<img src:"imagethatis800x600.jpg" style="width:400px; height:300px;" width="400" height="300" />

Is this correct? (I have already resolved that our company won't be using responsive.js or a cdn.)

A: An easier approach would be to use the srcset attribute of img. Then you can have images in different device pixels per CSS pixel.
Try to open this page both in a desktop browser and in a phone with a supported browser:
http://www.webkit.org/demos/srcset/
The support is still limited, but will probably be better supported soon:
http://caniuse.com/srcset

A: There's a new responsive images HTML5 standard. As of July 2014 it's only in beta builds of browsers yet. But the Picturefill polyfill is already available.
This article explains different use-cases quite well. But what you want here is to simply provide an alternative image for high-resolution (e.g. 'retina') displays:
<img srcset="small.jpg 1x, large.jpg 2x"
   src="small.jpg"
   alt="A rad wolf" />

A: For broad browser compatibility you could also use CSS background-images on container elements and control the background file (retina or non-retina) with media queries / dpi queries
Check out this fiddle
#container {
    background-image: url(http://placehold.it/200x200);
    width: 200px;
    height: 200px;

    @media
      only screen and (-webkit-min-device-pixel-ratio: 2),
      only screen and (min-resolution: 192dpi) {
          background-image: url(http://placehold.it/400x400);
    }
}


text:
Q: What is wavelength of electric field generated in a wire? I read link given below:
http://en.wikipedia.org/wiki/Speed_of_electricity
Above link says

_The speed at which energy or signals travel down a cable is actually the speed of the electromagnetic wave, not the movement of
  electrons. Electromagnetic wave propagation is fast and depends on the dielectric constant of the material. In a vacuum the wave travels at the speed of light and almost that fast in air.

and

Since the velocity of propagation is very
  high — about 300,000 kilometers per
  second — the wave of an alternating or
  oscillating current, even of high frequency,
  is of considerable length. At 60 cycles per
  second, the wavelength is 5,000 kilometers,
  and even at 100,000 hertz, the wavelength
  is 3 kilometers. This is a very large distance
  compared to those typically used in field
  measurement and application._

It gives wavelength of EM wave in wire.
How did they find it?
Edit : After reading comments
Also, why do you all say, it has nothing like that. That there is no such wavelength. Is Wikipedia wrong here then?
Edit 2 : I got that what wiki said was something different. They simply used $v = \lambda \nu$
Now, I wonder that electric field is caused by virtual photons. What is their frequency and wavelength in wire?

A: When you first connect the source, there is a very brief transient during which the steady-state DC solution is set up. The speed of the signal, i.e. the electromagnetic wave front that carries the information along the wire, is a bit less than the speed of light because of transmission line effects. Figuring out exactly how long the transient lasts would require a simulation that accounts for the distributed capacitance, distributed inductance, resistivity, and shape of the wire, not to mention the properties of the battery itself, but you can still make a rough estimate of the time constant as being the size of the system divided by the speed of light. For a small thing sitting on a table we're talking a nanosecond or so, so the transient will have a spread of frequencies roughly in the GHz range. It won't have a single well-defined frequency in general.
Once the transient is finished, you're now in a DC steady-state condition, and the frequency is 0 while the wavelength is infinite.


text:
Q: Solving cryptarithmetic problems I was recently trying to solve cryptarithmetic problems like:
       F Y H
     * E W T
     --------
     Z E T F
   E K Z Z
 Y Z T X
 ------------
 Y F Y W E F

But I am failing repeatedly to get the hang of such problems.I start solving problems but then I cannot get the intuition of such problems.How should I practise to master them?Any good resources in this regard?

A:      8 4 6
    *5 7 3
  ----------
   2 5 3 8
 5 9 2 2

4 2 3 0

4 8 4 7 5 8

where
F=8,
Y=4
H=6
E=5
W=7
T=3
Z=2
K=9
X=0


text:
Q: EWS Find Folder by Description I am working in VB.NET trying to attach to a folder within a user's account that has a specific word in the Description field.  In this particular case this folder will always be a calendar folder, but not always the user's main calendar.
This should be simple enough with a search filter, but to use one I need the correct extended property definition.  From what I can tell this should be PR_COMMENT_W (0x3004001F), but I cant seem to figure out how to adapt that to the New ExtendedPropertyDefinition Class.  Something like:
Dim TagComment As ExtendedPropertyDefinition = New ExtendedPropertyDefinition(0x3004001F, MapiPropertyType.String)
Dim view As New FolderView(10)
view.PropertySet = New PropertySet(BasePropertySet.IdOnly)
view.PropertySet.Add(TagComment)
Dim searchFilter As SearchFilter = New SearchFilter.ContainsSubstring(TagComment, "WordToFind")
Dim results As FindFoldersResults = Service.FindFolders(New FolderId(WellKnownFolderName.Root, New Mailbox("EmailAddress")), searchFilter, view)

A: Dim FolderDescription As ExtendedPropertyDefinition = New ExtendedPropertyDefinition(12292, MapiPropertyType.String)

That works =)


text:
Q: constexpr operator overloading issues with using arguments I am making a simple class inheriting from std::array. The point is that it should throw a compile time error if the subscript operator is used for an out of bounds index. However, I keep getting an error message. This is the code simplified.
#include <array>

using namespace std;

template<typename type, size_t size>
struct container : array<type,size>
{
    constexpr inline type& operator[](int index) const
    {
        static_assert(index<size,"");
        return ((static_cast<const array<type,size> >(*this))[index]);
    }

    template<class... bracelist>
    constexpr container(bracelist&&... B)
    :array<type,size>{std::forward<bracelist>(B)...}
    {}

    container() = default;
};

int main()
{
    constexpr container<int,4> myarray = {5,6,7,8};
    constexpr int number = myarray[2];
}

The error it gives me is:
main.cpp|80|error: non-constant condition for static assertion
main.cpp|80|error: 'index' is not a constant expression

However, I used "index" in the return statement, and commenting out the static_assert makes it work fine. If index was not a constant expression, wouldn't I not be able to use it in the subscript operator for std::array after the static_cast? I am new to using the constexpr functionality, so any help would be appreciated. Thank you.
Note: I am aware std::array's constexpr subscript operator already does this, I just want to know how to do this for future uses. Thanks.

A: There are 2 really useful features of constexpr functions, the interplay of which is not always fully appreciated.

*

*In constexpr context they only evaluate code paths that are taken for the constexpr arguments.

*In non-constexpr context they behave exactly like regular functions.
Which means that we can use exceptions to great effect.
Since while in constexpr context, if the exception path is taken, this is a compiler error (throw is not allowed in constexpr context). You get to see the "exception" in your compiler's error output.
example:
#include <array>
#include <stdexcept>

template<typename type, std::size_t size>
struct container : std::array<type,size>
{
    constexpr auto operator[](std::size_t index) const
    -> type const&
    {
        if (index < size)
            return static_cast<const std::array<type,size>>(*this)[index];
        else
            throw std::out_of_range("index out of range" + std::to_string(index));
    }

    template<class... bracelist>
    constexpr container(bracelist&&... B)
    : std::array<type,size>{std::forward<bracelist>(B)...}
    {}

    container() = default;

};

int main()
{
    constexpr container<int,4> myarray = {5,6,7,8};
    constexpr int number = myarray[4];
}

Example output:
main.cpp: In function 'int main()':
main.cpp:28:37:   in 'constexpr' expansion of 'myarray.container<int, 4>::operator[](4)'
main.cpp:13:81: error: expression '<throw-expression>' is not a constant expression
             throw std::out_of_range("index out of range" + std::to_string(index));

This approach is actually more versatile than static_assert, since it works at both compile and runtime.

A: The thing you have to keep in mind is that constexpr functions can be called at runtime with non constexpr arguments. constexpr means for a function that the function is usable in a compile-time evaluated expression (e.g. another constexpr or a template argument) but not exclusively. A constexpr function can still be called in the classical way, i.e. at run-time with run-time variables. Which means that the parameters of a constexpr function cannot be and are not compile-time constants.
It doesn't apply to your case but in general if you know a parameter will always be called with a compile time constant than you can make it a template parameter.
constexpr void foo(int a)
{
    static_assert(a != 0); // illegal code because the parameter
                           // cannot be a compile time constant
}

void test()
{
    int x;
    std::cin >> x;
    foo(x); // this is perfectly legal
}

template <int N>
void foo()
{
    static_assert(N != 0); // legal
}

void test()
{
    int x;
    std::cin >> x;
    foo<x>(); // illegal, x is not a compile time constant

    foo<24>(); // legal
    constexpr int c = 11;
    foo<c>();; // legal
}

A: This is the reason for std::get<N>(array) — it is the only way to assuredly pass a "compile-time value" in a manner that'll satisfy the rules of the language. Your attempt to create a compile-time op[] cannot work. You could of course make your own templated accessor like std::get, but one might ask why not just use std::array as it is already.