text:
Q: Is this the correct way to convert a UTC datetime string into localtime? Is this the correct way to convert a UTC string into local time allowing for daylight savings? It looks ok to me but you never know :)
import time
UTC_STRING = "2010-03-25 02:00:00"
stamp = time.mktime(time.strptime(UTC_STRING,"%Y-%m-%d %H:%M:%S"))
stamp -= time.timezone
now   = time.localtime()
if now[8] == 1:
    stamp += 60*60
elif now[8] == -1:
    stamp -= 60*60
print 'UTC: ', time.gmtime(stamp)
print 'Local: ', time.localtime(stamp)

--- Results from New Zealand (GMT+12 dst=1) ---
UTC:  (2010, 3, 25, 2, 0, 0, 3, 84, 0)
Local:  (2010, 3, 25, 15, 0, 0, 3, 84, 1)

A: timezone related calculations are not trivial and there are already good libraries available e.g. use pytz, using that you will be able to convert from any timezone to any other timezone with confidence. usage is as simple as this
>>> warsaw = pytz.timezone('Europe/Warsaw')
>>> loc_dt1 = warsaw.localize(datetime(1915, 8, 4, 23, 59, 59), is_dst=False)


text:
Q: What can change the include_path between php.ini and a PHP file I've inherited some code on a system that I didn't setup, and I'm running into a problem tracking down where the PHP include path is being set.
I have a php.ini file with the following include_path
 include_path = ".:/usr/local/lib/php"

I have a PHP file in the webroot named test.php with the following phpinfo call
 <?php
      phpinfo();

When I take a look at the the phpinfo call, the local values for the include_path is being overridden
                 Local Value                                        Master Value
 include_path    .;C:\Program Files\Apache Software Foundation\     .:/usr/local/lib/php
                 Apache2.2\pdc_forecasting\classes

Additionally, the php.ini files indicates no additional .ini files are being loaded
Configuration File (php.ini) Path           /usr/local/lib
Loaded Configuration File                   /usr/local/lib/php.ini
Scan this dir for additional .ini files     (none)
additional .ini files parsed                (none)

So, my question is, what else in a standard PHP system (include some PEAR libraries) could be overriding the include_path between php.ini and actual php code being interpreted/executed.

A: Outisde of the PHP ways
ini_set( 'include_path', 'new/path' );
// or
set_include_path( 'new/path' );

Which could be loaded in a PHP file via auto_prepend_file, an .htaccess file can do do it as well
phpvalue include_path new/path

A: There are several reasons why you are getting there weird results.

*

*include_path overridden somewhere in your php code. Check your code whether it contains set_include_path() call. With this function you can customise include path. If you want to retain current path just concatenate string . PATH_SEPARATOR . get_include_path()

*include_path overridden in .htaccess file. Check if there are any php_value or php_flag directives adding dodgy paths

*non-standard configuration file in php interpreter. It is very unlikely, however possible, that your php process has been started with custom php.ini file passed. Check your web server setup and/or php distribution to see what is the expected location of php.ini. Maybe you are looking at wrong one.

A: An .htaccess file or Apache's configuration (httpd.conf) could also be responsible.
Check for anything that looks like the following:
php_value include_path something

More information about that behavior here:

PHP: How to change configuration settings

The other option would be the use of ini_set() or set_include_path() somewhere, but considering that your test.php only contains phpinfo() (and assuming that test.php is called directly), I doubt that is your problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Eclipse Flash Builder 4: Syntax customization? Using Flash Builder 4 (FB), is there a way to customize syntax highlighting for variable scope (member, parameter, local)?
I've heard this is possible in other Eclipse plugins and wondering if it is possible with FB or if not is there an easy way to add it manually?
Cheers,
Jono

A: No.
Even in version 4.5, syntax highlighting is still the same primitive, useless crap.


text:
Q: Beeping hard disk in a multiple hard disk configuration I've been hearing a continuous beeping sound coming from my hard disk. The problem is, I have 2 hard disks and I'm not sure which one it was.
My primary hard disk is WD 250gb and the second one is a brand new Seagate 2tb (I'm still under the 1 week replacement warranty). Either of them started beeping after I reformatted my primary HDD. The beeping continues and I've had a boot failure 3 times. I've unplugged the second HDD and the beeping went away, and the boot was succesful this time. I've added back the second HDD and it's working perfectly.
Which HDD was most likely to have had that beeping sound?
Will my HDD last long after recovering from a stuck spindle?

A: If the beeping sound went away after you unplugged the 2nd HDD, then maybe the 2nd HDD was beeping...!
As the drive(s) no longer beep, it wouldn't be a bad idea to make sure they still work (If it was completely dead, it wouldn't beep).
To figure out which one was beeping, put a microphone (from you're phone or another computer's headset) next to each one and see which has the louder beep.


text:
Q: How to Add an Image with Image Name in Ionic 2 I want to Display the Users Image with users name at the center of the user Image,
so how i can achieve this with responsive.
enter image description here

A: You can try using existing CSS class text-center provided by Ionic.
https://ionicframework.com/docs/theming/css-utilities/

A: Here is sample of positioning text over image:
HTML:

Bottom Left

Top Left

Top Right

Bottom Right

Centered

AND CSS:
/* Container holding the image and the text */
.container {
    position: relative;
    text-align: center;
    color: white;
}

/* Bottom left text */
.bottom-left {
    position: absolute;
    bottom: 8px;
    left: 16px;
}

/* Top left text */
.top-left {
    position: absolute;
    top: 8px;
    left: 16px;
}

/* Top right text */
.top-right {
    position: absolute;
    top: 8px;
    right: 16px;
}

/* Bottom right text */
.bottom-right {
    position: absolute;
    bottom: 8px;
    right: 16px;
}

/* Centered text */
.centered {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}


text:
Q: CGImageCreateWithImageInRect() returning nil I'm trying to crop an image into a square, but once I actually try to do the crop by using CGImageCreateWithImageInRect(), this line crashes. I set breakpoints and made sure that the arguments passed into this function are not nil.
I'm fairly new to programming and Swift, but have searched around and haven't found any solution to my problem.
The failure reason:

fatal error: unexpectedly found nil while unwrapping an Optional value

func cropImageToSquare(imageData: NSData) -> NSData {

    let image = UIImage(data: imageData)
    let contextImage : UIImage = UIImage(CGImage: image!.CGImage!)
    let contextSize: CGSize = contextImage.size

    let imageDimension: CGFloat = contextSize.height
    let posY : CGFloat = (contextSize.height + (contextSize.width - contextSize.height)/2)
    let rect: CGRect = CGRectMake(0, posY, imageDimension, imageDimension)

    // error on line below: fatal error: unexpectedly found nil while unwrapping an Optional value
    let imageRef: CGImageRef = CGImageCreateWithImageInRect(contextImage.CGImage, rect)!
    let croppedImage : UIImage = UIImage(CGImage: imageRef, scale: 1.0, orientation: image!.imageOrientation)

    let croppedImageData = UIImageJPEGRepresentation(croppedImage, 1.0)

    return croppedImageData!

}

A: Your code uses a lot of force-unwrapping with !s. I would recommend avoiding this — the compiler is trying to help you write code that won't crash. Use optional chaining with ?, and if let / guard let, instead.
The ! on that particular line is hiding an issue where CGImageCreateWithImageInRect might return nil. The documentation explains that this happens when the rect is not correctly inside the image bounds. Your code works for images in portrait orientation, but not landscape.
Furthermore, there's a convenient function provided by AVFoundation which can automatically find the right rectangle for you to use, called AVMakeRectWithAspectRatioInsideRect. No need to do the calculations manually :-)
Here's what I would recommend:
import AVFoundation

extension UIImage
{
    func croppedToSquare() -> UIImage
    {
        guard let cgImage = self.CGImage else { return self }

        // Note: self.size depends on self.imageOrientation, so we use CGImageGetWidth/Height here.
        let boundingRect = CGRect(
            x: 0, y: 0,
            width: CGImageGetWidth(cgImage),
            height: CGImageGetHeight(cgImage))

        // Crop to square (1:1 aspect ratio) and round the resulting rectangle to integer coordinates.
        var cropRect = AVMakeRectWithAspectRatioInsideRect(CGSize(width: 1, height: 1), boundingRect)
        cropRect.origin.x = ceil(cropRect.origin.x)
        cropRect.origin.y = ceil(cropRect.origin.y)
        cropRect.size.width = floor(cropRect.size.width)
        cropRect.size.height = floor(cropRect.size.height)

        guard let croppedImage = CGImageCreateWithImageInRect(cgImage, cropRect) else {
            assertionFailure("cropRect \(cropRect) was not inside \(boundingRect)")
            return self
        }

        return UIImage(CGImage: croppedImage, scale: self.scale, orientation: self.imageOrientation)
    }
}

// then:
let croppedImage = myUIImage.croppedToSquare()


text:
Q: PHP not detecting radio inputs QUESTION
why does my php code not detect the radio inputs?
I have made a submit form with radio inputs as a part of the form. But the mail is sent blank on where the radio input value should be.
This has worked before but for some reason this isn't working...
You can see the code I have down below.
Any help would be awesome!!
PHP

    // Only process POST reqeusts.

  $name = $_POST["name"];
$phone = $_POST["phone"];
$date = $_POST["date"];
$email = $_POST["email"];
$tilaustyyppi = $_POST["tilaustyyppi"];
$autotyyppi = $_POST["autotyyppi"];
$message = $_POST["message"];

// Set the recipient email address.
$recipient = "jarkko@jarkkosalo.com";

// Set the email subject.
$subject = "Uusi tilaus $name";

// Build the email content.
$email_content = "Nimi: $name\n";
$email_content .= "Puhelin: $phone\n";
$email_content .= "Sposti: $email\n";
$email_content .= "Päivämäärä: $date\n\n";
$email_content .= "Tilaustyyppi: $tilaustyyppi\n";
$email_content .= "Autotyyppi: $autotyyppi\n\n";
$email_content .= "Viesti:\n$message\n";

// Build the email headers.
$email_headers = "Toimittanut: $name <$email>";

// Send the email.
mail($recipient, $subject, $email_content, $email_headers)

?>

HTML

Tilaustyyppi(Vaaditaan)

<input
    type="radio"
    name="tilaustyyppi"
    id="Niin pian kuin mahdollista"
    value="Niin pian kuin mahdollista"
    required=""
    aria-required="true"
/>

    Niin pian kuin mahdollista

<input
    type="radio"
    name="tilaustyyppi"
    id="Ennakkotilaus"
    value="Ennakkotilaus"
    required=""
    aria-required="true"
/>
Ennakkotilaus

Autotyyppi

<input
    type="radio"
    name="autotyyppi"
    id="Henkilöauto"
    value="Henkilöauto"
/>
 Henkilöauto

<input
    type="radio"
    name="autotyyppi"
    id="Tilataksi-6"
    value="Tilataksi 6:lle"
/>
 Tilataksi 6:lle

<input
    type="radio"
    name="autotyyppi"
    id="Tilataksi-8"
    value="Tilataksi 8:lle"
/>
 Tilataksi 8:lle


