text:
Q: Run all sql files with Chef Hello i need help i made a command that should read all the sql files inside of the sql_dumps folder but it isnt working.. here is what i got.
execute "Run_SQL_Files" do
  dirResults = Dir.glob("/tmp/sql_dumps/*.sql")
  var = 0
  while var < 15 do
    var = var + 1
    command "mysql --user=root --password=toomba source" + dirResults[var]
    # Already tried this also
    # command "mysql --user=root --password=toomba < "  dirResults[var]
    puts dirResults[var]
  end
end

I'am not very familiar with ruby. This is the error i received
 default: Errno::ENOENT
 default: -------------
 default: No such file or directory - Run_SQL_Files
 default:
 default: Resource Declaration:
 default: ---------------------
 default: # In /tmp/vagrant-chef-3/chef-solo-1/cookbooks/main/recip
 default.rb
 default:
 default: 214:
 default: 215: execute "Run_SQL_Files" do
 default: 216:   dirResults = Dir.glob("/tmp/sql_dumps/*.sql")
 default: 217:   var = 0
 default: 218:   while var < 15 do
 default: 219:     var = var + 1
 default: 220:     puts `mysql --user=root --password=toomba source
 {dirResults[var]}`
 default: 221:     puts dirResults[var]
 default: 222:   end
 default: 223:   #command "mysql --user=root --password=toomba < "
 iles
 default: 224: end

Thanks in advance!

A: There is a misconception here about how Chef compiles resources. You are expecting Chef to execute the command 15 times, but that's not how Chef operates. Chef runs in two phases - the execution phase, and the compilation phase. During the compilation phase (which runs first), the Ruby is evaluated and resources are added to the resource collection. With some exceptions, this phase does not alter the state of the system. So given your recipe:
execute "Run_SQL_Files" do
  dirResults = Dir.glob("/tmp/sql_dumps/*.sql")
  var = 0
  while var < 15 do
    var = var + 1
    command "mysql --user=root --password=toomba source" + dirResults[var]
    # Already tried this also
    # command "mysql --user=root --password=toomba < "  dirResults[var]
    puts dirResults[var]
  end
end

That is functionally equivalent to a recipe that was written like this (after the compilation phase completes)"
execute "Run_SQL_Files" do
  command "mysql --user=root --password=toomba source /tmp/sql_dumps/15.sql"
end

Notice that Chef is only going to utilize the last value for the command attribute. That is because Chef executes in two phases (as already mentioned).
Using conditional logic and loops inside of a resource definition is almost always going to cause problems. In this example, you need to compile the command outside of the execute resource. Each SQL command you want to execute needs to have it's own execute block. Here's a simple, refactored example:
Dir["/tmp/sql_dumps/*.sql"].each do |path|
  execute "run_sql_#{path}" do
    command "mysql --user=root --password=toomba < #{path}"
  end
end

This will put 15 (assumption from OP) execute resources in the resource collection, and execute them in order.


text:
Q: Firebase 2.0・Query Users for Username from UISearchField・Swift Im implementing a search box is my swift application that searches my firebase database for accounts that match their username.
my database structure is

"users" {

"uid" {

"first_name" : "Bob",

"last_name" : "Someone"

"username" : "bobby"

}

}

(Sorry for block quotes i could get it to look good)
My problem is that i need to search for peoples usernames not and to do this i need to have my database path as
Database.child("users").child(uid!)

and then i can see the data.
I need to be able to search for a users username without having to set the path with their UID
Thanks :)

A: Firebase 2.x and 3.x
Since you mentioned that you are using firebase 2.0 you should be looking into firebase legacy documentation for orderedByChild() combined with queryEqualToValue(). Either way, searching in the new firebase docs you will see that nothing changed in terms of Sorting and Filtering Data and so you will still be using the same call in both versions.
ref.child("users").queryOrderedByChild("username").queryEqualToValue(username).observeEventType(.ChildAdded, withBlock: { snapshot in
    if let username = snapshot.value["username"] as? String {
        print("UID: \(snapshot.key) Username: \(username)")
    }
})

redpajama_set_name: RedPajamaStackExchange


text:
Q: Plesk Schedule Task Empty File I want to create a cron job from scheduled tasks in Plesk. I am facing a weird problem with it, I have created the task and my command runs successfully if I press "Run now". If I let it runs automatically every 1 hour the file is empty.
Here is my command:
/usr/bin/mysqldump -u username -p'pass' dbname > path/mybackup.sql


text:
Q: how to retrieve latest data from mysql table out of duplicate records I am trying to retrieve latest data from my sql table for each record. There will be duplicate data for each record with some data changes. I need to retrieve the latest timestamped data. Can someone suggest which is the optimum solution in terms of performance. Have seen some solutions with inner joins and sub queries.
Sample data given below
Technology Students Amount Area      Date
python     500      1000   Bangalore 2021-08-06 12:03:26
Ruby       100      1000   Bangalore 2021-08-06 05:18:50
Java       300      1000   Bangalore 2021-08-06 18:23:40
python     900      1000   Bangalore 2021-08-06 16:23:30
Java       100      1000   Bangalore 2021-08-06 12:23:50
Ruby       500      1000   Bangalore 2021-08-06 15:13:40

my o/p should contain latest data for each tech
Technology Students Amount Area      Date
Java       300      1000   Bangalore 2021-08-06 18:23:40
python     900      1000   Bangalore 2021-08-06 16:23:30
Ruby       500      1000   Bangalore 2021-08-06 15:13:40

A: One way to do this:-
*Replace Table with real table Name.
select table.*
from table
join
(
    select Technology, max(Date) as max_dt
    from table
    group by Technology
) t
on table.Technology= t.Technology and table.Date = t.max_dt

A: The most performant solution where you don't need to self-join is to use a window function, optionally with a cte although a sub-query is fine also.
Unfortunately row_number() is supported only from version 8.0, however including here for completeness and to show why you should upgrade!
    with latest as (
        select * , Row_Number() over(partition by technology order by date desc) rn
        from t
    )
    select Technology, Students, Amount, Area, Date
    from latest
    where rn=1


text:
Q: Why won't Google app engine observe my health check interval? I am using Google App Engine Flexible environment (Node.js)
I have my own custom healthcheck implementation, however it is getting run every single second rather than the 8 seconds I have configured below.
Since my healthcheck does some things that are non trivial I would like to remove some load from my server by increasing the interval
health_check:
  enable_health_check: True
  check_interval_sec: 8
  unhealthy_threshold: 10
  healthy_threshold: 2
  timeout_sec: 8

Any idea why my interval won't work?

A: App Engine flexible health checks use the same underlying infrastructure as the cloud load balancer. From the load balancer docs:

multiple probers simultaneously evaluate the instances... The interval
and timeout settings that you configure for a health check are applied
to each prober. For a given backend, software access logs and tcpdump
show more frequent probes than your configured settings.


text:
Q: Measurement formalisms - POVM formalism vs Hermitian observables I am thinking in following way of thinking about measurements in quantum mechanics. Please correct any false statements I may be making below.

*

*We start with POVMs. Let our POVM be a set of positive operators
$\{E_i\}$ that sum to the identity. We have a set of possible
outcomes $i$ and each outcome occurs with probability $p_i$. The
post-measurement state depends on the implementation of the POVM so
we cannot say anything about it.

*We could rewrite the POVM as $\{E_i = M^\dagger_i M_i\}$ - a
specific implementation of the POVM. Now, we can also say that if we
observe outcome $i$, we have a post measurement state $\rho =
\frac{M_i\rho M_i^\dagger}{\text{Tr}(M_i\rho M_i^\dagger)}$.

*The last case is where the $M_i$ are projectors. Now, we can repeat
measurements and the state (after the first collapse) stays in the
eigenstate that it collapsed to.
Note that this formalism says nothing about eigenvalues. All you have are states, outcomes that occur with a certain probability and post-measurement states. We could label these outcomes with something and call the labels the result of the measurement.
On the other hand, we often hear this statement that all quantum observables correspond to Hermitian operators and their real eigenvalues represent the "measurement" we've made. How does one connect this to the formalism I wrote above? I can see that every Hermitian observable can be written as a projective POVM with some real number attached to each outcome. An answer here explains that in principle, one can label the POVM outcomes with anything (even apples, bananas and oranges as suggested).
Questions

*

*Do we choose Hermitian operators because we'd like all measurements we make in practice to have a real number in the outcome label and would like the state to collapse to one among an orthogonal set of eigenstates?

*If I chose not to use real numbers, do I not lose the physical meaning of quantities like energy? A three level atom has energy levels $E_1, E_2$ and $E_3$ and no matter what scale I use, the difference $E_2 - E_1$ being greater than or less than or equal to the difference $E_3 - E_2$ has clear physical consequences, no? It therefore seems like real eigenvalues are necessary if one wants to measure things like energy, position, etc.

*What about POVMs of type 1. and 2. above? Why are physical observables like position or momentum not of type 1 or 2?


text:
Q: Screenshots in Selenium Project Where to store screenshots while running selenium test cases?
I have developed an automation framework using Selenium in C#. I have developed by projrct in Visual Studio and using git Repository. I will be running my test cases through Jenkins.


text:
Q: Rolling mean with irregular boundaries I am using rolling mean on my data to smoothen it. My data can be found here.
An illustration of my original data is;

Currently, I am using
import pandas as pd
import numpy as np

data = pd.read_excel('data.xlsx')
data = np.array(data, dtype=np.float)
window_length = 9
res = pd.rolling_mean(np.array(data[:, 2]), window_length, min_periods=1, center=True)

This is what I get after applying rolling mean with a window_length of 9;

And when i increase the window_length to 20, I get a smoother image but at boundaries, the data seems to be erroneous.

The problem is, as seen in the figures above, the rolling mean introduces some sort of errors at the boundaries of my data which do not exist in the original data.
Is there any way to correct this?
My guess is, at the boundary, since part of the window_length is found outside my data, it exaggerates the mean.
Is there a way to correct this error using pandas rolling mean or is there a better pythonic way in doing this? Thanks.
Ps. I am aware the panda function of rolling mean i am using is deprecated in the new versión.

A: You can try a native 2D convolution method such as scipy.ndimage.filters.convolve with weights so just make the kernel an average (mean) function.
The weights would be:
n = 3. # size of kernel over which to calculate mean
weights = np.ones(n,n)/n**2

If the white area of your data are represented by nans, this would reduce the footprint of the result by n since any kernel stamp with a nan included will return a nan. If this is really an issue try look at astropy.convolution, which has better nan handling.


text:
Q: Can Null-conditional operator (Elvis operator) prevent IndexOutOfRangeException? I am reading null-conditional operator introduced in C#6.0.
I did chaining of ?. operator and came across following function
double SumNumbers(List<double[]> setsOfNumbers, int indexOfSetToSum)
{
    return setsOfNumbers?[indexOfSetToSum]?.Sum() ?? double.NaN;
}

Can it also handle IndexOutOfRangeException or I have to still add ugly try-catch?

A: No, simply because it is a null-conditional operator, not an indexoutofrange-conditional operator.
One way you could work around it is to use the ElementAtOrDefault method that checks for the index and returns null if its out of range.


