text:
Q: Fetch list of numbers I have used beautiful soup to fetch a class
soup.select('.pr-xs')

which results in
    [
     1,184,500 students
   ,
     697,000 students
   ,
     167,500 students
   ,
     145,500 students
   ,
     81,000 students
   ,
     172,000 students
   ]

Now I want a new list contains only numbers like
['1184500, 697000, 167500,145500,81000,172000]

A: Try this to get the following result:
from bs4 import BeautifulSoup

soup = BeautifulSoup(content,"lxml")
data = [item.text.split("students")[0].strip() for item in soup.select('.pr-xs')]
print(data)

Output:
['1,184,500', '697,000', '167,500', '145,500', '81,000', '172,000']

A: You can use re to find the numbers:
import re
numbers = [re.sub(',', '', re.findall('[\d,]+', str(i))[0]) for i in soup.select('.pr-xs')]

A: take the help of regression functions
import re
students = [re.sub(',', '', re.findall('[\d,]+', str(i))[0]) for i in soup.select('.pr-xs')]

this will give you the result as
['1184500','697000','167500','145500','81000','172000']


text:
Q: Does shutting down and restarting Ubuntu have an effect on its performance? This article talks about how OS's accumulate all sorts of unnecessary things in the RAM due to continued use. Is this the case with Ubuntu too?
Just curious as my computer has been getting a bit sluggish after a week of not turning off.

A: You probably don't need to restart to clear the ram and swap, as you can clear both without restarting:

*

*Clearing Swap: You can turn swap off and on again to clear it (make you have enough spare memory using free -m, top or similar) using sudo swapoff -a && sudo swapon -a. If stuff is moved to swap when you have enough free memory, and you don't want it to be, you need to configure swappiness.

*Clearing Cache: Can be done by the method suggested here: free && sync && echo 3 > /proc/sys/vm/drop_caches && free. Needs to be done as root, so you can run sudo -i beforehand to drop into a root shell, or try enclosing it in sudo sh -c " "

*Clearing programs from RAM: By closing open apps you don't need, and killing extra processes (CAREFULLY) in htop by selecting each process and pressing k+Enter (the tree view in htop is very useful here, press t to use it, then you can determine parent processes etc). Some applications (e.g KDE apps in a GNOME environment) start processes that you may not now need, so you can kill those
However, it may still be necessary to close the machine down every so often due to maintenance, memory leaks, overheating, power cuts etc. You also may need to restart to apply system updates (though you may not need to restart the system for kernel updates with kernel 4+),

A: Some applications, when working for days can "grow up" in memory because there might be memory leaks (memory is reserved and not returned when not needed). When you have less memory (because of memory leaks) system moves information from memory to disk (swap partitions) more often, and this is probably the reason of slowing down you experience.

A: You can also open a terminal and do the following
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install bleachbit
sudo bleachbit

It will open a program that removes a lot of clutter, old kernels and it will give you a performance boost. Also a reboot every now and then is not bad :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any way to run a separate notebook after one process is finished in zeppelin? Suppose the following is the example process
Notebook1

df.count()
df.show()

Notebook2

df2.count()
df2.show()

I want to call Notebook2 on zeppelin after Notebook1 is finished.

A: you need to access to dispatching system(eg: azakaban), zeppelin does not provied the note dependency

A: there are two ways

*

*at the end of last paragraph of notebook1, you can call
z.run("", "paragraphid of notebook2");

*there is a rest call( https://zeppelin.apache.org/docs/0.8.1/usage/rest_api/notebook.html#get-the-status-of-a-single-paragraph ) in zeppelin by which you can check the status of paragraphs, such as running state or finished. as soon as you get the status as finished of notebook1's last paragraph then you can call the notebook2's paragraph.
for more reference: Can I programmatically check the status of a paragraph in Zeppelin?


text:
Q: Kafka Stream - lookup by customer name and related info from the topics Kafka Stream lookup customer by value architecture
From the above problem statement  diagram ,the requirement is to fetch the attr1 and attr2 based on the incoming message containing customer: "XYZ".
customer
-------
customer_id,
customer_name

customer_config
---------------
customer_id,
attr1,
attr2,

cust_agg
--------
customer_id,
customer_name,
attr1,
attr2,

**since i use debezium and while cust rec delete,we dont get old value
 null means tombstone.
 so i am using custagggobj to get prev value,and after rekey,i will
 push to same topic cust-agg-topic ,is it a good way to code.i think that new key and value will be synced to all instances of the app. since any cust_name falls in specific partitions, consequent updates are reflected eventually.**

cust globalstore = fetch from customer topic
custcfg globalstore=fetch from customer-config topic9
custagg global store= fetch from cust-agg-topic topic  // fetch    from the topic (1)

// kstream tocustomeraggtopic =
transform(custgstore,custcfgstore,custaggstore);
{

custobj= ctx.get(custgstore) # customer_id is key
custcfgobj =ctx.get(custcfgstore) # customer_id is key
custagggobj = ctx.get(custagggstore) # customer_name is key

custaggkey = custagg(cust_name);  # use cust name as key
custaggvalue = custagg(cust,custcfg);
return KeyValue.pair(custaggkey, custaggvalue );
}

tocustomeraggtopic.to("cust-agg-topic")  // update to the same topic (1)


text:
Q: Question on MacPorts comment: "manually remove the catalog entry for this port when you uninstall it" I was recently installing Inkscape with MacPorts through a Mac OSX Leopard Terminal using
"sudo port install inkscape"
And during the search-and-download for dependencies, many of these type of comments were printed:
######################################################################
# As MacPorts does not currently have a post-deactivate hook,
# you will need to ensure that you manually remove the catalog
# entry for this port when you uninstall it.  To do so, run
# "xmlcatmgr remove nextCatalog /opt/local/share/xsl/docbook-xsl/catalog.xml".
######################################################################

Can anyone tell me what this message means?  I do not understand what "it" refers to in the phrase 'ensure that you manually remove the catalog entry for this port when you uninstall it'.
Does 'it' refer to a 'this port'?  How is a port uninstalled? Mostly: When will I have to manually remove the catalog entry using the provided command?
Also, what is a catalog entry?  is that what appears when I type "sudo port search inkscape" ?
I am kind of a MacPorts install n00b.
Thanks very much for your time.

A: This just means that if you ever remove the package that emitted this message, you have to execute the last line of the message manually.


text:
Q: Uncaught (in promise) Error: GraphQL error: unhashable type: 'dict' I am trying to have image upload feature but I am getting an error "Uncaught (in promise) Error: GraphQL error: unhashable type: 'dict'". I am using react-dropzone for uploading the image. It gives me File object which i then passed in mutation function with variables. Here is what, i have done
mutation.py
class UpdatePersonalProfile(graphene.Mutation):

    class Arguments:
        input = ProfileInput(description="These fields are required", required=True)

    success = graphene.Boolean()
    errors = graphene.List(graphene.String)
    profile = graphene.Field(ProfileNode)

    @staticmethod
    def mutate(self, info, **args):
        print ('info', args, info.context, info.context.FILES, info.context.FILES.get(args.get('input').get('avatar', None)))
        is_authenticated = info.context.user.is_authenticated
        profile = Profile.objects.get(user=CustomUser.objects.get(id=7))
        profile.company_name = args.get('input').get('company_name', None)
        profile.bio = args.get('input').get('bio', None)
        profile.website = args.get('input').get('website', None)
        profile.avatar = info.context.FILES.get(args.get('input').get('avatar', None))
        profile.job_title = args.get('input').get('job_title', None)
        profile.zip_code = args.get('input').get('zip_code', None)
        profile.save()
        return UpdatePersonalProfile(profile=profile, success=True, errors=None)

input.py
class Upload(graphene.types.Scalar):

    class Meta:
        description = '''Variables of this type must be set to null in
        mutations. They will be replaced with a filename from a following
        multipart part containing a binary file. See:
        https://github.com/jaydenseric/graphql-multipart-request-spec'''

    @staticmethod
    def serialize(value):
        return value

    @staticmethod
    def parse_literal(node):
        return node

    @staticmethod
    def parse_value(value):
        return value

class ProfileInput(graphene.InputObjectType):

    full_name = graphene.String(description='Full Name')
    user = graphene.String(description='User')
    bio = graphene.String(description='No more than 1000 characters')
    website = graphene.String()
    avatar = Upload(description='Avatar')
    job_title = graphene.String()
    company_name = graphene.String()
    zip_code = graphene.String()

Here is the data for avatar key where i have used files[0] that means whole File object.

How do i upload image when using django-graphene?

A: Here is good package I used and pretty satisfied: graphene-file-upload
It handles multipart data and replaces actual variables with passed files.


text:
Q: chess sliding pieces bitboards I understood non-sliding pieces quite easily but I've been having some trouble with the sliding pieces.
I currently have 64 bitboards (1 for each square, not saved in a array as well as 8 bitboards for masked rows, 8 bitboards for cleared rows, 8 bitboards for masked columns, and 8 bitboards for cleared columns, as well as, of course, a bitboard for each type of piece.
In generating legal moves for the bishop and rook I hear you are suppose to get the first occupied square on the column/row.
My questions are:

*

*how do you know where the rook is to and it together with the appropriate mask.

*how exactly do you get the first occupied square in the diagonal as well for the Bishop.

*if you know of any other common bitboards which will help me in my tasks at a latter point, please let me know of them.

Currently I have it going with no branches and would like to keep the amount of branches I use down but I feel some will be needed here and am curious about the most efficient way to go about solving this problem.

A: Wikipedia entries on Board representation and Bitboard provide good explanation on the topic.
Moreover, they contain a bunch of interesting links pointing to valuable references.
I particularly advise you to study Crafty's source code. It was written by a well known authority: Dr.Robert Hyatt.


text:
Q: how to group and show the counts of multiple fields in mongoose I have a collection in MongoDB that is generated via a data import of a CSV file. The data in the collection is for some basic reports and all the fields have been flattened and doesn't really look like a typical document.
Here is an example of 2 documents
{
"schoolCode": "0001",
"name": "Special Centre",
"ecsTaught": "N",
"elementaryTaught": "Y",
"juniorHighTaught": "N",
"seniorHighTaught": "N",
"authorityCode": "9000",
"offerHomeEducation": "N",
"offerHomeEducationBlended": "N",
"offerSchoolOnline": "N",
"offerSchoolOutreach": "N",
"extractDate": "2015-05-11"

}
{
"schoolCode": "0002",
"name": "High point Centre",
"ecsTaught": "y",
"elementaryTaught": "Y",
"juniorHighTaught": "N",
"seniorHighTaught": "Y",
"authorityCode": "9000",
"offerHomeEducation": "N",
"offerHomeEducationBlended": "N",
"offerSchoolOnline": "N",
"offerSchoolOutreach": "N",
"extractDate": "2015-05-11"

}
I would like to query using mongoose to get a count report as follows

*

*Ecs Taught : 20

*Elementatary Taught: 47

*JuniorHigh Taught: 55

*SeniorHigh Taught: 43

The count should take into account, any field that has "Y" and projected as above.
I am actually new to mongoose and have checked the docs but did not find much info on how to aggregate over multiple columns.

A: You will most likely be better off just retrieving the records (in chunks if the collection is large) and doing the aggregation yourself. MongoDB retrieves each document entirely anyway. Since you're using a considerable part of each document for your queries, it will be best to do the aggregation yourself.
That said, if you still want Mongoose to do it, use the aggregator function like this. The bad way would be to call this for each query you need, grouping by the fieldname and "Y/N" value - for each field you want to query.
A better way would be using Model.mapReduce to perform a reduce operation. This way you'll can do more kinds of queries on each document.


text:
Q: How run executable .jar file with Python & subprocess? I have been running the batch file before. ( with Python )
The batch file contents are like this
@echo off
"%JAVA_HOME%\bin\java" -Dfile.encoding=utf-8 -Djava.file.encoding=UTF-8 -jar -Xms1024m -Xmx1024m C:\val\val.jar --basedir C:\val --filetype shp --cidx 5 --layerdefpath C:\val\임상도layer.json --valoptpath C:\val\임상도option.json --objfilepath C:\val\50000.zip --crs EPSG:5186

pause>nul

Now I want to run the jar file directly, not the batch file.
But It is not work.
query = '"%JAVA_HOME/bin/java"' + ' -Dfile.encoding=utf-8 -Djava.file.encoding=UTF-8 -jar -Xms1024m -Xmx1024m C:/val/val.jar --basedir C:/val --filetype shp --cidx %s --layerdefpath %s --valoptpath %s --objfilepath %s --crs EPSG:5186 \npause>nul' % (cidx, self.dockwidget.path1.text(),self.dockwidget.path2.text(),self.dockwidget.path3.text())

process = subprocess.Popen(
    query,
    shell=True,
    stdout=subprocess.PIPE
)

The query of param is same with batch file contents.
I don't know what is problem.
Could you help me?

A: The most immediate problem seems to be a typo assuming your latter code block is an accurate copy/paste. Namely, %JAVA_HOME would need to be %JAVA_HOME% to be interpreted as variable by the shell called.
However, I'd make few more hopefully useful suggestions. The \npause>nul actually doesn't do anything (and even if it did, it would seem to make more sense to handle waiting for user input in the python script itself).
When you make subprocess.Popen call and perform output redirection into subprocess.PIPE, you likely want to also retrieve this output and follow that line with (out, err) = process.communicate().
The last but not least, instead of concatenating and formatting string and relying on the shell to parse it back into desired arguments, I would suggest looking into passing an arguments vector instead. I.e. define query as:
query = [os.path.join(os.environ["JAVA_HOME"], "bin/java"),
         "-Dfile.encoding=utf-8", "-Djava.file.encoding=UTF-8",
         "-jar", "-Xms1024m", "-Xmx1024m", "C:/val/val.jar",
         "--basedir", "C:/val", "--filetype", "shp", "--cidx", cidx,
         "--layerdefpath", self.dockwidget.path1.text(),
         "--valoptpath", self.dockwidget.path2.text(),
         "--objfilepath", self.dockwidget.path3.text(),
         "--crs", "EPSG:5186"]

and drop the shell=True keyword argument then.


text:
Q: How to find the accessible ip to see the play framework homepage on aws ec2? I have connected the ec2 with my local environment. Then the play app is installed there along with all the dependencies. Now while I run it, it is showing,
--- (Running the application from SBT, auto-reloading is enabled) ---

[info] play - Listening for HTTP on /0:0:0:0:0:0:0:0:9000

I can visit my public ip and there I can see the apache2 is running but while I visited public-ip:9000 it is showing nothing and page is not loaded.
Can anybody help me on, how to find the accessible ip to see the play framework homepage on aws ec2 ?

A: This sounds like you have not allowed necessary incoming rules in the Security Group for your EC2 instance. Please make sure that you have allowed incoming rule for port 9000 from 0.0.0.0/0 (anywhere).
If this is not the case, then provide more information like do you have any firewall (iptables) running on the instance? Do you actually have some process listening on port 9000 (netstat -anp | grep 9000) ?


text:
Q: Feed Dialog not working on some browsers Hi guys I have a weird problem with de feed dialog.
It works pefect on Firefox, but when I try to use it on IE or Chrome I got this error "An error occurred. Please try later"
I have tried to fix it but I can't. Can you help me please.
This is the code i'm using to call the dialog.

Post Feed

    </script>

A: A couple of things to try:
1: It could possibly be as simple as the rogue comma in your code here after actions:
actions: [{name: 'xx', link: 'xx'}],

Try removing that, however Chrome should better handle that, but that would have caused an issue with IE!
2: Use the Console to see if any errors are thrown.
3: Add oauth: true to your init statement like so:
FB.init({appId: "xxxx", status: true, cookie: true, oauth: true});

4: Remove the parameters in the call, and add them back in one by one after testing it works with each addition: start with:
var obj = {
              method: 'feed',
              link: 'http://apps.facebook.com/xxxx',
              picture: 'xxxx',
              name: 'xxxx',
              caption: 'xxxxx',
              description: 'xxxxx'
            };


text:
Q: How to write this snippet more clean In a turn-based game, I'd like to find the previous player.
To find the next player, I can just type:
int lastPlayer = match.currentPlayer - 1;

The problem is when the currentPlayer is player 1. Then lastPlayer becomes 0, which is wrong. It should be player6.
To fix this, I can do:
    int lastPlayer = match.currentPlayer - 1;

    if (lastPlayer == 0)
        lastPlayer = match.numberOfPlayers;

My question is how to write this in a cleaner way. I know game center, turn based code do something like:
    (currentIndex + 1) % match.participants.count];

How can I rewrite my code to do the same?
Thanks in advance

A: How about that?
int lastPlayer = match.currentPlayer > 1 ? match.currentPlayer - 1 : match.numberOfPlayers;

A: If you have a turn counter like this:
for(int i=0;i< maxTurns;i++){//do something}

and player1 plays the 1st turn, player2 the second and so on,
you can get the current players number exactly as its done in gamecenter.
Maybe you don't know the modulo "%" operator,
it returns the rest of a division, for example
3%2 = 1

your turncounter keeps counting up so the next player is
(turncounter + 1)%match.numberOfPlayer

in this case the modulo operator kind of "resets" your counter when it reaches the max player count (its round 6 and there are 5 players 6%5 = 1).
To sum it up, currentPlayer is turncounter%match.numberOfPlayer
nextPlayer is ++turncounter%match.numberOfPlayer


text:
Q: How to create a TS type which has enum value as key and corresponding React functional component as value Please see the code block below.
import Button from './Button'; // React component which has type React.FC<ButtonType>
import Select from './Select'; // React component which has type React.FC<SelectType>
import Checkbox from './Checkbox'; // React component which has type React.FC<CheckboxType>

enum ComponentType {
  button = 'bla_button',
  select = 'bla_select',
  checkbox = 'bla_checkbox',
}

type ComponentMap = {
  [key in ComponentType]: React.FC<any>;
};

const componentMap: ComponentMap = {
  [ComponentType.button]: Button,
  [ComponentType.select]: Select,
  [ComponentType.checkbox]: Checkbox,
};

I want to have a better type for ComponentMap instead of using React.FC<any> so it can infer when the key is 'bla_button', the value must be Button and so on.

A: You'll have to an interface/type which specifies the relational mapping from string key to function component value. You can use the typeof keyword to extract the type from the FC imports, and use indexed access types
type MapEnumToComponent = {
    'bla_button': typeof Button;
    'bla_select': typeof Select;
    'bla_checkbox': typeof Checkbox;
}

type ComponentMap = {
  [key in ComponentType]: MapEnumToComponent[key];
};

View this on TS Playground


text:
Q: C#: DateTime convert I am recieving a date in the format:
18/04/2011 4:57:20 PM

The DateTime.Parse() method does not access it.
Is there a way to get it to convert 18/04/2011 4:57:20 PM to return a Date object April 18, 2011?

A: This doesn't look like a standard format. The date is en-GB, the time en-US. Because of this, I would recommend you use DateTime.ParseExact and pass the format:
DateTime parsed = DateTime.ParseExact("18/04/2011 4:57:20 PM",
                                      "dd/MM/yyyy h:mm:ss tt",
                                      CultureInfo.InvariantCulture);

A: First of all, to change the format of a date, you need a DateTime value. You can not format a string date. Use DateTime.ParseExact to extract your date value from a formated date string:
DateTime dateValue =
   DateTime.ParseExact(stringDateValue, "dd/MM/yyyy h:mm:ss tt",
        CultureInfo.InvariantCulture);

Then you can use DateTime.ToString(format) to extract a formated string value:
resultStringDateValue = dateValue.ToString("MMM dd, yyyy");

A: try this:
DateTime dt = DateTime.ParseExact(dateString, "dd/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);

A: You can use ParseExact or better TryParseExact (that not generate exception when fail), with this two method you can pass the format provider description as parameter :
DateTime.ParseExact(strDate, "dd/MM/yyyy HH:mm:ss", null);

A: You need DateTime.ParseExact

A: You should use Convert.ToDateTime(String)
http://msdn.microsoft.com/es-es/library/xhz1w05e(v=VS.90).aspx
You'll have to see if Convert.ToDateTime accept the format you want to input it.

A: Have you tried this
DateTime.Now.ToString("MMM dd, yyyy")

A: your date format is mm/dd/yyyy there is no month of 18
try this
DateTime.Parse("04/18/2011 4:57:20PM").ToShortDateString();


text:
Q: How to combine cts:search searchable-expression and cts:not-query? I have been using cts:search with searchable-expression to extract specific elements from XML documents. For example:
Document:
<book>
  <recipe>
    <ingredients>cinnamon, peppermint</ingredients>
    <instruction/>
  </recipe>
  <recipe>
    <ingredients>sugar, peppermint</ingredients>
    <instruction/>
  </recipe>
  <recipe>
    <ingredients>coconut oil</ingredients>
    <instruction/>
  </recipe>
</book>

Query:
cts:search(//recipe, cts:parse("peppermint"))

Results:
<recipe>
  <ingredients>cinnamon, peppermint</ingredients>
  <instruction>
  </instruction>
</recipe>
<recipe>
  <ingredients>sugar, peppermint</ingredients>
  <instruction>
  </instruction>
</recipe>

However, this doesn't work with cts:not-query and no result is returned for the following search:
cts:search(//recipe, cts:parse("-cinnamon"))

Looking into the query plan, my understanding is that the cts:not-query is applied at the fragment (document) level prior to filtering so the above document is eliminated outright. If that is correct, this behavior makes sense.
Nevertheless I am still wondering if this can be accomplished somehow. Thanks!

A: Searchable expressions that don't match root nodes are discouraged.
One problem with more complex searchable expressions is that a small change can make the search require filtering.
That's one reason why the SJS version of search - cts.search() - doesn't support searchable expressions.
The recommended approach is

*

*To model the documents with a separate document for each object / row (recipe in this case) -- which eliminates the potential for false positives in unfiltered search that match parts of the criteria in two different objects.

*To use the cts:query argument for matching and to use XPaths on the returned documents for extracting nodes.

*To assemble objects into lists as needed based on queries.

Hoping that helps,


text:
Q: NULL checkbox in SSRS report In SSRS report if I mention Nullable tag in ReportParameter then it automatically creates a checkbox with text NULL. So is there a way to make the checkbox by default checked?

A: Try setting the default to =Nothing, i.e. NULL.
Or even just specify it from the dropdown:

A: Just set the parameter default value to 'TRUE'

This will result in


text:
Q: magnitude of unknown force on wall bracket question I'm really stuck with part b of this question, even where to start. I think I keep over complicating it. If anyone could help that'd be amazing!

A: Hint:  resolve $F_2$ and $F_3$ into $x$ and $y$ components.  Subtract them from the given resultant vector.  The result is $F_1$ in components.  Now change that to magnitude and compute $\theta$.


text:
Q: Permutation polynomials mod $p$ of the form $(x+1)^n-x^n$ Among some permutation polynomials I've been studying, $f(x)=(x+1)^n-x^n$ is one of the polynomials that I cannot grasp.

Question : For a given odd prime $p$, how can we find every positive integer $n$ such that $f(x)=(x+1)^n-x^n$ is a permutation polynomial mod $p$ ?

The answer seems $n=(p-1)m+2\ \ (m=0,1,2,\cdots)$, but I'm facing difficulty in proving that. This question has been asked previously on math.SE without receiving any answers.
The followings are what I've got.

*

*$f(0)\equiv 1.$

*$f(p-1)\equiv -(-1)^n\Rightarrow \text{$n$ has to be even}\Rightarrow f(p-1)\equiv p-1$.

*For $n=(p-1)m+r$, $f(x)\equiv (x+1)^r-x^r$ because $a^{p-1}\equiv 1$ for $a$ which is coprime to $p$.

*$f\left(\frac{p-1}{2}\right)\equiv 0$.

*$f\left(\frac{p-1}{2}+a\right)+f\left(\frac{p-1}{2}-a\right)\equiv 0$ for any $a$.
I would like to know any relevant references as well.

A: The expected answer is correct, it is a theorem by Norman Johnson, see here. Note that $(X+1)^n-X^n$ is a permutation polynomial if and only if $(X+a)^n-X^n$ is a permutation polynomial for each fixed nonzero $a$. This latter condition is a special case of planarity: A function $f:K\to K$ on a field $K$ is called planar, if $x\mapsto f(x+a)-f(x)$ is bijective for every nonzero $a$.
So you ask for planar monomials on $\mathbb F_p$ for odd primes $p$. Actually, it was later proved that any planar function on $\mathbb F_p$ is given by a quadratic polynomial, see this MO page for more information and references.


text:
Q: Input fields appended with jQuery doesnt submit on POST php I have done it like this:
https://stackoverflow.com/a/21724399/267304
But when the form submits the array only consist of first input array value.
Here's my HTML:
<form method="post" accept-charset="utf-8">

            Post nr
            Pris

            <input type="text" name="newd_zipcode[]" value="" placeholder="Fx: 999-2000 eller 2200">
            <input type="text" name="newd_price[]" value="" placeholder="Pris">

+Add new

And the jQuery:
    $('.newZipDelivery').click(function(){
        if($('.newZipDeliveryBox').hasClass('hide'))
        {
            $('.newZipDeliveryBox').removeClass('hide');
        }else{
            var $clone = $('.newZipDeliveryBox').clone();
            $clone.removeClass('newZipDeliveryBox');

            $('#deliveryZipTable > tbody > tr:last').after($clone);
        }
    });

What the script does is that first time it shows the  (remove class 'hide') and if you press add new again, it clones and appends.
It seems like the cloned tr with the inputs inside that gets appended, doesnt come on the form submit. Any solution?
if i in my html have multiple:
<input type="text" name="newd_zipcode[]" value="" placeholder="Fx: 999-2000 eller 2200">
<input type="text" name="newd_zipcode[]" value="" placeholder="Fx: 999-2000 eller 2200">
<input type="text" name="newd_zipcode[]" value="" placeholder="Fx: 999-2000 eller 2200">

all these submits fine.
So its only when cloning and appending the input fields, the data doesnt send with POST on submission. Any help?


text:
Q: Polar decompostion for the operator algebras I find that most of books discussing the polar decompostion at the W*-algebras, but not C*-algebras. I guess the rough reason is that the element of W*algebras has the well supported set, but I want to know more details.
1) What is the basic difference between the C*-algebras and W*-algebras such that the W*-algebras has the well supported set.
2) If we insist to do the polar decompostion for a noninvertible element in the C*-algebras, what will happen?

A: I'm not sure what you mean by the "well supported set", but in any case; C*-algebras are not closed under the polar decomposition of non-invertible elements. For this you have to go to the enveloping von Neumann (W*-) algebra.  This is essentially because von Neumann algebras are closed under the Borel functional calculus, whereas C*-algebras are only closed under the continuous functional calculus.  On the other hand, a (unital) C*-algebra is closed under the polar decomposition of its invertible elements.  This is easy to see using the continuous functional calculus.
For example, consider the identity map $f : [-1,1]\to [-1,1]$ as a member of the C*-algebra $C[-1,1]$.  It's easy to see that if $f = |f| v$ is the polar decomposition of $f$ (i.e. $v$ is a partial isometry), then $v$ must take the values $-1$ on $[-1,0)$ and $+1$ on $(0,1]$.  You can find such a $v$ in $L^\infty[-1,1]$ but not $C[-1,1]$.

A: This seems to be relevant for 2):
http://www.theta.ro/jot/archive/1987-017-002/1987-017-002-014.pdf
Since, this answer is two short to be submitted, I would just add redundantly as and answer to 1) that a C*-algebra doesn't have sufficiently many projections and that the proof that a von Neumann algebra does have enough is indeed the consequence of the double commutant theorem.
cf. also the algebraic proof of the polar decomposition Detail in the algebraic proof of the polar decomposition


text:
Q: Generics  super> wildcard I was wondering why the following bit of code does not work:
Collection <? super String> col = new ArrayList<String>();
col.add(new Object());// does not compile
col.add("yo!");// compiles indeed;

If the type is <? super String> it can contain anything which is super of String (String included) not?

A: With a Collection <? super String>, we don't know what kind of objects it contains exactly, but we know that it must be a collection of either String or some superclass of String, i.e. it is safe to put a String into it but not necessarily an Object.  Conversely for methods that take things out of the collection (e.g. when iterating) we can't be sure we'll get strings back.
On the other hand with Collection<? extends Foo> we know it's a collection of something that is either Foo or some subclass of Foo, so we can safely take something from the collection and know it will be assignable to Foo, but we can't put anything in because we have no way of knowing what types would be safe.

A: Collection<? super String>, counter to your intuition, does not mean "a collection which contains objects of type String or its supertype". It means "col will be a collection holding some definite type, which itself is String or its supertype" (such as Object, Serializable, or CharSequence).
The best way to think about Collection<? super String> is that it is not a type, like you are used to in Java, but a pattern against which specific types are matched.
Now, the only thing you can safely add to any collection which matches the above pattern is a String or its subclass (if there were any). Quite the opposite of what you would have expected, isn't it? That's Generics for you.


text:
Q: not insert data to rethinkdb i am trying to create NSQ topic and insert data at rethinkdb but i am unable to insert the data into rethinkdb. Can anyone help me.
**var nsq = require('nsqjs');
var r = require('rethinkdb');
var nsqdd = (process.env.NSQD_RETH || "localhost:4161").split(",");
var connection = null;
r.connect( {host: 'localhost', port: 28015, db:'test', authKey:''}, function(err, conn) {
    if (err) throw err;
    connection = conn;
})
var eventreader;
eventreader = new nsq.Reader('ev_topic', 'ev_channel', {
    lookupdHTTPAddresses: nsqdd
});
eventreader.connect();
eventreader.on('message', function (msg) {
    r.table('rethinkdb_test').insert(msg.json()).run(conn);
    console.log('Received message [%s]: %s', msg.id, msg.body.toString());
    msg.finish();
});**

A: It seems like your second query (the insert) does not have access to the conn variable. For this to work, you'd need to put the event reader code inside the callback for your connect function.
var nsq = require('nsqjs');
var r = require('rethinkdb');
var nsqdd = (process.env.NSQD_RETH || "localhost:4161").split(",");
var connection = null;
r.connect( {host: 'localhost', port: 28015, db:'test', authKey:''}, function(err, conn) {
    if (err) throw err;
    connection = conn;
    // Event Reader functionality inside connect callback
    var eventreader;
    eventreader = new nsq.Reader('ev_topic', 'ev_channel', {
        lookupdHTTPAddresses: nsqdd
    });
    eventreader.connect();
    eventreader.on('message', function (msg) {
        // Now we have access to the connection
        r.table('rethinkdb_test').insert(msg.json()).run(conn);
        console.log('Received message [%s]: %s', msg.id, msg.body.toString());
        msg.finish();
    });
});


text:
Q: How to maintain the Button position when changing the text in code? I have a button in my layout with ID btnsignIn_Master, and text "Sign In/Sign Up". On a click event I change the text of button, then the alignment of the button changes. How to maintain the alignment even after the text changed?
Below is my layout:
<RelativeLayout
android:id="@+id/LoginLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/relLayoutMenu"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp">

<TextView
    android:id="@+id/txtLoginName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
     android:gravity="left|center_horizontal"
    android:singleLine="true"
    android:text="Welcome"
    android:textColor="#E68A00"
    android:textSize="12sp"
    android:textStyle="bold"
    android:layout_marginLeft="1dp">
</TextView>

<Button
    android:id="@+id/btnsignIn_Master"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="30dp"
    android:layout_toRightOf="@+id/txtLoginName"
    android:background="@null"
    android:gravity="right|center_horizontal"
    android:onClick="btnSignIn_onclick"
    android:text="Sign In/Sign Up"
    android:textColor="#8b8989"
    android:textSize="12dp" >
</Button>

<ImageButton
    android:id="@+id/iv_Arrow"
    android:layout_width="30dp"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_gravity="right|center_horizontal"
    android:layout_toRightOf="@+id/btnsignIn_Master"
    android:background="@null"
    android:onClick="btnSignIn_onclick"
    android:layout_marginRight="10dp"
    android:src="@drawable/arrow1" />

Here is Java code:
Button ButtonSignInM= (Button) findViewById(R.id.btnsignIn_Master);
ButtonSignInM.setText("Your Account");

Am I doing anything wrong?

A: You probably have set the width property of the button to wrap_content. In that case, the alignment of the button may change. Use a fixed width for the button, to prevent it.

A: It seems that you have used this android:layout_width="wrap_content" in your xml .Remove wrap content and specify some values in it eg:android:layout_width="20dp"


text:
Q: Duplicate each element sublist I have a list of the form {{0,0},{0,1},{1,0},{1,1}} and I want to duplicate each of its elements, i.e. {{0,0,0,0},{0,0,1,1},{1,1,0,0},{1,1,1,1}}.
I saw some posts about similar issues, but none of them work for me, since they duplicate each "full" element of the list (e.g. {0,1} element becomes {0,1,0,1} instead of {0,0,1,1}).
For the record, I generate these lists as Tuples[Range[cmax] - 1, n], where cmax is the local dimension (two, the 0 and the 1, for the example I gave) and n is the number of elements (2 for the example).
This is a related question I've found:
How to repeat each element in a list and the whole list as well?

A: Here are a few ways:
list = {{0, 0}, {0, 1}, {1, 0}, {1, 1}};

Replace[list, x_ :> Splice[{x, x}], {2}]
Replace[list, x_ :> Sequence[x, x], {2}]
MapThread[Splice@*List, {list, list}, 2]
MapThread[Sequence, {list, list}, 2]
Join @@@ MapThread[List, {list, list}, 2]
MapThread[Riffle, {list, list}]
Riffle[#, #] & /@ list
(* {{0, 0, 0, 0}, {0, 0, 1, 1}, {1, 1, 0, 0}, {1, 1, 1, 1}} *)

A: list = {{0, 0}, {0, 1}, {1, 0}, {1, 1}};

k = 2;
Flatten[ConstantArray[#, k], {{2}, {3, 1}}] & @ list

{{0, 0, 0, 0}, {0, 0, 1, 1}, {1, 1, 0, 0}, {1, 1, 1, 1}}

k = 3;
Flatten[ConstantArray[#, k], {{2}, {3, 1}}] & @ list

{{0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 1}, {1, 1, 1, 0, 0, 0}, {1, 1, 1, 1, 1, 1}}

A: Another way using the Dot product:
list.{{1,1,0,0},{0,0,1,1}}

(*  {{0, 0, 0, 0}, {0, 0, 1, 1}, {1, 1, 0, 0}, {1, 1, 1, 1}} *)

list3.{{1,1,0,0},{0,0,1,1}}

(*  {{a, a, b, b}, {c, c, d, d}, {e, e, f, f}, {g, g, h, h}}  *)

In addition, using Inner:
Inner[ConstantArray, list3, {2,2},Join]

(*  {{a, a, b, b}, {c, c, d, d}, {e, e, f, f}, {g, g, h, h}}  *)

Inner[ConstantArray, list3, {3,3},Join]

(*  {{a, a, a, b, b, b}, {c, c, c, d, d, d}, {e, e, e, f, f, f}, {g, g, g, h, h, h}}  *)

Inner[ConstantArray, list, {2,2},Join]

(* {{0, 0, 0, 0}, {0, 0, 1, 1}, {1, 1, 0, 0}, {1, 1, 1, 1}}  *)

Or:
Inner[Times, list3, {1,1}, {#1,#1,#2,#2}&]

(*  {{a, a, b, b}, {c, c, d, d}, {e, e, f, f}, {g, g, h, h}}  *)

Inner[Times, list, {1,1}, {#1,#1,#2,#2}&]

(*  {{0, 0, 0, 0}, {0, 0, 1, 1}, {1, 1, 0, 0}, {1, 1, 1, 1}}  *)

where
list = {{0, 0}, {0, 1}, {1, 0}, {1, 1}};

list3={{a,b},{c,d},{e,f},{g,h}}

Edit
Use Apply (at level 1):
{#1,#1,#2,#2}&@@@list3

(*  {{a, a, b, b}, {c, c, d, d}, {e, e, f, f}, {g, g, h, h}}  *)

A: Function[x,Delete[#, 0] & /@ ({#, #} & /@ x)] /@ YourList

Let's have try :
In[1] Function[x,Delete[#, 0] & /@ ({#, #} & /@ x)] /@ {{0, 0}, {0, 1}, {1, 0}, {1, 1}}

Out[1] {{0, 0, 0, 0}, {0, 0, 1, 1}, {1, 1, 0, 0}, {1, 1, 1, 1}}

Done!


text:
Q: How can I change specific elements in all samples of a .csv file? As input, I have a .csv file like:
user, withdraw, date
50D8BF0DA22D6C914777D8F59DAAB4D8, -125, 01-02-2015
674BCF0CD236621E5680073334A73C32, -5, 01-02-2015
E17E1691D35FB2FB675E3B787B8BEDF1, -845, 01-02-2015
50D8BF0DA22D6C914777D8F59DAAB4D8, -250, 01-02-2015
674BCF0CD236621E5680073334A73C32, -98, 01-02-2015
50D8BF0DA22D6C914777D8F59DAAB4D8, -17, 01-02-2015

I would like to identify all similar 'hash' codes and change them for labels such as 'user1', 'user2', 'user3'...and so on.
I have been trying to do that without success with pandas. Any idea what I could do?

A: first read CSV into Pandas DF:
df = pd.read_csv('/path/to/file.csv', skipinitialspace=True)

yields:
In [84]: df
Out[84]:
                               user  withdraw        date
0  50D8BF0DA22D6C914777D8F59DAAB4D8      -125  01-02-2015
1  674BCF0CD236621E5680073334A73C32        -5  01-02-2015
2  E17E1691D35FB2FB675E3B787B8BEDF1      -845  01-02-2015
3  50D8BF0DA22D6C914777D8F59DAAB4D8      -250  01-02-2015
4  674BCF0CD236621E5680073334A73C32       -98  01-02-2015
5  50D8BF0DA22D6C914777D8F59DAAB4D8       -17  01-02-2015

now we can factorize user column:
In [85]: df['user'] = 'user' + pd.Series((pd.factorize(df.user)[0]+1).astype(str))

In [86]: df
Out[86]:
    user  withdraw        date
0  user1      -125  01-02-2015
1  user2        -5  01-02-2015
2  user3      -845  01-02-2015
3  user1      -250  01-02-2015
4  user2       -98  01-02-2015
5  user1       -17  01-02-2015

and write DF back to csv:
df.to_csv('/path/to/file_new.csv', index=False)

A: You need to first build a dictionary of users as follows:
import csv

hashes = {}
user_number = 1
entries = []

with open('input.csv', 'rb') as f_input:
    csv_input = csv.reader(f_input, skipinitialspace=True)
    header = next(csv_input)

    for row in csv_input:
        user = row[0]

        if user not in hashes:
            hashes[user] = "user{}".format(user_number)
            user_number += 1

        row[0] = hashes[user]
        entries.append(row)

with open('output.csv', 'wb') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(header)
    csv_output.writerows(entries)

Giving you an output.csv containing:
user,withdraw,date
user1,-125,01-02-2015
user2,-5,01-02-2015
user3,-845,01-02-2015
user1,-250,01-02-2015
user2,-98,01-02-2015
user1,-17,01-02-2015


text:
Q: Can a Microsoft SQL table have more than one Primary Key? I was always curious but can't find a concise answer. Any help?

A: It cannot have more than one primary key.  It can, however, have more than one column in the primary key.  It can also have more than one unique index.  Generally, the unique index is the primary key, but it is possible to have multiple unique indices on a single table.  Off the top of my head I cannot think of an example, but when I do I will add it.
EDIT: Maybe this: In the US, the Department of Motor Vehicles might have a person table with 2 unique columns -- Social Security Number and Driver's License Number.  Both should be unique.

A: As noted by MJB, a table can have at most one Primary Key, and should always have one (never zero).  A table may, however, have multiple candidate keys - one of which is designated as the primary key.  In normalization theory, the primary key is not critical; the candidate keys (the primary key is one of the candidate keys) are crucial in the theorems related to normalization.
An example of a table with three possible unique keys is, appropriately enough, the Table of Elements - where the Atomic Number, Symbol or Element Name could all be used as the primary key.  Indeed, depending on whether you're doing chemistry or physics, the atomic number or symbol might be the most appropriate primary key, and the other would be an alternative key (and the element name would probably always be an alternative key rather than the primary key):
CREATE TABLE elements
(
    atomic_number   INTEGER NOT NULL UNIQUE CONSTRAINT c1_elements
                    CHECK (atomic_number > 0 AND atomic_number < 120),
    symbol          CHAR(3) NOT NULL UNIQUE CONSTRAINT c2_elements,
    name            CHAR(20) NOT NULL UNIQUE CONSTRAINT c3_elements,
    atomic_weight   DECIMAL(8,4) NOT NULL,
    stable          CHAR(1) DEFAULT 'Y' NOT NULL
                    CHECK (stable IN ('Y', 'N'))
);

(The notation is for Informix Dynamic Server; the differences between that and Microsoft SQL Server or any other SQL DBMS are pretty trivial.  You can see that I've not designated any of the possible keys as 'the primary key'.  If I did, I'd probably nominate Atomic_Number as the primary key.)

Thanks for the pointers, Thomas.  I found this in the ISO/IEC 9075-2:2003 (SQL/Foundation):
§11.7 <unique constraint definition>
Function

Specify a uniqueness constraint for a table.

Format
<unique constraint definition> ::=
      <unique specification> <left paren> <unique column list> <right paren>
    | UNIQUE ( VALUE )
<unique specification> ::=
      UNIQUE
    | PRIMARY KEY
<unique column list> ::= <column name list>

Syntax Rules

*

*Each column identified by a <column name> in the <unique column list> is an operand of a grouping
operation. The Syntax Rules of Subclause 9.10, "Grouping operations", apply.

*Let T be the table identified by the containing <table definition> or <alter table statement>. Let TN be the <table name> of T.

*If <unique column list> UCL is specified, then
a. Each <column name> in the <unique column list> shall identify a column of T, and the same column
shall not be identified more than once.
b. The set of columns in the <unique column list> shall be distinct from the unique columns of any other
unique constraint descriptor that is included in the base table descriptor of T.
c. Case:
   i. If the <unique specification> specifies PRIMARY KEY, then let SC be the <search condition>:
        UNIQUE ( SELECT UCL FROM TN )
        AND
        ( UCL ) IS NOT NULL

ii. Otherwise, let SC be the <search condition>:
        UNIQUE ( SELECT UCL FROM TN )

*If UNIQUE (VALUE) is specified, then let SC be the <search condition>:
    UNIQUE ( SELECT TN.* FROM TN )

*If the <unique specification> specifies PRIMARY KEY, then for each <column name> in the explicit or
implicit <unique column list> for which NOT NULL is not specified, NOT NULL is implicit in the <column
definition>.

*A <table definition> shall specify at most one implicit or explicit <unique constraint definition> that
specifies PRIMARY KEY.

*If a <unique constraint definition> that specifies PRIMARY KEY is contained in an <add table constraint
definition>, then the table identified by the <table name> immediately contained in the containing <alter
table statement> shall not have a unique constraint that was defined by a <unique constraint definition>
that specified PRIMARY KEY.

Access Rules
None.
General Rules

*

*A <unique constraint definition> defines a unique constraint.
NOTE 254 — Subclause 10.8, "<constraint name definition> and <constraint characteristics>", specifies when a constraint is
effectively checked.

*The unique constraint is not satisfied if and only if
  EXISTS ( SELECT * FROM TN WHERE NOT ( SC ) )

is True.
Conformance Rules

*

*Without Feature S291, "Unique constraint on entire row", conforming SQL language shall not contain
UNIQUE(VALUE).

*Without Feature T591, "UNIQUE constraints of possibly null columns", in conforming SQL language, if
UNIQUE is specified, then the <column definition> for each column whose <column name> is contained
in the <unique column list> shall contain NOT NULL.

NOTE 255 — The Conformance Rules of Subclause 9.10, "Grouping operations", also apply.

Welcome to the wonderful world of the SQL standard!  It seems that feature T591 allows for possibly null values in the columns of a UNIQUE constraint (but not in the columns of a PRIMARY KEY).  The net result is that you have to understand how the following query works when there are NULLs in any of the columns in the UCL (unique column list):
      EXISTS ( SELECT * FROM TN WHERE NOT (
               UNIQUE ( SELECT UCL FROM TN ) ) )

And I know I am not sure how the UNIQUE operation works in those circumstances.

§8.10 <unique predicate>
Function
Specify a test for the absence of duplicate rows.
Format
<unique predicate> ::= UNIQUE <table subquery>

Syntax Rules

*

*Each column of user-defined type in the result of the <table subquery> shall have a comparison type.

*Each column of the <table subquery> is an operand of a grouping operation. The Syntax Rules of
Subclause 9.10, "Grouping operations", apply.

Access Rules
None.
General Rules

*

*Let T be the result of the .

*If there are no two rows in T such that the value of each column in one row is non-null and is not distinct
from the value of the corresponding column in the other row, then the result of the <unique predicate> is
True; otherwise, the result of the  is False.

Conformance Rules
1) Without Feature F291, "UNIQUE predicate", conforming SQL language shall not contain a <unique
predicate>.
NOTE 193 — The Conformance Rules of Subclause 9.10, "Grouping operations", also apply.

A: As far as I know, only one. However you can have more than one column (usually up to 8 or 20, depending on the RDBMS) combined with others as a composite key to uniquely identify the row. The lone primary key, single-column or composite, can also be used for joining to a foreign key in another table (one-to-many, many-to-one or many-to-many relationships).

A: No, a table can't have more than one PK.
It can however have a composite key (one PK that contains more than one column in its definition). Also, you can have multiple unique constraints which also can span multiple columns.


text:
Q: How to return number of digits match between 2 strings I have 2 strings of same length. I need to know the number of digits the differ by.
string1: SH32OLP9843G, string2: SH12OLP9843G, Result: should be 1
string1: SH32OLP9843G, string2: SH12OLP0843G, Result: should be 2
string1: SH32OLP9843G, string2: SH12OLP08431, Result: should be 3
string1: SH32OLP9843G, string2: SH32OLP9843G, Result: should be 0

Im using this on SQL query like:
select * from sometable where fn_somefunction('string1',somefield) = 3
select * from sometable where someRegex between string1 and somefield = 1

A: Try following :
            string[,] inputs = {{"SH32OLP9843G", "SH12OLP9843G"},
                    {"SH32OLP9843G", "SH12OLP0843G"},
                    {"SH32OLP9843G", "SH12OLP08431"},
                    {"SH32OLP9843G", "SH32OLP9843G"}};

            for(int i = 0; i < inputs.GetLongLength(0); i ++)
            {
                char[] input1 = inputs[i, 0].ToCharArray();
                char[] input2 = inputs[i, 1].ToCharArray();

                int diff = input1.Select((x, index) => x == input2[index] ? 0 : 1).Sum();
            }


text:
Q: Google Cloud Endpoint work in Google APIs Explorer but not on Android (Bad Request) I can't understand why my endpoint works perfectly fine in Google APIs Explorer and not on Android.
https://developers.google.com/apis-explorer/?base=https://prncts.appspot.com/_ah/api#p/pronocities/v1.0.1/pronocities.content.get?id=aghzfnBybmN0c3IJCxIBZBj5zAMM&_h=1&
In fact it almost works as I can see that the call is made to my GAE endpoint server side and that the user perfectly authentified via OAuth.
There seems to be something wrong in the way the data is sent back to the phone.
Here are the logs I get on the phone :
07-28 15:12:53.305: W/System.err(3034): com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
07-28 15:12:53.305: W/System.err(3034): {
07-28 15:12:53.305: W/System.err(3034):   "code": 400,
07-28 15:12:53.305: W/System.err(3034):   "errors": [
07-28 15:12:53.305: W/System.err(3034):     {
07-28 15:12:53.305: W/System.err(3034):       "domain": "global",
07-28 15:12:53.305: W/System.err(3034):       "message": "java.lang.IllegalArgumentException: name cannot be null or empty",
07-28 15:12:53.305: W/System.err(3034):       "reason": "badRequest"
07-28 15:12:53.305: W/System.err(3034):     }
07-28 15:12:53.305: W/System.err(3034):   ],
07-28 15:12:53.305: W/System.err(3034):   "message": "java.lang.IllegalArgumentException: name cannot be null or empty"
07-28 15:12:53.305: W/System.err(3034): }
07-28 15:12:53.305: W/System.err(3034):     at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:111)

The object sent back is a really simple POJO as you can see in Google APIs Explorer.
EDIT1:
Android side code mostly taken from the TicTacToe example :
settings = getSharedPreferences("PronoCities", 0);
credential = GoogleAccountCredential.usingAudience(
        this, "server:client_id:<myid>.apps.googleusercontent.com");
setAccountName(settings.getString(PREF_ACCOUNT_NAME, null));

Pronocities.Builder builder = new Pronocities.Builder(
        AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential);
service = builder.build();

Any help will be greatly appreciated.
François
Using google-api-client-1.15.0-rc librairies and running on a Samsung Galaxy S3 / Android 4.1.2.

A: It seems likely that the error is originating from Datastore, not Endpoints. Please double check that the URLs in both the Explorer and Android requests are identical, and also check any Datastore operations you're making in your test case. In particular, check to make sure if you create Datastore Key objects that they have names.


text:
Q: R performance on Ryzen+Ubuntu: openBLAS/MKL, Rcpp and other improvements? I'm trying to push the maximum from a Ryzen 3 3950x 16-core machine on Ubuntu 20.04, Microsoft R 3.5.2, with Intel MKL, and the RCpp code is compiled with Sys.setenv(MKL_DEBUG_CPU_TYPE=5) header.
The following are the main operations, that I'd like to optimize for:

*

*Fast multivariate random normal (for which I use the Armadillo version):

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

using namespace Rcpp;

// [[Rcpp::export]]
arma::mat mvrnormArma(int n, arma::vec mu, arma::mat sigma) {
  int ncols = sigma.n_cols;
  arma::mat Y = arma::randn(n, ncols);
  return arma::repmat(mu, 1, n).t() + Y * arma::chol(sigma);
}

*Fast SVD (I found that the base::svd performs better than any Rcpp realization I've found so far, including arma::svd("dc"), probably due to different U,S,V dimensions).

*Fast matrix multiplications for various results (found code written in C, rewrote all of it in base R and am finding vast improvements due to multicore vs previous 1-core performance. Can base R matrix operations be further improved?)

I've tried various setups with R4.0.2 and openBLAS (through the Ropenblas package), played with various Intel MKL releases, researched about AMD's BLIS and libflame (which I don't know how to even test with R).
Overall, this setup is able to outperform a laptop with i7-8750h and Microsoft R 3.5.1 (With working MKL) by around 2x, while based on 6 vs 16 cores (and faster RAM), I was expecting at least 3-3.5x improvement (based, e.g., by cinebench and similar performance benchmarks).
How can this setup be further improved?
My main issues/questions:
First, I've noticed that the current setup, when ran with 1 worker, is using around 1000-1200% cpu when looking at top call. Through experimentation, I've found that spawning two parallel workers uses most of the cpu, around 85-95%, and delivers the best performance. For example, 3 workers uses whole 100%, but bottlenecks somewhere, drastically reducing the performance for some reason.
I'm guessing that this is a limitation either coming from R/MKL, or something when compiling Rcpp code, since 10-12 cores seems oddly specific. Can this be improved by some hints when compiling Rcpp code?
Secondly, I'm sure I'm not using the optimal BLAS/LAPACK/etc drivers for the job. My guess is that properly compiled R4.0.2 should be significantly faster than Microsoft R3.5.2, but I have absolutely no idea what am I missing, whether the AVX/AVX2 are properly called/used, and what else should I try with the machine?
Lastly, I have seen zero guides for calling/working with AMD BLIS/libflame for R. If this is trivial, would appreciate any hints/help of what to look into.

A: Until any other (hopefully much better) answers pops up, will post here my latest findings by guesswork. Hopefully, someone with a similar machine will find this useful. Will try expanding the answer if any additional improvements comes up.

*

*Guide for clean R compiling. Seems outdated, but hopefully nothing much missing:
Speed up RcppArmadillo: How to link to OpenBlas in an R package
OpenBLAS and IntelMKL examples + Rstudio

*OpenBLAS works terrible on my Ryzen + Ubuntu configuration; with 3.10 BLAS, compiled with zen2 hints, uses all the CPU cores, but terribly. top reports 3200% usage for R instance, but total CPU utilisation doesn't rise more than 20-30%. Hence, the performance is at least 3x slower than with Intel MKL.

*IntelMKL. Versions till 2019 work with the MKL_DEBUG_CPU_TYPE workaround. Can confirm that intel-mkl-64bit-2019.5-075 works.
For later versions since 2020.0-088 a different
workaround is
needed. With my benchmarks the performance did not see any
improvement, however, this may change with future MKL releases.

*The 10-12 hardcoded cap per instance appears to be controlled by several environmental variables. I found the following list as per this old guide. Likely that these may change with later versions, but seems to work with 2019.5-075:
export MKL_NUM_THREADS=2
export OMP_NESTED="TRUE"
export MKL_DOMAIN_NUM_THREADS="MKL_BLAS=1"
export OMP_NUM_THREADS=1
export MKL_DYNAMIC="TRUE"
export OMP_DYNAMIC="FALSE"

Playing around with various configurations I was able to find that reducing the number of threads and spawning more workers, for my specific benchmark that I've tested on, increased the performance drastically (around 3-4 fold). Even though the claimed CPU usage were similar to multicore variants of the configuration, 2 workers using 16 threads each (totaling in ~70% cpu utilisation) are much slower than 16 workers using 2 threads each (also, similar cpu utilisation). The results may vary with different tasks, so these seem to be the go-to parameters to play with for every longer task.

*AMD BLIS. Testing this as an alternative to MKL BLAS, currently only experimenting, but the performance seems to be on par with the Intel MKL with all the fixes. Checked whether BLIS was actually used through perf, for my benchmarks the calls were made bli_dgemmsup_rd_haswell_asm_6x8m, bli_daxpyv_zen_int10 and others. Not sure yet whether the settings for compiling BLIS were optimal. The takeaway here could be that both the MKL and BLIS are actually pushing max from the CPU, given my specific benchmarks... or at least that both libraries are similarly optimized.

Important downside of sticking to AMD BLIS: noticed after months of usage, but there seems to be some unresolved issues with BLIS or LAPACK packed into AMD libraries that I have no idea about. I've noticed random matrix multiplication issues that are not replicable (essentially, hitting into this problem) and are solved by switching back to MKL libs. I can't say whether there's a problem with my way of building R or the actual libs, so just a warning.


text:
Q: Window HTTP IO Completion port I was going through the IO Completion port documentation of Windows programming with relation to the Windows HTTP Server API.
So in the HTTP Server API, we have a queue which is an abstraction over the responses/requests. We have the handle to the queue to get the relevant information.
If i am to associate a IO Completion port with this, does that mean that i have use the queue as the handle? Will this not reduce the granularity? Can't i associate a IO Completion port with each request rather than with the complete queue.
Detailed Query:
We register for certain URL using a request queue in windows http server api. So there maybe lots of requests on a queue. How can i associate a IO Completion port with the each request/response rather than with the Queue itself.
IO Completition:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa363862(v=vs.85).aspx
Queue Documentation:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa364483(v=vs.85).aspx
Receive a Request:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa364495(v=vs.85).aspx

A: Figured it out.
The IO port is associated with the queue handle. The underlying request and response are not associated with the IO port.
Overlapped structure is used for passing relevant information about response and request.


text:
Q: Buttons Stop working when I add TableView Functionality in the initialize() method My buttons were working well before I added the table (TableView) functionality to my code, but now an error occurs once I click on the same buttons. The error disappears and the buttons works if I comment out this lines of code in RoomsController:
intRoomIDColVR.setCellValueFactory(new PropertyValueFactory<>("roomID"));
vachRoomTypeIDColVR.setCellValueFactory(new PropertyValueFactory<>("roomTypeID"));
roomTableViewVR.setItems(olRoomData);

The FXML file:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.codetech.hotelmis.controller.RoomsController">
    <children>
      <BorderPane prefHeight="338.0" prefWidth="600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">

          <Accordion BorderPane.alignment="CENTER">
            <panes>
              <TitledPane fx:id="accVacant" animated="false" text="Vacant Rooms">
                <content>
                  <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0">
                    <children>
                              <BorderPane prefHeight="324.0" prefWidth="598.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">

                            <TableView fx:id="roomTableViewVR" BorderPane.alignment="CENTER">
                              <columns>
                                <TableColumn fx:id="intRoomIDColVR" prefWidth="75.0" text="Room ID" />
                                <TableColumn fx:id="vachRoomTypeIDColVR" prefWidth="115.00000762939453" text="Room Type" />
                                          <TableColumn fx:id="reservedColVR" prefWidth="94.0" text="Reserved?" />
                                          <TableColumn fx:id="resCustomerColVR" prefWidth="95.0" text="Customer " />
                              </columns>
                            </TableView>

                                 <top>
                                    <HBox>
                                       <children>
                                          <Button fx:id="btnCheckInPopUp" mnemonicParsing="false" text="Check In" BorderPane.alignment="CENTER" />
                                       </children>
                                    </HBox>
                                 </top>
                              </BorderPane>
                    </children>
                  </AnchorPane>
                </content>
              </TitledPane>
              <TitledPane fx:id="accOccupied" animated="false" text="Occupied Rooms">
                <content>
                  <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0">
                    <children>
                              <BorderPane prefHeight="324.0" prefWidth="598.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
                                 <top>
                                    <HBox>
                                       <children>
                                          <Button fx:id="btnTabCheckOut" mnemonicParsing="false" text="Check Out" BorderPane.alignment="CENTER" />
                                       </children>
                                    </HBox>
                                 </top>

                                    <TableView BorderPane.alignment="CENTER">
                                       <columns>
                                          <TableColumn fx:id="intRoomIDColOR" prefWidth="75.0" text="Room ID" />
                                          <TableColumn fx:id="vachRoomTypeIDColOR" prefWidth="115.00000762939453" text="Room Type" />
                                          <TableColumn fx:id="occupantColOR" prefWidth="83.0" text="Occupant" />
                                          <TableColumn fx:id="checkInDateColOR" prefWidth="121.0" text="Check In Date" />
                                          <TableColumn fx:id="checkOutDateColOR" prefWidth="181.99996948242188" text="Expected Check Out Date" />
                                       </columns>
                                    </TableView>

                              </BorderPane>
                    </children>
                  </AnchorPane>
                </content>
              </TitledPane>
            </panes>
          </Accordion>

        <top>
          <HBox prefHeight="24.0" prefWidth="600.0" BorderPane.alignment="CENTER">
            <children>
              <Button fx:id="btnNewRoom" mnemonicParsing="false" text="New Room" />
              <Button fx:id="btnEditRoom" mnemonicParsing="false" text="Edit Room" />
                  <Button fx:id="btnNewRoomType" mnemonicParsing="false" text="New Room Type" />
                  <Button fx:id="btnEditRoomType" mnemonicParsing="false" text="Edit Room Type" />
                  <Button fx:id="btnGuestLog" mnemonicParsing="false" text="Guest Log" />
            </children>
          </HBox>
        </top>
      </BorderPane>
    </children>
</AnchorPane>

The Controller Class:
    public class RoomsController implements Initializable {
    @FXML
    private TableView<RoomData> roomTableViewVR;
    @FXML
    private TableColumn<RoomData, Integer> intRoomIDColVR;
    @FXML
    private Button btnCheckInPopUp;
    @FXML
    private TableColumn<RoomData, String> vachRoomTypeIDColVR;

    //Declare ObservableList
    private ObservableList<RoomData> olRoomData;

    private ActionEvent event;
    private static Connection con;
    private static ResultSet rs;
    private static java.sql.Statement stmt;
    private static String sql;
    JavaToMySQL javaToMySQL = new JavaToMySQL();

    public RoomsController() {
        try {
            con = DatabaseConnection.getConnected();
            stmt = con.createStatement();
            olRoomData = FXCollections.observableArrayList();
            rs = con.createStatement().executeQuery("SELECT * FROM h_r_rooms");
            while (rs.next()){
                olRoomData.add(new RoomData(rs.getInt("intRoomID"),rs.getString("vachRoomTypeID")));
            }
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("Error on Building Data");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        listeners();

        intRoomIDColVR.setCellValueFactory(new PropertyValueFactory<>("roomID"));
        vachRoomTypeIDColVR.setCellValueFactory(new PropertyValueFactory<>("roomTypeID"));
        roomTableViewVR.setItems(olRoomData);
    }

    void listeners(){
        btnCheckInPopUp.setOnAction((event -> {
            System.out.println("I'm supposed to pop out a Check In window when you click me!");

            Stage stage;
            if (event.getSource()== btnCheckInPopUp){
                stage = new Stage();
                try {
                    Parent root = FXMLLoader.load(getClass().getResource("../view/popups/check_in.fxml"));
                    System.out.println("I work!");
                    stage.setScene(new Scene(root));
                    stage.setTitle("Check Customer In");
                    stage.initModality(Modality.APPLICATION_MODAL);
                    stage.initOwner(btnCheckInPopUp.getScene().getWindow());
                    stage.showAndWait();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }));
    }
}

When I click on the Check In(btnCheckInPopUp) the following error appears:
The Connection is open!
javafx.fxml.LoadException:
/home/mush/Programming/Dev/InteliJProjects/Hotel_MIS/out/production/Hotel_MIS/com/codetech/hotelmis/view/popups/check_in.fxml

    at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2605)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2583)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2445)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3218)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3179)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3152)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3128)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3108)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3101)
    at com.codetech.hotelmis.controller.RoomsController.lambda$listeners$0(RoomsController.java:87)
    at com.codetech.hotelmis.controller.RoomsController$$Lambda$104/1394020985.handle(Unknown Source)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8390)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3758)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3486)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2495)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:350)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:275)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$350(GlassViewEventHandler.java:385)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$$Lambda$252/507580015.get(Unknown Source)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:404)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:384)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:927)
    at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at com.sun.glass.ui.gtk.GtkApplication.lambda$null$48(GtkApplication.java:139)
    at com.sun.glass.ui.gtk.GtkApplication$$Lambda$43/1166661505.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at com.codetech.hotelmis.controller.RoomsController.initialize(RoomsController.java:74)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2552)
    ... 70 more

