text:
Q: Python printing weird characters I'm running Windows 11, with the output in Windows Terminal
from gnewsclient import gnewsclient
import requests

print("requesting google news...")
news_list = gnewsclient.NewsClient('english', 'entertainment', 'US', 10).get_news()

item = news_list[0]
print("extracting text from web page...")

title = item['title'].rpartition(' - ')[0]

print(title)
print(item['link'])

output:
requesting google news...
extracting text from web page...
ภาวะตลาดหุ้นไทย: ดิ่ง 28.82 จุด ตามตลาดหุ้นโลกผวาเงินเฟ้อสหรัฐพุ่ง-กังวล MSCI - อาร์วายที9
https://news.google.com/__i/rss/rd/articles/CBMiI2h0dHBzOi8vd3d3LnJ5dDkuY29tL3MvaXEwNS8zMzIxNzcx0gEA?oc=5

Does anyone know how to correct this text?

A: The problem here is the order of the parameters.  You should read the code.    It wants location, then language, then topic.  So, you're not telling it to send English.  This is why the documentation suggests using named parameters.
news_list = gnewsclient.NewsClient(language='english', topic='entertainment', location='US', max_results=10).get_news()


text:
Q: React Fetch() my local Node Express backend; Cannot return get request String value I'm setting up a local backend server with node, and I'm trying use fetch to get values to render in my frontend react app. I've gotten most of the way, as everything compiles, however I'm running into issues with fetching the correct values. Or at least, I think I'm doing everything correctly.
The goal is to use fetch() in my app.js to get render values from route foo in server.js.
I can get a response from /foo but it is not what I was sending. I was sending a json object {text: "Foo"}
However, I'm receiving this in the console: App.js:12 Response {type: "basic", url: "http://localhost:3000/foo", redirected: false, status: 200, ok: true, …}
Any idea what I'm doing wrong?
Am I not fetching or sending objects correctly between routes? How can I get "Foo" to render on the line
The current state is {this.state.message}
 in
'App.js`
Here is my app.js:
import React, {Component} from 'react';
import './App.css';

class App extends Component {
    state = {
        message: ""
    };

    componentDidMount() {
        fetch('/foo')
            .then(res => {
                console.log(res);
                return res.json();
                // .then(express => this.setState({ express }))
                // .then(() => console.log(this.state.message));
            });
    }

    render() {
        return (

Users

The current state is {this.state.message}

        );
    }
}

export default App;

Here is my server.js:
const express = require('express');
const users = require('./routes/users');
const foo = require('./routes/foo');

const app = express();
const port = process.env.PORT || 8080;

// Set a route for when commands are processed for users
app.use('/users', users);
app.use('/foo', foo);

app.get('/api/hello', (req, res) => {
    res.send({ express: 'Hello From Express' });
});

app.listen(port, () => console.log(`Listening on port ${port}`));

Here is my foo.js
let express = require('express');
let router = express.Router();

router.get('/', function(req, res) {
    res.send([{text: "Foo"}]);
});

router.post('/', function(req, res) {
    res.send('POST handler for /foo route.');
});

module.exports = router;

A: the res.json() is still returning a promise, try this out:
  componentDidMount() {
    fetch("/foo").then(res =>
      res.json().then(data => {
        console.log("data", JSON.stringify(data, null, 4));
        // here you can set state
        //...
      })
    );
  }

redpajama_set_name: RedPajamaStackExchange


text:
Q: First item getting selected in listbox I want to select items with keywords facebook and twitter in it. But the problem is the first item which is "aggregator" always gets selected. Can anyone tell me what is wrong in the code. Thanks.
   int j=0;
   jList1.setModel(listmodel);
   for (int i=0;i<listmodel.size();i++){

       if (listmodel.getElementAt(i).toString().indexOf("facebook")!=-1||listmodel.getElementAt(i).toString().indexOf("twitter")!=-1){
           a[j]=i;

           j++;
       }
   }

   jList1.setSelectedIndices(a);

A: To select multiple elements, you can to use something like JList#addSelectionInterval, for example...

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ListSelectionExample {

    public static void main(String[] args) {
        new ListSelectionExample();
    }

    public ListSelectionExample() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                DefaultListModel model = new DefaultListModel();
                model.addElement("Bananas on facebook");
                model.addElement("Bananas in pajamas");
                model.addElement("Teddies in space");
                model.addElement("Teddies on twitter");
                model.addElement("Rat on the moon");
                model.addElement("Cow over the moon");
                model.addElement("Facebook pandas");

                JList list = new JList(model);
                for (int index = 0; index < model.getSize(); index++) {
                    String text = model.getElementAt(index).toString().toLowerCase();
                    if (text.contains("facebook") || text.contains("twitter")) {
                        list.addSelectionInterval(index, index);
                    }
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new JScrollPane(list));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}

A: I would guess that your int-array, a, is too large. Since each slot in an int-array defaults to 0, that would mean that the 0-th item in the list most likely gets selected, since it will be featured in a, unless a is completely filled with values found in your for-loop.

A: The issue is most likely with the definition of your array a. You must have initialized it as
int[] a = new int[listmodel.size()];

which will default the array elements to 0. So after the for loop, your a will look something like [1, 2, 4, 6, 0, 0, 0, 0] and it causes first element to be selected as well since there is 0 in the array.
Solution is to intialize a with a number which is much greater than the number of list items you expect to have.


text:
Q: Helm - Override list values with override file I want to override values between prod and dev deployments.
The default values look like:
apps:
  myapp:
    replicaCount: 2
    containers:
      - name: foo
        env:
          MODE: "dev"

I can override this in command line with:
--set apps.myapp.containers[0].env.mode="prod"

However I want to keep all the overrides in a file and run helm upgrade passing in an override file as well. Adding the override in the file like:
apps:
  myapp:
    containers[0]:
      env:
        MODE: "prod"

does NOT work.  How do I override values inside a list?

A: It is weird to say the least.
This worked:
apps:
  myapp:
    containers[1]:
      env:
        MODE: "prod"

So the index for containers is 1 when overridden in a file, however 0 when done using command line:
--set apps.myapp.containers[0].env.mode="prod"


text:
Q: Cardinality of ultraproducts This might be a trivial question, but I couldn't see how to do this now.
Given an infinite model $M$ and infinite cardinal $\kappa > |M|$ and a non-principal ultrafilter $F$ over $\kappa$, is it always true that $N = M^\kappa/F$ has cardinality $\geq \kappa$? If not, is it sometimes true?
Thanks a lot!

A: This is only a partial answer.
If $κ>|M|^+$ and $F$ is $|M|^{++}$-complete then $|M|=|N|$, if not, let $(f_i\mid i\in|M|^+)$ be a (possibly partial) listing of representatives of elements of $N$
Let $D_{i,j}$ be the set of indices where $f_i$ and $f_j$ disagree, this is a $F$-big set, in particular $\bigcap_{i<j\in|M|^+}D_{i,j}$ is not empty, if $m\in \bigcap_{i<j\in\lambda}D_{i,j}$ we have
$f_i(m)≠f_j(m)$ for all $i,j∈λ$ so $|\{f_i(m)\mid i\in |M|^+\}|=|M|^+>|M|$, contradiction.

A: I think $|N|$ could be smaller than $\kappa$ for some trivial reason: if $F$ contains a set $X$ of size $\lambda$ such that $|M|^\lambda<\kappa$, then $N=M^\kappa/F$ is the same as $M^\lambda/F'$ where $F'$ is the restriction of $F$ on $X$, so has size at most $|M|^\lambda<\kappa$.
If $F$ is uniform then the question becomes more interesting (probably more difficult too). If $|M|$ is countable and $F$ is countably incomplete, then $|N|$ is at least continuum, see section 5 of this survey.
Here is another short note which I vaguely remember but it took some time to find it again...If $F$ is regular then $N$ has the largest size possible, namely $|M|^\kappa$. Also from here it seems the general question is indeed quite difficult.


text:
Q: Override CSS ValidationMessageFor I can't seem to manage to put a new css in a validationMessageFor in my Ajax form...
 @using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "POST", OnSuccess = "Success", OnFailure = "Fail" }))
{

        @Html.LabelFor(m => m.Name)

        @Html.TextBoxFor(m => m.Name)

            @Html.ValidationMessageFor(m => m.Name)

        <input type="submit" value="Save" />
        <input type="button" id="btnCancel" value="Cancel" />

}
My css
.field-validation-error {
color: #e80c4d;
font-weight: bold;
}

.field-validation-valid {
display: none;
}

input.input-validation-error {
border: 1px solid #e80c4d;
}

input[type="checkbox"].input-validation-error {
border: 0 none;
}

.validation-summary-errors {
color: #e80c4d;
font-weight: bold;
font-size: 1.1em;
}

.validation-summary-valid {
display: none;
}

It doesn't override.. Why is that? Any help would be appreciated!
I copied the css directly from the default Asp MVC 4 application from visual studio,
I have no idea why this doesnt work.
The application I'm doing is not the default application from mvc 4, so there must be something I'm missing

A: You need to set .input-validation-error for validation for inputs
This is how you do it
.input-validation-error{ background: pink; border: 1px solid red; }

If you style up the .field-validation-error it will change the validation error message(s).
.field-validation-error{ color: red; font-weight: bold; }

Hope it helps


text:
Q: How to multiply two multi dimension array in R? I have two multi dimension array in R like
c_t <- array(0, dim = c(2,5,4,3,2),
             dimnames = list(c("id1", "id2"),
                             c("t1","t2","t3","t4","t5"),
                             c("occ1","occ2","occ3","occ4"),
                             c("age1","age2","age3"),
                             c("lvl1","lvl2")))
cc <- array(1:96, dim = c(2,2,4,3,2),
            dimnames = list(c("id1", "id2"),
                            c("id1", "id2"),
                            c("occ1","occ2","occ3","occ4"),
                            c("age1","age2","age3"),
                            c("lvl1","lvl2")))
c_t[,1,,,]=1

Which "c_t" is the situation of people (id) in time t, We assume at time 1 all ids are 1 and "cc" is switching matrix from time t to t+1.
I want to multiply this tow so I can find the id situations. I've already tried for loop.
for (t in 2:(dim(c_t)[2])-1) {#t is time dimension
  for (i in 1:dim(c_t)[1]) {#i is id dimension
    for (j in 1:dim(c_t)[3]) {#j is occ dimension
      for (k in 1:dim(c_t)[4]) {#k is age dimension
        for (l in 1:dim(c_t)[5]){#l is lvl dimension
          c_t[,t+1,,,][i,j,k,l]=c_t[,t,j,k,l]%*%cc[,i,j,k,l]
        }
      }
    }
  }
}

Is there any better way (right way) for multiply this tow array?


text:
Q: File Upload via Ajax using XMLHttpRequest I have been trying hard to know what can be the issue of Uploading image. Tried several ways, but couldn't succeed in Ajax. If I will upload file without using Ajax, it works fine : I am new to AJAX , so thus may be missing some trick.
Moreover, The full form is working perfectly with ajax, but $_FILES is creating a problem . ERROR IS:
Notice: Undefined index: Upload in Z:\xampp\htdocs\webseite\a.php on line 70
What can be the reason  ?
I know there are several posts related to that, but none matches with  XMLHttpRequest .
Thanks
This is the code.
HTML file has HTML code and Javascript/AJAX code.
Second file : a.php has PHP code.
<div class="form-group  mygroup">
          <label   for="name"> Upload (optional) </label>
          <input type="file" class="form-control" name="Upload" id="Upload">

