问:
Devise - How to trigger a sign_in on page user already has access to
I am using Devise 3.5.2.  I have an Item model with a show action that anyone can access( before_filter :authenticate_user!, except: :show). On the show page I have a button that triggers a file upload dialog using jquery.

I only want this upload dialog to work for logged in users. If a user is logged out and they click the button I want it to bring them to my login page. When they login I want it to take them back to the show page.

How can I make it so clicking this link brings them to the login page and then after logging in they are redirected to the page they were just on and already had access to?

```<code><% unless current_user %>
  <%= link_to "Upload image", item_path @item, class: "btn btn-lg btn-success" %>
<% end %>
</code>```

This won't work because they already have access to this page.

EDIT: I tried following this link here https://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-on-successful-sign-in but it doesn't seem to be working.

My sessions controller looks like this. Maybe my create method is causing a conflict?

```<code>class SessionsController < Devise::SessionsController

   def new
     self.resource = resource_class.new(sign_in_params)
     store_location_for(resource, params[:redirect_to])
     super
   end

  def create
    self.resource = warden.authenticate!(auth_options)
    if resource.deactivated?
      set_flash_message(:notice, :reactivated) if is_flashing_format?
      resource.reactivate
    end
    sign_in(resource_name, resource)
    yield resource if block_given?
    respond_with resource, location: after_sign_in_path_for(resource)
  end
end
</code>```

答:
This sounds like you need some controller specific code.

When a user clicks on the link, have the corresponding action do something like this:

```<code>    def image_action # Whatever the action name is
      if current_user # current user is given to you by devise
        # Do stuff that a logged in user would do
      else
        # redirect to login page
      end
    end
</code>```

The idea being that you leave the logic out of the view, and instead either have the controller serve the logged in user the appropriate data / page or have an unauthenticated user redirected to the login page.

current_user is a method given to you by devise that evaluates either to the currently logged in user making the request or nil if the user is not logged in.

If you post your controller code, I'll file out more of my example code, I just didn't want to make it too specific at risk of being confusing.

Body:
I am using Devise 3.5.2.  I have an Item model with a show action that anyone can access( before_filter :authenticate_user!, except: :show). On the show page I have a button that triggers a file upload dialog using jquery.

I only want this upload dialog to work for logged in users. If a user is logged out and they click the button I want it to bring them to my login page. When they login I want it to take them back to the show page.

How can I make it so clicking this link brings them to the login page and then after logging in they are redirected to the page they were just on and already had access to?

<% unless current_user %>
  <%= link_to "Upload image", item_path @item, class: "btn btn-lg btn-success" %>
<% end %>

This won't work because they already have access to this page.

EDIT: I tried following this link here https://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-on-successful-sign-in but it doesn't seem to be working.

My sessions controller looks like this. Maybe my create method is causing a conflict?

class SessionsController < Devise::SessionsController

   def new
     self.resource = resource_class.new(sign_in_params)
     store_location_for(resource, params[:redirect_to])
     super
   end

  def create
    self.resource = warden.authenticate!(auth_options)
    if resource.deactivated?
      set_flash_message(:notice, :reactivated) if is_flashing_format?
      resource.reactivate
    end
    sign_in(resource_name, resource)
    yield resource if block_given?
    respond_with resource, location: after_sign_in_path_for(resource)
  end
end

Body:
This sounds like you need some controller specific code.

When a user clicks on the link, have the corresponding action do something like this:

    def image_action # Whatever the action name is
      if current_user # current user is given to you by devise
        # Do stuff that a logged in user would do
      else
        # redirect to login page
      end
    end

The idea being that you leave the logic out of the view, and instead either have the controller serve the logged in user the appropriate data / page or have an unauthenticated user redirected to the login page.

current_user is a method given to you by devise that evaluates either to the currently logged in user making the request or nil if the user is not logged in.

If you post your controller code, I'll file out more of my example code, I just didn't want to make it too specific at risk of being confusing.


来源: stackexchange

问:
TypeError: Cannot call method "getEmail" of undefined
I am new to Google script and trying to learn it.

I have the following code executing in one of my google spreadsheets. I have enabled both the Admin Directory and the Admin SDK, and i also created an OnEdit trigger to authorize the script. But the Execution transcript still shows this error :

Execution failed: TypeError: Cannot call method "getEmail" of undefined. (line 10, file "Code")

```<code> 1. function onEdit(e) {
 2. var sheet = e.source.getActiveSheet().getName();
 3. if (sheet == "Sheet1") {
 4.    var sheet1 = e.source.getSheetByName('Sheet1');
 5.    var range = e.range;
 6.    var getCol = range.getColumn();
 7.    var getRow = range.getRow();
 8.
 9.    if (getCol == 1) {
10.         var user = e.Session.getActiveUser().getEmail();
11.            var name = AdminDirectory.Users.get(user).name.fullName; // familyName, fullName or givenName
12.            sheet1.getRange(getRow, 2).setValue(name);
13.        var htmlEmail = "Cell " + range.getA1Notation() +
14.            " edited by " + name;
15.        GmailApp.sendEmail("----------", "Spreadsheet Update " + new Date(), "", {
16.            htmlBody : htmlEmail
17.        });
18.     }
19.  }
20.}
</code>```

答:
Try something like this and see if you get results: https://developers.google.com/apps-script/reference/base/user#getEmail()

// Log the email address of the person running the script.
 Logger.log(Session.getActiveUser().getEmail());```

ContentLicense: CC BY-SA 3.0

Body:
I am new to Google script and trying to learn it.

I have the following code executing in one of my google spreadsheets. I have enabled both the Admin Directory and the Admin SDK, and i also created an OnEdit trigger to authorize the script. But the Execution transcript still shows this error :

Execution failed: TypeError: Cannot call method "getEmail" of undefined. (line 10, file "Code")

 1. function onEdit(e) {
 2. var sheet = e.source.getActiveSheet().getName();
 3. if (sheet == "Sheet1") {
 4.    var sheet1 = e.source.getSheetByName('Sheet1');
 5.    var range = e.range;
 6.    var getCol = range.getColumn();
 7.    var getRow = range.getRow();
 8.
 9.    if (getCol == 1) {
10.         var user = e.Session.getActiveUser().getEmail();
11.            var name = AdminDirectory.Users.get(user).name.fullName; // familyName, fullName or givenName
12.            sheet1.getRange(getRow, 2).setValue(name);
13.        var htmlEmail = "Cell " + range.getA1Notation() +
14.            " edited by " + name;
15.        GmailApp.sendEmail("----------", "Spreadsheet Update " + new Date(), "", {
16.            htmlBody : htmlEmail
17.        });
18.     }
19.  }
20.}


问:
set and clear interval multiple times
On the first slide of my slider I've got some text that changes within an interval.
This is the jQuery to do this:

```<code><script>
    var x = 0;
   var text = ["STRATEGICALLY", "COST-EFFECTIVELY", "EFFICIENTLY", "EXCEPTIONALLY"];
var counter = 0;
var elem = document.getElementById("banner-change");

var intervalID = setInterval(change, 1500);

function change() {

  jQuery(elem).fadeOut('slow', function() {
    jQuery(elem).text(text[counter++]);

    if (counter >= text.length) {
      counter = 0;
    }

    jQuery(elem).fadeIn('fast');

       if (++x === 5) {
       window.clearInterval(intervalID);
   }
  });

}

    </script>
