问:
Delphi - OLE variant passing problem (RsLinx OPC, Group Adding working with only from constants)
We got OPC job. I cannot installed RsLinx to my Win7 (and XP mode too) because of errors, so I send my test app to the real place, and somebody testing it.

Because I don't have DLL, I cannot make Delphi interface, so I need to do OLE Calls only.

I got an interesting problem with Group Add.

I demonstrate it:

```<code>procedure TForm1.Button8Click(Sender: TObject);
var
    r, g : variant;
    s : string;
    v : variant;
    ws : WideString;
begin
    Log('Connect');
    r := CreateOleObject('RSI.OPCAutomation');
    r.Connect('RSLinx OPC Server');

    Log('Add as constant');
    g := r.OPCGroups.Add('MONKEY_C');
    Log('Name ' + g.Name);

    Log('Add as string');
    s := 'MONKEY_S';
    g := r.OPCGroups.Add(s);
    Log('Name ' + g.Name);

    Log('Add as variant');
    s := 'MONKEY_V';
    v := s;
    g := r.OPCGroups.Add(v);
    Log('Name ' + g.Name);

    Log('Add as ole variant');
    s := 'MONKEY_OV';
    v := VarAsType(s, varOleStr);
    g := r.OPCGroups.Add(v);
    Log('Name ' + g.Name);

    Log('Add as widestring');
    s := 'MONKEY_WS';
    ws := WideString(s);
    g := r.OPCGroups.Add(ws);
    Log('Name ' + g.Name);

    Log('Add as widestring var');
    s := 'MONKEY_WSV';
    ws := WideString(s);
    v := ws;
    g := r.OPCGroups.Add(v);
    Log('Name ' + g.Name);

    r := 0;

end;
</code>```

The result was:

```<code>Connect
Add as constant
Name MONKEY_C
Add as string
Name _Group0
Add as variant
Name _Group1
Add as ole variant
Name _Group2
Add as widestring
Name _Group3
Add as widestring var
Name _Group4
</code>```

So the problem that I cannot add any Group than constant defined...

I need to know HOW Delphi compile this constant to I can convert my variant value to this format.

Can anybody help me in this theme?

Thanks:
   dd

Hi!

So the problem is mysterious.
I found another errors in the pure OLE calls.

```<code>function TDDRsOPCObject.IndexOfGroup(GroupName: string): integer;
var
    ogs, g : variant;
    i : integer;
    s : string;
begin
    CheckObject;
    Result := -1;
    ogs := FObj.OPCGroups;
    s := '';
    for i := 1 to ogs.Count  do begin
        g := ogs.Item(i); // This is working
        if AnsiCompareText(g.Name, GroupName) = 0 then begin
            Result := i;
            Exit;
        end;
    end;
end;

function TDDRsOPCObject.GetGroupByName(GroupName: string): variant;
var
    idx : integer;
    ogs, g : variant;
begin
    CheckObject;
    VarClear(Result);
    idx := IndexOfGroup(GroupName);
    ogs := FObj.OPCGroups;
    if idx <> -1
        then begin
            g := ogs.Item(idx); // HERE I GOT:  The parameter is incorrect
            Result := g;
        end;
end;
</code>```

So it is interesting: the IndexOfGroup with same call is working, the GetGroupByName is not... :-(

So I determined I do not continue my fighting with windmills (Don Q).
I got TLB from a dear user that have Delphi7 (in Win7 the Delphi6 cannot produce OLE interface), and I found Kassl.

May these interfaces can help me...

Thanks:
    dd

答:
There are some issues in your code, also it would be nice to know which version of Delphi you're using, and what parameter type the Add() call use. Anyway some hints:

ws := WideString(s);

That's a wrong typecast. It won't convert your string to a WideString, it will just force the memory to be interpreted as such. Use

ws := s;

The compile will take care to call the conversion routine.

Body:
We got OPC job. I cannot installed RsLinx to my Win7 (and XP mode too) because of errors, so I send my test app to the real place, and somebody testing it.

Because I don't have DLL, I cannot make Delphi interface, so I need to do OLE Calls only.

I got an interesting problem with Group Add.

I demonstrate it:

procedure TForm1.Button8Click(Sender: TObject);
var
    r, g : variant;
    s : string;
    v : variant;
    ws : WideString;
begin
    Log('Connect');
    r := CreateOleObject('RSI.OPCAutomation');
    r.Connect('RSLinx OPC Server');

    Log('Add as constant');
    g := r.OPCGroups.Add('MONKEY_C');
    Log('Name ' + g.Name);

    Log('Add as string');
    s := 'MONKEY_S';
    g := r.OPCGroups.Add(s);
    Log('Name ' + g.Name);

    Log('Add as variant');
    s := 'MONKEY_V';
    v := s;
    g := r.OPCGroups.Add(v);
    Log('Name ' + g.Name);

    Log('Add as ole variant');
    s := 'MONKEY_OV';
    v := VarAsType(s, varOleStr);
    g := r.OPCGroups.Add(v);
    Log('Name ' + g.Name);

    Log('Add as widestring');
    s := 'MONKEY_WS';
    ws := WideString(s);
    g := r.OPCGroups.Add(ws);
    Log('Name ' + g.Name);

    Log('Add as widestring var');
    s := 'MONKEY_WSV';
    ws := WideString(s);
    v := ws;
    g := r.OPCGroups.Add(v);
    Log('Name ' + g.Name);

    r := 0;

end;

The result was:

Connect
Add as constant
Name MONKEY_C
Add as string
Name _Group0
Add as variant
Name _Group1
Add as ole variant
Name _Group2
Add as widestring
Name _Group3
Add as widestring var
Name _Group4

So the problem that I cannot add any Group than constant defined...

I need to know HOW Delphi compile this constant to I can convert my variant value to this format.

Can anybody help me in this theme?

Thanks:
   dd

Hi!

So the problem is mysterious.
I found another errors in the pure OLE calls.

function TDDRsOPCObject.IndexOfGroup(GroupName: string): integer;
var
    ogs, g : variant;
    i : integer;
    s : string;
begin
    CheckObject;
    Result := -1;
    ogs := FObj.OPCGroups;
    s := '';
    for i := 1 to ogs.Count  do begin
        g := ogs.Item(i); // This is working
        if AnsiCompareText(g.Name, GroupName) = 0 then begin
            Result := i;
            Exit;
        end;
    end;
end;

function TDDRsOPCObject.GetGroupByName(GroupName: string): variant;
var
    idx : integer;
    ogs, g : variant;
begin
    CheckObject;
    VarClear(Result);
    idx := IndexOfGroup(GroupName);
    ogs := FObj.OPCGroups;
    if idx <> -1
        then begin
            g := ogs.Item(idx); // HERE I GOT:  The parameter is incorrect
            Result := g;
        end;
end;

So it is interesting: the IndexOfGroup with same call is working, the GetGroupByName is not... :-(

So I determined I do not continue my fighting with windmills (Don Q).
I got TLB from a dear user that have Delphi7 (in Win7 the Delphi6 cannot produce OLE interface), and I found Kassl.

May these interfaces can help me...

Thanks:
    dd


来源: stackexchange

问:
TypeError: 'ShuffleSplit' object is not iterable
I am using ShuffleSplit to shuffle data, but I found there is an error

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-36-192f7c286a58> in <module>()
      1 # Fit the training data to the model using grid search
----> 2 reg = fit_model(X_train, y_train)
      3
      4 # Produce the value for 'max_depth'
      5 print "Parameter 'max_depth' is {} for the optimal model.".format(reg.get_params()['max_depth'])

<ipython-input-34-18b2799e585c> in fit_model(X, y)
     32
     33     # Fit the grid search object to the data to compute the optimal model
---> 34     grid = grid.fit(X, y)
     35
     36     # Return the optimal model after fitting the data

/Library/Python/2.7/site-packages/sklearn/grid_search.pyc in fit(self, X, y)
    827
    828         """
--> 829         return self._fit(X, y, ParameterGrid(self.param_grid))
    830
    831

/Library/Python/2.7/site-packages/sklearn/grid_search.pyc in _fit(self, X, y, parameter_iterable)
    571                                     self.fit_params, return_parameters=True,
    572                                     error_score=self.error_score)
--> 573                 for parameters in parameter_iterable
    574                 for train, test in cv)
    575

/Library/Python/2.7/site-packages/sklearn/externals/joblib/parallel.pyc in __call__(self, iterable)
    756             # was dispatched. In particular this covers the edge
    757             # case of Parallel used with an exhausted iterator.
--> 758             while self.dispatch_one_batch(iterator):
    759                 self._iterating = True
    760             else:

/Library/Python/2.7/site-packages/sklearn/externals/joblib/parallel.pyc in dispatch_one_batch(self, iterator)
    601
    602         with self._lock:
--> 603             tasks = BatchedCalls(itertools.islice(iterator, batch_size))
    604             if len(tasks) == 0:
    605                 # No more tasks available in the iterator: tell caller to stop.

/Library/Python/2.7/site-packages/sklearn/externals/joblib/parallel.pyc in __init__(self, iterator_slice)
    125
    126     def __init__(self, iterator_slice):
--> 127         self.items = list(iterator_slice)
    128         self._size = len(self.items)
    129

/Library/Python/2.7/site-packages/sklearn/grid_search.pyc in <genexpr>((parameters,))
    572                                     error_score=self.error_score)
    573                 for parameters in parameter_iterable
--> 574                 for train, test in cv)
    575
    576         # Out is a list of triplet: score, estimator, n_test_samples

TypeError: 'ShuffleSplit' object is not iterable
</code>```

And it showed the warning

/Library/Python/2.7/site-packages/sklearn/cross_validation.py:44: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.
    "This module will be removed in 0.20.", DeprecationWarning)
  /Library/Python/2.7/site-packages/sklearn/grid_search.py:43: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. This module will be removed in 0.20.
    DeprecationWarning)

The code will cause the error

```<code>from sklearn.metrics import make_scorer
from sklearn.tree import DecisionTreeRegressor
from sklearn.grid_search import GridSearchCV
</code>```

while the following not

```<code>from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import make_scorer
</code>```

The current scikit-learn version is 0.18.1.

How does this happen?

答:
While importing GridSearchCV from grid_search like this:

```<code>from sklearn.grid_search import GridSearchCV
</code>```

You must get a warning like the following:

This module was deprecated in version 0.18 in favor of the
  model_selection module into which all the refactored classes and
  functions are moved. Also note that the interface of the new CV
  iterators are different from that of this module. This module will be
  removed in 0.20.

This is self explanatory and conforms to what you are experiencing.

Solution:-
Dont use the deprecated grid_search package. Use the new model_selection.

ContentLicense: CC BY-SA 3.0

Body:
I am using ShuffleSplit to shuffle data, but I found there is an error

TypeError                                 Traceback (most recent call last)
<ipython-input-36-192f7c286a58> in <module>()
      1 # Fit the training data to the model using grid search
----> 2 reg = fit_model(X_train, y_train)
      3
      4 # Produce the value for 'max_depth'
      5 print "Parameter 'max_depth' is {} for the optimal model.".format(reg.get_params()['max_depth'])

<ipython-input-34-18b2799e585c> in fit_model(X, y)
     32
     33     # Fit the grid search object to the data to compute the optimal model
---> 34     grid = grid.fit(X, y)
     35
     36     # Return the optimal model after fitting the data

/Library/Python/2.7/site-packages/sklearn/grid_search.pyc in fit(self, X, y)
    827
    828         """
--> 829         return self._fit(X, y, ParameterGrid(self.param_grid))
    830
    831

/Library/Python/2.7/site-packages/sklearn/grid_search.pyc in _fit(self, X, y, parameter_iterable)
    571                                     self.fit_params, return_parameters=True,
    572                                     error_score=self.error_score)
--> 573                 for parameters in parameter_iterable
    574                 for train, test in cv)
    575

