text:
Q: Append line to /etc/hosts file with shell script I have a new Ubuntu 12.04 VPS. I am trying to write a setup script that completes an entire LAMP installation. Where I am having trouble is appending a line to the /etc/hosts file. My current hosts file looks like this:
127.0.0.1       localhost Venus

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

I would like it to look like this:
127.0.0.1       localhost Venus
192.241.xx.xx  venus.example.com venus

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

I have tried a variety of sed commands using the append (\a) command. For some reason Ubuntu either just echoes the contents of the hosts file in terminal or does nothing at all. How would I properly inject the second line into the file with a bash script?

A: Make sure to use the -i option of sed.
-i[SUFFIX], --in-place[=SUFFIX]
  edit files in place (makes backup if extension supplied)

sed -i "2i192.241.xx.xx  venus.example.com venus" /etc/hosts

Otherwise,
echo "192.241.xx.xx  venus.example.com venus" >> /etc/hosts

would append the line at the end of the file, which could work as you expect.

A: echo "127.0.0.1 localhost `hostname`">./temp_hosts
echo "192.241.xx.xx  venus.example.com">>./temp_hosts
cat /etc/hosts |tail -n +2 >>./temp_hosts
cat ./temp_hosts > /etc/hosts
rm ./temp_file

A: If your in mac or you need sudo permission to this try this:
sudo -- sh -c -e "echo '192.34.0.03   subdomain.domain.com' >> /etc/hosts";

It will still ask you for password.
alternative way from @kainjow
echo '192.34.0.03 subdomain.domain.com' | sudo tee -a /etc/hosts

A: Insert/Update Entry
If you want to programmatically insert/update a hosts entry using bash, here's a script I wrote to do that:
#!/bin/bash

# insert/update hosts entry
ip_address="192.168.x.x"
host_name="my.hostname.example.com"
# find existing instances in the host file and save the line numbers
matches_in_hosts="$(grep -n $host_name /etc/hosts | cut -f1 -d:)"
host_entry="${ip_address} ${host_name}"

echo "Please enter your password if requested."

if [ ! -z "$matches_in_hosts" ]
then
    echo "Updating existing hosts entry."
    # iterate over the line numbers on which matches were found
    while read -r line_number; do
        # replace the text of each line with the desired host entry
        sudo sed -i '' "${line_number}s/.*/${host_entry} /" /etc/hosts
    done <<< "$matches_in_hosts"
else
    echo "Adding new hosts entry."
    echo "$host_entry" | sudo tee -a /etc/hosts > /dev/null
fi

The script is intended for use with OS X but would work on linux as well with minor tweaking.