</div>

 <script>
     var xhttp = new XMLHttpRequest();
      var Upload_rek=document.getElementById('Upload').value;

        xhttp.open('GET', 'a.php?&Upload_var='+Upload_rek+'&Senden_var='+Senden_rek, true);
       xhttp.send();
 </script>

<?php
 $target = "uploads/".basename($_FILES['Upload']['name']);
 ?>

A: You need to append your file using FormData
var formData = new FormData();
formData.append(file, file);
xhr.send(formData);

In your current code state you don't send/upload the file to the server at all.


text:
Q: Is anything known about $2\pi$ integer multiple arguments of the cosine integral? I'm interested in $\text{Ci}(2\pi n)$ for integers $n\geq 1$.
As the graph below shows, as $n$ increases the cosine integral seems to (strictly?) monotonically decrease. I've looked online but can't find much, and I'm wondering - is there a closed form expression for such values?
I have surmised that
$$\lim_{n\to\infty}(2\pi n)^2\text{Ci}(2\pi n) = -1.$$

A: I did not find any closed form but here is an expansion for large values of $n$ $$\text{Ci}(2 \pi  n)=-\frac{1}{4 \pi ^2 n^2}+\frac{3}{8 \pi ^4 n^4}-\frac{15}{8 \pi ^6 n^6}+\frac{315}{16
   \pi ^8 n^8}+O\left(\left(\frac{1}{n}\right)^9\right)$$ Hoping that this helps a little.
What should be of interest to you is to plot $n^3 \text{Ci}(2 \pi  n)$ as a function of $n$ even for small values : it looks like a straight line going through origin.
You could find interesting also,for large values of $n$, $$\text{Si}(2 \pi  n)=\frac{\pi }{2}-\frac{1}{2 \pi  n}+\frac{1}{4 \pi ^3 n^3}-\frac{3}{4 \pi ^5
   n^5}+\frac{45}{8 \pi ^7 n^7}+O\left(\left(\frac{1}{n}\right)^{8}\right)$$


text:
Q: Customize Highchart Map's legend type and color I'm currently working with a Drilldown Map (with Europe instead of the USA).
I would like to change the legend's type : in the example, it's a fade from light green to dark green ; what I would like to have is something like : [0-5 : Green] ; [5-10 : Blue] ; [10-15 : Yellow] etc.
Is there any way to do something like that?
Thanks a lot!

A: You can use dataClasses to achieve that:
colorAxis: {
    dataClasses: [
    {
        color: 'red',
        from: 0,
        to: 5,
        name: 'foo'
      },
      {
        color: 'blue',
        from: 5,
        to: 15,
        name: 'bar'
      },
      {
        color: 'yellow',
        from: 15,
        to: 60,
        name: 'xpto'
      },
    ]
}

Here's a fiddle: https://jsfiddle.net/ro91Lv2d/
To achieve something like the gradient you see on drill down you sent, you have to do it by yourself, like this example: https://jsfiddle.net/pzepywwy/


text:
Q: No videos in the mostPopular chart for certain video categories I'm trying to get a list of the most popular videos for certain video categories, however some categories return an empty list of videos despite the response being successful.
For example, the News & Politics category (ID 25):

I get the same response when making this request from my app. The category ID is valid and correct (as obtained from /youtube/v3/videoCategories). Changing the regionCode doesn't make a difference.

It's really important for the functionality of my app that a list of popular/recent/noteworthy videos for particular categories are shown. If there's no way to get the above request to return some videos, is there some kind of workaround that would return appropriate videos for the troublesome categories?

A: This looks like a bug to me
I tested it in the apis-explorer
Testing request 1:
Without category.  test here  scroll down there are some with nr 25
Request

GET https://www.googleapis.com/youtube/v3/videos?part=snippet&chart=mostPopular&maxResults=50&regionCode=us&fields=items%2Fsnippet%2FcategoryId&key={YOUR_API_KEY}

Response
{
 "kind": "youtube#videoListResponse",
 "etag": "\"RmznBCICv9YtgWaaa_nWDIH1_GM/ewwRz0VbTYpp2EGbOkvZ5M_1mbo\"",
 "pageInfo": {
  "totalResults": 0,
  "resultsPerPage": 50
 },
 "items": [
     "snippet": {
     "categoryId": "25"
      }
  ......
 ]
}

but as soon as you add the catagori id it returns 0
Test 2 fun results
A fun thing i found in my testing is if i add a category id of 10 link

GET https://www.googleapis.com/youtube/v3/videos?part=snippet&chart=mostPopular&maxResults=50&regionCode=us&videoCategoryId=10&fields=items%2Fsnippet%2FcategoryId&key={YOUR_API_KEY}

it returns others as well.
{
 "items": [
  {
   "snippet": {
    "categoryId": "24"
   }
  },
  {
   "snippet": {
    "categoryId": "10"
   }
  },
  {
   "snippet": {
    "categoryId": "10"
   }

I would submit a bug report. issue forum


text:
Q: SQL join avoid cartesian product Trying to avoid a cartesian product using the below tables
#t1 (1,'2019-03-01','TN',0.33)
    (2,'2019-03-01','TN',0.13)
    (3,'2019-03-01','TN',0.63)

#t2 ('2019-03-01','TN',3.1)
#t2 ('2019-03-01','TN',4.1)
#t2 ('2019-03-01','TN',5.1)

select * from #t1
select * from #t2

select a.cd,a.loc,(a.sales*b.multi)
from #t2 a join #t1 b on a.cd=b.cd and a.loc=b.loc

This understandbly returns a cartesian product :
2019-03-01  TN  1.023
2019-03-01  TN  1.353
2019-03-01  TN  1.683
2019-03-01  TN  0.403
2019-03-01  TN  0.533
2019-03-01  TN  0.663
2019-03-01  TN  1.953
2019-03-01  TN  2.583
2019-03-01  TN  3.213

How can i write the query to return a single row result set with Table B as the driver?
Expected Output:
1  2019-03-01 TN (0.33*3.1) -- value of
2  2019-03-01 TN (0.13*4.1)
3  2019-03-01 TN (0.63*5.1)

A: declare @t1 table(id int, cd date, loc varchar(2), sales money);
insert into @t1(id, cd,loc, sales)
values
--#t1
(1,'2019-03-01','TN',0.33),
(2,'2019-03-01','TN',0.13),
(3,'2019-03-01','TN',0.63);

declare @t2 table(cd date, loc varchar(2), multi decimal(5, 2));
insert into @t2(cd, loc, multi)
values
('2019-03-01','TN',3.1),
('2019-03-01','TN',4.1),
('2019-03-01','TN',5.1)

select *
from
(
    --this is better...than using t1 directly, especially if other locs are there (they wont have id starting from 1, 2, 3)
    select *, row_number() over(partition by cd, loc order by id) as rownum
    from @t1
) as t1
join
(
    select *, row_number() over(partition by cd, loc order by multi) as rownum --lowest multi gets 1, next gets 2 and so on
    from @t2
) as t2 on t1.cd = t2.cd and t1.loc = t2.loc and t1.rownum = t2.rownum;


text:
Q: OutputCache not working correctly -> ASP.NET MVC5 My output caching doesn't appear to be working as expected
This is a controller method to return the default page for my website.
I have cached it for 40secs (test -> in live it is cached for much longer)
[OutputCache(Duration = 40, Location = OutputCacheLocation.ServerAndClient, VaryByParam = "none")]
public async Task<ActionResult> Index(){
......
}

I have 2 problems
First
When I hit the endpoint for the first time it is cached correctly on the server and returns the following response header (as expected) among others.
status:200
Cache-Control:"private, max-age=40, s-maxage=0"

When I open a new browser tab and paste in the same endpoint after 5 seconds. it goes to the server and returns a 200 with content and the following header
status:200
Cache-Control:"private, max-age=63622944145, s-maxage=63622944105"

This does not seem correct to me. I expected it to send a request to the server with the an If-modified-since header. If the cached response was rebuilt since the time in the header then it would return a 200 + content else a 304. So in this case as the server cache was not rebuilt it should return a 304. Also as the max-age is so large it is now invalid and thus is immediately regarded as stale.
So what am I doing wrong...?
Secondly
I put a breakpoint in my Index method and hit the endpoint from my browser. On the first time I hit the Index endpoint the breakpoint is hit. Subsequent requests to the endpoint do not hit the breakpoint for the next 40 seconds as expected. However if I add a "/" to the end of my endpoint in the browser it will hit the breakpoint ignoring the cache.
How do I avoid this ..?

A: I just had this same problem. There's a thread on github here (I think it's a bug):
https://github.com/Microsoft/dotnet/issues/330
The solution for me was as follows:
(1) Download and install the .Net 4.6.2 Dev Framework pack. Go to the Properties page of your project, and either select it form the list or go to Install Other Frameworks...
(2) Target your app to 4.6.2. You'll need to restart the project (it has a message).
(3) Go to web.config and ensure these values are set:
<system.web>
<compilation targetFramework="4.6.2" />
<httpRuntime targetFramework="4.6.2" />

(4) Finally, go to the NuGet Package Installer and install the following package (search for it): Microsoft.AspNet.OutputCache.OutputCacheModuleAsync
The problem was fixed for me. I hope this helps.
Question 2: Removing trailing slash
Add this code in web.config in the proper section:
<system.webServer>
<rewrite>
  <rules>
    <rule name="Remove trailing slash" enabled="true" stopProcessing="true">
      <match url="(.*)/$" />
      <conditions>
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
      </conditions>
      <action type="Redirect" redirectType="Permanent" url="{R:1}" />
    </rule>
  </rules>
</rewrite>
<validation validateIntegratedModeConfiguration="false" />


text:
Q: What does "plenaried" mean in this phrase? A recently-asked question, since deleted by its author, prompts the following question.
In a 12 March 2013 New York Times column called The Axis of Ennui, David Brooks  concluded with:

What are the names of the people who are leading this shift? Who is the Steve Jobs of shale? Magazine covers don't provide the answers. Whoever they are, they don't seem hungry for celebrity or good with the splashy project launch. They are strong economically, but they are culturally off the map.
This revolution will not be plenaried.

What does the last sentence mean?
Adjective plenary has senses that include "Fully attended; for everyone's attendance" and "(theology or law) Complete; full; entire; absolute".  The noun phrase plenary session typically refers to  "a session in a conference which is open to all (or a large number) of attendant speakers, who may each contribute prepared or ad-hoc material".
But what does  "This revolution will not be plenaried" mean?

A: David Brooks started his column explaining how he spends a lot of time on conference circuits.  He goes on to explain that the big drivers of innovation are not always the young, photogenic, well-spoken people seen at these lectures, but rather less visible or less media-exposed engineers and business people.
"The revolution will not be plenaried" means that big changes will not come from the "30 under 30" or Ted Talk types that many assume are doing great things.  Big changes will instead come from big companies that we might otherwise think are not capable of challenging the status quo.

A: This revolution will be driven by a small, anonymous collection of engineers, scientists, and entrepreneurs.

A: A closed and confidenial revolution.

A: Talked to death by the ill-informed.


text:
Q: MVC custom groups for authorization I've done some searching but it doesn't look like a very commonly-asked or answered question. I need to implement a custom group authorization policy in an MVC application I am developing. It sort of follows the "classic" example:
Group
A user can create a group. A group exists as an object in a database with an Id, Name, and, among other things, a List of Users who belong to this group.
Role
A user can hold a role in many groups. For example, the creator of the group instantly becomes the administrator of the group. Different roles can access different things within the group.
I know it's very easy with pre-defined groups, but what about when I want to make the groups dynamic and each group be an object in the database?
A simple example of this in the real world would be groups on facebook, which have Admins, moderators, content-creators, etc. And only members can see them, edit them, or post to them.
Any ideas?

A: This is a very subjective design question and there is probably no single "right" answer.
I tend to use the aspnet Roles for application-level roles, like for Sysadmins and normal users and has to do with application-level permissions - ability to add new users to the application, ability to delete records, ability to edit records, etc.
It sounds to me more like this is something you want users to be  able to do themselves without oversight.
Create a Groups table, and have a many to many relationship with a Users table that defines which groups users are a part of.
If you only want 1 admin per group, you could make the Group table have an AdminUserId column. Otherwise have a many-to-many relationship table, GroupAdmins (I'd go for this option as it allows extensibility).

A: You could inherit AuthorizeAttribute to create any security scheme you like. But since you said it is not about authorization I am not sure if that is the right approach.
The AuthorizeAttribute does 2 different things:

*

*Checks if the current user can access the current controller/action.

*Executes a handler to take an action when they are not authorized.

Both of these things can be customized by subclassing AuthorizeAttribute. It is unclear from your question what action is supposed to be taken if the user doesn't belong in a Group or Role.
In any case, the best option for cross-cutting concerns (which this appears to be) is to implement either IActionFilter or IAuthorizationFilter (which is implemented by AuthorizeAttribute).

NOTE: Microsoft hasn't implemented this feature very well (or at least they tend to favor ActionFilterAttribute in their marketing, which are attributes that have behavior) for those of us using dependency injection. See passive attributes for the best option if you happen to be using DI in your application. See a couple of examples here and here.


text:
Q: HTML DIV is not moving from right to left diagonally towards end

          <button onclick="myMove()">Click Me</button>

In the above code I have 2 cubes(div). On click of button, the left cube should move from left to right till the end of the container diagonally and right cube should move from right to left diagonally till the end of the container. But only left cube is moving from left to right and right cube is moving from top to bottom. I want right cube to be moved from right to left diagonally till the end of the container. And this is my sandbox link. https://codesandbox.io/s/autumn-sun-uz961?file=/index.html

A: .animate1 class has left:350px make it to right:0 it will work.

function myMove() {
        var elem = document.getElementById("animate");
        var elem1 = document.getElementById("animate1");

        var pos = 0;
        var pos1 = 0;
        var id = setInterval(frame, 5);
        var id1 = setInterval(frame1, 5);

        function frame() {
          if (pos == 350) {
            clearInterval(id);
          } else {
            pos++;
            elem.style.top = pos + "px";
            elem.style.left = pos + "px";
          }
        }

        function frame1() {
          if (pos1 == 350) {
            clearInterval(id1);
          } else {
            pos1++;
            elem1.style.top = pos1 + "px";
            elem1.style.right = pos1 + "px";
          }
        }
      }
    #container {
      width: 400px;
      height: 400px;
      position: relative;
      background: rgb(240, 240, 231);
    }

    #animate {
      width: 50px;
      height: 50px;
      position: absolute;
      background-color: red;
    }

    #animate1 {
      width: 50px;
      height: 50px;
      right:0px;
      position: absolute;
      background-color: rgb(43, 1, 1);
    }

      <button onclick="myMove()">Click Me</button>