I've really tried to figure out why but to no avail. I'd really appreciate the help and I will provide any more details concerning the code required to solve the issue.
The problem here
 seems quite similar to mine.

A: It appears you are using the same controller class for two different FXML files. Don't do this: use a different controller for each FXML.
When the FXMLLoader's load() method is called, it does the following (somewhat simplified description):

*

*Reads the FXML file

*If the FXML file specifies a controller class, it creates a new instance of the controller class by calling its no-argument constructor

*Creates an object hierarchy based on the FXML elements

*Sets event handlers on the elements, mapping to the controller class instance created in step 1

*For elements with an fx:id attribute, it injects the corresponding objects into any matching @FXML-annotated references in the controller instance

*Calls initialize() on the controller instance, if such a method exists.

*Returns the object corresponding to the root element of the FXML file.

In your case, you have two FXML files specifying the same controller class. When the "main" FXML file is loaded, the process above happens. A first instance of RoomsController is created, its @FXML-annotated fields matching fx:ids are injected (including intRoomIDColVR and others), event handlers are registered, and the initialize() method is called. All is fine at this point.
When the btnCheckInPopup button is pressed, its onAction handler is invoked. This causes check_in.fxml to be loaded. Since this specifies the same controller class, a second instance of that class is created. @FXML-annotated fields corresponding to elements of check_in.fxml with matching fx:ids are injected. However, note that, since check_in.fxml doesn't define any element with fx_id="intRoomIDColVR", intRoomIDColVR is not initialized for this second controller instance. The initialize() method is then invoked on this second controller instance, and since intRoomIDColVR is not initialized, this causes a NullPointerException at the line
intRoomIDColVR.setCellValueFactory(new PropertyValueFactory<>("roomID"));