</code>```

The slider looks something like this (The shortened code):

```<code><div id="myCarousel" class="hp-top carousel fade" data-ride="carousel" data-interval="6000">
<div class="carousel-inner">
<div class="item active"><img src="" alt="Chicago"/><div class="carousel-caption">
<div class="carousel-caption-inner">
<p class="slider-text small"><span class="slider-padding">What makes</span> us <span class="slider-green">specialists?</span></p>
<p class="slider-text">We just do ip</p>
<p class="slider-text"><span id="banner-change" class="slider-green">exceptionally</span></p>
</div>
</div>
</div>
</code>```

So the words in  keep changing. This works fine. However, it only works for the first time the first banner is shown. Which makes sense as I'm clearing the interval as each word is only supposed to show once, but not sure how to do this so that every time the first banner shows it starts the interval again?

答:
You can use the carousel evelts to trigger action.
e.relatedTarget will then refer to the slide, that is sliding into view.
So if you give it a unique id, you can identify it and run whatever action afterwards.

```<code>$('#myCarousel').on('slide.bs.carousel', function (e) {
  if (e.relatedTarget.id === 'firstSlide') // do something
})
</code>```

Title: set and clear interval multiple times

Body:
On the first slide of my slider I've got some text that changes within an interval.
This is the jQuery to do this:

The slider looks something like this (The shortened code):

What makes us specialists?

We just do ip

exceptionally

So the words in  keep changing. This works fine. However, it only works for the first time the first banner is shown. Which makes sense as I'm clearing the interval as each word is only supposed to show once, but not sure how to do this so that every time the first banner shows it starts the interval again?

Body:
You can use the carousel evelts to trigger action.
e.relatedTarget will then refer to the slide, that is sliding into view.
So if you give it a unique id, you can identify it and run whatever action afterwards.

$('#myCarousel').on('slide.bs.carousel', function (e) {
  if (e.relatedTarget.id === 'firstSlide') // do something
})


问:
firebase.database.ref path syntax in Cloud Functions and Nodejs
```<code>// cloud functions
exports.listenOnWrite = functions.database.ref('/foo/{id}').onWrite(event => {
    console.log("did match....");
})
</code>```

matches for example: /foo/123123 and /foo/jk3489

```<code>// node.js
function startLitener() {
  firebase.database().ref("/foo/{id}").on('child_added', function (postSnapshot) {
    console.log("did match....");
  });
};
</code>```

does not match anything

1) question

I understand the very comfortable {} syntax in the ref path works only for cloud functions.
Or did I miss something?

2) question

How would I formulate ref('/foo/{id}') on a nodejs server?

答:
In the declaration of your Cloud Function, you're using the syntax of the Cloud Functions for Firebase library. That's the module that interprets the {} syntax in the path.

The code inside your Node.js program is using the Firebase Admin SDK. So the paths there are interpreted by a different module and unfortunately use a different syntax:

```<code>firebase.database().ref("/foo/").on('child_added', function (postSnapshot) {
  var id = postSnapshot.key;
});
</code>```

Since you're listening for the child_added event, your code gets executed with a snapshot of the new child. When you then call snapshot.key you get the key of that child.

Body:
// cloud functions
exports.listenOnWrite = functions.database.ref('/foo/{id}').onWrite(event => {
    console.log("did match....");
})

matches for example: /foo/123123 and /foo/jk3489

// node.js
function startLitener() {
  firebase.database().ref("/foo/{id}").on('child_added', function (postSnapshot) {
    console.log("did match....");
  });
};

does not match anything

1) question

I understand the very comfortable {} syntax in the ref path works only for cloud functions.
Or did I miss something?

2) question

How would I formulate ref('/foo/{id}') on a nodejs server?

Body:
In the declaration of your Cloud Function, you're using the syntax of the Cloud Functions for Firebase library. That's the module that interprets the {} syntax in the path.

The code inside your Node.js program is using the Firebase Admin SDK. So the paths there are interpreted by a different module and unfortunately use a different syntax:

firebase.database().ref("/foo/").on('child_added', function (postSnapshot) {
  var id = postSnapshot.key;
});

Since you're listening for the child_added event, your code gets executed with a snapshot of the new child. When you then call snapshot.key you get the key of that child.


问:
How to copy a large file in Windows XP?
I have a large file in windows XP - its 38GB. (a VM image)

I cannot seem to copy it.

Dragging on the desktop - gives error of "Insufficient system resources exist to complete the requested service"

Using Java - FileChannel.transferTo(0, fileSize, dest) fails for all files > 2GB

Using Java - FileChannel.transferTo() in chunks of 100Mb fails after ~18Gb

```<code>java.io.IOException: Insufficient system resources exist to complete the requested service
at sun.nio.ch.FileDispatcher.write0(Native Method)
at sun.nio.ch.FileDispatcher.write(FileDispatcher.java:44)
at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:72)
at sun.nio.ch.IOUtil.write(IOUtil.java:28)
at sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:198)
at sun.nio.ch.FileChannelImpl.transferToTrustedChannel(FileChannelImpl.java:439)
at sun.nio.ch.FileChannelImpl.transferTo(FileChannelImpl.java:510)
</code>```

I mean - the computer has 3GB of RAM. A 100GB buffer should be enough!?!?

Apparently the DOS commands "copy" and "xcopy" also fail.

(edit) I've tried COPY & XCOPY - these fail with the same error. XCOPY seems to take a really really long time about it too.

I've heard of Robocopy, but it doesn't copy single files?

I'm really feeling that Windows is for the lose right now. Surely microsoft have heard of files larger than a few GB?

Thanks!

答:
Take a look at this Hotfix, worth a try as everything I have seen points to this as being a cure for your issue.

EDIT: You can also try XCOPY /Z as pointed out here.

ContentLicense: CC BY-SA 2.5

Title: How to copy a large file in Windows XP?

Body:
I have a large file in windows XP - its 38GB. (a VM image)

I cannot seem to copy it.

Dragging on the desktop - gives error of "Insufficient system resources exist to complete the requested service"

Using Java - FileChannel.transferTo(0, fileSize, dest) fails for all files > 2GB

Using Java - FileChannel.transferTo() in chunks of 100Mb fails after ~18Gb

java.io.IOException: Insufficient system resources exist to complete the requested service
at sun.nio.ch.FileDispatcher.write0(Native Method)
at sun.nio.ch.FileDispatcher.write(FileDispatcher.java:44)
at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:72)
at sun.nio.ch.IOUtil.write(IOUtil.java:28)
at sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:198)
at sun.nio.ch.FileChannelImpl.transferToTrustedChannel(FileChannelImpl.java:439)
at sun.nio.ch.FileChannelImpl.transferTo(FileChannelImpl.java:510)

I mean - the computer has 3GB of RAM. A 100GB buffer should be enough!?!?

Apparently the DOS commands "copy" and "xcopy" also fail.

(edit) I've tried COPY & XCOPY - these fail with the same error. XCOPY seems to take a really really long time about it too.

I've heard of Robocopy, but it doesn't copy single files?

I'm really feeling that Windows is for the lose right now. Surely microsoft have heard of files larger than a few GB?

Thanks!


问:
How to change edge thickness in D3.js?
Code example https://jsfiddle.net/greggyNapalm/xtg7t5ch/
I want to control edge thickness with weight attr.

答:
First remove this line from your path.link class from CSS file.

```<code>stroke-width: 2.0px;
</code>```

Then, in your java-script file add following line in path variable.

```<code>.attr("stroke-width", function(d) { return (d.weight); })
</code>```

Another method by which you can override the style property which @drone6502 suggested, is to add style attribute. Here, no need to remove stroke-width from CSS.

```<code>.attr("style", function(d) { return ("stroke-width:" + d.weight + "px;");})
</code>```

Title: How to change edge thickness in D3.js?

Body:
First remove this line from your path.link class from CSS file.

stroke-width: 2.0px;

Then, in your java-script file add following line in path variable.

.attr("stroke-width", function(d) { return (d.weight); })

Another method by which you can override the style property which @drone6502 suggested, is to add style attribute. Here, no need to remove stroke-width from CSS.

.attr("style", function(d) { return ("stroke-width:" + d.weight + "px;");})


问:
How should I define or reinitialize this variable?
I have something like this:

var menu = (function() {
  var itemContainer = $('#item-container');
  var items = $('.item');

  return {
    countItems: function() {
      //do something with items object.  This does not work.
      console.log('items.length: ' + items.length)
    },
    manipulateItemContainer: function() {
      //do something with itemContainer object. This works fine.
    },
    populate: function() {
      //dynamically create elements with .item class
      var item1 = $('
', {
        class: 'item'
      }).appendTo(itemContainer);
      var item2 = $('
', {
        class: 'item'
      }).appendTo(itemContainer);
      var item3 = $('
', {
        class: 'item'
      }).appendTo(itemContainer);
    },
    addItem: function() {
      var item = $('
', {
        class: 'item'
      }).appendTo(itemContainer);
    }
  }

})();

menu.populate();
menu.countItems();
menu.addItem();
menu.countItems();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.item {
  width: 20px;
  height: 20px;
  display: inline-block;
  background-color: green;
  margin: 1px;
}</code>```

```

In this scenario, items is empty.  How should I reconfigure this to address the issue?  Create an init() function and run it at the end of .populate()?  Other options?  Or am I missing something else completely?

答:
Since the number of items available is dynamic, perhaps using retrieving them with a function call would work better:</p>

```<code>var menu = function() {
  var itemContainer = $('#item-container');

  function getItems() {
      return $('.item');
  }

  return {
    manipulateItems: function() {
      //do something with items object.  This does not work.
      // check if there are any items first
      if (getItems()) {
        // work with items
      }
    },
    manipulateItemContainer: function() {
      //do something with itemContainer object. This works fine.
    },
    populate: function() {
      //dynamically create elements with .item class
    }
  }

}
</code>```

Body:
I have something like this:

var menu = (function() {
  var itemContainer = $('#item-container');
  var items = $('.item');

  return {
    countItems: function() {
      //do something with items object.  This does not work.
      console.log('items.length: ' + items.length)
    },
    manipulateItemContainer: function() {
      //do something with itemContainer object. This works fine.
    },
    populate: function() {
      //dynamically create elements with .item class
      var item1 = $('
', {
        class: 'item'
      }).appendTo(itemContainer);
      var item2 = $('
', {
        class: 'item'
      }).appendTo(itemContainer);
      var item3 = $('
', {
        class: 'item'
      }).appendTo(itemContainer);
    },
    addItem: function() {
      var item = $('
', {
        class: 'item'
      }).appendTo(itemContainer);
    }
  }

})();

menu.populate();
menu.countItems();
menu.addItem();
menu.countItems();

.item {
  width: 20px;
  height: 20px;
  display: inline-block;
  background-color: green;
  margin: 1px;
}

In this scenario, items is empty.  How should I reconfigure this to address the issue?  Create an init() function and run it at the end of .populate()?  Other options?  Or am I missing something else completely?

Body:
Since the number of items available is dynamic, perhaps using retrieving them with a function call would work better:

var menu = function() {
  var itemContainer = $('#item-container');

  function getItems() {
      return $('.item');
  }

  return {
    manipulateItems: function() {
      //do something with items object.  This does not work.
      // check if there are any items first
      if (getItems()) {
        // work with items
      }
    },
    manipulateItemContainer: function() {
      //do something with itemContainer object. This works fine.
    },
    populate: function() {
      //dynamically create elements with .item class
    }
  }

}


问:
D2L / BrightSpace - Create user within a course and within a section and assign user a role
So I am trying to Enroll a user in a section for a particular org unit (Course)

This all works fine and I can add them into the section etc using:

```<code>POST /d2l/api/lp/(version)/(orgUnitId)/sections/(sectionId)/enrollments/¶
</code>```

But the issue is, I am only able to POST one attribute, user ID. I need to be able to post the RoleID as well so I can specify whether they are a student or staff, as it assigned them 'teacher'.

Is there a way to do this / a different approach?

Cheers,

Alex.

答:
Enrollments in Sections and Groups are effectively treated as special sub-components of a Course Offering; the APIs that let you enroll a user into a Section or Group therefore assume that you want to take the user/role enrolled in the parent course offering and "assign" them to this Group or that Section (with the same enrollment role).

You are correct that if you want to have them enrolled with a different role, you should instead use the general enrollments API (assuming you have permissions; your calling user context may well have permissions to assign a user to a group or a section, but not to enroll them generally).

Body:
So I am trying to Enroll a user in a section for a particular org unit (Course)

This all works fine and I can add them into the section etc using:

POST /d2l/api/lp/(version)/(orgUnitId)/sections/(sectionId)/enrollments/¶

But the issue is, I am only able to POST one attribute, user ID. I need to be able to post the RoleID as well so I can specify whether they are a student or staff, as it assigned them 'teacher'.

Is there a way to do this / a different approach?

Cheers,

Alex.


问:
Show echo in previous php file
I'm Probably searching with the wrong keywords, but I can not find the correct answer.

I have a php file(overview.php) which contains a button, this button executes another php script(mailinfo.php) which sends a email and shows a echo line when successful .

```<code><input onclick="location.href = 'mailinfo.php';" type="button" value="Nee" class="btn btn-danger btn-md">
</code>```

When I click the button, mail.php is loaded and i only see the echo. I would like to see this echo on overview.php without showing the mail.php page.

答:
PHP is server-side code. Your button is on the client. Your button cannot "execute" a PHP file. It can trigger navigation to another page (as your code is currently doing) or send an AJAX request to mailinfo.php on the server.

It sounds like you are looking for an AJAX solution. You can read more about AJAX here: https://www.wired.com/2010/02/ajax_for_beginners/
Or here: https://www.tutorialspoint.com/ajax/

Title: Show echo in previous php file

Body:
I'm Probably searching with the wrong keywords, but I can not find the correct answer.

I have a php file(overview.php) which contains a button, this button executes another php script(mailinfo.php) which sends a email and shows a echo line when successful .

<input onclick="location.href = 'mailinfo.php';" type="button" value="Nee" class="btn btn-danger btn-md">

When I click the button, mail.php is loaded and i only see the echo. I would like to see this echo on overview.php without showing the mail.php page.


问:
How to prevent attacks on WordPress wp-login.php page
On my website, the highest GPU usage is actually on the WordPress login page, not the home page. I have basically come to the conclusion that it is being attacked by a brute force attack, or something similar.

I have installed a plugin that prevents password attacks from bots, but it doesn't prevent the bots from actually visiting the page in the first place.

I want to change the location of the login page to something like wp-login-here.php, or perhaps there is a better solution. The Stealth Plugin seems like it would do the trick, but it is not compatible with recent versions of WordPress. Any ideas?

EDIT: The real solution to this problem was for me to do a clean install of WordPress, this time in a version that was supported by the Stealth plugin. After installing WP and the Stealth plugin on this earlier version of WP, I used the .htaccess file that the plugin created and copied it over (after making a few modifications) to the production site. The reason I accepted the answer I did was because Bad Behavior ended up being a good plugin, and the other advice was useful.

答: As a suggestion, if you're on a static IP you could use a .htaccess .passwd file to restrict access to the admin directory to a known list of IP addresses. Whilst this won't prevent the access attempts, it will at least lower the resource usage. </p>


问:
sql including row even if values are null MS-Access
I'm creating a query that gets the amount of retired people per fiscal year.
Let's say I have this table:

```<code> table1