A: I should point out that sed (the stream editor) is not actually intended for editing files, although it can be used to do that. (Standard sed doesn't have a built-in mechanism for writing to other than standard output.) A more appropriate tool would be ed.
The following ed script says "find the line containing the (admittedly sloppy) regular expression /127.0.0.1/ and append at the next line." (The lone period tells ed to stop appending.)
ed /etc/hosts <<-'EOF'
    /127.0.0.1/a
    192.241.xx.xx  venus.example.com
    .
    wq
EOF

That said, you can really just append this line to the end of your /etc/hosts file very trivially:
echo '192.241.xx.xx  venus.example.com' >> /etc/hosts

A: you can use sed, like:
sed '/Venus/ a\
192.241.xx.xx  venus.example.com venus' /etc/hosts

A: try this with root access.
 public void edithost() {
    sudo("echo " + "192.168.43.1     www.openrap.com openrap" + " >> /etc/hosts");
    sudo("echo " + "192.168.43.1  openrap.com openrap" + " >> /etc/hosts");
    sudo("echo " + "192.168.2.144  www.openrap.com openrap" + " >> /etc/hosts");
    sudo("echo " + "192.168.2.144  openrap.com openrap" + " >> /etc/hosts");
}

sudo for super user permission
public static void sudo(String... strings) {
    try {
        Process su = Runtime.getRuntime().exec("su");
        DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

        for (String s : strings) {
            outputStream.writeBytes(s + "\n");
            outputStream.flush();
        }

        outputStream.writeBytes("exit\n");
        outputStream.flush();
        try {
            su.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

this will append the lines to hosts in the android


text:
Q: Cron job script - loading wordpress system fails I want to run a cron job that fetches data from an api and stores it in a database table.
I don't use "wp-cron". I load a script in a folder inside the theme. But I need to load the wordpress system somehow, so I have this code inside the script:
require_once( '../../../../../wp-load.php' );

I was thinking that I could require the wordpress system by requiring "wp-load.php", (which is also done in "wp-cron.php")  and after that I could import my custom classes which make use of $wpdb and other wordpress stuff.
If I only run a simple database insert and nothing else (with normal mysql syntax), it works. But when adding the require statement , it fails. Do you know why?
And do you know how I could make this work, so I can make use of the wordpress system?
EDIT
The problem is with "require_once", so it's not wordpress related... If I try to require another script, and put my test database insert code there, that script never runs.
So in the main script I do:
require_once( 'hello.php' );

In "hello.php" I have the database insert (which works if I put it in the original file, without no require statements.
I use windows task scheduler to run the script, so maybe it's more related to that.
EDIT2:
I tried placing the script in the root folder, so the require became:
require_once( 'wp-load.php' );

and this time it worked! So the problem seems to be related to using paths going back to the parents ( ../../../etc ) . I also tried absolute paths but wasn't lucky.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "NetworkError: 500 Internal Server Error" This is the jquery code in ColdFusion index.cfm which is calling chkUsername of cfc file.
<script type="text/javascript">
 chkUsernameUnique = function(theUsername){
  $.getJSON("selectuser.cfc", {
    method: 'chkUsername',
    Username: theUsername,
    returnformat: 'json'
}, function(isUsernameUnique){

    if (isUsernameUnique == true) {
        $("#theErrorDivID").html('Username is unique');
    }
    else {
        $("#theErrorDivID").html('Please select a new username');
    }
});
};
</script>

This is my component which is getting called from the cfm file.
<cfcomponent>
<cffunction name="chkUsername" returnformat="json" output="false">
    <cfargument name="username" required="true">

    <cfquery name="chkUsername" datasource="myDataSource">
    SELECT ID FROM employees_login WHERE username = <cfqueryparam value="#arguments.username#" cfsqltype="cf_sql_varchar" />
    </cfquery>

    <cfreturn yesNoFormat(chkUsername.recordCount) />
</cffunction>
</cfcomponent>

Nothing was getting displayed.
I tried to check the error on fire bug and i am getting this error -
"NetworkError: 500 Internal Server Error:http://localhost:8500/workspace/UniqueUsername/selectuser.cfc?method=chkUsername&Username=admin&returnformat=json"

A: I was working on it from long time.
Finally i got the answer. You need to write access="remote" in the cffunction tag like this-
<cfcomponent>
 <cffunction name="chkUsername" returnformat="json" access="remote" output="false">
  <cfargument name="username" required="true">

  <cfquery name="chkUsername" datasource="myDataSource">
   SELECT ID FROM employees_login WHERE username = <cfqueryparam value="#arguments.username#" cfsqltype="cf_sql_varchar" />
  </cfquery>

  <cfreturn yesNoFormat(chkUsername.recordCount) />
  </cffunction>
</cfcomponent>

A: Try replacing this: <cffunction name="chkUsername"returnformat="json" output="false">
with this: <cffunction name="chkUsername" returnformat="json" output="false">


text:
Q: ssh_exchange_identification: Connection closed by remote host under Git bash I work at win7 and set up git server with sshd.
I git --bare init myapp.git, and clone ssh://git@localhost/home/git/myapp.git in Cywgin correctly. But I need config git of Cygwin again, I want to git clone in Git Bash. I run git clone ssh://git@localhost/home/git/myapp.git and get following message
ssh_exchange_identification: Connection closed by remote host

then I run ssh -vvv git@localhost in Git Bash and get message
debug2: ssh_connect: needpriv 0
debug1: Connecting to localhost [127.0.0.1] port 22.
debug1: Connection established.
debug1: identity file /c/Users/MoreFreeze/.ssh/identity type -1
debug3: Not a RSA1 key file /c/Users/MoreFreeze/.ssh/id_rsa.
debug2: key_type_from_name: unknown key type '-----BEGIN'
debug3: key_read: missing keytype
debug3: key_read: missing whitespace
// above it repeats 24 times
debug2: key_type_from_name: unknown key type '-----END'
debug3: key_read: missing keytype
debug1: identity file /c/Users/MoreFreeze/.ssh/id_rsa type 1
debug1: identity file /c/Users/MoreFreeze/.ssh/id_dsa type -1
ssh_exchange_identification: Connection closed by remote host

it seems my private keys has wrong format? And I find that there are exactly 25 line in private keys without BEGIN and END.
I'm confused why it said NOT RSA1 key, I totally ensure it is RSA 2 key.
Any advises are welcome.
btw, I have read first 3 pages on google about this problem.

A: I had this problem today and I realize that I was connected to 2 differente networks (LAN and WLAN), I solved it just disconnecting the cable from my Ethernet adapter. I suppose that the problem is caused because the ssh key is tied with the MAC address of my wireless adapter. I hope this helps you.

A: After removing/deleting the rm ~/.ssh/known_hosts, my issue was fixed

A: Got the same error message.  Turning off WiFi and turning it back on again worked for me.

A: I solved it after changing the ssh port & MaxStartups variable in /etc/ssh/sshd_config to ,
port 2244
MaxStartups 100

Then, restart the service
service sshd restart

If still it does not work, restart you system.

A: if hostname does not work, try IP address.
This is going on right now so I have to say.  I try to ssh with my host name and it does not work
ssh root@host.example.net

this gives the error "ssh_exchange_identification: Connection closed by remote host"
this USED to work one hour back.
BUT, and here is the interesting part, the IP address works!
ssh root@192.168.0.100

(of course the actual IP address is different)
Go figure!

A: I just ran into this today and it was because the server I was trying to connect to was overloaded with processing. So it may be possible that the server is low on memory or CPU starved.

A: For fixing the issues add the Hostname for Git on ~/.ssh/config,
Host github.com
 Hostname ssh.github.com
 Port 443

In my case github!

A: Hi I fix this on one vps service,  restarting it, other way is if you have a console from your service o any other way to run a command in your remote machine the only command you must run is restart the ssh daemon and enjoy!! :P
/etc/init.d/ssh restart

A: We migrated our git host instance/servers this morning to a new data center and while being connected to both: VPN (from remote/home) or when in office network, I got the same error and was not able to connect to clone any GIT repo.
Cloning into 'some_repo_in_git_dev'...
ssh_exchange_identification: Connection closed by remote host
fatal: Could not read from remote repository.

This will help if you are connecting to some or all servers via a jump host server.
Earlier in my ~/.ssh/config file, my setting to connect were:
Host * !ssh.somejumphost.my.company.com
     ProxyCommand ssh -q -W %h:%p ssh.somejumphost.my.company.com

What this means is, for any SSH based connection, it will connect to any * server via the given jump host server except/by ignoring "ssh.somejumphost.my.company.com" server (as we don't want to connect to a jump host via jump host server.
To FIX the issue, all I did was, change the config to ignore git server as well:
Host * !ssh.somejumphost.my.company.com !mycompany-git.server.com !OrMyCompany-some-other-git-instance.server.com
     ProxyCommand ssh -q -W %h:%p ssh.somejumphost.my.company.com

So, now to connect to mycompany-git.server.com while doing git clone (git SSH url), I'm telling SSH not to use a jump host for those two extra git instances/servers.

A: For me this was caused by a limit on the number of concurrent ssh sessions.  I added the two params below to /etc/ssh/sshd_config and then things worked.
echo 'MaxSessions 2000' >> /etc/ssh/sshd_config
echo 'MaxStartups 2000' >> /etc/ssh/sshd_config
service ssh restart

A: Similar to Arun Sangal the problem lied in an in .ssh/config entry
Host my.sshhost.com
  ProxyCommand ssh -q -W %h:%p myremotemachine.my.company.com

The remote machine was added to avoid with ssh for VPN connections and worked well. But for the vacation period I switched off the myremotemachine and run into the described problem.

A: To solve this edit /etc/ssh/ssh_config and comment the following line
1
ProxyCommand /usr/bin/sss_ssh_knownhostsproxy -p %p %h
https://www.evilbox.ro/linux/solve-ssh_exchange_identification-connection-closed-by-remote-host/ for reference

A: Remove any config in ~/.ssh/config or other ssh config places which will disallow it to reach to Github servers
In my case it was below config, and I wasn't connected to VPN.
Host *
  ProxyJump 10.0.0.50

Note :-
If I am connected to VPN, This config would mean git clone or any git operation will be send via VPN which might be slow depending on type of VPN we are using.

A: Disconnecting and reconnecting to the current network worked for me.

A: Today Gitlab Server was in maintainence. Please check if it's working later.

A: Just enter on the server side :
echo 'SSHD: ALL' >> /etc/hosts.allow

It sorted it out for me.

A: Hit the following ssh restart command in linux
prayag@prayag:~/backup/NoisyNeighbour$ service ssh restart
stop: Rejected send message, 1 matched rules; type="method_call", sender=":1.75" (uid=1417676764 pid=5933 comm="stop ssh ") interface="com.ubuntu.Upstart0_6.Job" member="Stop" error name="(unset)" requested_reply="0" destination="com.ubuntu.Upstart" (uid=0 pid=1 comm="/sbin/init")
start: Rejected send message, 1 matched rules; type="method_call", sender=":1.76" (uid=1417676764 pid=5930 comm="start ssh ") interface="com.ubuntu.Upstart0_6.Job" member="Start" error name="(unset)" requested_reply="0" destination="com.ubuntu.Upstart" (uid=0 pid=1 comm="/sbin/init")

A: Make sure you are not connect to any kind of VPN.

A: Got the same error too when connecting to GitHub with ssh as I move from one workplace to another. according to my situation, it seems that dns servers of different networks may get various ip address of github and the known_hosts file not identify it when changes happened. So change dns or switch back original network may work.

A: You can get "ssh_exchange_identification: Connection closed by remote host" if your sshd service is not operational!
If you have access to the server check you have the sshd service running with:
  ps aux | grep ssh

and check it is listening on port 22:
 netstat -plant | grep :22

more details here

A: Simple server reboot solved the problem for me. Try hard reboot , if dont work after soft reboot.

A: Please use Port 7999 and Try. it will work

A: I solved it this way.
ssh -vvv <username>@github.com to see github IP.
Then opened browser and opened github via IP to find it was an issue with firewall.

A: I experienced this today and I just do a:
12345@123456 MINGW64 ~/development/workspace/test (develop)
$ git status
Refresh index: 100% (1204/1204), done.
On branch develop
Your branch is up to date with 'origin/develop'.

nothing to commit, working tree clean

12345@123456 MINGW64 ~/development/workspace/test (develop)
$ git fetch

Then all worked again.

A: For me, the issue was that there was a proxy set in /etc/ssh/ssh_config and it was down, solved the issue by whitelisting the remote git IP and removing the proxy line.
Hope this helps someone.

A: In windows machine, remove the content of config file present in C:\Users{yourusername}.ssh
This worked well for me.

A: If you are using a VPN, Turn it off and try to push again.

A: In my case I am developing a script for setting up Raspberry Pies. I forgot to add in that script enabling of the ssh.


text:
Q: get foreign key values drf django every thing working just want to modify the views:
models.py:
class TypeOfCity(models.Model):
    key = models.CharField(verbose_name=_("key"), max_length=15, unique=True)
    value = models.CharField(verbose_name=_("value"), unique=True, max_length=15)
    status = models.SmallIntegerField(_("status:1 for Active; 0: Inactive"), default=1)

    def __str__(self):
        return self.key

class CityTier(models.Model):
     key = models.CharField(verbose_name=_("key"), max_length=10, unique=True)
     value = models.CharField(verbose_name=_("value"), unique=True, max_length=10)
     status = models.SmallIntegerField(_("status:1 for Active; 0: Inactive"), default=1)
    def __str__(self):
        return self.key

class City(BaseModel):
      name = models.CharField(_("City Name"), max_length=80, null=False, blank=False)
      state_name = models.ForeignKey(State, to_field="uid", on_delete=models.DO_NOTHING, max_length=55, null=False, blank=False)
      city_type = models.ForeignKey(TypeOfCity, to_field="key", on_delete=models.DO_NOTHING, max_length=15, null=False, blank=False)
      city_tier = models.ForeignKey(CityTier, to_field="key", on_delete=models.DO_NOTHING, max_length=10, null=False, blank=False)
      status = models.SmallIntegerField(_("Status: 1 for Active; 0:Inactive"), default=1)

serializers.py:
 class TypeOfChoiceSerializer(serializers.ModelSerializer):
      class Meta:
          model = TypeOfChoice
          fields = ('value',)

  class CityTierSerializer(serializers.ModelSerializer):
       class Meta:
            model = CityTier
            fields = ('value',)

class CitySerializer(serializers.ModelSerializer):
      city_type = TypeOfChoiceSerializer(read_only=True)
      city_tier = CityTierSerializer(read_only=True)
      def get_typeofchoices(self,obj):
         return TypeOfChoiceSerializer(TypeOfChoice.objects.all()).data

      def get_city_tiers(self,obj):
          return CityTierSerializer(CityTier.objects.all()).data

      class Meta:
          model = City
          fields = '__all__'

views.py:
    @api_view(['POST'])
    def cityList(request):
        queryset = City.objects.all()
        serializer_obj = CitySerializer(queryset, many=True)
        return HttpResponse(serializer_obj.data)

output:
[{
"id": 1,
"city_type": {
    "value": "Normal City"
},
"city_tier": {
    "value": "Tier I"
},

"name": "test",
"status": 1,

}]

i'm expecting output like this:
[{
"id": 1,
"city_type": "Normal City",
"city_tier": "Tier I",
"name": "test",
"status": 1,

}]

or just add another city_type__values field in output. i tried that with :
City.objects.all().values('city_type','city_type__value')

like that nut its getting error.............................................................................................

A: I think the simplest way is to use source attribute:
class CitySerializer(serializers.ModelSerializer):
    city_type = serializers.CharField(source='city_type__value', read_only=True)
    city_tier =  serializers.CharField(source='city_tier__value', read_only=True)
    ...

If you want to preserve key-value structure for nested fields, you can use method field:
class CitySerializer(serializers.ModelSerializer):
    city_type =  serializers.SerializerMethodField()
    city_tier =  serializers.SerializerMethodField()
    class Meta:
        model = Parent
        fields = (<other_fields>, 'city_type', 'city_tier')

    def get_city_type(self, obj):
        return {obj.city_type.key: obj.city_type.value}

    def get_city_tier(self, obj):
        return {obj.city_tier.key: obj.city_tier.value}


text:
Q: C# How to create an Excel 5.0/95 file I need to create (save) an Excel 5.0/95 file with C# (to be use by an old software), but I'm stuck in not finding the necessary library.
Till this point I always used "EPPlus" (for .xlsx format) and "Excellibrary" (.xls format Excel 97-2003), and couldn't find a way to change the format in any of these two to save the Excel in 5.0/95.
Someone know how to do this?


text:
Q: How do I specify an XForm instance outside of an ``/`` in the same document? How do I do the equivalent of this hypothetical xform:instance attribute that connects externalinstance from the same document:
<mydata xmlns="mydata-namespace"
        xmlns:xform="http://www.w3.org/2002/xforms">
    <foo xform:instance="externalinstance">
        <bar>Baz</bar>
    </foo>
    <xform:model>
        <xform:instance id="myinstance" src="externalinstance" />
    </xform:model>
    <xform:output ref="instance('myinstance')/bar"/>
</mydata>

The enclosing document has defined an XSD Schema that specifies that <foo> must be a direct child of <mydata>, thus adding <xform:model>/<xform:instance> would have been in violation of the enclosing document's schema.
Suppose that I cannot change the parent's schema (as well as the many applications that have been written expecting <foo> to be a direct child of <mydata>), how can I use <foo> as an XForm instance?

A: XForms recommandation does not specify where xf:model should be located. But it does not consider the possibility for the model to be declared within an instance.
Is it possible for you to apply an XSLT stylesheet to generate a more conventional document for your XForms engine?
-Alain


text:
Q: Show that $(a,b)=1$ and $c\mid a$ implies $(c,b)=1$ I have a proof in mind:
Since $c\mid a$, there exist q such that $a = c q$.
Let $d\mid c$ and $d\mid b$, this then implies $d|(b+cq)$ and $d\mid (b-cq)$, which then implies $d\mid (b+a)$ and $d\mid (b-a)$.
And in turn, these imply $d\mid a$ and $d\mid b$. Since $(a,b)=1$, we have $d = 1$.
Therefore, $(b,c)=1$.
Is this a good/legit proof?

A: Or more succinctly, $d|(c,\,b)\implies d|c\land d|b\stackrel{c|a}{\implies}d|a\land d|b\stackrel{(a,\,b=1)}{\implies}d|1$, so $(c,\,b)=1$.

A: As you noted in comments, your proof is flawed.  I sure didn't catch it.
An alternate strategy is to use the fact that, since $(a,b)=1$, we can choose integers $x,y$ such that $$ax+by=1$$  Since we know that $a=cq$ as you say, this becomes $$c(qx)+by=1$$ from which we can conclude that $(b,c)=1$.

A: Well, this seems to be the equivalent as being told to buy a pack of gum from the local store, and solving that by going to the factory, buying a case of gum, taking the case of gum to the local store and selling it to the store but taking one package as commission, and then going home with your pack of gum.
Yes, your proof is legitimate.
But $\gcd(b,c)|c$ and $c|a$ so $\gcd(b,c)|a$ and $\gcd(b,c)|b$ so $\gcd(b,c)$ is a common divisor of $a,b$.  So $\gcd(b,c) \le \gcd(a,b)=1$.  So $\gcd(b,c) = 1$.


text:
Q: I get an error when I try to execute an XQuery statement My intention is to get the count of all the unique titles in an XML file (like the one shown below). However, I get an error as such:
Uncaught DOMException: Document.evaluate: The expression is not a legal expression

Cannot figure out what went wrong.
<channel>
<item>
<title>Trans Researchers Want Google Scholar to Stop Deadnaming Them</title>
<link>https://www.wired.com/story/trans-researchers-want-google-scholar-to-stop-deadnaming-them/</link>
<description>The academic search engine's policy on name changes is out of step with other search tools and publishers.</description>
<category>Business</category>
<thumbnail>https://media.wired.com/photos/630fe159567860ab6c66c667/master/pass/business-deadnames-google.jpg</thumbnail>
</item>
<item>
<title>Babylon Disrupted the UK's Health System. Then It Left</title>
<link>https://www.wired.com/story/babylon-disrupted-uk-health-system-then-left/</link>
<description>The AI-powered online doctor app is ditching its controversial NHS contracts as it focuses on the US market.</description>
<category>Business</category>
<thumbnail>https://media.wired.com/photos/63042ca2f06d7dee6f53bbc6/master/pass/Babylon-Leaves-NHS-Business-1253255825.jpg</thumbnail>
</item>
</channel>

My JavaScript code is as follows:
function displayCount() {
        // get the number of distinct titles using xquery
        var xquery = "count(distinct-values(/channel/item/title))";
        var count = xmlFile.evaluate(xquery, xmlFile, null, XPathResult.ANY_TYPE, null);
        //document.getElementById("count").innerHTML = count.textContent;
        console.log(count.numberValue);
}

What is the reason for the error and how do I correct it?

A: The XPath implementation in current browsers is usually an XPath 1.0 implementation; and distinct-values is a function introduced in XPath 2.0.
You can, however, run XPath 3.1 in the browser using Saxon-JS from Saxonica (also see https://www.saxonica.com/download/javascript.xml for download):

const xml = `<channel>
<item>
<title>Trans Researchers Want Google Scholar to Stop Deadnaming Them</title>
<link>https://www.wired.com/story/trans-researchers-want-google-scholar-to-stop-deadnaming-them/</link>
<description>The academic search engine's policy on name changes is out of step with other search tools and publishers.</description>
<category>Business</category>
<thumbnail>https://media.wired.com/photos/630fe159567860ab6c66c667/master/pass/business-deadnames-google.jpg</thumbnail>
</item>
<item>
<title>Babylon Disrupted the UK's Health System. Then It Left</title>
<link>https://www.wired.com/story/babylon-disrupted-uk-health-system-then-left/</link>
<description>The AI-powered online doctor app is ditching its controversial NHS contracts as it focuses on the US market.</description>
<category>Business</category>
<thumbnail>https://media.wired.com/photos/63042ca2f06d7dee6f53bbc6/master/pass/Babylon-Leaves-NHS-Business-1253255825.jpg</thumbnail>
</item>
</channel>`;

var doc = new DOMParser().parseFromString(xml, 'application/xml');

function displayCount() {
        // get the number of distinct titles using XPath
        var xpath = "count(distinct-values(/channel/item/title))";
        var count = SaxonJS.XPath.evaluate(xpath, doc);
        console.log(count);
}
<script src="https://martin-honnen.github.io/xslt3fiddle/js/SaxonJS2.js"></script>

<input type="button" value="test XPath 3.1" onclick="displayCount()"/>


text:
Q: How to display message box and keep the app executing In visual C#, a exception occur, call a message box to display error message. How can I continue to execute my program without waiting the message box be closed.

A: Instead of using MessageBox.Show, you can make your own error message Form and show it in a non-modal way, using the Form.Show() method. This will allow your UI thread to keep on rolling.
Of course this also mean you will have to set up a few things yourself like size, text alignment and the likes. But that shouldn't be too much trouble if you really just want to use it for one task.
I have to say though, I find your approach quite strange. Normally when an error occurs and you want the user to be informed of it, you'd want the app to hold until the message box is closed. Not doing so may lead into lots of unsuspected problems. For example: what happens if another error occurs while an error is already showing?
If you need a particular task to complete while the UI thread is on hold, I would strongly suggest that you look into doing it in a new thread if possible. This ought to give you what you want while keeping the end user experience up to expectations.

A: If you absolutely need to run it in a non-blocking manner you can initialize the message box in a separate thread:
Task.Run(() => MessageBox.Show("Test"));

Additionally, if you have to relay on the result of the dialog (Ok/Cancel) than probably the whole method has to be run in the new thread.
Task.Run(
    () =>
        {
            if (MessageBox.Show("Test", "test", MessageBoxButtons.OkCancel) == DialogResult.OK)
            {
                MessageBox.Show("Ok");
            }
            else
            {
                MessageBox.Show("Cancel");
            }
        }
    );


text:
Q: How to get the text of an etherpad in the padUpdate hook of a plugin? Im writing a plugin for etherpad. I am implementing the padUpdate hook and would like to know the contents of the pad.
This is my handler in the index.js of the plugin:
exports.padUpdate = function (hook_name, context) {
    // get text of pad
    const text = ...;

    processText(text);
};

Documentation says:
Things in context:

*

*pad - the pad instance

*author - the id of the author who updated the pad

*revs - the index of the new revision

*changeset - the changeset of this revision (see Changeset Library)

And there is a function getText(padID, [rev]). My first idea was to get the pad ID from context and call getText(padID), but I don't know on which object to call getText(padID).

A: Found it:
exports.padUpdate = function (hook_name, context) {
    const text = context.pad.atext.text;

    processText(text);
};


text:
Q: PostgreSQL, getting min and max date from text column I have such situation in table:
1   01.02.2011
2   05.01.2011
3   06.03.2012
4   07.08.2011
5   04.03.2013
6   06.08.2011
7
8   02.02.2013
9   04.06.2010
10  10.10.2012
11  04.04.2012

where first column is id (INT) and second column is TEXT in which may be written date in format 'dd.mm.yyyy'.
I would like to get:
1) lowest entered date in whole table and highest entered date in whole table.
2) lowest entered date in year 2012 and highest entered date in year 2012.
Lowest and highest date in year may be a same (like for year 2010) or field may be empty (like in row 7).
I am tying to use TO_TIMESTAMP but unsuccessfully.
Example:
SELECT (TO_TIMESTAMP(mydatetxt, 'DD.MM.YYYY'))
FROM " & myTable & "
ORDER BY (TO_TIMESTAMP(mydatetxt, 'DD.MM.YYYY')) ASC LIMIT 1

Also with BETWEEN I don't get wanted result.
How to write those two queries?
SOLUTION:
Thanks for all suggestions.
Igor's solution is most suitable and simple enough for me.
Dim sqlText As String = "SELECT min(to_date(nullif(mydate,''), 'DD.MM.YYYY')) FROM " & mytable
cmd1 = New NpgsqlCommand(sqlText, conn)
min = CDate(cmd1.ExecuteScalar())
If Not IsDate(min) Then
    min = CType(CDate("01.01." & myyear) & " 00:00:00", Date)
End If
fromdate = CType(CDate(min), Date)

sqlText = "SELECT max(to_date(mydate, 'DD.MM.YYYY')) FROM " & mytable
cmd1 = New NpgsqlCommand(sqlText, conn)
max = CDate(cmd1.ExecuteScalar())
If Not IsDate(max) Then
    max = CType(CDate("31.12." & myyear) & " 23:59:59.9999", Date)
End If
todate = CType(CDate(max), Date)

A: Try something like:
SELECT max(to_date(nullif(mydatetxt,''), 'DD.MM.YYYY')),
       min(to_date(nullif(mydatetxt,''), 'DD.MM.YYYY'))
FROM table_name;

SELECT max(to_date(nullif(mydatetxt,''), 'DD.MM.YYYY')),
       min(to_date(nullif(mydatetxt,''), 'DD.MM.YYYY'))
FROM table_name
WHERE date_part('year',to_date(nullif(mydatetxt,''), 'DD.MM.YYYY')) = 2012;


text:
Q: WordPress PaidMembershipsPro track day of the membership I was looking for a plugin that allowed only paid members to access certain WP pages and to display the content based on their day of the course (the course is 200 days long). I used PaidMembershipsPro, but I had to modify it to my needs and I post it here in case might be useful for someone else.
If someone buys a different "membership level" it extends it instead of overwriting (I had to make 3 levels for 3 payment plans, 1/3/6 months, I named them all the same but if someone buys 3 months and then another month it reset the duration, so there is a filter for it below). I asked on SO already, but I didn't get an answer, so I wrote the functions myself. It might be bit sloppy though.

A: the table:
tt_subs s_id(int) s_user(int) s_months(int) s_since(timestamp)

This is the function that puts the data into a table (it takes the duration as days, because all my levels were timed in days)
add_action("pmpro_after_checkout", tt_AddToSubs);

 function tt_AddToSubs($user_id){
   global $wpdb, $current_user;
   $days = $current_user->data->membership_level->expiration_number; //get days from current order
   $months = ceil($days/30);
   $today = date('Y-m-d H:i:s',strtotime('today midnight'));
   $result = $wpdb->get_results("SELECT s_user, s_months, s_since FROM tt_subs WHERE s_user = $user_id", ARRAY_A);
   $rowCount = $wpdb->num_rows;
   if($rowCount == 0)//if it's a new user
   {
     $wpdb->insert('tt_subs',array('s_user' => $user_id,
                   's_months' => $months,'s_since' => $today),
        array('%s','%d','%s')
    );
   }
   else
   {
     $sincedays = ($result[0]['s_months']*30); //counted without the new month
     $since = strtotime("-$sincedays days", strtotime('today midnight'));
     $newsince = (strtotime($result[0]['s_since']) <= $since ? $since : strtotime($result[0]['s_since'])); //if membership has passed, shift s_since so user is back in his day
     $newsince = date('Y-m-d H:i:s', $newsince);
     $months += $result[0]['s_months']; //add months to the existing ones

     $wpdb->update('tt_subs',
     array('s_months' => $months,'s_since' => $newsince),
     array( 's_user' => $user_id ), //where array(
        '%d',   // value1
        '%s'    // value2
     ),
     array( '%d' ) //where format
     );
   }
 }

this is a filter that I found for extending the memberships instead of overwriting them
add_filter("pmpro_checkout_level", "level_extend_memberships");

 function level_extend_memberships($level)
  {
  global $pmpro_msg, $pmpro_msgt, $current_user;
  //does this level expire? are they an existing members with an expiration date?
  if(!empty($level) && !empty($level->expiration_number) && pmpro_hasMembershipLevel() && !empty($current_user->membership_level->enddate))
  {
  //get the current enddate of their membership
  $expiration_date = $current_user->membership_level->enddate;
  //calculate days left
  $todays_date = time();
  $time_left = $expiration_date - $todays_date;
  //time left?
  if($time_left > 0)
  {
  //convert to days and add to the expiration date (assumes expiration was 1 year)
  $days_left = floor($time_left/(60*60*24));
  //figure out days based on period
  if($level->expiration_period == "Day")
  $total_days = $days_left + $level->expiration_number;
  elseif($level->expiration_period == "Week")
  $total_days = $days_left + $level->expiration_number * 7;
  elseif($level->expiration_period == "Month")
  $total_days = $days_left + $level->expiration_number * 30;
  elseif($level->expiration_period == "Year")
  $total_days = $days_left + $level->expiration_number * 365;
  //update number and period
  $level->expiration_number = $total_days;
  $level->expiration_period = "Day";
  }
  }
  return $level;
}

and finally a function that returns the day the user is on
function tt_myDay()
{
   global $wpdb;
   if(current_user_can('add_users'))
   {
     return 999;
   }
   else
   {
     $resultq = $wpdb->get_results("SELECT s_since, s_months FROM tt_subs WHERE s_user = ".get_current_user_id(), ARRAY_A);
     $day = ceil((time() - strtotime($resultq[0]['s_since']))/86400);
     return ($day > ($resultq[0]['s_months']*30) ? ($resultq[0]['s_months']*30) : $day );
   }
}


text:
Q: Is there a service pack for Windows 10? I was wondering, is there any service pack available for Windows 10? I had to format my disk recently, and it took several hours to download and install all the updates. I don't want to go through that process again. I wasn't able to find a single file that collects all Windows 10 updates.
I found on several places on Internet that Microsoft has announced that no service packs will be available. It is really annoying having to download over 1 GB of updates every time I install Windows 10 on a machine.

A: There is no Service Pack for Windows 10. The purpose of Service Packs is to bundle all available updates into 1 pack to avoid a long scan/install for new Updates like in Windows 7. The Updates for your current Windows 10 Build are cumulative, so they include all older updates. When you install the current Windows 10 (Version 1607, Build 14393), you only need to install the latest Cumulative Update. As today (2017-01-21), you only need to install KB3213986 which updates the Version 1607 to 14393.693.
And 1 or 2 times per year, you get a newer Feature Upgrade Build, which is technically a new OS version but still called Windows 10 which includes new features and UI changes. The next Update will be the Creators Update from April 2017 and after you made the upgrade to this Version the new Updates are again cumulative and you only need to install the latest one to be up 2 date after you have to reinstall Windows.
So, since Windows 10 service packs are not needed.

A: Windows 10 has moved away from a "Service Pack" model to a "yearly major feature update" model.
In practice, not a whole lot has changed, though! You'll be pleased to know that Microsoft makes ISO files available for download for the Windows 10 Anniversary Edition Update, which is a "Service Pack" in all but the name (its actual functionality is effectively identical to what they used to call a "Service Pack").
If you install Windows from an Anniversary Edition ISO (i.e., "Build 1607"), you'll have to do significantly less patching post-install than if you install from the "Windows 10 RTM" (Release To Manufacturing - the original Windows 10 build) ISO.
That said, there is currently no easy way that I know of to install to an end-user machine from a Windows ISO (with a graphical installer, etc.) that will leave you fully updated on first boot. This is possible using something called Slipstreaming where you basically build your own custom ISO that consists of the latest Windows Build (i.e. 1607) plus the latest Updates (which are so-called "slipstreamed into" the ISO file upon build). This is for advanced users as it's not especially easy or user-friendly to do it, and it's only worth your time to do so if you intend to reinstall very frequently or install Windows on many, many machines (5 or more).
The slipstreaming process, briefly, involves:

*

*Download and run WHDownloader

*Grab all the updates

*Grab an official ISO file of Windows 10 from Microsoft; e.g. you can find some links here (the direct links to Microsoft or its Content Delivery Network are legal ways to download Windows media; Microsoft no longer places tight control on the download of Windows installation media.)

*Use a slipstreaming tool, such as NTLite, to first open your Windows 10 ISO (the original, which you downloaded from Microsoft), and then slipstream all your updates into it.

The Winbuzzer article I linked to above contains some detailed instructions with screenshots, but I captured the general flow of it here for posterity's sake (I didn't want to take their images due to copyright).


text:
Q: Saving then loading a `tibble` causes it to be not recognised by S4 methods I have an obscure problem in R that involves the S4 class system.
First I create a tibble and save it:
df = tibble::tibble(a=1:5, b=2:6)
save(df, file="foo.Rdata")

Next, I close the R session, and start a new one (which for some reason matters).
Then, I define an S4 method that dispatches on a data.frame (which a tibble is a subclass of):
setGeneric("sumTheColumns", function(target){
  standardGeneric("sumTheColumns")
})
setMethod("sumTheColumns", signature(target="data.frame"), function(target){
    colSums(target)
})

load("foo.Rdata")
print(df)
print(class(df))
print(showMethods(sumTheColumns))
sumTheColumns(df)

From this, R outputs:
[1] "sumTheColumns"
  a b
1 1 2
2 2 3
3 3 4
4 4 5
5 5 6
[1] "tbl_df"     "tbl"        "data.frame"
Function: sumTheColumns (package .GlobalEnv)
target="data.frame"

Error in (function (classes, fdef, mtable)  :
  unable to find an inherited method for function 'sumTheColumns' for signature '"tbl_df"'
Calls: sumTheColumns -> <Anonymous>
Execution halted

So as you can see, the tibble is being saved and loaded correct, and it retains its classes, however it no longer dispatches correctly. Interestingly, if you define and call these same methods in the first R session where we create df, these dispatch correctly.
Why is this happening, and how can I fix it?
In case this is an OS-specific bug, here is some output from sessionInfo:
> sessionInfo()
R version 4.1.1 (2021-08-10)
Platform: x86_64-conda-linux-gnu (64-bit)
Running under: Ubuntu 21.04

A: Compare the loadedNamespaces() entries in the two situations.  I see
> loadedNamespaces()
[1] "compiler"  "graphics"  "utils"     "grDevices" "stats"     "datasets"  "methods"   "base"

in a clean new session, but after creating df, it grows to
> loadedNamespaces()
 [1] "compiler"  "magrittr"  "ellipsis"  "graphics"  "pillar"    "glue"      "utils"
 [8] "tibble"    "grDevices" "crayon"    "stats"     "utf8"      "fansi"     "datasets"
[15] "vctrs"     "methods"   "lifecycle" "pkgconfig" "rlang"     "base"

So one of those new packages fixes the issue.  I'd guess it's tibble itself, and indeed I see the error in the new session, but not after I run loadNamespace("tibble") (which gets everything in the second list).  So a solution is:
To get your dataframe methods to work on tibbles, you could run
loadNamespace("tibble")

before calling them.  You would want to do this if you intend to treat tibbles as tibbles in other places, e.g. to get them to print the way tibbles print.
Alternatively, if you just want your code to work on tibbles as if they were dataframes, you could do what the tibble package does, and run
methods::setOldClass(c("tbl_df", "tbl", "data.frame"))

That won't load any packages, but it will tell the S4 system that tibbles inherit from dataframes.


text:
Q: Apache HTTPD as a proxy I need to redirect all the requests from
localhost:8080/app1/ to localhost/app1.
which is the best way to do it.
The only requirement is that the user must never be aware that he is accessing the application at port 80. i guess I need to set up Apache HTTPD proxying - I'm just not sure which is the best way to do it.
Thanks in advance.

A: Here's a full example, it's what I use to frontend apt-proxy with an apache that's already using port 80.
You need to put this either inside the relevent VirtualHost directive.
    ProxyRequests on
    ProxyPass               / http://127.0.0.1:1723/
    ProxyPassReverse        / http://127.0.0.1:1723/

    <Proxy http://127.0.0.1:1723/>
            Order allow,deny
            Deny from none
            Allow from all
    </Proxy>

You may also need to run a2enmod proxy if the proxy module isn't enabled by default.

A: You're looking for "reverse proxy" configuration.  Check the mod_proxy docs, look at ProxyPass.


text:
Q: sharing foreign key Hibernate I am trying to code this model using JPA + Hibernate

here is my code for entity level one
Entity level one
@Entity
public class LevelOne {
@EmbeddedId
LevelOnePK levelOnePK;

@OneToOne(mappedBy = "levelOne")
private LevelTwo levelTwo;

private String valueCol;

//getters setters omitted
}

level one Pk
@Embeddable
public class LevelOnePK implements Serializable {
private int idOne;
private int idTwo;
private int idThree;

//getters setters omitted
}

Entity Level two
@Entity
public class LevelTwo {

@Id
private int LondId;

@OneToOne
@JoinColumn(name = "lone_id_one")
@JoinColumn(name = "lone_id_two")
@JoinColumn(name = "lone_id_three")
private LevelOne levelOne;

@OneToOne(mappedBy = "levelTwo")
private LevelThree levelThree;

//getters setters omitted
}

Entity Level three
@Entity
public class LevelThree {

@Id
private int LondId;

@OneToOne
@JoinColumn(name="l_one", referencedColumnName="lone_id_one", insertable=false, updatable=false)
@JoinColumn(name="l_two", referencedColumnName="lone_id_two", insertable=false, updatable=false)
@JoinColumn(name="l_three", referencedColumnName="lone_id_three", insertable=false, updatable=false)
private LevelTwo levelTwo;

private String valueCol;
//getters setters omitted
}

What this code is doing
this code is successfully mapping PK of Level one entity to Level two entity as foreign key.
Where I am having problem
I am unable to map composite foreign key of Level two entity into Level three entity and getting this error
Caused by: org.hibernate.AnnotationException: referencedColumnNames(lone_id_one, lone_id_two, lone_id_three) of com.example.testQuestions.LevelThree.LevelThree.levelTwo referencing com.example.testQuestions.LevelTwo.LevelTwo not mapped to a single property

where I am doing wrong?

A: Your model doesn't seem correct. The FK in LevelThree is a reference to LevelOne, not LevelTwo.
If you want LevelThree to have a reference to LevelTwo, the FK would be a single Long, as the PK of LevelTwo is a single Long


text:
Q: MongoDB-Style Array Aggregate in Postgres I'm trying to figure out how to translate a MongoDB aggregate query to Postgres. My schema has an array of strings called array_one, a date field updated, and a cluster field that identifies which documents are clustered together (i.e. share a cluster ID).
What I need to do is find the most popular cluster values of documents that pass a filter (array_one containing a value, updated between a time, etc).
This is my MongoDB aggregate pipeline:
var query = [
      { $match: { array_one: 'INCLUDE_VAL', updated: { $gt: new Date(Date.now() - (1000 * 60 * 60 * trendingDurationHours)), $lt: new Date() } } },
      { $group: {_id: '$cluster', count: { $sum: 1 } } },
      { $sort: { count: -1 } },
      { $limit: 10 }
];

Any idea how to do this in Postgres?


text:
Q: DynamoDB Restructuring StringSet to One-To-Many Tables I have DynamoDB table with the following structure:

*

*SN (String - Primary Partition Key)

*Label (String)

*Product (String)

*Tags (StringSet)

Here is some sample data:
SN          Label                        Product     Tags
XXXX-123    Acme Cheese System One       Z100        {"Acme Cheese", "Z100"}
XXXX-456    Acme Cheese System Two       X22         {"Acme Cheese", "X22"}
XXXX-789    Bob's Burritios System One   Z100        {"Bob's Burritios", "Z100"}

I need to be able to query against specific tags and return all items that contain the specified tag. For example, I might write a query to find all items tagged "Acme Cheese" or "Z100". I would want to retrieve all items that contained this tag.
I cannot use a Global Secondary Index, as DynamoDB does not support indexing StringSet fields. According to this question: DynamoDB - Global Secondary Index on set items, it is recommend to structure my data using a one-to-many table. I have read the documentation here DynamoDB Docs: OneToMany, but it still was not clear to me on how to create such a structure.
My question is: How do I create such a table? What would my table schema and keys look like?

A: I had a similar problem and I solved this by separating the main table into multiple tables.
Following would be the schema
SN_Master:

SN - Hash
Label
Product

SN_Details:

TagName - Hash
SN - Range

So now whenever you insert any row you have to insert in sn_master with main information and tag related information in sn_details
So basically now your data will look like:
SN          Label                        Product
XXXX-123    Acme Cheese System One       Z100
XXXX-456    Acme Cheese System Two       X22
XXXX-789    Bob's Burritios System One   Z100

TagName        SN
Acme Cheese    xxxx-123
Z100           xxxx-123
Acme Cheese    xxxx-456

Now you can query sn_details table to retrieve all the products of particular tags
CONS: If you have billions of record one particular tag then your performance will be affected as the Hash is not distributed properly.


text:
Q: Limit $\lim_{x\to2^+}x{\sqrt{x-1}\over\sqrt{x-2}}$ I am having problems with this  limit problem, I tried to rationalize and keep getting that the limit is $∞$ but in the book the answer is $2$, am I making a mistake here ?
$$\lim_{x\to 2^+} x\frac{\sqrt{x-1}}{\sqrt{x-2}}$$

A: The limit is $+\infty$ it of the form ${2\over 0}$

A: Note that
$$\lim_{x\to2^+}x{\sqrt{x-1}\over\sqrt{x-2}}=\left(2\cdot\frac{1}{0^+}\right)=+\infty$$


text:
Q: using git for web testing and deploying live site At the minute I have a local git repo which sits in H: drive. When I make changes to the files and save them, they are stored here. I can then commit, push and pull the files and branches to and from a remote repo on my git server.
What I would like to do is work on files and instead of saving them to the local H drive I would like to save them onto my test server, so that they can be run and tested from that server in a browser. When all of the testing is complete I would like to merge the files from the test server to the live server and have them there as the live system or would I need to pull files from my test server and from my live server and merge them locally and push the master branch back to the live server?
Also when the branches are merged into my live master branch and pushed to the live server, how would I 'unpack' all of the files from the git repo so they can run as the live site.
I have experimented with git archive and read up on git bundle to try and see if this would allow me to do an 'unpack' of sorts, but so far I haven't been able to achieve anything I can really work with.
Is it possible for this to work the way which I have described it and if so how would you go about doing it?
If it isn't possible or if there is a better way to do this which I have overlooked, please let me know.

A: I don't know what you mean with the unpacking thing but I guess what you are looking for is a possibility to deploy changes.
Let's say you are developing your app and you use a staging or dev branch for that. Now, if you want to test your app at your testserver you first have to push everything to your repository.
You might want to look into Capistrano.
With Capistrano you can easily deploy your app no matter what programming language you are using.
The Procedure for that would be to install Capistrano first using "sudo aptitude install capistrano" or even better "gem install capistrano".
Now that you have it you can go to your app locally and type "capify ."
Since you have multiple branches you want to deploy to different servers have a look at Capistrano Multistage Ext.
Now Capistrano should create some files and you should open .config/deploy.rb and insert your data for your repository, your targetserver and the branch you want to push to the targetserver. There are several HowTo's but the default.rb should look pretty familar to you.
Now through Capistrano your Test Server is linked to the Staging branch of your repository and you can use "cap staging deploy" to deploy your app to the test server via ssh.
In case everything works you can locally merge the staging branch into the master and push it into your repository. Now since your Live system should be linked to the master branch of your repo you can type "cap production deploy" to have the app working on your live system. You might have to care about database migrations but overall that's it.
A quick install/config and you have a way better workflow than you have now.
In case you don't have ssh access to your server you might have a look at git-ftp.
Hope this is a help for you to solve your problem.

A: If your test server is on your LAN, you can just install Samba on it, and then mount its webroot as your H: drive.  If it's a remote server, some sort of SSHFS client (such as Expandrive) might work.


text:
Q: Passing numpy arrays from dataframe after using groupby into a function that returns numpy arrays before appending back to dataframe If i have a dataframe with 2 groups,
--------------------------------------------------
| Date   | Code  | Input  |
--------------------------------------------------
| 1/1/18 | A     | 10     |
--------------------------------------------------
| 1/1/18 | B     | 100    |
--------------------------------------------------
| 1/2/18 | A     | 11     |
--------------------------------------------------
| 1/2/18 | B     | 101    |
--------------------------------------------------

I first apply groupby to the code to get the following,
--------------------------------------------------
| Date   | Code  | Input  |
--------------------------------------------------
| 1/1/18 | A     | 10     |
--------------------------------------------------
| 1/2/18 | A     | 11     |
--------------------------------------------------
| 1/1/18 | B     | 100    |
--------------------------------------------------
| 1/2/18 | B     | 101    |
--------------------------------------------------

I then pass the inputs according to the code and date to a function that only takes in and returns a numpy array
def func([10, 11]):
    returns [20, 25]

def func([100, 101]):
    returns [97, 95]

How can I join the numpy array to the corresponding date and code in the original order to get the intended dataframe below:
--------------------------------------------------
| Date   | Code  | Input  | Output
--------------------------------------------------
| 1/1/18 | A     | 10     | 20
--------------------------------------------------
| 1/1/18 | B     | 100    | 97
--------------------------------------------------
| 1/2/18 | B     | 11     | 25
--------------------------------------------------
| 1/2/18 | B     | 101    | 95
--------------------------------------------------

A: You should be able to do this with simple slicing.
First create dataframes to work with
cols = ['Code', 'Input]
index = pd.date_range('20180101', '20180105', freq='1D')

df1 = pd.DataFrame(data=np.random.randint(0, 10, (5, 2)), index=index, columns=cols)
df2 = pd.DataFrame(data=np.random.randint(0, 10, (5, 2)), index=index, columns=cols)

df3 = pd.concat([df1, df2], axis=0)

Identify rows you want to pass into your function.  Note: This is only an example, this can be modified to operate on a column instead of the index.
idx = df3.index==df3.index[0]

>>> df3.loc[idx, :]
Out[21]:
               Code  Input
    2018-01-01    A      1
    2018-01-01    B      0

You can then grab data from this slice and pass it into your function.
>>> df3.loc[idx, 'Input'].values
Out[21]:

       array([1, 0])  # see, it's an array.

You can add the row to df3 by passing the output of your function via
df3.loc[idx, 'Output'] = yourFunction(df3.loc[idx, 'Input'].values)


text:
Q: post-receive hook curl not found I have problem with automatic build of my project on Jenkins. I've created post-receive hook file:
 #!/bin/bash
curl --user myJenkinsLogin:APIToken -s http://myJenkinsUrl/job/JenkinsProjectName/build?token=AuthToken

But when I commit and push changes to my repo, after push i got a message:
remote: hooks/post-receive: line 2: curl: command not found
How can I fix this problem?


text:
Q: SabreAMF: PHP Integer array to Java Integer List I am using SabreAMF to call on a Java webservice.
This is the Java function:
@RemotingInclude
public Boolean testAMF(List<Integer> ints)
{
    for (Integer element : ints)
    {
        //do something
    }

    return true;
}

Note that this function accepts a List of Integers.
This is the PHP code:
<?php
    require 'SabreAMF/Client.php';

    function make_request($service, $method, $params)
    {
        $client = new SabreAMF_Client('https://xxx');
        return $client->sendRequest($service.'.'.$method,$params);
    }

    $ints = array(1,2);
    $parameters = array($ints);
    $result = make_request('chartManager','testAMF',$parameters);
    var_dump($result);
?>

I pass along an array containing 2 integers.
In Java, this array comes in as a list, but one containing Doubles, not ints.
I then get the following error:
java.lang.ClassCastException : java.lang.Double cannot be cast to java.lang.Integer

Why does it change my integer to a double ?

A: There are only Doubles in AMF0. So you need to change the type to Double.
You can get integer support if you use AMF3:
    $client = new SabreAMF_Client('https://xxx');
    $client->setEncoding(SabreAMF_Const::AMF3);
    return $client->sendRequest($service.'.'.$method,$params);


text:
Q: How to make  full width of page irrespective of the parent How do I make the
 width 100% of the screen, not its parent?
CSS
#abc {
  width: 700px;
}

hr {
  width: 100%;
}

HTML

adsasd

A: You cannot do it the way that you have it structured. You need the
 outside of that container that has a fixed width. Otherwise 100% width of the
 will be relative of its parent, not the page. Try

  adsasd

  asdfghjkl

Another thing that you can do is to enclose the content in a container with that width, but not the div containing the content and the hr.

adsasd

A: If it was me, I'd refactor the markup to something like:

Buttons

    Main

and use CSS for the horizontal lines:
#menu
{
    width:100%;
    border-top:solid 1px black;
    border-bottom:solid 1px black;
}

#menu .buttons, #main
{
    width:400px;
    margin:0 auto;
}

#menu .buttons
{
    background-color:#F00;
}

Demo


text:
Q: How does the introduction of living things into a closed system affect the rate of change of entropy? Does the introduction of living things into a closed system increase or decrease the overall rate of change of entropy of a system?

A: There is clearly no universal answer. One would have to say what living things, and in what state, have been introduced.
Life forms are generally capable of reducing their own entropy, but of course they increase the entropy of their environment by an even larger amount because no one, not even life forms, have the right to violate the second law of thermodynamics (saying that the total entropy never decreases).
So living things are able to cool them down, order them, and so on. However, we must realize that the numerical value of the entropy drop coming from organized or symmetric matter – e.g. from the symmetry of an egg – is very small. Moreover, there is nothing really mysterious or "vitalistic" about the effect of life on entropy. For example, the ability of the organisms to cool themselves down by sweating is shared by refrigerators.
If one really calculates the rate of change of the entropy, living things generally create heat by metabolism and this heat creation is the main term that influences the entropy, too. Once again, there is nothing terribly special or mysterious about heat arising from metabolism in living forms; fire is capable of increasing the entropy via produced heat, too.

A: Maybe we can consider a scenario. Suppose a human is introduced into the system. What if they have the ability to halt the largest entropic processes not directly related to their own survival? An example would be if there is fire in the closed system, the human might be able to stop the fire, thereby greatly reducing the entropy increase (proportional to the original magnitude of the fire). If the human's own metabolism incurs a smaller amount of entropic change than the fire was doing previously, then you have a case where this system's entropy has slowed its increase.

A: It is possible that in some very very special case the overall rate decreases, but in general it will increase.
Consider a mature living system, its thermodynamic state is well-approximated by a stationary state, which means that entropy does not change $\Delta S=0$. Now using the DeDonder decomposition
$$\Delta S= \Delta_\mathrm{i} S + \Delta_\mathrm{e} S$$
and the second law
$$\Delta_\mathrm{i} S \geq 0$$
We obtain the well-known relation $\Delta_\mathrm{e} S \leq 0$ that proves that living systems are dissipative structures which need a negative flow of entropy to survive. I suppose that by "closed" you really mean isolated (i.e. neither matter nor energy exchange). If the living system is isolated then the flow of entropy is zero $\Delta_\mathrm{e} S = 0$, cannot compensate the entropy generated by dissipative processes in its interior, and dies
$$\Delta S= \Delta_\mathrm{i} S \geq 0$$

A: Intelligent living things -despite of there behavior as a machines that decreasing their own entropy by producing external work and increasing environment entropy as was described by
Luboš Motl- can also decrease the entropy locally, see for example Boltzmann Brain Paradox and Maxwell Demon, anyway such statements still speculative to some extent and not resolved yet fully.


text:
Q: Mixing Text and Formulas I'm trying to do some typesetting in which I mix text with formulas.  The Mathematica documentation has a section titled "Mixing Text and Formulas" which pretty much describes what it is that I'd like to do. However I can't seem to work out how they do it.
The tutorial says to use Ctrl+( to start entering a formula within text or vice versa, however I don't seem to get the result I am after.
This is what their example looks like:

Notice that they have been able to mix text with a formula that is in TraditionalForm, this is what I would like to be able to do.
If I enter:    "Hello World = " x^2 but Ctrl+( before I enter the x^2....

Hello World = x^2

Further Clarification
Some further clarification (I would have preferred to enter this clarification after all of your helpful hints below but the guidelines recommend against answering your own question or adding further clarification in that way):
In my text box I'd like to use a prior defined equation rather than having to re-enter and format it in the text box. Hopefully this next image will clarify:

A: You need to be in a text cell to begin with. Starting on a cell division (so your cursor is horizontal instead of vertical), press Alt+7 to create a text cell. There you can type text and it will get interpreted as such. If you then want to input maths, type Ctrl+( and it will create a math box. You can also create a math box by, e.g. creating a superscript using Ctrl+^.

A: Use a palette from the menu when typing x^2 or use Ctrl+^ to get a superscript box.

A: Thanks for your help guy's, I have found a solution that fulfils my requirements.


text:
Q: Ruby On Rails in MAMP mySQL Snow Leopard I'm trying to find step-by-step instructions to run Ruby on Rails on MAMP server and use MAMP's mySQL database.  I am on Snow Leopard also.  I have read Hivelogic's article about this but I really don't want to compile rails, ruby and mySQL.
Anyone have any suggestions

A: It is very simple, just edit your socket to MAMP's mysql socket in your rail's /config/database.yml
development:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: myproject_development
  pool: 5
  username: root
  password: root
  host: localhost
  socket: /Applications/MAMP/tmp/mysql/mysql.sock

A: I can suggest this tutorial for you;
Using Ruby MySQL Gem with MAMP 1.8.x on Snow Leopard


text:
Q: RuntimeException: Could not dispatch event @ otto we have an issue in our current app-version with the EventHandler from otto.
We get a RuntimeException in our crash-log, with following description:

"Reason: java.lang.RuntimeException: Could not dispatch event:
  classcom.nameOfBrand.ui.events.SwitchFragmentEvent to handler
  [EventHandler public void
  com.nameOfBrand.ui.activities.MainActivity.onSwitchFragmentEvent(com.nameOfBrand.ui.events.SwitchFragmentEvent)]"

We have a button and in its onClickListener we fire an self-defined SwitchFragmentEvent.
In some weird situations, the framework can't dispatch the Event and throws an RuntimeException.
The fragment with the button extends AbstractResultListFragment and this one extends AbstractFragment. We register the EventBus in the onResume of AbstractFragement and unregister it at onPause. Everything works fine, except at this one button :/
Does anyone have an idea or had ever to do with something like this?
UPDATE:
Scompt was right. The RuntimeException was thrown from otto cause of a NullPointerException in our code. Thx
Tipp: Read your crash-logs until the end ;)

A: There should be a wrapped exception at that point that will provide more information about the crash.

A: If you use with AndroidAnnotation, add @UiThread to view treatment method. Note that the method should not be private.


text:
Q: reload the data of specific uitableview cell
Possible Duplicate:
Is it possible to refresh a single UITableViewCell in a UITableView?

Sorry if the question is stupid but instead of using [mytableview reloaddata],how can we reload the data of only specific UITableViewCell.

A: You want UITableView's reloadRowsAtIndexPaths: withRowAnimation: method.  I've linked the documentation for you.
All you need to provide is the index paths to the cell(s) you want to redraw.


text:
Q: Get back the webdriver.Locator out of an elementFinder Given I have the elmFinder variable:
var elmFinder = element(by.css('.thing'));

What if i need to get back the webdriver.Locator, a.k.a locator strategy? i.e.
elmFinder.??? //=> by.css('.thing')

I'm looking after the function ??? if it exists.
UPDATE:
This feature has been merged and we can now do:
elmFinder.locator();

A: UPDATE:
This feature has been merged and we can now do:
elmFinder.locator();

Old answer:
You cannot. The element finder does not keep a reference to the locator:
https://github.com/angular/protractor/blob/master/lib/protractor.js#L103

A: What I typically do is store the selector in it's own var, and then place that string into the selector, so I can use both interchangably:
var cssThingSelector = '.thing';
var elem = $(cssThingSelector);

Something like that.
Edit:
I will also add that you can nest findElement calls from selenium webelement objects.
So, if there is another item in the inner html of the .thing web element (say, a span tag), you could just nest another findElement call:
var spanElem = elem.$('span');

You can do this as much as you'd like.


text:
Q: How to set current data (not newData)? The Firebase Realtime Database Rules simulator is a very powerful way to test your rules.  However, it is not clear that you can simulate current data values. It seems that you can only test newData values.
That is, I can't seem to simulate rules that contain, for example (the actual rule here isn't important, just that it contains references to data, not just newData):
".write": data.child('child1').val() > newData.child('child2').val()

The simulator seems to allow the setting of newData, but not data. Is there a way?

A: The current data is always read from your existing Firebase Database. There is no way to specify a different value for data in the simulator.


text:
Q: Series/inequalities proof Suppose that $\{x_m\}$ is a sequence of positive, non-zero numbers such that $\sum_{n=1}^{\infty} {x_n}$ diverges, and let $S_n = x_1 + x_2 + ... + x_n$. Prove the following:
(i) $\sum_{n=1}^{\infty} \frac{x_n}{1 + x_n}$ diverges.
(ii) For all $m, n \geq 1$, $\sum_{j=1}^{n} \frac{x_{m + j}}{S_{m + j}} \geq 1 - \frac{S_m}{S_{m + n}}$
(iii) For all $n \geq 2$, $\frac{x_n}{S_n^2} \leq \frac{S_n - S_{n-1}}{S_nS_{n-1}}$
My attempt:
(i) We check using the convergence/divergence tests:
Divergence test: Consider the limit: $\lim_{n\to\infty} \frac{x_n}{1 + x_n}$. Does this limit $\neq 0$? Inconclusive.
Direct Comparison Test: Is $x_n \leq \frac{x_n}{1 + x_n}$? This only happens if $1 \leq \frac{1}{1 + x_n} \implies 1 \geq 1 + x_n$. This is false for $n \geq 1$ as $x_n$ is non-negative.
Ratio test: Consider the limit: $\lim_{n\to\infty} |\frac{\frac{x_{n+1}}{1 + x_{n+1}}}{\frac{x_{n}}{1 + x_{n}}}| = |\frac{x_{n+1}(1 + x_n)}{(1 + x_{n+1})x_n}|$. Inconclusive.
Root test: Consider the limit: $\lim_{n\to\infty} {|\frac{x_{n}}{(1 + x_{n})}|}^{1/n}$. Inconclusive.
(ii) No idea how to do this one.
(iii) Consider the elementary sum $S_n - S_{n-1}$:
$$S_n - S_{n-1} = (x_1 + x_2 + ... + x_n) - (x_1 + x_2 + ... + x_{n-1}) = x_n$$
Notice that because $x_n$ are non-negative, we have that
$$S_n \geq S_{n-1} \implies S_n^2 \geq S_nS_{n-1} \implies \frac{1}{S_n^2} \leq \frac{1}{S_nS_{n-1}} \implies \frac{x_n}{S_n^2} \leq \frac{x_n}{S_nS_{n-1}} \implies \frac{x_n}{S_n^2} \leq \frac{S_n - S_{n-1}}{S_nS_{n-1}}$$
For the ones I attempted, are they correct? Despite trying for the last few hours to use what I have learned thus far, I still cannot figure out how to go about proving (i) and (ii) ones? Any hints or assistance are much appreciated.

A: For (i) separate two cases: If $x_n>1/2$ infinitely often then $x_n/(1+x_n)$ does not tend to zero. Otherwise $x_n/(1+x_n) \ge  x_n/(3/2)$ for all large enough $n$.
For (ii) replace $S_{m+j}$ on LHS by $S_{m+n}$ to reduce the sum.


text:
Q: How to insert a colon between a number and a quote? Source:
9981"TVHeadend HTTP server (web interface)"

and add a colon between to make python dictionaries!
But these are registered known IP address and too many to do one at a time!
I tried replacing the same find and adding the : but it replaced the number with the regex code!
Not ever sure if my code was correct!
Also I want to find the first double quote as you can see each line has two!

A: *

*Ctrl+H

*Find what: \d+\K(?=")

*Replace with: :

*CHECK Wrap around

*CHECK Regular expression

*Replace all
Explanation:
\d+             # 1 or more digits
\K              # forget all we have seen until this position
(?=")           # positive lookahead, make sure we have a double quote after

Screen capture (before):

Screen capture (after):


text:
Q: Multiple MongoDB collection names for the same Java class I am using Spring's MongoRespository. I have one class but it is called by two methods and I want to store that class in Mongo based on which method called it. How would I differentiate how it was used by having two different collections based on that one class in mongo?
Right now I have my have two repository interfaces in my dao.
public interface PastOpportunityRepository extends MongoRepository<DMOpportunity, String>,       CustomPastOpportunityRepository {}

and
public interface PredictiveOpportunityRepository extends MongoRepository<DMOpportunity, String>, CustomPredictiveOpportunityRepository {`

I want to avoid making two differently named classes with the same code.

A: I suggest using Springs MongoTemplate that has overloads that take the collection name.
MongoTemplate
MongoTemplate.find(Query query,               Class entityClass,               String collectionName)
MongoTemplate.insert(Object objectToSave,          String collectionName)


text: Q: Raster projection changes to none when loading into MapWindows after already being defined in ArcMap I am trying to load a number of raster files (.tif) into MapWindows v.4.8.8. These rasters have previously been reprojected in ArcMap to have the projection WGS_1984_UTM_Zone_60S and saved with this projection. When I load these rasters into MapWindows their projection comes up as "none" and I can't run any analysis on them as a "no spatial reference information" error pops up. I am very new to using MapWindows but I need to use it for a specific plug-in.


text:
Q: Can I specify a custom color (e.g., RGB) for Alloy Analyzer to use in visualizations? In the theme pane, I'd love to get rid of the barely-readable yellow and replace it with an orange and maybe swap the red for a darker red.
Is there an XML (or some kind of easily-editable config file) in the Alloy build that defines something like RGB values that show in the Alloy visualizer theme selections? Or some other way to accomplish a change in what's available in the drop-down menu without too much effort?
I'm trying to avoid doing a deep dive into the repo and associated documentation if I can help it.
I have a series of modules that reuse certain signatures and relations and I'd like to keep my color scheme as consistent as possible, so Magic Layout won't really work for me. Thanks!

A: Have you tried switching colors schemes?


text:
Q: Joint density of minimum and maximum - minimum. Let X = min(S, T), Y = max(S, T) for independent exponential ($\lambda$) variables S, T. Let Z = Y - X.
Find the joint density of X and Z. Are they independent?
Identify the marginal distributions of X and Z.

A: Here is an exploration of your problem using simulation in R statistical software, with some additional hints.
I used $\lambda = 0.1$, so $E(S) = SD(S) = 10$ and $E(T) = SD(T) = 10.$
For a million iterations of your experiment, here are some findings (correct
to about three significant digits).
 s = rexp(10^6, .1);  t = rexp(10^6, .1)
 x = pmin(s,t);  y = pmax(s,t)
 z = y - x
 mean(x);  sd(x)
 ## 5.004163  # aprx E(X)
 ## 5.01231   # aprx SD(X)
 mean(y);  sd(y)
 ## 15.0305   # aprx E(Y)
 ## 11.19881  # aprx SD(Y)
 mean(z);  sd(z)
 ## 10.02633  # aprx E(Z)
 ## 10.01379  # aprx SD(Z)

Here are histograms of the simulated distributions of $X, Y,$ and $Z$.
The density curve of $Exp(2\lambda)$ is a good fit to the histogram of $X.$
The distribution of $Y$ is clearly not exponential [notice the shape of
the histogram and the fact that $E(Y) \ne SD(Y)$.] The density curve
of $Exp(\lambda)$ is a good fit to the histogram of $Z$.

To derive the distribution of $X,$ notice that its CDF is
$$ F_X(u) = 1 - P(X > u) = 1- P(S > u)P(T > u) = 1- e^{-\lambda u}e^{-\lambda u} = 1- e^{-2\lambda u},$$
and differentiate the CDF to find the PDF.
To derive the distribution of $Y,$ notice that its CDF is
$$ F_Y(u) = P(Y \le u) = P(S \le u)P(T \le u) = \cdots ,$$
and differentiate the CDF to find the (nonexponential) PDF.
As a check, you can see that $E(Y) = \frac{1}{2\lambda} + \frac{1}{\lambda}.$
Roughly, the rationale is that the mean is the sum of the waiting time for the minimum
[at which time we start the clock again because of the 'no-memory' property]
and we wait another $1/\lambda$ unit of time for the second exponential event
to occur.
To find the distribution of $Z$ ponder the intuitive rationale above
for $E(Y)$ and @Henry's Hint.
This does not answer everything you asked, but I hope it gives you enough
hints and intuition to finish the rest for yourself.


text:
Q: TextTheme fields not match Sketch project text styles I use material design plugin for Sketch to design my app. Now I need to set up my app theme to completely satisfy my prototype. There is no issues with colors. But with text I see mismatch of fields of TextTheme class and generated by plugin styles
Material typography:
headline1
headline2
headline3
headline4
headline5
headline6
subtitle1
subtitle2
body1
body2
button
caption
overline

TextTheme fields:
body1
body2
button
caption
display1
display2
display3
display4
headline
overline
subhead
subtitle
title

What is the correct fields matching here?

A: Found in reference:
NAME       SIZE   WEIGHT   SPACING  2018 NAME
display4   112.0  thin     0.0      headline1
display3   56.0   normal   0.0      headline2
display2   45.0   normal   0.0      headline3
display1   34.0   normal   0.0      headline4
headline   24.0   normal   0.0      headline5
title      20.0   medium   0.0      headline6
subhead    16.0   normal   0.0      subtitle1
body2      14.0   medium   0.0      body1
body1      14.0   normal   0.0      body2
caption    12.0   normal   0.0      caption
button     14.0   medium   0.0      button
subtitle   14.0   medium   0.0      subtitle2
overline   10.0   normal   0.0      overline


text:
Q: Differential of a matrix function with Taylor development I'm a beginner and I have a question. I'm sorry for my bad english.
Let $A$ be an invertible n by n matrix, and let $F$ be a function defined on $M_n(C)$ by $F(X) = X^2 - A$.
I would like to know how we can calculate $DF(X)(H)$ the differential of $F$ at the point $X \in M_n(C)$ for an increase $H \in M_n(C)$, using a Taylor development at the order 1.
Could someone help me ? Thank you in advance.

A: In this case, the best way to calculate the directional derivative is straight by definition.
$\begin{align}DF(X)H&=\lim_{t\to0}\frac{F(X+tH)-F(X)}{t}\\&=\lim_{t\to0}\frac{tHX+tXH+t^2H^2}{t}\\&=HX+XH.\end{align}$


text:
Q: failed to compute cache key: failed to create hash for : operation not supported while attempting to build an image in Docker/macOS, I get the following error:

failed to compute cache key: failed to create hash for
/app-temp/client/dist: operation not supported

My Dockerfile looks like this:
FROM node:lts-alpine as ui-build
WORKDIR /app-temp
COPY client/ ./client/
RUN cd client && npm install
RUN cd client && npm run build

FROM node:lts-alpine as api-build
WORKDIR /app
COPY --from=ui-build /app-temp/client/dist ./client/dist
COPY server/ ./server/
RUN cd server && npm install
EXPOSE 3000
CMD ["node", "/app/server/src/index.js"]

And the docker command that I am using is:
docker build -t test-image .

Now, note that the image is successfully built in a Linux machine. However, the above-mentioned error persists in a macOS machine.
I am running macOS Big Sur 11.2.1.
Any ideas as to how solve this problem?
Thanks in advance.

A: just in case someone else finds himself here
Look in your .dockerignore file if dist is in the list
Also, try building with BUILDKIT disabled
DOCKER_BUILDKIT=0 docker build ....

A: Im gonna throw my solution out there.
Setup: .net 5 web app with docker enabled, contains a dockerfile that was created by visual studio.
There was a step where the docker file was saying to copy my csproj up to the parent folder. I edited the source directory to from parent/myproject.csproj to myproject.csproj then I ran docker build and it worked.
Im assuming that when I run docker build I was down one level in the child folder where the dockerfile lives, and the paths just werent lining up.


text:
Q: Passing procs and methods I came across this code:
squareIt = Proc.new do |x|
  x * x
end

doubleIt = Proc.new do |x|
  x + x
end

def compose proc1, proc2
  Proc.new do |x|
    proc2.call(proc1.call(x))
  end
end

doubleThenSquare = compose(doubleIt, squareIt)
squareThenDouble = compose(squareIt, doubleIt)

doubleThenSquare.call(5)
squareThenDouble.call(5)

doubleThenSquare is called with 5. doubleThenSquare is equal to the return value of compose, which has its two parameters doubleIt and squareIt passed.
I don't see how 5 is passed all its way into the different procs Proc.new do |x|. How does it know what x is in each case?

A: Let's step through it.
doubleIt = Proc.new do |x|
  x + x
end
  #=> #<Proc:0x00000002326e08@(irb):1429>

squareIt = Proc.new do |x|
  x * x
end
  #=> #<Proc:0x00000002928bf8@(irb):1433>

proc1 = doubleIt
proc2 = squareIt

compose returns the proc proc3.
proc3 = Proc.new do |x|
    proc2.call(proc1.call(x))
end
  #=> #<Proc:0x000000028e7608@(irb):1445>

proc3.call(x) is executed in the same way as
proc3_method(x)

where
def proc3_method(x)
  y = proc1.call(x)
  proc2.call(y)
end

When x = 5,
y = proc1.call(5)
  #=> 10
proc2.call(10)
  #=> 100

proc3_method(5) therefore returns 100, as does proc3.call(5).


text:
Q: K2 Joomla: show the last modified article in home page I think this should be easy but cannot make it work ... I'm using k2 on Joomla for handling articles and i want to show on the home page the last modified blog post ... i've create a Home category under which i've put some subcategories, bound to several K2 article items. In the home menu item i've created a "Latest item from users or categories" that correctly select the last 1 item. If i change the modified date to another article, i do not see it in the home page.
What am i doing wrong?


text:
Q: Is there a possibility to get the content of the popdown list of a ttk::combobox before it is opened the first time? I create a mask which shows only a combobox. I want to color certain elements in red.
For several reasons I have to hold a given structure, so that I need three files for it. The first creates the toplevel, in the second the mask is created and there are also the methods to fill the combobox. The third file
includes all methods to create and to handle the combobox.
So this is the first file

(vmHelmert2.tcl):

    #!/bin/sh
    #\
    exec vmwish "$0" ${1+"$@"}

    package require itcl
    auto_mkindex . vmCombobox2.itcl vmMaskHelmert2.itcl
    lappend auto_path /myPath

    namespace eval vmHelmert2 {
       variable helmert
    }

    proc vmHelmert2::grundmaske {} {

       set top [toplevel .top  -class Helmert]
       set frMain [frame $top.centrum]
       pack $frMain -expand 1 -fill both

       set helmertWidget [vmMaskHelmert2 #auto $frMain]
       set helmert(widget) [$helmertWidget getThis]

    }

    vmHelmert2::grundmaske

This is the second file

(vmMaskHelmert2.itcl)

    package require Itcl

    ::itcl::class vmMaskHelmert2 {

       public method getThis {}

       private method createMaskHelmert {w}
       private method setAnsatzList {liste}
       private method faerbeAnsatzListe {}

       private variable pfd
       private variable data

       constructor {w} {
          createMaskHelmert $w
          return $this
       }

        destructor {
          #puts "DESTRUCTOR wird jetzt gestartet."
       }
    }

    ::itcl::body vmMaskHelmert2::getThis {} {
       return $this
    }

    ::itcl::body vmMaskHelmert2::createMaskHelmert {w} {
       set pfd(frMain) [frame $w.frMain]
       pack $pfd(frMain) -anchor nw -expand 1 -fill both
       set pfd(c_ansatznr) [vmCombobox2 $pfd(frMain).c_ansatznr \
                                -state normal \
                                -width 15\
                                -justify right]
       pack $pfd(c_ansatznr) -side left
       [$pfd(c_ansatznr) component combobox] configure -postcommand "[itcl::code $this faerbeAnsatzListe]"

       set data(ansatzList) [list 1 0 2 1 3 1]

       setAnsatzList $data(ansatzList)

    }

    ::itcl::body vmMaskHelmert2::setAnsatzList {liste} {
       # Alle Inhalte vorher loeschen
       $pfd(c_ansatznr) delete entry 0 end
       $pfd(c_ansatznr) delete list 0 end
       foreach {einElement status} $liste {
          $pfd(c_ansatznr) insert list end $einElement
       }
       return
    }

    ::itcl::body vmMaskHelmert2::faerbeAnsatzListe {} {
       foreach {elem state} $data(ansatzList) {
          if { $state } {
    #            puts "TODO: Farbe Ansatz $elem verändern!!!"
                $pfd(c_ansatznr) itemconfigure $elem red
          }
       }
    }

And this is the last file for the combobox

(vmCombobox2.itcl):

    package require Itcl
    package require Iwidgets
    itcl::class vmCombobox2 {
       inherit itk::Widget
       constructor {args} {}
       destructor {}

       public method insert {component index args}
       public method delete {component first {last {}}}
       public method itemconfigure {bez farbe}

       private variable popdown

       private method create {top}

       protected method _deleteList {first {last {}}}
    }

    itcl::body vmCombobox2::constructor {args} {
       ttk::style configure Combobox$this.TCombobox\
          -selectbackground #52719c\
          -borderwidth 1\
          -insertwidth 2\
          -selectforeground white\
          -fieldbackground white
       ttk::style map Combobox$this.TCombobox -background [list disabled #a3a3a3 readonly #a3a3a3]
       ttk::style map Combobox$this.TCombobox -foreground [list disabled #d9d9d9 readonly #d9d9d9]
       ttk::style map Combobox$this.TCombobox -arrowcolor [list disabled darkgrey readonly black]
       create $itk_interior
       itk_initialize {*}$args
       # wenn -values vor -textvariable steht wird die Variable nicht initialisiert deshalb:
       set idx [lsearch $args "-textvariable"]
       if {$idx != -1} {
          setVar [lindex [$itk_component(combobox) cget -values] end]
       }
    }

    itcl::body vmCombobox2::create {top} {
    #   puts "createCombobox"
       # Label
       itk_component add label {
          set label [label $top.label -anchor w]
          set label
       } {
          rename -font -labelfont labelFont Font
       }
       # Frame fuer highlightthickness
       itk_component add frame {
          set frame [frame $top.frame -highlightcolor black]
          set frame
       } {
       }

       # combobox
       itk_component add combobox {
          set combobox [ttk::combobox $top.frame.combo -style Combobox$this.TCombobox]
          set combobox
       } {
          keep -textvariable -values -cursor -exportselection -justify -height -state -width -takefocus -postcommand\
             -invalidcommand -foreground
          rename -validate -validateart validateArt ValidateArt
       }

       grid $itk_component(label) -row 0 -column 0 -sticky ne
       grid $itk_component(frame) -row 0 -column 1 -sticky ew
       pack $itk_component(combobox) -fill x -expand 1
       grid columnconfigure $top 1 -weight 1
       grid rowconfigure $top 0 -weight 1

       # aufgeklappte Liste
       set pd [ttk::combobox::PopdownWindow $itk_component(combobox)]
       set popdown $pd.f.l
    }

    itcl::body vmCombobox2::_deleteList {first {last {}}} {

        if {$last == {}} {
           set last $first
        }
        set valueList [$itk_component(combobox) cget -values]
        set newValuesList [lreplace $valueList $first $last]

        # remove the item if it is no longer in the list
        set text [$itk_component(combobox) get]
        if {$text != ""} {
           set index [lsearch -exact $newValuesList $text]
           if {$index == -1} {
              $itk_component(combobox) set ""
             }
        }
        $itk_component(combobox) configure -values $newValuesList
        return
    }

    itcl::body vmCombobox2::delete {component first {last {}}} {
        switch -- $component {
             entry {
                if {$last == {}} {
                   #set last [expr {$first + 1}]
                   set last $first
                }
              set text [$itk_component(combobox) get]
              set newText [string replace $text $first $last]
              $itk_component(combobox) set $newText
             }
             list {
                _deleteList $first $last
             }
             default {
                error "falsches Combobox component \"$component\":\
                         zugelassen sind: entry or list."
             }
       }
    }

    itcl::body vmCombobox2::insert {component index args} {
       set nargs [llength $args]

       if {$nargs == 0} {
            error "Kein Einfuegestring fuer parameter \"string\" in function\"vmCombobox2::insert\""
       }

       switch -- $component {
          list {
             if {$itk_option(-state) == "normal"} {
                set aktuell [$itk_component(combobox) cget -values]
                  if {[lsearch -exact $aktuell $args] != -1} {
                     return
                   }
                set neu [linsert $aktuell $index [join $args]]
                $itk_component(combobox) configure -values $neu
             }
          }
          default {error "Falsches vmCombobox2 component \"$component\": zugelassen be entry oder list."}
       }
    }

    itcl::body vmCombobox2::itemconfigure {bez farbe} {

       puts "content popdownListe >>[$popdown get 0 end]<<"
       # index des Elements in popDownListe
       set index [lsearch [$popdown get 0 end] $bez]
       try {
          $popdown itemconfigure $index -foreground red
       } on error {err errOpts} {
          puts "Error >>$err<<"
       }
    }

In the method vmCombobox2::itemconfigure I put the content of the popDownList. If the popDownList is opened for the first time, the content is empty and none of the elements are colored red (

content popdownListe

. I got the error

item number "-1" out of range

(for sure, the popDownList is empty). If I open it for the second time, the elements 2 and 3 are colored red as expected.
Is there a way to fill content to the popdown list before it is opened the first time?

A: One possible solution would be to configure the items after the list is displayed.
You need for this:

*

*new Version of vmCombobox (check out svn)
Example:
!/bin/sh
\
exec vmwish "$0" ${1+"$@"}
package require Itcl
package require vmWidgets
package require vmTclTools
toplevel .t
frame .t.fr
pack .t.fr
global wms
variable var
set cb1 [vmCombobox .t.fr.li\
    -textvariable ::wms(capabilitiesAddr)\
    -selectioncommand getV\
    -textfont {helvetica 10 bold}\
    -labelfont {helvetica 10 bold}\
    -values [list 1 2 3 33i 1000 7]\
    -textvariable ::wms(var)\
    -height 20\
    -validate all\
    -validate {valMass %P}\
    -labeltext testcombobox\
    ]
pack $cb1
$cb1 insert list end  jojo
set pd [$cb1 getPopdown]
$cb1 configure -postcallback [list configureLB $pd]
proc configureLB {pd} {
   foreach i [$pd get 0 end] {
      # hier Items konfigurieren
      puts $i
   }
   $pd itemconfigure end -foreground red
}

A: To illustrate, what was meant with the answer here the changes I made in vmCombobox2.itcl and vmMaskHelmert2.itcl

vmMaskHelmert2.itcl

I added a new option -postcallback to the combobox and configured it in faerbeAnsatzListe.
:itcl::body vmMaskHelmert2::faerbeAnsatzListe {} {
   set listIndex [list ]
   foreach {elem state} $data(ansatzList) {
      if { $state } {
#         puts "TODO: Farbe Ansatz $elem verändern!!!"
          set values [$pfd(c_ansatznr) getValues]
          set index [lsearch $values $elem]
          lappend listIndex $index
      }
   }
   set pd [$pfd(c_ansatznr) getPopdown]
   $pfd(c_ansatznr) configure -postcallback [list configureLB $pd $listIndex]
}

getValues is a method, which lists all items of the list in the combobox.

vmCombobox2.itcl

I added the option postcallback in vmCombobox2.itcl
itcl::class vmCombobox {
...
itk_option define -postcallback postCallback PostCallback ""
...
}

In constructor I added the following lines:
itcl::body vmCombobox::constructor {args} {
...
if {$idx != -1} {
   setVar [lindex [$itk_component(combobox) cget -values] end]
}
...
set pd [ttk::combobox::PopdownWindow $itk_component(combobox)]
set oldTags [bindtags $pd]
set tagList [concat $oldTags "callBack$this"]
bind callBack$this <Map> [itcl::code $this popUpCallback]
bindtags $pd $tagList
bind $pd <Unmap> [::itcl::code $this clearAfterSelect]

And I added three more methods (I also declared them in class as public method)
itcl::body vmCombobox::getPopdown {} {
   return $popdown
}
itcl::body vmCombobox::popUpCallback {} {
   if {$itk_option(-postcallback) != ""} {
      eval $itk_option(-postcallback)
   }
}

::itcl::body vmCombobox::configureLB {pd listIndex} {
   foreach index $listIndex {
      $pd itemconfigure $index -foreground red
   }
}

For me it worked, with the changes I can colour certain items.


text:
Q: url can't be opened by click directly there are two links on my page, the first url can only be opened by select open in new tab/window in right context menu.  Or the url can be pasted to browser address bar, then hit the enter. if i click that link directly, i got 403 forbidden page, and refresh doesn't work.

why?


text:
Q: ts-node-dev: no script to run provided My NodeJs project have an error message:

dev_api | yarn run v1.15.2
dev_api | warning package.json: No license field
dev_api | $ set debug=* && ts-node-dev --respawn --inspect --transpileOnly ./src/index.ts
dev_api | ts-node-dev: no script to run provided
dev_api | Usage: ts-node-dev [options] script [arguments]
dev_api |
dev_api | error Command failed with exit code 1.
dev_api | info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

My package.json:
{
   "name": "API_CLIENT_BANK",
   "version": "0.0.1",
   "description": "Awesome project developed with TypeORM.",
   "devDependencies": {
      "@types/jest": "^24.0.20",
      "@types/node": "^8.0.29",
      "ts-jest": "^24.1.0",
      "ts-node": "3.3.0",
      "typescript": "3.3.3333"
   },
   "dependencies": {
      "@sentry/node": "5.7.1",
      "@types/bcryptjs": "^2.4.2",
      "@types/body-parser": "^1.17.1",
      "@types/cors": "^2.8.6",
      "@types/helmet": "^0.0.44",
      "@types/jsonwebtoken": "^8.3.5",
      "@types/supertest": "^2.0.8",
      "@types/swagger-jsdoc": "^3.0.2",
      "bcryptjs": "^2.4.3",
      "body-parser": "^1.19.0",
      "class-transformer": "^0.2.3",
      "class-validator": "^0.10.2",
      "cors": "^2.8.5",
      "dotenv": "^8.2.0",
      "express": "^4.15.4",
      "helmet": "^3.21.2",
      "jest": "^24.9.0",
      "jsonwebtoken": "^8.5.1",
      "morgan": "^1.9.1",
      "mysql": "^2.17.1",
      "prettier": "^1.18.2",
      "reflect-metadata": "^0.1.10",
      "sqlite3": "^4.0.3",
      "supertest": "^4.0.2",
      "swagger-jsdoc": "^3.4.0",
      "swagger-stats": "^0.95.11",
      "swagger-ui-express": "^4.1.2",
      "ts-node-dev": "^1.0.0-pre.43",
      "tsc-watch": "^4.1.0",
      "tslint": "^5.20.0",
      "tslint-config-prettier": "^1.18.0",
      "tslint-eslint-rules": "^5.4.0",
      "tslint-plugin-prettier": "^2.0.1",
      "typeorm": "0.2.20"
   },
   "scripts": {
      "tsc": "tsc",
      "start": "set debug=* && ts-node-dev --respawn --inspect --transpileOnly ./src/index.ts",
      "prod": "tsc && node ./build/index.js",
      "schema:drop": "ts-node ./node_modules/typeorm/cli.js schema:drop",
      "schema:sync": "ts-node ./node_modules/typeorm/cli.js schema:sync",
      "migration:run": "ts-node ./node_modules/typeorm/cli.js migration:run",
      "test": "jest --maxWorkers=1 --verbose=true",
      "migration:start": "yarn schema:drop && yarn schema:sync && yarn migration:run"
   }
}

The error say ts-node-dev: no script to run provided, but I gave it:
set debug=* && ts-node-dev --respawn --inspect --transpileOnly ./src/index.ts

A: Try to run
npm i ts-node-dev --save-dev,
and modify your script to
npx ts-node-dev --respawn --transpile-only --debug ./src/index.ts

A: That no script to run provided error is the slightly unhelpful way that ts-node-dev's behaves if it doesn't recognize an option. (This is true as far as v1.1.6, at any rate.)
The problem here is that it doesn't understand the --transpileOnly option. Possibly older versions did, because you see a few examples around the web with that option. But now you need to write --transpile-only.
You'd think it would say something like "Unrecognized option: --transpileOnly", but no.
(The answer from Emefile Francis Waje does include this change, but it's easily missed, because it also proposes two more changes: making ts-node-dev a dev dependency, and using npx. So when I first read that answer, I totally missed the change from --transpileOnly to --transpile-only because I was focusing on the other two changes. So I'm calling this detail out here in a separate answer because it's the root cause of the error that the question mentions.)


text:
Q: Standard Error of variance component from the output of lmer I need to extract the standard error of variance component from the output of lmer .
library(lme4)
model <- lmer(Reaction ~ Days + (1|Subject), sleepstudy)

The following produces estimates of variance component :
s2 <- VarCorr(model)$Subject[1]

It is NOT the standard error of the variance. And I want the standard error . How can I have it ?
EDIT :
Perhaps I am unable to make you understand what I meant by "standard error of the variance component". So I am editing my post .
In Chapter 12 , Experiments with Random Factors , of the book Design and Analysis of Experiments , by Douglas C. Montgomery , at the end of the chapter , Example 12-2 is done by SAS . In Example 12-2 , the model is a two-factor factorial random effect model .The output is given in Table 12-17

I am trying to fit the model in R by lmer .
library(lme4)
fit <- lmer(y~(1|operator)+(1|part),data=dat)

R codes for extracting the Estimate , annotated by 4 in the table 12-17  :
est_ope=VarCorr(fit)$operator[1]
est_part = VarCorr(fit)$part[1]
sig = summary(fit)$sigma
est_res = sig^2

Now I want to extract the results of Std Errors , annotated by 5 in the table 12-17 from  lmer output .
Many Thanks !

A: I think you are looking for the Wald standard error of the variance estimates. Please note that these (as often pointed out by Doug Bates) the Wald standard errors are often very poor estimates of the uncertainty of variances, because the likelihood profiles are often far from quadratic on the variance scale ... I'm assuming you know what you're doing and have some good use for these numbers ...
This can be (now) done using the merDeriv package.
library(lme4)
library(merDeriv)
m1 <- lmer(Reaction ~ Days + (Days|Subject), sleepstudy)
sqrt(diag(vcov(m1, full = TRUE)))
vv <- vcov(m1, full = TRUE)
colnames(vv)
## [1] "(Intercept)"                  "Days"
## [3] "cov_Subject.(Intercept)"      "cov_Subject.Days.(Intercept)"
## [5] "cov_Subject.Days"             "residual"

If we want the standard errors of the variance components, we take the square root of the diagonal and keep only the last three elements:
sqrt(diag(vv)[3:5])
## [1] 288.78602  46.67876  14.78208

old answer
library("lme4")
model <- lmer(Reaction ~ Days + (1|Subject), sleepstudy, REML=FALSE)

(At present it's quite a bit harder to do this for the REML estimates ...)
Extract deviance function parameterized in terms of standard deviation and correlation rather than in terms of Cholesky factors (note this an internal function, so there's not a guarantee that it will keep working in the same way in the future ...)
 dd.ML <- lme4:::devfun2(model,useSc=TRUE,signames=FALSE)

Extract parameters as standard deviations on original scale:
 vv <- as.data.frame(VarCorr(model)) ## need ML estimates!
 pars <- vv[,"sdcor"]
 ## will need to be careful about order if using this for
 ## a random-slopes model ...

Now compute the second-derivative (Hessian) matrix:
library("numDeriv")
hh1 <- hessian(dd.ML,pars)
vv2 <- 2*solve(hh1)  ## 2* converts from log-likelihood to deviance scale
sqrt(diag(vv2))  ## get standard errors

These are the standard errors of the standard deviations: double them to get the standard errors of the variances (when you transform a value, its standard errors scale according to the derivative of the transformation).
I think this should do it, but you might want to double-check it ...

A: I'm not really sure what you mean by "standard error of variance component". My best guess (based on your code) is that you want the standard error of the random effect. You can get this using package arm:
library(arm)
se.ranef(model)
#$Subject
#    (Intercept)
#308    9.475668
#309    9.475668
#310    9.475668
#330    9.475668
#331    9.475668
#332    9.475668
#333    9.475668
#334    9.475668
#335    9.475668
#337    9.475668
#349    9.475668
#350    9.475668
#351    9.475668
#352    9.475668
#369    9.475668
#370    9.475668
#371    9.475668
#372    9.475668

This is actually the square root of the conditional variance-covariance matrix of the random effect:
sqrt(attr(ranef(model, condVar = TRUE)$Subject, "postVar"))

A: mn2=lmer(pun~ pre + (pre|pro), REML = TRUE, data = pro)
summary(mn2)
coe2=coef(mn2)
coe2

# Matriz de varianza-covarianza (covarianza)
as.data.frame(VarCorr(mn2))

# Extraer coeficientes fijos
fixef(mn2)

# Extraer desvios de a - alfa y b - beta
re=as.data.frame(ranef(mn2))