/Library/Python/2.7/site-packages/sklearn/externals/joblib/parallel.pyc in __call__(self, iterable)
    756             # was dispatched. In particular this covers the edge
    757             # case of Parallel used with an exhausted iterator.
--> 758             while self.dispatch_one_batch(iterator):
    759                 self._iterating = True
    760             else:

/Library/Python/2.7/site-packages/sklearn/externals/joblib/parallel.pyc in dispatch_one_batch(self, iterator)
    601
    602         with self._lock:
--> 603             tasks = BatchedCalls(itertools.islice(iterator, batch_size))
    604             if len(tasks) == 0:
    605                 # No more tasks available in the iterator: tell caller to stop.

/Library/Python/2.7/site-packages/sklearn/externals/joblib/parallel.pyc in __init__(self, iterator_slice)
    125
    126     def __init__(self, iterator_slice):
--> 127         self.items = list(iterator_slice)
    128         self._size = len(self.items)
    129

/Library/Python/2.7/site-packages/sklearn/grid_search.pyc in <genexpr>((parameters,))
    572                                     error_score=self.error_score)
    573                 for parameters in parameter_iterable
--> 574                 for train, test in cv)
    575
    576         # Out is a list of triplet: score, estimator, n_test_samples

TypeError: 'ShuffleSplit' object is not iterable

And it showed the warning

/Library/Python/2.7/site-packages/sklearn/cross_validation.py:44: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.
    "This module will be removed in 0.20.", DeprecationWarning)
  /Library/Python/2.7/site-packages/sklearn/grid_search.py:43: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. This module will be removed in 0.20.
    DeprecationWarning)

The code will cause the error

from sklearn.metrics import make_scorer
from sklearn.tree import DecisionTreeRegressor
from sklearn.grid_search import GridSearchCV

while the following not

from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import make_scorer

The current scikit-learn version is 0.18.1.

How does this happen?

Body:
While importing GridSearchCV from grid_search like this:

from sklearn.grid_search import GridSearchCV

You must get a warning like the following:

This module was deprecated in version 0.18 in favor of the
  model_selection module into which all the refactored classes and
  functions are moved. Also note that the interface of the new CV
  iterators are different from that of this module. This module will be
  removed in 0.20.

This is self explanatory and conforms to what you are experiencing.

Solution:-
Dont use the deprecated grid_search package. Use the new model_selection.


问:
Map network drive programmatically in C# on Windows 10
I followed the approache to map a network drive programmatically in the following link:
Mapping Network Drive using C#

The drive seems to be connected correctly because I can query directories and files within C#. BUT I do not see the drive on my computer.
My target is to map certain drives programmatically for my users.
I don'T want to use batch/cmd...
Is there maybe a problem with windows 10 or is this code just good for programming approaches.

Kind Regards

Use of code:

```<code>Utility.NetworkDrive.MapNetworkDrive("R", @"\\unc\path");
var dirs = Directory.GetDirectories("R:"); // got many nice directories...
Utility.NetworkDrive.DisconnectNetworkDrive("R", true);
</code>```

Full Code:

```<code>namespace Utility
{
    public class NetworkDrive
    {
        private enum ResourceScope
        {
            RESOURCE_CONNECTED = 1,
            RESOURCE_GLOBALNET,
            RESOURCE_REMEMBERED,
            RESOURCE_RECENT,
            RESOURCE_CONTEXT
        }
        private enum ResourceType
        {
            RESOURCETYPE_ANY,
            RESOURCETYPE_DISK,
            RESOURCETYPE_PRINT,
            RESOURCETYPE_RESERVED
        }
        private enum ResourceUsage
        {
            RESOURCEUSAGE_CONNECTABLE = 0x00000001,
            RESOURCEUSAGE_CONTAINER = 0x00000002,
            RESOURCEUSAGE_NOLOCALDEVICE = 0x00000004,
            RESOURCEUSAGE_SIBLING = 0x00000008,
            RESOURCEUSAGE_ATTACHED = 0x00000010
        }
        private enum ResourceDisplayType
        {
            RESOURCEDISPLAYTYPE_GENERIC,
            RESOURCEDISPLAYTYPE_DOMAIN,
            RESOURCEDISPLAYTYPE_SERVER,
            RESOURCEDISPLAYTYPE_SHARE,
            RESOURCEDISPLAYTYPE_FILE,
            RESOURCEDISPLAYTYPE_GROUP,
            RESOURCEDISPLAYTYPE_NETWORK,
            RESOURCEDISPLAYTYPE_ROOT,
            RESOURCEDISPLAYTYPE_SHAREADMIN,
            RESOURCEDISPLAYTYPE_DIRECTORY,
            RESOURCEDISPLAYTYPE_TREE,
            RESOURCEDISPLAYTYPE_NDSCONTAINER
        }
        [StructLayout(LayoutKind.Sequential)]
        private struct NETRESOURCE
        {
            public ResourceScope oResourceScope;
            public ResourceType oResourceType;
            public ResourceDisplayType oDisplayType;
            public ResourceUsage oResourceUsage;
            public string sLocalName;
            public string sRemoteName;
            public string sComments;
            public string sProvider;
        }
        [DllImport("mpr.dll")]
        private static extern int WNetAddConnection2
            (ref NETRESOURCE oNetworkResource, string sPassword,
            string sUserName, int iFlags);

        [DllImport("mpr.dll")]
        private static extern int WNetCancelConnection2
            (string sLocalName, uint iFlags, int iForce);

        public static void MapNetworkDrive(string sDriveLetter, string sNetworkPath)
        {
            //Checks if the last character is \ as this causes error on mapping a drive.
            if (sNetworkPath.Substring(sNetworkPath.Length - 1, 1) == @"\")
            {
                sNetworkPath = sNetworkPath.Substring(0, sNetworkPath.Length - 1);
            }

            NETRESOURCE oNetworkResource = new NETRESOURCE()
            {
                oResourceType = ResourceType.RESOURCETYPE_DISK,
                sLocalName = sDriveLetter + ":",
                sRemoteName = sNetworkPath
            };

            //If Drive is already mapped disconnect the current
            //mapping before adding the new mapping
            if (IsDriveMapped(sDriveLetter))
            {
                DisconnectNetworkDrive(sDriveLetter, true);
            }

            WNetAddConnection2(ref oNetworkResource, null, null, 0);
        }

        public static int DisconnectNetworkDrive(string sDriveLetter, bool bForceDisconnect)
        {
            if (bForceDisconnect)
            {
                return WNetCancelConnection2(sDriveLetter + ":", 0, 1);
            }
            else
            {
                return WNetCancelConnection2(sDriveLetter + ":", 0, 0);
            }
        }

        public static bool IsDriveMapped(string sDriveLetter)
        {
            string[] DriveList = Environment.GetLogicalDrives();
            for (int i = 0; i < DriveList.Length; i++)
            {
                if (sDriveLetter + ":\\" == DriveList[i].ToString())
                {
                    return true;
                }
            }
            return false;
        }

    }

}
</code>```

答:
Resting my laptop seemed to fix whatever problem windows had.
All three approaches below are working like a charm. My favorite one is of course the C# "only" approach.

// Approach 1
Utility.NetworkDrive.MapNetworkDrive("R", @"\\unc\path");
var dirs1 = Directory.GetDirectories("R:");
Utility.NetworkDrive.DisconnectNetworkDrive("R", true);

// Approach 2
DoProcess("net", @"use R: \\unc\path");
var dirs2 = Directory.GetDirectories("R:");
DoProcess("net", "use /D R:");

// Approach 3
DoProcess("cmd", @"/c C:\local\path\to\batch\connect.cmd");
var dirs3 = Directory.GetDirectories("R:");
DoProcess("cmd", @"/c C:\local\path\to\batch\diconnect.cmd");

public static string DoProcess(string cmd, string argv)
{
    Process p = new Process();
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.FileName = cmd;
    p.StartInfo.Arguments = $" {argv}";
    p.StartInfo.CreateNoWindow = true;
    p.Start();
    p.WaitForExit();
    string output = p.StandardOutput.ReadToEnd();
    p.Dispose();

    return output;
}
```

ContentLicense: CC BY-SA 4.0

Body:
I followed the approache to map a network drive programmatically in the following link:
Mapping Network Drive using C#

The drive seems to be connected correctly because I can query directories and files within C#. BUT I do not see the drive on my computer.
My target is to map certain drives programmatically for my users.
I don'T want to use batch/cmd...
Is there maybe a problem with windows 10 or is this code just good for programming approaches.

Kind Regards

Use of code:

Utility.NetworkDrive.MapNetworkDrive("R", @"\\unc\path");
var dirs = Directory.GetDirectories("R:"); // got many nice directories...
Utility.NetworkDrive.DisconnectNetworkDrive("R", true);

Full Code:

namespace Utility
{
    public class NetworkDrive
    {
        private enum ResourceScope
        {
            RESOURCE_CONNECTED = 1,
            RESOURCE_GLOBALNET,
            RESOURCE_REMEMBERED,
            RESOURCE_RECENT,
            RESOURCE_CONTEXT
        }
        private enum ResourceType
        {
            RESOURCETYPE_ANY,
            RESOURCETYPE_DISK,
            RESOURCETYPE_PRINT,
            RESOURCETYPE_RESERVED
        }
        private enum ResourceUsage
        {
            RESOURCEUSAGE_CONNECTABLE = 0x00000001,
            RESOURCEUSAGE_CONTAINER = 0x00000002,
            RESOURCEUSAGE_NOLOCALDEVICE = 0x00000004,
            RESOURCEUSAGE_SIBLING = 0x00000008,
            RESOURCEUSAGE_ATTACHED = 0x00000010
        }
        private enum ResourceDisplayType
        {
            RESOURCEDISPLAYTYPE_GENERIC,
            RESOURCEDISPLAYTYPE_DOMAIN,
            RESOURCEDISPLAYTYPE_SERVER,
            RESOURCEDISPLAYTYPE_SHARE,
            RESOURCEDISPLAYTYPE_FILE,
            RESOURCEDISPLAYTYPE_GROUP,
            RESOURCEDISPLAYTYPE_NETWORK,
            RESOURCEDISPLAYTYPE_ROOT,
            RESOURCEDISPLAYTYPE_SHAREADMIN,
            RESOURCEDISPLAYTYPE_DIRECTORY,
            RESOURCEDISPLAYTYPE_TREE,
            RESOURCEDISPLAYTYPE_NDSCONTAINER
        }
        [StructLayout(LayoutKind.Sequential)]
        private struct NETRESOURCE
        {
            public ResourceScope oResourceScope;
            public ResourceType oResourceType;
            public ResourceDisplayType oDisplayType;
            public ResourceUsage oResourceUsage;
            public string sLocalName;
            public string sRemoteName;
            public string sComments;
            public string sProvider;
        }
        [DllImport("mpr.dll")]
        private static extern int WNetAddConnection2
            (ref NETRESOURCE oNetworkResource, string sPassword,
            string sUserName, int iFlags);

        [DllImport("mpr.dll")]
        private static extern int WNetCancelConnection2
            (string sLocalName, uint iFlags, int iForce);

        public static void MapNetworkDrive(string sDriveLetter, string sNetworkPath)
        {
            //Checks if the last character is \ as this causes error on mapping a drive.
            if (sNetworkPath.Substring(sNetworkPath.Length - 1, 1) == @"\")
            {
                sNetworkPath = sNetworkPath.Substring(0, sNetworkPath.Length - 1);
            }

            NETRESOURCE oNetworkResource = new NETRESOURCE()
            {
                oResourceType = ResourceType.RESOURCETYPE_DISK,
                sLocalName = sDriveLetter + ":",
                sRemoteName = sNetworkPath
            };

            //If Drive is already mapped disconnect the current
            //mapping before adding the new mapping
            if (IsDriveMapped(sDriveLetter))
            {
                DisconnectNetworkDrive(sDriveLetter, true);
            }

            WNetAddConnection2(ref oNetworkResource, null, null, 0);
        }

        public static int DisconnectNetworkDrive(string sDriveLetter, bool bForceDisconnect)
        {
            if (bForceDisconnect)
            {
                return WNetCancelConnection2(sDriveLetter + ":", 0, 1);
            }
            else
            {
                return WNetCancelConnection2(sDriveLetter + ":", 0, 0);
            }
        }

        public static bool IsDriveMapped(string sDriveLetter)
        {
            string[] DriveList = Environment.GetLogicalDrives();
            for (int i = 0; i < DriveList.Length; i++)
            {
                if (sDriveLetter + ":\\" == DriveList[i].ToString())
                {
                    return true;
                }
            }
            return false;
        }

    }

}


问:
issue while printing the variable to html page
I am trying to get the first name of the user in the ajax method and trying to print it on the html page but it is not getting printed

this is my html:

```<code><div ng-app="app" ng-controller="VolController">
<div class="account-action">