A: Update your css and change left: 350px; to right: 0px; for #animate1 :

function myMove() {
  var elem = document.getElementById("animate");
  var elem1 = document.getElementById("animate1");

  var pos = 0;
  var pos1 = 0;
  var id = setInterval(frame, 5);
  var id1 = setInterval(frame1, 5);

  function frame() {
    if (pos == 350) {
      clearInterval(id);
    } else {
      pos++;
      elem.style.top = pos + "px";
      elem.style.left = pos + "px";
    }
  }

  function frame1() {
    if (pos1 == 350) {
      clearInterval(id1);
    } else {
      pos1++;
      elem1.style.top = pos1 + "px";
      elem1.style.right = pos1 + "px";
    }
  }
}
#container {
  width: 400px;
  height: 400px;
  position: relative;
  background: rgb(240, 240, 231);
}

#animate {
  width: 50px;
  height: 50px;
  position: absolute;
  background-color: red;
}

#animate1 {
  width: 50px;
  height: 50px;
  right: 0px; /* instead of right : 350px; */
  top: 2px;
  position: absolute;
  background-color: rgb(43, 1, 1);
}

  <button onclick="myMove()">Click Me</button>

A: Off Topic, but are you aware of CSS transitions?

function myMove() {
  document.getElementById("animate").classList.toggle("move");
  document.getElementById("animate1").classList.toggle("move");
}

// try clicking the boxes themselves
for (let item of document.querySelectorAll("#animate, #animate1")) {
  item.onclick = function() {
    item.classList.toggle("move");
  }
}
#container {
  width: 400px;
  height: 400px;
  position: relative;
  background: rgb(240, 240, 231);
}

#animate {
  width: 50px;
  height: 50px;
  top: 0;
  left: 0;
  position: absolute;
  background-color: red;
  transition: 3s linear;
}

#animate.move {
  top: 350px;
  left: 350px;
}

#animate1 {
  width: 50px;
  height: 50px;
  right: 0px;
  top: 2px;
  position: absolute;
  background-color: rgb(43, 1, 1);
  transition: 3s linear;
}

#animate1.move {
  top: 350px;
  right: 350px;
}

  <button onclick="myMove()">Click Me</button>


text:
Q: Css - How can I change a watermark according to active tab? I have the following links:

        Applicant

        Providers

Then I have:

which contains my watermark.
How can I change it dynamically, when a certain tab is selected?

A: You can try something like this:
$('#menu li').click(function()
{
    $(this).siblings('li').removeClass('active');
    $(this).addClass('active');

    if ($('#navAppPop').hasClass('active'))
    {
        $("#watermark").css('background-image', 'url(assets/images/appWatermark.png)');
    }
});

Just add the code for the other tabs in the click function as well.
What this does is to change which link is active and sets the background according to which link has the active class.


text:
Q: what is the regex pattern for a regex pattern? What is the regex pattern for a regex pattern? I am using Ruby version 1.8.7, and have a requirement to determine if a given string is a regex pattern. What is the best pattern to use to determine this?
Thanks,
Anand

A: well any word can be a regex pattern.  The string "cat" could be compiled to a regex pattern. You could do something like:
def is_regex?(str)
  Regexp.new(str) rescue false
end

A: There isn't one, since regexes themselves aren't a regular language (due to things like matching parentheses).
If you want to determine whether something is a valid regex, I'd recommend just trying to compile it as a regex and see if it fails.

A: Assuming the regex pattern is a string with two forward slashes, / defining the pattern, then the regex to find a pattern with two foward slashes at the beginning and end of a pattern is as following:
(\/(?:.)*\/(?:i|g|s|m|U)*)


text:
Q: Android Google Maps v2 testing I have an activity that displays a list on markers based on the state of a model.
Whenever the model's state is changed, the markers are refreshed to display the new location or display any new markers.
I want to test this behavior but GoogleMap does not provide a .getMarkers() method or similar to know which markers are shown on the map.
The question is, how can I test both the number of Markers and the LatLng or each marker.

A: keep an ArrayList of all plotted markers and iterate through to find the one you want?
or there is a 3rd party mapping library that you can call getMarkers, getPolygons etc..

A: Thats just an idea but you can store you marker (latlng, id, image, etc) on an ArrayList. Then when you create your marker, assign foreach the id and on click retrieve the id to get all information's from your Array.


text:
Q: What is a stable way to perform command line operations with multiple parameters from Java? I have read several questions about how to execute an external program from Java, for example:
Using Runtime.getRuntime().exec with multiple parameters
How to execute command with parameters?
Java: Running cmd commands (multiple commands with multiple arguments at once)
and probably a couple more, but none of the suggested solutions works for me.
Code:
public static void freezeAllChromeInstances() throws IOException, InterruptedException {

    String[] freezeAllChromeInstances = {"/usr/bin/killall", "-STOP "
            + "\'Google Chrome\'"
            + "chromedriver-mod"
            + "\'Google Chrome Helper (Renderer)\'"
            + "\'Google Chrome Helper\'"
            + "\'Google Chrome Helper (GPU)\'"};
    Runtime run = Runtime.getRuntime();
    Process pr = run.exec(freezeAllChromeInstances);
    Thread.sleep(1000);
    pr.waitFor();
    BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    String line = "";
    while ((line=buf.readLine())!=null) {
        System.out.println(line);
    }
}

Quite simple to understand: I want to pause everything Chrome. Running /usr/bin/killall -STOP 'Google Chrome' chromedriver-mod 'Google Chrome Helper (Renderer)' 'Google Chrome Helper' 'Google Chrome Helper (GPU)' from the command line works as expected but my code above has no effect at all.
I have tried with a single string, a string array as above, with or without escaping the apostrophes, combining kill and -STOP in one string and so on.
How are you supposed to do this? Would be good with a final, works for all, solution.

Update: forgot to mention - I have also tried
    ProcessBuilder pb = new ProcessBuilder("/usr/bin/killall", "-STOP "
            + "\'Google Chrome\'"
            + "chromedriver-mod"
            + "\'Google Chrome Helper (Renderer)\'"
            + "\'Google Chrome Helper\'"
            + "\'Google Chrome Helper (GPU)\'");
    Process p = pb.start();

A: You concatenate the chrome process names to a single one without spaces by using '+' instead of ','. Changing this works for me (I added the last one because this is the name of the process in my Ubuntu):
String[] freezeAllChromeInstances = {"/usr/bin/killall", "-STOP",
                                     "\'Google Chrome\'",
                                     "\'chromedriver-mod\'",
                                     "\'Google Chrome Helper (Renderer)\'",
                                     "\'Google Chrome Helper\'",
                                     "\'Google Chrome Helper (GPU)\'",
                                     "/opt/google/chrome/chrome"};
Runtime run = Runtime.getRuntime();
Process pr = run.exec(freezeAllChromeInstances);
pr.waitFor();

Same goes for the ProcessBuilder version - you need to create a String[] there as well:
ProcessBuilder pb = new ProcessBuilder(new String[]{"/usr/bin/killall", "-STOP",
                                       "\'Google Chrome\'",
                                       "\'chromedriver-mod\'",
                                       "\'Google Chrome Helper (Renderer)\'",
                                       "\'Google Chrome Helper\'",
                                       "\'Google Chrome Helper (GPU)\'",
                                       "/opt/google/chrome/chrome"});
Process p = pb.start();

Also, I think there is no need to sleep a second if you wait for the process to terminate anyways. And it may also help to print the getErrorStream() output as well.


