text:
Q: How to tell that a c++ application has disk I/O bottleneck? I'm working on a "search" project. The main idea is how to build a index to respond to the search request as fast as possible. The input is a query, such as "termi termj", ouput is docs where both termi and termj appear.
the index file looks like this:(each line is called a postlist, which is sorted array of unsigned int and can be compressed with good compression ratio)

term1:doc1, doc5, doc8, doc10
term2:doc10, doc51, doc111, doc10000
...
termN:doc2, doc4, doc10

3 main time resuming procedure is

*

*seek termi and termj's postlist in file (random disk read)

*decode the postlists (cpu)

*calculate the intersection of 2 postlists (cpu)

My question is, How can I know that the application can't be more efficient, it has a disk I/O bottleneck? How can I measure if my computer has used his disk 100 percent? Are there any tools on linux to help? Is there any tools can measure disk I/O perfectly like google cpu profiler can measure cpu?
My develop env is Ubuntu 14.04.
CPU: 8 cores 2.6GHz
disk: SSD
benchmark now is about 2000 queries/second, but I don't know how to improve it.

Any suggestion will be appreciated! Thank you very much!


text:
Q: Loading Addressable Sprites using their Address I have followed this document from first to last to do practice with Addressable Sprites.
Addressables: Sprite Loading
I can able to get success in Sprite loading through Addressables but when I try with specified Address, I am getting an exception like this:

Here are the addressable groups, I have created:

Now Image is not loading through a specific address:

Assets/Resources_moved/CityLights/Images/Cities/Charlotte.png

Please share your suggestion regarding this.
EDIT: Expanded Addressible Groups

A: Firstly as i can see in your screenshot that there is no image in that image component in unity inspector , so trace it first that is the particular image which you looking for is loading or not?? while it's running dynamicly check it first, and after it check the key value address of this particular addresable sprite from script while it running on unity.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Constructor injection in application where dependencies might not be able to be initialized My application is able to start without a database connection, how do I handle this with IoC and constructor injection?
Example:
public class ApplicationShellPresenter(IRepository repository, IView view)
{

}

When IRepository in this case will be constructed an exception will be thrown due to underlaying DAL cannot find config/file, wrong username/password etc. etc.
With this in mind I came to the conclusion that I cannot inject the repository in the constructor OR inject anything that eventually along the line have IRepository as dependency.
I need to start without IRepository dependency and when the user have made the correct database settings, register the IRepository in the container. But then I have already left the composition root.
Edit:
My problem was not really a IoC/Constructor injection - problem but rather a design flaw in our underlaying DAL.
Our DAL is constructing itself upon creation. And thats why that design didn't work because I couldn't construct a IRepository dependency without constructing our DAL-engine.
My simple solution was to wrap our DAL so it didn't construct itself upon creation.

A: Take this a stage further. If I understand you correctly we have:
Application Starts

User specifies some database settings

Repository initialises, passwords etc are checked

Application now uses repository

My immediate thought is, hmmm, wonder whether we can also get
User decides "I don't like that repository"

User specified new database settings

New repository is initialised

Application closes previous repository, and starts working with new one.

Now it may be that this is slightly more flexible than you had planned, but it leads me to thing that you have effectively two applications, with a transient relationship between them. There's the "shell", which is independent of the repository, that's the bit that starts up without a repository. Then there's the extra piece that works only when it's got a repository, and I think is seems to be pluggable, at least in concept.
Hence I don't think your shell is so much  being "Injected" as responding to interesting events such as:
Here is a repository, if you already have one please close it

Shut down, please close down your repository, and then yourself.

If you have a Event Interface I think you get what you need. The arrival of an Event is in effect an Injection.

A: See how I would do it.


text:
Q: Conditionally replacing specific values from a list R I am relatively new to R so please go easy on me!
I have a list of items, for example lets say:
Name   Location
AB     1
CD     20
EF     45
...and so on for about ~17,000 items.
However, I also have a list where some of these items have updated locations and names- but not all of them. For example, in this list
Name   Location    Updated_Name
AB     1                        (Same)
CD     32          EGG          (Changed)
EF     42          OOL          (Changed)
IS there a function where I can search by the 'original' name/location, and for those which are 'changed', replace the old name/location-- and where the 'original' name/location are the same, keep these? I would need to retain the positioning/order of the list.
I would really appreciate some help with this!


text:
Q: Adding an auto brush to the d3 timeline chart I am working on a d3 timeline chart -- but on load - I want the brush to be automatically deployed -- with the option of fine-tuning on a particular set of in/out dates

https://jsfiddle.net/nu1z4d3r/
https://jsfiddle.net/2y8gkas3/8/  -- latest example --
I've tried adding the -- draw brush logic to the bottom of the code base
https://bl.ocks.org/micahstubbs/3cda05ca68cba260cb81

*

*what would be the correct values to make this work -- should xTop be x2?
function drawBrush(a, b) {
  // define our brush extent
  // define our brush extent

  // note that x0 and x1 refer to the lower and upper bound of the brush extent
  // while x2 refers to the scale for the second x-axis, for the context or brush area.
  // unfortunate variable naming :-/
  var x0 = xTop.invert(a*w)
  var x1 = xTop.invert(b*w)
  console.log("x0", x0)
  console.log("x1", x1)
  brush.extent([x0, x1])

  // now draw the brush to match our extent
  // use transition to slow it down so we can see what is happening
  // set transition duration to 0 to draw right away
  //brush(d3.select(".brush").transition().duration(500));

  // now fire the brushstart, brushmove, and brushend events
  // set transition the delay and duration to 0 to draw right away
  //brush.event(d3.select(".brush").transition().delay(1000).duration(500));

}

    // call drawBrush once on load with the default value
//var zoomA = d3.select("input#a")[0][0].value;
//var zoomB = d3.select("input#b")[0][0].value;

var zoomA = 0;
var zoomB = -1;
drawBrush(zoomA, zoomB);

    /*
// update the extent and call drawBrush again
window.setTimeout(function() {
  d3.select("input#a")[0][0].value = .2;
  d3.select("input#b")[0][0].value = .7;
  var zoomA = d3.select("input#a")[0][0].value;
  var zoomB = d3.select("input#b")[0][0].value;
  drawBrush(zoomA, zoomB)
}, 2500);
*/

A: With the brush -- there were some modifications I had to make
https://jsfiddle.net/m6ueL79o/3/
where the brush is called -- we append a variable to the artefact. We make a 2nd call with "brush.move, x1.range()" -- this loads the scrubber
  var brush = d3.brushX()
  .extent([[0, 0], [w, miniHeight]])
  .on("brush", brushed);

  var gBrush = mini.append("g")
    .attr("class", "x brush")
    .call(brush)
    .call(brush.move, x1.range());

otherwise -- to load just the chart first -- do not have the .call(brush.move... and at the base add  "drawBrush(timeBegin, timeEnd);"


text:
Q: Kill all Gradle Daemons Regardless Version? Summary
I would like to know how to kill every single gradle daemon and process running on a machine regardless of the version of gradle or the version of the daemon, but the "--kill" or "--stop" command will only stop those processes that match the same version of gradle.
Use case
My CI build box will have several gradle daemons running with different versions (because I'm a good boy that uses the wrapper to execute builds). Occasionally I will find issues with caching or incremental builds, and as a precaution I like to kill the daemons. The same is true for my development boxes, although the conflicts are more often with whichever VCS or IDE I am using.
What I am looking for

*

*I'm hoping there is a flag or property I am missing that I could
pass to gradle to do this in a simple one line command, but if it's
simple enough I would be ok with more.

*No scripting (looping,
if-else etc).

*Killing all java processes is not acceptable.

Helpful links to the gradle docs
Disabling the Daemon
Stopping an existing Daemon

A: The gradle --status command will show you the process ids for each of the daemons. You can then use your OS to kill those processes.
I'm assuming this is cross-platform functionality, but this is the output on Windows:
  PID STATUS   INFO
10276 IDLE     5.4.1
14068 IDLE     5.4.1

It's a bit better than playing whack-a-mole with every java.exe process running on your system. Although it would be nice if gradle had a command that could terminate all running gradle daemons built-in.

A: I have a similar problem and I made this:

*

*Go To C:\Users\"Username"\.gradle\daemon

*There are a Folder for each version of gradle

*Delete the folder of your actual running version
Check with --status

A: Under linux you may use pkill:
pkill -f '.*GradleDaemon.*'

Under windows you may use wmic:
WMIC PROCESS where "Name like 'java%' AND CommandLine like '%GradleDaemon%'" Call Terminate

PS. Why "no scripting" when it is probably the easiest solution?

A: The gradle daemons did not disappear after 3hrs; this could be since I am running as Linux Guest in VirtualBox.
And hence, the following removes all gradle daemons but it could be "frowned upon" since it might be excessive...
(1) ./gradlew --stop   to ensure all daemons are stopped
(2) delete all folders/files in .gradle folder in the project
(3) delete .gradle folder in /home/username/
Linu
(4) reboot
All daemons are gone. The next build takes a bit longer but worthwhile as do not like seeing 6 stopped daemons everytime a gradle build or even clean is started.


text:
Q: How can I manage a list from Parent component in React and render it? I have a reactjs application.
In this I want to manage a list from parent component.
This application can add a object to list, delete it from list and show added objects in a table.
My problem is that I can add an object, but must refresh the whole page that it is shown in the list.
The two way binding not work and I don't know how to implement it.
I hope you can help me.
class Wrap extends React.Component{

    constructor(){
        super();
        this.state = {
            player: []
        };

    }

    render(){
        return(

            <Create />

        );
    }
}

class Table extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      player: []
    };
    this.deletePlayer = this.deletePlayer.bind(this);
  }

  componentDidMount() {
    axios.get('http://localhost:8081/player')
      .then(res => {
        this.setState({ player: res.data });
        console.log(this.state.player);
      });
  }

  deletePlayer(id) {
     fetch(`http://localhost:8081/player/${id}`, {
      method: 'DELETE',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    }).then(() => {
      let updatedPlayers = [...this.state.player].filter(i => i.id !== id);
      this.setState({player: updatedPlayers});
    });
  }

class Create extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: '',
      ownerid: ''
    };
  }
  onChange = (e) => {
    const state = this.state
    state[e.target.name] = e.target.value;
    this.setState(state);
  }

  onSubmit = (e) => {
    e.preventDefault();

    const { name, ownerid} = this.state;

    axios.post('http://localhost:8081/player', { name, ownerid})
    .then(() => this.setState(() => ({
    })))
  }
