问:
Laravel FatalErrorException
I created a new view, route and controller in laravel and when i go to access the view i get an error, all other views are fine.

Error
FatalErrorException in shopsalescontroller.php line 11: syntax error, unexpected 'class' (T_CLASS), expecting ',' or ';'

this is my shop sales controller:

```<code>   <?php
   namespace App\Http\Controllers;
   use Illuminate\Http\Request;
   use App\Http\Requests;
   use App\shopsales

   class shopsalescontroller extends Controller : (line 11)
    {
     public function index()
      {
       $storeNum = request('storeNum');
       $results = shopsales::where('StoreNumber','=',$storeNum)->get();
       return view('shopSales',compact('results'));
      }
    }
</code>```

PHP version 5.6.3
Zend engine v2.6.0

Laravel framework version 5.2.45

答:
You missed a semicolon on this line:</p>

```<code>use App\shopsales;
</code>```

Title: Laravel FatalErrorException

Body:
I created a new view, route and controller in laravel and when i go to access the view i get an error, all other views are fine.

Error
FatalErrorException in shopsalescontroller.php line 11: syntax error, unexpected 'class' (T_CLASS), expecting ',' or ';'

this is my shop sales controller:

   <?php
   namespace App\Http\Controllers;
   use Illuminate\Http\Request;
   use App\Http\Requests;
   use App\shopsales

   class shopsalescontroller extends Controller : (line 11)
    {
     public function index()
      {
       $storeNum = request('storeNum');
       $results = shopsales::where('StoreNumber','=',$storeNum)->get();
       return view('shopSales',compact('results'));
      }
    }

PHP version 5.6.3
Zend engine v2.6.0

Laravel framework version 5.2.45

Body:
You missed a semicolon on this line:

use App\shopsales;


来源: stackexchange

问:
How to create a AngularJS promise from a callback-based API
wifiservice.js:

```<code>angular.module('app.WifiServices', [])
    .factory('WifiService', function(){
        var unique_array = angular.fromJson('[]');

        function win_wifi(e){
        alert("Success");
        }

        function fail_wifi(e){
        alert("Error");
        }

        function connectWifi(wifi_ssid){
          WifiWizard.connectNetwork(wifi_ssid, win_wifi, fail_wifi);
        }

        function listHandler(a){

      var network_array = [];
      for(var i=0; i<a.length; i++){
        network_array.push("SSID: " + a[i].SSID + " Signal: " + a[i].level);
      }

      unique_array = network_array.filter(function(elem, pos) {
        return network_array.indexOf(elem) == pos;
      });

      // alert("Wifi List Ready!");
    }

    function getScanResult(){
      WifiWizard.getScanResults(listHandler, failNetwork);
    }

    function successNetwork(e){
      window.setTimeout(function(){
        getScanResult();
      }, 3000);
    }

    function failNetwork(e){
      alert("Network Failure: " + e);
    }

    window.setTimeout(function(){
      WifiWizard.startScan(successNetwork, failNetwork);
    }, 1000);

        return {
          list: function(){
            return unique_array;
          },

          connectionToWifi: function(name){
            connectWifi(name);
          }
        };
    });
</code>```

My whole controller:

```<code>app.controller('WifiController', ['$scope', 'WifiService', function($scope, WifiService) {

 $scope.wifiList = [];

 window.setTimeout(function() {
  $scope.wifiList = WifiService.list();
  // alert($scope.wifiList);
  $scope.$apply();
 }, 5000);

 $scope.getList = function() {
  $scope.wifiList = WifiService.list();
  return $scope.wifiList;
 }

 $scope.connectWifi = function(name) {
  WifiService.connectionToWifi(name);
 }

 $scope.checkin = function() {
  $scope.getList()
  .then(function(result) {
     console.log(result);
 });
}

}]);
</code>```

What I am trying to do is, to call the $scope.getList(), which returns a list of the surrounding wifi SSIDs, then within $scope.checkin() I would like to process those data.

Since scanning needs some time I have to wait the getList function to finish, thats Why I am trying to use .then, but it gives me the error says on the title. Any ideas?

答:
How to create a AngularJS promise from a callback-based API

To create an AngularJS promise from a callback-based API such as WifiWizard.connectNetwork, use $q.defer:

```<code>function connectWifi(wifi_ssid) {
   var future = $q.defer();
   var win_wifi = future.resolve;
   var fail_wifi = future.reject;
   WifiWizard.connectNetwork(wifi_ssid, win_wifi, fail_wifi);
   return future.promise;
};
</code>```

The above example returns a $q Service promise that either resolves or rejects using the callbacks from the API.

ContentLicense: CC BY-SA 3.0

Body:
wifiservice.js:

angular.module('app.WifiServices', [])
    .factory('WifiService', function(){
        var unique_array = angular.fromJson('[]');

        function win_wifi(e){
        alert("Success");
        }

        function fail_wifi(e){
        alert("Error");
        }

        function connectWifi(wifi_ssid){
          WifiWizard.connectNetwork(wifi_ssid, win_wifi, fail_wifi);
        }

        function listHandler(a){

      var network_array = [];
      for(var i=0; i<a.length; i++){
        network_array.push("SSID: " + a[i].SSID + " Signal: " + a[i].level);
      }

      unique_array = network_array.filter(function(elem, pos) {
        return network_array.indexOf(elem) == pos;
      });

      // alert("Wifi List Ready!");
    }

    function getScanResult(){
      WifiWizard.getScanResults(listHandler, failNetwork);
    }

    function successNetwork(e){
      window.setTimeout(function(){
        getScanResult();
      }, 3000);
    }

    function failNetwork(e){
      alert("Network Failure: " + e);
    }

    window.setTimeout(function(){
      WifiWizard.startScan(successNetwork, failNetwork);
    }, 1000);

        return {
          list: function(){
            return unique_array;
          },

          connectionToWifi: function(name){
            connectWifi(name);
          }
        };
    });

My whole controller:

app.controller('WifiController', ['$scope', 'WifiService', function($scope, WifiService) {

 $scope.wifiList = [];

 window.setTimeout(function() {
  $scope.wifiList = WifiService.list();
  // alert($scope.wifiList);
  $scope.$apply();
 }, 5000);

 $scope.getList = function() {
  $scope.wifiList = WifiService.list();
  return $scope.wifiList;
 }

 $scope.connectWifi = function(name) {
  WifiService.connectionToWifi(name);
 }

 $scope.checkin = function() {
  $scope.getList()
  .then(function(result) {
     console.log(result);
 });
}

}]);

What I am trying to do is, to call the $scope.getList(), which returns a list of the surrounding wifi SSIDs, then within $scope.checkin() I would like to process those data.

Since scanning needs some time I have to wait the getList function to finish, thats Why I am trying to use .then, but it gives me the error says on the title. Any ideas?

Body:
How to create a AngularJS promise from a callback-based API

To create an AngularJS promise from a callback-based API such as WifiWizard.connectNetwork, use $q.defer:

function connectWifi(wifi_ssid) {
   var future = $q.defer();
   var win_wifi = future.resolve;
   var fail_wifi = future.reject;
   WifiWizard.connectNetwork(wifi_ssid, win_wifi, fail_wifi);
   return future.promise;
};

The above example returns a $q Service promise that either resolves or rejects using the callbacks from the API.

ContentLicense: CC BY-SA 4.0


问:
Using Liquibase with OSGI and Hibernate
I would like to integrate a Liquibase to my project.  My first idea was to use a blueprint's bean that starts the Liquibase update from an onInit method. But there was a problem with a hibernate, because we have "hbm2ddl.auto" set to "validate" and validation was executed before my bean's onInit. (we use container managed persistence with persistence.xml in META-INF). So my second attemp was to use BundleTracker and when some entry in manifest exists, the liquibase performs db update. It is working well but I would like to enforce that bundle won't start if update of database won't be successful. But I don't have any idea how to do it from BundleTracker method addBundle. Is there any way how to prevent starting bundle from BundleTracker event? </p>

<p>I have another possible idea for doing it to create some addition bundle that performs update and other bundle with persistence.xml will depend on this bundle. But we have a lot of bundles with persistence.xml that`s why the solution with BundleTracker seems better to me. </p>

答:
You might be able to use the newest pax-jdbc-config for this task. It provides a DataSource service from a configuration. So this in it self is already a useful abstraction.

The newest version now contains a feature called PreHook. Basically you implement an OSGi service that implements the PreHook interface and publish it with a name property. In your DataSource config you can then refer to that service by its name. When the DataSource is created this service is called before the DataSource is published for use by other bundles. So inside the PreHook you can work on the databse using liquibase and the hibernate based bundle will only see the DataSource when the database is in the new state.

For an example see also the integration test for the PreHook.

Title: Using Liquibase with OSGI and Hibernate

Body:
I would like to integrate a Liquibase to my project.  My first idea was to use a blueprint's bean that starts the Liquibase update from an onInit method. But there was a problem with a hibernate, because we have "hbm2ddl.auto" set to "validate" and validation was executed before my bean's onInit. (we use container managed persistence with persistence.xml in META-INF). So my second attemp was to use BundleTracker and when some entry in manifest exists, the liquibase performs db update. It is working well but I would like to enforce that bundle won't start if update of database won't be successful. But I don't have any idea how to do it from BundleTracker method addBundle. Is there any way how to prevent starting bundle from BundleTracker event?

I have another possible idea for doing it to create some addition bundle that performs update and other bundle with persistence.xml will depend on this bundle. But we have a lot of bundles with persistence.xml that`s why the solution with BundleTracker seems better to me.


问:
Pinterest API stop working
We are offering Pinterest Pin scheduling features to our customer from last 1.5 years. We are suddenly started getting error response "Something went wrong on our end. Sorry about that." from today.

I have tried the Pinterest API explorer and also getting the same error message. The strange part is, though we are getting an error message, Pin is created with a broken image. I.e. https://in.pinterest.com/pin/573434965041286865/, When we try to open Image URL directly in browser i.e. https://s-media-cache-ak0.pinimg.com/originals/d0/ad/c8/d0adc8520559848912b22f392eb339c1.jpg, it shows Access Denied error.

Is there any API changes or any other issue? We are currently passing the image as image_url parameters. We have tried sending a picture as multipart/form with image parameter too, but we are getting the same error.

here is the sample of our request.

URL: https://api.pinterest.com/v1/pins/?access_token=&fields=id%2Clink%2Cnote%2Curl

Form Data:
image_url:http://d1ttb7iswciaye.cloudfront.net/wp-content/uploads/2015/06/slide1_img.png
note:Take one step forward, and then one more. It's all possible if you keep taking a small step forward#ows #success #possible
board:573435033743083706

Also, is there any way to connect to Pinterest support? Their help form at https://developers.pinterest.com/support/contact/ is also not working.

答: Now the bug is resolved . My pin is created with photos .</p>

Title: Pinterest API stop working


问:
RED HAT BRMS installation error on EAP7
While installing 'jboss-brms-6.3.0.GA-installer.jar' on my EAP 7.0 ('jboss-eap-7.0.0-installer.jar') I am getting error in BRMS installation wizard as below.

```<code>The provided EAP installation is missing the following required files:
\standalone\configuration\standalone-osgi.xml
</code>```

'standalone-osgi.xml' didn't come along with EAP 7 installation.

Can anyone please help me?

