问:
While automating script using selenium webdriver ,`.isDisplayed()` command is not working in `if else` statement
While automating script using selenium webdriver ,.isDisplayed() command is not working in if else statement.
If the condition is true under if statement, then it is working fine. But if the condition is not true, the code is not moving to else statement.

```<code>package module17;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class Dice {
static WebDriver driver = null;
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "D:\\Automation Software\\chromedriver_win32\\chromedriver_update.exe");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        //driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
        driver.get("http://www.dice.com/");
        Thread.sleep(15000);
        driver.findElement(By.xpath("//*[@alt='Close']")).click();
        driver.findElement(By.xpath("//*[@id='search-field-keyword']")).sendKeys("Selenium WebDriver");
        WebElement Place =driver.findElement(By.xpath("//input[@placeholder='Location']"));
        Place.clear();
        driver.findElement(By.xpath("//button[contains(text(),'Find Tech Jobs')]")).click();
        WebElement PageNumber = driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'2')]"));
        int i=2;
        while(i<=44)
        {
            try
                {
                    if(driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'"+i+"')]")).isDisplayed()  )
                        {
                            driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'"+i+"')]")).click();
                            Thread.sleep(5000);
                            i= i+5;
                        }
                    else if(driver.findElement(By.xpath("//*[@id='dice_paging_top']//a[@title='Go to next page']")).isDisplayed() )
                        {
                            driver.findElement(By.xpath("//*[@id='dice_paging_top']//a[@title='Go to next page']")).click();
                        }
                    else
                        {
                            driver.quit();
                        }
                }
            catch (Exception e)
                {
                    System.out.println("Exception");
                }

        }
    }
}
</code>```

答:
In the second iteration I value set to 7, with this value of I in xpath, element is not exist on the current page.If the element is not exist on the page then drive.findElement will throw NoSuchElementException so it won't be entered into your elseif block at all I modified your code accordingly(Update your solution below and provided my solution at last).

```<code>import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Dice {
static WebDriver driver = null;
public static void main(String[] args) throws InterruptedException {
    System.setProperty("webdriver.chrome.driver", "D:\\Automation Software\\chromedriver_win32\\chromedriver_update.exe");
    driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    //driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
    driver.get("http://www.dice.com/");
    Thread.sleep(15000);
    driver.findElement(By.xpath("//*[@alt='Close']")).click();
    driver.findElement(By.xpath("//*[@id='search-field-keyword']")).sendKeys("Selenium WebDriver");
    WebElement Place =driver.findElement(By.xpath("//input[@placeholder='Location']"));
    Place.clear();
    driver.findElement(By.xpath("//button[contains(text(),'Find Tech Jobs')]")).click();
    WebElement PageNumber = driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'2')]"));
    int i=2;
    while(i<=44)
    {
        try
        {
            if(driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'"+i+"')]")).isDisplayed()  )
            {
                driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'"+i+"')]")).click();
                Thread.sleep(5000);
                i+=1;
            }
        }
        catch (Exception e)
        {
            try{
                if(driver.findElement(By.xpath("//*[@id='dice_paging_top']//a[@title='Go to next page']")).isDisplayed() )
                {
                    driver.findElement(By.xpath("//*[@id='dice_paging_top']//a[@title='Go to next page']")).click();
                    i+=1;
                }
            }
            catch(Exception e1){
                driver.quit();
            }
          }

       }
      }
    }
</code>```

If you goal is to went through all job posts then below is my shorten code.

```<code>import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Dice {
  static WebDriver driver = null;
public static void main(String[] args) throws InterruptedException {
    System.setProperty("webdriver.chrome.driver", "D:\\Automation Software\\chromedriver_win32\\chromedriver_update.exe");
    driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    driver.get("http://www.dice.com/");
    Thread.sleep(15000);
    driver.findElement(By.xpath("//*[@alt='Close']")).click();
    driver.findElement(By.xpath("//*[@id='search-field-keyword']")).sendKeys("Selenium WebDriver");
    WebElement Place =driver.findElement(By.xpath("//input[@placeholder='Location']"));
    Place.clear();
    driver.findElement(By.xpath("//button[contains(text(),'Find Tech Jobs')]")).click();
    while(true)
    {
        List<WebElement> nextPage = driver.findElements(By.xpath("//*[@id='dice_paging_top']//a[@title='Go to next page']"));
        if(nextPage.size()>0&&nextPage.get(0).isEnabled()){
            nextPage.get(0).click();
        }
        else{
            break;
        }
    }
    driver.quit();
   }
  }
</code>```

Try it and let me know if you have any queries

ContentLicense: CC BY-SA 4.0

Body:
While automating script using selenium webdriver ,.isDisplayed() command is not working in if else statement.
If the condition is true under if statement, then it is working fine. But if the condition is not true, the code is not moving to else statement.

package module17;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class Dice {
static WebDriver driver = null;
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "D:\\Automation Software\\chromedriver_win32\\chromedriver_update.exe");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        //driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
        driver.get("http://www.dice.com/");
        Thread.sleep(15000);
        driver.findElement(By.xpath("//*[@alt='Close']")).click();
        driver.findElement(By.xpath("//*[@id='search-field-keyword']")).sendKeys("Selenium WebDriver");
        WebElement Place =driver.findElement(By.xpath("//input[@placeholder='Location']"));
        Place.clear();
        driver.findElement(By.xpath("//button[contains(text(),'Find Tech Jobs')]")).click();
        WebElement PageNumber = driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'2')]"));
        int i=2;
        while(i<=44)
        {
            try
                {
                    if(driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'"+i+"')]")).isDisplayed()  )
                        {
                            driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'"+i+"')]")).click();
                            Thread.sleep(5000);
                            i= i+5;
                        }
                    else if(driver.findElement(By.xpath("//*[@id='dice_paging_top']//a[@title='Go to next page']")).isDisplayed() )
                        {
                            driver.findElement(By.xpath("//*[@id='dice_paging_top']//a[@title='Go to next page']")).click();
                        }
                    else
                        {
                            driver.quit();
                        }
                }
            catch (Exception e)
                {
                    System.out.println("Exception");
                }

        }
    }
}

Body:
In the second iteration I value set to 7, with this value of I in xpath, element is not exist on the current page.If the element is not exist on the page then drive.findElement will throw NoSuchElementException so it won't be entered into your elseif block at all I modified your code accordingly(Update your solution below and provided my solution at last).

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Dice {
static WebDriver driver = null;
public static void main(String[] args) throws InterruptedException {
    System.setProperty("webdriver.chrome.driver", "D:\\Automation Software\\chromedriver_win32\\chromedriver_update.exe");
    driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    //driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
    driver.get("http://www.dice.com/");
    Thread.sleep(15000);
    driver.findElement(By.xpath("//*[@alt='Close']")).click();
    driver.findElement(By.xpath("//*[@id='search-field-keyword']")).sendKeys("Selenium WebDriver");
    WebElement Place =driver.findElement(By.xpath("//input[@placeholder='Location']"));
    Place.clear();
    driver.findElement(By.xpath("//button[contains(text(),'Find Tech Jobs')]")).click();
    WebElement PageNumber = driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'2')]"));
    int i=2;
    while(i<=44)
    {
        try
        {
            if(driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'"+i+"')]")).isDisplayed()  )
            {
                driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'"+i+"')]")).click();
                Thread.sleep(5000);
                i+=1;
            }
        }
        catch (Exception e)
        {
            try{
                if(driver.findElement(By.xpath("//*[@id='dice_paging_top']//a[@title='Go to next page']")).isDisplayed() )
                {
                    driver.findElement(By.xpath("//*[@id='dice_paging_top']//a[@title='Go to next page']")).click();
                    i+=1;
                }
            }
            catch(Exception e1){
                driver.quit();
            }
          }

       }
      }
    }

If you goal is to went through all job posts then below is my shorten code.

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Dice {
  static WebDriver driver = null;
public static void main(String[] args) throws InterruptedException {
    System.setProperty("webdriver.chrome.driver", "D:\\Automation Software\\chromedriver_win32\\chromedriver_update.exe");
    driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    driver.get("http://www.dice.com/");
    Thread.sleep(15000);
    driver.findElement(By.xpath("//*[@alt='Close']")).click();
    driver.findElement(By.xpath("//*[@id='search-field-keyword']")).sendKeys("Selenium WebDriver");
    WebElement Place =driver.findElement(By.xpath("//input[@placeholder='Location']"));
    Place.clear();
    driver.findElement(By.xpath("//button[contains(text(),'Find Tech Jobs')]")).click();
    while(true)
    {
        List<WebElement> nextPage = driver.findElements(By.xpath("//*[@id='dice_paging_top']//a[@title='Go to next page']"));
        if(nextPage.size()>0&&nextPage.get(0).isEnabled()){
            nextPage.get(0).click();
        }
        else{
            break;
        }
    }
    driver.quit();
   }
  }

Try it and let me know if you have any queries


来源: stackexchange

