问:
Using Distinct with LINQ and Objects
Until recently, I was using a Distinct in LINQ to select a distinct category (an enum) from a table. This was working fine.

I now need to have it distinct on a class containing a category and country (both enums). The Distinct isn't working now.

What am I doing wrong?

答:
For explanation, take a look at other answers. I'm just providing one way to handle this issue.

You might like this:

```<code>public class LambdaComparer<T>:IEqualityComparer<T>{
  private readonly Func<T,T,bool> _comparer;
  private readonly Func<T,int> _hash;
  public LambdaComparer(Func<T,T,bool> comparer):
    this(comparer,o=>0) {}
  public LambdaComparer(Func<T,T,bool> comparer,Func<T,int> hash){
    if(comparer==null) throw new ArgumentNullException("comparer");
    if(hash==null) throw new ArgumentNullException("hash");
    _comparer=comparer;
    _hash=hash;
  }
  public bool Equals(T x,T y){
    return _comparer(x,y);
  }
  public int GetHashCode(T obj){
    return _hash(obj);
  }
}
</code>```

Usage:

```<code>public void Foo{
  public string Fizz{get;set;}
  public BarEnum Bar{get;set;}
}

public enum BarEnum {One,Two,Three}

var lst=new List<Foo>();
lst.Distinct(new LambdaComparer<Foo>(
  (x1,x2)=>x1.Fizz==x2.Fizz&&
           x1.Bar==x2.Bar));
</code>```

You can even wrap it around to avoid writing noisy new LambdaComparer<T>(...) thing:

```<code>public static class EnumerableExtensions{
 public static IEnumerable<T> SmartDistinct<T>
  (this IEnumerable<T> lst, Func<T, T, bool> pred){
   return lst.Distinct(new LambdaComparer<T>(pred));
 }
}
</code>```

Usage:

```<code>lst.SmartDistinct((x1,x2)=>x1.Fizz==x2.Fizz&&x1.Bar==x2.Bar);
</code>```

NB: works reliably only for Linq2Objects

Title: Using Distinct with LINQ and Objects

Body:
For explanation, take a look at other answers. I'm just providing one way to handle this issue.

You might like this:

public class LambdaComparer<T>:IEqualityComparer<T>{
  private readonly Func<T,T,bool> _comparer;
  private readonly Func<T,int> _hash;
  public LambdaComparer(Func<T,T,bool> comparer):
    this(comparer,o=>0) {}
  public LambdaComparer(Func<T,T,bool> comparer,Func<T,int> hash){
    if(comparer==null) throw new ArgumentNullException("comparer");
    if(hash==null) throw new ArgumentNullException("hash");
    _comparer=comparer;
    _hash=hash;
  }
  public bool Equals(T x,T y){
    return _comparer(x,y);
  }
  public int GetHashCode(T obj){
    return _hash(obj);
  }
}

Usage:

public void Foo{
  public string Fizz{get;set;}
  public BarEnum Bar{get;set;}
}

public enum BarEnum {One,Two,Three}

var lst=new List<Foo>();
lst.Distinct(new LambdaComparer<Foo>(
  (x1,x2)=>x1.Fizz==x2.Fizz&&
           x1.Bar==x2.Bar));

You can even wrap it around to avoid writing noisy new LambdaComparer<T>(...) thing:

public static class EnumerableExtensions{
 public static IEnumerable<T> SmartDistinct<T>
  (this IEnumerable<T> lst, Func<T, T, bool> pred){
   return lst.Distinct(new LambdaComparer<T>(pred));
 }
}

Usage:

lst.SmartDistinct((x1,x2)=>x1.Fizz==x2.Fizz&&x1.Bar==x2.Bar);

NB: works reliably only for Linq2Objects


来源: stackexchange

问:
Arithmetic-static Variables error
```<code>import java.util.*;
import java.math.*;

public class Arithmectic {

    double mealCost;
    int tipPercent;
    int taxPercent;

    public Arithmectic(double inMeal, int inTip, int inTax){

    Scanner scan = new Scanner(System.in);

    inMeal = scan.nextDouble();
    mealCost = inMeal;

    inTip = scan.nextInt();
    tipPercent = inTip;

    inTax = scan.nextInt();
    taxPercent = inTax;

    }

    public void printValues(){

    System.out.println(mealCost);
    System.out.println(tipPercent);
    System.out.println(taxPercent);
    }

 public static void main(String[] args) {

     Arithmectic rest = new Arithmectic(mealCost, tipPercent, taxPercent);

 }
}
</code>```

**Am having an issue with

```<code>Arithmectic rest = new Arithmectic(mealCost, tipPercent, taxPercent);
</code>```

Can someone help me and explain why am i having this error ?**

答:
If your main is in the same class (i.e. Arithmectic) you are trying to access the instance variables of that class in order to pass them to the constructor of that class.

It makes no sense and cannot be done anyway (you can't access instance variables from a static context).

If your constructor is initializing the members from user input, it doesn't need to get those parameters from the outside.

That said, it would make more sense to get the user input in your main and pass it to the constructor:

```<code>public Arithmectic(double inMeal, int inTip, int inTax){
    mealCost = inMeal;
    tipPercent = inTip;
    taxPercent = inTax;
}

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    double inMeal = scan.nextDouble();
    int inTip = scan.nextInt();
    int inTax = scan.nextInt();
    Arithmectic rest = new Arithmectic(inMeal, inTip, inTax);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Arithmetic-static Variables error

Body:
import java.util.*;
import java.math.*;

public class Arithmectic {

    double mealCost;
    int tipPercent;
    int taxPercent;

    public Arithmectic(double inMeal, int inTip, int inTax){

    Scanner scan = new Scanner(System.in);

    inMeal = scan.nextDouble();
    mealCost = inMeal;

    inTip = scan.nextInt();
    tipPercent = inTip;

    inTax = scan.nextInt();
    taxPercent = inTax;

    }

    public void printValues(){

    System.out.println(mealCost);
    System.out.println(tipPercent);
    System.out.println(taxPercent);
    }

 public static void main(String[] args) {

     Arithmectic rest = new Arithmectic(mealCost, tipPercent, taxPercent);

 }
}

**Am having an issue with

Arithmectic rest = new Arithmectic(mealCost, tipPercent, taxPercent);

Can someone help me and explain why am i having this error ?**

Body:
If your main is in the same class (i.e. Arithmectic) you are trying to access the instance variables of that class in order to pass them to the constructor of that class.

It makes no sense and cannot be done anyway (you can't access instance variables from a static context).

If your constructor is initializing the members from user input, it doesn't need to get those parameters from the outside.

That said, it would make more sense to get the user input in your main and pass it to the constructor:

public Arithmectic(double inMeal, int inTip, int inTax){
    mealCost = inMeal;
    tipPercent = inTip;
    taxPercent = inTax;
}

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    double inMeal = scan.nextDouble();
    int inTip = scan.nextInt();
    int inTax = scan.nextInt();
    Arithmectic rest = new Arithmectic(inMeal, inTip, inTax);
}


问:
Image at center
I am coding a website in which I want the image to be in the center at all size of screens.

I tried:-

    <title></title>

    <form id="form1">

    </form>

```
</div>
</div>
</p>

<p>The above code couldn't give me success.</p>

<p>Please help me out!</p>

<p>Please share your codes for the same.</p>

<p>I am not able to center the image with my code so please help me out.</p>

<p>CSS is:-</p>

```
```

答:
try this code

```<code>    img
    {
      display:block;
      margin:auto;
      max-width:100%;
    }
</code>```

all images are center aligned.

Title: Image at center

Body:
I am coding a website in which I want the image to be in the center at all size of screens.

I tried:-

    <title></title>

    <form id="form1">

    </form>

The above code couldn't give me success.

Please help me out!

Please share your codes for the same.

I am not able to center the image with my code so please help me out.

CSS is:-

Body:
try this code

    img
    {
      display:block;
      margin:auto;
      max-width:100%;
    }

all images are center aligned.


问:
How do I create a link to pre-select a form option
I have the following code on another webpage on my site with a form (say on page index.html): JSFiddle

```<code><select class="select form-control" id="dropdown" name="dropdown" onchange="showForm()">
</code>```

i.e a dropdown form.

I want to have a link on another webpage that will go to this page, and have the "Sales" option already selected.

```<code><option value="1">
    Sales
</option>
</code>```

from the drop down menu (instead of the current default option), how do I create this?

答:
You must add some kind of router functionality with Javascript in your site.

I think the simplest thing you could do it to have a script in that page that checks the url if it has say a #bar hash like so: http://yoursite.com/foo.html#bar.

```<code><script>
// make sure you run this on DOM ready like in $.ready() in jQuery or in a script just before closing the body tag

if(window.location.hash === 'bar') {
  // add the selected attribute to the <option> you want
}
</script>
</code>```

Body:
I have the following code on another webpage on my site with a form (say on page index.html): JSFiddle

<select class="select form-control" id="dropdown" name="dropdown" onchange="showForm()">

i.e a dropdown form.

I want to have a link on another webpage that will go to this page, and have the "Sales" option already selected.

<option value="1">
    Sales
</option>

from the drop down menu (instead of the current default option), how do I create this?

Body:
You must add some kind of router functionality with Javascript in your site.

I think the simplest thing you could do it to have a script in that page that checks the url if it has say a #bar hash like so: http://yoursite.com/foo.html#bar.

<script>
// make sure you run this on DOM ready like in $.ready() in jQuery or in a script just before closing the body tag

if(window.location.hash === 'bar') {
  // add the selected attribute to the <option> you want
}
</script>


问:
I have a selection box with 5 option values. I want to repeat a table row based on the value I select from it
This is my select box code:

```<code><select class="form-control">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>
</code>```

This is the table row I want to repeat:

```<code><tr>
    <td><input type="text" class="form-control" name="" placeholder="Name"></td>
    <td><input type="text" class="form-control" name="" placeholder="Email"></td>
    <td><input type="text" class="form-control" name="" placeholder="Mobile No."></td>
</tr>
</code>```

答:
Write your Jquery like this -
Give an Id to your select box - </p>

```<code><select id="times" class="form-control">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>
</code>```

<p>I am assuming that your table has a class of tableData.
Now write Jquery - </p>

```<code>$(document).ready(function(){
     var row = '<tr>';
         row = row + '<td><input type="text" class="form-control" name="" placeholder="Name"></td>';
         row = row + '<td><input type="text" class="form-control" name="" placeholder="Email"></td>';
         row = row + '<td><input type="text" class="form-control" name="" placeholder="Mobile No."></td>';
         row = row + '</tr>';
     $("#times").change(function(){
        $(".tableData").html('');
        $(".tableData").html(row);
        var getTimes = $(this).val();
        for(var i = 0; i < getTimes; i++){
            $(".tableData").append(row);
        }
     });
});
</code>```

Body:
This is my select box code:

<select class="form-control">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>

This is the table row I want to repeat:

    <input type="text" class="form-control" name="" placeholder="Name">
    <input type="text" class="form-control" name="" placeholder="Email">
    <input type="text" class="form-control" name="" placeholder="Mobile No.">

Body:
Write your Jquery like this -
Give an Id to your select box -

<select id="times" class="form-control">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>

I am assuming that your table has a class of tableData.
Now write Jquery -

$(document).ready(function(){
     var row = '<tr>';
         row = row + '<td><input type="text" class="form-control" name="" placeholder="Name"></td>';
         row = row + '<td><input type="text" class="form-control" name="" placeholder="Email"></td>';
         row = row + '<td><input type="text" class="form-control" name="" placeholder="Mobile No."></td>';
         row = row + '</tr>';
     $("#times").change(function(){
        $(".tableData").html('');
        $(".tableData").html(row);
        var getTimes = $(this).val();
        for(var i = 0; i < getTimes; i++){
            $(".tableData").append(row);
        }
     });
});


问:
ASP.Net RequestValidation for json POST to match Form RequestValidation
I want to be able to do RequestValidation on content-type "application/json" in a consistent manner to Form validation ("application/x-www-form-urlencoded").

I've read https://msdn.microsoft.com/en-us/library/system.web.util.requestvalidator(v=vs.110).aspx but it hasn't been too much help.

I'm looking at trying to implement a custom request validator to replace the default System.Web.Util.RequestValidator.

I've also looked at https://msdn.microsoft.com/en-us/library/system.web.util.requestvalidator(v=vs.110).aspx

If I can't get the input to be consistently validated I will probably remove the ability to send json to the controllers and force everything through forms - not ideal as I'd like some methods to accept json.

I already encode the output (where possible) but I still want defense in depth by validating the input and ideally consistently for forms and json.

Unfortunately a lot of the MSDN docs on this are heavily out of date and now irrelevant.

I'm using .net 4.6.1 for reference.

Is it sensible to try and validate requests in this manner?

答:
In the end I've implemented a custom ModelBinder...this was a combination of reading this https://weblogs.asp.net/imranbaloch/security-issue-in-asp-net-mvc3-jsonvalueproviderfactory and this https://gist.github.com/jamescrowley/b8c0c006e7b00e28cbbf

It modifies the source of the request (RequestValidationSource.Form) to make it look like a form so it can be validated in the same pipeline.

```<code>public class JsonValidatingModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var result = base.BindModel(controllerContext, bindingContext);
        if (!IsJsonRequest(controllerContext))
        {
            return result;
        }
        if (!bindingContext.ModelMetadata.RequestValidationEnabled)
        {
            return result;
        }
        if (result != null)
        {
            EnsureRequestFieldIsValid(controllerContext, result);
        }
        return result;
    }

    static void EnsureRequestFieldIsValid(ControllerContext controllerContext, object result)
    {
        int index;
        // abusing RequestValidationSource enum
        if (!RequestValidator.Current.InvokeIsValidRequestString(
            controllerContext.HttpContext.ApplicationInstance.Context,
            result.ToString(), RequestValidationSource.Form, null, out index))
        {
            throw new HttpRequestValidationException(
                "A potentially dangerous value was detected from the client ");
        }
    }

    static bool IsJsonRequest(ControllerContext controllerContext)
    {
        return controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase);
    }
</code>```

and in the Global.asax...

```<code>    protected void Application_Start()
    {
        System.Web.Mvc.ModelBinders.Binders.DefaultBinder = new JsonValidatingModelBinder();

    }
</code>```

Body:
In the end I've implemented a custom ModelBinder...this was a combination of reading this https://weblogs.asp.net/imranbaloch/security-issue-in-asp-net-mvc3-jsonvalueproviderfactory and this https://gist.github.com/jamescrowley/b8c0c006e7b00e28cbbf

It modifies the source of the request (RequestValidationSource.Form) to make it look like a form so it can be validated in the same pipeline.

public class JsonValidatingModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var result = base.BindModel(controllerContext, bindingContext);
        if (!IsJsonRequest(controllerContext))
        {
            return result;
        }
        if (!bindingContext.ModelMetadata.RequestValidationEnabled)
        {
            return result;
        }
        if (result != null)
        {
            EnsureRequestFieldIsValid(controllerContext, result);
        }
        return result;
    }

    static void EnsureRequestFieldIsValid(ControllerContext controllerContext, object result)
    {
        int index;
        // abusing RequestValidationSource enum
        if (!RequestValidator.Current.InvokeIsValidRequestString(
            controllerContext.HttpContext.ApplicationInstance.Context,
            result.ToString(), RequestValidationSource.Form, null, out index))
        {
            throw new HttpRequestValidationException(
                "A potentially dangerous value was detected from the client ");
        }
    }

    static bool IsJsonRequest(ControllerContext controllerContext)
    {
        return controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase);
    }