text:
Q: Configure VPN Gateway on Ubuntu VM First of all, my understanding on the subject is very limited. Im trying to use an Ubuntu VM as a VPN Gateway for my other devices on the same network. The VPN uses the Cisco Anyconnect VPN Client.
The network configuration is as follows:
A TP-Link router that is connected to the "internet", works as the default gateway with the IP address 192.168.0.1. The VM should now work as the default gateway for the other devices with the IP 192.168.0.104.
When the client establishes the connections, the iptables on the VM look like this:
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-N ciscovpn
-N ciscovpnfinal
-N ciscovpnfw
-A INPUT -j ciscovpn
-A INPUT -j ciscovpnfw
-A INPUT -j ciscovpnfinal
-A FORWARD -j ciscovpn
-A FORWARD -j ciscovpnfw
-A FORWARD -j ciscovpnfinal
-A OUTPUT -j ciscovpn
-A OUTPUT -j ciscovpnfw
-A OUTPUT -j ciscovpnfinal
-A ciscovpn -m state --state RELATED,ESTABLISHED -j ACCEPT
-A ciscovpn -o lo+ -j ACCEPT
-A ciscovpn -i lo+ -j ACCEPT
-A ciscovpn -p udp -m udp --sport 68 --dport 67 -j ACCEPT
-A ciscovpn -p udp -m udp --sport 67 --dport 68 -j ACCEPT
-A ciscovpn -p udp -m udp --sport 546 --dport 547 -j ACCEPT
-A ciscovpn -p udp -m udp --sport 547 --dport 546 -j ACCEPT
-A ciscovpn -s 192.168.0.104/32 -d 193.175.213.80/32 -o enp0s3 -p tcp
-m tcp --dport 443 -j ACCEPT
-A ciscovpn -s 193.175.213.80/32 -d 192.168.0.104/32 -i enp0s3 -p tcp
-m tcp --sport 443 -j ACCEPT
-A ciscovpn -s 192.168.0.104/32 -d 193.175.213.80/32 -o enp0s3 -p udp
-m udp --dport 443 -j ACCEPT
-A ciscovpn -s 193.175.213.80/32 -d 192.168.0.104/32 -i enp0s3 -p udp
-m udp --sport 443 -j ACCEPT
-A ciscovpn -i cscotun0 -j RETURN
-A ciscovpn -s 10.60.38.146/32 -o cscotun0 -j RETURN
-A ciscovpn -j DROP
-A ciscovpnfinal -j ACCEPT

The VM has the interface enp0s3 that has access to the LAN network. The interface cscotun0 is the interface created by the VPN client to access the internet. To create the gateway I tried following commands taken from this tutorial:
sudo sh -c "echo 1 > /proc/sys/net/ipv4/ip_forward"
sudo iptables -A FORWARD -o cscotun0 -i enp0s3 -s 192.168.0.0/24 -m conntrack --ctstate NEW -j ACCEPT
sudo iptables -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A POSTROUTING -t nat -j MASQUERADE

However, the VM is still unreachable by the other devices in my network 192.168.0.0/24. Before establishing a connection with the VPN client I can send ping commands from the host machine to the VM. After the connection establishes, the VM becomes unreachable.
I fail to deeply understand those rules that are created by the VPN client.


text:
Q: program is stuck on taskbar while shutting down windows I have built a program with C# and the program keeps running on system tray near the windows clock. When I try to shut down windows, the program is still running and shutting down windows get stuck.
This is not a program with Windows 7.So my question here is how to add 'something magic' to allow windows to shut down?

A: In your form closing event you have to catch windows closing message.FormClosingEventArgs has a property named CloseReason. An example is shown below
    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (e.CloseReason == CloseReason.WindowsShutDown)
        {
            e.Cancel = false;// or Application.Exit();
        }
    }