<h3 style="display:inline;"><img class="img"  align="left" src="images/u11.png">
    <p style="color:white">   Welcome {{first_name}}<p></h3>
</div>
</code>```

this is my controller:

```<code>    app.controller('VolController',['$scope','$sessionStorage','$state',function($scope,$sessionStorage,$state){

    var b=sessionStorage.getItem("userid");

    var a="http://localhost:8080/volunteers/"+b;

        $.ajax({
    type:'GET',
    url:a,

    success:function(data){
     console.log(JSON.stringify(data));
    $scope.volunteer=data;
    $scope.first_name=JSON.stringify($scope.volunteer.VolunteersDTO.first_name);

    console.log(data);

    },
    error:function(data){
        alert(data);
        },
    dataType:"json",
    contentType:"application/json",
})

}]);
</code>```

Question Updated!!!!

答:
As you use $.ajax instead of native $http, you should wrap assigning into $apply:

```<code>success: function(data) {
    $scope.$apply(function(){
        $scope.volunteer = data;
        $scope.first_name = JSON.stringify($scope.volunteer.VolunteersDTO.first_name);
    });
}
</code>```

Body:
I am trying to get the first name of the user in the ajax method and trying to print it on the html page but it is not getting printed

this is my html:

   Welcome {{first_name}}

this is my controller:

    app.controller('VolController',['$scope','$sessionStorage','$state',function($scope,$sessionStorage,$state){

    var b=sessionStorage.getItem("userid");

    var a="http://localhost:8080/volunteers/"+b;

        $.ajax({
    type:'GET',
    url:a,

    success:function(data){
     console.log(JSON.stringify(data));
    $scope.volunteer=data;
    $scope.first_name=JSON.stringify($scope.volunteer.VolunteersDTO.first_name);

    console.log(data);

    },
    error:function(data){
        alert(data);
        },
    dataType:"json",
    contentType:"application/json",
})

}]);

Question Updated!!!!

Body:
As you use $.ajax instead of native $http, you should wrap assigning into $apply:

success: function(data) {
    $scope.$apply(function(){
        $scope.volunteer = data;
        $scope.first_name = JSON.stringify($scope.volunteer.VolunteersDTO.first_name);
    });
}


问:
How to return colour of point in scatterplot Python
Is there a way to obtain the colour (or a simple yes/no answer if colour is present) from the x, y coordinates of a matplotlib scatterplot?

Basically I want to give a coordinate (x, y) and know if there is a coloured circle at that position in my plot.

Any help will be appreciated.

答:
You can use get_color() e.g.

```<code>a = plt.plot(x,c, color="blue", linewidth=2.0, linestyle="-")
b = plt.plot(x,s, color="red", linewidth=2.0, linestyle="-")

print a[0].get_color()
print b[0].get_color()

>>blue
>>red
</code>```

Or you could assign the returned colors to variables to work with:

```<code>color_a = a[0].get_color()

if color_a == 'blue':
    ..do something
</code>```

Body:
You can use get_color() e.g.

a = plt.plot(x,c, color="blue", linewidth=2.0, linestyle="-")
b = plt.plot(x,s, color="red", linewidth=2.0, linestyle="-")

print a[0].get_color()
print b[0].get_color()

>>blue
>>red

Or you could assign the returned colors to variables to work with:

color_a = a[0].get_color()

if color_a == 'blue':
    ..do something


问:
Yii2 Call api method from backend controllers
I have implemented API based on advanced template following Yii Rest API documentation. And I want to call API methods from backend controllers. Is it possible to do?

Thanks

答:
A way could be this .

Assuming that you rest controller is in frontend

In your backend application config you could create an additional 'UrlManager' component name eg: urlManagerForRest

```<code>return [
  'components' => [
      'urlManager' => [
          // here is your backend URL rules
      ],
      'urlManagerForRest' => [
          'class' => 'yii\web\urlManager',
          'baseUrl' => 'http://your_path/frontend/web/index.php',
          'enablePrettyUrl' => true,
          'showScriptName' => false,
      ],

  ],
];
</code>```

Then you should invoke following to compose  URL:

```<code>Yii::$app->urlManagerFrontEnd->createUrl();
</code>```

Body:
A way could be this .

Assuming that you rest controller is in frontend

In your backend application config you could create an additional 'UrlManager' component name eg: urlManagerForRest

return [
  'components' => [
      'urlManager' => [
          // here is your backend URL rules
      ],
      'urlManagerForRest' => [
          'class' => 'yii\web\urlManager',
          'baseUrl' => 'http://your_path/frontend/web/index.php',
          'enablePrettyUrl' => true,
          'showScriptName' => false,
      ],

  ],
];

Then you should invoke following to compose  URL:

Yii::$app->urlManagerFrontEnd->createUrl();


问:
sed: replace many lines from a file with single notification
I'm looking for a solution in GNU sed, but POSIX sed is OK and awk will be OK but probably more complicated than necessary. I prefer sed for this, it should be easy but I'm stuck. Seems like a one-liner can do this, no need to create a python/bash script or anything.

my attempted solution

```<code>  sed -i '218,226140d; 218i ...REMOVED...' psql.log
</code>```

This deletes the desired rows, but the insert gets lost. If I move the insert to line 217 I get:

```<code>  sed -i '218,226140d; 217i ...REMOVED...' psql.log
</code>```

result:

```<code>  ┌────────────┬─────────────────────┬─────────────────┐
  │ col_one    │     col_two         │ column_three    │
  ├────────────┼─────────────────────┼─────────────────┤
  │ CC00CBSNRY │           553854451 │       15003.44  │
  │ CC00CBSNRY │          1334177150 │        5159.57  │
  ...REMOVED...
  │ CC6XDSQGH2 │         42385958605 │ [null]          │ (line 217 in original file)
  │ CC6XJ8YG5C │         24661013005 │ [null]          │ (line 226141 in original file)
  │ CC6XJ9HGRG │         44946564505 │ [null]          │
  │ CC6XMQW6SJ │         34496719615 │ [null]          │
  └────────────┴─────────────────────┴─────────────────┘
</code>```

I know - this should be good enough, but I'm annoyed that I can't get this simple one-liner to work right. What am I missing?

the problem

I keep the psql.log file as a reference for work I am doing developing SQL code. It's very useful to see iterations of the query and the results.

The problem is that sometimes I forget to limit the output and the query will generate 100k+ rows of results that aren't a helpful reference, and I'd like to delete them from my file, leaving a note that reminds me the query output has been excised.

It would be nice to match the pattern, say every output more than 50 rows I could squash down to just the first 5 rows and the last 5.  However, its easy for me to mark the line numbers where I've blown up the file, so I'd be happy with just using sed to delete lines N through M, and insert the message ...REMOVED... where line N was.

Here is an example log file, added notes are in parentheses. The query text can change and the number of columns can be from 1 to 100 or more:

```<code>  ...
  ********* QUERY **********
  select      *
  from        table
  where       rnk <= 3
  **************************

  ┌────────────┬─────────────────────┬─────────────────┐
  │ col_one    │     col_two         │ column_three    │
  ├────────────┼─────────────────────┼─────────────────┤
  │ CC00CBSNRY │           553854451 │       15003.44  │
  │ CC00CBSNRY │          1334177150 │        5159.57  │
  │ CC6XDSQGH2 │         42385958605 │ [null]          │ (line 217)
  │ CC6XF2SVWT │         13182280615 │ [null]          │
  (many rows)

  │ CC6XF2XWDT │           995086081 │ [null]          │
  │ CC6XFX3TL1 │         25195177405 │ [null]          │
  │ CC6XJ8YG5C │         24661013005 │ [null]          │  (line 226141)
  │ CC6XJ9HGRG │         44946564505 │ [null]          │
  │ CC6XMQW6SJ │         34496719615 │ [null]          │
  └────────────┴─────────────────────┴─────────────────┘
  (225926 rows)

  ********* QUERY **********
  /* another query begins */

  select * from table where X = 1 limit 20;

  /* well done you remembered to limit the output */
  **************************
  ...
</code>```

acceptable output

the query text should all be untouched, and the top/bottom three rows of output kept. The annotation ...REMOVED... has been added and rows 218 through 226140 have been deleted:

```<code>  ********* QUERY **********
  select      *
  from        table
  where       rnk <= 3
  **************************

  ┌────────────┬─────────────────────┬─────────────────┐
  │ col_one    │     col_two         │ column_three    │
  ├────────────┼─────────────────────┼─────────────────┤
  │ CC00CBSNRY │           553854451 │       15003.44  │
  │ CC00CBSNRY │          1334177150 │        5159.57  │
  │ CC6XDSQGH2 │         42385958605 │ [null]          │ (line 217 in original file)
  ...REMOVED...
  │ CC6XJ8YG5C │         24661013005 │ [null]          │ (line 226141 in original file)
  │ CC6XJ9HGRG │         44946564505 │ [null]          │
  │ CC6XMQW6SJ │         34496719615 │ [null]          │
  └────────────┴─────────────────────┴─────────────────┘
  (225926 rows)

  ********* QUERY **********
  (etc just like example above)