and in the Global.asax...

    protected void Application_Start()
    {
        System.Web.Mvc.ModelBinders.Binders.DefaultBinder = new JsonValidatingModelBinder();

    }


问:
Set Visibility not working on Image View
Why is my imageView not becoming visible with the checkingBalance = $1200 or more?

I have it set to invisible in the XML file. I essentially want the ivArrow ImageView to only appear visible IF my checkingBalance is over $1199.99.

```<code>public class MainActivity extends AppCompatActivity {

    ImageView ivArrow;
    TextView tvCheckingBalance;
    TextView tvInvestmentsBalance;
    TextView tvPayRate;
    TextView tvToday;
    TextView tvWorkBalance;
    Button btnWork;

    boolean runInitialize = true;
    float checkingBalance;
    float investmentsBalance;
    float payRate;
    float workBalance;
    int today;
    int weekDay;
    int workPercent;

    DecimalFormat dollarFormat = new DecimalFormat("#,###.00");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences settings = getSharedPreferences("com.vuvaia.lifeofme", MODE_PRIVATE);
        runInitialize = settings.getBoolean("runInitialize", runInitialize);

        if (runInitialize) {
            initialize();
            loadSettings();
        } else {
            loadSettings();
        }

        // INITIALIZING VIEW SETUP
        ivArrow = (ImageView) findViewById(R.id.ivArrow);
        tvCheckingBalance = (TextView) findViewById(R.id.tvCheckingBalance);
        tvCheckingBalance.setText("$" + dollarFormat.format(checkingBalance));
        tvInvestmentsBalance = (TextView) findViewById(R.id.tvInvestmentBalance);
        tvInvestmentsBalance.setText("$" + dollarFormat.format(investmentsBalance));
        tvPayRate = (TextView) findViewById(R.id.tvPayRate);
        tvPayRate.setText("$" + dollarFormat.format(payRate) + "/hr");
        tvToday = (TextView) findViewById(R.id.tvToday);
        tvToday.setText(String.valueOf(today));
        tvWorkBalance = (TextView) findViewById(R.id.tvWorkBalance);
        tvWorkBalance.setText("$" + dollarFormat.format(workBalance));

        btnWork = (Button) findViewById(R.id.btnWork);

        btnWork.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                workButtonPressed();
            }
        });

        // TODO SET UP THIS ARROW THAT TRANSFERS MONEY TO INVESTMENTS
        if(checkingBalance > 1199.99f) {
            ivArrow.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadSettings();
    }

    @Override
    protected void onPause() {
        super.onPause();
        saveSettings();
    }

    // WORK BUTTON PRESSED ACTIONS **************************************************
    public void workButtonPressed(){
        if(workPercent < 100){
            workBalance += (payRate * .4);
            tvWorkBalance.setText("$" + dollarFormat.format(workBalance));
            workPercent ++;
            advanceDays();
        } else {
            checkingBalance = checkingBalance + workBalance;
            tvCheckingBalance.setText("$" + dollarFormat.format(checkingBalance));
            workPercent = 0;
            workBalance = 0.0f;
            tvWorkBalance.setText("$" + dollarFormat.format(workBalance));
            today += 2;
            weekDay = 0;
            tvToday.setText(String.valueOf(today));
        }
    }
    // WORK BUTTON PRESSED ACTIONS **************************************************

    // ADVANCING THE CALENDAR DAYS **************************************************
    public void advanceDays(){
        if(weekDay <= 17){
            weekDay ++;
        } else {
            weekDay = 0;
            today ++;
            tvToday.setText(String.valueOf(today));
        }
    }
    // ADVANCING THE CALENDAR DAYS **************************************************

    // LOADING AND SAVING **************************************************
    public void initialize(){
        checkingBalance = 0.00f;
        investmentsBalance = 0.00f;
        payRate = 7.57f;
        today = 0;
        weekDay = 0;
        workBalance = 0.00f;
        workPercent = 0;

        saveSettings();
    }
    public void saveSettings(){
        SharedPreferences settings = getSharedPreferences("com.vuvaia.lifeofme", MODE_PRIVATE);
        settings.edit().putFloat("checkingBalance", checkingBalance).commit();
        settings.edit().putFloat("investmentsBalance", investmentsBalance).commit();
        settings.edit().putFloat("payRate", payRate).commit();
        settings.edit().putBoolean("runInitialize", false).commit();
        settings.edit().putInt("today", today).commit();
        settings.edit().putInt("weekDay", weekDay).commit();
        settings.edit().putFloat("workBalance", workBalance).commit();
        settings.edit().putInt("workPercent", workPercent).commit();
    }
    public void loadSettings(){
        SharedPreferences settings = getSharedPreferences("com.vuvaia.lifeofme", MODE_PRIVATE);
        checkingBalance = settings.getFloat("checkingBalance", checkingBalance);
        investmentsBalance = settings.getFloat("investmentsBalance", investmentsBalance);
        payRate = settings.getFloat("payRate", payRate);
        runInitialize = settings.getBoolean("runInitialize", runInitialize);
        today = settings.getInt("today", today);
        weekDay = settings.getInt("weekDay", weekDay);
        workBalance = settings.getFloat("workBalance", workBalance);
        workPercent = settings.getInt("workPercent", workPercent);
    }
    // LOADING AND SAVING **************************************************
}
</code>```