问:
User-Agent for osmdroid
I tried to put the user agent (cf https://github.com/osmdroid/osmdroid/wiki/Important-notes-on-using-osmdroid-in-your-app), but when I put the line OpenStreetMapTileProviderConstants.setUserAgentValue(BuildConfig.APPLICATION_ID); Android studio is telling me that setUserAgentValue is depreciated.

What can I do to solve that ? For now when I run the app I have a grid with no map.

Thanks you very much in advance !

答:
It's deprecated because it's been moved to another location which consolidates all configuration settings for osmdroid. Try the following

Configuration.getInstance().setUserAgentValue(...)

The older method was rewritten to wire it into the new configuration construct.

ContentLicense: CC BY-SA 3.0

Title: User-Agent for osmdroid


问:
Eclipse projects are not visible in workspace folder
The weird part is I can see my projects through package explorer.

I can also export them.

But when I want to access them elsewhere e.g windows explorer, they are not there.

All I see is .metadata folder.

An unexpected shutdown of the system occurred not too long ago.

Edit: When I switched the workspace, created and opened a project, they're still not visible/accessible outside of the eclipse project explorer.

Any ideas?

答:
Obviously, there is a problem with Windows explorer and OneDrive in particular.

When I navigate to C:/Users/username/OneDrive/Documents/workspace or through command line I do see my eclipse projects.

But when I try to use 'Open file..' option from any application or navigate through Windows explorer, projects are not recognized nor displayed.


问:
Value being added to an array twice and I can't figure out why
I'm quite new to JavaScript and I can't seem to figure out why this is happening. Using checkboxes I'm trying to add the value of the checkbox to the array when clicked. It seems to be adding fine but twice.

Here's the HTML:

```<code><form id= "checkboxes">
<label> Types of Places</label>
 <link rel="stylesheet" type="text/css"  href="css/style.css">
    <input type="checkbox" name="cbox" value="woodland" class="places"/>
    <label for="woodland"><img src="../img/Woodland.jpg" /></label>
    <input type="checkbox" name="cbox" value="lodging" class="places"/>
    <label for="viewpoint"><img src="../img/Viewpoint.jpg" /></label>
    <input type="checkbox" name="cbox" value="restaurant" class="places"/>
    <label for="restaurant"><img src="../img/Restaurant.jpg" /></label>
    <input type="checkbox" name="cbox" value="museum" class="places" />
    <label for="historical"><img src="../img/Historical.jpg" /></label>
  </form>
</code>```

and here's the relevant JS/JQuery:

```<code>var placeT = [];

function initialize() {
    // Default the map view to UK
    var mapOptions = {
        center: new google.maps.LatLng(55.3781, -3.4360),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        zoom: 5
    };

    new AutocompleteDirectionsHandler(map);

    $(".places").change(function() {
        $(".places").each(function() {
            if ($(this).is(':checked')) {
                placeT.push($(this).val());
            }
        });
        alert(placeT);
    });

}

function findPlaces(boxes, searchIndex) {

    var request = {
        bounds: boxes[searchIndex],
        types: [placeT]
    };

    // alert(request.bounds);
    service.radarSearch(request, function(results, status) {
        if (status != google.maps.places.PlacesServiceStatus.OK) {
            alert("Request[" + searchIndex + "] failed: " + status);

        }
        // alert(results.length);
        document.getElementById('side_bar').innerHTML += "bounds[" + searchIndex + "] returns " + results.length + " results<br>"
        for (var i = 0, result; result = results[i]; i++) {
            var marker = createMarker(result);
        }
        searchIndex++;
        if (searchIndex < boxes.length)
            findPlaces(boxes, searchIndex);
    });
}
</code>```

I know it's probably something simple but I just can't seem to figure it out. Thanks for any help!

答:
Change your code as below :</p>

```<code> $(".places").change(function()
    {
        placeT = [];
        $(".places").each(function()
        {
            if( $(this).is(':checked') )
            {
                placeT.push($(this).val());
            }
        });
        alert( placeT );
    });
</code>```

Body:
I'm quite new to JavaScript and I can't seem to figure out why this is happening. Using checkboxes I'm trying to add the value of the checkbox to the array when clicked. It seems to be adding fine but twice.

Here's the HTML:

<form id= "checkboxes">
 Types of Places
 <link rel="stylesheet" type="text/css"  href="css/style.css">
    <input type="checkbox" name="cbox" value="woodland" class="places"/>

    <input type="checkbox" name="cbox" value="lodging" class="places"/>

    <input type="checkbox" name="cbox" value="restaurant" class="places"/>

    <input type="checkbox" name="cbox" value="museum" class="places" />

  </form>

and here's the relevant JS/JQuery:

var placeT = [];

function initialize() {
    // Default the map view to UK
    var mapOptions = {
        center: new google.maps.LatLng(55.3781, -3.4360),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        zoom: 5
    };

    new AutocompleteDirectionsHandler(map);

    $(".places").change(function() {
        $(".places").each(function() {
            if ($(this).is(':checked')) {
                placeT.push($(this).val());
            }
        });
        alert(placeT);
    });

}

function findPlaces(boxes, searchIndex) {

    var request = {
        bounds: boxes[searchIndex],
        types: [placeT]
    };

    // alert(request.bounds);
    service.radarSearch(request, function(results, status) {
        if (status != google.maps.places.PlacesServiceStatus.OK) {
            alert("Request[" + searchIndex + "] failed: " + status);

        }
        // alert(results.length);
        document.getElementById('side_bar').innerHTML += "bounds[" + searchIndex + "] returns " + results.length + " results
"
        for (var i = 0, result; result = results[i]; i++) {
            var marker = createMarker(result);
        }
        searchIndex++;
        if (searchIndex < boxes.length)
            findPlaces(boxes, searchIndex);
    });
}

I know it's probably something simple but I just can't seem to figure it out. Thanks for any help!

Body:
Change your code as below :

 $(".places").change(function()
    {
        placeT = [];
        $(".places").each(function()
        {
            if( $(this).is(':checked') )
            {
                placeT.push($(this).val());
            }
        });
        alert( placeT );
    });


问:
QueryDsl with mongodb: Need help in String comparison with mapPath
I have a mongo query that is producing results as expected, here is my Query

```<code>db.getCollection('student').find({books: {$elemMatch: {"dynamicData.subject":/bbb/}}})
</code>```

I have prepared a query using query dsl which is

```<code>orFn.accept(student.books.any().dynamicData.get(subject).eq(value))
</code>```

Which is working fine for the exact match of value, I need the query to behave as sql like syntax to filter based on contains ignore case. Need help from some querydsl gurus

答:
Here is the solution, found it from here</p>

```<code>Path<?> path = student.books.any().dynamicData.get(subject);
Expression<String> constant = Expressions.constant(value);
orFn.accept(Expressions.predicate(Ops.STRING_CONTAINS_IC, path, constant));
</code>```

Body:
I have a mongo query that is producing results as expected, here is my Query

db.getCollection('student').find({books: {$elemMatch: {"dynamicData.subject":/bbb/}}})

I have prepared a query using query dsl which is

orFn.accept(student.books.any().dynamicData.get(subject).eq(value))

Which is working fine for the exact match of value, I need the query to behave as sql like syntax to filter based on contains ignore case. Need help from some querydsl gurus

Body:
Here is the solution, found it from here

Path<?> path = student.books.any().dynamicData.get(subject);
Expression<String> constant = Expressions.constant(value);
orFn.accept(Expressions.predicate(Ops.STRING_CONTAINS_IC, path, constant));


问:
Constantly Run a Service and check a value of a Variable
I had created some code that would tell me if the users window scrolled beyond a certain point. I quickly realised that this needed to be a service as other components needed this info as well.

I had used @HostListener in the logic and would get results. Now that this is all in a service, I only know if the window was scrolled beyond a certain point when I call the service.

The issue is, how do I constantly call the service? The service has a Boolean in it that I need real-time info on.

Service

```<code>import { Injectable, OnInit, HostListener, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';

@Injectable()
export class WindowScrollService {
  public navIsFixed: boolean = false;
  constructor(@Inject(DOCUMENT) private document: Document) {

   }
   @HostListener("window:scroll", [])
  onWindowScroll() {
    let number = this.document.body.scrollTop;
    if (number > 20) {
      this.navIsFixed = true;
      console.log(this.navIsFixed);
    } else if (this.navIsFixed && number < 10) {
      this.navIsFixed = false;
      console.log(this.navIsFixed);
    }
  }
}
</code>```

Component

```<code>import { Component, OnInit } from '@angular/core';
import { WindowScrollService } from '../window-scroll.service';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
  public navIsFixed: boolean;

  constructor( private windowscrollservice  : WindowScrollService) {
  this.navIsFixed = this.windowscrollservice.navIsFixed;

  }
  ngOnInit(){
    this.windowscrollservice.onWindowScroll()
  }
}
</code>```

答:
Use setInterval to repeatedly run some code. One possible implementation

```<code>import { Component, OnInit } from '@angular/core';
import { WindowScrollService } from '../window-scroll.service';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
  public navIsFixed: boolean;
  public interval;

  constructor( private windowscrollservice  : WindowScrollService) {
  this.navIsFixed = this.windowscrollservice.navIsFixed;

  }
  ngOnInit(){
    // run every 500ms
    this.interval = setInterval(() => this.windowscrollservice.onWindowScroll(), 500);
    // use clearInterval(this.interval) to stop
  }
}
</code>```

Body:
I had created some code that would tell me if the users window scrolled beyond a certain point. I quickly realised that this needed to be a service as other components needed this info as well.

I had used @HostListener in the logic and would get results. Now that this is all in a service, I only know if the window was scrolled beyond a certain point when I call the service.

The issue is, how do I constantly call the service? The service has a Boolean in it that I need real-time info on.

Service

import { Injectable, OnInit, HostListener, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';

@Injectable()
export class WindowScrollService {
  public navIsFixed: boolean = false;
  constructor(@Inject(DOCUMENT) private document: Document) {

   }
   @HostListener("window:scroll", [])
  onWindowScroll() {
    let number = this.document.body.scrollTop;
    if (number > 20) {
      this.navIsFixed = true;
      console.log(this.navIsFixed);
    } else if (this.navIsFixed && number < 10) {
      this.navIsFixed = false;
      console.log(this.navIsFixed);
    }
  }
}

Component

import { Component, OnInit } from '@angular/core';
import { WindowScrollService } from '../window-scroll.service';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
  public navIsFixed: boolean;

  constructor( private windowscrollservice  : WindowScrollService) {
  this.navIsFixed = this.windowscrollservice.navIsFixed;

  }
  ngOnInit(){
    this.windowscrollservice.onWindowScroll()
  }
}

Body:
Use setInterval to repeatedly run some code. One possible implementation

import { Component, OnInit } from '@angular/core';
import { WindowScrollService } from '../window-scroll.service';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
  public navIsFixed: boolean;
  public interval;

  constructor( private windowscrollservice  : WindowScrollService) {
  this.navIsFixed = this.windowscrollservice.navIsFixed;

  }
  ngOnInit(){
    // run every 500ms
    this.interval = setInterval(() => this.windowscrollservice.onWindowScroll(), 500);
    // use clearInterval(this.interval) to stop
  }
}


问:
mysql - group by column but show all the rows
I need help with this query, this is my output:

```<code>idProduccion | hp   | totalHp |
      4      | 40   | 40      |
      4      | 35   | 35      |
      5      | 90   | 90      |
      6      | 2500 | 2500    |
</code>```

how do I do to sum hp columns with the same idProduccion and show all the rows, for exampe:

```<code>idProduccion | hp   | totalHp |
      4      | 40   | 75      |
      4      | 35   | 75      |
      5      | 90   | 90      |
      6      | 2500 | 2500    |
....
</code>```

here is my sql query

```<code>SELECT
    lp.idProduccion,lp.hp, totalHp
FROM
    lotesproduccion lp
        JOIN
    (SELECT
        lp.hp, lp.idlotesproduccion, sum(lp.hp) AS totalHp
    FROM
        lotesproduccion lp
    GROUP BY lp.idlotesproduccion) AS lp1 ON lp.idlotesproduccion = lp1.idlotesproduccion
</code>```

答:
Thanks @Ramesh Yelda, it works really fine.. Actually the full query is this..