答:
From Redhat JBoss BPM Suite installation Guide: link

Section 2.1: This section describes the steps required to install Red Hat JBoss BPM Suite using the JAR file installer installation method. The JAR file is an executable file that installs Red Hat JBoss BPM Suite on an existing Red Hat JBoss EAP 6 installation.
However, the JAR installer does not support Red Hat JBoss EAP 7.0. For Red Hat JBoss EAP 7.0, only Deployable Zip installation option is supported.

So to install BPM/BRMS on EAP 7 You have 2 use the ZIP file.
EAP download page link.

You can find the steps required for installing with ZIP

Title: RED HAT BRMS installation error on EAP7

Body:
While installing 'jboss-brms-6.3.0.GA-installer.jar' on my EAP 7.0 ('jboss-eap-7.0.0-installer.jar') I am getting error in BRMS installation wizard as below.

The provided EAP installation is missing the following required files:
\standalone\configuration\standalone-osgi.xml

'standalone-osgi.xml' didn't come along with EAP 7 installation.

Can anyone please help me?


问:
Published output looking for wrong dependency

Goal

I have two .NET Core console applications - Application.dll and Updater.dll. I want to publish Updater.dll (with all its dependencies) together with Application.dll to a folder using MSBuild publish.

What I tried (Minimal Working Example)

I created a very small toy example which illustrates my problem (the solution can be downloaded here).

The Updater source and project file look like this:

```<code>using System;
using System.ServiceProcess;

namespace Updater
{
    class Program
    {
        static void Main(string[] args)
        {
            const string SERVICE_NAME = "TestService";
            try
            {
                var serviceController = new ServiceController(SERVICE_NAME);
                Console.WriteLine($"Status of {SERVICE_NAME}: {serviceController.Status}");
            }
            catch
            {
                Console.WriteLine($"Error getting {SERVICE_NAME}");
            }
        }
    }
}
</code>```

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="System.ServiceProcess.ServiceController" Version="4.3.0" />
  </ItemGroup>

</Project>
</code>```

The Application source and project file look like this:

```<code>using System;
using System.Diagnostics;

namespace Application
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}
</code>```

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <ProjectReference Include="..\Updater\Updater.csproj" />
  </ItemGroup>

  <!-- make sure the runtimeconfig of the referenced Updater is also included in the output -->
  <ItemGroup>
    <Content Include="..\Updater\bin\$(Configuration)\netcoreapp1.1\Updater.runtimeconfig.json" CopyToOutputDirectory="Always"></Content>
  </ItemGroup>

</Project>
</code>```

Ant this is the publish configuration I use for Application:

```<code><?xml version="1.0" encoding="utf-8"?>
<!--
This file is used by the publish/package process of your Web project. You can customize the behavior of this process
by editing this MSBuild file. In order to learn more about this please visit https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <PublishProtocol>FileSystem</PublishProtocol>
    <Configuration>Debug</Configuration>
    <TargetFramework>netcoreapp1.1</TargetFramework>
    <PublishDir>bin\Debug\PublishOutput</PublishDir>
  </PropertyGroup>
</Project>
</code>```

I can successfully build and run these two programs in the debugger. I can also publish the Application project and the Updater and its dependencies are included:

```<code>PublishOutput\runtimes\unix\lib\netstandard1.5\System.ServiceProcess.ServiceController.dll
PublishOutput\runtimes\win\lib\netstandard1.5\System.ServiceProcess.ServiceController.dll
PublishOutput\Application.deps.json
PublishOutput\Application.dll
PublishOutput\Application.pdb
PublishOutput\Application.runtimeconfig.json
PublishOutput\Updater.dll
PublishOutput\Updater.pdb
PublishOutput\Updater.runtimeconfig.json
</code>```

Also I can run the Application itself from the published output like this:

```<code>dotnet Application.dll
</code>```

Problem

I cannot run the Updater from the published output. When I try this:

```<code>dotnet Updater.dll
</code>```

It crashes with the following exception:

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'System.ServiceProcess.ServiceController, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.
     at Updater.Program.Main(String[] args)

Interestingly it is looking for version 4.1.0.0 of System.ServiceProcess.ServiceController. But as you can see in the project file, I'm actually referencing version 4.3.0

What am I doing wrong here? What do I need to change so that I can run the Updater from the published output?

答:
Updater.deps.json was missing in the published output. The following change was needed in the project file of the Application.

Before:

```<code><ItemGroup>
  <Content Include="..\Updater\bin\$(Configuration)\netcoreapp1.1\Updater.runtimeconfig.json" CopyToOutputDirectory="Always"></Content>
</ItemGroup>
</code>```

After:

```<code><ItemGroup>
  <Content Include="..\Updater\bin\$(Configuration)\netcoreapp1.1\Updater.runtimeconfig.json" CopyToOutputDirectory="Always"></Content>
  <Content Include="..\Updater\bin\$(Configuration)\netcoreapp1.1\Updater.deps.json" CopyToOutputDirectory="Always"></Content>
</ItemGroup>
</code>```

Body:
Goal

I have two .NET Core console applications - Application.dll and Updater.dll. I want to publish Updater.dll (with all its dependencies) together with Application.dll to a folder using MSBuild publish.

What I tried (Minimal Working Example)

I created a very small toy example which illustrates my problem (the solution can be downloaded here).

The Updater source and project file look like this:

using System;
using System.ServiceProcess;

namespace Updater
{
    class Program
    {
        static void Main(string[] args)
        {
            const string SERVICE_NAME = "TestService";
            try
            {
                var serviceController = new ServiceController(SERVICE_NAME);
                Console.WriteLine($"Status of {SERVICE_NAME}: {serviceController.Status}");
            }
            catch
            {
                Console.WriteLine($"Error getting {SERVICE_NAME}");
            }
        }
    }
}

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="System.ServiceProcess.ServiceController" Version="4.3.0" />
  </ItemGroup>

</Project>

The Application source and project file look like this:

using System;
using System.Diagnostics;

namespace Application
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <ProjectReference Include="..\Updater\Updater.csproj" />
  </ItemGroup>

  <ItemGroup>
    <Content Include="..\Updater\bin\$(Configuration)\netcoreapp1.1\Updater.runtimeconfig.json" CopyToOutputDirectory="Always"></Content>
  </ItemGroup>

</Project>

Ant this is the publish configuration I use for Application:

<?xml version="1.0" encoding="utf-8"?>

<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <PublishProtocol>FileSystem</PublishProtocol>
    <Configuration>Debug</Configuration>
    <TargetFramework>netcoreapp1.1</TargetFramework>
    <PublishDir>bin\Debug\PublishOutput</PublishDir>
  </PropertyGroup>
</Project>

I can successfully build and run these two programs in the debugger. I can also publish the Application project and the Updater and its dependencies are included:

PublishOutput\runtimes\unix\lib\netstandard1.5\System.ServiceProcess.ServiceController.dll
PublishOutput\runtimes\win\lib\netstandard1.5\System.ServiceProcess.ServiceController.dll
PublishOutput\Application.deps.json
PublishOutput\Application.dll
PublishOutput\Application.pdb
PublishOutput\Application.runtimeconfig.json
PublishOutput\Updater.dll
PublishOutput\Updater.pdb
PublishOutput\Updater.runtimeconfig.json

Also I can run the Application itself from the published output like this:

dotnet Application.dll

Problem

I cannot run the Updater from the published output. When I try this:

dotnet Updater.dll

It crashes with the following exception:

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'System.ServiceProcess.ServiceController, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.
     at Updater.Program.Main(String[] args)

Interestingly it is looking for version 4.1.0.0 of System.ServiceProcess.ServiceController. But as you can see in the project file, I'm actually referencing version 4.3.0

What am I doing wrong here? What do I need to change so that I can run the Updater from the published output?

Body:
Updater.deps.json was missing in the published output. The following change was needed in the project file of the Application.

Before:

<ItemGroup>
  <Content Include="..\Updater\bin\$(Configuration)\netcoreapp1.1\Updater.runtimeconfig.json" CopyToOutputDirectory="Always"></Content>
</ItemGroup>

After:

<ItemGroup>
  <Content Include="..\Updater\bin\$(Configuration)\netcoreapp1.1\Updater.runtimeconfig.json" CopyToOutputDirectory="Always"></Content>
  <Content Include="..\Updater\bin\$(Configuration)\netcoreapp1.1\Updater.deps.json" CopyToOutputDirectory="Always"></Content>
</ItemGroup>


问:
Read File to Print to Screen
I have a file Inventory.txt that I am trying to print to the screen. Each line from the file goes into an object array. My code compiles with no errors but when I run it, nothing prints nothing to the screen. Im using Mac and TextEdit/Terminal. </p>

```<code>import java.util.Scanner;
import java.io.*;

public class VendingMachineSimulator
{
    to be imported
    public static void main(String[] args) throws FileNotFoundException
    {

        File InventoryFile = new File("Inventory.txt");
        Scanner input = new Scanner(InventoryFile);

        //This code block will count the number of lines(products) are in the text file
        int counter = 0;
        while (input.hasNextLine())
        {
            counter = counter + 1;
        }

        Inventory[] InventoryObject = new Inventory[counter];
        String line = "";

        for (int i = 0; i < counter; i++)
        {
            String[] ProductArray = line.split("-");

            InventoryObject[i] = new Inventory(Integer.valueOf(ProductArray[0]), ProductArray[1], ProductArray[2],
                                               ProductArray[3],Double.valueOf(ProductArray[4]), ProductArray[5],
                                               Integer.valueOf(ProductArray[6]));
        }

        for (int i = 0; i < counter; i++)
        {
            System.out.println();
            InventoryObject[i].PrintInventory();
        }

    }

    public static void PrintMenu()
    {
        System.out.println();
        System.out.println("Display Inventory: <1>");
        System.out.println("Display Currency:  <2>");
        System.out.println("Purchase Item:     <3>");
        System.out.println("Exit:              <4>");
        System.out.println();
    }

}

class Inventory
{
    private int ID;
    private String Type;
    private String Name;
    private String PriceText;
    private double Cost;
    private String QuantityText;
    private int StockAmount;

    //Constructor method. values passed to it from the main method.
    public Inventory(int ID, String Type, String Name, String PriceText, double Cost, String QuantityText, int StockAmount)
    {
        this.ID = ID;
        this.Type = Type;
        this.Name = Name;
        this.PriceText = PriceText;
        this.Cost = Cost;
        this.QuantityText = QuantityText;
        this.StockAmount = StockAmount;
    }

    public void setID(int ID)
    {
        this.ID = ID;
    }

    public void setType(String Type)
    {
        this.Type = Type;
    }

    public void setName(String Name)
    {
        this.Name = Name;
    }

    public void setPriceText(String PriceText)
    {
        this.PriceText = PriceText;
    }

    public void setCost(double Cost)
    {
        this.Cost = Cost;
    }

    public void setQuantityText(String QuantityText)
    {
        this.QuantityText = QuantityText;
    }

    public void setStockAmount(int StockAmount)
    {
        this.StockAmount = StockAmount;
    }

    public int getID()
    {
        return ID;
    }

    public String getType()
    {
        return Type;
    }

    public String getName()
    {
        return Name;
    }

    public String getPriceText()
    {
        return PriceText;
    }

    public double getCost()
    {
        return Cost;
    }

    public String getQuantityText()
    {
        return QuantityText;
    }

    public int getStockAmount()
    {
        return StockAmount;
    }

    public void PrintInventory()
    {
        System.out.println(ID + " " + Type + " " + Name + " " + PriceText
                           + " " + Cost + " " + QuantityText + " " + StockAmount);
    }

}
</code>```

