问:
How to combine opencv and gstreamer?
I completed video streaming jetson tx1 and My PC

now I have opencvcode of video processing

so, I want to adapt opencv code to gstreamer in jetson

Next code is PC-jetson tx1 streaming and opencv code

//jetson code//

CLIENT_IP=10.100.0.70

gst-launch-1.0 nvcamerasrc fpsRange="30 30" intent=3 ! nvvidconv flip-method=6 \

! 'video/x-raw(memory:NVMM), width=(int)1920, height=(int)1080, format=(string)I420, framerate=(fraction)30/1' ! \

omxh264enc control-rate=2 bitrate=4000000 ! 'video/x-h264, stream-format=(string)byte-stream' ! \

h264parse ! rtph264pay mtu=1400 ! udpsink host=$CLIENT_IP port=5000 sync=false async=false

// PC code//

gst-launch-1.0 udpsrc port=5000 ! application/x-rtp,encoding-name=H264,payload=96 ! rtph264depay ! h264parse ! queue ! avdec_h264 ! xvimagesink sync=false async=false -e

opencv code

#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

int main()
{
    cv::Mat img,img_gray;

    cv::VideoCapture input(0);

    for(;;)
    {
    if (!input.read(img))
        break;

    cv::cvtColor(img, img_gray, CV_RGB2GRAY);

    cv::imshow("img", img);
    cv::imshow("gray", img_gray);
    char c = cv::waitKey(30);

    if (c == 27)
        break;
    }
} ```

答:
OpenCV support VideoCapture and VideoWriter gstreamer pipes support gstreamer pipes. You need to pass your pipe as a parameter finishing with appsink/ starting for appsrc.

```<code>char* inputPipe = "nvcamerasrc fpsRange="30 30" intent=3 ! nvvidconv flip-method=6 ! 'video/x-raw(memory:NVMM), width=(int)1920, height=(int)1080, format=(string)I420, framerate=(fraction)30/1' ! videoconvert ! appsink";
char* outputPipe = "appsrc ! videoconvert ! omxh264enc control-rate=2 bitrate=4000000 ! 'video/x-h264, stream-format=(string)byte-stream' ! 264parse ! rtph264pay mtu=1400 ! udpsink host=$CLIENT_IP port=5000 sync=false async=false";

cv::VideoCapture input(inputPipe);
cv::VideoWriter  writer(outputPipe, 0, 25.0, cv::Size(1920,1080));
for(;;)
{
if (!input.read(img))
    break;

cv::cvtColor(img, img_gray, CV_RGB2GRAY);
//cv::imshow("img", img);
//cv::imshow("gray", img_gray);
// instead of imshow pass the frame to VideoWriter
writer.write(img_gray);

char c = cv::waitKey(30);

if (c == 27)
    break;
}
</code>```

Performance tip:

OpenCv uses VideoCapture uses BGR colorspace and nvcamerasrc provides output at I420 colorspace.
If you use the following pipe videoconvert element will use too much CPU.

```<code>char* inputPipe = "nvcamerasrc fpsRange="30 30" intent=3 ! nvvidconv flip-method=6 ! 'video/x-raw(memory:NVMM), width=(int)1920, height=(int)1080, format=(string)I420, framerate=(fraction)30/1' ! videoconvert ! appsink";
</code>```

Instead, if you convert colorspace to BGRx or RGBA with nvvidconv, the colorspace conversion will be done on specialized hardware and the CPU usage will be significantly lower

```<code> char* inputPipe = "nvcamerasrc fpsRange="30 30" intent=3 ! nvvidconv flip-method=6 ! 'video/x-raw(memory:NVMM), width=(int)1920, height=(int)1080, format=(string)BGRx, framerate=(fraction)30/1' ! videoconvert ! appsink";
</code>```

Title: How to combine opencv and gstreamer?

Body:
OpenCV support VideoCapture and VideoWriter gstreamer pipes support gstreamer pipes. You need to pass your pipe as a parameter finishing with appsink/ starting for appsrc.

char* inputPipe = "nvcamerasrc fpsRange="30 30" intent=3 ! nvvidconv flip-method=6 ! 'video/x-raw(memory:NVMM), width=(int)1920, height=(int)1080, format=(string)I420, framerate=(fraction)30/1' ! videoconvert ! appsink";
char* outputPipe = "appsrc ! videoconvert ! omxh264enc control-rate=2 bitrate=4000000 ! 'video/x-h264, stream-format=(string)byte-stream' ! 264parse ! rtph264pay mtu=1400 ! udpsink host=$CLIENT_IP port=5000 sync=false async=false";

cv::VideoCapture input(inputPipe);
cv::VideoWriter  writer(outputPipe, 0, 25.0, cv::Size(1920,1080));
for(;;)
{
if (!input.read(img))
    break;

cv::cvtColor(img, img_gray, CV_RGB2GRAY);
//cv::imshow("img", img);
//cv::imshow("gray", img_gray);
// instead of imshow pass the frame to VideoWriter
writer.write(img_gray);

char c = cv::waitKey(30);

if (c == 27)
    break;
}

Performance tip:

OpenCv uses VideoCapture uses BGR colorspace and nvcamerasrc provides output at I420 colorspace.
If you use the following pipe videoconvert element will use too much CPU.

char* inputPipe = "nvcamerasrc fpsRange="30 30" intent=3 ! nvvidconv flip-method=6 ! 'video/x-raw(memory:NVMM), width=(int)1920, height=(int)1080, format=(string)I420, framerate=(fraction)30/1' ! videoconvert ! appsink";

Instead, if you convert colorspace to BGRx or RGBA with nvvidconv, the colorspace conversion will be done on specialized hardware and the CPU usage will be significantly lower

 char* inputPipe = "nvcamerasrc fpsRange="30 30" intent=3 ! nvvidconv flip-method=6 ! 'video/x-raw(memory:NVMM), width=(int)1920, height=(int)1080, format=(string)BGRx, framerate=(fraction)30/1' ! videoconvert ! appsink";


来源: stackexchange

问:
Login Page shared preference not working as expected
I have an android app in which I am using shared preferences for login.Until now I have a flow like user logs in..when login is successful the credentials are stored.And when the user opens the app again the username password appears in the edit text.I have a login button and have setonclicklistner to login and jump to the inner activities.
I am trying a flow like when the user logs in successfully..and the app is restarted the credentials are stored..it should automatically go the next activity(inner activity).
What I have tried until now..

In oncreate the onclicklistner that opens next activity if credentials are good

```<code>buttonlogin.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if(etemail.getText().toString().equals("") && etpass.getText().toString().equals(""))
                {
                    Toast.makeText(getApplicationContext(),"Enter your username and Password",Toast.LENGTH_LONG).show();
                }
                else
                {
                    load_data();
                }

            }
        });