This is a pretty good example of exactly why each FXML should have its own controller class. It gets very hard to keep track of which fields are initialized and which are not at any given time, and for any specific instance of the class, if you "share" controller classes like this.


text:
Q: How to open a file using "filedialog.askopenfile" with "utf-8' encoding. I am able to open the file but it is opening with different encoding When I usually open files I use open syntax where it gives me option of opening with a specific encoding, for eg.
f = open('L2G8970_PSA_PVS_SmokeTest_Report_Trial.xml', encoding="utf8")

But when I am trying with tkinter's filedialog.askopenfile() syntax
filename = filedialog.askopenfilename()

file is getting opened with different encoding.
Please help on how to import with utf-8 encoding.

A: from tkinter import filedialog

filename = filedialog.askopenfilename()
with open(filename, 'r', encoding='utf8') as file:
    textfromfile = file.read()
    file.close()
print(textfromfile)

The sample above pops up a filedialog, lets you choose a file, loads the file in reading modus, with utf-8 encoding, and prints it to the console.
I used this workaround with filedialog.askopenfilename() because the filedialog.askopenfile() method scrambled some of the characters in my textfiles ('ë' among others).
Now it works fine, since the original texts I use are all utf-8 encoded.


text:
Q: Replace jq predefined variable with number jq could have predefined variables and replace with --arg options. It works well with string. However, I don't know how to replace the variable as number.
$jq -n --arg number 3000 '{"number":$number}'
{
  "number": "3000"
}

