text:
Q: Can key presses be throttled on Linux? I've got a keyboard (razor black widow stealth) that is malfunctioning in such a way that it periodically sends duplicate key presses for various keys (h and n) so far. I'm looking for ways to delay the purchase of a new one in software.
I'm currently on Kubuntu 18.04. Is there any way to throttle key presses so that 2 key presses of the same key within 500ms (for example) would only register as a single key press? I tried extending the duration of repeat delay to see if it was just being pressed too long but it does look like the keyboard is sending duplicate presses.

A: If the issue is consistent, you could rig xdotool (install with sudo apt-get install xdotool -y to press backspace immediately after each of these keypresses to delete one of the two keystrokes, then set up a keyboard shortcut to each of the trouble keys to run xdotool key Delete sleep 1. What this does is has xdotool send the delete command immediately after the first keypress, but then provides a 1 second delay for the second keystroke to be sent through. Tested it on my own machine and it made it so that a single keypress wouldn't get sent through, but a quick double-press would.
If you need an inexpensive keyboard to get you through until you can get a new good quality one, thrift stores usually have large stocks of old (but clean)  USB office keyboards that can tie you over for $3-5, and you would have it immediately. Nothing flashy, but comfortable enough for typing and gaming so long as you aren't pressing more than 5 keys at once.


text:
Q: Inconsistent data when traversing through 4 tables I have 4 tables (with a lot of fields, but only a few important ones in each) that I'm working with.

*

*Customer table

*Inventory table

*Invoice table

*Invoice details table

What I've been doing is getting a customer or item's id.
If it's a customer, I take their id to get their information from the customer table. Now, in order to get the item's they carry I have to look at each invoice with that customer's id. So I grab all of those. Each invoice has and id that links to an invoice detail table, so I take that invoice id and grab the invoice details that match with the invoice. Then the items are in the iteminventory table, so I take the item id from the invoice detail and get all of the items for every invoice associated with that customer. Then I run that data through a loop to get rid of any empty values and pass the item array to the view.
Now if it's an item the actions are performed vice versa. I take the item, look at each invoice detail containing that wine, grab the invoice id from it, and grab the customer id from each invoice respectively.
Somehow I wind up with customer's carrying a product, but when I go to the product to see what customer's carry it, the previously mentioned customer won't be listed under the product.
Is there an easier way to do this?

A: Most SQL programmers solve this kind of problem with a single query using a series of JOIN directives and an appropriate ORDER BY directive. They write a bit of php code to read the resultset row by row, detect rows in which the invoice id changes, and format the information appropriately.
It seems like a good idea for you to read up on how to use JOIN directives if you don't already know.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why cannot add PPA deadsnakes? I have ubuntu version 20.04 and I would like to install python 3.6 from the shell. After sudo apt install software-properties-common I am trying to use the add-apt-repository ppa:deadsnakes/ppa command but I am getting this error:
Cannot add PPA: 'ppa:~deadsnakes/ubuntu/ppa'.
ERROR: '~deadsnakes' user or team does not exist

Did I forget any steps or does the repository no longer work?

A: For people having issues running this within a Dockerfile, changing:
RUN add-apt-repository ppa:deadsnakes/ppa

to:
RUN add-apt-repository 'ppa:deadsnakes/ppa'

Fixed the problem for me.

A: Just type this before running ppa command:
sudo apt install software-properties-common -y

A: I had the same problem, but was on a Docker container, so no sudo was avilable. I was able to manually add the repository at /etc/apt/sources.list:
deb http://ppa.launchpad.net/deadsnakes/ppa/ubuntu YOUR_UBUNTU_VERSION_HERE main

I was on 16.04, so used xenial.
then:
apt-key adv --keyserver keyserver.ubuntu.com/ --recv-keys BA6932366A755776

You should be able to install python 3.6 with
apt-get install python3.6

A: Did you check the existence of /etc/apt/sources.list.d? After messing around with my ppa, I found that I had not created that directory.
If this is also your case, please do
$ sudo mkdir /etc/apt/sources.list.d
$ sudo add-apt-repository ppa:deadsnakes/ppa

also, as @kuropan suggested, there is no need for add the ~ before 'deadsnakes'
I'm using ubuntu 20.04.1 LTS

A: You're probably behind a corporate proxy and to add -E to your sudo command to preserve the environment variables.
$ sudo add-apt-repository -y 'ppa:deadsnakes/ppa'
Cannot add PPA: 'ppa:~deadsnakes/ubuntu/ppa'.
ERROR: '~deadsnakes' user or team does not exist.
$ sudo -E add-apt-repository -y 'ppa:deadsnakes/ppa'
 This PPA contains more recent Python versions packaged for Ubuntu.

Disclaimer: there's no guarantee of timely updates in case of security problems or other issues. If you want to use them in a security-or-otherwise-critical environment (say, on a production server), you do so at your own risk.

Update Note
===========
...

A: I got this error with a fresh Ubuntu installation in a VM and none of the other answers worked for me. However, this command solved the problem for me:
sudo apt-get install --reinstall ca-certificates

(Credits: this was answered here at a related question.)


text:
Q: Defining a has many through relationship with polymorphism I'm adding a reporting feature to an existing application, the reports are made against one of two models (ideally could also be made against both but let's start small). The reports are configurable and the user should have the ability to "save" a set of filters to a new "Report Type" and setup optional recurring reports with those filters.
The trouble I'm having is how to show only the report types related to each model on their respective dashboards. Each report type will either apply to tests or tickets, but it doesn't have a direct relationship to a ticket or test, just it's class.

My initial thought was to use a hasManyThrough relationship but I am unsure how to do that through a polymorphic relationship, and how to query that for purposes of building a menu for the reports that is dynamic.
The end goal is to be able to generate the dropdown menu options and the tab headers in this mockup dynamically, if a model type (Ticket or Test) HAS Report Types then it should appear in the top dropdown menu and when you select it the tabs on the report page should only show the Report Types that have some kind of relationship to that model, so if there is a monthly ticket report then show that tab but don't show monthly test reports for example.

How do I go about creating the relationship between a ReportType (instance) and the models it could potentially be reporting on (Ticket, Test, etc).


text:
Q: sb = new StringBuilder(1024*1024*1024) > 'System.OutOfMemoryException' was thrown I need to append lots of string in a loop and this will create a very long string.
1GB should be long enough to store the string, therefore I do this:
var sb = new StringBuilder(1024 * 1024 * 1024);

but receives this error
'System.OutOfMemoryException' was thrown

any advice to append long strings?
I'm writing a backup tools for MySQL database. The tools will export data from database and write into a text file. The data contains BLOB and TEXT data type. So, will expect very long string.
This is the code: Code Updated 1
var conn = new MySqlConnection(Program.ConnectionString);
var cmd = new MySqlCommand();
cmd.Connection = conn;
conn.Open();

cmd.CommandText = selectSQL;

MySqlDataReader rdr = cmd.ExecuteReader();

while (rdr.Read())
{
    var sb = new StringBuilder(1024 * 1024 * 1024);
    for (int i = 0; i < rdr.FieldCount; i++)
    {
        if (sb.Length > 0)
            sb.AppendFormat(separator);

        if (rdr[i].GetType() == typeof(byte[]))
        {
            sb.AppendFormat(ConvertByteArrayToHexString((byte[])rdr[i]));
        }
        else
            sb.AppendFormat(rdr[i] + "");
    }
    WriteToFile(sb.ToString());
}

conn.Close();

A: Use a file stream to write long files.  There's no need to keep the full string in memory at any one time.

A: The out of memory error may be caused by any number of reasons, based on how Windows virtual memory and how the .NET runtime works.
Do you really need to dump everything into the StringBuilder all at once?  If you're writing to a file, you can do the operation in pieces at a time.
Use something like this as a starting point:
    int bufferSize = 65536;
using (StreamWriter sw = new StreamWriter("filename", true, System.Text.Encoding.UTF8, bufferSize))
{
    while(!finished)
    {
        string data = "foo"; //get next data here...
        sw.Write(data);
    }
}

