问:
ChartJS - Set different hover-text than x-axis description
I'm using chartjs to visualize some data in a bar diagram. The labels are quite long, so I cut them. However, I'd like to have the text for the tooltips (on hover) to be the original one. Can I achieve this with the default chartjs configuration?

I use the following to generate the charts:

```<code>function DrawChart(canvasID, remoteFields, remoteData, remoteColors, remoteBorderColors) {
    var ctx = document.getElementById(canvasID).getContext('2d');

    var orig = remoteFields;
    var maxLabelLength = 20;
    for(var i = 0; i < remoteFields.length; i++) {
        if(remoteFields[i].length > maxLabelLength) {
            remoteFields[i] = remoteFields[i].substring(0,maxLabelLength) + "...";
        }
    }
    var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
    labels: remoteFields,
        datasets: [{
            data: remoteData,
            backgroundColor: remoteColors,
            borderColor: remoteBorderColors,
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true,
                    stepSize: 1
                }
            }]
        },
        responsive: true,
        maintainAspectRatio: false,
        legend: {
        display: false
    }
    }
});
}
</code>```

答:
You can achieve this using ticks callback function (for trimming the x-axis labels) and tooltips callback function (to dispaly the original text on tooltips)

var ctx = document.getElementById('c').getContext('2d');
var myChart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: ['January', 'February', 'March', 'April', 'May'],
      datasets: [{
         data: [1, 2, 3, 4, 5],
         backgroundColor: ['#30799f', '#ac51c3', '#4ba57b', '#e3297d', '#e35c32'],
         borderColor: ['#30799f', '#ac51c3', '#4ba57b', '#e3297d', '#e35c32'],
         borderWidth: 1
      }]
   },
   options: {
      responsive: false,
      scales: {
         xAxes: [{
            ticks: {
               callback: function(t) {
                  var maxLabelLength = 3;
                  if (t.length > maxLabelLength) return t.substr(0, maxLabelLength) + '...';
                  else return t;
               }
            }
         }],
         yAxes: [{
            ticks: {
               beginAtZero: true,
               stepSize: 1
            }
         }]
      },
      legend: {
         display: false
      },
      tooltips: {
         callbacks: {
            title: function(t, d) {
               return d.labels[t[0].index];
            }
         }
      }
   }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="c" width="350" height="200"></canvas></code>```

Body:
I'm using chartjs to visualize some data in a bar diagram. The labels are quite long, so I cut them. However, I'd like to have the text for the tooltips (on hover) to be the original one. Can I achieve this with the default chartjs configuration?

I use the following to generate the charts:

function DrawChart(canvasID, remoteFields, remoteData, remoteColors, remoteBorderColors) {
    var ctx = document.getElementById(canvasID).getContext('2d');

    var orig = remoteFields;
    var maxLabelLength = 20;
    for(var i = 0; i < remoteFields.length; i++) {
        if(remoteFields[i].length > maxLabelLength) {
            remoteFields[i] = remoteFields[i].substring(0,maxLabelLength) + "...";
        }
    }
    var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
    labels: remoteFields,
        datasets: [{
            data: remoteData,
            backgroundColor: remoteColors,
            borderColor: remoteBorderColors,
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true,
                    stepSize: 1
                }
            }]
        },
        responsive: true,
        maintainAspectRatio: false,
        legend: {
        display: false
    }
    }
});
}

Body:
You can achieve this using ticks callback function (for trimming the x-axis labels) and tooltips callback function (to dispaly the original text on tooltips)

var ctx = document.getElementById('c').getContext('2d');
var myChart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: ['January', 'February', 'March', 'April', 'May'],
      datasets: [{
         data: [1, 2, 3, 4, 5],
         backgroundColor: ['#30799f', '#ac51c3', '#4ba57b', '#e3297d', '#e35c32'],
         borderColor: ['#30799f', '#ac51c3', '#4ba57b', '#e3297d', '#e35c32'],
         borderWidth: 1
      }]
   },
   options: {
      responsive: false,
      scales: {
         xAxes: [{
            ticks: {
               callback: function(t) {
                  var maxLabelLength = 3;
                  if (t.length > maxLabelLength) return t.substr(0, maxLabelLength) + '...';
                  else return t;
               }
            }
         }],
         yAxes: [{
            ticks: {
               beginAtZero: true,
               stepSize: 1
            }
         }]
      },
      legend: {
         display: false
      },
      tooltips: {
         callbacks: {
            title: function(t, d) {
               return d.labels[t[0].index];
            }
         }
      }
   }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="c" width="350" height="200"></canvas>


来源: stackexchange

问:
Change timestamp depends on user's country in Cakephp 3
I want to change the timezone of the country so when a user delete an object, I can set the $timestamp from the user's country into a row related on that object.

I call a function into my controller like this:

```<code> $turno = $this->Turnos->get($id);

    $countryid= $this -> Auth -> User()['countryid'];
$datos = getHoraDiaMesAnio($countryid);
    $fechaActual = date('Y-m-d',strtotime($datos[2]."-".$datos[1]."-".$datos[0]));
    $dia = $datos[0];   $mes = $datos[1];   $anio = $datos[2];
    $horaActual = date('H:i',strtotime($datos[4]));

    $hora = $datos[5];
    $timestamp = $anio."-".$mes."-".$dia." ".$hora;

    $turno->fechaBaja = $timestamp;
    //$turno->fechaBaja = $result;
    if ($this->Turnos->save($turno)) {
        $this->Flash->success(__('El turno se ha eliminado.'));
    } else {
        $this->Flash->error(__('El turno no se ha podido eliminar. Por favor intente de nuevo.'));
    }
    return $this->redirect(['action' => 'index']);
