Q:

How to use JPA in a existing project?

My team is working on a medium size application (OLTP style). We were interested by switching to JPA instead of only using JDBC queries. Mostly for performance and practical reason. I'm not looking for a tutorial that shows me how to create a persistence.xml or Entity class in Eclipse. What i would like to know is what would be the steps to convert all the database queries into the JPA format. I know that the whole application must use JPA.
Many programmers has worked on this project over the years, so not everyone has the same SQL knowledge or the same programming skills. So there must be in this application 1000+ customs queries, using multiple tables (something that native JPA does not support very well), or query that is selecting only a few fields in a table... This is getting a bit out of control and i think that JPA would create a nice toolbox to make sure that everyone is going the same direction.
What should i look for to make sure that i'm not going into a process (convertion) that will never end ? Some sort of guideline.
(Again, i'm not looking for programming exemples, nor Eclipse tutorial.)
Thanks!

A:

First step is convert you database schema into database model using JPA, you need to be clear what are the table, sequences, database objects that you are using in your existing application and start modeling all the schema with JPA you should consider use JPA annotation.
The step above will determine what will be your entities, embeddables and mapped superclass, their properties and the relationships they have, this step is very crucial as your logic will depends on the correctness of this model.
Then start looking for all the queries that are involved in your project, as you said that you have 1000+ queries consider use two scenario, convert all of them in JPQL queries or use a mix  between native queries and named queries, I really prefer to convert all in JPQL unless are very database dependent. A step you must follow is find all of them, probably are some existing tool that convert from SQL to JPQL but I believe is better idea make by your own.
Once you have queries and model for the database start the creation of your new DAO using JPA and EntityManager stuff, I should recommend extract the interface for your exisiting DAO and start moving to a JPA implementation using the same interface, this will avoid break some code on your own, don't forget unit and IT test for your new DAO.
Also with the above approach you could start moving the application module by module, DAO or by DAO does not require to move full application at once. This will give you a kind of process in which you will see some progress each time you finish a new DAO or module.
Not sure what you mean about programming examples, I think those are the required steps but each project is different from each other, so consider this as some kind of guidelines.


Q:

Accessing CCLayer headache!

I'm having abit of trouble accessing my layers and its driving me insane. Basically, my layer-scene hierachy is as follows:
Compiler.m - CCLayer - holds the +(CCScene) method and loads all the other CCLayers.
Construct.m - CCLayer - holds the box2d engine and its components
Background.m - CCLayer - holds the Background.
Hud.m - CCLayer - holds the HUD.
within the Compiler implementation class, I add the Scene and all the relevant nodes to the Compiler CCLayer:
@implementation Compiler

+(CCScene *) scene{
    Compiler *compiler = [CompileLayer node];
    CCScene *scene = [CCScene node];
    [scene addChild: compiler];

    //Add A Background Layer.
    Background *layerBackground = [Background node];
    layerBackground.position = CGPointMake(100,100);
    [compiler addChild: layerBackground z: -1 tag:kBackground];

    //Add The Construct.
    Construct *construct = [Construct node];
    [compiler addChild: construct z: 1];

    //Add A Foreground Layer Z: 2
    //After background is working.

    //Add the HUD
    HudLayer *hud = [Hud node];
        [compiler addChild: hud z:3];
}

This all works fine, my layers are added to the compiler and the compiler's scene is accessed by the delegate as predicted.
My problem is that im trying to access my Background CCLayers - CCsprite *background, inside the Construct layer so that I can move it according to the position of my Construct game hero.
I've tried many different methods, but I've currently decided to use a class method rather than an instance method to define CCSprite *background so that I can access it in my Construct Layer.
I've also tried accessing with @properties and initialising an instance variable of the class.
Here is my Background CCLayer:
@implementation Background
-(id) init
{
    self = [super init];
    if (self != nil)
    {
        CCSprite *temp = [Background bk];
        [self addChild:temp z:0 tag:kBackGround];
    }
    return self;

}

+(CCSprite *)bk{
    //load the image files
    CCSprite *background = [CCSprite spriteWithFile:@"background.jpg"];

    //get the current screen dimensions
    //CGSize size = [[CCDirector sharedDirector] winSize];
    background.anchorPoint = CGPointMake(0,0);
    background.position = ccp(0,0);
    return background;
}
@end

This works, it loads the image to the background layer.
Then finally, I try to access the background image from the Construct Layer.
@interface Construct : CCLayer{
     CCSprite *tempBack;
}
@end

@implementation Construct

-(id) init{
     tempBack = [Background bk]; //The background equals an instance variable
}

-(void) tick:(ccTime)dt {
     tempBack.position.x ++; // To do Something here.
     tempBack.opacity = 0.5; // Some more stuff here.

}
@end

This doesnt work, I receive a 'nil' pointer in some respects, tempBack doesnt access the background properly, or at all.
How can I access and modify the Background CCLayers Class Variable +(CCSprite) bk??

A:

It probably doesn't work because your tempBack iVar is autoreleased in compiler layer and you don't retain it. Here's how your init method should look like:
-(id) init{
     tempBack = [[Background bk] retain]; //The background equals an instance variable
}

Also - don't forget to release it in dealloc. And I am not sure if it will work either since you'll have different background sprite returned by bk class method (try printing temp and tempBack variable addresses and you'll see).
Update for notifications
In background layer, create the sprite and add it to the layer. Then afterwards add this snippet of code to subscribe to notifications:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateBackground:) name:@"PlayerChangedPosition" object:nil];

Then in construct layer's update method (or any other scheduled method) send this notification with new player coordinates:
[[NSNotificationCenter defaultCenter] postNotificationName:@"PlayerChangedPosition" object:player];

Now in background's layer, implement the updateBackground:(NSNotification *)aNotification method:
- (void)updateBackground:(NSNotification *)aNotification {
    // object message returns player object passed when posting notification
    CGPoint newCoords = [[aNotification object] position];
    // adjust background position according to player position
}


Q:

Do I need to inform my PI about every single project I am working on?

I feel like my PI doesn't care much about my thesis (as if I already had one), and keeps assigning me several unrelated tasks to support the publications of his postdocs. Even worse, I don't feel like he is my "academic" advisor: every weekly meeting revolves around grant writing and research expense rather than the experiment itself. And the worst? We differ in our approach to science: his is data-driven, mine is hypothesis-driven.
At the same time, I greatly enjoy the mentoring I have been receiving from three  members of my thesis committee. We did have many exciting sessions of exchanging ideas and fruitful follow-ups. I feel like with their help, I am becoming the kind of scientist I always try to be. Last but not least, although they are experts in different fields, they respect each other and are happy to collaborate through my thesis.
Here is my problem: I have several ideas with each of my three committee members, and want to turn them into publications. However, these are deemed not the interests of my PI's lab. Do I need to inform my PI that I am working on these projects? Do I need to describe these projects in detail (he will yawn his way through the meeting anyways)? And if I can get some publications, should I put my PI's name there?

A:

In your comments you mentioned that you are funded by your PI, which changes the dynamics and expectations somewhat between you and your PI; and I think he needs to know how you are spending your time.
My suggestion would be to seek approval from him to work on these. This is to show him that you are respectful and value his opinions on if these are worth working on. It can be in the form of I have some ideas I would like to develop with Prof xxx and Prof yyy, can I go ahead and discuss with them?
Your PI would probably also need assurances that working with them does not compromise too much in your abilitty to support his lab. And lastly remember this. It is in your best interests that relationships between your advisor and you remain cordial.


Q:

Integral expansion

I want to expand $Y_{\mu}(a,b)$ around $b=0$. I tried to link the integral to the generalized Marcum Q-function by doing a change of variable, however I wasn't able to get a relation between the two function. Do you think that writing the modified Bessel function as an infinite series will lead to something or will it make thing more complicated? Any ideas or hints on how to tackle this problem.
Attempt:
Using the definition of the modified bessel function
$$ I_{\mu}(x) = \sum_{n=0}^{+\infty}{\frac{x^{2n+\mu}}{n! 2^{2n+\mu} \Gamma(\mu+n+1)}}$$
Switching the integral and summation, I get
$$  Y_{\mu}(a,b) = \frac{1}{2} \left(\frac{a}{2}\right)^{2n+\mu-\frac{1}{2}} \sum_{n=0}^{+\infty}{\frac{\Gamma(n+2\mu,b^2)}{\Gamma(\mu+n+\frac{1}{2})}}$$
where  $\Gamma(a,b)$ is the upper incomplete Gamma function.
Thanks.

A:

No need for complicated stuff like $Q-$functions:
Define ($\mu>-1/2$)

$$
\mathcal{Y}_{\mu}(a,b)=\int_b^{\infty}\underbrace{x^{2\mu}e^{-x^2}I_{\mu-1/2}(a x^2)}_{f_{\mu}(x,a)}dx
$$

We write the integral as $$\mathcal{Y}_{\mu}(a,b)=\int_0^{\infty}f_{\mu}(x,a)dx-\int_0^bf_{\mu}(x,a)dx$$
as long as $a<1$ everything converges and the splitting is valid. Furthermore the first integral on the right is a constant independent of $b$, which we denote by $C_{\mu}(a)$.
To go further we observe that as $b\rightarrow0_+$ a taylor expansion in the second integral is valid (the arguments of any of the function contained in the integrand are much smaller then one). Therefore
$$
\int_0^bf_{\mu}(x,a)dx\sim\int_0^bx^{2\mu}\cdot(1+\mathcal{O}(x^2))\cdot \left(\frac{x^{2\mu-1}a^{\mu-1/2}}{2^{\mu-1/2}\Gamma[\mu+1/2]}+\mathcal{O}(x^{2\mu+3})\right)dx=\\b^{4\mu}\underbrace{\frac{a^{\mu-1/2}}{2^{\mu-1/2}\Gamma[\mu+1/2]4\mu}}_{D_{\mu}(a)}+\mathcal{O}(b^{4\mu+2})
$$
and

$$
\mathcal{Y}_{\mu}(a,b)\sim C_{\mu}(a)-D_{\mu}(a)b^{4\mu}+\mathcal{O}(b^{4\mu+2})\quad\text{as}\,\,b\rightarrow 0_+
$$

Note also that the coefficent $C_{\mu}(a)$ can be given in closed form as $C_{\mu}(a)=\frac{2^{-3/2+\mu}(1/a-a)^{-\mu} \Gamma[\mu]}{\sqrt{\pi a}}$. To prove this use term-by-term integration together with the duplication formula for the $\Gamma-$function and the series expansion for the square root.


Q:

Can I have a unique identifier variable for each replaced string with preg_replace?

I'm actually dealing with a preg_replace to prepare a text. But I need a unique identifier for each of the replaced elements.
I'm using a manually entered identifier to be able to use it in my preg replace :
$text = preg_replace("#<anecdote=(\d+) titre=\"([^\"]+)\" texte=\"([^\"]+)\">#", '?', $text);

And I would like to use something like #<anecdote titre=\"([^\"]+)\" texte=\"([^\"]+)\"># and assign automatically an identifier, something like an int that would increment.
Is it possible to do that ?
I've tried something with the $count variable for preg replace, but I couldn't find a proper solution, so far.

A:

you can do that with "preg_replace_callback"
http://php.net/preg_replace_callback


Q:

Regular Expression match and extract using group