text:
Q: .so file not found while importing ruby c extension. (on windows) I have googled a lot and tried many answers but I was not able to find the solution for my issue.
I was trying to install the ruby-ibmdb gem and when I require it, I got an error that .so file is not found but that file was there in that location.
Why ruby is lying to me?
I have placed the .so file in ruby/bin and /lib and many places but it is working.
I have installed devkit and built the .so file my self(Issue maybe because of diff build versions) and
Installed the extension. No issues while installing the gem. But when I require it in the sample program it says .so file cannot be found. (BUt that file is present in the same location)
Traceback (most recent call last):
        2: from connect.rb:2:in `<main>'
        1: from C:/Ruby26/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
C:/Ruby26/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- ibm_db (LoadError)
        9: from connect.rb:2:in `<main>'
        8: from C:/Ruby26/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:34:in `require'
        7: from C:/Ruby26/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:130:in `rescue in require'
        6: from C:/Ruby26/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:130:in `require'
        5: from C:/Ruby26/lib/ruby/gems/2.6.0/gems/ibm_db-4.0.0-x86-mingw32/lib/ibm_db.rb:21:in `<top (required)>'
        4: from C:/Ruby26/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
        3: from C:/Ruby26/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
        2: from C:/Ruby26/lib/ruby/gems/2.6.0/gems/ibm_db-4.0.0-x86-mingw32/lib/mswin32/ibm_db.rb:90:in `<top (required)>'
        1: from C:/Ruby26/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
C:/Ruby26/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require': 126: The specified module could not be found.   - C:/Ruby26/lib/ruby/gems/2.6.0/gems/ibm_db-4.0.0-x86-mingw32/lib/mswin32/rb2x/i386/ibm_db.so (LoadError)

can anyone help me with this?
Thanks,
Akhil


text:
Q: Backbone.js: View won't render when using RESTful API I'm learning Backbone.js. I can find a thousand and one Backbone.js tutorials, but none of them seem to cover getting data from a RESTful API. None of the other solutions I've found seem to fit my specific problem.
Summary
The following code works when models (containing static data) are created and added to the collection, but when I use a test RESTful service, the view won't render, but I can see the response in the console.
I'm sure I'm missing something simple, but can't put my finger on what it is.
Here's my fiddle: https://jsfiddle.net/Currell/xntpejwh/
Code snippets are below if you'd prefer to view them here.
Test RESTful API: https://jsonplaceholder.typicode.com/
HTML:

JS:
var Post = Backbone.Model.extend();

var Posts = Backbone.Collection.extend({

    model: Post,

    url: 'https://jsonplaceholder.typicode.com/posts',

    initialize: function(){
        this.fetch({
            success: this.fetchSuccess,
            error: this.fetchError
        });
    },

    fetchSuccess: function (collection, response) {
        console.log('Fetch response: ', response);
    },

    fetchError: function (collection, response) {
        throw new Error("Books fetch error");
    }
});

var PostView = Backbone.View.extend({

    tagName: 'li',

    render: function() {
        this.$el.html(this.model.get('title'));

        return this;
    }

});

var PostsView = Backbone.View.extend({

    render: function() {

        var _this = this;

        this.collection.each(function(post) {

            // Put the current post in the child view
            var _postView = new PostView({ model: post });

            // Render the post and append it to the DOM element of the postsView.
            _this.$el.append(_postView.render().$el);
        });
    }

});

var posts = new Posts();

var postsView = new PostsView({ el: '#js-spa-container', collection: posts });

postsView.render();

A: When you are working with REST API, you need a mechanism to wait for the request to succeed before doing stuff.
Here's a simple fix: https://jsfiddle.net/wnxhq98p/
posts.fetch({
  success: postsView.render.bind(postsView),
  error: this.fetchError
});

A common pattern is to fetch the collection inside the View's initialize and on success call it's render.
Or create collection, setup collection event listeners inside view's initialize which will render the view appropriately, and then fetch the collection inside a Backbone router, but for this to work collection fetch must not happen instantly on initialize in order to give other components chance to setup events listening to collection


text:
Q: Python data science: How to select three houses in dataset with budget constraint, optimizing for highest risidual between predicted and actual price I have gotten the assignment to analyze a dataset of 1.000+ houses, build a multiple regression model to predict prices and then select the three houses which are the cheapest compared to the predicted price. Other than selecting specifically three houses, there is also the constraint of a "budget" of 7.000.000 total for purchasing the three houses.
I have gotten so far as to develop the regression model as well as calculate the predicted prices and the risiduals and added them to the original dataset. I am however completely stumped as to how to write a code to select the three houses, given the budget restraint and optimizing for highest combined risidual.
Here is my code so far:
### modules
import pandas as pd
import statsmodels.api as sm

### Data import
df = pd.DataFrame({"Zip Code" : [94127, 94110, 94112, 94114],
                   "Days listed" : [38, 40, 40, 40],
                   "Price" : [633000, 1100000, 440000, 1345000],
                   "Bedrooms" : [0, 3, 0, 0],
                   "Loft" : [1, 0, 1, 1],
                   "Square feet" : [1124, 2396, 625, 3384],
                   "Lotsize" : [2500, 1750, 2495, 2474],
                   "Year" : [1924, 1900, 1923, 1907]})

### Creating LM
y = df["Price"] # dependent variable
x = df[["Zip Code", "Days listed", "Bedrooms", "Loft", "Square feet", "Lotsize", "Year"]]

x = sm.add_constant(x) # adds a constant
lm = sm.OLS(y,x).fit() # fitting the model

# predict house prices
prices = sm.add_constant(x)

### Summary
#print(lm.summary())

### Adding predicted values and risidual values to df
df["predicted"] = pd.DataFrame(lm.predict(prices)) # predicted values
df["risidual"] = df["Price"] - df["predicted"] # risidual values

If anyone has an idea, could you explain to me the steps and give a code example?
Thank you very much!

A: With the clarification that you are looking for the best combination your problem is more complicated ;)
I have tried a "brute-force" approach but at least my laptop takes forever with the full dataset. Find below my thoughts:
Obviously we have to calculate the combinations of many houses, therefore my first approach was to reduce the dataset as far as possible.

*

*If Price+2*min(Price)>budget there will be no combination with two houses that is smaller

*If risidual is negative we will not consider the house during optimization

In pandas this will look as this:
budget=7000000

df=df[df['Price']<(budget-2*df['Price'].min())].copy()
df=df[df['risidual']>0].copy()

This reduces the objects from 1395 to 550.
Unfortunatly, 550 ID are still many combinations (27578100) as calculated with itertools:
import itertools
idx=[a for a in itertools.combinations(df.index,3)]

You can evaluate these combinations by
result={comb: df.loc[[*comb], 'risidual'].sum() for comb in idx[10000:] if df.loc[[*comb], 'Price'].sum() < budget}

Note: I have limited the evaluation to the first 10000 values due to the calculation duration.
print("Combination: {}\nPrice: {}\nCost: {}".format(max(result),df.loc[[*max(result)], 'Price'].sum(),result[max(result)]  ))

Maybe it is advisable to calculate the combination of just two object first to further reduce the possible combinations. I think you should have a look at the Knapsack problem

I think you are almost there. Given that df["risidual"] has the difference between predicted and real price you have to select the subset that fits your limit e.g.
df_budget=df[df['price']<=budget].copy()

using pandas nlargest() you could retrieve the three biggest differences
df_budget.nlargest(3, 'risidual')

Note: Code was not tested due to missing sample data


text:
Q: How can I get values from jQuery dialog box which has 2 text boxes? Can I store them in a JavaScript variable? I have tried jQuery, but I am not able to get values from that dialog box.
Is there any way that I could store those values in a JavaScript variable (i.e., coming from jQuery dialog).

    What percentage would you like to refund?

    <input type="text" id="per" name="per" > %

    Reason: <input type="text" id="reason" name="reason" >

<input type="submit" id="proceed" name="proceed" value="PROCEED" style='width:60px;height:30px;background-color:#0066CC;color:#FFFAF0; -webkit-border-radius: 9px'>

Or is there any other method in JavaScript?

A: $(document).ready(function(){

    $("#proceed").click(function(){

    //using JQuery
    var perValue = $("#per").val();
    var reasonValue = $("#reason").val();
    console.log(reasonValue);
    console.log(perValue);
    });
});

//using javascript
document.getElementById('proceed').onclick = Onclick;
function Onclick(){
    var reasonValue = document.getElementById("reason").value;
    var perValue = document.getElementById("per").value;
    console.log(reasonValue);
    console.log(perValue);
}

I have included Jquery and normal javascript based on the onlick function of the button.  You can test it out on this: JsFiddle.  You can check you console to see the output of the var values.

A: Is this what you're looking for?
var something = document.getElementById("yourIDhere").value;


text:
Q: How should I design the method signature for the following scenario If you have a method where the input parameter might be the output.
Let's say that we have a save method that generates an autogenerated id that the client might be interested to use after the call to save().
Person

*

*id (autogenerated)

*name

*... (other fields)

Should you design the method signature like this:
1.
public void save(Person person);

The client call:
personService.save(person);
System.out.println(person.getId());

2.
public Person save(Person person);

The client call:
person = personService.save(person);
System.out.println(person.getId());

We know that in a method call that receives an object the reference to that object is passed so any changes made to the object will be perceived by others as long as they have the same reference. But in the case of remote calls serialization/deserialization occurs so my object reference is a different reference from the remote service object. So even though changes are made there the client won't notice the difference.
At this time I know that the method is not going to be a remote call so I could design it using the first signature. But what if in the future this changes and needs to be called as a remote call.
So my question is:
Should I design my API thinking that the API might be called in the future as a remote call and don't use the object parameter as a way to return a value to the client (2) or should I design my API according to my actual situation which the sevice is not remote (1)?
Thank you

A: Why not do both? Use the second signature, modify person locally, and for the time being, just return a reference to that same person. This way, changing it in the future for whatever needs arise won't change the API, and current users can still use your first approach.
That being said, in general, I am uncomfortable with methods that change their parameters unless that is their sole purpose and they are named and documented to indicate this. From the standpoint of "what is the method doing, and what new information do I get from it," I would probably opt for a signature like:
public ID save(Person);

A: It's OK to do both; have save() return the new ID and have a getId() method. Returning a value from a "setter" (a method that changes state) has lots of precedents - the java Collections API does it all the time, eg Map.remove(Object) returns a boolean.
Fluent Interface
There's another pattern you might want to consider, the Fluent Interface pattern. With a fluent API, you return the object (ie this) from every method you would otherwise return void. This lets the caller "chain up" method calls. With a fluent interface, your code would look like this:
public Person save() {
    // do your save stuff
    return this;
}

If you want the ID after a save, you'd code this:
save().getId();

Simple! This pattern has been used in lots of existing java code too, notably hibernate as in this java fluent code example
I would recommend using fluent, if nothing else to get the practice using it

A: I would recommend using the first approach since objects are seldom used in isolation. The Person object is usually referenced by other entities such as Employee. If you create a new instance, you're invalidating the whole object graph and believe me, you don't want to mess around with deep copying.
As for the possibility of future RPC's, whatever you'll be using to accomplish this, it will most likely be able to update the ID field after the operation commits.
@CPerkins - Objects are passed by "reference value" to be absolutely correct ;)


text:
Q: how to call a PHP function with HTML button click? I am a beginner with HTML and PHP and i am having problems with my code. all I need to do is to call a particular function on the button click in html. both the fuction and html are on same page. whenever i run this this doesn't generate the required output.
I shall be very thankful for help. please help as soon as possiblemyfirstpage.php

A: Like this?
<?php
  if (isset($_POST['submit'])) {
    someFunction();
  }
  function someFunction() {
    echo 'HI';
  }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <form action="" method="POST">
      <input type="submit" name="submit">
    </form>
</body>
</html>

Although quite weird, this will work, you can use $_GET if you want

A: Try these code:

function validateForm() {
      var x = document.forms["myForm"]["fname"].value;
      if (x == "") {
          alert("Name must be filled out");
          return false;
      }else{
       alert("Your name has been successfully submitted!!");
          return true;
      }
  }
<form name="myForm" action="/action_page_post.php" onsubmit="return validateForm()" method="post">
  Name: <input type="text" name="fname">
  <input type="submit" value="Submit">
 </form>

A: You are communicating with two languages:
HTML which is client-side language
PHP which is server-side language
You can't run PHP without communicating with server.
So to achieve that you need to write ajax function in javascript to make
$('button').click(function() {
    $.ajax({
        type: "POST",
        url: "sum.php",
        data: { input: "your values here" },
        function (response) {
            alert('sum performed sucessfully');
       }
    })
});

And your sum function in sum.php file


text:
Q: NPE using QBOVendorService I am trying to query vendors using the QBOVendorService but having no luck.
I am creating the service as follows:
       QBOVendorService vService = QBServiceFactory.getService(context, QBOVendorService.class);

where the context is a valid PlatformSessionContext. I know the platform session context is good since I can get information about the user with it. When I try
           vService.addVendor(context, vendor);

I end up with a NPE like my vService is null. Shouldn't I get an error initializing the QBOVendorService if it fails? Is there a good place to find more examples for using this since the intuit developer forums have been shut down?

A: I'm sharing a sample code snippet. Replace your OAuth tokens and relamId. It should work fine.
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import com.intuit.ds.qb.QBIdType;
import com.intuit.ds.qb.QBVendor;
import com.intuit.ds.qb.QBVendorQuery;
import com.intuit.ds.qb.QBVendorService;
import com.intuit.ds.qb.QBInvalidContextException;
import com.intuit.ds.qb.QBObjectFactory;
import com.intuit.ds.qb.QBServiceFactory;
import com.intuit.ds.qb.impl.QBRecordCountImpl;
import com.intuit.ds.qb.qbd.QBDRecordCountService;
import com.intuit.ds.qb.qbd.QBDServiceFactory;
import com.intuit.platform.client.PlatformSessionContext;
import com.intuit.platform.client.PlatformServiceType;
import com.intuit.platform.client.security.OAuthCredentials;
import com.intuit.ds.qb.QBSyncStatusRequest;
import com.intuit.ds.qb.QBSyncStatusRequestService;
import com.intuit.ds.qb.QBSyncStatusResponse;
import com.intuit.sb.cdm.NgIdSet;
import com.intuit.sb.cdm.ObjectName;
import org.slf4j.Logger;

// QBD API Docs - https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0500_quickbooks_windows/0600_object_reference/vendor
// QBO API Docs - https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0400_quickbooks_online/vendor
// JavaDocs     - http://developer-static.intuit.com/SDKDocs/QBV2Doc/ipp-java-devkit-2.0.10-SNAPSHOT-javadoc/

public class CodegenStubVendorall {
    final PlatformSessionContext context;

    public CodegenStubVendorall(PlatformSessionContext context) {
        this.context = context;
    }

    public void testAdd() {
        final List<QBVendor> entityList = new ArrayList<QBVendor>();
        try {
            QBVendorService service = QBServiceFactory.getService(context, QBVendorService.class);

            //Your Code
            //Use Vendor POJO for creating Vendor

            }
        } catch (QBInvalidContextException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        PlatformSessionContext context = getPlatformContext();
        CodegenStubVendorall testObj = new CodegenStubVendorall(context);
        testObj.testAdd();
    }

    public static PlatformSessionContext getPlatformContext() {

        String accesstoken = "rplce_your_application_token";
        String accessstokensecret = "rplce_your_application_token";
        String appToken = "rplce_your_application_token";
        String oauth_consumer_key = "rplce_your_application_token";
        String oauth_consumer_secret = "rplce_your_application_token";
        String realmID = "123456";
        String dataSource = "QBO";

        PlatformServiceType serviceType;
        if (dataSource.equalsIgnoreCase("QBO")) {
            serviceType = PlatformServiceType.QBO;
        } else {
            serviceType = PlatformServiceType.QBD;
        }

        final OAuthCredentials oauthcredentials = new OAuthCredentials(
                oauth_consumer_key, oauth_consumer_secret, accesstoken,
                accessstokensecret);

        final PlatformSessionContext context = new PlatformSessionContext(
                oauthcredentials, appToken, serviceType, realmID);

        return context;
    }
}

You can try to use ApiExplorer tool to verify your OAuth tokens and to check the create Vendor API endpoint.
Link - https://developer.intuit.com/apiexplorer?apiname=V2QBO
Please let me know how it goes.
Thanks


text:
Q: Amazon AppStore for Android Api? Does anyone know if Amazon has an open API for their Android AppStore?

A: Full disclosure: My team builds the Amazon Appstore SDK. Even though I work for A2Z, any opinions stated are my own, not my employer's.

As of the time of this answer, Amazon has a private beta for the In-App Purchase API. If you want access to the API, please fill out the form at:
http://developer.amazon.com/
You have to create an account to access the request form.

A: The current offerings for Developers that want to integrate Amazon into Applications can be found here. I have not seen a API for the Android App, or any other mobile App for that matter. Which would lead me to believe that they dont provide an API for that. I would suggest that you use the Web Service API, that may be able to work for you depending on what you are trying to do.


text:
Q: c++ - caching objects I have a std::vector<Character*> that will contain several different derived classes of Character, which i will just call Enemy1, Enemy2, and Player for the purpose of this question. I've seen other cases where someone has an array such as Character characters[30] but as I need polymorphism I don't think that will work for me (I could be wrong).
Essentially my question is of implementation, how can i set up/cache multiple characters for reuse in this way? I was looking at this (http://gameprogrammingpatterns.com/object-pool.html), and i'm not sure if vectors can work in the same way. If one of the objects in the vector has been instantiated with new Enemy1() for example, can I later override it and set it to new Enemy2()? Should I have separate vectors/arrays for each enemy type?

A: Accessing your characters from an std::vector<Character*> is possible. However to create data pools for your many possible character types you need separate vectors, usually*.
Check out this Related question I asked recently. I got this article reference you might find useful.
*note: I believe that, with some tricks, it is possible to store various types in a single vector, as long as they all have the same size in memory.


text:
Q: Make a triangle shape in C++ I am trying to print out the shape of a triangle but I am kinda lost...
this is what I have so far:
#include <iostream>
using namespace std;

int main()
{
    int i, k, n;

    cout << "Please enter number of rows you want to see: \n";
    cin >> n;
    for (k = 1; k <= n; k++)
    {
        for (i = 1; i <= k; i++)
            cout << '*';
        cout << endl;
    }

    getchar();
    getchar();
    return 0;
}

A: This code works fine for a right angled triangle -
*
**
***

But I guess you want a triangle like this -
  *
 ***
*****

Try this -
#include <iostream>
using namespace std;
int main()
{
    int i, j, k, n;
    cout << "Please enter number of rows you want to see: \n";
    cin >> n;
    for (k = 1; k <= n; k++)
    {
       for(j = 1; j <= n-k; j++)
            cout << ' ';
       for (i = 1; i <= 2*k-1; i++)
            cout << '*';
       cout << endl;
    }
    return 0;
}

I think the code is pretty straightforward to understand. The first inner for loop is to print the spaces and the second inner for loop is to print the *

A: This does print the shape of a triangle. For example, when you put in 5, the program outputs
*
**
***
****
*****

If your computer isn't printing this output, it's not a problem with your code.


text:
Q: How can resolve problem of Key in FlatList React native It my first experience with React,
I have this problem  in my program. Will you help me please ?
I use TMDB API in my application.
index.js:1 Warning: Encountered two children with the same key, `.$106242`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.
        in div (created by View)
        in View (created by ScrollView)
        in div (created by View)
        in View (created by ForwardRef)
        in ForwardRef (created by ScrollView)
        in ScrollView (created by VirtualizedList)
        in VirtualizedList (created by FlatList)
        in FlatList (at Search.js:71)
        in div (created by View)
        in View (at Search.js:65)
        in Search (at App.js:8)
        in App (created by ExpoRootComponent)
        in ExpoRootComponent (created by RootComponent)
        in RootComponent
        in div (created by View)
        in View (created by AppContainer)
        in div (created by View)
        in View (created by AppContainer)
        in AppContainer

<FlatList
  data={this.state.films}
  keyExtractor={(item, index) => item.id.toString()}
  renderItem={({ item }) => <Text> <FilmItem film={item} /> </Text>}
  onEndReachedThreshold={0.5}
  onEndReachedThreshold={0.5}
  onEndReached={() => {
    if (this.page < this.totalPages) { // On vérifie qu'on n'a pas atteint la fin de la pagination (totalPages) avant de charger plus d'éléments
      this._loadFilms()
    }
  }}
/>

Any proposition

A: Change you flatlist code to this,
<FlatList
    data = {this.state.films}
    keyExtractor = {(item, index) => index+"_"+item.id.toString() }
    renderItem={({item}) => <Text> <FilmItem film={item} /> </Text>}
    onEndReachedThreshold={0.5}
    onEndReachedThreshold={0.5}
    onEndReached={() => {
        if (this.page < this.totalPages) { // On vérifie qu'on n'a pas atteint la fin de la pagination (totalPages) avant de charger plus d'éléments
            this._loadFilms()
        }
    }}
/>

A:
you can use index or combination of index and any property of films for keyExtractor. In below example I have used index and added comment on the same line which can also be used in place of index.

<FlatList
    data = {this.state.films}
    keyExtractor = {(item, index) => index } // `${item.id.toString()}-${index}`
    renderItem={({item}) => <Text> <FilmItem film={item} /> </Text>}
    onEndReachedThreshold={0.5}
    onEndReachedThreshold={0.5}
    onEndReached={() => {
        if (this.page < this.totalPages) { // On vérifie qu'on n'a pas atteint la fin de la pagination (totalPages) avant de charger plus d'éléments
            this._loadFilms()
        }
    }}
/>


text:
Q: How to change the the number of digits of the mantissa using offset notation in matplotlib colorbar I have a contour plot in matplotlib using a colorbar which is created by
from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(axe) #adjust colorbar to fig height
cax = divider.append_axes("right", size=size, pad=pad)
cbar = f.colorbar(cf,cax=cax)
cbar.ax.yaxis.set_offset_position('left')
cbar.ax.tick_params(labelsize=17)#28
t = cbar.ax.yaxis.get_offset_text()
t.set_size(15)

How can I change the colorbar ticklabels (mantissa of exponent) showing up with only 2 digits after the '.' instead of 3 (keeping the off set notation)? Is there a possibility or do I have to set the ticks manually? Thanks
I have tried to use the str formatter
cbar.ax.yaxis.set_major_formatter(FormatStrFormatter('%.2g'))

so far but this doesn't give me the desired result.

A: The problem is that while the FormatStrFormatter allows to set the format precisely, it is not capable of handling offsets like the 1e-7 in the case from the question.
On the other hand the default ScalarFormatter automatically selects its own format, without letting the user change it. While this is mostly desireable, in this case, we want to specify the format ourself.
A solution is to subclass the ScalarFormatter and reimplement its ._set_format() method, similar to this answer.
Note that you would want "%.2f" instead of "%.2g" to always show 2 digits after the decimal point.
import numpy as np; np.random.seed(0)
import matplotlib.pyplot as plt
import matplotlib.ticker

class FormatScalarFormatter(matplotlib.ticker.ScalarFormatter):
    def __init__(self, fformat="%1.1f", offset=True, mathText=True):
        self.fformat = fformat
        matplotlib.ticker.ScalarFormatter.__init__(self,useOffset=offset,
                                                        useMathText=mathText)
    def _set_format(self, vmin, vmax):
        self.format = self.fformat
        if self._useMathText:
            self.format = '$%s$' % matplotlib.ticker._mathdefault(self.format)

z = (np.random.random((10,10))*0.35+0.735)*1.e-7

fig, ax = plt.subplots()
plot = ax.contourf(z, levels=np.linspace(0.735e-7,1.145e-7,10))

fmt = FormatScalarFormatter("%.2f")

cbar = fig.colorbar(plot,format=fmt)

plt.show()

A: Sorry for getting in the loop so late. If you still are looking for a solution, an easier way is as follows.
    import matplotlib.ticker as tick
    cbar.ax.yaxis.set_major_formatter(tick.FormatStrFormatter('%.2f'))

Note: it's '%.2f' instead of '%.2g'.


text:
Q: python 'import' package works in shell but not in Jupyter Notebook. Why? I'm trying to import a custom package into my Jupyter Notebook, but I'm have issues. The package works when I open my terminal however I get a 'no module error' when importing the package into my notebook.
I've set up a virtual environment with python3 -m venv and used setuptools to create a setup.py so I can use my custom packages
This is my project structure
./-- notebook -- my_notebook.ipynb
  └── src -- funct -- func.py
  └── setup.py

I also know I've correctly installed the package:
$ pip3 list
Package    Version Location
---------- ------- -------------------------------------------------------
pip        18.0
setuptools 39.0.1
src        0.1.0   /Users/me/project

In my terminal:
$ python3
>>> import src
>>> from src.funct import func
>>> func.foo()
'Foo'

However, when I run import src in my notebook, I get:
import src
ImportError: No module named src

This is my setup.py
from setuptools import find_packages, setup

setup(
    name='src',
    packages=find_packages(),
    version='0.1.0',
    description='Example',
    author='me',
    license='MIT',
)

If the package can be imported correctly into my python shell, why can't it be imported into my notebook? Is this a permissions issue, and if so how can I check that?
Any help would be appreciated.
Thank you.
* Update *
Here is the SOURCES.txt generated from the setup.py
README.md
src/__init__.py
src.egg-info/PKG-INFO
src.egg-info/SOURCES.txt
src.egg-info/dependency_links.txt
src.egg-info/top_level.txt
src/funct/__init__.py
src/funct/func.py

So now I'm more confused on why it won't import.


text:
Q: make ticklabels visible in pandas plot when sharex I want to make a grid of subplots with shared x axes. The plotting shall (for some reasons of convenience) be done by accessing the Pandas DataFrame's plot method. Also, I want to have the x-tick-labels be shown in the first row of my grid. I tried to achieve this with the following code:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

x = np.linspace(0,10,100)

nrows = 4
ncols = 3
fig, axes = plt.subplots(nrows, ncols, sharex=True)

for i, ax in enumerate(axes.reshape(-1)):
    y = np.cos(x+i*np.pi)
    df = pd.DataFrame(y, index=x)
    # ax.plot(x, y)                 # shows top labels
    df.plot(ax=ax, legend=None)     # doesn't show top labels

    if i < ncols:
        # first row: plot x-ticks + x-labels
        ax.tick_params(which='both', labeltop=True, top=True)
        # also none of these approaches works:
        # plt.setp(ax.get_xticklabels(), visible=True)
        # ax.xaxis.set_tick_params(which='both', labeltop=True, top=True, colors='g')
        # for label in ax.get_xticklabels():
        #     label.set_visible(True)

plt.show()

Using the original plotting routine from Matplotlib works, but when I use the Pandas method, the ticklabels stay hidden.
Any ideas, why and how I could solve this?
Thanks a lot in advance,
Markus

A: You can first create the plot as you are currently doing and then later set the ticks for whichever subplot or row/column of subplot you want by creating twin axis.
This example sets the x-ticklabels additionally for only the first row as you want. You add these lines before plt.show(). i<3 here means only the first row because that's how the subplots are accessed here in order. both means both major and minor ticks. Since you haven't yet shown the minor ticks, you only get major ticks at the moment. You can customize the if statements to add the x-ticklabels to another row if you want. I had to remove if i < ncols: command from your code to get it to work.

Complete working code
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import matplotlib
import sys

print (sys.version)
# 3.6.5 |Anaconda, Inc.|

print (matplotlib.__version__)
# 2.2.2

print (pd.__version__)
# 0.23.0

x = np.linspace(0,10,100)

nrows = 4
ncols = 3
fig, axes = plt.subplots(nrows, ncols, sharex=True,figsize=(12,6))

for i, ax in enumerate(axes.reshape(-1)):
    y = np.cos(x+i*np.pi)
    df = pd.DataFrame(y, index=x)
    df.plot(ax=ax, legend=None)     # doesn't show top labels

    if i < 3:
        ax1 = ax.twiny()
        ax1.set_xlim(ax.get_xlim())
        ax1.tick_params(axis='x', which='both', bottom=False, top=True, labelbottom=False)

plt.tight_layout()
plt.show()


text:
Q: Trying to create an editable pdf with Python I'm trying to create a PDF with checkboxes that can be checked (using python). I've been trying to use pisa to generate the pdf and have looked around the internet and tried different examples but I cannot find out how to make an editable PDF.
This is my most recent attempt:
import cStringIO
import ho.pisa as pisa
import os

# shortcut for dumping all logs on screen
pisa.showLogging()

def HTML2PDF(data, filename, open=False):
    """
        Simple test showing how to create a PDF file from
        PML Source String. Also shows errors and tries to start
        the resulting PDF
    """
    pdf = pisa.CreatePDF(cStringIO.StringIO(data), file(filename, "wb"))

    if open and not(pdf.err):
        os.startfile(str(filename))

    return not pdf.err

if __name__=="__main__":
    HTMLTEST = """
        <html>
            <body>
                <form name="deleteForm" method="get" action="">
                     User 1 <input type="checkbox" name="user" value="delete" />
                </form>
            </body>
        </html>
   """

   HTML2PDF(HTMLTEST, "test.pdf", open=True)

The form gives me an error:

Traceback (most recent call last):
  File "C:/Users/horeth/PycharmProjects/Reportlab/HTMLtoPF/Main.py", line 32, in
      HTML2PDF(HTMLTEST, "test.pdf", open=True)
  File "C:/Users/horeth/PycharmProjects/Reportlab/HTMLtoPF/Main.py", line 14, in HTML2PDF
      pdf = pisa.CreatePDF(cStringIO.StringIO(data), file(filename, "wb"))
IOError: [Errno 13] Permission denied: 'test.pdf'

The check boxes are for readers to decide if a user needs to be deleted or not.
I'm wondering if there is a way to create an editable PDF document with Python. This is just one of the attempts I've made so far, as an example.

A: Possible reasons. You don't have write permission to the directory. The file already exists but you do not have write access to it.

A: import cStringIO as StringIO
from xhtml2pdf import pisa
from django.template.loader import get_template
from django.template import Context
from cgi import escape

def render_to_pdf(template_path, context_dict):
    template = get_template(template_path)
    html  = template.render(context_dict)
    result = StringIO.StringIO()
    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-
1")), dest=result)
    if not pdf.err:
        return HttpResponse(result.getvalue(),
content_type='application/pdf')
    return HttpResponse('We had some errors<pre>%s</pre>' %
escape(html))

Call this function
def myview(request):
    return render_to_pdf('HTMLTEST.html', { 'pagesize':'A4',})

create a seperate html file
HTMLTEST.html
    <html>
        <body>
            <form name="deleteForm" method="get" action="">
                 User 1 <input type="checkbox" name="user" value="delete" />
            </form>
        </body>
    </html>


text:
Q: Influence of Normalization and PCA on Distance Metrics After standardizing my dataset, I perform a principal component analysis. Then I do a nearest neighbour search.
I observed then after performing the PCA, even though I kept (for testing purposes) all resulting dimensions (so the input dataset has the same number of features as the PCA-transformed one), my nearest neighbour results drop.
As a distance metric in the nearest neighbour search I use the cosine distance. My intuitive assumption was, that this distant metric should not be influenced by the PCA in the case I don't reduce the dimensionality of my dataset.
How can the performance drop be explained? Did I probably do something wrong?
Here is how I perform the PCA. I use Eigen and C++. traindata is my untouched input dataset where each row is a sample and each column a feature:
  // Mean centering data.
  featureMeans = traindata.colwise().mean();
  Eigen::MatrixXf centered = traindata.rowwise() - featureMeans;
  // Compute featurewise standard deviations.
  Eigen::MatrixXf cov = centered.adjoint() * centered;
  Eigen::VectorXf variances = cov.diagonal();
  stdDevs = variances.cwiseSqrt();
  // Normalize each feature with standard deviation.
  for (size_t i = 0; i < centered.rows(); i++) {
    centered.row(i) = centered.row(i).array() / stdDevs.array().transpose();
  }

  // Compute SVD.
  Eigen::JacobiSVD<Eigen::MatrixXf> svd(centered, Eigen::ComputeThinV);
  // Transformation matrix.
  pcaTransform = svd.matrixV();
  // Project the dataset.
  traindata = centered * pcaTransform;

And later when I get a new datapoint, I transform it in the space of the principal components like this:
Eigen::VectorXf NearestNeighbour::transform(Eigen::VectorXf& vec) {
  vec -= featureMeans;
  vec = vec.array() / stdDevs.array();
  vec = vec.transpose() * pcaTransform;
  return vec;
}

Then in the nearest neighbour algorithm I compute the cosine similarity like this:
float NearestNeighbour::calcCosineSimilarity(Eigen::VectorXf& vecOne, Eigen::VectorXf& vecTwo) {
  float dot = vecOne.dot(vecTwo);
  float cosine = dot / (vecOne.norm() * vecTwo.norm());
  return cosine;
}

I wrote a test script in python using my dataset. The input vector is randomly created as I only wanted to test the concept:
inpvec = [[ 0.73977109,  0.03620438,  0.25417753,  0.11561778,  0.82897718,
         0.13585422,  0.16245644,  0.97201561,  0.68201026,  0.52702283,
         0.21245685,  0.246901  ,  0.72042289,  0.52233973,  0.89980493,
         0.3394559 ,  0.92817351,  0.64084039,  0.73594745,  0.825488  ,
         0.87527608,  0.02777485,  0.30630228,  0.26867405,  0.10130528,
         0.43129711,  0.41076364,  0.22625131,  0.2616146 ,  0.52088176,
         0.23174206,  0.1674724 ,  0.81184377,  0.68945395,  0.12719359,
         0.97440578,  0.18162815,  0.29054626,  0.22535362,  0.44556911,
         0.15830425,  0.15641608,  0.00425475,  0.77260893,  0.84462181,
         0.98222192,  0.12986739,  0.16809029,  0.58549871,  0.38430837,
         0.39776035,  0.76900314]]

def loadTrainingData(path):
  f = open(path)
  tData = []
  for line in f:
    lsplit = line.split(",")
    datapoint = []
    for feature in lsplit:
      datapoint.append(float(feature))

    tData.append(datapoint)
  data = np.array(tData)
  X = np.delete(data, data.shape[1] - 1, 1) # Strip class.
  return X

inpvec = np.array(inpvec)
X = loadTrainingData("trainingfile.csv")

normalizer = Normalizer()
X_norm = normalizer.fit_transform(X)
cosdists = []
for datapoint in X_norm:
  cosdists.append(cosine(normalizer.transform(inpvec)[0], datapoint))
value = min(cosdists)
index = [i for i, j in enumerate(cosdists) if j == value]
print "min dist at " + str(index) + " with " + str(value)

# PCA
pipeline = Pipeline([('scaling', StandardScaler()), ('pca', PCA(n_components=X.shape[1]))])
X_reduced = pipeline.fit_transform(X)

inpVecReduced = pipeline.transform(inpvec)[0]
cosdistsTwo = []
for datapointPCA in X_reduced:
  cosdistsTwo.append(cosine(inpVecReduced, datapointPCA))
valuePCA = min(cosdistsTwo)
indexPCA = [i for i, j in enumerate(cosdistsTwo) if j == valuePCA]
print "min dist at " + str(indexPCA) + " with " + str(valuePCA)

The output of this is:
min dist at [462] with 0.322760977886
min dist at [304] with 0.461332258519

My assumption was that it should output the same index in both cases. Why is this happening?

A: PCA is a linear transformation, and if you are keeping every dimension, then your data should have the same distance function.  Supposing that your original data was some matrix $X$ and your resulting data is some transformed matrix $Y = AX$, then the distance should be unchanged:
$$ d(y_i, y_j) = d(A x_i, A x_j) $$
and if you are using the cosine distance,
$$ d(A x_i, A x_j) = 1 - ((A x_i)^T (A x_j)) / (\|A x_i\| \| A x_j \|) $$
and since the $\| A x_i \| = \| x_i \|$,
$$ = 1 - (x_i^T A^T A x_j) / (\| x_i \| \| x_j \|) $$
and since $A^T A = I$,
$$ = 1 - (x_i^T x_j) / (\| x_i \| \| x_j \|) = d(x_i, x_j) $$
so all this was a very roundabout way to say that distance calculations should not be affected.
Edit, once code appeared: in the calculation of centered, you are normalizing the features for unit variance.  This might be a good idea in general, but it's going to change the distances between points since essentially you are weighting some dimensions to be more or less important than others.  In that case, your resulting data is some transformed matrix $Y = ANX$ where $A$ is some orthogonal basis (so $A^T A = I$ as before), but $N$ is just a diagonal matrix that is not necessarily $I$.  In that case you can't show that $d(y_i, y_j) = d(x_i, x_j)$.  However, you can show that $d(y_i, y_j) = d(N x_i, N x_j)$.  That means that if you were to transform your input data to have unit variance in each dimension, then the distance would be the same as the post-PCA data.


text:
Q: How to make libxml2 parse non-strict HTML? I am using LibXML in my Vala application to parse HTML code. However the HTML I use is invalid if you pass it through validator (although browser displays it normally). In this HTML some tags are not closed, e.g. they use <img> instead of <img /> and <meta> instead of <meta/>. I cannot do anything about it, e.g. ask them to write valid HTML. But I need to parse it and libxml2 fails to do this (in short, doc->get_root_element() always return null).
Can I do something to make libxml2 parse invalid HTML?

A: HTML is not XML.  People tried to make it XML (it was called XHTML), and we mostly just learned that people can't be trusted to write valid XML.  When you say that it is invalid, I assume you mean it is not valid XML but is, in fact, valid HTML.
libxml includes an HTML parser, you need to use that.  In Vala everything is in the Html namespace.


text:
Q: Delivery of signal to mulitithreaded program with sigmask If I have a program that has N running threads, and N-1 of them block delivery of the SIGUSR1 signal using pthread_sigmask:
int rc;
sigset_t signal_mask;
sigemptyset(&signal_mask);
sigaddset(&signal_mask, SIGUSR1);
rc = pthread_sigmask(SIG_BLOCK, &signal_mask, NULL);
if (rc != 0) {
  // handle error
}

When the OS (Linux, recent kernel) delivers SIGUSR1 to the process, is it guaranteed to be delivered to the unblocked thread? Or could it, for example, try some subset of the blocked threads and then give up?

A: Yes, it is guaranteed that a process-directed signal will be delivered to one of the threads that has it unblocked (if there are any).  The relevant quote from POSIX Signal Generation and Delivery:

Signals generated for the process shall be delivered to exactly one of
  those threads within the process which is in a call to a sigwait()
  function selecting that signal or has not blocked delivery of the
  signal.


text:
Q: Find the range of the function $y = \sqrt{x^2 + 1}− x$? I have a function $y = \sqrt{x^2 + 1} − x$, where the Domain is $(−\infty,+\infty)$.
Explanation for the domain
I need to make sure the domain of the function does not include values of $x$
that will make the square root negative.
This means that I need:
$x^2+1\ge0$
the discriminant is negative and $x \in\mathbb R$. In fact, $x^2\ge 0$,  $\forall x\in\mathbb R$ and $1 > 0$.
I wish, if it's possible, to explain the value of the range with an algebraic demonstration. I am using an example to solve the function for $x$ using $y$ as parameter:
$\sqrt{x^2 + 1} − x = y$
$\sqrt{x^2 + 1} = y + x$
irrational equation, therefore:
$$
\begin{cases}
& y + x >= 0\\
& x^2 + 1 =(y+x)^2
\end{cases}
$$
$$
\begin{cases}
& x >= -y\\
& x^2 + 1 =y^2 + x^2 + 2yx
\end{cases}
$$
$$
\begin{cases}
& x >= -y\\
& 1 =y^2 + 2yx
\end{cases}
$$
$$
\begin{cases}
& x >= -y\\
& x = \frac{1 - y^2}{2y}
\end{cases}
$$
now I need to find for which values is $x >= -y$, therefore:
$ \frac{1 - y^2}{2y} < 0$
solving the numerator and denominator
numerator
$1 - y^2 > 0$
$y^2 -1 < 0$
solve for $-1 < y < +1$
denominator
$2y > 0$
solve for $y > 0$
combine the tow solutions the inequality has occurred when
$-1 < y < 0$ or $y> 1$

A: To determine the range you must study the variations of $y$ and apply the Intermediate value theorem (it's a continuous function).
Now $\;y'=\dfrac x{\sqrt{x^2+1}}-1=\dfrac {x-\sqrt{x^2+1}}{\sqrt{x^2+1}}<0,\;$ since $\;\lvert x\rvert<\sqrt{x^2+1} $. Hence the function is decreasing.
On the other hand,

*

*$\lim_{x\to-\infty}\sqrt{x^2+1}-x=+\infty+\infty=+\infty$,

*$\lim_{x\to+\infty}\sqrt{x^2+1}-x=\lim_{x\to+\infty}\dfrac{(x^2+1)-x^2}{\sqrt{x^2+1}+x}=0$.

Hence the range of $y$ is $(0,+\infty)$.
A purely computational solution:
As noted in another answer, $y=\dfrac1{x+\sqrt{x^2+1}}$. Hence the range is contained in $(0,+\infty)$. Lets show  for any $m>0$, the equation  $\dfrac1{x+\sqrt{x^2+1}}=m$ has a solution. Indeed, it is equivalent to
$$\sqrt{x^2+1}=\frac1m-x\iff x^2+1=\Bigl(\frac1m-x\Bigr)^2\enspace\textbf{and}\enspace x \le\frac 1m.$$
Now $$x^2+1=\Bigl(\frac1m-x\Bigr)^2=\frac1{m^2}-\frac 2mx+x^2\iff x=\frac{1-m^2}{2m}$$
and the condition $\;x\le\dfrac1m$ is satisfied iff $\;1-m^2\le 2$, i.e. $m^2\ge -1$.

A: Well, there is probably an easy algebraic method:
$$y=\sqrt{x^2+1}-x$$$$\implies y^2+x^2+2xy=x^2+1$$$$\implies y^2+2xy-1=0$$
to find range of $y$, we reform this equation as
$$0x^2+2xy+y^2-1=0$$
this is quadratic in $x$ and since $x$ is real , $y$ should also be real so discriminent should be greater than zero
$$D=(2y)^2-4(y^2-1)(0)>0$$
and this implies $$y^2>0$$$$\implies y>0$$or$$y<0$$ but $y<0$ is ruled out since
$|x|=\sqrt{x^2}<\sqrt{x^2+1}$, so $x<\sqrt{x^2+1}$ ,therefore $y>0$ for all values of $x$ so $$y\in (0,\infty)$$

A: Hint: Expand the fraction with $\sqrt{x^2+1}+x$ to see that
$$y=\frac{1}{\sqrt{x^2+1}+x}$$

A: Let's see:
$$\frac1{\sqrt{x^2+1}+x}=\frac1{-x\sqrt{1+\frac1{x^2}}+x}=\frac{-\frac1x}{\sqrt{1+\frac1{x^2}}-1}$$
With l'Hospital now (we have a $\;\frac00\;$ indeterminate);
$$\lim_{x\to-\infty}\frac{-\frac1x}{\sqrt{1+\frac1{x^2}}-1}=\lim_{x\to-\infty}\frac{\frac1{x^2}}{-\frac1{x^3\sqrt{1+\frac1{x^2}}}}=\lim_{x\to-\infty}-x\sqrt{1+\frac1{x^2}}=+\infty$$
And now:
$$\frac1{\sqrt{x^2+1}+x}=\frac1{x\sqrt{1+\frac1{x^2}}+x}=\frac{\frac1x}{\sqrt{1+\frac1{x^2}}+1}\xrightarrow[x\to\infty]{}\frac02=0$$
So I'd say the range is $\;(0,\infty)\;$ as this is a continuous function everywhere.
Other way: calculate any of the two limits above, and then check that
$$\left(\sqrt{x^2+1}-x\right)'=\frac x{\sqrt{x^2+1}}-1\le0\;\;\;\forall\,x\in\Bbb R$$
so the function is monotonic decreasing. Now, if you take the limit when $\;x\to-\infty\;$ then you use this and the fact that the function's always non-negative, and if you took the limit when $\;x\to\infty\;$ then use this and the fact the function's never constant in any interval.

A: This is only a partial answer as it only establishes the lower bound for the range.
Multiply by the conjugate
$$y=(\sqrt{x^2+1}-x) \cdot \dfrac{\sqrt{x^2+1}+x}{\sqrt{x^2+1}+x}$$
$$y=\dfrac{1}{\sqrt{x^2+1}+x}$$
This function is clearly approaching $0$ as $x$ is approaching positive infinity. Also the function is never negative, since $$1>0$$
$$x^2+1>x^2$$
$$\sqrt{x^2+1}>x$$
Therefore we established a lower bound of $0$ for your range.


text:
Q: Inno Setup Doesn't Create All ODBC REG Keys So I have been working with creating ODBC connections in Inno by utilizing the registry. The issue I have been running into is that Inno does not create all of the keys I set. I am using a 64bit version of Windows and installing a 32 bit application using the 32 bit Inno installer. The path I am using is HKLM\SOFTWARE\WOW6432Node\ODBC\ODBC.INI
Example:
I have a connection TESTDBF1 which holds the values:
TESTDBF1
This creates the connection in the 32 bit ODBC Administrator but I also need to specify the custom dBase version (IV) and directory (C:\DIR) shown. To accomplish this, the subkeys below must be added, or the ODBC Administrator will only show the default dBase version (V) and current directory.
This Xbase directory is needed to hold the custom settings specified in the main TESTDBF1 section
The keys in the Xbase directory.
In addition, I add the Name: TESTDBF1 as a string "Driver do Microsoft dBase (*.dbf)" into WOW6432Node\ODBC\ODBC.INI\ODBC Data Sources.
To run all of these commands, I created TESTDBF1.reg to confirm functionality.

    Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\ODBC\ODBC.INI\TESTDBF1]
"Driver"="C:\\WINDOWS\\system32\\odbcjt32.dll"
"DefaultDir"="C:\\IBS"
"DriverId"=dword:00000115
"FIL"="dBase IV;"
"SafeTransactions"=dword:00000000
"UID"=""

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\ODBC\ODBC.INI\TESTDBF1\Engines]

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\ODBC\ODBC.INI\TESTDBF1\Engines\Xbase]
"CollatingSequence"="ASCII"
"Deleted"=hex:00
"ImplicitCommitSync"=""
"PageTimeout"=dword:00000005
"Statistics"=hex:00
"Threads"=dword:00000003
"UserCommitSync"="Yes"

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\ODBC\ODBC.INI\ODBC Data Sources]
"TESTDBF1"="Driver do Microsoft dBase (*.dbf)"

Upon merging/running this file, all keys are successfully created and I can confirm the custom values are showing in the ODBC Administrator.
So, I'm thinking - Hey its working! Now I can add into Inno!
No.
I am using Inno Script Studio as my compiler.
I import the registry file TESTDBF1.reg I just used into the script and then run the installer. No such luck. All of the keys at \WOW6432Node\ODBC\ODBC.INI\TESTDBF1 are created but none of the following subdirectories are created (\Engines and \Engines\Xbase) Reminder: Xbase holds the keys that ensure the custom info in ODBC.INI\TESTDBF1 hold when you open the ODBC Administrator.
So after confirming the TESTDBF1.reg works again, I look at the code I am writing in Inno:
; Imported Registry File: "C:\Users\Support\Documents\test\TESTDBF1.reg"
Root: HKLM; Subkey: SOFTWARE\WOW6432Node\ODBC\ODBC.INI\TESTDBF1; ValueType: string; ValueName: "Driver"; ValueData: "C:\WINDOWS\system32\odbcjt32.dll"; Flags: uninsdeletekey;
Root: HKLM; Subkey: SOFTWARE\WOW6432Node\ODBC\ODBC.INI\TESTDBF1; ValueType: string; ValueName: "DefaultDir"; ValueData: "C:\DIR"; Flags: uninsdeletekey;
Root: HKLM; Subkey: SOFTWARE\WOW6432Node\ODBC\ODBC.INI\TESTDBF1; ValueType: dword; ValueName: "DriverId"; ValueData: "$00000115"; Flags: uninsdeletekey;
Root: HKLM; Subkey: SOFTWARE\WOW6432Node\ODBC\ODBC.INI\TESTDBF1; ValueType: string; ValueName: "FIL"; ValueData: "dBase IV;"; Flags: uninsdeletekey;
Root: HKLM; Subkey: SOFTWARE\WOW6432Node\ODBC\ODBC.INI\TESTDBF1; ValueType: dword; ValueName: "SafeTransactions"; ValueData: "$00000000"; Flags: uninsdeletekey;
Root: HKLM; Subkey: SOFTWARE\WOW6432Node\ODBC\ODBC.INI\TESTDBF1; ValueType: string; ValueName: "UID"; ValueData: ""; Flags: uninsdeletekey;
Root: HKLM; Subkey: SOFTWARE\WOW6432Node\ODBC\ODBC.INI\TESTDBF1\Engines\Xbase; ValueType: string; ValueName: "CollatingSequence"; ValueData: "ASCII"; Flags: uninsdeletekey;
Root: HKLM; Subkey: SOFTWARE\WOW6432Node\ODBC\ODBC.INI\TESTDBF1\Engines\Xbase; ValueType: binary; ValueName: "Deleted"; ValueData: "00"; Flags: uninsdeletekey;
Root: HKLM; Subkey: SOFTWARE\WOW6432Node\ODBC\ODBC.INI\TESTDBF1\Engines\Xbase; ValueType: string; ValueName: "ImplicitCommitSync"; ValueData: ""; Flags: uninsdeletekey;
Root: HKLM; Subkey: SOFTWARE\WOW6432Node\ODBC\ODBC.INI\TESTDBF1\Engines\Xbase; ValueType: dword; ValueName: "PageTimeout"; ValueData: "$00000005"; Flags: uninsdeletekey;
Root: HKLM; Subkey: SOFTWARE\WOW6432Node\ODBC\ODBC.INI\TESTDBF1\Engines\Xbase; ValueType: binary; ValueName: "Statistics"; ValueData: "00"; Flags: uninsdeletekey;
Root: HKLM; Subkey: SOFTWARE\WOW6432Node\ODBC\ODBC.INI\TESTDBF1\Engines\Xbase; ValueType: dword; ValueName: "Threads"; ValueData: "$00000003"; Flags: uninsdeletekey;
Root: HKLM; Subkey: SOFTWARE\WOW6432Node\ODBC\ODBC.INI\TESTDBF1\Engines\Xbase; ValueType: string; ValueName: "UserCommitSync"; ValueData: "Yes"; Flags: uninsdeletekey;
Root: HKLM; Subkey: SOFTWARE\WOW6432Node\ODBC\ODBC.INI\ODBC Data Sources; ValueType: string; ValueName: "TESTDBF1"; ValueData: "Driver do Microsoft dBase (*.dbf)"; Flags: uninsdeletekey;

Hmm. I can't find anything wrong with that. I ran the install script again and again with different names, directories, and the like and regardless of what I do, I cannot get the \Engines\Xbase keys to write from inside of the install script.
Now, why don't I just run the .reg file at the end of install?
Because part of my script uses the install directory (which changes) as part of these reg keys. Note ValueData. Example:
Root: HKLM; Subkey: SOFTWARE\WOW6432Node\ODBC\ODBC.INI\TESTDBF1; ValueType: string; ValueName: "DefaultDir"; ValueData: "{app}\IBS"; Flags: uninsdeletekey;

After running the installer, this is the key that is created at HKLM\Software\WOW6432Node\ODBC\ODBC.INI\TESTDBF1
Post Install Key
Any help would be much appreciated - I am pretty stumped at this point.

A: I think I figured it out - minutes after posting. The post probably helped get things straight.
So - when writing 32 bit keys, using a 32 bit application and a 32 bit installer, get this - you write to the 64 bit registry directory. You DO NOT write to the WOW6432Node because of whatever back end stuff with Inno. It just doesn't write.
You have to write to the 64 bit directory and somewhere, somehow, Inno and Windows communicate and will automatically take your 32 bit information and place it into the WOW6432Node for you. You just can't do it yourself.
So my actual fix was to change all of my reg entries to HKLM\SOFTWARE\ODBC\ODBC.INI\testdbf1etc and in doing so, everything worked and wrote properly into HKLM\SOFTWARE\WOW6432Node\ODBC\ODBC.INI\testdbf1etc.
I really wish this portion would have been better documented in Inno. If you remember above, my .reg file worked! Inno was the one who wouldn't write the keys properly, but I guess that is to be expected since it is an application instead of referencing the default Windows functions.
Hope this helps the rest of you!


text:
Q: Does Linux sends `SIGCHLD` to `init` when it inherits orphaned zombie processes? Does Linux sends SIGCHLD to init (PID 1 process) when it inherits orphaned zombie processes (processes that have not been reaped by its original parent)?

A: Yep.  I tested it.  And you can see where this happens in the Linux code.

Test: Start a nested shell.  From elsewhere, kill -s STOP the parent shell.  Then kill -s KILL the child shell and then the parent.
Note:
If you try this inside gnome-terminal, for example, the reaper will not be PID 1.  It will be a sub-reaper, the process systemd --user.
Also, systemd handles signals using a signalfd.  So when you run strace -p on the systemd process, you will not see a signal being received.  You will instead see that systemd wakes from epoll_wait() and performs a read() on a file descriptor.
You can confirm the file descriptor number is a signalfd using ls -l /proc/<PID>/fd/<FD>.  It will say anon_inode:[signalfd].


text:
Q: Splitting with Regular Expression in Python I am relatively new to Python, and I am trying to split a string using re.
I have researched a bit, and I have come across a few examples and I tried them out. They seem to work, but with limitation.
I am using a dictionary with a string key that is associated with an integer value. I'm trying to apply a weight to each word that depends on the integer value associated with the key string. My issue is that the string isn't formatted perfectly and I need to split it on underscores ( _ ) as well as whitespace and other various delimiters. From what I understand, this needs to be done with regular expressions. My bit of code is as follows:
for key, value in sorted_articles.items():
    wordList = print(re.split(r'(_|\s|:|)',key))

When I print this out, it splits everything fine, but it also prints out the delimiters rather than ignoring them in the list. For example, the string "Hello_how are you_" gets stored in the list as ['Hello', '_', 'how', ' ', 'are', ' ', 'you','_'].
I'm not sure why the delimiters would be added to the list and I can't figure out how to fix it. Thanks in advance for the help!

A: You can split using the \W+ character, which will split at all not alpha string items and use |_ to specifically search for underscores:
for key, value in sorted_articles.items():
    wordList = print(re.split('\W+|_',key))

For instance:
s = "Hello_how are you_"

print(re.split("\W+|_", s))

Output:
['Hello', 'how', 'are', 'you', '']


text:
Q: Can we change the SEDE workflow a little? Currently when a user goes to SEDE they must first pick a site for which to run their query.  Only then can they browse the available queries or compose one of their own.
Seeing that the queries are the focus of the site I think it'd work better if we allowed them to browse/compose queries first and once they have the query then allow them to switch what site they want to query on the fly.
So at http://odata.stackexchange.com/ users would see what's currently the queries page.
The Queries and Compose Query buttons are both visible on every page (just like SO's navigation buttons).
Once they select a query or hit the compose button I'm thinking they see a page that looks like this.  We can switch the radio buttons out for something better looking if necessary.
alt text http://img697.imageshack.us/img697/1699/screenshot20100601at111.png
We default to the SO database but if the user selects one of the others we save their preference for next time.  When they click Run Query they get the results for whatever site they have chosen.
I know this messes with the routing scheme (and permalinks?), but fixes the confusing navigation issue on the non query pages and gets rid of the "Select a site" page/click they have to go through every time they visit the site.

A: Well, I think I managed to make it kind of intuitive.

*

*There are no longer magic disappearing menu items, they all show up always

*On first visit we assume you want to look at "Stack Overflow" data, if at any point you change sites, it will be remembered

*You can change sites from the front page or by clicking a link

*We always show what site you are on in the query list

I am fairly comfortable with this, I think it is fairly easy to figure out.


text:
Q: How to Decrypt, incryptdumpfile in mysql using C# (MySqlBackup.dll) I want to Decrypt the Mysql Incrypted dump file with mysqlbackup.dll. I use bc.DecryptDumpFile() but this show error "Incorrect password or corrupted context" How to decrypt this file
MySqlBackup bc = new MySqlBackup();
bc.DecryptDumpFile(Application.StartupPath + "//POS_Assistant - 24-Jul-19.dll", Application.StartupPath + "//POS.sql", "Rehman92");

A: Maybe the below code helps:
   private void DecryptDumpFile()
    {
        string oldDumpFile = "C:\\backup.sql";
        string newDumpFile = "C:\\backup_new.sql";
        MySqlBackup mb = new MySqlBackup();
        mb.EnableEncryption = true;
        mb.EncryptionKey = "qwerty";
        mb.DecryptSqlDumpFile(oldDumpFile, newDumpFile);
    }


text:
Q: How to handle the content part in AJAX page switching in PWA? I have zero experience in native apps, which might help with this question.
Since service worker caches everything so nicely, then I don't see any reason why I should render the entire webpage again when the page gets switched (link gets clicked.) So I will switch only the content, use history pushstate to change the URL and change the title. I have that part figured out.
Problem is, I cannot find any resources that would support either of the two content load ideas I have:

*

*Load center content via AJAX with HTML.

*Load center content as data only and render the HTML on-the-fly in JS.

First method would be fairly straight forward, but would mean that the payload would be bigger.
Second seems much more advanced, but would mean that HTML templates have to be in the JS somehow already? I also have a feeling, that there is a method somewhere in here.. that would allow to open the heavily cached page (lets say the article page) and replace the (text) contents. But as I said, I cannot find any resources to wager the cons and pros or give any reliable information on PWA AJAX page switching.
Any credible information on this matter would be much appreciated.
EDIT
I have kept reading and researching on this matter, but sadly there is no clear indication on how to handle dynamic content over AJAX. Whether I should parse the JSON data from AJAX to HTML in JS or send it already as HTML from the backend.
To add in favour to second option. I have figured out, that my theory had somewhat weight to it. If I use pure.js to pull a HTML template from hidden template tag and generate the HTML on the fly from JSON over AJAX.

A: you make it so complicated can we take a look at your code please?!
if you mean retrieving data from database by ajaxthen all what when you need is a jquery plugin
$(document).ready(function(){
var contentData1 = document.getElementById('contentData1');
  $(function() {

    $.post("pathToPHP.php",{contentData1: contentData1},function(data){
        $("#container").html(data);
    });
});

and the pathToPHP.php file should retrieve the data you want
echo "";


text:
Q: Catching search matched term in to a variable and linking to other document please have my below code :
var pdf_files=["a1.pdf","a2.pdf","a3.pdf"];
for(k=0;k<pdf_files.length;k++)
{
    app.Open("/C/mySource/"+pdf_files[k]); //open the respective file

    for(var i=0;i<this.numPages;i++)
    {
        //loop through the entire document
        numWords=this.getPageNumWords(i);
        var WordString="";

        for(var j=0;j<numWords;j++)
        {
            WordString=WordString+" "+this.getPageNthWord(i,j);
        }

        if(WordString.match(/[0-9][0-9]-[0-9][0-9][0-9][0-9] FIG [0-9]+/)) //regular expression to match a string like "24-50-44 FIG 11"
        {
            search.matchWholeWord=true;
            var myMatch=search.query(WordString.match(/[0-9][0-9]-[0-9][0-9][0-9][0-9] FIG [0-9]+/),"ActiveDoc");
            console.println(myMatch);
        }
    }
}

the problem that I am facing here is :
I am opening one pdf file, searching the particular string as per regular expression. on successful search, I am trying to display that matched string onto console. But this is not happening. I need your suggestion in this regard.
Please let me know whether it is possible to store matched string in variable or not, also whether it's possible to link the matched string to one other .pdf file?

A: You have to use regex capturing groups to capture the content you want. You can use this regex:
([0-9]{2}-[0-9]{4} FIG [0-9]+)

With a code like this:
var re = /([0-9]{2}-[0-9]{4} FIG [0-9]+)/g;
var str = 'YOUR TEXT';
var m;

while ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    // View your result using the m-variable.
    // eg m[0] etc.
}


text:
Q: Update Query in GRN This is a stock management system and I have a problem with updating part in good received note. When we purchase goods, we get a good received note, so when we get the items the number of items has to be updated (has to be added to the remaining goods) according to the item code.
According to the following code data from GRN will be extracted and will be saved in GRN1 and GRN2 tables. There's another table called Item_Supplier, when we receive goods Stock in hand field in Item_Supplier table has to updated according to the item_Id as well.
Problem is following code does not work.
Connection ss = Class_DB.myconnection();
                    Statement st = ss.createStatement();

-
ResultSet rs = st.executeQuery("select stock_in_hand from item_supplier where item_ID =('" + TF_GRN_ITEMID.getText() + "')");

grniid = TF_GRN_NO_OF_ITEM.getText();

while (rs.next()) {
    nit = rs.getString("stock_in_hand");
}

sumn = grniid + nit;

st.executeUpdate("insert into grn1 values('" + TF_GRN_GRNNO.getText() + "','" + TF_GRN_SUPPLIERID.getText() + "','" + TF_GRN_AMOUNT.getText() + "','" + TF_GRN_DATE.getText() + "')");
st.executeUpdate("insert into grn2 values('" + TF_GRN_GRNNO.getText() + "','" + TF_GRN_ITEMID.getText() + "','" + TF_GRN_EXP_DATE.getText() + "','" + TF_GRN_TAX.getText() + "','" + TF_GRN_NO_OF_ITEM.getText() + "','" + TF_GRN_GAMOUNT.getText() + "','" + TF_GRN_NAMOUNT.getText() + "','" + TF_GRN_QTY.getText() + "','" + TF_GRN_UNIT.getText() + "','" + TF_GRN_FREE.getText() + "','" + TF_GRN_DIS.getText() + "')");
st.executeUpdate("update item_supplier set stock_in_hand='" + sumn + "' where item_ID='" + TF_GRN_ITEMID.getText() + "'");

JOptionPane.showMessageDialog(null, "Data Saved");

Please help.


text:
Q: SSIS CDC Permissions Error I am creating an SSIS package using Change Data Capture. I have created the package, but I get the error below while executing it:

[CDC Control Task] Error: "Only members of the sysadmin fixed server
  role or db_owner fixed database role can perform this operation.
  Contact an administrator with sufficient permissions to perform this
  operation.".

The error says sysadmin/db_owner role is required. However, is this really required or I am doing something wrong?

A: I depends on what you are trying to do in SSIS..Here is what MSDN lists out. and what privilege you need to have..
Access Authorization to Change Data:

Trickle-feed update packages need access to SQL Server 2016 CDC functions. Such access is granted, by default, to members of the db_owner fixed database role. Because the db_owner is a powerful role, when defining capture instances within SQL Server 2016 it is recommended to associate a gating security role to each capture instance that allows the SSIS CDC package to use a much more restricted user for processing the changes.

Access to CDC Database Current LSN:

The CDC Control task operations for marking the start LSN for change processing must be able to find the CDC Database current LSN. This is done using the procedure sp_replincrementlsn from the master database. Execute permission on this procedure must be given to the login used for connecting to the SQL Server 2016 CDC database.

Access to CDC States Table:

The CDC States table is used for automatically persisting CDC States that need to be updatable by the login used for connecting to the SQL Server 2016 CDC database. As this table is created by the SSIS developer, set the SQL Server 2016 system administrator as a user who is authorized to create SQL Server 2016 databases and perform administrative and maintenance tasks. In addition, a SQL Server 2016 system administrator who works with CDC enabled databases must be knowledgeable about SQL Server 2016 CDC technology and implementation.


text:
Q: Protect your API KEYS from Reverse Engineering Android I'm a bit disappointed about ProGuard.
I am using Gradle to hide my Google MAP API KEYS. I also read this question here Manage Google Maps API Key with Gradle in Android Studio
and did the same. If you follow the accepted answer in this question, your api key won't get obfuscated by ProGuard. The question is why?
There are two good answers. One with ManifestPlaceHolder, one with using @string
Still, if I decompile my app, there is still my weather api key to seen.
I am using private String myweatherapikey = BuildConfig.MY_API_WEATHER_KEY; and it is amazing (in a bad way) how ProGuard DOES NOT obfuscate this, even when using Gradle.
When you do reverse engineering it looks like private String myweatherapikey ="MY KEY IN PLAIN TEXT";
I am trying to obfuscate my keys since days but nothing worked, even using Gradle.
How do you hide your keys ? It really annoys me that all my keys are public, when you decompile my app.
Second question: I think it is impossible to hide your google maps api key. There are 2 keys, one for release-version and one for debug-version. Both of them are stored in src/debug and src/release. You can't hide this, right?

A: OBFUSCATION

your api key won't get obfuscated by ProGuard

If Proguard or any other tool obfuscates the API key, then it also needs to be de-obfuscated at run-time, otherwise you cannot use it.
No matter if you have an obfuscation mechanism or even an encryption mechanism, an attacker just needs to hook during run-time an instrumentation framework, like Frida, to the code that returns the API after it have been de-obfuscated or decrypted.
Frida:

Inject your own scripts into black box processes. Hook any function, spy on crypto APIs or trace private application code, no source code needed. Edit, hit save, and instantly see the results. All without compilation steps or program restarts.

Another approach for the attacker is to perform a MitM attack in a device he controls or was able to compromise, and intercept all requests between the mobile app and the backend in order to extract the API key from the header, and you can read my article Steal that API Key with a Man in the Midlle Attack to learn how it can be done:

So, in this article you will learn how to setup and run a MitM attack to intercept https traffic in a mobile device under your control, so that you can steal the API key. Finally, you will see at a high level how MitM attacks can be mitigated.

YES, IT'S PUBLIC

I am trying to obfuscate my keys since days but nothing worked, even using Gradle. How do you hide your keys ? It really annoys me that all my keys are public, when you decompile my app.

From the moment you publish a mobile app into the Google, Apple store or any other store, the binaries can be downloaded and reverse engineered, therefore anything inside of them must be considered to be in the public domain, be it secrets or just code.
Techniques to Hide API Keys and to Reverse Engineer them
My favorite tool to reverse engineer a binary of a mobile app is the MobSF:

Mobile Security Framework (MobSF) is an automated, all-in-one mobile application (Android/iOS/Windows) pen-testing, malware analysis and security assessment framework capable of performing static and dynamic analysis.

You can read my article How to Extract an API key from a Mobile App with Static Binary Analysis to understand how this is done and at same time to learn the several techniques used to try to hide an API key, and see how they are easily bypassed:

During this article we will use the Android Hide Secrets research repository that is a dummy mobile app with API keys hidden using several different techniques.
It's time to look for a more advanced technique to hide the API key in a way that will be very hard to reverse engineer from the APK, and for this we will make use of native C++ code to store the API key, by leveraging the JNI interface which uses NDK under the hood.

GOOGLE MAPS API KEY

Second question: I think it is impossible to hide your google maps api key. There are 2 keys, one for release-version and one for debug-version. Both of them are stored in src/debug and src/release. You can't hide this, right?

If you have read all the links I posted above, then by now you may already have realized that is indeed a Mission Impossible to hide any secret in the binary of your mobile app.
The bottom line is that if is in the binary it can be extracted by static analysis or during run-time.
I am not really familiar with the Google Maps usage in a mobile app, therefore I don't know if its possible to move the calls for it to the backend, because this is what it must be done with any usage of Third Party APIs in a mobile app, otherwise the API key is vulnerable to be extracted and abused, and if you are billed or rate limited based on it, then you may be in trouble when an attacker get hands on your API key.
THIRD PARTY APIS
Currently you are usage of Third Party APIs puts your mobile app in this position:

But preferentially your mobile app should be in this position:

While in the graphics I mention a Reverse Proxy, it could be the backend for your mobile app.

NOTE: The graphics belong to an article that I am currently writing about the use of a Reverse Proxy to access Third Party APIs.

Securing the API keys to access Third Party APIs is much easier when delegating access to them to a reverse proxy or backend we are in control of, and an immediate advantage of this approach is that the API keys for the Thrid Party services are not anymore in the public domain, aka the binary of your mobile app.
So from the graphics we are left with only one API key to secure, the one to access your reverse proxy or backend, where you can employ as many security measures as you can afford to prevent unauthorized access to it.
POSSIBLE SOLUTION

How do you hide your keys ?

Would not be better to not have any keys at all to hide in your mobile app, because that would be the ideal solution. So the above graphic would look more like:

To be in a position where you don't need to ship any secrets in your mobile app you need to resort to the Mobile App Attestation concept, and from this article section I will extract the relevant bits, that explain it's role:

Before we dive into the role of a Mobile App Attestation service, we first need to understand the difference between what and who is accessing the API server. This is discussed in more detail in this article, where we can read:

The what is the thing making the request to the API server. Is it really a genuine instance of your mobile app, or is it a bot, an automated script or an attacker manually poking around your API server with a tool like Postman?
The who is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.

The role of a Mobile App Attestation service is to authenticate what is sending the requests, thus only responding to requests coming from genuine mobile app instances and rejecting all other requests from unauthorized sources.
In order to know what is sending the requests to the API server, a Mobile App Attestation service, at run-time, will identify with high confidence that your mobile app is present, has not been tampered/repackaged, is not running in a rooted device, has not been hooked into by an instrumentation framework(Frida, xPosed, Cydia, etc.), and is not the object of a Man in the Middle Attack (MitM). This is achieved by running an SDK in the background that will communicate with a service running in the cloud to attest the integrity of the mobile app and device it is running on.
On a successful attestation of the mobile app integrity, a short time lived JWT token is issued and signed with a secret that only the API server and the Mobile App Attestation service in the cloud know. In the case that attestation fails the JWT token is signed with an incorrect secret. Since the secret used by the Mobile App Attestation service is not known by the mobile app, it is not possible to reverse engineer it at run-time even when the app has been tampered with, is running in a rooted device or communicating over a connection that is the target of a MitM attack.
The mobile app must send the JWT token in the header of every API request. This allows the API server to only serve requests when it can verify that the JWT token was signed with the shared secret and that it has not expired. All other requests will be refused. In other words a valid JWT token tells the API server that what is making the request is the genuine mobile app uploaded to the Google or Apple store, while an invalid or missing JWT token means that what is making the request is not authorized to do so, because it may be a bot, a repackaged app or an attacker making a MitM attack.
A great benefit of using a Mobile App Attestation service is its proactive and positive authentication model, which does not create false positives, and thus does not block legitimate users while it keeps the bad guys at bay.

The Mobile App Attestation liberates your mobile app to have an embedded secret in its code, instead now it only needs to pass to the reverse proxy or backend the JWT token it receives from the Attestation. Now the reverse proxy or backend can verify the JWT token, and on successful validation they can fulfill requests with a very high confidence that they are originated from what they expect, a genuine instance of the mobile app, with the added benefit of not exposing the API keys to access your Third Party services.
GOING THE EXTRA MILE
I cannot resist to recommend the excellent work done in the OWASP - Mobile Security Testing Guide:

The Mobile Security Testing Guide (MSTG) is a comprehensive manual for mobile app security development, testing and reverse engineering.


text:
Q: Can't install gensim with pip I am completely new to Python so I am trying to install gensim but it's not installing. I am using mac.
Below is the output I am getting in terminal:
Requirement already up-to-date: six>=1.5.0 in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/six-1.10.0-py2.7.egg (from gensim)
Requirement already up-to-date: boto>=2.32 in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages (from smart-open>=1.2.1->gensim)
Requirement already up-to-date: bz2file in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages (from smart-open>=1.2.1->gensim)
Requirement already up-to-date: requests in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages (from smart-open>=1.2.1->gensim)
Installing collected packages: numpy, scipy, gensim
  Found existing installation: numpy 1.8.0rc1
    DEPRECATION: Uninstalling a distutils installed project (numpy) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
    Uninstalling numpy-1.8.0rc1:
Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run
    prefix=options.prefix_path,
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 778, in install
    requirement.uninstall(auto_confirm=True)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 754, in uninstall
    paths_to_remove.remove(auto_confirm)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_uninstall.py", line 115, in remove
    renames(path, new_path)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/utils/__init__.py", line 267, in renames
    shutil.move(old, new)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move
    copy2(src, real_dst)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2
    copystat(src, dst)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat
    os.chflags(dst, st.st_flags)
OSError: [Errno 1] Operation not permitted: '/tmp/pip-lCcMmh-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy-1.8.0rc1-py2.7.egg-info'

A: The system python is managed by the OS vendor (Apple, Canonical, etc), and is meant to be used by other OS built-in tools. Having pip mess things up in the vendored python is dangerous. The SIP protection since El Capital makes it harder to break these things, and for good reasons.
Installing a separate python distribution, or
using pip with --user option circumvents the need to require elevated root access. You may still have to add the user's bin folder to the $PATH --
use this:
sudo pip install gensim --user


text:
Q: Async Yield call returning undefined in React I have an async function for getting token from firebase. But when I fired this function returned undefined.
When I consol.log my async function it's return token. After Yield call, returns undefined.
I am a new student and I have no idea what is happening. So..If anyone can help me with this problem It's really helped me with my studies. Thank you.❤
 React.useEffect(() => {
        dispatch(AddUserTokenListener())
    }, [])

async function getUserIDAsync() {
        const idTokenResult = await firebase.auth().currentUser.getIdTokenResult();
        // console.log('User JWT: ', idTokenResult); But this will return token
    }

    export function* getUserToken() {
        try {
            const userToken = yield call(getUserIDAsync);
           // console.log(userToken) this will return undefined .
            if (userToken) {
                console.log(userToken)
                yield put(AddUserTokenSuccess(userToken))
            }
        } catch (error) {
            console.log(error)
            yield put(AddUserTokenField(error))
        }
    }


text:
Q: Placing a Query Result in A String Variable Was wondering how can we put an SQL statement in a String Variable?
Example:
    Dim sqlQuery as String, qHolder as String
sqlQuery = "SELECT ID.table from table WHERE ID ='" userInputTextBox "'"

Whenever i do the above statement using either OpernRecordset() or RecordSource it gives me a bug. Can you give an example on how we do this, so we can use the value of sqlQuery for comparison for example
    if(sqlQuery = userInputTextBox)then
    MSgBox(" Match Found " )
    Else
    MsgBox("No Match Found")
Big Thanks in Advance.

A: Use the string concatenation operator (&).
sqlQuery = "SELECT ID.table from table WHERE ID ='" & userInputTextBox & "'"

Otherwise, it's a syntax error.
UPDATE
To get the value of ID.table into a string, use the Fields property of the Recordset:
Dim s As String
' by index
s = MyRec.Fields(0)
' or by name
s = MyRec.Fields("ID.table")