</code>```

update

the border comes from my .psqlrc with \pset border 2

therefore solutions depending on the ┌ character are fragile but OK

over time i've learned that manually flagging the line numbers is too time consuming, so the best solution needs a pattern match

答:
One in awk:</p>

```<code>$ awk '
/^  └/ {                  # at the end marker
    for(j=1;j<=6;j++)     # output from the buffer b the wanted records
        print b[j]
    for(j=(i-2);j<=i;j++)
        print b[j]
    delete b              # reset buffer
    i=0                   # and flag / counter
}
/^  ┌/ || i {             # at the start marker or when flag up
    b[++i]=$0             # gather records to buffer
    next
} 1' file                 # print records which are not between the markers
</code>```

Body:
I'm looking for a solution in GNU sed, but POSIX sed is OK and awk will be OK but probably more complicated than necessary. I prefer sed for this, it should be easy but I'm stuck. Seems like a one-liner can do this, no need to create a python/bash script or anything.

my attempted solution

  sed -i '218,226140d; 218i ...REMOVED...' psql.log

This deletes the desired rows, but the insert gets lost. If I move the insert to line 217 I get:

  sed -i '218,226140d; 217i ...REMOVED...' psql.log

result:

  ┌────────────┬─────────────────────┬─────────────────┐
  │ col_one    │     col_two         │ column_three    │
  ├────────────┼─────────────────────┼─────────────────┤
  │ CC00CBSNRY │           553854451 │       15003.44  │
  │ CC00CBSNRY │          1334177150 │        5159.57  │
  ...REMOVED...
  │ CC6XDSQGH2 │         42385958605 │ [null]          │ (line 217 in original file)
  │ CC6XJ8YG5C │         24661013005 │ [null]          │ (line 226141 in original file)
  │ CC6XJ9HGRG │         44946564505 │ [null]          │
  │ CC6XMQW6SJ │         34496719615 │ [null]          │
  └────────────┴─────────────────────┴─────────────────┘

I know - this should be good enough, but I'm annoyed that I can't get this simple one-liner to work right. What am I missing?

the problem

I keep the psql.log file as a reference for work I am doing developing SQL code. It's very useful to see iterations of the query and the results.

The problem is that sometimes I forget to limit the output and the query will generate 100k+ rows of results that aren't a helpful reference, and I'd like to delete them from my file, leaving a note that reminds me the query output has been excised.

It would be nice to match the pattern, say every output more than 50 rows I could squash down to just the first 5 rows and the last 5.  However, its easy for me to mark the line numbers where I've blown up the file, so I'd be happy with just using sed to delete lines N through M, and insert the message ...REMOVED... where line N was.

Here is an example log file, added notes are in parentheses. The query text can change and the number of columns can be from 1 to 100 or more:

  ...
  ********* QUERY **********
  select      *
  from        table
  where       rnk <= 3
  **************************

  ┌────────────┬─────────────────────┬─────────────────┐
  │ col_one    │     col_two         │ column_three    │
  ├────────────┼─────────────────────┼─────────────────┤
  │ CC00CBSNRY │           553854451 │       15003.44  │
  │ CC00CBSNRY │          1334177150 │        5159.57  │
  │ CC6XDSQGH2 │         42385958605 │ [null]          │ (line 217)
  │ CC6XF2SVWT │         13182280615 │ [null]          │
  (many rows)

  │ CC6XF2XWDT │           995086081 │ [null]          │
  │ CC6XFX3TL1 │         25195177405 │ [null]          │
  │ CC6XJ8YG5C │         24661013005 │ [null]          │  (line 226141)
  │ CC6XJ9HGRG │         44946564505 │ [null]          │
  │ CC6XMQW6SJ │         34496719615 │ [null]          │
  └────────────┴─────────────────────┴─────────────────┘
  (225926 rows)

  ********* QUERY **********
  /* another query begins */

  select * from table where X = 1 limit 20;

  /* well done you remembered to limit the output */
  **************************
  ...

acceptable output

the query text should all be untouched, and the top/bottom three rows of output kept. The annotation ...REMOVED... has been added and rows 218 through 226140 have been deleted:

  ********* QUERY **********
  select      *
  from        table
  where       rnk <= 3
  **************************

  ┌────────────┬─────────────────────┬─────────────────┐
  │ col_one    │     col_two         │ column_three    │
  ├────────────┼─────────────────────┼─────────────────┤
  │ CC00CBSNRY │           553854451 │       15003.44  │
  │ CC00CBSNRY │          1334177150 │        5159.57  │
  │ CC6XDSQGH2 │         42385958605 │ [null]          │ (line 217 in original file)
  ...REMOVED...
  │ CC6XJ8YG5C │         24661013005 │ [null]          │ (line 226141 in original file)
  │ CC6XJ9HGRG │         44946564505 │ [null]          │
  │ CC6XMQW6SJ │         34496719615 │ [null]          │
  └────────────┴─────────────────────┴─────────────────┘
  (225926 rows)

  ********* QUERY **********
  (etc just like example above)

update

the border comes from my .psqlrc with \pset border 2

therefore solutions depending on the ┌ character are fragile but OK

over time i've learned that manually flagging the line numbers is too time consuming, so the best solution needs a pattern match

Body:
One in awk:

$ awk '
/^  └/ {                  # at the end marker
    for(j=1;j<=6;j++)     # output from the buffer b the wanted records
        print b[j]
    for(j=(i-2);j<=i;j++)
        print b[j]
    delete b              # reset buffer
    i=0                   # and flag / counter
}
/^  ┌/ || i {             # at the start marker or when flag up
    b[++i]=$0             # gather records to buffer
    next
} 1' file                 # print records which are not between the markers


问:
Type mismatch vba 2d array
```<code>strData = "{""INTEREST EARNING ASSETS"", """";" & _
        """Interbank Placement"", ""goku"";" & _
        """Corporate Bonds"", ""goku"";" & _
        """Government Bonds and T-Bills"", ""goku"";" & _
        """Customer Loans"", ""cow"";" & _
        """"", ""soccer"";" & _
        """Customer Loans"", ""cow"";" & _
        """Customer Loans"", ""cow"";" & _
        """test"", 444444;" & _
        """drinks"", ""goal""}"

    varData = Evaluate(strData)

    For intCounter1 = 1 To UBound(varData, 1)
        For intCounter2 = 1 To UBound(varData, 2)
            ActiveCell.Value = varData(intCounter1, intCounter2)
            ActiveCell.Offset(0, 1).Select
        Next intCounter2
        ActiveCell.Offset(0, -2).Select
        ActiveCell.Offset(1, 0).Select
    Next intCounter1
</code>```

The above code works and it prints 2 columns of the given value. For example

```<code>INTEREST EARNING ASSETS *BLANK*
Interbank Placement      goku
Corporate bonds          goku
</code>```

and so on

However, when I add an extra line on the 3rd line in the strData like below, it says type mismatch. I really don't understand why? As a matter of fact, if I add an extra line to any lines below, it gives me the same error. Why is this happening?

```<code>strData = "{""INTEREST EARNING ASSETS"", """";" & _
            """Interbank Placement"", ""goku"";" & _
            """Interbank Placement"", ""goku"";" & _
            """Corporate Bonds"", ""goku"";" & _
            """Government Bonds and T-Bills"", ""goku"";" & _
            """Customer Loans"", ""cow"";" & _
            """"", ""soccer"";" & _
            """Customer Loans"", ""cow"";" & _
            """Customer Loans"", ""cow"";" & _
            """test"", 444444;" & _
            """drinks"", ""goal""}"
</code>```

答:
Use direct value assignment of table/array using Range().Resize(n,m).Value =

```<code>Dim varData() as Variant
ReDim varData(1 to 4, 1 to 2)

varData(1,1) = "INTEREST EARNING ASSETS"
varData(1,2) = "*BLANK*"
varData(2,1) = "Interbank Placement"
varData(2,2) = 1.2344#
varData(3,1) = "Corporate bonds"
varData(3,2) = 1.04305#
varData(4,1) = "Customer Loans"
varData(4,2) = 1.10383#

ActiveCell.Resize(4,2).Value = varData
</code>```

PS. There is never a need to use the select statement to assign values. Just pick the right cell reference and use it directly to read/write values.

Title: Type mismatch vba 2d array

Body:
strData = "{""INTEREST EARNING ASSETS"", """";" & _
        """Interbank Placement"", ""goku"";" & _
        """Corporate Bonds"", ""goku"";" & _
        """Government Bonds and T-Bills"", ""goku"";" & _
        """Customer Loans"", ""cow"";" & _
        """"", ""soccer"";" & _
        """Customer Loans"", ""cow"";" & _
        """Customer Loans"", ""cow"";" & _
        """test"", 444444;" & _
        """drinks"", ""goal""}"

    varData = Evaluate(strData)

    For intCounter1 = 1 To UBound(varData, 1)
        For intCounter2 = 1 To UBound(varData, 2)
            ActiveCell.Value = varData(intCounter1, intCounter2)
            ActiveCell.Offset(0, 1).Select
        Next intCounter2
        ActiveCell.Offset(0, -2).Select
        ActiveCell.Offset(1, 0).Select
    Next intCounter1

The above code works and it prints 2 columns of the given value. For example

INTEREST EARNING ASSETS *BLANK*
Interbank Placement      goku
Corporate bonds          goku

and so on

However, when I add an extra line on the 3rd line in the strData like below, it says type mismatch. I really don't understand why? As a matter of fact, if I add an extra line to any lines below, it gives me the same error. Why is this happening?

strData = "{""INTEREST EARNING ASSETS"", """";" & _
            """Interbank Placement"", ""goku"";" & _
            """Interbank Placement"", ""goku"";" & _
            """Corporate Bonds"", ""goku"";" & _
            """Government Bonds and T-Bills"", ""goku"";" & _
            """Customer Loans"", ""cow"";" & _
            """"", ""soccer"";" & _
            """Customer Loans"", ""cow"";" & _
            """Customer Loans"", ""cow"";" & _
            """test"", 444444;" & _
            """drinks"", ""goal""}"

Body:
Use direct value assignment of table/array using Range().Resize(n,m).Value =

Dim varData() as Variant
ReDim varData(1 to 4, 1 to 2)

varData(1,1) = "INTEREST EARNING ASSETS"
varData(1,2) = "*BLANK*"
varData(2,1) = "Interbank Placement"
varData(2,2) = 1.2344#
varData(3,1) = "Corporate bonds"
varData(3,2) = 1.04305#
varData(4,1) = "Customer Loans"
varData(4,2) = 1.10383#

ActiveCell.Resize(4,2).Value = varData

PS. There is never a need to use the select statement to assign values. Just pick the right cell reference and use it directly to read/write values.


问:
Checkboxes behave like Radiobutton
I have got 4 checkboxes ad they should act like checkboxes, but they don't.
I just can select one. Can somebody please help me with my problem?

My second question is, is it possible that they are all selected from the beginning?

Thanks!

I think i descriped my question wrong, I can click for example two checkboxes, but then nothing is shown.

Eg.: if i click green and red, then both colors should be shown.

    <input type="checkbox" id="stat1" ng-true-value="'black'" ng-model="statusblack"/>
    black

    <input type="checkbox" id="stat2" ng-true-value="'red'" ng-model="statusred"/>
    red

    <input type="checkbox" id="stat3" ng-true-value="'yellow'" ng-model="statusyellow"/>
    yellowt

    <input type="checkbox" id="stat4" ng-true-value="'green'" ng-model="statusgreen"/>
    green

            Number
            Color
            Info

            {{ co.no }}
            {{ co.color }}
            {{ co.info }}

```

答:
According to the code sample you provided,  they are acting like check boxes.
And regarding the second question you can use ng-checked="true" to check the checkbox
initially

Demo

angular.module("app",[])
.controller("ctrl",function($scope){

})

 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <div class="form-group">
    <input type="checkbox" id="stat1" ng-true-value="'black'"  ng-model="statusblack" ng-checked="true"/>
    <label for="stat1">black</label><br />
    <input type="checkbox" id="stat2" ng-true-value="'red'" ng-model="statusred" ng-checked="true"/>
    <label for="stat2">red</label><br />
    <input type="checkbox" id="stat3" ng-true-value="'yellow'" ng-model="statusyellow" ng-checked="true"/>
    <label for="stat3">yellowt</label><br />
    <input type="checkbox" id="stat4" ng-true-value="'green'" ng-model="statusgreen" ng-checked="true"/>
    <label for="stat4">green</label><br />
</div>

<table class="table table-striped">
    <thead>
        <tr>
            <th>Number</th>
            <th>Color</th>
            <th>Info</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="co in $ctrl.colors | filter:statusred | filter:statusblack | filter:statusgreen | filter:statusyellow">
            <td>{{ co.no }}</td>
            <td>{{ co.color }}</td>
            <td>{{ co.info }}</td>
        </tr>
    </tbody>
  </table>

</div></code>```

