问:
phone call doesn't work iOS 10
```<code>NSURL *phoneNumber = [NSURL URLWithString:@"telprompt://966555551111"];
[[UIApplication sharedApplication] openURL:phoneNumber];
</code>```

I am trying to make a call I a button action but in addition to it's deprecated, it doesn't make a call

答:
OpenURL is deprecated in iOS 10

So

```<code>[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel:966555551111"] options:@{} completionHandler:^(BOOL success) {
    if (success) {
        NSLog(@"Opened url");
    }
}];
</code>```

Check with your real time device.Don't check with simulator.

Title: phone call doesn't work iOS 10

Body:
NSURL *phoneNumber = [NSURL URLWithString:@"telprompt://966555551111"];
[[UIApplication sharedApplication] openURL:phoneNumber];

I am trying to make a call I a button action but in addition to it's deprecated, it doesn't make a call

Body:
OpenURL is deprecated in iOS 10

So

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel:966555551111"] options:@{} completionHandler:^(BOOL success) {
    if (success) {
        NSLog(@"Opened url");
    }
}];

Check with your real time device.Don't check with simulator.


来源: stackexchange

问:
Can't figure out how to display output
This might sound like a simple thing for you programmers out there but i can't seem to figure it out. I'm making a program that converts Decimal Numbers into Roman Numerals. I've got the core code working but i can't seem to think how i can display the results on the screen. I would like it so that when the user types a number into a text box the result appears in another text box at the press of a button. Thanks for your time & help.

```<code><html>
<head>
  <meta charset="UTF-8">
  <script src="Main.js" type="text/javascript"></script>
  <link href="Main.css" rel="stylesheet" type="text/css"/>
</head>
<body>
        <form id="Awesome">
        <label>Input Text Here: </label><input type="text" id="txtBox">
        <br><br>
        <label>Dec to Roman #: </label><input type="text" id="Results">
        <br><br>
        <input type="button" value="Calculate" id="Execute">

        </div>
        </form>
</body>
</html>
</code>```

Javascript

```<code>function convertToRoman(num) {
var romans = {
M:  1000,
CM: 900,
D:  500,
CD: 400,
C:  100,
XC: 90,
L:  50,
XL: 40,
X:  10,
IX: 9,
V:  5,
IV: 4,
I:  1,
};

var result = '';

for (var key in romans) {
if (num >= romans[key]) {
    result += key.repeat(Math.trunc(num / romans[key]));
    num -= romans[key] * Math.trunc(num / romans[key]);
}
}

return result;

}
</code>```

答:
There are many ways to display something on the screen of a browser.  You can go low level and work against the DOM API itself, or you can use any of several higher level frameworks to make this work easier, or perhaps just more complicated.

If you are wanting to learn about the whole browser as runtime environment for an application, you might checkout the DOM.  If you want to make something with a little more sophistication, try out jQUery.  jQuery allows you to interact with the visual elements on the page at a slightly higher level.

The next level of sophistication, which is pointless if you aren't building a sophisticated application, like stackoverflow itself, would be a full application framework, such as AngularJS or Vue.  You do NOT need this approach if you are doing something simple, or even if you are wanting to learn the browser as application platform.  The high level frameworks will obscure what's really happening, and you won't learn much.

ContentLicense: CC BY-SA 3.0

Title: Can't figure out how to display output

Body:
This might sound like a simple thing for you programmers out there but i can't seem to figure it out. I'm making a program that converts Decimal Numbers into Roman Numerals. I've got the core code working but i can't seem to think how i can display the results on the screen. I would like it so that when the user types a number into a text box the result appears in another text box at the press of a button. Thanks for your time & help.

  <meta charset="UTF-8">

  <link href="Main.css" rel="stylesheet" type="text/css"/>

        <form id="Awesome">
        Input Text Here: <input type="text" id="txtBox">

        Dec to Roman #: <input type="text" id="Results">

        <input type="button" value="Calculate" id="Execute">

        </form>

Javascript

function convertToRoman(num) {
var romans = {
M:  1000,
CM: 900,
D:  500,
CD: 400,
C:  100,
XC: 90,
L:  50,
XL: 40,
X:  10,
IX: 9,
V:  5,
IV: 4,
I:  1,
};

var result = '';

for (var key in romans) {
if (num >= romans[key]) {
    result += key.repeat(Math.trunc(num / romans[key]));
    num -= romans[key] * Math.trunc(num / romans[key]);
}
}

return result;

}


问:
creating .htaccess
I am developing a project with Struts2. I use jsp for web-side. I use MySQL database for my application and I installed wamp server for it. My urls are like localhost/xxx?name.action?blablabla... instead of this I wanna redirect urls. For example instead of name.action on my url I wanna use localhost/name or something like that. Also with .htaccess I wanna send data over it as like name.action?Id=$1... for my action at Struts2 side. However I couldn't redirect the urls, I couldn't define document root properly and .htaccess file. What should I do, can you explain it step by step?

Thanks.

答:
Your configuration will depend on what brand Java EE server you’re going to use. Apache Tomcat has a very good AJP integration with Apache webserver so that’s what I will be using in this example configuration.

You write that you would like to do URL remapping in Apache. I strongly advice against it, as this will make it very hard to dynamically generate you’re URL in your application. You can better use the URL mapping features of your web framework in order to keep link generating support of that framework.

I’m not familiar with Struts, but if it does not support this basic feature I would recommend you switch to the Stripes framework or the more complex Spring MVC framework. You further write you want to use JSP, so I also recommend you use the MVC pattern all these framework support. That means you map URL's to action/controller objects and never directly to JSP files.

Below is an example .htaccess configuration that will pass all incoming URL's that end on .action to your Java EE server. The URL's are passed through exactly the same as the requested URL including their (optional) parameters. Make sure that port 8009 is the AJP listener port of your Java EE server (or else change it to the port you have configured).

```<code># Example .htaccess
#
# Please make sure 8009 is the port number of your Java EE server
RewriteEngine On
RewriteBase /

RewriteRule ^(.*\.action)$ ajp://127.0.0.1:8009/$1 [P,QSA,L]
</code>```

Also make sure you have configured Apache correctly. For example you need to have configured the correct modules, these are the ones I have enabled (although you might not need all them):

```<code>LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule rewrite_module modules/mod_rewrite.so
</code>```

Title: creating .htaccess

Body:
Your configuration will depend on what brand Java EE server you’re going to use. Apache Tomcat has a very good AJP integration with Apache webserver so that’s what I will be using in this example configuration.

You write that you would like to do URL remapping in Apache. I strongly advice against it, as this will make it very hard to dynamically generate you’re URL in your application. You can better use the URL mapping features of your web framework in order to keep link generating support of that framework.

I’m not familiar with Struts, but if it does not support this basic feature I would recommend you switch to the Stripes framework or the more complex Spring MVC framework. You further write you want to use JSP, so I also recommend you use the MVC pattern all these framework support. That means you map URL's to action/controller objects and never directly to JSP files.

Below is an example .htaccess configuration that will pass all incoming URL's that end on .action to your Java EE server. The URL's are passed through exactly the same as the requested URL including their (optional) parameters. Make sure that port 8009 is the AJP listener port of your Java EE server (or else change it to the port you have configured).

# Example .htaccess
#
# Please make sure 8009 is the port number of your Java EE server
RewriteEngine On
RewriteBase /

RewriteRule ^(.*\.action)$ ajp://127.0.0.1:8009/$1 [P,QSA,L]

Also make sure you have configured Apache correctly. For example you need to have configured the correct modules, these are the ones I have enabled (although you might not need all them):

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule rewrite_module modules/mod_rewrite.so

ContentLicense: CC BY-SA 2.5


问:
CodeIgniter / Ajax . Posting parameters through ajax to CodeIgniter controller
I am trying to post some variables to CodeIgniter controller function through ajax but ts resulting in an error message .

This is my javascript function

```<code>$(document).ready(function()
 {

    $('.add_cart').click(function(){
      var quantity = $('#qty').val();
      var product_id = $(this).data("productid");
      var product_name = $(this).data("productname");
      var product_price = $(this).data("price");

      if(quantity != '' && quantity > 0)
          {
           $.ajax({
            url:"<?php echo base_url(); ?>products/add_product_to_cart",
            method:"POST",
            data:{product_id:product_id, product_name:product_name, product_price:product_price, quantity:quantity},
            success:function(data)
            {
                alert('success');
            }
           });
          }
          else
          {
           alert("Please Enter quantity");
          }

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

Here is my controller function.

```<code>    public function add_product_to_cart()
{

    echo $_POST["product_id"];

}
</code>```

But when i track the whole process through firebug .Its giving the error that undefined variable product_id or does not print any thing when i try to echo it as given below.

Here is the screen shot.

Can somebody help me about how to do this right or is there any special file that you need to include for ajax functions?

答:
Using Codeigniter (version 2 or 3), you should use the following:

```<code>$product_id = $this->input->post('product_id');
</code>```

Here is the documentation when using inputs in Codeigniter:

Using Codeigniter  Inputs

Ajax Request (Debugging):

If you are running an ajax call, on Chrome go to Inspector and look at the ajax requests being sent, this can show you the values that have been sent to the server. (right click on mouse)

```<code>Inspect -> Network (toggle on XHR)
</code>```

Then use your form to submit an ajax request, and a new item should show on the table in the network tab, click it, go to headers, and scroll down. It will show you all the information you need with your ajax request, and making sure they are being properly sent.

UPDATE:

As Kelvin pointed out, you need to update your ajax from method to type on the request.

method:"POST" to type:"POST"

Body:
I am trying to post some variables to CodeIgniter controller function through ajax but ts resulting in an error message .

This is my javascript function

$(document).ready(function()
 {

    $('.add_cart').click(function(){
      var quantity = $('#qty').val();
      var product_id = $(this).data("productid");
      var product_name = $(this).data("productname");
      var product_price = $(this).data("price");

      if(quantity != '' && quantity > 0)
          {
           $.ajax({
            url:"<?php echo base_url(); ?>products/add_product_to_cart",
            method:"POST",
            data:{product_id:product_id, product_name:product_name, product_price:product_price, quantity:quantity},
            success:function(data)
            {
                alert('success');
            }
           });
          }
          else
          {
           alert("Please Enter quantity");
          }

        });
      });

Here is my controller function.

    public function add_product_to_cart()
{

    echo $_POST["product_id"];

}

But when i track the whole process through firebug .Its giving the error that undefined variable product_id or does not print any thing when i try to echo it as given below.

Here is the screen shot.

Can somebody help me about how to do this right or is there any special file that you need to include for ajax functions?

Body:
Using Codeigniter (version 2 or 3), you should use the following:

$product_id = $this->input->post('product_id');

Here is the documentation when using inputs in Codeigniter:

Using Codeigniter  Inputs

Ajax Request (Debugging):

If you are running an ajax call, on Chrome go to Inspector and look at the ajax requests being sent, this can show you the values that have been sent to the server. (right click on mouse)

Inspect -> Network (toggle on XHR)

Then use your form to submit an ajax request, and a new item should show on the table in the network tab, click it, go to headers, and scroll down. It will show you all the information you need with your ajax request, and making sure they are being properly sent.

UPDATE:

As Kelvin pointed out, you need to update your ajax from method to type on the request.

method:"POST" to type:"POST"


问:
How to programatically process the image to black and white and separate out the polygon
I have an image that represents a polygon.

I want to process it in matlab and generate the image below.

Basically i am asking to separate the polygon from the rest of the image out.  This question got inspired here.

答:
We only interested in the red pixels we can use the first channel(Red) to extract coordinates centroid of each scaled pixel. Since there may be slight differences between the same coordinates we can use third output of the uniquetol function to convert absolute coordinates to relative coordinates then use accumarray to convert coordinates to a binary image.

```<code>[a,m]=imread('KfXkR.png');                             %read the indexed image
rgb = ind2rgb(a,m);                                    %convert it to rgb
region = rgb(:,:,1)>.5;                                %extract red cannel convert to binary to contrast red pixels
cen = regionprops(region,'Centroid');                  %find absolute coordinates of centeroid of each pixel
colrow = reshape([cen.Centroid],2,[]);                 %reformat/reshape
[~,~,col] = uniquetol(colrow(1,:),0.1,'DataScale',1);  %convert absolute coordinated to relative coordinates correcting possible slight variations
[~,~,row] = uniquetol(colrow(2,:),0.1,'DataScale',1);
result = accumarray([row col],1);                      %make the binary image from coordinates of pixels
imwrite(result,'result.png')
</code>```

Scaled result:

Unscaled:

Body:
We only interested in the red pixels we can use the first channel(Red) to extract coordinates centroid of each scaled pixel. Since there may be slight differences between the same coordinates we can use third output of the uniquetol function to convert absolute coordinates to relative coordinates then use accumarray to convert coordinates to a binary image.

[a,m]=imread('KfXkR.png');                             %read the indexed image
rgb = ind2rgb(a,m);                                    %convert it to rgb
region = rgb(:,:,1)>.5;                                %extract red cannel convert to binary to contrast red pixels
cen = regionprops(region,'Centroid');                  %find absolute coordinates of centeroid of each pixel
colrow = reshape([cen.Centroid],2,[]);                 %reformat/reshape
[~,~,col] = uniquetol(colrow(1,:),0.1,'DataScale',1);  %convert absolute coordinated to relative coordinates correcting possible slight variations
[~,~,row] = uniquetol(colrow(2,:),0.1,'DataScale',1);
result = accumarray([row col],1);                      %make the binary image from coordinates of pixels
imwrite(result,'result.png')

Scaled result:

Unscaled:


问:
How to quickly zero out an array?
I am currently doing it in a for loop, and I know in C there is the ZeroMemory API, however that doesn't seem to be available in C#. Nor does the somewhat equivalent Array.fill from Java exist either. I am just wondering if there is an easier/faster way?</p>

答:
Calling the method by using dll import.Its fast and easy to use :)

```<code> [DllImport("msvcrt.dll", EntryPoint = "memset", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
 public static extern IntPtr MemSet(IntPtr dest, int c, int byteCount);
</code>```

c is the value you want to set in the memory

OR

```<code>[DllImport("kernel32.dll", EntryPoint="RtlZeroMemory")]
public unsafe static extern bool ZeroMemory(byte* destination, int length);
</code>```

this only sets the given array to zero

Title: How to quickly zero out an array?

Body:
Calling the method by using dll import.Its fast and easy to use :)

 [DllImport("msvcrt.dll", EntryPoint = "memset", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
 public static extern IntPtr MemSet(IntPtr dest, int c, int byteCount);

c is the value you want to set in the memory

OR

[DllImport("kernel32.dll", EntryPoint="RtlZeroMemory")]
public unsafe static extern bool ZeroMemory(byte* destination, int length);

this only sets the given array to zero


问:
spring data sort by map-value within a given key
I would like to sort a Map of  by the value. For example I have Person class which has a map of details that are stored in a map with key-value Map<String, String>.

I am using springboot with hibernate5. This is the mapping.

```<code>public class Person implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @DocumentId
    @Column(name = "personid")
    private Integer id;

    @Column(name = "name")
    private String name;

    // this is a collection of person details
    @ElementCollection()
    @MapKeyColumn(name = "detailkey")
    @Column(name = "detailvalue")
    @CollectionTable(name = "details", joinColumns = @JoinColumn(name = "personid"))
    Map<String, String> details = new HashMap<>();

    //getter and setters omitted
</code>```

So far I am able to retrieve a person with some specific detailskey and specific detail value. So for example a person table in the DB has eyecolor as detail attribute and as value can have "green", "blue", "brown". Note this is not a real example, just for clarity purposes.

So for example I can get the list of persons and sort them by their name, in the controller I can do

```<code>Sort sort = new Sort(Sort.Direction.ASC, "name");
</code>```

and the opposite direction

```<code>Sort sort = new Sort(Sort.Direction.DESC, "name");
Pageable pageable = new PageRequest(1, 10, sort);
pageResult = personRepository.findAll(
            "eyecolor", "green", pageable
        );
</code>```

and this one will return the list of persons that have "eyecolor" as green. So far so good and this is working as expected. Now I would like to define a sorting on the detailvalue.

For example I would like to get a list of person sorted by their eyecolor. So first I should have the persons that have "blue", "brown", "green".

how can the Sort be specified in this case ?

In standard SQL it would be something like this:

SELECT p.* from persons p LEFT JOIN details d ON
  p.personid = d.personid AND p.detailkey='eyercolor' ORDER BY
  p.detailvalue ASC;

答:
The following query worked for me:

```<code>SELECT p FROM Person p JOIN p.details d WHERE KEY(d) = 'eyecolor' ORDER BY d
</code>```

(note that ORDER BY VALUE(d) would fail since VALUE(d) still seems to behave as described here: JPA's Map<KEY, VALUE> query by JPQL failed)

Now, I'm not particularly well versed with Spring Data, but I suppose you should be able to use the above query (without the ORDER BY part) with the @Query annotation on your PersonRepository.findAll method (I'm assuming that's a custom method) and provide the sorting using JpaSort.unsafe("d").

Body:
I would like to sort a Map of  by the value. For example I have Person class which has a map of details that are stored in a map with key-value Map<String, String>.

I am using springboot with hibernate5. This is the mapping.

public class Person implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @DocumentId
    @Column(name = "personid")
    private Integer id;

    @Column(name = "name")
    private String name;

    // this is a collection of person details
    @ElementCollection()
    @MapKeyColumn(name = "detailkey")
    @Column(name = "detailvalue")
    @CollectionTable(name = "details", joinColumns = @JoinColumn(name = "personid"))
    Map<String, String> details = new HashMap<>();

    //getter and setters omitted

So far I am able to retrieve a person with some specific detailskey and specific detail value. So for example a person table in the DB has eyecolor as detail attribute and as value can have "green", "blue", "brown". Note this is not a real example, just for clarity purposes.

So for example I can get the list of persons and sort them by their name, in the controller I can do

Sort sort = new Sort(Sort.Direction.ASC, "name");

and the opposite direction

Sort sort = new Sort(Sort.Direction.DESC, "name");
Pageable pageable = new PageRequest(1, 10, sort);
pageResult = personRepository.findAll(
            "eyecolor", "green", pageable
        );

and this one will return the list of persons that have "eyecolor" as green. So far so good and this is working as expected. Now I would like to define a sorting on the detailvalue.

For example I would like to get a list of person sorted by their eyecolor. So first I should have the persons that have "blue", "brown", "green".

how can the Sort be specified in this case ?

In standard SQL it would be something like this:

SELECT p.* from persons p LEFT JOIN details d ON
  p.personid = d.personid AND p.detailkey='eyercolor' ORDER BY
  p.detailvalue ASC;

Body:
The following query worked for me:

SELECT p FROM Person p JOIN p.details d WHERE KEY(d) = 'eyecolor' ORDER BY d

(note that ORDER BY VALUE(d) would fail since VALUE(d) still seems to behave as described here: JPA's Map<KEY, VALUE> query by JPQL failed)

Now, I'm not particularly well versed with Spring Data, but I suppose you should be able to use the above query (without the ORDER BY part) with the @Query annotation on your PersonRepository.findAll method (I'm assuming that's a custom method) and provide the sorting using JpaSort.unsafe("d").


问:
ldap vbscript : msExchOmaAdminWirelessEnable is randomly missing on different accounts
In my script:

```<code>Function getDescript (strname, uname)

    Set MyUser = GetObject ("LDAP://cn=" & uname & ",ou=" & strname & ",DC=tms-1,DC=net")

getDescript = myUser.Get("msExchOmaAdminWirelessEnable")
End Function

uname = "Bob Gardner"
strname = "bgConsultants"

WScript.Echo "wireless enable: " & getDescript(strname, uname)
</code>```

I have noticed some users in the same OU sometimes do and sometimes don't have the msExchOmaAdminWirelessEnable attribute when I check it in sysinternals' ACtive Directory Explorer.  All users are in the same OU and the exchange 2003 server has sp2 installed.

Anyone might know why this is?

Update:
I figured out that if I disable and re-enable the Outlook Mobile Access setting for each user, the msExchOmaAdminWirelessEnable attribute shows up again for those users missing that attribute...weird..

答:
According to Microsoft, By default, when you install Microsoft Exchange Server 2003, the option to permit all users to use Microsoft Outlook Mobile Access is turned on in Active Directory Users and Computers. So this would leave me to believe that this value is only prensent fo an account inwhich the setting has been toggled.  You could probably do an easy ADSI to return back only the users that don't have this setting set, or not set to enable see here for a good ADSI reference: http://www.rlmueller.net/ADOSearchTips.htm

<s>"By default, when you install Microsoft Exchange Server 2003, the option to permit all users to use Microsoft Outlook Mobile Access is turned on in Active Directory Users and Computers."</s>

OwnerDisplayName: phill

Body:
In my script:

Function getDescript (strname, uname)

    Set MyUser = GetObject ("LDAP://cn=" & uname & ",ou=" & strname & ",DC=tms-1,DC=net")

getDescript = myUser.Get("msExchOmaAdminWirelessEnable")
End Function

uname = "Bob Gardner"
strname = "bgConsultants"

WScript.Echo "wireless enable: " & getDescript(strname, uname)

I have noticed some users in the same OU sometimes do and sometimes don't have the msExchOmaAdminWirelessEnable attribute when I check it in sysinternals' ACtive Directory Explorer.  All users are in the same OU and the exchange 2003 server has sp2 installed.

Anyone might know why this is?

Update:
I figured out that if I disable and re-enable the Outlook Mobile Access setting for each user, the msExchOmaAdminWirelessEnable attribute shows up again for those users missing that attribute...weird..

LastEditorDisplayName: Rich B

OwnerDisplayName: mrTomahawk

ContentLicense: CC BY-SA 4.0


问:
Enabling gzip compression for JBoss cluster with mod_jk load balancer
We have a JBoss configured in cluster with Apache HTTP+mod_jk as a load balancer.
Do we need to configure anything on Apache side in addition to configuring compression in JBoss configuration for connector? </p>

答:
In standard JBoss gzip compression could be enabled for HTTP connector, but not for AJP. AJP connector is used between Apache HTTP server and JBoss.

To enable gzip compression on Apache HTTP server side add following lines to mod_jk.conf before </VirtualHost>:

```<code>AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/x-javascript application/javascript
</code>```

This will enable gzip compression for specified mime types by means of mod_deflate output filter http://httpd.apache.org/docs/2.2/mod/mod_deflate.html.

Also uncomment following line in httpd.conf to turn on mod_deflate:

LoadModule deflate_module
  modules/mod_deflate.so

Body:
In standard JBoss gzip compression could be enabled for HTTP connector, but not for AJP. AJP connector is used between Apache HTTP server and JBoss.

To enable gzip compression on Apache HTTP server side add following lines to mod_jk.conf before </VirtualHost>:

AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/x-javascript application/javascript

This will enable gzip compression for specified mime types by means of mod_deflate output filter http://httpd.apache.org/docs/2.2/mod/mod_deflate.html.

Also uncomment following line in httpd.conf to turn on mod_deflate:

LoadModule deflate_module
  modules/mod_deflate.so


问:
Xcode project crashes on load
I have been trying to get my build on iOS for the past 3 days to no avail. I have tried everything i have read with tonnes of research into this issue and still nothing so now i am asking you guys if you can help. This is built via Unity3D

My developer who does everything iOS is on holiday in paris, so their is no internal support for this issue either.

The app will just crash upon building and putting on device. This is the error log.

```<code>    2016-11-15 16:38:15.395 digital[639:115676] -> registered mono modules 0x1013cac00
 -> applicationDidFinishLaunching()
 -> applicationDidBecomeActive()
 GfxDevice: creating device client; threaded=1
 Init: screen size 2048x1536
 Initializing Metal device caps: Apple A7 GPU
 Initialize engine version: 5.4.2f2 (b7e030c65c9b)
 OnLevelWasLoaded was found on DOTweenComponent
 This message has been deprecated and will be removed in a later version of Unity.
 Add a delegate to SceneManager.sceneLoaded instead to get notifications after scene loading has completed

 (Filename:  Line: 375)

 The referenced script on this Behaviour (Game Object '1x4(Clone)') is missing!

 (Filename:  Line: 1656)

 The referenced script on this Behaviour (Game Object 'OneByThree') is missing!

 (Filename:  Line: 1656)

 The referenced script on this Behaviour (Game Object 'BokehController') is missing!

 (Filename:  Line: 1656)

 The referenced script on this Behaviour (Game Object 'BokehField') is missing!

 (Filename:  Line: 1656)

 The referenced script on this Behaviour (Game Object 'BokehField') is missing!

 (Filename:  Line: 1656)

 The referenced script on this Behaviour (Game Object 'BokehField') is missing!

 (Filename:  Line: 1656)

 The referenced script on this Behaviour (Game Object 'BokehField') is missing!

 (Filename:  Line: 1656)

 The referenced script on this Behaviour (Game Object 'New PAParticleField') is missing!

 (Filename:  Line: 1656)

 The referenced script on this Behaviour (Game Object 'New PAParticleField') is missing!

 (Filename:  Line: 1656)

 The referenced script on this Behaviour (Game Object 'BokehController') is missing!

 (Filename:  Line: 1656)

 UnloadTime: 44.684330 ms
 2016-11-15 16:38:25.911 digital[639:115676] -[NSTaggedPointerString al_containsSubstring:]: unrecognized selector sent to instance 0xa0045564954414e6
 2016-11-15 16:38:25.918 digital[639:115676] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSTaggedPointerString al_containsSubstring:]: unrecognized selector sent to instance 0xa0045564954414e6'
 *** First throw call stack:
 (0x182e1adb0 0x18247ff80 0x182e21c4c 0x182e1ebec 0x182d1cc5c 0x101213048 0x101210f40 0x10120fd5c 0x10120fae4 0x10008f458 0x1008aacf8 0x1011d418c 0x100a9e53c 0x100a9e90c 0x100a91c8c 0x100a939ec 0x100a93ce0 0x100a93958 0x100ab9b94 0x100ab9ab4 0x100ab9a48 0x100a9dc64 0x100a9dcb0 0x100a9d830 0x100a9d8f4 0x100a9d620 0x100a99660 0x100a99a68 0x1009906d4 0x100a56d2c 0x100cef1e0 0x100086960 0x1837e2658 0x182dd1794 0x182dd1438 0x182dceb4c 0x182cf8c50 0x1845e0088 0x187fda088 0x100072fac 0x1828968b8)
 libc++abi.dylib: terminating with uncaught exception of type NSException
 (lldb)
</code>```

And here is the screen shot of what is happening on Xcode

答:
Enable Linker Flags in Build Settings.

The -ObjC flag must be added for static libraries to run correctly.

Title: Xcode project crashes on load

Body:
I have been trying to get my build on iOS for the past 3 days to no avail. I have tried everything i have read with tonnes of research into this issue and still nothing so now i am asking you guys if you can help. This is built via Unity3D

My developer who does everything iOS is on holiday in paris, so their is no internal support for this issue either.

The app will just crash upon building and putting on device. This is the error log.

    2016-11-15 16:38:15.395 digital[639:115676] -> registered mono modules 0x1013cac00
 -> applicationDidFinishLaunching()
 -> applicationDidBecomeActive()
 GfxDevice: creating device client; threaded=1
 Init: screen size 2048x1536
 Initializing Metal device caps: Apple A7 GPU
 Initialize engine version: 5.4.2f2 (b7e030c65c9b)
 OnLevelWasLoaded was found on DOTweenComponent
 This message has been deprecated and will be removed in a later version of Unity.
 Add a delegate to SceneManager.sceneLoaded instead to get notifications after scene loading has completed

 (Filename:  Line: 375)

 The referenced script on this Behaviour (Game Object '1x4(Clone)') is missing!

 (Filename:  Line: 1656)

 The referenced script on this Behaviour (Game Object 'OneByThree') is missing!

 (Filename:  Line: 1656)

 The referenced script on this Behaviour (Game Object 'BokehController') is missing!

 (Filename:  Line: 1656)

 The referenced script on this Behaviour (Game Object 'BokehField') is missing!

 (Filename:  Line: 1656)

 The referenced script on this Behaviour (Game Object 'BokehField') is missing!

 (Filename:  Line: 1656)

 The referenced script on this Behaviour (Game Object 'BokehField') is missing!

 (Filename:  Line: 1656)

 The referenced script on this Behaviour (Game Object 'BokehField') is missing!

 (Filename:  Line: 1656)

 The referenced script on this Behaviour (Game Object 'New PAParticleField') is missing!

 (Filename:  Line: 1656)

 The referenced script on this Behaviour (Game Object 'New PAParticleField') is missing!

 (Filename:  Line: 1656)

 The referenced script on this Behaviour (Game Object 'BokehController') is missing!

 (Filename:  Line: 1656)

 UnloadTime: 44.684330 ms
 2016-11-15 16:38:25.911 digital[639:115676] -[NSTaggedPointerString al_containsSubstring:]: unrecognized selector sent to instance 0xa0045564954414e6
 2016-11-15 16:38:25.918 digital[639:115676] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSTaggedPointerString al_containsSubstring:]: unrecognized selector sent to instance 0xa0045564954414e6'
 *** First throw call stack:
 (0x182e1adb0 0x18247ff80 0x182e21c4c 0x182e1ebec 0x182d1cc5c 0x101213048 0x101210f40 0x10120fd5c 0x10120fae4 0x10008f458 0x1008aacf8 0x1011d418c 0x100a9e53c 0x100a9e90c 0x100a91c8c 0x100a939ec 0x100a93ce0 0x100a93958 0x100ab9b94 0x100ab9ab4 0x100ab9a48 0x100a9dc64 0x100a9dcb0 0x100a9d830 0x100a9d8f4 0x100a9d620 0x100a99660 0x100a99a68 0x1009906d4 0x100a56d2c 0x100cef1e0 0x100086960 0x1837e2658 0x182dd1794 0x182dd1438 0x182dceb4c 0x182cf8c50 0x1845e0088 0x187fda088 0x100072fac 0x1828968b8)
 libc++abi.dylib: terminating with uncaught exception of type NSException
 (lldb)

And here is the screen shot of what is happening on Xcode


问:
Print numbers in specific range without using any loop or conditions (Java)
Maybe first idea come to mind to solve this kind of problems is recursive function but also it will be a challenge to write recursive function without any condition.

I tried this approach to print numbers from 10 to 60:

```<code>public static void printNumbers(int n){
       int divisonByZero = 1 / (61 - n);
       System.out.println(n);
       printNumbers(n+1);
}
public static void main(String[] args) {
       printNumbers(10);
}
</code>```

But it will crash when it reach number 61 without exception handling

also even with try catch the Arithmetic Exception it's still not a preferable solution because it's handling an exception (runtime error).

I think main problem when using recursive functions is the stop condition.

As well I read that there is a way in C++ by creating a class with a static variable counter and initialize it then increment the counter variable and print it in the constructor after that instantiating number of objects of class counter will print these numbers.

Any suggested solutions to solve this challenge would be appreciated.

答:
Using an Exception for normal program flow is poor form, but this works.  Eventually there will be a division by zero exception which is the signal to quit.</p>

```<code>public class App {

    public static void main(String[] args) {
        App app = new App();
        try {
            app.print(10, 60);
        } catch (ArithmeticException ae) {
            // ignore
        }
    }

    private void print(int next, int until) {
        System.out.println(next);
        assertNotEndOfRange(next, until);
        print(++next, until);
    }

    private int assertNotEndOfRange(int next, int until) {
        return 0 / (until - next);
    }

}
</code>```

Body:
Maybe first idea come to mind to solve this kind of problems is recursive function but also it will be a challenge to write recursive function without any condition.

I tried this approach to print numbers from 10 to 60:

public static void printNumbers(int n){
       int divisonByZero = 1 / (61 - n);
       System.out.println(n);
       printNumbers(n+1);
}
public static void main(String[] args) {
       printNumbers(10);
}

But it will crash when it reach number 61 without exception handling

also even with try catch the Arithmetic Exception it's still not a preferable solution because it's handling an exception (runtime error).

I think main problem when using recursive functions is the stop condition.

As well I read that there is a way in C++ by creating a class with a static variable counter and initialize it then increment the counter variable and print it in the constructor after that instantiating number of objects of class counter will print these numbers.

Any suggested solutions to solve this challenge would be appreciated.

Body:
Using an Exception for normal program flow is poor form, but this works.  Eventually there will be a division by zero exception which is the signal to quit.

public class App {

    public static void main(String[] args) {
        App app = new App();
        try {
            app.print(10, 60);
        } catch (ArithmeticException ae) {
            // ignore
        }
    }

    private void print(int next, int until) {
        System.out.println(next);
        assertNotEndOfRange(next, until);
        print(++next, until);
    }

    private int assertNotEndOfRange(int next, int until) {
        return 0 / (until - next);
    }

}


问:
Dapper exception - Get<T> only supports en entity with a [Key] property, but [key] is defined
If the BO is marked as having a key with [key], why does dapper through an error?

```<code>[Table("tblWebReadyToWorkQualifications")]
public class TeacherQualificationBO
{
    [Key]
    public int TeacherID { get; set; }

    public string ReadyToWorkGuid { get; set; }

    public int QualificationID { get; set; }

}
</code>```

Call to dapper that throws the exception

```<code>      public IEnumerable<TeacherQualificationBO> GetTeacherQualifications(int TeacherID)
      {
        using (var connection = GetOpenConnection())
        {
            return connection.Get<IEnumerable<TeacherQualificationBO>>(TeacherID);
        }
      }
</code>```

The table tblWebReadyToWorkQualifications has a primary key on TeacherID.

Error:
  at Dapper.Contrib.Extensions.SqlMapperExtensions.Get[T](IDbConnection connection, Object id, IDbTransaction transaction, Nullable`1 commandTimeout) in d:\egna projekt\dapper-dot-net\Dapper.Contrib\SqlMapperExtensions.cs:line 128\r\n

答:
The error message is probably trying to tell you that the generic type IEnumerable<TeacherQualificationBO> does not have a [Key] attribute, which is true. Only the type TeacherQualificationBO does.

change

```<code>return connection.Get<IEnumerable<TeacherQualificationBO>>(TeacherID);
</code>```

to

```<code>return connection.Get<TeacherQualificationBO>(TeacherID);
</code>```

You also need to change the return type of your function to TeacherQualificationBO to reflect this. You state that TeacherID is a primary key (thus unique), so TeacherID will only ever correspond to a single record. Thus it makes sense not to return a collection.

Body:
If the BO is marked as having a key with [key], why does dapper through an error?

[Table("tblWebReadyToWorkQualifications")]
public class TeacherQualificationBO
{
    [Key]
    public int TeacherID { get; set; }

    public string ReadyToWorkGuid { get; set; }

    public int QualificationID { get; set; }

}

Call to dapper that throws the exception

      public IEnumerable<TeacherQualificationBO> GetTeacherQualifications(int TeacherID)
      {
        using (var connection = GetOpenConnection())
        {
            return connection.Get<IEnumerable<TeacherQualificationBO>>(TeacherID);
        }
      }

The table tblWebReadyToWorkQualifications has a primary key on TeacherID.

Error:
  at Dapper.Contrib.Extensions.SqlMapperExtensions.Get[T](IDbConnection connection, Object id, IDbTransaction transaction, Nullable`1 commandTimeout) in d:\egna projekt\dapper-dot-net\Dapper.Contrib\SqlMapperExtensions.cs:line 128\r\n

Body:
The error message is probably trying to tell you that the generic type IEnumerable<TeacherQualificationBO> does not have a [Key] attribute, which is true. Only the type TeacherQualificationBO does.

change

return connection.Get<IEnumerable<TeacherQualificationBO>>(TeacherID);

to

return connection.Get<TeacherQualificationBO>(TeacherID);

You also need to change the return type of your function to TeacherQualificationBO to reflect this. You state that TeacherID is a primary key (thus unique), so TeacherID will only ever correspond to a single record. Thus it makes sense not to return a collection.


问:
Beyond compare ignore one side comments
I found some instructions on how to show/hide differences in comments using beyond compare. However most of the answers show how to set comment as important text or not. That is, if a portion of code is commented on both sides then check if the comment are different or not.

I would like to ignore when only one side of the comparison is commented. In other words if I have

```<code># # line1
# line2
</code>```

on one side and

```<code># line1
line2
</code>```

I would like both lines to be marked as "unimportant differences" (if indeed the text is the same, otherwise to be marked as differences).

答:
Beyond Compare will only compare text if it is of the same grammar element type. If one side is regular code and the other side is a comment, it will always mark it as an important difference.

To make regular text on one side and the same text commented on the other side show as a match, you'll need to edit the definition of a comment in the file format.

To edit a format, open Tools > File Formats.

Select the format that matches your files.

Go to the Grammar tab.

Select the Comment grammar element, which might be defined as # to end of line.

Click the Edit (gear) button.

Set the Category radio button to Basic.

Text matching: ^#\s

Check Regular expression.

Click OK, then Save.

The updated file format will treat # followed by a whitespace character as an unimportant comment, the remaining text in the line will be treated as regular text and compared to the other side.

Title: Beyond compare ignore one side comments

Body:
I found some instructions on how to show/hide differences in comments using beyond compare. However most of the answers show how to set comment as important text or not. That is, if a portion of code is commented on both sides then check if the comment are different or not.

I would like to ignore when only one side of the comparison is commented. In other words if I have

# # line1
# line2

on one side and

# line1
line2

I would like both lines to be marked as "unimportant differences" (if indeed the text is the same, otherwise to be marked as differences).


问:
How do you create two tables within one excel sheet Using visual studio ETL?
I am creating an ETL on visual studio, and I want to export two different tables from my flow to the same excel sheet. So far I can only export the tables to different sheets within excel.</p>

答:
You can do that by using the Union all component.

SO you can use both sources and export them to your excel file.


问:
How to bypass the Firebase cache to refresh data (in Android app)?
On an Android application which must works offline most of the time I need, when it's online, to do some synchronous operations for i.e. :

```<code>User myUser =  MyclientFacade.getUser();
If (myUser.getScore > 10) {
    DoSomething()
}
</code>```

Where User is a POJO filled by Firebase;

The problem occurs when the Firebase cache is activated

```<code>Firebase.getDefaultConfig().setPersistenceEnabled(true);
</code>```

and the user is already in cache and the data are updated on Firebase DB by a third party (or even by another device). Indeed when I query Firebase to get the User I obtain first the data from the cache and later a second change event with the latest data from the Firebase server, but it's too late!

Let's see the synchronous method MyclientFacade.getUser() :

```<code>Public User  getUser()  {
  Firebase ref = myFireBaseroot.child("User").child(uid);
  ref.keepSynced(true);
  /* try {
    Thread.sleep(3000);
 } catch (InterruptedException e) {
    e.printStackTrace();
 }*/
final CountDownLatch signal = new CountDownLatch(1);

ref.addListenerForSingleValueEvent(new ValueEventListener() {
//ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
       this.user = dataSnapshot.getValue(User.class);
       signal.countDown();
    }
    @Override
    public void onCancelled(FirebaseError firebaseError) {
       signal.countDown();
    }
});
signal.await(5, TimeUnit.SECONDS);
ref.keepSynced(false);
return this.user;
}
</code>```

I obtain the same behavior if I use addValueEventListener or addListenerForSingleValueEvent mixed with ref.keepSynced:

Let's say my user's score value in cache is 5 and from Firebase DB is 11.

When I call getUser I will obtain the score of 5 (Firebase ask cache first) so I will not call the doSomething() method.

If I uncomment the Thread.sleep() code from my example, the Firebase cache will have enough time to be updated and my getUser will return the correct score value (11).

So how can I directly ask the latest value directly from server side and bypass the cache?

答:
Just add this code on onCreate method on your application class. (change the database reference)

Example:

```<code>public class MyApplication extendes Application{

 @Override
    public void onCreate() {
        super.onCreate();
            DatabaseReference scoresRef = FirebaseDatabase.getInstance().getReference("scores");
            scoresRef.keepSynced(true);
      }
}
</code>```

Works well to me.

Reference:
https://firebase.google.com/docs/database/android/offline-capabilities

Body:
On an Android application which must works offline most of the time I need, when it's online, to do some synchronous operations for i.e. :

User myUser =  MyclientFacade.getUser();
If (myUser.getScore > 10) {
    DoSomething()
}

Where User is a POJO filled by Firebase;

The problem occurs when the Firebase cache is activated

Firebase.getDefaultConfig().setPersistenceEnabled(true);

and the user is already in cache and the data are updated on Firebase DB by a third party (or even by another device). Indeed when I query Firebase to get the User I obtain first the data from the cache and later a second change event with the latest data from the Firebase server, but it's too late!

Let's see the synchronous method MyclientFacade.getUser() :

Public User  getUser()  {
  Firebase ref = myFireBaseroot.child("User").child(uid);
  ref.keepSynced(true);
  /* try {
    Thread.sleep(3000);
 } catch (InterruptedException e) {
    e.printStackTrace();
 }*/
final CountDownLatch signal = new CountDownLatch(1);

ref.addListenerForSingleValueEvent(new ValueEventListener() {
//ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
       this.user = dataSnapshot.getValue(User.class);
       signal.countDown();
    }
    @Override
    public void onCancelled(FirebaseError firebaseError) {
       signal.countDown();
    }
});
signal.await(5, TimeUnit.SECONDS);
ref.keepSynced(false);
return this.user;
}

I obtain the same behavior if I use addValueEventListener or addListenerForSingleValueEvent mixed with ref.keepSynced:

Let's say my user's score value in cache is 5 and from Firebase DB is 11.

When I call getUser I will obtain the score of 5 (Firebase ask cache first) so I will not call the doSomething() method.

If I uncomment the Thread.sleep() code from my example, the Firebase cache will have enough time to be updated and my getUser will return the correct score value (11).

So how can I directly ask the latest value directly from server side and bypass the cache?

Body:
Just add this code on onCreate method on your application class. (change the database reference)

Example:

public class MyApplication extendes Application{

 @Override
    public void onCreate() {
        super.onCreate();
            DatabaseReference scoresRef = FirebaseDatabase.getInstance().getReference("scores");
            scoresRef.keepSynced(true);
      }
}

Works well to me.

Reference:
https://firebase.google.com/docs/database/android/offline-capabilities


问:
ListView Filter Android Using SimpleAdapter
I have created a ListView in android and I want to add EditText above the list and when the user enter text the list will be filtered according to user input

Can anyone tell me please if there is a way to filter the list adapter in android (Use SimpleAdapter) ?

```<code>public class DanhSachHopDongChoNghiemThuActivity extends AppCompatActivity implements TextWatcher {
    String username = ...
    String password = ...
    String database = ...
    String server = ...
    Connection connect;
    EditText inputSearch;
    ListView listView;
    SimpleAdapter simpleAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inputSearch = (EditText)findViewById(R.id.editString);
        listView = (ListView)findViewById(R.id.listViewDanhSachHopDongChoNghiemThu);
        connect = CONN(username, password, database, server);
        querySQL();
        editString.addTextChangedListener(this);
    }
    public void querySQL() {
        ResultSet rs;
        try{
            PreparedStatement statement =
                    connect.prepareStatement("T_APIgetListThueBaoChoNghiemThu " + MainActivity.userId);
            rs = statement.executeQuery();
            List<Map<String,String>> data = null;
            data = new ArrayList<Map<String,String>>();
            if (rs != null) {
                while (rs.next()) {
                    Map<String, String> datanum = new HashMap<String, String>();
                    datanum.put("NgayHD", "Ngày HĐ: " + rs.getString("NgayLapHD"));
                    datanum.put("TenTB", rs.getString("TenTB"));
                    datanum.put("MaTB", rs.getString("MaTB"));
                    datanum.put("DiaChi", rs.getString("DiaChi"));
                    datanum.put("DaiVT", rs.getString("DaiVTTen"));
                    datanum.put("GhiChu", "Ghi chú: " + rs.getString("GhiChu"));
                    datanum.put("TenDVVT", rs.getString("DVVTTen"));
                    datanum.put("TrangThai", rs.getString("TrangThai"));
                    data.add(datanum);

                    String[] from = {"TenDVVT", "NgayHD", "TenTB", "MaTB", "DaiVT", "DiaChi", "GhiChu", "TrangThai"};
                    int[] to = {R.id.DichVu, R.id.txtNgayHD, R.id.txtTenTB, R.id.txtMaTB, R.id.txtDaiVT, R.id.txtDiaChi, R.id.txtGhiChu, R.id.txtTrangThai};

                    simpleAdapter = new SimpleAdapter(this, data, R.layout.danhsachchonghiemthu_listview_layout, from, to);
                    listView.setAdapter(simpleAdapter);
                }
            }
        }catch(SQLException e){
            e.printStackTrace();
        }
    }
    @SuppressLint("NewApi")
    private Connection CONN(String _user, String _pass, String _DB,
                            String _server) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection conn = null;
        String ConnURL = null;
        try {
            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            ConnURL = "jdbc:jtds:sqlserver://" + _server + ";"
                    + "databaseName=" + _DB + ";user=" + _user + ";password="
                    + _pass + ";";
            conn = DriverManager.getConnection(ConnURL);
        } catch (SQLException se) {
            Log.e("ERRO", se.getMessage());
        } catch (ClassNotFoundException e) {
            Log.e("ERRO", e.getMessage());
        } catch (Exception e) {
            Log.e("ERRO", e.getMessage());
        }
        return conn;
    }
}
</code>```

答:
it is very simple and this is work for me </p>

```<code>editText_search.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            ((SimpleAdapter)All_Reports_Fragment.this.listAdapter).getFilter().filter(s);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
</code>```

Body:
I have created a ListView in android and I want to add EditText above the list and when the user enter text the list will be filtered according to user input

Can anyone tell me please if there is a way to filter the list adapter in android (Use SimpleAdapter) ?

public class DanhSachHopDongChoNghiemThuActivity extends AppCompatActivity implements TextWatcher {
    String username = ...
    String password = ...
    String database = ...
    String server = ...
    Connection connect;
    EditText inputSearch;
    ListView listView;
    SimpleAdapter simpleAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inputSearch = (EditText)findViewById(R.id.editString);
        listView = (ListView)findViewById(R.id.listViewDanhSachHopDongChoNghiemThu);
        connect = CONN(username, password, database, server);
        querySQL();
        editString.addTextChangedListener(this);
    }
    public void querySQL() {
        ResultSet rs;
        try{
            PreparedStatement statement =
                    connect.prepareStatement("T_APIgetListThueBaoChoNghiemThu " + MainActivity.userId);
            rs = statement.executeQuery();
            List<Map<String,String>> data = null;
            data = new ArrayList<Map<String,String>>();
            if (rs != null) {
                while (rs.next()) {
                    Map<String, String> datanum = new HashMap<String, String>();
                    datanum.put("NgayHD", "Ngày HĐ: " + rs.getString("NgayLapHD"));
                    datanum.put("TenTB", rs.getString("TenTB"));
                    datanum.put("MaTB", rs.getString("MaTB"));
                    datanum.put("DiaChi", rs.getString("DiaChi"));
                    datanum.put("DaiVT", rs.getString("DaiVTTen"));
                    datanum.put("GhiChu", "Ghi chú: " + rs.getString("GhiChu"));
                    datanum.put("TenDVVT", rs.getString("DVVTTen"));
                    datanum.put("TrangThai", rs.getString("TrangThai"));
                    data.add(datanum);

                    String[] from = {"TenDVVT", "NgayHD", "TenTB", "MaTB", "DaiVT", "DiaChi", "GhiChu", "TrangThai"};
                    int[] to = {R.id.DichVu, R.id.txtNgayHD, R.id.txtTenTB, R.id.txtMaTB, R.id.txtDaiVT, R.id.txtDiaChi, R.id.txtGhiChu, R.id.txtTrangThai};

                    simpleAdapter = new SimpleAdapter(this, data, R.layout.danhsachchonghiemthu_listview_layout, from, to);
                    listView.setAdapter(simpleAdapter);
                }
            }
        }catch(SQLException e){
            e.printStackTrace();
        }
    }
    @SuppressLint("NewApi")
    private Connection CONN(String _user, String _pass, String _DB,
                            String _server) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection conn = null;
        String ConnURL = null;
        try {
            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            ConnURL = "jdbc:jtds:sqlserver://" + _server + ";"
                    + "databaseName=" + _DB + ";user=" + _user + ";password="
                    + _pass + ";";
            conn = DriverManager.getConnection(ConnURL);
        } catch (SQLException se) {
            Log.e("ERRO", se.getMessage());
        } catch (ClassNotFoundException e) {
            Log.e("ERRO", e.getMessage());
        } catch (Exception e) {
            Log.e("ERRO", e.getMessage());
        }
        return conn;
    }
}

Body:
it is very simple and this is work for me

editText_search.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            ((SimpleAdapter)All_Reports_Fragment.this.listAdapter).getFilter().filter(s);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });


问:
bool operator== within typedef struct
How can I add the bool operator== to the struct bd_addr_t? I'm using this file within a C++ project.

```<code>#ifndef APITYPES_H_
#define APITYPES_H_

#ifdef __GNUC__

#define PACKSTRUCT( decl ) decl __attribute__((__packed__))
#define ALIGNED __attribute__((aligned(0x4)))

#else //msvc

#define PACKSTRUCT( decl ) __pragma( pack(push, 1) ) decl __pragma( pack(pop) )
#define ALIGNED

#endif

typedef unsigned char  uint8;
typedef unsigned short uint16;
typedef signed short   int16;
typedef unsigned long  uint32;
typedef signed char    int8;

typedef struct bd_addr_t
{
    uint8 addr[6];

}bd_addr;

typedef bd_addr hwaddr;
typedef struct
{
    uint8 len;
    uint8 data[];
}uint8array;

typedef struct
{
    uint8 len;
    int8 data[];
}string;

#endif
</code>```

I tried to add

```<code>bool operator==(const bd_addr_t& a) const
    {
        return (addr[0] == a.addr[0] && addr[1] == a.addr[1] && addr[2] == a.addr[2] && addr[3] == a.addr[3] && addr[4] == a.addr[4] && addr[5] == a.addr[5]);
    }
</code>```

but this throws two errors during compilation:

```<code>unknown type name 'bool' bool operator==(const bd_addr_t& a) const

 expected ':', ',', ';', '}' or '__attribute__' before '==' token bool operator==(const bd_addr_t& a) const
</code>```

答:
You cannot add such function into this header which is used by C compiler as well. One of the way could be to create a wrapper header that you use only in you C++ code and add standalone function (it cannot be a method as that would require it's declaration within struct and make that code incompatible with C):

```<code>#include <original_header.h>
#ifndef __cplusplus
#error This header is only to be included in C++ code
#endif

bool operator==(const bd_addr_t& a, const bd_addr_t& b);
</code>```

and then implement it in one of .cpp files or you can implement it in this header and make that function inline

Title: bool operator== within typedef struct

Body:
How can I add the bool operator== to the struct bd_addr_t? I'm using this file within a C++ project.

#ifndef APITYPES_H_
#define APITYPES_H_

#ifdef __GNUC__

#define PACKSTRUCT( decl ) decl __attribute__((__packed__))
#define ALIGNED __attribute__((aligned(0x4)))

#else //msvc

#define PACKSTRUCT( decl ) __pragma( pack(push, 1) ) decl __pragma( pack(pop) )
#define ALIGNED

#endif

typedef unsigned char  uint8;
typedef unsigned short uint16;
typedef signed short   int16;
typedef unsigned long  uint32;
typedef signed char    int8;

typedef struct bd_addr_t
{
    uint8 addr[6];

}bd_addr;

typedef bd_addr hwaddr;
typedef struct
{
    uint8 len;
    uint8 data[];
}uint8array;

typedef struct
{
    uint8 len;
    int8 data[];
}string;

#endif

I tried to add

bool operator==(const bd_addr_t& a) const
    {
        return (addr[0] == a.addr[0] && addr[1] == a.addr[1] && addr[2] == a.addr[2] && addr[3] == a.addr[3] && addr[4] == a.addr[4] && addr[5] == a.addr[5]);
    }

but this throws two errors during compilation:

unknown type name 'bool' bool operator==(const bd_addr_t& a) const

 expected ':', ',', ';', '}' or '__attribute__' before '==' token bool operator==(const bd_addr_t& a) const

Body:
You cannot add such function into this header which is used by C compiler as well. One of the way could be to create a wrapper header that you use only in you C++ code and add standalone function (it cannot be a method as that would require it's declaration within struct and make that code incompatible with C):

#include <original_header.h>
#ifndef __cplusplus
#error This header is only to be included in C++ code
#endif

bool operator==(const bd_addr_t& a, const bd_addr_t& b);

and then implement it in one of .cpp files or you can implement it in this header and make that function inline


问:
Is it a coffeescript bug? Destructuring and Existential Operator
following coffeescript code:

```<code>{ baz } = @foo.bar?
</code>```

produces:

```<code>var baz;
baz = (this.foo.bar != null).baz;
</code>```

but I expect:

```<code>var ref, baz;
if ((ref = this.foo.bar) != null) {
  baz = ref.baz;
}
</code>```

Is it a bug or an expected behavior?

答:
I think you've confused the unary ? operator with the binary ?. operator.

The right-hand side of this expression:

```<code>baz = @foo.bar?.baz
</code>```

...uses the binary ?. operator. As you know, it returns the value of the subsequent property if it exists and null otherwise (and short-circuits evaluation of further properties).

On the other hand, the RHS of this expression:

```<code>{ baz } = @foo.bar?
</code>```

...uses the unary ? operator. It returns false if its operand (the preceding expression) is null or undefined, and true otherwise.

This is a really easy mistake to make; you can see someone ask the same question in this CoffeeScript issue. Compounding the problem, the CoffeeScript docs don't even give these two operators different names. They call ? the "existential operator" and ?. the "accessor variant of the existential operator."

Body:
following coffeescript code:

{ baz } = @foo.bar?

produces:

var baz;
baz = (this.foo.bar != null).baz;

but I expect:

var ref, baz;
if ((ref = this.foo.bar) != null) {
  baz = ref.baz;
}

Is it a bug or an expected behavior?

Body:
I think you've confused the unary ? operator with the binary ?. operator.

The right-hand side of this expression:

baz = @foo.bar?.baz

...uses the binary ?. operator. As you know, it returns the value of the subsequent property if it exists and null otherwise (and short-circuits evaluation of further properties).

On the other hand, the RHS of this expression:

{ baz } = @foo.bar?

...uses the unary ? operator. It returns false if its operand (the preceding expression) is null or undefined, and true otherwise.

This is a really easy mistake to make; you can see someone ask the same question in this CoffeeScript issue. Compounding the problem, the CoffeeScript docs don't even give these two operators different names. They call ? the "existential operator" and ?. the "accessor variant of the existential operator."


问:
Linq throws exception on .Substring()
I've got a situation where I need to have my LINQ to Entities query return a substring depending on the length of the string.
Here's the Query:

```<code>var query = (
    from f in Context.Files
    orderby f.DateAdded descending
    select new
    {
        Concerns = f.Concerns.Name,
        Sender = f.Sender.Name,
        CategoryCount = f.Categories.Count(),
        DateAdded = f.DateAdded,
        Comment = (f.Comment == null || f.Comment.Length < 5)
            ? f.Comment : f.Comment
    }).Take(10);
</code>```

So what I'm doing is getting the last 10 added Entities of type Files and then select a set of properties from it to display inside a listview. Some are plain strings (Concerns, Sender). CategoryCount returns the number of categories which are associated with the File object.

However, I want the comment to be truncated if it is longer then a given length. In the above code, everything is working correctly. Now when I replace this line:

```<code>Comment = (f.Comment == null || f.Comment.Length < 5)
    ? f.Comment : f.Comment
</code>```

With this line:

```<code>Comment = (f.Comment == null || f.Comment.Length < 5)
    ? f.Comment : f.Comment.SubString(0,5)
</code>```

the application throws a XamlParseException (???)

The invocation of the constructor on type 'DocumentManager.Views.ListEntriesView' that matches the specified binding constraints threw an exception

I really don't know why it would do that. Is the SubString method not supported in LINQ?

Hope someone can help me here. Until then, I'll just leave it the way it is.

EDIT 2 (Somehow, my first edit got lost. So I'm redoing it):
Based on the comments I got I changed my code to this and it works now:

```<code>var query = App.Context.Files.OrderByDescending(File => File.DateAdded).Take(10).AsEnumerable()
            .Select(File => new
            {
                Concerns = File.Concerns.Name,
                Sender = File.Sender.Name,
                CategoryCount = File.Categories.Count(),
                DateAdded = File.DateAdded,
                Comment = (File.Comment == null || File.Comment.Length < 100) ? File.Comment : File.Comment.Substring(0, 100) + "..."
            });
</code>```

I forgot to mention that I'm using SQLite. So maybe Substring is not implemented in the SQLite EF Provider.

答:
It's not LINQ's fault actually. Your model is bind to IQueryable, i.e. the routines directly supported by your database (everything else throws Exceptions). You should use AsEnumerable method at some point to do everything else.

Read more as Bill Wagner explains difference between IQueryable and IEnumerable here:

http://msdn.microsoft.com/en-us/vcsharp/ff963710

Title: Linq throws exception on .Substring()

Body:
I've got a situation where I need to have my LINQ to Entities query return a substring depending on the length of the string.
Here's the Query:

var query = (
    from f in Context.Files
    orderby f.DateAdded descending
    select new
    {
        Concerns = f.Concerns.Name,
        Sender = f.Sender.Name,
        CategoryCount = f.Categories.Count(),
        DateAdded = f.DateAdded,
        Comment = (f.Comment == null || f.Comment.Length < 5)
            ? f.Comment : f.Comment
    }).Take(10);

So what I'm doing is getting the last 10 added Entities of type Files and then select a set of properties from it to display inside a listview. Some are plain strings (Concerns, Sender). CategoryCount returns the number of categories which are associated with the File object.

However, I want the comment to be truncated if it is longer then a given length. In the above code, everything is working correctly. Now when I replace this line:

Comment = (f.Comment == null || f.Comment.Length < 5)
    ? f.Comment : f.Comment

With this line:

Comment = (f.Comment == null || f.Comment.Length < 5)
    ? f.Comment : f.Comment.SubString(0,5)

the application throws a XamlParseException (???)

The invocation of the constructor on type 'DocumentManager.Views.ListEntriesView' that matches the specified binding constraints threw an exception

I really don't know why it would do that. Is the SubString method not supported in LINQ?

Hope someone can help me here. Until then, I'll just leave it the way it is.

EDIT 2 (Somehow, my first edit got lost. So I'm redoing it):
Based on the comments I got I changed my code to this and it works now:

var query = App.Context.Files.OrderByDescending(File => File.DateAdded).Take(10).AsEnumerable()
            .Select(File => new
            {
                Concerns = File.Concerns.Name,
                Sender = File.Sender.Name,
                CategoryCount = File.Categories.Count(),
                DateAdded = File.DateAdded,
                Comment = (File.Comment == null || File.Comment.Length < 100) ? File.Comment : File.Comment.Substring(0, 100) + "..."
            });

I forgot to mention that I'm using SQLite. So maybe Substring is not implemented in the SQLite EF Provider.


问:
Adding a number to each column of a matrix
I have a matrix

```<code>A = [[  1.  2.  3.]
     [  4.  5.  6.]]
</code>```

and a vector

```<code>b = [ 5.  10.  15.]
</code>```

I want to add each column of A (A[:,i]) to b[i], i.e.

```<code>[[  6.  12.  18.]
 [  9.  15.  21.]]
</code>```

an easy way to do it would be

```<code>A = tf.constant([[1., 2, 3],[1, 2, 3]])
b = tf.constant([[5, 10, 15.]])
e = tf.ones((2,1))
a + tf.matmul( e, b ) # outer product "repmat"
</code>```

But it seems terribly wasteful to do this and have to construct an entire auxiliary matrix which we will eventually throw out. Is there a more idomatic way of doing this without writing my own op?

答:
As mentioned you can do A + b:

```<code>import tensorflow as tf
tf.InteractiveSession()
A = tf.constant([[1., 2, 3], [4, 5, 6]])
b = tf.constant([[5, 10, 15.]])
(A + b).eval()
</code>```

returns:

```<code>array([[  6.,  12.,  18.],
       [  9.,  15.,  21.]], dtype=float32)
</code>```

The reason this works is because of array broadcasting. The Numpy broadcasting page has great info and tensorflow broadcasting works the same way. Basically for each dimension (moving from trailing dimension to leading dimension) tensorflow/numpy attempts checks to see if the dimensions are compatible (either they have the same number of elements or one of them only has 1 element).

In your case A is of shape [2, 3] and b is of shape [1, 3]. The second dimensions match, but because b has a first dimension with only a single element that element of b is "broadcast" along the first dimension of A (two elements).

Body:
I have a matrix

A = [[  1.  2.  3.]
     [  4.  5.  6.]]

and a vector

b = [ 5.  10.  15.]

I want to add each column of A (A[:,i]) to b[i], i.e.

[[  6.  12.  18.]
 [  9.  15.  21.]]

an easy way to do it would be

A = tf.constant([[1., 2, 3],[1, 2, 3]])
b = tf.constant([[5, 10, 15.]])
e = tf.ones((2,1))
a + tf.matmul( e, b ) # outer product "repmat"

But it seems terribly wasteful to do this and have to construct an entire auxiliary matrix which we will eventually throw out. Is there a more idomatic way of doing this without writing my own op?

Body:
As mentioned you can do A + b:

import tensorflow as tf
tf.InteractiveSession()
A = tf.constant([[1., 2, 3], [4, 5, 6]])
b = tf.constant([[5, 10, 15.]])
(A + b).eval()

returns:

array([[  6.,  12.,  18.],
       [  9.,  15.,  21.]], dtype=float32)

The reason this works is because of array broadcasting. The Numpy broadcasting page has great info and tensorflow broadcasting works the same way. Basically for each dimension (moving from trailing dimension to leading dimension) tensorflow/numpy attempts checks to see if the dimensions are compatible (either they have the same number of elements or one of them only has 1 element).

In your case A is of shape [2, 3] and b is of shape [1, 3]. The second dimensions match, but because b has a first dimension with only a single element that element of b is "broadcast" along the first dimension of A (two elements).


答:
Your program will crash because at 61int divisonByZero = 1 / (61 - n);will become int divisonByZero = 1 / 0; Which is a division by zero and raises an exception.

You can use a try-catch to catch the exception but I don't know if you see this as a condition. It's also bad practice to use an exception for this. But below you find how you would implement such a version.

```<code>public class Main {

   public static void printNumbers(int n, int stop) {
       System.out.println(n);
       try {
          int divisonByZero = 1 / (stop - n);
          printNumbers(n + 1, stop);
       } catch (ArithmeticException e) {
          System.out.println("program is terminated");
       }
   }

   public static void main(String[] args) {
       printNumbers(Integer.parseInt(args[0]), Integer.parseInt(args[1]));
   }
}
</code>```

Title: Print numbers in specific range without using any loop or conditions (Java)

Body:
Your program will crash because at 61int divisonByZero = 1 / (61 - n);will become int divisonByZero = 1 / 0; Which is a division by zero and raises an exception.

You can use a try-catch to catch the exception but I don't know if you see this as a condition. It's also bad practice to use an exception for this. But below you find how you would implement such a version.

public class Main {

   public static void printNumbers(int n, int stop) {
       System.out.println(n);
       try {
          int divisonByZero = 1 / (stop - n);
          printNumbers(n + 1, stop);
       } catch (ArithmeticException e) {
          System.out.println("program is terminated");
       }
   }

   public static void main(String[] args) {
       printNumbers(Integer.parseInt(args[0]), Integer.parseInt(args[1]));
   }
}


问:
How can we pass current date-time to a angularjs function in a HTML page?
I am trying to get present date and pass it to the function - same-or-earlier-than But in the run-time, it does not pass date value to this class.  Below is my html code. I am trying to get date from javascript and printing it for test.
the date is printed, but when passing it to the function, it doesnt work.

```<code>  <div class="row">
 <div class="hh-dock-page-view panel">
 <div class="panel-body">
  <div class="container">
    <h2 class="hh-page-header">Issue Detail</h2>
    <h3 class="hh-action-heading"><span ng-hide="ctrl.readOnly">Edit </span>Details - {{ctrl.returnCurDate()}} - {{ctrl.issue.issue_date}}"</h3>
    <hh-model-form name="issueForm" model="ctrl.issue" page-controller="ctrl" submit-success="ctrl.submitSuccess" hide-actions="ctrl.readOnly">
        <h2 class="hh-page-header extra-margin">{{modelFormCtrl.model.provider_name_spec_prac}} - {{ctrl.issue.issue_date}}</h2>
        <div class="row">
            <div class="col-sm-6">

          <hh-field-messages>
            <label for="issue_date">Issue Date</label>
            <hh-american-date-field
               id="issue_date"
               name="issue_date"
               ng-model="modelFormCtrl.model.issue_date"
               ng-blur="modelFormCtrl.pageController.setStatus(this)"
               ng-disabled="modelFormCtrl.pageController.readOnly"
               same-or-earlier-than="{{ctrl.issue.issue_date}}"
               same-or-earlier-than-msg="Enter a date that is on or before Resolution Date."
               >
            </hh-american-date-field>
        </hh-field-messages>
            <div class="hh-breath"></div>
          </div>
          </div>

    </hh-model-form>
  </div>
</div>
</code>```

and here below is my angularjs file:

```<code>angular.module('Prm')
.controller('IssueDetailController',
['$scope', '$q', '$route', '$location', '$routeParams', 'moment', 'IssueService', 'IssuePriorityService', 'ActivityService',
 'ProviderService', 'DirtyFormCheckingService', 'ConfirmBox', 'ErrorAlertService', 'AlertBoxService', 'DateService',
 'ReferenceTableDataAdapter',
function ($scope, $q, $route, $location, $routeParams, moment, IssueService, IssuePriorityService, ActivityService, ProviderService,
          DirtyFormCheckingService, ConfirmBox, ErrorAlertService, AlertBoxService, DateService,
          ReferenceTableDataAdapter){
    'use strict';
    var ctrl = this,
        isExisting = false,
        issuePriority = null,
        initPromises = [];

    var currentUser = cpm.authentication.user.report_ownership_role_code;
    ctrl.isAdmin = cpm.authentication.user.dss_role_list.split(",").includes('USERADMIN');
    ctrl.readOnly = true;

    var getNameForEdit = function(row) {
        if (ctrl.readOnly) return 'View';
        return 'Edit';
    };

    ctrl.providerAdapter = ReferenceTableDataAdapter('provider');
    ctrl.ownerRoleAdapter = ReferenceTableDataAdapter('dss_report_owner_contact');
    ctrl.providerIssueStatusAdapter = ReferenceTableDataAdapter('provider_issue_status');
    ctrl.providerIssueSiteAdapter = ReferenceTableDataAdapter('provider_issue_site');
    ctrl.providerIssuePriorityAdapter = ReferenceTableDataAdapter('provider_issue_priority');
    ctrl.providerIssueCategoryAdapter = ReferenceTableDataAdapter('provider_issue_category');

    if($routeParams.issue_code) {
        isExisting = true;
        initPromises.push(IssueService.get({id: $routeParams.issue_code}).$promise.then(function (data) {
            ctrl.issue = data;

            // placing this on the controller for the Parent Issue grid (if exists). Grid needs list of objects...
            ctrl.parentActivities = [{'parent_provider_activity':ctrl.issue.parent_provider_activity,
                                      'parent_provider_activity_activity_date':ctrl.issue.parent_provider_activity_activity_date,
                                      'parent_provider_activity_description': ctrl.issue.parent_provider_activity_description}];
        }));

    } else {
        ctrl.issue = IssueService.wrapData({
            description: '',
            resolution: '',
            status: 'N',
            site: '',
            priority: 'N',
            category: '',
            provider: $routeParams.provider_code,
            issue_date: new Date(),
            owner_role: currentUser
        });

        ctrl.hide_resolution = true;
        //ctrl.issue_date = new Date();

        /* An issue may be created from a provider */
        if($routeParams.provider_code) {
            initPromises.push(ProviderService.get({id: $routeParams.provider_code}).$promise.then(function (data) {
                ctrl.issue.provider = data.provider_code;
            }));
        }
    }

    /* Issues can have their due dates set based on their priority */
    initPromises.push(IssuePriorityService.getPrioritiesMap().then(function (priorities) {
        issuePriority = priorities;
        if(!isExisting) {
            ctrl.issue.due_date = moment(DateService.todayAsUtcDate()).add(issuePriority.N, 'day').toDate();
        }
    }));

    /* Initialization */
    $q.all(initPromises).then(function () {
        /* Allow editing existing record only by owner & admins */
        if(!isExisting || ctrl.isAdmin || ctrl.issue.owner_role === cpm.authentication.user.report_ownership_role_code) {
            ctrl.readOnly = false;
        }

        // TODO: when grid actions are added
        // ctrl.activitiesGrid.hideAddButton = ctrl.readOnly;

        DirtyFormCheckingService($scope, 'issueForm', ctrl.issue);
    });

    ctrl.setDueDate = function (newModel, newCode) {
        ctrl.issue.due_date = moment(ctrl.issue.issue_date).add(issuePriority[newCode], 'day').toDate();
    };

    ctrl.setResolutionDate = function (newModel, newCode) {
        // ctrl.hide_resolution = (newCode !== 'R');
        if (newCode == 'R') {
            ctrl.issue.resolution_date = DateService.todayAsUtcDate();
        } else {
            ctrl.issue.resolution_date = null;
        }
    };

    $scope.$watch('ctrl.issue.status', function (newCode) {
        if(ctrl.issue) {
            ctrl.hide_resolution = (newCode !== 'R');
        }
    });

    ctrl.setStatus = function (event){
        if (ctrl.issue.resolution_date) {
            ctrl.issue.status = "R";
        } else {
            ctrl.issue.status = "N";
        }
    };

    ctrl.submitSuccess = function() {
        $location.url('/');
    };

    ctrl.parentActivityConfig = {
        modelSetName: 'parentIssues',
        actions: {
            editRow: {
                label: function(row) {
                    return ctrl.readOnly ? 'View' : 'Edit';
                },
                active: true,
                callback: function(row){
                    $location.path('/activity/'+ctrl.issue.parent_provider_activity);
                }
            },
            deleteRow: {
                active: false
            }
        },
        rowActions: ['editRow'],
        columns: [
            {col_description: 'Activity Date',
             datatype: 'date',
             model_field: 'parent_provider_activity_activity_date',
             field_type: 'american_date',
             field_name: 'activityDate'
            },
            {col_description: 'Description',
             datatype: 'text',
             model_field: 'parent_provider_activity_description',
             field_type: 'text',
             field_name: 'description'
            },
        ]
    };

    ctrl.activitiesTableConfig = {
        modelSetName: "activities",
        serializerChildName: 'activities',
        actions: {
            addRow: {
                label: 'Add Activity',
                callback: function(){
                    $location.path('/provider/'+ctrl.issue.provider+'/add_activity/'+ctrl.issue.provider_issue_code);
                },
                active: function(row) {return !ctrl.readOnly;}
            },
            editRow: {
                label: function(row) {
                    return getNameForEdit(row.modelSet);
                },
                active: true,
                callback: function(row){
                    $location.path('/activity/'+row.modelSet.provider_activity_code);
                }
            },
            deleteRow: {
                active: function(row) {return !ctrl.readOnly;},
                callback: function(row){
                    _.pull(ctrl.issue.activities, row.modelSet);
                }
            }
        },
        rowActions: ['editRow', 'deleteRow'],
        columns: [
            {col_description: 'Date',
             datatype: 'date',
             model_field: 'activity_date',
             field_type: 'american-date',
             field_name: 'activity_date'
         },
            {col_description: 'Type',
             datatype: 'text',
             model_field: 'provider_activity_type_description',
             field_type: 'text',
             field_name: 'provider_activity_type_description'
         },
            {col_description: 'Notes',
             datatype: 'text',
             model_field: 'description',
             field_type: 'text',
             field_name: 'description'
         },
            {col_description: 'Owner',
             datatype: 'text',
             model_field: 'owner_comp_name',
             field_type: 'text',
             field_name: 'owner_comp_name'
         },
        ]
    };
}]);
</code>```

答:
I'm trying my best to understand your question, but there's a lot of code to look through here. I do understand that you're trying to pass the current date to a function named "same-or-earlier than." However I can't seem to find a function with that name in your controller file.

I'm assuming that you've got a custom directive (attribute directive) that accepts the current date.

Either way, a simple solution for your problem of passing the current date could be to write a small function that when invoked returns the date using Javascript's native "Date" object.

Perhaps like this in your controller:

```<code>ctrl.returnCurDate = function() {
  return new Date();
};
</code>```

That way in your markup, you can invoke the method we've defined since it's attached to the scope of your controller.

```<code>same-or-earlier-than = "ctrl.returnCurDate()"
</code>```

I hope I'm answering your problem in a relevant fashion, please feel free to ask further if I've misunderstood your question.

Best of luck.

P.S. Inherently there are some pain-in-the-butt formatting issues that come with using JS's native Date constructor, I would consider using a library such as "Moment.js" to relieve you of parsing the returned value when invoking:

```<code>new Date();
</code>```

Body:
I am trying to get present date and pass it to the function - same-or-earlier-than But in the run-time, it does not pass date value to this class.  Below is my html code. I am trying to get date from javascript and printing it for test.
the date is printed, but when passing it to the function, it doesnt work.

Issue Detail

Edit Details - {{ctrl.returnCurDate()}} - {{ctrl.issue.issue_date}}"

    <hh-model-form name="issueForm" model="ctrl.issue" page-controller="ctrl" submit-success="ctrl.submitSuccess" hide-actions="ctrl.readOnly">

{{modelFormCtrl.model.provider_name_spec_prac}} - {{ctrl.issue.issue_date}}

          <hh-field-messages>
            Issue Date
            <hh-american-date-field
               id="issue_date"
               name="issue_date"
               ng-model="modelFormCtrl.model.issue_date"
               ng-blur="modelFormCtrl.pageController.setStatus(this)"
               ng-disabled="modelFormCtrl.pageController.readOnly"
               same-or-earlier-than="{{ctrl.issue.issue_date}}"
               same-or-earlier-than-msg="Enter a date that is on or before Resolution Date."
               >
            </hh-american-date-field>
        </hh-field-messages>

    </hh-model-form>

and here below is my angularjs file:

angular.module('Prm')
.controller('IssueDetailController',
['$scope', '$q', '$route', '$location', '$routeParams', 'moment', 'IssueService', 'IssuePriorityService', 'ActivityService',
 'ProviderService', 'DirtyFormCheckingService', 'ConfirmBox', 'ErrorAlertService', 'AlertBoxService', 'DateService',
 'ReferenceTableDataAdapter',
function ($scope, $q, $route, $location, $routeParams, moment, IssueService, IssuePriorityService, ActivityService, ProviderService,
          DirtyFormCheckingService, ConfirmBox, ErrorAlertService, AlertBoxService, DateService,
          ReferenceTableDataAdapter){
    'use strict';
    var ctrl = this,
        isExisting = false,
        issuePriority = null,
        initPromises = [];

    var currentUser = cpm.authentication.user.report_ownership_role_code;
    ctrl.isAdmin = cpm.authentication.user.dss_role_list.split(",").includes('USERADMIN');
    ctrl.readOnly = true;

    var getNameForEdit = function(row) {
        if (ctrl.readOnly) return 'View';
        return 'Edit';
    };

    ctrl.providerAdapter = ReferenceTableDataAdapter('provider');
    ctrl.ownerRoleAdapter = ReferenceTableDataAdapter('dss_report_owner_contact');
    ctrl.providerIssueStatusAdapter = ReferenceTableDataAdapter('provider_issue_status');
    ctrl.providerIssueSiteAdapter = ReferenceTableDataAdapter('provider_issue_site');
    ctrl.providerIssuePriorityAdapter = ReferenceTableDataAdapter('provider_issue_priority');
    ctrl.providerIssueCategoryAdapter = ReferenceTableDataAdapter('provider_issue_category');

    if($routeParams.issue_code) {
        isExisting = true;
        initPromises.push(IssueService.get({id: $routeParams.issue_code}).$promise.then(function (data) {
            ctrl.issue = data;

            // placing this on the controller for the Parent Issue grid (if exists). Grid needs list of objects...
            ctrl.parentActivities = [{'parent_provider_activity':ctrl.issue.parent_provider_activity,
                                      'parent_provider_activity_activity_date':ctrl.issue.parent_provider_activity_activity_date,
                                      'parent_provider_activity_description': ctrl.issue.parent_provider_activity_description}];
        }));

    } else {
        ctrl.issue = IssueService.wrapData({
            description: '',
            resolution: '',
            status: 'N',
            site: '',
            priority: 'N',
            category: '',
            provider: $routeParams.provider_code,
            issue_date: new Date(),
            owner_role: currentUser
        });

        ctrl.hide_resolution = true;
        //ctrl.issue_date = new Date();

        /* An issue may be created from a provider */
        if($routeParams.provider_code) {
            initPromises.push(ProviderService.get({id: $routeParams.provider_code}).$promise.then(function (data) {
                ctrl.issue.provider = data.provider_code;
            }));
        }
    }

    /* Issues can have their due dates set based on their priority */
    initPromises.push(IssuePriorityService.getPrioritiesMap().then(function (priorities) {
        issuePriority = priorities;
        if(!isExisting) {
            ctrl.issue.due_date = moment(DateService.todayAsUtcDate()).add(issuePriority.N, 'day').toDate();
        }
    }));

    /* Initialization */
    $q.all(initPromises).then(function () {
        /* Allow editing existing record only by owner & admins */
        if(!isExisting || ctrl.isAdmin || ctrl.issue.owner_role === cpm.authentication.user.report_ownership_role_code) {
            ctrl.readOnly = false;
        }

        // TODO: when grid actions are added
        // ctrl.activitiesGrid.hideAddButton = ctrl.readOnly;

        DirtyFormCheckingService($scope, 'issueForm', ctrl.issue);
    });

    ctrl.setDueDate = function (newModel, newCode) {
        ctrl.issue.due_date = moment(ctrl.issue.issue_date).add(issuePriority[newCode], 'day').toDate();
    };

    ctrl.setResolutionDate = function (newModel, newCode) {
        // ctrl.hide_resolution = (newCode !== 'R');
        if (newCode == 'R') {
            ctrl.issue.resolution_date = DateService.todayAsUtcDate();
        } else {
            ctrl.issue.resolution_date = null;
        }
    };

    $scope.$watch('ctrl.issue.status', function (newCode) {
        if(ctrl.issue) {
            ctrl.hide_resolution = (newCode !== 'R');
        }
    });

    ctrl.setStatus = function (event){
        if (ctrl.issue.resolution_date) {
            ctrl.issue.status = "R";
        } else {
            ctrl.issue.status = "N";
        }
    };

    ctrl.submitSuccess = function() {
        $location.url('/');
    };

    ctrl.parentActivityConfig = {
        modelSetName: 'parentIssues',
        actions: {
            editRow: {
                label: function(row) {
                    return ctrl.readOnly ? 'View' : 'Edit';
                },
                active: true,
                callback: function(row){
                    $location.path('/activity/'+ctrl.issue.parent_provider_activity);
                }
            },
            deleteRow: {
                active: false
            }
        },
        rowActions: ['editRow'],
        columns: [
            {col_description: 'Activity Date',
             datatype: 'date',
             model_field: 'parent_provider_activity_activity_date',
             field_type: 'american_date',
             field_name: 'activityDate'
            },
            {col_description: 'Description',
             datatype: 'text',
             model_field: 'parent_provider_activity_description',
             field_type: 'text',
             field_name: 'description'
            },
        ]
    };

    ctrl.activitiesTableConfig = {
        modelSetName: "activities",
        serializerChildName: 'activities',
        actions: {
            addRow: {
                label: 'Add Activity',
                callback: function(){
                    $location.path('/provider/'+ctrl.issue.provider+'/add_activity/'+ctrl.issue.provider_issue_code);
                },
                active: function(row) {return !ctrl.readOnly;}
            },
            editRow: {
                label: function(row) {
                    return getNameForEdit(row.modelSet);
                },
                active: true,
                callback: function(row){
                    $location.path('/activity/'+row.modelSet.provider_activity_code);
                }
            },
            deleteRow: {
                active: function(row) {return !ctrl.readOnly;},
                callback: function(row){
                    _.pull(ctrl.issue.activities, row.modelSet);
                }
            }
        },
        rowActions: ['editRow', 'deleteRow'],
        columns: [
            {col_description: 'Date',
             datatype: 'date',
             model_field: 'activity_date',
             field_type: 'american-date',
             field_name: 'activity_date'
         },
            {col_description: 'Type',
             datatype: 'text',
             model_field: 'provider_activity_type_description',
             field_type: 'text',
             field_name: 'provider_activity_type_description'
         },
            {col_description: 'Notes',
             datatype: 'text',
             model_field: 'description',
             field_type: 'text',
             field_name: 'description'
         },
            {col_description: 'Owner',
             datatype: 'text',
             model_field: 'owner_comp_name',
             field_type: 'text',
             field_name: 'owner_comp_name'
         },
        ]
    };
}]);

Body:
I'm trying my best to understand your question, but there's a lot of code to look through here. I do understand that you're trying to pass the current date to a function named "same-or-earlier than." However I can't seem to find a function with that name in your controller file.

I'm assuming that you've got a custom directive (attribute directive) that accepts the current date.

Either way, a simple solution for your problem of passing the current date could be to write a small function that when invoked returns the date using Javascript's native "Date" object.

Perhaps like this in your controller:

ctrl.returnCurDate = function() {
  return new Date();
};

That way in your markup, you can invoke the method we've defined since it's attached to the scope of your controller.

same-or-earlier-than = "ctrl.returnCurDate()"

I hope I'm answering your problem in a relevant fashion, please feel free to ask further if I've misunderstood your question.

Best of luck.

P.S. Inherently there are some pain-in-the-butt formatting issues that come with using JS's native Date constructor, I would consider using a library such as "Moment.js" to relieve you of parsing the returned value when invoking:

new Date();


问:
Disable console logs in isomorphic-fetch
I am using isomorphic-fetch https://github.com/matthew-andrews/isomorphic-fetch
and every time a response is returned whether successful or failed, I see a console log which falls under the debug category. Whence does it come? Can it be library specific? I couldn't find it in library source though. Or is it about Fetch API?</p>

答:
It's not related to isomorphic-fetch library. It is a feature directly offered by browsers (at least in Chrome and Firefox).

Chrome

For google-chrome you can disable it using the Log XMLHttpRequests checkbox inside the Developer tools "Console Setting":

https://developers.google.com/web/tools/chrome-devtools/console/#additional_settings

Open the DevTools settings, go to the General tab, and scroll down to the Console section for further Console settings.

Firefox

For firefox you have the Net > XHR setting in the toolbar of the Console tab:

https://developer.mozilla.org/en-US/docs/Tools/Web_Console/Console_messages#Filtering_and_searching

  To see only messages of particular categories, click the button labeled with that category ("Net", "CSS", and so on). Clicking the main part of the button toggles that category on or off, while clicking the arrow on the right gives you more fine-grained filter options within that category:

```<code>Net
- Errors
- Warnings
- XHR
- Log
...
</code>```

Body:
It's not related to isomorphic-fetch library. It is a feature directly offered by browsers (at least in Chrome and Firefox).

Chrome

For google-chrome you can disable it using the Log XMLHttpRequests checkbox inside the Developer tools "Console Setting":

https://developers.google.com/web/tools/chrome-devtools/console/#additional_settings

Open the DevTools settings, go to the General tab, and scroll down to the Console section for further Console settings.

Firefox

For firefox you have the Net > XHR setting in the toolbar of the Console tab:

https://developer.mozilla.org/en-US/docs/Tools/Web_Console/Console_messages#Filtering_and_searching

  To see only messages of particular categories, click the button labeled with that category ("Net", "CSS", and so on). Clicking the main part of the button toggles that category on or off, while clicking the arrow on the right gives you more fine-grained filter options within that category:

Net
- Errors
- Warnings
- XHR
- Log
...


问:
Reactjs, Typescript - Casting props in typescript - React Component
I'm using typescript 2.3.4 with React. I'm getting the error TS7006: Parameter 'props' implicitly has an 'any' type. Whats the correct way to cast props in typescript?

any help is appreciated.

```<code>interface State {
    name: string;
}

interface Props {

}

export class Profile extends React.Component<Props, State> {
    public state: State;
    public props: Props;
    constructor(props){
        super(props);
            this.state = {
               name: 'baz111'
            };
    }

    public render() {
        return (
            <section>
             <section>
                 <h3>profile 1</h3>
                 <div>baz</div>
             </section>
                <section>
                    <h3>profile 2</h3>
                    <div>{this.state.name}</div>
                </section>
            </section>
        )

    }
}
</code>```

答:
You're receiving this error because the parameter to your constructor doesn't have a type annotation. It should be:

```<code>constructor(props: Props) {
    super(props);
    this.state = {
       name: 'baz111'
    };
}
</code>```

When a function parameter doesn't have a type annotation it will implicitly be typed any. When you have the noImplicitAny option on in your tsconfig.json file enabled, it will result in an error when such a case (your case) happens.

On an other note, you don't have to redeclare the state and props fields, you can just leave them out.

Body:
I'm using typescript 2.3.4 with React. I'm getting the error TS7006: Parameter 'props' implicitly has an 'any' type. Whats the correct way to cast props in typescript?

any help is appreciated.

interface State {
    name: string;
}

interface Props {

}

export class Profile extends React.Component<Props, State> {
    public state: State;
    public props: Props;
    constructor(props){
        super(props);
            this.state = {
               name: 'baz111'
            };
    }

    public render() {
        return (

profile 1

baz

profile 2

{this.state.name}

        )

    }
}

Body:
You're receiving this error because the parameter to your constructor doesn't have a type annotation. It should be:

constructor(props: Props) {
    super(props);
    this.state = {
       name: 'baz111'
    };
}

When a function parameter doesn't have a type annotation it will implicitly be typed any. When you have the noImplicitAny option on in your tsconfig.json file enabled, it will result in an error when such a case (your case) happens.

On an other note, you don't have to redeclare the state and props fields, you can just leave them out.


问:
How to add days to Date?
How to add days to current Date using JavaScript? Does JavaScript have a built in function like .NET's AddDay()?

答:
Our team considers date-fns the best library in this space.  It treats dates as immutable (Moment.js will probably never adopt immutability), it's faster, and can be loaded modularly.

```<code>const newDate = DateFns.addDays(oldDate, 2);
</code>```

OwnerDisplayName: Ashesh

Title: How to add days to Date?

Body:
Our team considers date-fns the best library in this space.  It treats dates as immutable (Moment.js will probably never adopt immutability), it's faster, and can be loaded modularly.

const newDate = DateFns.addDays(oldDate, 2);