答:
You never read a line, you only count them:

```<code>while (input.hasNextLine())
{
    counter = counter + 1;
}
</code>```

You have to place line = input.readLine(); inside this loop somewhere and change your logic accordingly, otherwise, it will always stay in the while loop. Think about when you would need to update or read the counter.

Title: Read File to Print to Screen

Body:
I have a file Inventory.txt that I am trying to print to the screen. Each line from the file goes into an object array. My code compiles with no errors but when I run it, nothing prints nothing to the screen. Im using Mac and TextEdit/Terminal.

import java.util.Scanner;
import java.io.*;

public class VendingMachineSimulator
{
    to be imported
    public static void main(String[] args) throws FileNotFoundException
    {

        File InventoryFile = new File("Inventory.txt");
        Scanner input = new Scanner(InventoryFile);

        //This code block will count the number of lines(products) are in the text file
        int counter = 0;
        while (input.hasNextLine())
        {
            counter = counter + 1;
        }

        Inventory[] InventoryObject = new Inventory[counter];
        String line = "";

        for (int i = 0; i < counter; i++)
        {
            String[] ProductArray = line.split("-");

            InventoryObject[i] = new Inventory(Integer.valueOf(ProductArray[0]), ProductArray[1], ProductArray[2],
                                               ProductArray[3],Double.valueOf(ProductArray[4]), ProductArray[5],
                                               Integer.valueOf(ProductArray[6]));
        }

        for (int i = 0; i < counter; i++)
        {
            System.out.println();
            InventoryObject[i].PrintInventory();
        }

    }

    public static void PrintMenu()
    {
        System.out.println();
        System.out.println("Display Inventory: <1>");
        System.out.println("Display Currency:  <2>");
        System.out.println("Purchase Item:     <3>");
        System.out.println("Exit:              <4>");
        System.out.println();
    }

}

class Inventory
{
    private int ID;
    private String Type;
    private String Name;
    private String PriceText;
    private double Cost;
    private String QuantityText;
    private int StockAmount;

    //Constructor method. values passed to it from the main method.
    public Inventory(int ID, String Type, String Name, String PriceText, double Cost, String QuantityText, int StockAmount)
    {
        this.ID = ID;
        this.Type = Type;
        this.Name = Name;
        this.PriceText = PriceText;
        this.Cost = Cost;
        this.QuantityText = QuantityText;
        this.StockAmount = StockAmount;
    }

    public void setID(int ID)
    {
        this.ID = ID;
    }

    public void setType(String Type)
    {
        this.Type = Type;
    }

    public void setName(String Name)
    {
        this.Name = Name;
    }

    public void setPriceText(String PriceText)
    {
        this.PriceText = PriceText;
    }

    public void setCost(double Cost)
    {
        this.Cost = Cost;
    }

    public void setQuantityText(String QuantityText)
    {
        this.QuantityText = QuantityText;
    }

    public void setStockAmount(int StockAmount)
    {
        this.StockAmount = StockAmount;
    }

    public int getID()
    {
        return ID;
    }

    public String getType()
    {
        return Type;
    }

    public String getName()
    {
        return Name;
    }

    public String getPriceText()
    {
        return PriceText;
    }

    public double getCost()
    {
        return Cost;
    }

    public String getQuantityText()
    {
        return QuantityText;
    }

    public int getStockAmount()
    {
        return StockAmount;
    }

    public void PrintInventory()
    {
        System.out.println(ID + " " + Type + " " + Name + " " + PriceText
                           + " " + Cost + " " + QuantityText + " " + StockAmount);
    }

}

Body:
You never read a line, you only count them:

while (input.hasNextLine())
{
    counter = counter + 1;
}

You have to place line = input.readLine(); inside this loop somewhere and change your logic accordingly, otherwise, it will always stay in the while loop. Think about when you would need to update or read the counter.


问:
Need help for my search bar php
I have been following this link as a guideline for my search bar
https://www.youtube.com/watch?v=Wvs6sbLN3NI&t=678s

Im a beginner in php and sql please help me with this one.
i dont know what to do in sql syntax.
the error is, Notice: Undefined variable: q in C:\xampp\htdocs\login-system\search.php on line 21
thanks in advance.

```<code><?php

    $con = mysql_connect('localhost','root','');
    $db = mysql_select_db('accounts');

?>
<!DOCTYPE html>
<html>
<head>
        <title> Search Form </title>
        <link rel="stylesheet" type="text/css" href="css/stylesearch.css">

</head>
<body>

    <form action = "search.php" method ="GET" id="searchForm">
        <input type="text" name="q" id="searchBox" placeholder="Search Here" value="" /><input type="submit" id="searchBtn" value ="GO" />
    </form>

    <?php
        $query = mysql_query("SELECT * FROM provider WHERE provider LIKE '%$q%' OR broker LIKE '%$q%' OR deductible LIKE '%$q%' OR deductible_waiver LIKE '%$q%' OR accredited_banks LIKE '%$q%' OR can_not_offer_mortgaged_with LIKE '%$q%' OR casa_eligibility LIKE '%$q%' OR depreciation LIKE '%$q%' OR special_quotes LIKE '%$q%' OR unit_age_limit LIKE '%$q%' OR provider_information LIKE '%$q%' OR provider_branches LIKE '%$q%' OR mmx_exclusive LIKE '%$q%' OR disclaimer LIKE '%$q%' OR accredited_shops LIKE '%$q%' OR roadside_assistance_number LIKE '%$q%' OR roadside_assistance_coverage LIKE '%$q%' OR check_addressee LIKE '%$q%' OR accounts_details LIKE '%$q%' OR cancellation_charge LIKE '%$q%'");
        $num_rows = mysql_num_rows($query);

        while($row = mysql_fetch_array($query))
        {
            $id = $row['id'];
            $prov = $row['provider'];
            $brok = $row['broker'];
            $deduc = $row['deductible'];
            $deduc_waiver = $row['deductible_waiver'];
            $accre_banks = $row['accredited_banks'];
            $mort = $row['can_not_offer_mortgaged_with'];
            $casa_elig = $row['casa_eligibility'];
            $depre = $row['depreciation'];
            $s_quotes = $row['special_quotes'];
            $age = $row['unit_age_limit'];
            $prov_info = $row['provider_information'];
            $prov_branch = $row['provider_branches'];
            $mmx_exclusive = $row['mmx_exclusive'];
            $disclaimer = $row['disclaimer'];
            $accre_shops = $row['accredited_shops'];
            $roadside_assist_no = $row['roadside_assistance_number'];
            $roadside_assist_cov = $row['roadside_assistance_coverage'];
            $check_addressee = $row['check_addressee'];
            $acc_details = $row['accounts_details'];
            $can_charge = $row['cancellation_charge'];

            echo '<h3>' .$prov .'</h3><p>'. $brok.'<br>'. $deduc.'<br>'. $deduc_waiver.'<br>'. $accre_banks.'<br>'. $mort.'<br>'. $casa_elig.'<br>'. $depre.'<br>'. $s_quotes.'<br>'. $age.'<br>'. $prov_info.'<br>'. $prov_branch.'<br>'. $mmx_exclusive.'<br>'. $disclaimer.'<br>'. $accre_shops.'<br>'. $roadside_assist_no.'<br>'. $roadside_assist_cov.'<br>'. $acc_details.'<br>'. $check_addressee.'<br>'. $can_charge.'</p><br />';
        }
    ?>

</body>
</html>
</code>```

答:
You are not really stating what your problem is here. Just looking at your code though, you are not calling your database in your mysqli query, which should be mysqli_query($db, "SELECT...."), where $db is your mysqli_connect variable. There are a few examples in the php manual: http://php.net/manual/en/mysqli.query.php.

As mickmacusa said above too, if you add in "or die (mysqli_error($db)" on the backend, it will give you more information regarding your sql syntax.

Title: Need help for my search bar php

Body:
I have been following this link as a guideline for my search bar
https://www.youtube.com/watch?v=Wvs6sbLN3NI&t=678s

Im a beginner in php and sql please help me with this one.
i dont know what to do in sql syntax.
the error is, Notice: Undefined variable: q in C:\xampp\htdocs\login-system\search.php on line 21
thanks in advance.

<?php

    $con = mysql_connect('localhost','root','');
    $db = mysql_select_db('accounts');

?>
<!DOCTYPE html>

        <title> Search Form </title>
        <link rel="stylesheet" type="text/css" href="css/stylesearch.css">

    <form action = "search.php" method ="GET" id="searchForm">
        <input type="text" name="q" id="searchBox" placeholder="Search Here" value="" /><input type="submit" id="searchBtn" value ="GO" />
    </form>

    <?php
        $query = mysql_query("SELECT * FROM provider WHERE provider LIKE '%$q%' OR broker LIKE '%$q%' OR deductible LIKE '%$q%' OR deductible_waiver LIKE '%$q%' OR accredited_banks LIKE '%$q%' OR can_not_offer_mortgaged_with LIKE '%$q%' OR casa_eligibility LIKE '%$q%' OR depreciation LIKE '%$q%' OR special_quotes LIKE '%$q%' OR unit_age_limit LIKE '%$q%' OR provider_information LIKE '%$q%' OR provider_branches LIKE '%$q%' OR mmx_exclusive LIKE '%$q%' OR disclaimer LIKE '%$q%' OR accredited_shops LIKE '%$q%' OR roadside_assistance_number LIKE '%$q%' OR roadside_assistance_coverage LIKE '%$q%' OR check_addressee LIKE '%$q%' OR accounts_details LIKE '%$q%' OR cancellation_charge LIKE '%$q%'");
        $num_rows = mysql_num_rows($query);

        while($row = mysql_fetch_array($query))
        {
            $id = $row['id'];
            $prov = $row['provider'];
            $brok = $row['broker'];
            $deduc = $row['deductible'];
            $deduc_waiver = $row['deductible_waiver'];
            $accre_banks = $row['accredited_banks'];
            $mort = $row['can_not_offer_mortgaged_with'];
            $casa_elig = $row['casa_eligibility'];
            $depre = $row['depreciation'];
            $s_quotes = $row['special_quotes'];
            $age = $row['unit_age_limit'];
            $prov_info = $row['provider_information'];
            $prov_branch = $row['provider_branches'];
            $mmx_exclusive = $row['mmx_exclusive'];
            $disclaimer = $row['disclaimer'];
            $accre_shops = $row['accredited_shops'];
            $roadside_assist_no = $row['roadside_assistance_number'];
            $roadside_assist_cov = $row['roadside_assistance_coverage'];
            $check_addressee = $row['check_addressee'];
            $acc_details = $row['accounts_details'];
            $can_charge = $row['cancellation_charge'];

            echo '
' .$prov .'

'. $brok.'
'. $deduc.'
'. $deduc_waiver.'
'. $accre_banks.'
'. $mort.'
'. $casa_elig.'
'. $depre.'
'. $s_quotes.'
'. $age.'
'. $prov_info.'
'. $prov_branch.'
'. $mmx_exclusive.'
'. $disclaimer.'
'. $accre_shops.'
'. $roadside_assist_no.'
'. $roadside_assist_cov.'
'. $acc_details.'
'. $check_addressee.'
'. $can_charge.'

';
        }
    ?>