</code>```

Code of shared pref

```<code>private void savePreferences() {
    SharedPreferences settings = getSharedPreferences(PREFS_NAME,
            Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();

    // Edit and commit
    UnameValue = etemail.getText().toString();
    PasswordValue = etpass.getText().toString();
    editor.putString(PREF_UNAME, UnameValue);
    editor.putString(PREF_PASSWORD, PasswordValue);
    editor.commit();
}

private void loadPreferences()
{
    SharedPreferences settings = getSharedPreferences(PREFS_NAME,
            Context.MODE_PRIVATE);

    // Get value
    UnameValue = settings.getString(PREF_UNAME, DefaultUnameValue);
    PasswordValue = settings.getString(PREF_PASSWORD, DefaultPasswordValue);

    etemail.setText(UnameValue);
    etpass.setText(PasswordValue);
}
</code>```

What should I do in order to achieve this??if username password is stored automatically open next activity instead of clicking login button??
Thanks

答:
you can use contains(String key) in SharedPreferences class
could be done in loadPreferences()

if login is only used to allow access to the next activity, then you don't need to simulate the button click, but if the click loads other data based on the provided username/password then you have to do it using performClick() in Button class.

so your code may look like this:

```<code>private void loadPreferences()
{
    SharedPreferences settings = getSharedPreferences(PREFS_NAME,
            Context.MODE_PRIVATE);

    if(settings.contains(PREF_UNAME) && settings.contains(PREF_PASSWORD)){
        //you can start the 2nd activity directly here
        //Intent intent = new Intent (...)
        //startActivity(intent);
        //finish();

        //OR

        //load data into edittexts and programatically click the login button
        UnameValue = settings.getString(PREF_UNAME, DefaultUnameValue);
        PasswordValue = settings.getString(PREF_PASSWORD, DefaultPasswordValue);

        etemail.setText(UnameValue);
        etpass.setText(PasswordValue);

        //here it will click the button as if the user did it.
        btnLogin.performClick();
    }//contains
}
</code>```

Side note: it's not good practice (not secure) to store passwords in SharedPreferences specially plain-text, not encrypted

ContentLicense: CC BY-SA 3.0

Body:
I have an android app in which I am using shared preferences for login.Until now I have a flow like user logs in..when login is successful the credentials are stored.And when the user opens the app again the username password appears in the edit text.I have a login button and have setonclicklistner to login and jump to the inner activities.
I am trying a flow like when the user logs in successfully..and the app is restarted the credentials are stored..it should automatically go the next activity(inner activity).
What I have tried until now..

In oncreate the onclicklistner that opens next activity if credentials are good

buttonlogin.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if(etemail.getText().toString().equals("") && etpass.getText().toString().equals(""))
                {
                    Toast.makeText(getApplicationContext(),"Enter your username and Password",Toast.LENGTH_LONG).show();
                }
                else
                {
                    load_data();
                }

            }
        });

Code of shared pref

private void savePreferences() {
    SharedPreferences settings = getSharedPreferences(PREFS_NAME,
            Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();

    // Edit and commit
    UnameValue = etemail.getText().toString();
    PasswordValue = etpass.getText().toString();
    editor.putString(PREF_UNAME, UnameValue);
    editor.putString(PREF_PASSWORD, PasswordValue);
    editor.commit();
}

private void loadPreferences()
{
    SharedPreferences settings = getSharedPreferences(PREFS_NAME,
            Context.MODE_PRIVATE);

    // Get value
    UnameValue = settings.getString(PREF_UNAME, DefaultUnameValue);
    PasswordValue = settings.getString(PREF_PASSWORD, DefaultPasswordValue);

    etemail.setText(UnameValue);
    etpass.setText(PasswordValue);
}

What should I do in order to achieve this??if username password is stored automatically open next activity instead of clicking login button??
Thanks

Body:
you can use contains(String key) in SharedPreferences class
could be done in loadPreferences()

if login is only used to allow access to the next activity, then you don't need to simulate the button click, but if the click loads other data based on the provided username/password then you have to do it using performClick() in Button class.

so your code may look like this:

private void loadPreferences()
{
    SharedPreferences settings = getSharedPreferences(PREFS_NAME,
            Context.MODE_PRIVATE);

    if(settings.contains(PREF_UNAME) && settings.contains(PREF_PASSWORD)){
        //you can start the 2nd activity directly here
        //Intent intent = new Intent (...)
        //startActivity(intent);
        //finish();

        //OR

        //load data into edittexts and programatically click the login button
        UnameValue = settings.getString(PREF_UNAME, DefaultUnameValue);
        PasswordValue = settings.getString(PREF_PASSWORD, DefaultPasswordValue);

        etemail.setText(UnameValue);
        etpass.setText(PasswordValue);

        //here it will click the button as if the user did it.
        btnLogin.performClick();
    }//contains
}

Side note: it's not good practice (not secure) to store passwords in SharedPreferences specially plain-text, not encrypted


问:
Ho do I mock external functions used in recursive functions?
Take this function for example:

```<code>public static int[] mergeSort(int[] array, int lo, int hi) {
        if (lo == hi) {
            return array;
        }
    int mid = (lo + hi) / 2;
    mergeSort(array, lo, mid);
    mergeSort(array, mid, hi);
    merge(array, lo, mid + 1, hi);

    return array;
}
</code>```

As you can see there is the function merge which I want to mock in my test.
It is possible?

答:
Thanks guys,
The reason why I want to mock is:

Let's assume the followings:

this function, merge (or any) will be used in 100 functions

merge is modified causing unexpected result

100 tests are failing because merge is failing.

instead of having one test fail, the one who test merge function, we have 100 tests failing because merge is failing.

Body:
Take this function for example:

public static int[] mergeSort(int[] array, int lo, int hi) {
        if (lo == hi) {
            return array;
        }
    int mid = (lo + hi) / 2;
    mergeSort(array, lo, mid);
    mergeSort(array, mid, hi);
    merge(array, lo, mid + 1, hi);

    return array;
}

As you can see there is the function merge which I want to mock in my test.
It is possible?


问:
convert REGEXP to LIKE in MYSQL query
I have MYSQL query that looks as below

```<code>select * from table1 where host REGEXP 'host1';
</code>```

I want to execute the same query using LIKE
Please suggest how it can be achieved

答:
You can try using %</p>

```<code>select * from table1 where host LIKE '%host1%';
</code>```

Title: convert REGEXP to LIKE in MYSQL query

Body:
I have MYSQL query that looks as below

select * from table1 where host REGEXP 'host1';

I want to execute the same query using LIKE
Please suggest how it can be achieved

Body:
You can try using %

select * from table1 where host LIKE '%host1%';


问:
Capistrano Puma AWS can't seem to pass RVM check
I am having trouble connecting Rails webapp to Amazon AWS codedeploy this is the result of:

pachanga:~/workspace (master) $ ssh -v deploy@13.59.79.103

```<code>OpenSSH_6.6.1, OpenSSL 1.0.1f 6 Jan 2014
debug1: Reading configuration data /home/ubuntu/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to 13.59.79.103 [13.59.79.103] port 22.
debug1: Connection established.
debug1: identity file /home/ubuntu/.ssh/id_rsa type 1
debug1: identity file /home/ubuntu/.ssh/id_rsa-cert type -1
debug1: identity file /home/ubuntu/.ssh/id_dsa type -1
debug1: identity file /home/ubuntu/.ssh/id_dsa-cert type -1
debug1: identity file /home/ubuntu/.ssh/id_ecdsa type -1
debug1: identity file /home/ubuntu/.ssh/id_ecdsa-cert type -1
debug1: identity file /home/ubuntu/.ssh/id_ed25519 type -1
debug1: identity file /home/ubuntu/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.8
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu2.2
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.2 pat OpenSSH* compat 0x04000000
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-sha1-etm@openssh.com none
debug1: kex: client->server aes128-ctr hmac-sha1-etm@openssh.com none
debug1: sending SSH2_MSG_KEX_ECDH_INIT
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ECDSA 28:6c:c4:0c:e8:86:ee:c1:70:4e:35:cf:b3:29:86:61
debug1: Host '13.59.79.103' is known and matches the ECDSA host key.
debug1: Found key in /home/ubuntu/.ssh/known_hosts:17
debug1: ssh_ecdsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/ubuntu/.ssh/id_rsa
debug1: Authentications that can continue: publickey
debug1: Trying private key: /home/ubuntu/.ssh/id_dsa
debug1: Trying private key: /home/ubuntu/.ssh/id_ecdsa
debug1: Trying private key: /home/ubuntu/.ssh/id_ed25519
debug1: No more authentication methods to try.
Permission denied (publickey).
</code>```

I am following a tutorial here the tutorial

I have authorized_keys and it has the does have the ssh in it.

答:
I found it
the vi editor was deleting the first character in the ssh</p>

Body:
I am having trouble connecting Rails webapp to Amazon AWS codedeploy this is the result of:

pachanga:~/workspace (master) $ ssh -v deploy@13.59.79.103

OpenSSH_6.6.1, OpenSSL 1.0.1f 6 Jan 2014
debug1: Reading configuration data /home/ubuntu/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to 13.59.79.103 [13.59.79.103] port 22.
debug1: Connection established.
debug1: identity file /home/ubuntu/.ssh/id_rsa type 1
debug1: identity file /home/ubuntu/.ssh/id_rsa-cert type -1
debug1: identity file /home/ubuntu/.ssh/id_dsa type -1
debug1: identity file /home/ubuntu/.ssh/id_dsa-cert type -1
debug1: identity file /home/ubuntu/.ssh/id_ecdsa type -1
debug1: identity file /home/ubuntu/.ssh/id_ecdsa-cert type -1
debug1: identity file /home/ubuntu/.ssh/id_ed25519 type -1
debug1: identity file /home/ubuntu/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.8
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu2.2
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.2 pat OpenSSH* compat 0x04000000
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-sha1-etm@openssh.com none
debug1: kex: client->server aes128-ctr hmac-sha1-etm@openssh.com none
debug1: sending SSH2_MSG_KEX_ECDH_INIT
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ECDSA 28:6c:c4:0c:e8:86:ee:c1:70:4e:35:cf:b3:29:86:61
debug1: Host '13.59.79.103' is known and matches the ECDSA host key.
debug1: Found key in /home/ubuntu/.ssh/known_hosts:17
debug1: ssh_ecdsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/ubuntu/.ssh/id_rsa
debug1: Authentications that can continue: publickey
debug1: Trying private key: /home/ubuntu/.ssh/id_dsa
debug1: Trying private key: /home/ubuntu/.ssh/id_ecdsa
debug1: Trying private key: /home/ubuntu/.ssh/id_ed25519
debug1: No more authentication methods to try.
Permission denied (publickey).

I am following a tutorial here the tutorial

I have authorized_keys and it has the does have the ssh in it.


问:
Why is the ISO standard so for NULL when ANSI_NULL is set to ON?

When ANSI_NULL is set to ON:

SELECT 1 WHERE NULL = NULL return no rows

and SELECT 1 WHERE NULL IS NULL returns one row

I understand the reason why the above queries return what they return. But I am curious to know why the rule is so. Why, according to ISO standard, NULL = NULL is UNKNOWN instead of TRUE? Why 'NULL = NULL gives TRUE' not taken as ISO standard? Is it because NULL value doesn't have a datatype? Or some other reason. I assume there must be some reason.

答:
When SET ANSI_NULLS is OFF, the Equals (=) and Not Equal To (<>) comparison operators do not follow the ISO standard.

https://learn.microsoft.com/en-us/sql/t-sql/statements/set-ansi-nulls-transact-sql

What you describe in the question is exactly what you should expect if ANSI_NULLS is ON

The general standard that applies to NULL in SQL is that you cannot determine the value of NULL, therefore you also cannot know if it is equal to any value (because you are unable to determine one side of the predicate). If you can't figure out if NULL is equal to anything then it also follows that you cannot know if it is unequal either.

This is why SQL provide special methods for handling NULL:

    SELECT 1 WHERE NULL IS NULL

    SELECT 1 WHERE NULL IS NOT NULL


问:
enum vs separate table for storing roles?
I have to implement a role system in my app for authorization. We have around 5 kind of roles in our system.

To maintain these roles we have 2 options,

Alternative #1

1.Create an enum in rails Role model,

enum role: {super_admin: 1, translator: 2, approver: 3, sales_admin: 4, marketing_admin: 5, guest: 6}

2.In the Roles table , now we will have ID user_id role_id

Alternative #2

1.Create 2 models Role and Role_User.

Role table will only contain ID | role_name and Role_User will contain ID | user_id | role_id

Which should be preferred?

答:
An added benefit of the separate table is that users can have multiple roles, if that is something your system requires. Also, storing the different roles in the database should be better for enforcing database-level data integrity, i.e. you can't add nonexistent roles to users.

If you do end up using a separate table for roles and a join table, be sure to add proper indexing to the join table.

Other than that, it really depends on the context and use case. If the system is simple enough, nothing wrong with going the enum way.


问:
How do I add cluster markers to Gmaps4rails?
I was able to add the marker cluster in this format inside of the index.html.erb file. When I decided to add infowindows that is when my map started to break.

```<code><script type = "text/javascript">
    handler = Gmaps.build('Google',
    {markers:
      {clusterer: {
        gridSize: 60,
        maxZoom: 20,
        styles: [ {
          textSize: 10,
          textColor: '#ff0000',
          url: 'assets/creative/m1.png',
          height: 60,
          width: 60 }
        , {
          textSize: 14,
          textColor: '#ffff00',
          url:'assets/creative/m2.png',
          height: 60,
          width: 60 }
        , {
         textSize: 18,
         textColor: '#0000ff',
         url: 'assets/creative/m3.png',
         width: 60,
         height: 60}
        ]}}}
    );
        handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
             markers = handler.addMarkers(<%=raw @hash.to_json %>);
            handler.bounds.extendWith(markers);
            handler.fitMapToBounds();

        });