I would like to be able to generate something as following :
{
  "number": 3000
}

Thanks in advance.

A: Or:
jq -n --arg number 300 '{"number": $number|tonumber}'

or (as Jeff pointed out) with jq 1.5:
jq -n --argjson number 300 '{"number": $number}'

or (with versions of jq after June 26, 2015):
jq -n --arg number 300 '{$number} | .number |= tonumber'

A: Here is the solution:
jq -n --argfile number <(printf '%d' 3000) '{"number":$number}'

Or
jq -n --arg number 3000 '{"number":$number|fromjson}'


text:
Q: Dynamic Charts in ActiveReports I am currently developing a report using ActiveReport where there I need to display Charts.  The number of charts that will be displayed is dynamic based the data.... The report will be laied out somehting like this.

*

*Account Number/Name [group header]

*Some Account Details [details]

*Account Name & charts(s)(one for each detail line) [group footer]

As I said above, the contents of the details & charts could be different for each group.
I have read that that dynamic report creation had to be done in _ReportStart, but if I do that, I does the correct charts make it to the correct group (account number)??

A: It is a bit unclear what exactly you want to do and what the problem is. As I understand there is a set of charts in the group footer and you want to hide and show some of them depending on the data.
If you only want to hide and show some of them, then you can create the report statically in the designer, and in the Format event of the GroupFooter Section, you can hide or show the charts accordingly.
However, if it is entirely unclear how many charts will be in the group footer, then you should use a subreport. Design a report that has a template for the charts you need and then place that subreport in the group footer of the parent report. Using a subreport will allow you to completely change the charts/controls for every group.
If you'd like additional help please comment and explain more about what exactly is in the charts and what is changing based on the data. It is difficult to give more detail without understanding more about what you're doing, what you've tried and what exact problems you've encountered.