|  FY   |  Reason for leave |
|2011-12|       sick        |
|2011-12|       retired     |
|2011-12|       retire      |
|2012-13|       sick        |
|2014-15|       retired     |
|2014-15|       retired     |
|2014-15|       retired     |
</code>```

My Query is:

```<code>Select FY, Count(*) FROM table1 WHERE [Reason for leave] = "retired";
</code>```

The problem is it won't return 2012-13 as one of the fiscal years, which makes sense, but I'd like for it to include all the years with either 0 or a blank as the count column

Thanks alot in advance!

答:
If you have a separate table of years you could left join to your table1. If you don't, you could use something like this:-</p>

```<code>select FY, sum (iif([Reason for leave]="retired",1,0)) as Count_Retired
from table1
group by FY;
</code>```

Body:
I'm creating a query that gets the amount of retired people per fiscal year.
Let's say I have this table:

 table1

|  FY   |  Reason for leave |
|2011-12|       sick        |
|2011-12|       retired     |
|2011-12|       retire      |
|2012-13|       sick        |
|2014-15|       retired     |
|2014-15|       retired     |
|2014-15|       retired     |

My Query is:

Select FY, Count(*) FROM table1 WHERE [Reason for leave] = "retired";

The problem is it won't return 2012-13 as one of the fiscal years, which makes sense, but I'd like for it to include all the years with either 0 or a blank as the count column

Thanks alot in advance!

Body:
If you have a separate table of years you could left join to your table1. If you don't, you could use something like this:-

select FY, sum (iif([Reason for leave]="retired",1,0)) as Count_Retired
from table1
group by FY;


问:
Cannot deploy new version to App Engine Flexible
I tried to deploy new version to app engine. But it keeps saying

vm_check_disk_space.sh and health check logs.

and on web browser it gives me 502 error saying

```<code>Error: Server Error

The server encountered a temporary error and could not complete your
request.
Please try again in 30 seconds.
</code>```

I have tried 4 times trying to deploy but never worked.
I think you can reproduce this by deploying any project to app engine.

I am using Google Cloud SDK 157.0.0
and
tried to deploy service with java and nodejs environment

答:
I received many weird errors like this while deploying months ago with both maven and gradle.  Various strange things with app.yaml can cause this as well.  Even the example projects provided from google contained strange bugs like this when deployed.

Try one of the test projects that google provides: Google NodeJS bookshelf app

(Hopefully this project has been fixed by now and will deploy correctly!!)

Also, it's possible that an old version can prevent your new code from deploying.  Go to your console, and delete/stop all running versions of the service.  (I have had issues with old versions becoming stuck, which causes issues with the new deployment becoming the default service).

Body:
I tried to deploy new version to app engine. But it keeps saying

vm_check_disk_space.sh and health check logs.

and on web browser it gives me 502 error saying

Error: Server Error

The server encountered a temporary error and could not complete your
request.
Please try again in 30 seconds.

I have tried 4 times trying to deploy but never worked.
I think you can reproduce this by deploying any project to app engine.

I am using Google Cloud SDK 157.0.0
and
tried to deploy service with java and nodejs environment


问:
UISwitch detailed text underneath

I want to be able to put the descriptive text underneath the label. Below is the code I have thus far:

```<code>UISwitch *toggle = [[UISwitch alloc] init];
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"Cell"];
    cell.textLabel.text = @"Remote Execution";
    cell.detailTextLabel.text = @"Remote execution will permit registered devices to execute tests without manually starting them";
    [cell addSubview:toggle];
    cell.accessoryView = toggle;
    [cell.detailTextLabel setAlpha:1.0];
    [cell.detailTextLabel setTextColor:[UIColor redColor]];
</code>```

答:
Use UITableViewCellStyleSubtitle instead of UITableViewCellStyleValue1:

```<code>cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
</code>```

Title: UISwitch detailed text underneath

Body:
I want to be able to put the descriptive text underneath the label. Below is the code I have thus far:

UISwitch *toggle = [[UISwitch alloc] init];
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"Cell"];
    cell.textLabel.text = @"Remote Execution";
    cell.detailTextLabel.text = @"Remote execution will permit registered devices to execute tests without manually starting them";
    [cell addSubview:toggle];
    cell.accessoryView = toggle;
    [cell.detailTextLabel setAlpha:1.0];
    [cell.detailTextLabel setTextColor:[UIColor redColor]];

Body:
Use UITableViewCellStyleSubtitle instead of UITableViewCellStyleValue1:

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];


问:
The procedure entry point clCreateCommandQueueWithProperties could not be located in the dynamic link library
I've been trying to get OpenCL working with visual studio.

I followed this guide for configuring the AMD OpenCL SDK.

Here is my short example program

```<code>#include "stdafx.h"
#include <CL/cl.h>
#include <stdio.h>
#include <iostream>

using namespace std;

const char *source =
"__kernel void memset( __global uint *dst ) \n"
"{ \n"
" dst[get_global_id(0)] = get_global_id(0); \n"
"} \n";

int main()
{
    cl_platform_id platform;

    clGetPlatformIDs(1, &platform, NULL);

    cl_device_id device;

    clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL);

    cl_context context = clCreateContext
    (
        NULL,
        1,
        &device,
        NULL,
        NULL,
        NULL
    );

    cl_command_queue queue = clCreateCommandQueueWithProperties
    (
        context,
        device,
        0,
        NULL
    );

    return 0;

}
</code>```

But when I run it I get this runtime error

The procedure entry point clCreateCommandQueueWithProperties could not
  be located in the dynamic link library

I viewed the dll using dll export viewer and the function does indeed appear to be in the OpenCL.dll.

EDIT

I think Mats Petersson is right I did a file search on my PC and found multiple OpenCL.dll files

I'm not sure how to fix this in a sensible way....

EDIT

It's probably also worth noting here that the program runs fine when I remove the call to clCreateCommandQueueWithProperties.

答:
I replaced C:\Windows\System32\OpenCL.dll with the one located in C:\Program Files (x86)\AMD APP SDK\3.0\bin\x86\OpenCL.dll

AND

I replaced C:\Windows\SysWOW64\OpenCL.dll with the one located in C:\Program Files (x86)\AMD APP SDK\3.0\bin\x86_64\OpenCL.dll

This worked for me.

Body:
I've been trying to get OpenCL working with visual studio.

I followed this guide for configuring the AMD OpenCL SDK.

Here is my short example program

#include "stdafx.h"
#include <CL/cl.h>
#include <stdio.h>
#include <iostream>

using namespace std;

const char *source =
"__kernel void memset( __global uint *dst ) \n"
"{ \n"
" dst[get_global_id(0)] = get_global_id(0); \n"
"} \n";

int main()
{
    cl_platform_id platform;

    clGetPlatformIDs(1, &platform, NULL);

    cl_device_id device;

    clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL);

    cl_context context = clCreateContext
    (
        NULL,
        1,
        &device,
        NULL,
        NULL,
        NULL
    );

    cl_command_queue queue = clCreateCommandQueueWithProperties
    (
        context,
        device,
        0,
        NULL
    );

    return 0;

}

But when I run it I get this runtime error

The procedure entry point clCreateCommandQueueWithProperties could not
  be located in the dynamic link library

I viewed the dll using dll export viewer and the function does indeed appear to be in the OpenCL.dll.

EDIT

I think Mats Petersson is right I did a file search on my PC and found multiple OpenCL.dll files

I'm not sure how to fix this in a sensible way....

EDIT

It's probably also worth noting here that the program runs fine when I remove the call to clCreateCommandQueueWithProperties.


问:
how to connect to MySQL on localhost
I have wamp installed and have changed the default port (apache) to port 8888.
Now, I can see the landing page when I go to http://localhost:8888/app
But, when I try to connect to my database as follows:

```<code>function get_db_conn() {
    $conn = mysql_connect('localhost', 'root','');
    if (!$conn) {
    die('Could not connect: '. mysql_error());
    }
    $db_selected = mysql_select_db('bargainalerts_db', $conn);

    if ($db_selected) {
        return $conn;
    }
    else {
        return null;
    }
}
</code>```

The conn variable is always null. I can't connect to my database.I imagine it's something to do with the localhost:8888 bit. I tried setting this as the database url but it just times out. I can view the phpmyadmin control panel via the same url as above.

But I just cant get a php connection. Any help would be greatly welcolmed! Thank you.

答: Check that your database if started, that you have indeed root as user and an empty password (which I doubt). Check also your MySQL port (3306 by default) and inspect the output of mysql_error()

Title: how to connect to MySQL on localhost

Body:
I have wamp installed and have changed the default port (apache) to port 8888.
Now, I can see the landing page when I go to http://localhost:8888/app
But, when I try to connect to my database as follows:

function get_db_conn() {
    $conn = mysql_connect('localhost', 'root','');
    if (!$conn) {
    die('Could not connect: '. mysql_error());
    }
    $db_selected = mysql_select_db('bargainalerts_db', $conn);

    if ($db_selected) {
        return $conn;
    }
    else {
        return null;
    }
}

The conn variable is always null. I can't connect to my database.I imagine it's something to do with the localhost:8888 bit. I tried setting this as the database url but it just times out. I can view the phpmyadmin control panel via the same url as above.

But I just cant get a php connection. Any help would be greatly welcolmed! Thank you.


问:
Using a System.Exception Object in EventSource
I'm trying to use Event Source (Microsoft.Diagnostics.EventFlow.Inputs.EventSource) to create an event that is handled by Event Flow (Microsoft.Diagnostic.EventFlow) and whose output is passed to Application Insights (Microsoft.Diagnostics.EventFlow.Outputs.ApplicationInsights) for analysis.

The event flow library seems to require that I pass the full System.Exception object to event flow in order to for it to be successfully classified as an exception event in Application Insights.

Here is the filter I am using in Event Flow for my exception:

```<code>    {
      "type": "metadata",
      "metadata": "exception",
      "include": "EventId == 21",
      "exceptionProperty": "shark"
    }
</code>```

Here are my methods where I am currently generating the Event which I wish to handle with event flow. Currently this does appear inside application insights however I belie I have implemented it poorly as I see message below in the output window during runtime.

The parameters to the Event method do not match the parameters to the WriteEvent method. This may cause the event to be displayed incorrectly.

```<code>    private const int TestExceptionEventId = 21;
    [NonEvent]
    public void TestException(string operationType, Exception ex)
    {
        string shark = ex.ToString();
        TestException(operationType, shark);
        WriteEvent(TestExceptionEventId, operationType, ex);
    }

    [Event(TestExceptionEventId, Level = EventLevel.Error, Message = "{0} - {1}, {2}", Keywords = Keywords.Exception)]
    public void TestException(string operationType, string shark)
    {

    }
</code>```

Here is the method where the logging event is fired:

```<code> //EXCEPTION
 //id = 21
 try
 {
     int value = 1 / int.Parse("0");
 }
 catch (DivideByZeroException exception)
 {
     //id = 21
     _eventSource.TestException("hello", exception);
 }`
</code>```

Can anyone provide some clarity on the correct way to implement this and what is the correct way to pass an System.Exception Object through Event Flow and Onto Application Insights.

Many Thanks.

答:
There are two separate issues here. One is the error you get and the other one is the EventFlow configuration for the exception metadata. I will address both.

The error

The method that is decorated with the [Event] attribute is the one that should call WriteEvent. For example:

```<code>private const int TestExceptionEventId = 21;

[NonEvent]
public void TestException(string operationType, Exception ex)
{
    string shark = ex.ToString();
    TestException(operationType, shark);
}

[Event(TestExceptionEventId, Level = EventLevel.Error, Message = "{0} - {1}", Keywords = Keywords.Exception)]
public void TestException(string operationType, string shark)
{
    WriteEvent(TestExceptionEventId, operationType, shark);
}
</code>```

Note: your original Message property had the value Message = "{0} - {1}, {2}", yet you provide only 2 parameters to the method (string operationType and string shark). Hence the error. That is why I changed it to Message = "{0} - {1}"

There are some specific rules in order to have it working. From the docs:

When you implement a method that is identified as an ETW event in an EventSource-derived class. You must call the base class WriteEvent method passing the EventId and the same arguments as the implemented method

EventFlow configuration

Here lies the biggest issue. The EventSource class does not allow you to write non-primitives using WriteEvent. That includes an Exception. From the docs:

If the event has additional data, these should be passed as arguments. Currently only primitive types, DateTime, and string are allowed to be logged with the event.

There is an issue on the GitHub repo that outlines your possibilities:

I think you have a few options.

One is to use EventSource.Write method https://msdn.microsoft.com/en-us/library/system.diagnostics.tracing.eventsource.write(v=vs.110).aspx This should work well if you are using .NET Core, although I will be honest--I haven't tested it. Unfortunately with full framework there is a bug in the framework that prevents EventFlow from reading the event level correctly, so it is not a recommended way if you are using full (desktop) framework.

Second option is to use a different logging library (e.g. Serilog) that allows you to pass arbitrary objects into EventFlow.

Yet another option is to use custom EventFlow input. That should be not nearly as troublesome as a custom output for AI. I think you could even integrate it with your EventSource e.g. by making the EventSource implement IObservable and using [NonEvent] methods to raise events that carry exception objects. This way you will have just one logging API, your EventSource, for the application to use.

My 2 cents

My advice (I ended up doing that): forget about EventSource and use another logging library. The best part about using the EventSource is the fact that it features structured logging. I ended up using SeriLog that features this as well. It does support non-primitive types to be written to the log. EventFlow supports SeriLog as an input as well or you can configure the Application Insights (AI) sink for SeriLog that sends the data to Application Insights.

If you decide to go for that option you can take a look at my implementation

Body:
I'm trying to use Event Source (Microsoft.Diagnostics.EventFlow.Inputs.EventSource) to create an event that is handled by Event Flow (Microsoft.Diagnostic.EventFlow) and whose output is passed to Application Insights (Microsoft.Diagnostics.EventFlow.Outputs.ApplicationInsights) for analysis.

The event flow library seems to require that I pass the full System.Exception object to event flow in order to for it to be successfully classified as an exception event in Application Insights.

Here is the filter I am using in Event Flow for my exception:

    {
      "type": "metadata",
      "metadata": "exception",
      "include": "EventId == 21",
      "exceptionProperty": "shark"
    }

Here are my methods where I am currently generating the Event which I wish to handle with event flow. Currently this does appear inside application insights however I belie I have implemented it poorly as I see message below in the output window during runtime.

The parameters to the Event method do not match the parameters to the WriteEvent method. This may cause the event to be displayed incorrectly.

    private const int TestExceptionEventId = 21;
    [NonEvent]
    public void TestException(string operationType, Exception ex)
    {
        string shark = ex.ToString();
        TestException(operationType, shark);
        WriteEvent(TestExceptionEventId, operationType, ex);
    }

    [Event(TestExceptionEventId, Level = EventLevel.Error, Message = "{0} - {1}, {2}", Keywords = Keywords.Exception)]
    public void TestException(string operationType, string shark)
    {

    }

Here is the method where the logging event is fired:

 //EXCEPTION
 //id = 21
 try
 {
     int value = 1 / int.Parse("0");
 }
 catch (DivideByZeroException exception)
 {
     //id = 21
     _eventSource.TestException("hello", exception);
 }`

Can anyone provide some clarity on the correct way to implement this and what is the correct way to pass an System.Exception Object through Event Flow and Onto Application Insights.

Many Thanks.

Body:
There are two separate issues here. One is the error you get and the other one is the EventFlow configuration for the exception metadata. I will address both.

The error

The method that is decorated with the [Event] attribute is the one that should call WriteEvent. For example:

private const int TestExceptionEventId = 21;

[NonEvent]
public void TestException(string operationType, Exception ex)
{
    string shark = ex.ToString();
    TestException(operationType, shark);
}

[Event(TestExceptionEventId, Level = EventLevel.Error, Message = "{0} - {1}", Keywords = Keywords.Exception)]
public void TestException(string operationType, string shark)
{
    WriteEvent(TestExceptionEventId, operationType, shark);
}

Note: your original Message property had the value Message = "{0} - {1}, {2}", yet you provide only 2 parameters to the method (string operationType and string shark). Hence the error. That is why I changed it to Message = "{0} - {1}"

There are some specific rules in order to have it working. From the docs:

When you implement a method that is identified as an ETW event in an EventSource-derived class. You must call the base class WriteEvent method passing the EventId and the same arguments as the implemented method

EventFlow configuration

Here lies the biggest issue. The EventSource class does not allow you to write non-primitives using WriteEvent. That includes an Exception. From the docs:

If the event has additional data, these should be passed as arguments. Currently only primitive types, DateTime, and string are allowed to be logged with the event.

There is an issue on the GitHub repo that outlines your possibilities:

I think you have a few options.

One is to use EventSource.Write method https://msdn.microsoft.com/en-us/library/system.diagnostics.tracing.eventsource.write(v=vs.110).aspx This should work well if you are using .NET Core, although I will be honest--I haven't tested it. Unfortunately with full framework there is a bug in the framework that prevents EventFlow from reading the event level correctly, so it is not a recommended way if you are using full (desktop) framework.

Second option is to use a different logging library (e.g. Serilog) that allows you to pass arbitrary objects into EventFlow.

Yet another option is to use custom EventFlow input. That should be not nearly as troublesome as a custom output for AI. I think you could even integrate it with your EventSource e.g. by making the EventSource implement IObservable and using [NonEvent] methods to raise events that carry exception objects. This way you will have just one logging API, your EventSource, for the application to use.

My 2 cents

My advice (I ended up doing that): forget about EventSource and use another logging library. The best part about using the EventSource is the fact that it features structured logging. I ended up using SeriLog that features this as well. It does support non-primitive types to be written to the log. EventFlow supports SeriLog as an input as well or you can configure the Application Insights (AI) sink for SeriLog that sends the data to Application Insights.

If you decide to go for that option you can take a look at my implementation


问:
Syntax in ng-style & merging ng-styles
I have an ng-style in my project that looks like:

```<code>ng-style="{'background-color':(headerObj.inEditBool?'background-color: rgba(101, 182, 231, 0.11);':headerObj.confirmedOrSkipBool?'white':'rgba(215, 44, 44, 0.3)')}"
</code>```

I want a second attribute of the element (border color) to be affected in the same statement... How can I add that change?

```<code>ng-style="{'border-color':(headerObj.inEditBool?'border-color: #65B6E7;':headerObj.confirmedOrSkipBool?'#DFE3E9;':'#E06A62;')}"
</code>```

This is the border color I want to make a change to. How to merge 2 ng-styles so I can affect the background color and border color of the same element?

答:
Add another property to the style object:

```<code>  {
    'background-color':(headerObj.inEditBool?'rgba(101, 182, 231, 0.11)':headerObj.confirmedOrSkipBool?'white':'rgba(215, 44, 44, 0.3)'),
    'border-color':(headerObj.inEditBool?' #65B6E7':headerObj.confirmedOrSkipBool?'#DFE3E9':'#E06A62')
  }
</code>```

I don't like using multiple tertiary operators like that, it's difficult to read and hard to update. I'd break it out into a function instead. Also, I don't think you need the semicolons either. edit2: the object property name is where you list the style name, you also had it in the property value, I don't think that works.

Title: Syntax in ng-style & merging ng-styles

Body:
I have an ng-style in my project that looks like:

ng-style="{'background-color':(headerObj.inEditBool?'background-color: rgba(101, 182, 231, 0.11);':headerObj.confirmedOrSkipBool?'white':'rgba(215, 44, 44, 0.3)')}"

I want a second attribute of the element (border color) to be affected in the same statement... How can I add that change?

ng-style="{'border-color':(headerObj.inEditBool?'border-color: #65B6E7;':headerObj.confirmedOrSkipBool?'#DFE3E9;':'#E06A62;')}"

This is the border color I want to make a change to. How to merge 2 ng-styles so I can affect the background color and border color of the same element?

Body:
Add another property to the style object:

  {
    'background-color':(headerObj.inEditBool?'rgba(101, 182, 231, 0.11)':headerObj.confirmedOrSkipBool?'white':'rgba(215, 44, 44, 0.3)'),
    'border-color':(headerObj.inEditBool?' #65B6E7':headerObj.confirmedOrSkipBool?'#DFE3E9':'#E06A62')
  }

I don't like using multiple tertiary operators like that, it's difficult to read and hard to update. I'd break it out into a function instead. Also, I don't think you need the semicolons either. edit2: the object property name is where you list the style name, you also had it in the property value, I don't think that works.


问:
ZF3 - composer require module -> module could not be initialised
I am working with the skeleton-application as a base, using the Vagrant / Composer setup. After the initial install I realised I would need the LDAP module. I then ran composer require zendframework/zend-ldap which ran successfully and I have located the files in ~/vendor/zendframework/zend-ldap.

The issue is when I add 'Zend\Ldap' to my ~/config/modules.config.php I encounter the following error:

```<code>Fatal error: Uncaught Zend\ModuleManager\Exception\RuntimeException: Module (Zend\Ldap) could not be initialized. in /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php:203 Stack trace: #0 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(175): Zend\ModuleManager\ModuleManager->loadModuleByName(Object(Zend\ModuleManager\ModuleEvent))
#1 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(97): Zend\ModuleManager\ModuleManager->loadModule('Zend\\Ldap') #2 /var/www/vendor/zendframework/zend-eventmanager/src/EventManager.php(322): Zend\ModuleManager\ModuleManager->onLoadModules(Object(Zend\ModuleManager\ModuleEvent))
#3 /var/www/vendor/zendframework/zend-eventmanager/src/EventManager.php(171): Zend\EventManager\EventManager->triggerListeners(Object(Zend\ModuleManager\ModuleEvent))
#4 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(120): Zend\EventManager\EventManager->triggerEvent(Object(Zend\ModuleManager\ModuleEvent))
#5 /var/www/vendor/zendfr in /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php on line 203
</code>```

The ~/config/modules.config.php file:

```<code>/**
 * List of enabled modules for this application.
 *
 * This should be an array of module namespaces used in the application.
 */
return [
    'Zend\Session',
    'Zend\Mvc\Plugin\Prg',
    'Zend\Mvc\Plugin\Identity',
    'Zend\Mvc\Plugin\FlashMessenger',
    'Zend\Mvc\Plugin\FilePrg',
    'Zend\Log',
    'Zend\Form',
    'Zend\Db',
    'Zend\Router',
    'Zend\Validator',
    'Zend\Ldap',    // All is well if this is commented out
    'Application',

];
</code>```

and the ~/config/application.config.php file:

```<code>/**
 * If you need an environment-specific system or application configuration,
 * there is an example in the documentation
 * @see https://docs.zendframework.com/tutorials/advanced-config/#environment-specific-system-configuration
 * @see https://docs.zendframework.com/tutorials/advanced-config/#environment-specific-application-configuration
 */
return [
    // Retrieve list of modules used in this application.
    'modules' => require __DIR__ . '/modules.config.php',

    // These are various options for the listeners attached to the ModuleManager
    'module_listener_options' => [
        // This should be an array of paths in which modules reside.
        // If a string key is provided, the listener will consider that a module
        // namespace, the value of that key the specific path to that module's
        // Module class.
        'module_paths' => [
            './module',
            './vendor',
        ],

        // An array of paths from which to glob configuration files after
        // modules are loaded. These effectively override configuration
        // provided by modules themselves. Paths may use GLOB_BRACE notation.
        'config_glob_paths' => [
            realpath(__DIR__) . '/autoload/{{,*.}global,{,*.}local}.php',
        ],

        // Whether or not to enable a configuration cache.
        // If enabled, the merged configuration will be cached and used in
        // subsequent requests.
        'config_cache_enabled' => true,

        // The key used to create the configuration cache file name.
        'config_cache_key' => 'application.config.cache',

        // Whether or not to enable a module class map cache.
        // If enabled, creates a module class map cache which will be used
        // by in future requests, to reduce the autoloading process.
        'module_map_cache_enabled' => true,

        // The key used to create the class map cache file name.
        'module_map_cache_key' => 'application.module.cache',

        // The path in which to cache merged configuration.
        'cache_dir' => 'data/cache/',

        // Whether or not to enable modules dependency checking.
        // Enabled by default, prevents usage of modules that depend on other modules
        // that weren't loaded.
        // 'check_dependencies' => true,
    ],

    // Used to create an own service manager. May contain one or more child arrays.
    // 'service_listener_options' => [
    //     [
    //         'service_manager' => $stringServiceManagerName,
    //         'config_key'      => $stringConfigKey,
    //         'interface'       => $stringOptionalInterface,
    //         'method'          => $stringRequiredMethodName,
    //     ],
    // ],

    // Initial configuration with which to seed the ServiceManager.
    // Should be compatible with Zend\ServiceManager\Config.
    // 'service_manager' => [],
];
</code>```

I have tried removing cache folder, running composer update, restarting Vagrant, adding the full path to the 'modules_path' array in application.config.php but it is always the same error. Interestingly I run into the same issue with 'Zend\View' that was included from the install, but a module such as 'Zend\Session' can be added to the modules.config.php file with no issues (They are all located in the vendor/zendframework directory)

Can anyone point me in the right direction to resolve this issue?

答:
As others have noted, zend-ldap does not provide a Module class; it is simply a component that provides functionality. It has no service definitions, which is why there is no Module class.

Two things to note:

Install zendframework/zend-component-installer in your application: composer require --dev zendframework/zend-component-installer. When you do, any time you add another component to your application that exposes a Module class, it will prompt you, asking if you want to add it to your application configuration. (zend-component-installer is installed by default if you start your project with the zendframework/skeleton-application.)

We have recently opened our Zend Framework forums; consider directing your ZF questions there in the future, to make the answers easily discoverable for ZF users.

Body:
I am working with the skeleton-application as a base, using the Vagrant / Composer setup. After the initial install I realised I would need the LDAP module. I then ran composer require zendframework/zend-ldap which ran successfully and I have located the files in ~/vendor/zendframework/zend-ldap.

The issue is when I add 'Zend\Ldap' to my ~/config/modules.config.php I encounter the following error:

Fatal error: Uncaught Zend\ModuleManager\Exception\RuntimeException: Module (Zend\Ldap) could not be initialized. in /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php:203 Stack trace: #0 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(175): Zend\ModuleManager\ModuleManager->loadModuleByName(Object(Zend\ModuleManager\ModuleEvent))
#1 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(97): Zend\ModuleManager\ModuleManager->loadModule('Zend\\Ldap') #2 /var/www/vendor/zendframework/zend-eventmanager/src/EventManager.php(322): Zend\ModuleManager\ModuleManager->onLoadModules(Object(Zend\ModuleManager\ModuleEvent))
#3 /var/www/vendor/zendframework/zend-eventmanager/src/EventManager.php(171): Zend\EventManager\EventManager->triggerListeners(Object(Zend\ModuleManager\ModuleEvent))
#4 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(120): Zend\EventManager\EventManager->triggerEvent(Object(Zend\ModuleManager\ModuleEvent))
#5 /var/www/vendor/zendfr in /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php on line 203

The ~/config/modules.config.php file:

/**
 * List of enabled modules for this application.
 *
 * This should be an array of module namespaces used in the application.
 */
return [
    'Zend\Session',
    'Zend\Mvc\Plugin\Prg',
    'Zend\Mvc\Plugin\Identity',
    'Zend\Mvc\Plugin\FlashMessenger',
    'Zend\Mvc\Plugin\FilePrg',
    'Zend\Log',
    'Zend\Form',
    'Zend\Db',
    'Zend\Router',
    'Zend\Validator',
    'Zend\Ldap',    // All is well if this is commented out
    'Application',

];

and the ~/config/application.config.php file:

/**
 * If you need an environment-specific system or application configuration,
 * there is an example in the documentation
 * @see https://docs.zendframework.com/tutorials/advanced-config/#environment-specific-system-configuration
 * @see https://docs.zendframework.com/tutorials/advanced-config/#environment-specific-application-configuration
 */
return [
    // Retrieve list of modules used in this application.
    'modules' => require __DIR__ . '/modules.config.php',

    // These are various options for the listeners attached to the ModuleManager
    'module_listener_options' => [
        // This should be an array of paths in which modules reside.
        // If a string key is provided, the listener will consider that a module
        // namespace, the value of that key the specific path to that module's
        // Module class.
        'module_paths' => [
            './module',
            './vendor',
        ],

        // An array of paths from which to glob configuration files after
        // modules are loaded. These effectively override configuration
        // provided by modules themselves. Paths may use GLOB_BRACE notation.
        'config_glob_paths' => [
            realpath(__DIR__) . '/autoload/{{,*.}global,{,*.}local}.php',
        ],

        // Whether or not to enable a configuration cache.
        // If enabled, the merged configuration will be cached and used in
        // subsequent requests.
        'config_cache_enabled' => true,

        // The key used to create the configuration cache file name.
        'config_cache_key' => 'application.config.cache',

        // Whether or not to enable a module class map cache.
        // If enabled, creates a module class map cache which will be used
        // by in future requests, to reduce the autoloading process.
        'module_map_cache_enabled' => true,

        // The key used to create the class map cache file name.
        'module_map_cache_key' => 'application.module.cache',

        // The path in which to cache merged configuration.
        'cache_dir' => 'data/cache/',

        // Whether or not to enable modules dependency checking.
        // Enabled by default, prevents usage of modules that depend on other modules
        // that weren't loaded.
        // 'check_dependencies' => true,
    ],

    // Used to create an own service manager. May contain one or more child arrays.
    // 'service_listener_options' => [
    //     [
    //         'service_manager' => $stringServiceManagerName,
    //         'config_key'      => $stringConfigKey,
    //         'interface'       => $stringOptionalInterface,
    //         'method'          => $stringRequiredMethodName,
    //     ],
    // ],

    // Initial configuration with which to seed the ServiceManager.
    // Should be compatible with Zend\ServiceManager\Config.
    // 'service_manager' => [],
];

I have tried removing cache folder, running composer update, restarting Vagrant, adding the full path to the 'modules_path' array in application.config.php but it is always the same error. Interestingly I run into the same issue with 'Zend\View' that was included from the install, but a module such as 'Zend\Session' can be added to the modules.config.php file with no issues (They are all located in the vendor/zendframework directory)

Can anyone point me in the right direction to resolve this issue?


问:
Which PHP version is currently running 5.2.15 or 5.3.4?

           i often read official PHP website website.

on 9 Dec,2010 headlines was   PHP 5.2.15 Released! and

on 10 Dec,2010 headlines was  PHP 5.3.4 Released!

i m really confused that what means of two different headlines??
i think version order are may b wrong or what is this??please explain PHP GURU

please tell me what should i said when interviewer ask which version of php we works currently??

ONE MORE THING

so which version we need to use for safeside, is that 5.3.x or 5.2.x???

答: The 5.2 and 5.3 series are both maintained in parallel, since 5.3 introduces some fairly big changes and might break older scripts.  The older version will therefore be maintained with security patches and bug fixes for some time to allow people time to migrate their scripts to the new version.</p>


问:
IndexOf: how many vowels there are?
I need to have the code tell the user how many of the five vowels (a,e,i,o,u) are in the first string, as well as the second string. This is what I've worked up so far but I'm stuck in terms of how to print how many vowels there are total.</p>

```<code>Scanner in=new Scanner(System.in);

    System.out.println( "Enter String 1: ");
    String s1=in.next();
    System.out.println( "Enter String 2: ");
    String s2=in.next();

   int a= s1.length();

   int b= s2.length();

   if (a<b)
   System.out.println( s2 + "is longer than " + s1);
   else if (b<a)
   System.out.println( s1 + " is longer than " + s2);
   else
   System.out.println(s1 + " and " + s2 + " are the same length.");

   int c=(s1.indexOf(('a')));
   int d=(s1.indexOf(('e')));
   int e=(s1.indexOf(('o')));
   int f=(s1.indexOf(('i')));
   int g=(s1.indexOf(('u')));

   if (c>=0)
   System.out.println( "AFFIRMATIVE FOR A");
   if (d>=0)
   System.out.println( "AFFIRMATIVE FOR E");
   if (e>=0)
   System.out.println( "AFFIRMAtive fOR O");
   if (f>=0)
   System.out.println( "AFFIRMATIVE for I");
   if (g>=0)
   System.out.println( "AFFIRMATIVE for U");
</code>```

答:
Like the guy above me said, you need to set a variable called totalVowels (or something like that) and increment it every time you encounter a vowel.

I'll take your own code (to make it a bit easier for you), and modify it a bit so you can see what I mean

```<code>       int totalVowels=0;

       int letterA=(s1.indexOf(('a')));
       int letterE=(s1.indexOf(('e')));
       int letterO=(s1.indexOf(('o')));
       int letterI=(s1.indexOf(('i')));
       int letterU=(s1.indexOf(('u')));

       if(letterA >=0){
          totalVowels ++; (this increments the total number of vowels)
       }
       if(letterE >=0){
          totalVowels ++;
       }
       if(letterO >=0){
          totalVowels ++;
       }
       if(letterI >=0){
          totalVowels ++;
       }
       if(letterU >=0){
          totalVowels ++;
       }

      System.out.println ("String1 contains" + totalVowels +" of the 5 vowels");
      totalVowels =0;
</code>```

Now this is not really the optimal way of doing it, but it follows your code closely and should do the job.

Title: IndexOf: how many vowels there are?

Body:
I need to have the code tell the user how many of the five vowels (a,e,i,o,u) are in the first string, as well as the second string. This is what I've worked up so far but I'm stuck in terms of how to print how many vowels there are total.

Scanner in=new Scanner(System.in);

    System.out.println( "Enter String 1: ");
    String s1=in.next();
    System.out.println( "Enter String 2: ");
    String s2=in.next();

   int a= s1.length();

   int b= s2.length();

   if (a<b)
   System.out.println( s2 + "is longer than " + s1);
   else if (b=0)
   System.out.println( "AFFIRMATIVE FOR A");
   if (d>=0)
   System.out.println( "AFFIRMATIVE FOR E");
   if (e>=0)
   System.out.println( "AFFIRMAtive fOR O");
   if (f>=0)
   System.out.println( "AFFIRMATIVE for I");
   if (g>=0)
   System.out.println( "AFFIRMATIVE for U");

Body:
Like the guy above me said, you need to set a variable called totalVowels (or something like that) and increment it every time you encounter a vowel.

I'll take your own code (to make it a bit easier for you), and modify it a bit so you can see what I mean

       int totalVowels=0;

       int letterA=(s1.indexOf(('a')));
       int letterE=(s1.indexOf(('e')));
       int letterO=(s1.indexOf(('o')));
       int letterI=(s1.indexOf(('i')));
       int letterU=(s1.indexOf(('u')));

       if(letterA >=0){
          totalVowels ++; (this increments the total number of vowels)
       }
       if(letterE >=0){
          totalVowels ++;
       }
       if(letterO >=0){
          totalVowels ++;
       }
       if(letterI >=0){
          totalVowels ++;
       }
       if(letterU >=0){
          totalVowels ++;
       }

      System.out.println ("String1 contains" + totalVowels +" of the 5 vowels");
      totalVowels =0;

Now this is not really the optimal way of doing it, but it follows your code closely and should do the job.


问:
FilePath points to mapped drive instead of actual server name
When I use this formula: =LEFT(CELL("filename"),FIND("[",CELL("filename"),1)-1)
to retrieve the file location of the open workbook, it always gives me something like

C:\Folder1\Folder2\Folder3

when in reality, I want

\\ausp-fil\Folder1\Folder2\Folder3.

ausp-fil is mapped onto the C: drive, and that's why it's showing up like that, but is there a way to make the formula retrieve the file location with the server name? I may have mapped ausp-fil to C: but I'm sure other people haven't.

答:
I doubt you will be able to do it using just a formula, but you can use this VBA function to convert the mapped drive letter to its UNC path. VBA Functions can be used in formulas.

```<code>Function GETNETWORKPATH(ByVal DriveName As String) As String
    Dim objNtWork  As Object
    Dim objDrives  As Object
    Dim lngLoop    As Long

    Set objNtWork = CreateObject("WScript.Network")
    Set objDrives = objNtWork.enumnetworkdrives

    For lngLoop = 0 To objDrives.Count - 1 Step 2
        If UCase(objDrives.Item(lngLoop)) = UCase(DriveName) Then
            GETNETWORKPATH = objDrives.Item(lngLoop + 1)
            Exit For
        End If
    Next

End Function

Sub kTest()

    MsgBox GETNETWORKPATH("P:")

End Sub
</code>```

Body:
I doubt you will be able to do it using just a formula, but you can use this VBA function to convert the mapped drive letter to its UNC path. VBA Functions can be used in formulas.

Function GETNETWORKPATH(ByVal DriveName As String) As String
    Dim objNtWork  As Object
    Dim objDrives  As Object
    Dim lngLoop    As Long

    Set objNtWork = CreateObject("WScript.Network")
    Set objDrives = objNtWork.enumnetworkdrives

    For lngLoop = 0 To objDrives.Count - 1 Step 2
        If UCase(objDrives.Item(lngLoop)) = UCase(DriveName) Then
            GETNETWORKPATH = objDrives.Item(lngLoop + 1)
            Exit For
        End If
    Next

End Function

Sub kTest()

    MsgBox GETNETWORKPATH("P:")

End Sub


问:
Create multiindex from existing dataframe
I've spent hours browsing everywhere now to try to create a multiindex from dataframe in pandas. This is the dataframe I have (posting excel sheet mockup. I do have this in pandas dataframe):

And this is what I want:

I have tried

```<code>newmulti = currentDataFrame.set_index(['user_id','account_num'])
</code>```

But it returns a dataframe, not a multiindex. Also, I could not figure out how to make 'user_id' level 0 and 'account_num' level 1. I think this must be trivial but I've read so many posts, tutorials, etc. and still could not figure it out. Partly because I'm a very visual person and most posts are not. Please help!

答:
You could simply use groupby in this case, which will create the multi-index automatically when it sums the sales along the requested columns.

```<code>df.groupby(['user_id', 'account_num', 'dates']).sales.sum().to_frame()
</code>```

You should also be able to simply do this:

```<code>df.set_index(['user_id', 'account_num', 'dates'])
</code>```

Although you probably want to avoid any duplicates (e.g. two or more rows with identical user_id, account_num and date values but different sales figures) by summing them, which is why I recommended using groupby.

If you need the multi-index, you can simply access viat new_df.index where new_df is the new dataframe created from either of the two operations above.

And user_id will be level 0 and account_num will be level 1.

Body:
I've spent hours browsing everywhere now to try to create a multiindex from dataframe in pandas. This is the dataframe I have (posting excel sheet mockup. I do have this in pandas dataframe):

And this is what I want:

I have tried

newmulti = currentDataFrame.set_index(['user_id','account_num'])

But it returns a dataframe, not a multiindex. Also, I could not figure out how to make 'user_id' level 0 and 'account_num' level 1. I think this must be trivial but I've read so many posts, tutorials, etc. and still could not figure it out. Partly because I'm a very visual person and most posts are not. Please help!

Body:
You could simply use groupby in this case, which will create the multi-index automatically when it sums the sales along the requested columns.

df.groupby(['user_id', 'account_num', 'dates']).sales.sum().to_frame()

You should also be able to simply do this:

df.set_index(['user_id', 'account_num', 'dates'])

Although you probably want to avoid any duplicates (e.g. two or more rows with identical user_id, account_num and date values but different sales figures) by summing them, which is why I recommended using groupby.

If you need the multi-index, you can simply access viat new_df.index where new_df is the new dataframe created from either of the two operations above.

And user_id will be level 0 and account_num will be level 1.


问:
Stack Smashing Detected in GCC
I'm new to C and I've found a peculiar output from gcc that I'm having a hard time getting to the bottom of. The error upon running the application is:

```<code>*** stack smashing detected ***: /home/joshua/Research/cml/test terminated

Program received signal SIGABRT, Aborted.
0x00007ffff7a43428 in __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54
54  ../sysdeps/unix/sysv/linux/raise.c: No such file or directory.
</code>```

I've done some research on this, and it appears that this is many times caused by tying to put too large a value into an array, for example; I'm not doing anything like that.

Here is my sample code for reference:

```<code> 1 #include <stdio.h>
  2 #include <string.h>
  3
  4 struct student
  5 {
  6      int id;
  7      char name[10];
  8      float percentage;
  9 };
 10
 11 int main()
 12 {
 13      int i;
 14      struct student record[2];
 15
 16      // 1st student's record
 17      record[0].id=1;
 18      strcpy(record[0].name, "Raju");
 19      record[0].percentage = 86.5;
 20
 21      // 2nd student's record
 22      record[1].id=2;
 23      strcpy(record[1].name, "Surendren");
 24      record[1].percentage = 90.5;
 25
 26      // 3rd student's record
 27      record[2].id=3;
 28      strcpy(record[2].name, "Thiyagu");
 29      record[2].percentage = 81.5;
 30
 31      for(i=0; i<3; i++)
 32      {
 33          printf("     Records of STUDENT : %d \n", i+1);
 34          printf(" Id is: %d \n", record[i].id);
 35          printf(" Name is: %s \n", record[i].name);
 36          printf(" Percentage is: %f\n\n",record[i].percentage);
 37      }
 38      return 0;
 39 }
</code>```

答:
```<code>struct student record[2];
</code>```

You've got an array of size 2 and you're trying to store 3 elements in it. Array indices go from 0 to n-1. record[2] is an invalid index.

Title: Stack Smashing Detected in GCC

Body:
I'm new to C and I've found a peculiar output from gcc that I'm having a hard time getting to the bottom of. The error upon running the application is:

*** stack smashing detected ***: /home/joshua/Research/cml/test terminated

Program received signal SIGABRT, Aborted.
0x00007ffff7a43428 in __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54
54  ../sysdeps/unix/sysv/linux/raise.c: No such file or directory.

I've done some research on this, and it appears that this is many times caused by tying to put too large a value into an array, for example; I'm not doing anything like that.

Here is my sample code for reference:

 1 #include <stdio.h>
  2 #include <string.h>
  3
  4 struct student
  5 {
  6      int id;
  7      char name[10];
  8      float percentage;
  9 };
 10
 11 int main()
 12 {
 13      int i;
 14      struct student record[2];
 15
 16      // 1st student's record
 17      record[0].id=1;
 18      strcpy(record[0].name, "Raju");
 19      record[0].percentage = 86.5;
 20
 21      // 2nd student's record
 22      record[1].id=2;
 23      strcpy(record[1].name, "Surendren");
 24      record[1].percentage = 90.5;
 25
 26      // 3rd student's record
 27      record[2].id=3;
 28      strcpy(record[2].name, "Thiyagu");
 29      record[2].percentage = 81.5;
 30
 31      for(i=0; i<3; i++)
 32      {
 33          printf("     Records of STUDENT : %d \n", i+1);
 34          printf(" Id is: %d \n", record[i].id);
 35          printf(" Name is: %s \n", record[i].name);
 36          printf(" Percentage is: %f\n\n",record[i].percentage);
 37      }
 38      return 0;
 39 }

Body:
struct student record[2];

You've got an array of size 2 and you're trying to store 3 elements in it. Array indices go from 0 to n-1. record[2] is an invalid index.


问:
Kafka server configuration - listeners vs. advertised.listeners
To get Kafka running, you need to set some properties in config/server.properties file. There are two settings I don't understand.

Can somebody explain the difference between listeners and advertised.listeners property?

The documentation says:

listeners:  The address the socket server listens on.

and

advertised.listeners:
      Hostname and port the broker will advertise to producers and consumers.

When do I have to use which setting?

答:
Since I cannot comment yet I will post this as an "answer", adding on to M.Situations answer.

Within the same document he links there is this blurb about which listener is used by a KAFKA client (https://cwiki.apache.org/confluence/display/KAFKA/KIP-103%3A+Separation+of+Internal+and+External+traffic):

As stated previously, clients never see listener names and will make metadata requests exactly as before. The difference is that the list of endpoints they get back is restricted to the listener name of the endpoint where they made the request.

This is important as depending on what URL you use in your bootstrap.servers config that will be the URL* that the client will get back if it is mapped in advertised.listeners (do not know what the behavior is if the listener does not exist).

Also note this:

The exception is ZooKeeper-based consumers. These consumers retrieve the broker registration information directly from ZooKeeper and will choose the first listener with PLAINTEXT as the security protocol (the only security protocol they support).

As an example broker config (for all brokers in cluster):

advertised.listeners=EXTERNAL://XXXXX.compute-1.amazonaws.com:9990,INTERNAL://ip-XXXXX.ec2.internal:9993

inter.broker.listener.name=INTERNAL

listener.security.protocol.map=EXTERNAL:SSL,INTERNAL:PLAINTEXT

If the client uses XXXXX.compute-1.amazonaws.com:9990 to connect, the metadata fetch will go to that broker. However, the returning URL to use with the Group Coordinator or Leader could be 123.compute-1.amazonaws.com:9990* (a different machine!). This means that the match is done on the listener name as advertised by KIP-103 irrespective of the actual URL (node).

Since the protocol map for EXTERNAL is SSL this would force you to use an SSL keystore to connect.

If on the other hand you are within AWS lets say, you can then issue ip-XXXXX.ec2.internal:9993 and the corresponding connection would be plaintext as per the protocol map.

This is especially needed in IaaS where in my case brokers and consumers live on AWS, whereas my producer lives on a client site, thus needing different security protocols and listeners.

EDIT:
Also adding Inbound Rules is much easier now that you have different ports for different clients (brokers, producers, consumers).

EDIT2:
This article is a great in depth guide if the above is still not clear: https://rmoff.net/2018/08/02/kafka-listeners-explained/

ContentLicense: CC BY-SA 4.0


答:
The 2 in

```<code>struct student record[2];
</code>```

is not the top index, it is the number of elements. And as you seem to know indexes start at zero which means the valid indexes are 0 and 1 for the above array. Going out of bounds leads to undefined behavior.

Title: Stack Smashing Detected in GCC

Body:
The 2 in

struct student record[2];

is not the top index, it is the number of elements. And as you seem to know indexes start at zero which means the valid indexes are 0 and 1 for the above array. Going out of bounds leads to undefined behavior.


问:
lodash json group object costs
Please,
I have this JSON object and want to group values by type.

```<code>var costs = [
  { 'name': 'JON', 'flight':100, 'value': 12,  type: 'uns' },
  { 'name': 'JON', 'flight':100, 'value': 35,  type: 'sch' },
  { 'name': 'BILL', 'flight':200, 'value': 33,  type: 'uns' },
  { 'name': 'BILL', 'flight':200, 'value': 45,  type: 'sch' }
];
</code>```

I want something like this:

```<code>var costs = [
  { 'name': 'JON', 'flight':100, 'uns': 12,  'sch': 35 },
  { 'name': 'BILL', 'flight':200, 'uns': 33,  'sch': 45}
];
</code>```

I try use lodash but without sucess:

```<code>var compiled_costs = _.chain(costs)
                      .groupBy("flight")
                      .value();

{
"100":
    [    {"name":"JON","flight":100,"value":12,"type":"uns"},
         {"name":"JON","flight":100,"value":35,"type":"sch"}
    ],
"200":
    [
         {"name":"BILL","flight":200,"value":33,"type":"uns"},
         {"name":"BILL","flight":200,"value":45,"type":"sch"}
    ]
}
</code>```

答:
You could use a closure over a hash table for same named objects.

var data = [{ name: 'JON', flight: 100, value: 12, type: 'uns' }, { name: 'JON', flight: 100, value: 35, type: 'sch' }, { name: 'BILL', flight: 200, value: 33, type: 'uns' }, { name: 'BILL', flight: 200, value: 45, type: 'sch' }],
    grouped = data.reduce(function (hash) {
        return function (r, o) {
            if (!hash[o.name]) {
                hash[o.name] = { name: o.name, flight: o.flight };
                r.push(hash[o.name]);
            }
            hash[o.name][o.type] = (hash[o.name][o.type] || 0) + o.value;
            return r;
        }
    }(Object.create(null)), []);

console.log(grouped);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: lodash json group object costs

Body:
Please,
I have this JSON object and want to group values by type.

var costs = [
  { 'name': 'JON', 'flight':100, 'value': 12,  type: 'uns' },
  { 'name': 'JON', 'flight':100, 'value': 35,  type: 'sch' },
  { 'name': 'BILL', 'flight':200, 'value': 33,  type: 'uns' },
  { 'name': 'BILL', 'flight':200, 'value': 45,  type: 'sch' }
];

I want something like this:

var costs = [
  { 'name': 'JON', 'flight':100, 'uns': 12,  'sch': 35 },
  { 'name': 'BILL', 'flight':200, 'uns': 33,  'sch': 45}
];

I try use lodash but without sucess:

var compiled_costs = _.chain(costs)
                      .groupBy("flight")
                      .value();

{
"100":
    [    {"name":"JON","flight":100,"value":12,"type":"uns"},
         {"name":"JON","flight":100,"value":35,"type":"sch"}
    ],
"200":
    [
         {"name":"BILL","flight":200,"value":33,"type":"uns"},
         {"name":"BILL","flight":200,"value":45,"type":"sch"}
    ]
}

Body:
You could use a closure over a hash table for same named objects.

var data = [{ name: 'JON', flight: 100, value: 12, type: 'uns' }, { name: 'JON', flight: 100, value: 35, type: 'sch' }, { name: 'BILL', flight: 200, value: 33, type: 'uns' }, { name: 'BILL', flight: 200, value: 45, type: 'sch' }],
    grouped = data.reduce(function (hash) {
        return function (r, o) {
            if (!hash[o.name]) {
                hash[o.name] = { name: o.name, flight: o.flight };
                r.push(hash[o.name]);
            }
            hash[o.name][o.type] = (hash[o.name][o.type] || 0) + o.value;
            return r;
        }
    }(Object.create(null)), []);

console.log(grouped);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
basic concept for Linear Algebra
Question is: Let A and B be 3x3 (square) matrices. Which of following must necessarily hold true?
One of the option is A + B = B + A, but I didn't choose. The answer display this equation is true. I don't understand. In the identity matrix, A * I(n*n) = I * A
Can this multiply principal also be used in addition? Could you give a specific and simple example? Thanks a lot.</p>

答:
Adding Matrices is a element-wise operator:
Note adding is commutative which means you can change the order around.

A  = [ 1 2 3; 4 5 6; 7 8 9]
B = [4 9 2 ; 2 0 4 ; 3 6 7]

A + B = [1 + 4 ,2 + 9, 3 + 2; 4 + 2, 5 + 0, 6 + 4; 7 + 3 ,8 + 6, 7 + 9]

B + A = [4 + 1, 9 + 2, 2 + 3; 2 + 4, 0 + 5, 4 + 6; 3 + 7, 6 + 8, 9 + 7]

Notice both operations yield the same result since adding is commutative and bit wise adding means adding matrices is also commutative so the operands can be swapped! Not too sure about your second question though :(

Title: basic concept for Linear Algebra


问:
How do CRMs connect to Email accounts to interact with them? (i.e. Gmail)?
This is not a code question but more of a process question. I've had a few people ask me about CRMs and the way they connect to email.  I'm not sure about how they do this. When I write web or iOS applications I can send email via API or SMTP but I'm not sure how to really make a CRM "interact" with an email account.

Thanks
R

答:
I know about - Microsoft Dynamics CRM.

It has its own Email router/Server side sync (Exchange) to deliver & receive email through Queue concept.

Even the most powerful Outlook client helps to integrate with CRM from your workplace :)

(These are just pointers, pls explore yourself with these keywords in google)


问:
What does 'synchronized' mean?
I have some questions regarding the usage and significance of the synchronized keyword.

What is the significance of the synchronized keyword?

When should methods be synchronized?

What does it mean programmatically and logically?

答:
Synchronized simply means that multiple threads if associated with single object can prevent dirty read and write if synchronized block is used on particular object. To give you more clarity , lets take an example :

```<code>class MyRunnable implements Runnable {
    int var = 10;
    @Override
    public void run() {
        call();
    }

    public void call() {
        synchronized (this) {
            for (int i = 0; i < 4; i++) {
                var++;
                System.out.println("Current Thread " + Thread.currentThread().getName() + " var value "+var);
            }
        }
    }
}

public class MutlipleThreadsRunnable {
    public static void main(String[] args) {
        MyRunnable runnable1 = new MyRunnable();
        MyRunnable runnable2 = new MyRunnable();
        Thread t1 = new Thread(runnable1);
        t1.setName("Thread -1");
        Thread t2 = new Thread(runnable2);
        t2.setName("Thread -2");
        Thread t3 = new Thread(runnable1);
        t3.setName("Thread -3");
        t1.start();
        t2.start();
        t3.start();
    }
}
</code>```

We've created two MyRunnable class objects , runnable1 being shared with thread 1 and thread 3 & runnable2 being shared with thread 2 only.
Now when t1 and t3 starts without synchronized being used , PFB output which suggest that both threads 1 and 3 simultaneously affecting var value where for thread 2 , var has its own memory.

```<code>Without Synchronized keyword

    Current Thread Thread -1 var value 11
    Current Thread Thread -2 var value 11
    Current Thread Thread -2 var value 12
    Current Thread Thread -2 var value 13
    Current Thread Thread -2 var value 14
    Current Thread Thread -1 var value 12
    Current Thread Thread -3 var value 13
    Current Thread Thread -3 var value 15
    Current Thread Thread -1 var value 14
    Current Thread Thread -1 var value 17
    Current Thread Thread -3 var value 16
    Current Thread Thread -3 var value 18
</code>```

Using Synchronzied, thread 3 waiting for thread 1 to complete in all scenarios. There are two locks acquired , one on runnable1 shared by thread 1 and thread 3 and another on runnable2 shared by thread 2 only.

```<code>Current Thread Thread -1 var value 11
Current Thread Thread -2 var value 11
Current Thread Thread -1 var value 12
Current Thread Thread -2 var value 12
Current Thread Thread -1 var value 13
Current Thread Thread -2 var value 13
Current Thread Thread -1 var value 14
Current Thread Thread -2 var value 14
Current Thread Thread -3 var value 15
Current Thread Thread -3 var value 16
Current Thread Thread -3 var value 17
Current Thread Thread -3 var value 18
</code>```

Title: What does 'synchronized' mean?

Body:
Synchronized simply means that multiple threads if associated with single object can prevent dirty read and write if synchronized block is used on particular object. To give you more clarity , lets take an example :

class MyRunnable implements Runnable {
    int var = 10;
    @Override
    public void run() {
        call();
    }

    public void call() {
        synchronized (this) {
            for (int i = 0; i < 4; i++) {
                var++;
                System.out.println("Current Thread " + Thread.currentThread().getName() + " var value "+var);
            }
        }
    }
}

public class MutlipleThreadsRunnable {
    public static void main(String[] args) {
        MyRunnable runnable1 = new MyRunnable();
        MyRunnable runnable2 = new MyRunnable();
        Thread t1 = new Thread(runnable1);
        t1.setName("Thread -1");
        Thread t2 = new Thread(runnable2);
        t2.setName("Thread -2");
        Thread t3 = new Thread(runnable1);
        t3.setName("Thread -3");
        t1.start();
        t2.start();
        t3.start();
    }
}

We've created two MyRunnable class objects , runnable1 being shared with thread 1 and thread 3 & runnable2 being shared with thread 2 only.
Now when t1 and t3 starts without synchronized being used , PFB output which suggest that both threads 1 and 3 simultaneously affecting var value where for thread 2 , var has its own memory.

Without Synchronized keyword

    Current Thread Thread -1 var value 11
    Current Thread Thread -2 var value 11
    Current Thread Thread -2 var value 12
    Current Thread Thread -2 var value 13
    Current Thread Thread -2 var value 14
    Current Thread Thread -1 var value 12
    Current Thread Thread -3 var value 13
    Current Thread Thread -3 var value 15
    Current Thread Thread -1 var value 14
    Current Thread Thread -1 var value 17
    Current Thread Thread -3 var value 16
    Current Thread Thread -3 var value 18

Using Synchronzied, thread 3 waiting for thread 1 to complete in all scenarios. There are two locks acquired , one on runnable1 shared by thread 1 and thread 3 and another on runnable2 shared by thread 2 only.

Current Thread Thread -1 var value 11
Current Thread Thread -2 var value 11
Current Thread Thread -1 var value 12
Current Thread Thread -2 var value 12
Current Thread Thread -1 var value 13
Current Thread Thread -2 var value 13
Current Thread Thread -1 var value 14
Current Thread Thread -2 var value 14
Current Thread Thread -3 var value 15
Current Thread Thread -3 var value 16
Current Thread Thread -3 var value 17
Current Thread Thread -3 var value 18


问:
Scala subString function
Hi I am looking for a solution it will return a substring from string for the given indexes.For avoiding index bound exception currently using if and else check.Is there a better approach(functional).</p>

```<code>def subStringEn(input:String,start:Int,end:Int)={
  // multiple if check for avoiding index out of bound exception
    input.substring(start,end)
}
</code>```

答:
Not sure what you want the function to do in case of index out of bound, but slice might fit your needs:

```<code>input.slice(start, end)
</code>```

Some examples:

```<code>scala> "hello".slice(1, 2)
res6: String = e

scala> "hello".slice(1, 30)
res7: String = ello

scala> "hello".slice(7, 8)
res8: String = ""

scala> "hello".slice(0, 5)
res9: String = hello
</code>```

Title: Scala subString function

Body:
Hi I am looking for a solution it will return a substring from string for the given indexes.For avoiding index bound exception currently using if and else check.Is there a better approach(functional).

def subStringEn(input:String,start:Int,end:Int)={
  // multiple if check for avoiding index out of bound exception
    input.substring(start,end)
}

Body:
Not sure what you want the function to do in case of index out of bound, but slice might fit your needs:

input.slice(start, end)

Some examples:

scala> "hello".slice(1, 2)
res6: String = e

scala> "hello".slice(1, 30)
res7: String = ello

scala> "hello".slice(7, 8)
res8: String = ""

scala> "hello".slice(0, 5)
res9: String = hello


问:
Redefining Methods to a Javascript function
So I have a Javascript function i.e

```<code>var object = function(){
    function sayHello(){
       console.log("Hello");
    }
}
</code>```

Is there a way to redefine the object.sayHello method later on in my code such that instead it prints "Bonjour"?

答:
You can override functions in Javascript.  All you have to do is re-declare it later on.

var hello = function(){
    alert("Hello");
}

function changeFunction(){
    hello = function(){
     alert("Goodbye");
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="hello()">Run Function</button>
<button onclick="changeFunction()">Change function</button></code>```

Body:
So I have a Javascript function i.e

var object = function(){
    function sayHello(){
       console.log("Hello");
    }
}

Is there a way to redefine the object.sayHello method later on in my code such that instead it prints "Bonjour"?

Body:
You can override functions in Javascript.  All you have to do is re-declare it later on.

var hello = function(){
    alert("Hello");
}

function changeFunction(){
    hello = function(){
     alert("Goodbye");
    }
}

<button onclick="hello()">Run Function</button>
<button onclick="changeFunction()">Change function</button>


问:
CSS animation not working after replacing text?
For my website, I am trying to fade out part of a word, replace it, and then fade it back in. I am using animate.css to do this along with jquery.

HTML

```<code>      <h1>D<span id="span-header">iscover</span></h1>
</code>```

JavaScript

```<code>$("#span-header").addClass("animated fadeOut");
setTimeout(function() {
   var newText = $("#span-header").text().replace("iscover", "ispicio");
   $("#span-header").text(newText);
}, 700);
$("#span-header").addClass("animated fadeIn");
</code>```

What it is doing is fading out and replacing the text but it does not fade back in. What am I doing wrong?

答:
1st: you need to Move the code for .addClass("fadeIn") inside setTimeout call back function

2nd: use .removeClass('fadeOut') to remove fadeOut class before adding fadeIn class

Demo

```<code>$("#span-header").addClass("animated fadeOut");
setTimeout(function() {
   var newText = $("#span-header").text().replace("iscover", "ispicio");
   $("#span-header").text(newText);
   $("#span-header").removeClass('fadeOut').addClass("fadeIn");
}, 700);
</code>```

Body:
For my website, I am trying to fade out part of a word, replace it, and then fade it back in. I am using animate.css to do this along with jquery.

HTML

Discover

JavaScript

$("#span-header").addClass("animated fadeOut");
setTimeout(function() {
   var newText = $("#span-header").text().replace("iscover", "ispicio");
   $("#span-header").text(newText);
}, 700);
$("#span-header").addClass("animated fadeIn");

What it is doing is fading out and replacing the text but it does not fade back in. What am I doing wrong?

Body:
1st: you need to Move the code for .addClass("fadeIn") inside setTimeout call back function

2nd: use .removeClass('fadeOut') to remove fadeOut class before adding fadeIn class

Demo

$("#span-header").addClass("animated fadeOut");
setTimeout(function() {
   var newText = $("#span-header").text().replace("iscover", "ispicio");
   $("#span-header").text(newText);
   $("#span-header").removeClass('fadeOut').addClass("fadeIn");
}, 700);


问:
Getting error while trying to zip two list that are not equal in size in python
I have two lists that are different in size

```<code> a=[1,2,3,4,5,6]
 b=[3,6,7,8]
</code>```

Or

```<code> a=[3,4,5,6,7]
 b=[1,2,3,4,16,7,7,8,0]
</code>```

Now i want to zip those two lists , which are not equal in size
     c=zip(a,b)

so that i can do

```<code> for i,j in c:
   print i , j
</code>```

Please suggest .

答:
You can use izip_longest from itertools:

```<code>from itertools import izip_longest

a=[1,2,3,4,5,6]
b=[3,6,7,8]

new_val = list(izip_longest(a, b))
</code>```

This will give:

```<code>[(1, 3), (2, 6), (3, 7), (4, 8), (5, None), (6, None)]
</code>```

izip_longest (or zip_longest in Python3) will replace None with occurrence of a mismatch in lengths between two or more lists being zipped.

Body:
I have two lists that are different in size

 a=[1,2,3,4,5,6]
 b=[3,6,7,8]

Or

 a=[3,4,5,6,7]
 b=[1,2,3,4,16,7,7,8,0]

Now i want to zip those two lists , which are not equal in size
     c=zip(a,b)

so that i can do

 for i,j in c:
   print i , j

Please suggest .

Body:
You can use izip_longest from itertools:

from itertools import izip_longest

a=[1,2,3,4,5,6]
b=[3,6,7,8]

new_val = list(izip_longest(a, b))

This will give:

[(1, 3), (2, 6), (3, 7), (4, 8), (5, None), (6, None)]

izip_longest (or zip_longest in Python3) will replace None with occurrence of a mismatch in lengths between two or more lists being zipped.