</code>```

This is my function:

```<code>function getHoraDiaMesAnio($countyid){

    switch ($countyid){
        case 1://Argentina
            date_default_timezone_set('America/Argentina/Buenos_Aires');
            putenv('TZ=America/Argentina/Buenos_Aires');
            break;
        case 2://Bolivia
            date_default_timezone_set('America/La_Paz');
            putenv('TZ=America/La_Paz');
            break;
    $dia= date("j");
    $mes= date("m");
    $anio= date("Y");
    $horaRedondeada = date("H:00");
    $horaExacta = date("H:i");
    $horaCompleta = date("H:i:s");

return array($dia,$mes,$anio,$horaRedondeada,$horaExacta,$horaCompleta);`
</code>```

The problem is that the timestamp never sets correctly. In others services (without using cakephp) work perfectly. I think in cakephp I have to change in another way.

Could you help me?

Thanks!

答:
That looks unnecessarily complicated to me. I'd suggest to work with the date/time API provided by Cake/PHP instead, timezone adjustments should be a cake, and you can simply pass \DateTimeInterface objects into the saving process in case the column is of a date-time-ish type.

```<code>$now = \Cake\Chronos\Chronos::now(); // uses the default app timezone, see the
                                     // date_default_timezone_set() call in bootstrap.php

switch ($countryid) {
    case 1:
        $now = $now->setTimezone('America/Argentina/Buenos_Aires');
        break;

    case 2:
        $now = $now->setTimezone('America/La_Paz');
        break;
}

$turno->fechaBaja = $now;
</code>```

In case the fechaBaja column isn't of a date-time-ish type (it better be), simply format the object to a string:

```<code>$turno->fechaBaja = $now->toDateTimeString(); // formats as Y-m-d H:i:s
</code>```

See also

Cookbook > Chronos

Cookbook > Date & Time

PHP Manual > Date and Time

ContentLicense: CC BY-SA 3.0

Body:
I want to change the timezone of the country so when a user delete an object, I can set the $timestamp from the user's country into a row related on that object.

I call a function into my controller like this:

 $turno = $this->Turnos->get($id);

    $countryid= $this -> Auth -> User()['countryid'];
$datos = getHoraDiaMesAnio($countryid);
    $fechaActual = date('Y-m-d',strtotime($datos[2]."-".$datos[1]."-".$datos[0]));
    $dia = $datos[0];   $mes = $datos[1];   $anio = $datos[2];
    $horaActual = date('H:i',strtotime($datos[4]));

    $hora = $datos[5];
    $timestamp = $anio."-".$mes."-".$dia." ".$hora;

    $turno->fechaBaja = $timestamp;
    //$turno->fechaBaja = $result;
    if ($this->Turnos->save($turno)) {
        $this->Flash->success(__('El turno se ha eliminado.'));
    } else {
        $this->Flash->error(__('El turno no se ha podido eliminar. Por favor intente de nuevo.'));
    }
    return $this->redirect(['action' => 'index']);

This is my function:

function getHoraDiaMesAnio($countyid){

    switch ($countyid){
        case 1://Argentina
            date_default_timezone_set('America/Argentina/Buenos_Aires');
            putenv('TZ=America/Argentina/Buenos_Aires');
            break;
        case 2://Bolivia
            date_default_timezone_set('America/La_Paz');
            putenv('TZ=America/La_Paz');
            break;
    $dia= date("j");
    $mes= date("m");
    $anio= date("Y");
    $horaRedondeada = date("H:00");
    $horaExacta = date("H:i");
    $horaCompleta = date("H:i:s");

return array($dia,$mes,$anio,$horaRedondeada,$horaExacta,$horaCompleta);`

The problem is that the timestamp never sets correctly. In others services (without using cakephp) work perfectly. I think in cakephp I have to change in another way.

Could you help me?

Thanks!

Body:
That looks unnecessarily complicated to me. I'd suggest to work with the date/time API provided by Cake/PHP instead, timezone adjustments should be a cake, and you can simply pass \DateTimeInterface objects into the saving process in case the column is of a date-time-ish type.

$now = \Cake\Chronos\Chronos::now(); // uses the default app timezone, see the
                                     // date_default_timezone_set() call in bootstrap.php

switch ($countryid) {
    case 1:
        $now = $now->setTimezone('America/Argentina/Buenos_Aires');
        break;

    case 2:
        $now = $now->setTimezone('America/La_Paz');
        break;
}

$turno->fechaBaja = $now;

In case the fechaBaja column isn't of a date-time-ish type (it better be), simply format the object to a string:

$turno->fechaBaja = $now->toDateTimeString(); // formats as Y-m-d H:i:s

See also

Cookbook > Chronos

Cookbook > Date & Time

PHP Manual > Date and Time


问:
Couting the letters of given word
I am trying to count the letters of a given word. I stuck at the end. I do not know how to count the letters.</p>

```<code>static void Main(string[] args)
    {
        Console.WriteLine("Enter a word:");
        string kelime = Console.ReadLine();

        int numberofLetters = kelime.Length;

        Console.WriteLine("Your word has {0} characters", numberofLetters);

        for (int i = 0; i < numberofLetters; i++)
        {
            if
        }
    }
</code>```

答:
You should store somewhere the letters you have processed and how many times you processed them. A good choice it would be a Dictionary, with key the letter and value the times you found this letter.

```<code>var lettersDictionary = new Dictionary<char, int>();
for (int i = 0; i < numberofLetters; i++)
{
    var currentLetter = kelime[i];
    if(lettersDictionary.ContainsKey(currentLetter))
    {
        // The dictionary contains the currentLetter.
        // So we increase the times we found it by 1.
        lettersDictionary[currentLetter] += 1;
    }
    else
    {
        // The dictionary doesn't contain the currentLetter.
        // So we add the new key with the value of 1.
        lettersDictionary.Add(currentLetter,1);
    }
}
</code>```

Having done the above you could build the output you want like below:

```<code>var keyValues = lettersDictionary.Keys.Select(key=>$"{key}: {lettersDictionary[key]}");
var output = string.Join(",", keyValues);
</code>```

Title: Couting the letters of given word

Body:
I am trying to count the letters of a given word. I stuck at the end. I do not know how to count the letters.

static void Main(string[] args)
    {
        Console.WriteLine("Enter a word:");
        string kelime = Console.ReadLine();

        int numberofLetters = kelime.Length;

        Console.WriteLine("Your word has {0} characters", numberofLetters);

        for (int i = 0; i < numberofLetters; i++)
        {
            if
        }
    }

Body:
You should store somewhere the letters you have processed and how many times you processed them. A good choice it would be a Dictionary, with key the letter and value the times you found this letter.

var lettersDictionary = new Dictionary<char, int>();
for (int i = 0; i < numberofLetters; i++)
{
    var currentLetter = kelime[i];
    if(lettersDictionary.ContainsKey(currentLetter))
    {
        // The dictionary contains the currentLetter.
        // So we increase the times we found it by 1.
        lettersDictionary[currentLetter] += 1;
    }
    else
    {
        // The dictionary doesn't contain the currentLetter.
        // So we add the new key with the value of 1.
        lettersDictionary.Add(currentLetter,1);
    }
}

Having done the above you could build the output you want like below:

var keyValues = lettersDictionary.Keys.Select(key=>$"{key}: {lettersDictionary[key]}");
var output = string.Join(",", keyValues);


问:
Is there a standard function for "do this if Just x"?
I have the following code:

```<code>doIf :: (a -> IO ()) -> Maybe a -> IO ()
doIf f x = case x of
  Just i -> f i
  Nothing -> return ()

main = do
  mapM_ (doIf print) [Just 3, Nothing, Just 4]
</code>```

which outputs:

```<code>3
4
</code>```

In other words, the Just values are printed, but Nothing values cause no action.  (And do not interrupt computation.)

Is there a standard function like this in the Haskell libraries?  Also, can this be made more generic?  I tried replacing IO () with m b but then return () does not work.  How do you generically write return () for any monad? (If possible..)  Can even the Maybe be generalized here?

Lastly, can I do away with the doIf function entirely?  Can I have an operator <#> that applies an argument unless Nothing?

```<code>print <#> Just 3
print <#> Nothing
</code>```

would output

```<code>3
</code>```

But I don't know if this is possible.

答:
Take a look at the function:

```<code>maybe :: b -> (a -> b) -> Maybe a -> b
</code>```

You've almost written it in doIf except for the fixed return ()

ContentLicense: CC BY-SA 2.5

Body:
I have the following code:

doIf :: (a -> IO ()) -> Maybe a -> IO ()
doIf f x = case x of
  Just i -> f i
  Nothing -> return ()

main = do
  mapM_ (doIf print) [Just 3, Nothing, Just 4]

which outputs:

3
4

In other words, the Just values are printed, but Nothing values cause no action.  (And do not interrupt computation.)

Is there a standard function like this in the Haskell libraries?  Also, can this be made more generic?  I tried replacing IO () with m b but then return () does not work.  How do you generically write return () for any monad? (If possible..)  Can even the Maybe be generalized here?

Lastly, can I do away with the doIf function entirely?  Can I have an operator <#> that applies an argument unless Nothing?

print <#> Just 3
print <#> Nothing

would output

3

But I don't know if this is possible.

Body:
Take a look at the function:

maybe :: b -> (a -> b) -> Maybe a -> b

You've almost written it in doIf except for the fixed return ()


问:
remove empty bins with reduce Add Remove function not working
I'm looking for a solution in how I can remove empty bins when using a reduce Add/Remove function.

I have a jsfiddle here

Empty bins are removed when I want to provide a simple sum of 'Points', but not when I want to use an average calculation and using the valueAccessor in the charts.

My data is set up as follows:

```<code>{Season:"2016/17",
Manager:"Alan Curtis",
Points:1,
Formation:"4231",
date:"01 February 2017"},

{Season:"2016/17",
Manager:"Paul Clement",
Points:1,
Formation:"442",
date:"01 February 2018"},

{Season:"2015/16",
Manager:"Paul Clement",
Points:3,
Formation:"433",
date:"01 May 2017"},
</code>```

And my aim is to provide a 'Points Per Game' average, by 'Manager', and also by 'Formation'.

I'm using the reduce Add/Remove functions:

```<code>function reduceAdd(p, v) {
    p.total += v.Points;
    ++p.count;
    p.ppg = d3.round((p.total / p.count), 2);
    return p;
    }

function reduceRemove(p, v) {
    p.total -= v.Points;
    --p.count;
    p.ppg = d3.round((p.total / p.count), 2);
    return p;
    }

function reduceInitial() {
    return {
        total: 0,
        count: 0,
        ppg: 0,
        };
    }
</code>```

and the remove empty bins code:

```<code>function remove_empty_bins(source_group) {
return {
    all:function () {
        return source_group.all().filter(function(d) {
            return d.value !=0;
        });
    }
};
}
</code>```

My charts code:

```<code>managerChart
    .dimension(dimManager)
    .group(ManagerPPGGroup)
    .ordering(function(p) { return -p.value.ppg })
    .renderLabel(false)
    .othersGrouper(null)
    .renderTitle(false)
    .renderTitleLabel(true)
    .margins({top: 10, left: 10, right: 20, bottom: 80})
    .valueAccessor(function(p)
        { if (p.value.ppg >0) {
        return p.value.ppg } else { return "n/a"}; });

formationChart
    .dimension(dimFormation)
    .group(filteredFormationPPGGroup)
    .ordering(function(p) { return -p.value.ppg })
    .renderLabel(false)
    .cap(10)
    .elasticX(true)
    .renderTitle(false)
    .renderTitleLabel(true)
    .margins({top: 10, left: 10, right: 20, bottom: 80})
    .valueAccessor(function(p) { return p.value.count > 0 ? p.value.ppg : "not used"; });
</code>```

Everything works fine, apart from empty bins are not removed when a filter is applied.

I have tried all sorts of things to try and fix the issue, changing the valueAccessor of the charts and the remove_empty_bins function but nothing seems to work.

My current workaround is to provide "not used" text on the graph so users know the Manager didn't use the formation, but I'd prefer to remove empty bins as intended.

Thanks in advance for your help.

答:
Yes, remove_empty_bins needs to be adjusted if the reduction produces an object instead of just a number.

I can't think of any general way to do this that won't make it inefficient,* so let's adjust the function for this use-case:

```<code>function remove_empty_bins(source_group) {
    return {
        all:function () {
            return source_group.all().filter(function(d) {
                return d.value.total != 0;
            });
        }
    };
}
</code>```

We just need to pull .total out of the object, because an object (almost) never equals zero.

As a bonus, I've also set the bars to a fixed height in your fiddle:

```<code>formationChart
    .fixedBarHeight(30)
</code>```

Otherwise when there is a single bar, it will grow to fit the entire area, which many people consider ugly.

I also applied filtering to the managers rowChart. Fork of your fiddle: https://jsfiddle.net/gordonwoodhull/qw0oe8ea/6/

* Maybe it's time to refactor this into remove_bins() with a predicate? But that won't be terse until the no-arrow-function browsers go away.

Body:
I'm looking for a solution in how I can remove empty bins when using a reduce Add/Remove function.

I have a jsfiddle here

Empty bins are removed when I want to provide a simple sum of 'Points', but not when I want to use an average calculation and using the valueAccessor in the charts.

My data is set up as follows:

{Season:"2016/17",
Manager:"Alan Curtis",
Points:1,
Formation:"4231",
date:"01 February 2017"},

{Season:"2016/17",
Manager:"Paul Clement",
Points:1,
Formation:"442",
date:"01 February 2018"},

{Season:"2015/16",
Manager:"Paul Clement",
Points:3,
Formation:"433",
date:"01 May 2017"},

And my aim is to provide a 'Points Per Game' average, by 'Manager', and also by 'Formation'.

I'm using the reduce Add/Remove functions:

function reduceAdd(p, v) {
    p.total += v.Points;
    ++p.count;
    p.ppg = d3.round((p.total / p.count), 2);
    return p;
    }

function reduceRemove(p, v) {
    p.total -= v.Points;
    --p.count;
    p.ppg = d3.round((p.total / p.count), 2);
    return p;
    }

function reduceInitial() {
    return {
        total: 0,
        count: 0,
        ppg: 0,
        };
    }

and the remove empty bins code:

function remove_empty_bins(source_group) {
return {
    all:function () {
        return source_group.all().filter(function(d) {
            return d.value !=0;
        });
    }
};
}

My charts code:

managerChart
    .dimension(dimManager)
    .group(ManagerPPGGroup)
    .ordering(function(p) { return -p.value.ppg })
    .renderLabel(false)
    .othersGrouper(null)
    .renderTitle(false)
    .renderTitleLabel(true)
    .margins({top: 10, left: 10, right: 20, bottom: 80})
    .valueAccessor(function(p)
        { if (p.value.ppg >0) {
        return p.value.ppg } else { return "n/a"}; });

formationChart
    .dimension(dimFormation)
    .group(filteredFormationPPGGroup)
    .ordering(function(p) { return -p.value.ppg })
    .renderLabel(false)
    .cap(10)
    .elasticX(true)
    .renderTitle(false)
    .renderTitleLabel(true)
    .margins({top: 10, left: 10, right: 20, bottom: 80})
    .valueAccessor(function(p) { return p.value.count > 0 ? p.value.ppg : "not used"; });

Everything works fine, apart from empty bins are not removed when a filter is applied.

I have tried all sorts of things to try and fix the issue, changing the valueAccessor of the charts and the remove_empty_bins function but nothing seems to work.

My current workaround is to provide "not used" text on the graph so users know the Manager didn't use the formation, but I'd prefer to remove empty bins as intended.

Thanks in advance for your help.

Body:
Yes, remove_empty_bins needs to be adjusted if the reduction produces an object instead of just a number.

I can't think of any general way to do this that won't make it inefficient,* so let's adjust the function for this use-case:

function remove_empty_bins(source_group) {
    return {
        all:function () {
            return source_group.all().filter(function(d) {
                return d.value.total != 0;
            });
        }
    };
}

We just need to pull .total out of the object, because an object (almost) never equals zero.

As a bonus, I've also set the bars to a fixed height in your fiddle:

formationChart
    .fixedBarHeight(30)

Otherwise when there is a single bar, it will grow to fit the entire area, which many people consider ugly.

I also applied filtering to the managers rowChart. Fork of your fiddle: https://jsfiddle.net/gordonwoodhull/qw0oe8ea/6/

* Maybe it's time to refactor this into remove_bins() with a predicate? But that won't be terse until the no-arrow-function browsers go away.


问:
Windows make application to run at system startup (user login)
I am trying to make my application launch at user login (system startup).
I found such solution:

app.manifest

```<code><requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />
</code>```

PreferencesWindows.xaml.cs

```<code> if (ServerSettings.ShouldApplicationAutostart)
  {
      SystemStartupService.AddThisAppToCurrentUserStartup();
  } else
  {
       SystemStartupService.DeleteThisAppFromCurrentUserStartup();
  }
</code>```

SystemStartupService.cs

```<code> public static void AddThisAppToCurrentUserStartup()
        {
            AddAppToCurrentUserStartup(Assembly.GetExecutingAssembly().GetName().Name,
                                       Assembly.GetExecutingAssembly().Location, true);
        }

        public static void AddAppToCurrentUserStartup(string appName, string appPath, bool asBackground) {
            using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
            {
                registryKey.SetValue(appName, "\"" + appPath + "\"" + (asBackground ? " /background" : "") );
            }
        }

        public static void DeleteThisAppFromCurrentUserStartup()
        {
            DeleteAppFromCurrentUserStartup(Assembly.GetExecutingAssembly().GetName().Name);
        }

        public static void DeleteAppFromCurrentUserStartup(string appName)
        {
            using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
            {
                registryKey.DeleteValue(appName, false);
            }
        }
</code>```

Problem is that this solution doesn't work for my app and I don't know why. The above code successfully adds entries in registry and System Configuration > Startup

regedit

TaskManager

If it matters this is simple wpf application running in notification try.

Problem: Application do not start at user login!

答: The above solution works correctly. I have some error in code in MainWindow.cs which cause that app couldn't start correctly. Moreover it was in OnInitialized() method which prevents Debugger from showing this error while autorun of app failed. This error was related to bad icon path (I have been using loading Icon resource from Assembly directory which work perfectly while running app directly from Visual Studio but files with odd path (not found image file) when auto launching app at startup). </p>

Body:
I am trying to make my application launch at user login (system startup).
I found such solution:

app.manifest

<requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />

PreferencesWindows.xaml.cs

 if (ServerSettings.ShouldApplicationAutostart)
  {
      SystemStartupService.AddThisAppToCurrentUserStartup();
  } else
  {
       SystemStartupService.DeleteThisAppFromCurrentUserStartup();
  }

SystemStartupService.cs

 public static void AddThisAppToCurrentUserStartup()
        {
            AddAppToCurrentUserStartup(Assembly.GetExecutingAssembly().GetName().Name,
                                       Assembly.GetExecutingAssembly().Location, true);
        }

        public static void AddAppToCurrentUserStartup(string appName, string appPath, bool asBackground) {
            using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
            {
                registryKey.SetValue(appName, "\"" + appPath + "\"" + (asBackground ? " /background" : "") );
            }
        }

        public static void DeleteThisAppFromCurrentUserStartup()
        {
            DeleteAppFromCurrentUserStartup(Assembly.GetExecutingAssembly().GetName().Name);
        }

        public static void DeleteAppFromCurrentUserStartup(string appName)
        {
            using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
            {
                registryKey.DeleteValue(appName, false);
            }
        }

Problem is that this solution doesn't work for my app and I don't know why. The above code successfully adds entries in registry and System Configuration > Startup

regedit

TaskManager

If it matters this is simple wpf application running in notification try.

Problem: Application do not start at user login!


问:
Accessing Redux state in an action creator?
Say I have the following:

```<code>export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
  return {
    type: SOME_ACTION,
  }
}
</code>```

And in that action creator, I want to access the global store state (all reducers). Is it better to do this:

```<code>import store from '../store';

export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
  return {
    type: SOME_ACTION,
    items: store.getState().otherReducer.items,
  }
}
</code>```

or this:

```<code>export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
  return (dispatch, getState) => {
    const {items} = getState().otherReducer;

    dispatch(anotherAction(items));
  }
}
</code>```

答:
I would like to point out that it is not that bad to read from the store -- it might be just much more convenient to decide what should be done based on the store, than to pass everything to the component and then as a parameter of a function. I agree with Dan completely, that it is much better not to use store as a singletone, unless you are 100% sure that you will use only for client-side rendering (otherwise hard to trace bugs might appear).

I have created a library recently to deal with verbosity of redux, and I think it is a good idea to put everything in the middleware, so you have everyhing as a dependency injection.

So, your example will look like that:

```<code>import { createSyncTile } from 'redux-tiles';

const someTile = createSyncTile({
  type: ['some', 'tile'],
  fn: ({ params, selectors, getState }) => {
    return {
      data: params.data,
      items: selectors.another.tile(getState())
    };
  },
});
</code>```

However, as you can see, we don't really modify data here, so there is a good chance that we can just use this selector in other place to combine it somewhere else.

Body:
Say I have the following:

export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
  return {
    type: SOME_ACTION,
  }
}

And in that action creator, I want to access the global store state (all reducers). Is it better to do this:

import store from '../store';

export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
  return {
    type: SOME_ACTION,
    items: store.getState().otherReducer.items,
  }
}

or this:

export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
  return (dispatch, getState) => {
    const {items} = getState().otherReducer;

    dispatch(anotherAction(items));
  }
}

Body:
I would like to point out that it is not that bad to read from the store -- it might be just much more convenient to decide what should be done based on the store, than to pass everything to the component and then as a parameter of a function. I agree with Dan completely, that it is much better not to use store as a singletone, unless you are 100% sure that you will use only for client-side rendering (otherwise hard to trace bugs might appear).

I have created a library recently to deal with verbosity of redux, and I think it is a good idea to put everything in the middleware, so you have everyhing as a dependency injection.

So, your example will look like that:

import { createSyncTile } from 'redux-tiles';

const someTile = createSyncTile({
  type: ['some', 'tile'],
  fn: ({ params, selectors, getState }) => {
    return {
      data: params.data,
      items: selectors.another.tile(getState())
    };
  },
});

However, as you can see, we don't really modify data here, so there is a good chance that we can just use this selector in other place to combine it somewhere else.


问:
SQL multiple insert with sleep
Is it possible to insert multiple data with delay kind of thing/sleep for a few second?
for example here, Im going to insert the values (1,2) into my user table. Then after 5 seconds, it will proceed to insert value (3,4) into the same table, wait for 5 seconds and finally insert (5,6) into the table.

```<code>INSERT INTO User (col1, col2)
VALUES (1, 2), (3, 4), (5, 6)
</code>```

Any suggestions are really appreciated!

答:
I found the solution. Maybe it's a bit messy but this is what I've come with and solved my problem. Basically I just need to use prepare if I want to reuse the statement.

```<code>$stmt = $dbh->prepare("INSERT INTO user (col1, col2) VALUES ('1','2');
$stmt2 = $dbh->prepare("INSERT INTO user (col1, col2) VALUES ('3','4');
$stmt3 = $dbh->prepare("INSERT INTO user (col1, col2) VALUES ('5','6');

{ $stmt->execute();
  sleep(5);
  $stmt2->execute();
  sleep(5);
  $stmt3->execute();
}
</code>```

That's all. Thanks for those who tried to solve this.

Title: SQL multiple insert with sleep

Body:
Is it possible to insert multiple data with delay kind of thing/sleep for a few second?
for example here, Im going to insert the values (1,2) into my user table. Then after 5 seconds, it will proceed to insert value (3,4) into the same table, wait for 5 seconds and finally insert (5,6) into the table.

INSERT INTO User (col1, col2)
VALUES (1, 2), (3, 4), (5, 6)

Any suggestions are really appreciated!

Body:
I found the solution. Maybe it's a bit messy but this is what I've come with and solved my problem. Basically I just need to use prepare if I want to reuse the statement.

$stmt = $dbh->prepare("INSERT INTO user (col1, col2) VALUES ('1','2');
$stmt2 = $dbh->prepare("INSERT INTO user (col1, col2) VALUES ('3','4');
$stmt3 = $dbh->prepare("INSERT INTO user (col1, col2) VALUES ('5','6');

{ $stmt->execute();
  sleep(5);
  $stmt2->execute();
  sleep(5);
  $stmt3->execute();
}

That's all. Thanks for those who tried to solve this.


问:
Can't change volume in HTML5 Audio tag in FireFox
On this page http://www.metrovancouver.org/services/solidwaste/Holiday/Pages/Song.aspx

I'm using a regular <audio> tag so users can listen to the song. I have a flash fallback on it too for users of IE.

In Chrome it works OK.

In FireFox 3.6.12, however, I cannot adjust the volume. If I put my mouse over the volume button, the volume slider appears, but as soon as I move my mouse to the slider to adjust, it disappears. I can mute the volume and unmute, but can't manually adjust the slider. Is anyone else having this problem?

答: It doesn't look like you are the only one.  This bug has been reported in bugzilla and is being looked into it seems.</p>


问:
How to send a square matrix through sockets in udp?
I'm using python 2.7 and i have to send a square matrix between two hosts using socket programming in udp. My code sends a string but not a matrix.

This is my code:

```<code>import socket
import thread
import time
import ctypes
matrix = [[1,2],[3,5]]
def c():
  #print (file.read())
  UDP_IP = "127.0.0.1"
  UDP_PORT = 5002
  #MESSAGE = "Hello, World!"
  print "UDP target IP:", UDP_IP
  print "UDP target port:", UDP_PORT
  #print ("message:", MESSAGE)
  sock = socket.socket(socket.AF_INET, # Internet
                       socket.SOCK_DGRAM) # UDP
  sock.sendto(matrix, (UDP_IP, UDP_PORT))

def s():
  UDP_IP = "127.0.0.1"
  UDP_PORT = 5002
  sock = socket.socket(socket.AF_INET, # Internet
                       socket.SOCK_DGRAM) # UDP
  sock.bind((UDP_IP, UDP_PORT))
  while True:
       data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
       print "received message:", data
while True:
      thread.start_new_thread(c, ())
      thread.start_new_thread(s, ())
      time.sleep(10)
</code>```

Also, I found this code online. It sends a matrix but i am unable deserialize it according to my needs (in matrix form as the input). If anyone can help me understand this that would be of much help.

Server end:

```<code>import socket, pickle
HOST = "127.0.0.1"
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(4096)
    if not data: break
    conn.send(data)
conn.close()
</code>```

Client end

```<code>import socket, pickle

HOST = "127.0.0.1"
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
arr = [[11111],[1,2,3,4],[1,2,3,4,5,6],[1,2,3,4,5,6]]
data_string = pickle.dumps(arr)
s.send(data_string)

data = s.recv(4096)
data_arr = pickle.loads(data)

s.close()
print 'Received', repr(data_arr)
</code>```

答:
First you should read from the same port, as you send data. Data has to be send as binary. You can use pickle as in your second example. Don't start server threads over and over again.

```<code>import socket
import time
import pickle
import threading

UDP_IP = "127.0.0.1"
UDP_PORT = 5002

def server():
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind((UDP_IP, UDP_PORT))
    while True:
         data, addr = sock.recvfrom(102400)
         matrix = pickle.loads(data)
         print "received message:", matrix

def send_matrix(matrix):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    data = pickle.dumps(matrix)
    sock.sendto(data, (UDP_IP, UDP_PORT))

threading.Thread(target=server).start()
matrix = [[1,2],[3,5]]
while True:
    send_matrix(matrix)
    time.sleep(10)
</code>```

Body:
I'm using python 2.7 and i have to send a square matrix between two hosts using socket programming in udp. My code sends a string but not a matrix.

This is my code:

import socket
import thread
import time
import ctypes
matrix = [[1,2],[3,5]]
def c():
  #print (file.read())
  UDP_IP = "127.0.0.1"
  UDP_PORT = 5002
  #MESSAGE = "Hello, World!"
  print "UDP target IP:", UDP_IP
  print "UDP target port:", UDP_PORT
  #print ("message:", MESSAGE)
  sock = socket.socket(socket.AF_INET, # Internet
                       socket.SOCK_DGRAM) # UDP
  sock.sendto(matrix, (UDP_IP, UDP_PORT))

def s():
  UDP_IP = "127.0.0.1"
  UDP_PORT = 5002
  sock = socket.socket(socket.AF_INET, # Internet
                       socket.SOCK_DGRAM) # UDP
  sock.bind((UDP_IP, UDP_PORT))
  while True:
       data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
       print "received message:", data
while True:
      thread.start_new_thread(c, ())
      thread.start_new_thread(s, ())
      time.sleep(10)

Also, I found this code online. It sends a matrix but i am unable deserialize it according to my needs (in matrix form as the input). If anyone can help me understand this that would be of much help.

Server end:

import socket, pickle
HOST = "127.0.0.1"
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(4096)
    if not data: break
    conn.send(data)
conn.close()

Client end

import socket, pickle

HOST = "127.0.0.1"
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
arr = [[11111],[1,2,3,4],[1,2,3,4,5,6],[1,2,3,4,5,6]]
data_string = pickle.dumps(arr)
s.send(data_string)

data = s.recv(4096)
data_arr = pickle.loads(data)

s.close()
print 'Received', repr(data_arr)

Body:
First you should read from the same port, as you send data. Data has to be send as binary. You can use pickle as in your second example. Don't start server threads over and over again.

import socket
import time
import pickle
import threading

UDP_IP = "127.0.0.1"
UDP_PORT = 5002

def server():
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind((UDP_IP, UDP_PORT))
    while True:
         data, addr = sock.recvfrom(102400)
         matrix = pickle.loads(data)
         print "received message:", matrix

def send_matrix(matrix):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    data = pickle.dumps(matrix)
    sock.sendto(data, (UDP_IP, UDP_PORT))

threading.Thread(target=server).start()
matrix = [[1,2],[3,5]]
while True:
    send_matrix(matrix)
    time.sleep(10)


问:
set ComboBox selected item by Key not by value c#
Before post this question ,I believe it is simple issue , I search for the answer and didn't find suitable solution.

in my daily work , I am working with web applications and can easily get or set values of dropdownlists

i can not do the same in windows application C#

I have combobox and class comboItem

```<code> public class ComboItem
    {
        public int Key { get; set; }
        public string Value { get; set; }
        public ComboItem(int key, string value)
        {
            Key = key; Value = value;
        }
        public override string ToString()
        {
            return Value;
        }
    }
</code>```

Say the combobox is binded through hard code and the values are

Key : 1  / Value : Male

Key : 2  / Value : Female

Key : 3  / Value : Unknown

lets say i have the Key =3 and I want to set this item ( whose key is 3 ) through code
so when form is loaded , the selected value by default will be Unknown.

```<code>combobox1.selectedValue =3 //Not Working , selectedValue used to return an object
combobox1.selectedIndex = 2 //Working as 2 is the index of key 3/Unknown
</code>```

but lets say i don't know the index , how can i get the index of item whose key = 3 ?

index can be get through value in this way

```<code>int index = combobox1.FindString("Unknown") //will return 2
</code>```

FindString take a value not a key , i need something like FindString which take a key and return index

NOTE :
Here is how i bind my drop down menu

```<code> JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings();
                        jsonSerializerSettings.MissingMemberHandling = MissingMemberHandling.Ignore;

                        var empResult= await response.Content.ReadAsStringAsync();
                        List<Emp> Emps= JsonConvert.DeserializeObject<Emp[]>(empResult, jsonSerializerSettings).ToList();
                        foreach (var item in Emps)
                        {
                            ComboItem CI = new ComboItem(int.Parse(item.ID), item.Name);
                            combobox1.Items.Add(CI);
                        }
                        this.combobox1.DisplayMember = "Value";
                        this.combobox1.ValueMember = "Key";
</code>```

答:
You need to set the ValueMember property so the ComboBox knows what property to deal with when SelectedValue is being used. By default the ValueMember will be empty. So when you set the SelectedValue, the ComboBox does not know what you want to set.

```<code>this.comboBox1.ValueMember = "Key";
</code>```

Normally, you would also set the DisplayMember property:

```<code>this.comboBox1.DisplayMember = "Value";
</code>```

If you do not set it, it will just call ToString() on the object and display that. In your case the ToString() returns the Value.

how can i get the index of item whose key = 3 ?

If you want the item whose key is 3, why do you need to get it from the combobox? You can just get it from the collection the combobox is bound to:

For example, imagine this:

```<code>var items = new List<ComboItem> { new ComboItem(1, "One"),
    new ComboItem( 2, "Two") };

this.comboBox1.DataSource = items;
this.comboBox1.DisplayMember = "Value";
this.comboBox1.ValueMember = "Key";

this.comboBox1.SelectedValue = 2;
</code>```

If I need the item whose key is 2, then this will achieve that:

```<code>// Use Single if you are not expecting a null
// Use Where if you are expecting many items
var itemWithKey2 = items.SingleOrDefault(x => x.Key == 2);
</code>```

Body:
Before post this question ,I believe it is simple issue , I search for the answer and didn't find suitable solution.

in my daily work , I am working with web applications and can easily get or set values of dropdownlists

i can not do the same in windows application C#

I have combobox and class comboItem

 public class ComboItem
    {
        public int Key { get; set; }
        public string Value { get; set; }
        public ComboItem(int key, string value)
        {
            Key = key; Value = value;
        }
        public override string ToString()
        {
            return Value;
        }
    }

Say the combobox is binded through hard code and the values are

Key : 1  / Value : Male

Key : 2  / Value : Female

Key : 3  / Value : Unknown

lets say i have the Key =3 and I want to set this item ( whose key is 3 ) through code
so when form is loaded , the selected value by default will be Unknown.

combobox1.selectedValue =3 //Not Working , selectedValue used to return an object
combobox1.selectedIndex = 2 //Working as 2 is the index of key 3/Unknown

but lets say i don't know the index , how can i get the index of item whose key = 3 ?

index can be get through value in this way

int index = combobox1.FindString("Unknown") //will return 2

FindString take a value not a key , i need something like FindString which take a key and return index

NOTE :
Here is how i bind my drop down menu

 JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings();
                        jsonSerializerSettings.MissingMemberHandling = MissingMemberHandling.Ignore;

                        var empResult= await response.Content.ReadAsStringAsync();
                        List<Emp> Emps= JsonConvert.DeserializeObject<Emp[]>(empResult, jsonSerializerSettings).ToList();
                        foreach (var item in Emps)
                        {
                            ComboItem CI = new ComboItem(int.Parse(item.ID), item.Name);
                            combobox1.Items.Add(CI);
                        }
                        this.combobox1.DisplayMember = "Value";
                        this.combobox1.ValueMember = "Key";

Body:
You need to set the ValueMember property so the ComboBox knows what property to deal with when SelectedValue is being used. By default the ValueMember will be empty. So when you set the SelectedValue, the ComboBox does not know what you want to set.

this.comboBox1.ValueMember = "Key";

Normally, you would also set the DisplayMember property:

this.comboBox1.DisplayMember = "Value";

If you do not set it, it will just call ToString() on the object and display that. In your case the ToString() returns the Value.

how can i get the index of item whose key = 3 ?

If you want the item whose key is 3, why do you need to get it from the combobox? You can just get it from the collection the combobox is bound to:

For example, imagine this:

var items = new List<ComboItem> { new ComboItem(1, "One"),
    new ComboItem( 2, "Two") };

this.comboBox1.DataSource = items;
this.comboBox1.DisplayMember = "Value";
this.comboBox1.ValueMember = "Key";

this.comboBox1.SelectedValue = 2;

If I need the item whose key is 2, then this will achieve that:

// Use Single if you are not expecting a null
// Use Where if you are expecting many items
var itemWithKey2 = items.SingleOrDefault(x => x.Key == 2);


问:
Powershell script to see currently logged in users (domain and machine) + status (active, idle, away)
I am searching for a simple command to see logged on users on server.
I know this one :

```<code>Get-WmiObject -Class win32_computersystem
</code>```

but this will not provide me the info I need.
It returns :
domain
Manufactureer
Model
Name (Machine name)
PrimaryOwnerName
TotalPhysicalMemory

I run Powershell 3.0 on a Windows 2012 server.

Also

```<code>Get-WmiObject Win32_LoggedOnUser -ComputerName $Computer | Select Antecedent -Unique
</code>```

gives me not the exact answers I need.
I would love to see as well the idle time, or if they are active or away.

答:
Maybe you can do something with </p>

```<code>get-process -includeusername
</code>```

Body:
I am searching for a simple command to see logged on users on server.
I know this one :

Get-WmiObject -Class win32_computersystem

but this will not provide me the info I need.
It returns :
domain
Manufactureer
Model
Name (Machine name)
PrimaryOwnerName
TotalPhysicalMemory

I run Powershell 3.0 on a Windows 2012 server.

Also

Get-WmiObject Win32_LoggedOnUser -ComputerName $Computer | Select Antecedent -Unique

gives me not the exact answers I need.
I would love to see as well the idle time, or if they are active or away.

Body:
Maybe you can do something with

get-process -includeusername

ContentLicense: CC BY-SA 4.0


问:
PHP - Session doesnt work on mobile
For login im using a session_start(), for desktop its works fine, but on mobile, it doesnt work. When I make a session_id() with variable, for example, session_id('login') its works on mobile, but break other sessions on other computers. But when session_id() is generated automatically, it doesn't work on mobile. What should I do?

My session_start code on index.php

```<code>session_start();
if (isset($_SESSION['username'])){
    session_id();
}
</code>```

Whole code for login.php file

```<code><?php
require('config.php');
$usernameOK = false; $passwordOK = false;
if (isset($_POST['username']) and isset($_POST['password'])){

        $username = $_POST['username'];
        $password = $_POST['password'];

        $UserQuery = "SELECT username FROM `members` WHERE username='$username'";
        $userTestResult = mysqli_query($connection, $UserQuery);
        $usernameTEST = mysqli_num_rows($userTestResult);
        if($usernameTEST == 1){$usernameOK = true;}

        $PasswordQuery = "SELECT password FROM `members` WHERE username='$username'";
        $result = mysqli_query($connection,$PasswordQuery);
        $row = mysqli_fetch_row($result);

        if (password_verify($password, $row[0])){$passwordOK = true;}

        if($usernameOK == true && $passwordOK == true){
            $_SESSION['username'] = $username;
        }else{
            $error_message = "Incorrect login data";
        }
    }

    if (isset($_SESSION['username'])){
        header("Location: ../");
        exit;
    }else{?>
    <form class="login-form" method="POST">
        <?php if(isset($error_message)){ ?><div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>

        <span class="placeholder">username</span>
        <input type="text" name="username" placeholder="username" required>

        <span class="placeholder">password</span>
        <input type="password" name="password" id="inputPassword" placeholder="password" required>

        <button type="submit">Login</button>
        <a class="form-link" href="register.php">Register</a>
    </form>

<?php } ?>
</code>```

答:
Simplified the code to make it easier to understand.Ignoring checks for username and password etc. You're basically trying to set a session variable. That happens in login.php. Code for that is.

```<code> <?php
 $username = "Umesh";
 if (isset($_SESSION))
 {
      $_SESSION['username'] = $username;
 }
 else
 {
           session_start();
           $_SESSION['username'] = $username;
 }
 print_r($_SESSION);
?>
</code>```

In index.php you're trying to check the session status.  The code is below.

```<code> if (isset($_SESSION['username'])){
session_id();
} else if (!isset($_SESSION)){
    session_start();
}
print_r($_SESSION);
</code>```

The above works for me on every browser and device.  I even tested chrome on iphone. It seems to work fine. Please check this and see if it works. If not, we will have to check your webserver to see, what the issue is, with session objects on that system.

I verified that  print_r ($_SESSION) was same in both cases.

Title: PHP - Session doesnt work on mobile

Body:
For login im using a session_start(), for desktop its works fine, but on mobile, it doesnt work. When I make a session_id() with variable, for example, session_id('login') its works on mobile, but break other sessions on other computers. But when session_id() is generated automatically, it doesn't work on mobile. What should I do?

My session_start code on index.php

session_start();
if (isset($_SESSION['username'])){
    session_id();
}

Whole code for login.php file

<?php
require('config.php');
$usernameOK = false; $passwordOK = false;
if (isset($_POST['username']) and isset($_POST['password'])){

        $username = $_POST['username'];
        $password = $_POST['password'];

        $UserQuery = "SELECT username FROM `members` WHERE username='$username'";
        $userTestResult = mysqli_query($connection, $UserQuery);
        $usernameTEST = mysqli_num_rows($userTestResult);
        if($usernameTEST == 1){$usernameOK = true;}

        $PasswordQuery = "SELECT password FROM `members` WHERE username='$username'";
        $result = mysqli_query($connection,$PasswordQuery);
        $row = mysqli_fetch_row($result);

        if (password_verify($password, $row[0])){$passwordOK = true;}

        if($usernameOK == true && $passwordOK == true){
            $_SESSION['username'] = $username;
        }else{
            $error_message = "Incorrect login data";
        }
    }

    if (isset($_SESSION['username'])){
        header("Location: ../");
        exit;
    }else{?>
    <form class="login-form" method="POST">
        <?php if(isset($error_message)){ ?>
 <?php echo $error_message; ?>
<?php } ?>

        username
        <input type="text" name="username" placeholder="username" required>

        password
        <input type="password" name="password" id="inputPassword" placeholder="password" required>

        <button type="submit">Login</button>
        Register
    </form>

<?php } ?>

Body:
Simplified the code to make it easier to understand.Ignoring checks for username and password etc. You're basically trying to set a session variable. That happens in login.php. Code for that is.

 <?php
 $username = "Umesh";
 if (isset($_SESSION))
 {
      $_SESSION['username'] = $username;
 }
 else
 {
           session_start();
           $_SESSION['username'] = $username;
 }
 print_r($_SESSION);
?>

In index.php you're trying to check the session status.  The code is below.

 if (isset($_SESSION['username'])){
session_id();
} else if (!isset($_SESSION)){
    session_start();
}
print_r($_SESSION);

The above works for me on every browser and device.  I even tested chrome on iphone. It seems to work fine. Please check this and see if it works. If not, we will have to check your webserver to see, what the issue is, with session objects on that system.

I verified that  print_r ($_SESSION) was same in both cases.


问:
Override NewRelic config file used by Cloud Foundry java build pack
I have a Spring Boot application deployed in Cloud Foundry, using the standard Java build pack. Since the app is bound to NewRelic, the build pack injects a NewRelic agent into the environment.

NewRelic documentation talks about adding a newrelic.yml file next to the agent jar location to customize instrumentation behavior. In the CF scenario, can it be located in the classpath of the deployed Spring Boot jar? How do I enable this behavior?

答:
In the CF scenario, can it be located in the classpath of the deployed Spring Boot jar? How do I enable this behavior?

I don't know about that, but two things you can do:

Specify additional configuration options for the NewRelic agent through your bound user provided service.

https://github.com/cloudfoundry/java-buildpack/blob/master/docs/framework-new_relic_agent.md#user-provided-service-optional

(Optional) Any additional entries will be applied as a system property appended to -Dnewrelic.config. to allow full configuration of the agent.

If you were to fork the Java build pack, you could overlay your own configuration file.

https://github.com/cloudfoundry/java-buildpack/blob/master/docs/framework-new_relic_agent.md#additional-resources

Your custom file would go here:  https://github.com/cloudfoundry/java-buildpack/blob/master/resources/new_relic_agent/newrelic.yml

You probably don't want to fork the build pack though as that creates a whole mess of other problems.

I guess a third option might be to use a .profile.d script, but that's a pain with Java apps because you have to put the files at the root of your JAR file.  It could work though.

https://docs.cloudfoundry.org/devguide/deploy-apps/deploy-app.html#profile

Hope that helps!


问:
Background images are overlapping while fetching from database?
I am fetching images from the database which is working but all images are overlapping. I want to display all images one by one. Would you help me in this?</p>

```<code>    .img {
    position: relative;
    float: left;
    width:  300px;
    height: 300px;
    background-position: 50% 50%;
    background-repeat:   no-repeat;
    background-size:     cover;
}

   <?php if ($result_related_products->num_rows > 0) { // output data of each row
          while($row = $result_related_products->fetch_assoc()) {
                      $p_img=$row['p_img'];
                      ?>
                        <div class="img" style="background-image: url('admin/assets/img/products/<?php echo $p_img; ?>')">
                             <?php }
                              }
           else { echo "0 results"; } ?>
</code>```

答:
You have to close the DIV

```<code></div>
</code>```

(In your while loop)

Body:
I am fetching images from the database which is working but all images are overlapping. I want to display all images one by one. Would you help me in this?

    .img {
    position: relative;
    float: left;
    width:  300px;
    height: 300px;
    background-position: 50% 50%;
    background-repeat:   no-repeat;
    background-size:     cover;
}

   <?php if ($result_related_products->num_rows > 0) { // output data of each row
          while($row = $result_related_products->fetch_assoc()) {
                      $p_img=$row['p_img'];
                      ?>
                        <div class="img" style="background-image: url('admin/assets/img/products/<?php echo $p_img; ?>')">
                             <?php }
                              }
           else { echo "0 results"; } ?>

Body:
You have to close the DIV

</div>

(In your while loop)


答:
You forgot to close the div

change this

```<code><div class="img" style="background-image: url('admin/assets/img/products/<?php echo $p_img; ?>')">
</code>```

for this (see at the end of line the
)

```<code><div class="img" style="background-image: url('admin/assets/img/products/<?php echo $p_img; ?>')"></div>
</code>```

Title: Background images are overlapping while fetching from database?

Body:
You forgot to close the div

change this

<div class="img" style="background-image: url('admin/assets/img/products/<?php echo $p_img; ?>')">

for this (see at the end of line the </div>)

<div class="img" style="background-image: url('admin/assets/img/products/<?php echo $p_img; ?>')"></div>


问:
on adding foreign key, if specify constraint it won't add
If I do this

```<code>  ALTER TABLE cp8_sales_order_flat
  ADD CONSTRAINT fk_customer
  FOREIGN KEY (customer_id)
  REFERENCES customers(id)
  ON DELETE SET NULL
  ON UPDATE CASCADE;
</code>```

it will say it cant add foreign key error 1215

if I just write

```<code>ALTER TABLE sales_flat_order
ADD FOREIGN KEY (customer_id) REFERENCES customers(id);
</code>```

then it adds the FK, and the constraint, but it is set as: restrict.

it seems to me that this would allow correct select join queries, but not deletes or updates. Why is this? any fix?

UPDATE

One of the reasons may also be that the column you are using for ON DELETE SET NULL is not defined to be null. So make sure that the column is set default null.

This is the one I think, as I checked everything else, type, collation, length, attribute

答: my column customer_id was set to be not null, while I was saying in my constraint that "on delete" set null, so this is what I call logical schizophrenia, like voting for more immigration when we have dozens of millions of unemployed people in Europe. Luckily here I can rewrite the constraint,not so in politics.</p>

Body:
If I do this

  ALTER TABLE cp8_sales_order_flat
  ADD CONSTRAINT fk_customer
  FOREIGN KEY (customer_id)
  REFERENCES customers(id)
  ON DELETE SET NULL
  ON UPDATE CASCADE;

it will say it cant add foreign key error 1215

if I just write

ALTER TABLE sales_flat_order
ADD FOREIGN KEY (customer_id) REFERENCES customers(id);

then it adds the FK, and the constraint, but it is set as: restrict.

it seems to me that this would allow correct select join queries, but not deletes or updates. Why is this? any fix?

UPDATE

One of the reasons may also be that the column you are using for ON DELETE SET NULL is not defined to be null. So make sure that the column is set default null.

This is the one I think, as I checked everything else, type, collation, length, attribute


问:
Join to a table only when column value is true
I am using SQL Server 2005. I am trying to join 2 tables together, but only when a column value in the main table is true. Like this:

```<code>select * from T1
join T2 on T1.value = T2.value
where T2.value2 = 'variable2'
and T2.value3 = 'variable3'
</code>```

There is a column value in T1 which says if I have to use the values in T2. I could to a case around the where clause, but it will always join to the table, and if the value in T1 is false, there are no values in T2 to join to, so the select returns no rows.

You can't put a case around the join, so I am a little bit stuck with this ... can anyone help ?

答:
Dave Marke is right, but more generaly...

conditional join is answer to your question, try find some resources on web for example

http://weblogs.sqlteam.com/jeffs/archive/2007/04/03/Conditional-Joins.aspx

http://bytes.com/groups/ms-sql/641690-difference-condition-join-where

it is very powerful technique to make joins depending on data in tables

OwnerDisplayName: Arni Gunnar Ragnarsson

Body:
I am using SQL Server 2005. I am trying to join 2 tables together, but only when a column value in the main table is true. Like this:

select * from T1
join T2 on T1.value = T2.value
where T2.value2 = 'variable2'
and T2.value3 = 'variable3'

There is a column value in T1 which says if I have to use the values in T2. I could to a case around the where clause, but it will always join to the table, and if the value in T1 is false, there are no values in T2 to join to, so the select returns no rows.

You can't put a case around the join, so I am a little bit stuck with this ... can anyone help ?

OwnerDisplayName: Cicik

LastEditorDisplayName: Cicik


问:
Remove a modified file from pull request
I have 3 modified files (no new files) in a pull request at the moment.

I would like to remove one of those files from the pull request, so that the pull request only contains changes to two files and leaves the third in its original, untouched state.

I have tried a couple things (checking out the original version of the file, etc...) but it still shows as a changed file in the PR.

Is there a solution to this?

答:
Switch to the branch from which you created the pull request:

```<code>$ git checkout pull-request-branch
</code>```

Overwrite the modified file(s) with the file in another branch, let's consider it's master:

```<code>git checkout origin/master -- src/main/java/HelloWorld.java
</code>```

Commit and push it to the remote:

```<code>git commit -m "Removed a modified file from pull request"
git push origin pull-request-branch
</code>```

Reference:

See git checkout docs:

```<code>git checkout [-f|--ours|--theirs|-m|--conflict=<style>] [<tree-ish>] [--] <pathspec>…
</code>```

Overwrite the contents of the files that match the pathspec. When the <tree-ish> (most often a commit) is not given, overwrite working tree with the contents in the index. When the <tree-ish> is given, overwrite both the index and the working tree with the contents at the <tree-ish>.

Anything within [] is optional. In our case, we want to overwrite   items identified by a specific pathspec with its respective content at a different branch/commit/tag

Body:
Switch to the branch from which you created the pull request:

$ git checkout pull-request-branch

Overwrite the modified file(s) with the file in another branch, let's consider it's master:

git checkout origin/master -- src/main/java/HelloWorld.java

Commit and push it to the remote:

git commit -m "Removed a modified file from pull request"
git push origin pull-request-branch

Reference:

See git checkout docs:

git checkout [-f|--ours|--theirs|-m|--conflict=<style>] [<tree-ish>] [--] <pathspec>…

Overwrite the contents of the files that match the pathspec. When the <tree-ish> (most often a commit) is not given, overwrite working tree with the contents in the index. When the <tree-ish> is given, overwrite both the index and the working tree with the contents at the <tree-ish>.

Anything within [] is optional. In our case, we want to overwrite   items identified by a specific pathspec with its respective content at a different branch/commit/tag


问:
Reverse Contents in Array
I have an array of numbers that I am trying to reverse. I believe the function in my code is correct, but I cannot get the proper output.

The output reads: 10 9 8 7 6.
Why can't I get the other half of the numbers? When I remove the "/2" from count, the output reads: 10 9 8 7 6 6 7 8 9 10

```<code>void reverse(int [], int);

int main ()
{
   const int SIZE = 10;
   int arr [SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

   reverse(arr, SIZE);
   return 0;
}
void reverse(int arr[], int count)
{
   int temp;
   for (int i = 0; i < count/2; ++i)
   {
      arr[i] = temp;
      temp = arr[count-i-1];
      arr[count-i-1] = arr[i];
      arr[i] = temp;

      cout << temp << " ";
   }
}
</code>```

答:
Your loop will run only for count/2 times. So it will not print the whole array.

Also, temp=ar[i] should be used instead of ar[i]=temp as value of ar[i] is not getting stored anywhere in the latter statement, hence it is getting destroyed.

Title: Reverse Contents in Array

Body:
I have an array of numbers that I am trying to reverse. I believe the function in my code is correct, but I cannot get the proper output.

The output reads: 10 9 8 7 6.
Why can't I get the other half of the numbers? When I remove the "/2" from count, the output reads: 10 9 8 7 6 6 7 8 9 10

void reverse(int [], int);

int main ()
{
   const int SIZE = 10;
   int arr [SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

   reverse(arr, SIZE);
   return 0;
}
void reverse(int arr[], int count)
{
   int temp;
   for (int i = 0; i < count/2; ++i)
   {
      arr[i] = temp;
      temp = arr[count-i-1];
      arr[count-i-1] = arr[i];
      arr[i] = temp;

      cout << temp << " ";
   }
}


问:
Can't deal with accents in Elasticsearch indexing and search
I have an issue with elasticsearch and the way the data are indexed/retrieved. I don't understand what happens.

This is the mapping I use (sorry, it's yaml format) :
The idea is simple, in theory... I have a string analyzer with lowercase and asciifolding filters. I don't want to care about case or accents, and I would like to use this analyzer to index and search.

```<code>settings:
    index:
        analysis:
            filter:
                autocomplete_filter:
                    type: edgeNGram
                    side: front
                    min_gram: 1
                    max_gram: 20
            analyzer:
                autocomplete:
                    type: custom
                    tokenizer: standard
                    filter: [lowercase, asciifolding, autocomplete_filter]
                string_analyzer:
                    type:        custom
                    tokenizer:   standard
                    filter:      [lowercase, asciifolding]
types:
    city:
        mappings:
            cityName:
                type: string
                analyzer: string_analyzer
                search_analyzer: string_analyzer
            location: {type: geo_point}
</code>```

When I run this query :

```<code>{
    "query": {
        "prefix":{
            "cityName":"per"
        }
    }
    ,
    "size":20
}
</code>```

I get some results like "Perpezat", "Pern", "Péreuil" which is the excepted result.

But if I run the following query :

```<code>{
    "query": {
        "prefix":{
            "cityName":"pér"
        }
    }
    ,
    "size":20
}
</code>```

Then I get no result at all.

If you have any clue or help, I would be happy to know it.
Thanks

答:
In the Prefix Query, your search input is not analyzed like in other cases:

Matches documents that have fields containing terms with a specified prefix (not analyzed)

Your first example works because the documents are analyzed at index time  using your analyzer with lowercase and asciifolding, so they contain a term starting with per (perpezat, pern, pereuil).

Your second example does not work because those documents don't contain any terms starting with pér.

Since I couldn't find a way to tell Elasticsearch to analyze the prefix before performing the search, you could achieve your goal by manually adding this step:

Ask Elastisearch to analyze your input calling the Analyze API

Use the output from step 1 (it should be per in the examples) for the prefix query

For this to work, your search input should be a single term (I think that could be why Elasticsearch doesn't want to analyze it in the first place)

Body:
I have an issue with elasticsearch and the way the data are indexed/retrieved. I don't understand what happens.

This is the mapping I use (sorry, it's yaml format) :
The idea is simple, in theory... I have a string analyzer with lowercase and asciifolding filters. I don't want to care about case or accents, and I would like to use this analyzer to index and search.

settings:
    index:
        analysis:
            filter:
                autocomplete_filter:
                    type: edgeNGram
                    side: front
                    min_gram: 1
                    max_gram: 20
            analyzer:
                autocomplete:
                    type: custom
                    tokenizer: standard
                    filter: [lowercase, asciifolding, autocomplete_filter]
                string_analyzer:
                    type:        custom
                    tokenizer:   standard
                    filter:      [lowercase, asciifolding]
types:
    city:
        mappings:
            cityName:
                type: string
                analyzer: string_analyzer
                search_analyzer: string_analyzer
            location: {type: geo_point}

When I run this query :

{
    "query": {
        "prefix":{
            "cityName":"per"
        }
    }
    ,
    "size":20
}

I get some results like "Perpezat", "Pern", "Péreuil" which is the excepted result.

But if I run the following query :

{
    "query": {
        "prefix":{
            "cityName":"pér"
        }
    }
    ,
    "size":20
}

Then I get no result at all.

If you have any clue or help, I would be happy to know it.
Thanks


问:
How to fix getCount() in viewPager adapter in Android
I want use viewPager in my application and I want use this library: UltraViewPager.

I write below codes in adapter:

```<code>public class BoxOfficeAdapter extends PagerAdapter {
    private Context context;
    private List<BoxOfficeDatum> model;
    private LayoutInflater inflater;
    private BoxOfficeDateListener listener;

    public BoxOfficeAdapter(Context context, List<BoxOfficeDatum> model, BoxOfficeDateListener listener) {
        this.context = context;
        this.model = model;
        this.listener = listener;
        this.inflater = (LayoutInflater) this.context.getSystemService(this.context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return model.size();
    }

    @Override
    public Object instantiateItem(final ViewGroup container, final int position) {
        View view = this.inflater.inflate(R.layout.row_box_office, container, false);

        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }
</code>```

But when run application, show me this error :

```<code>FATAL EXCEPTION: main
                                                                       Process: com.example.app, PID: 5948
                                                                       java.lang.NullPointerException: Attempt to invoke virtual method 'int com.tmall.ultraviewpager.UltraViewPagerAdapter.getCount()' on a null object reference
                                                                           at com.tmall.ultraviewpager.UltraViewPagerView.getCurrentItem(UltraViewPagerView.java:220)
                                                                           at com.tmall.ultraviewpager.UltraViewPagerView.onMeasurePage(UltraViewPagerView.java:88)
                                                                           at com.tmall.ultraviewpager.UltraViewPagerView.onMeasure(UltraViewPagerView.java:84)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                                           at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                                           at com.tmall.ultraviewpager.UltraViewPager.onMeasure(UltraViewPager.java:177)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                                           at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6162)
                                                                           at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                           at android.support.v7.widget.CardView.onMeasure(CardView.java:211)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                                           at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.support.v4.widget.NestedScrollView.measureChildWithMargins(NestedScrollView.java:1420)
                                                                           at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                           at android.support.v4.widget.NestedScrollView.onMeasure(NestedScrollView.java:482)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                                           at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6162)
                                                                           at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1658)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                                           at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6162)
                                                                           at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                           at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6162)
                                                                           at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                                                                           at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                                                                           at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6162)
                                                                           at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6162)
                                                                           at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                                                                           at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                                                                           at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6162)
                                                                           at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                           at com.android.internal.policy.DecorView.onMeasure(DecorView.java:688)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2335)
                                                                           at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1410)