```<code>SELECT
    il.IdLoteNuevo AS id_lotes,
    icu.idCultivosNuevo AS id_cultivos,
    YEAR(p.fechaInicio) * 10000 + MONTH(p.fechaInicio) * 100 + DAY(p.fechaInicio) AS id_fechaInicio,
    YEAR(p.fechaCierre) * 10000 + MONTH(p.fechaCierre) * 100 + DAY(p.fechaCierre) AS id_fechaFin,
    CAST(p.estado AS SIGNED INTEGER) AS estado_produccion,
    rendimiento_hectarea,
    rendimiento_bruto,
    superficie_producida,
    lluvia_produccion,
    gastos_produccion
FROM
    (SELECT
        idlotes,
            idproduccion,
            idlotesproduccion,
            TRUNCATE(SUM(rb), 2) AS rendimiento_hectarea,
            TRUNCATE(SUM(rb * hp), 2) AS rendimiento_bruto,
            TRUNCATE(SUM(hp), 2) AS superficie_producida
    FROM
        lotesproduccion
    GROUP BY idlotesproduccion) AS lp
        JOIN
    ids_lotes il ON il.idLotesProduccion = lp.idlotesproduccion
        JOIN
    (SELECT
        c.idLote,
            SUM(c.lluvia) lluvia_produccion,
            lp.idlotesproduccion
    FROM
        clima c
    JOIN lotesproduccion lp ON c.idlote = lp.idlotes
    JOIN produccion p ON p.idproduccion = lp.idProduccion
    WHERE
        c.fecha >= p.fechaInicio
            AND c.fecha <= p.fechaCierre
    GROUP BY lp.idlotesproduccion) c ON c.idlotesproduccion = lp.idlotesproduccion
        JOIN
    produccion p ON p.idproduccion = lp.idProduccion
        JOIN
    ids_cultivos icu ON icu.idCultivos = p.idCultivo
        JOIN
    (SELECT
        lp.idlotesproduccion,
            hectareas,
            totalHp,
            CASE
                WHEN gp.costo IS NULL THEN 0
                ELSE TRUNCATE((SUM(gp.costo) * (hectareas)) / (totalHp), 2)
            END AS gastos_produccion
    FROM
        gastosproduccion gp
    JOIN (SELECT
        lp.idProduccion,
            lp.hp AS hectareas,
            lp1.totalHp AS totalHp,
            lp.idlotesproduccion
    FROM
        lotesproduccion lp
    LEFT JOIN (SELECT
        lp.idProduccion, SUM(lp.hp) AS totalHp
    FROM
        lotesproduccion lp
    GROUP BY lp.idProduccion) AS lp1 ON lp.idProduccion = lp1.idProduccion) AS lp ON lp.idProduccion = gp.idProduccion
    GROUP BY lp.idlotesproduccion) gp ON gp.idlotesproduccion = lp.idlotesproduccion
GROUP BY p.fechaInicio , p.fechaCierre , il.IdLoteNuevo , icu.idCultivosNuevo;
</code>```

It's work great now, the only doubt is that when gp.costo is null, it should show 0 (because de case when) but instead is does not show the entirely row.

pd: I don´t know how to add code in a comment

Body:
I need help with this query, this is my output:

idProduccion | hp   | totalHp |
      4      | 40   | 40      |
      4      | 35   | 35      |
      5      | 90   | 90      |
      6      | 2500 | 2500    |

how do I do to sum hp columns with the same idProduccion and show all the rows, for exampe:

idProduccion | hp   | totalHp |
      4      | 40   | 75      |
      4      | 35   | 75      |
      5      | 90   | 90      |
      6      | 2500 | 2500    |
....

here is my sql query

SELECT
    lp.idProduccion,lp.hp, totalHp
FROM
    lotesproduccion lp
        JOIN
    (SELECT
        lp.hp, lp.idlotesproduccion, sum(lp.hp) AS totalHp
    FROM
        lotesproduccion lp
    GROUP BY lp.idlotesproduccion) AS lp1 ON lp.idlotesproduccion = lp1.idlotesproduccion

Body:
Thanks @Ramesh Yelda, it works really fine.. Actually the full query is this..

SELECT
    il.IdLoteNuevo AS id_lotes,
    icu.idCultivosNuevo AS id_cultivos,
    YEAR(p.fechaInicio) * 10000 + MONTH(p.fechaInicio) * 100 + DAY(p.fechaInicio) AS id_fechaInicio,
    YEAR(p.fechaCierre) * 10000 + MONTH(p.fechaCierre) * 100 + DAY(p.fechaCierre) AS id_fechaFin,
    CAST(p.estado AS SIGNED INTEGER) AS estado_produccion,
    rendimiento_hectarea,
    rendimiento_bruto,
    superficie_producida,
    lluvia_produccion,
    gastos_produccion
FROM
    (SELECT
        idlotes,
            idproduccion,
            idlotesproduccion,
            TRUNCATE(SUM(rb), 2) AS rendimiento_hectarea,
            TRUNCATE(SUM(rb * hp), 2) AS rendimiento_bruto,
            TRUNCATE(SUM(hp), 2) AS superficie_producida
    FROM
        lotesproduccion
    GROUP BY idlotesproduccion) AS lp
        JOIN
    ids_lotes il ON il.idLotesProduccion = lp.idlotesproduccion
        JOIN
    (SELECT
        c.idLote,
            SUM(c.lluvia) lluvia_produccion,
            lp.idlotesproduccion
    FROM
        clima c
    JOIN lotesproduccion lp ON c.idlote = lp.idlotes
    JOIN produccion p ON p.idproduccion = lp.idProduccion
    WHERE
        c.fecha >= p.fechaInicio
            AND c.fecha <= p.fechaCierre
    GROUP BY lp.idlotesproduccion) c ON c.idlotesproduccion = lp.idlotesproduccion
        JOIN
    produccion p ON p.idproduccion = lp.idProduccion
        JOIN
    ids_cultivos icu ON icu.idCultivos = p.idCultivo
        JOIN
    (SELECT
        lp.idlotesproduccion,
            hectareas,
            totalHp,
            CASE
                WHEN gp.costo IS NULL THEN 0
                ELSE TRUNCATE((SUM(gp.costo) * (hectareas)) / (totalHp), 2)
            END AS gastos_produccion
    FROM
        gastosproduccion gp
    JOIN (SELECT
        lp.idProduccion,
            lp.hp AS hectareas,
            lp1.totalHp AS totalHp,
            lp.idlotesproduccion
    FROM
        lotesproduccion lp
    LEFT JOIN (SELECT
        lp.idProduccion, SUM(lp.hp) AS totalHp
    FROM
        lotesproduccion lp
    GROUP BY lp.idProduccion) AS lp1 ON lp.idProduccion = lp1.idProduccion) AS lp ON lp.idProduccion = gp.idProduccion
    GROUP BY lp.idlotesproduccion) gp ON gp.idlotesproduccion = lp.idlotesproduccion
GROUP BY p.fechaInicio , p.fechaCierre , il.IdLoteNuevo , icu.idCultivosNuevo;

It's work great now, the only doubt is that when gp.costo is null, it should show 0 (because de case when) but instead is does not show the entirely row.

pd: I don´t know how to add code in a comment


问:
Query tables in Hive using Presto jdbc driver - Failed with "Server refused connection" error
I am using Presto to query Hive tables in EMR. I initialized presto driver and get the connection, but when I am trying to execute a query on that connection, I am getting an error: Server refused connection: http://aws.address/v1/statement.

Do I need to set Hive/AWS credentials before using it? How can I do it?

```<code>public void init() {
    try {
        Class.forName("com.facebook.presto.jdbc.PrestoDriver");
        if(connection == null)
            connection = DriverManager.getConnection(url,username,password);
            // url = "jdbc:presto://aws.address:8889/hive/default"
        } catch (ClassNotFoundException | SQLException e) {
            // TOD: handle exception
            e.printStackTrace();
        }
    }

public void executeMyQuery() {
    if(connection == null) {
        connection = driver.getConnection();
    }

    ResultSet resultSet = null;
    Statement stmt = connection.createStatement();

    try {
        resultSet = stmt.executeQuery(query);

    } catch (Exception e) {
        logger.error("Failed to execute query, with error: ",e);
    } finally {
        if(resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stmt != null){
            stmt.close();
        }
    }
}
</code>```

答: I needed to use 'port forwarding' command (ssh) in order to reach presto driver in AWS.</p>

Body:
I am using Presto to query Hive tables in EMR. I initialized presto driver and get the connection, but when I am trying to execute a query on that connection, I am getting an error: Server refused connection: http://aws.address/v1/statement.

Do I need to set Hive/AWS credentials before using it? How can I do it?

public void init() {
    try {
        Class.forName("com.facebook.presto.jdbc.PrestoDriver");
        if(connection == null)
            connection = DriverManager.getConnection(url,username,password);
            // url = "jdbc:presto://aws.address:8889/hive/default"
        } catch (ClassNotFoundException | SQLException e) {
            // TOD: handle exception
            e.printStackTrace();
        }
    }

public void executeMyQuery() {
    if(connection == null) {
        connection = driver.getConnection();
    }

    ResultSet resultSet = null;
    Statement stmt = connection.createStatement();

    try {
        resultSet = stmt.executeQuery(query);

    } catch (Exception e) {
        logger.error("Failed to execute query, with error: ",e);
    } finally {
        if(resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stmt != null){
            stmt.close();
        }
    }
}


问:
Labeling along the axes, matplotlib
How do I place the labeling of the axes inside of the graph?

Right now i have this:

I want the numbering inside of the graph, along the axes.

Thanks,
Cro.

答:
Looking at the matplotlib spine placement demo you'd find that you can shift the spines using ax.spines['left'].set_position('zero').

```<code>import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

x = np.linspace(-3,3)
y = x**2

fig, ax = plt.subplots()
ax.set_ylim(-4,10)
ax.set_xlim(-10,10)
ax.plot(x, y)
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')

plt.show()
</code>```

Title: Labeling along the axes, matplotlib

Body:
Looking at the matplotlib spine placement demo you'd find that you can shift the spines using ax.spines['left'].set_position('zero').

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

x = np.linspace(-3,3)
y = x**2

fig, ax = plt.subplots()
ax.set_ylim(-4,10)
ax.set_xlim(-10,10)
ax.plot(x, y)
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')

plt.show()


问:
With hive's complex struct data type, how to write query with where clause
I've have following hive table with complex data type, STRUCT. Can you please help writing hive query with where clause for specific city?

```<code>CREATE EXTERNAL TABLE user_t (
 name      STRING,
 id        BIGINT,
 isFTE     BOOLEAN,
 role      VARCHAR(64),
 salary    DECIMAL(8,2),
 phones    ARRAY<INT>,
 deductions MAP<STRING, FLOAT>,
 address   ARRAY<STRUCT<street:STRING, city:STRING, state:STRING, zip:INT>>,
 others    UNIONTYPE<FLOAT,BOOLEAN,STRING>,
 misc      BINARY
 )
</code>```

I'm able to use STRUCT data type in select clause but not able to use same in where clause.

Working:

```<code>select address.city from user_t;
</code>```

Not working:

```<code>select address.city from user_t where address.city = 'XYZ'
</code>```

Documentation says it has limitation while using group by or where clause and gave a solution as well. But I didn't understand it clearly.