XML File:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#EEEEEE"
    tools:context="com.vuvaia.lifeofme.MainActivity">

    <Button
        android:id="@+id/btnWork"
        android:layout_width="0dp"
        android:layout_height="75dp"
        android:background="#2A2A2A"
        android:text="Work"
        android:textColor="#EEEEEE"
        android:textSize="30sp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="32dp" />

    <TextView
        android:id="@+id/tvWorkBalance"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="#2A2A2A"
        android:textColor="#EEEEEE"
        android:textSize="30sp"
        android:textAlignment="center"
        android:layout_marginBottom="8dp"
        android:paddingBottom="15dp"
        android:paddingTop="15dp"
        app:layout_constraintBottom_toTopOf="@+id/btnWork"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent" />

    <TextView
        android:id="@+id/tvPayRate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#2A2A2A"
        android:layout_marginTop="16dp"
        app:layout_constraintTop_toBottomOf="@+id/tvWorkBalance"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent" />

    <TextView
        android:id="@+id/tvCheckingBalance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#2A2A2A"
        android:textSize="15sp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="32dp" />

    <TextView
        android:id="@+id/tvToday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#2A2A2A"
        android:textSize="15sp"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="32dp"
        android:layout_marginLeft="32dp"
        app:layout_constraintLeft_toLeftOf="parent" />

    <TextView
        android:id="@+id/tvInvestmentBalance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#2A2A2A"
        android:textSize="15sp"
        android:layout_marginRight="32dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="32dp" />

    <ImageView
        android:id="@+id/ivArrow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="invisible"
        app:srcCompat="@drawable/ic_arrow"
        android:layout_marginTop="8dp"
        app:layout_constraintTop_toBottomOf="@+id/tvCheckingBalance"
        app:layout_constraintLeft_toRightOf="@+id/tvCheckingBalance"
        android:layout_marginLeft="8dp" />
</android.support.constraint.ConstraintLayout>
</code>```

答:
add Visibility code inside onClick of btnWork

```<code>btnWork.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            workButtonPressed();
           // TODO SET UP THIS ARROW THAT TRANSFERS MONEY TO INVESTMENTS

          if(checkingBalance > 1199.99f) {
              ivArrow.setVisibility(View.VISIBLE);
          }
        }
    });
</code>```

Body:
Why is my imageView not becoming visible with the checkingBalance = $1200 or more?

I have it set to invisible in the XML file. I essentially want the ivArrow ImageView to only appear visible IF my checkingBalance is over $1199.99.

public class MainActivity extends AppCompatActivity {

    ImageView ivArrow;
    TextView tvCheckingBalance;
    TextView tvInvestmentsBalance;
    TextView tvPayRate;
    TextView tvToday;
    TextView tvWorkBalance;
    Button btnWork;

    boolean runInitialize = true;
    float checkingBalance;
    float investmentsBalance;
    float payRate;
    float workBalance;
    int today;
    int weekDay;
    int workPercent;

    DecimalFormat dollarFormat = new DecimalFormat("#,###.00");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences settings = getSharedPreferences("com.vuvaia.lifeofme", MODE_PRIVATE);
        runInitialize = settings.getBoolean("runInitialize", runInitialize);

        if (runInitialize) {
            initialize();
            loadSettings();
        } else {
            loadSettings();
        }

        // INITIALIZING VIEW SETUP
        ivArrow = (ImageView) findViewById(R.id.ivArrow);
        tvCheckingBalance = (TextView) findViewById(R.id.tvCheckingBalance);
        tvCheckingBalance.setText("$" + dollarFormat.format(checkingBalance));
        tvInvestmentsBalance = (TextView) findViewById(R.id.tvInvestmentBalance);
        tvInvestmentsBalance.setText("$" + dollarFormat.format(investmentsBalance));
        tvPayRate = (TextView) findViewById(R.id.tvPayRate);
        tvPayRate.setText("$" + dollarFormat.format(payRate) + "/hr");
        tvToday = (TextView) findViewById(R.id.tvToday);
        tvToday.setText(String.valueOf(today));
        tvWorkBalance = (TextView) findViewById(R.id.tvWorkBalance);
        tvWorkBalance.setText("$" + dollarFormat.format(workBalance));

        btnWork = (Button) findViewById(R.id.btnWork);

        btnWork.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                workButtonPressed();
            }
        });

        // TODO SET UP THIS ARROW THAT TRANSFERS MONEY TO INVESTMENTS
        if(checkingBalance > 1199.99f) {
            ivArrow.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadSettings();
    }

    @Override
    protected void onPause() {
        super.onPause();
        saveSettings();
    }

    // WORK BUTTON PRESSED ACTIONS **************************************************
    public void workButtonPressed(){
        if(workPercent < 100){
            workBalance += (payRate * .4);
            tvWorkBalance.setText("$" + dollarFormat.format(workBalance));
            workPercent ++;
            advanceDays();
        } else {
            checkingBalance = checkingBalance + workBalance;
            tvCheckingBalance.setText("$" + dollarFormat.format(checkingBalance));
            workPercent = 0;
            workBalance = 0.0f;
            tvWorkBalance.setText("$" + dollarFormat.format(workBalance));
            today += 2;
            weekDay = 0;
            tvToday.setText(String.valueOf(today));
        }
    }
    // WORK BUTTON PRESSED ACTIONS **************************************************

    // ADVANCING THE CALENDAR DAYS **************************************************
    public void advanceDays(){
        if(weekDay <= 17){
            weekDay ++;
        } else {
            weekDay = 0;
            today ++;
            tvToday.setText(String.valueOf(today));
        }
    }
    // ADVANCING THE CALENDAR DAYS **************************************************

    // LOADING AND SAVING **************************************************
    public void initialize(){
        checkingBalance = 0.00f;
        investmentsBalance = 0.00f;
        payRate = 7.57f;
        today = 0;
        weekDay = 0;
        workBalance = 0.00f;
        workPercent = 0;

        saveSettings();
    }
    public void saveSettings(){
        SharedPreferences settings = getSharedPreferences("com.vuvaia.lifeofme", MODE_PRIVATE);
        settings.edit().putFloat("checkingBalance", checkingBalance).commit();
        settings.edit().putFloat("investmentsBalance", investmentsBalance).commit();
        settings.edit().putFloat("payRate", payRate).commit();
        settings.edit().putBoolean("runInitialize", false).commit();
        settings.edit().putInt("today", today).commit();
        settings.edit().putInt("weekDay", weekDay).commit();
        settings.edit().putFloat("workBalance", workBalance).commit();
        settings.edit().putInt("workPercent", workPercent).commit();
    }
    public void loadSettings(){
        SharedPreferences settings = getSharedPreferences("com.vuvaia.lifeofme", MODE_PRIVATE);
        checkingBalance = settings.getFloat("checkingBalance", checkingBalance);
        investmentsBalance = settings.getFloat("investmentsBalance", investmentsBalance);
        payRate = settings.getFloat("payRate", payRate);
        runInitialize = settings.getBoolean("runInitialize", runInitialize);
        today = settings.getInt("today", today);
        weekDay = settings.getInt("weekDay", weekDay);
        workBalance = settings.getFloat("workBalance", workBalance);
        workPercent = settings.getInt("workPercent", workPercent);
    }
    // LOADING AND SAVING **************************************************
}

XML File:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#EEEEEE"
    tools:context="com.vuvaia.lifeofme.MainActivity">

    <Button
        android:id="@+id/btnWork"
        android:layout_width="0dp"
        android:layout_height="75dp"
        android:background="#2A2A2A"
        android:text="Work"
        android:textColor="#EEEEEE"
        android:textSize="30sp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="32dp" />

    <TextView
        android:id="@+id/tvWorkBalance"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="#2A2A2A"
        android:textColor="#EEEEEE"
        android:textSize="30sp"
        android:textAlignment="center"
        android:layout_marginBottom="8dp"
        android:paddingBottom="15dp"
        android:paddingTop="15dp"
        app:layout_constraintBottom_toTopOf="@+id/btnWork"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent" />

    <TextView
        android:id="@+id/tvPayRate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#2A2A2A"
        android:layout_marginTop="16dp"
        app:layout_constraintTop_toBottomOf="@+id/tvWorkBalance"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent" />

    <TextView
        android:id="@+id/tvCheckingBalance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#2A2A2A"
        android:textSize="15sp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="32dp" />

    <TextView
        android:id="@+id/tvToday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#2A2A2A"
        android:textSize="15sp"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="32dp"
        android:layout_marginLeft="32dp"
        app:layout_constraintLeft_toLeftOf="parent" />

    <TextView
        android:id="@+id/tvInvestmentBalance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#2A2A2A"
        android:textSize="15sp"
        android:layout_marginRight="32dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="32dp" />

    <ImageView
        android:id="@+id/ivArrow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="invisible"
        app:srcCompat="@drawable/ic_arrow"
        android:layout_marginTop="8dp"
        app:layout_constraintTop_toBottomOf="@+id/tvCheckingBalance"
        app:layout_constraintLeft_toRightOf="@+id/tvCheckingBalance"
        android:layout_marginLeft="8dp" />
</android.support.constraint.ConstraintLayout>

Body:
add Visibility code inside onClick of btnWork

btnWork.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            workButtonPressed();
           // TODO SET UP THIS ARROW THAT TRANSFERS MONEY TO INVESTMENTS

          if(checkingBalance > 1199.99f) {
              ivArrow.setVisibility(View.VISIBLE);
          }
        }
    });


问:
Using typescript module without require()
I write a typescript 2.3 app.ts which needs Vuejs library v2.
Vuejs script src is added manually in html file.
I just want use Vuejs with type checking !
I expected i just have to reference like this :

/// < reference path="vue.d.ts" />

But the Vue class is not accessible from app.ts.

I tried to import the module directly :

import * as Vue from "./vue";

This time i have to use new Vue.Vue({}) to access to the class but VS 2017 build.
The app.js generated starts with var Vue = require("./vue");.
However in the browser, i got some errors :

exports reference (solved by adding export = 0; at line 1 in .ts

require is not a function

For require(), i add < script src="Scripts/require.js">< /script> but new error: has not been loaded yet for context.

I tried with systemjs instead of require.js, i add < script>System.import('scripts/app.js');< /script> i get a 404 accessing to "Scripts/vue" (the require from the app.js), the rest of app.js is not executed.

Note : i don't use tsconfig.json

I'm surprised cause in my memory, the reference of jQuery worked with typescript 0.9

I'm completely lost. Help me ! Thank you community !

答:
I typically work around the issue you ran into by creating globals.d.ts file which is responsible to setting up the global environment that my code expects. In your case something like:

```<code>import * as _Vue from "vue";