问:
-bash: chattr: command not found
I am trying to change my .bash_profile and it spits back

error writing to .bash_profile Permission denied

So, I use the chattr -i .bash_profile to make it immutable and it gives me

-bash: chattr: command not found.

Can someone please help me on this?

答:
If you use Ubuntu or Debian you can use

```<code>apt-get install e2fsprogs
</code>```

Then you try again.

Title: -bash: chattr: command not found

Body:
If you use Ubuntu or Debian you can use

apt-get install e2fsprogs

Then you try again.


答:
This is an endless loop. If there is text in the file, the input has a next line.
Since that line isn't read in the loop, input.hasNextLine() is always true.

```<code>        while (input.hasNextLine())
        {
            counter = counter + 1;
        }
</code>```

You should rather use a List to read the Objects, that way you don't need to know the size initially.

Title: Read File to Print to Screen

Body:
This is an endless loop. If there is text in the file, the input has a next line.
Since that line isn't read in the loop, input.hasNextLine() is always true.

        while (input.hasNextLine())
        {
            counter = counter + 1;
        }

You should rather use a List to read the Objects, that way you don't need to know the size initially.


问:
jQuery Plugin: How do I test the configuration of my plugin with qunit?
I am trying out qunit while writing a jQuery plugin and I was wondering how I can test the following:

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

    $.fn.myPlugin = function(options){
        var defaults = {
            foo: function(){
                return 'bar';
            }
        };

        options = $.extend(defaults, options);

        return this.each(function(){ ... });
    };

})(jQuery);
</code>```

This is a simple version of my qunit test:

```<code>module('MyPlugin: Configuration');

test('Can overwrite foo', function(){
    var mockFoo = function(){
        return 'no bar';
    };

    //equals(notsure.myPlugin({ foo: mockFoo }, 'no bar', 'Overwriting failed');
});
</code>```

So I was wondering how I could expose internal methods/members from my plugin inside my tests?

答:
Nice after I made my bounty I found a really good site that explains how to use .data() to expose plubic properties and methods.

Here you can find the whole blog post: building object oriented jquery plugin.

This is whole example from the above link so all credits go to the author of the blog post.

```<code>(function($){
   var MyPlugin = function(element, options)
   {
       var elem = $(element);
       var obj = this;
       var settings = $.extend({
           param: 'defaultValue'
       }, options || {});

       // Public method - can be called from client code
       this.publicMethod = function()
       {
           console.log('public method called!');
       };

       // Private method - can only be called from within this object
       var privateMethod = function()
       {
           console.log('private method called!');
       };
   };

   $.fn.myplugin = function(options)
   {
       return this.each(function()
       {
           var element = $(this);

           // Return early if this element already has a plugin instance
           if (element.data('myplugin')) return;

           // pass options to plugin constructor
           var myplugin = new MyPlugin(this, options);

           // Store plugin object in this element's data
           element.data('myplugin', myplugin);
       });
   };
})(jQuery);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying out qunit while writing a jQuery plugin and I was wondering how I can test the following:

(function($){

    $.fn.myPlugin = function(options){
        var defaults = {
            foo: function(){
                return 'bar';
            }
        };

        options = $.extend(defaults, options);

        return this.each(function(){ ... });
    };

})(jQuery);

This is a simple version of my qunit test:

module('MyPlugin: Configuration');

test('Can overwrite foo', function(){
    var mockFoo = function(){
        return 'no bar';
    };

    //equals(notsure.myPlugin({ foo: mockFoo }, 'no bar', 'Overwriting failed');
});

So I was wondering how I could expose internal methods/members from my plugin inside my tests?

Body:
Nice after I made my bounty I found a really good site that explains how to use .data() to expose plubic properties and methods.

Here you can find the whole blog post: building object oriented jquery plugin.

This is whole example from the above link so all credits go to the author of the blog post.

(function($){
   var MyPlugin = function(element, options)
   {
       var elem = $(element);
       var obj = this;
       var settings = $.extend({
           param: 'defaultValue'
       }, options || {});

       // Public method - can be called from client code
       this.publicMethod = function()
       {
           console.log('public method called!');
       };

       // Private method - can only be called from within this object
       var privateMethod = function()
       {
           console.log('private method called!');
       };
   };

   $.fn.myplugin = function(options)
   {
       return this.each(function()
       {
           var element = $(this);

           // Return early if this element already has a plugin instance
           if (element.data('myplugin')) return;

           // pass options to plugin constructor
           var myplugin = new MyPlugin(this, options);

           // Store plugin object in this element's data
           element.data('myplugin', myplugin);
       });
   };
})(jQuery);


问:
How to reset steps at midnight?
I have a service which is running in background which tracks user steps using the device sensor. My problem is my application is not resetting the steps to zero at midnight. I have a broadcast receiver where I have put the alarm manager but I am stuck how do I update my steps UI which is in fragment to zero?

Here is my fragment:

```<code>private void UpDateUi(int currentStep) {
    if (backgroundStepsDetails == null || backgroundStepsDetails.isEmpty()) {
        total_step = StepDetector.CURRENT_SETP;
        mDistanceInKm = getDistance();
        calories = countCalories();

    } else {
        if (total_step == 0) {
            total_step = Utilities.getIntValue(backgroundStepsDetails.get("total_steps"));

        }

        int temp = (mLastStepCount == StepDetector.CURRENT_SETP) ? 0 : StepDetector.CURRENT_SETP - mLastStepCount;
        mLastStepCount = StepDetector.CURRENT_SETP;
        Log.i(TAG, String.valueOf(temp));

        if (sessionDetails != null) {

            if (!SharedPreferenceManager.singleton().getString("LastFreeWalkSessionId").equals(sessionDetails.get("id"))) {
                total_step = total_step + temp + Utilities.getIntValue(sessionDetails.get("total_steps"));
                mDistanceInKm = getDistance() + Utilities.convertStringToDouble(backgroundStepsDetails.get("distance"))
                        + Utilities.convertMetersToKilometers(Utilities.convertStringToDouble(sessionDetails.get("total_distance_covered")));
                calories = countCalories() + Utilities.convertStringToDouble(backgroundStepsDetails.get("calories")) + Utilities.convertStringToDouble(sessionDetails.get("kalburnt"));
                SharedPreferenceManager.singleton().save("LastFreeWalkSessionId", sessionDetails.get("id"));
            } else {
                total_step = total_step + temp;
                mDistanceInKm = getDistance() + Utilities.convertStringToDouble(backgroundStepsDetails.get("distance"));
                calories = countCalories() + Utilities.convertStringToDouble(backgroundStepsDetails.get("calories"));
            }

        } else {
            total_step = total_step + temp;
        }

        if (mDistanceInKm == 0d) {
            mDistanceInKm = Utilities.convertStringToDouble(backgroundStepsDetails.get("distance"));
        }
            mDistanceInKm = getDistance() + Utilities.convertStringToDouble(backgroundStepsDetails.get("distance"));

        if (calories == 0d) {
            calories = Utilities.convertStringToDouble(backgroundStepsDetails.get("calories"));
            System.out.println("================CurrentCalories==========================");
            System.out.println(calories);

        }

            calories = countCalories() + Utilities.convertStringToDouble(backgroundStepsDetails.get("calories"));
            System.out.println("================UpdatedCalories==========================");
            System.out.println(calories);

    }
    textViewCalories.setText(Utilities.round(calories, 2) + getString(R.string.kcal));
    textViewDistance.setText(String.format("%.2f", mDistanceInKm) + getString(R.string.kmText));
    textViewStepCounter.setText(String.format("%,d", total_step));

    seekProgress.setProgress(total_step);

    boolean isRowPresent = dbController.isTodayDataPresent(currentDateandTime);

    if (isRowPresent) {

        dbController.updateSteps(String.valueOf(mDistanceInKm), String.valueOf(""), String.valueOf(total_step), String.valueOf((Utilities.round(calories, 2))));
    } else {
        storeStepsDataInDb();

    }
</code>```

}

Here is my receiver:

```<code>public class ConnectionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equalsIgnoreCase("com.journaldev.broadcastreceiver.SOME_ACTION")) {
        // Toast.makeText(context, "SOME_ACTION is received", Toast.LENGTH_LONG).show();

        Intent notificationIntent = new Intent(context, HomeActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.AM_PM, Calendar.AM);

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), 1000 * 60 *60 *24, contentIntent);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Mobiefit Walk")
                .setAutoCancel(false)
                .setOngoing(true)
                .setContentIntent(contentIntent);
        intent.hasExtra("TodayStep");
        final String action = intent.getAction();

       if(Intent.ACTION_TIME_TICK.equals(action) ||   Intent.ACTION_DATE_CHANGED.equals(action)){
           if(MobieFitWalkApp.mInstance != null){
              // MobieFitWalkApp.mInstance.setStepCount(0);
           }

       }
        Log.i("",String.valueOf(intent.getIntExtra("TodayStep", 0)));
        if (intent.getIntExtra("TodayStep", 0) > 0) {

            if (intent.getIntExtra("YourGoal", 0) != 0) {

                if (calculatePercentSixty(intent.getIntExtra("TodayStep", 0), intent.getIntExtra("YourGoal", 0))) {
                    mBuilder.setContentText("You’ve already completed" + intent.getIntExtra("TodayStep", 0) + " steps today!");
                } else if (calculatePercentEighty(intent.getIntExtra("TodayStep", 0), intent.getIntExtra("YourGoal", 0))) {
                    mBuilder.setContentText("You’re just" + +intent.getIntExtra("TodayStep", 0) + " steps away from today’s goal!");
                } else if (calculateGoal(intent.getIntExtra("TodayStep", 0), intent.getIntExtra("YourGoal", 0))) {
                    mBuilder.setContentText("Congrats! You’ve met your activity goal today!");
                } else {
                    mBuilder.setContentText("Today's Steps : " + " " + intent.getIntExtra("TodayStep", 0) + "");
                }
            }
        }

        else{
            mBuilder.setContentText("Today's Steps : " + " " + intent.getIntExtra("TodayStep", 0) + "");
        }
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(1, mBuilder.build());
        Notification n;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            n = mBuilder.build();
        } else {
            n = mBuilder.getNotification();
        }

        n.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;

    }
}
</code>```

Can someone tell me how can I achieve this?

答:
1) Save the data(steps) in the sqlite or sharedPreferences from the BroadCast Receiver.

2) In the Activity/Fragment whatever you are using for showing the step count, read steps from the sqlite and show it in UI.

Title: How to reset steps at midnight?

Body:
I have a service which is running in background which tracks user steps using the device sensor. My problem is my application is not resetting the steps to zero at midnight. I have a broadcast receiver where I have put the alarm manager but I am stuck how do I update my steps UI which is in fragment to zero?

Here is my fragment:

private void UpDateUi(int currentStep) {
    if (backgroundStepsDetails == null || backgroundStepsDetails.isEmpty()) {
        total_step = StepDetector.CURRENT_SETP;
        mDistanceInKm = getDistance();
        calories = countCalories();

    } else {
        if (total_step == 0) {
            total_step = Utilities.getIntValue(backgroundStepsDetails.get("total_steps"));

        }

        int temp = (mLastStepCount == StepDetector.CURRENT_SETP) ? 0 : StepDetector.CURRENT_SETP - mLastStepCount;
        mLastStepCount = StepDetector.CURRENT_SETP;
        Log.i(TAG, String.valueOf(temp));

        if (sessionDetails != null) {

            if (!SharedPreferenceManager.singleton().getString("LastFreeWalkSessionId").equals(sessionDetails.get("id"))) {
                total_step = total_step + temp + Utilities.getIntValue(sessionDetails.get("total_steps"));
                mDistanceInKm = getDistance() + Utilities.convertStringToDouble(backgroundStepsDetails.get("distance"))
                        + Utilities.convertMetersToKilometers(Utilities.convertStringToDouble(sessionDetails.get("total_distance_covered")));
                calories = countCalories() + Utilities.convertStringToDouble(backgroundStepsDetails.get("calories")) + Utilities.convertStringToDouble(sessionDetails.get("kalburnt"));
                SharedPreferenceManager.singleton().save("LastFreeWalkSessionId", sessionDetails.get("id"));
            } else {
                total_step = total_step + temp;
                mDistanceInKm = getDistance() + Utilities.convertStringToDouble(backgroundStepsDetails.get("distance"));
                calories = countCalories() + Utilities.convertStringToDouble(backgroundStepsDetails.get("calories"));
            }

        } else {
            total_step = total_step + temp;
        }

        if (mDistanceInKm == 0d) {
            mDistanceInKm = Utilities.convertStringToDouble(backgroundStepsDetails.get("distance"));
        }
            mDistanceInKm = getDistance() + Utilities.convertStringToDouble(backgroundStepsDetails.get("distance"));

        if (calories == 0d) {
            calories = Utilities.convertStringToDouble(backgroundStepsDetails.get("calories"));
            System.out.println("================CurrentCalories==========================");
            System.out.println(calories);

        }

            calories = countCalories() + Utilities.convertStringToDouble(backgroundStepsDetails.get("calories"));
            System.out.println("================UpdatedCalories==========================");
            System.out.println(calories);

    }
    textViewCalories.setText(Utilities.round(calories, 2) + getString(R.string.kcal));
    textViewDistance.setText(String.format("%.2f", mDistanceInKm) + getString(R.string.kmText));
    textViewStepCounter.setText(String.format("%,d", total_step));

    seekProgress.setProgress(total_step);

    boolean isRowPresent = dbController.isTodayDataPresent(currentDateandTime);

    if (isRowPresent) {

        dbController.updateSteps(String.valueOf(mDistanceInKm), String.valueOf(""), String.valueOf(total_step), String.valueOf((Utilities.round(calories, 2))));
    } else {
        storeStepsDataInDb();

    }

}

Here is my receiver:

public class ConnectionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equalsIgnoreCase("com.journaldev.broadcastreceiver.SOME_ACTION")) {
        // Toast.makeText(context, "SOME_ACTION is received", Toast.LENGTH_LONG).show();

        Intent notificationIntent = new Intent(context, HomeActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.AM_PM, Calendar.AM);

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), 1000 * 60 *60 *24, contentIntent);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Mobiefit Walk")
                .setAutoCancel(false)
                .setOngoing(true)
                .setContentIntent(contentIntent);
        intent.hasExtra("TodayStep");
        final String action = intent.getAction();

       if(Intent.ACTION_TIME_TICK.equals(action) ||   Intent.ACTION_DATE_CHANGED.equals(action)){
           if(MobieFitWalkApp.mInstance != null){
              // MobieFitWalkApp.mInstance.setStepCount(0);
           }

       }
        Log.i("",String.valueOf(intent.getIntExtra("TodayStep", 0)));
        if (intent.getIntExtra("TodayStep", 0) > 0) {

            if (intent.getIntExtra("YourGoal", 0) != 0) {

                if (calculatePercentSixty(intent.getIntExtra("TodayStep", 0), intent.getIntExtra("YourGoal", 0))) {
                    mBuilder.setContentText("You’ve already completed" + intent.getIntExtra("TodayStep", 0) + " steps today!");
                } else if (calculatePercentEighty(intent.getIntExtra("TodayStep", 0), intent.getIntExtra("YourGoal", 0))) {
                    mBuilder.setContentText("You’re just" + +intent.getIntExtra("TodayStep", 0) + " steps away from today’s goal!");
                } else if (calculateGoal(intent.getIntExtra("TodayStep", 0), intent.getIntExtra("YourGoal", 0))) {
                    mBuilder.setContentText("Congrats! You’ve met your activity goal today!");
                } else {
                    mBuilder.setContentText("Today's Steps : " + " " + intent.getIntExtra("TodayStep", 0) + "");
                }
            }
        }

        else{
            mBuilder.setContentText("Today's Steps : " + " " + intent.getIntExtra("TodayStep", 0) + "");
        }
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(1, mBuilder.build());
        Notification n;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            n = mBuilder.build();
        } else {
            n = mBuilder.getNotification();
        }

        n.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;

    }
}

Can someone tell me how can I achieve this?


问:
Greater Than and Less than MySql query failing with decimal field
I have a database which has 3 columns:

```<code>user_id | lat      | lon
1       |-1.403976 | 53.428692
2       |-1.353276 | 55.224692
etc etc
</code>```

Both lat and lon are set as decimal fields. I'm running a query similar to this but it isn't filtering based on being greater than and less than the given lat/lon numbers:

```<code>SELECT * FROM `table` WHERE `lat` < '-1.399999' AND 'lat' > '-1.300000'
AND 'lon' < '55.555555' AND > '53.000000'
</code>```

This query just returns every row in the table and I don't know why? Is it something to do with the fields being set as decimals?

I hope someone can help - i know its probably a simple answer if you know it.

As per comment - here's the create table:

```<code>CREATE TABLE IF NOT EXISTS `members` (
`user_id` int(10) NOT NULL AUTO_INCREMENT,
`lat` decimal(8,6) NOT NULL,
`lon` decimal(8,6) NOT NULL,
UNIQUE KEY `user_id` (`user_id`),
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=136 ;
</code>```

答:
Example:

Query the sum of Northern Latitudes (LAT_N) from STATION having values greater than 38.7880 and less than 137.2345. Truncate your answer to 4 decimal places.

```<code>SELECT TRUNCATE(SUM(LAT_N),4)
FROM STATION
WHERE LAT_N > 38.7880 and LAT_N < 137.2345;
</code>```

Body:
I have a database which has 3 columns:

user_id | lat      | lon
1       |-1.403976 | 53.428692
2       |-1.353276 | 55.224692
etc etc

Both lat and lon are set as decimal fields. I'm running a query similar to this but it isn't filtering based on being greater than and less than the given lat/lon numbers:

SELECT * FROM `table` WHERE `lat` < '-1.399999' AND 'lat' > '-1.300000'
AND 'lon' < '55.555555' AND > '53.000000'

This query just returns every row in the table and I don't know why? Is it something to do with the fields being set as decimals?

I hope someone can help - i know its probably a simple answer if you know it.

As per comment - here's the create table:

CREATE TABLE IF NOT EXISTS `members` (
`user_id` int(10) NOT NULL AUTO_INCREMENT,
`lat` decimal(8,6) NOT NULL,
`lon` decimal(8,6) NOT NULL,
UNIQUE KEY `user_id` (`user_id`),
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=136 ;

Body:
Example:

Query the sum of Northern Latitudes (LAT_N) from STATION having values greater than 38.7880 and less than 137.2345. Truncate your answer to 4 decimal places.

SELECT TRUNCATE(SUM(LAT_N),4)
FROM STATION
WHERE LAT_N > 38.7880 and LAT_N < 137.2345;


问:
Laravel 5.4 updated syntax
Hi guys got some problem....

```<code>Call to undefined method Illuminate\Database\Query\Builder::udpate()
</code>```

here's my update code...

```<code>DB::table('gpl_team')->where('id', $idteam)->udpate(['team_logo' => $logo, 'team_name' => $name, 'team_country' => $country, 'updated_at' => $updated_at]);
</code>```

答:
Its update & not udpate() spelling mistake

```<code>DB::table('gpl_team')->where('id', $idteam)->update(['team_logo' => $logo, 'team_name' => $name, 'team_country' => $country, 'updated_at' => $updated_at]);
</code>```

Title: Laravel 5.4 updated syntax

Body:
Hi guys got some problem....

Call to undefined method Illuminate\Database\Query\Builder::udpate()

here's my update code...

DB::table('gpl_team')->where('id', $idteam)->udpate(['team_logo' => $logo, 'team_name' => $name, 'team_country' => $country, 'updated_at' => $updated_at]);

Body:
Its update & not udpate() spelling mistake

DB::table('gpl_team')->where('id', $idteam)->update(['team_logo' => $logo, 'team_name' => $name, 'team_country' => $country, 'updated_at' => $updated_at]);


问:
Run vpython in python3 without jupyter possible?
In Python2.7 all my visual scripts were running fine. When I use Python3.5 I get the error message:

```<code>get_ipython().kernel.comm_manager.register_target('glow', GlowWidget)
AttributeError: 'NoneType' object has no attribute 'kernel'
</code>```

When I google the error message people say that you should use the jupyter notebook. But is it possible to run my old scripts without jupyter?

答:
you should install ipython and Jupyter Notebook, as following

```<code>sudo apt-get install ipython ipython-notebook
pip install jupyter
</code>```

And then you can use jupyter notebook in the terminal to start your notebook, from where you can create a new vpython notebook in your browser.
create vpython

and then you can write your vpython script and see the objects you created as following.
draw a sphere

also you can refer to other blogs to install your jupyter notebook and so on. But make sure that you have installed vpython.

Body:
In Python2.7 all my visual scripts were running fine. When I use Python3.5 I get the error message:

get_ipython().kernel.comm_manager.register_target('glow', GlowWidget)
AttributeError: 'NoneType' object has no attribute 'kernel'

When I google the error message people say that you should use the jupyter notebook. But is it possible to run my old scripts without jupyter?

Body:
you should install ipython and Jupyter Notebook, as following

sudo apt-get install ipython ipython-notebook
pip install jupyter

And then you can use jupyter notebook in the terminal to start your notebook, from where you can create a new vpython notebook in your browser.
create vpython

and then you can write your vpython script and see the objects you created as following.
draw a sphere

also you can refer to other blogs to install your jupyter notebook and so on. But make sure that you have installed vpython.


问:
Regex. Find paragraph containing some word
In text like this:

1 bla bla bla bla bla

2 bla bla bla bla TEXT bla

3 bla bla bla bla bla

4 bla bla bla bla TEXT bla

5 bla bla bla bla bla

I have to find paragraphs (between p tags) that contain string "TEXT".

I tried
.*?(TEXT).*?<\/p>

and I tried
(?!
).*?(TEXT).*?<\/p>

But it doesnt solve the problem.

答:
Sometimes you just have to add a delimiter like (...) or {...} or /.../ or [...] So try it like this:

```<code>/<p>.*?(TEXT).*?<\/p>/
</code>```

But as Barman pointed it out, this does not always stay within one paragraph. If you really want to only select 1 paragraph you need something like this:

```<code>(?:<p |<p>)(?:(?!\/p>).|\n)*(TEXT).*?<\/p>
</code>```

(?:<p |
) Starts with <p  or
 and ?: in the beginning means "do not capture this in output"

(?:(?!\/p>).|\n)* Any character or newline .|\n except a closing /p>  and ?: in the beginning means "do not capture this in output"

(TEXT) The word TEXT of course

.*? any character with lazy quantifier "?" .*? to stop on the shortest match (before we have a

<\/p> And must end with closing
 tag

And this one allows multiline text too!

Body:
Sometimes you just have to add a delimiter like (...) or {...} or /.../ or [...] So try it like this:

/<p>.*?(TEXT).*?<\/p>/

But as Barman pointed it out, this does not always stay within one paragraph. If you really want to only select 1 paragraph you need something like this:

(?:<p |<p>)(?:(?!\/p>).|\n)*(TEXT).*?<\/p>

(?:<p |<p>) Starts with <p  or <p> and ?: in the beginning means "do not capture this in output"

(?:(?!\/p>).|\n)* Any character or newline .|\n except a closing /p>  and ?: in the beginning means "do not capture this in output"

(TEXT) The word TEXT of course

.*? any character with lazy quantifier "?" .*? to stop on the shortest match (before we have a </p>

<\/p> And must end with closing </p> tag

And this one allows multiline text too!


问:
php url_exists function for https urls
```function url_exists($url) {
        $return = false;
        $content=@file_get_contents($url, FALSE, NULL, 0, 20);
        if($content == false ) {
            $return = false;
        } else if (count($content) ```

How to modify this function to check on content on https URLS as well. This is currently not able to check existense of file there.

答: Remove the silence operator @ and see what error you get.

Title: php url_exists function for https urls

Body:
function url_exists($url) {
        $return = false;
        $content=@file_get_contents($url, FALSE, NULL, 0, 20);
        if($content == false ) {
            $return = false;
        } else if (count($content)

How to modify this function to check on content on https URLS as well. This is currently not able to check existense of file there.


问:
Swift string encoding
My string has & and I want to replace it with the percentage encoding (%26). This is just an example. There can be any escape character.

I tried this but it is not replacing & with %26 :

```<code>password.text?.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
</code>```

答:
How about this short string extension:</p>

```<code>extension String
{
    func encode(_ chars: String) -> String
    {
        let forbidden = CharacterSet(charactersIn: chars)
        return self.addingPercentEncoding(withAllowedCharacters: forbidden.inverted) ?? self
    }
}

print("I can't read ENCODED text".encode("CDENO"))
// will print: I can't read %45%4E%43%4F%44%45%44 text

print("Command & Conquer".encode("&"))
// will print: Command %26 Conquer
</code>```

Title: Swift string encoding

Body:
My string has & and I want to replace it with the percentage encoding (%26). This is just an example. There can be any escape character.

I tried this but it is not replacing & with %26 :

password.text?.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

Body:
How about this short string extension:

extension String
{
    func encode(_ chars: String) -> String
    {
        let forbidden = CharacterSet(charactersIn: chars)
        return self.addingPercentEncoding(withAllowedCharacters: forbidden.inverted) ?? self
    }
}

print("I can't read ENCODED text".encode("CDENO"))
// will print: I can't read %45%4E%43%4F%44%45%44 text

print("Command & Conquer".encode("&"))
// will print: Command %26 Conquer


问:
How to Replace Bad Words in a Comment with Asterisks Using PHP

Hope All Of You are Fine.

I have a File in Of Bad Words, I want to Replace Bad Words in a Comments with Asterisks.

Bad Words URL : https://gist.githubusercontent.com/anonymous/e8e6798137b1ff4836d6ebcf73fef7dc/raw/415dfc8cbab13fa6033fbb4d4ce9eae7a9dbe7cd/Bad_Words.txt

I wrote Below Lines Of Code But It's not Working :(

Kindly Help.

```<code><?php
$abusive_words = file_get_contents('Bad_Words.txt');
$abusive_words = explode("\n", $abusive_words);
$input_string = 'Catch that bastard, Idiot .... !!';
$fixed = str_ireplace($abusive_words,'*****',$input_string);
echo "Input String <br> $input_string <br><br><hr><br>Input String Fixed <br> $fixed";
?>
</code>```

答:
There might be cases where whitespace is appended to the array element($abusive_words) while retrieving it from the text file. str_ireplace() might not be able to get perfect match due to these whitespaces. So its always better to trim the array elements before proceeding further especially for comparison.

array_map() and trim is what you need.

$abusive_words = array_map('trim', $abusive_words);

Do this before passing array to str_ireplace()

Body:
Hope All Of You are Fine.

I have a File in Of Bad Words, I want to Replace Bad Words in a Comments with Asterisks.

Bad Words URL : https://gist.githubusercontent.com/anonymous/e8e6798137b1ff4836d6ebcf73fef7dc/raw/415dfc8cbab13fa6033fbb4d4ce9eae7a9dbe7cd/Bad_Words.txt

I wrote Below Lines Of Code But It's not Working :(

Kindly Help.

<?php
$abusive_words = file_get_contents('Bad_Words.txt');
$abusive_words = explode("\n", $abusive_words);
$input_string = 'Catch that bastard, Idiot .... !!';
$fixed = str_ireplace($abusive_words,'*****',$input_string);
echo "Input String
 $input_string

Input String Fixed
 $fixed";
?>


问:
Chrome v35 desktop notification popup
Is there any fix yet for chrome version 35 desktop notification pop up ?

I have tried this also but no success.

Here is my code of html file

```<code><html>
<head>
    <title>Simple Notification example</title>
</head>

<button onclick="notifyMe()">Notify me!</button>

<script type="text/javascript">
function notifyMe() {
  if (!("Notification" in window)) {
    alert("This browser does not support desktop notification");
  }

  else if (Notification.permission === "granted") {
    var notification = new Notification("Hi there!");
  }

  else if (Notification.permission !== 'denied') {
    Notification.requestPermission(function (permission) {

      if(!('permission' in Notification)) {
        Notification.permission = permission;
      }

      if (permission === "granted") {
        var notification = new Notification("Hi there!");
      }
    });
  }

}
</script>
</html>
</code>```

This code is asking to "allow" or "deny" notification pop up. But not working after it.

Anyone else experiencing this problem or any fix of this?

答:
Please check allow or block status in browser. copy the following url and paste into your chrome browser.

chrome://settings/contentExceptions#notifications

Title: Chrome v35 desktop notification popup

Body:
Is there any fix yet for chrome version 35 desktop notification pop up ?

I have tried this also but no success.

Here is my code of html file

    <title>Simple Notification example</title>

<button onclick="notifyMe()">Notify me!</button>

This code is asking to "allow" or "deny" notification pop up. But not working after it.

Anyone else experiencing this problem or any fix of this?


答:
You can try something like this:

Create a regex to get all groups

Loop over these regex to check for necessary search key and filter out the matches.

var str = "
1 bla bla bla bla bla

2 bla bla bla bla TEXT bla

3 bla bla bla bla bla

4 bla bla bla bla TEXT bla

5 bla bla bla bla bla
";

var groupRegex = /(?:^|
)(.*?)(?:<\/p>|$)/g;
var searchRegex = /text/i
var groups = str.match(groupRegex);

var result = groups.filter(function(s){ return searchRegex.test(s) })

console.log(result)```

Title: Regex. Find paragraph containing some word

Body:
In text like this:

1 bla bla bla bla bla

2 bla bla bla bla TEXT bla

3 bla bla bla bla bla

4 bla bla bla bla TEXT bla

5 bla bla bla bla bla

I have to find paragraphs (between p tags) that contain string "TEXT".

I tried
.*?(TEXT).*?<\/p>

and I tried
(?!
).*?(TEXT).*?<\/p>

But it doesnt solve the problem.

Body:
You can try something like this:

Create a regex to get all groups

Loop over these regex to check for necessary search key and filter out the matches.

var str = "<p>1 bla bla <em>bla</em> bla bla</p><p>2 bla bla <em>bla</em> bla TEXT bla</p><p>3 bla bla <em>bla</em> bla bla</p><p>4 bla bla <em>bla</em> bla TEXT bla</p><p>5 bla bla <em>bla</em> bla bla</p>";

var groupRegex = /(?:^|<p>)(.*?)(?:<\/p>|$)/g;
var searchRegex = /text/i
var groups = str.match(groupRegex);

var result = groups.filter(function(s){ return searchRegex.test(s) })

console.log(result)


问:
How to ignore all headers in ESP8266 response?
I'm having trouble with the response of my server. I need to ignore all those headers in the response.

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Connection: close
Status: 200 OK

Balance:50
```

<pre class="lang-cpp prettyprint-override"><code>uint32_t len = wifi.recv(buffer, sizeof(buffer), 10);
if (len > 0) {
  Serial.print("Received:[");
  for(uint32_t i = 0; i < len; i++) {
    Serial.print((char)buffer[i]);
  }
  Serial.print("]\r\n");
}
</code>```

答:
First I put all response in String variable then find the index of my trigger ("OK" I can also use "\r\n\r\n" but I dunno why I'm using my own trigger lol) so I can filter all of those headers.</p>

```<code>wifi.send((const uint8_t*)httpPost, strlen(httpPost));
int t = 0;
char resp[] = {};
uint32_t len = wifi.recv(buffer, sizeof(buffer), 1024);
if (len > 0) {
  String resp;
  for (uint32_t i = 0; i < len; i++) {
     resp += String((char)buffer[i]);
  }
  Serial.println(resp);

  int ind = resp.indexOf("OK",20);
  String response;
  for(int x = ind+3;x<=resp.length();x++){
    response += resp[x];
  }
  Serial.println(response);
 }
</code>```

Body:
I'm having trouble with the response of my server. I need to ignore all those headers in the response.

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Connection: close
Status: 200 OK

Balance:50

uint32_t len = wifi.recv(buffer, sizeof(buffer), 10);
if (len > 0) {
  Serial.print("Received:[");
  for(uint32_t i = 0; i < len; i++) {
    Serial.print((char)buffer[i]);
  }
  Serial.print("]\r\n");
}

Body:
First I put all response in String variable then find the index of my trigger ("OK" I can also use "\r\n\r\n" but I dunno why I'm using my own trigger lol) so I can filter all of those headers.

wifi.send((const uint8_t*)httpPost, strlen(httpPost));
int t = 0;
char resp[] = {};
uint32_t len = wifi.recv(buffer, sizeof(buffer), 1024);
if (len > 0) {
  String resp;
  for (uint32_t i = 0; i < len; i++) {
     resp += String((char)buffer[i]);
  }
  Serial.println(resp);

  int ind = resp.indexOf("OK",20);
  String response;
  for(int x = ind+3;x<=resp.length();x++){
    response += resp[x];
  }
  Serial.println(response);
 }


问:
remove middle octets from an ip until some criteria is met
I have a string of IP and port numbers which is like :  "10.213.110.49.33482;10.213.106.12.20001:"
The two ip's are separated by a semi-colon. Last decimal shows port number.
What I need is to convert the above string which would look like:
"10.213.110.49 20001:".

I want to remove the middle octets and port number of first IP using SHELL SCRIPT only. I want to extract the IP from first part ignoring the port number and from second IP i want the port number only

Body:
using sed:

sed 's/\.[0-9]*;.*\.\([0-9]*:\)/ \1/' <<< \
         '10.213.110.49.33482;10.213.106.12.20001:'

gives:

10.213.110.49 20001:


问:
Get joined reulst from 2 table and when value not exist any of them, fill with empty value
I have tables clients and partners

Table clients

```<code>company_id | name
------------------
11         | UA prods.
12         | CI corp.
13         | UAC
</code>```

Table partners

```<code>company_id | name
------------------
11         | UA prods.
12         | CI corp.
20         | BDP Group
30         | UFF
</code>```

I need get all company names from both table. When company exists in both tables, then theyr names, when doesn't exist, just leave it empty.

I tried left joins, inner joins but it gives me not what I want.

I want result like this

```<code>clients    | partners
--------------------
UA prods.  | UA prods.
CI corp.   | CI corp.
UAC        |
           | BDP Group
           | UFF
</code>```

答:
You are looking for a FULL OUTER JOIN which is not supported by MySQL. But You can use a LEFT JOIN and a RIGHT JOIN, and an UNION ALL query instead:

```<code>select c.name as clients, p.name as partners
from
  clients c left join partners p
  on c.company_id = p.company_id

union all

select c.name as clients, p.name as partners
from
  clients c right join partners p
  on c.company_id = p.company_id
where
  c.company_id is null
</code>```

The first query uses a LEFT JOIN will return all clients, and all partners whenever there's a match (or null instead).

The second RIGHT JOIN query will return all partners that don't have a match on the clients table.

Body:
I have tables clients and partners

Table clients

company_id | name
------------------
11         | UA prods.
12         | CI corp.
13         | UAC

Table partners

company_id | name
------------------
11         | UA prods.
12         | CI corp.
20         | BDP Group
30         | UFF

I need get all company names from both table. When company exists in both tables, then theyr names, when doesn't exist, just leave it empty.

I tried left joins, inner joins but it gives me not what I want.

I want result like this

clients    | partners
--------------------
UA prods.  | UA prods.
CI corp.   | CI corp.
UAC        |
           | BDP Group
           | UFF

Body:
You are looking for a FULL OUTER JOIN which is not supported by MySQL. But You can use a LEFT JOIN and a RIGHT JOIN, and an UNION ALL query instead:

select c.name as clients, p.name as partners
from
  clients c left join partners p
  on c.company_id = p.company_id

union all

select c.name as clients, p.name as partners
from
  clients c right join partners p
  on c.company_id = p.company_id
where
  c.company_id is null

The first query uses a LEFT JOIN will return all clients, and all partners whenever there's a match (or null instead).

The second RIGHT JOIN query will return all partners that don't have a match on the clients table.


答:
You are blocking the input from the Inventory.txt file in you while loop. You are only checking if a next line exists without actually reading the next line. So you're going to an infinite loop here:

```<code>    int counter = 0;
    while (input.hasNextLine())
    {
        counter = counter + 1;
    }
</code>```

You need to call this at some point inside your whilte loop:

```<code>input.nextLine();
</code>```

Tip: You can consolidate all the actions that you are performing inside this while loop. You probably don't need as many loops:

Assigning to line; Declare line before the while loop.

Splitting line into ProductArray. This will be line.split assigned to ProductArray.

Creating the new Inventory object. You may not need an array of Inventory Objects. Simply create one using the ProductArray variable.

Printing the inventory. Simply call the PrintInventory method on the the object created in step 3.

Hope this helps!

Title: Read File to Print to Screen

Body:
I have a file Inventory.txt that I am trying to print to the screen. Each line from the file goes into an object array. My code compiles with no errors but when I run it, nothing prints nothing to the screen. Im using Mac and TextEdit/Terminal.

import java.util.Scanner;
import java.io.*;

public class VendingMachineSimulator
{
    to be imported
    public static void main(String[] args) throws FileNotFoundException
    {

        File InventoryFile = new File("Inventory.txt");
        Scanner input = new Scanner(InventoryFile);

        //This code block will count the number of lines(products) are in the text file
        int counter = 0;
        while (input.hasNextLine())
        {
            counter = counter + 1;
        }

        Inventory[] InventoryObject = new Inventory[counter];
        String line = "";

        for (int i = 0; i < counter; i++)
        {
            String[] ProductArray = line.split("-");

            InventoryObject[i] = new Inventory(Integer.valueOf(ProductArray[0]), ProductArray[1], ProductArray[2],
                                               ProductArray[3],Double.valueOf(ProductArray[4]), ProductArray[5],
                                               Integer.valueOf(ProductArray[6]));
        }

        for (int i = 0; i < counter; i++)
        {
            System.out.println();
            InventoryObject[i].PrintInventory();
        }

    }

    public static void PrintMenu()
    {
        System.out.println();
        System.out.println("Display Inventory: <1>");
        System.out.println("Display Currency:  <2>");
        System.out.println("Purchase Item:     <3>");
        System.out.println("Exit:              <4>");
        System.out.println();
    }

}

class Inventory
{
    private int ID;
    private String Type;
    private String Name;
    private String PriceText;
    private double Cost;
    private String QuantityText;
    private int StockAmount;

    //Constructor method. values passed to it from the main method.
    public Inventory(int ID, String Type, String Name, String PriceText, double Cost, String QuantityText, int StockAmount)
    {
        this.ID = ID;
        this.Type = Type;
        this.Name = Name;
        this.PriceText = PriceText;
        this.Cost = Cost;
        this.QuantityText = QuantityText;
        this.StockAmount = StockAmount;
    }

    public void setID(int ID)
    {
        this.ID = ID;
    }

    public void setType(String Type)
    {
        this.Type = Type;
    }

    public void setName(String Name)
    {
        this.Name = Name;
    }

    public void setPriceText(String PriceText)
    {
        this.PriceText = PriceText;
    }

    public void setCost(double Cost)
    {
        this.Cost = Cost;
    }

    public void setQuantityText(String QuantityText)
    {
        this.QuantityText = QuantityText;
    }

    public void setStockAmount(int StockAmount)
    {
        this.StockAmount = StockAmount;
    }

    public int getID()
    {
        return ID;
    }

    public String getType()
    {
        return Type;
    }

    public String getName()
    {
        return Name;
    }

    public String getPriceText()
    {
        return PriceText;
    }

    public double getCost()
    {
        return Cost;
    }

    public String getQuantityText()
    {
        return QuantityText;
    }

    public int getStockAmount()
    {
        return StockAmount;
    }

    public void PrintInventory()
    {
        System.out.println(ID + " " + Type + " " + Name + " " + PriceText
                           + " " + Cost + " " + QuantityText + " " + StockAmount);
    }

}

Body:
You are blocking the input from the Inventory.txt file in you while loop. You are only checking if a next line exists without actually reading the next line. So you're going to an infinite loop here:

    int counter = 0;
    while (input.hasNextLine())
    {
        counter = counter + 1;
    }

You need to call this at some point inside your whilte loop:

input.nextLine();

Tip: You can consolidate all the actions that you are performing inside this while loop. You probably don't need as many loops:

Assigning to line; Declare line before the while loop.

Splitting line into ProductArray. This will be line.split assigned to ProductArray.

Creating the new Inventory object. You may not need an array of Inventory Objects. Simply create one using the ProductArray variable.

Printing the inventory. Simply call the PrintInventory method on the the object created in step 3.

Hope this helps!


问:
Printing statements in thenReturn of mockito
I am using Mockito to mock a certain class while writing my test cases.

Is there a way to print some statements before returning a value? Like:

```<code>when(x.callFunction(10).thenReturn(new String("Hello"));
</code>```

The above statement works, however I am not able to do the following:

```<code>when(x.callFunction(10).thenReturn({
   System.out.println("Mock called---going to return hello");
   return new String("Hello");});
</code>```

答:
If the object you're going to create is not final, then besides thenAnswer provided by @Roland Weisleder, you can just use an anonymous subclass with init block in thenReturn, like the following example code:

```<code>class FoobarFactory {
    public Foobar buildFoobar() {
        return null;
    }
}

class Foobar {
    private String name;
    public Foobar(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}
</code>```

with mock code as:

```<code>@Test
public void testFoobar() throws Exception {
    FoobarFactory foobarFactory = mock(FoobarFactory.class);
    when(foobarFactory.buildFoobar()).thenReturn(new Foobar("somename") {
        {
            System.out.println("Creating mocked Foobar");
        }
    });

    Foobar foobar = foobarFactory.buildFoobar();
    assertThat(foobar.getName(), is("somename"));
}
</code>```

Body:
I am using Mockito to mock a certain class while writing my test cases.

Is there a way to print some statements before returning a value? Like:

when(x.callFunction(10).thenReturn(new String("Hello"));

The above statement works, however I am not able to do the following:

when(x.callFunction(10).thenReturn({
   System.out.println("Mock called---going to return hello");
   return new String("Hello");});

Body:
If the object you're going to create is not final, then besides thenAnswer provided by @Roland Weisleder, you can just use an anonymous subclass with init block in thenReturn, like the following example code:

class FoobarFactory {
    public Foobar buildFoobar() {
        return null;
    }
}

class Foobar {
    private String name;
    public Foobar(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

with mock code as:

@Test
public void testFoobar() throws Exception {
    FoobarFactory foobarFactory = mock(FoobarFactory.class);
    when(foobarFactory.buildFoobar()).thenReturn(new Foobar("somename") {
        {
            System.out.println("Creating mocked Foobar");
        }
    });

    Foobar foobar = foobarFactory.buildFoobar();
    assertThat(foobar.getName(), is("somename"));
}


问:
Supressing oracle banner
Is there a way to avoid banner text that sqlplus shows on connecting.
e.g.

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options

I want to goto prompt. Just want to avoid banner, rest every things is required, like feed back etc.

My requirement is for both 11g and 12c Oracle.

答:
Run sqlplus -s ...

However, it also suppress the prompt SQL>. I don't know a solution which does both: suppressing the banner but showing the prompt.

Title: Supressing oracle banner


问:
Placing two (or more) multi-line variables next to each other bash
Lets say I have 3 variables, each with a multi-line output, like so:

```<code>IPs="10.0.0.1
10.0.0.2
10.0.0.3
10.0.0.4"

MACs="08:16:E9:3D:12:D5
C6:70:A5:25:FF:58
42:96:ED:C8:D5:80
05:89:C6:37:68:9B"

Vendors="Apple
Intel
Sagemcom
HP"
</code>```

and I want to put them next to each other, like so:

```<code>10.0.0.1 08:16:E9:3D:12:D5 Apple
10.0.0.2 C6:70:A5:25:FF:58 Intel
10.0.0.3 42:96:ED:C8:D5:80 Sagemcom
10.0.0.4 05:89:C6:37:68:9B HP
</code>```

How would I do so?

Body:
Lets say I have 3 variables, each with a multi-line output, like so:

IPs="10.0.0.1
10.0.0.2
10.0.0.3
10.0.0.4"

MACs="08:16:E9:3D:12:D5
C6:70:A5:25:FF:58
42:96:ED:C8:D5:80
05:89:C6:37:68:9B"

Vendors="Apple
Intel
Sagemcom
HP"

and I want to put them next to each other, like so:

10.0.0.1 08:16:E9:3D:12:D5 Apple
10.0.0.2 C6:70:A5:25:FF:58 Intel
10.0.0.3 42:96:ED:C8:D5:80 Sagemcom
10.0.0.4 05:89:C6:37:68:9B HP

How would I do so?

Body:
With paste and bash:

paste -d " " <(echo "$IPs") <(echo "$MACs") <(echo "$Vendors")

10.0.0.1 08:16:E9:3D:12:D5 Apple
10.0.0.2 C6:70:A5:25:FF:58 Intel
10.0.0.3 42:96:ED:C8:D5:80 Sagemcom
10.0.0.4 05:89:C6:37:68:9B HP


问:
send variable to
I have a option selector, and I want the value of the chosen option to be based on to a href="#top"> tag. So that
Godfather links to #top,
Shawshank to #middle
Fightclub to #bottom

I have the following code:

```<code><select id="one">
    <option></option>
    <option value="1">Godfather</option>
    <option value="2">Shawshank</option>
    <option value="3">Fightclub</option>
</select>
</code>```

Javascript

```<code>var url;

    $("select").change(function () {

        //console.log($(this).val());

        var val = $(this).val();

        if (val == "1") {
            $("#image").css({"background-image": "url(image/godfather.jpg)"});
            url = "goodfather";
        }
        if (val == "2") {
            $("#image").css({"background-image": "url(image/shawshank.jpg)"});
            url = "shawshank";
        }
        if (val == "3") {
            $("#image").css({"background-image": "url(image/fightclub.jpg)"});
                            url = "fightclub";
</code>```

答:
Try this one.
The attr() method sets or returns attributes and values of the selected elements. When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements.

Set the attribute and value:

```<code>$(selector).attr(attribute,value)
</code>```

See .attr()

```<code>$('#movie-link').attr('href', '#' + url);
</code>```

Here we are setting the href of movie-link as #url.
eg: #godfather

```<code>$('#movie-link').text(url);
</code>```

This rewrites the text of movie-link with url.

var url;

$("select").change(function() {

  //console.log($(this).val());

  var val = $(this).val();

  if (val == "1") {
    $("#image").css({
      "background-image": "url('https://images-na.ssl-images-amazon.com/images/I/41fxpecg67L.jpg')"
    });
    url = "goodfather";
  }
  if (val == "2") {
    $("#image").css({
      "background-image": "url('http://68.media.tumblr.com/f60260c4de4eb3f44ed69c1b84aba752/tumblr_nyjjedR9C21s80h8lo1_1280.jpg')"
    });
    url = "shawshank";
  }
  if (val == "3") {
    $("#image").css({
      "background-image": "url('https://mir-s3-cdn-cf.behance.net/project_modules/disp/8c97ea7728123.560b0a46e7bb7.PNG')"
    });
    url = "fightclub";
  }
  $('#movie-link').attr('href', '#' + url);
  $('#movie-link').text(url);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#image {
  margin: 10px;
  height: 200px;
  width: 300px;
  background-size: contain;
  background-repeat: no-repeat;
  border: 1px solid #ccc;
}</code>```

<select id="one">
    <option>Select option</option>
    <option value="1">Godfather</option>
    <option value="2">Shawshank</option>
    <option value="3">Fightclub</option>
</select>

Select Link```

Title: send variable to <a href>

Body:
I have a option selector, and I want the value of the chosen option to be based on to a  tag. So that
Godfather links to #top,
Shawshank to #middle
Fightclub to #bottom

I have the following code:

<select id="one">
    <option></option>
    <option value="1">Godfather</option>
    <option value="2">Shawshank</option>
    <option value="3">Fightclub</option>
</select>

Javascript

var url;

    $("select").change(function () {

        //console.log($(this).val());

        var val = $(this).val();

        if (val == "1") {
            $("#image").css({"background-image": "url(image/godfather.jpg)"});
            url = "goodfather";
        }
        if (val == "2") {
            $("#image").css({"background-image": "url(image/shawshank.jpg)"});
            url = "shawshank";
        }
        if (val == "3") {
            $("#image").css({"background-image": "url(image/fightclub.jpg)"});
                            url = "fightclub";

Body:
Try this one.
The attr() method sets or returns attributes and values of the selected elements. When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements.

Set the attribute and value:

$(selector).attr(attribute,value)

See .attr()

$('#movie-link').attr('href', '#' + url);

Here we are setting the href of movie-link as #url.
eg: #godfather

$('#movie-link').text(url);

This rewrites the text of movie-link with url.

var url;

$("select").change(function() {

  //console.log($(this).val());

  var val = $(this).val();

  if (val == "1") {
    $("#image").css({
      "background-image": "url('https://images-na.ssl-images-amazon.com/images/I/41fxpecg67L.jpg')"
    });
    url = "goodfather";
  }
  if (val == "2") {
    $("#image").css({
      "background-image": "url('http://68.media.tumblr.com/f60260c4de4eb3f44ed69c1b84aba752/tumblr_nyjjedR9C21s80h8lo1_1280.jpg')"
    });
    url = "shawshank";
  }
  if (val == "3") {
    $("#image").css({
      "background-image": "url('https://mir-s3-cdn-cf.behance.net/project_modules/disp/8c97ea7728123.560b0a46e7bb7.PNG')"
    });
    url = "fightclub";
  }
  $('#movie-link').attr('href', '#' + url);
  $('#movie-link').text(url);
});

#image {
  margin: 10px;
  height: 200px;
  width: 300px;
  background-size: contain;
  background-repeat: no-repeat;
  border: 1px solid #ccc;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="one">
    <option>Select option</option>
    <option value="1">Godfather</option>
    <option value="2">Shawshank</option>
    <option value="3">Fightclub</option>
</select>
<br/>
<div id="image"></div>
<a id="movie-link" href="#">Select Link</a>


问:
Fetch all first child elements from a table
Pretty simple I need to fetch all first type of th elements text :

```<code><html>
<body>

  <table>
  <tr>
    <th>1</th>
    <th>2</th>
    <th>3</th>
  </tr>
  <tr>
    <td>Line #1</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Line #2</td>
    <td>SLD</td>
    <td>68</td>
  </tr>
  <tr>
    <td>Line #3</td>
    <td>MDK</td>
    <td>68</td>
  </tr>
</table>

<script type="text/javascript">

console.log(document.querySelectorAll('table tr td:first-of-type'));

</script>

</body>
</html>
</code>```

I want to be able to fetch all table tr td:first-of-type innertext... small tweak needed here.

答:
I solved it somehow... trail and error... Thanks :)</p>

```<code><html>

<body>

    <table>
        <tr>
            <th>A</th>
            <th>B</th>
            <th>C</th>
        </tr>
        <tr>
            <td>Line #1</td>
            <td>MKD</td>
            <td>68</td>
        </tr>
        <tr>
            <td>Line #2</td>
            <td>SLD</td>
            <td>32</td>
        </tr>
        <tr>
            <td>Line #3</td>
            <td>HAD</td>
            <td>53</td>
        </tr>
        <tr>
            <td>Line #4</td>
            <td>LRD</td>
            <td>49</td>
        </tr>
    </table>

    <script type="text/javascript">
        var theFirstChilds = document.querySelectorAll('table tr td:first-of-type');
        var i;

        for (i = 0; i < theFirstChilds.length; ++i) {
            console.log(theFirstChilds[i].innerText);
        }
    </script>

</body>

</html>
</code>```

Body:
Pretty simple I need to fetch all first type of th elements text :

    1
    2
    3

    Line #1
    Smith
    50

    Line #2
    SLD
    68

    Line #3
    MDK
    68

I want to be able to fetch all table tr td:first-of-type innertext... small tweak needed here.

Body:
I solved it somehow... trail and error... Thanks :)

<html>

<body>

    <table>
        <tr>
            <th>A</th>
            <th>B</th>
            <th>C</th>
        </tr>
        <tr>
            <td>Line #1</td>
            <td>MKD</td>
            <td>68</td>
        </tr>
        <tr>
            <td>Line #2</td>
            <td>SLD</td>
            <td>32</td>
        </tr>
        <tr>
            <td>Line #3</td>
            <td>HAD</td>
            <td>53</td>
        </tr>
        <tr>
            <td>Line #4</td>
            <td>LRD</td>
            <td>49</td>
        </tr>
    </table>

    <script type="text/javascript">
        var theFirstChilds = document.querySelectorAll('table tr td:first-of-type');
        var i;

        for (i = 0; i < theFirstChilds.length; ++i) {
            console.log(theFirstChilds[i].innerText);
        }
    </script>

</body>

</html>


问:
angular 2 tree component click event
In my angular2 project i have implemented angular tree component.i am using the following json data

```<code>nodes = [
{
  id: 1,
  name: 'root1',
  isExpanded: true,
  children: [
    { id: 2, name: 'child1' },
    { id: 3, name: 'child2' }
  ]
},
{
  id: 4,
  name: 'root2',
  children: [
    { id: 5, name: 'child2.1' },
    {
      id: 6,
      name: 'child2.2',
      children: [
        { id: 7, name: 'subsub' }
      ]
    }
  ]
}
];
</code>```

And my html template is,

```<code><tree-root [nodes]="nodes"></tree-root>

getNodeName()
{
//display selected node name
 console.log();
}
</code>```

Tree displaying in my tree,but my problem is, how can i get clicked node details. i want to print selected node name inside the getNodeName() function.

答:
You need to handle event on each node of tree and fire it.

On <tree root> component:

@Output() clickNode = new EventEmitter<Node>(); // with Node is class of data for node.

in template:

...

<your-tree-item (click)="clickHandler(node)"></your-tree-item>

...

clickHandler(node: Node){

this.clickNode.emit(node)

}

Using your tree:

<tree-root (clickNode)="yourHandler($event)"></tree-root>

yourHandler(node: Node) { alert(node.id) }

I also writing a virtual tree component for angular 2+. And it also support your case. You can find at: https://github.com/NamNgKh/angular2_virtual_tree

I going to make CSS theme for it. so other can easily change style of it.

Title: angular 2 tree component click event

Body:
In my angular2 project i have implemented angular tree component.i am using the following json data

nodes = [
{
  id: 1,
  name: 'root1',
  isExpanded: true,
  children: [
    { id: 2, name: 'child1' },
    { id: 3, name: 'child2' }
  ]
},
{
  id: 4,
  name: 'root2',
  children: [
    { id: 5, name: 'child2.1' },
    {
      id: 6,
      name: 'child2.2',
      children: [
        { id: 7, name: 'subsub' }
      ]
    }
  ]
}
];

And my html template is,

<tree-root [nodes]="nodes"></tree-root>

getNodeName()
{
//display selected node name
 console.log();
}

Tree displaying in my tree,but my problem is, how can i get clicked node details. i want to print selected node name inside the getNodeName() function.


Title: remove middle octets from an ip until some criteria is met

Body:
I have a string of IP and port numbers which is like :  "10.213.110.49.33482;10.213.106.12.20001:"
The two ip's are separated by a semi-colon. Last decimal shows port number.
What I need is to convert the above string which would look like:
"10.213.110.49 20001:".

I want to remove the middle octets and port number of first IP using SHELL SCRIPT only. I want to extract the IP from first part ignoring the port number and from second IP i want the port number only

Body:
awk solution:

s="10.213.110.49.33482;10.213.106.12.20001:"
echo $s | awk -F"[.;]" '{OFS=".";print $1,$2,$3,$4" "$10}'

The output:

10.213.110.49 20001: