问:
Page Loading Part in Angularjs
I finished the data loading part in the front-end, and also i'm trying to put the page loading part (Progress bar).But, it is not working in the correct way. I kindly request anyone to help me...

HTML

```<code><div class="w3-col m7" ng-init="init()" ng-show="IsVisibleForm">

    <div class="w3-row-padding">
        <div ng-show="IsVisible" style="text-align:center;">
            <md-progress-circular md-mode="indeterminate"></md-progress-circular>
            <h3>Please wait</h3>
        </div>
        <div class="w3-col m12">
            <div>
                <h2><b>New Dogs</b></h2>

                <br />
                <div>

                    <table class="table defaultTable" ng-show="resultTble">

                        <tr>
                            <th></th>
                            <th>Dog ID</th>
                            <th>Dog Name</th>
                            <th>Sex</th>
                            <th>Sire Name</th>
                            <th>Dam Name</th>
                            <th>Creater</th>
                            <th>Created Date</th>
                            <!--<th></th>-->
                            <!--<th></th>-->
                        </tr>
                        <tr ng-repeat="d in newDogList">
                            <td><a href="#/EditDog/{{d.id}}" target="_blank">$</a></td>
                            <td><a href="#">#</a></td>
                            <td><a href="#/ViewDog/{{d.id}}" target="_blank">{{d.name}}</a></td>
                            <td>{{d.gender==1 ? 'Male' : d.gender==2 ? 'Female' : 'Unknown'}}</td>
                            <td>{{d.sireName}}</td>
                            <td>{{d.damName}}</td>
                            <!--<td><a href="#/Mail">&</a></td>-->
                            <td><a href="#/Mail/{{d.createdMailId}}" target="_blank">{{d.createdUserName}}</a></td>
                            <td>{{d.createdDate}}</td>
                            <!--<td>
                                <a href="#/Edit" class="btn btn-success btn-lg" title="Edit">
                                <span style="font-size: 15px" class="glyphicon glyphicon-edit"></span></a>
                            </td>-->
                           <!-- {{d.gender==1 ? 'Male' : d.gender==2 ? 'Female' : 'Unknown'}}-->
                            <!--{{d.gender==1 ? 'Male' : 'Female' }}-->
                            <!--<td>
                                <a href="#" class="btn btn-success btn-lg" title="Delete">
                                    <span style="font-size: 15px" class="glyphicon glyphicon-remove"></span>
                                </a>
                            </td>-->
                        </tr>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

controller

```<code>    $scope.init = function () {
            $scope.IsVisible = true;
            $scope.IsVisibleForm = false;
            $scope.resultTble = false;
            //$scope.mail = urls.domain + "#/Mail/?createdMailId=";
    }

    var request = $http({
        method: 'GET',
        url: urls.api + 'Dog/NewDogs'

    }).success(function (data, status) {

        //console.log(data);
        //console.log(JSON.stringify(data));
        //console.log(JSON.parse(JSON.stringify(data)));

        $scope.newDogList = angular.fromJson(data);
        $scope.IsVisible = false;
        $scope.IsVisibleForm = true;
        $scope.resultTble = true;
    })
     .error(function (error) {
         $scope.status = 'Unable to load new dog list: ' + error.message;
         console.log($scope.status);
     });
</code>```

Thankyou

答:
Your ng-model named isVisibleForm is initialized to false which hides the entire div containing your progress bar. Shouldn't that be set (true)?

Nit: That model seems better named as isFormVisible.

UPDATE (after your comment):

You don't need another model, one is enough.

```<code><div class="w3-col m7" ng-init="init()">

    <div class="w3-row-padding">
        <div ng-show="IsVisible" style="text-align:center;">
            <md-progress-circular md-mode="indeterminate"></md-progress-circular>
            <h3>Please wait</h3>
        </div>
        <div ng-hide="IsVisible" class="w3-col m12">
            <div>
                <h2><b>New Dogs</b></h2>
.
.
</code>```

Title: Page Loading Part in Angularjs

Body:
I finished the data loading part in the front-end, and also i'm trying to put the page loading part (Progress bar).But, it is not working in the correct way. I kindly request anyone to help me...

HTML

            <md-progress-circular md-mode="indeterminate"></md-progress-circular>

Please wait

New Dogs

                            Dog ID
                            Dog Name
                            Sex
                            Sire Name
                            Dam Name
                            Creater
                            Created Date

                            $
                            #
                            {{d.name}}
                            {{d.gender==1 ? 'Male' : d.gender==2 ? 'Female' : 'Unknown'}}
                            {{d.sireName}}
                            {{d.damName}}

                            {{d.createdUserName}}
                            {{d.createdDate}}

controller

    $scope.init = function () {
            $scope.IsVisible = true;
            $scope.IsVisibleForm = false;
            $scope.resultTble = false;
            //$scope.mail = urls.domain + "#/Mail/?createdMailId=";
    }

    var request = $http({
        method: 'GET',
        url: urls.api + 'Dog/NewDogs'

    }).success(function (data, status) {

        //console.log(data);
        //console.log(JSON.stringify(data));
        //console.log(JSON.parse(JSON.stringify(data)));

        $scope.newDogList = angular.fromJson(data);
        $scope.IsVisible = false;
        $scope.IsVisibleForm = true;
        $scope.resultTble = true;
    })
     .error(function (error) {
         $scope.status = 'Unable to load new dog list: ' + error.message;
         console.log($scope.status);
     });

Thankyou

Body:
Your ng-model named isVisibleForm is initialized to false which hides the entire div containing your progress bar. Shouldn't that be set (true)?

Nit: That model seems better named as isFormVisible.

UPDATE (after your comment):

You don't need another model, one is enough.

<div class="w3-col m7" ng-init="init()">

    <div class="w3-row-padding">
        <div ng-show="IsVisible" style="text-align:center;">
            <md-progress-circular md-mode="indeterminate"></md-progress-circular>
            <h3>Please wait</h3>
        </div>
        <div ng-hide="IsVisible" class="w3-col m12">
            <div>
                <h2><b>New Dogs</b></h2>
.
.


来源: stackexchange

问:
Return mulitple string is not working
I want to return multiple string from the below function. How to do that</p>

```<code>public static string GETSTATE_SAP(string SAP)
    {
        string strState = "";
        string strSiteAdd = "";
        string strLatitude = "";
        string strLongtiude = "";
        try
        {
            OracleConnection Oraconn = new OracleConnection(ConfigurationManager.ConnectionStrings["ConnectionStringAPPSAPID"].ConnectionString);
            Oraconn.Open();
            OracleCommand cmd = new OracleCommand("Select STATE, SITE_NAME, SITE_ADDRESS, latitude, longitude from R4G_OSP.UBR where SAP_ID = '" + SAP + "'", Oraconn);
            OracleDataAdapter da = new OracleDataAdapter(cmd);
            DataTable dtSap = new DataTable();
            da.Fill(dtSap);
            strState = Convert.ToString(dtSap.Rows[0][0]);
            strSiteAdd = Convert.ToString(dtSap.Rows[0][0]);
            strLatitude = Convert.ToString(dtSap.Rows[0][0]);
            strLongtiude = Convert.ToString(dtSap.Rows[0][0]);
        }
        catch (Exception)
        {
        }
        return strState, strSiteAdd, strLatitude, strLongtiude;
    }