Link: Documentation

Please suggest. Thank you.

Body:
I've have following hive table with complex data type, STRUCT. Can you please help writing hive query with where clause for specific city?

CREATE EXTERNAL TABLE user_t (
 name      STRING,
 id        BIGINT,
 isFTE     BOOLEAN,
 role      VARCHAR(64),
 salary    DECIMAL(8,2),
 phones    ARRAY<INT>,
 deductions MAP<STRING, FLOAT>,
 address   ARRAY<STRUCT<street:STRING, city:STRING, state:STRING, zip:INT>>,
 others    UNIONTYPE<FLOAT,BOOLEAN,STRING>,
 misc      BINARY
 )

I'm able to use STRUCT data type in select clause but not able to use same in where clause.

Working:

select address.city from user_t;

Not working:

select address.city from user_t where address.city = 'XYZ'

Documentation says it has limitation while using group by or where clause and gave a solution as well. But I didn't understand it clearly.

Link: Documentation

Please suggest. Thank you.

Body:
Demo

create table user_t
(
    id        bigint
   ,address   array<struct<street:string, city:string, state:string, zip:int>>
)
;

insert into user_t

    select  1
           ,array
            (
                named_struct('street','street_1','city','city_1','state','state_1','zip',11111)
               ,named_struct('street','street_2','city','city_1','state','state_1','zip',11111)
               ,named_struct('street','street_3','city','city_3','state','state_3','zip',33333)
            )

    union all

    select  2
           ,array
            (
                named_struct('street','street_4','city','city_4','state','state_4','zip',44444)
               ,named_struct('street','street_5','city','city_5','state','state_5','zip',55555)
            )
;

Option 1: explode

select  u.id
       ,a.*

from    user_t as u
        lateral view explode(address) a as details

where   details.city = 'city_1'
;

+----+---------------------------------------------------------------------+
| id |                               details                               |
+----+---------------------------------------------------------------------+
|  1 | {"street":"street_1","city":"city_1","state":"state_1","zip":11111} |
|  1 | {"street":"street_2","city":"city_1","state":"state_1","zip":11111} |
+----+---------------------------------------------------------------------+

Option 2: inline

select  u.id
       ,a.*

from    user_t as u
        lateral view inline(address) a

where   a.city = 'city_1'
;

+----+----------+--------+---------+-------+
| id |  street  |  city  |  state  |  zip  |
+----+----------+--------+---------+-------+
|  1 | street_1 | city_1 | state_1 | 11111 |
|  1 | street_2 | city_1 | state_1 | 11111 |
+----+----------+--------+---------+-------+

Option 3: self join

select  u.*

from            user_t as u

        join   (select  distinct
                        u.id

                from    user_t as u
                        lateral view inline(address) a

                where   a.city = 'city_1'
                ) as u2

        on      u2.id = u.id
;

+----+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| id |                                                                                address                                                                                |
+----+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|  1 | [{"street":"street_1","city":"city_1","state":"state_1","zip":11111},{"street":"street_2","city":"city_1","state":"state_1","zip":11111},{"street":"street_3","city":"city_3","state":"state_3","zip":33333}] |
+----+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+


问:
canvas sprite sheet error
I found a lovely code snippet on canvas spritesheet animations. this is ts:

http://jsfiddle.net/m1erickson/h85Gq/

I tried to beautify this code, by writing an animate function that accepts Image objects, so that I can animate multiple images in my canvas simultaneously. This is my attempt at it:

```<code>    $(function(){
        var canvas=document.getElementById("canvas");
        var ctx=canvas.getContext("2d");
        var spritePosition=0;
        var spriteWidth=100;
        var spriteHeight=100;
        var spriteCount=40;
        var spritePlayCount=0;
        var maxSpritePlays=2;

        var objectS=new Image();
        objectS.src="sprites/first.png";

        var fps = 50;
        function animate(sprite) {
            setTimeout(function() {

                if(spritePlayCount<maxSpritePlays){
                    requestAnimationFrame(animate);
                }

                // Drawing code goes here
                ctx.clearRect(0,0,canvas.width,canvas.height);
                ctx.drawImage(sprite,spritePosition*spriteWidth, 0,spriteWidth, spriteHeight, 0,0,spriteWidth, spriteHeight);

                spritePosition++;
                if(spritePosition>spriteCount-1){
                    spritePosition=0;
                    spritePlayCount++;
                }
            }, 1000 / fps);
        }

        objectS.onload=function(){
            animate(objectS);
        }
    }); // end $(function(){});
</code>```

I am getting a much observed error, but I cant seem to find the fix for it:

index3.html:59 Uncaught TypeError: Failed to execute 'drawImage' on
  'CanvasRenderingContext2D': The provided value is not of type
  '(CSSImageValue or HTMLImageElement or HTMLVideoElement or
  HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'

Can you help me out finding my bug?

答:
You'll also need to pass the sprite parameter when calling the animate function using requestAnimationFrame.

```<code>$(function() {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    var spritePosition = 0;
    var spriteWidth = 100;
    var spriteHeight = 100;
    var spriteCount = 40;
    var spritePlayCount = 0;
    var maxSpritePlays = 2;
    var objectS = new Image();
    objectS.src = "sprites/first.png";
    var fps = 50;

    function animate(sprite) {
        setTimeout(function() {
            if (spritePlayCount < maxSpritePlays) {
                requestAnimationFrame(function() {
                    animate(sprite);
                });
            }
            // Drawing code goes here
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(sprite, spritePosition * spriteWidth, 0, spriteWidth, spriteHeight, 0, 0, spriteWidth, spriteHeight);
            spritePosition++;
            if (spritePosition > spriteCount - 1) {
                spritePosition = 0;
                spritePlayCount++;
            }
        }, 1000 / fps);
    }
    objectS.onload = function() {
        animate(objectS);
    };
});
</code>```

Title: canvas sprite sheet error

Body:
I found a lovely code snippet on canvas spritesheet animations. this is ts:

http://jsfiddle.net/m1erickson/h85Gq/

I tried to beautify this code, by writing an animate function that accepts Image objects, so that I can animate multiple images in my canvas simultaneously. This is my attempt at it:

    $(function(){
        var canvas=document.getElementById("canvas");
        var ctx=canvas.getContext("2d");
        var spritePosition=0;
        var spriteWidth=100;
        var spriteHeight=100;
        var spriteCount=40;
        var spritePlayCount=0;
        var maxSpritePlays=2;

        var objectS=new Image();
        objectS.src="sprites/first.png";

        var fps = 50;
        function animate(sprite) {
            setTimeout(function() {

                if(spritePlayCount<maxSpritePlays){
                    requestAnimationFrame(animate);
                }

                // Drawing code goes here
                ctx.clearRect(0,0,canvas.width,canvas.height);
                ctx.drawImage(sprite,spritePosition*spriteWidth, 0,spriteWidth, spriteHeight, 0,0,spriteWidth, spriteHeight);

                spritePosition++;
                if(spritePosition>spriteCount-1){
                    spritePosition=0;
                    spritePlayCount++;
                }
            }, 1000 / fps);
        }

        objectS.onload=function(){
            animate(objectS);
        }
    }); // end $(function(){});

I am getting a much observed error, but I cant seem to find the fix for it:

index3.html:59 Uncaught TypeError: Failed to execute 'drawImage' on
  'CanvasRenderingContext2D': The provided value is not of type
  '(CSSImageValue or HTMLImageElement or HTMLVideoElement or
  HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'

Can you help me out finding my bug?

Body:
You'll also need to pass the sprite parameter when calling the animate function using requestAnimationFrame.

$(function() {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    var spritePosition = 0;
    var spriteWidth = 100;
    var spriteHeight = 100;
    var spriteCount = 40;
    var spritePlayCount = 0;
    var maxSpritePlays = 2;
    var objectS = new Image();
    objectS.src = "sprites/first.png";
    var fps = 50;

    function animate(sprite) {
        setTimeout(function() {
            if (spritePlayCount < maxSpritePlays) {
                requestAnimationFrame(function() {
                    animate(sprite);
                });
            }
            // Drawing code goes here
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(sprite, spritePosition * spriteWidth, 0, spriteWidth, spriteHeight, 0, 0, spriteWidth, spriteHeight);
            spritePosition++;
            if (spritePosition > spriteCount - 1) {
                spritePosition = 0;
                spritePlayCount++;
            }
        }, 1000 / fps);
    }
    objectS.onload = function() {
        animate(objectS);
    };
});


问:
Rails / Heroku - How can I anti-virus scan an uploaded file?
How is it possible to scan a uploaded file for viruses, trojans etc.?

Just thinking about preventing some users to upload some nasty stuff.

I am using Heroku and Amazon S3.

答:
For anyone approaching this in future we recently created CarrierWave::AttachmentScanner to easily integrate virus and malware scanning into Rails and CarrierWave.

The plugin basically hooks into file uploads using carrierwave and sends the request to a JSON/REST web service to check the files.

If the file matches a known signature then it will raise a CarrierWave:: IntegrityError.


问:
Loop for reading more than 1 query in a bash file
I need a loop in a Bash script (analysis-run.sh) for running many queries. As I have many queries I can't run them manually so I need a way to automate them. So far, I created a file inputs.txt with all my queries and at the end of the bash script file I added the following:

```<code>while read f ; do
  ./analysis-run.sh $f
done < imputs.txt
</code>```

With that loop, analysis-run is only running the first query of inputs.txt over and over again. I am really new to this, so any help would be appreciated.

The content of imputs.txt is:

bones

muscles

blood

saliva

and so on..

The content of analysis-run.sh is:

Execute this script as ./analysis-run.sh [query] [group]

query=$1

group=$2

if [ $group = "clean" ]; then

```<code>    cluster=A
</code>```

else

```<code>    cluster=B
</code>```

fi

adamo-obtain_bundance.py - query $query -ref combined_$cluster.$group.align -splits 1 -group $group

adamo-obtain_structure.py -i $query.combined_$query$group.csv -o $query.$group -cutoff 0.5 -group $group

答:
Using loops in Bash can sometimes work, but it is loaded with perils.

Using xargs is usually the cleanest, most robust approach...

```<code><inputs.txt xargs --max-args=1 do_something
</code>```

The command to execute could be provided as a Bash function...

```<code>function do_something
   {
   echo value=${1}
   }
</code>```

Although the call to xargs is somewhat more involved when taking that approach.  See: Calling functions with xargs within a bash script

About xargs

xargs takes a list of arguments (usually file names), which are provided as an input file or stream, and it places those arguments on the command-line for another specified command or function.  If the command can handle multiple input arguments, you can drop the --max-args=1 option.

Body:
I need a loop in a Bash script (analysis-run.sh) for running many queries. As I have many queries I can't run them manually so I need a way to automate them. So far, I created a file inputs.txt with all my queries and at the end of the bash script file I added the following:

while read f ; do
  ./analysis-run.sh $f
done < imputs.txt

With that loop, analysis-run is only running the first query of inputs.txt over and over again. I am really new to this, so any help would be appreciated.

The content of imputs.txt is:

bones

muscles

blood

saliva

and so on..

The content of analysis-run.sh is:

Execute this script as ./analysis-run.sh [query] [group]

query=$1

group=$2

if [ $group = "clean" ]; then

    cluster=A

else

    cluster=B

fi

adamo-obtain_bundance.py - query $query -ref combined_$cluster.$group.align -splits 1 -group $group

adamo-obtain_structure.py -i $query.combined_$query$group.csv -o $query.$group -cutoff 0.5 -group $group

Body:
Using loops in Bash can sometimes work, but it is loaded with perils.

Using xargs is usually the cleanest, most robust approach...

<inputs.txt xargs --max-args=1 do_something

The command to execute could be provided as a Bash function...

function do_something
   {
   echo value=${1}
   }

Although the call to xargs is somewhat more involved when taking that approach.  See: Calling functions with xargs within a bash script

About xargs

xargs takes a list of arguments (usually file names), which are provided as an input file or stream, and it places those arguments on the command-line for another specified command or function.  If the command can handle multiple input arguments, you can drop the --max-args=1 option.


问:
How can i get my code to test just one line in a text file?
Hello i am looking for some help. so for some back ground this code is going to be used as a log in system for personal use. i am trying to get it to check just one line so i can get it to validate that the username is correct and or the password. how would i do this?</p>

```<code>user = input("please Enter your full name: ")
if os.path.isfile(user + ".txt"):
    with open(user + ".txt", "r")

        print("------------------------")
        Username = input("|Username: ")
        password = getpass.getpass("|Password: ")
        print("------------------------")
</code>```

答:
Ok, if you insist on doing it in an insecure way then I guess you have just a file with a plaintext user name and password in it. I understand that perhaps you are knew to Python so an insecure method is somewhat acceptable :P. Example below,

bosh

password

(in the file there would be no gap between lines as shown above, they would be on consecutive lines)

If not then I recommend you do this as this is how the code section below will expect it to be.

```<code>submittedUsername = input("Please enter username: ")
submittedPassword = input("Please enter password: ")
credentialsFile = open("credentials.txt", "r")
credentials = credentialsFile.readlines()
username = credentials[0].rstrip("\n\r")
password = credentials[1].rstrip("\n\r")
if submittedUsername == username:
    if submittedPassword == password:
        print("Login verified!")
        #both username and password verified here, do what you want
    else:
        #password incorrect
        print("Login invalid")
else:
    #username incorrect but whether you want to specify what is wrong is up to you
    print("Login invalid")
</code>```

If there are any parts you would like explaining, do ask. Hope that helps.

Body:
Hello i am looking for some help. so for some back ground this code is going to be used as a log in system for personal use. i am trying to get it to check just one line so i can get it to validate that the username is correct and or the password. how would i do this?

user = input("please Enter your full name: ")
if os.path.isfile(user + ".txt"):
    with open(user + ".txt", "r")

        print("------------------------")
        Username = input("|Username: ")
        password = getpass.getpass("|Password: ")
        print("------------------------")

Body:
Ok, if you insist on doing it in an insecure way then I guess you have just a file with a plaintext user name and password in it. I understand that perhaps you are knew to Python so an insecure method is somewhat acceptable :P. Example below,

bosh

password

(in the file there would be no gap between lines as shown above, they would be on consecutive lines)

If not then I recommend you do this as this is how the code section below will expect it to be.

submittedUsername = input("Please enter username: ")
submittedPassword = input("Please enter password: ")
credentialsFile = open("credentials.txt", "r")
credentials = credentialsFile.readlines()
username = credentials[0].rstrip("\n\r")
password = credentials[1].rstrip("\n\r")
if submittedUsername == username:
    if submittedPassword == password:
        print("Login verified!")
        #both username and password verified here, do what you want
    else:
        #password incorrect
        print("Login invalid")
else:
    #username incorrect but whether you want to specify what is wrong is up to you
    print("Login invalid")

If there are any parts you would like explaining, do ask. Hope that helps.


问:
formatting cell background color based on condition in javascript
i am trying to change cell background color based on condition on particular column, it is not working.please help to me to resolve. this is what i have tried.
my php page for your reference. thanks. i found a solution but it doesnt work on my php page. this that solution http://www.ok-soft-gmbh.com/jqGrid/BackgroundColorFormatter.htm

```<code>    <?php
$con=mysqli_connect("localhost","user","pass","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$val = mysqli_query($con,"select storenm,FA_SOH,FA_CY_QTY,FA_CT_QTY from pr_report");

   $arr=array();
   while ($row = mysqli_fetch_array($val)){
       $arr[] = "["."'".$row['storenm']."'".","."'".$row['FA_SOH']."'".","."'".$row['FA_CY_QTY']."'"."]";
   }
   $assign = implode(',',$arr);

   ?>

    <!DOCTYPE HTML>
    <html lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name=viewport content="width=device-width, initial-scale=1"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

<meta charset="utf-8">

<!--jQuery dependencies-->
    <link rel="stylesheet" href="jquery-ui.css" />
    <script src="jquery-1.11.0.min.js"></script>
    <script src="jquery-ui.min.js"></script>
    <script type="text/javascript" src="touch-punch.min.js"></script>
<!--PQ Grid files-->
    <link rel="stylesheet" href="pqgrid.min.css" />
    <script src="pqgrid.min.js"></script>
<!--PQ Grid Office theme-->
    <link rel="stylesheet" href="themes/office/pqgrid.css" />
<style type="text/css">
        span.cellWithoutBackground
        {
            display:block;
            background-image:none;
            margin-right:-2px;
            margin-left:-2px;
            height:14px;
            padding:4px;
        }
    </style>
<script>
    $(function () {
    var data = [<?PHP echo $assign;?>];
          var obj = {
          swipeModel: { on : true },
          //scrollModel: { autoFit: true },
            title: "Grid From JSON",
            collapsible: { on: true, collapsed: false },
virtualX: false,
virtualY: false,
        freezeRows: 0,

            freezeCols: 1,
            editable: false,
            resizable: false,
        width: 400,
        height: 400,
        title: "ParamQuery Grid Example"
        };

        obj.colModel = [{
        title: "Storenm", width: 100, dataType: "string" },
        { title: "FSOH", width: 200, dataType: "float",align: "center" },
        { title: "FCY", width: 150, dataType: "float",align: "center",
                        formatter: function (cellvalue) {
                            var color;
                            var val = Number(cellvalue);
                            if (val>25) {
                                color = 'red';
                            } else if (val>15) {
                                color = 'yellow';
                            } else {
                                color = 'green';
                            }

                            return '<span class="cellWithoutBackground" style="background-color:' + color + ';">' + cellvalue + '</span>';
                        }
                    },
        { title: "Profits ($ millions)", width: 150, dataType: "float", align: "right"}];

        obj.dataModel = {data: data};
        $("#grid_array").pqGrid(obj);

    });

</script>
</head>
<body>
<div id="grid_array" style="margin:100px;"></div>
</body>

</html>
</code>```

Thanks.

答:
You try to use very old example, which I created for the answer. Later I suggested to include another features: cellattr and rowattr, which I recommend to use instead of usage custom formatters just to set attributes and not the content of the cell. Look at the old answer for an example of usage cellattr. You can use, for example, the formatter: "number" to format the content of the column, and to use cellattr to set class attribute on the cells to change the background color of the cells.

You posted some code, where you don't use jqGrid at all. I suppose, that you wrote some wrapper pqGrid, which use colModel for jqGrid.

In any way, it's important to take in consideration some CSS rules to change the background color. You use currently background-color property to change the color. The default jQuery UI CSS apply background-image on the cells too. To be able to change the background color to red, for example, you can use either both background-color and background-image

background-color: red;
background-image: none;
```

<p>or to use</p>

<pre class="lang-css prettyprint-override"><code>background: red;
</code>```

which reset background-image together with the background-color.

The next problem. If you apply the CSS properties by usage a CSS rule, then the usage of

span.cellWithoutBackground {
    background-image:none;
}
```

<p>or</p>

<pre class="lang-css prettyprint-override"><code>.backgroundRed {
    background-color: red;
    background-image: none;
}
</code>```

will not work because there are exist jQuery UI rules with two selectors, which set background too. To force that your CSS rule will be applied you should use more complex CSS selector. For example

.ui-jqgrid .jqgrow .backgroundRed {
   background-color: red;
   background-image: none;
}
```

(the classes jqgrow and ui-jqgrid are applied on the outer elements).

Body:
i am trying to change cell background color based on condition on particular column, it is not working.please help to me to resolve. this is what i have tried.
my php page for your reference. thanks. i found a solution but it doesnt work on my php page. this that solution http://www.ok-soft-gmbh.com/jqGrid/BackgroundColorFormatter.htm

    <?php
$con=mysqli_connect("localhost","user","pass","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$val = mysqli_query($con,"select storenm,FA_SOH,FA_CY_QTY,FA_CT_QTY from pr_report");

   $arr=array();
   while ($row = mysqli_fetch_array($val)){
       $arr[] = "["."'".$row['storenm']."'".","."'".$row['FA_SOH']."'".","."'".$row['FA_CY_QTY']."'"."]";
   }
   $assign = implode(',',$arr);

   ?>

    <!DOCTYPE HTML>

    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name=viewport content="width=device-width, initial-scale=1"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

<meta charset="utf-8">

    <link rel="stylesheet" href="jquery-ui.css" />

    <link rel="stylesheet" href="pqgrid.min.css" />

    <link rel="stylesheet" href="themes/office/pqgrid.css" />

Thanks.

Body:
You try to use very old example, which I created for the answer. Later I suggested to include another features: cellattr and rowattr, which I recommend to use instead of usage custom formatters just to set attributes and not the content of the cell. Look at the old answer for an example of usage cellattr. You can use, for example, the formatter: "number" to format the content of the column, and to use cellattr to set class attribute on the cells to change the background color of the cells.

You posted some code, where you don't use jqGrid at all. I suppose, that you wrote some wrapper pqGrid, which use colModel for jqGrid.

In any way, it's important to take in consideration some CSS rules to change the background color. You use currently background-color property to change the color. The default jQuery UI CSS apply background-image on the cells too. To be able to change the background color to red, for example, you can use either both background-color and background-image

background-color: red;
background-image: none;

or to use

background: red;

which reset background-image together with the background-color.

The next problem. If you apply the CSS properties by usage a CSS rule, then the usage of

span.cellWithoutBackground {
    background-image:none;
}

or

.backgroundRed {
    background-color: red;
    background-image: none;
}

will not work because there are exist jQuery UI rules with two selectors, which set background too. To force that your CSS rule will be applied you should use more complex CSS selector. For example

.ui-jqgrid .jqgrow .backgroundRed {
   background-color: red;
   background-image: none;
}

(the classes jqgrow and ui-jqgrid are applied on the outer elements).


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答:
The DOS interrupt</p>

```<code>INT 21h
</code>```

OwnerDisplayName: Michael Buen

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Triptych

Body:
The DOS interrupt

INT 21h

OwnerDisplayName: edg

LastEditorDisplayName: edg


问:
Using external composite jQuery Templates
I wanted to try out jQuery Templates after being inspired by these 2 blog postings

http://encosia.com/2010/11/10/composition-with-jquery-templates-why-and-how/

http://encosia.com/2010/10/05/using-external-templates-with-jquery-templates/

Well, it's not quite working for me.  If I have the template code on the page itself it works fine, but loading remotely isn't working for me.  It appears the template is being retrieved ok. what is wrong here?

External template:

```<code><script id="contactsTemplate" type="text/x-jquery-tmpl">
  <table class="contacts">
    <thead><tr><td class="ui-helper-hidden">Id</td><td>Name</td><td>City</td><td>State</td></tr></thead>
    <tbody>
    {{each contact}}
        {{tmpl($value) '#contactTemplate'}}
    {{/each}}
    </tbody>
  </table>