text:
Q: Does anyone really say "SAYS" rather than "SEZ"? I've just heard Labour party leader Jeremy Corbyn, at 10:13 here (about a quarter of the way through Prime Minister's Questions, UK Parliament, Thurs 27 Oct) saying...

Amnesty International SAYS, and I quote, [blah blah, wot they sed]

Apologies to anyone who can't access the video (it's a BBC link, which I suppose gets tricky if you're not a license payer), but obviously the point is he clearly says SAYS (/seɪz/), not SEZ (/sɛz/).
As it happens, while saying those words Corbyn is constantly looking down on what are presumably pre-written notes/quotes, so I'm inclined to suppose it's actually just a one-off enunciation error (because sometimes reading and talking is like walking and chewing gum! :)
But seriously, does anyone talk like that today if they're not distracted by orthography?

I don't want to get bogged down in how non-native speakers affect things. I'm only really asking if there might perhaps be a surviving "dialectal pocket" of some kind (assuming the orthography represents an original pronunciation). Or could it be an "emergent usage", reflecting the general tendency to "regularise" irregular verbs?

A: *

*It seems that Jeremy Corbyn regularly pronounces "says" as /seɪz/, as witnessed by this other video (he repeats the word a number of times, e.g., at 1′31″ in the video clip, where it is unclear whether he is reading his notes at this point); as a matter of fact, I stumbled on this question because I thought it was unusual so I googled "says seɪz sɛz", which led me here.  Note that Corbyn pronounces "said" as /sɛd/ just a few seconds earlier, so I think we can rule out confusion due to the written form of the word.