06-04 16:37:47.075 5948-5948/com.example.app E/AndroidRuntime:     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1660)
                                                                           at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1286)
                                                                           at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6536)
                                                                           at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
                                                                           at android.view.Choreographer.doCallbacks(Choreographer.java:683)
                                                                           at android.view.Choreographer.doFrame(Choreographer.java:619)
                                                                           at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
                                                                           at android.os.Handler.handleCallback(Handler.java:751)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                           at android.os.Looper.loop(Looper.java:154)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:6247)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
</code>```

How can I fix it?

答:
List is null that why null Pointer is coming .
try different method to set data from response to your list

Like:

```<code>BoxOfficeResponse responseBody=response.body();
boxOfficeModel.addAll(responseBody.getBoxOfficeData().getBoxOfficeDatum())
</code>```

or

```<code>for(int i=0; i<responseBody.getBoxOfficeData().getBoxOfficeDatum(); i++){
 boxOfficeModel.add(responseBody.getBoxOfficeData().getBoxOfficeDatum().get(i))
}
</code>```

Body:
I want use viewPager in my application and I want use this library: UltraViewPager.

I write below codes in adapter:

public class BoxOfficeAdapter extends PagerAdapter {
    private Context context;
    private List<BoxOfficeDatum> model;
    private LayoutInflater inflater;
    private BoxOfficeDateListener listener;

    public BoxOfficeAdapter(Context context, List<BoxOfficeDatum> model, BoxOfficeDateListener listener) {
        this.context = context;
        this.model = model;
        this.listener = listener;
        this.inflater = (LayoutInflater) this.context.getSystemService(this.context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return model.size();
    }

    @Override
    public Object instantiateItem(final ViewGroup container, final int position) {
        View view = this.inflater.inflate(R.layout.row_box_office, container, false);

        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

But when run application, show me this error :

FATAL EXCEPTION: main
                                                                       Process: com.example.app, PID: 5948
                                                                       java.lang.NullPointerException: Attempt to invoke virtual method 'int com.tmall.ultraviewpager.UltraViewPagerAdapter.getCount()' on a null object reference
                                                                           at com.tmall.ultraviewpager.UltraViewPagerView.getCurrentItem(UltraViewPagerView.java:220)
                                                                           at com.tmall.ultraviewpager.UltraViewPagerView.onMeasurePage(UltraViewPagerView.java:88)
                                                                           at com.tmall.ultraviewpager.UltraViewPagerView.onMeasure(UltraViewPagerView.java:84)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                                           at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                                           at com.tmall.ultraviewpager.UltraViewPager.onMeasure(UltraViewPager.java:177)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                                           at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6162)
                                                                           at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                           at android.support.v7.widget.CardView.onMeasure(CardView.java:211)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                                           at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.support.v4.widget.NestedScrollView.measureChildWithMargins(NestedScrollView.java:1420)
                                                                           at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                           at android.support.v4.widget.NestedScrollView.onMeasure(NestedScrollView.java:482)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                                           at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6162)
                                                                           at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1658)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                                           at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6162)
                                                                           at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                           at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6162)
                                                                           at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                                                                           at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                                                                           at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6162)
                                                                           at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6162)
                                                                           at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                                                                           at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                                                                           at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6162)
                                                                           at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                           at com.android.internal.policy.DecorView.onMeasure(DecorView.java:688)
                                                                           at android.view.View.measure(View.java:19826)
                                                                           at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2335)
                                                                           at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1410)
06-04 16:37:47.075 5948-5948/com.example.app E/AndroidRuntime:     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1660)
                                                                           at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1286)
                                                                           at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6536)
                                                                           at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
                                                                           at android.view.Choreographer.doCallbacks(Choreographer.java:683)
                                                                           at android.view.Choreographer.doFrame(Choreographer.java:619)
                                                                           at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
                                                                           at android.os.Handler.handleCallback(Handler.java:751)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                           at android.os.Looper.loop(Looper.java:154)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:6247)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)

How can I fix it?

Body:
List is null that why null Pointer is coming .
try different method to set data from response to your list

Like:

BoxOfficeResponse responseBody=response.body();
boxOfficeModel.addAll(responseBody.getBoxOfficeData().getBoxOfficeDatum())

or

for(int i=0; i<responseBody.getBoxOfficeData().getBoxOfficeDatum(); i++){
 boxOfficeModel.add(responseBody.getBoxOfficeData().getBoxOfficeDatum().get(i))
}


问:
What's the difference of two tensorflow variable names?
A new beginner of tensorflow and a simple question is:
I saw a code:

```<code>W1 = tf.Variable(tf.zero((2,2)),name="weights")
</code>```

What is the different with "W1" and "weights"?

答:
In short, weights is the unique name of the variable in the Tensorflow graph, and W1 is the name of the python variable pointing to the Tensorflow variable. If you then assign W1 to a new variable; e.g W2 = W1, you'll see that the name of W2 is also weights; different python names (and variables), same Tensorflow name (and variable).

Naming a new variable with name='weights' will actually create a variable with the name weights_1:0 :

```<code>>>> tf.Variable(tf.zeros((2,2)), name="weights")
<tf.Variable 'weights_1:0' shape=(2, 2) dtype=float32_ref>
</code>```

Body:
A new beginner of tensorflow and a simple question is:
I saw a code:

W1 = tf.Variable(tf.zero((2,2)),name="weights")

What is the different with "W1" and "weights"?

Body:
In short, weights is the unique name of the variable in the Tensorflow graph, and W1 is the name of the python variable pointing to the Tensorflow variable. If you then assign W1 to a new variable; e.g W2 = W1, you'll see that the name of W2 is also weights; different python names (and variables), same Tensorflow name (and variable).

Naming a new variable with name='weights' will actually create a variable with the name weights_1:0 :

>>> tf.Variable(tf.zeros((2,2)), name="weights")
<tf.Variable 'weights_1:0' shape=(2, 2) dtype=float32_ref>