Using google custom search API to find images

Question: I want to use Google's Custom Search API to find images using GET request. Like described here. But I don't want to look on images on one specific site, but want to get results like this. How I can do this with the Custom Search API?
Sending this request returns nothing:
https://www.googleapis.com/customsearch/v1?key=[MY_KEY]&cx=017576662512468239146:omuauf_lfve&q=some+request&&safe=off&searchType=image&fileType=png. This cx is from google's manual
I must set cx param, but this value links my request to site, specified in cse control panel. However I don't want to limit my results to one site.
Answer: According to the documentation here:
Google Custom Search > Overview

Google Custom Search enables you to create a search engine for your website, your blog, or a collection of websites.

It doesn't sound like that is what you are trying to do (you don't seem to want to search a predefined subset of resources).
Comment: While digging the internet i found that [Ajax Search API](https://developers.google.com/web-search/docs/) is exactly what I need (am I right?), but it is deprecated and google recommends me to use Custom Search API.

Ok, if it not what I need, are there other API to solve my problem?
Answer: I'm aware the question is over 6 years old, but better late than never. It's possible to create a Google programmable search engine that can search the entire web for images. When you create a programmable search engine, there is an option to search the entire web instead of just web sites that you specify. See https://programmablesearchengine.google.com/about/.
As an alternative, you could try Bing Image Search API. There is a limit to the number of image searches you can submit per day for free, but I have rarely hit the limit.


Add "Sale" or "Discount" text to a product display using drupal commerce?

Question: I have been searching for an answer a long time with no success at all.
I am buildind a drupal commerce website and i would like to show on a specific products the word "Sale" or "Discount" as showing in the picture below (like the green Sale Tag).

I can do it using photoshop but is really a pain to go over hundred of product just to photoshop a "Sale" text on every product picture in question.
Can someone point me to a specific module that can do such job ?!
Note that i know basic CSS so if this could be done using some CSS code, a starting push from any body will be appreciated !
Thank you,
Comment: you can simply assign a "class" to particular products and css will handle the rest.
Answer: With Views Conditional you can make it that if Label Discount Name is equal to Sale then

 Otherwise output nothing.
Then do the same for Discount.

Views Conditional is a simple module that allows you to define
  conditionals (if xxx then yyy) with fields in views. Conditions
  include:
Equal To
Not Equal To
Greater Than
Less Than
Empty
Not Empty

Views conditional allows you to output text based on the result of the
  condition.
Comment: in your answer you mentioned the img src but i am trying to add a "sale" text to the content type so whatever the product or image will be, once the "sale" text exist the design will take effect and once the "sale" text is removed the design just disappear ! Is that possible to be done using your answer above ? Thank you for your help!
Comment: `i am trying to add a "sale" text to the content type so whatever the product or image will be, once the "sale" text exist the design will take effect` yes, my answer already takes that into account. As the views conditional checks if the text of `Label Discount Name` is equal to sale. I read your "answer" so I already knew you already created a field (Label Discount Name) in your content type which will have the sale/clearance text.
Comment: Alright, thank you so much i will go more in deep using the views conditional and revert back here with any issue i face, if any.
Answer: Finally resolved...
For the sake of anyone having the same question, the trick is to add a "CSS Class" to the field in question and use some CSS codes to achieve whatever the design you like.
1) Create the field in question in the correspondant content type.
2) Goto manage display of that content type, select what "view" you want to use between the available views on the "manage display" page and then make the field in question visible and choose the format to be: Linked and Wrapped and then click on field settings where you should:
_ Wrap the title in tag: DIV
_ Link title to: Nothing
_ Add your class: yourclass
3) Use yourclass and add some CSS Code to design the content of the field in question.
NOTE: The good thing is that when the field in question is empty all the design just disappear and you will see nothing on your product which is awesome.


How to script a button click in a separate JS file rather than HTML Script Header tag

Question: So I need some help, I am new to JS and I need to to find a solution to the problem I am having. I am trying to create a button when it clicks changes a piece of text. When I create a JS function in the script tag header and reference the function in the button onclick it works, but it doesn't work in a separate JS file. The HTML code is below. Hopefully, someone can help me.

<!DOCTYPE html>

  <title></title>

 hi

  <button id="ButtonText" onclick="Button()"> Click Here To Change The Text</button>
  <button id="ButtonText2" onclick="Button2()"> Click Here To Change The Text Back</button>

Comment: add your function inside changetext.js without script tag
Comment: Learn about [event attachment](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener). Using inline `onclick` statements is not ideal for various reasons.
Answer: Write your function in changetext.js and make sure that is in same place as your HTML file.
change   onclick to onClick
and remove your script tags in the head
Answer: this is an example...
    <!DOCTYPE html>

    <title>example</title>

 hi

    <button id="ButtonText" onclick="Button()"> Click Here To Change The Text</button>
    <button id="ButtonText2" onclick="Button2()"> Click Here To Change The Text Back</button>

first you need remove your script.. we include script only if you dont use a external js.
on your external js(changetext.js)
  function Button(){
        document.getElementById("demo").innerHTML = "hello from button 1";
    }
    function Button2(){
        document.getElementById("demo").innerHTML = "Hellow from button2";
    }

result:

if you dont use a external js the code is this:
<!DOCTYPE html>

<title>example</title>

 hi

<button id="ButtonText" onclick="Button();"> Click Here To Change The Text</button>
<button id="ButtonText2" onclick="Button2();"> Click Here To Change The Text Back</button>

we write the code js in the tag script good luck !!
Comment: ah I noticed my script tag was in the header, instead of the footer, im going through JS at the moment, why does this specific line of code not work with the script tag in the head?


Airflow - List of downstream tasks for a task

Question: May I know if there is an airflow command which list all downstream tasks for a task. For example, there are 4 tasks in a dag - dummy1 > dummy2 > dummy3 > dummy4. I need list of all downstream tasks of dummy2, output should be dummy3 and dummy4. If there is a command then it will help if there are many downstream tasks for a task and to do manual actions only on downstream tasks.
Dag - dummy1 > dummy2 > dummy3 > dummy4
Output : (downstream tasks list of dummy2)
dummy3
dummy4
Answer: There is no a CLI command for this, but it is a one-liner in Python.
Let's assume your DAG-script name is a_dag.py and the DAG object is referenced by the variable dag.
Then you can do something like this in the terminal:
$ cd airflow/dags

$ ls
a_dag.py

$ python
Python 3.8.2 ...
>>> from a_dag import dag
>>> dag.get_task('dummy2').get_flat_relative_ids()
{'dummy3', 'dummy4'}


Como mudar o tema de um App para Android para parecer com o iOS?

Question: Estou desenvolvendo um aplicativo Android e gostaria de utilizar um tema que o deixe parecido com aplicativos do iPhone (iOS).
Há algum lugar onde eu possa obter esse tema ou forma simples de implementar isso?
Comment: Depende, qual iOS ? a nova versão flat?
Comment: Talvez não ache um tema todo pronto parecido com iOS, se procurar componentes(Buttons, List, etc) com tema do iOS e desenhar seu `theme` com esses componentes terá um bom resultado.
Comment: iOS 6, preferencialmente.
Answer: Apesar de ser possível fazer isso com temas e customizando componentes, isso não é recomendável pelo simples fato do aplicativo ter um comportamento de app de iOS podendo comprometer a usabilidade do app como um todo, pois os usuários não estão habituados com a plataforma.
Esse texto explica melhor porque isso não é recomendado:
https://developer.android.com/design/patterns/pure-android.html
Comment: Apesar de ser a mais pura verdade, isso não responde a pergunta (se é que essa pergunta merece uma resposta).
Comment: Sei que não é ideal, mas como comentado acima, é apenas para adicionar alguns aspectos visuais interessantes.
Answer: Amigo eu não faria isso! Minha sugestão é que respeite as regras de UX e utilize "a cara de seu aplicativo" conforme a plataforma que ele pertence.
Até Breve!
Answer: Apesar de não ser exatamente apenas um tema e não permitir interface iOS em Android, e sim um framework completo para desenvolvimento mobile, o Framework7 parece uma solução interessante para simular interfaces nativas dos dispositivos.
Para saber mais: https://framework7.io/


Carleman's condition for Catalan numbers

Question: I've been going through some elementary random matrix theory and in these lecture notes we say a probability measure is completely determined by its moments so long as it obey's Carleman's condition i.e. the sequence of moments $m_k$ are such that
$$
\sum_{k \geq 1} m_k^{-1/(2k)}= \infty.
$$ Later on when the semicircle distribution is brought up, whose moments are 0 for odd moments and the Catalan numbers for even numbers, they use a complex analytic method to prove that the moments are completely determined by the probability measure which is natural following Hadamard's formula. However I was wondering if a pure real analysis proof could still be constructed as I haven't found anything online, i.e. is the criterion
$$
\sum_{k \geq 1} C_k^{-1/(2k)}= \infty
$$
obeyed without analytic continuation? I've tried using Sterling's Formula which I hoped would cancel the exponent as well but no success as this series tends to zero.
Comment: Please collect in the question all needed ingrediends, instead of delegating to a 60 pages link. Introducing or at least directly referencing the Carleman's condition - if we really need it - would be nice. We have a complex analytic proof for what? (What does it mean "for the semicircle"?! This is less than an *a propos* for a long mathematical story.) And what is a "series proof"? Also show explicitly the own attempts, a potential answerer will have to type else a lot. (Possibly missing the point of the question.)
Comment: Okay I'll add the one line for what Carleman's condition is.
Comment: As for my own answer I just said simply using an algebraic approximation for $n!$ by Sterling's formula since I'd hoped the powers would cancel leaving a harmonic series but this wasn't the case.
Comment: This $-1/2k$ in the exponent, is it $-1/(2k)$ or $-k/2$?
Comment: Few readers will get to the end of the first paragraph not wondering about what could be the moments of a general probably measure on a measurable space $(X,\mathscr A)$.
Comment: @Ruy The core of the question I'm asking has nothing to do with probabilitu distributions buth rather as a question on the convergence of a series. I could rewrite the question asking whether or not the infinite sum of $C_k^{-1/2k}$ diverges to positive infinity or not.
Comment: @Vincent It's -$1/(2k)$, I'll make it clearer.
Answer: Asymptotically, $C_k \sim \frac{4^k}{k^{3/2}\sqrt{\pi}}$.  Therefore,
$$ \lim_{k \to \infty} C_k^{-\frac{1}{2k}} = \frac{1}{2} \lim_{k \to \infty} \pi^{\frac{1}{4 k}} k^{\frac{3}{4k}} = \frac{1}{2} \lim_{k \to \infty}  \pi^{\frac{1}{4 k}} \exp\left(\frac{3 \log k}{4 k}\right) = \frac{1}{2} \left( 1 \cdot \exp(0) \right) = \frac{1}{2} $$
Since the terms in the series do not in fact tend toward zero, the series diverges.
Comment: Thanks for this, didn't know about this asymptotic relation.
Comment: No worries.  The asymptotic relation is just what you get when you plug in Stirling's formula to the definition of $C_k$ and simplify.


Create a remote copy of linux server filesystem

Question: I have a decommissioned server (VPS server with a hosting company) that I need to backup before we close our account. I don't need to run the server anywhere else, I just need a browse-able copy of all the files. What's the best way to get a copy of the server's filesystem based off ssh access?
VPS is a Debian distro.
Comment: rsync of the relevant directories?
Comment: Please tell us what OS type you are running.
Answer: Use rsync
rsync -avzH root@remoteserver:/ /local/folder

-a archive
-v verbose
-z compression
-H preserve hard links
Answer: Your options are endless!  The big three:

rsync the system to a remote storage location
(man rsync -- Too many sub-options to list, but rsync -azH is probably a good start)
tar everything up and shove it over SSH
tar cf - | ssh some-other-location tar xf -
-- Obviously you don't have to extract to the other location, you can keep it in a tarball, compress it before it goes over the network, etc.
Use your backup software to cut a "final archive"
You do have backup software, right?  So you can just cut a full backup and archive it.
(If you don't have backup software, GET SOME.)
Answer: Just to throw a block level copy into the ring:
You can use dd and nc to mirror the whole disk if you'd like.
On your receiving server, open up a listening port and redirect the output to a file.
nc -l someportnumber | dd of=/tmp/diskimage
On the VPS, read the disk with dd and redirect the output to your remote server.
dd if=/dev/sda | nc remote.server.hostname someportnumber


Output values in foreach loop only once

Question: I'm using a foreach loop to save error messages resulting from invalid user inputs in an array,change it into a a string and output them on another page.However, while i am able to output the string succesfully, the string is being repeated multiple times.
Extract of my code:
foreach($_POST as $field=>$value)
{
if(!empty($value))
{
    if($_POST['Email']==$_POST['Verify_Email'])
    {
        $email=$_POST['Email'];
        $email=mysqli_real_escape_string($cxn,$email);//Saves the input  data & preps it for insertion into database.
    }
    else
    {
        $error[]="Mismatched Email Addresses";
    }

    if(preg_match('/^[a-z\d_]{2,20}$/i',$_POST['Username']))
    {
        $user=$_POST['Username'];
        $user=mysqli_real_escape_string($cxn,$user);
    }
    else
    {
        $error[]="Invalid Username entered.Please enter an alphanumerical username between 2 to 20 characters";
    }

    if($_POST['Password']==$_POST['Verify_Password'])
    {
        $pass=$_POST['Password'];
        $pass=mysqli_real_escape_string($cxn,$pass);
    }
    else
    {
        $error[]="Your passwords do not match";
    }

    if(preg_match('/^[a-z\d_]{2,20}$/i',$_POST['BizName']))
    {
        $biz=$_POST['BizName'];
        $biz=mysqli_real_escape_string($cxn,$biz);
    }
    else
    {
        $error[]="Invalid BizName entered.Please enter an alphanumerical     username between 2 to 20 characters";

    }
}

if(!empty($_POST['Desc']))
{
    $desc=$_POST['Desc'];
    $desc=mysqli_real_escape_string($cxn,$desc);
}
else
{
    $desc="NULL";
    $desc=mysqli_real_escape_string($cxn,$desc);
}
}

foreach($_POST as $field => $value)
{
$$field = strip_tags(trim($value));
}
if(!empty($error))
{
$errormsg="";
foreach($error as $value)
{
    $errormsg.= "$value";
}
include("RegForm.php");
exit();
}
include("RegForm.php");

I suspect that the cause of $errormsg being repeated multiple times is due to the values in $error[ ]
(E.g $error[]="Invalid BizName entered.Please enter an alphanumerical username between 2 to 20 characters";)

This is because the number of times $error is being repeated coincides with the number of user input fields, and the number of $error [ ] i have.
Question
If i am correct in $error being the cause of $errormsg being repeated multiple times, could someone kindly point out why is it happening as the foreach loop should only run as many times as there are values in the $error array( How many erros there are).If my assumption is wrong, could someone point me in the right direction?
Thanks
Comment: why do you put a `foreach` loop here in?!?
Comment: So basically, you would like to exit the loop as soon as it retrieved one error message?
Comment: @bwoebi It's to convert the values in $error to a string, which i will output in another html page?
Comment: @Ken no, the `foreach ($_POST ...)`? It's absolutely unnecessary.
Comment: @Ghillied Not one error message, but to only output each error message once. (e.g if a user has a mismatched email and password, it would display both messages once.)
Comment: @Ken You might want to take a look at my answer then!
Answer: You are using a foreach loop wrong. Check below
<?php
foreach($_POST as $field=>$value)
{
  if(!empty($value))
  {
    /*
    this code block is executed for every POSTed var with a value.
    So once for Email
    So once for Verify_Email
    So once for Username
    So once for Password
    So once for Verify_Password
    So once for BizName
    So once for Desc
    etc..
    */

  }
}
?>

I guess you just want to use the code block without the foreach.
You are also doing this.
<?
foreach($_POST as $field => $value)
{
  $$field = strip_tags(trim($value));
}
?>

This way I can set any variable in your script to any value. If you would use a variable like $login = true to keep track of who is logged on, I can simply POST login=1 and I would have access.
Comment: Thanks for your help, my code is working now.I'm setting $_SESSION variables to true upon a successful user login. If so, would what you said about POST login= still hold true?
Comment: No, not directly. I cannot set session variables that way. But I can alter any regular variable and that could still be a security risk if not handled properly. For example any variable you use in regform.php that you do not set explicitly in that file, can be altered.
Answer: The problem is that for each key-value pair in $_POST you run all the checks and add error messages in $error. So, essentially, you run the checks as many times as there are keys in $_POST and for each loop you append the same error messages to $error.
Remove these lines:
foreach($_POST as $field=>$value)
{
if(!empty($value))
{

and the matching closing brackets and everything should work fine.
Answer: That happens because of the first foreach($_POST as $field=>$value) loop.
You tell the script to extract a key and his respective value in $_POST, set them to $key and $value and then exec the code inside the loop. The loop is executed for each variable in $_POST.
If you are accesing $_POST variables directly, then you don't need to loop all variables in $_POST.
Remove
foreach($_POST as $field=>$value)
{
if(!empty($value))
{

and everything will work fine.
Answer: Yo could develop your error array a little bit more then ! (following your answer to my comment):
Here would be the $error structure:
Array Structure
$error = array(
    'email'=>array(
        'hasError'=>'0',
        'message'=>'My error Message'
    ),
    'username'=>array(
        'hasError'=>'0',
        'message'=>'My error Message'
    ),
    ...=>array(
        'hasError'=>'0',
        'message'=>'My error Message'
    )
);

Creating the array
$errorMessages= array(
    'email'=>'Wrong email!',
    'username'=>'Wrong username!',
    'password=>'Wrong password!',
    'desc'=>'Wrong description!');

$elementsToBeValidated = array('email','username','password','desc');
$error = '';

foreach($elementsToBeValidated as $inputElem):
    $error[$inputElem]['hasError'] = false;
    $error[$inputElem]['message'] = $errorMessages[$inputElem];

so instead concatenating all your error messages in an array when validating, just change the flags to true:
Validation example
if(/*conditions for a wrong username */) $error['username']['hasError'] = true;

To check all the errors you got at the end, (out of the loop), do something along those lines:
PHP
$errorMessage = '';
foreach($error as $e):
    if($e['hasError']) #if the hasError flag is true
        $errorMessage.=$e['message'];
endforeach;

if(strlen($errorMessage)>0) return $errorMessage; #or echo, whatever you want !

Answer: By doing
$error[]="Invalid BizName entered.Please enter an alphanumerical username between 2 to 20 characters";

You are declaring the $error array each time you encounter it, the correct way is to define this array outside the foreach part with $error = array(); then inside your loop you want to append a value inside your array, you need to do array_push($error, "error message");
Your array will be filled fine then.

Output values in foreach loop only once


Django and Python handle changing date format

Question: Im importing records from a CSV file into a django model. The CSV file is uploaded by the user. The problem I'm facing is with the date field.
The date field expects the date to be in YYYY-MM-DDbut different spreadsheet programs default to different types of formats and I dont want the user to have to change their default format.
So I want to find the best method for django to accept dates that could possibly be in various formats.
What I thought could work is to specify a list of allowed date formats and try and match the string to one of them...
thanks
Comment: It's impossible to detect the format.  For example `11/07/2011` means November 7 in some countries and July 11 in others.  You can only try some "best guess".
Comment: Yeah I thought that, which is why I want to allow specified formats. so I could try and match it to one of the formats and run the risk of this being wrong. I'll update the question to be more specific
Comment: ok I hopefully have updated the question to better explain. Thanks for your help Sven
Answer: When you convert the date string into a datetime object, you'll likely use datetime.strptime with the format argument. I would ask the user what format they use and/or store it in the database (and by that I mean allow them to choose the format they want).
Comment: Thanks Mike, an option that would definitely be "fool proof" and jsut might be the way i'll have to go...although I would like to avoid it if possible
Answer: The best option I've seen for "fuzy" date string parsing is the dateutil library.
Unfortunately, there are still possible cases where things will be ambiguous and any code will sometimes guess wrong.  Dateutil has their matching logic pretty well documented tho, so should you run into wrong guesses you should be able to figure out what happened relatively quickly.
Comment: thanks! this is what I was looking for, plus it gives loads of other functions that will be useful in the future


How many three-digit numbers can be formed using digits {$1$, $6$, $9$, $9$, $9$,}?

Question: If I had $5$ distinct digits $(1,2,3,4,5)$ I would do it like so:

$\frac{5!}{(5-3)!} = 60$

But I don't understand what to do if I have $3$ repeating digits
Comment: How many 3 digit numbers can you make using $\{1,6,9\}$? Using $\{1,9,9\}$? Using $\{6,9,9\}$? Using $\{9,9,9\}$? Add 'em up.
Comment: For a general approach we can use exponential generating functions, or "egf"s. I have recently answered a similar question [here](http://math.stackexchange.com/questions/2178425/number-of-strings-generatable/2178550#2178550). For your case you have an *egf* $1+x$ for each character "1" and "6" and an *egf* $1+x+x^2/2!+x^3/3!$ for the "9"s. Hence you expand $$(1+x)^2\left(1+x+\frac{x^2}{2!}+\frac{x^3}{3!}\right)$$ and compute the coefficient of $x^3/3!$.
Answer:
First Number - $999$
Second Number (Take all distinct digits) = $3$!
Third Number (Take $2$ $9$'s) = $C(1,1) * C(3,2) * C(2,1)= 3$!

Total Numbers = $1 + 6 + 6 = 13$

$C(1,1)$ - How many repeating numbers are there ? Only $9$ is repeating and choose to include only that .
$C(3,2)$ - How many $9$'s are there ? How many are we using ?
$C(2,1)$ - After including $9$, only one place left . How many ways to fill that ?
Comment: Also a good answer. You could tighten up the third branch by saying (a) which digit is not a $9$? $\binom 31$ (b) which digit is it? $\binom 21$
Answer: You can just make a decision tree, showing the options to pick $9$ (blue) or other (pink) at the earlier stages where it will have an effect on subsequent options; the last choice is green because that just represents the available choices. Then multiply down each branch and add:
$$2\cdot 1\cdot 1 + 2\cdot 1\cdot 2 + 1\cdot 2\cdot 2 + 1\cdot 1\cdot 3 = 2+4+4+3 = \fbox {13}$$

An inclusion-exclusion approach would be to regard this a choice with restrictions on how many $1$s and $6$s we're allowed.
The unrestricted choice would be $3^3=27$ options.
Excluding choices with excess $1$s involves any cases with two $1$s, $6$ cases, or three $1$s, $1$ case - in total $7$ cases to remove.
Excluding choices with excess $6$s likewise gives $7$ cases to remove.
Total valid choices then is $27-2\cdot 7=13$.
Comment: All of this is true, but I can't do this with big numbers (8-digit numbers, etc.). I need a logic which I can apply in all situations using permutations/combinations/variations. I really appreciate the help.
Comment: @AverageBrick Added another approach.


placing a Tabbar controller on top of viewcontroller

Question: How do i place the TABBAR control on top of view control.by default it is at bottom how do i put it up..?
Used following code to do:
 UIImage* tabBarBackground = [UIImage imageNamed:@"footer-bg.png"];
[[UITabBar appearance] setBackgroundImage:tabBarBackground];
[[UITabBar appearance]setSelectionIndicatorImage:[UIImage imageNamed:@"footer-hover-bg.png"]];

if(IS_IOS_7)
{
    [[appDelegate.tabBarController tabBar] setSelectionIndicatorImage:[UIImage imageNamed:@"footer-hover-bg.png"]];
    [[UITabBar appearance] setTintColor:[UIColor blackColor]];
}
appDelegate.tabBarController.tabBar.frame = CGRectMake(0, 20, 320, 50);
appDelegate.tabBarController.delegate=self;

UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, -20, 320, 600)];

viewControllers = [[NSMutableArray alloc] init];

MainViewController *view1 = [[MainViewController alloc] init];
UINavigationController *nav1=[[UINavigationController alloc]initWithRootViewController:view1];
[viewControllers addObject:nav1];

ViewController1 *view2 = [[ViewController1 alloc] init];
UINavigationController *nav2=[[UINavigationController alloc]initWithRootViewController:view2];
[viewControllers addObject:nav2];

[appDelegate.tabBarController setViewControllers:viewControllers];

appDelegate.tabBarController.tabBarController.view.frame=CGRectMake(0, 0, 320, 480);
[view addSubview:appDelegate.tabBarController.view];

[self.view addSubview:view];

UITabBarItem *tabBarItem1 = [appDelegate.tabBarController.tabBar.items objectAtIndex:0];
UITabBarItem *tabBarItem2 = [appDelegate.tabBarController.tabBar.items objectAtIndex:1];

[tabBarItem1 setFinishedSelectedImage:[UIImage imageNamed:[arraySelectedImages objectAtIndex:0]] withFinishedUnselectedImage:[UIImage imageNamed:[arrayUnselectedImages objectAtIndex:0]]];
[tabBarItem2 setFinishedSelectedImage:[UIImage imageNamed:[arraySelectedImages objectAtIndex:1]] withFinishedUnselectedImage:[UIImage imageNamed:[arrayUnselectedImages objectAtIndex:1]]];

How do i do the same using storyboards?
Answer: First add a UIViewController then add the UITabBar and add contraint if you use autolayout.

Don't forgot to connect delegate.
Hope that will help.
Comment: i have used UITabBarController and added views to it.can i change its frame so that i can add it above.
Comment: No. If you use UITabBarController you will be not able to change the position
Comment: can u please give me sample links for Tabbar using storyboards.I couldn't find :(
Comment: a beginning : http://nullpointr.wordpress.com/2012/02/18/ios-dev-add-tabbar-to-a-view-without-a-tabbarcontroller/
Comment: Thanks a lot :).How do i connect first view controller with the first tabbaritem in a stroyboard?.I am not able load view controller.
Comment: the first view will be the current view ^^
Comment: this code doesnt work - (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    switch (item.tag) {
        case 1:
            if (tab1vc == nil)
            {
                UIStoryboard *storyBoard=[UIStoryboard storyboardWithName:@"Main" bundle:Nil];
                mainTabbar = [storyBoard instantiateViewControllerWithIdentifier:@"FirstViewController"];
               // self.tab1vc =[[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil];
            }
            [self.view insertSubview:tab1vc.view belowSubview:mainTabBar];
            break;
Comment: it is not related to my question :( there is no tabbar init.
Comment: don't build your app as `UITabBarController` because you DON'T have a UITabBarController. just navigate in the app without an `NavigationController` or `UITabBarController` like in this answer...


List uploaded files in django

Question: How can I list files after they have been uploaded? I want to display them so they can be viewed and downloaded later.
Here is my code.
models.py
class UploadFile(models.Model):
    file = models.FileField(upload_to='files/%Y/%m/%d')

forms.py
class UploadFileForm(forms.ModelForm): pass

class Meta:
    model = UploadFile

views.py
@login_required(login_url='/accounts/login/')
def home(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            new_file = UploadFile(file = request.FILES['file'])
            new_file.save()
            return HttpResponseRedirect(reverse('main:home'))
    else:
        form = UploadFileForm()
        data = {'form': form}
        return render_to_response('upload.html', data,
                                  context_instance=RequestContext(request))

Answer: No need to get file back from form and save it - just save it using your model. View have to be something like this:
    @login_required(login_url='/accounts/login/')
    def home(request):
        if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            form.save() # saving model instance
            return HttpResponseRedirect(reverse('main:home'))
        else:
            form = UploadFileForm()

        data = {'form': form}
        return render_to_response('upload.html', data, context_instance=RequestContext(request))

and after this you can take all uploaded files from your model:
files = [upload_file.file for upload_file in UploadFile.objects.all()]

and show them to user
Comment: i did this but it says NameError: name 'UploadFiles' is not defined
Comment: or you miss typed - not 'UploadFiles' - just 'UploadFile', or didn`t import model UploadFile from your models
Comment: ok error went away yeah i didn't import it but im not seeing any file i uploaded do i have to put some in upload.html to able to work
Comment: yes. You need to create view and template, send files from view to template and show them in template.

List uploaded files in django


why 15 yard circle is drawn incomplete?

Question: why 15 yard circle is drawn incomplete? It is written in rules that the area reserved for slips need not to be demarcated since the slips can go further deep in undemarcated area for fast bowler. So what if the short mid off fielder want to stand near the 15 yard line,it is not drawn?
And why dots are marked it is only drawn till 45 degree ?
Comment: Welcome to Sports SE. I notice you are using two accounts. For more information about merging these accounts, refer [here](https://sports.stackexchange.com/help/merging-accounts). And there is no problem with the site...you can comment on your own posts, but you must have [50 reputation](https://sports.stackexchange.com/help/privileges/comment) to comment elsewhere.
Comment: Why do you think the 15 yard circle is not drawn. It is drawn on the ground but is not applicable to slip fielders & keeper only. They can stand outside the circle.
Comment: No i m saying that it is drawn complete.It is drawn till 45 degree. So if it not applicable for slip but there is a short mid off fielder. So it should be drawn complete for the short mid off fielder. i am not able to comment because 50+ reputation need, so i am answering. But there is comment option available sometime. There some problem with the site.
Answer: The reason for not drawing the 15yard circle is that they would overlap and become confusing to the umpires.
So the circle is dotted to allow the umpires the reference point without the additional confusion of the full circle.
Additionally the groundsman would prefer not to draw white lines at random all over the other pitches on his square.

why 15 yard circle is drawn incomplete?


Phase portrait of a gradient system on a torus

Question:
Let $T$ be the torus defined as the square $0\leq \theta_1, \theta_2\leq 2\pi$ with opposite sides identified. Let $F(\theta_1,\theta_2)=\cos\theta_1+\cos\theta_2$. Sketch the phase portrait for the system $-\text{grad}\, F$ in $T$. Sketch a three-dimensional representation of this phase portrait with $T$ represented as the surface of a doughnut.

I understand that the $-\text{grad}(F) = (\sin(\theta_1), \sin(\theta_2))$, but I'm very confused on how the torus is defined here.  Why is a doughnut defined as a square?
I'm guessing in essence that we can find $\theta'_1$ and $\theta'_2$ and apply the domain to it, but the confusion on $T$ leaves me stuck?
Answer: It's called flat torus. Here is the animation from Wikipedia page about torus, that shows how you can map points of a square with identical sides to a torus surface in 3D.
Answer: To continue the answered of  Vasily Mitch, the torus is homeomorphic to
$ S^1\times S^1 $, where $S^1$ is the circle.
Thus, if we consider the square $0\leq\theta_1,\theta_2\leq 2\pi$, the top boundary $\theta_2=2\pi$ and the bottom one $\theta_2=0$ should be consider the same. In a completely analogous way, the left and right boundaries $\theta_1=0$ and $\theta_2=2\pi$ are supposed to be consider the same.
Take for example, the following vector field on a $T^2$ torus,
\begin{align}\theta_1'&=1\\\theta_2'&=\omega,\quad \omega\in\mathbb{R}\backslash\mathbb{Q}\end{align}
then you going to have something of this form, where the line represents the vectors field and they have slope $\omega$.. Note that this phase portrait is an approximation, because the solution $(\theta_1(t),\theta_2(t))$ fills $T^2$ densely.
In your exercise,
\begin{align}
\theta_1'&=\sin\theta_1\\
\theta_2'&=\sin\theta_2
\end{align}
with the following phase portrait in the square $0\leq\theta_1,\theta_2\leq 2\pi$, found by means of nullclines. Thus we have 4 equilibrium points: 1 sink, 2 saddle and 1 source. From this you can easily found the 3 dimensional phase portrait.
Comment: How would we know where the equilibrium points are? I'm trying to find them and how to determine which one are the sink, saddle and source..


mimic a domain on localhost

Question: I wish to know how can I host some domain names on my own machine.
I've installed wamp, but I don't wana use localhost/folder_name to access the project's I'm working on. I know that is possible to type www.myproject.com into my browser, but i don't know how or what to search on google. All I've tried didn't give me anything useful
Answer: The hosts file controls access to this.  In Windows XP, it's C:\Windows\System32\Drivers\Etc\Hosts with no file extension.  You'll need to use notepad to edit the file and add a line reading
127.0.0.1 www.example.com

If there is already a line starting 127.0.0.1 then you should add www.example.com to the end of it
127.0.0.1 localhost www.example.com

Keep in mind that while this line is there you will never be able to access www.example.com on the real server.
Answer: You can modify your etc/hosts file and add reference to www.myproject.com pointing to 127.0.0.1

mimic a domain on localhost


Job queue – dealing with stuck records

Question: I have a cron job that gets stuck because I have a loop claiming items from the queue that ends on numberOfItems() == 0, which never happens because one of the queue items is stuck and cannot be claimed.
Clearly this is a flaw on my side, but I am trying to understand how to best address it. The claimItem() method returns FALSE every time in this case, so it should be easy to handle cases of bad queue processing, for example:
while ($item = $queue->claimItem()) {
    // process item
}

However, what if the first queue item is "faulty", while there are other queue items that are perfectly fine? I will never be able to retrieve them in this method. It also seems impossible to move on to the next item in the queue if claimItem() returns false (please correct me if I am wrong).
What is the correct way to handle such cases with Drupal's queue?
Answer: When looking at the code from the claimItem method it only returns FALSE if no items are available to claim.
So if $queue->claimItem() returns FALSE you can be sure that all available items are claimed (or failed to be claimed).
public function claimItem($lease_time = 30) {
  // Claim an item by updating its expire fields. If claim is not successful
  // another thread may have claimed the item in the meantime. Therefore loop
  // until an item is successfully claimed or we are reasonably sure there
  // are no unclaimed items left.
  while (TRUE) {
    try {
      $item = $this->connection->queryRange('SELECT data, created, item_id FROM {' . static::TABLE_NAME . '} q WHERE expire = 0 AND name = :name ORDER BY created, item_id ASC', 0, 1, [':name' => $this->name])->fetchObject();
    }
    catch (\Exception $e) {
      $this->catchException($e);
      // If the table does not exist there are no items currently available to
      // claim.
      return FALSE;
    }
    if ($item) {
      // Try to update the item. Only one thread can succeed in UPDATEing the
      // same row. We cannot rely on REQUEST_TIME because items might be
      // claimed by a single consumer which runs longer than 1 second. If we
      // continue to use REQUEST_TIME instead of the current time(), we steal
      // time from the lease, and will tend to reset items before the lease
      // should really expire.
      $update = $this->connection->update(static::TABLE_NAME)
        ->fields([
          'expire' => time() + $lease_time,
        ])
        ->condition('item_id', $item->item_id)
        ->condition('expire', 0);
      // If there are affected rows, this update succeeded.
      if ($update->execute()) {
        $item->data = unserialize($item->data);
        return $item;
      }
    }
    else {
      // No items currently available to claim.
      return FALSE;
    }
  }
}

Job queue – dealing with stuck records


Problema com beans no spring : No qualifying bean of type

Question: estou tendo o seguinte problema com os beans no spring:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'agrupamentoTaxonomiaController' defined in file [D:\IBGE\workspaces\Agatha\adaptacao-RedHat-OpenShift\agatha\codigo-fonte\servico\target\classes\br\gov\mpog\gestaoriscos\controller\AgrupamentoTaxonomiaController.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [br.gov.mpog.gestaoriscos.servico.AgrupamentoTaxonomiaService]: Error creating bean with name 'agrupamentoTaxonomiaServiceImpl' defined in file [D:\IBGE\workspaces\Agatha\adaptacao-RedHat-OpenShift\agatha\codigo-fonte\servico\target\classes\br\gov\mpog\gestaoriscos\servico\impl\AgrupamentoTaxonomiaServiceImpl.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [br.gov.mpog.gestaoriscos.repositorio.AgrupamentoTaxonomiaRepository]: No qualifying bean of type [br.gov.mpog.gestaoriscos.repositorio.AgrupamentoTaxonomiaRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [br.gov.mpog.gestaoriscos.repositorio.AgrupamentoTaxonomiaRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'agrupamentoTaxonomiaServiceImpl' defined in file [D:\IBGE\workspaces\Agatha\adaptacao-RedHat-OpenShift\agatha\codigo-fonte\servico\target\classes\br\gov\mpog\gestaoriscos\servico\impl\AgrupamentoTaxonomiaServiceImpl.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [br.gov.mpog.gestaoriscos.repositorio.AgrupamentoTaxonomiaRepository]: No qualifying bean of type [br.gov.mpog.gestaoriscos.repositorio.AgrupamentoTaxonomiaRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [br.gov.mpog.gestaoriscos.repositorio.AgrupamentoTaxonomiaRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}

AgrupamentoTaxonomiaRepository
    package br.gov.mpog.gestaoriscos.repositorio;

    import br.gov.mpog.gestaoriscos.modelo.AgrupamentoTaxonomia;
    import org.springframework.data.jpa.repository.JpaRepository;

    /**
     * Spring Data JPA repository for the AgrupamentoTaxonomia entity.
     */
    public interface AgrupamentoTaxonomiaRepository extends JpaRepository<AgrupamentoTaxonomia, Long>{
    }

AgrupamentoTaxonomiaCustomRepositorioImpl
@Repository
public class AgrupamentoTaxonomiaCustomRepositorioImpl implements AgrupamentoTaxonomiaCustomRepositorio{

    @Autowired
    private JpaContext jpaContext;

    //RESTO DO CÓDIGO ...
}

Alguém saberia me informar como resolver? Aparentemente o @Autowired e os tipos de classe estão definidos e a classe repository também.
EDIT
AgrupamentoTaxonomiaController
@RestController
@RequestMapping(value = "/agrupamentotaxonomias", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class AgrupamentoTaxonomiaController {

    private final Logger log = LoggerFactory.getLogger(AgrupamentoTaxonomiaController.class);

    private final AgrupamentoTaxonomiaService service;

    @Autowired
    public AgrupamentoTaxonomiaController(AgrupamentoTaxonomiaService service) {
        this.service = service;
    }

    //RESTO DO CÓDIGO...
}

AgrupamentoTaxonomiaService
/**
 * Service Interface for managing Taxonomia.
 */
public interface AgrupamentoTaxonomiaService {

      //METODOS A SEREM IMPLEMENTADOS EM OUTRA CLASSE
}

AgrupamentoTaxonomiaServiceImpl
/**
 * Service Implementation for managing Taxonomia.
 */
@Service
@Transactional
public class AgrupamentoTaxonomiaServiceImpl implements AgrupamentoTaxonomiaService {

    private final Logger log = LoggerFactory.getLogger(AgrupamentoTaxonomiaServiceImpl.class);

    private final AgrupamentoTaxonomiaRepository agrupamentoTaxonomiaRepository;

    private final TaxonomiaRepository taxonomiaRepository;

    private final StatusTaxonomiaRepository statusTaxonomiaRepository;

    private final TipoTaxonomiaRepository tipoTaxonomiaRepository;

    private final AgrupamentoTaxonomiaCustomRepositorio agrupamentoTaxonomiaCustomRepositorio;

    private final TaxonomiaCustomRepositorio taxonomiaCustomRepositorio;

    private final EventoRepository eventoRepository;

    private final CausaRepository causaRepository;

    private final ConsequenciaRepository consequenciaRepository;

    private final ControleRepository controleRepository;

    private final OrgaoRepository orgaoRepository;

    private final EventoRiscoRepository eventoRiscoRepository;

    private final EventoCausaRepository eventoCausaRepository;

    private final EventoConsequenciaRepository eventoConsequenciaRepository;

    private final ControleEventoRepository controleEventoRepository;

    private final PlanoControleRepository planoControleRepository;

    private final EventoCustomRepositorio eventoCustomRepositorio;

    private final CausaCustomRepositorio causaCustomRepositorio;

    private final ConsequenciaCustomRepositorio consequenciaCustomRepositorio;

    private final ControleCustomRepositorio controleCustomRepositorio;

    private final AgrupamentoTaxonomiaMapper agrupamentoTaxonomiaMapper;

    private final TipoTaxonomiaMapper tipoTaxonomiaMapper;

    private final TaxonomiaMapper taxonomiaMapper;

    private final EventoMapper eventoMapper;

    private final CausaMapper causaMapper;

    private final ConsequenciaMapper consequenciaMapper;

    private final ControleMapper controleMapper;

    @Autowired
    public AgrupamentoTaxonomiaServiceImpl(AgrupamentoTaxonomiaRepository agrupamentoTaxonomiaRepository, CausaRepository causaRepository, TaxonomiaRepository taxonomiaRepository, StatusTaxonomiaRepository statusTaxonomiaRepository, TipoTaxonomiaRepository tipoTaxonomiaRepository, AgrupamentoTaxonomiaCustomRepositorio agrupamentoTaxonomiaCustomRepositorio, TaxonomiaCustomRepositorio taxonomiaCustomRepositorio, ControleCustomRepositorio controleCustomRepositorio, EventoRepository eventoRepository, PlanoControleRepository planoControleRepository, EventoCausaRepository eventoCausaRepository, ConsequenciaRepository consequenciaRepository, AgrupamentoTaxonomiaMapper agrupamentoTaxonomiaMapper, TaxonomiaMapper taxonomiaMapper, ControleRepository controleRepository, EventoCustomRepositorio eventoCustomRepositorio, ConsequenciaCustomRepositorio consequenciaCustomRepositorio, EventoConsequenciaRepository eventoConsequenciaRepository, OrgaoRepository orgaoRepository, ControleEventoRepository controleEventoRepository, EventoRiscoRepository eventoRiscoRepository, CausaCustomRepositorio causaCustomRepositorio, TipoTaxonomiaMapper tipoTaxonomiaMapper, EventoMapper eventoMapper, CausaMapper causaMapper, ConsequenciaMapper consequenciaMapper, ControleMapper controleMapper) {
        this.agrupamentoTaxonomiaRepository = agrupamentoTaxonomiaRepository;
        this.causaRepository = causaRepository;
        this.taxonomiaRepository = taxonomiaRepository;
        this.statusTaxonomiaRepository = statusTaxonomiaRepository;
        this.tipoTaxonomiaRepository = tipoTaxonomiaRepository;
        this.agrupamentoTaxonomiaCustomRepositorio = agrupamentoTaxonomiaCustomRepositorio;
        this.taxonomiaCustomRepositorio = taxonomiaCustomRepositorio;
        this.controleCustomRepositorio = controleCustomRepositorio;
        this.eventoRepository = eventoRepository;
        this.planoControleRepository = planoControleRepository;
        this.eventoCausaRepository = eventoCausaRepository;
        this.consequenciaRepository = consequenciaRepository;
        this.agrupamentoTaxonomiaMapper = agrupamentoTaxonomiaMapper;
        this.taxonomiaMapper = taxonomiaMapper;
        this.controleRepository = controleRepository;
        this.eventoCustomRepositorio = eventoCustomRepositorio;
        this.consequenciaCustomRepositorio = consequenciaCustomRepositorio;
        this.eventoConsequenciaRepository = eventoConsequenciaRepository;
        this.orgaoRepository = orgaoRepository;
        this.controleEventoRepository = controleEventoRepository;
        this.eventoRiscoRepository = eventoRiscoRepository;
        this.causaCustomRepositorio = causaCustomRepositorio;
        this.tipoTaxonomiaMapper = tipoTaxonomiaMapper;
        this.eventoMapper = eventoMapper;
        this.causaMapper = causaMapper;
        this.consequenciaMapper = consequenciaMapper;
        this.controleMapper = controleMapper;
    }
    //resto do código

}

Eu postei só o básico que não mostre as regras de negócio pois é um software da empresa.
Comment: Posta o código do seu controller `agrupamentoTaxonomiaController` e `AgrupamentoTaxonomiaService`
Answer: Os Mappers da aplicação estavam no construtor e a anotação @Autowired tentava injeta-las como dependências. Isso estava causando o problema, após tira-los do construtor de cada classe a aplicação funcionou normalmente.
Answer: Adicione a seguinte anotação na classe principal:
@EnableJpaRepositories("br.gov.mpog.gestaoriscos.repositorio");

Comment: Não funcionou. :/
Comment: @PedroTeixeira atualizei a resposta
Comment: Ainda não funcionou.
Answer: /**
 * Service Interface for managing Taxonomia.
 */
@Service
public interface AgrupamentoTaxonomiaService {

      //METODOS A SEREM IMPLEMENTADOS EM OUTRA CLASSE
}

Tente realizer a inserçao do @Service na Interface se estiver referenciando ela no seu Controller.
Comment: Já está no AgrupamentoTaxonomiaServiceImpl que coloquei agora ali em cima.
Comment: @PedroTeixeira pq exatamente esta criando uma implementaçao para o repository?
Comment: Esse projeto é da empresa. Não sei quem fez, me pediram pra alterar o mínimo possível. Também não sei qual foi a finalidade, acreditava ser algum design pattern.
Answer: O que pode estar acontecendo é que quando a controller tenta instanciar a classe AgrupamentoTaxonomiaServiceImpl ele não consegue pois só existe um método construtor nessa classe, que necessita a passagem de parametros. O que pode solucionar o seu problema é apagar o construtor da classe AgrupamentoTaxonomiaServiceImpl e colocar o @Autowired em cima de cada atributo da classe para ser feita a injeção de dependencia.
Comment: Continua dando erro, mas mudou o final dele:

`No qualifying bean of type [br.gov.mpog.gestaoriscos.servico.mapper.AgrupamentoTaxonomiaMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}`
Comment: tente marcar essa classe com `@Component`, ou crie um `bean` pra ela.


make page peel effect better

Question: I would like your suggestions here for the following points

Make peel effect more realistic if possible.
Reduce the size of the peel (to be able to see the full Ad).

Jsfiddle peel effect
I used a div pagePeelsmallrotate rotated at 24deg initially. Which i then animate its angle as well as dimensions .
Also div pagePeelcontainer dimensions are animated.
There are two functions
         var pagePeelopen = function() {}  /*opens the ad*/
         var pagePeelclose = function() {} /*closes the ad */

I tried skewing only the pagePeelcontainer  div and not its children to get small peel as provided here
css used to avoid child elements getting affected
#pagePeelcontainer > * {
    transform:skew(-45deg);
}

But couldn't get the peel effect properly on click of open.
Jsfiddle skewed peel
Let me know how i can do it
Comment: To Reduce the size of the peel (to be able to see the full Ad); change $('#pagePeelcontainer').stop().animate({
                width: desired,
                height: desired
            }

I don't quite understand your first point, make peel effect more realistic it is already, but you can change duration to get a slower or faster effect as required
Comment: @AhmadAlsanie Thank you. Can you provide me a fiddle link, where i can see peel size being reduced with the change you mentioned.
Comment: http://andrewplummer.github.io/Peel.js/ found this, but it would mean adding more to your site
Answer: Changing this section of code
            $('#pagePeelcontainer').stop().animate({
                width: 1000,
                height: 1000
            }, {
                duration: 500
            });

Will reveal the whole advert, as for the peeling it looks pretty good the way it is
Comment: Thanks. but the peel effect changes if i increase it

make page peel effect better


Show an exception message from a resharper plugin

Question: In the course of the development of a Resharper plugin, I'd like to show an error message to a user when they incorrectly use a context action. Is there a way to pop up a window in Visual Studio to communicate the Resharper exception message to the user? I'm developing a plugin with Resharper 8 and VS 2012
Comment: What's wrong with just using `MessageBox.Show`? Or do you have requirements that make this approach unworkable?
Answer: You can always use MessageBox - ReSharper also provides a MessageBox static class that provides a number of helper methods to make it easy to display what you want. It also allows for adding "message box handlers" so that you don't actually display a message box during testing.
Alternatively, if you're creating a context action, and you're (indirectly) deriving from BulbActionBase, your ExecutePsiTransaction method (which should do all the work) can return an Action<ITextControl>. This allows you to return an action that will execute after the quick fix/context action has completed, which can be anything from positioning the caret, changing the selection, executing a template or showing a tooltip as an error.
You can return something like this:
return tc => myLocks.QueueReadLock("MyContextAction", () => {
    myTooltipManager.Show("Something went wrong!",
      lifetime => new TextControlPopupWindowContext(lifetime, tc, myLocks, myActionManager);
  });

This is using a number of fields: IShellLocks myLocks, ITooltipManager myTooltipManager and IActionManager myActionManager. These can be injected into a component's constructor by ReSharper's component model, or you can get them with solution.GetComponent<IShellLocks>, etc.
What's happening is that you're returning an action that takes in an ITextControl, and which immediately queues up another action to run, on the UI thread, with the read lock taken. This second action tells the tooltip manager to show an error message as a tooltip, and provides a factory method for creating a popup window context (the lifetime parameter is created and disposed by the call to Show, and allows for cleanup of the context).
You could also look at the ShowAtCaret extension method to ITooltipManager - I can't remember offhand where Show will place the tooltip.


Reduzir esse jquery a somente 1 bloco e não 3, como faço?

Question: Qual a melhor forma de reduzir esse código abaixo a somente um bloco?
Estava usando somente um porem quando eu colocava o mouse sobre um icon o efeito hover aparecia para todos.

$('.sidebar-chart-1 .icon-info').mouseover(function(){
  $('.sidebar-chart-1 .tooltip-info').show();
 });

 $('.sidebar-chart-1 .icon-info').mouseout(function(){
  $('.sidebar-chart-1 .tooltip-info').hide();
 });
// =====
 $('.distribuicao-fundamental-1 .icon-info').mouseover(function(){
  $('.distribuicao-fundamental-1 .tooltip-info').show();
 });

 $('.distribuicao-fundamental-1 .icon-info').mouseout(function(){
  $('.distribuicao-fundamental-1 .tooltip-info').hide();
 });
// =====
 $('.distribuicao-fundamental-2 .icon-info').mouseover(function(){
  $('.distribuicao-fundamental-2 .tooltip-info').show();
 });

 $('.distribuicao-fundamental-2 .icon-info').mouseout(function(){
  $('.distribuicao-fundamental-2 .tooltip-info').hide();
 });

Acumulado e Meta do ciclo atual (2016/17)

    informações sobre o gráfico.

Comment: `.tooltip-info` é filho ou irmão de `.icon-info`? poderia por o HTML?
Comment: @GuilhermeLautert editei Obrigado.
Comment: Você quer dizer de 6 blocos para 1, não ?
Comment: Na vdd 3 mesmo, e que considero ação show e hide como um bloco só. @MagicHat
Comment: Hum saquei...;)
Answer: Você pode fazer isso criando um nova class genérica para todos os elementos.
Exemplo
utilizei a class show.

$('.show .icon-info').mouseover(function(){
 $(this).parent().find('.tooltip-info').show();
}).mouseout(function(){
 $(this).parent().find('.tooltip-info').hide();
});
.tooltip-info{
  display:none;
}

  SideBar

      test 1

  Descrição Funcionario

      test 1

Nota

Não á necessidade redeclarar a sentença apos chamar um evento no jQuery, pode usar chaining, pois ele retorna o this.
Comment: Perfeito, muto obrigado.
Answer: A maravilha do Jquery é justamente permitir selecionar praticamente tudo o que desejar sem ter que modificar o código html, segue abaixo alguns exemplos:

$('h1 .icon-info').hover(function() {
  $(this) // representa exatamente o 'h1 .icon-info' que disparou o hover, mesmo que tenham outros iguais na pagina
  .siblings('.tooltip-info') // seleciona o seu irmão chamado '.tooltip-info'
  .toggle() // se estiver oculto mostra, se estiver visivel oculta.
  .css({
    top: $(this).offset().top + $(this).outerHeight(),
    left: $(this).offset().left
  }); // posiciona '.tooltip-info' em relação a posição deste 'h1 .icon-info'
});

$('h2 .icon-info').hover(function() {
  $(this) // representa exatamente o 'h2 .icon-info' que disparou o hover, mesmo que tenham outros iguais na pagina
  .parent() // seleciona o elemento pai
  .find('.tooltip-info') // procura por '.tooltip-info' dentro do pai
  .toggle() // se estiver oculto mostra, se estiver visivel oculta.
  .css({
    top: $(this).offset().top + $(this).outerHeight(),
    left: $(this).offset().left
  }); // posiciona '.tooltip-info' em relação a posição deste 'h2 .icon-info'
});

$('h3 .icon-info').hover(function() {
  $(this) // representa exatamente o 'h3 .icon-info' que disparou o hover, mesmo que tenham outros iguais na pagina
  .parents('div') // seleciona o primeiro div pai que encontrar
  .next('div') // seleciona o proximo div depois do div pai
  .find('.tooltip-info') // procura por '.tooltip-info' dentro do proximo div
  .toggle() // se estiver oculto mostra, se estiver visivel oculta.
  .css({
    top: $(this).offset().top + $(this).outerHeight(),
    left: $(this).offset().left
  }); // posiciona '.tooltip-info' em relação a posição deste 'h3 .icon-info'
});

$('div > .icon-info').hover(function() {
  $(this) // representa exatamente o 'div > .icon-info' que disparou o hover, mesmo que tenham outros iguais na pagina
  .next('.tooltip-info') // seleciona o proximo '.tooltip-info' depois de 'div > .icon-info'
  .toggle() // se estiver oculto mostra, se estiver visivel oculta.
  .css({
    top: $(this).offset().top + $(this).outerHeight(),
    left: $(this).offset().left
  }); // posiciona '.tooltip-info' em relação a posição deste 'div > .icon-info'
});
.tooltip-info {
  display: none;
  position: absolute;
  border: 1px solid red;
  padding: 10px;
  background: white;
  border-radius: 5px;
  box-shadow: 3px 3px 10px grey;
  font: 14px normal;
  margin-top: 8px;
}
.icon-info {
  cursor: pointer;
}
<link rel="stylesheet" href="https://opensource.keycdn.com/fontawesome/4.6.3/font-awesome.min.css" integrity="sha384-Wrgq82RsEean5tP3NK3zWAemiNEXofJsTwTyHmNb/iL3dP/sZJ4+7sOld1uqYJtE" crossorigin="anonymous">

Lorem ipsum

    H1 Lorem ipsum dolor sit amet,
consectetur adipiscing elit.

Lorem ipsum

    H2 Lorem ipsum dolor sit amet,
consectetur adipiscing elit.

Lorem ipsum

  H3 Lorem ipsum dolor sit amet,
consectetur adipiscing elit.

  Loren

  Lorem sit amet,
consectetur adipiscing elit.
  Ipsum

  Ipsum sit amet,
consectetur adipiscing elit.
  Dolor

  Dolor sit amet,
consectetur adipiscing elit.


como criar uma máscara de moeda com regEx

Question: olá, sou iniciante com angular 4, estou tentando fazer uma mascara para uma campo do tipo texto para validar uma valor em m².
A class Mask contem o método para criar a mascara, o valor informado pode ser entre 1 e ilimitado.
queria que o método retorna-se algo nesse contexto: 1.000.000,00 ou 10.000,00 ou 1.000,00

export class Mask
{

  public static getArea():Array<string|RegExp>
    {

     return [/\d/,/\d/,/\d/,'.',/\d/,/\d/,/\d/,'.',/\d/,/\d/,/\d/,',',/\d/,/\d/];

    }
}
<input formControlName="areaImovel" [textMask]="{ mask: areaMask }" type="text" id="form-area-imovel" class="form-control">

Chamando no Component

import { Mask } from './mask';

export class EnderecoComponent implements OnInit {
  public areaMask = Mask.getArea();

  constructor(){}
}
Comment: Qual o problema ?
Comment: Tente esta Regex: `\d{1,3}(?:\.\d{3})+,\d{2}$` e a [demo na Regex101](https://regex101.com/r/NgnQnM/3). Para validação do campo.
Answer: Use o dependência do  ng2-currency-mask:

adicione a dependência no seu projeto:
npm i ng2-currency-mask --save

importe no seu modelo o componente:
import { CurrencyMaskModule } from 'ng2-currency-mask';

use:

<input type="text" id="form-area-imovel" formControlName="areaImovel"
 class="form-control" placeholder="0,00"
 currencyMask [options]="{ prefix: '', thousands: '.', decimal: ',', allowNegative: false }">

Answer: Encontrei em outro local uma regex para a validação de moeda, \^(\d{1,3}(\.\d{3})*|\d+)(\,\d{2})?$\.
Para verificar o funcionamento, https://regex101.com/r/VWk35U/2. A expressão aceita estes tipos de valores,

1.000.000,00
10.000,00
1.000,00
1042,35
100,25
999.999.999.999.999.999,00

O site original da regex é, O site é https://precisoestudarsempre.blogspot.com/2014/12/regex-para-validacao-de-moeda.html
Comment: Não precisa escapar a vírgula


Make a DIV the default scroll on page load

Question: I have a div within a div that's actually the main content of the page (due to the way the client wanted it to slide into the page with a parallax effect). The body has overflow: hidden, and the div with the content has overflow-x: hidden; overflow-y: auto; (so the vertical scroll works).
Unfortunately if the user loads the page and immediately presses PGNDN or scrolls the mouse, it attempts to scroll the body tag.
If the user clicks anywhere in the content in the div and then presses PGNDN or scrolls the mouse, then the right content is scrolled.
How can I mimic the user clicking in this div on pageload so that even if they don't click on the content all scrolling events will scroll the page content and not the body.
I've tried adding tabindex=0 to the div. I've also tried adding an ID and forcing focus using JS. Neither
document.getElementById('focus').scrollIntoView();

nor
window.location.hash = '#focus';

worked for me.
jQuery is available.
Here's an example JSFiddle
Comment: Could you post a minimum code to reproduce your issue.
Comment: You should be able to set `overflow:hidden;` on all parents that you don't want to scroll.  no?
Comment: Have you tried document.getElementById('Id').click()  on page load?
Comment: @ntgCleaner That would only prevent scroll, and not make scroll behaviour focus on that div by default, and I've already done it... the problem is that there's a top margin set, so the page will scroll the distance of the margin -- even though there's no scroll bar.
Comment: @Screech129 I just did and no luck.
Comment: @LGSon I'll try. It may be very difficult given the amount of effects happening on the page.
Answer: Here is an attempt that seems to work well.
Updated fiddle  (fiddle doesn't work in firefox but a html page does)
HTML

CSS
#content {
  outline: none;   /* remove the focus outline */
}

Script onload
var cn = document.getElementById('content');
cn.contentEditable=true;                      /* appears only needed in fiddle demo */
cn.focus();
cn.contentEditable=false;                     /* appears only needed in fiddle demo */

Update
After I created and loaded your demo as a html page (no fiddle), you actually don't need the cn.contentEditable = true/false


Hi I'm a new in Java

Question:

public class MoviesData {
String Const;
String Your_Rating;
String Date_Rated;
String Title;
String URL;
String Title_Type;
String IMDb_Rating;
String Runtime_mins;
String Year;
String Genres;
String Num_Votes;
String Release_Date;
String Directors;

String filename="ratings.csv";

String ReadData(){
    File file=new File(filename).getAbsoluteFile();
    file.getAbsolutePath();
    String data = null;
    try{
    Scanner S=new Scanner(file);
    S.nextLine();
    S.useDelimiter(",\n");
    while(S.hasNext())
    {
        data=data+S.next();
    }
    S.close();
    }
    catch(Exception e)
    { JOptionPane.showMessageDialog(null, e.getStackTrace()[0]);               }
    return data;
    //String Data=data.replace(",","-");

  ArrayList<MoviesData> MD=new ArrayList<MoviesData>();
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
MoviesData m=new MoviesData();

String L=m.ReadData();
String[] M=L.split(",");
m.Const=M[0]; m.Your_Rating=M[1]; m.Date_Rated=M[2]; m.Title=M[3]; m.URL=M[4]; m.Title_Type=M[5];
m.IMDb_Rating=M[6]; m.Runtime_mins=M[7]; m.Year=M[8]; m.Genres=M[9]; m.Num_Votes=M[10];
m.Release_Date=M[11];m.Directors=M[12];
System.out.println(L);

i field has many , between "" i want to chance it
I have String like this (6.2,108,1990,"Action, Horror, Sci-Fi, Thriller",119935,) want to change the , only between "" not all , i get the String from Scanner CSv file
Answer: Well I'm pretty stupid so I can't tell exactly what you want but I can guess, if you are asking how you could put anything into a String, you can convert it into a String, a character will go in since it is compatible, for putting in something like a double or an int you can use the Interger.parseInt() and Double.parseDouble() methods like String new = Double.parseDouble(5); but I am probably not understanding the question so If I did than feel free to ignore this answer.
Comment: Sorry for bad explain I have String like this (6.2,108,1990,"Action, Horror, Sci-Fi, Thriller",119935,) want to change the , only between "" not all ,
Comment: i get the String from Scanner CSv file and but it in String
Comment: Well there is a .replace() method you can use for that, like String
 = String.replace(","," ");
Comment: this method will replace the only , between "" not All
Comment: Well for that have you though of making a subString of the things between the "" and then replacing the original with that substring
Comment: sure one sec tho
Comment: public class StringReplacer{
 public static void main(String[] args){
  String string = "6.2,108,1990,\"Action, Horror, Sci-Fi, Thriller\",119935,";
  String replaced = null;
  String substring = string.substring(string.indexOf("\""), string.lastIndexOf("\""));
  System.out.println(substring);
  substring = substring.replace(",", " ");
  System.out.println(substring);
  String finalString = string.substring(0, string.indexOf("\"")) + substring + string.substring(string.lastIndexOf("\""), string.length());
  System.out.println(finalString);
 }
}
Comment: Sorry you put \ manual it's big data my IMDB.com data and i want to modify it automatically to put each part in variables but thank you for your help
Comment: @DaHomieAdamand please don't use comment section to post code answers. [edit] the answer instead.

Hi I'm a new in Java


IntelliJ standard dialog controls and chinese symbols

Question: How to make IntelliJ IDEA properly show chinese symbols in standard dialog controls I wonder?
I want to have chinese symbols in the configuration name
This is how it looks like:
Answer: Try changing the appearance font:
Comment: Works for me! Thanks. But I use DialogInput font instead.


Height of UITableViewCell based on cell Click

Question: i am trying to change the height of the first  UITableViewCell of UITableView on click on the cell, i have been able to change the height on click but its not giving me the desired effect, it reduces the height from the top of the cell not the bottom, i want the height to be reduce from the bottom to a particular point towards the top. This is the code am using at present.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.row == 0 {
        return checkHeightBasedOnVisibility()
    }else if indexPath.row == 1 {
        return 300
    }else {
        return 200
    }
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if indexPath.row == 0 {

        if isVisible {
            isVisible = false
            tableView.reloadData()
        }
        else {
            isVisible = true
            tableView.reloadData()
        }
    }
}

// MARK: Private Methods
func checkHeightBasedOnVisibility() -> CGFloat {
    if isVisible {
        return 239
    }
    else {
        return 44
    }
}

Comment: Are you using a custom UITableViewCell, and if so, what constraints have you set up?
Comment: did you upload your gif that show some error or issue ?
Comment: @MikeTaverne Thanks, the issue came from the constraints, and i have been able to solve it
Answer: Make your func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) function look like this:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if indexPath.row == 0 {
        isVisible = !isVisible
        tableView.beginUpdates()
        tableView.endUpdates()
    }
}

Comment: Thanks, this not what i want but it helped simplify my code
Answer: The issue is from the constraints i set, i mistakingly constraint the bottom of table to a different view, instead of the view below it.


Connecting a digital piano keyboard with guitar pedal and USB Audio Interface: what am I doing wrong?

Question: I am a n00b in the field of electronic music production, as I have been played acoustic piano for years.
I am trying to connect my digital piano, a Kawai CN37, to guitar pedals.
I have the following setup:
Piano LINE OUT -> Guitar Pedal (boss DS-1/ Zoom gx1on) -> USB Audio Interface (Behringer 202HD) -> Piano LINE IN
So the idea is to use the piano speakers to emit sound.
The problem is that often I get a high pitch distorted sound even when I am not playing anything. This happens when the output is the piano speaker, but NOT when the output is the headphones. With the DS-1 I can get rid of it by adjusting the gain on the USB interface. However for the Zoom gx1on, I can't actually get rid of it , even with the lower gain setting.
My understanding is that it has to do with the level used by the different device. The piano uses a Line Level, the pedals are Inst, and I can change the level on the USB interface from Line to Inst. However, I couldn't manage to get rid of the ringing noise.
Any idea?
Answer: Page 131 of the manual states:

Do not connect the LINE IN and LINE OUT jacks of the CN37 digital piano together with the same cable.  An audio loop (oscillation sound) will occur, resulting in damage to the unit.

From that, my assumption is that the input from the line in is always mixed to the line out.
Although you're not literally using the same cable in your setup, it sounds like you're still creating a feedback loop as the piano 'hears' its own signal from the line in, and sends it out again through the line out.
Comment: Thank you for your answer, I doubt that's what happens. I would expect to hear a lot more noise, whereas I have that problem only with some pedal. I think it depends on the output level from the pedals/piano to the USB interface. I edited the question to be clearer.
Comment: Can you try connecting a sound source to the line in of the piano, then connecting an amplifier to the line out, and seeing if you can hear the sound source? As I said in my answer, the manual strongly implies that the line in *is* mixed to the line out, which would give you a feedback loop.
Comment: @Vaaal I agree that you might expect to hear more feedback there was a feedback loop - but is it true that the line in of the piano is always sent to the line out? If so, then surely you must have a feedback loop. Do you get a different result if you plug headphones into the audio interface?
Comment: I believe that the line IN sends the signal to the speakers - but there is no connection from here to the line OUT again, so there is no loop. The line out sends the signal to the pedals and USB interface, but only the signal emitted when pressed the key - not the one capture by the speakers.
Comment: In the headphones the audio is better, I can hear that strange ringing tone only when the gain is really high, which again makes me think is something that has to do with the output level with some of the peals?
Comment: @Vaaal have you disconnected the line in when you tried with the headphones? Are you absolutely sure that there's no connection from the line in to the line out? The manual suggests otherwise. Have you tried putting something in to the line in and seeing if it comes out of the line out?
Comment: What do you mean put something in to the line in and see if it comes out exactly? :) Sorry, as I said I am a noob on this topic
Comment: ' Are you absolutely sure that there's no connection from the line in to the line out? ' No, I am not sure
' have you disconnected the line in when you tried with the headphones? ', yes, tried that too, headphones work normally
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/96606/discussion-between-vaaal-and-topo-morto).
Comment: Why would you doubt this answer? The manual says "Do not connect the LINE IN and LINE OUT jacks". You don't often get an answer as clear as that.
Comment: The manual says: 'Do not connect the LINE IN and LINE OUT jacks of the CN37 digital piano together with the same cable. ' I wasn't using the same cable.


Proving a theorem in classical propositional logic

Question: In van Fraasen and Beall's book Possibilities and Paradox, there is the following line (on pg 7):

"In classical propositional logic we can prove that $$(A \iff B) \lor (A
 \iff C) \lor (B \iff C)$$ is valid."

$A, B$ and $C$ have not been previously defined.
Can someone point me to the proof of this theorem?
Answer: The letters $A,B$, and $C$ stand for propositions, each of which may be either true of false. The point of the quoted statement is that it doesn't matter exactly what propositions they are or which of them (if any) are true: the displayed statement is true no matter what.
You can prove it with a truth table. However, you don't actually need one. $$(A\iff B)\lor(A\iff C)\lor(B\iff C)$$ is true if and only if at least one of the disjuncts $A\iff B$, $A \iff C$, and $B\iff C$ is true. $A\iff B$ is true exactly when $A$ and $B$ have the same truth value: both are TRUE, or both are FALSE. Similarly, $A\iff C$ is true exactly when $A$ and $C$ have the same truth value, and $B\iff C$ is true exactly when $B$ and $C$ have the same truth value.
Since there are only two truth values in classical propositional logic, no matter how you assign truth values to $A,B$, and $C$, two of them have to get the same truth value. This means that under any assignment of truth values to $A,B$, and $C$, at least one of the three disjuncts has to be true, and hence the whole proposition must be true as well.
Comment: You might want to add what **are** $A,B,C$. It seems to me that this is what confused the OP.
Comment: @Asaf: You beat me to it: I was just looking at it and thinking the same thing.
Answer: Here is a natural deduction proof using a Fitch-style proof checker.
The first part starts the proof using the law of the excluded middle on $(A\leftrightarrow B)\lor \neg A\leftrightarrow B)$. The left disjunct derives the desired goal in lines 1-2. The rest of the proof will show how the right disjunct does the same.

The law of the excluded middle will be used on $(B\leftrightarrow C)\lor \neg (B \leftrightarrow C)$ to derive the goal from the left disjunct of line 20:

The law of the excluded middle will be used on $(A\leftrightarrow C)\lor \neg (A \leftrightarrow C)$ to derive the goal from the right disjunct of line 20:

Kevin Klement's JavaScript/PHP Fitch-style natural deduction proof editor and checker http://proofs.openlogicproject.org/


fazer retornar a uma parte do codigo no java

Question:     System.out.println("digite Lançar para Rolar os dados para atirar no homem");
    P1_rolar = L.next();
    long P1_dado1 = (long) (Math.random() * 20);

    if (P1_dado1 < 21) {
        System.out.print("seu resultado é: ");

        System.out.print(P1_dado1);
        System.out.print(" e Idril errou o tiro pois estava claramente bebado quando atirou \n");

        System.out.println("Digite Lançar para Rolar os dados novamente");
        P1_rolar = L.next();
        P1_i = 0;
        while(P1_i < 2) {System.out.println("..");Thread.sleep(1000); P1_i++;}

            long P1_dado2 = (long) (Math.random() * 20);
            if(P1_dado2 < 21) {
                System.out.print("seu resultado é: ");

                    System.out.print(P1_dado2);
                System.out.print(" e Idril errou o tiro novamente \n");

                System.out.println("Digite Lançar para Rolar os dados novamente");
                P1_rolar = L.next();
                P1_i = 0;
                while(P1_i < 2) {System.out.println("..");Thread.sleep(1000); P1_i++;}

                    long P1_dado3 = (long) (Math.random() * 20);
                    if (P1_dado3 < 20) {
                        System.out.print("seu resultado é: ");
                        System.out.print(P1_dado3);
                        System.out.println("vc perdeu tente novamente ");

                       //  fazer retornar pro começo do codigo

                    } else {System.out.println("Idril consegui acertar seu oponete com um tiro que arrancou a orelha, fazendo o homen desmaiar");}

        } else {System.out.println("Idril consegui acertar seu oponete com um tiro que arrancou a orelha, fazendo o homen desmaiar");}

    }else {System.out.println("Idril consegui acertar seu oponete com um tiro que arrancou a orelha, fazendo o homen desmaiar");}

    System.out.println("vc perdeu");

Comment: Forneça mais detalhes do que você precisa de ajuda, sinceramente olhando a sua pergunta não consegui compreender o que você precisa.
Comment: coloca essa sua necessidade na sua pergunta, editando seu post.
Comment: eu quero que se caso chegue no Terceiro if , ele retorne para o começo do código
Answer: A pergunta não está muito clara, mas se eu entendi bem você pode fazer isso com um do while:
boolean tentarNovamente = false;

do
{
    System.out.println("digite Lançar para Rolar os dados para atirar no homem");
    P1_rolar = L.next();
    long P1_dado1 = (long) (Math.random() * 20);
    if (P1_dado1 < 21)
    {
        System.out.print("seu resultado é: ");

        System.out.print(P1_dado1);
        System.out.print(" e Idril errou o tiro pois estava claramente bebado quando atirou \n");

        System.out.println("Digite Lançar para Rolar os dados novamente");
        P1_rolar = L.next();
        P1_i = 0;
        while(P1_i < 2)
        {
            System.out.println("..");
            Thread.sleep(1000);
            P1_i++;
        }

        long P1_dado2 = (long) (Math.random() * 20);

        if(P1_dado2 < 21)
        {
            System.out.print("seu resultado é: ");

            System.out.print(P1_dado2);
            System.out.print(" e Idril errou o tiro novamente \n");

            System.out.println("Digite Lançar para Rolar os dados novamente");
            P1_rolar = L.next();
            P1_i = 0;
            while(P1_i < 2)
            {
                System.out.println("..");
                Thread.sleep(1000);
                P1_i++;
            }
            long P1_dado3 = (long) (Math.random() * 20);
            if (P1_dado3 < 20)
            {
                System.out.print("seu resultado é: ");
                System.out.print(P1_dado3);
                System.out.println("vc perdeu tente novamente ");

                //  fazer retornar pro começo do codigo
                tentarNovamente = true;
            }
            else
            {
                System.out.println("Idril consegui acertar seu oponete com um tiro que arrancou a orelha, fazendo o homen desmaiar");
                tentarNovamente = false;
            }

        }
        else
        {
            System.out.println("Idril consegui acertar seu oponete com um tiro que arrancou a orelha, fazendo o homen desmaiar");
            tentarNovamente = false;
        }

    }
    else
    {
        System.out.println("Idril consegui acertar seu oponete com um tiro que arrancou a orelha, fazendo o homen desmaiar");
        tentarNovamente = false;
    }

}while(tentarNovamente);

System.out.println("vc perdeu");

Comment: muito obrigado.
Comment: @zDarkSword Se uma das respostas resolveu o seu problema, você pode escolher a que melhor resolveu e aceitá-la, veja [aqui](https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta) como e porque fazê-lo. Não é obrigatório, mas é uma boa prática do site, para indicar a futuros visitantes que aquilo resolveu o problema.
Answer: Realmente reformular a pergunta ajudaria.
Mas pelo o que entendi você precisa que seu código seja recursivo.
https://pt.wikipedia.org/wiki/Recursividade_(ci%C3%AAncia_da_computa%C3%A7%C3%A3o)
public class MyClass {
    public static void main(String args[]) {
        System.out.println(fatorial(5));
    }

   private static int fatorial(int n){
        if(n==1)
            return n;
        return fatorial(n-1)*n;
    }
}


Load UITableView images on background thread

Question: I have an app that present images that sent from the server (similar to Instagram) using a tableView.
from the server I got:

Full size image URL
Description (String)
Image width
Image height

and I have a custom cell that present that as I want.
Like Instagram, the height of the image isn't fixed, so the cell's height changes dynamically to the image's height.
The image that I get from the server is really big, so I crop every image to be Width - Screen's width, Height - Based of the width (keeps the ratio), like that:
func imageWithImage (sourceImage:UIImage, scaledToWidth: CGFloat) -> UIImage {
    let oldWidth = sourceImage.size.width
    let scaleFactor = scaledToWidth / oldWidth

    let newHeight = sourceImage.size.height * scaleFactor
    let newWidth = oldWidth * scaleFactor

    UIGraphicsBeginImageContext(CGSize(width:newWidth, height:newHeight))
    sourceImage.draw(in: CGRect(x:0, y:0, width:newWidth, height:newHeight))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage!
}

my problem is that the tableView is VERY slow. So I thought of loading and cropping the images in a background thread and while its loading to present a default image.
I've tried that (using SDKs like Alamofire, Kingfisher etc...) but then the size of the cells (UITableViewAutomaticDimension) were a mess (because of the dynamic height), the images changed to wrong images while scrolling and sometimes even crashed while scrolling.
So that's why I'm asking here, how can I load the cells in a background thread and to keep its dynamic size, its correct photos and to avoid crashing?
Thank you very much in advanced for you answers!
Note: I know both Swift and Objective-C, select your favorite :)
Comment: have you tried `SDWebImage` library its really good option for you to achieve above requirement.
Answer: I recommend using Alamofire for this. Check out this answer, providing both a solution using Alamofire and a custom one.
Edited post-comments:
For calculating the cell height based on the image, you will need to download and cache those images prior to reloading your tableView, as heightForRowAtIndexPath will be called before cellForRowAtIndexPath, so you need to know the image height before actually setting it as that cell's property. This answer is what you need for that.
Comment: I am using Alamofire, please pay attention to what I wrote, thanks!
`I've tried that (using Alamofire) but then the size of the cells (UITableViewAutomaticDimension) were a mess (because of the dynamic height), the images changed to wrong images while scrolling and sometimes even crashed while scrolling.`
Comment: Sorry  but there's no mention in your question of Alamofire.
Comment: I edited my answer, I think you should edit the subject of your question too, as its focused more on calculating the image height than on loading images on a back thread. Hope this will work for you.
Comment: OK, now everything is fine (`cell.imageView.setImageWith(myUrl)`), but sometimes the wrong images while scrolling
Comment: This shouldn't happen, there might be some other conflict there, try printing out the indexes of your cells at they show on screen and match them with the links and images you have in your array, see where the error might be. Also, please accept the answer if it helped you. Thanks


puts() e printf(), quando e qual usar?

Question: As solicitações de entrada da dados geralmente são precedidas de um texto indicativo do que desejasse receber e geralmente não possuem dados para serem formatados.
Se não estão sendo apresentado dados de variáveis no texto de solicitação, porquê nos livros e os professores sempre usam o printf()? A função puts() não serve para apresentar 'texto' simples?
Answer: As duas funções são iguais, porém a função puts() adiciona uma quebra de linha, igual a printf("\n")
Porem ao usar o puts() temos de ter noção que apenas imprime a string, não temos o controlo do printf() em que podemos imprimir algo como printf("int: %d, float: %f", x, y)
#include <stdio.h>
main() {
    printf("Hello world!");
    return 0;
}

Nesse exemplo do Hello world o compilador converte o printf() para puts()
push rbp
mov rbp,rsp
mov edi,str.Helloworld!
call dword imp.puts
mov eax,0x0
pop rbp
ret

Para concluir, o printf() é um pouco mais lento porque é preciso formatar as variaveis e concatenar para uma string para ser imprimido. Porém essa diferença é praticamente irrelevante.
Comment: o `puts()` tem muitas limitações, é por isso que não usado, até porque o desempenho é igual ao `printf()` aquela diferença que o compilador faz é insignificante
Comment: Esclarecedor, já que estou apenas começando já vou assumir isso como prática, quando quiser apenas escrever textos como "Hello word!" irei utilizar o `puts()`, assim o compilador tem menos uma tarefa, e ganho um pouco mais em performance...msm que a diferença seja praticamente irrelevante...de grão, em grão... kkk.
Comment: @J.Ferreira em geral os programadores experientes não fazem isto, hoje em dia há zero motivos para usar o `puts()`.
Comment: Essas coisas que eu não entendo, se o comando tem suas vantagens ou ao menos não tem desvantagens e no final o compilador o utiliza tbém, pq a comunidade não o utiliza? há em algum lugar em que essas boas práticas são citadas?(Perguntas retóricas que aceitariam respostas)
Answer: A diferença básica é que o printf() possui formatação e tem um controle mais amplo de como imprimir os dados desejados, é uma solução completa de impressão. O puts() é uma solução bem simples para jogar caracteres no console, você tem que entregar exatamente o que deseja, ele não manipula nada, então não pode mandar um número ou um conteúdo com um texto e esperar que saia algo visível como o esperado por um humano. A única coisa que ele faz a mais que o printf() é colocar uma quebra de linha automaticamente.
Já respondi mais sobre ele em Qual a diferença entre puts() e fputs()?.
Coloquei no GitHub para referência futura.

puts() e printf(), quando e qual usar?


Intermittent authorization failure on publish

Question: I am seeing an odd intermittent authorization failure on publish. My publisher is running on App Engine Standard (Python). Because of that, I am using the "old" python client library. So the code looks like this:
from googleapiclient.discovery import build
build('pubsub','v1').projects().topics().publish(topic=topic,body=body).execute()

This works just fine. The identity gets picked up and everything is authenticated. However, again intermittently, it will stop working and I get 403 forbidden errors. Then later it will start working again (even with the same topic and body). In the meantime, no code changes, no deployments.
I have had to wrap the publish to catch this error, throw it on a task queue and have the request repeat with decaying frequency until it finally starts working again a few hours later. This is OK in the very short term, but obviously this will not work for us.
To summarize, this is on the publish side, GAE Standard ... it works, then stops working, then works again.
Thanks for any insight or help.
Answer: It turns out, of course, that in fact there were deployments when I wasn't aware. So I thought, "no code change - no deployments", but there were deployments. And the issue was that the person making these deployments had an old library (or other dependency) for google_api_python_client. Once corrected, pubsub is working just fine.
Comment: Hi @Jay, good work finding the solution! Can you [accept your own answer](https://stackoverflow.blog/2009/01/06/accept-your-own-answers/)? It will make it more visible and help someone with the same issue as you find the solution. Thanks!
Comment: Thanks for the nudge. I had intended to accept my own answer - lost track of it.


How to plot several barplots using seaborn with respect to row?

Question: Let's consider the data following:
accuracies_in = ([0.5959219858156029, 0.5736842105263158, 0.5670212765957447, 0.3])
accuracies_out = [0.5, 0.6041666666666666, 0.2, 0.4]
auc_out = [0.5182608695652174, 0.6095652173913042, 0.5, 0.7]
algorithm = ["Logistic Regression", "Decision Tree", "Random Forest", "Neural Network"]
frame = pd.DataFrame([accuracies_in, accuracies_out, auc_out])
frame.index = ["accuracies_in", "accuracies_out", "auc_out"]
frame.columns = algorithm

I want to have a barplot which will show results for those three characteristics (accuracies_in, accuarcies_out and auc_out). In other words on the barplot I want to group barplots more or less like this:

The first group (first row - accuracy_in) will contain four bars - accuracies_in for Logistic Regression, Decision Tree, Random Forest and Neural Network. Second group of bars will contain again four bars but this time for second row - accuracies_out. And lastly - the third group of bars will contain four bars with auc_out in each of them.
Could you please help me how it can be done? I searched a lot of questions but I couldn't find anything which will plot barplots with respect to rows. Could you please give me a hand in this problem?
Answer: You need to convert your dataframe to long form, using pd.melt.
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

# frame: given dataframe

df = frame.melt(var_name='Algorithm', value_name='Accuracy', ignore_index=False)
sns.set()
sns.barplot(data=df, x=df.index, y='Accuracy', hue='Algorithm')

Answer: You really have almost nothing to do but using the pandas builtin plot.bar:
frame.plot.bar()

input frame:
                Logistic Regression  Decision Tree  Random Forest  Neural Network
accuracies_in              0.595922       0.573684       0.567021             0.3
accuracies_out             0.500000       0.604167       0.200000             0.4
auc_out                    0.518261       0.609565       0.500000             0.7

output:
Comment: Or `frame.plot.bar(width=0.8, rot=0)`
Answer: What you can use is something like:
X = frame.index

X_axis = np.arange(len(X))
dist = 0.2
plt.figure(figsize=(10,8))
plt.bar(X_axis + (-1)* dist, frame["Logistic Regression"], dist, label = 'accuracies_in')
plt.bar(X_axis + 0 * dist, frame["Decision Tree"], dist, label = 'accuracies_out')
plt.bar(X_axis + 1 * dist, frame["Random Forest"], dist, label = 'auc_out')
plt.bar(X_axis + 2 * dist, frame["Neural Network"], dist, label = 'auc_out')

plt.xticks(X_axis, X)
plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.legend()
plt.show()

Output


reading an INI file and retrieving the required information

Question: I am looking for a way to read an .ini file to get the server host information from it. I got it loading static data, that part was easy, but I want to expand it so I can add more then one server in the .ini, and then let my program add them in order.
[Data]
Server[1]=tcp/220.127.116.11/7799 // server one
Server[2]=udp/126.96.36.199/7780 // server two
Server[3]=tcp/184.108.40.206/7733 // server three

I would like to be able to add multiple servers, here 1 to 10 or whatever, then display the correct server information, the protocol and ip and port. I have done that via split code, but I don't know how to do multiple servers.
I was thinking maybe a for loop to get the server number from .ini file:
sData := IniFile.ReadString('Data', 'Server['+ IntToStr(i) +']', '<none>');

Does anyone have any ideas how to do this?
Comment: You already provide the right answer. Not sure what your question is ? In any case, you may find [ReadSection](https://docwiki.embarcadero.com/Libraries/Sydney/en/System.IniFiles.TIniFile.ReadSection) and [ReadSectionValues](https://docwiki.embarcadero.com/Libraries/Sydney/en/System.IniFiles.TIniFile.ReadSectionValues) which builds a key=value list for you. This way, you can lookup from the variable list.
Answer: Drop the square brackets on the entry names:
[Data]
Server1=tcp/22.214.171.124/7799
Server2=udp/220.127.116.11/7780
Server3=tcp/126.96.36.199/7733

sData := IniFile.ReadString('Data', 'Server' + IntToStr(i), '<none>');

To know how many servers are present, you could add a ServerCount entry, eg:
[Data]
ServerCount=3
Server1=tcp/220.127.116.11/7799
Server2=udp/22.214.171.124/7780
Server3=tcp/18.104.22.168/7733

count := IniFile.ReadInteger('Data', 'ServerCount', 0);
for i := 1 to count do
begin
  sData := IniFile.ReadString('Data', 'Server' + IntToStr(i), '<none>');
  ...
end;

Or, you could use IniFile.ReadSection() to get all of the entry names into a local TStringList, then loop through that, eg:
names := TStringList.Create;
try
  IniFile.ReadSection('Data', names);
  for i := 0 to names.Count-1 do
  begin
    if StartsText('Server', names[i]) then
    begin
      sData := IniFile.ReadString('Data', names[i], '<none>');
      ...
    end;
  end;
finally
  names.Free;
end;

Comment: @dummzeuch, unless you're talking about a performance issue, it doesn't matter if the numbers are in order or not.  Perhaps you mean without gaps?  That can also be handled by doing a ValueExists() check first, although that's probably best reserved for cases where you are changing and deleting entries but wanting to retain the numbers.
Comment: Having that ServerCount entry can be a hassle. I usually read the full section and then parse all entries that match a given mask, e.g. Server??, allowing for numbers as well as other characters. It has the advantage that you don't need to keep those numbers in order. Just make sure they are unique. So your second example would be my way to go.
Comment: If the entries are named Server1 to Server3, you're not going to want to loop from 0 to Count-1.
Comment: thanks for the help people, going to see if I can get this working today and I agree the 2nd option seams to be what I may need so ill test it and let you know.

Thanks


Utilizar vírgula no input com Bootstrap Touchspin

Question: Estou utilizando o Bootstrap Toutchspin para montar um input,

   <input type="text" id="P8473_QTDE" name="p_t05" value="0" size="25" onkeypress="return submitEnter(this,event)" class="mt10 form-control">

Até aqui maravilha,
porém preciso que o input utilize vírgula ao invés do ponto.
Comment: No lugar do ponto?
Comment: isso mesmo, desculpe.
Answer: Se quiser trocar o ponto pela vírgula, você pode fazer um replace no value do input. Basta usar os eventos change touchspin.on.min touchspin.on.stopspin e substituir um pelo outro:

$("input[name='p_t05']").TouchSpin({
  min: 0,
  max: 1000,
  boostat: 5,
  decimals: 3,
  forcestepdivisibility: "none",
  step: 1,
  maxboostedstep: 10,
  buttondown_class: "btn btn-ciano btn-lg btn-mob",
  buttonup_class: "btn btn-ciano btn-lg btn-mob",
  mousewheel: "true",
  initval: 0
}).on("change touchspin.on.min touchspin.on.stopspin", function(){
   var t = this;
   t.value = t.value.replace(/\./g, ",");
}).trigger("change");

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

   <input type="text" id="P8473_QTDE" name="p_t05" value="0" size="25" onkeypress="return submitEnter(this,event)" class="mt10 form-control">

Comment: Muito grato!! funcionou.
Comment: Quando altera o valor após a vírgula, o campo perde a referência.
Comment: Como assim?....
Comment: ao informar 1,250 por exemplo, e sair do input o campo perde a referência da fração e está sendo arredondado para 1.
Comment: Entendi. É só vc voltar o ponto quando for tratar o número no calculo. Só mudar os sinais no replace
Comment: Na hora de tratar o valor como número, vc vai fazer assim: `parseFloat($("input[name='p_t05']").val().replace(",", "."))`