</code>```

When I add infowindows to my web app under my custom.js.coffee file as

```<code>class InfoBoxBuilder extends Gmaps.Google.Builders.Marker

create_infowindow: ->
return null unless _.isString @args.infowindow

boxText = document.createElement("div")
boxText.setAttribute('class', 'panel panel-green')
boxText.innerHTML = @args.infowindow
@infowindow = new InfoBox(@infobox(boxText))

infobox: (boxText)->
content: boxText
pixelOffset: new google.maps.Size(-140, 0)
boxStyle:
  width: "280px"

@buildMap = (markers)->
handler = Gmaps.build 'Google', { builders: { Marker: InfoBoxBuilder}
}
handler = Gmaps.build 'Google', { builders: { markers:
      {clusterer: {
        gridSize: 60,
        maxZoom: 20,
        styles: [ {
          textSize: 10,
          textColor: '#ff0000',
          url: 'assets/creative/m1.png',
          height: 60,
          width: 60 }
        , {
          textSize: 14,
          textColor: '#ffff00',
          url:'assets/creative/m2.png',
          height: 60,
          width: 60 }
        , {
         textSize: 18,
         textColor: '#0000ff',
         url: 'assets/creative/m3.png',
         width: 60,
         height: 60}
        ]}}} }  #dependency injection

  handler.buildMap { provider: {}, internal: {id: 'map'} }, ->
  markers = handler.addMarkers(markers)
  handler.bounds.extendWith(markers)
  handler.fitMapToBounds()
</code>```

I get the marker cluster working but I lose the infowindow formatting. How do I inject the infowwindow and the marker cluster code into the custom.coffee.js file.

答:
I finally figured it out. I first converted the infobox builder from coffeescript to plain old vanilla javascript and then after the first dependency injection I added the marker cluster dependency. I added the following code to the view.

```<code>    var InfoBoxBuilder, handler,
      extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
      hasProp = {}.hasOwnProperty;

    InfoBoxBuilder = (function(superClass) {
      extend(InfoBoxBuilder, superClass);

      function InfoBoxBuilder() {
        return InfoBoxBuilder.__super__.constructor.apply(this, arguments);
      }

      InfoBoxBuilder.prototype.create_infowindow = function() {
        var boxText;
        if (!_.isString(this.args.infowindow)) {
          return null;
        }
        boxText = document.createElement("div");
        boxText.setAttribute('class', 'panel panel-green');
        boxText.innerHTML = this.args.infowindow;
        return this.infowindow = new InfoBox(this.infobox(boxText));
      };

      InfoBoxBuilder.prototype.infobox = function(boxText) {
        return {
          content: boxText,
          pixelOffset: new google.maps.Size(-140, 0),
          boxStyle: {
            width: "280px"
          }
        };
      };

      return InfoBoxBuilder;

    })(Gmaps.Google.Builders.Marker);

        handler = Gmaps.build('Google', {
          builders: {
            Marker: InfoBoxBuilder
          },
           markers:
                  {clusterer: {
                    gridSize: 60,
                    maxZoom: 20,
                    styles: [ {
                      textSize: 10,
                      textColor: '#ff0000',
                      url: 'assets/creative/m1.png',
                      height: 60,
                      width: 60 }
                    , {
                      textSize: 14,
                      textColor: '#ffff00',
                      url:'assets/creative/m2.png',
                      height: 60,
                      width: 60 }
                    , {
                     textSize: 18,
                     textColor: '#0000ff',
                     url: 'assets/creative/m3.png',
                     width: 60,
                     height: 60}
                    ]}}
        });
        handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
                         markers = handler.addMarkers(<%=raw @hash.to_json %>);
                        handler.bounds.extendWith(markers);
                        handler.fitMapToBounds();

                    });
</code>```

Now I can have both marker clusters and a custom infowindow for each of my locations.

Body:
I finally figured it out. I first converted the infobox builder from coffeescript to plain old vanilla javascript and then after the first dependency injection I added the marker cluster dependency. I added the following code to the view.

    var InfoBoxBuilder, handler,
      extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
      hasProp = {}.hasOwnProperty;

    InfoBoxBuilder = (function(superClass) {
      extend(InfoBoxBuilder, superClass);

      function InfoBoxBuilder() {
        return InfoBoxBuilder.__super__.constructor.apply(this, arguments);
      }

      InfoBoxBuilder.prototype.create_infowindow = function() {
        var boxText;
        if (!_.isString(this.args.infowindow)) {
          return null;
        }
        boxText = document.createElement("div");
        boxText.setAttribute('class', 'panel panel-green');
        boxText.innerHTML = this.args.infowindow;
        return this.infowindow = new InfoBox(this.infobox(boxText));
      };

      InfoBoxBuilder.prototype.infobox = function(boxText) {
        return {
          content: boxText,
          pixelOffset: new google.maps.Size(-140, 0),
          boxStyle: {
            width: "280px"
          }
        };
      };

      return InfoBoxBuilder;

    })(Gmaps.Google.Builders.Marker);

        handler = Gmaps.build('Google', {
          builders: {
            Marker: InfoBoxBuilder
          },
           markers:
                  {clusterer: {
                    gridSize: 60,
                    maxZoom: 20,
                    styles: [ {
                      textSize: 10,
                      textColor: '#ff0000',
                      url: 'assets/creative/m1.png',
                      height: 60,
                      width: 60 }
                    , {
                      textSize: 14,
                      textColor: '#ffff00',
                      url:'assets/creative/m2.png',
                      height: 60,
                      width: 60 }
                    , {
                     textSize: 18,
                     textColor: '#0000ff',
                     url: 'assets/creative/m3.png',
                     width: 60,
                     height: 60}
                    ]}}
        });
        handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
                         markers = handler.addMarkers(<%=raw @hash.to_json %>);
                        handler.bounds.extendWith(markers);
                        handler.fitMapToBounds();

                    });

Now I can have both marker clusters and a custom infowindow for each of my locations.


问:
Bundle inside Intent from Native cpp application using Binder
I'm trying to call an intent from native cpp code.
Basically, from what i've understand, i have to compose a Parcel to match the exact deserialization sequence from frameworks/base/core/java/android/app/ActivityManagerNative.java ; case BROADCAST_INTENT_TRANSACTION.

The progress so far is that i've received the intent in a Java app, but i have some problem with the bundle payload. I've debugged the Java app and it seems that it reads garbage as an int instead of reading the int which holds the type for the keys of the bundle.

```<code>W/System.err( 1386): java.lang.RuntimeException: Parcel android.os.Parcel@71aa5c5: Unmarshalling unknown type code 6815843 at offset 12
W/System.err( 1386):    at android.os.Parcel.readValue(Parcel.java:2228)
W/System.err( 1386):    at android.os.Parcel.readArrayMapInternal(Parcel.java:2485)
W/System.err( 1386):    at android.os.BaseBundle.unparcel(BaseBundle.java:221
</code>```

Here is the native code used

```<code>#include <unistd.h>
#include <binder/IBinder.h>
#include <binder/IServiceManager.h>
#include <binder/Parcel.h>
#include <utils/String8.h>
#include <assert.h>

namespace android {

static const int BROADCAST_INTENT_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION + 13;

int send_intent()
{
    int NULL_TYPE_ID = 0;

    sp<IServiceManager> sm = defaultServiceManager();
    sp<IBinder> am = sm->checkService(String16("activity"));
    assert(am != NULL);

    Parcel data, reply;
    data.writeInterfaceToken(String16("android.app.IActivityManager"));
    data.writeStrongBinder(NULL);

    /*intent*/

    data.writeString16(String16("com.etc.etc.receiver")); /* action */

    data.writeInt32(NULL_TYPE_ID); /* mData */
    data.writeString16(NULL, 0); /* type */
    data.writeInt32(0); /* flags */
    data.writeString16(NULL, 0); /* package name  */
    data.writeString16(NULL, 0); /* ComponentName - class */

    data.writeInt32(0); /*  no source bounds */
    data.writeInt32(0); /* no categories  */

    /* skip categories */

    data.writeInt32(0); /* no selector  */
    data.writeInt32(0); /* no clip data  */
    data.writeInt32(0); /* content user hint */

    { /* Extras Bundle */
        data.writeInt32(0); /* dummy, will hold length */

        data.writeInt32(0x4C444E42); // 'B' 'N' 'D' 'L'
        int oldPos = data.dataPosition();
        { /* writeMapInternal */
            data.writeInt32(2); /* writeMapInternal - size in pairs */

            data.writeInt32(VAL_STRING); /* type for key */
            data.writeString16(String16("first")); /* key */
            data.writeInt32(VAL_INTEGER); /* type for value */
            data.writeInt32(1337); /* value */

            data.writeInt32(VAL_STRING); /* type for key */
            data.writeString16(String16("second")); /* key */
            data.writeInt32(VAL_INTEGER);   /* type for value */
            data.writeInt32(1338); /* value */

        }
        int newPos = data.dataPosition();
        data.setDataPosition(oldPos - 8); /* eight bytes: size integer + bundle integer  */
        int difference = newPos - oldPos;
        data.writeInt32(difference); /* total length of the bundle */

        data.setDataPosition(newPos);
    }

    data.writeString16(NULL, 0); /* resolvedType */
    data.writeStrongBinder(NULL); /* resultTo */
    data.writeInt32(-1);          /* resultCode */
    data.writeString16(NULL, 0);  /* resultData */
    data.writeInt32(-1);        /* result extras */

    data.writeString16(NULL, 0);  /* grant all permissions */
    data.writeInt32(0); /* appOp */
    data.writeInt32(0); /* serialized */
    data.writeInt32(0); /* sticky */
    data.writeInt32(0); /* userid */

    status_t ret = am->transact(BROADCAST_INTENT_TRANSACTION, data, &reply);

    if (ret == NO_ERROR)
    {
        int32_t exceptionCode = reply.readExceptionCode();
        if (!exceptionCode)
        {
            ALOGD("sendBroadcast succeed\n");
        }
        else
        {
            // An exception was thrown back; fall through to return failure
            ALOGE("sendBroadcastcaught exception %d\n", exceptionCode);
        }
    }
    else
    {
        ALOGD("am->transact returned: %d", ret);
    }

    return 0;
}
};
</code>```

答:
remove code below:

```<code>data.writeInt32(VAL_STRING); /* type for key */
</code>```

the key type is not needed because it is always a string. This field is not marshalled, then don't unmarshall it.

Body:
I'm trying to call an intent from native cpp code.
Basically, from what i've understand, i have to compose a Parcel to match the exact deserialization sequence from frameworks/base/core/java/android/app/ActivityManagerNative.java ; case BROADCAST_INTENT_TRANSACTION.

The progress so far is that i've received the intent in a Java app, but i have some problem with the bundle payload. I've debugged the Java app and it seems that it reads garbage as an int instead of reading the int which holds the type for the keys of the bundle.

W/System.err( 1386): java.lang.RuntimeException: Parcel android.os.Parcel@71aa5c5: Unmarshalling unknown type code 6815843 at offset 12
W/System.err( 1386):    at android.os.Parcel.readValue(Parcel.java:2228)
W/System.err( 1386):    at android.os.Parcel.readArrayMapInternal(Parcel.java:2485)
W/System.err( 1386):    at android.os.BaseBundle.unparcel(BaseBundle.java:221

Here is the native code used

#include <unistd.h>
#include <binder/IBinder.h>
#include <binder/IServiceManager.h>
#include <binder/Parcel.h>
#include <utils/String8.h>
#include <assert.h>

namespace android {

static const int BROADCAST_INTENT_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION + 13;

int send_intent()
{
    int NULL_TYPE_ID = 0;

    sp<IServiceManager> sm = defaultServiceManager();
    sp<IBinder> am = sm->checkService(String16("activity"));
    assert(am != NULL);

    Parcel data, reply;
    data.writeInterfaceToken(String16("android.app.IActivityManager"));
    data.writeStrongBinder(NULL);

    /*intent*/

    data.writeString16(String16("com.etc.etc.receiver")); /* action */

    data.writeInt32(NULL_TYPE_ID); /* mData */
    data.writeString16(NULL, 0); /* type */
    data.writeInt32(0); /* flags */
    data.writeString16(NULL, 0); /* package name  */
    data.writeString16(NULL, 0); /* ComponentName - class */

    data.writeInt32(0); /*  no source bounds */
    data.writeInt32(0); /* no categories  */

    /* skip categories */

    data.writeInt32(0); /* no selector  */
    data.writeInt32(0); /* no clip data  */
    data.writeInt32(0); /* content user hint */

    { /* Extras Bundle */
        data.writeInt32(0); /* dummy, will hold length */

        data.writeInt32(0x4C444E42); // 'B' 'N' 'D' 'L'
        int oldPos = data.dataPosition();
        { /* writeMapInternal */
            data.writeInt32(2); /* writeMapInternal - size in pairs */

            data.writeInt32(VAL_STRING); /* type for key */
            data.writeString16(String16("first")); /* key */
            data.writeInt32(VAL_INTEGER); /* type for value */
            data.writeInt32(1337); /* value */

            data.writeInt32(VAL_STRING); /* type for key */
            data.writeString16(String16("second")); /* key */
            data.writeInt32(VAL_INTEGER);   /* type for value */
            data.writeInt32(1338); /* value */

        }
        int newPos = data.dataPosition();
        data.setDataPosition(oldPos - 8); /* eight bytes: size integer + bundle integer  */
        int difference = newPos - oldPos;
        data.writeInt32(difference); /* total length of the bundle */

        data.setDataPosition(newPos);
    }

    data.writeString16(NULL, 0); /* resolvedType */
    data.writeStrongBinder(NULL); /* resultTo */
    data.writeInt32(-1);          /* resultCode */
    data.writeString16(NULL, 0);  /* resultData */
    data.writeInt32(-1);        /* result extras */

    data.writeString16(NULL, 0);  /* grant all permissions */
    data.writeInt32(0); /* appOp */
    data.writeInt32(0); /* serialized */
    data.writeInt32(0); /* sticky */
    data.writeInt32(0); /* userid */

    status_t ret = am->transact(BROADCAST_INTENT_TRANSACTION, data, &reply);

    if (ret == NO_ERROR)
    {
        int32_t exceptionCode = reply.readExceptionCode();
        if (!exceptionCode)
        {
            ALOGD("sendBroadcast succeed\n");
        }
        else
        {
            // An exception was thrown back; fall through to return failure
            ALOGE("sendBroadcastcaught exception %d\n", exceptionCode);
        }
    }
    else
    {
        ALOGD("am->transact returned: %d", ret);
    }

    return 0;
}
};

Body:
remove code below:

data.writeInt32(VAL_STRING); /* type for key */

the key type is not needed because it is always a string. This field is not marshalled, then don't unmarshall it.


问:
FullText In Microsoft Sql Server - Returning exactly word
Can anyone tell me how to query a fulltext table in Sql Server, and get only exactly matches? Example:

I have those records in a table named "Items":

Bath

  Bathroom

  Test

  Testing

I need to query for Bath and get only 1 record, "bath", excluding the word Bathroom. The same to the word "Test", wich in my context is different to "Testing".

答:
are you searching for bath and test in one query or in different?
if in single, then one of the solutions i see is:

```<code>select top 1 from table where column like '[., ]bath[., ]%'
</code>```

if in different, then union a series of such select's

ContentLicense: CC BY-SA 2.5

Body:
are you searching for bath and test in one query or in different?
if in single, then one of the solutions i see is:

select top 1 from table where column like '[., ]bath[., ]%'

if in different, then union a series of such select's


答:
After storing username and password in sharedpreference editor.putBoolean("hasLoggedin", true);

So it should be like

```<code>    UnameValue = etemail.getText().toString();
    PasswordValue = etpass.getText().toString();
    editor.putString(PREF_UNAME, UnameValue);
    editor.putString(PREF_PASSWORD, PasswordValue);
    editor.putBoolean("hasLoggedin", true);
    editor.commit();
</code>```

then check in Oncreate method like

```<code>    boolean hasLoggedin = sp.getBoolean("hasLoggedin", false);
            if (hasLoggedin) {
                Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                startActivity(intent);
                finish();
}
</code>```

Title: Login Page shared preference not working as expected

Body:
After storing username and password in sharedpreference editor.putBoolean("hasLoggedin", true);

So it should be like

    UnameValue = etemail.getText().toString();
    PasswordValue = etpass.getText().toString();
    editor.putString(PREF_UNAME, UnameValue);
    editor.putString(PREF_PASSWORD, PasswordValue);
    editor.putBoolean("hasLoggedin", true);
    editor.commit();

then check in Oncreate method like

    boolean hasLoggedin = sp.getBoolean("hasLoggedin", false);
            if (hasLoggedin) {
                Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                startActivity(intent);
                finish();
}


问:
R integrate\sapply three variables function
I have the following problem:
I consider a two entries function (fvec) and I want to integrate it wrt one variable (i.e. x). Therefore I do;

```<code>fvec = function(x, y) sapply(x, function(z, y) z-y, y=y)
gvec = function(x) sapply(x, function(y) integrate(fvec, lower=2, upper=3, y=y)$val)
</code>```

Then I eveluate gvec when y=2

```<code>a=gvec(2)
</code>```

and the code works.

However if I introduce a third variable and I try to apply the same procedure:

```<code>fvec = function(x, y, w) sapply(x, function(z, y, w) z-y+w, y=y, w=w)

gvec = function(x,t) sapply(x, function(y,w) integrate(fvec, lower=2, upper=3, y=y, w=w)$val)

b=gvec(2,2)
</code>```

R gives me the following error:

Error in FUN(X[[i]], ...) : argument "w" is missing, with no default

I can't understand why and I would really appreciate your help.
Thanks

答:
you have a typo in this line

```<code>gvec = function(x,t) sapply(x, function(y,w) integrate(fvec, lower=2, upper=3, y=y, w=w)$val)
</code>```

you call the variable t in the beginning and later you call it w. This version works as intended:

```<code>gvec = function(x,t) sapply(x, function(y,w) integrate(fvec, lower=2, upper=3, y=y, w=t)$val)
</code>```

Body:
I have the following problem:
I consider a two entries function (fvec) and I want to integrate it wrt one variable (i.e. x). Therefore I do;

fvec = function(x, y) sapply(x, function(z, y) z-y, y=y)
gvec = function(x) sapply(x, function(y) integrate(fvec, lower=2, upper=3, y=y)$val)

Then I eveluate gvec when y=2

a=gvec(2)

and the code works.

However if I introduce a third variable and I try to apply the same procedure:

fvec = function(x, y, w) sapply(x, function(z, y, w) z-y+w, y=y, w=w)

gvec = function(x,t) sapply(x, function(y,w) integrate(fvec, lower=2, upper=3, y=y, w=w)$val)

b=gvec(2,2)

R gives me the following error:

Error in FUN(X[[i]], ...) : argument "w" is missing, with no default

I can't understand why and I would really appreciate your help.
Thanks

Body:
you have a typo in this line

gvec = function(x,t) sapply(x, function(y,w) integrate(fvec, lower=2, upper=3, y=y, w=w)$val)

you call the variable t in the beginning and later you call it w. This version works as intended:

gvec = function(x,t) sapply(x, function(y,w) integrate(fvec, lower=2, upper=3, y=y, w=t)$val)


问:
If else statement with string JavaScript
I am designing a page where can display score when the users make their choices.

However, this code seems not working and does not show any result in the 'score' field.
My Html code:

```<code><tr>
  <td>
    <div>
      <input list="typeList" name="type" id="type">
      <datalist id="typeList">
        <option value="basketball">
        <option value="soccer">
        <option value="table tenis">
      </datalist>
    </div>
  </td>

  <td><input type="text" id="score" name="score" autocomplete="off"></td>
</tr>
</code>```

My Script is below:

```<code>var type = document.getElementById("type");
var score = document.getElementById("score");

if (type === 0) {
  score.value = 0;
} else if (type === 'basketball') {
  score.value = 1;
} else if (type === 'soccer') {
  score.value = 2;
} else if (type === 'table tenis') {
  score.value = 3;
}
</code>```

答:
You were able to access the element. You just need to use the value attribute of the element. You need to add the event change with dropdown so that it can bind the data in the score textbox when index is changed.

var type = document.getElementById("type");
var score = document.getElementById("score");

type.addEventListener('change', function() {
     if (type.value === 0) {
      score.value = 0;
    } else if (type.value === 'basketball') {
      score.value = 1;
    } else if (type.value === 'soccer') {
      score.value = 2;
    } else if (type.value === 'table tennis') {
      score.value = 3;
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><tr>
  <td>
    <div>
      <input list="typeList" name="type" id="type">
      <datalist id="typeList">
        <option value="basketball">
        <option value="soccer">
        <option value="table tennis">
      </datalist>
    </div>
  </td>

  <td><input type="text" id="score" name="score" autocomplete="off" ></td>
</tr></code>```

Body:
I am designing a page where can display score when the users make their choices.

However, this code seems not working and does not show any result in the 'score' field.
My Html code:

      <input list="typeList" name="type" id="type">
      <datalist id="typeList">
        <option value="basketball">
        <option value="soccer">
        <option value="table tenis">
      </datalist>

  <input type="text" id="score" name="score" autocomplete="off">

My Script is below:

var type = document.getElementById("type");
var score = document.getElementById("score");

if (type === 0) {
  score.value = 0;
} else if (type === 'basketball') {
  score.value = 1;
} else if (type === 'soccer') {
  score.value = 2;
} else if (type === 'table tenis') {
  score.value = 3;
}

Body:
You were able to access the element. You just need to use the value attribute of the element. You need to add the event change with dropdown so that it can bind the data in the score textbox when index is changed.

var type = document.getElementById("type");
var score = document.getElementById("score");

type.addEventListener('change', function() {
     if (type.value === 0) {
      score.value = 0;
    } else if (type.value === 'basketball') {
      score.value = 1;
    } else if (type.value === 'soccer') {
      score.value = 2;
    } else if (type.value === 'table tennis') {
      score.value = 3;
    }
});

<tr>
  <td>
    <div>
      <input list="typeList" name="type" id="type">
      <datalist id="typeList">
        <option value="basketball">
        <option value="soccer">
        <option value="table tennis">
      </datalist>
    </div>
  </td>

  <td><input type="text" id="score" name="score" autocomplete="off" ></td>
</tr>


问:
iOS app error - Can't add self as subview
I received this crash report, but I don't know how to debug it.

```<code>Fatal Exception NSInvalidArgumentException
Can't add self as subview
0 ...    CoreFoundation  __exceptionPreprocess + 130
1    libobjc.A.dylib     objc_exception_throw + 38
2    CoreFoundation  -[NSException initWithCoder:]
3    UIKit   -[UIView(Internal) _addSubview:positioned:relativeTo:] + 110
4    UIKit   -[UIView(Hierarchy) addSubview:] + 30
5    UIKit   __53-[_UINavigationParallaxTransition animateTransition:]_block_invoke + 1196
6    UIKit   +[UIView(Animation) performWithoutAnimation:] + 72
7    UIKit   -[_UINavigationParallaxTransition animateTransition:] + 732
8    UIKit   -[UINavigationController _startCustomTransition:] + 2616
9    UIKit   -[UINavigationController _startDeferredTransitionIfNeeded:] + 418
10   UIKit   -[UINavigationController __viewWillLayoutSubviews] + 44
11   UIKit   -[UILayoutContainerView layoutSubviews] + 184
12   UIKit   -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 346
13   QuartzCore  -[CALayer layoutSublayers] + 142
14   QuartzCore  CA::Layer::layout_if_needed(CA::Transaction*) + 350
15   QuartzCore  CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 16
16   QuartzCore  CA::Context::commit_transaction(CA::Transaction*) + 228
17   QuartzCore  CA::Transaction::commit() + 314
18   QuartzCore  CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 56
</code>```

The iOS version is 7.0.3.
Anyone experience this weird crash?

UPDATE:

I don't know where in my code caused this crash, so I can not post the code here, sorry.

Second UPDATE

See the answer below.

答:
I had searched this problem a lot, it maybe pushing two or more VC at same time, which cause the pushing animation problem,
you can refer to this :Can't Add Self as Subview 崩溃解决办法

just make sure the there is one VC on transition progress at same time，good luck.

Body:
I received this crash report, but I don't know how to debug it.

Fatal Exception NSInvalidArgumentException
Can't add self as subview
0 ...    CoreFoundation  __exceptionPreprocess + 130
1    libobjc.A.dylib     objc_exception_throw + 38
2    CoreFoundation  -[NSException initWithCoder:]
3    UIKit   -[UIView(Internal) _addSubview:positioned:relativeTo:] + 110
4    UIKit   -[UIView(Hierarchy) addSubview:] + 30
5    UIKit   __53-[_UINavigationParallaxTransition animateTransition:]_block_invoke + 1196
6    UIKit   +[UIView(Animation) performWithoutAnimation:] + 72
7    UIKit   -[_UINavigationParallaxTransition animateTransition:] + 732
8    UIKit   -[UINavigationController _startCustomTransition:] + 2616
9    UIKit   -[UINavigationController _startDeferredTransitionIfNeeded:] + 418
10   UIKit   -[UINavigationController __viewWillLayoutSubviews] + 44
11   UIKit   -[UILayoutContainerView layoutSubviews] + 184
12   UIKit   -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 346
13   QuartzCore  -[CALayer layoutSublayers] + 142
14   QuartzCore  CA::Layer::layout_if_needed(CA::Transaction*) + 350
15   QuartzCore  CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 16
16   QuartzCore  CA::Context::commit_transaction(CA::Transaction*) + 228
17   QuartzCore  CA::Transaction::commit() + 314
18   QuartzCore  CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 56

The iOS version is 7.0.3.
Anyone experience this weird crash?

UPDATE:

I don't know where in my code caused this crash, so I can not post the code here, sorry.

Second UPDATE

See the answer below.


问:
Flex performance hit?
I looked at this demo:
http://bubblemark.com/

Flex seems very slow compared to silverlight 3. Unfortunately can't see pure flash but should flex be forbidden if performance is top requirements compared to Flash ?

答:
Gosh... If I were to make an app like that, why would I incur the penalty of the Flex layer?  To me, Flex is not the right development stack for that app... but Flash might be.  I'd be curious to see how it works directly using the Flash API without the overhead of Flex controls and libraries?

I guess my point is: most Flex applications are not animations like that.  Flex is really good as an application development stack.  Silverlight is too, for that matter.  The performance overhead that Flex incurs for most applications you might build is small enough that it isn't noticed by the user.

That being said, it really depends on the type of app you are developing.  Pretty UIs over data services, which is a huge percentage of Flex apps, is what Flex does best IMO.  In other words, I wouldn't develop Angry Birds in Flex.  It wasn't built for that type of app.  BUT, when Flex is good at something, it is really good at it.  The productivity gain is certainly worth it to me when compared to performance hit that is negligible for most Flex apps I build.

Just for the record, everything I am saying here about Flex is also true of Silverlight, IMO.  It is just that with Silverlight, there is no distinction between the animation layer and the application layer... it is not broken into two layers like Flash/Flex is.

Title: Flex performance hit?


问:
Using kafka streams to segregate messages
I have a setup where each kafka message will contain a "sender" field. All these message are sent to a single topic.

Is there a way to segregate these messages at the consumer side? I would like sender specific consumer that will read all messages pertaining to that sender alone.

Should I be using Kafka Streams to achieve this? I am new to Kafka Streams, any advice guidance will be helpful.

```<code>public class KafkaStreams3 {

public static void main(String[] args) throws JSONException {

    Properties props = new Properties();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, "kafkastreams1");
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");

    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

    final Serde < String > stringSerde = Serdes.String();

    Properties kafkaProperties = new Properties();
    kafkaProperties.put("key.serializer",
            "org.apache.kafka.common.serialization.StringSerializer");
    kafkaProperties.put("value.serializer",
            "org.apache.kafka.common.serialization.StringSerializer");

    kafkaProperties.put("bootstrap.servers", "localhost:9092");

    KafkaProducer<String, String> producer = new KafkaProducer<String, String>(kafkaProperties);

    KStreamBuilder builder = new KStreamBuilder();

   KStream<String, String> source = builder.stream(stringSerde, stringSerde, "topic1");

    KStream<String, String> s1 = source.map(new KeyValueMapper<String, String, KeyValue<String, String>>() {
        @Override
        public KeyValue<String, String> apply(String dummy, String record) {
            JSONObject jsonObject;

            try {
                jsonObject = new JSONObject(record);
                return new KeyValue<String,String>(jsonObject.get("sender").toString(), record);
            } catch (JSONException e) {
                e.printStackTrace();
                return new KeyValue<>(record, record);
            }

        }
      });

    s1.print();

    s1.foreach(new ForeachAction<String, String>() {

        @Override
        public void apply(String key, String value) {
            ProducerRecord<String, String> data1 = new ProducerRecord<String, String>(
                    key, key, value);
            producer.send(data1);

        }

    });

    KafkaStreams streams = new KafkaStreams(builder, props);

    streams.start();

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
          streams.close();
          producer.close();
        }
      }));

}
</code>```

}

答:
I believe the simplest way to achieve this is to use your "sender" field as a key and to have a single topic partitioned by "sender", this will give you locality and order per "sender" so you get a stronger ordering guarantee per "sender" and you can connect clients to consume from specific partitions.

Other possibility is that from the initial topic you stream your messages to other topics aggregating by key so you would end up having one topic per "sender".

Here's a fragment of code for a producer and then streaming with json serializers and deserializers.

Producer:

```<code>private Properties kafkaClientProperties() {
    Properties properties = new Properties();

    final Serializer<JsonNode> jsonSerializer = new JsonSerializer();

    properties.put("bootstrap.servers", config.getHost());
    properties.put("client.id", clientId);
    properties.put("key.serializer", StringSerializer.class);
    properties.put("value.serializer", jsonSerializer.getClass());

    return properties;
}

public Future<RecordMetadata> send(String topic, String key, Object instance) {
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode jsonNode = objectMapper.convertValue(instance, JsonNode.class);
    return kafkaProducer.send(new ProducerRecord<>(topic, key,
            jsonNode));
}
</code>```

The stream:

```<code>log.info("loading kafka stream configuration");
    final Serializer<JsonNode> jsonSerializer = new JsonSerializer();
    final Deserializer<JsonNode> jsonDeserializer = new JsonDeserializer();
    final Serde<JsonNode> jsonSerde = Serdes.serdeFrom(jsonSerializer, jsonDeserializer);

    KStreamBuilder kStreamBuilder = new KStreamBuilder();
    Properties props = new Properties();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, config.getStreamEnrichProduce().getId());
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, hosts);

    //stream from topic...
    KStream<String, JsonNode> stockQuoteRawStream = kStreamBuilder.stream(Serdes.String(), jsonSerde , config.getStockQuote().getTopic());

    Map<String, Map> exchanges = stockExchangeMaps.getExchanges();
    ObjectMapper objectMapper = new ObjectMapper();
    kafkaProducer.configure(config.getStreamEnrichProduce().getTopic());
    // - enrich stockquote with stockdetails before producing to new topic
    stockQuoteRawStream.foreach((key, jsonNode) -> {
        StockQuote stockQuote = null;
        StockDetail stockDetail;
        try {
            stockQuote = objectMapper.treeToValue(jsonNode, StockQuote.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        JsonNode exchangeNode = jsonNode.get("exchange");
        // get stockDetail that matches current quote being processed
        Map<String, StockDetail> stockDetailMap = exchanges.get(exchangeNode.toString().replace("\"", ""));
        stockDetail = stockDetailMap.get(key);
        stockQuote.setStockDetail(stockDetail);
        kafkaProducer.send(config.getStreamEnrichProduce().getTopic(), null, stockQuote);
    });

    return new KafkaStreams(kStreamBuilder, props);
</code>```

Body:
I have a setup where each kafka message will contain a "sender" field. All these message are sent to a single topic.

Is there a way to segregate these messages at the consumer side? I would like sender specific consumer that will read all messages pertaining to that sender alone.

Should I be using Kafka Streams to achieve this? I am new to Kafka Streams, any advice guidance will be helpful.

public class KafkaStreams3 {

public static void main(String[] args) throws JSONException {

    Properties props = new Properties();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, "kafkastreams1");
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");

    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

    final Serde < String > stringSerde = Serdes.String();

    Properties kafkaProperties = new Properties();
    kafkaProperties.put("key.serializer",
            "org.apache.kafka.common.serialization.StringSerializer");
    kafkaProperties.put("value.serializer",
            "org.apache.kafka.common.serialization.StringSerializer");

    kafkaProperties.put("bootstrap.servers", "localhost:9092");

    KafkaProducer<String, String> producer = new KafkaProducer<String, String>(kafkaProperties);

    KStreamBuilder builder = new KStreamBuilder();

   KStream<String, String> source = builder.stream(stringSerde, stringSerde, "topic1");

    KStream<String, String> s1 = source.map(new KeyValueMapper<String, String, KeyValue<String, String>>() {
        @Override
        public KeyValue<String, String> apply(String dummy, String record) {
            JSONObject jsonObject;

            try {
                jsonObject = new JSONObject(record);
                return new KeyValue<String,String>(jsonObject.get("sender").toString(), record);
            } catch (JSONException e) {
                e.printStackTrace();
                return new KeyValue<>(record, record);
            }

        }
      });

    s1.print();

    s1.foreach(new ForeachAction<String, String>() {

        @Override
        public void apply(String key, String value) {
            ProducerRecord<String, String> data1 = new ProducerRecord<String, String>(
                    key, key, value);
            producer.send(data1);

        }

    });

    KafkaStreams streams = new KafkaStreams(builder, props);

    streams.start();

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
          streams.close();
          producer.close();
        }
      }));

}

}

Body:
I believe the simplest way to achieve this is to use your "sender" field as a key and to have a single topic partitioned by "sender", this will give you locality and order per "sender" so you get a stronger ordering guarantee per "sender" and you can connect clients to consume from specific partitions.

Other possibility is that from the initial topic you stream your messages to other topics aggregating by key so you would end up having one topic per "sender".

Here's a fragment of code for a producer and then streaming with json serializers and deserializers.

Producer:

private Properties kafkaClientProperties() {
    Properties properties = new Properties();

    final Serializer<JsonNode> jsonSerializer = new JsonSerializer();

    properties.put("bootstrap.servers", config.getHost());
    properties.put("client.id", clientId);
    properties.put("key.serializer", StringSerializer.class);
    properties.put("value.serializer", jsonSerializer.getClass());

    return properties;
}

public Future<RecordMetadata> send(String topic, String key, Object instance) {
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode jsonNode = objectMapper.convertValue(instance, JsonNode.class);
    return kafkaProducer.send(new ProducerRecord<>(topic, key,
            jsonNode));
}

The stream:

log.info("loading kafka stream configuration");
    final Serializer<JsonNode> jsonSerializer = new JsonSerializer();
    final Deserializer<JsonNode> jsonDeserializer = new JsonDeserializer();
    final Serde<JsonNode> jsonSerde = Serdes.serdeFrom(jsonSerializer, jsonDeserializer);

    KStreamBuilder kStreamBuilder = new KStreamBuilder();
    Properties props = new Properties();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, config.getStreamEnrichProduce().getId());
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, hosts);

    //stream from topic...
    KStream<String, JsonNode> stockQuoteRawStream = kStreamBuilder.stream(Serdes.String(), jsonSerde , config.getStockQuote().getTopic());

    Map<String, Map> exchanges = stockExchangeMaps.getExchanges();
    ObjectMapper objectMapper = new ObjectMapper();
    kafkaProducer.configure(config.getStreamEnrichProduce().getTopic());
    // - enrich stockquote with stockdetails before producing to new topic
    stockQuoteRawStream.foreach((key, jsonNode) -> {
        StockQuote stockQuote = null;
        StockDetail stockDetail;
        try {
            stockQuote = objectMapper.treeToValue(jsonNode, StockQuote.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        JsonNode exchangeNode = jsonNode.get("exchange");
        // get stockDetail that matches current quote being processed
        Map<String, StockDetail> stockDetailMap = exchanges.get(exchangeNode.toString().replace("\"", ""));
        stockDetail = stockDetailMap.get(key);
        stockQuote.setStockDetail(stockDetail);
        kafkaProducer.send(config.getStreamEnrichProduce().getTopic(), null, stockQuote);
    });

    return new KafkaStreams(kStreamBuilder, props);


答:
You need to add a event listener (or two, one for change and one for input) and then wrap your code in a function:

var type = document.getElementById("type");
var score = document.getElementById("score");

type.addEventListener("change", function() {
    myFunction(type.value);
});

type.addEventListener("input", function() {
    myFunction(type.value);
});

var myFunction = function(type) {
  if (type === 0) {
    score.value = 0;
  } else if (type === 'basketball') {
    score.value = 1;
  } else if (type === 'soccer') {
    score.value = 2;
  } else if (type === 'table tenis') {
    score.value = 3;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><tr>
  <td>
    <div>
      <input list="typeList" name="type" id="type">
      <datalist id="typeList">
        <option value="basketball">
        <option value="soccer">
        <option value="table tenis">
      </datalist>
    </div>
  </td>

  <td><input type="text" id="score" name="score" autocomplete="off"></td>
</tr></code>```

Title: If else statement with string JavaScript

Body:
You need to add a event listener (or two, one for change and one for input) and then wrap your code in a function:

var type = document.getElementById("type");
var score = document.getElementById("score");

type.addEventListener("change", function() {
    myFunction(type.value);
});

type.addEventListener("input", function() {
    myFunction(type.value);
});

var myFunction = function(type) {
  if (type === 0) {
    score.value = 0;
  } else if (type === 'basketball') {
    score.value = 1;
  } else if (type === 'soccer') {
    score.value = 2;
  } else if (type === 'table tenis') {
    score.value = 3;
  }
}

<tr>
  <td>
    <div>
      <input list="typeList" name="type" id="type">
      <datalist id="typeList">
        <option value="basketball">
        <option value="soccer">
        <option value="table tenis">
      </datalist>
    </div>
  </td>

  <td><input type="text" id="score" name="score" autocomplete="off"></td>
</tr>


问:
How to get same value for current time in milliseconds on localhost and server?
I have created a web listener which contains a ScheduledExecutorService to run a job on a specific date and time and after that at regular fixed time interval. This scheduler checks for a specific date and time to do the job. The scheduler works with UTC time.

The problem is when I run it on my localhost it works perfectly but when I put it on remote server (server and my localhost are not in same TimeZone) it fails to work properly( they produce different value of System.currentTimeMillis() . With the help of a logger I have checked  the value of System.currentTimeMillis() both on localhost and server and they are different.

Here is my Scheduler.

```<code>private static ScheduledExecutorService execService = Executors.newScheduledThreadPool(1, namedThreadFactory);
final Calendar date = new GregorianCalendar();
date.setTimeZone(TimeZone.getTimeZone("UTC"));
    execService.scheduleAtFixedRate(new Runnable() {
                @Override
        public void run() {

                    logger.info("Scheduler ran");

                    try {

                        if (date.get(Calendar.DAY_OF_MONTH) == 1) {
                            if (!(System.currentTimeMillis() - getStartTime().getTime() > 300000)) {
                                logger.info("Doing the job");
                                myJob();
                            }
                            else{
                                logger.info("Too late after scheduled time");
                            }
                        } else {

                            logger.info("Current Day of Month: " + date.get(Calendar.DAY_OF_MONTH) + ". Job will be done on  1st Day of the month");
                        }
                    } catch (Exception ex) {

                        logger.info(ex);
                    }

                }

            }, getInitialDelay(), (2*60000), TimeUnit.MILLISECONDS);

        }

        private static long getOffsetTime() {
            Calendar dateForOffset = new GregorianCalendar();
            dateForOffset.setTimeZone(TimeZone.getTimeZone("UTC"));
            int days = dateForOffset.getActualMaximum(Calendar.DAY_OF_MONTH);

            switch (days) {
                case 31:
                    offsetTimeInMilli = PERIOD;
                    break;
                case 29:
                    offsetTimeInMilli = (-1) * PERIOD;
                    break;
                case 28:
                    offsetTimeInMilli = (-2) * PERIOD;
                    break;
                default:
                    break;
            }
            return offsetTimeInMilli;
        }

        private static long getInitialDelay() {
            long currentTime = System.currentTimeMillis();
            logger.info( "Current Time " + currentTime);
            logger.info("Set Time to do the job   -->" + getStartTime().getTime() + " Milliseconds");
            initialDelay = getStartTime().getTime() - currentTime;
            logger.info("Initial Delay Found : " + initialDelay + " Milliseconds");
            return initialDelay;

        }

        private static Date getStartTime() {
            Calendar d10am = Calendar.getInstance();
            d10am.setTimeZone(TimeZone.getTimeZone("UTC"));
            //logger.info("Day of Month  ----- >" + d10am.get(Calendar.DAY_OF_MONTH));
            //d10am.set(Calendar.DAY_OF_MONTH, 1);
            d10am.set(Calendar.HOUR_OF_DAY, 5);
            d10am.set(Calendar.MINUTE, 55);
            d10am.set(Calendar.SECOND, 0);
            d10am.set(Calendar.MILLISECOND, 0);
            d10am.get(Calendar.DAY_OF_MONTH);
            //logger.info("Day of Month  ----- >" + Calendar.DAY_OF_MONTH);

            return d10am.getTime();
        }
</code>```

答:
One or both of them must be wrong.  The value System.currentTimeMillis() is independent of time zones.  Really, the proper way to synchronize times on these servers is for each server to synchronize with a time server using NTP (Network Time Protocol).

This is more of a systems administration problem than a Java programming problem.

Body:
I have created a web listener which contains a ScheduledExecutorService to run a job on a specific date and time and after that at regular fixed time interval. This scheduler checks for a specific date and time to do the job. The scheduler works with UTC time.

The problem is when I run it on my localhost it works perfectly but when I put it on remote server (server and my localhost are not in same TimeZone) it fails to work properly( they produce different value of System.currentTimeMillis() . With the help of a logger I have checked  the value of System.currentTimeMillis() both on localhost and server and they are different.

Here is my Scheduler.

private static ScheduledExecutorService execService = Executors.newScheduledThreadPool(1, namedThreadFactory);
final Calendar date = new GregorianCalendar();
date.setTimeZone(TimeZone.getTimeZone("UTC"));
    execService.scheduleAtFixedRate(new Runnable() {
                @Override
        public void run() {

                    logger.info("Scheduler ran");

                    try {

                        if (date.get(Calendar.DAY_OF_MONTH) == 1) {
                            if (!(System.currentTimeMillis() - getStartTime().getTime() > 300000)) {
                                logger.info("Doing the job");
                                myJob();
                            }
                            else{
                                logger.info("Too late after scheduled time");
                            }
                        } else {

                            logger.info("Current Day of Month: " + date.get(Calendar.DAY_OF_MONTH) + ". Job will be done on  1st Day of the month");
                        }
                    } catch (Exception ex) {

                        logger.info(ex);
                    }

                }

            }, getInitialDelay(), (2*60000), TimeUnit.MILLISECONDS);

        }

        private static long getOffsetTime() {
            Calendar dateForOffset = new GregorianCalendar();
            dateForOffset.setTimeZone(TimeZone.getTimeZone("UTC"));
            int days = dateForOffset.getActualMaximum(Calendar.DAY_OF_MONTH);

            switch (days) {
                case 31:
                    offsetTimeInMilli = PERIOD;
                    break;
                case 29:
                    offsetTimeInMilli = (-1) * PERIOD;
                    break;
                case 28:
                    offsetTimeInMilli = (-2) * PERIOD;
                    break;
                default:
                    break;
            }
            return offsetTimeInMilli;
        }

        private static long getInitialDelay() {
            long currentTime = System.currentTimeMillis();
            logger.info( "Current Time " + currentTime);
            logger.info("Set Time to do the job   -->" + getStartTime().getTime() + " Milliseconds");
            initialDelay = getStartTime().getTime() - currentTime;
            logger.info("Initial Delay Found : " + initialDelay + " Milliseconds");
            return initialDelay;

        }

        private static Date getStartTime() {
            Calendar d10am = Calendar.getInstance();
            d10am.setTimeZone(TimeZone.getTimeZone("UTC"));
            //logger.info("Day of Month  ----- >" + d10am.get(Calendar.DAY_OF_MONTH));
            //d10am.set(Calendar.DAY_OF_MONTH, 1);
            d10am.set(Calendar.HOUR_OF_DAY, 5);
            d10am.set(Calendar.MINUTE, 55);
            d10am.set(Calendar.SECOND, 0);
            d10am.set(Calendar.MILLISECOND, 0);
            d10am.get(Calendar.DAY_OF_MONTH);
            //logger.info("Day of Month  ----- >" + Calendar.DAY_OF_MONTH);

            return d10am.getTime();
        }


问:
How to check whether a given file is a valid video file in C++?
I tried to do it using OpenCV:

```<code>std::string input_name = "<path to file>";
cv::VideoCapture cap(input_name);
if(!cap.isOpened()) printf("Invalid video\n");
</code>```

However, when I try passing a .txt file, VideoCapture reads it successfully for unknown reasons. When I try to find the number of frames in the video,

```<code>if(cap.get(cv::CV_CAP_PROP_FRAME_COUNT) == 0) printf("Invalid video\n");
</code>```

I get a different number of frames each time I execute. I also tried finding the width and height of a frame in the file,

```<code>cv::Mat Frame;
if(!cap.read(Frame)) printf("Cannot read frame\n");
else
{
    printf("Frame width is %d\n", Frame.cols);
    printf("Frame height is %d\n", Frame.rows);
}
</code>```

their values are 640 and 400 respectively. Why is this happening? Is there a way to check if a given file is a valid video file preferably using OpenCV?

答:
I'm not familiar with openCV but you can always check for file extension.

kdt wrote a method for this in this question
https://stackoverflow.com/a/874160/4612406

```<code>bool hasEnding (std::string const &fullString, std::string const &ending)
{
    if (fullString.length() >= ending.length()) {
        return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending));
    } else {
        return false;
    }
}
</code>```

Just pass the name of the file and the file extension you want like ".mp4". You can change this method to take vector for ending string and check for every string in the vector where you can place .mp4 .avi etc.

Body:
I tried to do it using OpenCV:

std::string input_name = "<path to file>";
cv::VideoCapture cap(input_name);
if(!cap.isOpened()) printf("Invalid video\n");

However, when I try passing a .txt file, VideoCapture reads it successfully for unknown reasons. When I try to find the number of frames in the video,

if(cap.get(cv::CV_CAP_PROP_FRAME_COUNT) == 0) printf("Invalid video\n");

I get a different number of frames each time I execute. I also tried finding the width and height of a frame in the file,

cv::Mat Frame;
if(!cap.read(Frame)) printf("Cannot read frame\n");
else
{
    printf("Frame width is %d\n", Frame.cols);
    printf("Frame height is %d\n", Frame.rows);
}

their values are 640 and 400 respectively. Why is this happening? Is there a way to check if a given file is a valid video file preferably using OpenCV?

Body:
I'm not familiar with openCV but you can always check for file extension.

kdt wrote a method for this in this question
https://stackoverflow.com/a/874160/4612406

bool hasEnding (std::string const &fullString, std::string const &ending)
{
    if (fullString.length() >= ending.length()) {
        return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending));
    } else {
        return false;
    }
}

Just pass the name of the file and the file extension you want like ".mp4". You can change this method to take vector for ending string and check for every string in the vector where you can place .mp4 .avi etc.


问:
Cannot implicitly convert type 'double' to 'long'
In this code i got the above error in lines i commented.

```<code>public double bigzarb(long u, long v)
{
    double n;
    long x;
    long y;
    long w;
    long z;
    string[] i = textBox7.Text.Split(',');
    long[] nums = new long[i.Length];
    for (int counter = 0; counter < i.Length; counter++)
    {
        nums[counter] = Convert.ToInt32(i[counter]);
    }

    u = nums[0];
    int firstdigits = Convert.ToInt32(Math.Floor(Math.Log10(u) + 1));
    v = nums[1];
    int seconddigits = Convert.ToInt32(Math.Floor(Math.Log10(v) + 1));
    if (firstdigits >= seconddigits)
    {
        n = firstdigits;

    }
    else
    {
        n = seconddigits;
    }
    if (u == 0 || v == 0)
    {
        MessageBox.Show("the Multiply is 0");
    }

    int intn = Convert.ToInt32(n);
    if (intn <= 3)
    {
        long uv = u * v;
        string struv = uv.ToString();
        MessageBox.Show(struv);
        return uv;
    }
    else
    {
        int m =Convert.ToInt32(Math.Floor(n / 2));

        x = u % Math.Pow(10, m); // here
        y = u / Math.Pow(10, m); // here
        w = v % Math.Pow(10, m); // here
        z = v / Math.Pow(10, m); // here

        long result = bigzarb(x, w) * Math.Pow(10, m) + (bigzarb(x, w) + bigzarb(w, y)) * Math.Pow(10, m) + bigzarb(y, z);///here
        textBox1.Text = result.ToString();
        return result;
    }
}
</code>```

Whats is the problem? Thanks!

答:
Math.Pow returns a double.

the Right Hand Side (RHS) of % can only be an integer type.

you need

```<code>x = u % (long)Math.Pow(10, m);///<----here
y = u / (long)Math.Pow(10, m);///here
w = v % (long)Math.Pow(10, m);///here
z = v / (long)Math.Pow(10, m);///here
</code>```

Additionally, You have the possibility of dividing by zero and destroying the universe.

Body:
In this code i got the above error in lines i commented.

public double bigzarb(long u, long v)
{
    double n;
    long x;
    long y;
    long w;
    long z;
    string[] i = textBox7.Text.Split(',');
    long[] nums = new long[i.Length];
    for (int counter = 0; counter = seconddigits)
    {
        n = firstdigits;

    }
    else
    {
        n = seconddigits;
    }
    if (u == 0 || v == 0)
    {
        MessageBox.Show("the Multiply is 0");
    }

    int intn = Convert.ToInt32(n);
    if (intn <= 3)
    {
        long uv = u * v;
        string struv = uv.ToString();
        MessageBox.Show(struv);
        return uv;
    }
    else
    {
        int m =Convert.ToInt32(Math.Floor(n / 2));

        x = u % Math.Pow(10, m); // here
        y = u / Math.Pow(10, m); // here
        w = v % Math.Pow(10, m); // here
        z = v / Math.Pow(10, m); // here

        long result = bigzarb(x, w) * Math.Pow(10, m) + (bigzarb(x, w) + bigzarb(w, y)) * Math.Pow(10, m) + bigzarb(y, z);///here
        textBox1.Text = result.ToString();
        return result;
    }
}

Whats is the problem? Thanks!

Body:
Math.Pow returns a double.

the Right Hand Side (RHS) of % can only be an integer type.

you need

x = u % (long)Math.Pow(10, m);///<----here
y = u / (long)Math.Pow(10, m);///here
w = v % (long)Math.Pow(10, m);///here
z = v / (long)Math.Pow(10, m);///here

Additionally, You have the possibility of dividing by zero and destroying the universe.


答:
in your if it should be

```<code>type.value
</code>```

to get the value of the input box. Also when are you running the script?

Body:
in your if it should be

type.value

to get the value of the input box. Also when are you running the script?


问:
php namespace load javascript file error
I'm trying to load a javascript and css file with link and script tags. The project uses php namespaces so the files are trying to load via the router script that sets the controllers. Maybe a little more explanation is needed.

When the visitor first comes to http://site0 the root .htaccess file rewrites to the /public directory with the /public/.htaccess file rewrites everything to the /public/index.php file. The /public/index.php is just a spl_autoload function and calls the router.class.php script that decides which controller class to call.

Contents of root .htaccess:

```<code><IfModule mod_rewrite.c>
RewriteEngine On

RewriteBase /

#RewriteCond %{REQUEST_URI} \.css$
RewriteRule (styles/[^/]+\.css)$ /$1 [L]

# File is located in /foldername/images/
# Internal redirect. Does not change address in the browsers address bar.
RewriteCond %{REQUEST_URI} \.(gif|jpg|png)$
RewriteRule ^.*(images)/(.*)(\.gif|jpg|png)$ $1/$2$3 [L]

# File is located in /foldername/scripts/.
# Internal redirect. Does not change address in the browsers address bar.
RewriteCond %{REQUEST_URI} \.js$
RewriteRule (scripts/[^/]+\.js)$ /$1 [L]

RewriteRule ^$ public/  [L]
RewriteRule (.*) public/$1  [L]
</IfModule>
</code>```

Contents of public/.htaccess :

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?url=$1     [PT,L]

</IfModule>
</code>```

Contents of public/index.php :

```<code> <?
 //set_include_path('PATH_TO_GLOBAL_LIBS; PATH_TO_LIBRARY_1; PATH_TO_LIBRARY_X; PATH_TO_DOCUMENT_ROOT');

define('DS', DIRECTORY_SEPARATOR);
define ('ROOT', dirname(dirname(__FILE__)));

include_once (ROOT . DS . 'inc/dbconf.php');

function multi_autoloader($class)
{
    $class = preg_replace('/^((\w*)\\\){2}/', '', $class);

    $file = ROOT . DS . str_replace('\\', DS, strtolower($class)) . '.class.php';

        if ( file_exists($file) )
        {
           require ($file);
        }
}

spl_autoload_register('multi_autoloader');

use potts\john\libs\router\Router as Router;

$router = Router::getInstance();
$router->initRouter();
</code>```

The router.class.php file is quite large but if you need to see it, let me know. Via console/inspector I get a status 500 from both css and javascript files. In a project where I didn't need to use php namspaces all worked fine. So this has to be a problem caused by the namspaces.

Any suggestions on how to fix this ?

答:
It's an ugly hack but it works :

```<code>/**
 * Sets the appropriate controller
 *
 *
 * @return object $this->controller
 */

private function setController()
{

   $this->_seo_uri = $this->seoUrl();

   $this->__controller = array_shift($this->_seo_uri);

        if ($this->__controller == 'styles')
        {
               /* dev purposes only. php will return error that gets
                  appended to end of file.
                */
          ini_set('display_errors',0);

          /* include will return file with mime type 'text/html
             thus not interpreting file as stylesheet
           */
           header('Content-type: text/css');

           // readfile works too. your choice...
           //readfile($_SERVER['DOCUMENT_ROOT']. '/styles/style.css');

             include ($_SERVER['DOCUMENT_ROOT']. '/styles/style.css');

        }
        elseif ($this->__controller == 'scripts')
        {
               /* dev purposes only. php will return error that gets
                  appended to end of file.
               */
          ini_set('display_errors',0);

             include ($_SERVER['DOCUMENT_ROOT']. '/scripts/gui.js');

        }
        else
        {

            $this->_controller = ucfirst($this->__controller);

            $this->_controller = $this->_controller . "_Controller";

            $this->_base_namespace = '\bizdir\bizvend\controllers\\' . $this->__controller . '\\' . strtolower($this->_controller);

              //use $this->_base_namespace as $this->_controller;

           $this->controller = new $this->_base_namespace;

            return $this->controller;

        }

}
</code>```

Refer to where I'm testing $this->__controller for either styles or scripts. What was happening is in the link and script tags the directory (either /styles/ or /scripts/) was being set as the controller in the namespace and the router class was trying to find the Styles_Controller class or the Scripts_Controller class. I'm probable going to have to test for images as well when I get to that point.

Hope this saves someone else a few hours of headbanging.

Any cleaner ways... I'm open to suggestions.

Body:
I'm trying to load a javascript and css file with link and script tags. The project uses php namespaces so the files are trying to load via the router script that sets the controllers. Maybe a little more explanation is needed.

When the visitor first comes to http://site0 the root .htaccess file rewrites to the /public directory with the /public/.htaccess file rewrites everything to the /public/index.php file. The /public/index.php is just a spl_autoload function and calls the router.class.php script that decides which controller class to call.

Contents of root .htaccess:

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteBase /

#RewriteCond %{REQUEST_URI} \.css$
RewriteRule (styles/[^/]+\.css)$ /$1 [L]

# File is located in /foldername/images/
# Internal redirect. Does not change address in the browsers address bar.
RewriteCond %{REQUEST_URI} \.(gif|jpg|png)$
RewriteRule ^.*(images)/(.*)(\.gif|jpg|png)$ $1/$2$3 [L]

# File is located in /foldername/scripts/.
# Internal redirect. Does not change address in the browsers address bar.
RewriteCond %{REQUEST_URI} \.js$
RewriteRule (scripts/[^/]+\.js)$ /$1 [L]

RewriteRule ^$ public/  [L]
RewriteRule (.*) public/$1  [L]
</IfModule>

Contents of public/.htaccess :

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?url=$1     [PT,L]

</IfModule>

Contents of public/index.php :

 <?
 //set_include_path('PATH_TO_GLOBAL_LIBS; PATH_TO_LIBRARY_1; PATH_TO_LIBRARY_X; PATH_TO_DOCUMENT_ROOT');

define('DS', DIRECTORY_SEPARATOR);
define ('ROOT', dirname(dirname(__FILE__)));

include_once (ROOT . DS . 'inc/dbconf.php');

function multi_autoloader($class)
{
    $class = preg_replace('/^((\w*)\\\){2}/', '', $class);

    $file = ROOT . DS . str_replace('\\', DS, strtolower($class)) . '.class.php';

        if ( file_exists($file) )
        {
           require ($file);
        }
}

spl_autoload_register('multi_autoloader');

use potts\john\libs\router\Router as Router;

$router = Router::getInstance();
$router->initRouter();

The router.class.php file is quite large but if you need to see it, let me know. Via console/inspector I get a status 500 from both css and javascript files. In a project where I didn't need to use php namspaces all worked fine. So this has to be a problem caused by the namspaces.

Any suggestions on how to fix this ?

Body:
It's an ugly hack but it works :

/**
 * Sets the appropriate controller
 *
 *
 * @return object $this->controller
 */

private function setController()
{

   $this->_seo_uri = $this->seoUrl();

   $this->__controller = array_shift($this->_seo_uri);

        if ($this->__controller == 'styles')
        {
               /* dev purposes only. php will return error that gets
                  appended to end of file.
                */
          ini_set('display_errors',0);

          /* include will return file with mime type 'text/html
             thus not interpreting file as stylesheet
           */
           header('Content-type: text/css');

           // readfile works too. your choice...
           //readfile($_SERVER['DOCUMENT_ROOT']. '/styles/style.css');

             include ($_SERVER['DOCUMENT_ROOT']. '/styles/style.css');

        }
        elseif ($this->__controller == 'scripts')
        {
               /* dev purposes only. php will return error that gets
                  appended to end of file.
               */
          ini_set('display_errors',0);

             include ($_SERVER['DOCUMENT_ROOT']. '/scripts/gui.js');

        }
        else
        {

            $this->_controller = ucfirst($this->__controller);

            $this->_controller = $this->_controller . "_Controller";

            $this->_base_namespace = '\bizdir\bizvend\controllers\\' . $this->__controller . '\\' . strtolower($this->_controller);

              //use $this->_base_namespace as $this->_controller;

           $this->controller = new $this->_base_namespace;

            return $this->controller;

        }

}

Refer to where I'm testing $this->__controller for either styles or scripts. What was happening is in the link and script tags the directory (either /styles/ or /scripts/) was being set as the controller in the namespace and the router class was trying to find the Styles_Controller class or the Scripts_Controller class. I'm probable going to have to test for images as well when I get to that point.

Hope this saves someone else a few hours of headbanging.

Any cleaner ways... I'm open to suggestions.


问:
Can A Password Be Passed As A Parameter To Your Script When Using Fake.Deploy?
As you all know, Fake.Deploy uses NuGet Packages for deployment to servers.  My question is, is there a way, from the command line, to call fake.deploy and pass along a password and other parameters to Fake.exe on the remote server?  I'm thinking that there would be something like this:

fake.deploy.exe /deployRemote http://example.com:8080/fake $package --nocache password="MyP4ssw0rd"

I'd like to be able to input my password from my build server versus putting the password in my deploy script that's in the NuGet package.  The reason I need to pass along a password is because we do things like set up scheduled tasks or set different identities for app pools, which requires the username and password.

答:
Looking at Fake.Deploy's source code you can send arguments exactly as your example.
In your nuget package you need a fsx script (setup.fsx) where you handle the arguments.