`
References: What consumes less resources and is faster File.AppendText or File.WriteAllText storing first in StringBuilder?

A: You haven't asked for a StringBuilder with enough capacity to store 1 GB - you've asked for one with enough capacity to store 1024 * 1024 * 1024 characters, which'll require (roughly) 2 GB of memory. That's smaller than the maximum string length (2^31-1 characters), but larger than the heap space available in a 32-bit process.
You may not need a StringBuilder with that kind of capacity - others answers discuss that. Assuming you need a string that gigantic, you definitely don't need to pre-allocate your StringBuilder with that size. Just create a StringBuilder, and let it grow on its own:
var sb = new StringBuilder();

or pre-allocate something more reasonable, if you know you'll have huge amounts of data:
var sb = new StringBuilder(1024 * 1024);


text:
Q: Does there exist a process to build a list of numbers whose standard deviation is an integer? Or rephrased, is there a way to make a list of numbers whose sample variance is a square number? I'm interested in sequences of arbitrary length with integer elements.
(I come from a computer science background so my apologies if this question is a poor one).

A: Essentially, this problem is to generate integers $n,s,a_1,\dots,a_n$ such that $n\ge1$ and
$$(n-1)s^2=a_1^2+\dots+a_n^2.\tag{1}$$
To do this, let $k:=\lfloor n/4\rfloor$ and take any nonnegative integers $t_1,\dots,t_k$ such that
$$(n-1)s^2=t_1+\dots+t_k.\tag{2}$$
For each $j\in[k]:=\{1,\dots,k\}$, by Lagrange's four-square theorem, there exist integers $a_{j1},\dots,a_{j4}$ such that
$$t_j=\sum_{i=1}^4 a_{ji}^2,$$
so that
$$(n-1)s^2=\sum_{j=1}^k\sum_{i=1}^4 a_{ji}^2.\tag{3}$$
The latter expression is the sum of $4k\le n$ squares of nonnegative integers. Complementing this sum by the sum of $n-4k$ squares of $0$, we get representation (1) -- for any given natural $n$ and integer $s$.

This is illustrated by the the following image of a Mathematica notebook, finding a representation (1) for $n=15$ and $s=5$;
$$(15-1)5^2=4^2 + 0^2 + 8^2 + 6^2 + 10^2 + 0^2 + 4^2 + 2^2 + 5^2 + 0^2 + 8^2 +
 5^2 + 0^2 + 0^2 + 0^2.$$

Of course, the $a_i$'s in (1) are the deviations of the sample values from the sample mean. Previously, I forgot to take into account that the sum of the $a_i$'s must of course be $0$.
$\newcommand\ep\epsilon$One way to get that is to try to attach "signs" $\ep_i\in\{-1,1\}$ to the $a_i$'s so that $\sum_{i=1}^m\ep_i a_i=0$. I think usually this will be possible to do when $\sum_{i=1}^m a_i$ is even, as is the case with the above example (continued below). Otherwise, repeat with other $t_1,\dots,t_k$ in (2) and/or with other instances of the $a_{j1},\dots,a_{j4}$'s.

The problem of the existence of "balancing" signs $\ep_i\in\{-1,1\}$ is obviously equivalent to the so-called partition problem, which is easily solved for not too big values $n$ and $\sum_{i=1}^m a_i$ in view of the simple recurrence relation, whose application to the particular $a_i$'s considered in the mentioned Mathematica notebook is illustrated here:

This again confirms that for our particular $a_i$'s "balancing" signs $\ep_i\in\{-1,1\}$ exist.
The problem of actually finding an appropriate partition (which is equivalent to finding "balancing" signs $\ep_i\in\{-1,1\}$) was solved by Korf.
For our particular $a_i$'s there actually are $18$ different "balancing" sign assignments $(\ep_i)$, not counting sign assignments to the $0$'s.

Another way to make the sum of the deviations $0$ is as follows. If $(n-1)s^2$ is even, find integers $b_1,\dots,b_{4l}$ such that
$$(n-1)s^2/2=b_1^2+\dots+b_{4l}^2$$
(cf. (3)), where $l:=\lfloor n/8\rfloor$. Then, letting
$$(a_1,\dots,a_n):=(b_1,\dots,b_{4l},-b_1,\dots,-b_{4l},0,\dots,0),$$
we have both (1) and the balance condition $\sum_{i\in[n]}a_i=0$ satisfied. Of course, one can also replace $(a_1,\dots,a_n)$ by any permutation of this $n$-tuple.

A: Alternatively, given rational numbers $u_1,\dotsc,u_n$ you can define $v=\sum_iu_i^2$ and $w_i=2u_i/(1+v)$ for $i\leq n$ and $w_{n+1}=(1-v)/(1+v)$.  Then the numbers $w_j$ are rational with $\sum_jw_j^2=1$.  By clearing denominators you get an equation $\sum_{j=1}^{n+1}a_j^2=b^2$ in integers.


text:
Q: invalid syntax tried almost everything I'm running into issues with this code:
return render(request, 'count.html',{'fulltext':fulltext,'count':len(wordlist),'worddictionary':worddictionary.items("")})

CMD is telling me line 22 invalid syntax but, I cant find anything wrong with it.
    from django.http import HttpResponse
    from django.shortcuts import render
    import operator

    def homepage(request):
        return render(request, 'home.html')

    def count(request):
        fulltext = request.GET['fulltext']

        wordlist = fulltext.split()

worddictionary = {}
for word in wordlist:
    if word in worddictionary:
        #increase
        worddictionary[word] += 1

    else:
        #add to the dictionary
        worddictionary[word] = 1
sortedwords = sorted(worddictionary.items(), key=operator.itemgetter(1), reverse=True)

return render(request, 'count.html',{'fulltext':fulltext,'count':len(wordlist),'worddictionary':worddictionary.items()})

A: After checking your code I am seeing that you are giving the  key value pair of the dictionary like : 'count':len(word list) . I suggest you to make a new variable suppose x=len(word list) and then use this in the dictionary like that 'count':x. I hope it will get resolves after that.

A: That may be because of an extra ' at the end of your return statement.


text:
Q: .gitignore not working. My environment variables are being pushed to my repo when they should be un-tracked Common sense says don't push environment variables on a public git repo. I always make sure to add my environment variable to my .gitignore file.
This time I do everything correct and when I do a git push files the environment variable is in the repo! I immediately remove it. I go back for a re-do.
I called my environment variable important.env
The un-tracked file under git status shows important.env.env Why does it have .env twice under the un-tracked filename?

A:
The un-tracked file under git status shows important.env.env

It depends on how the file was created (with which editor).
Sometime, said editor will add automatically an extension to the filename (even when said filename already have an extension)
Rename it, and check if the file is currently ignored:
git check-ignore -v -- important.env

If the result is empty, remove it from Git first:
git rm --cached -- important.env
git commit -m "Remove env file"
git push


text:
Q: BOM Preamble in .NET Rest API causing Twilio Parse Error 12100 We have a .NET Rest API that is a web-hook for Twilio. It returns a TwilioResponse object.  Suddenly, Twilio is reporting a Parse Error 12100 on the hook. We looked closer and it seems to be due to a BOM preamble that is getting added to our response now (for some reason; this code hasn't changed in years).
Does anyone know what might cause this problem to suddenly crop up. And, more importantly, how can I fix it?
Here is the HttpGet method that Twilio is calling (and choking on)...
        [HttpGet]
        [Route("TransferMessage", Name = "GetTransferMessage")]
        public TwilioResponse GetTransferMessage()
        {
            var response = new TwilioResponse();
            response.Pause(2);
            response.Say("Hello. This call is being transferred by Acme Products and may be recorded " +
                "for quality assurance.");

            return response;
        }

Thanks in advance...!
Here is the xml returned by our endpoint. If you look at the raw data in a hex editor, it's clearly encoded with UTF-8-BOM.


text:
Q: How to delete readonly variable in bash? $ mySite="superuser"
$ readonly mySite
$ unset mySite
bash: unset: mySite: cannot unset: readonly variable

How can we delete mySite, as it is a readonly variable?

A: Walker Hale IV's solution can be expressed in a much shorter fashion using options available in more recent versions of gdb:
gdb --batch-silent --pid=$$ --eval-command='call unbind_variable("mySite")'

Again, this is dark magic that should be kept well away from production environments.

A: You can't delete mySite. The whole point of the readonly command is to make it final and permanent (until the shell process terminates). If you need to change a variable, don't mark it readonly.

A: See https://stackoverflow.com/a/21294582/642372
This is dark magic. It uses gdb to tell the bash process to clear the variable by calling an internal C function.
mySite="superuser"
readonly mySite
gdb -n <<EOF >>/dev/null 2>&1
attach $$
call unbind_variable("mySite")
detach
quit
EOF

You should never have this in production. I have it in my .bashrc.


text:
Q: Using HTML5, how do I use contenteditable fields in a form submission? So I have a bunch of paragraph elements which are dynamically populated from a db.  I have made the elements contenteditable.  I now want to submit edits back the the db via a standard form submission.  Is there a way to post the contenteditable elements back?

A: You have to use javascript one way or the other, it won't work as a "standard" form element as it would with a textarea or the like.  If you like, you could make a hidden textarea within your form, and in the form's onsubmit function copy the innerHTML of the contenteditable to the textarea's value.  Alternatively you could use ajax/xmlHttpRqeuest to submit the stuff a bit more manually.
function copyContent () {
    document.getElementById("hiddenTextarea").value =
        document.getElementById("myContentEditable").innerHTML;
    return true;
}

<form action='whatever' onsubmit='return copyContent()'>...

A: If anyone is interested I patched up a solution with VueJS for a similar problem. In my case I have:

<textarea class="d-none" name="gift[main_message]" :value="mainMessage"></textarea>

In "data" you can set a default value for mainMessage, and in methods I have:
methods: {
  updateMainMessage: function(e) {
    this.mainMessage = e.target.innerText;
  }
}

"d-none" is a Boostrap 4 class for display none.
Simple as that, and then you can get the value of the contenteditable field inside "gift[main_message]" during a normal form submit for example, no AJAX required. I'm not interested in formatting, therefore "innerText" works better than "innerHTML" for me.

A: Does it NEED to be standard form submission? If you cannot or do not want use a form with inputs, you may try AJAX (XMLHttpRequest + FormData), through which you could perform asynchronous requests and control better how response shows up.
If you want it even simpler, try jQuery's $.ajax function (also $.get and $.post). It sends data using simple JS objects.

A: Made a fully working example based on Rob's idea:
After hitting submit, the (hidden) textarea is updated with the table-data, in JSON-format.
(return true to submit)

function copyContent() {
  const table = [];
  $("tr").each(function() {
    const row = [];
    $("th, td", this).each(function() {
      row.push($(this).text());
    });
    table.push(row);
  });
  $("#rows").val(JSON.stringify(table));

  // return true to submit
  return false;
}

<form onsubmit='return copyContent()'>
  <textarea name="rows" id="rows" rows="4"></textarea>
  <button type="submit">Submit</button>
</form>

      Head 1
      Head 2

      edit
      me

      please


text:
Q: ManyToManyField initialization in Django I have following model:
class Comment(models.Model):
    uuid = models.CharField(max_length=40, default='random')
    news = models.ForeignKey('News')
    user = models.OneToOneField(User, primary_key=True) # ForeignKey('User')
    text = models.CharField(max_length=300, null=True)
    upvotes = models.PositiveIntegerField(default=0)
    downvotes = models.PositiveIntegerField(default=0)
    votes = models.ManyToManyField(User, through='Vote', related_name='votes_table')

class Vote(models.Model):
    cmt = models.ForeignKey(Comment)
    user = models.ForeignKey(User)
    vote_type = models.SmallIntegerField(default=0) # vote_type is +1 for upvote & -1 for downvote

When a user submits a new comment, I initialize a new one, like this: c = Comment(uuid=uuid.uuid4(),news=n, user=request.user, text=comment_text). Now the problem is, when I print c.votes.exists(), it's True. How did this comment c have an entry in the comments_votes table?

A: The generated 'sql': u'SELECT (1) AS "a" FROM "auth_user" INNER JOIN "app_vote" ON ("auth_user"."id" = "app_vote"."user_id") WHERE "app_vote"."cmt_id" = 62  LIMIT 1'
As the primary key for Comment is User, c.votes.exists() actually checks if the user has any votes rather than checking if the comment has any votes.
P.S. You can get the comment votes with a query on Vote if you filter by the comment uuid instead of pk


text:
Q: How do I produce  with the link_to helper? All I want to produce is this HTML tag:

I tried:
<%= link_to root_path, id: "logo" %>

But this produces:
/

I also tried:
<%= link_to(root_path), id: "logo" %>

But that produces:
SyntaxError at /
syntax error, unexpected ',', expecting ')'

Thoughts?
Edit 1
The reason I am doing it like this is because I am including the logo via CSS....so that's why I haven't done a link_to ... do block.

A: This works for me:
<%= link_to "linky", "/", id: "logo" %>

If you don't want there to be a value you can just omit "linky" but leave the string declaration like:
<%= link_to "", "/", id: "logo" %>

This returns
linky

A: Wouldn't it be:
<%= link_to '', root_path, :id => "logo" %>


text:
Q: Show all data from array in codeigniter My code Is
$co = count($da);
print_r($co);
foreach($da as $abc) {
  $myarray = array(
    date("j", strtotime($abc - > date)) => ''
  );
}

$da have four value but show only one record into calender I use
$data = $this->calendar->generate(2017,12, $myarray);
$this->load->view('calen',['va'=>$data]);

Screen shot of output
Output
Into $da have four date store and pass this array into calender->generate but still show only one date highlight  that is last index date so how to solve this problem
Thanks in Advance

A: You are overwriting the value of $myarray in every iteration of the loop
Change it to:
foreach($da as $abc) {
  $myarray[] = array(
        //^^ [] denotes new index in array
    date("j", strtotime($abc - > date)) => ''
  );
}


text:
Q: Python string replace for UTF-16-LE file Python 2.6
Using Python string.replace() seems not working for UTF-16-LE file. I think of 2 ways:

*

*Find a Python module that can handle Unicode string manipulate.

*Convert the target Unicode file to ASCII, use string.replace(), then convert it back. But I am worry about this may cause loss data.

Can the community suggest me a good way to solve this? Thanks.
EDIT:
My code looks like this:
infile = open(inputfilename)
for s in infile:
 outfile.write(s.replace(targetText, replaceText))

Looks like the for loop can parse the line correct. Did I make any mistakes here?
EDIT2:
I've read the Python Unicode tutorial and tried below code, and get it worked. However, just wondering if there's any better way to do this. Can anyone help? Thanks.
infile = codecs.open(infilename,'r', encoding='utf-16-le')

newlines = []
for line in infile:
    newlines.append(line.replace(originalText,replacementText))

outfile = codecs.open(outfilename, 'w', encoding='utf-16-le')
outfile.writelines(newlines)

Do I need to close infile or outfile?

A: You don't have a Unicode file. There is no such thing (unless you are the author of NotePad, which conflates "Unicode" and "UTF-16LE").
Please read the Python Unicode HOWTO and Joel on Unicode.
Update I'm glad the suggested reading helped you. Here's a better version of your code:
infile = codecs.open(infilename,'r', encoding='utf-16-le')
outfile = codecs.open(outfilename, 'w', encoding='utf-16-le')
for line in infile:
    fixed_line = line.replace(originalText,replacementText)
    # no need to save up all the output lines in a list
    outfile.write(fixed_line)
infile.close()
outfile.close()

It's always a good habit to release resources (e.g. close files) immediately when you are finished with them. More importantly, with output files, the directory is usually not updated until you close the file.
Read up on the "with" statement to find out about even better practice with file handling.

A: Python 3
Looks like Python 3.6 will assume your file is UTF-8 by default if you open it in text mode (default):
>>> open('/etc/hosts')
<_io.TextIOWrapper name='/etc/hosts' mode='r' encoding='UTF-8'>

A function like file.readlines() will return str objects and in Python 3 strings are unicode. If you open the file in binary mode, it will be almost like Python 2 behavior:
>>> open('/etc/hosts', 'rb)
<_io.BufferedReader name='/etc/hosts'>

In this case readlines will return bytes objects and you must decode in order to get unicode:
>>> type(open('/etc/hosts', 'rb').readline())
bytes

>>> type(open('/etc/hosts', 'rb').readline().decode('utf-8'))
str

You can open your file using another encoding using the encoding argument:
>>> open('/etc/hosts', encoding='ascii')
<_io.TextIOWrapper name='/etc/hosts' mode='r' encoding='ascii'>

Python 2 (this is a very old answer)
Python 2 does not care about encoding, a file is just a stream of bytes. A function like file.readlines() will return str objects, not unicode even if you open the file in text mode. You can convert each line to an unicode object using str.decode('your-file-encoding').
>>> f = open('/etc/issue')
>>> l = f.readline()
>>> l
'Ubuntu 10.04.1 LTS \\n \\l\n'
>>> type(l)
<type 'str'>
>>> u = l.decode('utf-8')
>>> type(u)
<type 'unicode'>

You can get results similar to Python 3 using codecs.open instead of just open.


text:
Q: GCP: connect to Memotystore from cloud run Django app? I'd like to add cache to my Django app hosting on Cloud Run.
From Django official docs, we can connect Django to a memory-based cache. Since I'm using Cloud Run, the memory get cleaned.
Memotystore seems good for this purpose, but there's only tutorial for flask and redis.
How could I achieve this?
Or should I just use a database caching?

A: *

*Connect Redis instance to Cloud Run service using the steps in
documentation.

*To connect from Cloud Run (fully managed) to Memorystore you need to
use the mechanism called "Serverless VPC Access" or a "VPC
Connector"

*First, you have to create a Serverless VPC Access    Connector
and then configure Cloud Run to use this connector

*See connecting to a VPC Network for more information.

Alternatives to using this include:

*

*Use Cloud Run for Anthos, where GKE provides the capability to
connect to Memorystore if the cluster is configured for it.

*Stay within fully managed Serverless but use a GA version of the
Serverless VPC Access feature by using App Engine with Memorystore.

*See this answer to connect to Memorystore from Cloud Run using an SSH
tunnel via GCE.


text:
Q: Convert JSON to Array of Objects using lodash I have a JSON object in NoSql database in this format. We are getting this data after migrating some records from some other database and these are multi-valued fields.(Basically we are trying to clean the data for further processing).
{
    "BPContName":"aName;bName;cName",
    "BPContEmail":"aEmail;bEmail;cEmail",
    "BPContPWID":"aPWID;bPWID;cPWID"
}

I want to add another key "bpTableDataName" in the same JSON which should have this format and values,
"bpTableDataName": [
    {
      "name": "aName",
      "email": "aEmail",
      "pwdid": "aPWID"
    },
    {
      "name": "bName",
      "email": "bEmail",
      "pwdid": "bPWID"
    },
    {
      "name": "cName",
      "email": "cEmail",
      "pwdid": "cPWID"
    }
  ],

Is there a way we can achieve this using lodash?

A: Try following code -

o = {
  "BPContName": "aName;bName;cName",
  "BPContEmail": "aEmail;bEmail;cEmail",
  "BPContPWID": "aPWID;bPWID;cPWID"
}

map = { "BPContName" : "name", "BPContEmail": "email", "BPContPWID": "pwdid" }

const result = _.reduce(o, (arr, v, k) => ( v.split(";").forEach((x,i) => _.set(arr, `${i}.${map[k]}`, x)), arr ), [])

console.log(result)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

A: You can use split() to split the values into an array.
Then iterate over the array and create the require json and then push that into results.
Check this out.

var data = {
    "BPContName":"aName;bName;cName",
    "BPContEmail":"aEmail;bEmail;cEmail",
    "BPContPWID":"aPWID;bPWID;cPWID"
}
var names = data.BPContName.split(';');
var emails = data.BPContEmail.split(';');
var pwids = data.BPContPWID.split(';');

var results = [];

for(var i = 0 ; i < names.length; i++) {
  var obj = {
    name: names[i],
    email: emails[i],
    pwdid: pwids[i]
  }
  results.push(obj);
}

console.log(results)

A: You could reduce the entries returned by Object.entries like this:

let obj = {
  "BPContName": "aName;bName;cName",
  "BPContEmail": "aEmail;bEmail;cEmail",
  "BPContPWID": "aPWID;bPWID;cPWID"
}

let bpTableDataName = Object.entries(obj).reduce((r, [key, value]) => {
  let splits = value.split(";");
  key = key.replace("BPCont", "").toLowerCase();
  splits.forEach((split, i) => (r[i] = r[i] || {})[key] = split)
  return r;
}, [])

obj.bpTableDataName = bpTableDataName;

console.log(obj)

*

*Object.entries returns an array of key-value pair. Loop through each of them

*split the each value at ;

*get the key by removing BPCont part and making it lowerCase

*Loop through the splits and update specific keys of objects at each index

Update:
Since you have an extra d in the output's key, you can create a mapping object:
propertyMap = {
  "BPContName": "name",
  "BPContEmail": "email",
  "BPContPWID": "pwdid"
}

And inside the reduce, change the replace code to this:
key = propertyMap[key]

A: Using Object.assign, Object.entries, Array#map and the spread operator make this trivial

    const inputdata = {
        "BPContName":"aName;bName;cName",
        "BPContEmail":"aEmail;bEmail;cEmail",
        "BPContPWID":"aPWID;bPWID;cPWID"
    };

    const t1=Object.assign({},...Object.entries(inputdata).map(([k,v])=>({[k]:v.split(';')})));
    inputdata.bpTableDataName=t1.BPContName.map((name,i)=>({name,email:t1.BPContEmail[i],pwdid:t1.BPContPWID[i]}));
    console.log(inputdata);

Of course, it wouldn't be me without a one-liner

const obj = {
    "BPContName":"aName;bName;cName",
    "BPContEmail":"aEmail;bEmail;cEmail",
    "BPContPWID":"aPWID;bPWID;cPWID"
};
// one line to rule them all
obj.bpTableDataName=Object.entries(obj).reduce((r,[k,v])=>(v.split(';').forEach((v,i)=>(r[i]=r[i]||{})[{BPContName:'name',BPContEmail:'email',BPContPWID:'pwdid'}[k]]=v),r),[]);
//
console.log(obj);

A: You can use lodash's _.flow() to create a function. Use _.map() with _.overArgs() to create a function that splits the values, format the key, and then converts them to an array of pairs using _.unzip(), for example [['name', 'x'], ['name', 'y']]. Transpose the array of arrays with _.unzip() to combine pairs of different properties. Then use _.map() to iterate, and convert each array of pairs to an object using _.fromPairs().

const { flow, partialRight: pr, map, unzip, overArgs, times, size, constant, split, fromPairs } = _

const keysMap = new Map([['BPContName', 'name'], ['BPContEmail', 'email'], ['BPContPWID', 'pwdid']])

const formatKey = key => keysMap.get(key)
const splitVals = pr(split, ';')

const fn = flow(
  pr(map, overArgs(
    (vals, k) => unzip([vals, times(size(vals), constant(k))]),
    [splitVals, formatKey])
  ),
  unzip, // transpose
  pr(map, fromPairs) // convert each pairs array to object
)

const data = {
    "BPContName":"aName;bName;cName",
    "BPContEmail":"aEmail;bEmail;cEmail",
    "BPContPWID":"aPWID;bPWID;cPWID"
}

const results = fn(data)

console.log(results)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

A: Basically what you need is to zip it.
Snippet:

let obj = {"BPContName":"aName;bName;cName","BPContEmail":"aEmail;bEmail;cEmail","BPContPWID":"aPWID;bPWID;cPWID"},
    res = _.zipWith(
      ..._.map(obj, v => v.split(';')),
      (name, email, pwid) => ({name, email, pwid})
    );

console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Note, the sequence of the parameters we have to put such a way, the original object give us values when using Object.values or giving us keys when using Object.keys usually it is alphabetical order. But, In case in any env the order is not guranted we can sort it with a sequence of keys as a metadata.
Or else you can explicitly pass the arguments like:
(obj.BPContName.split(';'), obj.BPContEmail.split(';'), obj.BPContPWID.split(';'))


text:
Q: DFT of basis functions Suppose functions $u_{1}(x)$,..$u_{K}(x)$ are a basis of $H[0,1]$(
some space of real-valued functions). Define Discrete Fourier transform
$$
U_{l}(x)=\sum_{j=1}^{K}u_{j}(x)\exp(2\pi i lj/K)
$$
and suppose functions $U_{1}(x),\ldots,U_{K}(x)$ are orthogonal in
$L_{2}$ norm.

*

*Do functions $U_{1}(x),\ldots,U_{K}(x)$ construct a basis of $H[0,1]$

*Is it possible to construct a real valued orthogonal basis using
$U_{1}(x),\ldots,U_{K}(x)$

*Is there a general theory for such cases?

A: *

*By definition, a basis of a vector space is a certain collection of elements of the space. Since the functions $U_1,\dots,U_K$ are not elements of $H[0,1]$, then do not form a basis of $H[0,1]$.

*Possible, but the only way I can think of is to invert the DFT (returning to $u_j$) and use the Gram-Schmidt on $u_j$.


text:
Q: Make SharePoint Online list columns read only based on yes/no checkbox I have 7 columns that I need to make Read Only (greyed out) as soon as the item is saved when "Field 7" is ticked (yes/no checkbox column).
I have managed to make these 7 columns read only using the following Javascript, however I am struggling with the IF statement. Any help would be appreciated.
    <script>
// A $( document ).ready() block.
$( document ).ready(function() {
    jQuery("input[title='Field 1']").attr("disabled", "disabled");
    jQuery("input[title='Field 2']").attr("disabled", "disabled");
    jQuery("input[title='Field 3']").attr("disabled", "disabled");
    jQuery("input[title='Field 4']").attr("disabled", "disabled");
    jQuery("input[title='Field 5']").attr("disabled", "disabled");
    jQuery("textarea[title='Field 6']").attr("disabled", "disabled");
    jQuery("input[title='Field 7']").attr("disabled", "disabled");
    }
);
</script>

<script language="javascript"> $(function(){ $('a[onclick*="clickDatePicker"]').css('display','none'); }); </script>

A: You can add the IF condition like below:
$("input[id ^= 'YourCheckboxFieldName']").is(function()
{
    var isChecked = $(this).is(":checked");  //This will return True or False
    var theVal = $(this).next().text();    //get the label for this checkbox
    alert(checked + " : " + theVal);
});

In your code you can add like below:
if (isChecked === true)
{
   jQuery("input[title='Field 1']").attr("disabled", "disabled");
    jQuery("input[title='Field 2']").attr("disabled", "disabled");
    jQuery("input[title='Field 3']").attr("disabled", "disabled");
    jQuery("input[title='Field 4']").attr("disabled", "disabled");
    jQuery("input[title='Field 5']").attr("disabled", "disabled");
    jQuery("textarea[title='Field 6']").attr("disabled", "disabled");
    jQuery("input[title='Field 7']").attr("disabled", "disabled");
    }

}

Reference:
Accessing a SharePoint 2013 checkbox with JavaScript?

A: Here is the modified code to check if the checkbox checked and enable/disable by checkbox changed:
<script type="text/javascript">
$( document ).ready(function() {
if($("input[title='Field 7']").is(":checked"))
{
                jQuery("input[title='Field 1']").attr("disabled", true);
                jQuery("input[title='Field 2']").attr("disabled", true);
                jQuery("input[title='Field 3']").attr("disabled", true);
                jQuery("input[title='Field 4']").attr("disabled", true);
                jQuery("input[title='Field 5']").attr("disabled", true);
                jQuery("textarea[title='Field 6']").attr("disabled",true);

}

$("input[title='Field 7']").change(function() {
        if($(this).is(':checked')) {
                jQuery("input[title='Field 1']").attr("disabled", true);
                jQuery("input[title='Field 2']").attr("disabled", true);
                jQuery("input[title='Field 3']").attr("disabled", true);
                jQuery("input[title='Field 4']").attr("disabled", true);
                jQuery("input[title='Field 5']").attr("disabled", true);
                jQuery("textarea[title='Field 6']").attr("disabled",true);
            }
           else
           {
                jQuery("input[title='Field 1']").attr("disabled", false);
                jQuery("input[title='Field 2']").attr("disabled", false);
                jQuery("input[title='Field 3']").attr("disabled", false);
                jQuery("input[title='Field 4']").attr("disabled", false);
                jQuery("input[title='Field 5']").attr("disabled", false);
                jQuery("textarea[title='Field 6']").attr("disabled", false);

           }
    });

});
</script>


text:
Q: Split a text file into multiple files by percentage for test and train I have a large txt file with 50000+ line, how can I randomly split them into 70% for training, 20% for test, and 10% for dev.
result expecting :
train.txt, test.txt, dev.txt

A: Check out Scikit Learn's method train_test_split() to split your training data in subsets.
Then just save your variables in files.

A: I found this code much simpler.
## allocating train, test and validate datasets
import random

fin = open('unique.txt', 'rb')
f75out = open("train.txt", 'wb')
f125aout = open("test.txt", 'wb')
f125bout = open("validate.txt", 'wb')

for line in fin:
  r = random.random()
  if (0.0 <=  r <= 0.75):
    f75out.write(line)
  elif (0.75 < r <= 0.875):
    f125aout.write(line)
  else:
    f125bout.write(line)
fin.close()
f75out.close()
f125aout.close()
f125bout.close()


text:
Q: In square Is there a way to automatically print orders in the receipt printer of my client? I'm building a native android app to sale pickup products of my client but the orders should be automatically printed in the Receipt printer of my client I want to know is this possible?
Currently I'm trying to use the "In-App Payments SDK", "orders API" and "payment API" to process the orders and payments.
Thanks

A: With Square Orders API Pickup Order is a type of fulfillment order that can track delivery details and can track the status of whether the order has been picked up. Additionally you can configure your Square app to automatically print incoming orders by enabling "Automatically Print New Orders" in the Settings section of the Square app under "Remote Orders."


text:
Q: Can't graph value in Kibana using data placed in Elasticsearch by Logstash I have a log that looks like this:
2014-06-12T14:59:01.120997 - MONITOR - Load [0.01] Spawn [9]
2014-06-12T15:00:01.187993 - MONITOR - Load [0.67] Spawn [7]
2014-06-12T15:01:01.292163 - MONITOR - Load [0.86] Spawn [0]
2014-06-12T15:02:01.409863 - PROVISION - [other line format]
2014-06-12T15:02:03.305833 - MONITOR - Load [0.09] Spawn [8]

I have logstash monitoring it and sending to elasticsearch with this input and filter (more efficient way to write this also appreciated.  I'm completely new to logstash/elasticsearch):
input {
   file {
       type => "load_monitor"
       path => "/var/log/load_monitor.log"
       sincedb_path => ["/opt/load_monitor"]
   }
}

filter {
    if [type] == "load_monitor" {
        grok {
            match => ["message", "%{TIMESTAMP_ISO8601:logtime} - %{WORD:montype} - %{GREEDYDATA:content}"]
        }
        if [montype] == "MONITOR" {
            grok {
                match => ["content", "Load \[%{NUMBER:load:float}\] Spawn \[%{NUMBER:spawn:int}\]"]
            }
            mutate {
                remove_field => ['content']
            }
        }
        if [montype] == "PROVISION" {
            // do other stuff
        }
    }
}

It seems to be correct in elasticsearch via kibana (the load and spawn fields exist and are populated correctly):
{
"message":"2014-06-12T15:15:01.436632 - MONITOR - Load [0.71] Spawn [5]",
"@version":"1",
"@timestamp":"2014-06-12T22:15:02.304Z",
"type":"load_monitor",
"host":"prx01",
"path":"/var/log/load_monitor.log",
"logtime":"2014-06-12T15:15:01.436632",
"montype":"MONITOR",
"load":0.71,
"spawn":5
}

When I try to create a histogram in kibana of the "spawn" value, "spawn" isn't auto-suggested and I get this error when I try to graph spawn anyway:
SearchParseException[
    [logstash-2014.06.12][4]: from[-1],size[-1]:
    Parse Failure [
        Failed to parse source
        [
            {
                "facets": {
                    "0": {
                        "date_histogram": {"key_field":"@timestamp","value_field":"spawn","interval":"10s"},
                        "global":true,
                        "facet_filter": {
                            "fquery":{
                                "query":{
                                    "filtered":{
                                        "query":{
                                            "query_string": {
                                                "query":"type: \"load_monitor\""
                                            }
                                        },
                                        "filter":{
                                            "bool":{
                                                "must":[
                                                    {
                                                        "range":{
                                                            "@timestamp":{"from":1402610796579,"to":1402611696579}
                                                        }
                                                    },
                                                    {
                                                        "fquery":{
                                                            "query":{
                                                                "query_string":{
                                                                    "query":"type:(\"load_monitor\")"
                                                                }
                                                            },
                                                            "_cache":true
                                                        }
                                                    }
                                                ]
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
                "size":0
            }
        ]
    ]
]

Can anyone help with this?  I suspect I have to tell elasticsearch to make the spawn field searchable somehow, but I'm not sure how.


text:
Q: Python, run package with `python3.6 -m somepackge.run` I'd like to do the same I can do with python3.6 -m http.server. I'd like to run my oneliner like that. How do I do this? For now I've got:
def run():
    print('Great!')

if __name__ == '__main__':
    run()

I tried python3.6 -m fastapi and I've got /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6: No module named test.__main__; 'test' is a package and cannot be directly executed,
and with python3.6 -m fastapi.run /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6: No module named test.run

A: You need to define a magic file, called __main__.py within your module. See the Python 3 docs on __main__.
In there you typically run a single main() entrypoint function.
For examples, look at pip's, or Tox's one.


text:
Q: How to write a single click event in Visual Basic? I have created a form that allow users to close a form by clicking anywhere on the enlarged picture form (There are 3 objects to consider) and go back to the other form, which is called: "frmPhone". There's an actual picture on the form: "frmPhonePics" which is what I'm using to accomplish what I'm trying to do (was unable to insert an image on here. Sorry.) What I want to do is write a single click event to close the large picture form to allow the user to close it absolutely anywhere in the form, but I don't know how to do that. Here's the code I have so far:
Private Sub frmPhonePics_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Click
    frmPhone.Show()
    Me.Hide()
End Sub

A: You can map the click handler for various object to one thing, if that is what you are asking:
Private Sub frmPhonePics_Click(ByVal sender As System.Object, _
       ByVal e As System.EventArgs) _
          Handles MyBase.Click, Handles  picLarge.Click, Handles otherThing.Click

   frmPhone.Show()
   Me.Hide()           ' should be Me.Close?
End Sub

Not sure why it is MyBase.Click in your code instead of Me.Click.  Is this a subclassed form?

A: It sounds as though you have a picture on your frmPhonePics form. If you double click that (from the VBA editor), you should be taken to the code - for example, you might see
Private Sub Image1_Click()

End Sub

Now all you have to do is add your code there:
Private Sub Image1_Click()
  Me.Hide
  frmPhone.Show()
End Sub

Note - the order matters, since frmPhone.Show() will "hijack" the code flow until it's dismissed, and in your code Me.Hide will not execute (so the form will not close) until frmPhone has been dismissed.

A: I'd strongly suggest using a DoubleClick instead of a single Click.  The chances of an errant click doing the wrong thing is very great.
The easiest way is right from the designer.  Write the sub routine, then for each control, in the properties window, click the events icon(thunderbolt) and assign the sub routine to the double-click event.
Alternatively, dispense with the Handles clause completely and use a series of Addhandler statements in the Load event handler.  If you put a unique string in the names of the controls or if it's all the controls, you can iterate through the controls and use one addhandler statement for all of them
For Each c As Control In Me.Controls
    AddHandler c.DoubleClick, AddressOf Ctrl_DoubleClick
Next

Private Sub Ctrl_DoubleClick(sender As Object, e As EventArgs)
    'Do stuff
End Sub


text:
Q: What OpenGL version to use in LWJGL? Thanks to the LWJGL (LightWeight Java Game Library), I have access to plenty of static OpenGL classes. However, one think I don't understand is why should I use a specific version. In the LWJGL 3 wiki, they say:

The static classes GL11, GL12, GL13, GL20, GL21, GL22,... can be used the access functions of a certain GL Version where GL11 would correspond to OpenGL 1.1, and GL20 would correspond to OpenGL 2.0

I understand that each class is a different version of OpenGL, but I often see many tutorials that depending on what they're doing will use a different class, switching between GL11, GL13 etc. in the same function. Wouldn't it be safer to use the same class everywhere for consistency sake? And why stay with GL11, when GL41 is available? Couldn't it be faster, since it's a more recent version?

A: The LWJGL wiki appears to be out of date. It states that:

Note, only functions which were added in a specific OpenGL version are in a GLXX class (eg. functions in OpenGL 1.2 which were in OpenGL 1.1 are in GL11, not GL12)

Emphasis added. This was true for LWJGL 2.x. This would mean that you have to access a 1.1 function through GL11, even though as far as the OpenGL specification is for, that function would be available through version 4.6.
It's still technically true in LWJGL 3.x, in that each GLXX class only defines the functions added to that specific version. However, in LWJGL 3.x, all of the versioned classes inherit from the previous version. So while the 1.1 functions are still defined in the GL11 class, they are accessible from any higher version.


text:
Q: How does a LINQ IEnumerable work under the hood? After reading various LINQ tutorials I am wondering how exactly it works under the hood and I am hoping someone could confirm some of the questions I have with the following example code:
// The Three Parts of a LINQ Query:
//  1. Data source.
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

// 2. Query creation.
// numQuery is an IEnumerable<int>
var numQuery =
    from num in numbers
    where (num % 2) == 0
    select num;

// 3. Query execution.
foreach (int num in numQuery)
{
    Console.Write("{0,1} ", num);
}

My questions refer to part 2:

*

*Here we are using LINQ syntax to create an IEnumerable object.
Is this no different to any other IEnumerable object used within a
foreach statement, such as List?

*As with all IEnumerables the contents are iterated over using a foreach statement. My query comes from LINQ IEnumerables using deferred execution - when are the contents of the IEnumerable actually gathered? Is it when the GetEnumerator() is called?

With question 2 my assumption would be that the object generated from the LINQ query produces code within the GetEnumerator function which retrieves the data in a fashion represented by our LINQ syntax. Just my guess... Unless I'm thinking about LINQ completely wrong...

A: Both of your questions are closely related.
So, yes, there is a difference.
LINQ query operator return decorator sequences and this decoration enables deferred execution. Decorator sequence is a wrapper over another sequence (int[] in your case) that also knows which query to apply on wrapped sequence.
Actual execution occurs at GetEnumerator().MoveNext() call.


text:
Q: How to wrap a div vertically and then horizontally I need to show the search result data in my site horizontally. I follow a metro UI approach for my website, so I want the data to flow horizontally instead of vertically.
What I require is demonstrated in the below image:

The resulted data is dynamic. I want to draw the divs vertically first based on the parent div height and then horizontally. Something similar to WPF wrap panel, but I haven't been able to achieve it yet.
This is what I have tried, drawing horizontally and then vertically:
Fiddle: http://jsfiddle.net/4wuJz/2/
HTML:

1

Test

2

Test

CSS
#wrap {
   width:100%;
   height: 500px;
   background-color: rgba(0,0,0,0.5);
   overflow:scroll;
   overflow-y:hidden;
}

#wrap1 {
   width:2500px;
   height:500px;
   text-align: center;
}

.result {
   width: 300px;
   vertical-align: middle;
   float:left;
   background: rgba(120,30,20,0.5);
   padding: 10px;
   margin: 30px 0px 30px 30px;
}

How can I change my code so that I meet the desired output? Any jQuery plugins available for this?

A: Add clear: left to the .result class so your boxes are stacked vertically.
Then wrap results in blocks of 3 and float these blocks horizontally. You can do that logic with whichever back-end language you may be using to output the results markup or with jQuery:
$('.result:nth-child(3n+1)').each(function() {
    $(this).add( $(this).next().next().addBack() ).wrapAll('

');
});

Fiddle

Here's a more responsive solution which re-calculates on window resize: Demo.
Note: it assumes all boxes have the same height. You can hardcode a max-height in the resultHeight variable if that's not the case.
$(window).resize(function() {
    var resultHeight = $('.result:first').outerHeight(true),
        nRows = Math.floor( $('#wrap1').height() / resultHeight );

    $('.results-column').contents().unwrap();
    $('.result:nth-child('+nRows+'n+1)').each(function() {
        $(this).nextAll().slice(0, nRows-1).add(this).wrapAll('

');
    });
}).resize();

Added CSS:
#wrap1 {
    white-space: nowrap;
}
.results-column {
    display: inline-block;
    vertical-align: top;
}

Also check out Isotope with its cellsByColumn/fitColumns layouts.

And lastly, your use case is a prime example for the use of the Flexible Box Layout. I haven't mentioned this yet because there are already other answers showing this solution, and also because it is rather hard to make cross-browser at the moment:

*

*Firefox <= 27, IE10 and Safari <= 6 support an old version of the spec

*Newer Chrome, Safari and IE11 support the new syntax

*Can't forget all the browser prefixes!

Reference: http://caniuse.com/flexbox
Though, all is not lost yet. If you want to use Flexbox today, there's a very useful Flexbox generator.
CSS-only solution using Flexbox: Demo
#wrap1 {
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -webkit-box-direction: normal;
    -moz-box-direction: normal;
    -webkit-box-orient: vertical;
    -moz-box-orient: vertical;
    -webkit-flex-direction: column;
    -ms-flex-direction: column;
    flex-direction: column;
    -webkit-flex-wrap: wrap;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    -webkit-box-pack: start;
    -moz-box-pack: start;
    -webkit-justify-content: flex-start;
    -ms-flex-pack: start;
    justify-content: flex-start;
    -webkit-align-content: flex-start;
    -ms-flex-line-pack: start;
    align-content: flex-start;
    -webkit-box-align: start;
    -moz-box-align: start;
    -webkit-align-items: flex-start;
    -ms-flex-align: start;
    align-items: flex-start;
}

I've tested this solution and it works correctly in IE10, IE11, Chrome 31, Opera 18 and Firefox 29 Nightly.
Note: Firefox <= 27 does not support Flexbox with more than one row/column (it does not support flex-wrap: wrap). I've tested this on Firefox 29 (nightly) and it works correctly, so I believe it should land on stable soon enough.

A: Flexbox will be a JavaScript-less solution:
#wrap1 {
    display: flex;
    flex-wrap: wrap;
    flex-direction: column;
}

Demo: http://jsfiddle.net/4wuJz/5/

A: You can simply use the CSS columns, without changing much of your code:
div.wrap {
    width: 100%;
    height: 300px;
    -webkit-column-width: 100px;
       -moz-column-width: 100px;
            column-width: 100px;
    -webkit-column-gap: 16px;
       -moz-column-gap: 16px;
            column-gap: 16px;
}

Check this fiddle: http://jsfiddle.net/Be9B3/

A: You can do this with display:flex
Check the forked codepen demo: http://codepen.io/surjithctly/pen/zolcF
Read more here
HTML

1

2

3

4

5

6

CSS
.flex-container {
  padding: 0;
  margin: 0;
  list-style: none;
  max-height:600px;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;

  -webkit-flex-flow: column wrap;
  justify-content: space-around;
}

.flex-item {
  background: tomato;
  padding: 5px;
  width: 200px;
  height: 150px;
  margin-top: 10px;

  line-height: 150px;
  color: white;
  font-weight: bold;
  font-size: 3em;
  text-align: center;
}


text:
Q: Which UML diagram should I start with? Extends
Say you're looking at the 6 basic types of UML diagram (from this The Elements Of UML 2.0 Style)

*

*Class diagrams

*Use case diagrams

*State machine diagrams

*Activity diagram

*Sequence diagram

*Physical diagram

Pretend you're insane and you feel like drawing up all 6 diagrams for your system.
Which would you start with?  Then which would you go to?  What's the best order to visit each diagram if you have a pretty clear idea of what you want your system to do?
I think you should start with the physical diagram and work your way to class diagram.  Top down, I always say..?  Am I wrong?

A: Class, sequence and usecase diagram represents over 90% of usually created diagram inside a project. Class diagram itself sometimes represents more diagram than all the other diagrams.
The best solution is to keep it simple and adapt the modeling to the level of the team.
If no UML experience then just create class diagram to represent the skeleton of your application.
If beginner level then start with an usecase, sequence and class diagram.
If medium level then use all the diagrams because each diagram cover another view which is not always possible to code with Java. I mean that java is only related to class and sequence diagram.

A: Use cases are the main ones that define "what" your system does, possibly followed by state machines and activity diagrams (which could be seen either way -- normally the activity diagrams are more about the "what" and the state machines more about the "how", but I've seen counterexamples to each); class and sequence diagrams, and even more so component and deployment ones (collectively the "physical"), are more and more about how your system does what it does.  I'd definitely go from the "what" towards the "how" as the reverse sequence makes little sense -- how can "how" make sense if you haven't defined the "what"?
So, summarizing, roughly: use cases, activity, state machine, class, sequence, component, deployment.  This order makes sense because it gets deeper towards the implementation aspects and away from the analysis aspects, so e.g. somebody interested in understanding exactly what use cases you'll cater to and what business rules you'll apply (activity diagrams) may stop "reading" earlier than somebody who needs to understand the full detailed logic of your deployment strategy.

A: Physical diagram is probably as good a place to start as any. I find activity diagrams really helpful in working out the kinks in a design, and sequences are good for much the same reason. I've rarely bothered with state machine diagrams.
I think realistically you're going to want to revisit whatever design you do first anyway (iterated design, woo!) so it's probably worth starting with whatever is going to bring the most clarity to your project.

A: UML diagrams are depictions of various models of a design. I am not sure that they can be cleanly serialized the way you describe. Frequently a class diagram is used in both the analysis and design phases of a process. Similarly other diagrams are used in multiple phases.
It depends on which aspect of a design you are interested in at any point in time you use the appropriate diagram to "view" a model of the design.
I have seen both "start with class diagram" and "start with use case model" proposed. I have come to realize that it really does not matter.
I think you want to start with the high level behaviour of the system using several diagrams then gradually work your way down to more detailed design using the same set of diagrams.


text:
Q: Amazing ListView with onclicklistener not working, help pls I have used the android-amazing-listview from :https://code.google.com/p/android-amazing-listview/
I added a setOnItemClickListener, But it does not work. Can someone please give me a hand :
PaginationDemoActivity
package com.foound.amazinglistview.demo;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.foound.widget.AmazingAdapter;
import com.foound.widget.AmazingListView;

public class PaginationDemoActivity extends Activity {
    AmazingListView lsComposer;
    PaginationComposerAdapter adapter;
    ImageLoader imageLoader;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pagination_demo);
        imageLoader = new ImageLoader(this);

        lsComposer = (AmazingListView) findViewById(R.id.lsComposer);
        lsComposer.setLoadingView(getLayoutInflater().inflate(R.layout.loading_view, null));
        lsComposer.setAdapter(adapter = new PaginationComposerAdapter());

        adapter.notifyMayHaveMorePages();
    }

    public void bRefresh_click(View v) {
        adapter.reset();
        adapter.resetPage();
        adapter.notifyMayHaveMorePages();
    }

    class PaginationComposerAdapter extends AmazingAdapter {
        List<Composer> list = Data.getRows(1).second;

        private AsyncTask<Integer, Void, Pair<Boolean, List<Composer>>> backgroundTask;

        public void reset() {
            if (backgroundTask != null) backgroundTask.cancel(false);

            list = Data.getRows(1).second;

            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Composer getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        protected void onNextPageRequested(int page) {
            Log.d(TAG, "Got onNextPageRequested page=" + page);

            if (backgroundTask != null) {
                backgroundTask.cancel(false);
            }

            backgroundTask = new AsyncTask<Integer, Void, Pair<Boolean, List<Composer>>>() {
                @Override
                protected Pair<Boolean, List<Composer>> doInBackground(Integer... params) {
                    int page = params[0];

                    Log.e("more page", "page: " + page);
                    return Data.getRows(page);
                }

                @Override
                protected void onPostExecute(Pair<Boolean, List<Composer>> result) {
                    if (isCancelled()) return;

                    Log.e("onPostExecute", "result: " + result.first);
                    list.addAll(result.second);
                    nextPage();
                    notifyDataSetChanged();

                    if (result.first) {
                        // still have more pages
                        notifyMayHaveMorePages();
                    } else {
                        notifyNoMorePages();
                    }
                };
            }.execute(page);
        }

        @Override
        protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
        }

        @Override
        public View getAmazingView(int position, View convertView, ViewGroup parent) {
            View res = convertView;

            if (res == null) res = getLayoutInflater().inflate(R.layout.item_composer, null);

            // we don't have headers, so hide it
            res.findViewById(R.id.header).setVisibility(View.GONE);

            TextView lName = (TextView) res.findViewById(R.id.lName);
            TextView lYear = (TextView) res.findViewById(R.id.lYear);
            TextView lId = (TextView) res.findViewById(R.id.lId);
            // Locate the ImageView in listview_item.xml
            ImageView lImg = (ImageView) res.findViewById(R.id.lImg);

            final Composer composer = getItem(position);
            lName.setText(composer.name);
            lYear.setText(composer.year);
            lId.setText(composer.id);

            Log.e("getAmazingView PRINT THE URL 1111111111", "URL: " + composer.img);
            // Capture position and set results to the ImageView
            // Passes img images URL into ImageLoader.class
            imageLoader.DisplayImage(composer.img, lImg);
            Log.e("222","333");

            //test
            lsComposer.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    Log.e("onItemClick","4444444444444444444444");

                    /*// getting values from selected ListItem
                    String lId =   ((TextView) view.findViewById(R.id.lId))  .getText()   .toString();
                    String lName = ((TextView) view.findViewById(R.id.lName)).getText()   .toString();
                    String lYear = ((TextView) view.findViewById(R.id.lYear)).getText()   .toString();
                    String lImg =  ((ImageView) view.findViewById(R.id.lImg)).getContext().toString();
                    */
                    // Starting new intent
                    Intent in = new Intent(getApplicationContext(), SingleItemView.class);
                    in.putExtra("id", composer.id);
                    in.putExtra("title", composer.name);
                    in.putExtra("s_desc", composer.year);
                    in.putExtra("img", composer.img);

                    Log.e("onItemClick PRINT THE URL 777777777777", "onItemClick: ");

                    startActivity(in);

                }
            });
            //test */

            return res;

        }

        @Override
        public void configurePinnedHeader(View header, int position, int alpha) {
        }

        @Override
        public int getPositionForSection(int section) {
            return 0;
        }

        @Override
        public int getSectionForPosition(int position) {
            return 0;
        }

        @Override
        public Object[] getSections() {
            return null;
        }

    }
}

Single item View
package com.foound.amazinglistview.demo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class SingleItemView extends Activity {
    // Declare Variables
    String id;
    String name;
    String year;
    String img;
    String position;
    ImageLoader imageLoader = new ImageLoader(this);

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from singleitemview.xml
        setContentView(R.layout.singleitemview);

        Intent in = getIntent();
        // Get the result of id
        id = in.getStringExtra("id");
        // Get the result of title
        name = in.getStringExtra("name");
        // Get the result of s_desc
        year = in.getStringExtra("year");
        // Get the result of img
        img = in.getStringExtra("img");

        // Locate the TextViews in singleitemview.xml
        TextView lId =   (TextView) findViewById(R.id.lId);
        TextView lName = (TextView) findViewById(R.id.lName);
        TextView lYear = (TextView) findViewById(R.id.lYear);

        // Locate the ImageView in singleitemview.xml
        ImageView imgimg = (ImageView) findViewById(R.id.lImg);

        // Set results to the TextViews
        lId.setText(id);
        lName.setText(name);
        lYear.setText(year);

        // Capture position and set results to the ImageView
        // Passes img images URL into ImageLoader.class
        imageLoader.DisplayImage(img, imgimg);
    }

A: This implementation is wrong.
Either you write setOnItemClickListener for your ListView in your onCreate,
        lsComposer.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                    // action
            }
        });

or you will change it to another View's onClickListenner inside Adapter
Example:
        res.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                    Intent in = new Intent(getApplicationContext(), SingleItemView.class);
                    in.putExtra("id", composer.id);
                    in.putExtra("title", composer.name);
                    in.putExtra("s_desc", composer.year);
                    in.putExtra("img", composer.img);

                    Log.e("onItemClick PRINT THE URL 777777777777", "onItemClick: ");

                    startActivity(in);
            }
        });


text:
Q: Unique Readability An essential ingredient of the workings of mathematical logic is the possibility of defining functions by recursion on the complexity of formulas. In order to ensure that such a function assigns exactly one value to each of its arguments one usually has to use a unique readability theorem, which says that every formula can be formed in only one way. More precisely, in the case of classical propositional logic the theorem says the following:

*

*For every formula $\phi$ exactly one of the following cases holds:

*

*$\phi$ is a propositional variable.

*there is unique formula $\psi$ such that $\phi = \neg \psi$.

*there is a unique pair $\langle \psi, \chi \rangle$ of formulas and a unique binary connective $\circ$ such that $\phi = (\psi \circ \chi)$.

The complexity of the proof of this theorem crucially depends on how formulas are defined. If we follow orthodoxy and define formulas as some finite sequences the proof gets quite involved.
However, there is a different way of defining formulas, which immediately implies the result. According to that approach formulas are ordered tuples whose members belong to the usual propositional alphabet. Such a definition might run as follows:

*

*The set of formulas, $\mathcal{F}$, is the smallest set such that:

*

*$\langle p \rangle \in \mathcal{F}$ for every propositional variable $p$.

*$\langle \neg, \phi \rangle \in \mathcal{F}$, if $\phi \in \mathcal{F}$

*$\langle \phi, \circ, \psi \rangle \in \mathcal{F}$, if $\phi, \psi \in \mathcal{F}$ and $\circ$ is binary.

On may retain familiar notation by letting $\neg \phi := \langle \neg, \phi  \rangle$ etc. It's obvious that under such a treatment we can dispense with brackets. If we want to stick to them one has to introduce them as part of the meta language.
Question: Why is this definition of formulas, which is equivalent to the orthodox one, so rarely seen in the literature? Are there any problems technical or conceptual that arise in connection with this definition but not in connection with the orthodox one?

A: Short, rough answer: the first style of definition is [naturally read as] a definition for a  class of well-formed formulae as expression-types, and the second style of definitions is a definition for a class of set-theoretic proxies for formulae in the sense of expression-types.
Suppose we say '$P$' and '$Q$' are propositional variables, and that '$\to$' is a connective. What are we talking about here? Surely not particular ink markings, or particular arrays of pixels. The obvious thing to say is that we are talking of expression types, types or patterns of which particular inscriptions are physical tokens or instances. Likewise, when we say '$(P \to Q)$' is a wff: what we are talking about is surely another expression type (which has many instances on bits of paper and laptop screens etc). Defining the class of wffs is naturally done, then, by telling us the rules for forming more complex expression types out of simpler ones. And that's what the first-style of definition for the class of wffs does -- it deals directly in expression types. This is the obvious line to take.
How are we to read the second kind of definition? It too talks of propositional variables, so on the face of it, the construction is done in a set theory with expressions types as urelemente (which might seem to be more heavy-duty apparatus than we need: if we already countenance expression types, why not do the whole story simply in terms of them??). But perhaps the so-called propositional variables here are really more sets, being used as proxies (or models or implementations) for expression-types, so the whole construction is done in pure set theory.
If you look at the fine print of many logic books, you find authors take different lines about what's going on in their formal languages, and it takes patience to sort things out. For example, while many introduce the symbol '$\to$' as a conditional, for some the symbol serves as proxy or representation for whatever symbol is the conditional connective of your favourite ground-level language $L$ (as Bell and Machover put it, "what the latter symbol actually looks like is of no importance; and the reader may give free rein to his imagination"). If you take this more abstract line, you aren't directly specifying expression-types but providing abstract representations of them. In this case, you might as well use set-theoretic representations of them with nice properties (like trivial "unique readability"). But note the nice properties come at a price -- you've stopped talking about expression types directly, and started talking about set-theoretic proxies for them.

A: There are, as the question says and Peter Smith describes, two main options:

*

*Define formulas to be a particular kind of expression - a concrete object like a sequence of written symbols.

*Define formulas to be a particular kind of abstract object - for example, when formalizing logic in ZFC, we may define a formula to be a particular kind of set such as an ordered tuple or a tree.
The main reason for being interested in the former is that, apart from the mathematical goals of logic, there are also foundational and computational goals. These are closely related.
Foundationally, we may want to rely on as few abstract concepts as possible when setting up our logic.  Some results (e.g. completeness) will rely on abstract concepts, but the basic concepts of syntax and provability don't have to. We can define an expression to be a particular kind of physical structure - a sequence of physical objects of a certain type. There is a small amount of idealization, because no physical object can make a perfect "$\land$", but this is a much smaller amount of idealization than if we define an expression to be some kind of abstract object with no physical token.  This goal of having foundational systems with the minimum number of abstract assumptions was particularly of interest during the period in time when the details of modern formal logic were first developed.
Computationally, we may want to be able to verify a formal deduction, or to create a formal deduction automatically with a theorem prover. For example, there are completely formalized and verified proofs of the prime number theorem and a few other "big" theorems. We need to pass the input to the theorem prover in some concrete form (probably inside a computer file). Until we have a computer program to which we can directly pass a set, it won't help us to define a formula to be a set if we want to pass that formula to the computer.
In elementary settings, the authors will want to keep the students' options open. So the author is likely to choose a presentation that can be used by students whose primary goals are mathematical, foundational, or computational. Of course each book will have its own mix of the three.
In more advanced settings, it is more common to define a formula to be a set (e.g. a tuple or a tree). This is because readers in those settings will be familiar with the possibility of representing everything in a more concrete way.  Making the definition abstract avoids the need to prove the unique readability theorem. But even these authors probably still think of formulas as expressions; they are likely to look at the abstract definitions as a slick way of doing things from an advanced point of view.

A: Because both options are exactly isomorphic to ASTs (abstract syntax trees).


text:
Q: shared object import error while cross compiling for ARM I am cross compiling my files to put in raspberry pi. tool chain from raspberry pi official site was downloaded. Then cross compiled in my ubuntu 64 system using arm-bcm2708-linux-gnueabi-gcc. But when I tried to use these cross compiled .so file in raspberry pi it shows an error as follows :
error while loading shared libraries: libtest.so: cannot open shared object file: No such file or directory
How this error can be resolved?

A: arm-bcm2708-linux-gnueabi is an old version,
have you tried a newer cross compiler such as arm-rpi-4.9.3-linux-gnueabihf


text:
Q: Integrate $\int_{C} \frac{1}{r-\bar{z}}dz$ - conflicting answers In an homework exercise, we're asked to integrate $\int_{C} \frac{1}{k-\bar{z}}dz$ where C is some circle that doesn't pass through $k$.
I tried solving this question through two different approaches, but have arrived at different answers.
Idea: use the fact that in C, $z\bar{z}=r^2$, where $r$ is the radius of C, to get
$$\int_{C} \frac{1}{k-\frac{r^2}{z}}dz$$
We then apply Cauchy to get that the answer is $2πi r^2/k^2$ when C contains $r^2/k$, and 0 otherwise.
Another idea: Intuitively, since C is a circle we get ${\int_{C} \frac{1}{k-\bar{z}}dz} = \int_{C} \frac{1}{k-z}dz$ (since $\bar{z}$ belongs to C iff $z$ belongs to C) and we can then use Cauchy's theorem and Cauchy's formula (depending on what C contains) to arrive at a different answer.
Which answer (if any) is correct?

A: I think that the first approach is correct. If the circle is centered about the origin, then it is true that the conjugate also lies on the same circle. However, "dz" at $ z $ is not the same as "dz" at $ \bar{z} $ . This is why they are different.

A: I've definitely made the same "intuitive" argument about $z \in C$ iff $\bar{z} \in C$, so eh, the integrals are probably the same. In retrospect, this is because I didn't understand, formally or intuitively, what $dz$ means.
First off, what is a contour integral? For concreteness, let's work with a circle $C \subset \mathbb{C}$ and a (continuous) function $f: C \rightarrow \mathbb{C}$. This is literally all you do: wind around the circle (counterclockwise) and along the way, pick out some points $z_0, \ldots, z_n$. Just as in integrating functions $f: \mathbb{R} \rightarrow \mathbb{R}$, you consider the quantity $\sum_i f(z_i)(z_i - z_{i-1})$:
For roughly the same reason as its true in real analysis, when you take finer and finer samplings, these all approach a common value, which we call $\int_C f dz$.
Now, from this it should be clear heuristically that when $C$ is centered at the origin, $\int_C zdz$ need not equal $\int_C \bar{z} dz$, since when you exchange $z_i$ and $\bar{z_i}$, you'd also need to exchange $(z_i - z_{i-1})$ with $(\bar{z}_i - \bar{z}_{i-1})$ (with a sign to account for switching from counterclockwise to clockwise) but you don't when you leave the $dz$ untouched.
P.S. For fun, consider working out that $\int_{|z| = 1} zdz = 0, \int_{|z|=1} \bar{z} dz = 2 \pi i$ straight from this definition. I tried sampling at the $n^{th}$ roots of unity, for $zdz$ I got 0, and for $\bar{z}dz$ I got $n(1 - \zeta^{-1})$, where $\zeta = e^{2\pi i/n}$.

A: The original function is not holomorphic since $\frac{d}{d\overline{z}}\frac{1}{k-\overline{z}}=\frac{-1}{(k-\overline{z})^{2}}$. So you cannot apply Cauchy's integral formula.
Let $C$ be centered at $c$ with radius $r$, then we have $z=re^{i\theta}+c=c+r\cos(\theta)+ri\sin(\theta)$, and its conjugate become $c+r\cos(\theta)-ri\sin(\theta)=c+re^{-i\theta}$. Therefore we have $k-\overline{z}=k-c-re^{-i\theta}$. To noramlize it we mutiply $(k-c-r\cos(\theta))-ri\sin(\theta)=k-c-re^{i\theta}$. The result is $(k-c-r\cos(\theta))^{2}+r^{2}\sin^{2}\theta$. Rearranging gives $$k^{2}+c^{2}+r^{2}-2kc-2(k-c)r\cos(\theta)=A-2Br\cos(\theta),A=k^{2}+c^{2}+r^{2}-2kc,B=k-c$$
So we have $$\int_{C}\frac{1}{k-\overline{z}}=\int^{2\pi}_{0}\frac{k-c-re^{i\theta}}{(k-c-re^{-i\theta})(k-c-re^{-i\theta})}dre^{i\theta}=ri\int^{2\pi}_{0}\frac{Be^{i\theta}-re^{2i\theta}}{A-2Br\cos(\theta)}d\theta$$
So it suffice to integrate $$\frac{e^{i\theta}}{1-C\cos(\theta)}d\theta,C=constant$$ since the above integral is a linear combination of integrals of this type. But this should be possible in general as we can make trigonometric substitutions.


text:
Q: Creating table with current date plus 30 days after current date Can someone help me create a table with the date being equal to current date plus 30 days. Is this right?
CREATE TABLE SAMPLE
( datetoday DATETIME NOT NULL DEFAULT current_datetime(),
  dateafter30days DATETIME NOT NULL DEFAULT current_date(+30)
);

The logic is for example there is a subscriber that registered now so it will be recorded on the database and the expiration of his registration is after 30 days.
Meaning date of registration and date of expiration..
Many Thanks
Joey

A: You may use calculated (and optionally persistent) field for this:
CREATE TABLE YourTableName
(
Subscriber INT PRIMARY KEY,
IssueDate DATETIME,
ExpireDate AS DATEADD(DAY, 30, IssueDate)
)

A: create table SAMPLE
(
   SUBSCRIBER_ID    INT Primary Key,
   REGISTER_DT      DATETIME NOT NULL,
   EXPIRE_DT        DATETIME NOT NULL
)

you can update expire date when register for new user as follow.
 INSERT INTO SAMPLE(SUBSCRIBER_ID,REGISTER_DT,EXPIRE_DT)
    VALUES (1,GETDATE(), DATEADD(DAY,30,GETDATE())

A: Yes, here you try. When new subscriber data is inserted, registere date is current date, expire date is 30 days after current date. Your insert sql statement, don't need to mention these two columns (REGISTER_DT,EXPIRE_DT), these two will be updated auto on inserting statement.
Based on following table structure, your insert statement should be
INSERT INTO SAMPLE (SUBSCRIBER_NM) VALUES ('John');

-- table creation statement
 CREATE TABLE [dbo].[SAMPLE](
        [SUBSCRIBER_ID] [int] IDENTITY(1,1) NOT NULL,
        [SUBSCRIBER_NM] [nvarchar](50) NOT NULL,
        [REGISTER_DT] [datetime] NOT NULL CONSTRAINT [DF_SAMPLE_REGISTER_DT]  DEFAULT (getdate()),
        [EXPIRE_DT] [datetime] NOT NULL CONSTRAINT [DF_SAMPLE_EXPIRE_DT]  DEFAULT (dateadd(day,(30),getdate())),
     CONSTRAINT [PK_SAMPLE] PRIMARY KEY CLUSTERED
    (
        [SUBSCRIBER_ID] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]

A: Create a table and a trigger on insert
*Table *
create table test
(
sub_id int primary key,
issueDate datetime,
expDate datetime
)

CREATE TRIGGER test_trigger BEFORE INSERT ON `test`
FOR EACH ROW SET NEW.issueDate = IFNULL(NEW.issueDate,NOW()),
NEW.expDate= TIMESTAMPADD(DAY,30,NEW.issueDate)


text:
Q: Select row names based on character in R I have a character x:
x<-c("TTTCGATGTCCACACG", "TTTGTTGAGACGTCGA", "TTTGTTGTCATCTGTT")

and a data frame z
z <- data.frame (y=c(8, 10, 5, 10, 5, 10))
row.names (z) <- c("TTTCGATGTCCACACG", "TTTGTTGAGACGTCGA", "TTTGTTGTCATCTGTT", "TTTCGATGTCCAAACG", "TTTGTTGAATCCTCGA", "TTTGTTGTCATGTGTT")

I would like to select for columns and rows that match names in the x.
output
                  y
TTTCGATGTCCACACG  8
TTTGTTGAGACGTCGA  10
TTTGTTGTCATCTGTT  5

A: With R base
> z[rownames(z) %in% x, , drop=FALSE]
                  y
TTTCGATGTCCACACG  8
TTTGTTGAGACGTCGA 10
TTTGTTGTCATCTGTT  5

With dplyr
 library(dplyr)
 library(tibble)

 z %>%
   tibble::rownames_to_column() %>%
   filter(rowname %in% x)
           rowname  y
1 TTTCGATGTCCACACG  8
2 TTTGTTGAGACGTCGA 10
3 TTTGTTGTCATCTGTT  5


text:
Q: Multiple Param with React Router I have two components one is AddList component and second is DetailList compnent. What i am doing is there is a list of AddList component and button in every li . Whenever the user click on any button the respective id and name of that particualar LI is sent to DetailList component so that user can read more on that particular product.
I am using react roouter and when i pass one param in the route every thing works i fine. I can console.log the respected Id <Route exact path="/details/:id" component={DetailOffAdd} />. But when i pass second param in route <Route exact path="/details/:id/:name" component={DetailOffAdd} /> my component did not mount and also it does not shows any error. It also do not console the id and name i am priting in DetailList component.
Here is my AddList
export default class Addlist extends Component {
    constructor(props) {
      super(props)
      this.state = {
        posts : []
      }
    }
passToDetailList(id,name) {
     this.props.history.push('/details/'+id+name)
}
    render() {
      const { posts } = this.state;
        return (

          {
            posts.map(post => {
              return (

                <button onClick={() => this.passToDetailList(post.id, post.add_title)}>VIEW</button>

              );
            })}

**And the DetailList Component**

    export default class DetailOffAdd extends Component {
    componentDidMount(){
        console.log(this.props.match.params.id)
      }
    render() {
        return (
            <Fragment>
              Some code
            </Fragment>
        )
    }
}

A: You can use a single slug in the router path to send much more details -
<Route exact path="/details/:id" component={DetailOffAdd} />

let dataObj  = {
       id:1,
       name:"someProduct"
    }
let stringifyData = JSON.stringify(dataObj);

To pass the data  -
passToDetailList(id,name) {
  this.props.history.push('/details/'+stringifyData)
}

To Get the data in details file -
let data  = JSON.parse(this.props.match.params.id);
console.log(data) // here is your full data

A: I think you are missing a '/', try changing your passToDetailList to this:
this.props.history.push(`/details/${id}/${name}`)


text:
Q: OpenVPN switch back to primary server after connection recovery on pfSense We are using pfSense as Openvpn server / clients.
We are have around 20 site to site pfSense clients which connects to main site using Openvpn site to site configuration.
On main pfSense (vpn server) we did install multiple wans and we have setup failover site to site connection, by setting server to listen localhost and port forwards vpn ports from multiple wans to 127.0.0.1.
On the clients in Custom options we added:
remote serverAlternatieWanIp VpnPort udp
This scenario working OK for us when main link goes down clients established new connection over alternative WAN.
What we do not know is:
How to push clients to switch back (reconnect) to main WAN after main WAN connection get up again ? (Our workaround is now to restart Openvpn client or sometimes to restart whole pfSense to push vpn clients to connect again to main WAN, or to "kill" alternative WAN to push VPN clients to reconnect to main. All of them seems for me is bad way to do that).
We will also love to see which of clients is connected to alternate WAN.
Now workaround is to go on each vpn client pfsense and to read remote host address on vpn status of client.
We are using Zabbix to monitor our network infrastructure, and we will love to try figure which wan is used for connection in some API way so we can at least trigger error on Zabbix and tell admins to reconnect client to main WAN.

A: I have two ideas
1. You could have OpenVPN wait until there is no activity (if possible, maybe at night?) and then drop the connection or re-resolve the servers IP (and maybe do something tricky/creative with DNS) automatically. I have not tested any of this, I've just glanced at the documentation. It looks like this could work for you, you'll just need to experiment.
Aside from that, I don't see anything inherently wrong with dropping client connections to get them to reconnect by restarting their instances or taking the backup link down momentarily as long as users can handle a brief disconnect. Were you worried about that? Or just keen on having it happen automatically?
Extracted from OpenVPN man page: https://openvpn.net/index.php/open-source/documentation/manuals/65-openvpn-20x-manpage.html

--inactive n (Experimental) Causes OpenVPN to exit after n seconds of inactivity on the TUN/TAP device. The time length of inactivity is
measured since the last incoming tunnel packet.
--ping n Ping remote over the TCP/UDP control channel if no packets have been sent for at least n seconds (specify --ping on both peers to
cause ping packets to be sent in both directions since OpenVPN ping
packets are not echoed like IP ping packets). When used in one of
OpenVPN's secure modes (where --secret, --tls-server, or --tls-client
is specified), the ping packet will be cryptographically secure. This
option has two intended uses:
(1) Compatibility with stateful firewalls. The periodic ping will
ensure that a stateful firewall rule which allows OpenVPN UDP packets
to pass will not time out.
(2) To provide a basis for the remote to test the existence of its
peer using the --ping-exit option.
--ping-exit n Causes OpenVPN to exit after n seconds pass without reception of a ping or other packet from remote. This option can be
combined with --inactive, --ping, and --ping-exit to create a
two-tiered inactivity disconnect. For example,
openvpn [options...] --inactive 3600 --ping 10 --ping-exit 60
when used on both peers will cause OpenVPN to exit within 60 seconds
if its peer disconnects, but will exit after one hour if no actual
tunnel data is exchanged.
--ping-restart n Similar to --ping-exit, but trigger a SIGUSR1 restart after n seconds pass without reception of a ping or other packet from
remote. This option is useful in cases where the remote peer has a
dynamic IP address and a low-TTL DNS name is used to track the IP
address using a service such as http://dyndns.org/ + a dynamic DNS
client such as ddclient.
If the peer cannot be reached, a restart will be triggered, causing
the hostname used with --remote to be re-resolved (if --resolv-retry
is also specified).
In server mode, --ping-restart, --inactive, or any other type of
internally generated signal will always be applied to individual
client instance objects, never to whole server itself. Note also in
server mode that any internally generated signal which would normally
cause a restart, will cause the deletion of the client instance object
instead.
In client mode, the --ping-restart parameter is set to 120 seconds by
default. This default will hold until the client pulls a replacement
value from the server, based on the --keepalive setting in the server
configuration. To disable the 120 second default, set --ping-restart 0
on the client.
See the signals section below for more information on SIGUSR1.
Note that the behavior of SIGUSR1 can be modified by the
--persist-tun, --persist-key, --persist-local-ip, and --persist-remote-ip options.
Also note that --ping-exit and --ping-restart are mutually exclusive
and cannot be used together.

I suggest reading the manual. There's more stuff there.
See this too - PfSense specific discussion about the matter: https://forum.pfsense.org/index.php?topic=42935.0
2. Another idea is to run a script (to restart OpenVPN?) on interface status change. This also, I'm not going to go test or anything but I did find some discussion about it.
https://forum.pfsense.org/index.php?topic=65846.0
Apparently you can store commands in /etc/devd.conf
Mine contains:
# $Id$
# $FreeBSD: src/etc/devd.conf,v 1.26.2.1 2005/09/03 22:49:22 sam Exp $

options {
        directory "/etc/devd";
        directory "/usr/local/etc/devd";
        pid-file "/var/run/devd.pid";
        set scsi-controller-regex
                "(aac|adv|adw|aha|ahb|ahc|ahd|aic|amd|amr|asr|bt|ciss|ct|dpt|\
                esp|ida|iir|ips|isp|mlx|mly|mpt|ncr|ncv|nsp|stg|sym|trm|wds)\
                [0-9]+";
};

# CARP notify hooks. This will call carpup/carpdown with the
# interface (carp0, carp1) as the first parameter.
notify 100 {
    match "system"          "CARP";
    match "type"            "MASTER";
    action "/usr/local/sbin/pfSctl -c 'interface carpmaster $subsystem'";
};

notify 100 {
    match "system"          "CARP";
    match "type"            "BACKUP";
    action "/usr/local/sbin/pfSctl -c 'interface carpbackup $subsystem'";
};

notify 100 {
    match "system"          "CARP";
    match "type"            "INIT";
    action "/usr/local/sbin/pfSctl -c 'interface carpbackup $subsystem'";
};

# When a USB keyboard arrives, attach it as the console keyboard.
attach 100 {
        device-name "ukbd0";
        action "kbdcontrol -k /dev/ukbd0 < /dev/console 2>/dev/null";
};

detach 100 {
        device-name "ukbd0";
        action "kbdcontrol -k /dev/kbd0 < /dev/console 2>/dev/null";
};

#
# Signal upper levels that an event happened on ethernet class interface
#
notify 0 {
        match "system"          "IFNET";
        match "type"            "LINK_UP";
        media-type              "ethernet";
        action "/usr/local/sbin/pfSctl -c 'interface linkup start $subsystem'";
};

notify 0 {
        match "system"          "IFNET";
        match "type"            "LINK_DOWN";
        media-type              "ethernet";
        action "/usr/local/sbin/pfSctl -c 'interface linkup stop $subsystem'";
};

#
# Signal upper levels that an event happened on 802.11 class interface
#
notify 0 {
        match "system"          "IFNET";
        match "type"            "LINK_UP";
        match "subsystem"       "[a-z]+[0-9]+_wlan[0-9]+";
        action "/usr/local/sbin/pfSctl -c 'interface linkup start $subsystem'";
};

# Notify all users before beginning emergency shutdown when we get
# a _CRT or _HOT thermal event and we're going to power down the system
# very soon.
notify 10 {
        match "system"          "ACPI";
        match "subsystem"       "Thermal";
        match "notify"          "0xcc";
        action "logger -p kern.emerg 'WARNING: system temperature too high, shutting down soon!'";
};

Maybe that will work for you


text:
Q: Link to a section of an html doc that's been loaded in a div My site has a "nav" div, with links to different html files, a "sidebar" div with static information, and a "content" div, which the different html files get loaded into.  I've also set my url base in the header. One of these html files is a long document, and I'd like to be able to include links to sections of this file.  So I named the section headers and used the hashtag to link to them:
portfolio.html snippet:

PULSE OXIMETRY IN ZAMBIA

DENGUE DIAGNOSIS IN NICARAGUA

EYE HEALTH IN INDIA

MAS.531 COMPUTATIONAL CAMERA AND PHOTOGRAPHY

MAS.S60 HANDS ON FOUNDATIONS

PULSE OXIMETRY IN ZAMBIA

lorem ipsum

And this works wonderfully when I've opened the html by itself.  But when it's been loaded into the "content" div within the meta html file, it tries to take me to <myurlbase>#pulseox.  How do I make the  link refer to html doc within the "content" div?  I haven't set a base url in the portfolio.html file.
Here's my meta html doc, if that helps:

<link rel="stylesheet" type="text/css" href="index_test.css" />
<base href="http://myurl/" />

HOME.

ABOUT.

PORTFOLIO.

CV.

myname