text:
Q: How to implement an asynchronous parallel genetic algorithm using the MATLAB Parallel Computing Toolbox? I am struggling to find a way to implement an asynchronous evolutionary process in MATLAB.
I've already implemented a "standard" GA that evaluates the fitness of individuals in parallel using MATLAB's parfor routine. However, this also means that the different workers in my parallel pool have to wait for the last worker to finish his assesment before I can create a new generation and continue with my parallel fitness evaluation. But when the fitness assessment time is very heterogeneous, such an approach can involve significant idle times.
The suggested solution in the literature is what is sometimes called asynchronous evolution. It means that there are no generations anymore, instead every time a worker becomes idle we immediately let him breed a new individual and evalute its fitness. As such there is hardly any idle time as no worker has to wait for others to complete their fitness assessment. The only problem is that those parallel threads/workers need to work on the same population, i.e. they need to communicate to each other whenever they want to breed a new individual (because they need to select parents out of a population that is constantly altered by the workers).
Now ideally you would control each worker separately, letting him access the joint population to select parents, evaluate the offspring's fitness and then replace a parent in the joint population. That involves an ongoing iterative process where parallel workers need to exchange and alter joint information and doing independent fitness evaluation.
My big question is: How can this be achieved in MATLAB?
Things I've already tried:

*

*MATLAB's 'spmd'-functionality using the labSend and labReceive functions but this also seems to involve waiting for other workers.

*creating jobs and assigning them tasks. Does not seem to work as multiple jobs are processed sequentially on the cluster. Only tasks within a job use multiple workers but that fails since you can't assign tasks dynamically (you always have to submit the whole job anew to the queue.

*parfeval in a recursive while statement. I do not see how this would reduce waiting time.
So does anyone know a way how to implement something like this in MATLAB?


text:
Q: $(\varphi,\Gamma)$-modules and valuation in Zp The theory of $(\varphi,\Gamma)$-modules and a reciprocity law due to Cherbonnier and Colmez involve the ring $A_K$, that is described below.
The question is why for the valuation defined as $l_ν(a):=min\{i| p^ν - does- not- divide - a_i\}$ of $a=\sum_i a_i(\pi_k)^i$ $\in$ $A_K$, the $l_1(a)$ is independent of a choice of uniformizer for $A_K$ but $l_v(a)$ for $v\geq2$ is not?
Can someone help me here, please? Is there an example of where one can see this?
The ring $A_K$:
Set $E$ to be the set of sequences $(x^{(0)},x^{(1)}, . . . )$ of elements of $C_p$ satisfying $(x^{(n+1)})^p=x^{(n)}$, with addition given by $(x + y)^{(n)} = \lim_m (x^{(n+m)} + y^{(n+m)})^{p^m}$ and $(xy)^{(n)} = x^{(n)}y^{(n)}$. Then $E$ is a complete, algebraically closed field of characteristic $p$.
Fix a compatible system of roots of unity $(\zeta_p^m),\forall m\in\mathbb N$ where $(\zeta_p^{m+1})^p= \zeta_p^m$ , and write $K_n=K(\zeta_p^n)$. We set $\epsilon=(1,\zeta_p,\zeta_p^2,...)$ and denote by $E_{\mathbb Q_p}$ the subfield of $E$ given by $F_p((\epsilon− 1))$.
We write $E_s$ for its separable closure and note that $E$ is the completion of the algebraic closure. We write $E_K=E^{H_K}$ for the subfield of $E$ fixed by $H_K=\ker\chi^{cyclo}$.
We take $A=W(E)$ the ring of Witt vectors over $E$, and $B=A[1/p]=Frac(A)$. This is a complete discrete valuation field with residue field $E$. We can write $x\in A$ as $\sum_{k=0}^\infty p^k[x_k]$ where $x_k\in E$ and $[\cdot]$ is the Teichmüller lift.
We write $\pi=[\epsilon]−1$, and $A_{\mathbb Q_p}$ for the closure of $\mathbb Z_p[\pi,\pi^{−1}]$ in $A$; it is a complete discrete valuation ring with residue field $E_{\mathbb Q_p}$. We write $B_{\mathbb Q_p}=Frac(A_{\mathbb Q_p})=A_{\mathbb Q_p}[1/p]$.
We have actions of $\varphi$ and $G$ on $B$ given by $\varphi(\pi)=(1 + \pi)^p−1$ and $g(\pi)=(1+\pi)^{\chi^{cyclo}(g)}−1$.
We write $B_c$ for the closure of the maximal unramified extension of $B_{\mathbb Q_p}$ in $B$ and $A_c=B\cap A$ such that $A_c[1/p]=B$
We have $B_K=B^{H_K}$ and $A_K=A^{H_K}$. We observe that
$$ B_K=\{\sum_{n \in\mathbb Z} a_n \pi_K^n : a_n \in F, \lim_{n \rightarrow -\infty} a_n=0\}$$
where $\pi_K$ is $e-$th root of $\pi$ and a uniformizer of $B_K$ . We likewise have
$$ A_K=\{\sum_{n \in\mathbb Z} a_n \pi_K^n \in B_K : a_n \in\mathcal O_F, \forall n\in\mathbb Z\}$$