text:
Q: Error: Could not find a suitable provider for cron From what I'm reading it seems cron is built into Puppet.
cron { 'apply puppet master config':
  command => 'puppet apply /etc/puppetlabs/puppet/master.pp',
  hour    => [ 12, 0 ],
}

Yet when I try to run the above configuration I get the following error:

Error: Could not find a suitable provider for cron

Why isn't Puppet using the built in cron type?

A: Despite the fact that my system had cron jobs located in /etc/cron.daily
and /etc/cron.weekly the cron package on ubuntu which Puppet relies on wasn't installed. (As pointed out in comments by Dominic & Matt).
I was able to fix this by adding this to my configuration file before running the cron configuration:
package { 'cron':
  ensure => installed,
}


text:
Q: Running multiple CMD in dockerfile I have a requirement to run both the Mock API and UI of a reactjs application. Can i use something like
CMD /usr/src/api/ npm start ; /usr/src/app/ npm start

after npm install of the respective package.json files.
Please advise.
Thanks.

A: While it's possible, a solution with two containers would actually be simpler:
since npm start is probably blocking, it would need to be put to background, otherwise you wouldn't be able to run the second npm start. But putting the servers to the background would end up stopping the container as there would be no foreground process running anymore and the container would exit.
So, in adddition to having to background them, you would have to add a way to make the container not exit.


text:
Q: forever keep restarting sails after every 100s I have built web socket based application using sails js(v0.11.2) and mysql (5.6.22) with sails_mysql_live_connect .
I have set mysql wait_timeout to 100s for GC(Garbage collector) to close any unused open connections.
Due to wait_timeout, mysql is now closing web socket connection to db after 100s and forever restarts sails as db connection has been closed.
I am getting following error in sails every time mysql closes the connection

Is there any work around for this without increasing wait_timeout?


text:
Q: Who assigns private IP addresses? Suppose I have a router and a local network, can I freely assign my devices private IP addresses (as many as I want, up till there are no more private IP addresses left)? Who decides how many private IP addresses I can have?

A: They are PRIVATE. If you wire a house, who decides how many doors you can have?
The IP address spaces that are NOT USED ON THE INTERNET are defined in an RFC. Private addresses are part of that (actually THE part of it) and are in there.
You can use whatever you want from that. There is no authority. They are not existing on the internet.
Obviously if you VPN etc. to another entity, they can do the same, so you better coordinate.


text:
Q: Prevent Android webView rotation I have a webview on my activity and I want to be able to control its rotation behaviour. According to Android documentation

The standard behavior for an Activity is to be destroyed and recreated when the device orientation or any other configuration changes. This will cause the WebView to reload the current page. If you don't want that, you can set your Activity to handle the orientation and keyboardHidden changes, and then just leave the WebView alone. It'll automatically re-orient itself as appropriate. Read Handling Runtime Changes for more information about how to handle configuration changes during runtime.

So,that "It'll automatically re-orient itself as appropriate" is what I want to control.

A: If you need to stop the rotation of webview, then You can set the orientation in manifest only for the activity which holds the webview.


text:
Q: Embed a local HTML file How do I embed a local HTML file in an executable file???
For example I have something called war.html, how do I embed it on an executable file?
I use Visual Studio 2010 and can use different encodings like Visual Basic, Visual C++, etc.
Thank you and hope you understand.

A: You can use the file2c utility, which converts a file into a definition that can be used in C source.


text:
Q: Некорректно работает Bootstrap v4 на Safari Есть данный кусок кода

лучшее заведение

Работаем с 12:00

            <button class="booking btn btn-lg btn-outline-light">Резервация столика</button>

Три div внутри div.container в Chrome браузере отображаются вертикально по центру, но только не в Safari. Не знаю, что с этим делать, опыта не так много, узнал недавно и так как у многих юзеров Safari, все это выглядит не очень.

A: Советую вам почитать о сетке bootstrap. Зачем использовать container внутри container-fluid?
Думаю, что это решит вашу проблему:

лучшее заведение

Работаем с 12:00

      <button class="booking btn btn-lg btn-outline-light">Резервация столика</button>


text:
Q: SQL Server View Access Speed Versus Writing View to Table I have a SQL Server 2008 DB that has a set of views that are accessed by a program.  Our goal is to optimize the access speed of the program (which pulls in data on a user request), to minimize end-user impact.
Right now we are writing all of our views to tables, and passing those mappings to the application (we found the application performed better reading from tables as opposed to views).  We are soon going to implement indexes (still need to discuss with the application vendor what indexes will speed up their import), but for now we're trying to figure out the best way to optimize the import.
The plan currently is to write the views to tables, add the proper indexes and then run a (select *) statement to force them into memory.  My question is whether A) writing them to tables is necessary once we have the indices and the select * and B) what are some methods that we are missing?
Edited to clarify question goal.

A: OK I think I follow
Select into implies you are dropping the table and let select into create
You are probably better off with a truncate
If it is a FK then you need to delete but they tend to be smaller
And then just do an insert into
This way you also don't need to drop and recreate views
If you can take the hit you are better off taking a tablock hit the whole table
If the linked is slow then insert into some local staging tables
From the staging table load the production table
I totally don't get why you would materialize a view into table.
If you have performance issue with a view then first optimize the view.
What is going on in the view that is slow?


text:
Q: I try to make it blink, but it won't work I'm trying to create notifications system in my company's ERP, similar to Facebook one. For now, after few hours of work, it looks like this:

Each menu item is a lielement. Each element can have one of classes that will modify it's background color:

*

*selected is blue, shown on a picture

*restricted is red

Now, what I'm trying to achieve is to make li background blink on some events (when new message comes in and list is not opened (and also selectedclass is not present)).
The problem is: it won't blink. :(
here's snap of my html (excluding messagebox)

3

   :

  Strona główna
   :

Also, there's some JavaScript initiating object (don't mind comments):
function notificationsObject(){
  var nl = new Object();

  //atrybuty klasy
  nl.liElement = $('.notifications-topmenu-button');
  nl.menuButton = $('.notifications-topmenu-button-wrapper');
  nl.menuButtonCounter = nl.menuButton.find('.notifications-topmenu-button-counter');
  nl.notificationsCount = jQuery.trim(nl.menuButtonCounter.text());
  nl.notificationsList = $('.notifications-list-wrapper');
  nl.blinkingInterval = null;

  nl.startBlinking = function(){
    nl.blinkingInterval = setInterval(function(){
                                        if(nl.liElement.hasClass('restricted') == false){
                                          console.debug(nl.liElement.addClass('restricted'));
                                        }
                                          else {
                                            nl.liElement.removeClass('restricted');
                                          }
                                      }, 1000);
  }

  nl.stopBlinking = function(){
    if(nl.blinkingInterval != null) nl.blinkingInterval = null;
  }

  (more 'class' functions)

  return nl;
}

Now to test it, I simply call
$(document).ready(function(){

  var notifications = notificationsObject();
  notifications.startBlinking();

});

Of course I call it after function declaration.
funny fact is that when I change nl.startBlinking function setInterval internals to only add restrictedclass, it works. I'm pretty sure it must be some typo or stupid error, but I can't find it.
Please, help!

A: Try to use the toggleClass function instead of checking classes yourself like:
setInterval(function(){
    nl.liElement.toggleClass('restricted');
}, 1000);

jQuery reference: http://api.jquery.com/toggleClass/

A: I put all your code into a Fiddle here and it worked. Not sure what the problem is.
added css
.restricted{
    visibility:hidden;
}

Also removed (more 'class' functions) line. But I assume you just added that to the post and it's not part of your code.

A: Ok, problem solved.
the thing was that this function
nl.startBlinking = function(){
    nl.blinkingInterval = setInterval(function(){
                                        if(nl.liElement.hasClass('restricted') == false){
                                          console.debug(nl.liElement.addClass('restricted'));
                                        }
                                          else {
                                            nl.liElement.removeClass('restricted');
                                          }
                                      }, 1000);
  }

started executing on declaration.
so when I called
$(document).ready(function(){

  var notifications = notificationsObject();
  notifications.startBlinking();

});

I had not one, but two intervals working at the same time.

A: Add and remove the 2 classes in stead of only restricted
if(nl.liElement.hasClass('restricted') == false){
                                           nl.liElement.addClass('restricted');
                                           nl.liElement.removeClass('selected');
                                        }
                                          else {
                                           nl.liElement.removeClass('restricted');
                                           nl.liElement.addClass('selected');
                                          }


text:
Q: How to install Terraform in Ubuntu I tried to install terraform in Ubuntu desktop but I am getting error:
bash: /usr/local/bin/terraform: cannot execute binary file: Exec format error"

The same steps working for cloud servers.

A: What about using Terraform official deb repository, you can than install and update  Terraform using apt.
https://www.terraform.io/docs/cli/install/apt.html#repository-configuration
Like this:
curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add -
sudo apt-add-repository "deb [arch=$(dpkg --print-architecture)] https://apt.releases.hashicorp.com $(lsb_release -cs) main"
sudo apt update
sudo apt install terraform