*This doesn't seem to have been mentioned elsewhere in this thread, but the entry for "say" in the Longman Pronunciation Dictionary by J. C. Wells gives the result of a poll they conducted in 1998 among British English speakers concerning various words, with the result that "says" is pronounced /sɛz/ by 84% of respondents and /seɪz/ by 16% [the dictionary uses the transcription /e/ for the DRESS vowel, so they write "sez", but I'm normalizing for consistency's sake].  They mark the pronunciation /seɪz/ with a '§' symbol, meaning "BrE non-RP".

A: The following extract from Grammarphobia (2008) seems to suggest that "says" pronounced /seiz/ can still be heard:

*

*Q: I hear BBC correspondents pronounce "says" with a long "a" to rhyme with "prays." Why do Americans pronounce it like "sez" instead of like "pays," "lays," and other "ays" word that come to mind. Is it just a quirk of English?

*A: The third-person singular of the verb "say" should be pronounced "sez" on both sides of the Atlantic, according to American and British dictionaries. But pompous broadcasting twits, especially across the pond, have never let standard pronunciations get in the way of on-air affectations.

According to the following extract from  Wise  Words, /seiz/ used to be the  standard pronunciation of "says" which  was gradually  replaced by the shorter /sɛz/. The former  appears to have survived as a non-standard dialectal form:

*

*As the linguist Fidelholtz wrote back in 1975 — 'Frequent words can do exceptional things'. The verb to 'say' is a good example of a mundane verb that is used a lot and that does exceptional things. 'I say, you say, we say, they say'. There's nothing peculiar here. It's the so-called third person form that is the problem — this is where the verb falls out of kilter. In Standard English this is pronounced as 'he/she/it sez', and not 'he/she/it says'. So it's the shortened version 'sez' that is standard; the full form 'says' is now considered non-standard, dialectal.

*The pronunciation shift from 'says' to 'sez' must have occurred some time ago — writers were already commenting on it as far back as the mid 1600s.  Frequency has to be the trigger for the change here. I can think of no other explanation. The 'he/she/it' forms of verbs are used more often than other forms. And so the repetition of 'says' will have the effect of streamlining the way we articulate it. In other words, we know what we're doing; we've done it so often, so we make short-cuts.

*As in anything we do automatically, we get more efficient, faster and we decrease the size of whatever gestures are involved.  In the case of speech, the transition between the sounds becomes more fluent — longer 'says' reduces to 'sez'. You can see this also in the pronunciation of the form said, pronounced, in Standard English at least, with the same short vowel and not as you'd expect from the spelling (and as it was once pronounced) — 'said'. Again you can imagine the regularity with which we produce phrases like 'he said'/'she said'/'it said'. Because we say it so often, we opt for a shorter route.

(www.abc.net)

A: was Googling this as I was watching a BBC documentary about Anne Boleyn and the presenter , TRacy Borman, consistently used SAYS (like prays) not SEZ. Perhaps it's a  regional thing?

A: It's been my experience that many Canadians pronounce "says" as "sāys", especially in Windsor and Toronto. As an American I can say that in my 70 years, I've never heard an American do so. However, I often do listen to BBC radio, where it seems "sāys" is trending upward.


text:
Q: sax parser returns empty string from xml i'm trying to parse xml with stax.
after i'm going to this line in xml -
<temperature>38</temperature>

i am get a empty  string value. Why this happens ? What can i do to solve this ?
 my xml :
<?xml version="1.0" encoding="UTF-8"?>
<flowers>
    <flower name="rose">
        <soil>podzolic</soil>
        <visualParameters>
            <stemColor>Green</stemColor>
            <leafColor>Red</leafColor>
            <averageSize>50</averageSize>
        </visualParameters>
        <growingTips>
            <temperature>38</temperature>
            <watering>1200</watering>
            <value>photophilous</value>
        </growingTips>
    <multiplying>bySeeds</multiplying>
    <origin>Belarus</origin>
        <description>Classic Choice</description>
    </flower>