A: After clarifying terminology in the comments, I think this is what's going on here:
Let $F$ be a local field with ring of integers $O_F$ whose maximal ideal is $(p)$, and residue field $k := O_F/(p)$. Let $A$ be the set of Laurent series
$\displaystyle \sum_{i\in \Bbb Z} a_i \pi^i: a_i \in O_F$ such that $\lim_{i\to -\infty} a_i=0$
(i.e. the series can be infinite on both sides, but to the left, the coefficients go to $0$). Then one can show that $A$ is a complete DVR  with maximal ideal $(p)$, whose residue field $A/p$ (that's $E_K$ in your question) is of the form $k((t))$ (usual Laurent series, with finite negative part, over the field $k$). Notice that $k((t))$ is itself a complete field with a discrete valuation, whose ring of integers is $k[[t]]$ (power series over $k$). The uniformisers of this are precisely the elements of the form $\bar a_1 t + \sum_{i\ge 2}\bar a_i t^i$, where $\bar a_i \in k$ and $\bar a_1 \neq 0$.
Next, let $\varpi \in A$ be any lift of any such uniformiser. It is of the form
$\varpi = \displaystyle \sum_{i\in \Bbb Z} a_i \pi^i$ with $a_i \in (p)$ for $i\le 0$, and $a_1\in O_F^*$
(a special case being $\varpi = \pi$ itself).

Claim: Every element of $A$ can also be written uniquely in the form  $$\displaystyle \sum_{i\in \Bbb Z} b_i \varpi^i: b_i \in O_F \text{ such that } \lim_{i\to -\infty} b_i=0.$$

Now in the article they define functions $l_\nu: A \rightarrow \Bbb Z$ by
$l_\nu(\sum_{i\in \Bbb Z} a_i \pi^i) := \min\lbrace i: p^\nu \text{does not divide } a_i\rbrace$.
but one could also define, for each $\varpi$, the variant
$l_{\nu, \varpi}(\sum_{i\in \Bbb Z} b_i \varpi^i) :=\min\lbrace i: p^\nu \text{does not divide } b_i\rbrace$
(so that $l_\nu$ is the choice $l_{\nu, \pi}$).
Now:

*

*For $\nu \ge 2$, in the examples $\varpi = p^{\nu-1} + \pi$ we have $l_\nu(\varpi) = 0$ but $l_{\nu, \varpi}(\varpi) = 1$.

*For $\nu=1$ however, a little consideration shows that both $l_{\nu}$ and $l_{\nu, \varpi}$ can actually be described as
$l_\nu(a)= l_{\nu, \varpi}(a) = \text{ the } t-\text{adic valuation of } \bar a \in A/(p) = k((t))$
which does not depend on the choice of $\varpi$.


text:
Q: Sorted array and finding sum with complexity O(n) We have sorted array arr[]={2,4,5,7,8,12,16,18,20}.
We need to find out pair of elements whose addition is 12, with complexity O(n).
Could anyone help on it?

A: No solution for you unfortunately, just some things to think about that should lead you in the right direction:
Keeping in mind that the array is sorted, which of the following are true?
   arr[x+1] + arr[y] < arr[x] + arr[y]
or arr[x+1] + arr[y] > arr[x] + arr[y]

   arr[x] + arr[y-1] < arr[x] + arr[y]
or arr[x] + arr[y-1] > arr[x] + arr[y]

If you think about the answers to these long enough (and maybe draw it), a solution should follow.
Hint for how to start:
Let x = 0, y = n-1.
...

A: Try this:
Since the array is sorted, take the sum of the first element (arr[0]) and the last element(arr[8]).
If the sum is greater than 12, then we need to lower the sum, so we replace the largest number by the next largest number(in this case, arr[7]);
If the sum is less than 12, we need to increase the sum, so we replace the smallest number by the next smallest number, (in this case, replace arr[0] with arr[1]). Keep repeating this process until you get the sum you want or the two numbers you are summing up is from the same index in the array.


text:
Q: File format supported by windows media player component I m developing media player in c# and I m using windows media player component for that..
This is my code
private void songList_SelectedIndexChanged(object sender, EventArgs e)
{
   axWindowsMediaPlayer1.URL = paths[songList.SelectedIndex];
}

Can anyone tell me the supported file formats for this component?
The version information property of the component is '12.0.7600.16385'

A: See this microsoft website for the supported file formates. All the file formats are listed and the compatible windows media player versions.


text:
Q: What is the difference between 'pat him on the back' and 'pat his back'? In the TV shows or something, I've come across that kind of sentences. And make me wonder.
why won't say just 'I pat his back'. it's shorter than 'pat him on the back'.
and what situation would people say with the latter sentence 'pat him on the back' and could you give me more examples related to mine?
(I hit him in the eyes.. or I hit his eyes.)

A: Looking at your examples, I feel that you are talking about some actions to be done on others.
Pat him on the back will be used with the preposition 'on' for a solid reason: it is an idiom and we use idioms as they are.
When you are performing some action on someone's organ, it has to be specified. Patting happens on someone's shoulder; hitting happens in someone's eyes considering that eyes were open then.
The safest way is to refer some dictionary and check whether it's an idiom/phrase. In other cases, I feel that the preposition is to be mentioned. Another example is kick on his ____ over kick his ____.

A: It means

Praise given to a person for an achievement or a job well done.

Pat him on the back is would be better for this.

The coach patted each player on the back after the game.
The teacher patted all the students on the back for their good work.
Let's give them a pat on the back for doing a good job.

A: There's no real "why" in all of this. It's just how English is. And sometimes it can go either way. I can say "I punched him in the arm" or "I punched his arm." Other expressions are less lenient.
However, there is a peculiarity in the language around this. If you "pat him on the back," then you patted him. The body part is secondary information. If you "pat his back," then a morbid-minded person might wonder how his back had become detached from the rest of his body.
This is especially true with "head" and "eyes." If you "hit his head," there's a real possibility that he'd been decapitated, and you are just taking out your extra aggression on his now-lifeless head.
But ultimately, it's just the language. In English, I would say "I wash my hands." In French, I would say "je me lave les mains," which literally means "I wash myself the hands." So this linguistic thing with people and their body parts isn't unique to English. The linguists among us may even have a name for it.


text:
Q: Why don't need to specify variable in the constructor? I am learning javascript, in the constructor there isn't a var declaration there, just get and set method there. Could anyone tell me why? I think there should be a statement like var name; in the constructor?
<script>
function Person(name){
    this.getName=function(){
        return name;
    };

    this.setName=function(value){
        name=value;
    };
}
</script>

why don't put
var name

in the constructor?

A: because function arguments are already in scope and you don't want to override the argument by undefined?
see What is the scope of variables in JavaScript? to learn more about scope

A: function Person(name){
    this.getName=function(){
        return name;
    };

    this.setName=function(value){
        name=value;
    };
}

because name is already scoped to Person function since it's an argument of Person
you dont need (and shouldnt) write var name.

A: setName method is implemented in case you want to change the name of an existing object.
e.g:
function Person(name){
    this.getName=function(){
        return name;
    };

    this.setName=function(value){
        name=value;
    };
}

var tom = new Person("tom");
var harry = new Person("harry");

So If you want tom to have new name you must call
tom.setName("Dick");

After this
tom.getName();

Will return "Dick".
Best regards.


text:
Q: How does "Closure" affect my nested traversal of dom nodes in jQuery? I understand closure somewhat, but sometimes I can't seem to get it right.  I believe this to be the culprit here... Since i'm traversing tho, i'm not sure if closure is necessary or possible.
So I have to parse some external markup that looks like this:

Fried Calamari

Price:$8.95

Pan-fried calamari served with our delicious homemade tomato sauce.

Extra Sauce

Required:0 / Up To:99

Extra Sauce

Price:$0.99

Fried Zuchinni

Price:$6.95

Tossed with garlic and herbs. Served with a side of tomato sauce.

Extra Sauce

Required:0 / Up To:99

Extra Sauce

Price:$0.99

Eggplant Rollatini Appetizer

Price:$7.95

Fresh rolled eggplant filled with Ricotta and topped with tomato sauce and melted Mozzarella.

Extra Sauce

Required:0 / Up To:99

Extra Sauce

Price:$0.99

Mozzarella Sticks

Price:$6.95

Classic Mozzarella sticks served with a side of tomato sauce.

Extra Sauce

Required:0 / Up To:99

Extra Sauce

Price:$0.99

Buffalo Rock Shrimp

Price:$9.75

Crispy rock shrimp toasted in our signature buffalo sauce. Served with Blue cheese crumbles.

Extra Dressing

Required:0 / Up To:99

Extra Dressing

Price:$0.99

Here's my js using jQuery...
$(document).ready(function(){

 $('h2').each(function(i) {
     //to hold the info
     var itemDetail = new Object();
     //h2's contain the name
     itemDetail['name'] = $(this).html();

     // but dd's contain price description and other
     // and we need to traverse all
 tags for each

     $(this).siblings('dd').each(function(){
         var itemInfo = $(this).html();
         var priceLabel = itemInfo.slice(0,7);
         var priceValue = itemInfo.slice(7);
         if (priceLabel='Price:$'){
             itemDetail['price'] = priceValue;
         }else{
             // discard required info (leaving description)
             if (itemInfo.slice(0,9) != 'Required:')
             //descriptions don't have a label
             itemDetail['description'] = itemInfo;
         }
     });
     console.log(itemDetail)
 });
});

if i step thru the traversals using alert() on priceLabel and priceValue, the logic echo's the correct values (specifically priceValue is a numberwhen priceLabel matches the criteria, but when I log the object, i'm not getting info for each iteration of the inner traversal.  Instead priceLabel is equal to the .slice() of the final  iteration.
Is there a better way to avoid this or use closure to force info into my objects...

A: A couple of issues:

*

*The = does assignment but you used it for comparison instead of using == or ===

*You used .siblings('dd') which is giving you all the dd elements, instead of just the next adjacent ones. With your current markup, you can use nextUntil(':not(dd)') instead.

 $('h2').each(function(i) {
     var itemDetail = new Object();
     itemDetail['name'] = $(this).html();

       // ----v---get next siblings of "h2" until on that is not "dd" is reached
     $(this).nextUntil(':not(dd)').each(function(){
         var itemInfo = $(this).html();
         var priceLabel = itemInfo.slice(0,7);
         var priceValue = itemInfo.slice(7);

              //--------v----------- use == instead of =
         if (priceLabel == 'Price:$'){
             itemDetail['price'] = priceValue;
         }else{
             if (itemInfo.slice(0,9) != 'Required:')
             itemDetail['description'] = itemInfo;
         }
     });
     console.log(itemDetail)
 });

EDIT:
If your markup is consistent the way it shows, then you can shorten your code a bit like this:
 $('h2').each(function(i) {
     var itemDetail = new Object();
     itemDetail['name'] = $(this).html();

     var dds = $(this).nextUntil(":not(dd)");
     itemDetail['price'] = dds.eq(0).html().slice(7);
     itemDetail['description'] = dds.eq(1).html();
     console.log(itemDetail);
 });

Or even shorter using an object literal:
 $('h2').each(function(i) {
     var dds = $(this).nextUntil(":not(dd)");
     var itemDetail = {
                name: $(this).html(),
               price: dds.eq(0).html().slice(7),
         description: dds.eq(1).html()
     };
     console.log(itemDetail);
 });

A: Since you declared itemDetail inside the function you passed on your first .each, its scope is limited to that function(and the functions you made inside that function).
Also, you're overwriting  itemDetail['price'] and itemDetail['description'] over and over again as you step through  $(this).siblings('dd'), is this intentional?


text:
Q: Bash diff body text of html file only I'm writing a shell script which tracks the changes of a website and emails me with the contents of the change if one occurs.  The idea is to use wget to grab a copy of the html and compare it to the version from the last time the script ran.  Wget works fine to save the html file but I'm having trouble comparing the files.  The trouble is that I'm only interested in changes in the html file's plain text, not the code, links, etc.
Diff works to find all the changes in the two files but it ALWAYS returns changes even when the plain text is identical.  This is because each link on the site has a corresponding authenticity token that differs each time the page is accessed.  In order to diff only the lines that include plain text I'm attempting to filter it to exclude any line that begins with "<" OR "(any_amount_of_spaces)<".  I've looked at the diff man page but I can't seem to find an operator that will do what I need.  I don't know much about REGEX but would that work with diff -I for this?
Thanks!

A: You could use lynx -dump to render the pages and feed those to diff, but since you are not interested in links you would need to get rid of the References section that this yields (with e.g. awk) rendering this a not-so-robust solution (but maybe good enough for your use case).
If you don't mind using something 3rd-party go for html2text:
diff <(html2text before.html) <(html2text after.html)

PS: There are two different programs called html2text.


text:
Q: Format Excel File using C# The Bellow function is used to formate the excel file but after running the function the Application Excel is not closeing from the Try.. (not able to kill the application) Please Help me on this
private void FormateExcelFile()
{
    try
    {
        int nI = 0;//For Loop
        string nFieldName = string.Empty;
        nUserName=  WindowsIdentity.GetCurrent().Name; //Get Windows Login User
        string reportFilenPath = Application.StartupPath + "\\OutPutFiles\\" + "NewTempFile.xls";
        string connString = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + reportFilenPath + "';Extended Properties=Excel 8.0;";
        DataTable parts = new DataTable();
        using (OleDbConnection conn = new OleDbConnection(connString))
        {
            string sqlParts = "Select * from [" + nSheetName + "]";
            OleDbDataAdapter adapter = new OleDbDataAdapter(sqlParts, conn);
            adapter.Fill(parts);
        }

        for (nI = 0; nI < parts.Columns.Count; nI++)
        {
            DataColumn column = parts.Columns[nI];
            if (nI == 0) { nFieldName = column.ColumnName; }
            else { nFieldName = nFieldName + "," + column.ColumnName; }
        }
        parts.Dispose(); parts = null;

        oExcel = new Excel.Application();
        oBook = oExcel.Workbooks.Open(reportFilenPath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
        oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oBook.Worksheets.get_Item(nSheetName.Replace("$", ""));
        oExcel.DisplayAlerts = false;
        oExcel.Visible = true;

        //Check the Field Is Avilable in the Sheet if not then Add
        if (nFieldName.Contains("Sub Device") == false)
        {
            nRng = oSheet.get_Range("A1", oMissing);
            nRng.EntireColumn.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight, false);
            oSheet.Cells[1, 1] = "Sub Device";
        }
        if (nFieldName.Contains("Brand") == false)
        {
            nRng = oSheet.get_Range("A1", oMissing);
            nRng.EntireColumn.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight, false);
            oSheet.Cells[1, 1] = "Brand";
        }
        if (nFieldName.Contains("Model") == false)
        {
            nRng = oSheet.get_Range("A1", oMissing);
            nRng.EntireColumn.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight, false);
            oSheet.Cells[1, 1] = "Model";
        }
        if (nFieldName.Contains("Product Details") == false)
        {
            nRng = oSheet.get_Range("A1", oMissing);
            nRng.EntireColumn.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight, false);
            oSheet.Cells[1, 1] = "Product Details";
        }
        if (nFieldName.Contains("Price") == false)
        {
            nRng = (Excel.Range)oSheet.Cells[1, 1];
            //nRng = oSheet.get_Range("A1", oMissing);
            nRng.EntireColumn.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight, false);
            oSheet.Cells[1, 1] = "Price";
        }

        oBook.Save();
        oBook.Close(false, oMissing, oMissing);
        oExcel.DisplayAlerts = true;
        releaseObject(oSheet);
        releaseObject(oBook);
        oExcel.Quit();
        releaseObject(oExcel);
        releaseObject(nRng);
        nRng = null;
        oExcel = null;
        oSheet = null;

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
        releaseObject(oSheet);
        releaseObject(oBook);
        //oExcel.Quit();
        releaseObject(oExcel);
    }
}

private void releaseObject(object obj)
{
    try
    {
        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); obj = null;
    }
    catch (Exception ex)
    {
        obj = null;
        MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
    }
    finally
    {
        GC.Collect();
    }
}

A: You need to release all the Excel objects you're referencing.  For example:
if (nFieldName.Contains("Sub Device") == false)
{
    nRng = oSheet.get_Range("A1", oMissing);
    nRng.EntireColumn.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight, false);
    oSheet.Cells[1, 1] = "Sub Device";
}

should be something like (leaving out try/finally for simplicity)
if (nFieldName.Contains("Sub Device") == false)
{
    nRng = oSheet.get_Range("A1", oMissing);
    var col = nRng.EntireColumn
    col.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight, false);
    var cells = oSheet.Cells;
    var firstCell = cells[1,1];
    firstCell.Value = "Sub Device";

    Marshal.ReleaseComObject(nRng);
    Marshal.ReleaseComObject(col);
    Marshal.ReleaseComObject(cells);
    Marshal.ReleaseComObject(firstCell);

}

