text:
Q: Parallel cURL Request with WRITEFUNCTION Callback I'm trying to limit my cURL responses as suggested in these posts:Retrieve partial web page and PHP CURLOPT_WRITEFUNCTION doesn't appear to be working. The idea is to limit the response to 4000 characters as specified in the callback function.
I wrote the following function, but I already know that it doesn't make sense, because a parameter in the callback function definition doesn't vary within a loop as it would within a function call. By the time the functions are actually called, the value for $key is fixed, so my references to that index won't vary.
It seems that I need a new closure function for each of the loops, and each one needs to reference its own $full_length variable. However, I don't see how that's possible. In order to do that, it seems I would have to somehow make a reference the closure object in order to specify the specific $full_length variable.
Any help would be appreciated. Thanks.
function get_headers($urls){
    $curly = array();
    $result = array();
    $mh = curl_multi_init();
    $obj = $this;
    foreach ($urls as $key => $url) {
        $this->full_length[$key] = 0;
        $callback = function ($ch, $string) use ($obj, $key){
                    $length = strlen($string);
                    $obj->full_length[$key] += $length;
                    if($obj->full_length[$key] >= 4000){
                        return -1;
                    }
                    return $length;
                };
        $curly[$key] = curl_init
        curl_setopt($curly[$key], CURLOPT_URL,            $url);
        curl_setopt($curly[$key], CURLOPT_HEADER,         0);
        curl_setopt($curly[$key], CURLOPT_WRITEFUNCTION, $callback);
        curl_setopt($curly[$key], CURLOPT_RETURNTRANSFER, 1);
        curl_multi_add_handle($mh, $curly[$key]);
    }
    $running = null;
    do {
        curl_multi_exec($mh, $running);
    } while($running > 0);
    foreach($curly as $key => $cnt) {
        $content = curl_multi_getcontent($cnt);
        curl_multi_remove_handle($mh, $cnt);
        if (strlen($content) > 0){
            $result[$key] = $content;
        } else {
            curl_multi_close($mh);
            return FALSE;
        }
    }
    curl_multi_close($mh);
    return $result;
}

EDIT:
I found a post that does exactly what I'm trying to do, but it's in javascript:
closure inside a for loop - callback with loop variable as parameter . I wrote the following function to try to do the same thing in PHP:
function get_write_function($key){
    $this->full_length[$key] = 0;
    $obj = $this;
    $funky = function ($ch, $str) use ($obj, $key){
        $length = strlen($str);
        $obj->full_length[$key] += $length;
        if($obj->full_length[$key] >= 4000){
            return -1;
        }
        return $length;
    };
    return $funky;
}

The code ran without errors, but it still didn't do what I wanted. After closing my cURL handles I dumped the $full_length array, and it only showed:
array([0] => 0, [1] => 0)