I would like to match "1) Exception Information" or "2) Exception Information" and extract the digit using regular expression Match and Group
I'm using
Regex.Match("1) Exception Information", @"\d[) Exception Information]").Groups[0].Value

but this returns me "1)" and not "1"

A:

The following line of code will do what you intended:
Regex.Match("1) Exception Information", @"(\d)\) Exception Information").Groups[1].Value

Your current regex pattern has problems:
\d[) Exception Information]

This will match a single digit, followed by a single character coming from the following set of characters in brackets: [) Exception Information].  In your original string, the parenthesis following the 1 would match, and so your match comes back as 1).
Another note, I used (\d) in my corrected pattern, which will match and capture that single digit.  Then, to access the first (and only) capture group, we can use Groups[1].  Groups[0] will return the entire matched pattern, which in this case coincides with the input string.
Demo here:
Rextester


Q:

Is a real background preferable to an artificial one?

I'm learning fashion and nude photography and I usually post-process my photos to give them a better look (photoshop CS5) .
I noticed that lots of photographers uses texture or digital background to improve their shots as you can see for example in this photo
http://500px.com/photo/26301849
Now I was wondering is it a good idea? I mean should we always prefer "real" background instead of digital one?
What is the best technique to replace the background with a photoshop texture? (at the moment I'm using channels selection + refine edge)

A:

It's much easier to get a realistic looking background in camera.
It's much easier to get a nice looking background in Photoshop.
Some people's philosophy is to do as much as possible in camera and leave Photoshop out of the equation or only only as a last resort. Some people's philosophy is to get the highest quality results possible using whatever tools are available. There's no right answer.
Speaking of specific techniques, getting a good background in camera requires a lot of space, a background support system and material. For the standard mottled portrait background printed cloths are available and you can also dye your own. Getting out of focus highlights in the background like the example link you posted is harder in camera as you need a rough texture which is lit evenly but obliquely (required a lot of space to prevent spilling onto your subject).
Replacing the background in Photoshop requires generation of a good subject mask. The ideal solution is a proper chroma key setup such as is used for VFX work (the classic blue or green screen). This too is expensive and requires space and coloured lighting. But provided you have a plain background you can get good results using Photoshop's select colour tool, which lets you select a series of colours to add to the mask as well as letting you finetune the tolerances. There are some commercial plugins designed for exactly this type of job which use a more sophisticated approach.
It helps when the real background is similar in colour/shade to the image you're inserting. If you try and replace a black background with a very light image or vice versa any imperfections in your mask will be very detrimental to the image.


Q:

Use readonly attribute in  without changing the cursor

If I have an <input> field with the readonly attribute, it still appears with the I-beam text cursor. Is there a way to stop that cursor from showing?
I cant use the disabled attribute because request.getParameter() does not work on disabled fields.

A:

The idea of readonly elements is that you can still read and copy the text, just not edit them. That said, you can change the cursor using CSS attribute selectors. This example will match any input element with a readonly attribute:
input[readonly] {
     cursor: pointer;
}

A:

I did not want to override bootstrap's default styles so I came along with the following solution:
My LESS File:
input[readonly] {
    &.default-cursor {
        cursor: default;
    }
}

Or in CSS:
input[readonly].default-cursor {
    cursor: default;
}

My HTML:
<input type="text" class="form-control text-xl default-cursor" readonly>

A:

Try this markup in your form for text field
<input type="text" value="test" onfocus="this.blur()" readonly="readonly" />
main thing which helps you hide the cursor is onfocus="this.blur()".


Q:

how to pass custom array list in one activity to another activity

I have a todolist application and ı cant pass customlist in one activity to another one.I  use data wrapper but when ı click add button program gives nullpointerexception.
this is AddItem.java
  okButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {

            ArrayList<Entry> itemList = new ArrayList<Entry>();

            task = editText1.getText().toString();
            priorityLevel = spinner.getSelectedItem().toString();
            status = toggleButton.getText().toString();

            int day = datePicker.getDayOfMonth();
            int month = datePicker.getMonth() + 1;
            int year = datePicker.getYear();

            date = day + "/" + month + "/" + year;

            itemList.add(new Entry(task, priorityLevel, date, status));

            Intent okIntent = new Intent();
            okIntent.putExtra("item",new DataWrapper(itemList));
            setResult(Activity.RESULT_OK, okIntent);
            finish();
        }
    });

and MainActivity.java
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {

        switch (requestCode) {
        case ADD_NOTE:
            Log.w("1", "one");

            DataWrapper dw = (DataWrapper) getIntent().getSerializableExtra("item");

            Log.w("2", "two");

            entryList = dw.getEntryList();

            Log.w("3", "three");

            //String extraName = AddItem.code;
            //ArrayList<Entry> list = data.getParcelableArrayListExtra(extraName);
            todoItems.addAll(entryList);

            Log.w("4", "four");

            todoArrayAdapter.notifyDataSetChanged();

            Log.w("5", "five");

            break;

A:

replace
DataWrapper dw = (DataWrapper) getIntent().getSerializableExtra("item");

with
DataWrapper dw = (DataWrapper) data.getSerializableExtra("item");

in onActivityResult()...


Q:

JQuery replace html element contents if ID begins with prefix

I am looking to move or copy the contents of an HTML element. This has been asked before and I can get innerHTML() or Jquery's html() method to work, but I am trying to automate it.
If an element's ID begins with 'rep_', replace the contents of the element after the underscore.
So,

Hello World.

would replace:

Hrm it doesn't seem to work..

I've tried:
$(document).ready(function() {
    $('[id^="rep_"]').html(function() {
        $(this).replaceAll($(this).replace('rep_', ''));
    });
});

-and-
$(document).ready(function() {
    $('[id^="rep_"]').each(function() {
        $(this).replace('rep_', '').html($(this));
    });
});

Neither seem to work, however, this does work, only manual:
var target = document.getElementById('rep_target').innerHTML;
document.getElementById('target').innerHTML = target;

Related, but this is only text.
JQuery replace all text for element containing string in id

A:

You have two basic options for the first part: replace with an HTML string, or replace with actual elements.
Option #1: HTML
$('#target').html($('#rep_target').html());

Option #2: Elements
$('#target').empty().append($('#rep_target').children());

If you have no preference, the latter option is better, as the browser won't have to re-construct all the DOM bits (whenever the browser turns HTML in to elements, it takes work and thus affects performance; option #2 avoids that work by not making the browser create any new elements).
That should cover replacing the insides.  You also want to change the ID of the element, and that has only one way (that I know)
var $this = $(this)
$this.attr($this.attr('id').replace('rep_', ''));

So, putting it all together, something like:
$('[id^="rep_"]').each(function() {
    var $this = $(this)
    // Get the ID without the "rep_" part
    var nonRepId = $this.attr('id').replace('rep_', '');
    // Clear the nonRep element, then add all of the rep element's children to it
    $('#' + nonRepId).empty().append($this.children());

    // Alternatively you could also do:
    // $('#' + nonRepId).html($this.html());

    // Change the ID
    $this.attr(nonRepId);

    // If you're done with with the repId element, you may want to delete it:
    // $this.remove();
});

should do the trick.  Hope that helps.


Q:

ssrs 2005 matrix divide count value by the subtotal

I have this table
SELECT ProductName, Grade, COUNT(Grade) AS count
FROM   Inspection
WHERE (Branch = @branchno) AND (Date BETWEEN @DateFrom AND DATEADD(day, 1, @DateTo))
          AND (Grade <> '')
GROUP BY ProductName, Grade
ORDER BY ProductName

and the report matrix has subtotals that i would like to divide with count of grade
                         | =Fields!grade.Value       |Total
========================= =========================== ======
=Fields!ProductName.Value|=Sum(Fields!count.Value)   |

but ive been trying to get the fields count value to divide by the total value but having trouble with that
cause what i need the table to look like is this
       Grade 1 | Grade 2 | Grade 3 |  bad
======|========|=========|=========|=======
orange| 17.65% |  11.76% |  58.82% | 11.76%
------ -------- --------- ---------|--------
banana| 13.33% |  13.33% |  53.33% | 20.00%

which we would get by doing the following
       Grade 1 | Grade 2 | Grade 3 |  bad  | Total
======|========|=========|=========|=======|======
orange|  3/17  |  2/17   |  10/17  |  2/17 | 17
------ -------- --------- --------- ------- ------
banana|  2/15  |  2/15   |  8/15   |  3/15 | 15

Thanks for your help

A:

Thanks to Maciej from http://www.codeproject.com/ we got this to work
SELECT ProductName, Grade, COUNT(Grade) AS CountOfGrades, (SELECT COUNT(Grade) FROM Inspection WHERE (Branch = @branchno) AND (Date BETWEEN @DateFrom AND DATEADD(day, 1, @DateTo))
          AND (Grade<>'') AND (productname=i.productname) AS TotalOfGrades
FROM   Inspection as i.inspection
WHERE (Branch = @branchno) AND (Date BETWEEN @DateFrom AND DATEADD(day, 1, @DateTo))
          AND (Grade <>'')
GROUP BY ProductName, Grade
ORDER BY ProductName


Q:

Can we define the Schema Model dynamically in the kendo ui

I am using KendoUi controls. I have defined the dataSource like
  var dataSource = new kendo.data.DataSource({
   schema: {
    model: {
       id: "ProductID",
         fields: {
            ProductID: { type:"id" },
            ProductName: {type:"string"}
           }
         }
       }
     });

Now my question is can we define fileds as an array like
 var arry = [{ProductID:{type:"id"}}, {ProductName:{type:"string"}}];

Now can we define the dataSource like
 var dataSource = new kendo.data.DataSource({
   schema: {
    model: {
       id: "ProductID",
         fields: arry
         }
       }
     });

A:

Both definitions are not equivalent.
The first one:
fields: {
    ProductID: { type:"id" },
    ProductName: {type:"string"}
}

uses associate arrays (index are ProductID and ProductName) while the second:
var arry = [{ProductID:{type:"id"}}, {ProductName:{type:"string"}}];
...
fields: arry
...

You use an array with index 0 and 1.
You can define them dynamically but you should define arry as:
var arry = { ProductID:{type:"id"}, ProductName:{type:"string"} };

or
var arry = {};
arry.ProductID = { type: "id" };
arry.ProductName = { type : "string" };

or
var arry = {};
arry["ProductID"] = { type: "id" };
arry["ProductName"] = { type : "string" };

but arr needs to be an object and not an array


Q:

Android dev in Intellij,How to clean PNG cache only?

Is there anyway to clean cache(like png),as we do in eclipse -->clean project.
I knew it can do file-->invalidate caches,but in this way, the local history will be cleaned also. I just clean PNG caches,because sometimes we modified some png,then save as the same name, when we run programe again,the png will still use the cache file.It puzzle me for a long time.Anyone could help me? thanks a lot!

A:

Try Build -> Rebuild Project.


Q:

How to execute a perl script on crontab

I have written a perl script test.pl which uses a subroutine written in another file testing .pm. I'm able to run this script successfully manually, but when I run the same script on crontab, I get the following error
Can't locate testing.pm in @INC
I have changed the permissions of both the files to execute permission and used "use testing" at the top of the script. How can I successfully run the script on crontab.
Crontab : */2 * * * *  PERL5LIB=$PERL5LIB:/home/test/testing.pm /home/test/test.pl > /home/test/test.log 2>&1
**
test.pl
#!/usr/bin/perl -w
 use DBI;
 use warnings;
 use Time::Piece;
 use HTML::Entities;
 use lib '/home/test';
 use testing
# Connecting to the database #
my $dbh = DBI->connect("DBI:mysql:database=test;host=localhost;mysql_socket=/var/run/mysqld/mysqld.sock","root","password", {'RaiseError' => 1});
# my $dob = '2009-04-21 00:00:00';
my $dob = '2009-04-22 00:00:00';
#my $dob = localtime->strftime('%Y-%m-%d %H:%M:%S');
print "\ndob : $dob\n";
$name="test";
$number=1;
$email="test@test.com"
$id="123";
if ($mail==0)
{
 send_msg(0,$name,$number,$email,$aid);
}
if ($sms==0)
{
 send_msg(1,$name,$number,$email,$id);
}
}
sub send_msg {
   my ($type,$name,$number,$email,$id) = @_;
   $sql7 = "select Sms,email from settings where Id='$id'";
   $sth7 = $dbh->prepare($sql7);
   $sth7->execute
   or die "SQL Error: $DBI::errstr\n";
   my ($sms,$email)=$sth7->fetchrow_array();
   my $xml=testing::xml($type,$name,$number,$email,$sms,$email);
}

**

A:

You will have to tell your Perl binary where to look for testing.pm. You could do this in your crontab:
0 * * * * PERL5LIB=$PERL5LIB:/directory/where/testing.pm/lives perl myperlscript.pl

Or you could do it in your .pl script by using use lib:
#!/usr/bin/perl
use strict;
use warnings;
use lib '/directory/where/testing.pm/lives';
...

Update:
Your edited question shows several problems:

Your crontab says PERL5LIB=$PERL5LIB:/home/test/testing.pm. You need to add the directory to PERL5LIB not the path to the file. The correct version would be: `PERL5LIB=$PERL5LIB:/home/test'.
Your test.pl says use testing. There is no semicolon to be found anywhere after testing.


Q:

Python Selenium only getting first row when iterating over table

I am trying to extract the most recent headlines from the following news site:
http://news.sina.com.cn/hotnews/
#save ids of relevant buttons that need to be clicked on the site
buttons_ids = ['Tab21' , 'Tab22', 'Tab32']

#save ids of relevant subsections
con_ids = ['Con11']

#start webdriver, go to site, hover over buttons
driver = webdriver.Chrome()
driver.get("http://news.sina.com.cn/hotnews/")
time.sleep(3)
for button_id in buttons_ids:
    button = driver.find_element_by_id(button_id)
    ActionChains(driver).move_to_element(button).perform()

Then I iterate through each section that I am interested in and within each section through all the headlines which are rows in an HTML table. However, on every iteration, it returns the first element
for con_id in con_ids:
    for news_id in range(2,10):
        print(news_id)
        headline = driver.find_element_by_xpath("//div[@id='"+con_id+"']/table/tbody/tr["+str(news_id)+"]")
        text = headline.find_element_by_xpath("//td[2]/a")
        print(text.get_attribute("innerText"))
        print(text.get_attribute("href"))
        com_no = comment.find_element_by_xpath("//td[3]/a")
        print(com_no.get_attribute("innerText"))

I also tried the following approach by essentially saving the table as a list and then iterating through the rows:
for con_id in con_ids:
    table = driver.find_elements_by_xpath("//div[@id='"+con_id+"']/table/tbody/tr")
    for headline in table:
        text = headline.find_element_by_xpath("//td[2]/a")
        print(text.get_attribute("innerText"))
        print(text.get_attribute("href"))
        com_no = comment.find_element_by_xpath("//td[3]/a")
        print(com_no.get_attribute("innerText"))

In the second case I get exactly the number of headlines in the section, so it apparently correctly picks up the number of rows. However, it is still only returning the first row on all iterations. Where am I going wrong? I know a similar question has been asked here: Selenium Python iterate over a table of rows it is stopping at the first row but I am still unable to figure out where I am going wrong.

A:

In XPath, queries that begin with // will search relative to the document root; so even though you're calling find_element_by_xpath() on the correct container element, you're breaking out of that scope, thereby performing the same global search and yielding the same result every time.
To constrain your query to descendants of the current element, begin your query with .//, e.g.,:
text = headline.find_element_by_xpath(".//td[2]/a")


Q:

jQuery bind on change of length

I have a table that is being updated by Ajax. I want to do something when new data is added to it, but since the change is in appearance, it should be done by the preloaded JS rather than Ajax returned JS.
I am looking for something like $('table tr').length.change( ... ), So I can do something like this
$('table tr').length.change( function() {
  if ($('table tr').length>1) $('table').show() else $('table').hide()
}

The Ajax-returned JS will do something like this (say in Rails)
$('table').append('
 <%= @person.name %>	 <%= @person.age %>
')

(in Rails this will be in some /app/views/container_name/method_name.js.erb)

A:

You could use a pub-sub approach.
$('table')
   .append('
 <%= @person.name %>	 <%= @person.age %>
')
   .trigger('tableModified');

Then in your layout/design,
$('table').on('tableModified',function(){
    if ($('tr', this).length>1) $(this).show() else $(this).hide()
});

This way your table code doesn't have to be aware of your layout/design or anything else that may need to know when the table is modified.


Q:

state disappears when method is call

I'm working on a class project and my state is disappearing. After componentDidMount console.log(this.state) is fine. I initiate setInterval and call inc().  Somehow when I enter inc() the state gets wiped out.

import React from 'react';
import { TextInput,Button,StyleSheet, Text, View } from 'react-native';
import styles from './styles/styles.js';

debug=true

export default class App extends React.Component {
  constructor(){
    super()
    this.state={timer:'WORK',
                workTime: 25*60+0,
                breakTime: 5*60+0,
                currentTime:0,
                remainingTime:null,
                min:0,
                sec:0,
                startFlag:false,
                resetFlag:false}
  }
  componentDidMount(){
    this.interval=setInterval(this.inc,10000)
    if(debug)console.log('COMPONENTDIDMOUNT',this.state)
  }
  static getDerivedStateFromProps(nextProps, prevState) {
    if(debug)console.log('GETDERIVEDSTATEFROMPROPS',prevState)
  return null
  }
  shouldComponentUpdate(nextProps,nextState){
    if(debug)console.log('SHOULDCOMPONENTUPDATE',nextState)
    return true
  }
  componentDidUpdate(){
   if(debug)console.log('COMPONENTDIDUPDATE',this.state)
  }
  componentWillUnmount(){
   if(debug)console.log('COMMPONENTWILLUNMOUNT',this.state)
  }

  startToggle(){
    if(endTime === null)this.setState({remainingTime:this.state.workTime,
                                         startFlag:!this.state.startToggle})
    else this.setState({remainingTime:!this.state.startFlag})
  }
  textTime(){
    let min = Math.floor(this.state.remainingTime / 60).toString()
    let sec = (this.state.remainingTime % 60)
    if (sec < 10)sec ? '0' + sec : sec.toString()
    this.setState({min:min,sec:sec})
  }

  inc(){
    console.log(this.state)
  }

  captureInput(){}

  render() {
    console.log('RENDER',this.state)

    return (
      <View style={styles.container}>
        <Text style={styles.bigFont}>{`${this.state.timer + 'TIMER'}`}</Text>
        <Text style={styles.bigFont}>12:00</Text>
        <View style={styles.button}>
          <Button title='START' onPress={()=>this.startToggle()} />
          <Button title='RESET' onPress={()=>this.resetToggle()} />
        </View>
             <View style={styles.row}>
                <Text style={[styles.bold,{marginRight:10},{width:112},
                            {textAlign:'right'}]}>
                            'Work Timer:'</Text>
                <Text style={styles.bold}> min:</Text>
                <TextInput
                   defaultValue='50'
                   style={styles.input}
                   onChangeText={(text) => {this.captureInput(text)}}
                />
                <Text style={styles.bold}> sec:</Text>
                <TextInput
                   defaultValue='50'
                   style={styles.input}
                   onChangeText={(text) => {this.captureInput(text)}}
                />
             </View>
             <View style={styles.row}>
                <Text style={[styles.bold,{marginRight:10},{width:112},
                            {textAlign:'right'}]}>
                            'Break Timer:'</Text>
                <Text style={styles.bold}> min:</Text>
                <TextInput
                   defaultValue='50'
                   style={styles.input}
                   onChangeText={(text) => {this.captureInput(text)}}
                />
                <Text style={styles.bold}> sec:</Text>
                <TextInput
                   defaultValue='50'
                   style={styles.input}
                   onChangeText={(text) => {this.captureInput(text)}}
                />
             </View>
      </View>
    )
  }
}

A:

You have 2 options:

Change inc() to inc = () =>
or
Change this.inc to this.inc.bind(this)


Q:

Не работает ::after и ::before

                <form action="" class="form-action">
                    Регистрация

                        <input class="input-email" type="text" name="email">

                        <input class="input-login" type="text" name="login">

                        <input class="input-password" type="password" name="password">

                </form>

В чем проблема ? По идее все верно сделано.
При нажатии на поле, подсказка (Email, Login, Password) должны подниматься вверх и полоска заливаться градиентом. Пример: prntscr.com/nwgkrn

A:

• Селектор :focus (не путать с классом .focus) поддерживают только элементы <input>, <textarea>, <button> (возможно кого-то не знаю).
• Запись двух селекторов через пробел, означает что второй находится где-то внутри первого. В данном случае input, на котором сейчас поставлен фокус - должен находться где-то внутри .form-input.
• Символ ~ находит элемент, который находится где-то ниже в коде от первого. При этом они оба не должны быть обернуты в дополнительные теги. В данном случае нужный span.focus прямо под input:focus, поэтому сработает.
.form-input input:focus ~ .focus::after {...} — Перевод на Русский: Поменять что-то у псевдоэлемента :after у класса .focus, но который находится ниже в коде от input, на который поставлен фокус, и который находится внутри .form-input
.form-input input:focus ~ .focus::after {
  transition: 0.5s;
  top: -10px;
}

.form-input input:focus ~ .focus::before {
  transition: 0.5s;
  width: 100%;
}

Почти есть желаемый результат, но если ввести что-нибудь в инпут и убрать фокус - оно возвращается на место. Посмотрел на исходный код - а на инпут добавляется класс has-val, когда в нем что-то введено. Дальше уже без JS никак.
var input = document.querySelectorAll('.form-input input');
//Нашли и сохранили все инпуты внутри блоков с этим классом
var i;
for( i = 0; i < input.length; i++){
  //Для каждого из них добавляем функцию, которая будет запускаться при вводе текста
  input[i].addEventListener('input', function(){
    if(this.value == ""){
      //Если текст внутри окажется равным пустой строке - убираем класс
      this.classList.remove('has-val');
    } else { // Иначе - добавляем.
      this.classList.add('has-val');
    }
  });
}

И к добавляемому классу, тоже небольшой CSS:
.form-input input.has-val ~ .focus::after {
  transition: 0.5s;
  top: -10px;
}

.form-input input.has-val ~ .focus::before {
  transition: 0.5s;
  width: 100%;
}

Результат:

var input = document.querySelectorAll('.form-input input');
var i;
for( i = 0; i < input.length; i++){
  input[i].addEventListener('input', function(){
    if(this.value == ""){
      this.classList.remove('has-val');
    } else {
      this.classList.add('has-val');
    }
  });
}
* {
  margin: 0;
  padding: 0;
}
body, html {
    background-color: #ECEFF4;
    height: 100%;
}
.tc {
    text-align: center;
}
.wrapper {
    width: 100%;
    margin: 0 auto
}
.content {
    width: 100%;
    min-height: 100vh;
    display: -webkit-box;
    display: -webkit-flex;
    display: -moz-box;
    display: -ms-flexbox;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
}
.form-reg {
    width: 390px;
    background: #fff;
    border-radius: 10px;
    overflow: hidden;
    padding: 77px 55px 33px 55px;
    box-shadow: 0 5px 10px 0px rgba(0, 0, 0, 0.1);
    -moz-box-shadow: 0 5px 10px 0px rgba(0, 0, 0, 0.1);
    -webkit-box-shadow: 0 5px 10px 0px rgba(0, 0, 0, 0.1);
    -o-box-shadow: 0 5px 10px 0px rgba(0, 0, 0, 0.1);
    -ms-box-shadow: 0 5px 10px 0px rgba(0, 0, 0, 0.1);
}
.form-action {
    width: 100%;
}
.form-name {
    display: block;
    font-weight:bold;
    font-family: 'Poppins', sans-serif;
    font-size: 30px;
    color: #333333;
    line-height: 1.2;
    text-align: center;
    padding-bottom: 26px;
}
.form-title {
    display: block;
    font-size: 30px;
    color: #333333;
    line-height: 1.2;
    text-align: center;
    padding-bottom: 48px;
}
input {
    outline: none;
    border: none;
}
.form-input {
    width: 100%;
    position: relative;
    border-bottom: 2px solid #adadad;
    margin-bottom: 37px;
}
.input-email, .input-login, .input-password {
    font-family: 'Poppins', sans-serif;
    font-size: 15px;
    color: #555555;
    line-height: 1.2;
    display: block;
    width: 100%;
    height: 45px;
    background: transparent;
    padding: 0 5px;
}
.focus {
    position: absolute;
    display: block;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    pointer-events: none;
}
.focus::before {
    content: "";
    display: block;
    position: absolute;
    bottom: -2px;
    left: 0;
    width: 0;
    height: 2px;
    -webkit-transition: all 0.4s;
    -o-transition: all 0.4s;
    -moz-transition: all 0.4s;
    transition: all 0.4s;
    background: #6a7dfe;
    background: -webkit-linear-gradient(left, #21d4fd, #b721ff);
    background: -o-linear-gradient(left, #21d4fd, #b721ff);
    background: -moz-linear-gradient(left, #21d4fd, #b721ff);
    background: linear-gradient(left, #21d4fd, #b721ff);
}
.focus::after {
    content: attr(data-placeholder);
    font-family: 'Poppins', sans-serif;
    font-size: 15px;
    color: #999999;
    line-height: 1.2;
    display: block;
    width: 100%;
    position: absolute;
    top: 16px;
    left: 0px;
    padding-left: 5px;
    -webkit-transition: all 0.4s;
    -o-transition: all 0.4s;
    -moz-transition: all 0.4s;
    transition: all 0.4s;
}

::after, ::before {
    box-sizing: inherit;
}
button, input {
    overflow: visible;
}

.form-input input:focus ~ .focus::after {
  transition: 0.5s;
  top: -12px;
}

.form-input input:focus ~ .focus::before {
  transition: 0.5s;
  width: 100%;
}

.form-input input.has-val ~ .focus::after {
  transition: 0.5s;
  top: -12px;
}

.form-input input.has-val ~ .focus::before {
  transition: 0.5s;
  width: 100%;
}

      <form action="" class="form-action">
        Регистрация

          <input class="input-email" type="text" name="email">

          <input class="input-login" type="text" name="login">

          <input class="input-password" type="password" name="password">

      </form>


Q:

Bootstrap popovers on Rails simple_form inputs

I'm trying to show some popovers in a form I am currently building. They should appear when the user has focus on a specific field, but I can't quite manage to do so, here is what I got (in Slim):
#sample_form=simple_form_for sample do |form|
    =form.input :sample_name, placeholder: "Name", rel="popover" data-content="content" data-original-title="title"

javascript:
    $('#sample_form input').hover(function()
        {
            $(this).popover('show')
        });

And here is what I get when I try to load the page:
..._form.html.slim:4: syntax error, unexpected tIDENTIFIER, expecting tASSOC
...", rel="popover" data-content="lol" data-original-...
...                     ^
..._form.html.slim:4: syntax error, unexpected tIDENTIFIER, expecting ')'
...opover" data-content="content" data-original-title="title"))).to_...
...                                   ^

Probably a simple syntax mistake but I can't figure it out.
Thanks in advance.

A:

The problem is that you are mixing Slim and Ruby together on the second line. Try something like this instead:
= form.input :sample_name, placeholder: "Name", :input_html => {:rel => "popover", :data => {:content => "content", "original-title" => "title"}}


Q:

JUNIT : run setup only once for a large number of test classes

I have a class, which I use as a basis for my unit tests. In this class I initialize the whole environment for my tests, setting up database mappings, enter a number of database records across multiple tables, etc. That class has a method with a @BeforeClass annotation which does the initialization. Next thing, I extend that class with specific classes in which I have @Test methods.
My question is, since the before class is exactly the same for all these test classes, how can I ensure that they are run only once for all the tests.
One simple solution is that I could keep all the tests in one class. However, the number of tests is huge, also they are categorised based on functional heads. So they are located in different classes. However since they need the exact same setup, they inherit the @BeforeClass. As a result the whole setup is done at least once per test class, taking much more time in total than I would prefer.
I could, though, put them all in various subpackages under one package, hence if there is a way, how I can run set up once for all the tests within that package, it would be great.

A:

With JUnit4 test suite you can do something like this :
@RunWith(Suite.class)
@Suite.SuiteClasses({ Test1IT.class, Test2IT.class })
public class IntegrationTestSuite
{
    @BeforeClass
    public static void setUp()
    {
        System.out.println("Runs before all tests in the annotation above.");
    }

    @AfterClass
    public static void tearDown()
    {
        System.out.println("Runs after all tests in the annotation above.");
    }
}

Then you run this class as you would run a normal test class and it will run all of your tests.

A:

JUnit doesn't support this, you will have to use the standard Java work-arounds for singletons: Move the common setup code into a static code block and then call an empty method in this class:
 static {
     ...init code here...
 }

 public static void init() {} // Empty method to trigger the execution of the block above

Make sure that all tests call init(), for example my putting it into a @BeforeClass method. Or put the static code block into a shared base class.
Alternatively, use a global variable:
 private static boolean initialize = true;
 public static void init() {
     if(!initialize) return;
     initialize = false;

     ...init code here...
 }


Q:

How do I order a group by clause in sql

I want to select from my FileList all different files using group by. But I want to get Back only the elements with the highest id. I only get the first entry back.
How to fix this?
select * from files group by name;

This is my table-content...
 ID      NAME          DATE               USER
1443 - /test.txt - 24 May 2013 12:56:15 - XX
1444 - /test.txt - 24 May 2013 12:54:41 - XX
1445 - /test.txt - 24 May 2013 12:53:38 - AB
1446 - /test.txt - 24 May 2013 12:44:32 - XX
1983 - /asdf.txt - 24 May 2013 13:46:32 - KS

A:

select * from files
where id in
(
  select max(id)
  from files
  group by name
)

or
select f.*
from files f
inner join
(
  select max(id) as id
  from files
  group by name
) x on x.id = f.id

SQLFiddle demo


Q:

How to configure Django application at http://SERVER-IP/ instead of http://SERVER-IP/Project using bitnami aws?

I want to serve Django application at http://SERVER-IP/ OR a domain (www.example.com) instead of http://SERVER-IP/Project (www.example.com/Project) using BITNAMI Django Stack(v4.2).
I followed the documentation here for creating new application which is working perfect but I didn't find the way how to configure Django application at http://SERVER-IP/.
OS Details:
PRETTY_NAME="Debian GNU/Linux 9 (stretch)"
NAME="Debian GNU/Linux"
VERSION_ID="9"
VERSION="9 (stretch)"
ID=debian

I had tried:

Move application files form ~/apps/django/django_projects/PROJECT/ to ~/apps/django/django_projects/
Updated all path in thses conf files:

httpd-prefix.conf
httpd-app.conf
PROJECT/wsgi.py

Restart the Apache server.

But unfortunately, still I'm getting the apache homepage at http://SERVER-IP/ instead of Django application homepage. One more thing Django application still accessible at http://SERVER-IP/Project successfully.
Note: I need both services is running php and django.
PHP demo app I've placed in htdocs/demo/index.php I want also this approachable form URL http://SERVER-IP/hello/index.php.
Someone, please guide me!!! How to do that?

A:

In order to change the URL for your Django project to "/", you need to modify this file (supposing that the project you want to move to "/" is "Project"):
INSTALLDIR/apps/django/django_projects/Project/conf/httpd-app.conf

Inside the file, change these lines:
Alias /Project/static "INSTALLDIR/..."
WSGIScriptAlias /Project 'INSTALLDIR/...'

To this:
Alias /static "INSTALLDIR/..."
WSGIScriptAlias / 'INSTALLDIR/...'

And restart Apache after that:
sudo INSTALLDIR/ctlscript.sh restart

Please refer Bitnami Django For AWS Cloud And  How can change the default URL


Q:

Custom json response for internal exception in spring

While implementing a global exception handler in Spring, I noticed that in case of a not recognized Accept header, Spring would throw it's own internal error. What I need is to return a custom JSON error structure instead. Works fine for application specific exceptions and totally fails for Spring HttpMediaTypeNotAcceptableException.
This code tells me "Failed to invoke @ExceptionHandler method: public java.util.Map RestExceptionHandler.springMalformedAcceptHeaderException()" when I try to request a page with incorrect Accept header. Any other way to return custom JSON for spring internal exceptions?
@ControllerAdvice
public class RestExceptionHandler {

    @ExceptionHandler(value = HttpMediaTypeNotAcceptableException.class)
    @ResponseBody
    public Map<String, String> springMalformedAcceptHeaderException() {

         Map<String, String> test = new HashMap<String, String>();
         test.put("test", "test");
         return test;
     }
}

A:

Eventually figured that the only way is to do the json mapping manually.
@ExceptionHandler(value = HttpMediaTypeNotAcceptableException.class)
@ResponseBody
public String springMalformedAcceptHeaderException(HttpServletResponse response) {
    // populate errorObj, set response headers, etc
    ObjectWriter jsonWriter = new ObjectMapper().writer();
    try {
        return  jsonWriter.writeValueAsString(errorObj);
    } catch(Exception e){}
    return "Whatever";
}


Q:

Java Script redirect approcach

I have a java script code where I try to redirect to a different url. Also I need to pass certain information during the redirect. So, my code looks like this:
function testRedirectCode(){

 var dataToBePassed = "abc";

 var url="https://anydomain.com/hello.aspx";
 var form=$('<form action="'+url+'"
     method="post">'+'<input type="text" name="srcUrl" value="http://myapplication.com/helloPage" />'
     +'<input type="text" name="data" value="'+dataToBePassed+'" />'
     +'</form>');
     $('body').append(form);
    form.submit();
}

My 2 problems:
1) Is there a more clean way of writing the src url than hardcoding i.e. identify the current url and pass the same in this value.
2) I see that on my button click I am able to get redirected on the new page but the problem is that instantaneously I am again redirected to my srcUrl.
Anyway of getting past this?
Thanks in advance
-Vivek

A:

Yes! you can identify the current url without hardcoding it
To get the current url

<script>

var url =window.location.href;
console.log(url);

var protocol =location.protocol; //http or https

var baseUrl =location.hostname; //myapplication.com

var path =location.pathname; //login

var urlSrc =protocol +'//' +baseUrl+ '/'+path
console.log(urlSrc);

</script>


Q:

What types of tree are these?

I would like to know the names of these trees. And whether the small black berry looking fruits are edible.
Edit: The small tree is not doing well, so I want to learn more about this tree in order to give it the best chance to survive.

A:

The first one looks like Hawthorn, or Crataegus. But for more specific ID we need to see the fruits as well. See here for an example with the same leaf shape.
The second one is a Prunus, I think a Prunus serrulata 'Royal Burgundy' (as seen here), but it could be another variety as well. This cherry tree is more ornamental, and not meant for fruit production. So the fruits are edible, but won't taste as good as the real cherry. See here about edibility of fruit that come from ornamental trees.
Your trees look indeed not in perfect shape, and stormy gives you already some advice. Maybe more people (arborists) here can give you more advice.


Q:

Getting rid of inadvertent "actionPerformed: code in Java Netbeans

When I create event-handling code for a component on a form, it shows up with grayed-background lines and a "do not edit" warning.  They don't need to post the warning, because the code cannot be edited! However, I may (and have) goof by accidentally double-clicking a component, which inserts actionPerformed code in my main.java file.
I find that that grayed portion of the actionPerformed code can't be moved or deleted. Is there a secret ritual by which I can eliminate or move such code blocks?

A:

Go back into the form editor and simply delete the "xxxActionPerformed" out of the text box (in the list of possible event handlers).
Explained in slightly more detail here


Q:

TCP Socket send/receive always waiting

I have a TCP connection between a server and a client. Server sending data, client receiving data and client feedback the server. But if client closes socket and creates again, server never accept it because it is waiting feedback from client. So how can i solve that?
Server
byte[] buffer = new byte[1000];
string ip = "192.168.1.17";
int port = 15500;

IPAddress ipAddress = IPAddress.Parse(ip);
IPEndPoint localEndpoint = new IPEndPoint(ipAddress, port);

Socket sock = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

Console.WriteLine("Waiting client...");
sock.Bind(localEndpoint);
sock.Listen(5);

Socket confd = sock.Accept();

Console.WriteLine("Connected with {0} at port {1}", ip, port);
Sender sender = new Sender();
Receiver receiver = new Receiver();

while (true) {
    if (confd.Connected) {
        sender.SendData(confd);
        receiver.ReceiveData(confd); //Waiting here
    }
    else {
        confd.Close();
        Console.WriteLine("Waiting client...");
        confd = sock.Accept();
    }
}

A:

Having a thread per socket is usually a bad idea. Having a single thread that deals with socket IO and accepting connections is usually a terrible idea. There are a myriad reasons why a socket disconnect can go unnoticed - either for a while, or in some cases: indefinitely. The way to avoid this problem is usually to have one thread (or theses days: async loop) dedicated to accepting connections, and initializing connections, and then rather than creating a thread per socket, use async IO to read/write without requiring threads. Although if you have a very low number of sockets, you might be able to get away with thread-per-socket. Finally, either use read/write timeouts, or have a periodic "have I seen this socket lately?" check (over all sockets), to help shut down sockets that have failed silently.


Q:

Textmate Clone for Windows?

Havent checked in a while but is there any good text editors out there. I have tryed e-text editor and sublime. They are perfect, but I want something with more features but not as bloated as notepad+

A:

I would recommend Vim


Q:

Are there any reasons I shouldn’t use a nodemcu’s 3.3v pin with this component?

I have this Hydrogen Sulfide gas sensor and the datasheet says the supply voltage requires a regulated voltage with a min of 2.6v and max of 3.6v
I can’t find any datasheet for the nodemcu v3 (spent hours looking, but none mention anything relevant) that’s says whether or not the power output of the 3.3 pin is regulated (how can I tell?) but others have said an Arduino Uno’s 5v and 3.3v pins are regulated.  Assuming it is regulated (I know what they say about assumptions), are there any reasons why I should be concerned about using the 3.3 pin?
What about using the aforementioned Arduino Uno, whose power pins are regulated?
This sensor is kinda pricey and I don’t want to burn it out due to stupidity.

A:

The 3v3 rails of both NodeMCU and Arduino boards should indeed be regulated.
The more meaningful question is how much current they are able to safely provide to external devices.  On Arduino boards where the MCU runs at 5v, the 3v3 rails are often produced by an on-chip regulator in the USB interface and don't have much current to spare.
In the NodeMCU case, the ESP8266 (or ESP32) is itself running off 3v3 so typically a SOT223 or SOT23-5 regulator is used.  These generally have higher current capacity.
The data sheet for your device implies it draws 4 mA from the supply.  Almost any discrete regulator would be chosen with enough margin to be able to supply that along with the on-board loads.   It's fairly likely even the USB-chip's weak 3v3 supply as found in an Arduino could handle this, as long as you were not adding additional things as well.
It may be that using a separate regulator or various LC filtering approaches would yield a quieter sensor reading, but it would be worth seeing what you get in the easy case before worrying about that.


Q:

Positive roots of polynomial $q(x)=p(x)+k^2$

Let $p(x)$ a polynomial of degree $n\in\mathbb N$ such that
$$p(x)=0$$
has exactly $n$ real and positive solutions. Is it true that polynomial $q(x)=p(x)+k^2$, for $k\in\mathbb R$ has only positive roots?
I think the answer is: yes. Because the sum of a function to a number only has the effect of translate it upwards and downwards.

A:

Consider $P(x)=x-1$, which has the root $x=1$.
Now consider $Q(x)=x+3$ ($k=2$), which has the root $x=-3$.


Q:

Running a JavaScript script in all browsers installed on an operating system from one place

I have a JavaScript script that blocks a group of 1 or more websites I don't wish to visit like news websites that I have an addiction-like behavior to.
It is a hassle for me to run it in three different environments: Firefox (Greasemonkey), Chrome (Tampermonkey), Edge (Tampermonkey).
Is there a more aesthetic way to on it for all browsers "brutally" (without specifically allow it in a given browser)?
As I use Windows10 mostly maybe an AutoHotkey solution be helpful but I do care about Linux users (which I'm one of them).

A:

I'd use a Proxy-Server to restrict the user to go to specific Websites:
It works for Windows, Linux  and Mac and is Browser independent.
In addition Javascript could be disabled in the Browser and your Script takes no effect.


Q:

How To Convert JSON String That Contains Encoded Unicode

Could anyone tell me how to convert the following json object string, which contains encoded unicode characters (Chinese in this case) to human readable one using c# in asp.net?
records:[{"description":"\u849c\u8089","id":282}]

The string is submitted via Ajax from an Ext JS web application.
Any help is much appreciated.

A:

There is no need to convert this string in any special manner. Any JSON decoder that more or less sticks to the specification will automatically create a correct string for the description attribute.
Update:
However, your current sample is not valid JSON. It's missing brackets or braces around the complete sample and it's missing double qutoes around records.
A correct JSON snippet would be:
{"records":[{"description":"\u849c\u8089","id":282}]}

Giving:

records:

[]

description: 蒜肉
id: 282


Q:

Copy instances of type T, when any of the methods of a named type T have a pointer receiver

I read The Go Programming Language Book recently, the good resource for learning golang programming language.
There is a paragraph in 6.2 section about copy instance of type T when it is pointer receiver or not in methods, that I can't understand it.
Is there any that explain this paragraph with a meaningful example?

6.2 Methods with a Pointer Receiver
If all the methods of a named type T have a receiver type of T itself (not *T ), it is safe to copy instances of that type; calling any of its methods necessarily makes a copy. For example, time.Duration values are liberally copied, including as arguments to functions. But if any method has a pointer receiver, you should avoid copying instances of T because doing so may violate internal invariants. For example, copying an instance of bytes.Buffer would cause the original and the copy to alias ( §2.3.2 ) the same underlying array of bytes. Subsequent method calls would have unpredictable effects.
(The Go Programming Language Alan A. A. Donovan · Brian W. Kernighan)

A:

When calling a method, the value the method is called on is first copied, and that copy is passed / used as the receiver.
If a type only has methods with value receivers, that means no matter what the methods do inside, and no matter what methods you (or anyone else) call, the methods won't be able to change the original value, because –as noted above– only a copy is passed and the method  could only modify the copy – and not he original.
So this means if you copy the value, you don't have to worry, neither  the methods called on the original nor on the copy can't / won't modify the value(s).
Not, when the type has methods with pointer receivers. If a method has a pointer receiver, the method can change / modify the pointed value, which is not a copy, it's the original value (only the pointer is a copy but it points to the original value).
Let's see an example. We create an int wrapper type, which has 2 fields: an int and an *int. We intend to store the same number in both fields, but one is a pointer (and we store the int in the pointed value):
type Wrapper struct {
    v int
    p *int
}

To make sure both values (v and *p) are the same, we provide a Set() method, which sets both:
func (w *Wrapper) Set(v int) {
    w.v = v
    *w.p = v
}

Wrapper.Set() has a pointer receiver (*Wrapper) as it has to modify the value (which is of type Wrapper). No matter what number we pass to Set(), we can be sure that once Set() returns, both v and *p will be the same, and equal to the number passed to Set().
Now if we have a value of Wrapper:
a := Wrapper{v: 0, p: new(int)}

We can call the Set() method on it:
a.Set(1)

The compiler will automatically take the address of a to use as the receiver, so the above code means (&a).Set(1).
We'd expect that any value of type Wrapper has the same number stored in Wrapper.v and *Wrapper.pv, if only the Set() method is used to change the fields' values.
Now let's see the problem if we make a copy of a:
a := Wrapper{v: 0, p: new(int)}
b := a
fmt.Printf("a.v=%d, a.p=%d;  b.v=%d, b.p=%d\n", a.v, *a.p, b.v, *b.p)

a.Set(1)
fmt.Printf("a.v=%d, a.p=%d;  b.v=%d, b.p=%d\n", a.v, *a.p, b.v, *b.p)

Output (try it on the Go Playground):
a.v=0, a.p=0;  b.v=0, b.p=0
a.v=1, a.p=1;  b.v=0, b.p=1

We made a copy of a (stored it in b), and printed the values. So far so good. Then we called a.Set(1), after which a is still good, but internal state of b became invalid: b.v does not equal to *b.p anymore. The explanation is quite clear: when we made a copy of a (which is a struct type), that copies the values of its fields (including the pointer p), and the pointer in b will point to the same value as the pointer in a. Hence modifying the pointed value will affect both copies of Wrapper, but we have 2 distinct v fields (they are non-pointers).
If you have methods with pointer receivers, you should work with pointer values.
Note that if you would copy a value of *Wrapper, everything would still be cool:
a := &Wrapper{v: 0, p: new(int)}
b := a
fmt.Printf("a.v=%d, a.p=%d;  b.v=%d, b.p=%d\n", a.v, *a.p, b.v, *b.p)

a.Set(1)
fmt.Printf("a.v=%d, a.p=%d;  b.v=%d, b.p=%d\n", a.v, *a.p, b.v, *b.p)

Output (try it on the Go Playground):
a.v=0, a.p=0;  b.v=0, b.p=0
a.v=1, a.p=1;  b.v=1, b.p=1

In this case a is a pointer, it's of type *Wrapper. We made a copy of it (stored it in b), called a.Set(), and both the internal state of a and b remained valid. Here we only have one Wrapper value, a only holds a pointer to it (its address). When we copy a, we only make a copy of the pointer value, and not the struct value (of type Wrapper).


Q:

How to implement a self-cancelling poller without using a var?

I'm curious if it's possible to safely implement a self-cancelling poller without using a var to keep the instance of akka.actor.Cancellable
So far, I came up with something like what you see in the example below. However, I'm curious if it's safe to assume that the "tick" message will never be dispatched before the hotswap happens, i.e the line that schedules the poller:
tick(1, 5, context.system.scheduler.schedule(Duration.Zero, 3 seconds, self, "tick"))

is basically the same as:
val poll = context.system.scheduler.schedule(Duration.Zero, 3 seconds, self, "tick")
tick(1, 5, poll)

So, I would think that in some cases the first tick would be received before the hotswap has a chance to happen... Thoughts?
import akka.actor.{Cancellable, ActorSystem}
import akka.actor.ActorDSL._
import concurrent.duration._

object PollerDemo {
  def run() {
    implicit val system = ActorSystem("DemoPoller")
    import system.dispatcher

    actor(new Act{
      become {
        case "tick" => println("UH-OH!")
        case "start" =>
          become {
            tick(1, 5, context.system.scheduler.schedule(Duration.Zero, 3 seconds, self, "tick"))
          }
      }
      def tick(curr:Long, max:Long, poll:Cancellable):Receive = {
        case "tick" => {
          println(s"poll $curr/$max")
          if(curr > max)
            cancel(poll)
          else
            become{ tick(curr + 1, max, poll) }
        }
      }
      def cancel(poll:Cancellable) {
        println("cancelling")
        poll.cancel()
        println(s"cancelled successfully? ${poll.isCancelled}")
        println("shutting down")
        context.system.shutdown()
      }
    }) ! "start"

    system.awaitTermination(1 minute)
  }
}

A:

My guess is that your code will be okay.  Remember, actors only process their mailbox one at a time.  When you receive the start message, you setup a timer that will deliver another message to the mailbox and then you swap the receive implementation.  Because you do the receive swap while you are still processing the start message, then you will have already changed the actors's receive behavior before it processes the next message in the mailbox.  So when it moves on to process the tick message you can be sure that it will be using the new receive behavior.
You could verify this by sending an additional tick message inside the first become like so:
become {
  self ! "tick"
  tick(1, 5, context.system.scheduler.schedule(Duration.Zero, 3 seconds, self, "tick"))
}

Here we are really eliminating the timer from the equation when asking if a message sent during the become block will be processed by the old receive or the new receive.  I did not run this, but from my understanding or akka, both of these ticks should be handled by the new receive.


Q:

Database setup and design for 15 questions game - PostgreSQL and Rails

I am working on a small game where people have the ability to create 15 question quizzes. I am struggling to figure out how to structure my database for the best optimization.  The questions each have a point value assigned to them (same kind of structure as who wants to be a millionaire). I am debating whether to keep everything in the same table or to separate the game from the questions (or anything else if there is a more efficient method).
Strategy 1:
Creating columns for each in the Game table.  So there would be a column for title, 100 point question, 100 point answer, 200 point question, 200 point answer, etc..
Strategy 2:
Creating a new table for questions.  Each question belongs to a game, and is assigned the point value, and an answer
Strategy 3:
Create many tables for each point value.  There would be a 100 table, a 200 table, etc.  The columns would then be only the question or answer.
Are any of these the most efficient way of implementing this game?   I am trying to learn how database setup can effect speed.

A:

Most of the time efficiency is not as important as normalisation. You should have a separate games, questions and answers tables. Your models would look something like:
class Game
  has_many :questions
end

class Question
  belongs_to :game
  has_many :answers
end

class Answer
  belongs_to :question
end


Q:

Protocol extension default method causing a "self is immutable" error

I am trying to extend a class-bound protocol (UITextInputTraits) with a default method:
extension UITextInputTraits where Self: UIView {

    func setTextInputTraits() {

        self.autocapitalizationType = .none // <- compiler error
    }
}

It gives a "Cannot assign to property: 'self' is immutable" error.
It works if I change the constraint from UIView to UITextField though, but that defeats the purpose of using protocols.
Why is it an error? How can I achieve implementing this default method?
Thank you!

cannot mark the func mutating, since 'mutating' isn't valid on methods in classes or class-bound protocols
tried sending messages to self, Objective-C style, but perform does not work with non-object value arguments:
func setTextInputTraits() {

    let sel = #selector(setter: self.autocapitalizationType)
    self.perform(sel, with: .none)
}

A:

It works if I change the constraint from UIView to UITextField though, but that defeats the purpose of using protocols. Why is it an error?

Because UIView doesn't already have an autocapitalizationType property. Thus, the compiler has no reason to believe that if it did have one, it would be settable.

How can I achieve implementing this default method?

I think you might be after something like this:
protocol MyTextInputTraits : UITextInputTraits {
    var autocapitalizationType: UITextAutocapitalizationType {get set}
}
extension MyTextInputTraits {
    func setTextInputTraits() {
       self.autocapitalizationType = .none
    }
}
extension UITextView : MyTextInputTraits {}
extension UITextField : MyTextInputTraits {}
extension UISearchBar : MyTextInputTraits {}


Q:

Sending messages to groups using SignalR Core

This is my first implementation of SignalR and I'm starting with SignalR Core so some of the examples and documentation don't seem to apply to the new version.
My objective is to send the received message to a particular chat room. I understand this could be achieved using Groups.
First question: I'm not seeing a way to check if a connection is already in a group. Do I NOT need to check if a connection is already in the Group? I receive a ChatRoomId with each message so I can easily add the user/connection to a Group. I just want to know if I need to check whether or not the connection is already a member of group.
Second question: I want to exclude the sender from receiving the broadcast of his own message. Looks like OthersInGroup has been removed from SignalR Core. How do I exclude the sender if I'm sending the message to a Group?
These are the options I'm getting from IntelliSense:

A:

For the first question:
There is no built in way to check if a connection is in a group. It is up to you to handle that via an injected service to your hub or a static Dictionary or something. So each time you call Groups.AddAsync and Groups.RemoveAsync you can keep track of that.
For the second question:
GroupExcept(string groupName, IReadOnlyList<string> excludeIds) was added recently and should be exactly what you're asking for.


Q:

How can I get my local host and port in a Java servlet method init()?

How do I retrieve the port number in the init method.
In a doGet or doPost I can use:
request.getLocalPort();

but in the init() method there is no request object.
I don't want to configure it, I want the port dynamically.

A:

You can't. There is no such thing as 'the' port. The container could be listening on any number of ports and any number of IP addresses.


Q:

Go SQL query inconsistency

I am experiencing some really weird inconsistencies when executing queries, and was wondering if anyone knew why.
Imagine I have a struct defined as follows:
type Result struct {
    Afield string      `db:"A"`
    Bfield interface{} `db:"B"`
    Cfield string      `db:"C"`
    Dfield string      `db:"D"`
}

And a MySQL Table with the following cols:
A : VARCHAR(50)
B : INT
C : VARCHAR(50)
D : VARCHAR(50)

The query I would like to execute:

SELECT A, B, C, D FROM table WHERE A="a"

first way it can be executed:
db.Get(&result, `SELECT A, B, C, D FROM table WHERE A="a"`)

second way it can be executed:
db.Get(&result, `SELECT A, B, C, D FROM table WHERE A=?`, "a")

The inconsistencies I am experiencing are as follows: When executing the query the first way, the type of Bfield is int. However, when executing the query the second time, it is []uint8.
This outcome is occurring for example when B is 1.
Why is the type of Bfield different depending on how the query is executed?
connection declaration:
// Connection is an interface for making queries.
type Connection interface {
    Exec(query string, args ...interface{}) (sql.Result, error)
    Get(dest interface{}, query string, args ...interface{}) error
    Select(dest interface{}, query string, args ...interface{}) error
}

EDIT
This is also happening using the Go database/sql package + driver. The queries below are assigning Bfield to []uint8 and int64 respectively.

db is of type *sql.DB

query 1:
db.QueryRow(SELECT A, B, C, D FROM table WHERE A="a").Scan(&result.Afield, &result.Bfield, &result.Cfield, &result.Dfield)
-- > type of Bfield is []uint8
query 2:
db.QueryRow(SELECT A, B, C, D FROM table WHERE A=?, "a").Scan(&result.Afield, &result.Bfield, &result.Cfield, &result.Dfield)
--> type of Bfield is int64
EDIT
Something else to note, when chaining multiple WHERE clauses, as long as at least 1 is populated using ?, the query will return int. Otherwise if they are all populated in the string, it will return []uint8

A:

Short answer: because the MySQL driver uses a different protocol for queries with and without parameters. Use a prepared statement to get consistent results.
The following explanation refers to the standard MySQL driver github.com/go-sql-driver/mysql, version 1.4
In the first case, the driver sends the query directly to MySQL, and interprets the result as a *textRows struct. This struct (almost) always decodes results into a byte slice, and leaves the conversion to a better type to the Go sql package. This works fine if the destination is an int, string, sql.Scanner etc, but not for interface{}.
In the second case, the driver detects that there are arguments and returns driver.ErrSkip. This causes the Go SQL package to use a PreparedStatement. And in that case, the MySQL driver uses a *binaryRows struct to interpret the results. This struct uses the declared column type (INT in this case) to decode the value, in this case to decode the value into an int64.
Fun fact: if you provide the interpolateParams=true parameter to the database DSN (e.g. "root:testing@/mysql?interpolateParams=true"), the MySQL driver will prepare the query on the client side, and not use a PreparedStatement. At this point both types of query behave the same.
A small proof of concept:
package main

import (
    "database/sql"
    "log"

    _ "github.com/go-sql-driver/mysql"
)

type Result struct {
    Afield string
    Bfield interface{}
}

func main() {
    db, err := sql.Open("mysql", "root:testing@/mysql")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    if _, err = db.Exec(`CREATE TABLE IF NOT EXISTS mytable(A VARCHAR(50), B INT);`); err != nil {
        log.Fatal(err)
    }
    if _, err = db.Exec(`DELETE FROM mytable`); err != nil {
        log.Fatal(err)
    }
    if _, err = db.Exec(`INSERT INTO mytable(A, B) VALUES ('a', 3)`); err != nil {
        log.Fatal(err)
    }

    var (
        usingLiteral         Result
        usingParam           Result
        usingLiteralPrepared Result
    )
    row := db.QueryRow(`SELECT B FROM mytable WHERE A='a'`)
    if err := row.Scan(&usingLiteral.Bfield); err != nil {
        log.Fatal(err)
    }
    row = db.QueryRow(`SELECT B FROM mytable WHERE A=?`, "a")
    if err := row.Scan(&usingParam.Bfield); err != nil {
        log.Fatal(err)
    }
    stmt, err := db.Prepare(`SELECT B FROM mytable WHERE A='a'`)
    if err != nil {
        log.Fatal(err)
    }
    defer stmt.Close()
    row = stmt.QueryRow()
    if err := row.Scan(&usingLiteralPrepared.Bfield); err != nil {
        log.Fatal(err)
    }

    log.Printf("Type when using literal:  %T", usingLiteral.Bfield)         // []uint8
    log.Printf("Type when using param:    %T", usingParam.Bfield)           // int64
    log.Printf("Type when using prepared: %T", usingLiteralPrepared.Bfield) // int64
}


Q:

What is $\int_{-\pi}^\pi \cos(nx)\cos(mx)\,dx$?

I'm pretty sure that there's a theorem that says that the Fourier coefficients of a sum of $\cos(nx)$ and $\sin(nx)$ 's are the coefficients of the sum itself.
I tried to prove that in the specific case of $f(x) = \sum_{n=1}^{\infty}\frac{\cos(nx)}{n^2}$. In calculating the Fourier coefficients I got to calculating  $\cos(nx)\cdot\cos(mx)$, but I'm now stuck. Any tips would be appreciated!

A:

Let $m,n\ge 1$. Use
$$\cos (m x) \cos (n x)=\frac{1}{2} (\cos (m x-n x)+\cos (m x+n x)).$$
Then if $m\not=n$ we get $0$, since $\int_{-\pi}^\pi \cos(kx)dx=\frac{2\sin(n\pi)}{n}=0$ for all $k\in\mathbb{Z}, k\not=0$. For $m=n$ we have
$$\int_{-\pi}^\pi \cos(nx)^2 dx = \frac{1}{2}\int_{-\pi}^\pi (1+\cos(2nx)) dx = \frac{1}{2} 2\pi+\underbrace{\frac{1}{2}\int_{-\pi}^\pi \cos(2nx) dx}_{=0}=\pi.$$
This is exactly what we expected.


Q:

pydrive get only folders from list

I use library pydrive for google drive. Now I need get all folders (root, parent, child) name in google drive.
I have found this:
self.drive.ListFile().GetList()

but it returns all the files. Can I get only all folders in google drive?

A:

How about this modification? It retrieves the files with mimeType of application/vnd.google-apps.folder using query.

The mimeType of application/vnd.google-apps.folder means folders.
trashed=false means that files are retrieved from outside of the trashbox.
In this case, title means folder name.

Modified script :
f = self.drive.ListFile({"q": "mimeType='application/vnd.google-apps.folder' and trashed=false"}).GetList()
for folder in f:
    print(folder['title'])

References :

About q

If I misunderstand your question, I'm sorry.


Q:

How would I go about comparing two character that will convert to the same character?

So basically, I want to use the switch statement. I have a chart for each encoded character that a user will enter. However, each uppercase character and lowercase character has the same meaning. I find it unnecessary to copy each switch statement and revise the same thing. So how would I come about this?

A:

You can use the function toUpperCase:

Converts the character argument to uppercase using case mapping information from the UnicodeData file.

switch (Character.toUpperCase(character)) {
    case 'A':
        // code ...
        break;
    case 'B':
        // code ...
        break;
    ...
    default:
        // default code
}


Q:

Show $f$ is integrable over $[1, \infty)$ iff $\sum_{n=1}^{\infty}\left|\int_n^{n+1}f \right|$ converges

For a measurable funtion on $[1,\infty)$ which is bounded on bounded sets define $a_n=\int_n^{n+1}f $. Is it true that $f$ is integrable over $[1,\infty)$ iff the series $\sum_na_n$ converges absolutely?

I think the answer is yes and I have already shown that if $f$ is integrable then $\sum_na_n$ converges absolutely. I am having trouble with the other direction.
Since $f$ is bounded on bounded sets and is measurable then $f$ is integrable on bounded sets and $\sum_{n=1}^{k}\int_n^{n+1}f=\int_1^{k+1}f$ by finite additivity. Also for each $k \in \Bbb N$ $\; \left| \int_1^{k+1}f \right| \le  \sum_{n=1}^{k}\left|\int_n^{n+1}f \right| \le \sum_{n=1}^{\infty}\left|\int_n^{n+1}f \right| = M < \infty$ beacuse of the assumtion that $\sum_na_n$ converges absolutely. So since this is true for each $k$ then $\left| \int_1^{\infty}f \right| \le M$.
I cant figure out how to get $ \int_1^{\infty}\left|f \right| < \infty$ which is what we need to show $f$ is integrable. Any help is appreciated, thanks.

A:

Might be reading this wrong, but consider a function that has $0$ integral on each interval $[n,n+1]$. For instance, consider $f(x)=-1$ on $[n,n+.5)$ and $f(x)=1$ on $[n+.5, n+1)$ for each $n \in \mathbb{Z}$. Then $\int_n^{n+1} f=0$ for each $n$, but $f$ is not integrable. The problem is $\vert a_n \vert = 0 \neq 1 = \int_n^{n+1} \vert f \vert$.


Q:

Using "Would you like" vs "Do you want" between friends

Does it sound normal or overly polite to use "Would you like" between friends, for example "Hey Bob, would you like to play chess with me?"

A:

Not necessarily. The difference in formality between would you like and do you want stems from the difference in timeframe. Do you want is immediate, refers to right now; would you like is unspecific, may refer to right now or one day. This is typical of English culture, in which formality is expressed through vagueness, allowing the interlocutor to respond without seeming blunt or dismissive of an offer in good heart, rather than via structure and deference, as in continental European cultures. This cultural difference is reflected in the language.


Q:

Event from PrimeNG p-datatable when row is added

I have a p-datatable bound to a list of entries. I want to set focus on newly, dynamically created rows; specifically on an input in the new row. But how?
Whenever I dynamically add an entry to the bound list of entries a new datatable row is added. Works fine. But I need to know when that has happened and I need access to the new row so I can set the focus. I've been looking for some kind of onRowAdded event, but p-datatable doesn't seem to have one. How to get around this?
<p-dataTable [value]="entries">
   . . .
   <p-column>
      <ng-template let-item="rowData" pTemplate="body">
          <input type="time" [value]="item.StartTime"/>
   . . .

A:

Ok, so I found a solution/workaround, independent of the p-datatable.
I set up an angular QueryList on one of the templated elements in the rendered row and subscribe to changes on it. This way I can get to the newly added rows in order to set focus.
So, in the html:
<p-dataTable [value]="entries">
   <p-column">
      <ng-template let-item="rowData" pTemplate="body">
          <input #myInput />

... and in the codebehind:
@ViewChildren('myInput') startTimeInputList: QueryList<ElementRef>;
. . .
ngAfterViewInit() {
   this.startTimeInputList.changes.subscribe((p) => {
       this._renderer.invokeElementMethod(p.last.nativeElement, 'focus');
   });
}


Q:

How can a print elements in a list randomly in python?

I've got a list which I want to print in random order. Here is the code I've written so far:
import random
words=["python","java","constant","immutable"]
for i in words:
    print(i, end=" ")
input("") #stops window closing

I've tried a variety of things to print them out randomly, such as making a variable which selects only one of them randomly and then deleting the randomly. I would then repeat this step until they are all deleted and within another variable. Then I would put the variables in a list then print them out. This kept on generating errors though. Is there another way this can be done?

A:

Use random.shuffle() to shuffle a list, in-place:
import random

words = ["python", "java", "constant", "immutable"]
random.shuffle(words)
print(*words)

input('')

Demo:
>>> import random
>>> words = ["python", "java", "constant", "immutable"]
>>> random.shuffle(words)
>>> words
['python', 'java', 'constant', 'immutable']

If you wanted to preserve words (maintain the order), you can use sorted() with a random key to return a new randomized list:
words = ["python", "java", "constant", "immutable"]
print(*sorted(words, key=lambda k: random.random()))

This leaves words unaltered:
>>> words = ["python", "java", "constant", "immutable"]
>>> sorted(words, key=lambda k: random.random())
['immutable', 'java', 'constant', 'python']
>>> words
['python', 'java', 'constant', 'immutable']


Q:

PHP requests need body/form content to be sent with quotations

I need to send the body with quotation for the http post request to work. The correct body content should look like this:
{"pnr" : "123", "orgnr" : "456"}

Question: How can I use below code as a base and get above body as outcome?
I am using this document as reference: https://github.com/rmccue/Requests/blob/master/docs/usage.md

Results of attempts (summary):
Attempt-1:
"data": "{personal_number: 123, org_number: 456}"

Attempt-2:
"data": "{personal_number: 123, org_number: 456}"

Attempt-3:
"form": {"{personal_number: 123, org_number: 456}": ""

Attempt 1 - Encode json string, sending body inside [$data].
require_once '../../../../packages/Requests/library/Requests.php';
Requests::register_autoloader();

$url      = 'http://httpbin.org/post';

$data = '{personal_number: 123, org_number: 456}';

$headers = array(
    'Accept-Encoding'  => 'gzip, deflate',
    'Accept'           => 'application/json, text/xml, application/xml, */*',
    'Content-Type'     => 'application/json; charset=UTF-8'
);

$response_1 = Requests::post($url, $headers, json_encode($data));

var_dump($response_1->body);

Attempt 1 - Result:
string(567) "{
  "args": {},
  "data": "\"{personal_number: 123, org_number: 456}\"",
  "files": {},
  "form": {},
  "headers": {
    "Accept": "application/json, text/xml, application/xml, */*",
    "Accept-Encoding": "gzip, deflate",
    "Content-Length": "41",
    "Content-Type": "application/json; charset=UTF-8",
    "Host": "httpbin.org",
    "Referer": "http://httpbin.org/post",
    "User-Agent": "php-requests/1.7"
  },
  "json": "{personal_number: 123, org_number: 456}",
  "origin": "82.117.105.239, 8"...

Attempt 2 - Send json string without encode, sending body inside [$data].
require_once '../../../../packages/Requests/library/Requests.php';
Requests::register_autoloader();

$url      = 'http://httpbin.org/post';

$data = '{personal_number: 123, org_number: 456}';

$headers = array(
    'Accept-Encoding'  => 'gzip, deflate',
    'Accept'           => 'application/json, text/xml, application/xml, */*',
    'Content-Type'     => 'application/json; charset=UTF-8'
);

$response_2 = Requests::post($url, $headers, $data);

var_dump($response_2->body);

Attempt 2 - Result:
string(526) "{
  "args": {},
  "data": "{personal_number: 123, org_number: 456}",
  "files": {},
  "form": {},
  "headers": {
    "Accept": "application/json, text/xml, application/xml, */*",
    "Accept-Encoding": "gzip, deflate",
    "Content-Length": "39",
    "Content-Type": "application/json; charset=UTF-8",
    "Host": "httpbin.org",
    "Referer": "http://httpbin.org/post",
    "User-Agent": "php-requests/1.7"
  },
  "json": null,
  "origin": "82.117.105.239, 82.117.105.239",
  "url": "https://httpbi"...

Attempt 3 - Send json string without encode, sending body inside of [form].
require_once '../../../../packages/Requests/library/Requests.php';
Requests::register_autoloader();

$url      = 'http://httpbin.org/post';

$data = '{personal_number: 123, org_number: 456}';

$headers = array(
    'Accept-Encoding'  => 'gzip, deflate',
    'Accept'           => 'application/json, text/xml, application/xml, */*',
    'Content-Type'     => 'application/json; charset=UTF-8'
);

$response_2 = Requests::post($url, array(), $data);

var_dump($response_3->body);

Attempt 3 - Result:
string(497) "{
  "args": {},
  "data": "",
  "files": {},
  "form": {
    "{personal_number: 123, org_number: 456}": ""
  },
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "deflate, gzip",
    "Content-Length": "39",
    "Content-Type": "application/x-www-form-urlencoded",
    "Host": "httpbin.org",
    "Referer": "http://httpbin.org/post",
    "User-Agent": "php-requests/1.7"
  },
  "json": null,
  "origin": "82.117.105.239, 82.117.105.239",
  "url": "https://httpbin.org/post"
}

A:

Create an array
then set key and its value
finally, it should be wrapped in json_encode.
$data = Array();
$data["personal_number"] = "123";
$data["org_number"] = "456";

$response_2 = Requests::post($url, $headers, json_encode($data));


Q:

Replace part of string in table column

Using Remove part of string in table as an example, I want to change part of my string in my database column with a different string.
Ex:
Database says E:\websites\nas\globe.png , E:\websites\nas\apple.png and etc
I want it to say \\nas\globe.png, \\nas\apple.png,
Only part I want to replace is the E:\websites\ not the rest of the string
How do I do this?
So far I have:
SELECT file_name,
REPLACE(file_name,'E:\websites\','\\nas\')
FROM t_class;

I just referenced http://nntp-archive.sybase.com/nntp-archive/action/article/%3C348_1744DC78C1045E920059DE7F85256A8B.0037D71C85256A8B@webforums%3E
and used:
SELECT REPLACE('E:\websites\web\Class\Main_Image\','E:\websites\web\Class\Main_Image\','\\nas\class_s\Main_Image\') "Changes"
FROM DUAL;

but once again it wouldn't change O.o

A:

I found a reference at how to replace string values of column values by SQL Stored Procedure
by doing the following:
UPDATE t_class SET file_name =

REPLACE

(file_name, 'E:\websites\web\Class\Main_Image\No_Image_Available.png', '\\nas\class_s\Main_Image\No_Image_Available.png');

so only difference is the update and = sign


Q:

How many threads Parallel.For(Foreach) will create? Default MaxDegreeOfParallelism?

I want to know, how many threads will be used when I run Parallel.For/ForEach loop.
I found, that it can be changed by MaxDegreeOfParallelism option.
MaxDegreeOfParallelism help on MSDN says (link):

By default, For and ForEach will utilize however many threads the
  underlying scheduler provides, so changing MaxDegreeOfParallelism from
  the default only limits how many concurrent tasks will be used.

But I don't know how many threads underlying scheduler provides.
How can I find out that?
I could test it with loop with 9999999 runs, however this test will show me number, but not the rule that determine that number.
Edit/added later:
I googled for "sheduler max concurrency", and I found (at MSDN - link), that TashSheduler class has MaximumConcurrencyLevel property, and:

Returns an integer that represents the maximum concurrency level. The
  default scheduler returns Int32.MaxValue.

That TaskSheduler class is used as "underlying scheduler" for these parallel loops?

A:

According to MSDN:

The default scheduler for Task Parallel Library and PLINQ uses the .NET Framework ThreadPool to queue and execute work. In the .NET Framework 4, the ThreadPool uses the information that is provided by the System.Threading.Tasks.Task type to efficiently support the fine-grained parallelism (short-lived units of work) that parallel tasks and queries often represent.

Looking at the documentation of ThreadPool, it says:

There is one thread pool per process. Beginning with the .NET Framework 4, the default size of the thread pool for a process depends on several factors, such as the size of the virtual address space. A process can call the GetMaxThreads method to determine the number of threads. The number of threads in the thread pool can be changed by using the SetMaxThreads method.


Q:

How many commands could redis-py pipeline have?

I want to use pipeline to reduce the number of interaction between my program and redis-server.
I may set many commands in pipeline but I couldn't find any document describing the max number of commands that could be set in pipeline.
Is there any advice? Thanks in advance.

A:

Not sure that there is a maximum, but I don't think that you want to reach it in case there is.
In most cases, limiting the size of the pipeline to 100-1000 operations gives the best results. But, you can do a little benchmark research that includes typical requests that you send.
Pipelining requests is generally good, but keep in mind that the responses are kept in Redis memory until all pipeline requests are served, and your client waits for the long reply of all requests.
You should try to find the sweet spot of concurrent connections, pipelined requests and your Redis memory.
Your client will not start reading replies until the last query of your pipeline has been sent to Redis. When the pipeline is too long, it has the potential to block things.
You can use redis-benchmark or memtier_benchmark. Here's a more detailed description and instructions on the memtier_benchmark.
When you find the number of pipelined requests and number of connections, you should implement it with your redis-py client in your app.


Q:

WebBrowser Control Loading Twice

Alrighty, guys. If you'd like to pull your hair out, the I've got a great problem for you. This problem seems very rare, but it effects my program on a few different sites that have pages that load content twice.
For instance: http://www.yelp.com/search?find_desc=donuts&find_loc=78664&ns=1#start=20
If you visit this site, you'll notice that it loads, then reloads different data. That's because there is a parameter in the URL that says start=20, so the results should start at #20 instead of #10. No matter what that is set to, Yelp loads the first 10 results. Not sure why they do this, but this is a prime example of what absolutely breaks my program. :(
Basically, whenever my program has a page that loads, it copies the source code to a string so it can display it somewhere else. It's not really important- What is important is that the string needs to actually have the last thing that is loaded in the page. Whenever a page loads, then loads again, I am not sure how to catch it and it ruins the program by exiting the while loop, and copying the source code into the string called source.
Here is a snippit of some code that I reproduced the problem with. When I attempt to use this in a new program, it will copy the source code for the first pages' results instead of what it is changed to.
GetSite = "http://www.yelp.com/search?find_desc=donuts&find_loc=78664&ns=1#start=20";
webBrowser9.Navigate(GetSite);
while (webBrowser9.ReadyState != WebBrowserReadyState.Complete)
{
    p++;
    if (p == 1000000)
    {
        MessageBox.Show("Timeout error. Click OK to skip." + Environment.NewLine + "This could crash the program, but maybe not.");
        label15.Text = "Error Code: Timeout";
        break;
    }
    Application.DoEvents();
}
mshtml.HTMLDocument objHtmlDoc = (mshtml.HTMLDocument)webBrowser9.Document.DomDocument;
Source = objHtmlDoc.documentElement.innerHTML;

A:

Why do you wait in while loop for the browser to finish loading data?
Use DocumentCompleted event and you can remember the document's URL from there.


Q:

Giving Syntax error in Scrapy (Python) - XPath

I'm using Scrapy Crawler to extract some details like username, upvotes, join date etc.
I'm using XPath for extracting the contents from each user's webpage.
Code:
import scrapy
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request
from scrapy.spiders import BaseSpider
from scrapy.http import FormRequest
from loginform import fill_login_form
from scrapy.selector import Selector
from scrapy.http import HtmlResponse

class UserSpider(scrapy.Spider):
    name = 'userspider'
    start_urls = ['http://forum.nafc.org/login/']
    #Getting the list of usernames
    user_names = ['Bob', 'Tom']  #List of Usernames

    def __init__(self, *args, **kwargs):
        super(UserSpider, self).__init__(*args, **kwargs)

    def parse(self, response):
        return [FormRequest.from_response(response,
                    formdata={'registerUserName': 'user', 'registerPass': 'password'},
                    callback=self.after_main_login)]

    def after_main_login(self, response):
        for user in self.user_names:
            user_url = 'profile/' + user
            yield response.follow(user_url, callback=self.parse_user_pages)

    def parse_user_pages(self, response):
        yield{
            "USERNAME": response.xpath('//div[contains(@class, "main") and contains(@class, "no-sky-main")]/h1[contains(@class, "thread-title")]/text()').extract_first()
            "UPVOTES": response.xpath('//div[contains(@class, "proUserInfoLabelLeft") and @id="proVotesCap"]/text()').extract()[0]
        }

if __name__ == "__main__":
    spider = UserSpider()

Error looks like this
P.S. I have manually checked the syntax of my XPath on the Scrapy Shell and it was working fine
Is there anything that I'm not noticing in the code?

A:

You're missing a , after your first dict element:
{"USERNAME": response.xpath(...).extract_first(),
 "UPVOTES": response.xpath(...).extract()[0]}


Q:

How to prevent images from being resized in game maker?

This warning appeared in the compilation menu of my game.

The images were rescaled in half. I understand that this happened because they had very large dimensions.
It turns out that the images, although they have a large size (pixels), are very light, because they are composed for the most part by simple traces in addition to having the transparent background.
Below, one of the images:

You see, it is very light.
It turns out that in the game it stops being clear.

How do I solve my problem? Using smaller images is out of the question.

A:

When your image is bigger than texture pages size then GMS resizes the image.
Don't see how small your PNGs are. They will be unpacked when loaded into memory. Each pixel will eat 4 bytes (32 bits). So 2446×1008 requires more than 9 MB. Moreover, some videocards can work only with textures which size is a power of two. It means that 2446×1008 actually will be 4096×1024 (empty area will be added). And Texture pages is thing which allows to optimize it (but for very big images it may work inefficient in some cases).
Change texture pages size from 2048*2048 (default value) to 4096*4096.
But keep in mind that then your game may not work on some “old” hardware. Also you can split your each big image into two smaller. Like 2446×1008 → 2048×1008 + 398×1008

But when I see your images I don't see any reason to do it as big images. It's very inefficient. I would prefer draw it using that small blocks.


Q:

How do I manually deploy a specific TFS changeset using TeamCity?

I have the following setup in TeamCity:
A) CI upon check-in with build, tests and deploy to test environment.
B) Manual deploy
Deployment is based on MSBuild build task with MsDeployServiceUrl parameters.
My CVS is TFS and im not using any build scripts.
A is working great, what I can't figure out is B.
Now, what I would like B to do is, when triggered (manually), get the source from TFS as a changeset based on the latest pinned build of A, build the source (Using build step MSBuild with /p:Configuration=Release) and run the deploy to a production server.
My question here is, how do I get source from a specific changeset from TFS based on the build id of last pinned build of A? Is that even possible?
I have read the documentation on custom builds and artifacts:  http://confluence.jetbrains.net/display/TCD65/Triggering+a+Custom+Build
But could not figure out how to use it in my scenario and I am not even sure if this is the road to take on specific need.
Any ideas on how to do this would be greatly appreciated.

A:

Ok, I figured it out.
You need to set "Artifacts path" in build configuration A to something like:
/**/* => Src

And then in build configuration B set "Artifact Dependencies" to something this:
"Artifacts path" = Src/**/*
"Destination path" = Builds/Release

And finally use this "Destination path" as a prefix when adding the "Build file path" in the MSBuild "Build step" on B.
Works like a charm every build! :-)