Similarly:
oBook = oExcel.Workbooks.Open(reportFilenPath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oBook.Worksheets.get_Item(nSheetName.Replace("$", ""));

needs to be:
oBooks = oExcel.Workbooks
oBook = oBooks.Open(...);
oSheets = oBook.Worksheets
oSheet = oSHeets.get_Item(...);

and you need to release oBooks and oSheets.

A: Try to end your excel task with these commands:
        Marshal.FinalReleaseComObject(sheet);
        app.DisplayAlerts = false; //Very important!
        range = null;
        sheet = null;
        // Garbage collecting
        GC.Collect();
        GC.WaitForPendingFinalizers();
        book.Close(false, Missing.Value, Missing.Value);
        Marshal.FinalReleaseComObject(book);
        book = null;
        app.Quit();
        Marshal.FinalReleaseComObject(app);
        app = null;

I had the same problem accessing my excel files, but with the shown code it closes all the time.
Of course not if the program crashes before it reaches the code, check your code with the debugger.
In your case: book --> oBook, app --> oExcel, sheet --> oSheet.

A: Take away these lines:
nRng = null;
oExcel = null;
oSheet = null;

I think you are releasing your Excel object, and then by making it equal to null afterwards you are doing something with Excel which starts a new instance on your machine.
After releasing the object, you don't need to set variables to null, or run GC.Collect();, the garbage collector will take care of this for you, and I think in this instance trying to clean up the managed objects yourself (after correctly cleaning up the unmanaged Excel object) is actually causing your problems.

A: I had the same kind of issue working with Excel interop. The problem should be originated by this kind of lines (at least it was in my case):
oBook = oExcel.Workbooks.Open(reportFilenPath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);

In the end you reales oBook, but this is what's really happening here: in order to get oBook pointing to your opened workbook, you accessed a Workbooks object (using oExcel.Workbooks). This is never released, and keeps Excel from quitting.
I solved the problem by rewriting that line as:
Microsoft.Interop.Excel.Workbooks oBooks = oExcel.Workbooks;
oBook = oBooks.Open(reportFilenPath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
releaseObject(oBooks);

Of course this has to be done for every line of this kind (for instance oBook.Worksheets.get_Item(...), nRng.EntireColumn.Insert(...), and so on).


text:
Q: Limit of files and/or length of "name:" search boolean query in Windows Explorer? What is the limit of to how long a query like 'name:("name1.txt" OR "name2.txt" OR ...)' can be for Windows Explorer search bar? Or, in which Windows documentation can one find that info?
I have small lists of files (30/40 in no) which I need to see from the large folder. One of the list I took to construct a query (with 19 long filenames, total length of query 4154 chars). It worked on that list, but on a larger set it fails, so there is some limit at play here (not sure whether it's the number of files or query length.
(This is a follow up to the comment for this question.) Hope I'm not inadvertently committing a SE crime by turning it into a question!

A: I think I have figured out how many files it will accept:
My trials:

*

*Windows 7: 35 filenames in the query (total query length was 1798 characters long, and as mentioned in question, I have already done a query with 4154 chars but with larger names and fewer files (so it appears the length does not matter, the number of files does). Though I do have a feeling that the 4145 char long query might've been a mistake, in counting the length properly and it could've been shorter, but anyway, it's the number of filenames that matter anyway apparently

*Windows 10: Won't even accept a query longer than 518 in my trial with 35 name query pasted in the box (truncates), so make whatever of that, if you will.


text:
Q: Drools - Check objects inside multiple nested Arrays I'm using drools to make a validation service to validate input XMLs (which are parsed to a Java object) for rules.
These XML-Files usually have a lot of data and some of that data is packed really deep inside multiple arrays and objects:
Example
Now I need to check the value in "attributeValueFrom". Or for a matter of fact I have troubles accessing any object "deeper" down the tree than "condition".
rule "Every_Attribute_has_a_Value_True"
when
    G10EValidationObject($columns : getNormalisedMetaDataContainer().getMetaDataContainer().getNormalisedOrder().getSelection().getColumn());
    $column : NormalisedDataColType($condition : attributeCondition.getCondition()) from $columns;

    $column3 : NormalisedDataColType($attrValueGroup : attributeCondition.condition.getAttrValueGroup()) from $condition;
    //$column2 : NormalisedDataColType ($attrValueGroup : condition.getAttrValueGroup()) from $condition;
    $attrValueRanges : QualifiedAttributeNameValueGroupType(valueGroup.getValueRange()) from $attrValueGroups;
    $attrValueRange : QualifiedAttributeNameValueGroupType(valueRange.getAttributeValueFrom() != "", valueRange.getAttributeValueFrom() != null, valueRange.getAttributeValueTo() != "", valueRange.getAttributeValueTo() != null ) from $attrValueRanges;
then
    validationRuleResults.addResult("Every_Attribute_has_a_Value", true, "Rule passed");

end
The first two line of the when clause work and I've tried to access objects farther down the tree in a similar fashion but it always throws an error "Unable to analyze expression".
I could solve the issue by extracting that data in a separate Java method and calling that method but if possible I'd prefer doing it Drools internally (it appears to me to be possible)
Thanks for any help
Leo K.
PS: If it helps this would be the Java method call to get the specified data:
normalisedMetaDataContainer.getMetaDataContainer()
.getNormalisedOrder().getSelection().getColumn()
.get(0).getAttributeCondition().getCondition()
.get(0).getAttrValueGroup().get(0).getValueGroup()
.getValueRange().get(0).getAttributeValueFrom()

Note I don't only want to get the first objects in the arrays but all of them as I want to check the rule on all objects present.
If you need additional information I'll be happy to provide.


text:
Q: Highcharts cannot read property 'marker' of undefined error I am using highcharts 3.0 version. I am trying to add a gauge chart. The chart is generating but i am getting error as 'cannot reaad property 'marker' of undefined.
I am not getting the value of series in chart. Also used highcharts-more.js as suggested.
Please reply what is going wrong
chart: {
        type: 'gauge',
                renderTo: selector

    },

    title: null,

    pane: {
        center: ['50%', '85%'],
        size: '140%',
        startAngle: -90,
        endAngle: 90,
        background: {
            backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || '#EEE',
            innerRadius: '60%',
            outerRadius: '100%',
            shape: 'arc'
        }
    },

    tooltip: {
        enabled: false
    },

    // the value axis
    yAxis: {

        lineWidth: 0,
        minorTickInterval: null,
        tickPixelInterval: 400,
        tickWidth: 0,
        title: {
            y: -70
        },
        labels: {
            y: 16
        },
            min: 0,
        max: 200,
        title: {
            text: 'Speed'
        }
    },

    plotOptions: {
        series: {
            color: '#FF0000'
    },
    },

         series: [{
        name: 'Speed',
        data: [80],
        dataLabels: {
            format: '
{y}
' +
                   'km/h
'
        },

    }]
});


text:
Q: Python Tkinter Clear frame and associate user's answer to a value I am trying to clear the frame between each question that is asked in the multiple choice survey but I would like the frame itself to stay. I tried to created a next button that will allow the user to skip to the next question but the frame doesn't appear when I run my code (No error message is appering either).
And in order to store the answers of the user to the questions, is it better to use the values (1,2,3,4,5) of the radiobuttons or the variables of the radiobuttons.
Here is my code:
from Tkinter import *

fenetre = Tk()
fenetre.title("Life Quiz")
from random import shuffle

#questions

quest_1 = "What is your favorite color?"
quest_2 = "Which of these animals do you like the most?"
quest_3 = "Which of these superpowers would you want to have the most?"
quest_4 = "Which food would you want to eat right now?"
quest_5 = "If you could only bring one thing on an island, what would it be?"

#liste de réponse

list_reponse = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]

#Associé liste_reponse avec IntVar()

list_reponse[0] = IntVar()
list_reponse[1] = IntVar()
list_reponse[2] = IntVar()
list_reponse[3] = IntVar()
list_reponse[4] = IntVar()

class Questions(object):

#fonction pour afficher les questions et les choix de réponses

    def __init__(self, master, n_question):
        self.master = master
        self.liste_choix =[ [quest_1, "Blue", "White", "Yellow", "RAINBOWS", "Red"], [ quest_2, "Blue Whale", "Pig", "Cat", "Unicorns", "Dog"], [quest_3, "Make it rain whenever you want", "Transform yourself into a ladder", "Invisibility when no one's around", "Read the mind of unicorns", "Ability to fly" ], [quest_4, "Ice cream", "Sushi", "Salad", "Cupcakes", "Pizza"] ,[quest_5, "Nothing...", "A fishing rod", "A book", "A leprechaun", "A knife"] ]

        self.liste_choix_questions = self.liste_choix [n_question]
        shuffle(self.liste_choix_questions)
        self.display_frame = None
        self.next_question = 0

        def display_next(self):
            if self.next_question < len(self.liste_choix_questions):
                if self.display_frame:
                    self.display_frame.destroy()
                self.display_frame=Frame(self.master)
                self.display_frame.grid(row=0, column=0)
                Label(self.display_frame,
                      text=self.liste_choix_questions[0],
                      bg="lightblue").grid(row=0, column=0)

        display_next(self)

        R1 = Radiobutton(fenetre, text= self.liste_choix[n_question][1], variable= list_reponse[n_question], value=1)
        R1.pack( anchor = W )
        R2 = Radiobutton(fenetre, text= self.liste_choix[n_question][2], variable= list_reponse[n_question], value=2)
        R2.pack( anchor = W )
        R3 = Radiobutton(fenetre, text= self.liste_choix[n_question][3], variable= list_reponse[n_question], value=3)
        R3.pack( anchor = W)
        R4 = Radiobutton(fenetre, text= self.liste_choix[n_question][4], variable= list_reponse[n_question], value=4)
        R4.pack( anchor = W )
        R5 = Radiobutton(fenetre, text= self.liste_choix[n_question][5], variable= list_reponse[n_question], value=5)
        R5.pack( anchor = W )

        Button(self.display_frame, text="next",
               command=display_next).grid(row=1, column=0)
        n_question += 1

Q = Questions(fenetre,1)
fenetre.mainloop()

A: One solution is to use an inner frame to hold your radiobuttons. Then, you can delete the frame which will delete all of the radiobuttons. Finally, you can recreate the frame with new radiobuttons.
Another solution is to simply iterate over the radiobuttons, reconfiguring them for the current question (assuming all questions have the same number of choices).


text:
Q: Securely de-identifying while retaining unqiue IDs I'm creating a data warehouse of customer data.  This involves reading CSVs with various information:
cell      email         gender  language  transaction
5551212   foo@bar.com     M        E         005

I uniquely identify customers by using cell+email (I know this is not great, separate questions), and I'm interested in de-identifying this data such that I remove cell and email, while retaining the ability to match non-identifiable information to future records with particular customers.
One approach I had considered was hashing cell+email, using a secure hash algorithm like SHA2.  So the data stored would be:
uid         gender  language  transaction
aW51SGvswX...     M        E         005

When I receive additional records, I hash cell+email.  If its new, I create new customer.  If hash exists, increment transaction counter on customer.
If an attacker steals the DB, they would need to hash various combinations of email+cell to recover the transaction history.
I've read How to separate a person's identity from his personal data?, and of course I realize that if an attacker has prolonged access to the system, all of the records observed during that time are compromised.  The specific scenario I'm looking to avoid however, is one-time theft of the DB.
I assume keystretching the hash is a good idea.  I don't believe its possible to use a salt to protect against rainbow tables, since I need to calculate and store the salt before hand, and look it back up, which I can't do without the hash.
Any alternatives to this system?
Any thing I'm overlooking?
Thanks,
Justin

A: This is a place where a surrogate key (e.g. an identity or autonumbering column) would help. Rather than hashing existing data to identify it back to the original rows, I'd either add a surrogate key to source table or I'd create a mapping table of surrogate keys-to-cell+email and use the surrogate key in my data warehouse. If the data warehouse gets compromised, the attacker only has an arbitrary reference value. One big reason for using a surrogate key is the performance of queries against the data warehouse should be noticeably better than a hashed value.
Btw, the assumption with this solution is that only the data warehouse is compromised. It is assumed that the source databases are protected from attack via encryption or other such means.

A: You could encrypt the cell+email with a symmetric key before you hash it. This would make successful lookups in rainbow tables less likely. However, if the DB is compromised, it is likely that the attacker has also access to the symmetric key.


text:
Q: I want to use a promise return value inside the get method. nodejs rest api I am creating a rest api. My get method will return the result according to the total supply value of the contract or it will not respond, but the request I made to the contract returns a promise. How can I use this value?
const NameContract = new web3.eth.Contract(abi, '0xE3A2beCa..........1D901F8');
NameContract.methods.totalSupply().call().then(value => console.log(value))

app.get('/:id', (req, res) => {
    let id = parseInt(req.params.id);
    //I want to use an if here.
    //I want to throw the query according to the value returned from above,
    // but it returns a promise, how can I use it value?
    nft.findOne({ id: id }, (err, doc) => {
        if (doc != null) {
            res.json(doc)
        }
        else {
            res.status(404).json(err)
        }
    });

});

A: Try saving the promise whose value will end up being the total value
 const pTotalSupply = NameContract.methods.totalSupply().call();

(assuming this is valid - the .call method looks a little strange). Options then are to

*

*Not start the server until pTotalSupply above has been fulfilled, provided total supply is a static value and there to be only one name contract the server has to deal with,

*Wait for the result to be obtained within the app.get handler, either by using an await operator inside an asynchronous function body, or wrapping request processing in a promise then argument function, or

*Using a promise then call to save the supply value and call next in a two part app.get handler. This is more an express oriented solution using a pattern along the lines of:

app.get('/:id', (req, res, next) => {
    pTotalSupply.then( value => {
        res.locals.value = value;
        next();
    }
    .catch( err => res.status(500).send("server error")); // or whatever
 }
 , (req, res) => {
    const value = res.locals.value;
    let id = parseInt(req.params.id);
    // process request with value and id:
    ...
 });

The second option is covered in answers to How to return the response from an asynchronous call


text:
Q: How to perform IP subnetting on 192.168.0.0/16? I need to have at least 30 subnets.
Also, in this case, what is the number of bits borrowed, and bits left?
I am confused with the many information I got online. I appreciate any help. Thank you in advance.

A: For an easy explanation, I need to write down the subnet mask in binary format:
IP: 192.168.0.0/16
Netmask (Decimal Format): 255.255.0.0 or,
Net mask (Binary Format): 1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0
As far as the Netmask and (/16) show 16 bits belong to network portion and 16 bits belong to host portion. In order to make 30 subnets, you need to add 5 bits of host portion to the network portion. Then 11 bits remain in host portion that provide {(2^11 = 2048), or [(2^3 = 8) * (2^8 = 256)] = 2048} IP address for each subnet.
As a result of adding 5 bits to the network portion, the new subnet mask becomes:
CIDR: /21
Decimal: 255.255.248.0
Binary: 1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.0.0.0.0.0.0.0.0.0.0.0
Note: This way, you can create (2^5 = 32) subnets. However, you should know that you can't create exactly 30 subnets since the IP works in binary format. Therefore, you have to create either (2^5 = 32) subnets or (2^4 = 16) subnets. As far as 16 subnets don't meet your requirement, you would choose 32 subnets.
Now you can assign each subnet 2048 IP address and write down as following:
1st subnet: (192.168.0.0 ~ 192.168.7.255)/21
2nd subnet: (192.168.8.0 ~ 192.168.15.255)/21
3rd subnet: (192.168.16.0 ~ 192.168.23.255)/21
…
30th subnet: (192.168.232.0 ~ 192.168.239.255)/21
31st subnet: (192.168.240.0 ~ 192.168.247.255)/21
32nd subnet: (192.168.248.0 ~ 192.168.255.255)/21


text:
Q: Dynamic Eigen Matrix Random Initialization I have a vector<MatrixXf*> called weights. In the loop, a new MatrixXf is allocated, pointer pushed to the vector, and meant to be initialized to random values. However, I want to avoid setRandom() in favor of my He distribution.
The uncommented code below works as-is, but it feels very clunky to create a 'local' matrix that may be in the stack (or heap, but the class doc is vague) and copy it into my destination matrix. The commented lines are things I've tried before that had no effect (matrix values remained 0).
What would be the better solution?
    /* context */
    typedef Eigen::MatrixXf Matrix;
    vector<Matrix*> weights;
    random_device rd;
    mt19937 rgen(rd());

    ...

    // Initialize weights (using He)
    if (i > 0) {
        uint p = neurons[i-1]->size();
        uint c = neurons[i]->size();

        normal_distribution<float> dist(0.0, sqrt(2.0/p));
        auto he = [&](){return dist(rgen);};

        // This is what feels clunky
        Matrix m = Eigen::MatrixXf::NullaryExpr(c, p, he);
        weights.push_back(new Matrix(c, p));
        (*weights.back()) = m;

        // This is what I tried before
        //weights.back()->NullaryExpr(weights.back()->rows(), weights.back()->cols(), he);
        //weights.back()->NullaryExpr([&](){return dist(rgen);});
    }

A: You could use a vector of shared pointers:
#include <memory>
...
vector<shared_ptr<Matrix>> weights;
...
Matrix m = Eigen::MatrixXf::NullaryExpr(c, p, he);
weights.push_back(make_shared<Matrix>(m));

Perhaps one could criticize that this approach is syntactic sugar that doesn't change much in the inner workings of the original "clunky" version. But it obviates the need to use new and to copy afterward the content with *weights.back().
Of course, this can also be written as a one-liner:
weights.push_back(make_shared<Matrix>(Matrix::NullaryExpr(c, p, he)));


text:
Q: LibGDX - How do I get my button to work? I'm new to LibGDX and I am taking it slowly. When I run the application it just force closes due to an error. But I'm not sure what the problem is. Here is the code for the button that I have.
@Override
public void show() {
    // Viewport Camera
    camera = new PerspectiveCamera();
    viewport = new ExtendViewport(800, 480, camera);

    stage = new Stage(new ExtendViewport(800, 840));
    Gdx.input.setInputProcessor(stage);

    skin = new Skin(atlas);
    atlas = new TextureAtlas(Gdx.files.internal("ui/button.pack"));

    table = new Table(skin);
    table.setBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

    textButtonStyle = new TextButtonStyle();
    textButtonStyle.up = skin.getDrawable("button.up");
    textButtonStyle.down = skin.getDrawable("button.down");

    buttonPlay = new TextButton("Play", textButtonStyle);
    buttonPlay.setWidth((float) (Gdx.graphics.getWidth()/2.5));
    buttonPlay.setHeight(Gdx.graphics.getHeight()/6);
    buttonPlay.setPosition((Gdx.graphics.getWidth()/2-buttonPlay.getWidth()/2), (float) (Gdx.graphics.getHeight()-(buttonPlay.getHeight())*2.5));
    buttonPlay.toFront();

    stage.addActor(buttonPlay);
    table.debug();
    table.add(buttonPlay);

}

The error:
Exception in thread "LWJGL Application" java.lang.NullPointerException
at com.badlogic.gdx.scenes.scene2d.ui.Skin.addRegions(Skin.java:102)
at com.badlogic.gdx.scenes.scene2d.ui.Skin.<init>(Skin.java:88)
at com.badlogic.gdx.screens.Menu.show(Menu.java:83)
at com.badlogic.gdx.Game.setScreen(Game.java:61)
at com.badlogic.gdx.screens.Splash.render(Splash.java:38)
at com.badlogic.gdx.Game.render(Game.java:46)
at com.dakotapederson.slingshotsteve.SlingshotSteve.render(SlingshotSteve.java:29)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:206)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)

Line 75 is where the show() method is.

A: Your problem is that you are initialising your skin with an atlas before your atlas has been initialised, the atlas is the null pointer. You have done:
skin = new Skin(atlas); //Here atlas isn't loaded so exception occurs
atlas = new TextureAtlas(Gdx.files.internal("ui/button.pack"));

When it should be:
atlas = new TextureAtlas(Gdx.files.internal("ui/button.pack")); // Load atlas first
skin = new Skin(atlas);


text:
Q: caching not working for map Java - Spring - ehcache
have following code to implement eh-cache working perfect for list of objects but when i tried to cache maps it always trying to load fresh copy... does cache does not work for map ? any help appreciated.
Spring configuration
@Bean
public CacheManager cacheManager() {
    return new EhCacheCacheManager(ehCacheCacheManager().getObject());
}

@Bean
public EhCacheManagerFactoryBean ehCacheCacheManager() {
    EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();
    cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));
    cmfb.setShared(true);
    return cmfb;
}

<!-- ehcache entry -->
    <cache name="serviceMapCache"
        maxEntriesLocalHeap="5000"
        maxEntriesLocalDisk="50000"
        eternal="false"
        diskSpoolBufferSizeMB="20"
        timeToLiveSeconds="10800"
        memoryStoreEvictionPolicy="LFU"
        transactionalMode="off">
        <persistence strategy="localTempSwap" />
    </cache>

Usage
@Cacheable(value=CacheNames.SERVICE_MAP_CACHE)
public Map<String, Service> getAllServicesToMap(){
 // load map
 // return map
 }

A: As you want to use a disk store, you need to make sure the object you cache are Serializable.
In the case of your map example, it means the map itself, the keys and the values it contains.


text:
Q: jQuery mouseout always triggered I have a vertical menubar and the active menu item has a 1px line underneath it. When hover another menu item, the line is slide to under the hovered item. When mouse over the menu, the line should slide back to the active menu item. The problem is, that the mouseout event always triggered, even when cursor only moves over the menu items. In this case, every time when hovers an item, the line slides under it, and when hover the menu item next to it, the line slides to the active menu item (because mouseout triggered) and slides from active item to the hovered.

menu1

menu1

menu1

menu1

menu1

CSS
.header { height: 21px; }
ul { list-style-type: none; margin: 0; padding: 0; height: 20px; }
ul li { display: inline-block; float: left; height: 20px; }
ul li a { padding: 0px 15px; line-height: 20px; }
.line { height: 1px; background-color: red; }

JS
$(document).ready(function(){
    // Select active item
    var currentWidth = $(".header ul li.active").css('width');
    var marginLeft = 0;
    $.each($(".header ul li"), function(){
        if ( $(this).hasClass('active') ) return false;
        else marginLeft += parseInt($(this).css('width').replace('px', ''));
    });
    $(".header .line").css({ 'width': currentWidth, 'margin-left': marginLeft + 'px' });

    // Hover item
    $(".header ul li").hover(function() {
        var thisPos = $(".header ul li").index($(this));
        var thisWidth = parseInt($(this).css('width').replace('px', ''));
        marginLeft = 0;
        $.each($(".header ul li"), function(){
          if ( $(this).is($(".header ul li:eq(" + thisPos + ")")) ) return false;
          else marginLeft += parseInt($(this).css('width').replace('px', ''));
        });
        $(".header .line").animate({ 'width': thisWidth, 'margin-left': marginLeft }, 200);
    }, function(){
        // This one works wrong !!!
        var currentWidth = $(".header ul li.active").css('width');
        var marginLeft = 0;
        $.each($(".header ul li"), function(){
          if ( $(this).hasClass('active') ) return false;
          else marginLeft += parseInt($(this).css('width').replace('px', ''));
        });
        $(".header .line").animate({ 'width': currentWidth, 'margin-left': marginLeft }, 200);
    });

});

Fiddle

A: Instead of mouseleave of the li elements, handle mouseleave from the ul element
// Hover item
$(".header ul li").mouseenter(function () {
    var thisPos = $(".header ul li").index($(this));
    var thisWidth = parseInt($(this).css('width').replace('px', ''));
    marginLeft = 0;
    $.each($(".header ul li"), function () {
        if ($(this).is($(".header ul li:eq(" + thisPos + ")"))) return false;
        else marginLeft += parseInt($(this).css('width').replace('px', ''));
    });
    $(".header .line").animate({
        'width': thisWidth,
            'margin-left': marginLeft
    }, 200);
});

$('.header ul').mouseleave(function () {
    // This one works wrong !!!
    var currentWidth = $(".header ul li.active").css('width');
    var marginLeft = 0;
    $.each($(".header ul li"), function () {
        if ($(this).hasClass('active')) return false;
        else marginLeft += parseInt($(this).css('width').replace('px', ''));
    });
    $(".header .line").animate({
        'width': currentWidth,
            'margin-left': marginLeft
    }, 200);
})

Demo: Fiddle

Another way is a timer based solution like
var $ul = $('.header ul')
// Hover item
$ul.find$("li").hover(function () {
    clearTimeout($ul.data('mouseleave'));

    var thisPos = $(".header ul li").index($(this));
    var thisWidth = parseInt($(this).css('width').replace('px', ''));
    marginLeft = 0;
    $.each($(".header ul li"), function () {
        if ($(this).is($(".header ul li:eq(" + thisPos + ")"))) return false;
        else marginLeft += parseInt($(this).css('width').replace('px', ''));
    });
    $(".header .line").animate({
        'width': thisWidth,
            'margin-left': marginLeft
    }, 200);
}, function () {
    var timer = setTimeout(function () {
        var currentWidth = $(".header ul li.active").css('width');
        var marginLeft = 0;
        $.each($(".header ul li"), function () {
            if ($(this).hasClass('active')) return false;
            else marginLeft += parseInt($(this).css('width').replace('px', ''));
        });
        $(".header .line").animate({
            'width': currentWidth,
                'margin-left': marginLeft
        }, 200);
    }, 100);
    $ul.data('mouseleave', timer)
});

Demo: Fiddle


text:
Q: Display elastic search hits values using NEST I am using following code for searching the articleid and control fields. it will hold the 2 fields values. But I can't access these two fields values.
HERE search<> is dynamic.
  var searchrange = _client.Search<dynamic>(s =>  s
               .Indices("kb_v2").Types("kb")
               .From(0).Size(10)
               .Fields("articleid","control")
               .Query(q => q
                     .Range(r =>r
                         .OnField("articleid")
                         .Greater("2")
                         .Lower("5"))));

can you explain How to get the this two fields values..

A: Since Elasticsearch 1.0 fields are always returned as a Dictionary<string, object[]> on hits to access these in NEST you can use:
foreach (var doc in queryResults.FieldSelections)
{
    var articleIds = doc.FieldValues<int[]>("articleid");
}

See this PR for more details on the syntax.

A: The search response (ISearchResponse type) has a FieldSelections property which holds the results and details. With the older version of Nest, one had to loop over the Hits property to find the value of each field.
"hits": [
         {
            "_index": "kb_v2",
            "_type": "kb",
            "_id": "3565178",
            "_score": 1,
            "fields": {
               "articleid": [
                  "3"
               ]
            }
         },
         {
            "_index": "kb_v2",
            "_type": "kb",
            "_id": "3932480",
            "_score": 1,
            "fields": {
               "articleid": [
                  "4"
               ]
            }
         }]

More on how to use the FieldSelections in ElastichSearch.net client is mentioned in this Unit test here


text:
Q: Finding different elements between 2 vectors in R If I have 2 vectors of length 7 and 4 respectively (in R),
vec1 <- c(1.0, 1.0, 2.0, 3.0, 4.0, 4.0, 5.0)

vec2 <- c(1.0, 2.0, 4.0, 5.0)

I want to output a vector that shows the elements added to vec2 in order to create vec1
output <- c(1.0, 3.0, 4.0)

A: setdiff seems to be working just fine:
> sort(unique(vec1))
 [1] -14.5 -13.5 -10.5 -10.0  -9.0  -8.5  -8.0  -7.5  -6.5  -5.5  -5.0  -4.5  -4.0  -3.5  -2.5   1.5   2.0
[18]   2.5   5.0   5.5   6.5   8.0   8.5  10.5
> sort(unique(vec2))
 [1] -14.5 -13.5 -10.5 -10.0  -9.0  -8.5  -8.0  -7.5  -6.5  -5.5  -5.0  -4.5  -4.0  -3.5  -2.5   2.0   2.5
[18]   5.5   6.5   8.0   8.5  10.5

Only 1.5 and 5.0 are in vec1 and not in vec2


text:
Q: Error en la consola al usar value estaba haciendo un ejercicio de cajero y cuando quise traer un número de la caja de texto del html a mi javascript, es decir obtener el valor del input y convertirlo a entero y extraer el valor no me funciona 'value' busqué en internet sobre el error y no pude encontrar algo al igual que estuve buscando un error de typo, espero me puedan ayudar y gracias de antemano.
class Billete{
    constructor(v, c)
    {
        this.valor = v;
        this.cantidad = c;
    }
}

function entregarDinero()
{
    var t = document.getElementById("dinero");
    dinero = parseInt(t.value);   //en esta línea radica el problema
    for(var bi of caja)
    {
        if(dinero > 0)
        {
            div = Math.floor(dinero / bi.valor);
            if(div > bi.cantidad)
            {
                papeles = bi.cantidad;
            }
            else
            {
                papeles = div;
            }
            entregado.push( new Billete(bi.valor, papeles) );
            dinero = dinero - (bi.valor * papeles);
        }
    }
    if(dinero > 0)
    {
        alert("Dinero insuficiente");
    }
    console.log(entregado);
}

var caja = []
var entregado = []
caja.push( new Billete(50, 10) );
caja.push( new Billete(20, 30) );
caja.push( new Billete(10, 10) );
var dinero;
var papeles = 0;
var div = 0;

var b = document.getElementById("retirar");
b.addEventListener("click", entregarDinero);


text:
Q: How can I use Z3 SMT locally Any one have an idea how to use Z3 SMT locally instead of using the website?
I know how to use z3.py but I need to use SMT. rise4fun.com is down which makes it difficult to check my models.

A: Z3 binaries for various platforms are available for download on the Z3 Website.


text:
Q: Is the [web-api] tag useful? The web-api does not add anything useful to a questoin.
It is usually used to mean:

*

*I am using an API - These should be tagged with the specific API or platform

*Which API can I use to do X - These are off topic and should be closed

I think web-api should be burninated.


text:
Q: jQuery for displaying div not working I want a dialog div to appear and rest page to be greyed out. I should not be able to click anything else on page.
Following is the code I am using. Somehow the code is not working. Page just refreshes on click of hyperlink.
Can anyone help ?

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

                        <asp:Button ID="btnDownload" runat="server" Text="Download" />

                        <asp:Button ID="btnClose" runat="server" Text="Close" />

        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <Triggers>
                <asp:PostBackTrigger ControlID="DownloadButton" />
            </Triggers>
            <ContentTemplate>

                    <asp:LinkButton ID="DownloadButton" runat="server">Download</asp:LinkButton>

                <asp:GridView>
                </asp:GridView>
            </ContentTemplate>
        </asp:UpdatePanel>
    </asp:Content>

A: If DownloadButton, btnClose & btnDownload are IDs of server control, then for getting client ID you have to use:
$("#<%=DownloadButton.ClientID%>")

instead of
 $("#DownloadButton")

in you jQuery Code.
Or
If you are using ASP.Net 4.0
Use ClientIDMode="static" with your server side controls.
For Closing the Dialog:
Use link to close the model popup:
Eg.

and in you Javascript use:
$("#btnClose").click(function (e) {
                    HideDialog();
                });

A: why don't you use simply anchor tag? it won't cause a postback at least, no need to use update panel.
Download

$("#DownloadButton").click(function (e) {
                ShowDialog(true);
                e.preventDefault();
            });

Otherwise Kapil Khandelwal answer is correct if you want to use server side control.
$("#<%=DownloadButton.ClientID%>")

A: In document ready:
        jQuery("#overlay").dialog(
            {
                bgiframe: true,
                autoOpen: false,
                modal: true,
                width: 800
            }
        );

in the click event:
        $('#overlay').dialog('open');

You'll have to specify more options in the dialog declaration, I'm sure, but this approach is working fine for me.


text:
Q: Php can't find tidy I am using a  php7 in docker container to run a service based on phpdocx library. It needs tidy and some other extensions installed and active to work. I have installed php-tidy however I am getting following warning.
PHP Warning:  PHP Startup: Unable to load dynamic library 'tidy' (tried: /usr/lib/php7/modules/tidy (Error loading shared library /usr/lib/php7/modules/tidy: No such file or directory), /usr/lib/php7/modules/tidy.so (Error relocating /usr/lib/php7/modules/tidy.so: _zval_ptr_dtor: symbol not found)) in Unknown on line 0
Dockerfile
FROM php:7.3.2-cli-alpine3.9
USER root

COPY . code
WORKDIR code

RUN apk update && apk add php-tidy && apk add php-zip &&  apk add php-curl && apk add php-sodium

# RUN sed -i s/;extension=tidy/extension=tidy/ -f /usr/local/etc/php/php.ini-development
# RUN sed -i s/;extension=tidy/extension=tidy/ -f /usr/local/etc/php/php.ini-production

COPY php.ini /usr/local/etc/php/php.ini-development
COPY php.ini /usr/local/etc/php/php.ini-production

COPY php.ini /usr/local/etc/php/php.ini

CMD php -S 0.0.0.0:8080

Output from docker shell
on running phpinfo()
Server API => Command Line Interface
Virtual Directory Support => disabled
Configuration File (php.ini) Path => /usr/local/etc/php
Loaded Configuration File => /usr/local/etc/php/php.ini
Scan this dir for additional .ini files => /usr/local/etc/php/conf.d
Additional .ini files parsed => /usr/local/etc/php/conf.d/docker-php-ext-sodium.ini

# vi /usr/local/etc/php/php.ini

extension=tidy

[Tidy]
; The path to a default tidy configuration file to use when using tidy
; http://php.net/tidy.default-config
;tidy.default_config = /usr/local/lib/php/default.tcfg

; Should tidy clean and repair output automatically?
; WARNING: Do not use this option if you are generating non-html content
; such as dynamic images
; http://php.net/tidy.clean-output
tidy.clean_output = Off

; Directory in which the loadable extensions (modules) reside.
; http://php.net/extension-dir
extension_dir = "/usr/lib/php7/modules/"
; On windows:
;extension_dir = "ext"

#ls /usr/lib/php7/modules/
curl.so    sodium.so  tidy.so    zip.so

A: There are docker commands to install php libraries. So instead of using linux command eg: apk add php-tidy  using docker-php-ext-install tidy solved my problem. Below is the docker file that works.

FROM php:7

ENV DEBIAN_FRONTEND noninteractive

USER root
RUN apt-get update
RUN apt-get upgrade -y
RUN apt-get install -y apt-utils
RUN apt-get install -y libzip-dev
RUN apt-get install -y libtidy-dev
RUN apt-get install -y curl
RUN apt-get install -y libcurl3
RUN apt-get install -y libcurl3-dev
RUN docker-php-ext-install zip
RUN docker-php-ext-install curl
RUN docker-php-ext-install tidy
RUN docker-php-ext-enable zip
RUN docker-php-ext-enable curl
RUN docker-php-ext-enable tidy

COPY . code
WORKDIR code

EXPOSE 8080
CMD php -S 0.0.0.0:8080

A: On Debian Bullseye based Dockerfile:
RUN apt-get update && \
    apt-get install -y libtidy-dev && \
    rm -rf /var/lib/apt/lists/* && \
    docker-php-ext-install tidy && \
    docker-php-ext-enable tidy