That indicates that they were initialized by the get_write_function (since I didn't initialize anything in the class declaration), but that the values were never updated afterwards.

A: I finally got it figured out. The biggest problem was the fact that cURL was ignoring the WRITEFUNCTION until I placed it as the very last option specified, as I posted here: cURL WRITEFUNCTION not Being Called. I actually didn't need the return transfer, since I wrote the output to a class variable. That was necessary because when the callback returns -1, nothing gets returned. The following code works great:
var $full_length = array();
var $result = array();

function get_headers($urls){
    $curly = array();
    $mh = curl_multi_init();
    foreach ($urls as $key => $url) {
        $callback = $this->get_write_function($key);
        $curly[$key] = curl_init
        curl_setopt($curly[$key], CURLOPT_URL,            $url);
        curl_setopt($curly[$key], CURLOPT_HEADER,         0);
        curl_setopt($curly[$key], CURLOPT_WRITEFUNCTION, $callback);
        curl_multi_add_handle($mh, $curly[$key]);
    }
    $running = null;
    do {
        curl_multi_exec($mh, $running);
    } while($running > 0);
    foreach($curly as $key => $cnt) {
        curl_multi_remove_handle($mh, $cnt);
    }
    curl_multi_close($mh);
    return $this->result;
}

function get_write_function($key){
    $this->full_length[$key] = 0;
    $this->result[$key] = '';
    $obj = $this;
    $funky = function ($ch, $str) use ($obj, $key){
        $obj->result[$key] .= $str;
        $length = strlen($str);
        $obj->full_length[$key] += $length;
        if($obj->full_length[$key] >= 4000){
            return -1;
        }
        return $length;
    };
    return $funky;
}


text:
Q: Product of homogenous polynomials Suppose $f,g$ are in $R[x_1,x_2,...,x_n]$ and $fg$ is homogeneous, then
$f$ and $g$ are both homogeneous.
My argument is:
Considering $f$ and $g$ as monomials.  suppose $fg$ is homogeneous and using the fact that deg$fg$ = deg$f$ + deg$g$, we can conclude that $f$ and $g$ are homogeneous.
Am I right?
Thanks

A: As YACP we need $R$ to be a domain.
The proof you give is insufficient because the "degree" ignores stuff of lower degree. How do you know $f$ and $g$ don't have stuff in lower degree that cancels out?
For example, if we worked over the ring $\mathbb{C}[t]/t^2$, then we have
$$ (x+t)(x-t) = x^2$$
(Notice that your "proof" doesn't mind if $R$ is a domain or not, so we need to use that.)
Instead, it may be useful to look at the terms of lowest total degree in $f$ and $g$ and look what happens to their product in $fg$. (An ordering on monomials within a given total degree might make the argument slicker.)
If that's not enough of a hint to work it out I'll add more later.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to handle a legacy database in the Django framework I'm working on an Django app that needs to access a very large (MySQL) database, the db has no foreign keys whatsoever. I need to do queries on multiple tables. The way I'm doing it is VERY inefficient and involves doing multiple loops:
{% for flower in especies_id %}
    {{flower.especies}}
    {% for family in family_id %}
        {% if family.family_id == flower.family_id %}

                {{family.family_name}}
        {% endif %}
    {% endfor %}
{% endfor %}

Is there a way to handle this db with the Django shell maybe JavaScript? Or refactor the db entirely?
(edit):
the db has ~3000 entries
relationship between two tables are made using an additional one:
flower2estate which contains estate_id, flower_id
Models.py:
    class Listflower(models.Model):

        especies_id = models.AutoField(primary_key=True)
        family_id = models.IntegerField(blank=True, null=True)
        especies = models.CharField(max_length=255, blank=True, null=True)

        class Meta:
            managed = False
            db_table = 'listflower'

class Estate(models.Model):
    estate_id = models.AutoField(primary_key=True)
    estate_name = models.CharField(max_length=100, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'estates'

class Flower2Estate(models.Model):
        estate_id = models.IntegerField(primary_key=True)
        especies_id = models.IntegerField()

        class Meta:
            managed = False
            db_table = 'flower2estate'
            unique_together = (('estado_id', 'especie_id'),)

Views.py:
def flowers(request):
    list_flower = ListFlower.objects.all().order_by('especies_id')
    paginator = Paginator(list_flower, 3)
    page = request.GET.get("page")
    try:
        flowers = paginator.page(page)
    except PageNotAnInteger:
        flowers = paginator.page(1)
    except EmptyPage:
        flowers= paginator.page(paginator.num_pages)
    return render(request, 'accounts/flowers.html', {'page':page,"flowers"

:flowers,"especies_id":flowers})
I need to get the "flower" and the corresponding "estate" without the need to loop between 3000 entries.

A: You can add some methods to legacy models to retrieve related items a bit more efficiently:
class Listflower(models.Model):
    especies_id = models.AutoField(primary_key=True)
    family_id = models.IntegerField(blank=True, null=True)
    especies = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'listflower'

    def get_family(self):
        return FamilyModel.objects.get(family_id=self.family_id)

class Estate(models.Model):
    estate_id = models.AutoField(primary_key=True)
    estate_name = models.CharField(max_length=100, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'estates'

    def get_flowers(self):
        flower_ids = Flower2Estate.objects.filter(estate_id=self.estate_id).values_list('especies_id', flat=True)
        return Listflower.objects.filter(especies_id__in=flower_ids)

But if it is not the last time you work with this data probably the better way is to define regular django models with fks and write once a script to convert legacy data to a new model structure. The challenge shouldn't take more than an hour.
UPDATE
class FlowerFamily(models.Model):
    # assuming you old family model has
    # "family_id" and "family_name" fields
    family_id = models.IntegerField(blank=True, null=True)
    family_name = models.CharField(max_length=255, blank=True, null=True)

class Flower(models.Model):
    # you might want preserve old model fields in the new model
    # at least id fields
    especies_id = models.IntegerField(blank=True, null=True)
    family_id = models.IntegerField(blank=True, null=True)
    especies = models.CharField(max_length=255, blank=True, null=True)

    family = models.ForegnKey(FlowerFamily, related_name='flowers')

class NewEstate(models.Model):
    estate_id = models.IntegerField(blank=True, null=True)
    estate_name = models.CharField(max_length=100, blank=True, null=True)
    flowers = models.ManyToManyField(Flower, related_name='estates')

# this is a slightly primitive example
# in real life you might want to use get_or_create instead of direct creation
# in case script fails and you'll need to run it again
# also objects.get() might better be used with try-except ObjectDoesNotExist
def convert_legacy():
    # create new instances
    for ff in YourOldFamilyModel.objects.all():
        new_ff = FlowerFamily(family_id=ff.family_id, family_name=ff.family_name)
        new_ff.save()

    for fl in Listflower.objects.all():
        new_fl = Flower(...)

        family = FlowerFamily.objects.get(family_id=fl.family_id)

        new_fl.family = family
        new_fl.save()

    # same thing for Estate
    for ...:
        new_estate ...
        new_estate.save()

        # and restore relations
        flower_ids = Flower2Estate.objects.filter(estate_id=new_estate.estate_id).values_list('especies_id', flat=True)

        for new_lf in Flower.objects.filter(especies_id__in=flower_ids):
            new_estate.flowers.add(new_fl)


text:
Q: Is there a shorter code for the following simple file manipulation program? The following is the problem and i have  written the code.Can someone have the answer code shortened?

Suppose the file studentdata.txt contains information on grades students earned on various
  assignments. Each line has the last name of a student (which you can assume is one word) and
  the numeric grade that student received. All grades are out of 100 points. Students can appear
  multiple times in the file.
  Here's a sample file:

Arnold 90
Brown 84
Arnold 80
Cocher 77
Cocher 100

Write a function that reads the data from the file into a dictionary. Then continue prompting the
user for names of students. For each student, it should print the average of that student's grades.
Stop prompting when the user enters the name of a student not in the dictionary.
A sample run for the given file:
Enter name: Arnold
The average for Arnold is: 85.0
Enter name: Brown
The average for Brown is: 84.0
Enter name: Cocher
The average for Cocher is: 88.5
Enter name: Doherty
Goodbye!

Here is my code :
import os
PATH="C:/Users/user/Desktop/studentdata.txt"
fd=open("C:/Users/user/Desktop/studentdata.txt","r")

d=fd.read()
p1=r"\b[A-za-z]+\b"
p2=r"\b[0-9]+\b"
l1=re.findall(p1,d)
fd=open("C:/Users/user/Desktop/studentdata.txt","r")
l2=re.findall(p2,d)
d={}
for key,val in list(zip(l1,l2)):
    if key not in d:
        d[str(key)]=int(val)
    else:
        d[str(key)]+=int(val)
for key in d:
    d[key]=d[key]/l1.count(key)

while True:
    key=input("Enter name:")
    if key not in d:
        print("Goodbye!")
        break
    print("the average for "+key+" is: "+str(d[key]))

A: PATH = "C:/Users/user/Desktop/"
FILE = "studentdata.txt"
with open(PATH + FILE, 'r') as fp:
  lines = fp.readlines()
notes_with_students = {}

for line in lines:
  student = line.split()[0]
  note = line.split()[1]
  if student not in notes_with_students:
    notes_with_students.setdefault(student, [int(note), 1])
  else:
    notes_with_students[student][0] += int(note)
    notes_with_students[student][1] += 1

while True:
  student = input("Enter name: ")
  if student not in notes_with_students:
    print("Goodbye!")
    break
  print("The average for {} is: {}".format(student, notes_with_students[student][0]/notes_with_students[student][1]))

This can be useful.


text:
Q: Resolving conflicts with branch containing features we don't want to move forward Apologies in advance if this question doesn't make much sense.
We have three branches Dev, Master and Stable. When we create a new feature, we create that from Stable and then create pull requests to Dev and Master.
It will first get deployed on Dev, then on Master and eventually merged back to Stable when it goes to production.
My feature branch S1 is created from Stable and I am trying to create a pull request to Dev but some files are ending up in conflict with Dev and I need to resolve this conflict.
This is the current situation
Dev
  -- D1
  -- D2

Master
  -- M1

Stable
  -- S1

The change made in S1 conflicts with changes made in D1. To resolve the conflict I can simply merge the Dev branch into my feature branch.
But if I do that then when I move S1 to Master it will also carry D2 with it. I don't want that. D2 needs to stay in Dev for a longer period of time and I only need to move D1 forward to Master and Stable.
I can also create two separate feature branches one from Dev and one from Master and then merge them back to Dev and Master respectively and create a release branch from Master. But this will create too many branches.
How can I resolve conflict in situation like this?

A: If D1 and D2 are sequentials (first D1 commits, then D2), you can also:

*

*create a tmp branch at D1

*rebase S1 top of D1 (resolving conflicts locally)

*merge S1 to Dev (where you test D1 and D2)


text:
Q: Assigning values to Pandas Multiindex DataFrame by index level I have a Pandas multiindex dataframe and I need to assign values to one of the columns from a series. The series shares its index with the first level of the index of the dataframe.
import pandas as pd
import numpy as np
idx0 = np.array(['bar', 'bar', 'bar', 'baz', 'foo', 'foo'])
idx1 = np.array(['one', 'two', 'three', 'one', 'one', 'two'])
df = pd.DataFrame(index = [idx0, idx1], columns = ['A', 'B'])
s = pd.Series([True, False, True],index = np.unique(idx0))
print df
print s

out:
             A    B
bar one    NaN  NaN
    two    NaN  NaN
    three  NaN  NaN
baz one    NaN  NaN
foo one    NaN  NaN
    two    NaN  NaN

bar     True
baz    False
foo     True
dtype: bool

These don't work:
df.A = s # does not raise an error, but does nothing
df.loc[s.index,'A'] = s # raises an error

expected output:
             A     B
bar one    True   NaN
    two    True   NaN
    three  True   NaN
baz one    False  NaN
foo one    True   NaN
    two    True   NaN

A: Series (and dictionaries) can be used just like functions with map and apply (thanks to @normanius for improving the syntax):
df['A'] = pd.Series(df.index.get_level_values(0)).map(s).values

Or similarly:
df['A'] = df.reset_index(level=0)['level_0'].map(s).values

Results:
A    B
bar one     True  NaN
    two     True  NaN
    three   True  NaN
baz one    False  NaN
foo one     True  NaN
    two     True  NaN

A:
df.A = s does not raise an error, but does nothing

Indeed this should have worked.Your point is actually related to mine.
ᐊᐊ The workaround ᐊᐊ
>>> s.index = pd.Index((c,) for c in s.index)  # ᐊᐊᐊᐊᐊᐊᐊᐊ
>>> df.A = s
>>> df
               A    B
bar one     True  NaN
    two     True  NaN
    three   True  NaN
baz one    False  NaN
foo one     True  NaN
    two     True  NaN

Why does the above work ?
Because when you do directly df.A = s without the workaround, you are actually trying to assign pandas.Index-contained coordinates within a subclass instance,which somehow looks like a "counter-opposition" to the LS principle i.e. an instance of pandas.MultiIndex. I mean, look for yourself:
>>> type(s.index).__name__
'Index'

whereas
>>> type(df.index).__name__
'MultiIndex'

Hence this workaround that consists in turning s's index into a 1-dimensional pandas.MultiIndex instance.
>>> s.index = pd.Index((c,) for c in s.index)
>>> type(s.index).__name__
'MultiIndex'

and nothing has perceptibly changed
>>> s
bar     True
baz    False
foo     True
dtype: bool

A thought: From many views (mathematical, ontological) all this somehow shows that pandas.Index should have been designed as a subclass of pandas.MultiIndex, not the opposite, as it is currently.

A: You can use the join method on the df DataFrame, but you need to name the indexes and the series accordingly:
>>> df.index.names = ('lvl0', 'lvl1')
>>> s.index.name = 'lvl0'
>>> s.name = 'new_col'

Then the join method creates a new column in the DataFrame:
>>> df.join(s)
              A    B  new_col
lvl0 lvl1
bar  one    NaN  NaN     True
     two    NaN  NaN     True
     three  NaN  NaN     True
baz  one    NaN  NaN    False
foo  one    NaN  NaN     True
     two    NaN  NaN     True

To assign it to an existing column:
>>> df['A'] = df.join(s)['new_col']
>>> df
                A    B
lvl0 lvl1
bar  one     True  NaN
     two     True  NaN
     three   True  NaN
baz  one    False  NaN
foo  one     True  NaN
     two     True  NaN


text:
Q: How to install CorePlot framework correctly? I want to use CorePlot.framework in Mac OS X. However, I cannot install it correctly though it has costed me several hours.
I downloaded it (0.4 version) from google host site, and have tried to put CorePlot.framework  in "/Library/Frameworks/" or some other custom places.
I also have added it into "link binary and libraries". unfortunately, the compiler always cannot find "" .
Any one who have some experience can give me some advice to install and use it?

A: If you check the readme files, you can find the instructions as follows:

*

*Copy the CorePlotHeaders to your Xcode project

*Copy libCorePlotCocoaTouch.a to your Xcode project

*Add to Other Linker Flags in your target build settings: -ObjC -all_load

*Add the QuartzCore framework to the project.
To follow these instructions, create a new blank project and copy the folder (drag and drop) CorePlotHeaders into Xcode. When prompted, be sure to check "copy these files/folders to the source directory".
Next drag the libCorePlayCocoaTouch.a library in the same manner (again, select the checkbox). You should now have the .h files and the .a included in your project.
Now, select your project and choose the "Target" and in the 3rd tab "Build Settings" search for "Other Linker Flags" and add -"ObjC -all_load" without quotes.
Finally, add the QuartzCore framework to your project and you're done.
I've been working with CorePlot today and am rather impressed with it so far. It's not 100% comprehensive but it's good enough for what we need. If you get stuck, be sure to follow the readme instructions and double check everything is setup as needed. I didn't struggle with getting it set up unlike some other libraries so hopefully you should be able to get sorted with minimal fuss :)


text:
Q: Is there a difference between TDD and Test First Development (or Test First Programming)? Both ideas sound very similar to me, but there might be subtle differences or the exact same thing, explained in different ways. What is the relationship between TDD and Test First Development/Programming?

A: Historically Correct: Test-First Programming and Test-Driven Development mean Same Thing with an Improved Name
In the context of XP (Extreme Programming), which is the software development process that made Test-First Programming and Test-Driven Development popular, Test-First Programming was renamed to Test-Driven Development and then Test-Driven Design following the realization that writing tests first has a tremendously positive effect on the software architecture and design of a software system.
This influence on architecture and design is a consequence of more or less surprising synonyms:

*

*Testable

*Decoupled

*Reusable

*Independently Deployable

*Independently Developable

*Independently Reasonable

Software entities can only be easily reused, tested, deployed independently, developed independently, or easily reasoned separately if they are decoupled. Writing tests before the actual implementation is an almost bullet-proof method to ensure continuous decoupling.
This influence on software design and architecture became so important besides the other positive effects that the creators found it worthwhile renaming it from Test-First Programming to Test-Driven Development.
The name Test-Driven Development also helps marketing the method better in terms of acceptance as well as proper understanding because the name Test-Driven Development emphasises better on the holistic aspects of the method than Test-First Programming.
Not Historically Correct but Useful
While historically not correct, I find the following distinction very useful:
Test-First Programming…
…is any method in which tests for the code under test are written before the code under test.
Test-Driven Development…
…is a specific subset of Test-First Programming that follows the 3 Laws of Test-Driven Development as described by Robert C. Martin:

*

*You can't write any production code until you have first written a failing unit test.

*You can't write more of a unit test than is sufficient to fail, and not compiling is failing.

*You can't write more production code than is sufficient to pass the currently failing unit test.
  — Robert C. Martin, The Three Laws of Test-Driven Development

Following these three rules puts you in what is called the Red-Green-Refactor cycle.
1. You write a failing test.
2. You make it pass.
3. Now that it passes, you can refactor mercilessly before writing the next failing test.
Note that refactoring safely requires tests. Refactoring means changing the structure of source code without changing the significant behavior. But how do we know that we haven't accidentally altered significant behavior? What defines significant behavior? That's one of the many things for which tests are useful.
BTW if your tests get in the way of refactoring, your tests are too low-level, too tightly coupled, and maybe you've used too much mocking.
Other interesting renames in Extreme Programming

*

*Continuous Integration -> Continuous Delivery -> Continuous Deployment; Strictly speaking they mean different things, however, in the spirit of XP, it meant Continuous Deployment from the start, and when people jumped on the bandwagon, it was realized that integration was taken too literally and people stopped before they are done.

*Continuous Refactoring -> Continuous Design Improvement; Refactoring is not a means to an end in itself, but follows a higher purpose.

*40 hours week -> Sustainable Pace (Urban legend: This rename happened after protests by French software developers.)

A: There's a difference in terms of what the driving factor is.
Do you have a vague idea of what the class (or system - this can happen at different scales, of course) should look like, then think up tests which give it the actual shape? That's TDD.
Do you know exactly what the public API of the class should be, and just write the tests before the implementation? That's test-first development.
My style tends to be a mixture of the two. Sometimes it's obvious what the API should be before writing any tests - in other cases testability really drives the design.
To put it another way, TDD starts with "What questions do I want to ask?" whereas non-TDD (whether test first or not) starts with "What answer do I want to give?"

A: They are basically different names describing the same thing - well, in fact five names, as the last D can stand for Design as well as for Development.
Test First was the term used originally, especially in the context of Extreme Programming, for the test-code-refactor cycle. The name Test Driven Development has been proposed - and quickly adopted - later, to stress the fact that TFD is - and always has been - more of a design strategy than a testing strategy.
Obviously today some people have different connotations for those two terms, but that wasn't the intent behind their existance, and I wouldn't rely on it being common knowledge (because it's not). In fact, I'd rather see the term TFD as being deprecated.

A: In Test Driven Development: By Example, the author, Kent Beck, clearly states that "test first" (TF) is the rule. So TF is the principle that rules TDD. The later one is the process.

A: The are a lot of similar terms like test-first programming, test-first development, test-driven development or even test-driven design. It is important to clarify a few points:
1. Test First Programming (TFP)
The term test-first programming is a programming best practice. It was reintroduced (if not coined) by Kent Beck in his book "Extreme Programming Explained": "Write unit tests before programming and keep all of the tests running at all times". So, when talking about test-first programming we are talking about writing automated unit tests by the very developer that is going to write the code to satisfy those tests. The unit tests pile up and build an automated regression test suite that could be run periodically.
2. Test Driven Development (TDD)
Test-driven development (TDD) is the name of a methodology introduced by Kent Beck in his book "Test Driven Development by Example". It is a software development process, it is not only about writing tests before code. The whole book is trying to explain it by patterns, workflows, culture and so forth. One important aspect of it is the emphasis on refactoring.
Some people use the terms test-first development, test-driven design, or test-driven programming and ... One thing is for sure: the well established methodology is test-driven development and the programming technique is test-first programming. The rest are either generally referring to the idea of writing tests before code or mistakenly referring to test-driven development or test-first programming.

A: TDD = TFD + Refactoring.
When you do TFD , you apply some refactoring to make code more generic and robust.

A: TDD (Test Driven Development) is Test First Development/Programming although I have seen and heard TDD used to mean creating persistent, repeatable unit tests (even after the code), but really it implies the tests are written before the code they are testing.

A: They are exactly the same thing. Both reference writing tests first, then writing the code that will pass the test


text:
Q: Command execution elapsed time in jshell I looked for an option to have jshell report the execution time of a command, but I could not find any.
Then my question is what is the best way to have elapsed time reported when submitting a command for execution in jshell?
Example
To check the time required to perform 100k string concatenations (e.g. to compare to StringBuffer.append())
My basic solution is:
/reset
/set feedback verbose
int i;
long t0;
String s="";
for(t0=System.nanoTime(),i=0; i<100000; ++i){
s+=i;
} long elapsed=System.nanoTime()-t0;

Where jshell executes the loop in a whole single step and prints the elapsed time after completing all iterations.
Then to compare to a different solution (using StringBuffer)
/reset
/set feedback verbose
int i;
long t0;
StringBuilder b=new StringBuilder();
for(t0=System.nanoTime(),i=0; i<100000; ++i){
b.append(i);
} long elapsed=System.nanoTime()-t0;

Is there a better, cleaner, smarter way?

PS: I know the measure you get with this approach is not accurate, though this is a quick way to get a rough idea


text:
Q: Clearing Angular Router queryParams Currently I have a displayed page, the URL thereof being the following:
http://localhost:4200/alert?sid=success
Inside that page there's an a link, as follows:
<a [routerLink]="['/']">Home</a>
I want the user to no longer see ?sid=success when they go back home. I tried using [queryParams]="{}" and [queryParamsHandling]="" with no success.

A: To remove ALL query parameters, do:
$location.search({});

To remove ONE particular query parameter, do:
$location.search('queryParam', null);


text:
Q: C# Any way slow down how fast HtmlWeb.Load() loads or bypass captcha? I am trying to scrape some web page but because HtmlWeb.Load() is so fast (I believe) it blocks me and asks me to do a captcha. Sometimes I can load it and other times I can't.
I'm wondering if there is any way to slow that down (maybe htmlweb has some built in methods/properties to do it? or maybe there's a way to limit the resources for my app so it purposely runs slow?). If that's not possible is there an easy-ish way to bypass captchas? Any tips/help would be greatly appreciated, thanks.

    As you were browsing, something about your browser made us think you might be a bot. There are a few reasons this might happen, including:

You're a power user moving through this website with super-human speed

You've disabled JavaScript and/or cookies in your web browser

A third-party browser plugin is preventing JavaScript from running.

A: You think it's because you're loading a single page too fast, but that's not at all what they're telling you. You're switching between pages far too quickly to be a human. And/Or, as I suspect your app may be doing, you're not loading JavaScript in your program. And/Or you're not handling cookies.
Any or all of these three things can be signs of bot activity. Which you are by the way. So they throw a captcha up because they don't want bots trying to crawl their site. You're not going to bypass captcha easily for sure, so your best bet is to address the actual issues they lay out in the message.

*

*Slow down the time between page loads to something more realistic for humans browsing. You might still get snagged if you're going over their entire site in a non-human fashion though.

*Handle whatever cookies they're trying to set so that you look like a normal user. A few  successive no-cookie hits to the site from the same IP might not set off a flag, but a few dozen to hundreds will.

*If those don't work, perhaps they're really insistent on JavaScript elements loading on their site, and you'll have to find a way to make your app run the JavaScript pieces so that it doesn't look like you're a bot.

But to sum it up, you're a bot, and their system is working as intended.


text:
Q: Retaining work emails on office exchange server - iPhone I am considering leaving my current employer as the ethics practiced there are not the ones I grew up with (being kind). I have a work email account on my personal iPhone where I have all my prior email messages that I would like to retain access to, as they will tend to prove any point I may need to make re:ethics.
Can the office limit my access to these emails that seem to be resident on my phone? If so, how can I archive them for later viewing?
I am not looking to keep access to the account and use the email for any new messages, I simply want to be able to access messages already received/sent/forwarded, etc...
A few years ago, I had another business email account where I switched departments and lost access to the earlier emails after upgrading my phone (the new phone attempted to access those emails with the earlier ID/Password combo but since it wasn't active, I lost them - although they are still on my Mac.)
I guess my bottom line is, will an Exchange email account work in the same way? The emails I have on the phone presently, will remain on the phone, unless I switch devices? Or can an Exchange server actively limit access to the messages I have already received/sent/forwarded, etc...
I hope I have been clear - thank you all in advance.
Uncle Reggie

A: You need a lawyer's advice plus another job before you leave (or enough savings or enough support from family and friends to stay afloat) .  That being said, I won't get into the specifics in this Answer, because it involves legal matters, uncertainty of the programs and platforms you're using, and uncertainty of the security methods of your employer.  Of course, you won't be able to ask your employer or IT for assistance.
Don't assume that access getting cut off = you continue to keep the old emails.  Instead, intentionally save an external backup file of all of your emails, both Inbox and Sent.
Don't work on just the one platform.  Your phone was mentioned, but Android and iOS programs tend to keep small local caches instead of the whole set of your emails.  Instead, work on a desktop or laptop, using a standard email program to connect to the email server, download all emails, and make the backup file.  Put a date in the filename.
You will need to be certain that your backup contains ALL of the old messages, in their entirety.  Also be certain that your backup includes the whole message and also attachments, not just headers.  Frequently, email programs will load just the headers by default, and load the rest of the message online when requested.  Instead, you will need the whole thing.
Also, it sounds like you have multiple addresses.  Make separate backups of all of them.
Depending on how long you stay with the employer, you might make weekly backups.  If you find yourself there too long, ask yourself if you're protecting yourself, or getting dirt on someone else.


text:
Q: How do i get another window to recognize alt+ f4 key press I am trying to send alt + f4 combination from my c++ application to another window. I can get it to work for ctrl + c but when i try to close the application by sending the code below which is alt + f4 it isn't doing what i expect it to do. What is the correct combination for alt + f4?
INPUT ip;

ip.type = INPUT_KEYBOARD;
    ip.ki.wScan = 0; // hardware scan code for key
    ip.ki.time = 0;
    ip.ki.dwExtraInfo = 0;

ip.ki.wVk = VK_MENU;
   ip.ki.dwFlags = 0; // 0 for key press
   SendInput(1, &ip, sizeof(INPUT));

   ip.ki.wVk = VK_F4;
   ip.ki.dwFlags = 0; // 0 for key press
   SendInput(1, &ip, sizeof(INPUT));

   ip.ki.wVk = VK_MENU;
   ip.ki.dwFlags = KEYEVENTF_KEYUP;
   SendInput(1, &ip, sizeof(INPUT));

   ip.ki.wVk = VK_F4;
   ip.ki.dwFlags = KEYEVENTF_KEYUP;
   SendInput(1, &ip, sizeof(INPUT));


text:
Q: Repeatcolumn property of DataList I am using a DataList to render some divs in table layout and RepeatColumn property set to 3.
when my datasource has 3 or more than 3 records it works correctly and renders 3 columns and as many required rows.
But when my datasource contains one or two records it renders only one or two columns respectively, so violating standard of site.
Is there any way of padding so that if my datasource contains one record then other two columns will be generated automatically(of-course empty) or if datasource contains two records then third column will be generated automatically.

A: Just make sure you always have at least three items in your datasource before you bind it.
Some psuedo-code should suffice:
datasource = GetDatasourceMethod();
while(datasource.Count <= 3) {
    datasource.Add(emptyItem);
}
datalist.DataSource = dataSource;
datalist.DataBind();

A: Add ItemStyle Width ="25%" to get 4 columns

          " data-model="<%# ParameterModel(Container.ItemIndex) %>"><%# Eval("Name") %>
</ItemTemplate>


text:
Q: Python: Creating a movie from a list of pictures Currently I have a process that creates a series of pictures and I then save them into a folder.
Is there a way that I can create a movie from them, say in 1 second, or 2 second intervals?
For example, I found this example from the matplotlib website:
from __future__ import print_function

import os
import matplotlib.pyplot as plt
import numpy as np

files = []
fig, ax = plt.subplots(figsize=(5, 5))
for i in range(50):  # 50 frames
    plt.cla()
    plt.imshow(np.random.rand(5, 5), interpolation='nearest')
    fname = '_tmp%03d.png' % i
    print('Saving frame', fname)
    plt.savefig(fname)
    files.append(fname)

print('Making movie animation.mpg - this make take a while')
os.system("mencoder 'mf://_tmp*.png' -mf type=png:fps=10 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o animation.mpg")
#os.system("convert _tmp*.png animation.mng")

# cleanup
for fname in files:
    os.remove(fname)

When I look at the folder that the notebook is in, I see the images being created. However, I don't see an animation.mpg being created anywhere.
What am I doing wrong?


text:
Q: Push Notifications without alert Can I get push notifications without alert view?
The idea in what service for game will send notifications as response for change game state (may be game state will store in database), if this is impossible, what you can suggest about how me send new game state to each connected game client as response of changing game state.
Game will be developing for iPad.
Thanks,
Roman

A: Use content-available property:

The aps dictionary can also contain the content-available property. The content-available property with a value of 1 lets the remote notification act as a "silent" notification. When a silent notification arrives, iOS wakes up your app in the background so that you can get new data from your server or do background information processing. Users aren't told about the new or changed information that results from a silent notification, but they can find out about it the next time they open your app.

https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html

A: Why not!
You can send a hidden push notification without any alert, banner or sound.
PHP CODE
without a text:
$payload['aps'] = array('badge'=> 0, 'sound' => 'default');

Without text and sound
$payload['aps'] = array('badge'=> 0);

and on your ios end you can make a condition for this:
//Receiving a Push Notification
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSMutableDictionary *pushNotiFicationDict = [userInfo objectForKey:@"aps"];
    NSLog(@":%@", pushNotiFicationDict);

    if([pushNotiFicationDict objectForKey:@"alert"])
    {
        // when push notification has text
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"MESSAGE" message:[pushNotiFicationDict objectForKey:@"alert"]
                                                        delegate:nil
                                               cancelButtonTitle:@"ok"
                                               otherButtonTitles:nil];
        [alert show];
    }
    else
    {
        // when push notification does not have text
    }
}

But i think you can not perform any action if application is not running or running in background.

A: No, a push notification will always display a notification as it requires user consent to wake up or launch your application. However if your Application is in the foreground and running, the push notification will not appear and your app can handle the message that the  push notification has. All of the preceding applies to local notifications aswhile.
I don't know what you mean by game state. But just have your app listen in on a script on your server which will pass information to your app. Edit: Or like I said above if your app is open in the foreground, push notifications won't appear on screen and you can send information that way. However if you want to do it in the background its not possible no matter what unless you are truly multitasking (GPS, VOIP, Music) or you have user consent through push notification.

A: For me @Ajay answer is not correct (sorry).
With push notification you can choose between three user options: text message (alerts), sounds and badges. Every push notification can contain one or more of these options, so you can send for example a notification with sound and badge, but without message and in this case any alert is shown.
Note that you can even pass hidden options in a private dictionary to your application.

A: You can handle notifications in app and store data in DB, or instead show a message but when app is not running NO.

A: I agree with @MacTeo.  You can delivery a push notification with a payload that contains only one attribute (Sound, Alert (or message) and badge.
With your requirement, keep track of the users device on the server when they open and close the app (foreground and background).  If something happens then you can check to see the device's state on the server. You could then decide on how to construct a notification (if any is necessary) base on the last reported state of the device.
Just spitballing:
You could, if you wanted to (however, it isn't what the APNs is designed to do), deliver a push notification with only a badge count = 0 and pass some extra dictionary data with it.  That would not alert the user and could be handled in the app if it was in the foreground.


text:
Q: how to modify a row that is read from sql table I have a table in PHP where want modify its cells, by clicking on Update link and it should send the data of the selected row to modify and update
I've been looking for examples but I can't find anything,and very new to php. Any help will be very useful.
while($row=mysqli_fetch_array($result)) {
    echo
'

    <form name="frmRow" method="post"   action="update.php?id='.$row['id'].' ">

    Update
    Delete
    '.$row['name1'].'
    '.$row['name2'].'
    '.$row['name3'].'
    '.$row['id'].'

   </form>

';
}

The table is filled with data from a mysql table
and  this is update.php
<?php

require_once('config/config.php');

if(isset($_GET['id']))
{

    $sql='update TABLE set name1="'.$_POST['name1'].'" ,
    name2=="'.$_POST['name2'].'" , name3=='.$_POST['name3'].'
    where id='.$_POST['id'].'    ';
    mysqli_query($connect,$sql);0
}

?>

but GET['id']  and $_POST are always empty.

A: I would not echo out your form as a string.  A foreach loop can print plain html and php in the same iteration.  Second, you need to have input boxes.
//  You wont need this if you do the while loop the way you original had it
$rows = mysqli_fetch_array($result);

foreach($rows as $row) {
// or your original method while($row = mysqli_fetch_array($result)){
<form method="post" action="update.php">

   <button type="submit">Submit</button>
   <a href="delete.php?id=<?php echo $row['id']; ?>">Delete
   <input name='name1' value="<?php echo $row['name1']; ?>">
   <input name='name2' value="<?php echo $row['name2']; ?>">
   <input name='name3' value="<?php echo $row['name3']; ?>">
   <input name='id' value="<?php echo $row['id']; ?>">

</form>
}

Also remove action="update.php?id='.$row['id'].' and just make it action="update.php' for both get and post methods.
Note: if there is no value you need to be able handle that while looping through your results
Note:  As some comments have already mentioned, you can not grab from post with $_GET and vice versa


text:
Q: Crashing Fragment I am making a webview browser that uses sliding menu fragments. When I open this fragment then the app crashes. I am new to fragments so I apologize if this is nooby. If there's anything else I can do to help with this then just ask.
Below is the fragment class
public class WhatsHotFragment extends Fragment {

public WhatsHotFragment(){}

WebView WebViewB;
ProgressBar Pbar6;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_whats_hot, container, false);

    Pbar6 = (ProgressBar) getView().findViewById(R.id.progBar6);
    WebViewB = (WebView) getView().findViewById(R.id.wvBrowserAesir);

    WebSettings webSettings = WebViewB.getSettings();
    webSettings.setJavaScriptEnabled(true);
    WebViewB.getSettings().setLoadWithOverviewMode(true);
    WebViewB.getSettings().setUseWideViewPort(true);
    WebViewB.getSettings().setBuiltInZoomControls(true);
    WebViewB.getSettings().setAllowFileAccess(true);

    WebViewB.setWebViewClient(new InsideWebViewClient());
    WebViewB.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress)
           {
           if(progress < 100 && Pbar6.getVisibility() == ProgressBar.VISIBLE){
               Pbar6.setVisibility(ProgressBar.VISIBLE);
           }
           Pbar6.setProgress(progress);
           if(progress == 100) {
               Pbar6.setVisibility(ProgressBar.VISIBLE);
           }
           }
       });
        {
            WebViewB.loadUrl("http://www.google.com");
        }

    return rootView;
}
}

Thanks in advance!

A: Change to
  Pbar6 = (ProgressBar) rootView.findViewById(R.id.progBar6);
  WebViewB = (WebView) rootView.findViewById(R.id.wvBrowserAesir);

You can also use getView().findViewById in onActivityCreated to initialize your views.


text:
Q: s3 chunked uploads with blueimp.fileupload I'm implementing AWS chunked uploads using the blueimp plugin, and I've run into a problem in the event ordering.
Instead of Content-Range (presence of which causes Amazon to immediately throw a 403), S3 uses an upload ID and part number query parameters.
So before each chunk, I need to reach out to my signing service and change the url of the next chunk.
It doesn't appear that options.chunksend blocks the event system like options.add, so my next chunk is sent to the same URL as the first chunk (set in options.add), overwriting it.
How can I block the send of a chunk so I can change the url?

A: The chunksend event and the call to upload the chunk are simultaneous. I overrode this section of https://github.com/blueimp/jQuery-File-Upload/blob/master/js/jquery.fileupload.js:
            that._initProgressListener(o);
            jqXHR = ((that._trigger('chunksend', null, o) !== false && $.ajax(o)) ||
                    that._getXHRPromise(false, o.context))
                .done(function (result, textStatus, jqXHR) {

to
            that._initProgressListener(o);
              o.uploadPromise = $.Deferred();
              that._trigger('chunksend', null, o);
              o.uploadPromise.done(function() {
                  jqXHR = ((that._trigger('stillneeded', null, o) !== false && $.ajax(o)) ||
                          that._getXHRPromise(false, o.context))
                      .done(function (result, textStatus, jqXHR) {

And then resolve the promise in my chunksend event handler.


text:
Q: Access JSON_encode array objects I have a problem access values from array objects.
From PHP I send my array of objects like this
initiate_data(".json_encode($my_array).");

From javascript to check the array I have this code
function initiate_data(my_array){
window.alert(my_array);}

The data I have is
{'name':'name1','surname':'surname1','email':'email1'},{'name':'name2','surname':'surname2','email':'email2'},{'name':'name3','surname':'surname3','email':'email3'}

I am also able to access the first object
window.alert(my_array[0]);

The result is
{'name':'name1','surname':'surname1','email':'email1'}

My problem is that I cannot access name from the object.
I have tried (my_array[0].name) and I get undefined
I googled for the solution but I cannot get a solution specific to my problem
when I try to access my_array[0][0] the result {
Thank you for your help thus far
console.log gives me this
["{"rec":"1","name":"Home","code":"mmenu_home","type":"1","level":"0","default_view":"show_post"}", "{"rec":"2","name":"Home","code":"mmenu_home","type":"2","level":"0","default_view":"show_post"}", "{"rec":"3","name":"Home","code":"mmenu_home","type":"3","level":"1","default_view":"show_post"}", "{"rec":"4","name":"Home","code":"mmenu_home","type":"3","level":"2","default_view":"show_post"}", "{"rec":"5","name":"Home","code":"mmenu_home","type":"3","level":"3","default_view":"show_post"}", "{"rec":"6","name":"Home","code":"mmenu_home","type":"3","level":"4","default_view":"show_post"}", "{"rec":"7","name":"Home","code":"mmenu_home","type":"3","level":"5","default_view":"show_post"}", "{"rec":"8","name":"Home","code":"mmenu_home","type":"3","level":"6","default_view":"show_post"}", "{"rec":"9","name":"Home","code":"mmenu_home","type":"4","level":"0","default_view":"show_post"}", "{"rec":"10","name":"Opporunities","code":"mmenu_op…":"1","level":"0","default_view":"show_opp_tips"}", "{"rec":"11","name":"Careers","code":"mmenu_careers…e":"1","level":"0","default_view":"show_careers"}", "{"rec":"12","name":"Tertiary","code":"mmenu_tertia…":"1","level":"0","default_view":"show_tertiary"}", "{"rec":"13","name":"News","code":"mmenu_news","type":"1","level":"0","default_view":"show_news"}", "{"rec":"14","name":"News","code":"mmenu_news","type":"2","level":"0","default_view":"show_news"}", "{"rec":"15","name":"News","code":"mmenu_news","type":"3","level":"1","default_view":"show_news"}", "{"rec":"16","name":"News","code":"mmenu_news","type":"3","level":"2","default_view":"show_news"}", "{"rec":"17","name":"News","code":"mmenu_news","type":"3","level":"3","default_view":"show_news"}", "{"rec":"18","name":"News","code":"mmenu_news","type":"3","level":"4","default_view":"show_news"}", "{"rec":"19","name":"News","code":"mmenu_news","type":"3","level":"5","default_view":"show_news"}", "{"rec":"20","name":"News","code":"mmenu_news","type":"3","level":"6","default_view":"show_news"}", "{"rec":"21","name":"News","code":"mmenu_news","type":"4","level":"0","default_view":"show_news"}", "{"rec":"22","name":"Profile","code":"mmenu_profile…e":"1","level":"0","default_view":"show_profile"}", "{"rec":"23","name":"Profile","code":"mmenu_profile…e":"2","level":"0","default_view":"show_profile"}", "{"rec":"24","name":"Profile","code":"mmenu_profile…e":"3","level":"1","default_view":"show_profile"}", "{"rec":"25","name":"Profile","code":"mmenu_profile…e":"3","level":"2","default_view":"show_profile"}", "{"rec":"26","name":"Profile","code":"mmenu_profile…e":"3","level":"3","default_view":"show_profile"}", "{"rec":"27","name":"Profile","code":"mmenu_profile…e":"3","level":"4","default_view":"show_profile"}", "{"rec":"28","name":"Profile","code":"mmenu_profile…e":"3","level":"5","default_view":"show_profile"}", "{"rec":"29","name":"Profile","code":"mmenu_profile…e":"3","level":"6","default_view":"show_profile"}", "{"rec":"30","name":"Profile","code":"mmenu_profile…e":"4","level":"0","default_view":"show_profile"}", "{"rec":"31","name":"SMS","code":"sms_send_function…"type":"3","level":"2","default_view":"sms_home"}", "{"rec":"32","name":"SMS","code":"sms_send_function…"type":"3","level":"5","default_view":"sms_home"}", "{"rec":"33","name":"SMS","code":"sms_send_function…"type":"3","level":"6","default_view":"sms_home"}", "{"rec":"34","name":"Learners","code":"learners_mme…":"3","level":"2","default_view":"view_learners"}", "{"rec":"35","name":"Learners","code":"learners_mme…":"3","level":"3","default_view":"view_learners"}", "{"rec":"36","name":"Learners","code":"learners_mme…":"3","level":"4","default_view":"view_learners"}", "{"rec":"37","name":"Learners","code":"learners_mme…":"3","level":"5","default_view":"view_learners"}", "{"rec":"38","name":"Learners","code":"learners_mme…":"3","level":"6","default_view":"view_learners"}", "{"rec":"39","name":"Parents","code":"parents_mmenu…e":"3","level":"2","default_view":"view_parents"}", "{"rec":"40","name":"Parents","code":"parents_mmenu…e":"3","level":"3","default_view":"view_parents"}", "{"rec":"41","name":"Parents","code":"parents_mmenu…e":"3","level":"4","default_view":"view_parents"}", "{"rec":"42","name":"Parents","code":"parents_mmenu…e":"3","level":"5","default_view":"view_parents"}", "{"rec":"43","name":"Parents","code":"parents_mmenu…e":"3","level":"6","default_view":"view_parents"}", "{"rec":"44","name":"Staff","code":"staff_function"…:"3","level":"2","default_view":"staff_view_all"}", "{"rec":"45","name":"Staff","code":"staff_function"…:"3","level":"5","default_view":"staff_view_all"}", "{"rec":"46","name":"Staff","code":"staff_function"…:"3","level":"6","default_view":"staff_view_all"}", "{"rec":"47","name":"SGB","code":"sgb_home","type":"3","level":"2","default_view":"sgb_view_all"}", "{"rec":"48","name":"SGB","code":"sgb_home","type":"3","level":"5","default_view":"sgb_view_all"}", "{"rec":"49","name":"SGB","code":"sgb_home","type":"3","level":"6","default_view":"sgb_view_all"}", "{"rec":"50","name":"Photos","code":"photos_mmenu",…vel":"2","default_view":"view_all_websitephotos"}", "{"rec":"51","name":"Photos","code":"photos_mmenu",…vel":"5","default_view":"view_all_websitephotos"}", "{"rec":"52","name":"Photos","code":"photos_mmenu",…vel":"6","default_view":"view_all_websitephotos"}", "{"rec":"53","name":"Departments","code":"mm_depart…3","level":"2","default_view":"view_departments"}", "{"rec":"54","name":"Departments","code":"mm_depart…3","level":"5","default_view":"view_departments"}", "{"rec":"55","name":"Departments","code":"mm_depart…3","level":"6","default_view":"view_departments"}", "{"rec":"56","name":"Academic","code":"mm_academic"…":"3","level":"2","default_view":"view_academic"}", "{"rec":"57","name":"Academic","code":"mm_academic"…":"3","level":"5","default_view":"view_academic"}", "{"rec":"58","name":"Academic","code":"mm_academic"…":"3","level":"6","default_view":"view_academic"}", "{"rec":"59","name":"Term","code":"mm_term","type":"1","level":"0","default_view":"view_term"}", "{"rec":"60","name":"Term","code":"mm_term","type":"2","level":"0","default_view":"view_term"}", "{"rec":"61","name":"Term","code":"mm_term","type":"3","level":"1","default_view":"view_term"}", "{"rec":"62","name":"Term","code":"mm_term","type":"3","level":"2","default_view":"view_term"}", "{"rec":"63","name":"Term","code":"mm_term","type":"3","level":"3","default_view":"view_term"}", "{"rec":"64","name":"Term","code":"mm_term","type":"3","level":"4","default_view":"view_term"}", "{"rec":"65","name":"Term","code":"mm_term","type":"3","level":"5","default_view":"view_term"}", "{"rec":"66","name":"Term","code":"mm_term","type":"3","level":"6","default_view":"view_term"}", "{"rec":"67","name":"Sports","code":"mm_sports","type":"1","level":"0","default_view":"view_sports"}", "{"rec":"68","name":"Sports","code":"mm_sports","type":"2","level":"0","default_view":"view_sports"}", "{"rec":"69","name":"Sports","code":"mm_sports","type":"3","level":"1","default_view":"view_sports"}", "{"rec":"70","name":"Sports","code":"mm_sports","type":"3","level":"2","default_view":"view_sports"}", "{"rec":"71","name":"Sports","code":"mm_sports","type":"3","level":"3","default_view":"view_sports"}", "{"rec":"72","name":"Sports","code":"mm_sports","type":"3","level":"4","default_view":"view_sports"}", "{"rec":"73","name":"Sports","code":"mm_sports","type":"3","level":"5","default_view":"view_sports"}", "{"rec":"74","name":"Sports","code":"mm_sports","type":"3","level":"6","default_view":"view_sports"}", "{"rec":"75","name":"Timetable","code":"mm_timetabl…:"1","level":"0","default_view":"view_belltimes"}", "{"rec":"76","name":"Timetable","code":"mm_timetabl…:"2","level":"0","default_view":"view_belltimes"}", "{"rec":"77","name":"Timetable","code":"mm_timetabl…:"3","level":"1","default_view":"view_belltimes"}", "{"rec":"78","name":"Timetable","code":"mm_timetabl…:"3","level":"2","default_view":"view_belltimes"}", "{"rec":"79","name":"Timetable","code":"mm_timetabl…:"3","level":"3","default_view":"view_belltimes"}", "{"rec":"80","name":"Timetable","code":"mm_timetabl…:"3","level":"4","default_view":"view_belltimes"}", "{"rec":"81","name":"Timetable","code":"mm_timetabl…:"3","level":"5","default_view":"view_belltimes"}", "{"rec":"82","name":"Timetable","code":"mm_timetabl…:"3","level":"6","default_view":"view_belltimes"}"]

Additional Info**
The php class implements JsonSerializable and I have created a array of the object, I hope this will help in clarifying my problem
Temporary Fix
Although they might be a better way to do it, this is what I have done to solve the problem
var my_obj = JSON.parse(my_array[0]);

Now I am able to access name
console.log(my_obj.name);

Gives me name1
Temporary Fix, Until I am able to pass all the array to a variable.

A: Looks like your $my_array contains json strings:
$my_array = array(
    '{"name":"name1","surname":"surname1","email":"email1"}',
    '{"name":"name2","surname":"surname2","email":"email2"}',
    '{"name":"name3","surname":"surname3","email":"email3"}'
);

If it is the case, you can create javascript array of it by simple implode and add brackets:
initiate_data([".implode(',',$my_array)."]);

A: is the json well encoded??
http://jsonlint.com/
{
"obj1": {
    "name": "name1",
    "surname": "surname1",
    "email": "email1"
},
"obj3": {
    "name": "name1",
    "surname": "surname1",
    "email": "email1"
},
"obj2": {
    "name": "name1",
    "surname": "surname1",
    "email": "email1"
}
}


text:
Q: Intel MKL function cblas_sgemv gives different results each time I used Intel MKL's function cblas_sgemv to do matrix-vector multiplication but this function gives different results each time. Sometimes this can give the correct result (with 1e-6 error in L2 norm compared with the reference result).
I have checked that the inputs of this function are the same each time and I just use this function according to this document.
My code is as follows:
cblas_sgemv(CblasRowMajor, Trans, M, N, alpha, A, lda, x, incx, beta, y, incy);

Hope someone can shed some light.

A: I have solved the problem. The solution can be found here.


text:
Q: Partition dataframe to overlapping segments I have a dataframe with time indices and need to partition it into overlapping segments (say 5 days in length with 1 day offset).
Here is a sample dataframe:
import pandas as pd
i=pd.date_range('05-01-2015', '21-05-2018', freq='D')
x=pd.DataFrame(index=i, data = np.random.randint(0, 100, len(i)))

After partitioning the indices of the segments should range respectively from 2015-05-01 to 2015-05-05, from 2015-05-02 to 2015-05-06, from 2015-05-03 to 2015-05-08 etc. I assume there should be some trick with groupby to do it, but couldn't come up with an efficient implementation.
As a reference, this is implemented in mathematica:
Partition[list,n,d] - generates sublists with offset d.
I would greatly appreciate any insight you guys can provide.

A: As @alkasm pointed out, you can perform aggregate calculations on 5-day partitions using your sample dataframe using rolling in pandas:
import pandas as pd
i = pd.date_range('05-01-2015', '21-05-2018', freq='D')
x = pd.DataFrame(index=i, data = np.random.randint(0, 100, len(i)))

x.rolling(5).sum()

The trick with this is, it calculates the aggregate function looking backwards, so you may need to expand your index to include the four days prior. A row in your dataframe with index 2018-05-06 with a 5-row rolling() call would represent the segment 2018-05-02 to 2018-05-06 inclusive (which is 5 days).


text:
Q: WLST execute stored variable "connect()" statement So, I am passing a environment variable from bash to python;
#!/usr/bin/env python2
import os

#connect("weblogic", "weblogic", url=xxx.xxx.xxx.xxx:xxxx)
os.environ['bash_variable']

via wlst.sh I can print exported bash_variable, but how do I execute stored variable?  Basically, I am trying to remove the original connect statement and pass a variable that has said information.  Thanks

A: Question though, why wouldn't you called the script with the variable as an argument and use sys.argv[] ?
By example something like this.
import os
import sys
import traceback
from java.io import *
from java.lang import *

wlDomain = sys.argv[1]
wlDomPath = sys.argv[2]
wlNMHost = sys.argv[3]
wlNMPort = sys.argv[4]
wlDPath="%s/%s" %(wlDomPath,wlDomain)
wlNMprop="/apps/bea/wls/scripts/.shadow/NM.prop"

try:
    print "Connection to Node Manager"
    print ""
    loadProperties(wlNMprop)
    nmConnect(username=NMuser,password=NMpass,host=wlNMHost,port=wlNMPort,domainName=wlDomain,domainDir=wlDPath,mType='ssl',verbose='true')
except:
    print "Fatal Error : No Connection to Node Manager"
    exit()

print "Connected to Node Manager"

The NM.prop file is a 600 file with the username/password for the NM.
EDIT :
So from what I understand you want to do something like this :
URLS = ['t3s://Host1:Port1','t3s://Host2:Port2','t3s://Host3:Port3']
for urls in URLS:
    connect('somebody','password',urls)
    {bunch of commands}
    disconnect()

And the values of the list URLS would be define by the environment.
The way I see it you have 3 choices :

*

*Have 1 script per environment, more or less identical save for the URLS list

*Have 1 script but with a conditionnal branching on sys.argv[1] (the environment as a parameter) and create the list there.

*Have 1 script which use a parameter file for each environment according to the environment. Each parameter file containing the list in question.

Something like that :
propENV = sys.argv[1]
propPath = "/path1/path2"
propFile = "%s/%s" %(propPath,propENV)

loadProperties(propFile)

I would probably use the properties file option myself as it is more flexible from an operational standpoint...at least IMHO.


text:
Q: scala range returns Long instead of Int I have the following code to print the numbers from 1 to 9 in letters
class IntToNumber(num:Int) {
    val digits = Map("1" -> "one", "2" -> "two", "3" -> "three", "4" -> "four", "5" -> "five", "6"  -> "six", "7" -> "seven", "8" -> "eight", "9" -> "nine")
    def inLetters():String = {
        digits.getOrElse(num.toString,"")
    }
}

implicit def intWrapper(num:Int) = new IntToNumber(num)
(1 until 10).foreach(n => println(n.inLetters))

When I run this code I get an error saying the method is not available for Long
Script.scala:9: error: value inLetters is not a member of Long
(1 until 10).foreach(n => println(n.inLetters))
                                    ^
one error found

Changing the last line to
(1 until 10).foreach(n => println(n.toInt.inLetters))

Works fine..
Can someone help me understand Why is that (1 until 10) range returning Long and not int?

A: I've changed the name of your implicit conversion to intWrapperX. The following session shows the fixed example.
The problem is, that your intWrapper shadows scala.Predef.intWrapper(i:Int): RichInt which is needed to create the Range object. I leave the explanation of why the conversion to Long (or presumable RichLong) kicks in to the commenters.
scala> :paste
// Entering paste mode (ctrl-D to finish)

class IntToNumber(num:Int) {
    val digits = Map("1" -> "one", "2" -> "two", "3" -> "three", "4" -> "four", "5" -> "five", "6"  -> "six", "7" -> "seven", "8" -> "eight", "9" -> "nine")
    def inLetters():String = {
        digits.getOrElse(num.toString,"")
    }
}

implicit def intWrapperX(num:Int) = new IntToNumber(num)

// Exiting paste mode, now interpreting.

defined class IntToNumber
intWrapperX: (num: Int)IntToNumber

scala> (1 until 10).foreach(n => println(n.inLetters))
one
two
three
...


text:
Q: How to duplicate manyToOne in doctrine yaml using the same Entity i want to get the users and employees from the same Entity and use them in the same Entity also.
manyToOne:
  User:
    targetEntity: \UserBundle\Entity\User
    joinColumn:
      name: user_id
      referencedColumnName: id

manyToOne:
  User:
    targetEntity: \UserBundle\Entity\User
    joinColumn:
      name: employee_id
      referencedColumnName: id

when i use the first part it works perfect and the second one don't seems to be working.  After i updated the schema still no employees.
What do you think guys should i do?
so it is also not working!
manyToOne:
  User:
    targetEntity: \UserBundle\Entity\User
    joinColumn:
      name: user_id
      referencedColumnName: id
    joinColumn:
      name: employee_id
      referencedColumnName: id

A: Considering Doctrine documentation :
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html

manyToOne:
  user:
    targetEntity: \UserBundle\Entity\User
    joinColumn:
      name: user_id
      referencedColumnName: id
  employee:
    targetEntity: \UserBundle\Entity\User
    joinColumn:
      name: employee_id
      referencedColumnName: id


text:
Q: lockscreen not available Ubuntu 20.04.2 My look screen is not working or even "not presented".
After reboot I can unlock the device but after that I cant lock it anymore
Super + L not working
gnome-screensaver-command -l not working, but I get

** (gnome-screensaver-command:6363): WARNING **: 10:22:19.218: unable to send message: Zeitüberschreitung wurde erreicht
** Message: 10:22:19.220: Did not receive a reply from the screensaver.

Auto lockscreen not working, although configured

I cant even choose a lockscreen image...

Whats that?

A: You check result with this command once
gsettings get org.gnome.desktop.lockdown disable-lock-screen

if result is true, then make it false like
gsettings set org.gnome.desktop.lockdown disable-lock-screen false

Source.


text:
Q: Python - How to insert '*' into a string after every nth character I'm currently stuck on this question that takes 2 arguments (string, and an int, n) and it should return a new string where every nth character (from 0) is followed by an '*'.
I've found similar questions on stack overflow but the answers include more advanced coding functions that I don't know how to use (like range(), emurate etc) as I just started out coding.
What the code supposed to do:
>>> string_chunks("Once upon a time, in a land far, far away", 5)
'O*nce u*pon a* time*, in *a lan*d far*, far* away*'

My code so far only prints out every 5th character from the string:
def string_chunks(string, x):
    new = ''
    for ch in string[::x]:
        new += ch
    return new

>>>'Ouae nrry'

I'm not sure if I'm supposed to use str.find()/str.split() in my code. It would be a great help if someone can help me improve or guide me. Thanks!

A: Your example seems incorrecnt. nth position meaning each index is a multiple of n.
But, if your phrasing is wrong, you can always shift n or cnt to make sure it matches your desired output.
You are not adding any starts in your function, just check if the position is a multiple of x, if yes then add a *.
def string_chunks(string, x):
    new = ''
    cnt = 0
    for ch in string:
        if cnt%x==0 and cnt!=0: # checking if cnt is a multiple of x and not 0, we don't want to put star at index 0
            new += '*'
        cnt += 1
        new += ch
    return new
string_chunks("Once upon a time, in a land far, far away", 5)

Out:
'Once *upon *a tim*e, in* a la*nd fa*r, fa*r awa*y'

A: def add_asterisk_every(string, n):
    # Create a list to hold the characters in the new string we'll be creating.
    with_asterisks = []

    # Keep track of how many characters we've passed since the last asterisk was added.
    characters_scanned = 0

    # Iterate through each character of the input string and add each character of the input string to with_asterisks.
    # Once we scan n characters, we'll add an asterisk and restart the counter.
    for character in string:
        if characters_scanned == n:
            with_asterisks.append('*')
            characters_scanned = 0
        characters_scanned += 1
        with_asterisks.append(character)

    # Create the output string from our character list.
    return ''.join(with_asterisks)

print(add_asterisk_every("Once upon a time, in a land far, far away", 5))

Which produces:
Once *upon *a tim*e, in* a la*nd fa*r, fa*r awa*y


text:
Q: Apache module in C: how to write data to client socket? I have created a simple mod_perl module, which writes a 0-terminated string to the Flash-clients connecting to the port 843. It works ok, but uses 20m per httpd-child at my CentOS 5 Linux machine.
So I'm trying to rewrite my module in C, but I'm not sure how to access the client socket through the conn_rec struct that my protocol handler receives.
I've asked at a mailing list and tried adding #define CORE_PRIVATE and using ap_get_module_config(conn->conn_config, &core_module) but this breaks my web server: the string is served both to port 843 (which is ok), but also to the port 80 (which is not ok).
Does anybody please have a suggestion here?
Here is my SocketPolicy.pm (works ok, but needs mucho memory):
package SocketPolicy;

# Listen 843
# <VirtualHost _default_:843>
#       PerlModule                   SocketPolicy
#       PerlProcessConnectionHandler SocketPolicy
# </VirtualHost>

use strict;
use warnings FATAL => 'all';
use APR::Const(-compile => 'SO_NONBLOCK');
use APR::Socket();
use Apache2::ServerRec();
use Apache2::Connection();
use Apache2::Const(-compile => qw(OK DECLINED));

use constant POLICY =>
qq{<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM
"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">

<cross-domain-policy>
<allow-access-from domain="*" to-ports="8080"/>
</cross-domain-policy>
\0};

sub handler {
        my $conn   = shift;
        my $socket = $conn->client_socket();
        my $offset = 0;

        # set the socket to the blocking mode
        $socket->opt_set(APR::Const::SO_NONBLOCK => 0);

        do {
                my $nbytes = $socket->send(substr(POLICY, $offset), length(POLICY) - $offset);
                # client connection closed or interrupted
                return Apache2::Const::DECLINED unless $nbytes;
                $offset += $nbytes;
        } while ($offset < length(POLICY));

        my $slog = $conn->base_server()->log();
        $slog->warn('served socket policy to: ', $conn->remote_ip());
        return Apache2::Const::OK;
}

1;

Here is my broken mod_socket_policy.c (hijacks the port 80):
/*
LoadModule socket_policy_module modules/mod_socket_policy.so
Listen 843
<VirtualHost _default_:843>
        SetHandler socket_policy
</VirtualHost>
*/

#include <httpd.h>
#include <http_protocol.h>
#include <http_connection.h>
#include <http_config.h>
#include <http_log.h>
#define CORE_PRIVATE
#include <http_core.h>

#define POLICY "<?xml version=\"1.0\"?>\n" \
               "<!DOCTYPE cross-domain-policy SYSTEM\n" \
               "\"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd\">\n" \
               "<cross-domain-policy>\n" \
               "<allow-access-from domain=\"*\" to-ports=\"8080\"/>\n" \
               "</cross-domain-policy>\0"

static int socket_policy_handler(conn_rec *conn) {
        apr_socket_t *socket = ap_get_module_config(conn->conn_config, &core_module);
        apr_size_t len = strlen(POLICY);

        apr_socket_send(socket, POLICY, &len);

        ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, conn->base_server,
                "served socket policy to %s", conn->remote_ip);

        return OK;
}

static void register_hooks(apr_pool_t *pool) {
        ap_hook_process_connection(socket_policy_handler, NULL, NULL, APR_HOOK_MIDDLE);
}

module AP_MODULE_DECLARE_DATA socket_policy_module = {
        STANDARD20_MODULE_STUFF,
        NULL,
        NULL,
        NULL,
        NULL,
        NULL,
        register_hooks
};

Also, I've looked at mod_perl source and they seemingly use the same method to access the client socket:
static MP_INLINE
apr_socket_t *mpxs_Apache2__Connection_client_socket(pTHX_ conn_rec *c,
                                                    apr_socket_t *s)
{
    apr_socket_t *socket =
        ap_get_module_config(c->conn_config, &core_module);

    if (s) {
        ap_set_module_config(c->conn_config, &core_module, s);
    }

    return socket;
}

So why does my Perl module work and the C one not?

A: For content handlers the convention is
to use SetHandler XXX in httpd.conf and
then at the runtime they check for that string with
if (!r->handler || (strcmp(r->handler, "XXX") != 0))
   return DECLINED;

But for protocol handlers there is no such convention.
You have to introduce some keyword for httpd.conf
and check for it. For example mod_echo (source code included with Apache) introduces ProtocolEcho On. Or in my case you could just check the port:
   if (conn->base_server->port != 843)
           return DECLINED;

Also below is the working module for the same purpose, but using bucket brigades, which is better than writing directly to client socket:
/*
LoadModule socket_policy_module modules/mod_socket_policy.so
Listen 843
<VirtualHost _default_:843>
</VirtualHost>
*/
#include <httpd.h>
#include <http_protocol.h>
#include <http_connection.h>
#include <http_config.h>
#include <http_log.h>

#define POLICY "<?xml version=\"1.0\"?>\n" \
               "<!DOCTYPE cross-domain-policy SYSTEM\n" \
               "\"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd\">\n" \
               "<cross-domain-policy>\n" \
               "<allow-access-from domain=\"*\" to-ports=\"8080\"/>\n" \
               "</cross-domain-policy>\n"

static int socket_policy_handler(conn_rec *conn) {
        apr_bucket_brigade *bb;
        apr_bucket *b;
        apr_status_t rv;

        if (conn->base_server->port != 843)
                return DECLINED;

        bb = apr_brigade_create(conn->pool, conn->bucket_alloc);
        /* this will send the terminating 0 as well */
        b = apr_bucket_immortal_create(POLICY, sizeof(POLICY), bb->bucket_alloc);
        APR_BRIGADE_INSERT_TAIL(bb, b);
        b = apr_bucket_eos_create(bb->bucket_alloc);
        APR_BRIGADE_INSERT_TAIL(bb, b);
        rv = ap_pass_brigade(conn->output_filters, bb);
        if (rv != APR_SUCCESS) {
                ap_log_error(APLOG_MARK, APLOG_ERR, 0, conn->base_server, "output error");
                return DECLINED;
        }

        ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, conn->base_server,
            "served socket policy to %s", conn->remote_ip);
        return OK;
}

static void register_hooks(apr_pool_t *pool) {
        ap_hook_process_connection(socket_policy_handler, NULL, NULL, APR_HOOK_MIDDLE);
}

module AP_MODULE_DECLARE_DATA socket_policy_module = {
        STANDARD20_MODULE_STUFF,
        NULL,
        NULL,
        NULL,
        NULL,
        NULL,
        register_hooks
};


text:
Q: How to find the index of the first row of a matrix that satisfies two conditions in APL Language? One more question to learn how to use APL Language.
Suppose you have an array, as an example:

c1
c2
c3
c4
c5
c6

3
123
0
4
5
6

3
134
0
2
3
4

3
231
180
1
2
5

4
121
0
3
2
4

4
124
120
4
6
3

4
222
222
5
3
5

So, how to find out which row has a value of 4 in the 1st column and a value grather than 0 in the 3rd column?
The expected answer is 5th line, in the just 5

A: When you want to make such "queries", think Boolean masks.
      table ← 6 6⍴3 123 0 4 5 6 3 134 0 2 3 4 3 231 180 1 2 5 4 121 0 3 2 4 4 124 120 4 6 3 4 222 222 5

Let's extract the first column:
      table[;1]
3 3 3 4 4 4

And indicate which elements have a value of 4:
      table[;1] = 4
0 0 0 1 1 1

Similarly, we can indicate which elements of column 3 have value greater than 0:
      table[;3] > 0
0 0 1 0 1 1

Their intersection (logical AND) indicates all rows that fulfil your criteria:
      (table[;1] = 4) ∧ (table[;3] > 0)
0 0 0 0 1 1

The index of the first 1 is the row number for the first row that fulfils your criteria:
      ((table[;1] = 4) ∧ (table[;3] > 0)) ⍳ 1
5

Try it online!
Alternatively, we can use the final mask to filter the table and obtain all rows that fulfil your criteria:
      ((table[;1] = 4) ∧ (table[;3] > 0)) ⌿ table
4 124 120 4 6 3
4 222 222 5 3 5

Try it online!
Or we can generate all the row numbers:
      ⍳ 1 ↑ ⍴ table
1 2 3 4 5 6

Then use our Boolean mask to filter that, finding the row numbers of all the rows that fulfil your criteria:
      ((table[;1] = 4) ∧ (table[;3] > 0)) ⌿ ⍳ 1 ↑ ⍴ table
5 6

Try it online!


text:
Q: Mysql query random order (pause and continue) question Okay i am trying to create a mysql query that does this:
show 3 random records from table then after the 3th record show TEXT
and then show the same 3 items but other field (equaling to the items ofcourse) from same table.
eg table info:
--ids | titles------

10   | one

20   | two

30   | three

and the query results from the given example:
30 10 20  TEXT three one two

if anyone understand what i am asking,post your suggestion/asnwer
thanks for your time all :)

A: Just for kicks..
select t1.id, t2.id, t3.id, 'TEXT', t1.title, t2.title, t3.title
FROM
(
    select @r := @r + 1 rownum, id
    from (select @r:=0) initvar, (
        select id
        from tbl
        order by rand()
        limit 3
    ) X
) Y
join tbl t1 on Y.rownum=1 and t1.id = Y.id
join tbl t2 on Y.rownum=2 and t2.id = Y.id
join tbl t3 on Y.rownum=3 and t3.id = Y.id

You should really just do the query below, and do whatever display processing using the 3 rows returned, in whatever programming environment you use (Java/PHP/.Net etc).
select id, title
from tbl
order by rand()
limit 3

EDIT
To get the data in 7 different rows, you can use the below. I stress again that this is front-end display code. I will not use such SQL code in a production system.
select display
from
(
select sorter, rownum,
    case when sorter=3 then title else id end display
from
(
    select @r := @r + 1 rownum, id, title
    from (select @r:=0) initvar,
    (
        select id, title
        from tbl
        order by rand()
        limit 3
    ) X
) Y, (select 1 sorter union all select 3) dup
union all
select 2, 0, 'TEXT'
) Z
order by sorter, rownum

Example Output
7
2
1
TEXT
test 7    << title for id=7
test 2
test 1


text:
Q: What are the two orbs Clu is using during Sam's battle with Rinzler? Once Sam is introduced into the games he defeats a couple of combatants and is then paired with Rinzler. Just as the battle begins Clu begins manipulating two orbs in his hand.

Is Clu controlling Rinzler or manipulating the game grid with these devices?

A: The use of Baoding Balls in the scene is likely meant to convey to the audience that CLU is currently in control of the world that Sam has found himself in, even if there is not a direct obviousness to how exactly it works.

A: The real-word name of those is baoding balls. They are not explicitly named anywhere on promotional material, so their name in the Tron universe is mysterious.
So, Clu only grabs those balls when Sam starts the final battle with Rinzler in the Disc Wars.
He starts turning them in his hand, stops suddenly, and then starts turning them in the opposite direction. As soon as he does that, the gravity on the arena switches sides.
So yes, he manipulates the game grid, but we don't know for sure if he is only able to manipulate gravity with them. There's some speculation that he also uses them to control Rinzler, as he seems to activate when Clu start to roll the balls. Maybe Clu could control the speed and/or aggressiveness of Rinzler by modifying the speed at which he rolls the balls. However, the first time Clu switches gravity, Rinzler turns his head to look at some control plate that is rotating, so he is not advised automatically of Clu's commands on gravity. Anyway, we also saw Rinzler obey a verbal command from Clu, so if they control him, they are optional.


text:
Q: LocalStorage getItem and Loop Values I am storing some values into local storage using the following line of code;
localStorage.setItem(event.lastEventId, JSON.stringify(data));

Looking at the browser console, the storage looks like this;

I want to loop through the localstorage and display the values.
The loop I have so far is;
for (var i = 0; i < localStorage.length; i++) {
  $("#result").prepend("New transaction " + localStorage.getItem(localStorage.key(i)) + "
");
}

The #result displays the following;

New transaction {"TimeStamp":"2017-08-18
16:34:15","Direction":"Out","CardNo":"40160433","SerialNo":20559458}
New transaction {"TimeStamp":"2017-08-18
16:34:55","Direction":"In","CardNo":"40160432","SerialNo":20559459}

I want to display the values only, not associated keys. For example;

New transaction 2017-08-18
16:34:15, Out, 40160433, 20559458
New transaction 2017-08-18
16:34:55, In, 40160432, 20559459

What do I need to change in order to achieve this?
Any help is appreciated.

A: getItem() returns you a string. So in order to achieve what you want, you need to parse the returned string in JSON and extract the values. Something like this:
for (var i = 0; i < localStorage.length; i++) {
    let data = JSON.parse(localStorage.getItem(localStorage.key(i)));
    $("#result").prepend("New transaction " + data.TimeStamp + ", " + \
         data. Out + ", " + data. CardNo + ", " + data. SerialNo + "
");
}

A: You need to

*

*Parse the data, and

*Loop through the resulting object showing only the values of its properties, and

*Join those together into a string in some way, perhaps with , in-between
For instance:
for (var i = 0; i < localStorage.length; i++) {
  var obj = JSON.parse(localStorage.getItem(localStorage.key(i)));
  var str = Object.keys(obj).map(function(key) { return obj[key]; }).join(", ");
  $("#result").prepend("New transaction " + str + "
");
}

Live Example:

// The string from local storage
var stringFromLocalStorage = '{"TimeStamp":"2017-08-18 16:34:15","Direction":"Out","CardNo":"40160433","SerialNo":20559458}';

var obj = JSON.parse(stringFromLocalStorage);
var str = Object.keys(obj).map(function(key) { return obj[key]; }).join(", ");
$("#result").prepend("New transaction " + str + "
");

Or, of course, hardcode the property names if your structure is static.


text:
Q: How is Objcet.clone() knows which class must be cloned? How is clone() method in Object class knows which class/fields must be cloned? For example how Objcet.super() can know that I need to serialize exactly A class or B class if I don't put any arguments in it?
clone() defined as nativ son I can not see it's implementstion
class A implements Cloneable
{
    public int a = 1;

    @Override
    public Object clone() throws CloneNotSupportedException
    {
        return super.clone();
    }
}
class B extends A
{
    public int b = 2;

    @Override
    public Object clone() throws CloneNotSupportedException
    {
        return super.clone();
    }
}


text:
Q: Model for probability threshold selection, how to make differentiable loss? I have an object detection model that outputs bounding boxes and probabilities associated with them. The probability expresses the chance that the object found is a tumor. I have noticed that the default 0.5 probability threshold works well for small objects but is heavily underestimated for small ones. I would like to create a model that would take the object volume as input and will give me a probability threshold as output.
I am not sure how to create such a model. One of the operations I need to perform is a comparison of the predicted threshold against the (constant) probabilities given by the detection model. This operation is not differentiable so I can't train this model with gradient methods. What would be the right approach to that problem?


text:
Q: Difference between static members of Java and static members of C++ I have studied C++ and now I'm studying Java. In C++ we can use static members in non-static/instance member functions. But while studying Java I found this :

I wrote a program to check if " the non-static function can access static member or not". And there was no problem in the program below :
public class Animal
{
    static int CountOfAnimal;
    public Animal()
    {
        CountOfAnimal++;
    }
    public int showCount()
    {
        CountOfAnimal++;
        return CountOfAnimal;
    }
    public static void main(String []args)
    {
        new Animal();
        new Animal();
        Animal C = new Animal();
        System.out.println("Total animals are : " + C.showCount());
    }
}

So, can I say that in Java also the non-static/instance member functions can access static members of same class?
Also, I want to know if there is any difference between static members(methods and variables) in Java and C++ other than the way of calling the members?
One difference I know is in the way of calling the static members in C++ and calling static members in Java. Any other?

A: Yes. Note that it doesn't say that a non-static method can't access a static class member, which is what your code does. It says that a static method cannot access a non-static class member (or method). It's the other way around.
This is also true with C++ for exactly the same, underlying, fundamental reasons.

A: Like Sam Varshavchik had mentioned "static method cannot access a non-static class member".
For your other question, what's the difference between static in C++ and Java.

C++ supports static Local Variables. Java Doesn't.

Ex: Perfectly Valid in C++, but Error in Java.
static int fun()  {
     static int abc = 1;
   }

Java Supports Static Blocks/Static Classes. C++ Doesn't

Ex:
static
{
   System.out.println("Static block called");
}

class TestOuter1{
  static int data=30;
  static class Inner{
   void msg(){System.out.println("data is "+data);}
  }
  public static void main(String args[]){
  TestOuter1.Inner obj=new TestOuter1.Inner();
  obj.msg();
  }
}


text:
Q: Nested aggregation with term agg I have a document with 2 nested paths - path.to.node and different.path.
I want to be able to get a date histogram based on the path.to.node.date field but then group the buckets based on different.path.to.name.
Is that possible?
I tried something like this but it doesn't seem to work...
{
  "size":0,
  "query":{...},
    "aggregations":{
      "path.to.node.date":{
        "nested":{
          "path":"path.to.node"
        },
        "aggregations":{
          "path.to.node.date":{
            "filter":{
              "range":{...}
              }
            },
            "aggregations":{
              "different.path.name":{
                "nested":{
                   "path":"different.path"
                },
                "terms":{
                  "field":"different.path.name"
                  ...
                },
                "aggregations":{
                  "path.to.node.date":{
                    "date_histogram":{
                      "field":"path.to.node.date",
                      "interval":"1M",
                      "offset":0,
                      "order":{"_key":"asc"},
                      "keyed":false,"min_doc_count":0}
                    }
                  }
                }
              }
            }
          }
        }
      }
    }


text:
Q: Graceful javascript re-adjustment after setting style.display= none I am trying to make some code that deletes an item that is represented in a card on a web page.
When the user clicks the remove-item-btn ajax is called which removes the item in the backend. And on the front end the item's display is changed to none so it disappears. All of this is working well. In an instant the item disappears from the grid and the later item's have filled in its place.
Question: Is it possible to write javascript that causes the other cards to gracefully move over to fill in the empty space?
I am using bootstrap, sass, ruby on rails, and htmlslim.
The cards are currently in a grid that varies in width depending on the screen size with the average width of the grid being 3 cards.
HTML

...

...

...

...

...

...

JS
$('.remove-item-btn').mousedown(function(ev) {
  var item_card = document.getElementById(...);
  item_card.style.display = 'none'
  $.ajax(this removes the item)
});

CSS
.item-card {
  ...
  display: inline-block;
  ...
}

A: Instead of just making display equal to none, you can use animation methods for hiding with jQuery. Something like this:
$("#ID_OF_ELEMENT").hide("slow");

More stuff is here: http://api.jquery.com/hide/
More general animation stuff is here: http://api.jquery.com/animate/


text:
Q: Python 3 - How do I extract data from SQL database and process the data and append to pandas dataframe row by row? I have a MySQL database, its columns are:
+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| id           | int unsigned | NO   | PRI | NULL    | auto_increment |
| artist       | text         | YES  |     | NULL    |                |
| title        | text         | YES  |     | NULL    |                |
| album        | text         | YES  |     | NULL    |                |
| duration     | text         | YES  |     | NULL    |                |
| artistlink   | text         | YES  |     | NULL    |                |
| songlink     | text         | YES  |     | NULL    |                |
| albumlink    | text         | YES  |     | NULL    |                |
| instrumental | tinyint(1)   | NO   |     | 0       |                |
| downloaded   | tinyint(1)   | NO   |     | 0       |                |
| filepath     | text         | YES  |     | NULL    |                |
| language     | json         | YES  |     | NULL    |                |
| genre        | json         | YES  |     | NULL    |                |
| style        | json         | YES  |     | NULL    |                |
| artistgender | text         | YES  |     | NULL    |                |
+--------------+--------------+------+-----+---------+----------------+

I need to extract data from it and process the data and add the data to a pandas DataFrame.
I know how to extract data from SQL database, and I have already implemented a way to pass the data to DataFrame, but it is extremely slow (about 30 seconds), whereas when I used a flat list of namedtuples the operation is tremendously faster (under 3 seconds).
Specifically, filepath is default NULL unless the file is downloaded (currently none of the songs are downloaded), and when Python gets filepath the value will be None, and I need that value become ''.
And because MySQL doesn't have BOOLEAN type, I need to cast the received ints to bool.
And the language, genre, style fields are tags stored as JSON lists, and they are all currently NULL, when Python gets them they are strings and I need to make them lists using json.loads unless they are None, and if they are None I need to append empty lists instead.
This is my inefficient solution to the problem:
import json
import mysql.connector
from pandas import *

fields = {
    "artist": str(),
    "album": str(),
    "title": str(),
    "id": int(),
    "duration": str(),
    "instrumental": bool(),
    "downloaded": bool(),
    "filepath": str(),
    "language": list(),
    "genre": list(),
    "style": list(),
    "artistgender": str(),
    "artistlink": str(),
    "albumlink": str(),
    "songlink": str(),
}

conn = mysql.connector.connect(
    user="Estranger", password=PWD, host="127.0.0.1", port=3306, database="Music"
)
cursor = conn.cursor()

def proper(x):
    return x[0].upper() + x[1:]

def fetchdata():
    cursor.execute("select {} from songs".format(', '.join(list(fields))))
    data = cursor.fetchall()
    dataframes = list()
    for item in data:
        entry = list(map(proper, item[0:3]))
        entry += [item[3]]
        for j in range(4, 7):
            cell = item[j]
            if isinstance(cell, int):
                entry.append(bool(cell))
            elif isinstance(cell, str):
                entry.append(cell)
        if item[7] is not None:
            entry.append(item[7])
        else:
            entry.append('')
        for j in range(8, 11):
            entry.append(json.loads(item[j])) if item[j] is not None else entry.append([])
        entry.append(item[11])
        entry += item[12:15]
        df = DataFrame(fields, index=[])
        row = Series(entry, index = df.columns)
        df = df.append(row, ignore_index=True)
        dataframes.append(df)
    songs = concat(dataframes, axis=0, ignore_index=True)
    songs.sort_values(['artist', 'album', 'title'], inplace=True)
    return songs

Currently there are 4464 songs in the database and the code takes about 30 seconds to finish.
I sorted my SQL database by artist and title and I need to resort the entries by artist, album and title for QTreeWidget, and MySQL sorts data differently from Python and I prefer Python sorting.
In my testing, df.loc and df = df.append() methods are slow, pd.concat is fast, but I really don't know how to create dataframes with only one row and pass flat lists to dataframe instead of a dictionary, and if there is a faster way than pd.concat, or if operations in the for loop can be vectorized.
How can my code be improved?

I figured out how to create a DataFrame with a list of lists and specify column names, and it is tremendously faster, but I still don't know how to also specify the data types elegantly without the code throwing errors...
def fetchdata():
    cursor.execute("select {} from songs".format(', '.join(list(fields))))
    data = cursor.fetchall()
    for i, item in enumerate(data):
        entry = list(map(proper, item[0:3]))
        entry += [item[3]]
        for j in range(4, 7):
            cell = item[j]
            if isinstance(cell, int):
                entry.append(bool(cell))
            elif isinstance(cell, str):
                entry.append(cell)
        if item[7] is not None:
            entry.append(item[7])
        else:
            entry.append('')
        for j in range(8, 11):
            entry.append(json.loads(item[j])) if item[j] is not None else entry.append([])
        entry.append(item[11])
        entry += item[12:15]
        data[i] = entry
    songs = DataFrame(data, columns=list(fields), index=range(len(data)))
    songs.sort_values(['artist', 'album', 'title'], inplace=True)
    return songs

And I still need the type conversions, they are already pretty fast, but they don't look elegant.

A: You could make a list of conversion functions for each column:
funcs = [
    str.capitalize,
    str.capitalize,
    str.capitalize,
    int,
    str,
    bool,
    bool,
    lambda v: v if v is not None else '',
    lambda v: json.loads(v) if v is not None else [],
    lambda v: json.loads(v) if v is not None else [],
    lambda v: json.loads(v) if v is not None else [],
    str,
    str,
    str,
    str,
]

Now you can apply the function that converts the value for each field
for i, item in enumerate(data):
    row = [func(field) for field, func in zip(item, funcs)]
    data[i] = row

A: For the first part of the question, for generic database 'history':
    import pymysql
    # open database
    connection = pymysql.connect("localhost","root","123456","blue" )
    # prepare a cursor object using cursor() method
    cursor = connection.cursor()
    # prepare SQL command
    sql = "SELECT * FROM history"
    try:
        cursor.execute(sql)
        data = cursor.fetchall()
        print ("Last row uploaded",list(data[-1]))
    except:
        print ("Error: unable to fetch data")
    # disconnect from server
    connection.close()

A: You can simply fetch data from the table and create a Data-frame using Pandas.

import pymysql
import pandas as pd
from pymysql import Error
conn = pymysql.connect(host="",user="",connect_timeout=10,password="",database="",port=)
if conn:
    cursor = conn.cursor()
    sql = f"""SELECT * FROM schema.table_name;"""
    cursor.execute(sql)
    data =pd.DataFrame(cursor.fetchall())
    conn.close()
# You can go ahead and create a csv from this Data-Frame
    csv_gen = pd.to_csv(data,index=False)

    enter code here


text:
Q: How to get value with jquery from complex input name Here's my case:
I'm trying to get value from form's input that has name="data[type][answer]", something like:
<form id="form" method="POST" >
<input type="hidden" name="data[type][answer]" value="Hello from Space">
</form>

So, my code for function should look like:
 function queryForm(key) {
   return $('#form input[name=' + key + ']').val();
 }

I'm getting input[name=order[type][answer]] which is not working and I'm aware why.
Is there a way how to write this thing differently or is there any other way how to get the value? By the way, I need the name exactly in this form: name="data[type][answer]"
Any advice or solution would be nice!

A: You just need quotes around the value for name. Then you have to select the first result from the returned and wrap it again with jquery to be able to call .val():

function queryForm(key) {
    return $("#form input[name='" + key + "']").first()
      .val();
}

console.log(queryForm('data[type][answer]'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <html>
    <head></head>
    <body>
    <form id="form" method="POST" >
    <input type="hidden" name="data[type][answer]" value="Hello from Space">
    </form>
    </body>
    </html>

A: All you just need to do is ...
function queryForm(key) {
   return $('#form input[name="' + key + '"]').val();
}

note the double quote (") around key.


text:
Q: FileSystemWatcher under Mono: Heavy CPU load on Linux I subscribe to changes inside a directory:
FileSystemWatcher watcher = new FileSystemWatcher(directory);
watcher.NotifyFilter = NotifyFilters.LastAccess;
watcher.Changed += OnChanged;
watcher.IncludeSubdirectories = includeSubdirectories;
watcher.EnableRaisingEvents = true;

Most of the time this .NET 4.7 code works fine, but when it's running under mono on Debian, on some directories, I notice the following behavior:

*

*The CPU load increases to 250% (2.5 cores are fully loaded)

*The number of child threads increases, and they load the CPU

This continues endlessly until the app is totally stuck.

UPD: Additional research shows that heavy CPU load is caused by an endless flood of WatcherChangeTypes.Changed events on every subdirectory inside the watched directory (1-2 events in a row for every directory, when all dirs were reported as changed, it starts again).

UPD: Minimal buggy example

A: In Mono's Technical FAQ, you can find a What are the issues with FileSystemWatcher? section, which says that under certain conditions

Mono falls back to polling the directories for changes, which far from optimal.

Experimentally, I found out that one of these conditions is:
The total number of watched directories is more than 4096
There may be more conditions related to files count, but I did not met them.

So, you may face the described problem if the following conditions are met:

*

*You run a .NET Framework 4.7 code under Mono 6.8 on Linux (or in Docker)

*You use System.IO.FileSystemWatcher to recursively monitor a directory changes

*Your NotifyFilter includes NotifyFilters.LastAccess

*The find watched-directory -type d | wc -l command returns more than 4096