declare global {
    const Vue: typeof _Vue;
}
</code>```

This makes it so that the compiler will see a Vue symbol in the global space which is of the same type as what the "vue" module exports.

With the above file, this compiles:

```<code>const q = new Vue();
</code>```

Note that you either will have to use a tsconfig.json. Even an empty one works. (By "empty", I mean a file that contains only an empty JSON structure: {}.) Or you will have to list all files to compile, including globals.d.ts at the command line.

Body:
I typically work around the issue you ran into by creating globals.d.ts file which is responsible to setting up the global environment that my code expects. In your case something like:

import * as _Vue from "vue";

declare global {
    const Vue: typeof _Vue;
}

This makes it so that the compiler will see a Vue symbol in the global space which is of the same type as what the "vue" module exports.

With the above file, this compiles:

const q = new Vue();

Note that you either will have to use a tsconfig.json. Even an empty one works. (By "empty", I mean a file that contains only an empty JSON structure: {}.) Or you will have to list all files to compile, including globals.d.ts at the command line.


问:
Strange groupby/Dataframe behavior with list ()
I needed to build a dict of selected values in groups built from a dataframe ("grouped"). idcolumn was a list of one string ["column_name"] (I made it a list because at some point, I needed to append various other strings/columns name for operations using labels).

so I used as a mean to retrieve the groups this statement:

```<code>grouped.get_group(k).loc[:,idcolumn]
</code>```

which works perfectly identically to

```<code>grouped.get_group(k).loc[:,idcolumn[0]]
</code>```

outputting a dataframe of the selected data with ["column_name"] as header.

My complete expression was:

```<code>dict_to_build= {k: list(grouped.get_group(k).loc[:,idcolumn]) for k in grouped.groups.keys() }
</code>```

but I had a very strange error.

the built dict contains all the keys but as a unique value "column_name".
While if I use

```<code>dict_to_build= {k: list(grouped.get_group(k).loc[:,idcolumn[0]) for k in grouped.groups.keys() }
</code>```

The dict is perfectly ok.

as examplified like this:

```<code>In [115]: pde=pd.DataFrame({"a":[1,2,3,1,2,3], "column_name":["a","b","c","d","e","f"]})

In [116]: pde
Out[116]:
   a column_name
0  1           a
1  2           b
2  3           c
3  1           d
4  2           e
5  3           f

In [117]: grouped=pde.groupby[1]
Traceback (most recent call last):

  File "<ipython-input-117-b504dadfee12>", line 1, in <module>
    grouped=pde.groupby[1]

TypeError: 'method' object is not subscriptable

In [118]: grouped=pde.groupby("a")

In [119]: grouped.get_group(1).loc[:,"column_name"]
Out[119]:
0    a
3    d
Name: column_name, dtype: object

In [120]: list(grouped.get_group(1).loc[:,"column_name"])
Out[120]: ['a', 'd']

In [121]: list(grouped.get_group(1).loc[:,["column_name"]])
Out[121]: ['column_name']
</code>```

Can someone enlighten me about what is happening? It is absolutely strange for me. Does the problem comes from dataframes, loc with list as a parameter, or the list function?

答:
I think the reason is

```<code>grouped.get_group(1).loc[:,"column_name"]
</code>```

returns a Series while

```<code>grouped.get_group(1).loc[:,["column_name"]]
</code>```

returns a Dataframe.

When you do list(Series), it returns the values of the Series, while when you do a list(Dataframe), it returns the columns of the df, in this case 'column_name'.

Body:
I needed to build a dict of selected values in groups built from a dataframe ("grouped"). idcolumn was a list of one string ["column_name"] (I made it a list because at some point, I needed to append various other strings/columns name for operations using labels).

so I used as a mean to retrieve the groups this statement:

grouped.get_group(k).loc[:,idcolumn]

which works perfectly identically to

grouped.get_group(k).loc[:,idcolumn[0]]

outputting a dataframe of the selected data with ["column_name"] as header.

My complete expression was:

dict_to_build= {k: list(grouped.get_group(k).loc[:,idcolumn]) for k in grouped.groups.keys() }

but I had a very strange error.

the built dict contains all the keys but as a unique value "column_name".
While if I use

dict_to_build= {k: list(grouped.get_group(k).loc[:,idcolumn[0]) for k in grouped.groups.keys() }

The dict is perfectly ok.

as examplified like this:

In [115]: pde=pd.DataFrame({"a":[1,2,3,1,2,3], "column_name":["a","b","c","d","e","f"]})

In [116]: pde
Out[116]:
   a column_name
0  1           a
1  2           b
2  3           c
3  1           d
4  2           e
5  3           f

In [117]: grouped=pde.groupby[1]
Traceback (most recent call last):

  File "<ipython-input-117-b504dadfee12>", line 1, in <module>
    grouped=pde.groupby[1]

TypeError: 'method' object is not subscriptable

In [118]: grouped=pde.groupby("a")

In [119]: grouped.get_group(1).loc[:,"column_name"]
Out[119]:
0    a
3    d
Name: column_name, dtype: object

In [120]: list(grouped.get_group(1).loc[:,"column_name"])
Out[120]: ['a', 'd']

In [121]: list(grouped.get_group(1).loc[:,["column_name"]])
Out[121]: ['column_name']

Can someone enlighten me about what is happening? It is absolutely strange for me. Does the problem comes from dataframes, loc with list as a parameter, or the list function?

Body:
I think the reason is

grouped.get_group(1).loc[:,"column_name"]

returns a Series while

grouped.get_group(1).loc[:,["column_name"]]

returns a Dataframe.

When you do list(Series), it returns the values of the Series, while when you do a list(Dataframe), it returns the columns of the df, in this case 'column_name'.


问:
How to insert row with MAX(number) + 1 in PostgreSQL transactionally without sequence
I have a PostgreSQL table that can be simplified as this:

```<code>CREATE TABLE car(
  garage_id uuid,
  number integer
);
</code>```

I need that in each garage, each car has a unique integer number (Car N°1, Car N°2).

First idea with sequence

My first idea was to create a PostgreSQL sequence for each garage thanks to a trigger, and then when I insert a car, I just need to call nextval on the sequence created for the garage. (Like seen here)

The problem is that for each garage, I need to create a sequence. My garage table will soon grow up to 1M rows, and according to this thread: Maximum number of sequences that can be created, too much PostgreSQL sequence can really hurt performance and make pgdump fails.

Second Idea

I found another idea on stackoverflow.

The second idea was to create another table like

```<code>CREATE TABLE garage_number(
  garage_id uuid,
  max_number integer
);
</code>```

This table would keep the max car number, and then at each insert we select the max_number of the garage, and update the max_number of the garage.

Problem: For the moment it does not work in terms of concurrency (2 cars can have the same number if inserted at the same time).

Do you have any idea of how I can make this be transaction-proof and work at scale? Maybe locking the garage_number table?

Thank you very much for your help,

答:
"how I can make this be transaction-proof and work at scale" - you can't. The best bet is to minimize the locking that is needed when you generate the numbers via the non-sequence approach.

Your garage_number table can be used for that, however I wouldn't actually use the max() on the actual garage table, but rather something like this:

```<code>create or replace function next_car_number(p_garage uuid)
  returns integer
as
$$
  update garage_number
     set max_number = max_number + 1
  where garage_id = p_garage
  returning max_number;
$$
language sql;
</code>```

Of course you would need to initialize the garage_number once, and you also need to insert a new row into that table each time a new garage is created (with a value of 0 for max_number)

Then to assign a new car number, you can use something like this:

```<code>insert into car
  (garage, number)
values
  ('a0ee-bc99-9c0b-4ef8-bb6d-6bb9-bd38-0a11', next_car_number('a0ee-bc99-9c0b-4ef8-bb6d-6bb9-bd38-0a11'));
</code>```

The row for that garage will be locked until that insert is committed and no other insert using the same function can finish until then. Once that is committed any waiting transaction will see the new value.

You need to generate (and know) the UUID for the garage before you insert a new car - but I guess as there is another table named garage that is referenced by the car table, the garage PK is already know when inserting a new car.

This still serializes access to the "generator" for a single garage, but will be faster then running a max() query for each insert

Body:
I have a PostgreSQL table that can be simplified as this:

CREATE TABLE car(
  garage_id uuid,
  number integer
);

I need that in each garage, each car has a unique integer number (Car N°1, Car N°2).

First idea with sequence

My first idea was to create a PostgreSQL sequence for each garage thanks to a trigger, and then when I insert a car, I just need to call nextval on the sequence created for the garage. (Like seen here)

The problem is that for each garage, I need to create a sequence. My garage table will soon grow up to 1M rows, and according to this thread: Maximum number of sequences that can be created, too much PostgreSQL sequence can really hurt performance and make pgdump fails.

Second Idea

I found another idea on stackoverflow.

The second idea was to create another table like

CREATE TABLE garage_number(
  garage_id uuid,
  max_number integer
);

This table would keep the max car number, and then at each insert we select the max_number of the garage, and update the max_number of the garage.

Problem: For the moment it does not work in terms of concurrency (2 cars can have the same number if inserted at the same time).

Do you have any idea of how I can make this be transaction-proof and work at scale? Maybe locking the garage_number table?

Thank you very much for your help,

Body:
"how I can make this be transaction-proof and work at scale" - you can't. The best bet is to minimize the locking that is needed when you generate the numbers via the non-sequence approach.

Your garage_number table can be used for that, however I wouldn't actually use the max() on the actual garage table, but rather something like this:

create or replace function next_car_number(p_garage uuid)
  returns integer
as
$$
  update garage_number
     set max_number = max_number + 1
  where garage_id = p_garage
  returning max_number;
$$
language sql;

Of course you would need to initialize the garage_number once, and you also need to insert a new row into that table each time a new garage is created (with a value of 0 for max_number)

Then to assign a new car number, you can use something like this:

insert into car
  (garage, number)
values
  ('a0ee-bc99-9c0b-4ef8-bb6d-6bb9-bd38-0a11', next_car_number('a0ee-bc99-9c0b-4ef8-bb6d-6bb9-bd38-0a11'));

The row for that garage will be locked until that insert is committed and no other insert using the same function can finish until then. Once that is committed any waiting transaction will see the new value.

You need to generate (and know) the UUID for the garage before you insert a new car - but I guess as there is another table named garage that is referenced by the car table, the garage PK is already know when inserting a new car.

This still serializes access to the "generator" for a single garage, but will be faster then running a max() query for each insert


问:
CLLocationmanager "locationServicesEnabled" method deprecated in iOS 4?
I know the property locationServicesEnabled is deprecated in iOS 4. Instead, I should call locationServicesEnabled

In my app delegate method

```<code>-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //Some Code Here...
    CLLocationManager *manager = [[CLLocationManager alloc] init];
    if (![manager locationServicesEnabled])
    {   //show an alert
    }
 }