</flowers>

my code :
  List<Flower> getFlowerList() {
        return flowerList;
    }
    public void startElement(String namespaceURI, String localName, String qName, Attributes attrs) throws SAXException {
        switch (qName) {
            case "flowers":
                flowerList = new ArrayList<Flower>();
                break;
            case "flower":
                flower = new Flower();
                flower.setName(attrs.getValue("name"));
                break;
            case "visualParameters":
                visual = new VisualParameters();
                break;
            case "GrowingTips":
                tips = new GrowingTips();
                break;
        }

    }
    public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
        switch (qName) {
            case "flower":
                flowerList.add(flower);
                break;
            case "soilType":
                soil = new SoilType();
                soil.setValue(SoilName.fromValue(content));
                break;
            case "origin":
                flower = new Flower();
                flower.setOrigin(content);
              break;
            case "averageSize":
                  visual.setAverageSize(Integer.valueOf(content));
              flower.setParameters(visual);
               break;
            case "leafColor":
                visual.setLeafColor(content);
                flower.setParameters(visual);
                break;
            case "temperature":
             //in this line content = ""
                tips.setTemperature(Integer.valueOf(content));

                break;
            case "stemColor":
                visual.setStemColor(content);
                flower.setParameters(visual);
                break;
            case "watering":
                tips.setWatering(Integer.valueOf(content));
                break;
            case "lightingType":
                tips.setValue(LightingName.fromValue(content));
                break;
            case "multiplying":
                multiplyingType = new MultiplyingType();
                multiplyingType.setValue(MultiplyingName.fromValue(content));
                break;
            case "description":
                flower.setDescription(content);
                break;
        }

    }
 public void characters(char[] ch, int start, int length) {
        content = String.copyValueOf(ch, start, length).trim();
    }

and the stacktrace:
java.lang.NullPointerException
    at tasks.five.parser.SAXHandler.endElement(SAXHandler.java:75)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.endElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(Unknown Source)
    at javax.xml.parsers.SAXParser.parse(Unknown Source)
    at tasks.five.parser.SAXParserClass.SAXParser(SAXParserClass.java:22)
    at tasks.five.command.SAXParserCommand.execute(SAXParserCommand.java:13)
    at tasks.five.command.CommandExecutor.execute(CommandExecutor.java:21)
    at tasks.five.runner.Main.main(Main.java:14)

A: Your characters() method is wrong:
content = String.copyValueOf(ch, start, length).trim();

Text data can be divided up into chunks any way the parser chooses, and delivered in multiple calls of characters(). You need to append to the value of content, not to overwrite it each time.

A: Your case code in startElement() is searching for "GrowingTips" instead of "growingTips", and case statements are case sensitive. So in the endElement() code, when you try to set the temperature, tips is null, and causes NullPointerException to be thrown.


text:
Q: Android: Gesture Accessibility Service blocks default touch actions I'm creating an app that can detect double tap gesture from any screen.
I'm able to successfully detect the double tap gesture using flagServiceHandlesDoubleTap
The issue that I'm facing is that this blocks the default touch actions and nothing happens on tapping or swiping to go back.
MyAccessibility Class
public class MyAccessibilityService extends AccessibilityService {

    private static final String TAG = "MyAccessibilityService";
    public static final int GLOBAL_ACTION_LOCK_SCREEN = 8;

    @Override
    public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
    }

    @Override
    public void onInterrupt() {
        Log.e(TAG, "onInterrupt: something went wrong");
    }

    @Override
    public boolean onGesture(@NonNull AccessibilityGestureEvent gestureEvent) {
        int gestureId = 0;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
            gestureId = gestureEvent.getGestureId();
        }
        Log.d(TAG, "onGesture: Gesture Detected " + gestureId);
        switch (gestureId){
            case 17:
                Log.d(TAG, "onGesture: Double Tap Happened");
        }
        return super.onGesture(gestureEvent);
    }

}

accessibility_service_config.xml
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
    android:description="@string/accessibility_service_description"
    android:accessibilityEventTypes="typeWindowContentChanged"
    android:accessibilityFlags="flagRequestTouchExplorationMode|flagServiceHandlesDoubleTap"
    android:canRetrieveWindowContent="true"
    android:canRequestTouchExplorationMode="true"
    android:accessibilityFeedbackType="feedbackGeneric"
    android:notificationTimeout="100"
    android:settingsActivity="com.example.android.accessibility.ServiceSettingsActivity"
    />

How can I handle the double tap gesture without blocking touch or default gesture actions?


text:
Q: How to cancel previous WooCommerce subscription automatically when new subscription is purchased? I'm building a membership site where users must only have one active subscription at a time. I would like that on a purchase of any new subscription/product all other subscriptions to be cancelled/expired and all associated membership deleted/cancelled. Only the latest subscription should remain active with its accompanying membership.
I cannot/don't want to use the built-in function to limit subscriptions for several reasons.
Is there any way that on the thank you page, a snipped loops in all active subscriptions from current user and cancel/expire them, except for the one that has been just bought?
I've checked this post which looks similar but no real solution was provided (WooCommerce Subscriptions - Only Allow user one active subscription)
Thanks a lot for your help
Best regards

A: Auto-answering as I've managed to solve my issue with the help of other SO posts.
Basically I'm getting all active subscriptions by descending ID and set a counter inside my loop. If it loops more than once then it sets the status of the subscription to cancelled. I hooked this in the thank you page to be sure it fires only when the payment has been made...
add_action( 'woocommerce_thankyou', 'edf_cancel_previous_active_subscription' );
function edf_cancel_previous_active_subscription() {

    $no_of_loops = 0;
    $user_id = get_current_user_id();

    // Get all customer subscriptions
    $args = array(
        'subscription_status'       => 'active',
        'subscriptions_per_page'    => -1,
        'customer_id'               => $user_id,
        'orderby'                   => 'ID',
        'order'                     => 'DESC'
    );
    $subscriptions = wcs_get_subscriptions($args);

    // Going through each current customer subscriptions
    foreach ( $subscriptions as $subscription ) {
        $no_of_loops = $no_of_loops + 1;

        if ($no_of_loops > 1){
            $subscription->update_status( 'cancelled' );
        }
    }
}

Not sure whether this is the "Wordpress/WooCommerce" way of doing it but I brought my other programming languages experience with me for this one. If someone has a better idea, feel free to post it.

A: I modified the code mentioned below as it cancels all subscriptions if a new user registers though the mentioned code works fine for existing users but when a new user registers all subscriptions of all users will be cancelled
Hence I have developed code as
    function edf_cancel_previous_active_subscription() {

        $no_of_loops = 0;
        $user_id = get_current_user_id();

        // If is an existing user
        if($user_id!=0)
        {
        $args = array(
            'subscription_status'       => 'active',
            'subscriptions_per_page'    => -1,
            'customer_id'               => $user_id,
            'orderby'                   => 'ID',
            'order'                     => 'DESC'
        );
        $subscriptions = wcs_get_subscriptions($args);
        // Going through each current customer subscriptions
         foreach ( $subscriptions as $subscription ) {
             $no_of_loops = $no_of_loops + 1;
//Cancel previous subscription of user applying for new subscription
             if ($no_of_loops = 1) {
                 $subscription->update_status( 'pending-cancel' );
             }
         }
     }
    }
//when checkout is in progress previous subscriptions will be cancelled and after successful checkout the subscription for which checkout process was initiated becomes active
    add_action('woocommerce_before_checkout_process', 'edf_cancel_previous_active_subscription');


text:
Q: OpenDNS Redirects Website - Firefox Does not Load Body I bought a domain and created a website for it. It seems to work, however, after a fraction of a second, OpenDNS redirects me to the "Website Unavailable" page. How can I fix this. I cannot remove OpenDNS, as it is used for parental control.
In addition, the body of the webpage does not load at all when I use Firefox.
Update: Firefox seemed to fix itself. Weird. However, I still get the OpenDNS error in Chromium, but only in Chromium.

A: Depending on when you setup your domain name to point to your server it could have to to with DNS Propagation. Why DNS Propagation Takes So Long
Chromium may still be holding on to an old DNS entry, here are instructions to flush you chromium DNS cache


text:
Q: How to move content from a textarea to a div using javascript I want to move content from a <textarea> to a
 and I don't really know how to do it.
this is my code:

   <textarea id="mssg" rows="5" cols="40" >
       Hey, I am cooking. what are you doing?
   </textarea>

<input type="button" value="swap" onclick="swap()">
Sign out

Sent messages appear here:

Here's an example.

A:

It is a weird behaviour, really. Anyway, you are swapping contents, not elements.
I hope it helps.

A: function swap()
{
    var one = document.getElementById("one").innerHTML;

    var two = document.getElementById("two");
    var twohtml = document.getElementById("two").innerHTML
    document.getElementById('one').remove();
    two.innerHTML =   "
"+twohtml+"
" + "
"+one+"
" ;

}


text:
Q: Deploy to iPhone without running How do I deploy my app down to the iPhone (for testing purposes) from XCode without actually running the app?

A: Xcode -> Product -> Scheme -> Edit Scheme -> Run -> Info -> Wait for executable to be launched

A: Edit your launch Scheme, open the section titled "Run myApp.app" and toggle ON the option to "Wait for myApp.app to launch".
It will then just install, and not run the app.  If you do run it yourself, the debugger should attach.  This is useful for when you want to test how your applications works when launched via a URL, amongst other things.
NOTE - To be fair, this answer is the same as the one for this question.  I didn't mark this question as a duplicate though, because you might have a different reason for wanting to do this.  Still, if you want a more detailed explanation, look there.

A: ☝ One...:

✌...Two...:

... and Three:

A: You can create an archive, drag that .ipa onto iTunes and sync the device.
Or you can just run it from XCode, and then kill the XCode process, and run it from the SpringBoard, though I assume you need the virgin case or you wouldn't have asked the question.

A: Connect your device, set the Scheme on your top left to iOS Device.

A: If you time it just right by watching the Xcode console, you can kill the debugger after the app is completely downloaded, but before any code in the app is executed.
If you don't want to depend on timing, and don't need to consider the app to be running until it hits some Cocoa Touch or Objective C runtime code, you could set a breakpoint on an NSLog inserted as the first line of main() and kill the app after it hits that breakpoint.