Title: Checkboxes behave like Radiobutton

Body:
According to the code sample you provided,  they are acting like check boxes.
And regarding the second question you can use ng-checked="true" to check the checkbox
initially

Demo

angular.module("app",[])
.controller("ctrl",function($scope){

})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <div class="form-group">
    <input type="checkbox" id="stat1" ng-true-value="'black'"  ng-model="statusblack" ng-checked="true"/>&nbsp;
    <label for="stat1">black</label><br />
    <input type="checkbox" id="stat2" ng-true-value="'red'" ng-model="statusred" ng-checked="true"/>&nbsp;
    <label for="stat2">red</label><br />
    <input type="checkbox" id="stat3" ng-true-value="'yellow'" ng-model="statusyellow" ng-checked="true"/>&nbsp;
    <label for="stat3">yellowt</label><br />
    <input type="checkbox" id="stat4" ng-true-value="'green'" ng-model="statusgreen" ng-checked="true"/>&nbsp;
    <label for="stat4">green</label><br />
</div>

<table class="table table-striped">
    <thead>
        <tr>
            <th>Number</th>
            <th>Color</th>
            <th>Info</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="co in $ctrl.colors | filter:statusred | filter:statusblack | filter:statusgreen | filter:statusyellow">
            <td>{{ co.no }}</td>
            <td>{{ co.color }}</td>
            <td>{{ co.info }}</td>
        </tr>
    </tbody>
  </table>

</div>


问:
checkboxes are not appearing in browser
```<code><table class="table table-striped table-bordered table-hover" id="datatable_users">
    <thead>
        <tr role="row" class="heading">
            <th class="table-checkbox" align="center" style="padding-right:0px;">
                <input type="checkbox" class="group-checkable" data-set="#sample_1 .checkboxes" id="checkAll" />
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model.NotificationRecord)
        {
            <tr>
                <td>
                    <input type="checkbox" class="checkboxes chk" value="@item.GCMRegistrationId" name="SelectedAdmissions"/>
                </td>
            </tr>
        }
    </tbody>
</table>
</code>```

jquery for above checkbox

```<code><script type="text/javascript" language="javascript">
    $('#checkAll').click(function (event) {
        if (this.checked) {
            $('.chk').each(function () {
                $('.checker span').addClass('checked');
                this.checked = true;
            });
        }
        else {
            $('.chk').each(function () {
                this.checked = false;
                $('.checker span').removeClass('checked');
            });
        }
    });
</script>
</code>```

When I am running my code in Chrome or in Mozilla, the checkboxes are not appearing but they are there: When I check in inspect element I can see that they are there but they are hidden.

How can I solve this?

答:
Thanks to all,
I gave CSS to my class and now checkboxes are appering in Chrome and  Mozilla both.enter code here

```<code> div.checker input[type=checkbox] {
        opacity: 1 !important;
        -moz-appearance: checkbox !important;
        -webkit-appearance: checkbox !important;
         width:15px;
    }
</code>```

Title: checkboxes are not appearing in browser

Body:
                <input type="checkbox" class="group-checkable" data-set="#sample_1 .checkboxes" id="checkAll" />

        @foreach (var item in Model.NotificationRecord)
        {

                    <input type="checkbox" class="checkboxes chk" value="@item.GCMRegistrationId" name="SelectedAdmissions"/>

        }

jquery for above checkbox

When I am running my code in Chrome or in Mozilla, the checkboxes are not appearing but they are there: When I check in inspect element I can see that they are there but they are hidden.

How can I solve this?

Body:
Thanks to all,
I gave CSS to my class and now checkboxes are appering in Chrome and  Mozilla both.enter code here

 div.checker input[type=checkbox] {
        opacity: 1 !important;
        -moz-appearance: checkbox !important;
        -webkit-appearance: checkbox !important;
         width:15px;
    }


问:
iPhone UIImagePickerController video mode
When using the UIImagePickerController, is there a way to specify the resolution of the captured video, or to restrict the length of the video (based on size).  I would love to be able to have the video capture at a standard lower res mode rather than 720P.</p>

答:
For iOS 3.1 or later, you can use the videoQuality property of UIImagePickerController. The values are an in the enumeration
UIImagePickerControllerQualityType which defines UIImagePickerControllerQualityType{Low|Medium|High}. The default is UIImagePickerControllerQualityTypeMedium. 4.0 and later have additional resolution options.

As for duration, the property videoMaximumDuration allows you to specify the maximum time in seconds.

ContentLicense: CC BY-SA 2.5


问:
How to display Tooltip on GridView Row Hover
I need to show a tooltip when mouse is placed on GridView Row (onmouseover)
I need to set the Tooltip content Dynamically in GridView_RowData

How can I Do this??

Can I Do this in e.Row.Attributes.Add(... ??

答:
try this</p>

```<code>    If e.Row.RowType = DataControlRowType.DataRow Then
        'your dynamic data fill to e.row.tooltip
        e.Row.ToolTip = e.Row.Cells(1).Text & "-" & e.Row.Cells(3).Text
    End If
</code>```

Body:
try this

    If e.Row.RowType = DataControlRowType.DataRow Then
        'your dynamic data fill to e.row.tooltip
        e.Row.ToolTip = e.Row.Cells(1).Text & "-" & e.Row.Cells(3).Text
    End If


问:
pySpark How to change the column names using sqlContext.sql
I run a command using sqlContext.sql
The result is a dataframe but the column names did not reflect what I am trying to represent

```<code>test=("SELECT SUBJECT_ID ,DRUG, COUNT(*), SUM(DOSE_VAL_RX) AS Dosage\
from sel_meds_pats_icustays \
GROUP BY SUBJECT_ID , DRUG ")
test_df= sqlContext.sql(tot_icustay_meds_pat_query).withColumnRenamed('_c1','count')
</code>```

The resulting Dataframe show this way... eventhough I tried to rename the columns.

```<code> [Row(SUBJECT_ID=6, DRUG=u'Syringe (IV Room)', count(1)=3, sum(CAST(DOSE_VAL_RX AS DOUBLE))=3.0), Row(SUBJECT_ID=13, DRUG=u'Potassium Chloride', count(1)=2, sum(CAST(DOSE_VAL_RX AS DOUBLE))=60.0), Row(SUBJECT_ID=36, DRUG=u'Cisatracurium Besylate', count(1)=1, sum(CAST(DOSE_VAL_RX AS DOUBLE))=100.0), Row(SUBJECT_ID=36, DRUG=u'Heparin Flush CVL  (100 units/ml)', count(1)=1, sum(CAST(DOSE_VAL_RX AS DOUBLE))=1.0), Row(SUBJECT_ID=36, DRUG=u'Lansoprazole Oral Disintegrating Tab', count(1)=1, sum(CAST(DOSE_VAL_RX AS DOUBLE))=30.0)]
</code>```

I also tried using ALIAS in the SELECT statement and it also does not show

Also how do I save this results to a csv file..

答:
You can use below mention three approach for same:-

```<code>1) sqlContext.sql("SELECT SUBJECT_ID, DRUG, COUNT(*) total_subject, SUM(DOSE_VAL_RX) dosage\
                     from sel_meds_pats_icustays \
                     GROUP BY SUBJECT_ID , DRUG ").show()

2) sqlContext.sql("SELECT SUBJECT_ID, DRUG, COUNT(*), SUM(DOSE_VAL_RX) \
                     from sel_meds_pats_icustays \
                     GROUP BY SUBJECT_ID , DRUG ").withColumnRenamed("_c0", "total_subjects").withColumnRenamed("_c1", "dosage").show()

import pyspark.sql.functions as F
3) sqlContext.sql("SELECT SUBJECT_ID, DRUG, COUNT(*), SUM(DOSE_VAL_RX) \
                     from sel_meds_pats_icustays \
                     GROUP BY SUBJECT_ID , DRUG ").select("SUBJECT_ID", "DRUG", col("_c0").alias("total_subjects"), col("_c1").alias("dosage")).show()
</code>```

Save To CSV:-

```<code># First Install This Package com.databricks.spark.csv
df.coalesce(1).write.format("com.databricks.spark.csv").option("header", "true").save("testing.csv")
</code>```

Body:
I run a command using sqlContext.sql
The result is a dataframe but the column names did not reflect what I am trying to represent

test=("SELECT SUBJECT_ID ,DRUG, COUNT(*), SUM(DOSE_VAL_RX) AS Dosage\
from sel_meds_pats_icustays \
GROUP BY SUBJECT_ID , DRUG ")
test_df= sqlContext.sql(tot_icustay_meds_pat_query).withColumnRenamed('_c1','count')

The resulting Dataframe show this way... eventhough I tried to rename the columns.

 [Row(SUBJECT_ID=6, DRUG=u'Syringe (IV Room)', count(1)=3, sum(CAST(DOSE_VAL_RX AS DOUBLE))=3.0), Row(SUBJECT_ID=13, DRUG=u'Potassium Chloride', count(1)=2, sum(CAST(DOSE_VAL_RX AS DOUBLE))=60.0), Row(SUBJECT_ID=36, DRUG=u'Cisatracurium Besylate', count(1)=1, sum(CAST(DOSE_VAL_RX AS DOUBLE))=100.0), Row(SUBJECT_ID=36, DRUG=u'Heparin Flush CVL  (100 units/ml)', count(1)=1, sum(CAST(DOSE_VAL_RX AS DOUBLE))=1.0), Row(SUBJECT_ID=36, DRUG=u'Lansoprazole Oral Disintegrating Tab', count(1)=1, sum(CAST(DOSE_VAL_RX AS DOUBLE))=30.0)]

I also tried using ALIAS in the SELECT statement and it also does not show

Also how do I save this results to a csv file..

Body:
You can use below mention three approach for same:-

1) sqlContext.sql("SELECT SUBJECT_ID, DRUG, COUNT(*) total_subject, SUM(DOSE_VAL_RX) dosage\
                     from sel_meds_pats_icustays \
                     GROUP BY SUBJECT_ID , DRUG ").show()

2) sqlContext.sql("SELECT SUBJECT_ID, DRUG, COUNT(*), SUM(DOSE_VAL_RX) \
                     from sel_meds_pats_icustays \
                     GROUP BY SUBJECT_ID , DRUG ").withColumnRenamed("_c0", "total_subjects").withColumnRenamed("_c1", "dosage").show()

import pyspark.sql.functions as F
3) sqlContext.sql("SELECT SUBJECT_ID, DRUG, COUNT(*), SUM(DOSE_VAL_RX) \
                     from sel_meds_pats_icustays \
                     GROUP BY SUBJECT_ID , DRUG ").select("SUBJECT_ID", "DRUG", col("_c0").alias("total_subjects"), col("_c1").alias("dosage")).show()

Save To CSV:-

# First Install This Package com.databricks.spark.csv
df.coalesce(1).write.format("com.databricks.spark.csv").option("header", "true").save("testing.csv")


问:
Getting the closest string match
I need a way to compare multiple strings to a test string and return the string that closely resembles it:

```<code>TEST STRING: THE BROWN FOX JUMPED OVER THE RED COW

CHOICE A   : THE RED COW JUMPED OVER THE GREEN CHICKEN
CHOICE B   : THE RED COW JUMPED OVER THE RED COW
CHOICE C   : THE RED FOX JUMPED OVER THE BROWN COW
</code>```

(If I did this correctly) The closest string to the "TEST STRING" should be "CHOICE C".  What is the easiest way to do this?

I plan on implementing this into multiple languages including VB.net, Lua, and JavaScript.  At this point, pseudo code is acceptable.  If you can provide an example for a specific language, this is appreciated too!

答:
To query a large set of text in efficient manner you can use the concept of Edit Distance/ Prefix Edit Distance.

Edit Distance ED(x,y): minimal number of transfroms to get from term x to term y

But computing ED between each term and query text is resource and time intensive. Therefore instead of calculating ED for each term first we can extract possible matching terms using a technique called Qgram Index. and then apply ED calculation on those selected terms.

An advantage of Qgram index technique is it supports for Fuzzy Search.

One possible approach to adapt QGram index is build an Inverted Index using Qgrams. In there we store all the words which consists with particular Qgram, under that Qgram.(Instead of storing full string you can use unique ID for each string). You can use Tree Map data structure in Java for this.
Following is a small example on storing of terms

col : colmbia, colombo, gancola, tacolama

Then when querying, we calculate the number of common Qgrams between query text and available terms.

```<code>Example: x = HILLARY, y = HILARI(query term)
Qgrams
$$HILLARY$$ -> $$H, $HI, HIL, ILL, LLA, LAR, ARY, RY$, Y$$
$$HILARI$$ -> $$H, $HI, HIL, ILA, LAR, ARI, RI$, I$$
number of q-grams in common = 4
</code>```

number of q-grams in common = 4.

For the terms with high number of common Qgrams, we calculate the ED/PED against the query term and then suggest the term to the end user.

you can find an implementation of this theory in following project(See "QGramIndex.java"). Feel free to ask any questions. https://github.com/Bhashitha-Gamage/City_Search

To study more about Edit Distance, Prefix Edit Distance Qgram index please watch the following video of Prof. Dr Hannah Bast https://www.youtube.com/embed/6pUg2wmGJRo (Lesson starts from 20:06)

Title: Getting the closest string match

Body:
I need a way to compare multiple strings to a test string and return the string that closely resembles it:

TEST STRING: THE BROWN FOX JUMPED OVER THE RED COW

CHOICE A   : THE RED COW JUMPED OVER THE GREEN CHICKEN
CHOICE B   : THE RED COW JUMPED OVER THE RED COW
CHOICE C   : THE RED FOX JUMPED OVER THE BROWN COW

(If I did this correctly) The closest string to the "TEST STRING" should be "CHOICE C".  What is the easiest way to do this?

I plan on implementing this into multiple languages including VB.net, Lua, and JavaScript.  At this point, pseudo code is acceptable.  If you can provide an example for a specific language, this is appreciated too!

Body:
To query a large set of text in efficient manner you can use the concept of Edit Distance/ Prefix Edit Distance.

Edit Distance ED(x,y): minimal number of transfroms to get from term x to term y

But computing ED between each term and query text is resource and time intensive. Therefore instead of calculating ED for each term first we can extract possible matching terms using a technique called Qgram Index. and then apply ED calculation on those selected terms.

An advantage of Qgram index technique is it supports for Fuzzy Search.

One possible approach to adapt QGram index is build an Inverted Index using Qgrams. In there we store all the words which consists with particular Qgram, under that Qgram.(Instead of storing full string you can use unique ID for each string). You can use Tree Map data structure in Java for this.
Following is a small example on storing of terms

col : colmbia, colombo, gancola, tacolama

Then when querying, we calculate the number of common Qgrams between query text and available terms.

Example: x = HILLARY, y = HILARI(query term)
Qgrams
$$HILLARY$$ -> $$H, $HI, HIL, ILL, LLA, LAR, ARY, RY$, Y$$
$$HILARI$$ -> $$H, $HI, HIL, ILA, LAR, ARI, RI$, I$$
number of q-grams in common = 4

number of q-grams in common = 4.

For the terms with high number of common Qgrams, we calculate the ED/PED against the query term and then suggest the term to the end user.

you can find an implementation of this theory in following project(See "QGramIndex.java"). Feel free to ask any questions. https://github.com/Bhashitha-Gamage/City_Search

To study more about Edit Distance, Prefix Edit Distance Qgram index please watch the following video of Prof. Dr Hannah Bast https://www.youtube.com/embed/6pUg2wmGJRo (Lesson starts from 20:06)


问:
How to get the all table(s) name which are used in particular stored procedure?
I have a requirement to get all the database tables name which are used in specific stored procedure?

As an example, I have one stored procedure as given below.

```<code>CREATE PROCEDURE [dbo].[my_sp_Name]
    @ID INT = NULL
AS
BEGIN

    SELECT ID, NAME, PRICE

    FROM tbl1
    INNER JOIN tbl2 ON tbl1.ProductId = tbl2.ProductId
    LEFT JOIN tbl3 ON tbl2.ProductSalesDate = tbl3.ProductSalesDate
    LEFT JOIN tbl4 ON tbl1.ProductCode = tbl4.ItemCode
END
</code>```

Expected output:

Used_Table_Name

tbl1

tbl2

tbl3

tbl4

Can any one suggest a way?

答:
Use below script to get table names in your store procedure :</p>

```<code>  SELECT DISTINCT [object_name] = SCHEMA_NAME(o.[schema_id]) + '.' + o.name
        , o.type_desc
  FROM sys.dm_sql_referenced_entities ('[dbo].[Your_procedurename]',
  'OBJECT')d
  JOIN sys.objects o ON d.referenced_id = o.[object_id]
  WHERE o.[type] IN ('U', 'V')
</code>```

Body:
I have a requirement to get all the database tables name which are used in specific stored procedure?

As an example, I have one stored procedure as given below.

CREATE PROCEDURE [dbo].[my_sp_Name]
    @ID INT = NULL
AS
BEGIN

    SELECT ID, NAME, PRICE

    FROM tbl1
    INNER JOIN tbl2 ON tbl1.ProductId = tbl2.ProductId
    LEFT JOIN tbl3 ON tbl2.ProductSalesDate = tbl3.ProductSalesDate
    LEFT JOIN tbl4 ON tbl1.ProductCode = tbl4.ItemCode
END

Expected output:

Used_Table_Name

tbl1

tbl2

tbl3

tbl4

Can any one suggest a way?

Body:
Use below script to get table names in your store procedure :

  SELECT DISTINCT [object_name] = SCHEMA_NAME(o.[schema_id]) + '.' + o.name
        , o.type_desc
  FROM sys.dm_sql_referenced_entities ('[dbo].[Your_procedurename]',
  'OBJECT')d
  JOIN sys.objects o ON d.referenced_id = o.[object_id]
  WHERE o.[type] IN ('U', 'V')


问:
Python - 3D Medical Image Registration Libraries
What are some libraries in Python that have the ability to read CT model files with extensions such as .vtk or .stl and perform 3D image registration with normal videos. I have found many softwares that have this ability but what I am looking for is not a program but a Python library such as Numpy or OpenCV, where all I need to do is import numpy or import cv2.

Made up example of what I want to do

Step 1 - Get the 3D CT model of a person's skull

Step 2 - Read the 3D CT model into Python

Step 3 - Get a normal video of a person standing still

Step 4 - Perform registration of the 3D CT skull and
person's head from the normal video

Step 5 - Display the registration output

I have found a couple of Python libraries that "seem" to do this sort of thing but they do not have enough information in the library description to be sure that this is what I want. I am also open to using multiple libraries. Is there anyone who has done something similar to this and it would be great if someone with experience with any libraries could give me some recommendations, thanks. If there aren't any, I will also consider libraries in other languages.

What I have considered so far

FW4SPL Libarary in C++

MITK Library in C++

MeVisLab Software in Python

Elastix Library in C++

SimpleElastix Library in Python

ITK Library in C++

SimpleITK Library in Python

For FW4SPL and MITK, I have been unable to successfully compile the source code due to new errors continuously occurring after debugging old errors. It seems that the occurrence of new errors will not stop occurring (I have spent a lot of time doing this and do not wish to continue anymore).

For MeVisLab, this is not a Python library such as numpy or opencv but it is a GUI which is also said to be programmable.

For Elastix, SimpleElastix, ITK and SimpleITK, they are indeed C++ and Python libraries which seem perfect but I am not sure if they provide the requirements of my application described above. Also, I am very confused about the relationship to one another.

答:
I am playing with vtk and stl files for the first time. Your question drove me curious but I am clearly not experienced. I started looking into this before the above comment. I did not realize we were off-topic, sorry. So I give you my conclusions at this point, since there were built for sharing.

1) for .vtk files
It turns out that most of the library I saw are for python 2.7 while I prefer the up to date version (3.5 for now).
For 3.5 I finally adopted the version of ‘woodscn’ that seems promising, for coding it seems to me all the required info is on  Reading a .vtk file with python

2) for .stl files
the ‘nestly’ package from 'conda-forge’ looks good, with a typical example on https://github.com/fhcrc/nestly/blob/master/examples/basic_nest/make_nest.py

then you just have to write import vtk and import nestly in the python script.

hope this helps


问:
Python printing without commas
How can I print lists without brackets and commas?

I have a list of permutations like this:

```<code>   [1, 2, 3]
   [1, 3, 2] etc..
</code>```

I want to print them like this: 1 2 3

答:
Example you have a list called names.</p>

```<code>names = ["Sam", "Peter", "James", "Julian", "Ann"]
for name in range(len(names)):
    print names[name],
</code>```

Title: Python printing without commas

Body:
How can I print lists without brackets and commas?

I have a list of permutations like this:

   [1, 2, 3]
   [1, 3, 2] etc..

I want to print them like this: 1 2 3

Body:
Example you have a list called names.

names = ["Sam", "Peter", "James", "Julian", "Ann"]
for name in range(len(names)):
    print names[name],


问:
How to pause the service while getting a incoming call and resume the service after call has ended?
My app is has a simple service, i need to pause that service when user makes or receive a call and service has to resume after call has ended.

Here is my Main Activity looks like:-

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

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

    Intent intent = new Intent(getApplicationContext(), MyService.class);
    startService(intent);

    TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    TelephonyMgr.listen(new TeleListener(),
            PhoneStateListener.LISTEN_CALL_STATE);
}

class TeleListener extends PhoneStateListener {
    public void onCallStateChanged(int state, String incomingNumber) {
        super.onCallStateChanged(state, incomingNumber);
        switch (state) {
            case TelephonyManager.CALL_STATE_IDLE:
                Toast.makeText(getApplicationContext(), "CALL_STATE_IDLE",
                        Toast.LENGTH_LONG).show();
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
                Toast.makeText(getApplicationContext(), "CALL_STATE_OFFHOOK",
                        Toast.LENGTH_LONG).show();
                break;
            case TelephonyManager.CALL_STATE_RINGING:
                Toast.makeText(getApplicationContext(), incomingNumber,
                        Toast.LENGTH_LONG).show();
                Toast.makeText(getApplicationContext(), "CALL_STATE_RINGING",
                        Toast.LENGTH_LONG).show();
                break;
            default:
                break;
        }
    }
}}
</code>```

Here is my Service class file:-

```<code>public class MyService extends Service {
private static final String TAG = "MyService";

private boolean isRunning = false;

@Override
public void onCreate() {
    Log.i(TAG, "Service onCreate");

    isRunning = true;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Log.i(TAG, "Service onStartCommand");
    new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < Integer.MAX_VALUE; i++) {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }

                if (isRunning) {
                    Log.i(TAG, "Service running");
                }
            }

            stopSelf();
        }
    }).start();

    return Service.START_STICKY;
}

@Override
public IBinder onBind(Intent arg0) {
    Log.i(TAG, "Service onBind");
    return null;
}

@Override
public void onDestroy() {

    isRunning = false;

    Log.i(TAG, "Service onDestroy");
}}
</code>```

From the TeleListener class in MainActivity i'm able to fetch the phone state. My problem is when the TelephonyManager is equal to CALL_STATE_OFFHOOK i need to pause the MyService and when the TelephonyManager is equal to CALL_STATE_IDLE i need to resume the MyService

答:
you need to use onCallStateChanged method.

put this lines in your onCreate() method,it will initialize object of TelephonyManager and will setup listener for you.

```<code>TelephonyManager tManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
ListenToPhoneState listener = new ListenToPhoneState()
tManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
</code>```

class definition of innerclass ListenToPhoneState will be looking like this,

```<code>private class ListenToPhoneState extends PhoneStateListener {

    boolean callEnded=false;
    public void onCallStateChanged(int state, String incomingNumber) {

        switch (state) {
        case TelephonyManager.CALL_STATE_IDLE:
            UTILS.Log_e("State changed: " , state+"Idle");

            if(callEnded)
            {
                //you will be here at **STEP 4**
                //you should stop service again over here
            }
              else
              {
                //you will be here at **STEP 1**
             //stop your service over here,
                //i.e. stopService (new Intent(`your_context`,`CallService.class`));
                //NOTE: `your_context` with appropriate context and `CallService.class` with appropriate class name of your service which you want to stop.

              }

            break;
        case TelephonyManager.CALL_STATE_OFFHOOK:
            UTILS.Log_e("State changed: " , state+"Offhook");
                //you will be here at **STEP 3**
             // you will be here when you cut call
            callEnded=true;
            break;
        case TelephonyManager.CALL_STATE_RINGING:
            UTILS.Log_e("State changed: " , state+"Ringing");
                //you will be here at **STEP 2**

            break;

        default:
            break;
        }
    }

}
</code>```

Explaination: While the call,your listener will go through following states,

Step 1: TelephonyManager.CALL_STATE_IDLE

initially your call state will be idle that is why the variable callEnded will have the value false.

Step 2: TelephonyManager.CALL_STATE_RINGING

now you are waiting for the receiver person to receive your call

Step 3: TelephonyManager.CALL_STATE_OFFHOOK

you cut the call

Step 4: TelephonyManager.CALL_STATE_IDLE

idle again

NOTE: If you don't want to know when the call ends and what should be done after ending the call then just remove callEnded variable and stop the service whenever you enter in the block of TelephonyManager.CALL_STATE_IDLE

I hope it will be helpful !!

Body:
My app is has a simple service, i need to pause that service when user makes or receive a call and service has to resume after call has ended.

Here is my Main Activity looks like:-

public class MainActivity extends Activity {

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

    Intent intent = new Intent(getApplicationContext(), MyService.class);
    startService(intent);

    TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    TelephonyMgr.listen(new TeleListener(),
            PhoneStateListener.LISTEN_CALL_STATE);
}

class TeleListener extends PhoneStateListener {
    public void onCallStateChanged(int state, String incomingNumber) {
        super.onCallStateChanged(state, incomingNumber);
        switch (state) {
            case TelephonyManager.CALL_STATE_IDLE:
                Toast.makeText(getApplicationContext(), "CALL_STATE_IDLE",
                        Toast.LENGTH_LONG).show();
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
                Toast.makeText(getApplicationContext(), "CALL_STATE_OFFHOOK",
                        Toast.LENGTH_LONG).show();
                break;
            case TelephonyManager.CALL_STATE_RINGING:
                Toast.makeText(getApplicationContext(), incomingNumber,
                        Toast.LENGTH_LONG).show();
                Toast.makeText(getApplicationContext(), "CALL_STATE_RINGING",
                        Toast.LENGTH_LONG).show();
                break;
            default:
                break;
        }
    }
}}

Here is my Service class file:-

public class MyService extends Service {
private static final String TAG = "MyService";

private boolean isRunning = false;

@Override
public void onCreate() {
    Log.i(TAG, "Service onCreate");

    isRunning = true;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Log.i(TAG, "Service onStartCommand");
    new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < Integer.MAX_VALUE; i++) {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }

                if (isRunning) {
                    Log.i(TAG, "Service running");
                }
            }

            stopSelf();
        }
    }).start();

    return Service.START_STICKY;
}

@Override
public IBinder onBind(Intent arg0) {
    Log.i(TAG, "Service onBind");
    return null;
}

@Override
public void onDestroy() {

    isRunning = false;

    Log.i(TAG, "Service onDestroy");
}}

From the TeleListener class in MainActivity i'm able to fetch the phone state. My problem is when the TelephonyManager is equal to CALL_STATE_OFFHOOK i need to pause the MyService and when the TelephonyManager is equal to CALL_STATE_IDLE i need to resume the MyService

Body:
you need to use onCallStateChanged method.

put this lines in your onCreate() method,it will initialize object of TelephonyManager and will setup listener for you.

TelephonyManager tManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
ListenToPhoneState listener = new ListenToPhoneState()
tManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);

class definition of innerclass ListenToPhoneState will be looking like this,

private class ListenToPhoneState extends PhoneStateListener {

    boolean callEnded=false;
    public void onCallStateChanged(int state, String incomingNumber) {

        switch (state) {
        case TelephonyManager.CALL_STATE_IDLE:
            UTILS.Log_e("State changed: " , state+"Idle");

            if(callEnded)
            {
                //you will be here at **STEP 4**
                //you should stop service again over here
            }
              else
              {
                //you will be here at **STEP 1**
             //stop your service over here,
                //i.e. stopService (new Intent(`your_context`,`CallService.class`));
                //NOTE: `your_context` with appropriate context and `CallService.class` with appropriate class name of your service which you want to stop.

              }

            break;
        case TelephonyManager.CALL_STATE_OFFHOOK:
            UTILS.Log_e("State changed: " , state+"Offhook");
                //you will be here at **STEP 3**
             // you will be here when you cut call
            callEnded=true;
            break;
        case TelephonyManager.CALL_STATE_RINGING:
            UTILS.Log_e("State changed: " , state+"Ringing");
                //you will be here at **STEP 2**

            break;

        default:
            break;
        }
    }

}

Explaination: While the call,your listener will go through following states,

Step 1: TelephonyManager.CALL_STATE_IDLE

initially your call state will be idle that is why the variable callEnded will have the value false.

Step 2: TelephonyManager.CALL_STATE_RINGING

now you are waiting for the receiver person to receive your call

Step 3: TelephonyManager.CALL_STATE_OFFHOOK

you cut the call

Step 4: TelephonyManager.CALL_STATE_IDLE

idle again

NOTE: If you don't want to know when the call ends and what should be done after ending the call then just remove callEnded variable and stop the service whenever you enter in the block of TelephonyManager.CALL_STATE_IDLE

I hope it will be helpful !!


问:
Should I use real or sample data for unit tests?
I'm writing a parser for the output of a legacy application, and since there are no specs on the file syntax I've got as many samples of these files as I could.

Now I'm writing the unit tests before implementing the parser (because there is no other sane way to do this) but I'm not sure whether I should:

use the real files produced by the application, reading from them and comparing the output with the output that I would store in json format in another file.

or create a sample string with the tokens and possibilities I want to test and a dict (this is python) with the expected output.

I'm inclined to use the second alternative because I would test only what I need to, without all the "real-world" data included on the actual files, but I'm afraid I could forget to test for one possibility or another.

What do you think?

答: Don't forget to structure the test such that you can add additional possibilities (i.e., regression tests) as they become known.</p>


答:
Below query will help you to get used database tables in stored procedure.</p>

```<code>;WITH stored_procedures AS (
    SELECT oo.name AS table_name,
    ROW_NUMBER() OVER(partition by o.name,oo.name ORDER BY o.name,oo.name) AS row
    FROM sysdepends d
    INNER JOIN sysobjects o ON o.id=d.id
    INNER JOIN sysobjects oo ON oo.id=d.depid
    WHERE o.xtype = 'P' AND o.name = 'my_sp_Name'
)
SELECT Table_name AS 'Used_Table_Name' FROM stored_procedures
WHERE row = 1
</code>```

Title: How to get the all table(s) name which are used in particular stored procedure?

Body:
Below query will help you to get used database tables in stored procedure.

;WITH stored_procedures AS (
    SELECT oo.name AS table_name,
    ROW_NUMBER() OVER(partition by o.name,oo.name ORDER BY o.name,oo.name) AS row
    FROM sysdepends d
    INNER JOIN sysobjects o ON o.id=d.id
    INNER JOIN sysobjects oo ON oo.id=d.depid
    WHERE o.xtype = 'P' AND o.name = 'my_sp_Name'
)
SELECT Table_name AS 'Used_Table_Name' FROM stored_procedures
WHERE row = 1


问:
how to restore databases in phpmyadmin after uninstallation of xampp
As my XAMPP was not working properly, I have uninstalled it from my computer. While installation, I got the warning message about whether I want to delete the htdocs folder too. As all my programs were in htdocs, I have not deleted it. But I got no warning message about the databases and as a result I have forgotten about the databases. I have no backup copy too. After uninstallation, I found that xampp contains only the folder htdocs and no databases. Is there anyway to restore the  databases? Please help. I am very anxious as there were a lot of data and tables in the databases.  </p>

答:
When you restore old mysql\data\ to new installed xamp, your newly installed xamp version must be same as old xamp version.

Then only restore data will work.


问:
How angular works in WebApi asp.net mvc
I´m working on Angular Application Asp.Net MVC and I want to know how to received parameters from view to controller:

View:

```<code><div class="input-group">
    <span class="input-group-addon">
        <i class="fa fa-key"></i>
    </span>
    <input class="form-control" type="password" ng-model="usuario.Pass" autocomplete="off" name="pass" maxlength="30" required validate-on="blur" ng-minlength="8" ng-pattern="/[0-9]+/" />
</div>

<div class="input-group">
    <span class="input-group-addon">
        <i class="fa fa-key"></i>
    </span>
    <input class="form-control" type="password" ng-model="usuario.PassConfirmacion" autocomplete="off" name="passr" maxlength="30" required validator="usuario.PassConfirmacion === usuario.Pass" validate-on="blur" ng-minlength="8" required-message="'El campo es requerido'"
        invalid-message="'Las contraseñas no coinciden'" />