</code>```

I called the method, however, Xcode showed me a warning "locationServicesEnabled is deprecated". Anyone knows how to fix this? Because of the warning, if I turned off the location service in system preference, the alert view can't show.

Thanks!

答: So you just need to remove [(id)self.locationManager headingAvailable] and replace it with [CLLocationManager locationServicesEnabled] problem solved...

Body:
I know the property locationServicesEnabled is deprecated in iOS 4. Instead, I should call locationServicesEnabled

In my app delegate method

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //Some Code Here...
    CLLocationManager *manager = [[CLLocationManager alloc] init];
    if (![manager locationServicesEnabled])
    {   //show an alert
    }
 }

I called the method, however, Xcode showed me a warning "locationServicesEnabled is deprecated". Anyone knows how to fix this? Because of the warning, if I turned off the location service in system preference, the alert view can't show.

Thanks!


问:
SQL Query (Simple)
I would like to know how could a return the number of songs registred each year based on this table:

```<code>Musics={MusicID, SingerID, Recorder, YearOfRecord}
MusicID as PK
</code>```

Thanks for the attention

答:
```<code>SELECT Count(MusicID)
FROM Musics
GROUP BY YearOfRecord
</code>```

That query should work

ContentLicense: CC BY-SA 2.5

Title: SQL Query (Simple)

Body:
I would like to know how could a return the number of songs registred each year based on this table:

Musics={MusicID, SingerID, Recorder, YearOfRecord}
MusicID as PK

Thanks for the attention

Body:
SELECT Count(MusicID)
FROM Musics
GROUP BY YearOfRecord

That query should work


问:
Android new Intent with back button
In my Android App I use an empty activity with one button. If I push the button I call a new activity with an intent. But on the new activity the back button (top left) to jump back to the last page is missing. Isn't there already a activity template from android studio or a spezial intent call to do this? Or what is the best way to do this?

This is the function which is called on the button press

```<code>void scanClicked(View v){
    Intent intent = new Intent(this, ServiceActivity.class);
    startActivity(intent);
}
</code>```

The ServiceActivity is just an Empty Activity

```<code>    <activity
        android:name=".LoginActivity"
        android:label="@string/title_activity_login"
        android:theme="@style/SplashTheme"
        android:windowSoftInputMode="adjustPan">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".NavigationActivity"
        android:label="@string/title_activity_navigation"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity android:name=".ServiceActivity"
        android:label="@string/annualServiceTitle">
    </activity>
</code>```

答:
There are 2 options to do that.

Either you can use the android ToolBar in your XML
Adding toolbar

Or you can add a Layout which has a ImageButton aligned to the left of the layout. Then you can do this.

```<code>ImageButton backBtn;

backBtn = (ImageButton) findViewById(R.id.backBtn);
backBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onBackPressed();
        }
    });
</code>```

Hope this helps.

Title: Android new Intent with back button

Body:
In my Android App I use an empty activity with one button. If I push the button I call a new activity with an intent. But on the new activity the back button (top left) to jump back to the last page is missing. Isn't there already a activity template from android studio or a spezial intent call to do this? Or what is the best way to do this?

This is the function which is called on the button press

void scanClicked(View v){
    Intent intent = new Intent(this, ServiceActivity.class);
    startActivity(intent);
}

The ServiceActivity is just an Empty Activity

    <activity
        android:name=".LoginActivity"
        android:label="@string/title_activity_login"
        android:theme="@style/SplashTheme"
        android:windowSoftInputMode="adjustPan">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".NavigationActivity"
        android:label="@string/title_activity_navigation"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity android:name=".ServiceActivity"
        android:label="@string/annualServiceTitle">
    </activity>

Body:
There are 2 options to do that.

Either you can use the android ToolBar in your XML
Adding toolbar

Or you can add a Layout which has a ImageButton aligned to the left of the layout. Then you can do this.

ImageButton backBtn;

backBtn = (ImageButton) findViewById(R.id.backBtn);
backBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onBackPressed();
        }
    });

Hope this helps.


问:
Performing a bitwise sum
As part of a complex aggregate I want to know the bitwise sum of some data, i.e. if I have rows with values 1,1,1,2,2,8 the bitwise sum is 11. In this case the values are all exact powers of two (single bits), so I can hack around it by grouping and summing over the groups (obviously this example is a bit tortured compared to the real query):

```<code>select SUM(y.test)
from (
    select x.test
    from ( -- garbage test data
        select 1 as [test]
        union all select 1
        union all select 1
        union all select 2
        union all select 2
        union all select 8) x
group by x.test) y
</code>```

but is there a clean way to perform a bitwise sum in [T]SQL?

答:
Its a bit convoluted but this does what you're after (note that ive included bit's up to 128, you may need to go higher, or may not need to go any higher than 8).

```<code>with data(i)
AS
(
    select 1
        union all select 1
        union all select 1
        union all select 2
        union all select 2
        union all select 8
)
SELECT MAX(i & 1) +
MAX(i & 2) +
MAX(i & 4) +
MAX(i & 8) +
MAX(i & 16) +
MAX(i & 32) +
MAX(i & 64) +
MAX(i & 128)
from data
</code>```

which can obviously be converted to a UDF if you so desire.

Title: Performing a bitwise sum

Body:
As part of a complex aggregate I want to know the bitwise sum of some data, i.e. if I have rows with values 1,1,1,2,2,8 the bitwise sum is 11. In this case the values are all exact powers of two (single bits), so I can hack around it by grouping and summing over the groups (obviously this example is a bit tortured compared to the real query):

select SUM(y.test)
from (
    select x.test
    from ( -- garbage test data
        select 1 as [test]
        union all select 1
        union all select 1
        union all select 2
        union all select 2
        union all select 8) x
group by x.test) y

but is there a clean way to perform a bitwise sum in [T]SQL?

Body:
Its a bit convoluted but this does what you're after (note that ive included bit's up to 128, you may need to go higher, or may not need to go any higher than 8).

with data(i)
AS
(
    select 1
        union all select 1
        union all select 1
        union all select 2
        union all select 2
        union all select 8
)
SELECT MAX(i & 1) +
MAX(i & 2) +
MAX(i & 4) +
MAX(i & 8) +
MAX(i & 16) +
MAX(i & 32) +
MAX(i & 64) +
MAX(i & 128)
from data

which can obviously be converted to a UDF if you so desire.


问:
OmniAuth::NoSessionError - You must provide a session to use OmniAuth. (configured in devise)
Hi I am learning how to use omniauth as backend for ember app.

when i run my application I get the below mentioned erroe
OmniAuth::NoSessionError - You must provide a session to use OmniAuth

on resue rails s my applicataion halts at line below.

```<code>  172: def call!(env) # rubocop:disable CyclomaticComplexity
    173:   unless env['rack.session']
    174:     error = OmniAuth::NoSessionError.new('You must provide a session to use OmniAuth.')
 => 175:     fail(error)
    176:   end
    177:
</code>```

config/intializer/devise

```<code>Devise.setup do |config|

  config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com'
  require 'devise/orm/active_record'
  config.case_insensitive_keys = [ :email ]
  config.strip_whitespace_keys = [ :email ]
  config.http_authenticatable = true
  config.skip_session_storage = [:http_auth]
  config.stretches = Rails.env.test? ? 1 : 10
  config.reconfirmable = true
  config.expire_all_remember_me_on_sign_out = true
  config.password_length = 8..128
  config.reset_password_within = 6.hours
  config.http_authenticatable_on_xhr = false
  config.navigational_formats = ['*/*', :html,:json]
  config.sign_out_via = :delete
  require 'omniauth-facebook'
  config.omniauth :facebook, ENV['8987087080'] , ENV['3d6a359a37c8780870dxxxx5'],:strategy_class => OmniAuth::Strategies::Facebook
end
</code>```

config/intializer/session_store.rb

```<code>Rails.application.config.session_store :disabled
</code>```

routes.rb

```<code>Rails.application.routes.draw do

  namespace :api do
    namespace :v1 do
      resources :users
      resources :games
    end
  end

  ActiveAdmin.routes(self)
  #devise_for :admin_users, ActiveAdmin::Devise.config
  devise_for :users, controllers: {
    omniauth_callbacks: 'omniauth_callbacks',
    sessions: 'sessions' ,
    registrations: "registrations",

  }
   devise_scope :user do
    match 'users/sign_in', to: 'sessions#create', via: :post
    match 'api/v1/users' , to: 'registrations#create' , via: :post
  end

end
</code>```

gemfile.rb

```<code>source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.1.6'

platforms :ruby do # linux
  gem 'unicorn'
  gem 'foreman'
  gem 'delayed_job_active_record'
end
group :development, :test do
    gem 'compass'
    gem 'pry'
    gem 'pry-remote'
    gem 'pry-rails'
    gem 'pry-rescue'
    gem 'pry-stack_explorer'
    gem 'pry-byebug'
    gem 'guard'
    gem 'guard-livereload'
    gem 'guard-rails'
    gem 'guard-rspec'
    gem 'guard-cucumber'
    gem 'guard-zeus'
    gem 'rspec-rails'

end
group :production do
    #gem 'pg'
end

#authentication
gem 'cancan'
gem 'rolify'
gem 'devise'
gem 'omniauth'
gem 'omniauth-facebook', '=1.4.0'
gem 'oauth2'

# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.0'
gem 'bootstrap-sass', '~> 3.1.1'
gem 'bootswatch-rails'

# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'

# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'

group :doc do
  # bundle exec rake doc:rails generates the API under doc/api.
  gem 'sdoc', require: false
end

#ember
gem "active_model_serializers"
gem "ember-source", "~>1.7.0"

#asyc http calls
gem 'hashie_rails'
gem "typhoeus"
gem "virtus"

#middleware
gem "rack-cors", require: 'rack/cors'

platforms :mswin do
  gem "wdm", :group => [:development, :test]
end
#gem 'wdm', '>= 0.1.0'

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin]
</code>```

答:
Into application.rb

```<code>...