</script>

<script id="contactTemplate" type="text/x-jquery-tmpl">
    <tr><td class="ui-helper-hidden">${id}</td><td>${name}</td><td>${city}</td><td>${state}</td></tr>
</script>
</code>```

On my page I'm using this code to retrieve and load the template:

```<code>var contacts = {
    contact: [
        { id: 1, name: "John Green", city: "Orange Beach", state: "AL" },
        { id: 2, name: "Sam Thompson", city: "Pensacola", state: "FL" },
        { id: 3, name: "Mary Stein", city: "Mobile", state: "AL" }
    ]
};

$("#ShowDataRemote").button().click(function() {
    $.get('templates/Contact.htm', function(template) {
        alert(template);
        $.tmpl(template, contacts).appendTo("body");
        alert("async done");
    });
});
</code>```

Update:

A new blog post on Encosia explains this question and answer...

http://encosia.com/2010/12/02/jquery-templates-composite-rendering-and-remote-loading/

答:
That simple remote loading technique won't work with composite templates, since the string you're loading isn't a valid template itself.  You can get it working by changing your click handler like this:</p>

```<code>$("#ShowDataRemote").button().click(function() {
  $.get('templates/Contact.htm', function(template) {
    // Inject the template script blocks into the page.
    $('body').append(template);

    // Use those templates to render the data.
    $('#contactsTemplate').tmpl(contacts).appendTo("body");
  });
});
</code>```

Body:
I wanted to try out jQuery Templates after being inspired by these 2 blog postings

http://encosia.com/2010/11/10/composition-with-jquery-templates-why-and-how/

http://encosia.com/2010/10/05/using-external-templates-with-jquery-templates/

Well, it's not quite working for me.  If I have the template code on the page itself it works fine, but loading remotely isn't working for me.  It appears the template is being retrieved ok. what is wrong here?

External template:

On my page I'm using this code to retrieve and load the template:

var contacts = {
    contact: [
        { id: 1, name: "John Green", city: "Orange Beach", state: "AL" },
        { id: 2, name: "Sam Thompson", city: "Pensacola", state: "FL" },
        { id: 3, name: "Mary Stein", city: "Mobile", state: "AL" }
    ]
};

$("#ShowDataRemote").button().click(function() {
    $.get('templates/Contact.htm', function(template) {
        alert(template);
        $.tmpl(template, contacts).appendTo("body");
        alert("async done");
    });
});

Update:

A new blog post on Encosia explains this question and answer...

http://encosia.com/2010/12/02/jquery-templates-composite-rendering-and-remote-loading/

Body:
That simple remote loading technique won't work with composite templates, since the string you're loading isn't a valid template itself.  You can get it working by changing your click handler like this:

$("#ShowDataRemote").button().click(function() {
  $.get('templates/Contact.htm', function(template) {
    // Inject the template script blocks into the page.
    $('body').append(template);

    // Use those templates to render the data.
    $('#contactsTemplate').tmpl(contacts).appendTo("body");
  });
});


问:
How to fetch the changed object from an array in AngularJs?
I have 2 arrays stored in arr1 and arr2

```<code>var arr1 = [
  {
    "status": 4,
    "id": 1
  },
  {
    "status": 2,
    "id": 2
  },
  {
    "status": 1,
    "id": 3
  }];

var arr2 = [{
    "status": 4,
    "id": 1
  },
  {
    "status": 2,
    "id": 2
  },
  {
    "status": 4,
    "id": 3
  }];
</code>```

Am using  angular.equals(arr1, arr2) to check 2 arrays are same but when the status changes in arr2, how can i fetch the respective id from arr2.

答:
This will give you the array which contains the ids of the elements with different status value.</p>

```<code> var elementsChanged = arr1.map((val, idx) => {
        if (val.status !== arr2[idx].status)
          return arr2[idx].id
      })
</code>```

Body:
I have 2 arrays stored in arr1 and arr2

var arr1 = [
  {
    "status": 4,
    "id": 1
  },
  {
    "status": 2,
    "id": 2
  },
  {
    "status": 1,
    "id": 3
  }];

var arr2 = [{
    "status": 4,
    "id": 1
  },
  {
    "status": 2,
    "id": 2
  },
  {
    "status": 4,
    "id": 3
  }];

Am using  angular.equals(arr1, arr2) to check 2 arrays are same but when the status changes in arr2, how can i fetch the respective id from arr2.

Body:
This will give you the array which contains the ids of the elements with different status value.

 var elementsChanged = arr1.map((val, idx) => {
        if (val.status !== arr2[idx].status)
          return arr2[idx].id
      })


问:
How to get size of String array
I create a string array in "Arduino" like this:

```<code>String commandList[] = {"dooropen", "doorlock"};
</code>```

And in my code I want to know size of this array and I don't want define size of this array like bottom code:

```<code>#define commandListArraySize 2
</code>```

I try to get size of this variable like this:

```<code>int size = sizeof(commandList);
</code>```

But the returned size = 12.

答:
As long as you are the in scope that the array was created (you aren't passing the array to a function), you can use this common macro:

```<code>#define ARRAY_SIZE(x) sizeof(x)/sizeof(x[0])
</code>```

and use it like so:

```<code>String[] myStrings{"Hello", "World", "These", "Are", "Strings"};
for (size_t i = 0; i < ARRAY_SIZE(myStrings); i++) {
    Serial.println(myStrings[i]);
}
</code>```

Title: How to get size of String array

Body:
I create a string array in "Arduino" like this:

String commandList[] = {"dooropen", "doorlock"};

And in my code I want to know size of this array and I don't want define size of this array like bottom code:

#define commandListArraySize 2

I try to get size of this variable like this:

int size = sizeof(commandList);

But the returned size = 12.

Body:
As long as you are the in scope that the array was created (you aren't passing the array to a function), you can use this common macro:

#define ARRAY_SIZE(x) sizeof(x)/sizeof(x[0])

and use it like so:

String[] myStrings{"Hello", "World", "These", "Are", "Strings"};
for (size_t i = 0; i < ARRAY_SIZE(myStrings); i++) {
    Serial.println(myStrings[i]);
}


问:
Link to an open tab
I want to create a link to an open tab on a different page.
Here's my html where the tab's are on:

```<code>// This are internal links
<ul class="tabs">
  <li class="tab-link current" data-tab="tab-1">Tab 1</li>
  <li class="tab-link" data-tab="tab-2">Tab 2</li>
  <li class="tab-link" data-tab="tab-3">Tab 3</li>
  <li class="tab-link" data-tab="tab-4">Tab 4</li>
</ul>

<div id="tab-1" class="tab-content current"><p>some content</p></div>
<div id="tab-2" class="tab-content"><p>some content</p></div>
<div id="tab-3" class="tab-content"><p>some content</p></div>
<div id="tab-4" class="tab-content"><p>some content</p></div>
</code>```

I use this script:

```<code>$(document).ready(function(){
  $('ul.tabs li').click(function(){
    var tab_id = $(this).attr('data-tab');

    $('ul.tabs li').removeClass('current');
    $('.tab-content').removeClass('current');

    $(this).addClass('current');
    $("#"+tab_id).addClass('current');
  })
})
</code>```

Now I have this link on an external page, I want to redirect to the page with the tabs and show the content of tab 2:

```<code><a href="tabpage.html#tab-2>Some link</a>
</code>```

This is not working, can anyone help me? Maybe with an onclick() in the a element?

答:
Read the hash in the url when page loads and trigger a click on corresponding

Something like:

```<code>$(document).ready(function() {
  // your existing tabs click listener
  $('ul.tabs li').click(function() { .... })
  // get hash from url
  var hash = location.hash;
  // check if tab matching hash exists
  if (hash && $(hash).length) {
    // now trigger click on appropriate tab
    $('.tab-link[data-tab="' + hash.slice(1) + '"]').click();
  }

})
</code>```

Title: Link to an open tab

Body:
I want to create a link to an open tab on a different page.
Here's my html where the tab's are on:

// This are internal links

Tab 1

Tab 2

Tab 3

Tab 4

some content

some content

some content

some content

I use this script:

$(document).ready(function(){
  $('ul.tabs li').click(function(){
    var tab_id = $(this).attr('data-tab');

    $('ul.tabs li').removeClass('current');
    $('.tab-content').removeClass('current');

    $(this).addClass('current');
    $("#"+tab_id).addClass('current');
  })
})

Now I have this link on an external page, I want to redirect to the page with the tabs and show the content of tab 2:

Some link

This is not working, can anyone help me? Maybe with an onclick() in the a element?

Body:
Read the hash in the url when page loads and trigger a click on corresponding <li>

Something like:

$(document).ready(function() {
  // your existing tabs click listener
  $('ul.tabs li').click(function() { .... })
  // get hash from url
  var hash = location.hash;
  // check if tab matching hash exists
  if (hash && $(hash).length) {
    // now trigger click on appropriate tab
    $('.tab-link[data-tab="' + hash.slice(1) + '"]').click();
  }

})


问:
Retrieve Urls from SQL Database and display the images in a repeater in ASP.NET
So basically Its a image uploader and Image viewer project.

I am able to upload the image to a local folder and just save the image url in database which looks like

Now next the user should be able to view the images based on the palbum and pcat selected. palbum = album names. pcat = Public,Private etc(ignore the first pcat being animal).

Now on Page 1 my code will be:

```<code>protected void btn_view_Click(object sender, EventArgs e)
    {

        Response.Redirect("viewimage.aspx?album='"+DropDownList_album.SelectedValue+"'&cat='"+DropDownList_category.SelectedValue+"'");
    }