</div>
</code>```

As you can see I have two input that I want to received in controller

JSController

```<code>function cambiarContrasenaCtrl($scope, notificationService, $rootScope, vcRecaptchaService, membershipService, $state, apiService, $window) {
    $scope.usuario = {};
    $scope.cambiarContrasena = cambiarContrasena;

    function cambiarContrasena() {
        $('#recovery').prop('disabled', true);
        $('.page-spinner-bar').removeClass('hide');
        membershipService.cambiarContrasena($scope.usuario, credencialCorrecta, credencialIncorrecta);
    }
</code>```

MembershipService JS:

```<code>(function (app) {
    'use strict';

    app.factory('membershipService', membershipService);

    membershipService.$inject = ['apiService', 'notificationService', '$http', '$base64', '$cookies', '$rootScope', '$localStorage', '$sessionStorage'];

    function membershipService(apiService, notificationService, $http, $base64, $cookies, $rootScope, $localStorage, $sessionStorage) {

        var service = {
            cambiarContrasena: cambiarContrasena,
        }
        var url = window.location.href.split('?Token=')[1];;

        function cambiarContrasena(usuario, completado, fallo) {
            apiService.post('/api/usuario/cambiarContrasena?token='+url, usuario,
            completado,
            fallo);
        }
</code>```

When I run application and I fill inputs the post action returns me on $scope.usuario input values

```<code>Pass:"newpass"
PassConfirmacion:"newpass"
</code>```

Now I want to know how to get these on my controller

```<code>[AllowAnonymous]
[HttpPost]
[ActionName("cambiarContrasena")]
[Route("cambiarContrasena")]
public HttpResponseMessage CambiarContrasena(HttpRequestMessage request, Guid token)
{
    return CreateHttpResponse(request, () =>
    {
        HttpResponseMessage response = null;

        if (ModelState.IsValid)
        {
            _usuarioRecuperacionService.CambiarContrasena(token);
        }
        return response;
    });
}
</code>```

How can I do it?. Regards

Note: I based my application into: this one

答:
You have to create  (POCO) model class in API.

```<code>public class UserInfo
{
 public string Pass { get; set; }
 public string PassConfirmacion { get; set; }
}
</code>```

API POST method

```<code>    [AllowAnonymous]
    [HttpPost]
    [ActionName("cambiarContrasena")]
    [Route("cambiarContrasena")]
    public HttpResponseMessage CambiarContrasena(UserInfo model, Guid token)
    {
        //here you can access properties of model
        //model.Pass
        //model.PassConfirmacion
        return CreateHttpResponse(request, () =>
        {
            HttpResponseMessage response = null;

            if (ModelState.IsValid)
            {
                _usuarioRecuperacionService.CambiarContrasena(token);
            }
            return response;
        });
    }
</code>```

Please ensure your request conentType in $http call , it should be application/json.

Title: How angular works in WebApi asp.net mvc

Body:
I´m working on Angular Application Asp.Net MVC and I want to know how to received parameters from view to controller:

View:

    <input class="form-control" type="password" ng-model="usuario.Pass" autocomplete="off" name="pass" maxlength="30" required validate-on="blur" ng-minlength="8" ng-pattern="/[0-9]+/" />

    <input class="form-control" type="password" ng-model="usuario.PassConfirmacion" autocomplete="off" name="passr" maxlength="30" required validator="usuario.PassConfirmacion === usuario.Pass" validate-on="blur" ng-minlength="8" required-message="'El campo es requerido'"
        invalid-message="'Las contraseñas no coinciden'" />

As you can see I have two input that I want to received in controller

JSController

function cambiarContrasenaCtrl($scope, notificationService, $rootScope, vcRecaptchaService, membershipService, $state, apiService, $window) {
    $scope.usuario = {};
    $scope.cambiarContrasena = cambiarContrasena;

    function cambiarContrasena() {
        $('#recovery').prop('disabled', true);
        $('.page-spinner-bar').removeClass('hide');
        membershipService.cambiarContrasena($scope.usuario, credencialCorrecta, credencialIncorrecta);
    }

MembershipService JS:

(function (app) {
    'use strict';

    app.factory('membershipService', membershipService);

    membershipService.$inject = ['apiService', 'notificationService', '$http', '$base64', '$cookies', '$rootScope', '$localStorage', '$sessionStorage'];

    function membershipService(apiService, notificationService, $http, $base64, $cookies, $rootScope, $localStorage, $sessionStorage) {

        var service = {
            cambiarContrasena: cambiarContrasena,
        }
        var url = window.location.href.split('?Token=')[1];;

        function cambiarContrasena(usuario, completado, fallo) {
            apiService.post('/api/usuario/cambiarContrasena?token='+url, usuario,
            completado,
            fallo);
        }

When I run application and I fill inputs the post action returns me on $scope.usuario input values

Pass:"newpass"
PassConfirmacion:"newpass"

Now I want to know how to get these on my controller

[AllowAnonymous]
[HttpPost]
[ActionName("cambiarContrasena")]
[Route("cambiarContrasena")]
public HttpResponseMessage CambiarContrasena(HttpRequestMessage request, Guid token)
{
    return CreateHttpResponse(request, () =>
    {
        HttpResponseMessage response = null;

        if (ModelState.IsValid)
        {
            _usuarioRecuperacionService.CambiarContrasena(token);
        }
        return response;
    });
}

How can I do it?. Regards

Note: I based my application into: this one

Body:
You have to create  (POCO) model class in API.

public class UserInfo
{
 public string Pass { get; set; }
 public string PassConfirmacion { get; set; }
}

API POST method

    [AllowAnonymous]
    [HttpPost]
    [ActionName("cambiarContrasena")]
    [Route("cambiarContrasena")]
    public HttpResponseMessage CambiarContrasena(UserInfo model, Guid token)
    {
        //here you can access properties of model
        //model.Pass
        //model.PassConfirmacion
        return CreateHttpResponse(request, () =>
        {
            HttpResponseMessage response = null;

            if (ModelState.IsValid)
            {
                _usuarioRecuperacionService.CambiarContrasena(token);
            }
            return response;
        });
    }

Please ensure your request conentType in $http call , it should be application/json.


问:
System.InvalidOperationException >> occurred in EntityFramework.dll but was not handled in user code?
I would like to ask about this problem please. this my code>

context :

```<code>public class ArchifeContext: DbContext
{
    public DbSet<Department> Departments { get; set; }
    public DbSet<Employee> Employees { get; set; }
    public DbSet<Book> Books { get; set; }
}
</code>```

Controller :

```<code>public ArchifeContext db = new ArchifeContext();

public ActionResult Index()
{
    return View(db.Books.ToList());
}
</code>```

答: This might be occurring because your database doesn't match your context, try to backup and delete old database and try again. If you don't wana do this then try to migrate changes to your database by using Enable-Migrations and Update-Database

Body:
I would like to ask about this problem please. this my code>

context :

public class ArchifeContext: DbContext
{
    public DbSet<Department> Departments { get; set; }
    public DbSet<Employee> Employees { get; set; }
    public DbSet<Book> Books { get; set; }
}

Controller :

public ArchifeContext db = new ArchifeContext();

public ActionResult Index()
{
    return View(db.Books.ToList());
}


答: Using the second solution you offer will allow you to control what is expected and what is returned, which is ideal for unit testing. When creating automated tests, it is best to avoid manual interaction as often as possible - visually scanning the results is one of those practices you should avoid when possible (assuming that's what you meant by "compare").</p>

Title: Should I use real or sample data for unit tests?

Body:
I'm writing a parser for the output of a legacy application, and since there are no specs on the file syntax I've got as many samples of these files as I could.

Now I'm writing the unit tests before implementing the parser (because there is no other sane way to do this) but I'm not sure whether I should:

use the real files produced by the application, reading from them and comparing the output with the output that I would store in json format in another file.

or create a sample string with the tokens and possibilities I want to test and a dict (this is python) with the expected output.

I'm inclined to use the second alternative because I would test only what I need to, without all the "real-world" data included on the actual files, but I'm afraid I could forget to test for one possibility or another.

What do you think?


问:
check if an item in weblist is indented or not
I have list of items in a weblist and which has both parent and child.  Child is indented to the right,  I need to retrieve values of child and parent in two different columns in a datatable.

My code goes like this:

```<code>list = qtp_getroproperty(page.weblist(), "items count", itemsCount
For n = 1 To itemsCount
  items = page.weblist(), getitem(n)
</code>```

答:
Try this</p>

```<code>if strSurname.StartsWith(" ")
</code>```

Body:
I have list of items in a weblist and which has both parent and child.  Child is indented to the right,  I need to retrieve values of child and parent in two different columns in a datatable.

My code goes like this:

list = qtp_getroproperty(page.weblist(), "items count", itemsCount
For n = 1 To itemsCount
  items = page.weblist(), getitem(n)

Body:
Try this

if strSurname.StartsWith(" ")


问:
begin() and end() for STL algorithms
I have a class whose data container is backed by an array, and I have the following implementations for begin() and end().

```<code>template <size_t size>
double * MyContainerClass<size>::begin(){
    return std::begin(mContainer);
}

template <size_t size>
double * MyContainerClass<size>::end(){
    return std::end(mContainer);
}
</code>```

In other member functions, I am attempting to use begin() and end() for STL algorithms such as std::transform and std::copy. When const objects are passed as parameters to these member functions, I encounter the error:

error: passing 'const MyContainerClass<size>' as 'this' argument discards qualifiers.

  note: in call to 'double* MyContainerClass<size>::begin() [with unsigned int size = size]'

Is this caused by incorrect begin() and end() implementations?

```<code>std::copy(begin(), end(), someOutputIterator);
</code>```

答:
Is this caused by incorrect begin() and end() implementations?

Yes, you need const versions of the functions. For example:

```<code>template <size_t size>
const double * MyContainerClass<size>::begin() const {
    return std::begin(mContainer);
}
</code>```

Title: begin() and end() for STL algorithms

Body:
I have a class whose data container is backed by an array, and I have the following implementations for begin() and end().

template <size_t size>
double * MyContainerClass<size>::begin(){
    return std::begin(mContainer);
}

template <size_t size>
double * MyContainerClass<size>::end(){
    return std::end(mContainer);
}

In other member functions, I am attempting to use begin() and end() for STL algorithms such as std::transform and std::copy. When const objects are passed as parameters to these member functions, I encounter the error:

error: passing 'const MyContainerClass<size>' as 'this' argument discards qualifiers.

  note: in call to 'double* MyContainerClass<size>::begin() [with unsigned int size = size]'

Is this caused by incorrect begin() and end() implementations?

std::copy(begin(), end(), someOutputIterator);

Body:
Is this caused by incorrect begin() and end() implementations?

Yes, you need const versions of the functions. For example:

template <size_t size>
const double * MyContainerClass<size>::begin() const {
    return std::begin(mContainer);
}


问:
on click of div Collapse all the other divs
i have 7 divs one beside the other in horizontal line.

i want to make animation when the user click on a div of them the other divs will collapse under the dive clicked.

is there any code to do it no matter what is the code that will do it?

also is the code will work if the divs in a table ?

答:
Your question with horizontal divs, and the ability to collapse with animation looks very close to accordion functionality.

I've used a jQuery plugin zAccordion to create this: https://jsfiddle.net/bc2x2e1s/3/

JS:

```<code>$(document).ready(function() {
  $("#boxes").zAccordion({
    width: 700,
    height: 310,
    tabWidth: 100,
    invert: true
  });
});
</code>```

CSS:

```<code>#boxes div {
  background-color: #fff;
  border: 1px solid #ccc;
}
</code>```

HTML:

```<code><div id="boxes">
  <div>
  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus es.
  </div>
  <div>
  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus es.
  </div>
  <div>
  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus es.
  </div>
</div>
</code>```

Body:
Your question with horizontal divs, and the ability to collapse with animation looks very close to accordion functionality.

I've used a jQuery plugin zAccordion to create this: https://jsfiddle.net/bc2x2e1s/3/

JS:

$(document).ready(function() {
  $("#boxes").zAccordion({
    width: 700,
    height: 310,
    tabWidth: 100,
    invert: true
  });
});

CSS:

#boxes div {
  background-color: #fff;
  border: 1px solid #ccc;
}

HTML:

<div id="boxes">
  <div>
  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus es.
  </div>
  <div>
  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus es.
  </div>
  <div>
  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus es.
  </div>
</div>