config.api_only = true
config.session_store :cookie_store, key: '_interslice_session'
config.middleware.use ActionDispatch::Cookies # Required for all session management
config.middleware.use ActionDispatch::Session::CookieStore, config.session_options
</code>```

Body:
Hi I am learning how to use omniauth as backend for ember app.

when i run my application I get the below mentioned erroe
OmniAuth::NoSessionError - You must provide a session to use OmniAuth

on resue rails s my applicataion halts at line below.

  172: def call!(env) # rubocop:disable CyclomaticComplexity
    173:   unless env['rack.session']
    174:     error = OmniAuth::NoSessionError.new('You must provide a session to use OmniAuth.')
 => 175:     fail(error)
    176:   end
    177:

config/intializer/devise

Devise.setup do |config|

  config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com'
  require 'devise/orm/active_record'
  config.case_insensitive_keys = [ :email ]
  config.strip_whitespace_keys = [ :email ]
  config.http_authenticatable = true
  config.skip_session_storage = [:http_auth]
  config.stretches = Rails.env.test? ? 1 : 10
  config.reconfirmable = true
  config.expire_all_remember_me_on_sign_out = true
  config.password_length = 8..128
  config.reset_password_within = 6.hours
  config.http_authenticatable_on_xhr = false
  config.navigational_formats = ['*/*', :html,:json]
  config.sign_out_via = :delete
  require 'omniauth-facebook'
  config.omniauth :facebook, ENV['8987087080'] , ENV['3d6a359a37c8780870dxxxx5'],:strategy_class => OmniAuth::Strategies::Facebook
end

config/intializer/session_store.rb

Rails.application.config.session_store :disabled

routes.rb

Rails.application.routes.draw do

  namespace :api do
    namespace :v1 do
      resources :users
      resources :games
    end
  end

  ActiveAdmin.routes(self)
  #devise_for :admin_users, ActiveAdmin::Devise.config
  devise_for :users, controllers: {
    omniauth_callbacks: 'omniauth_callbacks',
    sessions: 'sessions' ,
    registrations: "registrations",

  }
   devise_scope :user do
    match 'users/sign_in', to: 'sessions#create', via: :post
    match 'api/v1/users' , to: 'registrations#create' , via: :post
  end

end

gemfile.rb

source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.1.6'

platforms :ruby do # linux
  gem 'unicorn'
  gem 'foreman'
  gem 'delayed_job_active_record'
end
group :development, :test do
    gem 'compass'
    gem 'pry'
    gem 'pry-remote'
    gem 'pry-rails'
    gem 'pry-rescue'
    gem 'pry-stack_explorer'
    gem 'pry-byebug'
    gem 'guard'
    gem 'guard-livereload'
    gem 'guard-rails'
    gem 'guard-rspec'
    gem 'guard-cucumber'
    gem 'guard-zeus'
    gem 'rspec-rails'

end
group :production do
    #gem 'pg'
end

#authentication
gem 'cancan'
gem 'rolify'
gem 'devise'
gem 'omniauth'
gem 'omniauth-facebook', '=1.4.0'
gem 'oauth2'

# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.0'
gem 'bootstrap-sass', '~> 3.1.1'
gem 'bootswatch-rails'

# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'

# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'

group :doc do
  # bundle exec rake doc:rails generates the API under doc/api.
  gem 'sdoc', require: false
end

#ember
gem "active_model_serializers"
gem "ember-source", "~>1.7.0"

#asyc http calls
gem 'hashie_rails'
gem "typhoeus"
gem "virtus"

#middleware
gem "rack-cors", require: 'rack/cors'

platforms :mswin do
  gem "wdm", :group => [:development, :test]
end
#gem 'wdm', '>= 0.1.0'

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin]

Body:
Into application.rb

...

config.api_only = true
config.session_store :cookie_store, key: '_interslice_session'
config.middleware.use ActionDispatch::Cookies # Required for all session management
config.middleware.use ActionDispatch::Session::CookieStore, config.session_options


问:
Loop through HTML table for specific dropdown value
I have a table which has 3 sections (section1, section2, section3), now inside the dropdown, user will select any of the above mentioned sections, and add record, now the table will have all the records for each sections.

I want to just loop through table for specific section like only for section1. I am currently able to loop through all the checked rows (using checkbox) but now i want to loop through that specific section only.

Here's what I am doing for looping through checked rows:

```<code>$.each($("input[type=checkbox]:checked"), function (index, item) {
    .... my code here.
}
</code>```

UPDATE

From the above table, we have category as gear/artists/lessons, as you can see each has 3 records, highlighted in different colors, now i want to fetch data for specific dropdown items, like rows of all lessons etc.

答:
There are a severel solution, you can simply check the value in your loop like this :

$("input[type=checkbox]:checked").each(function(index, item) {
    var $tr = $(item).closest("tr");
    var $select = $tr.find("select");
    if ( $select.val() === "section1" ) {
        // do something
    }
});
```

<p><strong>EDIT : pre filter with grep</strong></p>

<p>An other solution to do that is to store in array your matched elements with <strong>grep</strong> function, like this :</p>

```var array = $.grep( $("input[type=checkbox]:checked"), function(index, elem) {
    var $tr = $(item).closest("tr");
    var $select = $tr.find("select");
    return ( $select.val() === "section1" );
});
```

Body:
I have a table which has 3 sections (section1, section2, section3), now inside the dropdown, user will select any of the above mentioned sections, and add record, now the table will have all the records for each sections.

I want to just loop through table for specific section like only for section1. I am currently able to loop through all the checked rows (using checkbox) but now i want to loop through that specific section only.

Here's what I am doing for looping through checked rows:

$.each($("input[type=checkbox]:checked"), function (index, item) {
    .... my code here.
}

UPDATE

From the above table, we have category as gear/artists/lessons, as you can see each has 3 records, highlighted in different colors, now i want to fetch data for specific dropdown items, like rows of all lessons etc.

Body:
There are a severel solution, you can simply check the value in your loop like this :

$("input[type=checkbox]:checked").each(function(index, item) {
    var $tr = $(item).closest("tr");
    var $select = $tr.find("select");
    if ( $select.val() === "section1" ) {
        // do something
    }
});

EDIT : pre filter with grep

An other solution to do that is to store in array your matched elements with grep function, like this :

var array = $.grep( $("input[type=checkbox]:checked"), function(index, elem) {
    var $tr = $(item).closest("tr");
    var $select = $tr.find("select");
    return ( $select.val() === "section1" );
});


问:
PyDev tells "error == cudaSuccess (35 vs. 0)CUDA driver version is insufficient for CUDA runtime version",but command line works fine
My configuration like this:

```<code>Ubuntu        16.04
Java          1.8
Python        2.7.12
Caffe         1.0
Cuda          8.0
Nvidia driver 375-66
PyDev         5.7.0.201704111357

And I tried to run this in bash:
</code>```

https://github.com/ZheC/Realtime_Multi-Person_Pose_Estimation/tree/master/testing/python

by

```<code>python -m Demo
</code>```

It works fine,but when try to run from eclipse-pydev,got this error:

```<code>WARNING: Logging before InitGoogleLogging() is written to STDERR
E0606 09:34:43.905447 15924 common.cpp:114] Cannot create Cublas handle. Cublas won't be available.
0
E0606 09:34:43.905640 15924 common.cpp:121] Cannot create Curand generator. Curand won't be available.
F0606 09:34:43.905845 15924 common.cpp:152] Check failed: error == cudaSuccess (35 vs. 0)  CUDA driver version is insufficient for CUDA runtime version
*** Check failure stack trace: ***
</code>```

I think this problem comes from that I start up OS with nvidia driver then switchs to intel like this:

This is what I want due to hope to use embeded intel VC to handle OS related work,and leave Nvidia VC for caffe(a deep learning framework) jobs.The
question is :

Why,for same python wrapped caffe job,does command line work fine but PyDev give the these error?

答:
Usually this means that you have some environment variable in your command line that's not replicated in PyDev.

The usual fix is to launch Eclipse from the command line, so that it inherits the variables set there.

Body:
My configuration like this:

Ubuntu        16.04
Java          1.8
Python        2.7.12
Caffe         1.0
Cuda          8.0
Nvidia driver 375-66
PyDev         5.7.0.201704111357

And I tried to run this in bash:

https://github.com/ZheC/Realtime_Multi-Person_Pose_Estimation/tree/master/testing/python

by

python -m Demo

It works fine,but when try to run from eclipse-pydev,got this error:

WARNING: Logging before InitGoogleLogging() is written to STDERR
E0606 09:34:43.905447 15924 common.cpp:114] Cannot create Cublas handle. Cublas won't be available.
0
E0606 09:34:43.905640 15924 common.cpp:121] Cannot create Curand generator. Curand won't be available.
F0606 09:34:43.905845 15924 common.cpp:152] Check failed: error == cudaSuccess (35 vs. 0)  CUDA driver version is insufficient for CUDA runtime version
*** Check failure stack trace: ***

I think this problem comes from that I start up OS with nvidia driver then switchs to intel like this:

This is what I want due to hope to use embeded intel VC to handle OS related work,and leave Nvidia VC for caffe(a deep learning framework) jobs.The
question is :

Why,for same python wrapped caffe job,does command line work fine but PyDev give the these error?


问:
What is the difference between null and undefined in JavaScript?
I want to know what the difference is between null and undefined in JavaScript.

答:
OK, we may get confused when we hear about null and undefined, but let's start it simple, they both are falsy and similar in many ways, but weird part of JavaScript, make them a couple of significant differences, for example, typeof null is 'object' while typeof undefined is 'undefined'.

```<code>typeof null; //"object"
typeof undefined; //"undefined";
</code>```

But if you check them with == as below, you see they are both falsy:

```<code>null==undefined; //true
</code>```

Also you can assign null to an object property or to a primitive, while undefined can simply be achieved by not assigning to anything.

I create a quick image to show the differences for you at a glance.

Body:
OK, we may get confused when we hear about null and undefined, but let's start it simple, they both are falsy and similar in many ways, but weird part of JavaScript, make them a couple of significant differences, for example, typeof null is 'object' while typeof undefined is 'undefined'.

typeof null; //"object"
typeof undefined; //"undefined";

But if you check them with == as below, you see they are both falsy:

null==undefined; //true

Also you can assign null to an object property or to a primitive, while undefined can simply be achieved by not assigning to anything.

I create a quick image to show the differences for you at a glance.

ContentLicense: CC BY-SA 4.0


问:
Placeholder in date_field_tag rails 4
I am trying to use placeholder in date_field_tag using rails 4. But instead of showing placeholder value it keeps showing 'dd-mm-yyyy'

My code

```<code><%= date_field_tag "event_date", "", class: "form-control input-md", placeholder: "Event Date *", required: true %>
</code>```

答:
```<code>You can use in html format like this
In Html
<input placeholder="Event Date *" class="textbox-n" type="text" onfocus="(this.type='date')"  id="date">

In Haml
%input#date.textbox-n{:onfocus => "(this.type='date')", :placeholder => "Event Date *", :type => "text"}/
</code>```

Title: Placeholder in date_field_tag rails 4

Body:
I am trying to use placeholder in date_field_tag using rails 4. But instead of showing placeholder value it keeps showing 'dd-mm-yyyy'

My code

<%= date_field_tag "event_date", "", class: "form-control input-md", placeholder: "Event Date *", required: true %>


问:
Replace image with another one in QTextEdit
Say there is a text and images in a QTextEdit. And say you extract HTML code of the QTextEdit. Now how it is posible to find the places in the HTML code where the images are instantiated () and replace with another images that I have as a QImage objects retaining the position and the size of the former image.

In other words it is necessary to exchange pictures while retaining the position and the size of the first picture, when the second picture is stored in the program as a QImage.

Please consider that the first image may not exist at all. The HTML code that hase  may be set to the QTextEdit artificially regardless there if is an image  like file://path/to/image/image_name.png or not.

答:
```<code>//Add images as resources
for(int i = 0; i < vectorOfImages.size(); i++ )
{
    QUrl url(QString("image_%1").arg(i));
    textEdit->document()->addResource(QTextDocument::ImageResource, url,  vectorOfImages.at(i));
}

//Process the htmlCode that is in QTextEdit.

int count = 0;
int pos = 0;

QRegExp rx("<img src=\".+/>");
while ((pos = rx.indexIn(htmlCode, pos)) != -1)
{
    QString strToReplace(QString("<img src=\"image_%1\" />").arg(count));
    htmlCode.replace(pos, rx.matchedLength(), strToReplace);
    pos += rx.matchedLength();
    count++;
}

textEdit->setText(htmlCode);
</code>```


问:
Ember JS tutorial: TypeError: Cannot read property 'maps' of undefined
I am currently running through the official EmberJS tutorial on their website and I'm on this part. Everything works perfectly in the app itself when I run ember serve but the problem is when I run the unit tests for the new service. I am running ember test --server and I get an error that I took a screenshot of below:

The unit test code:

```<code>import { moduleFor, test } from 'ember-qunit';
import Ember from 'ember';

const DUMMY_ELEMENT = {};

let MapUtilStub = Ember.Object.extend({
  createMap(element, location) {
    this.assert.ok(element, 'createMap called with element');
    this.assert.ok(location, 'createMap called with location');
    return DUMMY_ELEMENT;
  }
});

moduleFor('service:maps', 'Unit | Service | maps', {
  needs: ['util:google-maps']
});

test('should create a new map if one isnt cached for location', function (assert) {
  assert.expect(4);
  let stubMapUtil = MapUtilStub.create({ assert });
  let mapService = this.subject({ mapUtil: stubMapUtil });
  let element = mapService.getMapElement('San Francisco');
  assert.ok(element, 'element exists');
  assert.equal(element.className, 'map', 'element has class name of map');
});

test('should use existing map if one is cached for location', function (assert) {
  assert.expect(1);
  let stubCachedMaps = Ember.Object.create({
    sanFrancisco: DUMMY_ELEMENT
  });
  let mapService = this.subject({ cachedMaps: stubCachedMaps });
  let element = mapService.getMapElement('San Francisco');
  assert.equal(element, DUMMY_ELEMENT, 'element fetched from cache');
});
</code>```

From the tutorial, my understanding is that this.subject({ cachedMaps: stubCachedMaps }) will set up all the maps for me but it seems the service itself might be undefined, leading to no property maps. Is this right? What could be causing this?

System specs from running ember --version:

ember-cli: 2.13.0

node: 6.8.1

os: darwin x64

答:
I run at the same thing, too. The solution by @cythrawll works, but it's not the root cause of TypeError: Cannot read property 'maps' of undefined error.

In tutorial they forget to add

```<code><script src="https://maps.googleapis.com/maps/api/js?v=3.22"></script>
</code>```

in test/index.html file. Issue is already reported.

Body:
I am currently running through the official EmberJS tutorial on their website and I'm on this part. Everything works perfectly in the app itself when I run ember serve but the problem is when I run the unit tests for the new service. I am running ember test --server and I get an error that I took a screenshot of below:

The unit test code:

import { moduleFor, test } from 'ember-qunit';
import Ember from 'ember';

const DUMMY_ELEMENT = {};

let MapUtilStub = Ember.Object.extend({
  createMap(element, location) {
    this.assert.ok(element, 'createMap called with element');
    this.assert.ok(location, 'createMap called with location');
    return DUMMY_ELEMENT;
  }
});

moduleFor('service:maps', 'Unit | Service | maps', {
  needs: ['util:google-maps']
});

test('should create a new map if one isnt cached for location', function (assert) {
  assert.expect(4);
  let stubMapUtil = MapUtilStub.create({ assert });
  let mapService = this.subject({ mapUtil: stubMapUtil });
  let element = mapService.getMapElement('San Francisco');
  assert.ok(element, 'element exists');
  assert.equal(element.className, 'map', 'element has class name of map');
});

test('should use existing map if one is cached for location', function (assert) {
  assert.expect(1);
  let stubCachedMaps = Ember.Object.create({
    sanFrancisco: DUMMY_ELEMENT
  });
  let mapService = this.subject({ cachedMaps: stubCachedMaps });
  let element = mapService.getMapElement('San Francisco');
  assert.equal(element, DUMMY_ELEMENT, 'element fetched from cache');
});

From the tutorial, my understanding is that this.subject({ cachedMaps: stubCachedMaps }) will set up all the maps for me but it seems the service itself might be undefined, leading to no property maps. Is this right? What could be causing this?

System specs from running ember --version:

ember-cli: 2.13.0

node: 6.8.1

os: darwin x64

Body:
I run at the same thing, too. The solution by @cythrawll works, but it's not the root cause of TypeError: Cannot read property 'maps' of undefined error.

In tutorial they forget to add

<script src="https://maps.googleapis.com/maps/api/js?v=3.22"></script>

in test/index.html file. Issue is already reported.


问:
Flow - Defining interface based on props for a react component
With Flow, I want to be able to specify an interface for a functional react component that defines a few methods that the component takes as properties.

I want a wrapper component to be able to set those properties on the child component that implements those properties.

Here is the code I have now:

```<code>interface Updateable {
  update(string): void
};

const Edit = ({
  update
}: {
  update: string => void
}) => <a onClick={e => update(e.target.value)}>Something</a>

const UpdateContainer = ({ toRender }: { toRender: Updateable } ) => (
  <toRender update={message => alert(message)} />
)

const Wrapper = (
    <UpdateContainer toRender={Edit} />
);
</code>```

This gives me the error:

const UpdateContainer = ({ toRender }: { toRender: Updateable } ) => (

update of Updateable. Property not found in
  <UpdateContainer toRender={Edit} />

How can I specify an interface based on react component properties? Or is there another thing besides an interface I should be using?

答:
Playground

```<code>type Updateable = {
  update: (value: string) => void
};

const Edit = ({
  update
}: Updateable ) => <a onClick={e => update(e.target.value)}>Something</a>

const Foo = ({
  foo
}: {
  foo: string => void
}) => <a onClick={e => foo(e.target.value)}>Something</a>

const UpdateContainer = ({ toRender }: { toRender: (props: Updateable) => React$Element<any> }) => (
  <toRender update={message => alert(message)} />
)

const Wrapper1 = (
    <UpdateContainer toRender={Foo} />
);

const Wrapper2 = (
    <UpdateContainer toRender={Edit} />
);
</code>```

With this code, Wrapper1 generates an error but Wrapper2 doesn't. I switched the interface to a type as I'm not really familiar with interfaces in flowtype.

As for the problem, the problem is this part { toRender: Updateable }.

{ toRender: Updateable } states toRender is something that implements Updateable, however that isn't the case when passing Edit.

Edit is a function that takes an argument props, and it's those props who implement Updateable.

I changed the code to be { toRender: (props: Updateable) => React$Element<any> } to reflect this (and switched the interface to a type as previously mentioned, I'm not sure if that's needed, it's just way I know).

I hope this helps.

Body:
With Flow, I want to be able to specify an interface for a functional react component that defines a few methods that the component takes as properties.

I want a wrapper component to be able to set those properties on the child component that implements those properties.

Here is the code I have now:

interface Updateable {
  update(string): void
};

const Edit = ({
  update
}: {
  update: string => void
}) =>  update(e.target.value)}>Something

const UpdateContainer = ({ toRender }: { toRender: Updateable } ) => (
  <toRender update={message => alert(message)} />
)

const Wrapper = (
    <UpdateContainer toRender={Edit} />
);

This gives me the error:

const UpdateContainer = ({ toRender }: { toRender: Updateable } ) => (

update of Updateable. Property not found in
  <UpdateContainer toRender={Edit} />

How can I specify an interface based on react component properties? Or is there another thing besides an interface I should be using?

Body:
<a href="https://flow.org/try/#0C4TwDgpgBAqmAmBDYFECMA20C8UDeAUFFAK4LIQBcUAFAG6IYlVQDOwATgJYB2A5gEoo2AHxQ6Aey7wCAXwDcBAgGMJPdlACi8LsGG1CxMkhRzqh0uRTV23fsLGTpcoaKgAeRFDUBhDF2UAa2w8HDFjChoIADpgRA4+CGBohiYIAVkRAGUJAFskgAtePncAekQRJVV1PQAxCQl9GgsAMwazfCIoNokbTmKHcSkZWVcxT28ePwDg0MGeqNj4xOTU5gzsvMLisoqqtQ04EwgfNTjeCA4mvChgCQAlCB54S6hZc1uHp5eOahowDgSMCsahHCjoLBjKCPRDKYAAEk0WHyPGAnh4IDEo0GNC67juj2erwiKBC+VYrEQiUGjEuwBo5MpiQyUFKlQE+xqUAA6hxEGBIBwAIxNLrEdxglCnVGIC5XAnfS4heoSWSs9mKFQHPS8-mCgBMouI4slJzOsp4rwVRI4IW0ujVbIIAnkQA" rel="nofollow noreferrer">Playground

type Updateable = {
  update: (value: string) => void
};

const Edit = ({
  update
}: Updateable ) => <a onClick={e => update(e.target.value)}>Something</a>

const Foo = ({
  foo
}: {
  foo: string => void
}) => <a onClick={e => foo(e.target.value)}>Something</a>

const UpdateContainer = ({ toRender }: { toRender: (props: Updateable) => React$Element<any> }) => (
  <toRender update={message => alert(message)} />
)

const Wrapper1 = (
    <UpdateContainer toRender={Foo} />
);

const Wrapper2 = (
    <UpdateContainer toRender={Edit} />
);

With this code, Wrapper1 generates an error but Wrapper2 doesn't. I switched the interface to a type as I'm not really familiar with interfaces in flowtype.

As for the problem, the problem is this part { toRender: Updateable }.

{ toRender: Updateable } states toRender is something that implements Updateable, however that isn't the case when passing Edit.

Edit is a function that takes an argument props, and it's those props who implement Updateable.

I changed the code to be { toRender: (props: Updateable) => React$Element<any> } to reflect this (and switched the interface to a type as previously mentioned, I'm not sure if that's needed, it's just way I know).

I hope this helps.


问:
How to avoid auto increment of primary key in inserting query?
First I allowed user to type in combo box to search quickly when there are many projects. I was wondering if I can stop the insert query if the user accidentally press an additional letter and it will cause null, and I had try catch block but it only shows error message but the primary key skip a number.

Selecting ProjectID to fill comboBox

```<code>private void GetProjectID()
{
    newConnection.ConnectionM();
    SqlCommand cmd = SqlConnectionOLTP.cn.CreateCommand();
    cmd.CommandText = "Select * from Project where ProjectName='" + comboBoxProjectTitle.Text + "' ";
    try
    {
        SqlDataReader reader = cmd.ExecuteReader();
        while(reader.Read())
        {
            ProjectID = reader.GetInt32(0);

        }
        reader.Close();
        SqlConnectionOLTP.cn.Close();
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
</code>```

Inserting to database:

```<code>SqlCommand cmd = SqlConnectionOLTP.cn.CreateCommand();
cmd.CommandText = "Insert into Cost(ProjectID,PropertyID,CostCategoryID,EstimatedAmount) values ('" + ProjectID + "','" + PropertyID + "','" + CostCatID + "'," + "'" + textBoxAmount.Text + "') ";
cmd.ExecuteNonQuery();
SqlConnectionOLTP.cn.Close();
MessageBox.Show("Saved");
</code>```

答:
```<code>SET IDENTITY_INSERT <TableName> ON
-- Do the inserting in the table with name <TableName>
SET IDENTITY_INSERT <TableName> OFF
</code>```

Body:
First I allowed user to type in combo box to search quickly when there are many projects. I was wondering if I can stop the insert query if the user accidentally press an additional letter and it will cause null, and I had try catch block but it only shows error message but the primary key skip a number.

Selecting ProjectID to fill comboBox

private void GetProjectID()
{
    newConnection.ConnectionM();
    SqlCommand cmd = SqlConnectionOLTP.cn.CreateCommand();
    cmd.CommandText = "Select * from Project where ProjectName='" + comboBoxProjectTitle.Text + "' ";
    try
    {
        SqlDataReader reader = cmd.ExecuteReader();
        while(reader.Read())
        {
            ProjectID = reader.GetInt32(0);

        }
        reader.Close();
        SqlConnectionOLTP.cn.Close();
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Inserting to database:

SqlCommand cmd = SqlConnectionOLTP.cn.CreateCommand();
cmd.CommandText = "Insert into Cost(ProjectID,PropertyID,CostCategoryID,EstimatedAmount) values ('" + ProjectID + "','" + PropertyID + "','" + CostCatID + "'," + "'" + textBoxAmount.Text + "') ";
cmd.ExecuteNonQuery();
SqlConnectionOLTP.cn.Close();
MessageBox.Show("Saved");


问:
How to remove these characters from NSString
I want to load a URL Request, but there are some not desired characters in the URL (I´m retrieving the URL from a remote place, so I can´t change the source).

```<code>NSString *link = [[notification userInfo] valueForKey:@"link"];
link = [link stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSLog(@"Requesting Link: %@",link); /* see below for output */
NSURL *url = [NSURL URLWithString:link];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

[self.theWebView loadRequest:request];
</code>```

The console shows the NSLog output like this:

```<code>%0A%09%09%09http://192.168.0...
</code>```

The loadRequest doesn't do anything, I´m sure it's because the NSURL isn´t encoded properly, but I don´t know how to remove those characters.

Edit

The Raw string (linebreak and space):

```<code>Requesting Link:
        http://192.168.0...
</code>```

答:
Use this

[link stringByRemovingPercentEncoding];

Body:
I want to load a URL Request, but there are some not desired characters in the URL (I´m retrieving the URL from a remote place, so I can´t change the source).

NSString *link = [[notification userInfo] valueForKey:@"link"];
link = [link stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSLog(@"Requesting Link: %@",link); /* see below for output */
NSURL *url = [NSURL URLWithString:link];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

[self.theWebView loadRequest:request];

The console shows the NSLog output like this:

%0A%09%09%09http://192.168.0...

The loadRequest doesn't do anything, I´m sure it's because the NSURL isn´t encoded properly, but I don´t know how to remove those characters.

Edit

The Raw string (linebreak and space):

Requesting Link:
        http://192.168.0...


问:
Best way to communicate between forms?
I almost never used (advanced, or at all) graphical interfaces, or one simple form with simple controls... but this time I've got something a little more complex, and I don't have much experience with GUI.
I have one main form (and possibly more in the future) from which other sub-forms open (and they might have sub-forms of themselves) and I wonder what is, in your opinion, the best way to communicate between them?

I thought of passing the main form as a parameter to the constructors of the sub-forms, but it doesn't seem like a good way, especially if I'm going to need to communicate between other, distinct, sub-forms, not to mention I have to double check the input, or make a few methods, but it seems more like functional programming than object oriented programming...

Perhaps I can:

Create a static class (or Properties.Settings) for global settings. Cons: every change of data is needed to be copied to the class, I'm looking for something a bit more comfortable and elegant.

Use the ugly way of accessing the controls from Application.OpenForms - fixes the problem of passing the main form as parameter. Cons: not very stable.

Do something else I haven't thought of. Suggestions? Cons: don't know what it is yet.

答:
The most flexible, scalable (and IMHO the most professional) way to do it is to use CAB (Composite Application Block). In simple terms CAB is a set of 2-3 assemblies that implement a lot of plumbing required to make complex UI  applications the right way and it exposes this plumbing to the user of the library in a nice way. Among others it has a very nice event and command (as in command pattern) system.

The downside: requires some time to learn and not very trivial to grasp.

Here is a comprehensive (but easy to understand) tutorial that will help you make the learning easier.

Title: Best way to communicate between forms?


问:
How do I track a single user throughout my website using google analytics?
I'm trying to track a single users path throughout my site all the way until conversion. Is there a way to legally do this through google analytics? I'm mainly trying to see if my homepage buttons are doing as well taking people through the whole process as my inner sites processes. </p>

答: Try User Explorer under Audience. You could use segments to then narrow down your search for specific users e.g. only those who accessed certain pages.


问:
Eloquent updateOrInsert
I would like the eloquent to be able to auto-feed the created_at and updated_at fields, using the following commands below</p>

```<code>                DB::table('partida')->updateOrInsert(
                    [
                        'rodada' => $values->rodada,
                        'mandante_fk' => $value->clube_casa_id,
                        'visitante_fk' => $value->clube_visitante_id
                    ],
                    [
                        'partida_id' => $key,
                        'rodada' => $values->rodada,
                        'mandante_fk' => $value->clube_casa_id,
                        'visitante_fk' => $value->clube_visitante_id,
                        'partida_data' => (string)$value->partida_data,
                        'placar_mandante' => $value->placar_oficial_mandante,
                        'placar_visitante' => $value->placar_oficial_visitante,
                        'local' => (string)$value->local
                    ]
                );
</code>```

答:
If you want to use the Eloquent methods properly, use Eloquent and not the query builder.

You can practically do the same with the updateOrCreate() method, which will set the timestamps if the model defines them.

You'll get something like (assuming the Partida model exists):

```<code>Partida::updateOrCreate([
        'rodada' => $values->rodada,
        'mandante_fk' => $value->clube_casa_id,
        'visitante_fk' => $value->clube_visitante_id
    ],
    [
        'partida_id' => $key,
        'rodada' => $values->rodada,
        'mandante_fk' => $value->clube_casa_id,
        'visitante_fk' => $value->clube_visitante_id,
        'partida_data' => (string)$value->partida_data,
        'placar_mandante' => $value->placar_oficial_mandante,
        'placar_visitante' => $value->placar_oficial_visitante,
        'local' => (string)$value->local
    ]);
</code>```

Title: Eloquent updateOrInsert

Body:
I would like the eloquent to be able to auto-feed the created_at and updated_at fields, using the following commands below

                DB::table('partida')->updateOrInsert(
                    [
                        'rodada' => $values->rodada,
                        'mandante_fk' => $value->clube_casa_id,
                        'visitante_fk' => $value->clube_visitante_id
                    ],
                    [
                        'partida_id' => $key,
                        'rodada' => $values->rodada,
                        'mandante_fk' => $value->clube_casa_id,
                        'visitante_fk' => $value->clube_visitante_id,
                        'partida_data' => (string)$value->partida_data,
                        'placar_mandante' => $value->placar_oficial_mandante,
                        'placar_visitante' => $value->placar_oficial_visitante,
                        'local' => (string)$value->local
                    ]
                );

Body:
If you want to use the Eloquent methods properly, use Eloquent and not the query builder.

You can practically do the same with the updateOrCreate() method, which will set the timestamps if the model defines them.

You'll get something like (assuming the Partida model exists):

Partida::updateOrCreate([
        'rodada' => $values->rodada,
        'mandante_fk' => $value->clube_casa_id,
        'visitante_fk' => $value->clube_visitante_id
    ],
    [
        'partida_id' => $key,
        'rodada' => $values->rodada,
        'mandante_fk' => $value->clube_casa_id,
        'visitante_fk' => $value->clube_visitante_id,
        'partida_data' => (string)$value->partida_data,
        'placar_mandante' => $value->placar_oficial_mandante,
        'placar_visitante' => $value->placar_oficial_visitante,
        'local' => (string)$value->local
    ]);


问:
input placeholder text getting cutoff
I am creating webview wherein I am using couple of INPUT tags with placeholder text to get the user input.

However, in some devices i.e. MOTO E2 for instance, the placeholder text is getting cutoff and we can only view the top part (around 1px) of the text.

How to solve this issue?

答: In the Css for this web view I had used line height of 2px and when I removed it, the problem was solved.</p>

Title: input placeholder text getting cutoff