</code>```

答:
Your method returns a string and thus return strState, strSiteAdd, strLatitude, strLongtiude; statement is illegal.

You can consider changing your method signature to return a DataTable like below and return the DataTable you created

```<code> public static DataTable GETSTATE_SAP(string SAP)
    {
</code>```

(OR)

Change it to return a array of string

```<code> public static IEnumerable<string> GETSTATE_SAP(string SAP)
    {
</code>```

ContentLicense: CC BY-SA 3.0

Title: Return mulitple string is not working

Body:
I want to return multiple string from the below function. How to do that

public static string GETSTATE_SAP(string SAP)
    {
        string strState = "";
        string strSiteAdd = "";
        string strLatitude = "";
        string strLongtiude = "";
        try
        {
            OracleConnection Oraconn = new OracleConnection(ConfigurationManager.ConnectionStrings["ConnectionStringAPPSAPID"].ConnectionString);
            Oraconn.Open();
            OracleCommand cmd = new OracleCommand("Select STATE, SITE_NAME, SITE_ADDRESS, latitude, longitude from R4G_OSP.UBR where SAP_ID = '" + SAP + "'", Oraconn);
            OracleDataAdapter da = new OracleDataAdapter(cmd);
            DataTable dtSap = new DataTable();
            da.Fill(dtSap);
            strState = Convert.ToString(dtSap.Rows[0][0]);
            strSiteAdd = Convert.ToString(dtSap.Rows[0][0]);
            strLatitude = Convert.ToString(dtSap.Rows[0][0]);
            strLongtiude = Convert.ToString(dtSap.Rows[0][0]);
        }
        catch (Exception)
        {
        }
        return strState, strSiteAdd, strLatitude, strLongtiude;
    }

Body:
Your method returns a string and thus return strState, strSiteAdd, strLatitude, strLongtiude; statement is illegal.

You can consider changing your method signature to return a DataTable like below and return the DataTable you created

 public static DataTable GETSTATE_SAP(string SAP)
    {

(OR)

Change it to return a array of string

 public static IEnumerable<string> GETSTATE_SAP(string SAP)
    {


问:
Are there any free parser generators that generate C++ code and handle Unicode correctly?
After asking this question, I'm now sold on trying to use a parser generator, where before I was going to write things manually.

However, I can't seem to find any such parser that generates C++ code, nor can I find a parser that correctly handles Unicode. (note that my input is in UCS-2 -- I don't care about supporting bits outside of the Basic Multilingual Plane if that makes building the parser more difficult)

There are some parsers which can generate C, but such parsers all seem to throw exception safety out the window, which would prevent me from using C++ inside any semantic actions.

Does a parser generator exist which meets these two tenets, or am I stuck doing everything by hand?

EDIT: Oh, and my project is BSL licensed, so there can't be many restrictions on use of the output of the parser generator itself.

答: ANTLR has Unicode support. It has C++ (and C, Java and a few other languages) support, though I've never used the C++ support so I'm not sure how well developed it is.</p>

ContentLicense: CC BY-SA 2.5


问:
HttpResponse does not contain a definition for AddHeader for Dot Net Core
When moving a project into .Net Core, AddHeader throws an error:

Error CS1061  'HttpResponse' does not contain a definition for
  'AddHeader' and no extension method 'AddHeader' accepting a first
  argument of type 'HttpResponse' could be found (are you missing a
  using directive or an assembly reference?)    .NETCoreApp,Version=v1.0

答:
The answer is to instead do the following (without using AddHeader) :</p>

```<code>Response.Headers["key-goes-here"] = "value-goes-here";
</code>```

Body:
The answer is to instead do the following (without using AddHeader) :

Response.Headers["key-goes-here"] = "value-goes-here";


问:
OPC UA.NET custom Node Manager creating
I'm trying to use UA-.NETStandardLibrary by OPC Foundation to create my own OPC UA Server that will maintain some variables.
I've created a server class inherited from StandardServer and node manager inherited from CustomNodeManager2.
There were some node managers in their examples, I removed them and add my own one. The server starts normally and doesn't contain any nodes except from standard ones, as planned. So, my problem is how to create my own variable node from code (not from xml, as in examples) and be able update its value on demand.

For example, I want to add a folder with couple of nodes inside.

Does anyone have a code snippet which demonstrates how to do it? I don't want anybody write it for me, I will appreciate only if you just tell me about a right way to make it.

Thanks a lot.

答:
I am pretty sure the snippets you are looking for are included. Here is my testing code and I am 100% positive, I didn't write the second piece of code. Anyway, if this helps you...

```<code>                {
                    var ticker_seq = createVariable(myFolder, "MyFolder/Ticker", "Ticker", BuiltInType.UInt64, ValueRanks.Scalar);
                    variables.Add(ticker_seq);

                    subscriptions.Add(clock.Ticker.Subscribe(val =>
                    {
                        lock (Lock)
                        {
                            ticker_seq.Value = val;
                            ticker_seq.Timestamp = DateTime.UtcNow;
                            ticker_seq.ClearChangeMasks(SystemContext, false);
                        }
                    }));
                }
</code>```

and creation

```<code>    private BaseDataVariableState createVariable(NodeState parent, string path, string name, NodeId dataType, int valueRank)
    {
        BaseDataVariableState variable = new BaseDataVariableState(parent);

        variable.SymbolicName = name;
        variable.ReferenceTypeId = ReferenceTypes.Organizes;
        variable.TypeDefinitionId = VariableTypeIds.BaseDataVariableType;
        variable.NodeId = new NodeId(path, NamespaceIndex);
        variable.BrowseName = new QualifiedName(path, NamespaceIndex);
        variable.DisplayName = new LocalizedText("en", name);
        variable.WriteMask = AttributeWriteMask.DisplayName | AttributeWriteMask.Description;
        variable.UserWriteMask = AttributeWriteMask.DisplayName | AttributeWriteMask.Description;
        variable.DataType = dataType;
        variable.ValueRank = valueRank;
        variable.AccessLevel = AccessLevels.CurrentReadOrWrite;
        variable.UserAccessLevel = AccessLevels.CurrentReadOrWrite;
        variable.Historizing = false;
        variable.Value = 0;
        variable.StatusCode = StatusCodes.Good;
        variable.Timestamp = DateTime.UtcNow;

        if (parent != null)
        {
            parent.AddChild(variable);
        }

        return variable;
    }
</code>```

creating the folder:

```<code>    private FolderState CreateFolder(NodeState parent, string path, string name)
    {
        FolderState folder = new FolderState(parent);

        folder.SymbolicName = name;
        folder.ReferenceTypeId = ReferenceTypes.Organizes;
        folder.TypeDefinitionId = ObjectTypeIds.FolderType;
        folder.NodeId = new NodeId(path, NamespaceIndex);
        folder.BrowseName = new QualifiedName(path, NamespaceIndex);
        folder.DisplayName = new LocalizedText("en", name);
        folder.WriteMask = AttributeWriteMask.None;
        folder.UserWriteMask = AttributeWriteMask.None;
        folder.EventNotifier = EventNotifiers.None;

        if (parent != null)
        {
            parent.AddChild(folder);
        }

        return folder;
    }
</code>```

Title: OPC UA.NET custom Node Manager creating

Body:
I am pretty sure the snippets you are looking for are included. Here is my testing code and I am 100% positive, I didn't write the second piece of code. Anyway, if this helps you...

                {
                    var ticker_seq = createVariable(myFolder, "MyFolder/Ticker", "Ticker", BuiltInType.UInt64, ValueRanks.Scalar);
                    variables.Add(ticker_seq);

                    subscriptions.Add(clock.Ticker.Subscribe(val =>
                    {
                        lock (Lock)
                        {
                            ticker_seq.Value = val;
                            ticker_seq.Timestamp = DateTime.UtcNow;
                            ticker_seq.ClearChangeMasks(SystemContext, false);
                        }
                    }));
                }

and creation

    private BaseDataVariableState createVariable(NodeState parent, string path, string name, NodeId dataType, int valueRank)
    {
        BaseDataVariableState variable = new BaseDataVariableState(parent);

        variable.SymbolicName = name;
        variable.ReferenceTypeId = ReferenceTypes.Organizes;
        variable.TypeDefinitionId = VariableTypeIds.BaseDataVariableType;
        variable.NodeId = new NodeId(path, NamespaceIndex);
        variable.BrowseName = new QualifiedName(path, NamespaceIndex);
        variable.DisplayName = new LocalizedText("en", name);
        variable.WriteMask = AttributeWriteMask.DisplayName | AttributeWriteMask.Description;
        variable.UserWriteMask = AttributeWriteMask.DisplayName | AttributeWriteMask.Description;
        variable.DataType = dataType;
        variable.ValueRank = valueRank;
        variable.AccessLevel = AccessLevels.CurrentReadOrWrite;
        variable.UserAccessLevel = AccessLevels.CurrentReadOrWrite;
        variable.Historizing = false;
        variable.Value = 0;
        variable.StatusCode = StatusCodes.Good;
        variable.Timestamp = DateTime.UtcNow;

        if (parent != null)
        {
            parent.AddChild(variable);
        }

        return variable;
    }

creating the folder:

    private FolderState CreateFolder(NodeState parent, string path, string name)
    {
        FolderState folder = new FolderState(parent);

        folder.SymbolicName = name;
        folder.ReferenceTypeId = ReferenceTypes.Organizes;
        folder.TypeDefinitionId = ObjectTypeIds.FolderType;
        folder.NodeId = new NodeId(path, NamespaceIndex);
        folder.BrowseName = new QualifiedName(path, NamespaceIndex);
        folder.DisplayName = new LocalizedText("en", name);
        folder.WriteMask = AttributeWriteMask.None;
        folder.UserWriteMask = AttributeWriteMask.None;
        folder.EventNotifier = EventNotifiers.None;

        if (parent != null)
        {
            parent.AddChild(folder);
        }

        return folder;
    }


问:
google search, json_decode gives null
```<code>    $query = "Poultry meat is a major source of animal protein considering";

function fetch_google($query) {
$cleanQuery = str_replace(" ","+",$query);

$url = 'http://www.google.com/search?q='.urlencode($cleanQuery);
$data=file_get_contents($url);
$json = json_decode($data, true);

for($x=0;$x<count($json->responseData->results);$x++){

echo "<b>Result ".($x+1)."</b>";
echo "<br>URL: ";
echo $json->responseData->results[$x]->url;
echo "<br>VisibleURL: ";
echo $json->responseData->results[$x]->visibleUrl;
echo "<br>Title: ";
echo $json->responseData->results[$x]->title;
echo "<br>Content: ";
echo $json->responseData->results[$x]->content;
echo "<br><br>";
}
  }

  fetch_google($query);
</code>```

i am try to get search result, but in return json_decode giving null values ..
tried searching for answer but failed.

var_dump($url);  gives result .. but not $json

答:
Might also have to use this when decoding raw 'google json'</p>

```<code>$php_json_txt = str_replace('\\x', '\\\\x', $google_json_txt);
$data = json_decode($php_json_txt, true);
</code>```

Title: google search, json_decode gives null

Body:
    $query = "Poultry meat is a major source of animal protein considering";

function fetch_google($query) {
$cleanQuery = str_replace(" ","+",$query);

$url = 'http://www.google.com/search?q='.urlencode($cleanQuery);
$data=file_get_contents($url);
$json = json_decode($data, true);

for($x=0;$x<count($json->responseData->results);$x++){

echo "Result ".($x+1)."";
echo "
URL: ";
echo $json->responseData->results[$x]->url;
echo "
VisibleURL: ";
echo $json->responseData->results[$x]->visibleUrl;
echo "
Title: ";
echo $json->responseData->results[$x]->title;
echo "
Content: ";
echo $json->responseData->results[$x]->content;
echo "

";
}
  }

  fetch_google($query);

i am try to get search result, but in return json_decode giving null values ..
tried searching for answer but failed.

var_dump($url);  gives result .. but not $json

Body:
Might also have to use this when decoding raw 'google json'

$php_json_txt = str_replace('\\x', '\\\\x', $google_json_txt);
$data = json_decode($php_json_txt, true);


问:
How to deploy my Dynamic web project on internet
I am working in my final year project and I created a web service in a dynamic web project using eclipse JEE, tomcat 8.5 and Axis 2 ( all this is running in Ubuntu 16). this web servicie calls some programs that are installed on a computer ( Matlab for instance) so I need this computer to host the Web Service. This web service works fine in local host ( I created a client  to check it) now I need to do the next step. how can I deploy this web service on internet? ( NO localhost), There is any tutorial or documentation to do something like this? The computer where I am working is of my university so it is connected to the university network.

I have read that I need a WAR file, I know that if  I right click my project and the select export it says "WAR file", this  war is going to have all the references and .jar that I added ? ( I am afraid of this because I neeeded to add some .jar and also some native library locations to them) Also I know that I need to have a Statc IP instead of a dynamic one. how can I achieve it if I have no access to the university routers?

Thanks for your help.

答:
As you stated you need a "computer to host the Web Service" on internet, as you also have the constrain to use specific libraries so you cannot use a "ready-to-host"(paas) solution like heroku because you wouldn't have access/control to the computer hosting your webapp. The only solution I know to deal with that is VPS hosting (https://www.ovh.com/us/vps/) with that you can "rent" a remote computer (with ubuntu 16 if you want) and have total control on it for example you can install whatever native library you want on it, and also any servlet container/web server you want like you would on your local computer.

But then your web service will be on internet, which is "outside" the university network, if you need to access some data/services only accessible from the university network, you cannot use this solution unless you have a special (and secured) access to connect the university network via VPN for example but you'd have to ask to your university if something exists in the university network to allow traffic coming from internet (which I suppose is not the case...but you can still ask to the IT department of the university). Anyway, what you want to do cannot be achieved the "easy-way", lot of work foreseen to have something like this working. If it's a university project, maybe it should stay inside the university network.


问:
PHP (7.1) inheritance issue
I have the following structure:

```<code>class AffiliateRepository extends GenericRepository implements IAffiliateRepository {

}

abstract class GenericRepository  {
    public function save(BaseModel $model) : int{
        $model->save();
        return $model->getId();
    }

}

interface IAffiliateRepository  {

    public function save(Affiliate $affiliate) : int;
}

public class Affiliate extends BaseModel{}

$affiliateRepository  = new AffiliateRepository();
$affiliateRepository->save(new Affiliate());
</code>```

I am expecting GenericRepository to take care on the save action.

but I'm getting the following error:

Declaration of App\Services\AffiliateRepository::save(App\Models\Affiliate $affiliate): int
should be compatible with
App\Services\GenericRepository::save(App\Models\BaseModel $model): int

Why is that? Affiliate inherits from BaseModel.

Whats the best way to overcome that and let GenericRepository handle the save function call.

thanks

答: @enricog gave the correct answer in a comment: to satisfy the interface the save method must accept any object that is a BaseModel. The method provided by IAffiliateRepository does not do that.

Title: PHP (7.1) inheritance issue

Body:
I have the following structure:

class AffiliateRepository extends GenericRepository implements IAffiliateRepository {

}

abstract class GenericRepository  {
    public function save(BaseModel $model) : int{
        $model->save();
        return $model->getId();
    }

}

interface IAffiliateRepository  {

    public function save(Affiliate $affiliate) : int;
}

public class Affiliate extends BaseModel{}

$affiliateRepository  = new AffiliateRepository();
$affiliateRepository->save(new Affiliate());

I am expecting GenericRepository to take care on the save action.

but I'm getting the following error:

Declaration of App\Services\AffiliateRepository::save(App\Models\Affiliate $affiliate): int
should be compatible with
App\Services\GenericRepository::save(App\Models\BaseModel $model): int

Why is that? Affiliate inherits from BaseModel.

Whats the best way to overcome that and let GenericRepository handle the save function call.

thanks


问:
Retrieve Grid Id on CellEdit JqGrid
i was trying to do a Cell Editing based on this documentation
http://www.trirand.com/jqgridwiki/doku.php?id=wiki:cell_editing

I have two questions:

How can i get the Index of my row posted to the server:
The information i'm getting posted is the following:
a) value of the cell
b) RowId

The thing is that the rowId doesn't help me. I need the actual Id of the information I'm displaying so i can do the server update with that Id.

colNames: ['Id', 'Codigo', 'Nombre'],

colModel: [
{ name: 'Id', index: 'Id', width: 50, align: 'left', hidden: true },

{ name: 'Codigo', index: 'Codigo', width: 55, align: 'left', editable: true, editrules:
{ number: true} },

{ name: 'Nombre', index: 'Nombre', width: 200, align: 'left' }],

I need the value of the column 'Id' to do my update.

2.I don't understand in the documentation how to manage an error from the server, so I can display the error message.

Thank you very much!

Notes:

a) I've already asked in the forum of trirand, but no one reply it to me.

b) If anyone has done this, it would help if help me pasting the code.

c) I'm working on MVC 2 Asp.net

答:
Q1:
you can use Key:true , editable: true, in colModel

```<code>{ key:true, name: 'Id', index: 'Id', width: 50, align: 'left', editable: true, hidden:true}

  Then in add/edit method ( add beforeShowForm method in add/edit method), you have to explicitly hide this field the field of id inside of beforeShowForm method
  $('#tr_Id').hide();

   i.e
         beforeShowForm: function (e) {
                   $('#tr_Id').hide();
                }
</code>```

Q2:

```<code>  add 'afterSubmit' method in add/edit/delete method , i'm using Web api Server ,
  i.e
      afterSubmit: function (response) {
            if (response.statusText == 'Created') {
                //   alert("Create Successfully")
                ShowMessage("Add Successfully", 'Success');
                //reload the grid
                $(this).jqGrid("setGridParam", { datatype: 'json' });
                return [true];
            }
            else {
                ShowMessage("Operation Failed", 'Error');
                return [false];
            }

        },
</code>```

I hope this will work for you. Still u Need Any kind of help please comment below

Title: Retrieve Grid Id on CellEdit JqGrid

Body:
Q1:
you can use Key:true , editable: true, in colModel

{ key:true, name: 'Id', index: 'Id', width: 50, align: 'left', editable: true, hidden:true}

  Then in add/edit method ( add beforeShowForm method in add/edit method), you have to explicitly hide this field the field of id inside of beforeShowForm method
  $('#tr_Id').hide();

   i.e
         beforeShowForm: function (e) {
                   $('#tr_Id').hide();
                }

Q2:

  add 'afterSubmit' method in add/edit/delete method , i'm using Web api Server ,
  i.e
      afterSubmit: function (response) {
            if (response.statusText == 'Created') {
                //   alert("Create Successfully")
                ShowMessage("Add Successfully", 'Success');
                //reload the grid
                $(this).jqGrid("setGridParam", { datatype: 'json' });
                return [true];
            }
            else {
                ShowMessage("Operation Failed", 'Error');
                return [false];
            }

        },

I hope this will work for you. Still u Need Any kind of help please comment below


问:
Adding a single character to add keys in Counter
If the type of a Counter object's keys is str, i.e.:

I could do this:

```<code>>>> vocab_counter = Counter("the lazy fox jumps over the brown dog".split())

>>> vocab_counter  = Counter({k+u"\uE000":v for k,v in vocab_counter.items()})
>>> vocab_counter
Counter({'brown\ue000': 1,
         'dog\ue000': 1,
         'fox\ue000': 1,
         'jumps\ue000': 1,
         'lazy\ue000': 1,
         'over\ue000': 1,
         'the\ue000': 2})
</code>```

What would be a quick and/or pythonic way to add a character to all keys?

Is the above method the only way to achieve the final counter with the character appended to all keys? Are there other way(s) to achieve the same goal?

答:
Shortest way i used is,</p>

```<code>vocab_counter = Counter("the lazy fox jumps over the brown dog".split())
for key in vocab_counter.keys():
  vocab_counter[key+u"\uE000"] = vocab_counter.pop(key)
</code>```

Body:
If the type of a Counter object's keys is str, i.e.:

I could do this:

>>> vocab_counter = Counter("the lazy fox jumps over the brown dog".split())

>>> vocab_counter  = Counter({k+u"\uE000":v for k,v in vocab_counter.items()})
>>> vocab_counter
Counter({'brown\ue000': 1,
         'dog\ue000': 1,
         'fox\ue000': 1,
         'jumps\ue000': 1,
         'lazy\ue000': 1,
         'over\ue000': 1,
         'the\ue000': 2})

What would be a quick and/or pythonic way to add a character to all keys?

Is the above method the only way to achieve the final counter with the character appended to all keys? Are there other way(s) to achieve the same goal?

Body:
Shortest way i used is,

vocab_counter = Counter("the lazy fox jumps over the brown dog".split())
for key in vocab_counter.keys():
  vocab_counter[key+u"\uE000"] = vocab_counter.pop(key)


答:
There are several ways to return info, I advise you to return a class. This is because the info is related but does not have the same meaning. You use an array or list when the elements are representing the same type of data. For example a list of menu items, a list of state info's etc.

```<code>public class StateInfo
{
    public string State {get;set;}
    public string SiteAdd {get;set;}
    public string Latitude {get;set;}
    public string Longtiude {get;set;}
}

public static StateInfo GETSTATE_SAP(string SAP)
{
    var result = new StateInfo();

    try
    {
        OracleConnection Oraconn = new OracleConnection(ConfigurationManager.ConnectionStrings["ConnectionStringAPPSAPID"].ConnectionString);
        Oraconn.Open();
        OracleCommand cmd = new OracleCommand("Select STATE, SITE_NAME, SITE_ADDRESS, latitude, longitude from R4G_OSP.UBR where SAP_ID = '" + SAP + "'", Oraconn);
        OracleDataAdapter da = new OracleDataAdapter(cmd);
        DataTable dtSap = new DataTable();
        da.Fill(dtSap);
        result.State = Convert.ToString(dtSap.Rows[0][0]);
        result.SiteAdd = Convert.ToString(dtSap.Rows[0][0]);
        result.Latitude = Convert.ToString(dtSap.Rows[0][0]);
        result.Longtiude = Convert.ToString(dtSap.Rows[0][0]);
    }
    catch (Exception)   // <--- I'll explain below..
    {
        return null;
    }

    return result;
}
</code>```

This way you're not depending on the order of returning the info. It's making a lot easier to handle.

Usage:

```<code>var stateInfo = GETSTATE_SAP(sap);

if(stateInfo != null)
    Debug.WriteLine(stateInfo.Longtiude);
</code>```

try/catch in your method:

I marked your try/catch as 'explain below'.Imagine you call this method to get your information, and you can't 'see' what went wrong, but the information is empty. The called cannot verify the information is right of wrong. Either return null or do not catch the exception here:

Title: Return mulitple string is not working

Body:
There are several ways to return info, I advise you to return a class. This is because the info is related but does not have the same meaning. You use an array or list when the elements are representing the same type of data. For example a list of menu items, a list of state info's etc.

public class StateInfo
{
    public string State {get;set;}
    public string SiteAdd {get;set;}
    public string Latitude {get;set;}
    public string Longtiude {get;set;}
}

public static StateInfo GETSTATE_SAP(string SAP)
{
    var result = new StateInfo();

    try
    {
        OracleConnection Oraconn = new OracleConnection(ConfigurationManager.ConnectionStrings["ConnectionStringAPPSAPID"].ConnectionString);
        Oraconn.Open();
        OracleCommand cmd = new OracleCommand("Select STATE, SITE_NAME, SITE_ADDRESS, latitude, longitude from R4G_OSP.UBR where SAP_ID = '" + SAP + "'", Oraconn);
        OracleDataAdapter da = new OracleDataAdapter(cmd);
        DataTable dtSap = new DataTable();
        da.Fill(dtSap);
        result.State = Convert.ToString(dtSap.Rows[0][0]);
        result.SiteAdd = Convert.ToString(dtSap.Rows[0][0]);
        result.Latitude = Convert.ToString(dtSap.Rows[0][0]);
        result.Longtiude = Convert.ToString(dtSap.Rows[0][0]);
    }
    catch (Exception)   // <--- I'll explain below..
    {
        return null;
    }

    return result;
}

This way you're not depending on the order of returning the info. It's making a lot easier to handle.

Usage:

var stateInfo = GETSTATE_SAP(sap);

if(stateInfo != null)
    Debug.WriteLine(stateInfo.Longtiude);

try/catch in your method:

I marked your try/catch as 'explain below'.Imagine you call this method to get your information, and you can't 'see' what went wrong, but the information is empty. The called cannot verify the information is right of wrong. Either return null or do not catch the exception here:


问:
extending c# syntax with roslyn
I'm trying to implement a "return if"/"return value if" without an else case, since I only want to return or return a value if a condition is valid.

I know, there is the if (condition) return; or if (condition) return value; but I want to have the code a bit cleaner AND it would be nice to have that syntax since it is more readable.

I heard with roslyn this is possible and read the question with its answeres here: Is there a way to implement custom language features in C#? but I have no clue how to implement it.

So the code would be something like this:

```<code>public class Testclass
{
    public static void Main(String[] args)
    {
        Testclass t = new Testclass();
        t.TestMyClassWithVoid();
        bool success = t.TestMyClassWithInt(3) == 3;
        bool fail = t.TestMyClassWithInt(2) == 2;
    }

    public void TestMyClassWithVoid()
    {
        int value = GetValueFromSomeWhere();
        return if value == 3;

        DoSomeOtherStuffSinceValueIsNotThree();
    }

    public int TestMyClassWithInt(int value)
    {
        return value if value == 3;

        DoSomeOtherStuffSinceValueIsNotThree();
        return -1;
    }
}
</code>```

any idea how I could solve this? I started trying with the Roslyn.Compilers.CSharp-namespace but I have no clue how to start implementing.

答:
Here is an alternative suggestion that may work for someone who is looking for extension points into roslyn. It can even be provided as a nuget package! Create an analyser and a code fix provider for your syntax.

Essentially what you would get is a red squiggly line under any syntax of your choosing, with a auto-fix hint which would let you transform it into the regular C# equivalent.

It could also be used for validating the usage of your library, checking that the right attributes are in the right locations, detect common code smells, etc.

Read up more on code analysers at this post: https://msdn.microsoft.com/en-us/magazine/dn879356.aspx

A quick summary of that link (but by no means a replacement):

Install VS SDK, Roslyn SDK, Compiler Platform SDK

Create new project: Analyzer with Code Fix (NuGet + VSIX) template.

There will be 3 samples on how to create an analyser / code fix provider

Set the VSIX project as the startup project and run

Title: extending c# syntax with roslyn

Body:
I'm trying to implement a "return if"/"return value if" without an else case, since I only want to return or return a value if a condition is valid.

I know, there is the if (condition) return; or if (condition) return value; but I want to have the code a bit cleaner AND it would be nice to have that syntax since it is more readable.

I heard with roslyn this is possible and read the question with its answeres here: Is there a way to implement custom language features in C#? but I have no clue how to implement it.

So the code would be something like this:

public class Testclass
{
    public static void Main(String[] args)
    {
        Testclass t = new Testclass();
        t.TestMyClassWithVoid();
        bool success = t.TestMyClassWithInt(3) == 3;
        bool fail = t.TestMyClassWithInt(2) == 2;
    }

    public void TestMyClassWithVoid()
    {
        int value = GetValueFromSomeWhere();
        return if value == 3;

        DoSomeOtherStuffSinceValueIsNotThree();
    }

    public int TestMyClassWithInt(int value)
    {
        return value if value == 3;

        DoSomeOtherStuffSinceValueIsNotThree();
        return -1;
    }
}

any idea how I could solve this? I started trying with the Roslyn.Compilers.CSharp-namespace but I have no clue how to start implementing.


问:
How can I use binary heap in the Dijkstra algorithm?
I am writing code of dijkstra algorithm, for the part where we are supposed to find the node with minimum distance from the currently being used node, I am using a array over there and traversing it fully to figure out the node.

This part can be replaced by binary heap and we can figure out the node in O(1) time, but We also update the distance of the node in further iterations, How will I incorporate that heap?

In case of array, all I have to do is go to the (ith -1) index and update the value of that node, but same thing can't be done in Binary heap, I will have to do the full search to figure out the position of the node and then update it.

What is workaround of this problem?

答:
I am using the following approach. Whenever I insert something into the heap I pass a pointer to an integer (this memory location is ownned by me, not the heap) which should contain the position of the element in the array managed by the heap. So if the sequence of elements in the heap is rearranged it is supposed to update the values pointed to by these pointers.

So for the Dijkstra algirithm I am creating a posInHeap array of sizeN.

Hopefully, the code will make it more clear.

```<code>template <typename T, class Comparison = std::less<T>> class cTrackingHeap
{
public:
    cTrackingHeap(Comparison c) : m_c(c), m_v() {}
    cTrackingHeap(const cTrackingHeap&) = delete;
    cTrackingHeap& operator=(const cTrackingHeap&) = delete;

    void DecreaseVal(size_t pos, const T& newValue)
    {
        m_v[pos].first = newValue;
        while (pos > 0)
        {
            size_t iPar = (pos - 1) / 2;
            if (newValue < m_v[iPar].first)
            {
                swap(m_v[pos], m_v[iPar]);
                *m_v[pos].second = pos;
                *m_v[iPar].second = iPar;
                pos = iPar;
            }
            else
                break;
        }
    }

    void Delete(size_t pos)
    {
        *(m_v[pos].second) = numeric_limits<size_t>::max();// indicate that the element is no longer in the heap

        m_v[pos] = m_v.back();
        m_v.resize(m_v.size() - 1);

        if (pos == m_v.size())
            return;

        *(m_v[pos].second) = pos;

        bool makingProgress = true;
        while (makingProgress)
        {
            makingProgress = false;
            size_t exchangeWith = pos;
            if (2 * pos + 1 < m_v.size() && m_c(m_v[2 * pos + 1].first, m_v[pos].first))
                exchangeWith = 2 * pos + 1;
            if (2 * pos + 2 < m_v.size() && m_c(m_v[2 * pos + 2].first, m_v[exchangeWith].first))
                exchangeWith = 2 * pos + 2;
            if (pos > 0 && m_c(m_v[pos].first, m_v[(pos - 1) / 2].first))
                exchangeWith = (pos - 1) / 2;

            if (exchangeWith != pos)
            {
                makingProgress = true;
                swap(m_v[pos], m_v[exchangeWith]);
                *m_v[pos].second = pos;
                *m_v[exchangeWith].second = exchangeWith;
                pos = exchangeWith;
            }
        }
    }

    void Insert(const T& value, size_t* posTracker)
    {
        m_v.push_back(make_pair(value, posTracker));
        *posTracker = m_v.size() - 1;

        size_t pos = m_v.size() - 1;

        bool makingProgress = true;
        while (makingProgress)
        {
            makingProgress = false;

            if (pos > 0 && m_c(m_v[pos].first, m_v[(pos - 1) / 2].first))
            {
                makingProgress = true;
                swap(m_v[pos], m_v[(pos - 1) / 2]);
                *m_v[pos].second = pos;
                *m_v[(pos - 1) / 2].second = (pos - 1) / 2;
                pos = (pos - 1) / 2;
            }
        }
    }

    const T& GetMin() const
    {
        return m_v[0].first;
    }

    const T& Get(size_t i) const
    {
        return m_v[i].first;
    }

    size_t GetSize() const
    {
        return m_v.size();
    }

private:
    Comparison m_c;
    vector< pair<T, size_t*> > m_v;
};
</code>```

Body:
I am using the following approach. Whenever I insert something into the heap I pass a pointer to an integer (this memory location is ownned by me, not the heap) which should contain the position of the element in the array managed by the heap. So if the sequence of elements in the heap is rearranged it is supposed to update the values pointed to by these pointers.

So for the Dijkstra algirithm I am creating a posInHeap array of sizeN.

Hopefully, the code will make it more clear.

template <typename T, class Comparison = std::less<T>> class cTrackingHeap
{
public:
    cTrackingHeap(Comparison c) : m_c(c), m_v() {}
    cTrackingHeap(const cTrackingHeap&) = delete;
    cTrackingHeap& operator=(const cTrackingHeap&) = delete;

    void DecreaseVal(size_t pos, const T& newValue)
    {
        m_v[pos].first = newValue;
        while (pos > 0)
        {
            size_t iPar = (pos - 1) / 2;
            if (newValue < m_v[iPar].first)
            {
                swap(m_v[pos], m_v[iPar]);
                *m_v[pos].second = pos;
                *m_v[iPar].second = iPar;
                pos = iPar;
            }
            else
                break;
        }
    }

    void Delete(size_t pos)
    {
        *(m_v[pos].second) = numeric_limits<size_t>::max();// indicate that the element is no longer in the heap

        m_v[pos] = m_v.back();
        m_v.resize(m_v.size() - 1);

        if (pos == m_v.size())
            return;

        *(m_v[pos].second) = pos;

        bool makingProgress = true;
        while (makingProgress)
        {
            makingProgress = false;
            size_t exchangeWith = pos;
            if (2 * pos + 1 < m_v.size() && m_c(m_v[2 * pos + 1].first, m_v[pos].first))
                exchangeWith = 2 * pos + 1;
            if (2 * pos + 2 < m_v.size() && m_c(m_v[2 * pos + 2].first, m_v[exchangeWith].first))
                exchangeWith = 2 * pos + 2;
            if (pos > 0 && m_c(m_v[pos].first, m_v[(pos - 1) / 2].first))
                exchangeWith = (pos - 1) / 2;

            if (exchangeWith != pos)
            {
                makingProgress = true;
                swap(m_v[pos], m_v[exchangeWith]);
                *m_v[pos].second = pos;
                *m_v[exchangeWith].second = exchangeWith;
                pos = exchangeWith;
            }
        }
    }

    void Insert(const T& value, size_t* posTracker)
    {
        m_v.push_back(make_pair(value, posTracker));
        *posTracker = m_v.size() - 1;

        size_t pos = m_v.size() - 1;

        bool makingProgress = true;
        while (makingProgress)
        {
            makingProgress = false;

            if (pos > 0 && m_c(m_v[pos].first, m_v[(pos - 1) / 2].first))
            {
                makingProgress = true;
                swap(m_v[pos], m_v[(pos - 1) / 2]);
                *m_v[pos].second = pos;
                *m_v[(pos - 1) / 2].second = (pos - 1) / 2;
                pos = (pos - 1) / 2;
            }
        }
    }

    const T& GetMin() const
    {
        return m_v[0].first;
    }

    const T& Get(size_t i) const
    {
        return m_v[i].first;
    }

    size_t GetSize() const
    {
        return m_v.size();
    }

private:
    Comparison m_c;
    vector< pair<T, size_t*> > m_v;
};


问:
How to Fill Nulls for Lead window using multiple criteria
I have OppTable

```<code>   ID           actualclosedate    status
--------------------------------------
    1            10-March    Won
    2            11-June     Lost
    3            13-July     Open
</code>```

I have stage change

```<code>--------------------------------------
   ID         stage       createdon
--------------------------------------
    1         Propsect    1-Jan
    1         Qualify     15-Jan
    1         Develop     25-Jan
    2         Qualify     9-Feb
    2         Develop     7-March
    3         Prospect    9-April
    3         Prospect    9-April
</code>```

How Can I fill the NULL values in the new column generated based on multiple criteria.
Ex: if Opp is WON/LOST put close date
    if Opp is Open put today date

Expected results:

```<code>--------------------------------------
   OppID      Stage       createdon   newcolumn
--------------------------------------
    1         Propsect    1-Jan        15-Jan
    1         Qualify     15-Jan       25-Jan
    1         Develop     25-Jan       10-March ---(closedate for Wonn Opp1)
    2         Qualify     9-Feb        7-March
    2         Develop     7-March      11-june  ---(closedate for lost Opp2)
    3         Prospect    9-April      10-April
    3         Qualify     10-April     4/2/2017----(todaydate for Open Opp3)
</code>```

Using this Query, will get me actual close date for open but I want Today Date

```<code>Select *
      ,NewColumn = COALESCE(Lead(A.createdon) over (Partition By A.ID Order By A.CreatedOn),B.actualclosedate)

 From  stagechange A
 Join  OppTable B on A.ID=B.ID
</code>```

答:
You can try this query:

```<code>WITH cte AS (
    SELECT a.ID, a.Stage, a.CreatedOn, b.CloseDate, b.Status,
           LEAD(a.CreatedOn) OVER (PARTITION BY a.ID ORDER BY a.CreatedOn) ld,
           ROW_NUMBER() OVER (PARTITION BY a.ID ORDER BY a.CreatedOn DESC) rn,
           DENSE_RANK() OVER (PARTITION BY a.ID ORDER BY a.CreatedOn DESC) dr
    FROM stagechange a
    INNER JOIN OppTable b
        ON a.ID = b.ID
)
SELECT t.ID, t.Stage, t.CreatedOn,
       CASE WHEN (t.rn <> 1 OR t.rn = t.dr) AND t.ld IS NOT NULL THEN t.ld
            WHEN t.Status <> 'Open' THEN t.CloseDate
            ELSE GETDATE()
        END AS newcolumn
FROM cte t
ORDER BY t.ID, t.CreatedOn;
</code>```

I found that using both ROW_NUMBER() and DENSE_RANK() was necessary to handle the edge case of where a given ID can have multiple equivalent closing dates.  In this case, we need some way of identifying which one is the oldest.

Output:

Demo here:

Rextester

Body:
I have OppTable

   ID           actualclosedate    status
--------------------------------------
    1            10-March    Won
    2            11-June     Lost
    3            13-July     Open

I have stage change

--------------------------------------
   ID         stage       createdon
--------------------------------------
    1         Propsect    1-Jan
    1         Qualify     15-Jan
    1         Develop     25-Jan
    2         Qualify     9-Feb
    2         Develop     7-March
    3         Prospect    9-April
    3         Prospect    9-April

How Can I fill the NULL values in the new column generated based on multiple criteria.
Ex: if Opp is WON/LOST put close date
    if Opp is Open put today date

Expected results:

--------------------------------------
   OppID      Stage       createdon   newcolumn
--------------------------------------
    1         Propsect    1-Jan        15-Jan
    1         Qualify     15-Jan       25-Jan
    1         Develop     25-Jan       10-March ---(closedate for Wonn Opp1)
    2         Qualify     9-Feb        7-March
    2         Develop     7-March      11-june  ---(closedate for lost Opp2)
    3         Prospect    9-April      10-April
    3         Qualify     10-April     4/2/2017----(todaydate for Open Opp3)

Using this Query, will get me actual close date for open but I want Today Date

Select *
      ,NewColumn = COALESCE(Lead(A.createdon) over (Partition By A.ID Order By A.CreatedOn),B.actualclosedate)

 From  stagechange A
 Join  OppTable B on A.ID=B.ID

Body:
You can try this query:

WITH cte AS (
    SELECT a.ID, a.Stage, a.CreatedOn, b.CloseDate, b.Status,
           LEAD(a.CreatedOn) OVER (PARTITION BY a.ID ORDER BY a.CreatedOn) ld,
           ROW_NUMBER() OVER (PARTITION BY a.ID ORDER BY a.CreatedOn DESC) rn,
           DENSE_RANK() OVER (PARTITION BY a.ID ORDER BY a.CreatedOn DESC) dr
    FROM stagechange a
    INNER JOIN OppTable b
        ON a.ID = b.ID
)
SELECT t.ID, t.Stage, t.CreatedOn,
       CASE WHEN (t.rn <> 1 OR t.rn = t.dr) AND t.ld IS NOT NULL THEN t.ld
            WHEN t.Status <> 'Open' THEN t.CloseDate
            ELSE GETDATE()
        END AS newcolumn
FROM cte t
ORDER BY t.ID, t.CreatedOn;

I found that using both ROW_NUMBER() and DENSE_RANK() was necessary to handle the edge case of where a given ID can have multiple equivalent closing dates.  In this case, we need some way of identifying which one is the oldest.

Output:

Demo here:

Rextester


问:
Is there a tool that allows to edit related code in single file?
My idea is that it's much easier to edit related code when it sits in single "work" file. E.g. in Rails application when you implementing some functionality you may edit 1 function per file in the following files: integration test, controller test, controller, model, controller helper. So if it would be possible to 1) mark this code fragments 2) automatically collect them in "work" file 3) edit them togather 4) the tool synchronizes (puts back) the changes; it could simplify development process in many cases. Especially if you need to go through many tweek-and-try iterations.</p>

答:
Vim works fine for this. Install the Rails.vim(1) plugin and with the command :AV you can open a vertical split with the accompanied tests/specs, or :RV to open related files like migrations and views (depending on whether you're viewing model or controller). When you're workspace becomes to cluttered, use :only to go back to one file. Splits are the best way to manage multiple related files IMHO. You can even open the same file twice to see two parts of the same file. It's not exactly the same as you are describing, but it comes close.

1: http://rails.vim.tpope.net/


问:
Why this jquery else if statements are not working?
Could you please take a look at this? It does not work. I can not figure out why.

$(document).ready(function() {
  var result = parseInt($('#kmi').text());
  if (result < 18, 5) {
    $("#line1").css("background-color", "#eee");
  } else if (result >= 18, 5 && result < 24, 9) {
    $("#line2").css("background-color", "#eee");
  } else if (result >= 25 && result = < 29, 9) {
    $("#line3").css("background-color", "#eee");
  } else if (result >= 30 && result = < 34.9) {
    $("#line4").css("background-color", "#eee");
  } else if (result >= 35 && result = < 39.9) {
    $("#line5").css("background-color", "#eee");
  } else if (result >= 40) {
    $("#line6").css("background-color", "#eee");
  } else {
    $("#line1").css("background-color", "#fff");
  }
}
});
```

答:
first of all you should change comma to dot and you have used  => instead of <= and don't use much else if statement you can use one class property for all lines because all CSS having same property background-color, "#eee" something like this , please check the condition for if statement </p>

```<code>$(document).ready(function(){
var result = parseInt($('#kmi').text());
if(result<18.5 || result>=40){
$(".lines").css("background-color", "#eee");
}else{
    $("#line1").css("background-color", "#fff");
}

}
});
</code>```

Body:
first of all you should change comma to dot and you have used  => instead of <= and don't use much else if statement you can use one class property for all lines because all CSS having same property background-color, "#eee" something like this , please check the condition for if statement

$(document).ready(function(){
var result = parseInt($('#kmi').text());
if(result<18.5 || result>=40){
$(".lines").css("background-color", "#eee");
}else{
    $("#line1").css("background-color", "#fff");
}

}
});


问:
The best temmplate for codeigniter
Can you tell me what's the best template for CI pls?
I'm using CI 3.x
I just want to show my html files in veiws
Thank you

答:
How to render a view (HTML) in codeigniter

Step-1

You need to set a default controller . In your application folder go to config and open routes.php. Scroll down, find the line which says default_controller change it to

```<code>$route['default_controller'] = "Controller_Name";
</code>```

Step-2

Place your HTML view file in Application -> views folder

Step-3

From your controller, create a function index and call that view

```<code>class Controller_Name extends CI_Controller
{
 public function index()
 {
    $this->load->view('_layout/index');
 }
}
</code>```

Step-4

Open your browser. Hoping that your server (xampp/wamp) is running. Type in URL
http://localhost/projectFolder/index.php/Controller_Name

OR

http://localhost/projectFolder/

Where projectFolder is the name of the folder in which you have CI installed

Title: The best temmplate for codeigniter

Body:
How to render a view (HTML) in codeigniter

Step-1

You need to set a default controller . In your application folder go to config and open routes.php. Scroll down, find the line which says default_controller change it to

$route['default_controller'] = "Controller_Name";

Step-2

Place your HTML view file in Application -> views folder

Step-3

From your controller, create a function index and call that view

class Controller_Name extends CI_Controller
{
 public function index()
 {
    $this->load->view('_layout/index');
 }
}

Step-4

Open your browser. Hoping that your server (xampp/wamp) is running. Type in URL
http://localhost/projectFolder/index.php/Controller_Name

OR

http://localhost/projectFolder/

Where projectFolder is the name of the folder in which you have CI installed


问:
Select hardcoded values in Informix DB
I need to select hardcoded values in one column, so I will be able to join them with table in Informix DB. So I try in different variations to do something like this:

```<code>select a from ( values (1), (2), (3) ) ;
</code>```

And I expect to get results:

```<code>1
2
3
</code>```

I think in other DB this or some other variations that I tried would return the values. However, in Informix it does not work.

Could anyone suggest the solution working in Informix please?

答:
Although what Gordon Linoff suggests will certainly work, there are also more compact notations available using Informix-specific syntax.

For example:

```<code>SELECT a
  FROM TABLE(SET{1, 2, 3}) AS t(a)
</code>```

This will generate a list of integers quite happily (and succinctly).  You can use LIST or MULTISET in place of SET.  A MULTISET can have repeated elements, unlike a SET; a LIST preserves order as well as allowing repeats.

Very often, you won't spot order not being preserved with simple values — just a few items in the list.  Order is not guaranteed for SET or MULTISET; if order matters, use LIST.

You can find information about this in the IBM Informix 12.10 manual under Collection Constructors.  No, it isn't obvious how you get to it — I started at SELECT, then FROM, then 'Selecting from a collection variable' and thence to 'Expression'; I spent a few seconds staring blankly at that, then looked at 'Constructor expressions' and hence 'Collection Constructors'.

Title: Select hardcoded values in Informix DB

Body:
I need to select hardcoded values in one column, so I will be able to join them with table in Informix DB. So I try in different variations to do something like this:

select a from ( values (1), (2), (3) ) ;

And I expect to get results:

1
2
3

I think in other DB this or some other variations that I tried would return the values. However, in Informix it does not work.

Could anyone suggest the solution working in Informix please?

Body:
Although what Gordon Linoff suggests will certainly work, there are also more compact notations available using Informix-specific syntax.

For example:

SELECT a
  FROM TABLE(SET{1, 2, 3}) AS t(a)

This will generate a list of integers quite happily (and succinctly).  You can use LIST or MULTISET in place of SET.  A MULTISET can have repeated elements, unlike a SET; a LIST preserves order as well as allowing repeats.

Very often, you won't spot order not being preserved with simple values — just a few items in the list.  Order is not guaranteed for SET or MULTISET; if order matters, use LIST.

You can find information about this in the IBM Informix 12.10 manual under Collection Constructors.  No, it isn't obvious how you get to it — I started at SELECT, then FROM, then 'Selecting from a collection variable' and thence to 'Expression'; I spent a few seconds staring blankly at that, then looked at 'Constructor expressions' and hence 'Collection Constructors'.


问:
How to convert likes number to percents , Flask?
I have a small problem, which is, i want to convert the number of the client likes to a percents inside the admin panel , the maximum float number is up to 5.0 so he got the 5 stars and downward tell 0.0 if no likes has been founded .

Here is my model.py:

```<code>appointment_upvotes = db.Table('appointment_upvotes',
    db.Column('appointment_id', db.Integer, db.ForeignKey('appointment.id')),
    db.Column('rate_appo_id', db.Integer, db.ForeignKey('rate_appo.id'))
)

class Appointment(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    start_time = db.Column(db.Integer(), nullable=False)
    end_time = db.Column(db.Integer(), nullable=False)
    timezone = db.Column(db.String(TIMEZONE_LEN_MAX), nullable=False)
    note = db.Column(db.String())
    status = db.Column(db.Boolean(), default=False)

    is_accepted = db.Column(db.Boolean(), default=False)
    is_not_accepted = db.Column(db.Boolean(), default=True)

    client_id = db.Column(db.Integer(), db.ForeignKey('client.id'))
    user_id = db.Column(db.Integer(), db.ForeignKey('user.id'))
    service_id = db.Column(db.Integer(), db.ForeignKey('service.id'))

    rates = db.relationship('RateAppo', backref='appointment', lazy='dynamic')

class RateAppo(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    rate_punctuality = db.Column(db.Integer(), default=0)
    rate_nonconf = db.Column(db.Integer(), default=0)
    rate_solvency = db.Column(db.Integer(), default=0)
    text = db.Column(db.Text(), default=None)

    appo_id = db.Column(db.Integer(), db.ForeignKey('appointment.id'))

    def __repr__(self):
        return "Comment: {}".format(self.text)[0:15]

    def has_voted(self, appointment_id):
        select_votes = appointment_upvotes.select(
                db.and_(
                    appointment_upvotes.c.appointment_id == appointment_id,
                    appointment_upvotes.c.rate_appo_id == self.id
                )
        )
        rs = db.engine.execute(select_votes)
        return False if rs.rowcount == 0 else True

    def vote(self, appointment_id, typevote):
        already_voted = self.has_voted(appointment_id)
        vote_status = None
        if not already_voted:
            if typevote == 'rate_punctuality':
                db.engine.execute(
                appointment_upvotes.insert(),
                    appointment_id = appointment_id,
                    rate_appo_id = self.id
                )
                self.rate_punctuality = self.rate_punctuality + 1
                vote_status = True
            elif typevote == 'rate_nonconf':
                db.engine.execute(
                appointment_upvotes.insert(),
                    appointment_id = appointment_id,
                    rate_appo_id = self.id
                )
                self.rate_nonconf = self.rate_nonconf + 1
                vote_status = True
            else:
                db.engine.execute(
                appointment_upvotes.insert(),
                    appointment_id = appointment_id,
                    rate_appo_id = self.id
                )
                self.rate_solvency = self.rate_solvency + 1
                vote_status = True
        db.session.commit()
        return vote_status
</code>```

Inside the Admin panel the rate will be looks like this for instance:

Average Rating: 4.5

doesn't matter how many likes he got, lets say he got 100 likes, i don't want to show them by count, just need to get the value up to marks 5.0

Another thing i forgot to mention, maybe inside my jinja template i can make it work ??

Here is an example :

Punctuality : 100 likes in percent maybe it will be 4.52

Solvency: 63 in percent it will be maybe 3.23

so in Punctuality there will be 4 stars, and in Solvency will be 3 stars and so on .

Last thing is to show a full statistics of all these likes in one line , for example inside my panel i will get something like this :

click me to see an example

So inside my templates i can type something like this:

```<code><div class="col-sm-8"><h2>Average Rating: <strong> {{ "%.2f" % user.rate_appo.count }} </strong></h2>
    <div class="table-responsive">
    <table class="table table-striped text-center">
      <thead>
        <tr>
          <th class="text-center">Punctuality</th>
          <th class="text-center">Non-Conflict</th>
          <th class="text-center">Solvency</th>

        </tr>
      </thead>
      <tbody>
        <tr>
          <td>{{ "%.2f" % user.rate_appo.rate_punctuality.count}} </td>
          <td>{{ "%.2f" % user.rate_appo.rate_nonconf.count}} </td>
          <td>{{ "%.2f" % user.rate_appo.rate_solvency.count}} </td>

        </tr>

      </tbody>
    </table>
</div>
</code>```

Am really not sure of what i typed above, i used the %.2f just to simplify the example to be more clear for all of you .

Eventually, its a project that am working in and please any suggestions would be tons appreciated :) .