</code>```

On Page 2 I have applied a repeater and want to display only those pictures based on the queries only.

```<code>protected void Page_Load(object sender, EventArgs e)
    {
        string album = Request.QueryString["album"];
        string cat = Request.QueryString["cat"];

        SqlConnection con = new SqlConnection(" *hiding this* ");
        con.Open();

        string cmd = "select * from Pics where palbum='" + Request.QueryString["album"].ToString() + "' and pcat='" + Request.QueryString["cat"].ToString() +"'";     // have tried replacing select purl with select * but same problem.

        SqlDataAdapter adp = new SqlDataAdapter(cmd, con);

        DataTable dt = new DataTable();

        adp.Fill(dt);

        Repeater1.DataSource = dt;
        Repeater1.DataBind();
    }
</code>```

But everytime i try this with different syntax and what not I either get a blank screen with no images in the repeater or this error:

答:
Depending on SQL Server parameters, double quotes are no accepted, if I recall correctly is quote_identifier parameter.

You have a hidden problem that could be troublesome called SQL Injection. Yous should get rid of both problems altogether using parametrized queries:

SqlConnection con = new SqlConnection(" hiding this ");
        con.Open();

```<code>    string cmd = "select * from Pics where palbum= @album and pcat=@cat";

    SqlDataAdapter adp = new SqlDataAdapter(cmd, con);

    adp.Parameters.AddWithValue("@album", Request.QueryString["album"]);
    adp.Parameters.AddWithValue("@cat", Request.QueryString["cat"]);

    DataTable dt = new DataTable();

    adp.Fill(dt);

    Repeater1.DataSource = dt;
    Repeater1.DataBind();
</code>```

Body:
So basically Its a image uploader and Image viewer project.

I am able to upload the image to a local folder and just save the image url in database which looks like

Now next the user should be able to view the images based on the palbum and pcat selected. palbum = album names. pcat = Public,Private etc(ignore the first pcat being animal).

Now on Page 1 my code will be:

protected void btn_view_Click(object sender, EventArgs e)
    {

        Response.Redirect("viewimage.aspx?album='"+DropDownList_album.SelectedValue+"'&cat='"+DropDownList_category.SelectedValue+"'");
    }

On Page 2 I have applied a repeater and want to display only those pictures based on the queries only.

protected void Page_Load(object sender, EventArgs e)
    {
        string album = Request.QueryString["album"];
        string cat = Request.QueryString["cat"];

        SqlConnection con = new SqlConnection(" *hiding this* ");
        con.Open();

        string cmd = "select * from Pics where palbum='" + Request.QueryString["album"].ToString() + "' and pcat='" + Request.QueryString["cat"].ToString() +"'";     // have tried replacing select purl with select * but same problem.

        SqlDataAdapter adp = new SqlDataAdapter(cmd, con);

        DataTable dt = new DataTable();

        adp.Fill(dt);

        Repeater1.DataSource = dt;
        Repeater1.DataBind();
    }

But everytime i try this with different syntax and what not I either get a blank screen with no images in the repeater or this error:

Body:
Depending on SQL Server parameters, double quotes are no accepted, if I recall correctly is quote_identifier parameter.

You have a hidden problem that could be troublesome called SQL Injection. Yous should get rid of both problems altogether using parametrized queries:

SqlConnection con = new SqlConnection(" hiding this ");
        con.Open();

    string cmd = "select * from Pics where palbum= @album and pcat=@cat";

    SqlDataAdapter adp = new SqlDataAdapter(cmd, con);

    adp.Parameters.AddWithValue("@album", Request.QueryString["album"]);
    adp.Parameters.AddWithValue("@cat", Request.QueryString["cat"]);

    DataTable dt = new DataTable();

    adp.Fill(dt);

    Repeater1.DataSource = dt;
    Repeater1.DataBind();


问:
Should I use past or present tense in git commit messages?
I read once that git commit messages should be in the imperative present tense, e.g. "Add tests for x". I always find myself using the past tense, e.g. "Added tests for x" though, which feels a lot more natural to me.

Here's a recent John Resig commit showing the two in one message:

Tweak some more jQuery set results in the manipulation tests. Also fixed the order of the expected test results.

Does it matter? Which should I use?

答:
Stick with the present tense imperative because

it's good to have a standard

it matches tickets in the bug tracker which naturally have the form "implement something", "fix something", or "test something."


问:
Stuff isn't appending to my list
I'm trying to create a simulation where there are two printers and I find the average wait time for each.  I'm using a class for the printer and task in my program.  Basically, I'm adding the wait time to each of each simulation to a list and calculating the average time.  My issue is that I'm getting a division by 0 error so nothing is being appended.  When I try it with 1 printer (Which is the same thing essentially) I have no issues.  Here is the code I have for the second printer.  I'm using a queue for this.

```<code>if printers == 2:
    for currentSecond in range(numSeconds):
        if newPrintTask():
            task = Task(currentSecond,minSize,maxSize)
            printQueue.enqueue(task)

        if (not labPrinter1.busy()) and (not labPrinter2.busy()) and \
           (not printQueue.is_empty()):
            nexttask = printQueue.dequeue()
            waitingtimes.append(nexttask.waitTime(currentSecond))
            labPrinter1.startNext(nexttask)

        elif (not labPrinter1.busy()) and (labPrinter2.busy()) and \
             (not printQueue.is_empty()):
            nexttask = printQueue.dequeue()
            waitingtimes.append(nexttask.waitTime(currentSecond))
            labPrinter1.startNext(nexttask)

        elif (not labPrinter2.busy()) and (labPrinter1.busy()) and \
             (not printQueue.is_empty()):
            nexttask = printQueue.dequeue()
            waitingtimes.append(nexttask.waitTime(currentSecond))
            labPrinter2.startNext(nexttask)

        labPrinter1.tick()
        labPrinter2.tick()

        averageWait = sum(waitingtimes)/len(waitingtimes)
        outfile.write("Average Wait %6.2f secs %3d tasks remaining." \
              %(averageWait,printQueue.size()))
</code>```

Any assistance would be great!

Edit:  I should mention that this happens no matter the values.  I could have a page range of 99-100 and a PPM of 1 yet I still get divided by 0.

答:
I think your problem stems from an empty waitingtimes on the first iteration or so. If there is no print job in the queue, and there has never been a waiting time inserted, you are going to reach the bottom of the loop with waitingtimes==[] (empty), and then do:

```<code>sum(waitingtimes) / len(waitingtimes)
</code>```

Which will be

```<code>sum([])  / len([])
</code>```

Which is

```<code>0 / 0
</code>```

The easiest way to deal with this would just be to check for it, or catch it:

```<code>if not waitingtimes:
    averageWait = 0
else:
    averageWait = sum(waitingtimes)/len(waitingtimes)
</code>```

Or:

```<code>try:
    averageWait = sum(waitingtimes)/len(waitingtimes)

except ZeroDivisionError:
    averageWait = 0
</code>```

Title: Stuff isn't appending to my list

Body:
I'm trying to create a simulation where there are two printers and I find the average wait time for each.  I'm using a class for the printer and task in my program.  Basically, I'm adding the wait time to each of each simulation to a list and calculating the average time.  My issue is that I'm getting a division by 0 error so nothing is being appended.  When I try it with 1 printer (Which is the same thing essentially) I have no issues.  Here is the code I have for the second printer.  I'm using a queue for this.

if printers == 2:
    for currentSecond in range(numSeconds):
        if newPrintTask():
            task = Task(currentSecond,minSize,maxSize)
            printQueue.enqueue(task)

        if (not labPrinter1.busy()) and (not labPrinter2.busy()) and \
           (not printQueue.is_empty()):
            nexttask = printQueue.dequeue()
            waitingtimes.append(nexttask.waitTime(currentSecond))
            labPrinter1.startNext(nexttask)

        elif (not labPrinter1.busy()) and (labPrinter2.busy()) and \
             (not printQueue.is_empty()):
            nexttask = printQueue.dequeue()
            waitingtimes.append(nexttask.waitTime(currentSecond))
            labPrinter1.startNext(nexttask)

        elif (not labPrinter2.busy()) and (labPrinter1.busy()) and \
             (not printQueue.is_empty()):
            nexttask = printQueue.dequeue()
            waitingtimes.append(nexttask.waitTime(currentSecond))
            labPrinter2.startNext(nexttask)

        labPrinter1.tick()
        labPrinter2.tick()

        averageWait = sum(waitingtimes)/len(waitingtimes)
        outfile.write("Average Wait %6.2f secs %3d tasks remaining." \
              %(averageWait,printQueue.size()))

Any assistance would be great!

Edit:  I should mention that this happens no matter the values.  I could have a page range of 99-100 and a PPM of 1 yet I still get divided by 0.

Body:
I think your problem stems from an empty waitingtimes on the first iteration or so. If there is no print job in the queue, and there has never been a waiting time inserted, you are going to reach the bottom of the loop with waitingtimes==[] (empty), and then do:

sum(waitingtimes) / len(waitingtimes)

Which will be

sum([])  / len([])

Which is

0 / 0

The easiest way to deal with this would just be to check for it, or catch it:

if not waitingtimes:
    averageWait = 0
else:
    averageWait = sum(waitingtimes)/len(waitingtimes)

Or:

try:
    averageWait = sum(waitingtimes)/len(waitingtimes)

except ZeroDivisionError:
    averageWait = 0


问:
datasets.load_iris() in Python
What does the function load_iris() do ?
Also, I don't understand what type of data it contains and where to find it.

```<code>iris = datasets.load_iris()
X = iris.data
target = iris.target
names = iris.target_names
</code>```

Can somebody please tell in detail what does this piece of code does?
Thanks in advance.

答: load_iris is a function from sklearn. The link provides documentation: iris in your code will be a dictionary-like object. X and y will be numpy arrays, and names has the array of possible targets as text (rather than numeric values as in y).

Title: datasets.load_iris() in Python

Body:
What does the function load_iris() do ?
Also, I don't understand what type of data it contains and where to find it.

iris = datasets.load_iris()
X = iris.data
target = iris.target
names = iris.target_names

Can somebody please tell in detail what does this piece of code does?
Thanks in advance.


答:
You need to first put arr2 in $scope and then set $watch on your data to detect the exact id change.
$scope.$watch('arr2', function(newValue, oldValue){.//iterate and detect your id change..}, true);

Demo for watcher

Demo Updated with @korte map suggestion.

Title: How to fetch the changed object from an array in AngularJs?


问:
Firebase signup with user, email and password
After leaving Parse and moving to Firebase I faced a problem that it's only possible to signup with email and password, how can I make Firebase store the username as well?  </p>

答:
Try This...    </p>

```<code>FIRAuth.auth()?.createUser(withEmail: emailField.text!, password: passwordField.text!, completion: { (user: FIRUser?, error) in
            if error != nil {
                print(error)
                return

            } else {
            print("User Created...") }

            guard let uid = user?.uid else { return }

            // You can set these values to whatever you want, plus add more!
            let values = ["email": emailField.text!, "username": usernameField.text!] as [String : Any]

         // Then pass your values into another function called 'RegisterUserIntoDatabase'
         // which creates the user in your Firebase Database...

            self.registerUserIntoDatabase(uid, values: values as [String : AnyObject])
        })