A: My one-liner to install the latest version:
sudo echo ; zcat <( CURRR_VER=$(curl -s https://checkpoint-api.hashicorp.com/v1/check/terraform | jq -r -M '.current_version') ; curl -q "https://releases.hashicorp.com/terraform/${CURRR_VER#?}/terraform_${CURRR_VER#?}_linux_amd64.zip" ) | sudo tee /usr/local/bin/terraform > /dev/null ; sudo chmod +x /usr/local/bin/terraform

Using the line from https://github.com/hashicorp/terraform/issues/9803#issuecomment-257903082

A: Steps to install terraform on Ubuntu / Ubuntu cloud server :

*

*Install unzip
sudo apt-get install unzip

*Confirm the latest version number on the terraform website:
https://www.terraform.io/downloads.html

*Download latest version of the terraform (substituting newer version number if needed)
wget https://releases.hashicorp.com/terraform/1.0.7/terraform_1.0.7_linux_amd64.zip

*Extract the downloaded file archive
unzip terraform_1.0.7_linux_amd64.zip

*Move the executable into a directory searched for executables
sudo mv terraform /usr/local/bin/

*Run it
terraform --version

A: If you're running Ubuntu plus snap installed, just call:
sudo snap install terraform --classic

A: This error occured when you try run 64 bit exec file on 32 bit system.
Check your system:

uname -a

x86_64 or i686 mean 64 or 32 bit accordinary.

A: You can also use 3 different tools that can help you to install and use specific versions of Terraform (similar to nvm, pyenv, rbenv, rustup tools):

*

*tfswitch: https://github.com/warrensbox/terraform-switcher/

*cloudposse/tfenv: https://github.com/cloudposse/tfenv

*tfutils/tfenv: https://github.com/tfutils/tfenv/
I like the first one as it was made in golang and a snap package is available (but not currently in latest version https://github.com/warrensbox/terraform-switcher/issues/126).
The most popular is tfutils/tfenv/ and that's the one that I'm using right now.

A: I referred to The Official Terraform Website to install Terraform for Ubuntu and Debian.
Ensure that your system is up to date, and you have the gnupg, software-properties-common, and curl packages installed. You will use these packages to verify HashiCorp's GPG signature, and install HashiCorp's Debian package repository:
sudo apt-get update && sudo apt-get install -y gnupg software-properties-common curl

Add the HashiCorp GPG key:
curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add -

Add the official HashiCorp Linux repository:
sudo apt-add-repository "deb [arch=amd64] https://apt.releases.hashicorp.com $(lsb_release -cs) main"

Update to add the repository, and install the Terraform CLI:
sudo apt-get update && sudo apt-get install terraform

Check if Terraform is successfully installed:
terraform -v

A: sudo apt-get install terraform

then run the command sudo apt-get update then sudo apt-get upgrade
will help you to get the suitable version of the teraform into the simulated hardware that was fetched from the Ubuntu install or any of the Linux version installed into your system.


text:
Q: Electron pass creator window id to new BrowserWindow I'm making an electron app that runs a custom script on a website in the background. This code is being executed in a second window created by the main window. The second window then creates another hidden window where the website will be loaded and the custom script will be run. I need to be able to pass the window id of the second window to the hidden window so when the custom script is finished running it can send an ipc message back specifically to the second window.
I found an issue on github where someone answered in 2016 that it appeared you could assign custom values to win and then read them in the newly created window but I have had no success implementing that.
        // In second window
        const currentWindow = require('electron').remote.getCurrentWindow();
        // Create hidden window
        win = new BrowserWindow({ show: false });
        win.creatorId = currentWindow.id; // CUSTOM: Set creator window ID
        win.webContents.openDevTools();
        win.webContents.on('dom-ready', () => {
            // Load dependencies every time a new url is loaded
            win.webContents.executeJavaScript(`
                const currentWindow = require('electron').remote.getCurrentWindow();
                alert(currentWindow.creatorId); // This is undefined :(
                const { BrowserWindow } = require('electron').remote;
                const ipc = require('electron').ipcRenderer;
                window.$ = window.jQuery = require('jquery');
            `);
        });

        ...

        worker.win.loadURL(`random.webpage`);
        // Run custom script on a website and send the result back to the creator window
        win.webContents.executeJavaScript(`
            $(document).ready(function () {
BrowserWindow.fromId(currentWindow.creatorId).webContents.send('coolMessage', {});
            });
    `);

When I try to read win.creatorId it is undefined. How can I identify the second window from the hidden window so I can send messages to it?

A: In your win.webContents.executeJavaScript you could set the variable inside the execute javascript function like this:
win.webContents.executeJavaScript("var creatorId = " + currentWindow.webContents.id + ";");

That would mean you can delete the: win.creatorId = currentWindow.id;. And change the:
BrowserWindow.fromId(currentWindow.creatorId).webContents.send('coolMessage', {});

To:
BrowserWindow.fromId(creatorId).webContents.send('coolMessage', {});

webContents.id Docs


text:
Q: Align numpy arrays based on array keys I was wondering how I could potentially align two numpy array based each array value's "key", for use in NLP (I realize that this could probably be done much easier with the NLTK, but I'm trying not to use it for this implementation).
For Example, say I have two arrays defined as:
array1 = [['dolor' 5] ['sit' 3] ['amet' 1]]
array2 = [['scripsit' 10] ['sit' 1] ['amet' 1]]

I would like the output arrays to be the following:
array1 = [['scripsit' 0] ['dolor' 5] ['sit' 3] ['amet' 1]]
array2 = [['scripsit' 10] ['dolor' 0] ['sit' 1] ['amet' 1]]

Would this be possible?

A: First you can get the unique keys then create a dict view of arrays and use a list comprehension to create the desire out put :
>>> all_keys=np.unique(np.array((array1,array2)).T[0])
>>> dict1=dict(array1)
>>> dict2=dict(array2)

>>> array1=np.array([[i,dict1.get(i,0)] for i in all_keys])
>>> array1
array([['amet', '1'],
       ['dolor', '5'],
       ['scripsit', '0'],
       ['sit', '3']],
      dtype='|S8')
>>> array2=np.array([[i,dict2.get(i,0)] for i in all_keys])
>>> array2
array([['amet', '1'],
       ['dolor', '0'],
       ['scripsit', '10'],
       ['sit', '1']],
      dtype='|S8')

Note :This approach will produce new arrays with same order.


text:
Q: UITableView delegate methods are not called when added on GooeySlideMenu I want to add UITableView on top of UIView which is a subclass of GooeySlideMenu. As in example shown in git I created UITableView instead of UIButtons but delegate methods are not called.
Below is my code for reference:
class GooeySlideMenu: UIView {

fileprivate var _option: MenuOptions
fileprivate var keyWindow: UIWindow?
fileprivate var blurView: UIVisualEffectView!
fileprivate var helperSideView: UIView!
fileprivate var helperCenterView: UIView!

fileprivate var diff: CGFloat = 0.0
fileprivate var triggered: Bool = false
fileprivate var displayLink: CADisplayLink?
fileprivate var animationCount: Int = 0
fileprivate   var myTableView: tableViewCustomClass  =  tableViewCustomClass()

init(options: MenuOptions) {
    _option = options
    if let kWindow = UIApplication.shared.keyWindow{
        keyWindow = kWindow
        let frame = CGRect(
            x: -kWindow.frame.size.width/2 - options.menuBlankWidth,
            y: 0,
            width: kWindow.frame.size.width/2 + options.menuBlankWidth,
            height: kWindow.frame.size.height)
        super.init(frame:frame)
    } else {
        super.init(frame:CGRect.zero)
    }
    setUpViews()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

override func draw(_ rect: CGRect) {
    let path = UIBezierPath()
    path.move(to: CGPoint(x: 0, y: 0))
    path.addLine(to: CGPoint(x: frame.width-_option.menuBlankWidth, y: 0))
    path.addQuadCurve(to: CGPoint(x: frame.width-_option.menuBlankWidth, y: frame.height), controlPoint: CGPoint(x: frame.width-_option.menuBlankWidth+diff, y: frame.height/2))
    path.addLine(to: CGPoint(x: 0, y: frame.height))
    path.close()

    let context = UIGraphicsGetCurrentContext()
    context?.addPath(path.cgPath)
    _option.menuColor.set()
    context?.fillPath()
}

func trigger() {
    if !triggered {
        if let keyWindow = keyWindow {
            keyWindow.insertSubview(blurView, belowSubview: self)
            UIView.animate(withDuration: 0.3, animations: { [weak self] () -> Void in
                self?.frame = CGRect(
                    x: 0,
                    y: 0,
                    width: keyWindow.frame.size.width/2 + (self?._option.menuBlankWidth)!,
                    height: keyWindow.frame.size.height)
            })

            beforeAnimation()
            UIView.animate(withDuration: 0.7, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.9, options: [.beginFromCurrentState,.allowUserInteraction], animations: { [weak self] () -> Void in
                self?.helperSideView.center = CGPoint(x: keyWindow.center.x, y: (self?.helperSideView.frame.size.height)!/2);
                }, completion: { [weak self] (finish) -> Void in
                    self?.finishAnimation()
                })

            UIView.animate(withDuration: 0.3, animations: { [weak self] () -> Void in
                self?.blurView.alpha = 1.0
            })

            beforeAnimation()
            UIView.animate(withDuration: 0.7, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: [.beginFromCurrentState,.allowUserInteraction], animations: { [weak self] () -> Void in
                self?.helperCenterView.center = keyWindow.center
                }, completion: { [weak self] (finished) -> Void in
                    if finished {
                        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(GooeySlideMenu.tapToUntrigger))
                        self?.blurView.addGestureRecognizer(tapGesture)
                        self?.finishAnimation()
                    }
            })
          //  animateButtons()
            myTableView.reloadData()
            triggered = true
        }
    } else {
        tapToUntrigger()
    }
}

}

 extension GooeySlideMenu {

fileprivate func setUpViews() {
    if let keyWindow = keyWindow {
        blurView = UIVisualEffectView(effect: UIBlurEffect(style: _option.blurStyle))
        blurView.frame = keyWindow.frame
        blurView.alpha = 0.0

        helperSideView = UIView(frame: CGRect(x: -40, y: 0, width: 40, height: 40))
        helperSideView.backgroundColor = UIColor.red
        helperSideView.isHidden = true
        keyWindow.addSubview(helperSideView)

        helperCenterView = UIView(frame: CGRect(x: -40, y: keyWindow.frame.height/2 - 20, width: 40, height: 40))
        helperCenterView.backgroundColor = UIColor.yellow
        helperCenterView.isHidden = true
        keyWindow.addSubview(helperCenterView)

        backgroundColor = UIColor.clear
        keyWindow.insertSubview(self, belowSubview: helperSideView)

        addUItableView()
      //  addButton()
    }
}

fileprivate func addUItableView(){

    myTableView.frame = CGRect(x: 0, y: 20, width: 300, height: 200)

    myTableView.backgroundColor = UIColor.white
    myTableView.delegate = tableViewCustomClass() as? UITableViewDelegate
    myTableView.dataSource = tableViewCustomClass() as? UITableViewDataSource
    addSubview(myTableView)

}

A: You need to declared tableview's delegate on tableViewCustomClass's class instead of GooeySlideMenu class .
In tableViewCustomClass
self.delegate = self in tableViewCustomClass's initialiser method


text:
Q: boost::asio async_read doesn't receive data or doesn't use callback I am trying to receive data from a server application using boost asio's async_read() free function, but the callback I set for when the receiving is never called.
The client code is like this:
Client::Client()
{
  m_oIoService.run(); // member boost::asio::io_service
  m_pSocket = new boost::asio::ip::tcp::socket(m_oIoService);

  // Connection to the server
  [...]

  // First read
  boost::asio::async_read(*m_pSocket,
                          boost::asio::buffer((void*)&m_oData, sizeof(m_oData)),
                          boost::bind(&Client::handleReceivedData, this,
                                      boost::asio::placeholders::error,
                                      boost::asio::placeholders::bytes_transferred));
}

I tried with small data (a short string) and I can't get it to work. When I use the synchronous read function (boost::asio::read()) using the two same first parameters, everything works perfectly.
Am I missing something with the use of the io_service? I am still unsure about how it works.

A: boost::asio::service::run () is a blocking call. Now, in your example it may or may not return immediately. In case it doesn't, you you are blocked even before you create a socket, and never call read, so cannot expect a callback. Otherwise, dispatch loop is exited, so no callbacks are ever delivered.
Read more about boost::asio::service::run (). I recommend you check out documentation including tutorial, examples and reference. It is worth going trough it in full to understand the concept.
Hope it helps!
P.S.: On a side note, your code is not exception safe. Beware that if constructor of the class fails with exception then destructor of that class instance is never called. Thus, you may leak at least m_pSocket if its type is not one of the "smart pointers". You should consider making it exception safe, moving the code to another method that should be called by user, or even wrapping this functionality with a free function.


text:
Q: which event is used when change the one textbox value it should change the related value in another textbox in jquery I want to change multiple textbox value, at that time the result should come on result textbox value on the spot.
I googled this question and most answered is that from change event this will work, but I try change as well as on event still didnt work for me.
Here is my view code
<nop-editor asp-for="Weight" />
<nop-editor asp-for="Quantity" />
<nop-editor asp-for="Fine" />
<nop-editor asp-for="Rate" />
<nop-editor asp-for="LabourCharge" />
<nop-editor asp-for="UnitPriceInclTax" />

Here is my jquery code,
$("#LabourCharge, #LabourChargeUnit, #Rate").on('input', function () {
    var fine = $('input[id="Fine"]').val();
    var rate = $('input[id="Rate"]').val();
    totalFineRate = fine * rate;

    if (selectedLabourChargeUnitId == 1) {
        var weight = $('input[id="Weight"]').val();
        var labourCharge = $('input[id="LabourCharge"]').val();
        var totalLabourCharge = weight * labourCharge;
    }

    if (selectedLabourChargeUnitId == 2) {
            var pcs = $('input[id="Quantity"]').val();
            var labourCharge = $('input[id="LabourCharge"]').val();
        var totalLabourCharge = pcs * labourCharge;
    }

    totalPrice = totalLabourCharge + totalFineRate;
    $('#UnitPriceInclTax').val(totalPrice);
});

Now as per the code, when I change totalLabourCharge or totalFineRate then the related value should show the $('#UnitPriceInclTax').val(); which is not working.


text:
Q: How to make multiple react Route where the path is almost same except the id I have an object called machines object.This object has it's unique key.Now i want to make Route like path={"/machine" + key} for all the machines.I am trying to do it like the following but it doesn't work
{Object.keys(this.state.machines).forEach((key, index) => {
  // console.log(this.state.machines[key].machineNo)
  <Route
    exact
    path={"/machine" + key}
    component={() => (
      <MachineComposition machine={this.state.machines[key]} />
    )}
  />
})}

A: Issue
You are using Array.prototype.forEach instead of Array.prototype.map to map the this.state.machines array to JSX. The .forEach callback is missing a return statement, but that wouldn't matter as .forEach is a void return so no routes would be returned to be rendered to the DOM anyway.
Solution
Use .map to map the machines array to JSX. Use the render prop if you are passing additional props to the routed component, and don't forget to also pass along the route props (i.e. history, match, location) if the component needs them.
{Object.entries(this.state.machines).map(([key, machine]) => {
  return (
    <Route
      exact
      path={"/machine" + key}
      render={(props) => (
        <MachineComposition machine={machine} {...props} />
      )}
    />
  );
})}

Suggestion
Since all these routes are effectively the same it would be better to render a single route where the machine key is a route path parameter, and the MachineComposition uses the params to access the machine key and get the specific machine.
Example:
<Route
  exact
  path="/machine/:key"
  render={(props) => {
    const machine = this.state.machines[props.match.params.key];
    return <MachineComposition machine={machine} {...props} />
  }}
/>


text:
Q: How can I sign a message(not transaction) from a dApp? When creating a dApp using Elrond Network, I need to authenticate a user without actually sending a transaction.
For other blockchains like Ethereum this is achieved using MetaMask which can sign a message and you can be sure that the user is who he sais he is.
I noticed that Elrond Wallet has a "Sign" feature but I'm unsure of how this would be used from the outside or how can I prompt the user to sign a message and send it back.
Can I use Maiar extension or Elrond Wallet to sign a message?

A: If you are not doing so already, I suggest you to use erdjs or the dapp package (which includes erdjs) to build your dapp.
Using those you will get the various signing providers that elrond made. This includes:

*

*WalletConnectProvider, which is used to login via the maiar app

*ExtensionProvider, which is used to login via a metamask like browser extension called the maiar defi wallet

*HWProvider, which is used to login via the ledger hardware

All of these providers allow you to login, sign transactions, send transactions and also to sign custom messages.
Example code to login via the ExtensionProvider:
let provider = ExtensionProvider.getInstance();
await provider.init();
let walletAddress = await provider.login();
let message = new SignableMessage({message: "Sign this message to make sure you are logged in"});
let signedMessage = await provider.signMessage(message);

Of course using the signed message in this case is optional, but can be useful if you plan to implement some server side authentication flow.

A: Contributing to Martin W answer:
dapp package is deprecated. Use dapp-core instead


text:
Q: java - losing focus I have an applet which you can make a player 32 pixels in any of 4 ways using WASD keys. But when I add a textarea or label, I cannot move my image anymore. Something to do with focus.
Code:
/**
Tile Generator
Programmer: Dan J.
Thanks to: g00se, pbl, Manny.
Started May 23, 2010
**/

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import java.io.*;
import java.util.*;

public class tileGen extends Applet implements KeyListener  {

    Image[] tiles; // tile arrays
    Image player; // player image
    int x, y, px, py, tx, ty; // x tile - y tile // player x - player y // tile x - tile y
    boolean left, right, down, up, canMove, respawn; // is true?
    int[][] board; // row tiles for ultimate mapping experience!
    final int NUM_TILES = 33; // how many tiles are we implementing?
    Label lx, ly; // to see where we are!

    int lastX, lastY, row, col;
    Label lbl1;

  public void init() {

    board = loadBoard();

    tiles = new Image[NUM_TILES];
    for(int i = 0;i < NUM_TILES;i++) {
        tiles[i] = getImage(getClass().getResource(String.format("tiles/t%d.png", i)));
    }

        player = getImage(getClass().getResource("player.png")); // our player
        addKeyListener(this);
        canMove = true;
        int spawnX = 4;
        int spawnY = 4;
        px =0;
        py =0;
        lastX = 0;
        lastY= 0;
            lbl1 = new Label("Label 2");
           add(lbl1);
           this.requestFocusInWindow();
    }

    private static final HashSet<Integer> BLOCKED_TILES = new HashSet<Integer>();
    static {
      BLOCKED_TILES.add(24);
      BLOCKED_TILES.add(0);
      BLOCKED_TILES.add(6);
      BLOCKED_TILES.add(25);
      BLOCKED_TILES.add(3);
      //add more tiles here
    }

    public void keyPressed(KeyEvent e) {

if (isInBound(lastX,lastY) == true) {
    System.out.println("\nYOU WENT OFF THE GRID.\n");
}

        int r1 = lastX + 1;
        if (lastX > 0) {
        r1 = lastX + 1;
        }else{
        r1 = 0;
        }
        int r2 = lastY;

        int u1 = lastX;
        int u2;
        if (lastY > 0) {
         u2 = lastY - 1;
         }else{
         u2 = 0;
         }

        int l1;
        if (lastX > 0) {
        l1 = lastX - 1;
        }else{
        l1 = 0;
        }
        int l2 = lastY;

        int d1 = lastX;
        int d2;
        if (lastY > 0) {
            d2 = lastY + 1;
        }else{
            d2 = 0;
        }

        right = true;
        left = true;
        up = true;
        down = true;

        if (blocked(r1,r2) == true) right = false; // we cannot go right
        if (blocked(u1,u2) == true) up = false; // we cannot go up
        if (blocked(l1,l2) == true) left = false; // we cannot go left
        if (blocked(d1,d2) == true) down = false; // we cannot go down
    if (left == true) {
            if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                left = true;
                px = px - 32;
                lastX = lastX - 1;
            }
        }

    if (right == true) {
            if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                right = true;
                px = px + 32;
                lastX = lastX + 1;
        }
    }

    if (down == true) {
            if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                down = true;
                py = py + 32;
                lastY = lastY + 1;
            }
        }

    if (up == true) {

            if (e.getKeyCode() == KeyEvent.VK_UP) {
                up = true;
                py = py - 32;
                lastY = lastY - 1;
            }
    }
repaint();

    }
public void keyReleased(KeyEvent e){

    } // ignore
public void keyTyped(KeyEvent e){} // ignore

  public void paint(Graphics g) {

        for (row = 0; row < board.length; row++) {
            for (col = 0; col < board[row].length; col++) {
                int index = board[row][col];
                g.drawImage(tiles[index], 32 * col, 32 * row, this);

            }
        }
        if (respawn == false) {
        g.drawImage(player, px, py, this);
    }
    if (respawn == true) {
         g.drawImage(player, 0,0, this);
         System.out.println("Respawned!");
         respawn = false;
 }
    } // end paint method

     public void update(Graphics g)
     {
          paint(g);
     }

    public int[][] loadBoard() {
        int[][] board = {
                { 2,2,24,24,24,24,24,1,3,0,0,0 },
                { 2,2,24,23,23,23,24,1,3,0,0,0 },
                { 1,1,24,23,23,23,24,1,3,3,3,1 },
                { 1,1,24,24,23,24,24,1,1,1,1,1 },
                { 1,1,1,1,7,1,1,1,1,1,1,1 },
                { 5,1,1,1,7,7,7,7,7,1,1,1 },
                { 6,1,3,1,1,1,3,1,7,7,7,1 },
                { 6,1,3,1,3,1,1,1,1,1,7,3 }
            };
    return board;
    }

public boolean blocked(int tx, int ty) {
  return BLOCKED_TILES.contains(board[ty][tx]);
}

    public boolean isInBound(int r, int c) {
    return (r >= 0) && (r < 8) && (c >= 12) && (c < 1);
}

} // end whole thing

A: When using a KeyListener in Swing the KeyEvent is only passed to the component that has focus.
I would guess that by default when no components are added to the Applet then it has focus. As soon as you add a label it probably has focus. You can try using
this.setFocusable( true );

before requesting focus on the Applet.
Also, why don't you use Swing instead of AWT?


text:
Q: How to fetching current month and year data from firebase in kotlin Does anyone have any idea on fetching current month and year data from firebase database. I will be appreciated if someone tell me

A: @kianhun4167 chai your question is not clear.
You cannot fetch dates from the firebase database until some date or month is already present inside the firebase database, its similar to when you create a new folder there's nothing inside it, you need to have some files inside that folder to access those.
Rather if you just want to get the current date or month or year or all. There are two different methods by which you can do that directly in android kotlin.
The first one would be
        val time :Long = System.currentTimeMillis()
        val format :SimpleDateFormat= SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        val date :String= format.format(time)

The second one would be, both of them will generate the kind of same results
        val a:LocalDate = LocalDate.now()
        val date:String = a.toString()

You need to figure out which one works best for you.


text:
Q: Copy the elements I am trying to copy the elements if an atray.
I have written the code below which returns the values stored in src in inverse and I can't find a way to return the elements in dest in the same order:
0 1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1 0
Here is my code:
.data
         n:        .word 10
     src:      .word 0 1 2 3 4 5 6 7 8 9
     dest:     .space 40
     i:        .word 0
     space:   .asciiz " "

.text
    main:
    la $t0, src
    lw $t1, i
    la $t2, dest
    lw $t4, n

    jal Function_CopytoStack

        jal Function_copyfrom_Stack_to_Dest

###############################################
       Function_CopytoStack:

 ################################################
 ###################

A: The second half works by (a) popping one item off the stack, then (b) storing that into an pointer, which starts at the beginning of the destination and advances forward.
Do the (b) part backwards, to accomplish a double reversal, which will cancel out the first reversal from the stack use.


text:
Q: Is copying a C# class library from one solution to another the only way to "share" that library? A useful principle in computer programming is DRY (Don't Repeat Yourself). I am trying to follow this rule as I am refactoring a large .NET Framework MVC project by breaking it down into separate solutions.
One problem that I am still unable to resolve to my satisfaction involves a set of C# libraries (static functions, Authorization Attribute overrides, and others) that need to be identical in each solution. These solutions are pushed to TFS source control, which means that linked projects outside the solution will not copy to source control. In other words, all projects need to be contained within the solution.
This image is a (highly simplified) illustration of what I am trying to describe. My intention is for the top solution "C# .NET Framework Solution" to have the "master copy". The other solutions rely on those same libraries. While I can "link" to those solutions, that approach only works on the PC where those solutions are authored. Projects linked to outside the solution cannot be pushed (in my experience) to source control.

The approach I am using – which does work as intended – is to maintain my "master copy" of C# class libraries in a specific solution. I have manually copied the specific C# class library projects to each of the solutions that need them.  The good thing is that because the "copied" project exists in the solution, the solution can be pushed to source control in the intended manner. The bad thing is that this is a "copy".
My one question is this: is there a way to have the best of both worlds, where the C# library project exists in the solution, but if I make a change to the "master copy" all the "copies" in the other solutions are synced?  Why would I want this? Imagine if the code does change in one or more of those libraries and I (or my successor) forgets to make those changes in all those other solutions? What if I make a mistake in one or more of the copies?
Is my current technique the only option I have, or is there a different way for me not to break the DRY principle?

A: If you're not into using NuGet, create a common utilities DLL and put it in a shareable folder. For example, we have a DBUtils.dll library of commonly used DB methods that we can add as a reference. It works great for us.

A: Shortest answer ever : publish reusable library with required dependencies as NuGet package and install it wherever you need. It will help you in versioning as well.
If your class library is .NET Framework, converting it to .NET Standard will solve many problems involved with publishing it as a NuGet package. Visual Studio 2017 makes it very easy to do this, but only if it is .NET Standard.
To serve the NuGet packages, there are some options:

*

*Copy the .nupkg file to a shared folder location. In Visual Studio, you can configure NuGet to read from that folder location Tools > Options > NuGet Packge Manager > Package Sources.

*Follow the instructions on Hosting your own NuGet feeds.


text:
Q: wordpress site domain open the old site domain old path

*

*http://www.tantifilm.top
testing path

*

*http://www.tantifilm.top/test
i uploaded my complete wordpress project in test folder my new wordpress site path like this when i open this url site opened perfectly

*

*http://www.tantifilm.top/test/
when i click on any navigation link  page opened and urls show me this
http://www.tantifilm.top/serie-tv/ link
 instead of this http://www.tantifilm.top/test/serie-tv/
siteurl   : http://www.tantifilm.top/test/
baseurl   : http://www.tantifilm.top/test/

i import the database and update the link in wp_option i dont understand why  http://www.tantifilm.top/test/serie-tv/ this link not open

A: Try this on your databse (sql):
//SQL to change domain name
UPDATE wp_posts SET guid = replace(guid, 'http://www.old-domain.com','http://www.new-domain.com');
UPDATE wp_posts SET post_content = replace(post_content, 'http://www.old-domain.com', 'http://www.new-domain.com');
UPDATE wp_postmeta SET meta_value = replace(meta_value, 'http://www.old-domain.com', 'http://www.new-domain.com');
UPDATE wp_options SET option_value = replace(option_value, 'http://www.old-domain.com', 'http://www.new-domain.com') WHERE option_name = 'home' OR option_name = 'siteurl';

And then go to the WordPress backend, "Settings" -> "Permalinks" and click "Save Changes".
I hope this helps.


text:
Q: Can I use 'eval' to define a function in Python? I want to define a Python function using eval:
func_obj = eval('def foo(a, b):  return a + b')

But it return invalid syntax error?
How can I make it?
Btw, how can I transform a function obj to a string object in Python?

A: You can use eval with lambda, like:
func_obj = lambda a, b: eval('a + b')

A: Use exec. eval is used for expressions not statements.
>>> exec 'def foo(a, b):  return a + b'
>>> foo(1, 2)
3

Function code from function object:
def func():
    """ I'm func """
    return "Hello, World"
...
>>> import inspect
>>> print inspect.getsource(func)
def func():
    """ I'm func """
    return "Hello, World"

A: def test_eval():
    exec('def foo(a, b):  return a + b')
    foo(1, 2)

@niitsuma This code will return error: NameError: name 'foo' is not defined
This is because foo is defined in other scope that you execute it. To fix it and make it visible in oouter scope, you can make foo global variable:
def test_eval():
    exec('global foo\ndef foo(a, b):  return a + b')
    foo(1, 2)

A: I wrote
def test_eval():
    exec('def foo(a, b):  return a + b')
    foo(1, 2)

in mypackage/tests/test_mycode.py with approprite mypackage/setup.py.
But python setup.py test cause
NameError: name 'foo' is not defined.
How to test codes from string?


text:
Q: Jenkins / Hudson automatically permute parameter values of parameterized builds I have a parameterized build that has some options as to how to build the project. For example:

*

*color: red, green or blue

*package: yes, no

Since this list is likely to grow and I would like to be notified which configuration specifically broke I'd like Jenkins to build all variants of this build. So that after each checkin it executes the build with all available colors and each color with and without packaging.
Is there something like this? Specifically I'd like to avoid creating a new job for each configuration of the build.

A: Jenkins has matrix projects, see the wiki. They do exactly what you want and more.


text:
Q: Python like inheritance for JavaScript In python I can do something like this
main.py
class MainClass:
    def __init__(self):
        self.name = "some_name"
    def startDoingStuff(self):
        print("I'm doing something boring")

    def printName(self):
        print("My name is " + self.name)

sub.py
import main
class Sub(main.MainClass):
    def startDoingStuff(self):
        print("I'm doing something interesting")
        self.name = "sub"

sub = Sub()
sub.printName() # prints 'My name is some_name'
sub.startDoingStuff()
sub.printName() # prints 'My name is sub'

Is there a JavaScript equivalent?

A: If prototype-based inheritance is a little daunting, you might look into extension based inheritance.
A really basic implementation looks like this.   (John Resig's implementation linked above is more robust, but I think this is a little more readable, but with the same basic concept)
var extend = function(subTypeInit) {
    var SuperType = this;
    var SubType = function () {
         function SuperTypeProxy(args) {
              return SuperType.apply(this, args);
         }
         var base = new SuperTypeProxy(arguments);
         subTypeInit.apply(base, arguments);
         return base;
    }
    SubType.extend = extend.bind(SubType);
    return SubType;
}

Then it can be used like this:
var Main = function (name) {
    var self = this;
    self.name = name;
    self.doSomething = function () {
         console.log("something boring");
    };
    self.printName = function () {
         console.log("Hi, I'm "+name);
    };
};

Main.extend = extend.bind(Main); //Manually attach to first parent.

var Sub = Main.extend(function () {
    var self = this;

    self.doSomething = function () {
         console.log("something interesting");
    };

    var superPrintName = self.printName;
    self.printName = function () {
         superPrintName();
         console.log("And I'm a sub class");
    };
});

var sub = new Sub("foo");
sub.doSomething(); //logs "something interesting"
sub.printName(); //logs "Hi, I'm foo" "And I'm a sub class"

Some caveats here, you really probably should look into prototype based inheritance, which is what javascript is really built for.  Extension-based inheritance is a little more natural for someone who's used to other OO languages' approaches to inheritance, but the disadvantage is that it consumes more resources to do inheritance this way; you're creating a lot of functions (and a lot of closures), which can really add up.


text:
Q: JavaScript prompt if/else response When the object is clicked, the prompt shows up, but nothing happens when the answer is submitted. Is there an issue with the naming of the password? Any advice much appreciated!

var password;
var pass1 = "thailand";
password = function password() {
  prompt('What was the first country we visited together?');
};
if (password == pass1) {
  //Change the page here
  console.log("Correct");
} else {
  console.log('sorry, try again!')
};

Click me!

A: You need to store what's been inputted in the prompt. Also you made the comparison outside of the function before the prompt was displayed.
I updated the code, but you might need to make some adjustments :

Click me!

Hope this helps

A: You don't need function password(). Removed that.
And also added window.location.href instead of window.location

Click me!


text:
Q: Determine whether $-7 + \frac {14} 3 - \frac {28} 9 + \frac {56} {27} + \dots$ converges or not. Determine whether the series converges or not.
$$-7 + \frac {14} 3 - \frac {28} 9 +  \frac {56} {27} + \dots$$
This is the Alternating Harmonic Series but I can't see the common ratio here. Any suggestion? Thank you.

A: One may recall that

$$
\sum_{n=0}^\infty x^n=\frac1{1-x},\qquad |x|<1.
$$

Then you may write your series as
$$
-7\times\sum_{n=0}^\infty \left(-\frac23\right)^n.
$$ and conclude.


text:
Q: What is the exact gravitational force between two masses including relativistic effects? Is there a closed-form formula for the force between two masses $m_1$ and $m_2$ if relativistic effects are included? My understanding is that the classic formula $G \frac{m_1 m_2}{r^2}$ is just an approximation (which is probably good enough even for going to the Moon), but what would the correct formula be according to the general theory of relativity? Does a closed formula even exist? For example for an idealized situation of two uniform spherical masses?

A: Yes the non-relativistic equation of motion
$$\frac{dp}{dt} = F = -\frac{G m_1 m_2}{r^2}$$
for a single particle interacting gravitationally with other is only valid for velocities much smaller than the speed of light and for small enough masses. Notice the minus sign in the expression for the non-relativistic force F --gravitation is attractive--.
First, general relativity is a (geo)metric theory. There is no gravitational forces in general relativity. In general relativity, bodies affected only by gravitation are moving freely, but in a curved spacetime

(source: twimg.com)
The general relativistic equation of motion for a single body is the geodesic equation
$$\frac{DP^\mu}{D\tau} = 0$$
Note the zero at the right, which is a consequence of the absence of gravitational forces in general relativity. The greek indices run over 0,1,2,3 --the spacetime coordinates-- and summation convention is being used. $P^\mu$ is the four-momentum, $\tau$ the proper time and $D$ denotes the covariant derivative, which includes the effects due to spacetime curvature
$$\frac{DP^\mu}{D\tau}
=
\frac{dP^\mu}{d\tau}
+
\Gamma_{\nu\lambda}^\mu U^\nu P^\lambda ,$$
where $\Gamma_{\nu\lambda}^\mu$ are the Christoffel symbols and $U^\nu$ the four-velocity.
Second, the field theory of gravity provides a non-geometrical description of gravity. There are gravitational forces in the field theory. In this theory, bodies affected only by gravitation are moving in a flat spacetime --sometimes this is named the flat spacetime approach to gravitation-- but feel a gravitational force associated to gravitons

(source: twimg.com)
The field-theoretic equation of motion for a single body in a gravitational field is the Kalman equation
$$A_\mu^\nu \frac{dP^\mu}{d\tau} = F^\nu  = - B_{\mu\lambda}^\nu U^\mu P^\lambda$$
where $F^\nu$ is the exact gravitational force with
$$A_\mu^\nu = \left( 1 - \frac{1}{c^2} \psi_{\lambda\gamma} U^\lambda U^\gamma \right) \eta_\mu^\nu - \frac{2}{c^2} \psi_{\mu\gamma} U^\gamma U^\nu + \frac{2}{c^2} \psi_\mu^\nu$$
and
$$B_{\mu\lambda}^\nu = \frac{2}{c^2} \psi_{\mu,\lambda}^\nu - \frac{1}{c^2} \psi_{\mu\lambda}^{,\nu} - \frac{1}{c^2} \psi_{\mu\lambda,\gamma} U^\gamma U^\nu$$
Here $\psi_{\alpha\beta}$ is the gravitational field potential and the comma denotes the ordinary flat spacetime partial derivative.

A: As in Electrodynamics, the forces become retarded, the corresponding equations become complicated and include radiation too.

A: The expression that is actually used by JPL to calculate/approximate the relativistic effects under given promises comes from the "post-Newtonian expansion" at the 1PN-level and, including the classical Newtonian acceleration, it looks like:
$$\frac{d\bar{v}}{dt}=-\frac{GM}{r^2}\left(1-\frac{4GM}{rc^2}+\frac{v^2}{c^2}\right)\hat{r} +\frac{4GM}{r^2}\left(\hat{r}\cdot \hat{v}\right)\frac{v^2}{c^2}\hat{v}$$
So they are basically introducing one component that is "repulsive inverse cube gravity" and two velocity dependent terms. This expression is also availabe at the 3PN-level, see this post. Note that this is only an approximation that is able to reproduce the "anomalous perihelion shift" in the weak field limit. The extra repulsive inverse cube term causes very strange behaviour if you try to use it in the strong field limit. Here are a few simulations I made where the green circle denotes the Schwarzschild radius and the red circle denotes the radial distance to the "innermost stable circular orbit." It is easy to see the bouncing caused by the repulsive inverse cube term:

Note: This is the expression for the case of infinite mass ratio. If you cannot use the infinite mass ratio approximation, the expression would be more complicated I think.

A: Worse than electrodynamics, general relativity is non-linear, in the sense that the field from multiple sources is not just the sum of fields from each isolated source. Even the simple case you are asking about, which is the two-body problem in general relativity, has not been solved exactly.
An even simpler case is the limit $m_2 \to 0$. In that case only $m_1$ affects the geometry of spacetime, and $m_2$ follows a geodesic in that spacetime. This has been solved exactly. The linked article gives details.
[Addendum] To directly answer the original question for the limit $m_2 \to 0$:
Of course if $m_2=0$, then the force between the two masses is $0$. But the thing about classical gravity is that the acceleration due to gravity is independent of mass.  (This is the equivalence principle and is actually one of the starting points of the theory of general relativity.) So it still makes sense to ask what would be the acceleration of a negligible mass (aka, a test body) due to the gravity of another mass. The classical answer is $a_2 = \frac{Gm_1}{r^2}$.
In general relativity, the acceleration of a test body due to the gravity of a single spherical, homogenous, non-rotating mass is given exactly by the Schwarzschild solution, which link you can consult for details. The result of which is that
$$\ddot{r} = -\frac{Gm_1}{r^2} + r\dot{\theta}^2 - \frac{3Gm_1}{c^2}\dot{\theta}^2$$
$$\ddot{\theta} = -\frac{2}{r}\dot{r}\dot{\theta}$$
[CORRECTED AND SIMPLIFIED Jan 2]
where $r$ and $\theta$ are polar co-ordinates centred on the gravitating mass, the dots represent differentiation by the proper time of the test body.
So the first term is just the classical radial acceleration $-\frac{Gm_1}{r^2}$. The terms $r\dot{\theta}^2$ and $-\frac{2}{r}\dot{r}\dot{\theta}$ are the classical centrifugal and Coriolis acceleration for polar co-ordinates.
What's not classical is the extra term $\frac{3Gm_1}{c^2}\dot{\theta}^2$. Finally, there is the fact that differentiation is with respect to proper time of the test body. Different test bodies will experience time differently. They can be related by:
$$(1 - \frac{r_s}{r})\dot{t}^2 - \frac{\dot{r}^2}{(1 - \frac{r_s}{r}) c^2} - \frac{r^2\dot{\theta}^2}{c^2} = 1$$
The constant $r_s = \frac{2Gm_1}{c^2}$ is introduced for simplicity. It is called the Schwarzschild radius of the gravitating mass.
Here the co-ordinate $t$ is introduced as a reference time, so $\dot{t}$ is the rate of change of reference time with respect to proper time of the test body. For a distant ($r \to \infty$), stationary ($\dot{r}=0, \dot{\theta}=0$) test body, this becomes $\dot{t} = 1$, so the reference time can be interpreted as the time measured on a distant, stationary clock.
In the classical case of course every body experiences the same time, but it can also be compared to the special relativistic case, where the equation would be:
$$\dot{t}^2 - \frac{\dot{r}^2}{c^2} - \frac{r^2\dot{\theta}^2}{c^2} = 1$$
So what's new in general relativity is the factor $(1 - \frac{r_s}{r})$. To get some idea of scale, for the Earth, $\frac{r_s}{r}$ is about one and a half parts per billion on the surface of the Earth. (Note the Schwarzschild solution is only applicable outside the gravitating body.)
This is exact only for $m_2 \to 0$, but it remains a very good approximation as long as $m_2$ is much smaller than $m_1$, such as for a planet orbiting a star.

A: I think if we consider a much bigger mass then the force becomes relativistically:
$$ F=-\frac{GMm}{r^2}+\frac{4G^2M^2m}{r^3c^2}$$


text:
Q: attempting to script r commands to run I have files in two different directories that I would like to merge the same files.
for example:
in c:/data1, I have files like this:
teamA.Rdata, teamB.RData, teamC.RDate
in c:/data2 I have the same files:
teamA.Rdata, teamB.RData, teamC.RDate
The file names are the same but the content of the files are different. I like to write an r script to combile files with the same names. For example, I would like to merge teamA.RData file locate in C:/data1 and c:/data2 directories:
I have written this piece of code:
for (i in dir("c:/data1", pattern = "^team"))

     {

      print(i)

      for (r in dir("c:/data2", pattern= "^team"))

        {

             print(r)
             if(i==r) {
             print("yesssssssssssssssssssssss")
             }
         }
   }

I put this line of code to R console, I get a print out. However, when I tried to run this in via an rscript, I dont get anything even though I have print statements in the code. Is there something that I have to do in rscript to make this happen?

A: Do the paths exist? Do the regexes match? Try pattern=".*team" or pattern="*team".
> system('touch hello')
> system('touch helloo')
> system('touch hellooo')
> system('ls')
1  2  hello  helloo  hellooo
> list.files('.',pattern='hello*')
[1] "hello"   "helloo"  "hellooo"
> list.files('.',pattern='hello.*')
[1] "hello"   "helloo"  "hellooo"

You can read in the history how you can concatenate files.


text:
Q: Springboot increasing threads even if server.tomcat.max-threads=5 I have a springboot application right now that the threads keeps on increasing even if the server is idle. This causes the machine to crash over time. Causing very high memory and CPU usage.
I tried setting server.tomcat.max-threads=5 but I am very unlucky and the threads keeps on rising.
By the way, these are my components:
  - Rest Template
  - OK HTTP
  - Hikari CP
  - Springboot and Spring Framework (@RestController and @Service)
  - HttpInterceptor (Request and Outgoing)
  - Hibernate / JPA
I am also counting the threads using htop and the JNI I have created.
The JNI PID/TID can get htop's light-weight-process IDs. So this JNI can virtually map that LWPID and the java thread.
Any help will be much appreciated.
Thanks,
Artanis Zeratul

A: So I bet tomcat only has 5 threads, and some other technology you have in your server is creating those additional threads.  Now tomcat follows a naming scheme for its threads.  Typically those 5 threads would be named something like:
http-bio-8080-exec-1
http-bio-8080-exec-2
http-bio-8080-exec-3
...

You get the picture.  So if you list the names of the threads in your VM (ctrl-page-break on windows, kill -3 JAVA_PID on linux, jconsole - probably your best bet.  You should only see that thread naming pattern for 1-5.  All other threads would be owned by something else.  Tomcat does have extra threads beyond the exec threads, but they are fixed number (stop thread, main, etc).

A: My problem solved now.
These were the things I have observed and were the root causes of the problem.

Firstly, I have created Hikari Thread Pool and Local Entity Manager Factory Bean for every query I made which should only be done once in the application's lifetime or once for every datasource connection. This was the major cause of threads keeps spawning up. Creation of Thread Pool/LocalEntityManagerFactoryBean pertains to this code snippet:
HikariDataSource connectionPoolDatasource = new HikariDataSource(connectionPoolConfig);

localContainerEntityManagerFactoryBean.setDataSource(connectionPoolDatasource);
localContainerEntityManagerFactoryBean.setJpaProperties(jpaProperties);
localContainerEntityManagerFactoryBean.afterPropertiesSet();

Reference: https://groups.google.com/forum/#!topic/hikari-cp/IsVEn-D6oFA
 See Brett Wooldridge response to Jen-Ming Chung.

Lastly, I didn't call Connection.close() everytime I have made query or connection to the DB.
Which also leads to threads not being terminated or closed.
As well as leaving DB connections open.
Reference: Getting Database connection in pure JPA setup

Cheers!


text:
Q: Update Query issue in php This is my table 'tbl_size'
**Col Name**        **Data Type**
size_id            int(11)
pd_id              int(11)
size_name          varchar(20)
size_chart         int(6)
qty                text

Now I'm trying to update this table with following query
$query="update tbl_size set `qty`='10' where `size_id`=335";

When i run this query in mysql, it works fine but when same thing i tries to do from php then it is updating qty to '0' and not to '10'.
I'm not getting why this is happening. Please help me to solve this problem.
New Updated Code :
// $rowvo['od_qty']=10;

// $row_1['qty']=20;

$sql = "SELECT qty  FROM tbl_size WHERE size_id =".$rowvo['size_id'];

$result = dbQuery($sql);

$row_1    = dbFetchAssoc($result);

$pqty=$row_1['qty']-$rowvo['od_qty'];

echo "Total Quantity Available Before Diduction : ".$row_1['qty'];

echo "Sold Quantity : ".$rowvo['od_qty'];

echo "Remaining Quantity : $pqty";

$sql_qty="update tbl_size set `qty`=$pqty where `size_id`=".$rowvo['size_id'];

echo "$sql_qty
";

$result_qty=mysql_query($sql_qty) or die('Error : '.mysql_error());

echo "No of Rows Affected : ".mysql_affected_rows()."
".mysql_error(); // 1

New Code with PDO :
try {
$b=$a->prepare("update tbl_size set `qty`=:qty where `size_id`=:size");
$b->bindValue(":size",$size_id);
$b->bindValue(":qty",$pqty);
$b->execute();

 } catch(PDOException $ex) {
echo "An Error occured!"; //user friendly message

}

and var_dump($ex)=NULL

A: Check the structure of your table you have text type for qty. It's possible that it is not of type char or varchar (or that it is and has a default value set to '0'). To resolve this you can use phpmyadmin, SQLyog or other MySql admin programs.
change your query
$sql_qty="update tbl_size set `qty`=$pqty where `size_id`=".$rowvo['size_id'];

to
$sql_qty="update tbl_size set `qty`='$pqty' where `size_id`='".$rowvo['size_id']."'";

A: Your Code       ==> `qty`= $pqty

Changes to this ==> `qty`='$pqty'

A: try this:
$query="update tbl_size set qty=10 where size_id=335";


text:
Q: Using Omnipay for standard PayPal payments As you know, PayPal Express and Pro methods not available for all counties.
I'm wondering if there is any way for implement PayPal standard that available for Asian countries like UAE using Omnipay.


text:
Q: How to select text in an input after a change in Angular at the right time? I have an input box. When the text changes, I need to select the text. I understand that there are many events going on and I need to wait for them to finish. I put in a timeout and it works. However I don't want to rely on a constant time. Is there any way how to select the text when Angular is finished changing the text?
Example HTML:
<input type="text" value="{{txt}}">
<button ng-click="select()">Press</button>

Example JS:
angular.module('MyApp', []).controller('MyCtrl', function ($scope, $interval) {
    $scope.txt = "Hello World";
    $scope.select = function () {
        $scope.txt = "Bye World";
        // doesn't work, too early
        document.querySelector("input").setSelectionRange(0, 4);
        // works
        $interval(function () {
            document.querySelector("input").setSelectionRange(0, 4);
        }, 10, 1);
    }
});

Working example is JSFiddle.
EDIT: From the answers it looks like using timeouts (even with 0 delay) is a common practice, but the question remains whether this will guarantee that the selection happens after Angular finishes updating the text.

A: You can use $timeout with 0 delay for this purpose.
$timeout(function(){
    document.querySelector("input").setSelectionRange(0, 4);
});

Angular changes the DOM in next $digest cycle, it is extremely fast, but it won't be available as soon as you run $scope.x = ??. Normally we would use $timeout to "wait" in this case.

A: $timeout 0 delay is in fact good enough since angular's dirty checking (and $digest cycle) happens synchronously. (0 delay would only fire up when the current process is free).
If you really really want to guarantee it, here's how:
angular.module('MyApp', []).controller('MyCtrl', function ($scope, $timeout) {
    $scope.txt = "Hello World";
    $scope.select = function () {
        $timeout(function () {
            $scope.$apply(function () {
                $scope.txt = "Bye World";
            });
            document.querySelector("input").setSelectionRange(0, 4);
        });
    };
});

You have to use timeout to wrap the $apply, because the scope function would trigger a $digest and you cannot call $digest within a $digest cycle($apply calls $digest for you). $apply here guarantee the scope variable is updated, hence your setSelectionRange would only happen after the update.

A: If you do not want to use $timeout, you can fire event with ng-blur. A blur event fires when an element has lost focus.
Working fiddle
HTML:
    <div ng-controller="MyCtrl">
        <form>
            <input type="text" ng-blur="select()" value="{{txt}}">
            <button>Press</button>
        </form>
    </div>

Script:
angular.module('MyApp', []).controller('MyCtrl', function ($scope, $interval) {
    $scope.select = function () {
        document.querySelector("input").setSelectionRange(0, 4);
    }
});


text:
Q: How to set up a working VPN? I've tried to set up a VPN server on my copy of Ubuntu 10.10 with insuccess. Community material on the topic is little and poorly documented (clients only information, scenario-specific information, WIP pages, ...)
What I need in specific is tunnelling of traffic over HTTPS to go around a proxy server that only allows HTTP and HTTPS protocols.
What I did try is following this ubuntugeek.com guide. I've gone through each step (here are my config files), set up an account through DynDns.com, set up port forwarding and set up a VPN on my copy of Windows 7:

*

*Endpoint: redacted

*Username: badp (I also tried delta)

*Password: redacted
I've also turned on logging on the Windows 7 side of things and attempted to connect from an unfiltered location. From the logs, it seems like the connection is dropped right after authentication takes place.
Where did I go wrong?  Was there a guide on the Ubuntu official resources I could've tried instead?

A: Why not just use OpenVPN? It's very easy both on Windows and Linux.

A: Here's a straightforward guide: http://rootmanager.com/ubuntu-ipsec-l2tp-windows-domain-auth/setting-up-openswan-xl2tpd-with-native-windows-clients.html but it doesn't cover tunneling it over http/https
another solution is here: http://www.exiledmind.net/vpn-tunnel/ this maps EXACTLY to what you are trying to do.
I prefer openswan since openvpn is client number limited now
if the auth is succeeding but the tunnel isn't formed this usually means the two end-points can't agree on tunnel mode and/or crypto system.  another possibility is a routing problem where the near and far networks are on the same private subnet and your traffic gets dropped because it doesn't know to transit the vpn link.


text:
Q: How does bootstrapping work? So I'm trying to understand bootstrapping,
I watched the following video:
https://www.youtube.com/watch?v=gcPIyeqymOU&t=338s
And starting from 2:53 the speaker explains that through bootstrapping we can get a closer inference on the population mean by creating a sample distribution of random samples from our original sample
I tried to visualize this in python with the following code:

However, as you can see, the if I make a sampling distribution of my sample I get a distribution that's centered around the sample mean, not the population mean.
This actually makes sense to me, but because of this result I don't understand the purpose of bootstrapping. Could someone explain how bootstrapping works?
EDIT: I read the answer here: Explaining to laypeople why bootstrapping works
And it still doesn't make sense to me based on the way that i've visualized it. To me, it seems that I'm only getting information about the sample, not the population.


text:
Q: Field extension and faithfully flatness
There is given the ring $R := k[T_1, T_2, ..., T_n]/(f_1, ..., f_r)$ of finite type, a field extension $k \subset k'$ and $R' := R \otimes _k k' \cong k'[T_1, T_2, ..., T_n]/(f_1, ..., f_r)$. How can I prove that $R'$ is a faithfully flat $R$-module?

My ideas (flatness):
If $M, N$ are $R$-modules with an injection $\phi: M \to N$ I have to show that the induced module morphism $ \bar{\phi}: M \otimes_R R' \to N \otimes_R R'$ is injective, too.
According to the definition of $R'$ we have $M \otimes_R R' \cong M \otimes_R k'$ and for N vice versa. So have to show that that $ M \otimes_R k' \to N \otimes_R k'$ is injective or respectively that the functor $ - \otimes_R k'$ between $R$-modules is exact but I unsure that if it's true ...

A: Your mistake is that you say $- \otimes_R R' = - \otimes_R k'$, but actually we have $$- \otimes_R R' = - \otimes_k k'$$ and the latter is clearly a faithful exact functor since field extension are always faithfully flat.


text:
Q: Is it a good idea to only catch exceptions in production? I have inherited a codebase which contains code such as the following (note: example code is PHP):
try {
    // Do something which doesn't intentionally throw exceptions.
} catch (\Exception $e) {
    $this->log->log($e->getMessage());
    $this->product->setError($e->getMessage());
    return false;
}

So essentially, the code is catching the exception. Logging it, and the failing silently (apart from the log message).
This behaviour seems to make sense in production, but makes development much more difficult (as stack traces have to be looked up in log files, rather than being printed to the console). So I have come up with the following function:
private function tryCatch ($func) {

    // Bind closure, so that $this allows it to access class properties
    if (is_object($func) && ($func instanceof Closure)) {
        \Closure::bind($func, $this, "static");
    }

    if (\App::environment('test')) {
        return $func();
    } else {
        try {
            return $func();
        } catch (\Exception $e) {
            $this->log->log($e->getMessage());
            $this->product->setError($e->getMessage());

            return false;
        }
    }

}

which can then be used like so:
$this->tryCatch(function () {
    // Do something
});

This code special-cases the 'test' environment which it calls the passed in function without exception handling (so any exceptions remain unhandled). In every other environment (e.g. production), it wraps the passed in closure in a try-catch block in production behaves as the code originally behaved.
This solutions solves my problems, but it seems a bit hacky, and leaves me with aI have nagging feeling that it isn't a good idea.
My question: Is there any reason why I shouldn't do this? Or is there a better way of handling this situation?

A: Don't try to reinvent the wheel with regards to exceptions. There is one and only one scenario in which you should catch an exception:
Catch an exception if you have an alternative plan what to do with it.
An exception means that your code encountered an exceptional condition in which it cannot continue its work and has no choice but to throw in the towel. That's a perfectly good way to abandon a function/module/execution context and signal to the caller higher up what happened. That's exactly what exceptions do.
During development you want to see the exception in all its ugly glory to be able to debug. In production you do not want your users to see exceptions, but instead present them with a nice looking error screen and/or have all sorts of bells and whistles go off which notify the admin/developer/CTO/whoever.
That means, in production you only want one global error handler which responds appropriately if an unexpected, uncaught exception occurs. The exception should be thrown and (not) caught exactly as in development, you do not want two completely separate code paths. This global error handler could be set conditionally by some bootstrapping script simply with set_exception_handler; or probably even better, you configure your web server appropriately to serve useful error pages. Configuring the web server is the best possible way, since this is a system specific setting (production only) without any need to change anything about your code.
The only time you should actually write a try..catch is if there's a legitimate reason a subsystem might fail and you have a backup plan. E.g.:
try {
    $file = download_file_from_url($url);
    echo "Cool, got your file.";
} catch (HttpNotFound $e) {
    echo "Hey user, that file doesn't exist.";
} catch (HttpEmptyResponse $e) {
    echo "Hey user, that file seems empty.";
}
..

In this scenario a failed HTTP download is an expected outcome and can be handled well with exceptions, so this is a good use case. But don't reflexively try to catch them all even if they don't represent expected outcomes.


text:
Q: how to reset "alerting" state in Grafana I have set up a Grafana alert, that alerts when my values in a graph reaches a specific value.
And that value was reached a month ago and ever since then the state has been "ALERTING".
I obviously want to reset this state to "OK", since the incident happened a month ago and has been resolved.
Any idea how to do that?
I've taken some screenshots of the graph/panel and the settings for the alert, so you can see, what I've set it to.

The main goal is to get a alert everytime the values reach over 468.

A: Well it is obvious and I guess you just get better at Grafana when trying...
I've found out that you should simple go to the page "Alert Rules" and from there pause and then restart the alert.

When you re-enable it it will change status from "alerting" to "pending", the alert will then check after some time (check what time you've set it too) and if the query no longer calls the alert, it will change to "OK", if not - it will again send out a new alert.
Grafana should normally do this itself - but I've experienced that I've had to manually do this.
Should you not have this possibility - meaning that the query should not call the alert, but should show "OK" and it instead keeps showing "Alerting", then I couldn't find another way around than to delete the alert and set it up again. Not the best solution, but pausing and re-enabling didn't work and I haven't had any difficulties since.
If anyone have had the same experience and found a better solution, then please feel free to post it.
I can also see that this has been a bug/known error as stated here


text:
Q: QGIS Error while executing Python function in openProject() Macro: "QgsMapLayerRegistry is not defined" I have the following script that sets the a feature id automatically after a new feature is digitized.
I want the following function to be executed automatically when project is opened (and layers are loaded) so that users don't need to do anything.
import os

# Set layer by Name

layer=None
for lyr in QgsMapLayerRegistry.instance().mapLayers().values():
    if lyr.name() == "Pozos":
        layer = lyr
        break

# Define function to select added feature and add attribute to field "id"
def update(featureAdded):
    idx = layer.fieldNameIndex('id')
    max = layer.maximumValue(idx) +1
    layer.changeAttributeValue(featureAdded, idx, max)

# Connect "featureAdded" event to "select" function
layer.featureAdded.connect(update)

I tried adding the function inside the project's Macro section inside openProject() function:

But when the project is opened I get:

It looks like QgsMapLayerRegistry is not loaded when the function is triggered?

A: Within QGIS 3.0 and above updates took place within the API, QgsMapLayerRegistry has been removed and its functionality has been moved to QgsProject.
As a beginner, I found it confusing because they didn't make an update for the Developer Cookbook pdf version. This has also been answered in Is QgsMapLayerRegistry removed in QGIS3?

A: To fix the error:

NameError: global name 'QgsMapLayerRegistry' is not defined

Just add the following at the top of your script:
from qgis.core import QgsMapLayerRegistry

Tip:
What I do normally when I receive similar errors is to type the class into the Python Console. It will then provide you with a list of classes and libraries in which they belong to:

Or you can just type it in the console and press 'Enter':

In both cases, we can see that we need to call qgis.core in order to import the QgsMapLayerRegistry class.


text:
Q: Count SalesOrder Items more elegantly in SuiteTalk I'm working on creating the backend for a NetSuite-based application using SuiteTalk. I'm trying to count the total number of items in SalesOrders.
My issue is that, when performing a search operation to get all SalesOrders, the Record[] object returned loses precision when cast to a SalesOrder[] (using Array.ConvertAll(...) and manually). In my case, this means getting a Null Reference exception when trying to access the itemList field.
My eventual solution was as follows:
for (SearchResult searchResult = _service.search(salesOrderSearch); searchResult.pageIndex <= searchResult.totalPages; searchResult = _service.searchNext()) {

                if (searchResult.status.isSuccess) {

                    // Convert Record[] to SalesOrder[]. Note that direct conversion causes some fields to become Null
                    SalesOrder[] salesOrdersNull = Array.ConvertAll(searchResult.recordList, item => (SalesOrder)item);

                    // To avoid the null issue, send a get request for each order by its internalId
                    foreach (SalesOrder salesOrderNull in salesOrdersNull) {
                        SalesOrder salesOrder = getSalesOrder(salesOrderNull.internalId);

                        // Increment the count by the total number of items
                        count += salesOrder.itemList.item.Length;
                    }
                } else {
                    string errorCodes = Helpers.generateErrorString(searchResult.status.statusDetail);
                    throw new SuiteTalkServiceException("count Sales Order Lines. Failed with error code(s) " + errorCodes);
                }
            }

However this calls a get request for every single Sales Order, meaning it takes an age and is very inelegant. Is there a more elegant solution I'm missing? Has anyone else had a similar issue or am I being dense?
The class definition for Record is:
public abstract partial class Record {

        private string[] nullFieldListField;

        /// <remarks/>
        [System.Xml.Serialization.XmlArrayItemAttribute("name", IsNullable=false)]
        public string[] nullFieldList {
            get {
                return this.nullFieldListField;
            }
            set {
                this.nullFieldListField = value;
            }
        }
    }

The class definition for SalesOrder is several thousand lines of code, but the SchemaBrowser entry is fairly clear.

A: I have found an answer to my question here.
Essentially, to prevent the itemList field from becoming null, you have to set the searchPreferences.bodyFieldsOnly field to false. This now runs in 1/10th the time of my solution.


text:
Q: How to prove that functional ANOVA components are orthogonal? Given a multivariate real function $f(x_1, x_2, \ldots, x_d)$, let's define:
$$
L_j f= E_{x_j \sim X_j}f(\cdot, \cdot, \ldots, x_j, \ldots, \cdot) \quad (j \in S = \{ 1,2,\ldots, d\}) \\
L_u f = \left(\prod_{j \in u} L_j \right)f \quad (u \subseteq S)
$$
The functional component of $f$ acting only on the variables whose indices are in $u \subseteq S$ is defined as:
$$
f_u = L_{S \setminus u}f- \sum_{v \subset u}f_v
$$
How can we prove that $\boldsymbol{f_u}$ and $\boldsymbol{f_v}$ are orthogonal for $\boldsymbol{u \neq v}$? This comes up in many papers on functional ANOVA, but I couldn't prove it.
I've managed to prove these results:
$$
(\forall u \subseteq S)(\forall j \in u) L_j f_u = 0 \\
(\forall u \subseteq S)(\forall j \not\in u) L_j f_u = f_u \\
(\forall u \subseteq S, u \neq \emptyset)L_u f_u = 0 \\
f = \sum_{u \subseteq S} f_u \\
$$
The orthogonality of $f_u$ and $f_v$ in the case $u \neq v$ should flow from there. I've got a feeling that it's pretty obvious, but I'm stuck. Any help?

A: I think I got it.
For $u \neq v$, suppose w.l.o.g. that $w = v \setminus u \neq  \emptyset$. Then, we have:
$$
\langle f_u, f_v \rangle = L_S f_uf_v = L_{(S \setminus w) \cup w} f_uf_v = L_{S \setminus w} L_w f_u f_v
$$
Since $w \cap v = \emptyset$, $f_v$ is a constant w.r.t. $L_w$, so:
$$
\langle f_u, f_v \rangle = L_{S\setminus w} (f_v (L_w f_u)) = L_{S \setminus w} (f_v0) = L_{S \setminus w} 0 = 0$$


text:
Q: Override methods with "?" parameters in scala I am trying to extend the following java class in Scala
https://kafka.apache.org/082/javadoc/org/apache/kafka/common/serialization/Serializer.html#configure(java.util.Map, boolean)
So far the code I have written is
package com.abhi

import org.apache.kafka.common.serialization.Serializer

import scala.runtime.ObjectRef

class PersonSerializer extends Serializer[Person] {
  override def configure(configs: Map[String, ObjectRef], isKey: Boolean) : Unit = {

  }

  override def serialize(topic: String, p : Person) : Array[Byte] = {
    Array[Byte]()
  }
}

But this gives me compile time error method configure overrides nothing
I have tried searching but I am not able to figure out how to override the the configure method because of the "?" in the java definition

A: Notice that in the Serializer interface you have a java.util.Map, not scala.collection.Map.
Also you need need to define close.
Thus you should fix your code so that is like this:
class PersonSerializer extends Serializer[Person] {
  override def configure(configs: java.util.Map[String, _], isKey: Boolean) : Unit = {

  }

  override def serialize(topic: String, p : Person) : Array[Byte] = {
    Array[Byte]()
  }

  def close() {
    //do something
  }
}

Notice that it's not possible possible to define a more precise type to configs Map right parameter because it is ? in its java definition, thus we should accept java.util.Map whose values can be anything(_ type in scala).


text:
Q: Static method call not working in typescript The static access in my following example does not modify the html document as expected and I don't understand why. I am new to typescript. Compilations were successful.
File Main.ts:
import { BabylonApplication } from './BabylonApplication';
BabylonApplication.test(); //<-- this static access yields no result

File BabylonApplication.ts:
import * as BABYLON from 'babylonjs';

export class BabylonApplication {
    public static test() {
        document.getElementById("demo").innerHTML = "Hello World.";
    }
    //..some out commented stuff where i need the BABYLON import
}

The index.html:

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Babylon Template</title>

test

    <canvas id="renderCanvas"></canvas>

I noticed that when I write simple javascript classes with no export definition and import definition the static access is working.
For instance, the following plain javascript static method call is working
SimpleJavaScriptClass.ts:
class SimpleJavaScriptClass{

    static test() {
        document.getElementById("demo").innerHTML = "Hello World from javascript";
    }

}

Adjusted Main.ts:
//import { BabylonApplication } from './BabylonApplication';
//BabylonApplication.test();
SimpleJavaScriptClass.test();

So the simple javascript calls are fine. I have the suspicion that it has something to do with the import definition.
I used npm install --save babylonjs on the project (no, I don't confuse babylonjs with babel).
What am I doing wrong in typescript? Or what is wrong with the import?


text:
Q: why is my ubuntu 16.04 32 bit fresh install painfully slow? I have intel core i3 with 4GB ram and 2.4Ghz machine. Previously i was using Windows 10 to run Android Studio. But as its license experied i switched to Ubuntu 16.04 LTS 32 bit. But unfortunately its lagging very much for simple task only. I don't know what will happen if I start using Android Studio :(
Also do i need to upgrade to 64 bit? Or switch to any lower versions of Ubuntu like 14.04LTS? Or switch to Windows again.
Specs--

*

*Os : Ubuntu 16.04 LTS

*RAM : 3.8 GiB

*Processor : Intel Core i3-3110M CPU @ 2.4GHz x 4

*Graphics : Intel ivybridge Mobile x86/MMX/SSE2

*OS type : 32-bit

*Disk : 488.1 GB

Please let me know if anyone faced similar problem.
Also any further clarification needed to this question? For graphic card detail i got this information from my system

A: After using 64-bit os and Nvidia Proprietary driver my system is working great :) Thank you @dobey and @JonasCz for such a in depth information and help. And i am adding this line just to complete minimum word limit to answer on StackExchange.


text:
Q: What represents the HttpStatus of a ResponseEntity object in Spring MVC? in the Spring MVC Showcase example dowlodable from the STS dashboard
I have some doubt about the following situation:
In my view I have the following link:

            <a id="responseEntityStatus" class="textLink" href="<c:url value="/response/entity/status" />">ResponseEntity (custom status)

This link generate an HTTP Request towards the URL: "/response/entity/status"
This URL is handled by the following method of a @Controller class named ResponseController (which in turn is annotated with @RequestMapping(value="/response", method=RequestMethod.GET) )
The method thath handled the previus HTTP Request is:
@RequestMapping("/entity/status")
public ResponseEntity<String> responseEntityStatusCode() {
    return new ResponseEntity<String>("The String ResponseBody with custom status code (403 Forbidden)",
            HttpStatus.FORBIDDEN);
}

This method return a ResponseEntity object and, reading the documentation, I understand that returning a setted ResponseEntity objct is substantially the same thing as a return a @ResponseBody String object
So, in my particular case, I am returning a ResponseEntity object (that rappresent my HTTP Response) in wicht I have setted the

*

*HTTP RESPONSE Body field with the String The String ResponseBody with custom status code (403 Forbidden)

*I have not setted Headers fields

*I have setted the HTTP Status status code to HttpStatus.FORBIDDEN
Now, I have read that this HttpStatus is a field of ResponseEntity class but I have not understand what this object exactly rappresent...
So what rappresent the HttpStatus object? and what mean if it is setted to FORBIDDEN?

A: HttpStatus is not an object, it's a Enum that contains an enumeration of HTTP status code. The FORBIDDEN status represent the HTTP 403 status code