答:
I couldn't find out which is the "count of likes" in your models, but I think your problem is "converting a number into another format in flask-Admin panel".

If so, this might help:

An example of Custom forms - flask-Admin. It converted file path into HTML tag  by using customized model view.

here is the key code:

https://github.com/flask-admin/flask-admin/blob/master/examples/forms/app.py#L110

EDIT :

Assume that there is a python function named convertLikes could convert likes number into stars number, like: convertLikes(100) will return 4.52. Then define it as a filter of jinja2, and replace your code:

```<code><td>{{ "%.2f" % user.rate_appo.rate_punctuality.count}} </td>
</code>```

with:

```<code><td>{{ user.rate_appo.rate_punctuality.count | convertLikes }} </td>
</code>```

the filter syntax will invoke convertLikes(user.rate_appo.rate_punctuality.count) and return the stars number into  tag.

For example:

Define a filter function in python:

```<code>def convertLikes(count):
    # do the convertion
    return stars_number
</code>```

Register it on the template environment:

```<code>app = Flask(__name__)
app.jinja_env.filters['convertLikes'] = convertLikes
</code>```

Use it in jinja2 template:

```<code><td>{{ user.rate_appo.rate_punctuality.count | convertLikes }} </td>
</code>```

Body:
I have a small problem, which is, i want to convert the number of the client likes to a percents inside the admin panel , the maximum float number is up to 5.0 so he got the 5 stars and downward tell 0.0 if no likes has been founded .

Here is my model.py:

appointment_upvotes = db.Table('appointment_upvotes',
    db.Column('appointment_id', db.Integer, db.ForeignKey('appointment.id')),
    db.Column('rate_appo_id', db.Integer, db.ForeignKey('rate_appo.id'))
)

class Appointment(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    start_time = db.Column(db.Integer(), nullable=False)
    end_time = db.Column(db.Integer(), nullable=False)
    timezone = db.Column(db.String(TIMEZONE_LEN_MAX), nullable=False)
    note = db.Column(db.String())
    status = db.Column(db.Boolean(), default=False)

    is_accepted = db.Column(db.Boolean(), default=False)
    is_not_accepted = db.Column(db.Boolean(), default=True)

    client_id = db.Column(db.Integer(), db.ForeignKey('client.id'))
    user_id = db.Column(db.Integer(), db.ForeignKey('user.id'))
    service_id = db.Column(db.Integer(), db.ForeignKey('service.id'))

    rates = db.relationship('RateAppo', backref='appointment', lazy='dynamic')

class RateAppo(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    rate_punctuality = db.Column(db.Integer(), default=0)
    rate_nonconf = db.Column(db.Integer(), default=0)
    rate_solvency = db.Column(db.Integer(), default=0)
    text = db.Column(db.Text(), default=None)

    appo_id = db.Column(db.Integer(), db.ForeignKey('appointment.id'))

    def __repr__(self):
        return "Comment: {}".format(self.text)[0:15]

    def has_voted(self, appointment_id):
        select_votes = appointment_upvotes.select(
                db.and_(
                    appointment_upvotes.c.appointment_id == appointment_id,
                    appointment_upvotes.c.rate_appo_id == self.id
                )
        )
        rs = db.engine.execute(select_votes)
        return False if rs.rowcount == 0 else True

    def vote(self, appointment_id, typevote):
        already_voted = self.has_voted(appointment_id)
        vote_status = None
        if not already_voted:
            if typevote == 'rate_punctuality':
                db.engine.execute(
                appointment_upvotes.insert(),
                    appointment_id = appointment_id,
                    rate_appo_id = self.id
                )
                self.rate_punctuality = self.rate_punctuality + 1
                vote_status = True
            elif typevote == 'rate_nonconf':
                db.engine.execute(
                appointment_upvotes.insert(),
                    appointment_id = appointment_id,
                    rate_appo_id = self.id
                )
                self.rate_nonconf = self.rate_nonconf + 1
                vote_status = True
            else:
                db.engine.execute(
                appointment_upvotes.insert(),
                    appointment_id = appointment_id,
                    rate_appo_id = self.id
                )
                self.rate_solvency = self.rate_solvency + 1
                vote_status = True
        db.session.commit()
        return vote_status

Inside the Admin panel the rate will be looks like this for instance:

Average Rating: 4.5

doesn't matter how many likes he got, lets say he got 100 likes, i don't want to show them by count, just need to get the value up to marks 5.0

Another thing i forgot to mention, maybe inside my jinja template i can make it work ??

Here is an example :

Punctuality : 100 likes in percent maybe it will be 4.52

Solvency: 63 in percent it will be maybe 3.23

so in Punctuality there will be 4 stars, and in Solvency will be 3 stars and so on .

Last thing is to show a full statistics of all these likes in one line , for example inside my panel i will get something like this :

click me to see an example

So inside my templates i can type something like this:

Average Rating:  {{ "%.2f" % user.rate_appo.count }}

          Punctuality
          Non-Conflict
          Solvency

          {{ "%.2f" % user.rate_appo.rate_punctuality.count}}
          {{ "%.2f" % user.rate_appo.rate_nonconf.count}}
          {{ "%.2f" % user.rate_appo.rate_solvency.count}}

Am really not sure of what i typed above, i used the %.2f just to simplify the example to be more clear for all of you .

Eventually, its a project that am working in and please any suggestions would be tons appreciated :) .

Body:
I couldn't find out which is the "count of likes" in your models, but I think your problem is "converting a number into another format in flask-Admin panel".

If so, this might help:

An example of Custom forms - flask-Admin. It converted file path into HTML tag <img> by using customized model view.

here is the key code:

https://github.com/flask-admin/flask-admin/blob/master/examples/forms/app.py#L110

EDIT :

Assume that there is a python function named convertLikes could convert likes number into stars number, like: convertLikes(100) will return 4.52. Then define it as a filter of jinja2, and replace your code:

<td>{{ "%.2f" % user.rate_appo.rate_punctuality.count}} </td>

with:

<td>{{ user.rate_appo.rate_punctuality.count | convertLikes }} </td>

the filter syntax will invoke convertLikes(user.rate_appo.rate_punctuality.count) and return the stars number into <td> tag.

For example:

Define a filter function in python:

def convertLikes(count):
    # do the convertion
    return stars_number

Register it on the template environment:

app = Flask(__name__)
app.jinja_env.filters['convertLikes'] = convertLikes

Use it in jinja2 template:

<td>{{ user.rate_appo.rate_punctuality.count | convertLikes }} </td>


问:
Convert a part of a string into upper case
I am automatically obtaining directories from an application but I can't seem to get the actual directories with the correct case of letters.

For example I get $a='C:\test\dir\log\wqerst' but the actual directory is C:\test\dir\log\WQERST.

What I want is to uppercase only wqerst so it would show C:\test\dir\log\WQERST

I've already tried using substring but I don't know how I would be able to connect it to the whole directory once it is uppercase.

答:
Windows system is not case sensitive, but if you want really this result, you can do it :</p>

```<code>$a='C:\test\dir\log\wqerst'
$parentpath=Split-Path -Path $a
$file=(Split-Path -Path $a -Leaf).ToUpper()
$result=Join-Path $parentpath $file

$result
</code>```

Body:
Windows system is not case sensitive, but if you want really this result, you can do it :

$a='C:\test\dir\log\wqerst'
$parentpath=Split-Path -Path $a
$file=(Split-Path -Path $a -Leaf).ToUpper()
$result=Join-Path $parentpath $file

$result


问:
why onInterceptTouchEvent overrides the all touch event
I have a viewpager and several fragments.I extend a ViewPager and implement a my own class.Also i implemented onInterceptTouchEvent method.Now when i swipe it doesn't work.I think onInterceptTouchEvent intercept them. How to handle this?

```<code>  package com.android.ho;

import com.sph.custom.ViewPagerWithTapGestreDetection;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class PDFActivity extends FragmentActivity implements ImageOnTapCallback,OnPageChangeListener{
    static final int ITEMS = 20;
    MyAdapter mAdapter;
    //ViewPager mPager;
    ViewPagerWithTapGestreDetection mPager;
    //ViewPager mPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_pager);
        try {
            mAdapter = new MyAdapter(getSupportFragmentManager());
            mPager = (ViewPagerWithTapGestreDetection) findViewById(R.id.pager);
            mPager.setId(5000);
            mPager.setImageOnTapCallback(this);
            mPager.setAdapter(mAdapter);
            //mPager.setOffscreenPageLimit(1);
            mPager.setOnPageChangeListener(this);

            /*
            Button button = (Button) findViewById(R.id.first);
            button.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    mPager.setCurrentItem(0);
                }
            });
            button = (Button) findViewById(R.id.last);
            button.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    mPager.setCurrentItem(ITEMS - 1);
                }
            });
            */

            mPager.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    view.getParent().requestDisallowInterceptTouchEvent(true);
                    Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");

                    return false;
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

        public static class MyAdapter extends FragmentStatePagerAdapter {
        public MyAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
        }

        @Override
        public int getCount() {
            return ITEMS;
        }

        @Override
        public Fragment getItem(int position) {

            switch (position) {
            case 0: // Fragment # 0 - This will show image
                return MyFragment.newInstance("1.pdf");
            case 1: // Fragment # 1 - This will show image
                return MyFragment.newInstance("2.pdf");
            case 2: // Fragment # 1 - This will show image
                return MyFragment.newInstance("3.pdf");
            case 3: // Fragment # 1 - This will show image
                return MyFragment.newInstance("4.pdf");
            case 4: // Fragment # 1 - This will show image
                return MyFragment.newInstance("5.pdf");
            default:// Fragment # 2-9 - Will show list
                return MyFragment.newInstance("1.pdf");
            }

        }
    }

    @Override
    public void tapDetected() {
        // TODO Auto-generated method stub
        Log.e("tapDetected", "tapDetected");
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
        // TODO Auto-generated method stub
        Log.e("onPageScrollStateChanged", "onPageScrollStateChanged");
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        // TODO Auto-generated method stub
        Log.e("onPageScrolled", "onPageScrolled");
    }

    @Override
    public void onPageSelected(int arg0) {
        // TODO Auto-generated method stub
        Log.e("onPageSelected", "onPageSelected");
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Log.e("onDestroy", "onDestroy onDestroy onDestroy");
    }

}
</code>```

This is my fragment class

```<code>package com.android.ho;

import java.io.File;
import java.io.InputStream;

import com.epapyrus.plugpdf.core.viewer.ReaderView;

import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MyFragment extends Fragment{
    public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
    public static int count = 1;

    static String file;
    TextView txt;
    ReaderView readerView;

    public static final MyFragment newInstance(String message) {
        MyFragment f = new MyFragment();
        Bundle bdl = new Bundle(1);
        bdl.putString(EXTRA_MESSAGE, message);
        f.setArguments(bdl);
        file = message;
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.myfragment_layout, container, false);
        try {

            File fl = new File(Environment.getExternalStorageDirectory(), "/pdf/2.pdf");
            readerView = (ReaderView) v.findViewById(R.id.pdfviews);
            //readerView.setOnClickListener(this);
            Log.e("readerView", fl.toString());

            v.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    view.getParent().requestDisallowInterceptTouchEvent(true);
                    Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");

                    return true;
                }
            });

            // readerView.openFile("/mnt/sdcard/pdf/1.pdf","");
            if (count > 5)
                count = 1;
            readerView.openFile("/mnt/sdcard/pdf/" + count + ".pdf", "");
            Log.e("Inside onCreateView count is ", "" + count);
            count++;

            v.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    Toast.makeText(getActivity(), "Cilcked..",Toast.LENGTH_SHORT).show();

                }
            });

            /*v.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    view.getParent().requestDisallowInterceptTouchEvent(true);
                    Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");

                    return false;
                }
            });*/

        } catch (Exception e) {
            e.printStackTrace();
        }
        return v;
    }

    @Override
    public void onDestroyView() {

        super.onDestroyView();
        // Log.d("PDFVIEW", "onDestroyView");

        try {
            if (readerView != null) {
                readerView.clear();
                // readerView.clearAllField(5);
                // readerView.destroyDrawingCache();
                // readerView.
                // readerView=null;
                // mPDFView.purgeMemory();
                // mPDFView.destroy();//added to force release memory
                // mPDFView = null;
            }
            Log.e("Fragment onDestroyView ", " onDestroyView readerView is "+readerView);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
</code>```

This is my custom viewpager class

```<code>package com.android.ho

import java.util.Calendar;
import java.util.Currency;
import java.util.Date;

import com.sph.bh.ImageOnTapCallback;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.GestureDetector.OnGestureListener;
import android.widget.Toast;

public class ViewPagerWithTapGestreDetection extends ViewPager {

    private ImageOnTapCallback imageOnTapCallback;
    private GestureDetector tapGestureDetector;
    private OnGestureListener mGestureListener;

    public ViewPagerWithTapGestreDetection(Context context) {

        super(context);
        try {
            imageOnTapCallback = null;// set if needed
            mGestureListener = new GestureListener();
            tapGestureDetector = new GestureDetector(getContext(), mGestureListener, null, true);
        } catch (Exception e) {

        }
    }

    public ViewPagerWithTapGestreDetection(Context context, AttributeSet attrs) {
        super(context, attrs);
        try {
            imageOnTapCallback = null;// set if needed
            mGestureListener = new GestureListener();
            tapGestureDetector = new GestureDetector(getContext(), mGestureListener, null, true);
        } catch (Exception e) {

        }
    }

     @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
                //Don't let any touches be passed down to the children automatically
         Log.d("onInterceptTouchEvent ", "onInterceptTouchEvent");
                return true;
         }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.d("onTouchEvent", "onTouchEvent");
        if (imageOnTapCallback != null) {
            tapGestureDetector.onTouchEvent(event);
        }

        return super.onTouchEvent(event);
    }

    public ImageOnTapCallback getImageOnTapCallback() {
        return imageOnTapCallback;
    }

    public void setImageOnTapCallback(ImageOnTapCallback imageOnTapCallback) {
        this.imageOnTapCallback = imageOnTapCallback;
    }

    public class GestureListener extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {

            Log.d("onSingleTapConfirmed", "onSingleTapConfirmed");

            if (null != imageOnTapCallback) {
                imageOnTapCallback.tapDetected();
            }

            return super.onSingleTapConfirmed(e);
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            Log.d("onDoubleTap", "onDoubleTap");
            return super.onDoubleTap(e);
        }

        @Override
        public void onLongPress(MotionEvent e) {
            Log.d("onLongPress", "onLongPress");
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            Log.d("onScroll", "onScroll");
            return super.onScroll(e1, e2, distanceX, distanceY);
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            Log.e("onFling ", "onFling");
            return super.onFling(e1, e2, velocityX, velocityY);
        }
    }
}
</code>```

答:
I think onInterceptTouchEvent intercept them.

Well, you are returning true from onInterceptTouchEvent(), which means, that as a ViewGroup you do not want any touch event to be passed to children, instead pass that touch event to onTouchEvent().

You should listen for event in onInterceptTouchEvent() return false until you see that this is such a gesture, that shouldn't be handled by children. And on that point only you should return true.

Body:
I have a viewpager and several fragments.I extend a ViewPager and implement a my own class.Also i implemented onInterceptTouchEvent method.Now when i swipe it doesn't work.I think onInterceptTouchEvent intercept them. How to handle this?

  package com.android.ho;

import com.sph.custom.ViewPagerWithTapGestreDetection;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class PDFActivity extends FragmentActivity implements ImageOnTapCallback,OnPageChangeListener{
    static final int ITEMS = 20;
    MyAdapter mAdapter;
    //ViewPager mPager;
    ViewPagerWithTapGestreDetection mPager;
    //ViewPager mPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_pager);
        try {
            mAdapter = new MyAdapter(getSupportFragmentManager());
            mPager = (ViewPagerWithTapGestreDetection) findViewById(R.id.pager);
            mPager.setId(5000);
            mPager.setImageOnTapCallback(this);
            mPager.setAdapter(mAdapter);
            //mPager.setOffscreenPageLimit(1);
            mPager.setOnPageChangeListener(this);

            /*
            Button button = (Button) findViewById(R.id.first);
            button.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    mPager.setCurrentItem(0);
                }
            });
            button = (Button) findViewById(R.id.last);
            button.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    mPager.setCurrentItem(ITEMS - 1);
                }
            });
            */

            mPager.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    view.getParent().requestDisallowInterceptTouchEvent(true);
                    Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");

                    return false;
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

        public static class MyAdapter extends FragmentStatePagerAdapter {
        public MyAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
        }

        @Override
        public int getCount() {
            return ITEMS;
        }

        @Override
        public Fragment getItem(int position) {

            switch (position) {
            case 0: // Fragment # 0 - This will show image
                return MyFragment.newInstance("1.pdf");
            case 1: // Fragment # 1 - This will show image
                return MyFragment.newInstance("2.pdf");
            case 2: // Fragment # 1 - This will show image
                return MyFragment.newInstance("3.pdf");
            case 3: // Fragment # 1 - This will show image
                return MyFragment.newInstance("4.pdf");
            case 4: // Fragment # 1 - This will show image
                return MyFragment.newInstance("5.pdf");
            default:// Fragment # 2-9 - Will show list
                return MyFragment.newInstance("1.pdf");
            }

        }
    }

    @Override
    public void tapDetected() {
        // TODO Auto-generated method stub
        Log.e("tapDetected", "tapDetected");
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
        // TODO Auto-generated method stub
        Log.e("onPageScrollStateChanged", "onPageScrollStateChanged");
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        // TODO Auto-generated method stub
        Log.e("onPageScrolled", "onPageScrolled");
    }

    @Override
    public void onPageSelected(int arg0) {
        // TODO Auto-generated method stub
        Log.e("onPageSelected", "onPageSelected");
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Log.e("onDestroy", "onDestroy onDestroy onDestroy");
    }

}

This is my fragment class

package com.android.ho;

import java.io.File;
import java.io.InputStream;

import com.epapyrus.plugpdf.core.viewer.ReaderView;

import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MyFragment extends Fragment{
    public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
    public static int count = 1;

    static String file;
    TextView txt;
    ReaderView readerView;

    public static final MyFragment newInstance(String message) {
        MyFragment f = new MyFragment();
        Bundle bdl = new Bundle(1);
        bdl.putString(EXTRA_MESSAGE, message);
        f.setArguments(bdl);
        file = message;
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.myfragment_layout, container, false);
        try {

            File fl = new File(Environment.getExternalStorageDirectory(), "/pdf/2.pdf");
            readerView = (ReaderView) v.findViewById(R.id.pdfviews);
            //readerView.setOnClickListener(this);
            Log.e("readerView", fl.toString());

            v.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    view.getParent().requestDisallowInterceptTouchEvent(true);
                    Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");

                    return true;
                }
            });

            // readerView.openFile("/mnt/sdcard/pdf/1.pdf","");
            if (count > 5)
                count = 1;
            readerView.openFile("/mnt/sdcard/pdf/" + count + ".pdf", "");
            Log.e("Inside onCreateView count is ", "" + count);
            count++;

            v.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    Toast.makeText(getActivity(), "Cilcked..",Toast.LENGTH_SHORT).show();

                }
            });

            /*v.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    view.getParent().requestDisallowInterceptTouchEvent(true);
                    Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");

                    return false;
                }
            });*/

        } catch (Exception e) {
            e.printStackTrace();
        }
        return v;
    }

    @Override
    public void onDestroyView() {

        super.onDestroyView();
        // Log.d("PDFVIEW", "onDestroyView");

        try {
            if (readerView != null) {
                readerView.clear();
                // readerView.clearAllField(5);
                // readerView.destroyDrawingCache();
                // readerView.
                // readerView=null;
                // mPDFView.purgeMemory();
                // mPDFView.destroy();//added to force release memory
                // mPDFView = null;
            }
            Log.e("Fragment onDestroyView ", " onDestroyView readerView is "+readerView);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

This is my custom viewpager class

package com.android.ho

import java.util.Calendar;
import java.util.Currency;
import java.util.Date;

import com.sph.bh.ImageOnTapCallback;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.GestureDetector.OnGestureListener;
import android.widget.Toast;

public class ViewPagerWithTapGestreDetection extends ViewPager {

    private ImageOnTapCallback imageOnTapCallback;
    private GestureDetector tapGestureDetector;
    private OnGestureListener mGestureListener;

    public ViewPagerWithTapGestreDetection(Context context) {

        super(context);
        try {
            imageOnTapCallback = null;// set if needed
            mGestureListener = new GestureListener();
            tapGestureDetector = new GestureDetector(getContext(), mGestureListener, null, true);
        } catch (Exception e) {

        }
    }

    public ViewPagerWithTapGestreDetection(Context context, AttributeSet attrs) {
        super(context, attrs);
        try {
            imageOnTapCallback = null;// set if needed
            mGestureListener = new GestureListener();
            tapGestureDetector = new GestureDetector(getContext(), mGestureListener, null, true);
        } catch (Exception e) {

        }
    }

     @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
                //Don't let any touches be passed down to the children automatically
         Log.d("onInterceptTouchEvent ", "onInterceptTouchEvent");
                return true;
         }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.d("onTouchEvent", "onTouchEvent");
        if (imageOnTapCallback != null) {
            tapGestureDetector.onTouchEvent(event);
        }

        return super.onTouchEvent(event);
    }

    public ImageOnTapCallback getImageOnTapCallback() {
        return imageOnTapCallback;
    }

    public void setImageOnTapCallback(ImageOnTapCallback imageOnTapCallback) {
        this.imageOnTapCallback = imageOnTapCallback;
    }

    public class GestureListener extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {

            Log.d("onSingleTapConfirmed", "onSingleTapConfirmed");

            if (null != imageOnTapCallback) {
                imageOnTapCallback.tapDetected();
            }

            return super.onSingleTapConfirmed(e);
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            Log.d("onDoubleTap", "onDoubleTap");
            return super.onDoubleTap(e);
        }

        @Override
        public void onLongPress(MotionEvent e) {
            Log.d("onLongPress", "onLongPress");
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            Log.d("onScroll", "onScroll");
            return super.onScroll(e1, e2, distanceX, distanceY);
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            Log.e("onFling ", "onFling");
            return super.onFling(e1, e2, velocityX, velocityY);
        }
    }
}


问:
how to distribute a java-application with libraries such as itext?
I have written an application in java. It uses iText, jXL and JAI.

How do I build a jar which contains all these libraries? Or do I have to force the user to install these too?

答: You could use an utility like jarjar to merge your classes and the other libraries into a single deployable file.</p>