```

A: Add your .get call in a method in parent component and pass it as props. Use it to refresh your list.
    class Wrap extends React.Component {

        constructor() {
            super();
            this.state = {
                players: []
            };
        }
        getData = () => {
            axios.get('http://localhost:8081/player')
            .then(res => {
                this.setState({ players: res.data });
            });
        }

removePlayerFromState = (id) => {
    let updatedPlayers = [...this.state.players].filter(i => i.id !== id);
  this.setState({players: updatedPlayers});
    }
        render() {
            return (

                    <Create getData={this.getData}/>

            );
        }
    }
    class Table extends React.Component {
        // use this.props.players
    }
    class Create extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                name: '',
                ownerid: ''
            };
        }
        onChange = (e) => {
            const state = this.state
            state[e.target.name] = e.target.value;
            this.setState(state);
        }

        onSubmit = (e) => {
            e.preventDefault();

            const { name, ownerid } = this.state;

            axios.post('http://localhost:8081/player', { name, ownerid })
                .then(() => this.props.getData())
        }
    }


text:
Q: Set up different static IP addresses for different networks I'm relatively inexperienced with networking, but I know what I want to achieve in this case. I have a computer that I physically move between two separate local networks, but when the computer is on one of those networks I want to assign a different static IP address to the machine.
One internal network is 192.168.1.0, and the other is 192.168.2.0. Therefore, I want one static IP address to be 192.168.1.x and the other to be 192.168.2.x.
Is there a way of assigning two static IPs, but with only one taking effect depending on the network its connected to? Can this be done purely in /etc/network/interfaces, for example?
I may well have misunderstood the situation, so if there's a different way of achieving what I want then I'm happy to hear the solution.

A: There may be better solutions (at least ones closer to what you're asking for) but here's what springs to my mind:

*

*Configure the DHCP servers at each location to assign your MAC address a static IP, and on the laptop, just have it automatically grab the IP from DHCP. This is by far the easiest if you have router access at each place.

*The next three are essentially the same solution as each other - split the connections up:

*

*Add and use a different network card for one location.

*Leave USB network cards on the two ethernet cables (slower than native gigabit).

*Use two wireless connections. Network Manager can do the hard stuff automatically so you just roam from one place to another.

*Script something for when the interface comes up. I don't know what the event would really be called - but you essentially want to know when the cable is plugged in and the whole thing is ready to go. You could just have a static setup for one network and wait for when that comes up.

*

*Bind in using upstart if you know the connection is there on boot, or consider this Call script after connecting to a wireless network if you make the connection after boot.

*When the network is up, do some service discovery. Is the gateway where you expect it? Are there other known servers you should be able to ping?

*If everything is correct, leave the configuration as it is, otherwise switch to the alternative network configuration. You can either manually set this up using ifconfig or you can have two connections set up in Network Manager and just use nmcli to switch which one you're on.
Out of the three, DHCP is the easiest.

A: You should create a Virtual interface and assign an IP address to it.
If you want to configure more Static IP address you need to edit the

/etc/network/interfaces

and you need to enter the following lines replace eth0 with your network interface card.
The primary network interface
auto eth0
iface eth0 inet static
address 192.168.1.2
gateway 192.168.1.1
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255

The virtual network interface
To assign a second IP address to your  machine  you need to edit again  the /etc/network/interfaces file. The second IP is named eth0:0, the third one eth0:2 and so on... So just add them in the file:

sudo vi /etc/network/interfaces

auto eth0:0
iface eth0:0 inet static
address 192.168.2.2
netmask 255.255.255.0
gateway 192.168.2.1

After entering all the details you need to restart networking services using the following command

sudo /etc/init.d/networking restart


text:
Q: Apache2 is serving "download" document instead of website I updated my Ubuntu server this morning from 20.04 to 22.04. Apache2, PHP, Mysql all got updated in the process. I have Cacti installed on this server to monitor a few of our switches and firewall. After the OS update, when I try to visit the Cacti site, Edge, Safari, Firefox, etc etc, all try to download a file called.. "download". It the index.php of the cacti directory.
Thinking PHP wasn't installed, I set up a test.php with the phpinfo(), and it serves it fine.
I'am not the best at Apache2 configs, but I've been digging all day to get my Cacti server back up and running.
PHP went from 7.4 -> 8.1
I did update the cacti install, thinking that could have been the issue, but its the same problem.
Looking for some help before I just blow this server away and start over.

A: probably one of these commands
sudo apt install apache2-mod-php
sudo a2enmod php8.1
sudo apache2 restart


text:
Q: Regex undesireably removing substring I'm trying to extract void <init>(java.lang.String) and java.io.File getOutputMediaFileUri(int) from the string below (and strings like it).
specialinvoke $r1.<java.io.File: void <init>(java.lang.String)>($r16)@<com.jpgextractor.PicViewerActivity: java.io.File getOutputMediaFileUri(int)>

Currently, I'm matching to the regex:
/.*<.* (\S+ .*)>.*<.* (\S+ .*)>.*/

Which works, except for instead of void <init>(java.lang.String) I just get void (java.lang.String).
I'm a bit mistified where <init> has gone off too...I've tried several different ways to coax it back, but so far no luck.
Thanks folks!

A: The issue was nothing to do with the regex; as pointed out by acdcjunior and nhahtdh, the regex was operating correctly, but the issue was in displaying the text. I was putting the output void <init>() into a web page as unescaped HTML, where <init> was interpreted as an HTML tag; the <> characters should be escaped.
See Fastest method to escape HTML tags as HTML entities? for information on escaping such tags.


text:
Q: Query with JOIN on multiple tables I have this little query that is working fine:
SELECT * FROM Components AS T1
WHERE Cost=null or Cost=''
Order by Code

Now I need to grab also the filed "description" from other tables where code=code
SELECT * FROM Components AS T1
WHERE Cost=null or Cost=''

LEFT JOIN on Table_321 AS T2
where T1.Code=T2.Code

Order by Code

But it is giving me a sintax error around "LEFT" which I have not been able to solve and I am not sure if such JOIN is the correct way to get it. Some help indicating me the how to solve the problem will be really appreciated. Moreover, I have also another table "Table_621 from which I need to take the description. How can I add this second table in the query?

A: SELECT * FROM Components T1
LEFT JOIN Table_321 T2 ON T1.Code=T2.Code
LEFT JOIN Table3 T3 ON T3.Code = T1.Code
WHERE T1.Cost=null or T1.Cost=''
ORDER BY T1.Code

A: SELECT * FROM Components AS T1
LEFT JOIN Table_321 AS T2
ON T1.Code=T2.Code
WHERE Cost=null or Cost=''

Order by Code

A: Order by is ambiguous In below case:
SELECT * FROM Components T1
    LEFT JOIN Table_321 T2
    ON T1.Code=T2.Code
    WHERE T1.Cost=null or T1.Cost=''
    ORDER BY Code

try like this
SELECT * FROM Components T1
        LEFT JOIN Table_321 T2
        ON T1.Code=T2.Code
        WHERE T1.Cost=null or T1.Cost=''
        ORDER BY T2.Code --or T1.Code


text:
Q: Admob Integration I'm trying to add admob to my app and I'm confused with step 4 which is

Under Other Linker Flags, add -all_load to both Debug and Release.

Is that under OTHER_LDFLAGS? How would I exactly do this? Thanks!

A: Do this:
1. Go to target seetings of your project.

2. Now go to Build settings. In Search bar type " Other Linker Flags ". As shown below in image will appear on screen.

Now add -all_load to both Debug and Release.

A: Check this image to set Other Linker flag. hope helps.


text:
Q: Update driver for scangearmp2-3.50-1-deb The scangearmp2 application in scangearmp2-3.50-1-deb does not work with Ubuntu Mate 20.04.
My printer is a Canon TS9120.
The Canon site has no newer driver listed.
I need help in finding a newer driver if it exists.


text:
Q: How come my desktop computer is still on kernel 3.13.0-63-generic, when current version is 3.13.0-70? It used to update nicely, until 63.
I have other computers on Lubuntu and Xubuntu, and they are both still updating correctly.

A: You can try updating the kernels that have been downloaded then update your grub file.
When I checked the apt-cache for the kernel, it returned the following:
apt-cache policy linux-headers-3.13.0-70-generic
linux-headers-3.13.0-70-generic:
  Installed: 3.13.0-70.113
  Candidate: 3.13.0-70.113
  Version table:
 *** 3.13.0-70.113 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty-updates/main amd64 Packages
        500 http://security.ubuntu.com/ubuntu/ trusty-security/main amd64 Packages
        100 /var/lib/dpkg/status

from what I can see the kernel files come from trusty-updates main and trusty-security main.
Edit your /etc/apt/sources.list and make sure that the following lines are not commented # out or make sure that they exist:
deb http://us.archive.ubuntu.com/ubuntu/ trusty-updates main restricted
deb http://security.ubuntu.com/ubuntu trusty-security main restricted

Run the following to make sure the newest kernel is downloaded:
sudo apt-get update
sudo apt-get dist-upgrade

Also from our conversation, install the generic kernel:
sudo apt-get install linux-generic-lts-trusty

If it installs the kernel correctly, there would be no reason to go any further than here.

To update the current installed kernels, from a terminal prompt type in:
sudo update-initramfs -u -k all

You should see something like:
update-initramfs: Generating /boot/initrd.img-3.19.0-33-generic
update-initramfs: Generating /boot/initrd.img-3.13.0-70-generic

Then type in the following to update grub:
sudo update-grub

If the kernel was installed correctly, you should see something similar to the following:
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-3.19.0-33-generic
Found initrd image: /boot/initrd.img-3.19.0-33-generic
Found linux image: /boot/vmlinuz-3.13.0-70-generic
Found initrd image: /boot/initrd.img-3.13.0-70-generic
Found memtest86+ image: /boot/memtest86+.elf
Found memtest86+ image: /boot/memtest86+.bin
Found Windows 10 (loader) on /dev/sdd1
done

Once you have seen
Found linux image: /boot/vmlinuz-3.13.0-70-generic
Found initrd image: /boot/initrd.img-3.13.0-70-generic

reboot your system so it will boot to the 3.13.0-70-generic kernel.
Hope this helps!


text:
Q: Can I use Amiibo as a playable character in Smash? I recall seeing an ad of bunch of teenagers playing Smash as their Amiibo characters, but I can't seem to find a way to actually do it.
I know I can play in a team with Amiibo and have it be controller by the CPU, but is it possible to control it myself?

A: It is impossible to control the Amiibo character.
I checked the electronic manual and it specifically mentions that Amiibo can be used as a Figurine Player and cannot be controlled.

A: I checked Nintendo's FAQ on amiibo, and confirm you can't play as your amiibo.  I felt so let down when I saw that you cannot use your them as a player.  It's like you have your own Poke'mon but for Smash Bros.

A: Unfortunately, no you can't. Trust me, I just figured this out as well. They're like a pet, you can train them and battle other pets. I bought 5 today. It's like a Pokemon I can train it and everything. Until I log on and find out all I do is watch it fight and level up. You can't play as them, but you can fight beside them. But still, I just spent about $60, and the commercial on TV showed teens playing as their Amiibo, which is apparently wrong. So you can not be them.


text:
Q: Can I use my existing SSL certificates on a new server with Plesk? We are migrating to a Virtual Private Server running on Ubuntu 8.04 LTS and with a Plesk configuration panel.
We have some valid SSL certificates on the old server, which I would like to use on the new configuration. I have the CSR, private key, certificate and CA-certificate.
I cannot find a way to change the CSR and private key in the Plesk configuration panel.
Anyone know, if this is possible and how?

A: On my Plesk 9.3 server, when I attempt to add a certificate, it prompts me for the Private Key, Certificate, and (optionally) the CA Certificate.  If you have those three components, you should be good to go.  You don't need the CSR if you already have a signed cert.
Note that you have to skip the first option on the page -- which allows you to Request, Buy, or Self-Sign a certificate.  Further down the page, there are options to either upload or paste in the three blocks for existing certificates.
I checked my Plesk 8.4 server, and the UI is pretty much the same.

A: I cannot say for sure with Plesk, but in CPanel it is not possible to use the old data. I think the question you should ask is how do you change the CSR and pk data in Plesk.

A: Every CSR is different, you will have to make a new one.
Go to the website of the company issuing the SSL certificate and look for the redeem option.
This will let you enter a new CSR and make it valid on a new server. At least this is what I did.

A: Not sure what version of Plesk you are using , but this should help you out. Link Here!!


text:
Q: The process of updating a "Normal Release"? I was amazed to see 13.04 "just work" when it came to getting my wireless internet up and running.  Not sure if it was the firmware or the drivers or just having a very up-to-date linux kernel... but I digress.  The short term support concerns me a little.
Am I going to need to keep a spindle of CD/DVD's with me at all times to always be updating (every 6 months or so)?
Is it possible to update cleanly without having to completely wipe out my existing install?
Is there any way to go from 13.04 to 13.10 (or any future releases) purely through updates, as opposed to completely replacing the operating system?
Thanks guys!

A: I wouldn't recommend any rolling release of Linux to a new user. It's easy to break your system with a rolling release, and then you may have to reinstall the operating system anyway. Compare this with installing a Long Term Support release which only takes about a half an hour, and is supported by updates for a 5-year term of support. The latest Long Term Support release of Ubuntu is Ubuntu 12.04 which is supported by updates until April, 2017.
Regarding your other questions: no, Ubuntu does not have rolling releases. It is possible to do an operating system upgrade to the next available release in the 6-month release cycle, and in addition to that it is possible to upgrade a Long Term Support release of Ubuntu to the next available Long Term Support release.


text:
Q: Why does the ansible option "--private-key" works on one host but not on another? I installed ansible 2.8.0 on VM-1 without modifying any other default configs in ansible.cfg except the "host_key_checking = false".
Then I ran ansible all -i "<IP of VM-3>," --private-key <key of VM-3> -u root -m ping with OK on VM-3, but ran ansible all -i "<IP of VM-2>," --private-key <key of VM-2> -u root -m ping with ERROR on VM-2.
I generated a pair of ssh-key on VM-2 (user is root) and copy its private key (id_rsa) content to VM-1. I save it in a file named 'key', and set this file's mode to be '700'. Finally, I ran the command below:
ansible all -i "<ip of VM-2>," --private-key key -u root -m ping

It works wrong. The error info is:
/opt # ansible --version
ansible 2.8.0
  config file = /opt/ansible.cfg
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.6/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.6.8 (default, Apr  8 2019, 18:17:52) [GCC 8.3.0]
/opt # ls
ansible.cfg  key
/opt # ansible all -i "192.168.100.100," --private-key key -u root -m ping
192.168.100.100 | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: root@192.168.100.100: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).",
    "unreachable": true
}

Then I turned to use option "-k" instead, and it works.
/opt # ansible all -i "192.168.100.100," -k -u root -m ping
SSH password:
192.168.100.100 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

Then I tried again on VM-3 with the same steps of VM-2. The command using "--private-key" works. The environment of VM-2 and VM-3 are very similar.
I didn't find any difference between VM-2 and VM-3's sshd configure at all.
So I got very confused with these above.
In addition, the "--private-key" command will be OK after the "-k" command was run, because there is a ansible process living on the background, like this:
/opt # ansible all -i "192.168.100.100," -k -u root -m ping
SSH password:
192.168.100.100 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
/opt # ps -ef |grep ansible
  126 root      0:00 ssh: /root/.ansible/cp/e42d5dc861 [mux]
/opt # ansible all -i "192.168.100.100," --private-key key -u root -m ping
192.168.100.100 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

I want to know how to use "--private-key" correctly in ansible command line.


text:
Q: Which App Store, the user is logged into Is it possible to detect which App Store (US, German, UK, France...etc) the user is logged into on his device?
Thanks

A: With this snippet of code you can determinethe users country. So that means that in most cases the store is also set to the country they live in.
- (NSString *)getUserCountry {
    NSLocale *locale = [NSLocale currentLocale];
    return [locale objectForKey: NSLocaleCountryCode];
}

For example this can return the Netherlands or England if you live in the Netherlands or England,


text:
Q: Kubernetes - apiservice Available=False I'm currently running Kubernetes cluster in Azure. I am having an issue where my metrics-server is saying  False (FailedDiscoveryCheck)when running kubectl get apiservice. I have tried restarting the cluster, the services and pods relating to the server, to no avail. Does anyone know any troubleshooting steps I can take or how I can restart this specific apiservice?
Thanks,


text:
Q: ffmpeg scale, overlap & opacity How do I chain several filters into one video?
Basically - I have an overlay image (transparent gif), want to center it, and apply an opacity of 30% to the gif. This is what I have:
ffmpeg -i inputmovie.mov -i transparentgif.gif -filter_complex "[0]scale=1280:-2[bg];[bg][1]overlay=main_w-overlay_w-200:main_h-overlay_h-200" -b:v 1500k outputvideo.mp4
(Basically, I want the output video to be 1280x760 (input is 4k)
then the gif overlay to be centered, and specify the alpha/opacity/transparency).
But I am not sure how/where to add this in that command line:
blend=all_mode='overlay':all_opacity=0.3[v]
Could you please help? Thanks very much!
PPS - what would be REALLY nice is if there was some kind of way I could do this in "batch", i.e.,
say: video1.mov
video2.mov
etc
and output it as
output_video1.mov
output_video2.mov
etc.

A: Almost there. You can use the colorchannelmixer filter to set transparency for the GIF.
ffmpeg -i inputmovie.mov -i transparentgif.gif -filter_complex "[0]scale=1280:-2[bg];[1]colorchannelmixer=aa=0.3[gif];[bg][gif]overlay=(main_w-overlay_w)/2:(main_h-overlay_h)/2" -b:v 1500k outputvideo.mp4


text:
Q: How to see which device uses which kernel module? I have a Samsung phone GT-B3210. For some time I was unable to find working Windows drivers for it. I eventually gave up looking. Then one time I was charging phone over its USB port and booted Ubuntu and was pleasantly surprised when I saw phone's μSD card reader on my desktop.
I now need to switch to Gentoo and would like to be able to work with phone there too. Lsusb tells me it's detected as
Bus 007 Device 006: ID 04e8:663f Samsung Electronics Co., Ltd SGH-E720/SGH-E840
but lsmod wasn't very helpful. On the list of loaded modules, I wasn't able to find one which looks like it's related to the phone.
Is there some other way to see which  module is used by the telephone?

A: The USB device should appear under /sys/bus/usb/devices as several entries beginning with 7-6 or something similar. Where the driver link within the directories point will be the name of the module bound to the device.

A: I find lsusb easier and faster to use in such situations.  Example output follows:
 $ lsusb -t
/:  Bus 04.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/2p, 5000M
/:  Bus 03.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/2p, 480M
/:  Bus 02.Port 1: Dev 1, Class=root_hub, Driver=ehci-pci/3p, 480M
    |__ Port 1: Dev 2, If 0, Class=Hub, Driver=hub/8p, 480M
...

If no driver is used, the line will look like this (the device in my example is a camera for which I did remove the driver from the kernel):
    |__ Port 6: Dev 4, If 1, Class=Video, Driver=, 480M


text:
Q: how to convert a given level of a binary search tree into a linked chain? I have to do a function where, given an int n and a binary search tree, i have to convert the level n of the bst int a linked list.
for example if given the numer 2 and this tree
      2
     /  \
    5    3

i have to make a liked list with 5 - 3
I have problems getting to the level given, and then getting each node on that level, because if i do reach the level i don't know how to reach the next node. Meaning, i can only get to the level on only one branch, and i cant think of any way to do it recursively.
so this is the struct for the bst and the linked chain:
struct nodo {
    info_t dato;
    nodo *anterior;
    nodo *siguiente;
};
struct rep_cadena {
    nodo *inicio;
    nodo *final;
};
struct rep_binario {
    info_t dato;
    rep_binario *izq;
    rep_binario *der;
};

and this is the function i cant figure out:
cadena_t nivel_en_binario(nat l, binario_t b)

i have tried using another function i already made, that calculates the height of a tree, but i can't stop on the wanted level.
nat altura_binario(binario_t b) {
    if (b==NULL) return 0;
    else return maximo(altura_binario(b->izq), altura_binario(b->der))+ 1;
    }

where maximo() returns the highest number between the two given numbers.

A: You can do this by implementing Breadth-first_search algorithm, and modifying a little bit. Instead of enqueuing just nodes, you can enqueue pairs of (node, level) (where node level = parent level + 1), and then when enqueuing you can check if you have reached the desired level, and just output it as the result instead of queuing it further.
Pseudocode sketch:
target_level = ...read from input...

let level_nodes = ...an empty list...

let queue = ...an empty queue...
queue.enqueue((root_node, 0))

while queue is not empty:
    node, level = queue.dequeue()
    if level == target_level:
        level_nodes.append(node)
    else:
        if node has left child:
            queue.enqueue((left_child_node, level + 1))
        if node has right child:
            queue.enqueue((right_child_node, level + 1))


text:
Q: Jquery AJAX - Update span of text when this button is clicked I've been trying to figure out how to use ajax in this simple function.
I have a span that displays how many songs a user has in their playlist. It's simply showing how many values exist inside of a localStorage key.

We are using jPlayer and we have a playlist set up. When you remove a song from the playlist (by clicking a remove button), we would like to update the contents of that div, "count-songs-span", with the new count. For now, it only works when we refresh the page, but we'd like it to update using ajax.
We have added a click event for the remove button here:
$('.jp-playlist').on('click', '.jp-playlist-item-remove', function(){
    window.setTimeout(updatePlaylist, 500);
});

updatePlaylist() is as follows:
function updatePlaylist(){
      playlist = myPlaylist.playlist;
      storage.set( 'playlist', playlist );
    }

The click event is saving the list to localStorage, and that's fine. But before that, we'd like to update the countSongs variable with ajax.
I have this snippet from another website, and I've tried to adapt it to my site, but I just can't get it to work. It's just not the right code for my site.
$.ajax({
           type : "get",
           dataType : "json",
           url : ajax_object.ajaxurl,
           data : {action: "get_media", id : id},
           success: function(obj) {
              if(obj.length == 1){
                player.add( obj[0], true );
                updatePlaylist();
              }else if(obj.length > 1){
                player.setPlaylist(obj);
                player.play(0);
                updatePlaylist();
              }
           }
        });

Can anyone help me use ajax to update the "count-songs-span"?
Thanks so much if you can help.

UPDATE:
Here is a demo of what is being stored.
The method to store the playlist data:
function updatePlaylist(){
      playlist = myPlaylist.playlist;
      storage.set( 'playlist', playlist );
    }

Anywhere we need to store the playlist information, we call that method - updatePlaylist()
This is an example of what is being stored:
[{"title":"Mauvais Temps","artist":"Right Beat Radio","mp3":"/mp3s/MauvaisTemps.mp3"},{"title":"Line Steppers","artist":"Right Beat Radio","mp3":"/mp3s/LineSteppers.mp3"},{"title":"Try My Best","artist":"Right Beat Radio","mp3":"/mp3s/TryMyBest.mp3"},{"title":"San Ignacio","artist":"Right Beat Radio","mp3":"/mp3s/SanIgnacio.mp3"}]

So when we want to count the number of songs in the playlist, we use this (the localStorage key is called "playlist":
var countSongs = JSON.parse(localStorage.playlist).length;
document.write(countSongs);

UPDATE #2:
Screenshot:
https://rightbeatradio.com/wp-content/uploads/2015/09/Screen-Shot-2015-09-07-at-9.13.34-AM.png
Hopefully this screenshot will help. You can see the playlist there, and above that, you will see the number of songs currently in the list (7 songs).
Beside each song on the list, there's a remove (x) button. This button allows a user to remove a song from the list.
Upon clicking that button, these functions fire:
//Remove Item from Playlist
    $('.jp-playlist').on('click', '.jp-playlist-item-remove', function(){
      window.setTimeout(updatePlaylist, 500);
    });

// update playlist
    function updatePlaylist(){
      playlist = myPlaylist.playlist;
      storage.set( 'playlist', playlist );
    }

Somewhere in there, we'd like to also count the number of items in the localStorage, "playlist" key, and update the count by using ajax.
Here's the HTML of the span that counts the number of songs in the playlist:

The only time that script is being called is when we refresh the page. We'd like that countSongs script to be called when the remove button is clicked, and update the count within that span using ajax.

A: I figured it out by using the jquery .load() function instead of using ajax directly.
It takes 3 files to accomplish this.

*

*The actual HTML document that displays the page (page-listen.php)

*The javascript file that houses all of my jPlayer js functions (demo.js)

*The html document that will run the code that is loaded with .load() (countthesongs.html)

I'll post the important section of each document, with comments.

page-listen.php (This span will act as the container that will display the number of songs that are currently in the users playlist.)

When the page is first displayed, the number of songs that are in the playlist will be counted and shown to the user inside of the span called "count-songs-span".

demo.js (These are the jPlayer functions that are doing the heavy lifting.)
  // Function to store the playlist in LocalStorage
    function updatePlaylist() {
      playlist = myPlaylist.playlist; // define playlist variable
      storage.set( 'playlist', playlist ); // store the playlist in localStorage as "playlist"
    }

  // Function to count the number of songs and print to the container
    function countTheSongs() {
    $( "#count-songs-span" ).load( "/js/jPlayer/countthesongs.html", function() {
        var theDiv = document.getElementById('count-songs-span'); // Assign the count-songs-span container we discussed earlier to a variable called theDiv
        theDiv.innerHTML = theDiv.innerHTML + countSongs; // Print the results of countthesongs.html using jquery .load() function
      });
  }

  // Function to remove an item from playlist
    $('.jp-playlist').on('click', '.jp-playlist-item-remove', function(){
      window.setTimeout(updatePlaylist, 500); // Store the playlist in localStorage with new number of songs, on a delay
      window.setTimeout(countTheSongs, 550); // Display the number of songs in the count-songs-span container
    });

countthesongs.html (This is the HTML file that runs the short script to count the number of songs in the playlist.)

So to make sense of these 3 documents, here's what's happening:

*

*A user removes a song from the playlist by clicking the remove
button.

*The function to remove an item from playlist is fired, which stores the new number of items to localStorage (updatePlaylist()), then counts and prints that new number to it's container on the page (countTheSongs()).

Using the .load() function, we're able to display the number of songs on the playlist as a user removes items, without the page reloading, just as it would if we would have used ajax.
Hope this helps someone. Sorry if it's a little confusing.


text:
Q: Spring Setter Injection on shadowed fields I want to shadow a variable and change its type from boolean to string in its child class. Yet, the setter injection fails. I know it is a bad practice to use shadowing, however I would like to know if it is possible and how.
Example what I would like to do:
public class A {

    public boolean field;

    @SuppressWarnings("javadoc")
    public boolean isField() {

        return field;
    }

    @SuppressWarnings("javadoc")
    public void setField(boolean field) {

        this.field = field;
    }
}

I want to shadow the attribute 'field' to be a String in the subclass.
public class B extends A {

    private String field;

    @SuppressWarnings("javadoc")
    public String getField() {

        return field;
    }

    @SuppressWarnings("javadoc")
    public void setField(String field) {

        this.field = field;
    }
}

I get an exception that the setter Injection does not work:
org.springframework.beans.TypeMismatchException: Failed to convert property value of type [java.lang.String] to required type [boolean] for property 'field'
<bean id="exampleBean" class="B" >
                <property name="field" value="value"/>
            </bean>

A: Though I haven't tested it. But you can try the following way.
<bean id="beanA" class="A">
    <property name="field" value="false"></property>
</bean>
<bean id="beanB" parent="beanA" class="B">
    <property name="field" value="anyValue"></property>
</bean>

Let me know If it works for you.
Edit-
Please go through the Bean definition inheritance doc.
I have tested the example for shadowed field that you are using. You must have to configure a bean for parent class as well, because if you only configure bean for child class, you would get exception below -
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'helloWorld' is defined

I don't know what you are trying to accomplish using so-called shadowed fields. But here I have created a working example which might help you. Check it out.
MainApp.java
package com.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
    public static void main(String args[]){
        ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

        HelloWorld hw = (HelloWorld) context.getBean("helloWorld");
        System.out.println("Is message:" + hw.isMsg());

        HelloCountry hc = (HelloCountry) context.getBean("helloCountry");
        System.out.println("Message:" + hc.getMessage());

    }
}

class HelloWorld {
    private boolean message;

       public void setMessage(boolean message){
          this.message  = message;
       }

       public boolean isMsg(){
           return message;
       }
}

class HelloCountry extends HelloWorld {
    private String message;

       public void setMessage(String message){
          this.message  = message;
       }

       public String getMessage(){
           return message;
       }
}

Beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <!-- A parent class bean must be defined to create its instance -->
   <bean id = "helloWorld" class = "com.example.HelloWorld">
      <property name = "message" value = "false"/>
   </bean>

   <bean id = "helloCountry" class = "com.example.HelloCountry">
      <property name = "message" value = "Hello Country!!!"/>
   </bean>

</beans>

Output

Note-
You would get a below exception only when you pass any value other than boolean in your parent bean. In your case, your data type of child class field is matching with the injected bean value, but you must have to have a configured bean for parent class as well. In short this is how It works Dependency Injection in case of Inheritance.-
Caused by: org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.lang.String' to required type 'boolean' for property 'message';

Let me know If it was helpful.


text:
Q: Assigning a docker container a static private ip to access it without port forwarding My laptop has an ip address of 10.0.0.128 on the local network. I'm trying to assign a docker container it's own ip address within the same range(?) for example, 10.0.0.135. In order to do this, I tried creating a new bridged network in docker; however, I keep encountering an error.
docker network create -d bridge --subnet 255.255.255.0/24 --gateway 10.0.0.1 testnetwork
no matching subnet for gateway 10.0.0.1

I've looked at a couple of other examples, and have only got it to work when specifying an ip starting with 172, like in the following example.
docker network create -d bridge --subnet 172.25.0.0/16 testnetwork
docker run -d --net=testnetwork --ip=172.25.3.3 nginx

But I'm still unable to access the nginx server directly with the ip, and have to use port forwarding instead. Is there a way to assign a docker container an ip that I can use to access the container without port forwarding?


text:
Q: Spark error java.lang.NoSuchMethodError: scala.Predef$.refArrayOps Using Sparklyr, I'm trying to do a spark_connect(master="yarn"), but I'm receiving this error:
Exception in thread "main" java.lang.NoSuchMethodError: scala.Predef$.refArrayOps([Ljava/lang/Object;)Lscala/collection/mutable/ArrayOps
...
Error in spark_connect_gateway(gatewayAddress, gatewayPort,sessionId,   :
   Gateway in localhost:8880 did not respond

I have Spark version 2.4.8 and Scala version 2.12.10. I'm running on a Google DataProc cluster using these version specs. I'm using Sparklyr version 1.3.1.


text:
Q: Are there stable string theory vacua with non-minimal cosmological constant? Naive reasoning suggests that a string theory vacuum with cosmological constant Lambda1 is always unstable as long as there is a string theory vacuum with cosmological constant Lambda2 < Lambda1 since the later is a state with lower energy density. If it's true, there should be very few stable vacua since these would be the vacua with the lowest possible cosmological constant. These vacua would probably have a Planckian-size cosmological constant and therefore be highly non-classical.
However, I suspect there is something wrong with this line of reasoning. Probably I am thoroughly confused about something.
Also, how to compare stability of vacua with different number of large dimensions? Comparing cosmological constants doesn't feel to make sense.

A: OK, I will bite on this one.
Suppose you have a quantum mechanical model with a metastable state: it is a local but not a global minimum of the potential. If your wavefunction is initially approximately localized near this so-called "false" vacuum, it will tunnel to the true vacuum sooner or later. This is a probabilistic event, the rate per unit time depends on details of the potential barrier, but if you wait long enough you'll eventually find yourself in the true vacuum.
In field theory this is slightly more complicated because you have to take into account the spatial dependence of the process. Suppose you start in the false vacuum everywhere, then there will be some probability amplitude anywhere in space to tunnel to the true vacuum, exactly as in quantum mechanics. This will result in formation of bubbles of true vacuum suspended in the false vacuum.
The fate of these bubbles depends on their size. The energetics of this is as follows: you gain energy by converting volume from false to true vacuum, but you lose energy because the surface of the bubble has surface tension (in other words interpolating from true to false vacuum costs some gradient energy). So, in flat space bubbles large enough expand out, percolate and eventually eat out the false vacuum, and small bubbles shrink and die. The calculation of tunnelling probability is explained by this classic Coleman paper.
Now, enter gravity. This is not only a quantum gravity process, it is a non-perturbative quantum gravity process, so in all honesty we do not know how to calculate anything about it with complete confidence. But for some intents and purposes, the extent of which is not entirely clear to anyone, you can use semi-classical methods. The standard reference for how to calculate this process semi-classically is this beautiful paper by Coleman and de Luccia.
The value of the potential at the minimum acts as a cosmological constant, so your intuition is that if two local minima exist with different cosmological constants, the higher one is metastable, it decays to the lower one. But this is not correct:
Relevant to your question is repeating the above energetics analysis. You still have volume versus surface competition, but now they are calculated in curved rather than flat spacetime, because you have to include backreaction on the geometry. This makes all the difference in the world: in flat space volume always scales faster than surface, so large enough bubbles always want to expand, resulting in complete conversion of false into true vacuum. Once we take curved spacetime effects into account you compare volume in one geometry to surface in another, and all kinds of things can happen; the detailed picture is quite complicated. In particular, it is no longer always true that the false vacuum necessarily is converted into true vacuum! In other words, some expected decays (for example decays into negative cosmological constant) do not actually happen once you take gravitational effects into account.
For more details I recommend you immerse yourself in these papers, they are beautiful and are known for their style as well as their content. I also have to apologize for not referring directly to string theory. None of this has to do directly with string theory, only with expectations we have from the semi-classical theory.


text:
Q: Retrieve choice values from lookup field in SharePoint2013 I am trying to retrieve choice values from a lookup field in SharePoint 2013 using REST API.
PFB the code:
$.ajax({
    url: _spPageContextInfo.webAbsoluteUrl+"/_api/web/lists/GetByTitle('Test')/fields?$filter=EntityPropertyName eq 'Category'",
    type: "GET",
    headers: {
        "accept": "application/json;odata=verbose",
    },
    success: function (data) {
        $scope.choices=data.d.results[0].Choices.results;
         alert();
    },

            error: function (error) {
        alert(JSON.stringify(error));
    }
});

This works fine for a normal choice field but doesnt work with Lookup field. Any solution?
Thanks,
Dheeraj

A: Use Expand option to retrieve Lookup column values.
_api/web/lists/getbytitle('project')/items?$select=Client/Name,ClientId,Name,Id&$expand=Client

In above example, Client is lookup column.
Refer this.


text:
Q: How can i reverse the order of hex in c++ To start with, I have a char array that store data
unsigned char dat[3];

memset(dat, 0, sizeof(dat));
memcpy(dat, &no, 2);

when I inspect dat, it contain a hex of 0xfd 0x01
as the value of no is 509, the hex should be 0x01 0xfd
I'm wondering should I be concern of the order of the hexadecimal,
should I change the order. Many thanks

A: Your system is little endian. It's hardware dependent and on little endian platform first byte is the least significant one  when treated as part of multi-byte value. Look up: https://en.wikipedia.org/wiki/Endianness
Essentially if CPU is little endian, then value 0x12345689 would be represented as set of bytes starting with 0x89. On big endian it's opposite order and on mixed endian it may change during run-time.

A: The question really is what do you want to do next ? On your current hardware (Little Endian) this is how the system orders bytes of a numeric. The least significant byte comes first: 0xfd 0x01.
In case you really want to swap this byte order, for whatever reason, checkout: How do I convert between big-endian and little-endian values in C++?


text:
Q: TypeError: can't multiply sequence by non-int of type 'str' >>>
Enter muzzle velocity (m/2): 60
Enter angle (degrees): 45
Traceback (most recent call last):
  File "F:/Python31/Lib/idlelib/test", line 9, in <module>
    range()
  File "F:/Python31/Lib/idlelib/test", line 7, in range
    Distance = float(decimal((2*(x*x))((decimal(math.zsin(y)))*(decimal(math.acos(y)))))/2)
TypeError: can't multiply sequence by non-int of type 'str'

I'm only new, so don't be too harsh if this is really obvious, but why am i getting this error?

A: >>> '60' * '60'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'

You are trying to multiply two strings together.  You must convert the string input from the user to a number using int() or float().
Also, I'm not sure what you're doing with decimal; it looks like you're trying to call the module (the type is in the module, decimal.Decimal) but there's not much point in converting to a Decimal after doing some floating point math and then converting back to a float.
In the future, post the code that causes the problem (and keep the interaction and traceback).  But first try and shrink the code as much as possible while making sure it still causes the error.  This is an important step in debugging.

A: You should convert the data you get from console to integers:
x = int(x)
y = int(y)
Distance = float(decimal((2*(x*x))((decimal(math.zsin(y)))*(decimal(math.acos(y)))))/2)

A: You are using raw_input() for getting the input.
Instead use input(). It will return an Int. Make sure that you input only numbers or input() will raise an error (say in case of a string).
Also, it would be nice if you name your variables properly. x and y don't convey much. (velocity and angle would be so much better)


text:
Q: How to purge the Database data and log files in MySQL? I want to purge the ibdata1, ib_logfile0 and ib_logfile1 files in MySQL. Because these files are taking too much space of my C:\ disk. And I don't want to move these files anywhere else in the Hard disk. I heard about purging which can shrink the data. I am using Windows Vista. What are the steps to be done to purge the data ?

A: The log files can be removed anytime. Only the most recent log is kept open/locked. However, deleting id_data will trash all of your InnoDB databases - that's the actual data store.

A: Short answer: There's no way to reduce the size of the ibdata files once they grew to a certain size. MySQL recommends dumping all innodb type data, shutting down mysql, deleting the ibdata files and restarting, then loading the data again. A one-click "compact" solution like other systems have is still missing.

A: As pointed out by MarcB, you can delete the (old) logfiles without problems; MySQL does not need them to run.
The data file ibdata* must not be deleted, it contains the actual database data.
I will grow as the database grows; unfortunately there is not way to shrink it, even if you later delete data from the database. The only way is to dump and reimport the whole database.
Also see this question: MySQL data file won't shrink
It explains various options to better cope with growing data files.


text:
Q: Why I can't use text editor to edit randomize_va_space I have did search and people say that I must use
sudo sh -c 'echo 1 > /proc/sys/kernel/randomize_va_space to edit this file. Can someone explain to me why?
When I use vim with root to edit this file and save it shows an error: "/proc/sys/kernel/randomize_va_space" E667: Fsync failed

A: The files in /proc are not regular files. They are in fact kernel variables exposed through filesystem for easier access. Because of that, they don't support all functions of "normal" files, namely, fsync.
The text editor doesn't know that it's dealing with a special file and tries to use some unsupported function. On the other hand, echo ... > file works because it does not use fsync function.
fsync is a function that tells the OS to write any pending changes from file to disk.


text:
Q: dimplejs 100 percent stacked vertical bar with two values by date I have a 100% stacked chart in google charts that I want to convert to dimplejs.
The two y values are a combo of two percentage values that equal 100%, but I only have one percentage value and the second should be the bar completing the other part to equal up 100%
The x series is a month/year combination.
Here is a functional attempt but notice I essentially duped my data to match what the example was expecting.
    var svg = dimple.newSvg("#chartContainer", 900, 400);
    var data = [
        {'YRMO': '01-01-2014', 'halfit': 'first', 'Percent':'24'},
        {'YRMO': '02-01-2014', 'halfit': 'first', 'Percent':'76'},
        {'YRMO': '03-01-2014', 'halfit': 'first', 'Percent':'31'},
        {'YRMO': '04-01-2014', 'halfit': 'first', 'Percent':'69'},
        {'YRMO': '05-01-2014', 'halfit': 'first', 'Percent':'20'},
        {'YRMO': '06-01-2014', 'halfit': 'first', 'Percent':'70'},
        {'YRMO': '07-01-2014', 'halfit': 'first', 'Percent':'28'},
        {'YRMO': '08-01-2014', 'halfit': 'first', 'Percent':'70'},
        {'YRMO': '01-01-2014', 'halfit': 'second', 'Percent':'76'},
        {'YRMO': '02-01-2014', 'halfit': 'second', 'Percent':'24'},
        {'YRMO': '03-01-2014', 'halfit': 'second', 'Percent':'69'},
        {'YRMO': '04-01-2014', 'halfit': 'second', 'Percent':'31'},
        {'YRMO': '05-01-2014', 'halfit': 'second', 'Percent':'80'},
        {'YRMO': '06-01-2014', 'halfit': 'second', 'Percent':'30'},
        {'YRMO': '07-01-2014', 'halfit': 'second', 'Percent':'72'},
        {'YRMO': '08-01-2014', 'halfit': 'second', 'Percent':'30'},
        ];

  var myChart = new dimple.chart(svg, data);
  myChart.setBounds(65, 45, 505, 315)
  myChart.addCategoryAxis("x", "YRMO");
  myChart.addPctAxis("y", "Percent");
  myChart.addSeries("halfit", dimple.plot.bar);
  myChart.addLegend(200, 10, 380, 20, "right");
  myChart.draw();

And what I am struggling with is how I can make this work:
    var data = [
        {'YRMO': '01-01-2014', 'Percent':'24'},
        {'YRMO': '02-01-2014', 'Percent':'76'},
        {'YRMO': '03-01-2014', 'Percent':'31'},
        {'YRMO': '04-01-2014', 'Percent':'69'},
        {'YRMO': '05-01-2014', 'Percent':'20'},
        {'YRMO': '06-01-2014', 'Percent':'70'},
        {'YRMO': '07-01-2014', 'Percent':'28'},
        {'YRMO': '08-01-2014', 'Percent':'70'}];

My JSFiddle....

A: Dimple's percent axis works based off of the sum of the values for that series/category intersection, so it will only work if, like you said, you jank with the dataset and add the complement values. It should be pretty easy to generate the opposite values :
var data = [
    {'YRMO': '01-01-2014', 'Percent':'24'},
    {'YRMO': '02-01-2014', 'Percent':'76'},
    {'YRMO': '03-01-2014', 'Percent':'31'},
    {'YRMO': '04-01-2014', 'Percent':'69'},
    {'YRMO': '05-01-2014', 'Percent':'20'},
    {'YRMO': '06-01-2014', 'Percent':'70'},
    {'YRMO': '07-01-2014', 'Percent':'28'},
    {'YRMO': '08-01-2014', 'Percent':'70'}];
//add property for first half (or put directly in data if possible)
data.forEach(function(row){
   row.halfit = 'first';
});

//create second half
var opposites = data.map(function(row){
    return { "YRMO" : row.YRMO,
        "Percent": (100 - Number(row.Percent)),
        "halfit" : "second"
       };
});
//combine the two - concat returns a new array
var chartData = data.concat(opposites);
var myChart = new dimple.chart(svg, chartData);
...
//add order rule so original data is on bottom
var series = myChart.addSeries("halfit", dimple.plot.bar);
series.addOrderRule(['first', 'second']);

Otherwise, you could just graph the original values without the opposite bars by using a measure axis locked at 100 (this will only work because your values are already percents, however) :
  var yAxis = myChart.addMeasureAxis("y", "Percent");
 yAxis.overrideMax = 100;

However it sounds like that won't work for your use case, but it is an option.


text:
Q: GitHub: How to set headers for ajax request? How do I set authorization headers for ajax request to make request on GitHub account?
I have created Personal Access Tokens on GitHub to use it with ajax for authentication to perform operations on my repository.
ajax request is made as shown below:
var apiDomain = 'https://api.github.com',
    api="/users/" + username;
    $.ajax({
        beforeSend: function (xhr) {
            xhr.setRequestHeader ("Authorization", "token 8da3512a16c3fc0d33d8932ca37e6f5bc4c695c0");
        },
        url:apiDomain+api+'?callback=testUser',
        dataType:'script'
    });

I get the response data as expected. However, the ajax call is unauthenticated and I always see the following on the meta object
X-RateLimit-Limit: "60"
X-RateLimit-Remaining: "55"
X-RateLimit-Reset: "1387964695"
status: 200

If the ajax request is authenticated I should be able to make ~5000 requests.
How do I use my Personal Access Tokens to make more ajax requests on GitHub?

A: Passing the access_token as a query parameter solved the problem.
Here is the modified version with the query parameter "access_token"
var apiDomain = 'https://api.github.com',
    api="/users/" + username;
    $.ajax({
        url:apiDomain+api+'?callback=testUser&access_token=8da3512a16c3fc0d33d8932ca37e6f5bc4c695c0',
        dataType:'script'
    });

P.S: The comment in the question helped me find the solution. Thanks @VonC


text:
Q: How fix it. Unhandled exception at 0x0099B514 in ConsoleApplication15.exe: 0xC0000094: Integer division by zero I am trying to solve problem with c++: Find all unique elements of a two-dimensional array of integers using MPI_Scatter and MPI_Comm_split to distribute the array's rows among a set of processes, so that the set of processes is split into three groups.
Got the code
#include <iostream>
#include <unordered_set>
#include <mpi.h>

using namespace std;

int main(int argc, char* argv[])
{
    int rank, size;
    int rows = 0, columns = 0;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    int* matrix = nullptr;
    if (rank == 0)
    {
        cout << "Enter the number of rows: ";
        cin >> rows;
        cout << "Enter the number of columns: ";
        cin >> columns;

        matrix = new int[rows * columns];

        cout << "Enter the elements of the matrix: " << endl;
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < columns; j++)
            {
                cin >> matrix[i * columns + j];
            }
        }
    }

    MPI_Bcast(&rows, 1, MPI_INT, 0, MPI_COMM_WORLD);
    MPI_Bcast(&columns, 1, MPI_INT, 0, MPI_COMM_WORLD);

    int sub_size = rows / size;
    int* local_matrix = new int[sub_size * columns];

    MPI_Scatter(matrix, sub_size * columns, MPI_INT, local_matrix, sub_size * columns, MPI_INT, 0, MPI_COMM_WORLD);

    unordered_set<int> local_set;
    for (int i = 0; i < sub_size; i++)
    {
        for (int j = 0; j < columns; j++)
        {
            local_set.insert(local_matrix[i * columns + j]);
        }
    }

    MPI_Comm sub_comm;
    MPI_Comm_split(MPI_COMM_WORLD, rank / (size / 3), rank, &sub_comm);

    int sub_rank, new_sub_size;
    MPI_Comm_rank(sub_comm, &sub_rank);
    MPI_Comm_size(sub_comm, &new_sub_size);

    unordered_set<int>* global_set = nullptr;
    if (sub_rank == 0)
    {
        global_set = new unordered_set<int>[new_sub_size];
    }

    MPI_Gather(&local_set, sizeof(unordered_set<int>), MPI_BYTE, global_set, sizeof(unordered_set<int>), MPI_BYTE, 0, sub_comm);

    if (sub_rank == 0)
    {
        unordered_set<int> final_set;
        for (int i = 0; i < new_sub_size; i++)
        {
            for (auto it = global_set[i].begin(); it != global_set[i].end(); it++) {
                final_set.insert(*it);
            }
        }
        cout << "The unique elements in the matrix are: ";
        for (auto it = final_set.begin(); it != final_set.end(); it++) {
            cout << *it << " ";
        }
        cout << endl;
        delete[] global_set;
    }

    delete[] local_matrix;
    if (rank == 0) {
        delete[] matrix;
    }

    MPI_Finalize();
    return 0;
}

After compile and input data microsoft visual studio 2019 gives an error message
Unhandled exception at 0x0099B514 in ConsoleApplication15.exe: 0xC0000094: Integer division by zero.
to this line
MPI_Comm_split(MPI_COMM_WORLD, rank / (size / 3), rank, &sub_comm);

How fix it?


text:
Q: Calculation on groups after group by with Pandas I have a data frame that is grouped by 2 columns - Date And Client and I sum the amount so:
new_df = df.groupby(['Date',Client'])
Now I get the following df:
             Sum
Date Client
1/1   A      0.8
      B      0.2
1/2   A      0.1
      B      0.9

I want to be able to catch the fact that there is a high fluctuation between the ratio of 0.8 to 0.2 that changed to 0.1 to 0.9. What would be the most efficient way to do it? Also I can't access the Date and Client fields when I try to do
new_df[['Date','Client']]

Why is that?

A: IIUC you can use pct_change or diff:
new_df = df.groupby(['Date','Client'], as_index=False).sum()
print (new_df)
  Date Client  Sum
0  1/1      A  0.8
1  1/1      B  0.2
2  1/2      A  0.1
3  1/2      B  0.9

new_df['pct_change'] = new_df.groupby('Date')['Sum'].pct_change()
new_df['diff'] = new_df.groupby('Date')['Sum'].diff()
print (new_df)
  Date Client  Sum  pct_change  diff
0  1/1      A  0.8         NaN   NaN
1  1/1      B  0.2       -0.75  -0.6
2  1/2      A  0.1         NaN   NaN
3  1/2      B  0.9        8.00   0.8


text:
Q: SimpleXMLElement array only returns one element I have the following Simple XML structure var_dump'ed:
var_dump($data) results in:
object(SimpleXMLElement)[269]
  public 'columns' =>
    object(SimpleXMLElement)[283]
      public 'column' =>
        array (size=11)
          0 =>
            object(SimpleXMLElement)[274]
              public '@attributes' =>
                array (size=2)
                  'name' => string 'test' (length=10)
                  'display' => string 'test ID' (length=11)
          1 =>
            object(SimpleXMLElement)[273]
              public '@attributes' =>
                array (size=2)
                  'name' => string 'blah' (length=8)
                  'display' => string 'blah' (length=8)
          ....
          ....
          ....
  public 'row' =>
    array (size=6)
      0 =>
        object(SimpleXMLElement)[270]
          public '@attributes' =>
            array (size=11)
              'test' => string '3445543' (length=8)
              'blah' => string 'Some Text' (length=13)
      1 =>
        object(SimpleXMLElement)[279]
          public '@attributes' =>
            array (size=11)
              'test' => string '3445543' (length=8)
              'blah' => string 'Some Text' (length=13)
      2 =>
        object(SimpleXMLElement)[278]
          ....
          ....
          ....

I shortened the output as you can see just to save room. But the row array contains 6 elements as you can see.
Now if I do this:
echo count($data->row); I get 6 as expected.
If I do this:
var_dump($data->row); I get this...
object(SimpleXMLElement)[270]
  public '@attributes' =>
    array (size=11)
      'test' => string '3445543' (length=8)
      'blah' => string 'Some Text' (length=13)

It prints out one element. No array.
Why would the count of the array return the right value but fetching the array only gets the first element of the array? How do I get all of the elements?


text:
Q: Issue with ~/.profile after fixing NPM permissions Installed Node.js on OS X. Fixed the permissions (i.e. sudo required) issue by changing NPM's default directory (https://docs.npmjs.com/getting-started/fixing-npm-permissions see Option 2). However, after booting up commands like grunt are not available until I run source ~/.profile.
Any way to avoid this hassle?

A: Did the node/NPM setup create a ~/.bash_profile or ~/.bash_login file? if so, bash will source that instead of ~/.profile at startup. If this is the problem, there are a couple of ways to fix it:

*

*Copy the contents of your ~/.profile file into ~/.bash_profile (or ~/.bash_login). You may also want to delete ~/.profile to avoid future confusion.

*Add a command to ~/.bash_profile (or ~/.bash_login) to source ~/.profile as well:
[ -f ~/.profile ] && source ~/.profile


text:
Q: SQL: Check if a row exists for each condition I'm not able to find a correct SQL query for my needs.
I have a table like this:
first_id | second_id | value
1          1           valueABC
1          2           valueLoL
2          1           valueBlaBla
2          2           valueLoL

Now I would like to select the first_ids where they have at least one row for EACH condition:
second_id = 1 and value = 'valueABC'
AND
second_id = 2 and value = 'valueLoL'

I already tried this, but the query is not correct:
select distinct first_id from myTable where (second_id = 1 and value = 'valueABC')
and (second_id = 2 and value = 'valueLoL') group by first_id having count(first_id) = 2

So in my example, first_id = 1 should be selected, as we have a row for each condition.
Can you help me please ?
Thank you.

A: I think you can do something like the following:
select first_id
from t
group by first_id
having
    Max(case when second_id = 1 and value = 'valueABC' then 1 end) is not null and
    Max(case when second_id = 2 and value = 'valueLoL' then 1 end) is not null;

A: Try this:
select first_id from
(select first_id,
sum(case when second_id = 1 and value = 'valueABC' then 1 else 0 end) as nbCond1,
sum(case when second_id = 2 and value = 'valueLoL' then 1 else 0 end) as nbCond2
from myTable
group by first_id) t
where nbCond1 > 0 and nbCond2 > 0;

Basically grouping by first_id and counting how many times the two conditions appear in a row for each first_id, then only selecting first_ids that have the number of occurences of both conditions > 0.
Fiddle


text:
Q: Are there methods to determine the stability of functional differential equations? For nonlinear differential equations there are methods to determine the stability of fixed points and limit cycles using a phase plane analysis. If I have a functional differential equation with two (or more) solutions how would I determine the stability of the solution functions? Is it correct to think of the solutions like I would think of fixed points of a differential equation?

A: Yes, it is possible to do this, but you have to think carefully about the space of functions that you are working with, and what the topology on that space is. It is often possible to solve certain PDE by considering their solutions to be fixed points of a continuous map on a convex subset of a Banach space, such as a Sobolev space. Existence would follow from an appropriate fixed point theorem.
In a similar fashion, you can formulate (theoretically, at least), the concept of stability with respect to the topology you've given on your function space (e.g. induced by the Sobolev norm if you're working with $H^1(\Omega)$, etc). Now, whether you can analyze or determine whether or not you have stability is less obvious to me, and it seems like it would depend a lot on the function you're using.


text:
Q: Wordpress: Local database to live server I have setup a wordpress website at my local machine, intalled wocommerce and did the theme configuration and updates. Its working fine. Then I exported the mysqldump and changed the all local url reference to live url. Then I imported that updated mysqldump in my server phpmyadmin. When I checked the new tables all values are there. Rsynced all local files to server. Then updated the wp-config.php to server database credentials.
The issue is, If I take the live website url in browser, the database automatically updates with basic wordpress table datas. And woocommerce data is not visible through wordpress admin. Do I need to do anything extra changes in the code other than wp-config.php?
While importing mysql database, I got a collation error,
#1273 – Unknown collation: 'utf8mb4_unicode_520_ci'

I solved the collation isssue by renaming "utf8mb4_unicode_520_ci"  to "utf8mb4_unicode_ci".


text:
Q: Unable to get Java to trust my self-signed certificate Even after adding my self signed certificate to cacerts, I still can't get Java to trust it
I have nginx running on my local machine as an SSL reverse proxy with a self signed certificate. I have generated the certificate like this:
openssl req -new -nodes -keyout server.key -out server.csr
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

I filled in my-org.local when prompted for Common Name. In my hosts file, my-org.local is an alias for localhost.
Testing this setup in the browser, I got a warning that the certificate was not signed by a known authority, which is what I would expect. I then told the browser to trust the certificate, and that worked.
Next, I wrote this small little Java program to be able to verify if I can get Java to trust the certificate:
import java.net.*;
import java.io.*;

public class Main {

    public static void main(String[] args) throws Exception {
        String url = "https://my-org.local/";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);
    }
}

If I test this against e.g. https://google.com, everything works as expected. Against my local machine I get the following stack trace:
Exception in thread "main" javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1884)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:270)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1341)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:153)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868)
    at sun.security.ssl.Handshaker.process_record(Handshaker.java:804)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1016)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:563)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1300)
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338)
    at Main.main(Main.java:10)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
    at sun.security.validator.Validator.validate(Validator.java:260)
    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1323)
    ... 13 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
    ... 19 more

... which is more or less what I would expect.
My understanding is that to get Java to trust my self signed certificate, I have to add the certificate to Java's cacerts. On my machine (a mac running Mavericks), this file is to be found here:
/System/Library/Frameworks/JavaVM.framework/Home/lib/security/cacerts

This is how I tried to add the certificate:
sudo keytool -import -keystore /System/Library/Frameworks/JavaVM.framework/Home/lib/security/cacerts -storepass changeit -noprompt -alias myorg -file server.crt

This however has no effect; my small Java program still dies with the same stack trace. What am I doing wrong?

A: You're getting SSLHandshakeException which clearly means the certificate is not successfully imported into your cacerts file.
So, let's first check if your cacerts has the certificate or not:
echo 'changeit' | keytool -list -v -keystore $(find $JAVA_HOME -name cacerts) | grep 'Owner:'

changeit is the default password. This will just list the owners of all the certificates. You can also grep by the keywords of your own certificate to check if it exists.
If it doesn't, this code does a wonderful job in creating the cacerts file. I'm adding the code for reference:
import javax.net.ssl.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class CustomTrustManager implements X509TrustManager
{
    private static final String JAVA_CA_CERT_FILE_NAME = "cacerts";
    private static final String CLASSIC_JAVA_CA_CERT_FILE_NAME = "jssecacerts";
    private static final int DEFAULT_HTTPS_PORT = 443;

    private String[] hostsToTrust = {"server1.company.com", "server2.company.com"};
    private char[] defaultCAKeystorePassphrase = "changeit".toCharArray();
    private KeyStore certificateTrustStore;
    private X509TrustManager defaultTrustManager;

    public static void initSsl()
    {
        try
        {
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new TrustManager[] { new CustomTrustManager() }, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
        }
        catch (Exception e)
        {
            throw new RuntimeException(e);
        }
    }

    public CustomTrustManager()
    {
        try
        {
            initTrustStore();
            addTrustedHosts();
            initDefaultTrustManager();
        }
        catch (Exception e)
        {
            throw new RuntimeException(e);
        }
    }

    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException
    {
        defaultTrustManager.checkClientTrusted(chain, authType);
    }

    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException
    {
        defaultTrustManager.checkServerTrusted(chain, authType);
    }

    public X509Certificate[] getAcceptedIssuers()
    {
        return defaultTrustManager.getAcceptedIssuers();
    }

    private void initTrustStore() throws Exception
    {
        File javaTrustStoreFile = findJavaTrustStoreFile();
        InputStream inputStream = new FileInputStream(javaTrustStoreFile);
        certificateTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        certificateTrustStore.load(inputStream, defaultCAKeystorePassphrase);
        inputStream.close();
    }

    private void addTrustedHosts() throws Exception
    {
        SSLContext tempConnectContext = SSLContext.getInstance("TLS");
        ExtractX509CertTrustManager getX509CertTrustManager = new ExtractX509CertTrustManager();
        tempConnectContext.init(null, new TrustManager[] { getX509CertTrustManager }, null);
        SSLSocketFactory socketFactory = tempConnectContext.getSocketFactory();
        for (String host : hostsToTrust)
        {
            SSLSocket socket = (SSLSocket) socketFactory.createSocket(host, DEFAULT_HTTPS_PORT);
            // connect the socket to set the cert chain in getX509CertTrustManager
            socket.startHandshake();
            for (X509Certificate cert : getX509CertTrustManager.getCurrentChain())
            {
                if (!certificateTrustStore.isCertificateEntry(host))
                {
                    certificateTrustStore.setCertificateEntry(host, cert);
                }
            }
        }
    }

    private void initDefaultTrustManager() throws Exception
    {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(certificateTrustStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        for (TrustManager trustManager : trustManagers)
        {
            if (trustManager instanceof X509TrustManager)
            {
                defaultTrustManager = (X509TrustManager) trustManager;
                break;
            }
        }
    }

    /**
     * Trust Manager for the sole purpose of retrieving the X509 cert when a connection is made to a host we want
     * to start trusting.
     */
    private static class ExtractX509CertTrustManager implements X509TrustManager
    {
        private X509Certificate[] currentChain;
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { }
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException
        {
            currentChain = x509Certificates;
        }
        public X509Certificate[] getAcceptedIssuers() { return null; }
        public X509Certificate[] getCurrentChain()
        {
            return currentChain;
        }
    }

    private File findJavaTrustStoreFile()
    {
        File javaHome = new File(System.getProperty("java.home") + File.separatorChar + "lib" + File.separatorChar + "security");
        File caCertsFile = new File(javaHome, JAVA_CA_CERT_FILE_NAME);
        if (!caCertsFile.exists() || !caCertsFile.isFile())
        {
            caCertsFile = new File(javaHome, CLASSIC_JAVA_CA_CERT_FILE_NAME);
        }
        return caCertsFile;
    }
}

To get started quickly:

*

*Add your hosts to the hostsToTrust String array.

*Call CustomTrustManager.initSsl().

*Make SSL connections to your hosts.

That being said, I won't recommend updating cacerts because it's at a common JVM location as is thus used by every Java application. You should create a custom trustStore for the specific application you're working on and only allow that application to trust the self-signed certificate. Checkout this answer for how to do that.


text:
Q: The correct way to manage data for display in the YII framework? If I have a shop that displays a bunch of products and I get these products returned from the database as an array, is there a specific way that you can display this data using YII templates or is it sufficient to simply loop through the array and print it out in "divs" as needed?
I know if I just spit it out in DIVs, it would work, but is it the "correct" way to do it according to the framework?

A: For this there are zii widgets, and also many extensions.
I think for a store CListView will be a good start. There are many wikis that explain a lot about CListView.
You can easily extend it and add functionality.
Zii widgets provide pagination, sorting, and custom styling too, when used alongwith a data provider.


text:
Q: How to subset a dataset by time but not date? I have a dataset with a list of times and dates. I want to subset it so I only have entries between 06:30:00 and 07:30:00. I have tried subsetting it using the following function:
field1_temp$Time<-field1_temp$Time["T06:30:00/T07:30:00"].
The structure of the dataset is as follows:
> str(field1_temp)
'data.frame':   17066 obs. of  3 variables:
 $ No.         : int  1 2 3 4 5 6 7 8 9 10 ...
 $ Time        : POSIXlt, format: "2021-02-08 14:56:07" "2021-02-08 14:57:07" "2021-02-08 14:58:07" ...
 $ Temperature.: num  6.8 6.5 6 5 4.7 4.8 4.2 3.6 2.9 2.3 ...

When running the function I only returned NAs, despite their being times in the right period specified.

A: Since you Time in POSIXlt format hour and min information should be present in itself. Try :
result <- field1_temp[with(field1_temp$Time, hour == 6 & min >= 30 |
                                             hour == 7 & min <= 30), ]

A: Using the input shown reproducibly in the Note at the end, we read it into a zoo object, convert that to xts and  finally we subset it using the notation in the question. The code below also converts the POSIXlt date times to POSIXct which is a more suitable class for time series.  You can turn it back to data frame using fortify.zoo(x0) but it's probably better to just leave it as an xts object to facilitate access to the time series functionality it and zoo provide.
library(xts)

z <- read.zoo(d, index = "Time", FUN = as.POSIXct)
x <- as.xts(z)
x0 <- x["T14:56:00/T14:56:59"]
x0
                    No Temperature
2021-02-08 14:56:07  1         6.8

Note
d <- data.frame(No = 1:2,
 Time =  as.POSIXlt(c("2021-02-08 14:56:07", "2021-02-08 14:57:07")),
 Temperature = c(6.8, 6.5))


text:
Q: How to save high score using SharedPreferences on Android Studio? I am using Android Studio to created a game currently I am trying to save my high score. I have managed to get it working however when I exit out of the application the high score seems to reset. Is there any way I can save the score even after I exit the application.
My code:
prefs = this.getSharedPreferences("com.example.dreamchase.HIGHSCORE", Context.MODE_PRIVATE);

private int highScore = Game.prefs.getInt("HIGHSCORE", 0);

if (player.getScore() > highScore) {
                    highScore = player.getScore();
                    Game.prefs.edit().putInt("HIGHSCORE", highScore).commit();
                }


text:
Q: iso date is not converted successfully into time with 12 hour format My code is as shown below:
private String getFormattedDate(String date){
    try {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date value = formatter.parse(date);

        SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM HH:mm a");

        dateFormatter.setTimeZone(TimeZone.getDefault());
        date = dateFormatter.format(value);

    } catch (Exception e) {
        date = "00-00-0000 00:00";
    }

    return date;
}

Here what I want to do is , I want to convert 2018-03-19T19:24:41.396Z into the format 19-03 7:24 PM, but here it gives me the output 19-03 19:24 PM . Am I missing anything in my method because of which it is giving the false output?

A: SimpleDateFormat
Capital H   Hour in day (0-23) and Small h  Hour in am/pm (1-12)
Change this line
  SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM HH:mm a");

to
  SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM hh:mm a");

A: HH outputs hour in 0-23 format. You must use hh instead.

A: Try This
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date value = formatter.parse(date);

            SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM hh:mm a");

            dateFormatter.setTimeZone(TimeZone.getDefault());
            date = dateFormatter.format(value);
            System.out.println("Date :- "+date);


text:
Q: In what book was "the oldest joke in the book"? I'd like to understand the derivation of the phrase "oldest X in the book."  Was this referring to a particular book, or was it an idiom that developed without a particular object in mind?
If it is just an idiom, how old is the idiom, and how did it develop?

A: Good question. It is an idiom: "They committed every crime in the book"; "He was always one step ahead of me, as he seems to know every trick in the book."; "He used every trick in the book to get her to sign the contract."
See every trick in the book on Wiktionary.
'The book' appears to be a metaphor for the body of knowledge. Compare: by the book, 'according to the correct or established form' (originally could have referred to the Bible).
'to play by the book' (strictly according to the rules of the game):
Edgar Allan Poe, Murders in Rue Morgue, 1845:

"To have a retentive memory, and to proceed by 'the book', are points commonly regarded as the sum total of good playing."

A: There's no literal "The Book", but rather a metaphorical "the book you got it from". Joke books are indeed a thing that exists. Here's one I used to own as a kid.
Jokes generally have prestige based on how original they are. If a person has heard a joke several times before, they aren't going to find it nearly as funny.
If you made it up yourself, that's clearly original. Someone who isn't that clever would be forced to get their jokes from a jokebook like perhaps the one I linked above.
So basically this is a way of denigrating the humor of someone who just told a joke. You are implying they are so unfunny that, not only did they have to get their humor "canned" from a book, but they don't even know enough to avoid jokes their audience is likely to have heard before.


text: Q: Is it possible to automate mobile games with a pc application, if so what language is used and how is it done Alright, so I've had some basic experience with java, and some c# on the side, and I was wondering if either could be used to make some type of desktop app that could work on mobile to automate some simple tasks. There's plenty of programs that can be made and used to automate tasks on pc, and I was wondering if there was something similar for mobile.


text:
Q: Sorting Hashed maps Map I am trying to sort and get the top 3 maxium values for the VALUE(?)
Map<String,?> points = map

Tried using Map<String, String> and it works fine, but in this case I need Map<String, ?>.

A: The type of the values will need to implement Comparable.
If the size of the map is not too large, you could try something like this:
private <T extends Comparable> SortedSet<T> sortValues(final Map<?, T> m)
    {
    final SortedSet<T> result = new TreeSet<>();
    result.addAll(m.values());
    return result;
    }

I haven't tested this, but I think I have all of the type declarations correct.  Then just take the first, or last as the case may be, elements from the sorted set.  I believe you can optionally provide your own Comparator to the set to choose how to order the objects.

A: You cannot sort non-Comparable objects, to begin with, so you'll need a map with Comparable values, not ?. Having that, however, you could do something like this:
public static <T extends Comparable<? super T>> List<T> sortValues(Map<?, T> map) {
    List<T> buffer = new ArrayList<T>(map.values());
    Collections.sort(buffer);
    return(buffer);
}

Then you can do whatever you want with the return value of sortValues, such as picking the first three objects in it.


text:
Q: When the primary obstruction is the only obstruction, is it still the only obstruction after a pull-back? Consider the following situation:

*

*We have a Hurewicz fibration $p: E \rightarrow B$  with path-connected base $B$ and $(d-1)$-connected fiber $F$ for some $d \geq 1$. In case $d=1$ we require $\pi_1(F)$ to be abelian.

*There is a continuous map $f: X \rightarrow B$ where $X$ is a finite CW complex.

*For every $k \geq 0$, the action of the fundamental group $\pi_1(F)$ on the homotopy group $\pi_k(F)$ is trivial. As a consequence, there is a well-defined action [Davis-Kirk, Proposition 6.62] of $\pi_1(B)$ on $\pi_k(F)$.

*For each $k \geq 0$, we write $\rho(f,k): \pi_1(X) \rightarrow Aut(\pi_k(F))$ for the induced action of $\pi_1(X)$ on $\pi_k(F)$. We regard  this as a local coefficient system over $X$, so that there are well-defined cohomology groups $H^*(X;\pi_k(F)_{\rho(f,k)})$ with local coefficients.

Under these conditions, there is a well-developed obstruction theory. Using [Davis-Kirk, Theorem 7.37] and the remarks later: First of all, $f$ can be lifted over the $(d-1)$-skeleton $X_{d-1}$. Second, no matter which lift over the $(d-1)$-skeleton we choose, the obstruction class for lifting it further over the $d$-skeleton is unique. This primary obstruction $z_f$ is an element of $H^d(X;\pi_{d-1}(F)_{\rho(f,d-1)})$. In case $f$ can be lifted over $X_k$ for some $k \geq d$, the next obstructions lie in  $H^{k+1}(X;\pi_k(F)_{\rho(f,k)})$ (but these higher obstructions are not necessarily unique).
Now suppose that $f$ factors through a $d$-dimensional $CW$ complex $Y$: say $u: X \rightarrow Y$ and $v: Y \rightarrow B$ where $u$ is cellular and $vu = f$. The problem of lifting $v$ along $p$ has a similar obstruction theory to above, but for dimension reasons here the primary obstruction $z_v \in H^d(X;\pi_{d-1}(F)_{\rho(v,d-1)})$ is the only obstruction for lifting $v$ along $p$.
Here is my question: suppose $z_v \neq 0$ but $z_f = 0$. In other words (by the naturality of the obstruction classes), $z_v$ lies in the kernel of the induced map $$u^*: H^d(Y;\pi_{d-1}(F)_{\rho(v,d-1)}) \rightarrow H^d(X;\pi_{d-1}(F)_{\rho(f,d-1)}) \, .$$
Does this imply that $f$ can be lifted over the whole $X$ (not just its $d$-skeleton)? My intuition is that because $f = vu$ factors through $v$, the lifting problem for $f$  should not be harder  than the lifting problem for $v$. And we know that the only obstruction for lifting $v$ is pulled-back along $u^*$ to zero, hence there should be no obstructions left for lifting $f$.
Davis, James F.; Kirk, Paul, Lecture notes in algebraic topology, Graduate Studies in Mathematics. 35. Providence, RI: AMS, American Mathematical Society. xvi, 367 p. (2001). ZBL1018.55001.


text:
Q: Write to session on anchor click ASP.NET I have ASP.NET based site. For example I have two anchors:
Popular
Recent

At code behind I can build href attributes:
sortByPopular.Href = BuildURL(POPULAR);
sortByRecent.Href = BuildURL(RECENT);

And I want to remember, which sort order user is using on listing page. I think there should be the way to create new Session variable when user clicks on link. Could someone help me with this?
Thanks in advance.

A: You can use LinkButton
<asp:LinkButton runat="server" ID="sortByRecent" Text="Recent" OnClick="sortByRecent_Click"></asp:LinkButton>

codebehind
protected void sortByRecent_Click(object sender, EventArgs e)
{
   //do your session thing here
}


text:
Q: Facebook Graphi API user Request returns 400 Bad Request I have two Facebook applications (websites) using the OAuth login from Facebook functionality.  One works, the other gives me a 400 error when I request the user data.  The request looks like this:
https://graph.facebook.com/me?fields=id,name,email,first_name,last_name,username,locale,location&access_token=[token returned by earlier calls]
Both websites use the exact same code (but get their app IDs and app secret from a db call).  The token request and token check are returning OK, it's when I go ahead and ask for the user data, then I get an error.
Ideas?
TIA,
Owen

A: The problem has to be with the access token. Try debugging the access token to confirm.