private func registerUserIntoDatabase(_ uid: String, values: [String: AnyObject]) {
    // Adding User Info
    let ref = FIRDatabase.database().reference()
    let usersReference = ref.child("users").child(uid)

    usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in
        if err != nil {
            print(err)
            return
        }
        print("Successfully Added a New User to the Database")
    })
}
</code>```

Body:
Try This...

FIRAuth.auth()?.createUser(withEmail: emailField.text!, password: passwordField.text!, completion: { (user: FIRUser?, error) in
            if error != nil {
                print(error)
                return

            } else {
            print("User Created...") }

            guard let uid = user?.uid else { return }

            // You can set these values to whatever you want, plus add more!
            let values = ["email": emailField.text!, "username": usernameField.text!] as [String : Any]

         // Then pass your values into another function called 'RegisterUserIntoDatabase'
         // which creates the user in your Firebase Database...

            self.registerUserIntoDatabase(uid, values: values as [String : AnyObject])
        })

private func registerUserIntoDatabase(_ uid: String, values: [String: AnyObject]) {
    // Adding User Info
    let ref = FIRDatabase.database().reference()
    let usersReference = ref.child("users").child(uid)

    usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in
        if err != nil {
            print(err)
            return
        }
        print("Successfully Added a New User to the Database")
    })
}


问:
Stack multiple plots vertically in R or Python
I am trying to reproduce the plot below, which shows the mean and standard deviation in separate sections of the y-axis. Rather than plotting them in separate subfigures, they share the x-axis.

I see this suggestion to use the lattice library in R, but I'd like to do it with labels to the side, instead of separating each graph—as in the example I've provided.

答:
In R, here's a ggplot2 version:

```<code>library(ggplot2)
library(reshape2)

# Fake data
set.seed(2)
n = 20
dat = data.frame(mp=rep(seq(0,1,length=n),2),
                 group=rep(LETTERS[1:2], each=n),
                 Mean=rep(c(1,1.1),each=n)*seq(0.7,0,length=n),
                 SD=rep(c(0.1,.12), each=n) + rnorm(2*n,0,0.02))

dat = melt(dat, id.var=c("mp","group"))
dat$variable = factor(dat$variable, levels=c("SD","Mean"))

ggplot(dat, aes(mp, value, colour=group)) +
  facet_grid(variable ~ ., scales="free", space="free", switch="y", ) +
  geom_vline(xintercept=0.6, colour="grey40", linetype="11") +
  geom_line() +
  geom_point() +
  scale_y_continuous(breaks=function(x) {round(seq(0,max(x),length=5)[-5],1)}) +
  expand_limits(y=c(0,0.2)) +
  labs(x="Mixing Parameter", y="") +
  theme_bw() +
  theme(panel.spacing.y=unit(0,"lines"),
        strip.placement="outside",
        strip.background=element_rect(fill=NA, colour=NA)) +
  guides(colour=FALSE)
</code>```

Body:
In R, here's a ggplot2 version:

library(ggplot2)
library(reshape2)

# Fake data
set.seed(2)
n = 20
dat = data.frame(mp=rep(seq(0,1,length=n),2),
                 group=rep(LETTERS[1:2], each=n),
                 Mean=rep(c(1,1.1),each=n)*seq(0.7,0,length=n),
                 SD=rep(c(0.1,.12), each=n) + rnorm(2*n,0,0.02))

dat = melt(dat, id.var=c("mp","group"))
dat$variable = factor(dat$variable, levels=c("SD","Mean"))

ggplot(dat, aes(mp, value, colour=group)) +
  facet_grid(variable ~ ., scales="free", space="free", switch="y", ) +
  geom_vline(xintercept=0.6, colour="grey40", linetype="11") +
  geom_line() +
  geom_point() +
  scale_y_continuous(breaks=function(x) {round(seq(0,max(x),length=5)[-5],1)}) +
  expand_limits(y=c(0,0.2)) +
  labs(x="Mixing Parameter", y="") +
  theme_bw() +
  theme(panel.spacing.y=unit(0,"lines"),
        strip.placement="outside",
        strip.background=element_rect(fill=NA, colour=NA)) +
  guides(colour=FALSE)


问:
Using Sessions in Cassandra
When using cassandra datastax java driver, When can I use multiple sessions under same cluster? I am not able to find any good usecase for having a cluster and multiple sessions.
My application have multiple components/modules that accesses Cassandra. Based on the answer I may decide Should I be having one session per component/module or just one session shared across all the components of my application.

Update: Everywhere on the internet they recommend to use one session. I get it, but my question is "in what scenario do you create multiple sessions for one cluster?". If there is no such scenario, why the library allows to create multiple sessions, instead the library can just have a method to return a singleton session object.

答:
Use Just One Session across all your component.

Because In Cassandra Session is a heavy object. Thread-safe. It maintain multiple connection, cached prepared statement etc.

Here is the JavaDoc :

A session holds connections to a Cassandra cluster, allowing it to be queried. Each session maintains multiple connections to the cluster nodes, provides policies to choose which node to use for each query (round-robin on all nodes of the cluster by default), and handles retries for failed query (when it makes sense), etc...

Session instances are thread-safe and usually a single instance is enough per application. As a given session can only be "logged" into one keyspace at a time (where the "logged" keyspace is the one used by query if the query doesn't explicitely use a fully qualified table name), it can make sense to create one session per keyspace used. This is however not necessary to query multiple keyspaces since it is always possible to use a single session with fully qualified table name in queries.

Source :

https://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Session.html
https://ahappyknockoutmouse.wordpress.com/2014/11/12/246/

Title: Using Sessions in Cassandra


问:
Duplicate entries when using JOIN and GROUP BY
I'm trying to make a query for "pagination", basically joining the user table with the threads and posts table to display the forum page (with the threads in range) it's supposed to be sorted by the last post inside each thread. The problems I'm facing are either:

threads get duplicated

takes too long to complete

The user ID of the LAST post is the same as the thread author id (in this case the thread aren't duplicated)

This is the query I'm currently using

```<code>SELECT
t.TId AS thread_id,
t.TName AS thread_name,
t.TAuthorId AS thread_author_id,
u2.UName AS thread_author_name,
t.TDeleted AS thread_deleted_boolean,

/* This might slow down things */
(SELECT COUNT(forum_posts.PId) FROM forum_posts WHERE forum_posts.TId = t.TId) AS thread_posts,
(SELECT CEIL(COUNT(forum_posts.PId) / 20) FROM forum_posts WHERE forum_posts.TId = t.TId) AS thread_pages,
/* This might slow down things */

p.PId AS lastpost_id,
FROM_UNIXTIME(p.PDate/1000) AS lastpost_date,
p.PAuthorId AS lastpost_author_id,
u.UName AS lastpost_author_name

FROM forum_posts AS p

LEFT JOIN forum_threads AS t
ON t.TId = p.TId

/*
* Not used
LEFT JOIN forum_users AS u
ON t.TAuthorId = u.UId OR p.PAuthorId = u.UId
*/

LEFT JOIN forum_users AS u
ON p.PAuthorId = u.UId

LEFT JOIN forum_users AS u2
ON t.TAuthorId = u2.UId

ORDER BY p.PId DESC
LIMIT 50
</code>```

This one is relatively fast, the thread author id and the lastpost author id are different and work just fine, the problem is that the threads are shown multiple times (duplicated). I've tried adding a

```<code>GROUP BY t.TId
</code>```

near the end but it just makes the query never finish loading.

Is this a indexing problem?

It's worth noting that it would be nice if I could change what I order by and what I limit by dynamically...

```<code>query += `LIMIT ` + ((page - 1) * (THREADS_SHOWN_PER_PAGE)) + `,` + THREADS_SHOWN_PER_PAGE;
</code>```

Also, it's not a big deal if the user is null, the way I'm inserting things in the database sometimes the user is created after the post/thread.

答:
How to do a forum...

Materialize last_post_id and post_count in threads table (update them on posting)

Create an index on (forum_id,last_post_id)

This little bit of denormalization is essential for performance. Without this, it will not work. The index on (forum_id,last_post_id) will allow you to sort threads in each forum by last post, which is what you usually want to display.

Caching post count will greatly speed up your pagination.

And, obviously, since the last page of a topic is the most accessed, you will display posts with ORDER BY post_id DESC when you're accessing a page closer to the end than to the beginning of the topic. Adjust LIMIT values accordingly.

Body:
I'm trying to make a query for "pagination", basically joining the user table with the threads and posts table to display the forum page (with the threads in range) it's supposed to be sorted by the last post inside each thread. The problems I'm facing are either:

threads get duplicated

takes too long to complete

The user ID of the LAST post is the same as the thread author id (in this case the thread aren't duplicated)

This is the query I'm currently using

SELECT
t.TId AS thread_id,
t.TName AS thread_name,
t.TAuthorId AS thread_author_id,
u2.UName AS thread_author_name,
t.TDeleted AS thread_deleted_boolean,

/* This might slow down things */
(SELECT COUNT(forum_posts.PId) FROM forum_posts WHERE forum_posts.TId = t.TId) AS thread_posts,
(SELECT CEIL(COUNT(forum_posts.PId) / 20) FROM forum_posts WHERE forum_posts.TId = t.TId) AS thread_pages,
/* This might slow down things */

p.PId AS lastpost_id,
FROM_UNIXTIME(p.PDate/1000) AS lastpost_date,
p.PAuthorId AS lastpost_author_id,
u.UName AS lastpost_author_name

FROM forum_posts AS p

LEFT JOIN forum_threads AS t
ON t.TId = p.TId

/*
* Not used
LEFT JOIN forum_users AS u
ON t.TAuthorId = u.UId OR p.PAuthorId = u.UId
*/

LEFT JOIN forum_users AS u
ON p.PAuthorId = u.UId

LEFT JOIN forum_users AS u2
ON t.TAuthorId = u2.UId

ORDER BY p.PId DESC
LIMIT 50

This one is relatively fast, the thread author id and the lastpost author id are different and work just fine, the problem is that the threads are shown multiple times (duplicated). I've tried adding a

GROUP BY t.TId

near the end but it just makes the query never finish loading.

Is this a indexing problem?

It's worth noting that it would be nice if I could change what I order by and what I limit by dynamically...

query += `LIMIT ` + ((page - 1) * (THREADS_SHOWN_PER_PAGE)) + `,` + THREADS_SHOWN_PER_PAGE;

Also, it's not a big deal if the user is null, the way I'm inserting things in the database sometimes the user is created after the post/thread.