问:
Any trick to defining an enum as flags/powers of 2 without eventually needing a calculator?
I know I can multiply but being the lazy programming I am I do not want to.

Has anyone devised some sorcery to auto number the enums as powers of two?

Here's the example I have just to make it concrete:

```<code>[Flags]
private enum Targets : uint
{
    None = 0,
    Campaigns = 1,
    CampaignGroups = 2,
    Advertisers = 4,
    AdvertiserGroups = 8,
    AffiliateGroups = 16,
    Affiliates = 32,
    Creatives = 64,
    DetailedLeads = 128,
    DetailedSales = 256,
    ProgramLeads = 512,
    CreativeDeployments = 1024,
    CampaignCategories = 2048,
    Payouts = 4096,
    All = uint.MaxValue
}
</code>```

答:
Here's yet another alternative approach:</p>

```<code>[Flags]
public enum COURSECOMPONENT_T : int
{
    Everything = -1,
    Nothing = 0,
    AttendanceRegisters = 1,
    Checklists = 2 * AttendanceRegisters,
    Competencies = 2 * Checklists,
    Content = 2 * Competencies,
    CourseFiles = 2 * Content,
    Discussions = 2 * CourseFiles,
    DisplaySettings = 2 * Discussions,
    Dropbox = 2 * DisplaySettings,
    Faq = 2 * Dropbox,
    Forms = 2 * Faq,
    Glossary = 2 * Forms,
    Grades = 2 * Glossary,
    GradesSettings = 2 * Grades,
    Groups = 2 * GradesSettings,
    Homepages = 2 * Groups,
    IntelligentAgents = 2 * Homepages,
    Links = 2 * IntelligentAgents,
    LtiLink = 2 * Links,
    LtiTP = 2 * LtiLink,
    Navbars = 2 * LtiTP,
    News = 2 * Navbars,
    QuestionLibrary = 2 * News,
    Quizzes = 2 * QuestionLibrary,
    ReleaseConditions = 2 * Quizzes,
    Rubrics = 2 * ReleaseConditions,
    Schedule = 2 * Rubrics,
    SelfAssessments = 2 * Schedule,
    Surveys = 2 * SelfAssessments,
    ToolNames = 2 * Surveys,
    Widgets = 2 * ToolNames,
}
</code>```

Body:
I know I can multiply but being the lazy programming I am I do not want to.

Has anyone devised some sorcery to auto number the enums as powers of two?

Here's the example I have just to make it concrete:

[Flags]
private enum Targets : uint
{
    None = 0,
    Campaigns = 1,
    CampaignGroups = 2,
    Advertisers = 4,
    AdvertiserGroups = 8,
    AffiliateGroups = 16,
    Affiliates = 32,
    Creatives = 64,
    DetailedLeads = 128,
    DetailedSales = 256,
    ProgramLeads = 512,
    CreativeDeployments = 1024,
    CampaignCategories = 2048,
    Payouts = 4096,
    All = uint.MaxValue
}

Body:
Here's yet another alternative approach:

[Flags]
public enum COURSECOMPONENT_T : int
{
    Everything = -1,
    Nothing = 0,
    AttendanceRegisters = 1,
    Checklists = 2 * AttendanceRegisters,
    Competencies = 2 * Checklists,
    Content = 2 * Competencies,
    CourseFiles = 2 * Content,
    Discussions = 2 * CourseFiles,
    DisplaySettings = 2 * Discussions,
    Dropbox = 2 * DisplaySettings,
    Faq = 2 * Dropbox,
    Forms = 2 * Faq,
    Glossary = 2 * Forms,
    Grades = 2 * Glossary,
    GradesSettings = 2 * Grades,
    Groups = 2 * GradesSettings,
    Homepages = 2 * Groups,
    IntelligentAgents = 2 * Homepages,
    Links = 2 * IntelligentAgents,
    LtiLink = 2 * Links,
    LtiTP = 2 * LtiLink,
    Navbars = 2 * LtiTP,
    News = 2 * Navbars,
    QuestionLibrary = 2 * News,
    Quizzes = 2 * QuestionLibrary,
    ReleaseConditions = 2 * Quizzes,
    Rubrics = 2 * ReleaseConditions,
    Schedule = 2 * Rubrics,
    SelfAssessments = 2 * Schedule,
    Surveys = 2 * SelfAssessments,
    ToolNames = 2 * Surveys,
    Widgets = 2 * ToolNames,
}


来源: stackexchange

问:
How are Python in-place operator functions different than the standard operator functions?
From the docs:

Many operations have an “in-place”
version. The following functions
provide a more primitive access to
in-place operators than the usual
syntax does; for example, the
statement x += y is equivalent to x =
operator.iadd(x, y). Another way to
put it is to say that z =
operator.iadd(x, y) is equivalent to
the compound statement z = x; z += y.

Questions:

Why isn't operator.iadd(x, y) equivalent to z = x; z += y?

How does operator.iadd(x, y) differ from operator.add(x, y)?

Related question, but I'm not interested in Python class methods; just regular operators on built-in Python types.

答:
Perhaps because some Python objects are immutable.

I'm guessing operator.iadd(x, y) is equivalent to z = x; z += y only for mutable types like dictionaries and lists, but not for immutable types like numbers and strings.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
Sum values recursively in one line
I am pretty sure that it can be done in one line using things like map, sum etc. I cannot figure out how exactly, because I just started learning ruby. Could someone help? Thanks</p>

```<code> class Something < ApplicationRecord
 def function
    res = items.count
    items.each do |i|
      res += i.function
    end
    res
  end
</code>```

答:
The straightforward oneliner equivalent to yours:

```<code>  def function
    items.count + items.sum(&:function)
  end
</code>```

Demo (testing it alongside your original):

```<code>class Something
  attr_accessor :items

  def initialize(items = [])
    self.items = items
  end

  def function
    res = items.count
    items.each do |i|
      res += i.function
    end
    res
  end

  def function2
    items.count + items.sum(&:function2)
  end
end

root = Something.new([
         Something.new,
         Something.new([
           Something.new,
           Something.new([
             Something.new,
             Something.new([
               Something.new
             ])
           ])
         ])
       ])

puts root.function
puts root.function2
</code>```

Prints:

```<code>7
7
</code>```

Another way:

```<code>  def function
    items.sum { |i| 1 + i.function }
  end
</code>```

By the way, you count all items except for the root item. Is that intentional?
You could count all including the root with this:

```<code>  def function
    1 + items.sum(&:function)
  end
</code>```

ContentLicense: CC BY-SA 3.0

Title: Sum values recursively in one line

Body:
I am pretty sure that it can be done in one line using things like map, sum etc. I cannot figure out how exactly, because I just started learning ruby. Could someone help? Thanks

 class Something < ApplicationRecord
 def function
    res = items.count
    items.each do |i|
      res += i.function
    end
    res
  end

Body:
The straightforward oneliner equivalent to yours:

  def function
    items.count + items.sum(&:function)
  end

Demo (testing it alongside your original):

class Something
  attr_accessor :items

  def initialize(items = [])
    self.items = items
  end

  def function
    res = items.count
    items.each do |i|
      res += i.function
    end
    res
  end

  def function2
    items.count + items.sum(&:function2)
  end
end

root = Something.new([
         Something.new,
         Something.new([
           Something.new,
           Something.new([
             Something.new,
             Something.new([
               Something.new
             ])
           ])
         ])
       ])

puts root.function
puts root.function2

Prints:

7
7

Another way:

  def function
    items.sum { |i| 1 + i.function }
  end

By the way, you count all items except for the root item. Is that intentional?
You could count all including the root with this:

  def function
    1 + items.sum(&:function)
  end


问:
interaction between adjacent components in angular
Hi all can we please describe how to interaction between adjacent components in angular? not parent/child.

For example: i have two components (not parent/child, just neighbors). In first component i have bool variable which changes in function, and the second component must to know which value of variable in first component, and depending on the value of the variable, function in second component performs a different code block. how can i implement this?
thanks for helping.

1 component

```<code> let bool = false;
     function() {
        //something to do
        bool = true;
     }
</code>```

2 component

```<code>function() {
    if (bool === true) {
    //something to do
    }
    else {
        something new to do
    }
}
</code>```

答:
You can use a template variable to reference sibling components (directives, elements)

```<code><my-comp1 #first></my-comp>
<my-comp1 (foo)="first.something = $event"></my-comp>
</code>```

You can use a the common parent as mediator, or use a shared service (provided on a common ancestor)

Body:
Hi all can we please describe how to interaction between adjacent components in angular? not parent/child.

For example: i have two components (not parent/child, just neighbors). In first component i have bool variable which changes in function, and the second component must to know which value of variable in first component, and depending on the value of the variable, function in second component performs a different code block. how can i implement this?
thanks for helping.

1 component

 let bool = false;
     function() {
        //something to do
        bool = true;
     }

2 component

function() {
    if (bool === true) {
    //something to do
    }
    else {
        something new to do
    }
}

Body:
You can use a template variable to reference sibling components (directives, elements)

<my-comp1 #first></my-comp>
<my-comp1 (foo)="first.something = $event"></my-comp>

You can use a the common parent as mediator, or use a shared service (provided on a common ancestor)


问:
UICollectionView inside UITableViewCell default contentOffset
In my app I have a tableView which contains several cells with UICollectionView, The layout of UICollectionView is custom and set in cellForRowAtIndexPath.

In prepare method of collectionViewLayout I set a default contentOffset to collectionView.

But this contentOffset only works for visible table cells and when I scroll tableview other cells do not have this default content offset.

How to fix this issue ?

```<code>override func prepare() {
    guard cache.isEmpty, let collectionView = collectionView else {
        return
    }

    // ...
    // Prepare cell attributes and add to cache array
    // ...

    collectionView.contentOffset = CGPoint(x: 100, y:0)
}
</code>```

答:
I used the following solution to fix this issue, Set content offset after a few milliseconds delay fixed this issue.

```<code>DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .milliseconds(10), execute: {
    collectionView.contentOffset = self.initialContentOffset!
})
</code>```

But I think this isn't the best solution but I couldn't find another solution to fix this issue

Body:
In my app I have a tableView which contains several cells with UICollectionView, The layout of UICollectionView is custom and set in cellForRowAtIndexPath.

In prepare method of collectionViewLayout I set a default contentOffset to collectionView.

But this contentOffset only works for visible table cells and when I scroll tableview other cells do not have this default content offset.

How to fix this issue ?

override func prepare() {
    guard cache.isEmpty, let collectionView = collectionView else {
        return
    }

    // ...
    // Prepare cell attributes and add to cache array
    // ...

    collectionView.contentOffset = CGPoint(x: 100, y:0)
}

Body:
I used the following solution to fix this issue, Set content offset after a few milliseconds delay fixed this issue.

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .milliseconds(10), execute: {
    collectionView.contentOffset = self.initialContentOffset!
})

But I think this isn't the best solution but I couldn't find another solution to fix this issue


问:
Where to start debugging, when you get the "Activity is not responding, Force Close, Wait"?
I have worked on a simple application. It application includes diffrent levels that can be solved by placing some components inside a canvas, dragging them to the right place and so on.

The application is working fine, but when trying it on my HTC Desire 2.2, I sometimes get the warning message:

Sorry:
Activity xxxxx is not respoding.
Force Close - Wait

If I press the wait-button and let it be for some seconds (up to ~30 sec sometimes), then it runs without any problems. I don´t know where I should start debugging the code, since it happenes only once in a while.

I have read the stuff in google developer site and it was just mostly very general stuff that did not really help.

any ideas?

since, I was not able to debug the problem myself, I am going to post the most important parts of the application. Please check and let me know If I need to post more classes.

```<code>//Evrything else
Bitmap bitmap;
GraphicObject.Coordinates coords;
for (GraphicObject graphic : _graphics) {
    bitmap = graphic.getGraphic();
    coords = graphic.getCoordinates();
    canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
}
// draw current graphic at last...
if (_currentGraphic != null) {
    bitmap = _currentGraphic.getGraphic();
    coords = _currentGraphic.getCoordinates();
    canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
}
</code>```

答:
I think you are creating the 30 second sleep on the main thread, if so, the application will be unresponsive for about 30 seconds and the android system will show force close dialog will show up after 5 second. Try creating the 30 second pause and action on a new thread. Check android developers site for more information about threads.

And if you don't know where to start debugging, check your logcat log and search for errors or warnings. Check this -> http://www.droidnova.com/debugging-in-android-using-eclipse,541.html for some information about logcat.

Hope that helped. :) Good luck.

Edit: Then i think that you should put the functions that the wait button performs inside a new thread, so that the application becomes responsive instantly and the child thread remains unresponsive, which doesnt matter.

Edit Again: oh, i get it now, sorry for the misunderstanding, so you are not sure where the problem is, try searching for any network connections, sleep/pauses in your code. Oh, and connect your phone to your computer, run the app by pressing F5 and try to search for warnings or errors in logcat just when the force close box opens. And try to copy the logcat log and send it to me, and ill check whats wrong.

Body:
I have worked on a simple application. It application includes diffrent levels that can be solved by placing some components inside a canvas, dragging them to the right place and so on.

The application is working fine, but when trying it on my HTC Desire 2.2, I sometimes get the warning message:

Sorry:
Activity xxxxx is not respoding.
Force Close - Wait

If I press the wait-button and let it be for some seconds (up to ~30 sec sometimes), then it runs without any problems. I don´t know where I should start debugging the code, since it happenes only once in a while.

I have read the stuff in google developer site and it was just mostly very general stuff that did not really help.

any ideas?

since, I was not able to debug the problem myself, I am going to post the most important parts of the application. Please check and let me know If I need to post more classes.

//Evrything else
Bitmap bitmap;
GraphicObject.Coordinates coords;
for (GraphicObject graphic : _graphics) {
    bitmap = graphic.getGraphic();
    coords = graphic.getCoordinates();
    canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
}
// draw current graphic at last...
if (_currentGraphic != null) {
    bitmap = _currentGraphic.getGraphic();
    coords = _currentGraphic.getCoordinates();
    canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
}


问:
How do I enable logging for Spring Security?
I am setting up Spring Security to handle logging users in. I have logged in as a user, and am taken to an Access Denied error page upon successful login. I don't know what roles my user has actually been assigned, or the rule that causes access to be denied, because I can't figure out how to enable debugging for the Spring Security library.

My security xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans ... >

    <security:debug/>

    <security:http auto-config="true">

        <security:intercept-url pattern="/Admin**" access="hasRole('PROGRAMMER') or hasRole('ADMIN')"/>
        <security:form-login login-page="/Load.do"
            default-target-url="/Admin.do?m=loadAdminMain"
            authentication-failure-url="/Load.do?error=true"
            username-parameter="j_username"
            password-parameter="j_password"
            login-processing-url="/j_spring_security_check"/>
        <security:csrf/>
    </security:http>

    <security:authentication-manager>
        <security:authentication-provider>
            <security:jdbc-user-service data-source-ref="loginDataSource"
                users-by-username-query="SELECT username, password, active FROM userinformation WHERE username = ?"
                authorities-by-username-query="
                    SELECT ui.username, r.rolename
                    FROM role r, userrole ur, userinformation ui
                    WHERE ui.username=?
                    AND ui.userinformationid = ur.userinformationid
                    AND ur.roleid = r.roleid "
            />
            <security:password-encoder hash="md5"/>
        </security:authentication-provider>
    </security:authentication-manager>
</beans>
```

I've also tried adding log4j.logger.org.springframework.security=DEBUG to my log4j.properties

How can I get debug output for Spring Security?

答:
Assuming you're using Spring Boot, another option is to put the following in your application.properties:

```<code>logging.level.org.springframework.security=DEBUG
</code>```

This is the same for most other Spring modules as well.

If you're not using Spring Boot, try setting the property in your logging configuration, e.g. logback.

Here is the application.yml version as well:

```<code>logging:
  level:
    org:
      springframework:
        security: DEBUG
</code>```

Body:
I am setting up Spring Security to handle logging users in. I have logged in as a user, and am taken to an Access Denied error page upon successful login. I don't know what roles my user has actually been assigned, or the rule that causes access to be denied, because I can't figure out how to enable debugging for the Spring Security library.

My security xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans ... >

    <security:debug/>

    <security:http auto-config="true">

        <security:intercept-url pattern="/Admin**" access="hasRole('PROGRAMMER') or hasRole('ADMIN')"/>
        <security:form-login login-page="/Load.do"
            default-target-url="/Admin.do?m=loadAdminMain"
            authentication-failure-url="/Load.do?error=true"
            username-parameter="j_username"
            password-parameter="j_password"
            login-processing-url="/j_spring_security_check"/>
        <security:csrf/>
    </security:http>

    <security:authentication-manager>
        <security:authentication-provider>
            <security:jdbc-user-service data-source-ref="loginDataSource"
                users-by-username-query="SELECT username, password, active FROM userinformation WHERE username = ?"
                authorities-by-username-query="
                    SELECT ui.username, r.rolename
                    FROM role r, userrole ur, userinformation ui
                    WHERE ui.username=?
                    AND ui.userinformationid = ur.userinformationid
                    AND ur.roleid = r.roleid "
            />
            <security:password-encoder hash="md5"/>
        </security:authentication-provider>
    </security:authentication-manager>
</beans>

I've also tried adding log4j.logger.org.springframework.security=DEBUG to my log4j.properties

How can I get debug output for Spring Security?

Body:
Assuming you're using Spring Boot, another option is to put the following in your application.properties:

logging.level.org.springframework.security=DEBUG

This is the same for most other Spring modules as well.

If you're not using Spring Boot, try setting the property in your logging configuration, e.g. logback.

Here is the application.yml version as well:

logging:
  level:
    org:
      springframework:
        security: DEBUG


问:
how to compile string(contains angular dir) before appending into html in jquery?
Here is the code of html and jquery that used to generate invoice automatically. here I displayed total amount by qnty*rate but if I passed it by jquery then I have to compile angular because I know I have to compile it before doing this, but how can I compile it in jquery?

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<table class="tg">
  <tr>
    <td class="tg-9hbo">Description of Goods</td>
    <td class="tg-9hbo">HSN CODE</td>
    <td class="tg-9hbo">QTY</td>
    <td class="tg-9hbo">Units</td>
    <td class="tg-9hbo">Rate</td>
    <td class="tg-9hbo">AMOUNT (INR)</td>
  </tr>

  <tr class="products" ng-app="">
    <td class="tg-yw4l"><input type="text"></td>
    <td class="tg-yw4l"><input type="text"></td>
    <td class="tg-yw4l"><input type="number" ng-model="qty"></td>
    <td class="tg-yw4l"><input type="text"></td>
    <td class="tg-yw4l"><input type="number" ng-model="rate"></td>
    <td class="tg-yw4l">{{qty * rate}}</td>
  </tr>

  <tr>
    <td class="tg-yw4l">
      <button class="addp">Add New Product</button>
    </td>
  </tr>

  <tr>
    <td class="tg-yw4l">TAX<br>GST <input type="number">%</td>
    <td class="tg-yw4l"></td>
    <td class="tg-yw4l"></td>
    <td class="tg-yw4l"></td>
    <td class="tg-yw4l">18%</td>
    <td class="tg-yw4l">718.2</td>
  </tr>

  <tr>
    <td class="tg-yw4l"></td>
    <td class="tg-yw4l"></td>
    <td class="tg-yw4l"></td>
    <td class="tg-yw4l"></td>
    <td class="tg-yw4l">GRAND TOTAL</td>
    <td class="tg-yw4l">4708</td>
  </tr>
</table>

<script>
var tbl = '<tr class="products1" ng-app="">'+
            '<td class="tg-yw4l1"><input type="text"></td>'+
            '<td class="tg-yw4l1"><input type="text"></td>'+
            '<td class="tg-yw4l1"><input type="number" ng-model="qty1"></td>'+
            '<td class="tg-yw4l1"><input type="text"></td>'+
            '<td class="tg-yw4l1"><input type="number" ng-model="rate1"></td>'+
            '<td class="tg-yw4l1">{{qty1 * rate1}}</td>'+
          '</tr>';

$(document).ready(function(){
    $(".addp").click(function(){
      $(".products").after(tbl);
    });
});
</script>
</code>```

答:
Your question is not very clear and assuming you want to mimic similar behavior in angularjs (dynamically add products rows), here's an example on how you can do this.

Render your products using an ng-repeat by iterating over a products array.

```<code><html  ng-app="MyApp">
<head>... </head>
<body ng-controller="ProductsController">
    <table class="tg">
        <tr>...</tr>
        <tr class="products" ng-repeat="p in products track by $index">
            <td class="tg-yw4l"><input type="text"></td>
            <td class="tg-yw4l"><input type="text"></td>
            <td class="tg-yw4l"><input type="number" ng-model="p.qty"></td>
            <td class="tg-yw4l"><input type="text"></td>
            <td class="tg-yw4l"><input type="number" ng-model="p.rate"></td>
            <td class="tg-yw4l">{{p.qty * p.rate}}</td>
       </tr>
       <tr>
           <td class="tg-yw4l">
               <button class="addp" ng-click="addProduct()">Add New Product</button>
           </td>
       </tr>
    </table>
</body>
</html>
</code>```

Add objects to products array dynamically.

```<code>angular.module('MyApp', []).controller('ProductsController',
   function($scope) {
       // this array is bound to view
       $scope.products= [{qty:0, rate:0}];

       // this function is bound to the ng-click event of the button
       $scope.addProducts = function() {
           $scope.products.push({qty:0, rate:0});
       };
   }
);
</code>```

Body:
Here is the code of html and jquery that used to generate invoice automatically. here I displayed total amount by qnty*rate but if I passed it by jquery then I have to compile angular because I know I have to compile it before doing this, but how can I compile it in jquery?

    Description of Goods
    HSN CODE
    QTY
    Units
    Rate
    AMOUNT (INR)

    <input type="text">
    <input type="text">
    <input type="number" ng-model="qty">
    <input type="text">
    <input type="number" ng-model="rate">
    {{qty * rate}}

      <button class="addp">Add New Product</button>

    TAX
GST <input type="number">%

    18%
    718.2

    GRAND TOTAL
    4708

Body:
Your question is not very clear and assuming you want to mimic similar behavior in angularjs (dynamically add products rows), here's an example on how you can do this.

Render your products using an ng-repeat by iterating over a products array.

<html  ng-app="MyApp">
<head>... </head>
<body ng-controller="ProductsController">
    <table class="tg">
        <tr>...</tr>
        <tr class="products" ng-repeat="p in products track by $index">
            <td class="tg-yw4l"><input type="text"></td>
            <td class="tg-yw4l"><input type="text"></td>
            <td class="tg-yw4l"><input type="number" ng-model="p.qty"></td>
            <td class="tg-yw4l"><input type="text"></td>
            <td class="tg-yw4l"><input type="number" ng-model="p.rate"></td>
            <td class="tg-yw4l">{{p.qty * p.rate}}</td>
       </tr>
       <tr>
           <td class="tg-yw4l">
               <button class="addp" ng-click="addProduct()">Add New Product</button>
           </td>
       </tr>
    </table>
</body>
</html>

Add objects to products array dynamically.

angular.module('MyApp', []).controller('ProductsController',
   function($scope) {
       // this array is bound to view
       $scope.products= [{qty:0, rate:0}];

       // this function is bound to the ng-click event of the button
       $scope.addProducts = function() {
           $scope.products.push({qty:0, rate:0});
       };
   }
);


问:
Where is git.exe located?
I have PyCharm and I am looking around trying to find git.exe to set it up with my repo.

What is the PATH to git.exe?

答:
For anyone who might not find the other solutions suitable,

I just today downloaded the newest version and the git.exe was located in

```<code>C:\Users\<user>\AppData\Local\GitHubDesktop\app-1.0.10\resources\app\git\cmd
</code>```

Title: Where is git.exe located?

Body:
For anyone who might not find the other solutions suitable,

I just today downloaded the newest version and the git.exe was located in

C:\Users\<user>\AppData\Local\GitHubDesktop\app-1.0.10\resources\app\git\cmd


问:
How do you load a module @everywhere inside a function in Julia
I am trying to load a module in my workers after creating them with addprocs. When addprocs is called at the top level, everything is fine. However, I am not able to do the same thing when I wrap the code in a function.

In my case, I am adding workers dynamically, so it is not feasible to call @everywhere using XXX always on the top level, I would need to do this inside a function.

In short, this works:

```<code>addprocs(1)
@everywhere using XXX
</code>```

and this doesn't:

```<code>function myaddprocs()
    addprocs(1)
    @everywhere using XXX
end
</code>```

Any ideas?

答:
After a bit more investigation, I have pinpointed some of the issues which were making my code not work.

Imports must happen after addprocs. If an import has happened before, the import must be prefixed by an @everywhere.

Top-level expressions (such as using) inside functions do not work, unless wrapped in an eval statement.

A fix to my code would be:

```<code>function myaddprocs()
    addprocs(1)
    eval(macroexpand(quote @everywhere using XXX end))
end
</code>```

Examples

I have tested the following snippets on Julia 0.6.1. I have also tested them using the same version on a SGE cluster (OGS/GE 2011.11p1), by substituting all addprocs by addprocs_sge, and importing ClusterManagers.jl. The following snippets work:

using after addprocs:

```<code>addprocs(1)
using SpecialFunctions
pmap(x->SpecialFunctions.sinint(1), workers())
</code>```

using before and after addprocs, the second with @everywhere:

```<code>using SpecialFunctions
addprocs(1)
@everywhere using SpecialFunctions
pmap(x->sinint(1), workers())
</code>```

using wrapped in eval after addprocs within function

```<code>function getprocs()
    addprocs(1)
    eval(Expr(:using,:SpecialFunctions))
    pmap(x->SpecialFunctions.sinint(1), workers())
end
getprocs()
</code>```

Same as before with with @everywhere applied to eval

```<code>function getprocs()
    addprocs(1)
    @everywhere eval(Expr(:using,:SpecialFunctions))
    pmap(x->sinint(1), workers())
end
getprocs()
</code>```

Same as before with with @everywhere within eval instead

```<code>function getprocs()
    addprocs(1)
    eval(macroexpand(quote @everywhere using SpecialFunctions end))
    pmap(x->sinint(1), workers())
end
getprocs()
</code>```

These snippets, on the other hand, do not work:

using before addprocs

```<code>using SpecialFunctions
addprocs(1)
pmap(x->SpecialFunctions.sinint(1), workers())
</code>```

using before and after addprocs

```<code>using SpecialFunctions
addprocs(1)
using SpecialFunctions
pmap(x->SpecialFunctions.sinint(1), workers())
</code>```

using within function

```<code>using SpecialFunctions
function getprocs()
    addprocs(1)
    @everywhere using SpecialFunctions
    pmap(x->sinint(1), workers())
end
getprocs()
</code>```

using within function

```<code>function getprocs()
    addprocs(1)
    using SpecialFunctions
    pmap(x->SpecialFunctions.sinint(1), workers())
end
getprocs()
</code>```

Body:
I am trying to load a module in my workers after creating them with addprocs. When addprocs is called at the top level, everything is fine. However, I am not able to do the same thing when I wrap the code in a function.

In my case, I am adding workers dynamically, so it is not feasible to call @everywhere using XXX always on the top level, I would need to do this inside a function.

In short, this works:

addprocs(1)
@everywhere using XXX

and this doesn't:

function myaddprocs()
    addprocs(1)
    @everywhere using XXX
end

Any ideas?

Body:
After a bit more investigation, I have pinpointed some of the issues which were making my code not work.

Imports must happen after addprocs. If an import has happened before, the import must be prefixed by an @everywhere.

Top-level expressions (such as using) inside functions do not work, unless wrapped in an eval statement.

A fix to my code would be:

function myaddprocs()
    addprocs(1)
    eval(macroexpand(quote @everywhere using XXX end))
end

Examples

I have tested the following snippets on Julia 0.6.1. I have also tested them using the same version on a SGE cluster (OGS/GE 2011.11p1), by substituting all addprocs by addprocs_sge, and importing ClusterManagers.jl. The following snippets work:

using after addprocs:

addprocs(1)
using SpecialFunctions
pmap(x->SpecialFunctions.sinint(1), workers())

using before and after addprocs, the second with @everywhere:

using SpecialFunctions
addprocs(1)
@everywhere using SpecialFunctions
pmap(x->sinint(1), workers())

using wrapped in eval after addprocs within function

function getprocs()
    addprocs(1)
    eval(Expr(:using,:SpecialFunctions))
    pmap(x->SpecialFunctions.sinint(1), workers())
end
getprocs()

Same as before with with @everywhere applied to eval

function getprocs()
    addprocs(1)
    @everywhere eval(Expr(:using,:SpecialFunctions))
    pmap(x->sinint(1), workers())
end
getprocs()

Same as before with with @everywhere within eval instead

function getprocs()
    addprocs(1)
    eval(macroexpand(quote @everywhere using SpecialFunctions end))
    pmap(x->sinint(1), workers())
end
getprocs()

These snippets, on the other hand, do not work:

using before addprocs

using SpecialFunctions
addprocs(1)
pmap(x->SpecialFunctions.sinint(1), workers())

using before and after addprocs

using SpecialFunctions
addprocs(1)
using SpecialFunctions
pmap(x->SpecialFunctions.sinint(1), workers())

using within function

using SpecialFunctions
function getprocs()
    addprocs(1)
    @everywhere using SpecialFunctions
    pmap(x->sinint(1), workers())
end
getprocs()

using within function

function getprocs()
    addprocs(1)
    using SpecialFunctions
    pmap(x->SpecialFunctions.sinint(1), workers())
end
getprocs()


问:
Developer moving from SQL Server to Oracle
We are bringing a new project in house and whereas previously all our work was on SQL Server the new product uses an oracle back end.

Can anyone advise any crib sheets or such like that gives an SQL Server person like me a rundown of what the major differences are - Would like to be able to get up and running as soon as possible.

答:
to andy47, I did not mean that you can use the empty string in a comparison, but oracle treats it like null if you use it in an insert.
Re-read my entry, then try the following SQL:

```<code>CREATE TABLE atable (acol VARCHAR(10));
INsERT INTO atable VALUES( '' );
SELECT * FROM atable WHERE acol IS NULL;
</code>```

And to avoid a "yes it is, no it isn't" situation, here is an external link

OwnerDisplayName: Martin

Body:
to andy47, I did not mean that you can use the empty string in a comparison, but oracle treats it like null if you use it in an insert.
Re-read my entry, then try the following SQL:

CREATE TABLE atable (acol VARCHAR(10));
INsERT INTO atable VALUES( '' );
SELECT * FROM atable WHERE acol IS NULL;

And to avoid a "yes it is, no it isn't" situation, here is an external link

OwnerDisplayName: hamishmcn

LastEditorDisplayName: hamishmcn


问:
How to design native form on onsen ui
I need a nicely formatted form on onsen ui but i cant. Can someone help.
Also the page navigation is not working when i have different hmtl files

window.fn.pushPage = function (page, anim){
  if (anim) {
    document.getElementById('myNavigator').pushPage(page.id, { data: { title: page.title }, animation: anim });
  } else {
    document.getElementById('myNavigator').pushPage(page.id, { data: { title: page.title } });
  }
};

答:
To achieve a smooth navigation on your multipaged mobile html site using onsen UI, you have to do the following:

1) Insert the  tag in the index.html page. This should be placed inside the  tag example is shown below

```<code> <!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <meta http-equiv="Content-Security-Policy"
          content="default-src * data:; style-src * 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'">
    <script src="lib/onsenui/js/onsenui.min.js"></script>
    <link rel="stylesheet" href="lib/onsenui/css/onsenui.css">
    <link rel="stylesheet" href="lib/onsenui/css/onsen-css-components.css">

</head>
<body>

<ons-navigator id="navigator" var="navigator"></ons-navigator>

......
</body>
</html>
</code>```

2) Your inner pages should not have a  opening tag,  or other similar tags, but should look somewhat as shown below (assuming this page is my-second-page.html)

```<code><ons-page id="my-second-page">

 .......

</ons-page>
</code>```

3) To navigate from my-second-page to my-third-page.html, use the Onsen UI pushPage function as shown below. This is a javascript snippet that will be placed in your javasript file. This code will be executed when a user clicks a button to navigate to my-third-page.html

```<code>document.querySelector('#navigator').pushPage('my-third-page.html');
</code>```

Title: How to design native form on onsen ui

Body:
To achieve a smooth navigation on your multipaged mobile html site using onsen UI, you have to do the following:

1) Insert the  tag in the index.html page. This should be placed inside the  tag example is shown below

 <!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <meta http-equiv="Content-Security-Policy"
          content="default-src * data:; style-src * 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'">
    <script src="lib/onsenui/js/onsenui.min.js"></script>
    <link rel="stylesheet" href="lib/onsenui/css/onsenui.css">
    <link rel="stylesheet" href="lib/onsenui/css/onsen-css-components.css">

</head>
<body>

<ons-navigator id="navigator" var="navigator"></ons-navigator>

......
</body>
</html>

2) Your inner pages should not have a  opening tag,  or other similar tags, but should look somewhat as shown below (assuming this page is my-second-page.html)

<ons-page id="my-second-page">

 .......

</ons-page>

3) To navigate from my-second-page to my-third-page.html, use the Onsen UI pushPage function as shown below. This is a javascript snippet that will be placed in your javasript file. This code will be executed when a user clicks a button to navigate to my-third-page.html

document.querySelector('#navigator').pushPage('my-third-page.html');


问:
referencing a button on a parent form
On my website...form1 is the parent web page and has a disabled button (button1), a login button and an iframe. The login button sets the source of the iframe to a login form (form2) with a user id and password text boxes and an ok button. Form2's ok button click sets the same iframe source to form3 which evaluates the login and on success, enables the disabled button on form1.

Question: what is the javascript command in form3 to enable the disabled button in form1?

neither

```<code>window.parent.getElementById("button1").disabled = false
</code>```

or

```<code>window.document.form1.getElementById("button1").disabled = false
</code>```

seem to enable the button.

答:
Problem solved. The answer is:

window.top.document.getElementById('button1') or window.parent.document.getElementById('button1') if the parent document isn't the top document.

Title: referencing a button on a parent form

Body:
On my website...form1 is the parent web page and has a disabled button (button1), a login button and an iframe. The login button sets the source of the iframe to a login form (form2) with a user id and password text boxes and an ok button. Form2's ok button click sets the same iframe source to form3 which evaluates the login and on success, enables the disabled button on form1.

Question: what is the javascript command in form3 to enable the disabled button in form1?

neither

window.parent.getElementById("button1").disabled = false

or

window.document.form1.getElementById("button1").disabled = false

seem to enable the button.


问:
Connecting MySQL with JavaScript Calendar
```<code><?php
$host = 'localhost';
$dbusername ='root';
$dbpassword ='';
$database ='mp19';

$link =mysql_connect('localhost', 'root','12345678');
$db_selected = mysql_select_db('mp19', $link);

if (!$link)
  {exit("Connection Failed: " . $link);}

$sql="SELECT * FROM 3-33";
$rs=mysql_query_exec($link,$sql);

if (!$rs)
  {exit("Error in SQL");}

mysql_close($link);
?>
</code>```

These are the codes I generated for the connection of phpmysql and javascript calendar however there seems to be an error with the connection. Can someone help me check the codes  for this connection? :/

Also, I'm not sure how to incorporate these codes into the javascript calendar. The calendar is a hardcoded one which makes use of only javascript. My intention is to print the tasks stored in the phpmysql database in the javascript calendar but I'm totally lost. Can someone please advice me on how to continue? Thanks in advance

答:
There is nothing called mysql_query_exec() in php

use mysql_query() in this way

```<code> mysql_query ( string $query [, resource $link_identifier ] )

mysql_query($sql, $link);
</code>```

you are passing parameter wrongly

Body:
<?php
$host = 'localhost';
$dbusername ='root';
$dbpassword ='';
$database ='mp19';

$link =mysql_connect('localhost', 'root','12345678');
$db_selected = mysql_select_db('mp19', $link);

if (!$link)
  {exit("Connection Failed: " . $link);}

$sql="SELECT * FROM 3-33";
$rs=mysql_query_exec($link,$sql);

if (!$rs)
  {exit("Error in SQL");}

mysql_close($link);
?>

These are the codes I generated for the connection of phpmysql and javascript calendar however there seems to be an error with the connection. Can someone help me check the codes  for this connection? :/

Also, I'm not sure how to incorporate these codes into the javascript calendar. The calendar is a hardcoded one which makes use of only javascript. My intention is to print the tasks stored in the phpmysql database in the javascript calendar but I'm totally lost. Can someone please advice me on how to continue? Thanks in advance

Body:
There is nothing called mysql_query_exec() in php

use mysql_query() in this way

 mysql_query ( string $query [, resource $link_identifier ] )

mysql_query($sql, $link);

you are passing parameter wrongly


问:
Non local static viariable as members of a class
There are several questions out there about static variables, but I have not yet found an answer to my question. I just read Scott Meyers' explanation on the initialization of static variables and possible issues with it, like the static initialization order fiasco. What I would like to know is this: are static variables at class scope considered non-local?

Most sources I have seen say that static non local variables are defined either at global namespace or in a namespace while static local variables are defined in functions. But consider these two translations unit:

```<code>// MyClass.h:
class MyClass
{
public:
    static int z; // Is this non local?
};

// MyClass.cpp:
int MyClass::z = 4;

// MyOtherClass.h:
class MyOtherClass
{
public:
    static int w;
};

// MyOtherClass.cpp:
int MyOtherClass::w = MyClass::z; // Potential fiasco?
</code>```

Is z non local? In other words, can we assume z is initialized when w is?

答:
Both MyClass::z and MyOtherClass::w are non-local, static variables.

Your example potentially contains problems.

It's because MyOtherClass::w refers to MyClass::z, which potentially (from the viewpoint of compiling MyOtherClass) requires dynamic initialization [basic.start.static/3]:

An implementation is permitted to perform the initialization of a
  variable with static or thread storage duration as a static
  initialization even if such initialization is not required to be done
  statically, provided that

the dynamic version of the
  initialization does not change the value of any other object of static
  or thread storage duration prior to its initialization, and

the static version of the initialization produces the same value in the initialized variable as would be produced by the dynamic initialization if all variables not required to be initialized statically were initialized dynamically.

[ Note: As a consequence, if
  the initialization of an object obj1 refers to an object obj2 of
  namespace scope potentially requiring dynamic initialization and
  defined later in the same translation unit, it is unspecified whether
  the value of obj2 used will be the value of the fully initialized obj2
  (because obj2 was statically initialized) or will be the value of obj2
  merely zero-initialized. For example,

```<code>inline double fd() { return 1.0; }
extern double d1;
double d2 = d1;     // unspecified:
                    // may be statically initialized to 0.0 or
                    // dynamically initialized to 0.0 if d1 is
                    // dynamically initialized, or 1.0 otherwise
double d1 = fd();   // may be initialized statically or dynamically to 1.0
</code>```

— end note ]

So when the compiler compiles MyOtherClass.cpp, it doesn't know which way MyClass::z will be actually initialized, so it falls into the "not required to be initialized statically" category. And then it is unspecified, what value MyOtherClass::w will have. It could have

0, when the compiler choose to statically initialize it

4, if the compiler choose to dynamically initialize it

Thanks to StoryTeller for drawing attention to this.

Body:
There are several questions out there about static variables, but I have not yet found an answer to my question. I just read Scott Meyers' explanation on the initialization of static variables and possible issues with it, like the static initialization order fiasco. What I would like to know is this: are static variables at class scope considered non-local?

Most sources I have seen say that static non local variables are defined either at global namespace or in a namespace while static local variables are defined in functions. But consider these two translations unit:

// MyClass.h:
class MyClass
{
public:
    static int z; // Is this non local?
};

// MyClass.cpp:
int MyClass::z = 4;

// MyOtherClass.h:
class MyOtherClass
{
public:
    static int w;
};

// MyOtherClass.cpp:
int MyOtherClass::w = MyClass::z; // Potential fiasco?

Is z non local? In other words, can we assume z is initialized when w is?

Body:
Both MyClass::z and MyOtherClass::w are non-local, static variables.

Your example potentially contains problems.

It's because MyOtherClass::w refers to MyClass::z, which potentially (from the viewpoint of compiling MyOtherClass) requires dynamic initialization [basic.start.static/3]:

An implementation is permitted to perform the initialization of a
  variable with static or thread storage duration as a static
  initialization even if such initialization is not required to be done
  statically, provided that

the dynamic version of the
  initialization does not change the value of any other object of static
  or thread storage duration prior to its initialization, and

the static version of the initialization produces the same value in the initialized variable as would be produced by the dynamic initialization if all variables not required to be initialized statically were initialized dynamically.

[ Note: As a consequence, if
  the initialization of an object obj1 refers to an object obj2 of
  namespace scope potentially requiring dynamic initialization and
  defined later in the same translation unit, it is unspecified whether
  the value of obj2 used will be the value of the fully initialized obj2
  (because obj2 was statically initialized) or will be the value of obj2
  merely zero-initialized. For example,

inline double fd() { return 1.0; }
extern double d1;
double d2 = d1;     // unspecified:
                    // may be statically initialized to 0.0 or
                    // dynamically initialized to 0.0 if d1 is
                    // dynamically initialized, or 1.0 otherwise
double d1 = fd();   // may be initialized statically or dynamically to 1.0

— end note ]

So when the compiler compiles MyOtherClass.cpp, it doesn't know which way MyClass::z will be actually initialized, so it falls into the "not required to be initialized statically" category. And then it is unspecified, what value MyOtherClass::w will have. It could have

0, when the compiler choose to statically initialize it

4, if the compiler choose to dynamically initialize it

Thanks to StoryTeller for drawing attention to this.


问:
Junit test debugged in netbeans is far slower than running without debug
I am having an issue running a junit test in netbeans 8.2.  When simply run, it is something like 10x faster than when debugged.  Both are done inside netbeans IDE. For example, a snippet of code to access CosmosDB using the MongoDB API:

```<code>MongoClientOptions.Builder builder = MongoClientOptions.builder();
builder.sslEnabled(mongodbSsl);
</code>```

Will take about 20 seconds and consume a full CPU core while doing so.  If I run with -verbose, I see 570 lines of classloader output during the second line of code, but that doesn't strike me as something that should take 20 seconds, nor does it explain the in-debugger time difference.  Could it be exceptions caught-and-ignored hitting the IDE?  Is there a way to get extra output explaining where the time is going?  Unfortunately I don't know how to debug and profile at the same time.

Update: this issue does not occur in Eclipse.

答: As Corey mentioned, this was a case of breakpoints in Netbeans.  Apparently, some cases of breakpoints are very expensive.  In particular, Netbeans can have breakpoints that it fails to set (because they are on a line or method or class that is no longer valid).  You can't see them, and so you cannot easily delete them either.  You have to "clear all breakpoints".  Then everything is back to normal.</p>

Body:
I am having an issue running a junit test in netbeans 8.2.  When simply run, it is something like 10x faster than when debugged.  Both are done inside netbeans IDE. For example, a snippet of code to access CosmosDB using the MongoDB API:

MongoClientOptions.Builder builder = MongoClientOptions.builder();
builder.sslEnabled(mongodbSsl);

Will take about 20 seconds and consume a full CPU core while doing so.  If I run with -verbose, I see 570 lines of classloader output during the second line of code, but that doesn't strike me as something that should take 20 seconds, nor does it explain the in-debugger time difference.  Could it be exceptions caught-and-ignored hitting the IDE?  Is there a way to get extra output explaining where the time is going?  Unfortunately I don't know how to debug and profile at the same time.

Update: this issue does not occur in Eclipse.


问:
Same pattern of a special character in 2 strings. Check outline level code of two strings
I have two strings like A.B.C.D_E and in other string I have "..._*" as shown in str.
I want to check if both string are at the same outline level code and both have the same structure.

I tried the following.

```<code>string str= "*.*.*.*_*";
str= str.Replace("*", "");
</code>```

So I will get only dots and dashes and I can count them.

```<code>string abc = "A.B.C.D_E";
var count = Regex.Matches(abc, ".").Count;
var countdash = Regex.Matches(abc, "_").Count;
count= count+countdash;
</code>```

If count is equal to characters in string one than the string have same format.
Unfortunately this solution does not work for different formats.
Is there any better way of doing it?

答:
what you can do is remove all characters except dot and dashes and compare them.

```<code>private string RemoveExtraText(string value)
    {
        var allowedChars = "._";
        return new string(value.Where(c => allowedChars.Contains(c)).ToArray());
    }
</code>```

for your string "A.B.C.D_E". This function will return "...._". Compare it to the other string and you can find if both have same pattern

Body:
I have two strings like A.B.C.D_E and in other string I have "..._*" as shown in str.
I want to check if both string are at the same outline level code and both have the same structure.

I tried the following.

string str= "*.*.*.*_*";
str= str.Replace("*", "");

So I will get only dots and dashes and I can count them.

string abc = "A.B.C.D_E";
var count = Regex.Matches(abc, ".").Count;
var countdash = Regex.Matches(abc, "_").Count;
count= count+countdash;

If count is equal to characters in string one than the string have same format.
Unfortunately this solution does not work for different formats.
Is there any better way of doing it?

Body:
what you can do is remove all characters except dot and dashes and compare them.

private string RemoveExtraText(string value)
    {
        var allowedChars = "._";
        return new string(value.Where(c => allowedChars.Contains(c)).ToArray());
    }

for your string "A.B.C.D_E". This function will return "...._". Compare it to the other string and you can find if both have same pattern


问:
Android Tests skipped due to test package parsing error in AWS Device Farm
Just started with Espresso test case in android and AWS DF from  this video. When uploading both APK's(build, AndroidTest) in AWS device Farm, it says  -"Tests skipped due to test package parsing error. Please check Parsing result for more details."

Parsing result:

```<code>[
    {
        "name": "Setup Suite",
        "tests": [
            {
                "name": "Setup Test"
            }
        ]
    },
    {
        "name": "Teardown Suite",
        "tests": [
            {
                "name": "Teardown Test"
            }
        ]
    }
]
</code>```

答:
When you get the chance can you let me know the result of these questions:

To rule out an issue with the device can we run the same apk with a fuzz test?

If the app is successful, do the sample tests also work?

https://github.com/awslabs/aws-device-farm-sample-app-for-android

If these tests work then can you paste a code snippet of the failing tests ?

There may be something very granular going on.

I look forward to your response

Best regards

James

Body:
Just started with Espresso test case in android and AWS DF from  this video. When uploading both APK's(build, AndroidTest) in AWS device Farm, it says  -"Tests skipped due to test package parsing error. Please check Parsing result for more details."

Parsing result:

[
    {
        "name": "Setup Suite",
        "tests": [
            {
                "name": "Setup Test"
            }
        ]
    },
    {
        "name": "Teardown Suite",
        "tests": [
            {
                "name": "Teardown Test"
            }
        ]
    }
]


问:
Socket System EOFException (ObjectInputStream)
Hey i'm coding a socket system with a open src library...
and everytime when i'm sending a message or something i get an EOFException

```<code>public Datapackage sendMessage(Datapackage message, int timeout) {
    try {
        Socket tempSocket;
        if (secureMode) {
            tempSocket = ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(address.getAddress(),
                    address.getPort());
        } else {
            tempSocket = new Socket();
            tempSocket.connect(address, timeout);
        }

        ObjectOutputStream tempOOS = new ObjectOutputStream(tempSocket.getOutputStream());
        message.sign(id, group);
        tempOOS.writeObject(message);

        ObjectInputStream tempOIS = new ObjectInputStream(tempSocket.getInputStream());
        Object raw = tempOIS.readObject();

        tempOOS.close();
        tempOIS.close();
        tempSocket.close();

        if (raw instanceof Datapackage) {
            return (Datapackage) raw;
        }
    } catch (Exception ex) {
        onLogError("[Client] Error while sending message:");
        ex.printStackTrace();
    }

    return null;
}
</code>```

Please can anyone help me :c

答: The peer has closed the connection without creating an ObjectOutputStream. Almost certainly it isn't using Serialization at all.

Body:
Hey i'm coding a socket system with a open src library...
and everytime when i'm sending a message or something i get an EOFException

public Datapackage sendMessage(Datapackage message, int timeout) {
    try {
        Socket tempSocket;
        if (secureMode) {
            tempSocket = ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(address.getAddress(),
                    address.getPort());
        } else {
            tempSocket = new Socket();
            tempSocket.connect(address, timeout);
        }

        ObjectOutputStream tempOOS = new ObjectOutputStream(tempSocket.getOutputStream());
        message.sign(id, group);
        tempOOS.writeObject(message);

        ObjectInputStream tempOIS = new ObjectInputStream(tempSocket.getInputStream());
        Object raw = tempOIS.readObject();

        tempOOS.close();
        tempOIS.close();
        tempSocket.close();

        if (raw instanceof Datapackage) {
            return (Datapackage) raw;
        }
    } catch (Exception ex) {
        onLogError("[Client] Error while sending message:");
        ex.printStackTrace();
    }

    return null;
}

Please can anyone help me :c


问:
SQL Add empty rows in a Details Table per each Record in a Master Tble
I once asked this question on this forum:

I need to add empty rows to a SQL SELECT statement in such a way that the result is in multiples of 10, meaning if there are 8 rows in a Tables, 2 empty Rows should be added so that the select statement has 10 rows and if there are say 16 rows in a Table, 4 empty rows should be added so that the select statement has 20 rows etc, etc.
  In short at all times the rows selected must be 10,20,30,40, etc, etc

I then got this answer which works.

```<code>DECLARE @tmpTable TABLE (ID INT, _Text NVARCHAR(255))
DECLARE @X INT=1
WHILE @X <9
 BEGIN
 INSERT INTO @tmpTable
 VALUES (@X, 'XXXXX') SET
@X=@X+1 END SELECT * FROM @tmpTable
UNION ALL
 SELECT TOP (10 - ISNULL(NULLIF((SELECT COUNT(*) FROM @tmpTable) % 10, 0), 10))
(SELECT MAX(ID) FROM @tmpTable)+n, NULL     FROM (VALUES(1), (2),(3), (4),(5),
(6),(7), (8),(9), (10)) A(n)
</code>```

RESULT

```<code>ID  _Text
1   XXXXX
2   XXXXX
3   XXXXX
4   XXXXX
5   XXXXX
6   XXXXX
7   XXXXX
8   XXXXX
9   NULL
10  NULL
</code>```

In case of 16 rows in a Table the result would be like this:

```<code>DECLARE @tmpTable TABLE (ID INT, _Text NVARCHAR(255))
DECLARE @X INT=1
WHILE @X <17
BEGIN
    INSERT INTO @tmpTable
    VALUES  (@X, 'XXXXX')
SET @X=@X+1
END
SELECT * FROM @tmpTable
    UNION ALL
    SELECT TOP (10 - ISNULL(NULLIF((SELECT COUNT(*) FROM @tmpTable) % 10, 0), 10))
    (SELECT MAX(ID) FROM @tmpTable)+n, NULL
    FROM (VALUES(1), (2),(3), (4),(5), (6),(7), (8),(9), (10)) A(n)
</code>```

RESULTS

```<code>ID  _Text
1   XXXXX
2   XXXXX
3   XXXXX
4   XXXXX
5   XXXXX
6   XXXXX
7   XXXXX
8   XXXXX
9   XXXXX
10  XXXXX
11  XXXXX
12  XXXXX
13  XXXXX
14  XXXXX
15  XXXXX
16  XXXXX
17  NULL
18  NULL
19  NULL
20  NULL
</code>```

However, I want to modify the answer so that it works in a Master/Details scenario as follows:
Assuming there are two records in a Master Table as follows:

```<code>MasterID
1
2
</code>```

And assuming the following records in a Details Table:

```<code>ID  MasterID    DetailsDescription
1      1        XXXXX
2      1        XXXXX
3      1        XXXXX
4      1        XXXXX
5      1        XXXXX
6      1        XXXXX
7      2        XXXX
8      2        XXXX
9      2        XXXX
10     2        XXXX
11     2        XXXX
12     2        XXXX
13     2        XXXX
14     2        XXXX
</code>```

I want the result to be:

```<code>ID  MasterID    DetailsDescription
1      1        XXXXX
2      1        XXXXX
3      1        XXXXX
4      1        XXXXX
5      1        XXXXX
6      1        XXXXX
       1        NULL
       1        NULL
       1        NULL
       1        NULL
7      2        XXXX
8      2        XXXX
9      2        XXXX
10     2        XXXX
11     2        XXXX
12     2        XXXX
13     2        XXXX
14     2        XXXX
       2        NULL
       2        NULL
</code>```

In such a way that for Master Record 1 there must be 10 records selected in the Details Table (i.e. with 4 empty rows added since there are only 6 records in the Details Table linked to Master Record 1) and similarly for Master Record 2 10 rows should be selected in the Details Table (i.e 2 empty rows added since there are 8 rows in the Details Table linked to Master Record 2) etc,etc,etc.

I tried doing it this way but empty rows are added at the end:

```<code>DECLARE @MasterTable TABLE(MasterID INT)
INSERT INTO @MasterTable
VALUES(1),(2)

DECLARE @DetailsTable TABLE (ID INT, MasterID INT, _Text NVARCHAR(255))
DECLARE @X INT=1
WHILE @X <7
 BEGIN
 INSERT INTO @DetailsTable
 VALUES (@X,1, 'XXXXX') SET
@X=@X+1
END

SET @X=1
WHILE @X <9
 BEGIN
 INSERT INTO @DetailsTable
 VALUES (@X, 2, 'XXXXX') SET
@X=@X+1
END
 SELECT D.* FROM @DetailsTable as D INNER JOIN @MasterTable AS M ON M.MasterID = D.MasterID
UNION ALL
 SELECT TOP (10 - ISNULL(NULLIF((SELECT COUNT(*)
 FROM  @DetailsTable as D INNER JOIN AS M ON M.MasterID = D.MasterID) % 10, 0), 10))
(SELECT MAX(ID) FROM @DetailsTable as D INNER JOIN @MasterTable AS M ON M.MasterID = D.MasterID)+n, NULL, NULL
FROM (VALUES(1), (2),(3), (4),(5),
(6),(7), (8),(9), (10)) A(n)
</code>```

RESULT

```<code>ID  MasterID    _Text
1      1        XXXXX
2      1        XXXXX
3      1        XXXXX
4      1        XXXXX
5      1        XXXXX
6      1        XXXXX
1      2        XXXXX
2      2        XXXXX
3      2        XXXXX
4      2        XXXXX
5      2        XXXXX
6      2        XXXXX
7      2        XXXXX
8      2        XXXXX
9     NULL      NULL
10    NULL      NULL
11    NULL      NULL
12    NULL      NULL
13    NULL      NULL
14    NULL      NULL
</code>```

答:
try the following:

```<code>DECLARE @MasterTable TABLE(MasterID INT)
INSERT INTO @MasterTable
VALUES(1),(2)

DECLARE @DetailsTable TABLE (ID INT, MasterID INT, _Text NVARCHAR(255))
DECLARE @X INT=1
WHILE @X <7
BEGIN
    INSERT INTO @DetailsTable VALUES (@X,1, 'XXXXX')
    SET @X+=1
END

SET @X=1
WHILE @X <9
BEGIN
    INSERT INTO @DetailsTable VALUES (@X, 2, 'XXXXX')
    SET @X+=1
END

DECLARE @TEMP TABLE (M_ID INT)
DECLARE @ID INT
INSERT @TEMP SELECT DISTINCT MasterID FROM @MASTERTABLE
WHILE ((SELECT COUNT(1) FROM @TEMP) > 0)
BEGIN
    SET @ID = (SELECT TOP 1 M_ID FROM @TEMP)
    INSERT @DETAILSTABLE
     SELECT TOP (10 - ISNULL(NULLIF((SELECT COUNT(*) FROM  @DETAILSTABLE WHERE MASTERID = @ID) % 10, 0), 10))
    (SELECT MAX(ID) FROM @DETAILSTABLE WHERE MasterID = @ID)+n, @ID, NULL
    FROM (VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) A(n)
    DELETE @TEMP WHERE M_ID = @ID
END

SELECT * FROM @DETAILSTABLE ORDER BY MasterID, ID
</code>```

HTH!

Thanks.

Body:
I once asked this question on this forum:

I need to add empty rows to a SQL SELECT statement in such a way that the result is in multiples of 10, meaning if there are 8 rows in a Tables, 2 empty Rows should be added so that the select statement has 10 rows and if there are say 16 rows in a Table, 4 empty rows should be added so that the select statement has 20 rows etc, etc.
  In short at all times the rows selected must be 10,20,30,40, etc, etc

I then got this answer which works.

DECLARE @tmpTable TABLE (ID INT, _Text NVARCHAR(255))
DECLARE @X INT=1
WHILE @X <9
 BEGIN
 INSERT INTO @tmpTable
 VALUES (@X, 'XXXXX') SET
@X=@X+1 END SELECT * FROM @tmpTable
UNION ALL
 SELECT TOP (10 - ISNULL(NULLIF((SELECT COUNT(*) FROM @tmpTable) % 10, 0), 10))
(SELECT MAX(ID) FROM @tmpTable)+n, NULL     FROM (VALUES(1), (2),(3), (4),(5),
(6),(7), (8),(9), (10)) A(n)

RESULT

ID  _Text
1   XXXXX
2   XXXXX
3   XXXXX
4   XXXXX
5   XXXXX
6   XXXXX
7   XXXXX
8   XXXXX
9   NULL
10  NULL

In case of 16 rows in a Table the result would be like this:

DECLARE @tmpTable TABLE (ID INT, _Text NVARCHAR(255))
DECLARE @X INT=1
WHILE @X <17
BEGIN
    INSERT INTO @tmpTable
    VALUES  (@X, 'XXXXX')
SET @X=@X+1
END
SELECT * FROM @tmpTable
    UNION ALL
    SELECT TOP (10 - ISNULL(NULLIF((SELECT COUNT(*) FROM @tmpTable) % 10, 0), 10))
    (SELECT MAX(ID) FROM @tmpTable)+n, NULL
    FROM (VALUES(1), (2),(3), (4),(5), (6),(7), (8),(9), (10)) A(n)

RESULTS

ID  _Text
1   XXXXX
2   XXXXX
3   XXXXX
4   XXXXX
5   XXXXX
6   XXXXX
7   XXXXX
8   XXXXX
9   XXXXX
10  XXXXX
11  XXXXX
12  XXXXX
13  XXXXX
14  XXXXX
15  XXXXX
16  XXXXX
17  NULL
18  NULL
19  NULL
20  NULL

However, I want to modify the answer so that it works in a Master/Details scenario as follows:
Assuming there are two records in a Master Table as follows:

MasterID
1
2

And assuming the following records in a Details Table:

ID  MasterID    DetailsDescription
1      1        XXXXX
2      1        XXXXX
3      1        XXXXX
4      1        XXXXX
5      1        XXXXX
6      1        XXXXX
7      2        XXXX
8      2        XXXX
9      2        XXXX
10     2        XXXX
11     2        XXXX
12     2        XXXX
13     2        XXXX
14     2        XXXX

I want the result to be:

ID  MasterID    DetailsDescription
1      1        XXXXX
2      1        XXXXX
3      1        XXXXX
4      1        XXXXX
5      1        XXXXX
6      1        XXXXX
       1        NULL
       1        NULL
       1        NULL
       1        NULL
7      2        XXXX
8      2        XXXX
9      2        XXXX
10     2        XXXX
11     2        XXXX
12     2        XXXX
13     2        XXXX
14     2        XXXX
       2        NULL
       2        NULL

In such a way that for Master Record 1 there must be 10 records selected in the Details Table (i.e. with 4 empty rows added since there are only 6 records in the Details Table linked to Master Record 1) and similarly for Master Record 2 10 rows should be selected in the Details Table (i.e 2 empty rows added since there are 8 rows in the Details Table linked to Master Record 2) etc,etc,etc.

I tried doing it this way but empty rows are added at the end:

DECLARE @MasterTable TABLE(MasterID INT)
INSERT INTO @MasterTable
VALUES(1),(2)

DECLARE @DetailsTable TABLE (ID INT, MasterID INT, _Text NVARCHAR(255))
DECLARE @X INT=1
WHILE @X <7
 BEGIN
 INSERT INTO @DetailsTable
 VALUES (@X,1, 'XXXXX') SET
@X=@X+1
END

SET @X=1
WHILE @X <9
 BEGIN
 INSERT INTO @DetailsTable
 VALUES (@X, 2, 'XXXXX') SET
@X=@X+1
END
 SELECT D.* FROM @DetailsTable as D INNER JOIN @MasterTable AS M ON M.MasterID = D.MasterID
UNION ALL
 SELECT TOP (10 - ISNULL(NULLIF((SELECT COUNT(*)
 FROM  @DetailsTable as D INNER JOIN AS M ON M.MasterID = D.MasterID) % 10, 0), 10))
(SELECT MAX(ID) FROM @DetailsTable as D INNER JOIN @MasterTable AS M ON M.MasterID = D.MasterID)+n, NULL, NULL
FROM (VALUES(1), (2),(3), (4),(5),
(6),(7), (8),(9), (10)) A(n)

RESULT

ID  MasterID    _Text
1      1        XXXXX
2      1        XXXXX
3      1        XXXXX
4      1        XXXXX
5      1        XXXXX
6      1        XXXXX
1      2        XXXXX
2      2        XXXXX
3      2        XXXXX
4      2        XXXXX
5      2        XXXXX
6      2        XXXXX
7      2        XXXXX
8      2        XXXXX
9     NULL      NULL
10    NULL      NULL
11    NULL      NULL
12    NULL      NULL
13    NULL      NULL
14    NULL      NULL

Body:
try the following:

DECLARE @MasterTable TABLE(MasterID INT)
INSERT INTO @MasterTable
VALUES(1),(2)

DECLARE @DetailsTable TABLE (ID INT, MasterID INT, _Text NVARCHAR(255))
DECLARE @X INT=1
WHILE @X <7
BEGIN
    INSERT INTO @DetailsTable VALUES (@X,1, 'XXXXX')
    SET @X+=1
END

SET @X=1
WHILE @X <9
BEGIN
    INSERT INTO @DetailsTable VALUES (@X, 2, 'XXXXX')
    SET @X+=1
END

DECLARE @TEMP TABLE (M_ID INT)
DECLARE @ID INT
INSERT @TEMP SELECT DISTINCT MasterID FROM @MASTERTABLE
WHILE ((SELECT COUNT(1) FROM @TEMP) > 0)
BEGIN
    SET @ID = (SELECT TOP 1 M_ID FROM @TEMP)
    INSERT @DETAILSTABLE
     SELECT TOP (10 - ISNULL(NULLIF((SELECT COUNT(*) FROM  @DETAILSTABLE WHERE MASTERID = @ID) % 10, 0), 10))
    (SELECT MAX(ID) FROM @DETAILSTABLE WHERE MasterID = @ID)+n, @ID, NULL
    FROM (VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) A(n)
    DELETE @TEMP WHERE M_ID = @ID
END

SELECT * FROM @DETAILSTABLE ORDER BY MasterID, ID

HTH!

Thanks.


问:
Remove null values in SQL server

Hello, Does anuone knows how can I remowe the null values corresponding to the description of the same product key? So, I have one product Key and its description in each language.

I'm trying to use the coalesce function, but it doesnt return me anything.

答:
It looks like you want to combine the rows together for each ProductKey.

So instead of 5 lines, each with a single column populated, you want one line, with all 5 columns populated.

Do it like this:

```<code>Select Distinct T.ProductKey, C1.Column1, C2.Column2, C3.Column3 from MyTable T
left join MyTable C1 on C1.ProductKey = T.ProductKey and C1.Column1 is not null
left join MyTable C2 on C2.ProductKey = T.ProductKey and C2.Column2 is not null
left join MyTable C3 on C3.ProductKey = T.ProductKey and C3.Column3 is not null
</code>```

Just replace "MyTable" above with your table name, and "Column1, Column2, Column3" with the names of the columns your data is in.

Pretend that each column is on its own separate table, and you need to use joins to connect all the tables back to your master set of ProductKeys.

Think about it in sets:
Basically you are going to make one master list of the keys that is distinct/unique (step 1), and then do a new left join for each column you want to attach to the master list (step 2), and as part of the joins, tell it to get the non-NULL values and ignore the NULLs.

Title: Remove null values in SQL server

Body:
It looks like you want to combine the rows together for each ProductKey.

So instead of 5 lines, each with a single column populated, you want one line, with all 5 columns populated.

Do it like this:

Select Distinct T.ProductKey, C1.Column1, C2.Column2, C3.Column3 from MyTable T
left join MyTable C1 on C1.ProductKey = T.ProductKey and C1.Column1 is not null
left join MyTable C2 on C2.ProductKey = T.ProductKey and C2.Column2 is not null
left join MyTable C3 on C3.ProductKey = T.ProductKey and C3.Column3 is not null

Just replace "MyTable" above with your table name, and "Column1, Column2, Column3" with the names of the columns your data is in.

Pretend that each column is on its own separate table, and you need to use joins to connect all the tables back to your master set of ProductKeys.

Think about it in sets:
Basically you are going to make one master list of the keys that is distinct/unique (step 1), and then do a new left join for each column you want to attach to the master list (step 2), and as part of the joins, tell it to get the non-NULL values and ignore the NULLs.


问:
Listen preference change and transfer boolean in checkbox to MainActivity
I have 2 file:

control_preferences.xml:`

```<code><PreferenceCategory
    android:title="@string/control_category">

    <CheckBoxPreference
        android:title="Debug Information ON/OFF"
        android:defaultValue="false"
        android:summary="Show debug information when ON"
        android:key="checkboxPref" />

</PreferenceCategory>
</code>```

`

SettingsActivity.java:

```<code>package com.sample;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

public class SettingsActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {

    public static final String KEY_PREF_DEBUG = "checkboxPref";

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                                          String key) {
        if (key.equals(KEY_PREF_DEBUG)) {
            Toast.makeText(getApplicationContext(), "CLICK",
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onBuildHeaders(List<Header> target) {
        loadHeadersFromResource(R.xml.preference_headers, target);
    }

    public static class ControlPrefsFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // load the preferences from an XML resource
            addPreferencesFromResource(R.xml.fragmented_control_preferences);
        }
    }}
</code>```

I have 2 questions:

Why when selecting or deselecting Checkbox Toast doesn't display?

How to store in SharedPreferences boolean from this CheckBox and later read this boolean in MainActivity.

答:
Use this instead of implementing interface</p>

```<code>checkboxPref = (CheckBoxPreference) getPreferenceScreen().findPreference(your_key);

checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{

     @Override
     public boolean onPreferenceChange(Preference preference, Object newValue)
     {

          YOUR CODE

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

Body:
I have 2 file:

control_preferences.xml:`

<PreferenceCategory
    android:title="@string/control_category">

    <CheckBoxPreference
        android:title="Debug Information ON/OFF"
        android:defaultValue="false"
        android:summary="Show debug information when ON"
        android:key="checkboxPref" />

</PreferenceCategory>

`

SettingsActivity.java:

package com.sample;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

public class SettingsActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {

    public static final String KEY_PREF_DEBUG = "checkboxPref";

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                                          String key) {
        if (key.equals(KEY_PREF_DEBUG)) {
            Toast.makeText(getApplicationContext(), "CLICK",
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onBuildHeaders(List target) {
        loadHeadersFromResource(R.xml.preference_headers, target);
    }

    public static class ControlPrefsFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // load the preferences from an XML resource
            addPreferencesFromResource(R.xml.fragmented_control_preferences);
        }
    }}

I have 2 questions:

Why when selecting or deselecting Checkbox Toast doesn't display?

How to store in SharedPreferences boolean from this CheckBox and later read this boolean in MainActivity.

Body:
Use this instead of implementing interface

checkboxPref = (CheckBoxPreference) getPreferenceScreen().findPreference(your_key);

checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{

     @Override
     public boolean onPreferenceChange(Preference preference, Object newValue)
     {

          YOUR CODE

          return false;
     }
});


问:
Using a CASE statement in a WHERE clause in SQL Server
I am trying to create query form on a website.  First object is a dropdown list with operators. Default first value in the dropdown list is NULL(1), second value is LIKE(2), etc...  Second object is a textbox where the user can enter a string like "A".

Therefore, I am trying to build the below SQL query to simulate the variables coming from the website.  It runs and returns all values when the @op = 1.  But I keep getting the following error when I change @op = 2:

Conversion failed when converting the nvarchar value 'Tom LIKE A%' to data type int."

```<code>DECLARE @StartDate DATETIME2(7) = '2017-11-08 00:00:00.0000000 +00:00'
DECLARE @EndDate DATETIME2(7) = '2017-11-08 00:00:00.0000000 +00:00'
DECLARE @Op INT = 2
DECLARE @name NVARCHAR(25) = 'A'
SELECT
    name,
    dttm
FROM
    tableName
WHERE
    dttm BETWEEN @StartDate AND @EndDate
    AND CASE @Op
        WHEN 1 THEN 1
        WHEN 2 THEN name + ' LIKE ' + @name +'%'
        END <> 0
</code>```

答:
Don't use case.  Just use regular boolean logic:

```<code>WHERE dttm BETWEEN @StartDate AND @EndDate AND
      ( (@op = 1) OR
        (@op = 2 AND name LIKE @name + '%')
      )
</code>```

Your specific issue involves constructing a LIKE comparison in a string.  However, the above appears to be what you want to do.

Body:
I am trying to create query form on a website.  First object is a dropdown list with operators. Default first value in the dropdown list is NULL(1), second value is LIKE(2), etc...  Second object is a textbox where the user can enter a string like "A".

Therefore, I am trying to build the below SQL query to simulate the variables coming from the website.  It runs and returns all values when the @op = 1.  But I keep getting the following error when I change @op = 2:

Conversion failed when converting the nvarchar value 'Tom LIKE A%' to data type int."

DECLARE @StartDate DATETIME2(7) = '2017-11-08 00:00:00.0000000 +00:00'
DECLARE @EndDate DATETIME2(7) = '2017-11-08 00:00:00.0000000 +00:00'
DECLARE @Op INT = 2
DECLARE @name NVARCHAR(25) = 'A'
SELECT
    name,
    dttm
FROM
    tableName
WHERE
    dttm BETWEEN @StartDate AND @EndDate
    AND CASE @Op
        WHEN 1 THEN 1
        WHEN 2 THEN name + ' LIKE ' + @name +'%'
        END <> 0

Body:
Don't use case.  Just use regular boolean logic:

WHERE dttm BETWEEN @StartDate AND @EndDate AND
      ( (@op = 1) OR
        (@op = 2 AND name LIKE @name + '%')
      )

Your specific issue involves constructing a LIKE comparison in a string.  However, the above appears to be what you want to do.


问:
How to make Enter Key as Default key for Tab Changing for all the textbox in a Window Form C#?
I am using c# window form application. I have already tried many example on the internet for this query but nothing works for me. I just want to replace the action of Enter key with Tab key on a Window Forms. I don't want to apply keydown or up event on one by one on my textbox. I just want a single event which I can apply on my window form.

Thanks.

答:
It works fine now I used these code of lines on form keyup event, and set the KeyPreview property True.</p>

```<code>    if (e.KeyData == System.Windows.Forms.Keys.Enter)
        {
            SendKeys.Send("{TAB}");
        }
</code>```

Body:
It works fine now I used these code of lines on form keyup event, and set the KeyPreview property True.

    if (e.KeyData == System.Windows.Forms.Keys.Enter)
        {
            SendKeys.Send("{TAB}");
        }


问:
Detect Page Close Event
What is the best way for page closed event detection ?

I have a page and I want to check if the page get's closed.
I have to do something if the user closes the page.

I tried this way and it didn't work.

I will rollback progress if user leave.

答:
you can use beforeunload in javascript, check this example

```<code><script type="text/javascript">
$(document).ready(function () {
    $(window).on('beforeunload', function () {
        return 'Do something...';
    });
});
</code>```

Title: Detect Page Close Event

Body:
you can use beforeunload in javascript, check this example

<script type="text/javascript">
$(document).ready(function () {
    $(window).on('beforeunload', function () {
        return 'Do something...';
    });
});


问:
Inserting some fields values of one model to another model and showing all fields on one view in odoo 10
Inserting some fields values of one model to another model and showing all fields on one view.
For example !

I am having a student model which basic information (first name, last name etc) and want to save it into res_partner table. This is because i don't want to show extra fields of res_partner on student registration form view. Just using custom form view having tabs and other fields.

答:
@api.multi
   def open_second_class(self):
               ac=self.env['ir.model.data'].xmlid_to_res_id('account.invoice_form',raise_if_not_found=True)
            write_obj = ac.create({'partner_id': self.name_id})
            accountant = False
            for o in self:
                accountant = o.id
            result = {
                'name': '2nd class',
                'view_type': 'form',
                'res_model': 'account.invoice',
                'res_id': write_obj.id,
                'view_id': False,
                'context': {'default_id_tbl1': accountant},
                'type': 'ir.actions.act_window',
                'view_mode': 'form',
                'target': 'new',
                'domain': '[]'
            }
            return result</p>


问:
Variables in Stylus CSS Media Queries
I've tried everything but I can't get the Stylus CSS preprocessor to use variables in media queries.

For instance this doesn't work:

```<code>t = 1000px

@media screen and (max-width: t)
    html
        background blue
</code>```

Anyone know how to do this?

答:
I liked the answer from Tony Tai Nguyen. Here's another iteration:</p>

```<code>sizes = {
  mobile: 0 768
  tablet: 769 1023
  desktop: 1024 1215
  widescreen: 1216 1407
  fullhd: 1408 99999999
}
query = {}

for name, pxs in sizes
  min = '(min-width:' + pxs[0] + 'px)'
  max = '(max-width:' + pxs[1] + 'px)'
  query[name] = min + ' and ' + max
  query[name + '-up'] = 'screen and ' + min
  query[name + '-down'] = 'screen and ' + max

// Usage: @media query.mobile or @media query.tablet-up etc...
</code>```

Title: Variables in Stylus CSS Media Queries

Body:
I've tried everything but I can't get the Stylus CSS preprocessor to use variables in media queries.

For instance this doesn't work:

t = 1000px

@media screen and (max-width: t)
    html
        background blue

Anyone know how to do this?

Body:
I liked the answer from Tony Tai Nguyen. Here's another iteration:

sizes = {
  mobile: 0 768
  tablet: 769 1023
  desktop: 1024 1215
  widescreen: 1216 1407
  fullhd: 1408 99999999
}
query = {}

for name, pxs in sizes
  min = '(min-width:' + pxs[0] + 'px)'
  max = '(max-width:' + pxs[1] + 'px)'
  query[name] = min + ' and ' + max
  query[name + '-up'] = 'screen and ' + min
  query[name + '-down'] = 'screen and ' + max

// Usage: @media query.mobile or @media query.tablet-up etc...


问:
VIM set spell in file .git/COMMIT_EDITMSG
I want to "set spell" automatically when i am editing the commit text in git. From the % I see that it is writing to a filename called  .git/COMMIT_EDITMSG.  How do I update my .vimrc to automatically set spell on when editing that file.
something on the lines

if ( filename has a word COMMIT)

set spell

fi

答:
You can add 'set spell' to your .vimrc file to make Vim automatically spell check all documents including your git commit messages.  Vim is smart enough to spell check comments and strings while ignoring your source code.

Depending on your colorscheme, this can be annoying though to see variable names in your comments and strings highlighted as misspelled words.

See this stackoverflow question for more details on spell checking.


问:
Memory copy speed comparison CPU<->GPU
I am now learning boost::compute openCL wrapper library.
I am experiencing very slow copy procedure.

If we scale CPU to CPU copy speed as 1, how fast is GPU to CPU, GPU to GPU, CPU to GPU copy?

I don't require precise numbers. Just a general idea would be a great help. In example CPU-CPU is at least 10 times faster than GPU-GPU.

答:
No one is answering my question.
So I made a program to check the copy speed.

```<code>#include<vector>
#include<chrono>
#include<algorithm>
#include<iostream>
#include<boost/compute.hpp>
namespace compute = boost::compute;
using namespace std::chrono;
using namespace std;

int main()
{
    int sz = 10000000;
    std::vector<float> v1(sz, 2.3f), v2(sz);
    compute::vector<float> v3(sz), v4(sz);

    auto s = system_clock::now();
    std::copy(v1.begin(), v1.end(), v2.begin());
    auto e = system_clock::now();
    cout << "cpu2cpu cp " << (e - s).count() << endl;

    s = system_clock::now();
    compute::copy(v1.begin(), v1.end(), v3.begin());
    e = system_clock::now();
    cout << "cpu2gpu cp " << (e - s).count() << endl;

    s = system_clock::now();
    compute::copy(v3.begin(), v3.end(), v4.begin());
    e = system_clock::now();
    cout << "gpu2gpu cp " << (e - s).count() << endl;

    s = system_clock::now();
    compute::copy(v3.begin(), v3.end(), v1.begin());
    e = system_clock::now();
    cout << "gpu2cpu cp " << (e - s).count() << endl;
    return 0;
}
</code>```

I expected that gpu2gpu copy would be fast.
But on the contrary, cpu2cpu was fastest and gpu2gpu was so slow in my case.
(My system is Intel I3 and Intel(R) HD Graphics Skylake ULT GT2.)
Maybe parallel processing is one thing and copy speed is another.

cpu2cpu cp 7549776

cpu2gpu cp 18707268

gpu2gpu cp 65841100

gpu2cpu cp 65803119

I hope anyone can benefit with this test program.

Title: Memory copy speed comparison CPU<->GPU

Body:
No one is answering my question.
So I made a program to check the copy speed.

#include<vector>
#include<chrono>
#include<algorithm>
#include<iostream>
#include<boost/compute.hpp>
namespace compute = boost::compute;
using namespace std::chrono;
using namespace std;

int main()
{
    int sz = 10000000;
    std::vector<float> v1(sz, 2.3f), v2(sz);
    compute::vector<float> v3(sz), v4(sz);

    auto s = system_clock::now();
    std::copy(v1.begin(), v1.end(), v2.begin());
    auto e = system_clock::now();
    cout << "cpu2cpu cp " << (e - s).count() << endl;

    s = system_clock::now();
    compute::copy(v1.begin(), v1.end(), v3.begin());
    e = system_clock::now();
    cout << "cpu2gpu cp " << (e - s).count() << endl;

    s = system_clock::now();
    compute::copy(v3.begin(), v3.end(), v4.begin());
    e = system_clock::now();
    cout << "gpu2gpu cp " << (e - s).count() << endl;

    s = system_clock::now();
    compute::copy(v3.begin(), v3.end(), v1.begin());
    e = system_clock::now();
    cout << "gpu2cpu cp " << (e - s).count() << endl;
    return 0;
}

I expected that gpu2gpu copy would be fast.
But on the contrary, cpu2cpu was fastest and gpu2gpu was so slow in my case.
(My system is Intel I3 and Intel(R) HD Graphics Skylake ULT GT2.)
Maybe parallel processing is one thing and copy speed is another.

cpu2cpu cp 7549776

cpu2gpu cp 18707268

gpu2gpu cp 65841100

gpu2cpu cp 65803119

I hope anyone can benefit with this test program.


问:
Python3 UnicodeDecodeError, can't read file with cp1251 encoding
I've upgraded Ubuntu from 14.04 (Python 3.4.3) to 16.04 (Python 3.5.2). Now my script can't read a file with the encoding cp1251:

```<code>with open(fs[0], encoding='cp1251') as f:
    lines = f.readlines()
    f.close()
</code>```

It gives an error:

```<code>Traceback (most recent call last):
  File "/home/michael/PycharmProjects/Rad/get_info.py", line 9, in <module>
    r.get_tests()
  File "/home/michael/PycharmProjects/Rad/rad.py", line 166, in get_tests
    s = f.readlines()
  File "/usr/lib/python3.5/encodings/cp1251.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 13: character maps to <undefined>

Process finished with exit code 1
</code>```

Debugging leads to the this code in the file /usr/lib/python3.5/encodings/cp1251.py:

```<code>class IncrementalDecoder(codecs.IncrementalDecoder):
    def decode(self, input, final=False):
        return codecs.charmap_decode(input,self.errors,decoding_table)[0]
</code>```

What was changed in this Python version and how to avoid this error?

答:
So I found a way to fix this error that works both in Python 2 and 3:</p>

```<code>import codecs
...........
with codecs.open(fs[0], encoding='cp1251', errors='replace') as f:
    lines = f.readlines()
    f.close()
</code>```

Body:
I've upgraded Ubuntu from 14.04 (Python 3.4.3) to 16.04 (Python 3.5.2). Now my script can't read a file with the encoding cp1251:

with open(fs[0], encoding='cp1251') as f:
    lines = f.readlines()
    f.close()

It gives an error:

Traceback (most recent call last):
  File "/home/michael/PycharmProjects/Rad/get_info.py", line 9, in <module>
    r.get_tests()
  File "/home/michael/PycharmProjects/Rad/rad.py", line 166, in get_tests
    s = f.readlines()
  File "/usr/lib/python3.5/encodings/cp1251.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 13: character maps to <undefined>

Process finished with exit code 1

Debugging leads to the this code in the file /usr/lib/python3.5/encodings/cp1251.py:

class IncrementalDecoder(codecs.IncrementalDecoder):
    def decode(self, input, final=False):
        return codecs.charmap_decode(input,self.errors,decoding_table)[0]

What was changed in this Python version and how to avoid this error?

Body:
So I found a way to fix this error that works both in Python 2 and 3:

import codecs
...........
with codecs.open(fs[0], encoding='cp1251', errors='replace') as f:
    lines = f.readlines()
    f.close()


问:
String.size() returns incorrect number if there is space in the string
I'm trying to write a program that returns the number of characters in a string. As I was writing my program, I've noticed that there's a bug in the string class.

Say my program is this:

```<code>#include <iostream>
#include <string>
using namespace std;

int main()
{
   string input;

   cout << "Input string: ";
   cin >> input

   cout << "Number of characters: " << input.size() << endl;

   return 0;
}
</code>```

If my input is Test String, I should see the number 11 as the output.

However, the output I get is this:

```<code>Number of characters: 4
</code>```

It seems like the size() method does not work when there is space in the string.

My question is, is there another way to get the number of characters in a string? I tried length() method but the result was the same.

答: After taking input correctly, you can get the length of the string or char pointer(char*)(including whitespaces) by using strlen(string_name), this will return the length.</p>

Body:
I'm trying to write a program that returns the number of characters in a string. As I was writing my program, I've noticed that there's a bug in the string class.

Say my program is this:

#include <iostream>
#include <string>
using namespace std;

int main()
{
   string input;

   cout << "Input string: ";
   cin >> input

   cout << "Number of characters: " << input.size() << endl;

   return 0;
}

If my input is Test String, I should see the number 11 as the output.

However, the output I get is this:

Number of characters: 4

It seems like the size() method does not work when there is space in the string.

My question is, is there another way to get the number of characters in a string? I tried length() method but the result was the same.


问:
Unable to get filename/foldername of team drive file using GAS
I have been trying to get the filename of a file/folder which is located in my team drive.

I have tried with

```<code>showAlert(DriveApp.getFolderById('0ANNqmMDkIgpzUk9PVA').getName());
</code>```

答:
Your code is good, so

Check that you have the complete folder id. If you missed out some characters, it will not work.

Check that you have at least viewing permission for the folder.

I successfully tested the following with a public folder:

```<code>SpreadsheetApp.getUi().alert(
  "Folder name: " +
  DriveApp.getFolderById('16EbJb18MXxnDrbc0OsMbOk4CBxrT1upM').getName()
);
</code>```

The alert popped up in an open Google Sheets page.

You could also replace SpreadsheetApp.getUi().alert with Browser.msgBox

Body:
I have been trying to get the filename of a file/folder which is located in my team drive.

I have tried with

showAlert(DriveApp.getFolderById('0ANNqmMDkIgpzUk9PVA').getName());

Body:
Your code is good, so

Check that you have the complete folder id. If you missed out some characters, it will not work.

Check that you have at least viewing permission for the folder.

I successfully tested the following with a public folder:

SpreadsheetApp.getUi().alert(
  "Folder name: " +
  DriveApp.getFolderById('16EbJb18MXxnDrbc0OsMbOk4CBxrT1upM').getName()
);

The alert popped up in an open Google Sheets page.

You could also replace SpreadsheetApp.getUi().alert with Browser.msgBox


问:
How do you set specific values to a dynamic array?
Apparently I'm misunderstanding this, but I'm trying to simply set specific numbers to a dynamic memory array.</p>

```<code>#include <iostream>
#include <cstdlib>
using namespace std;

int main () {
    int *arr = new int [4][5]
    {{3, 6, 9, 23, 16},
    {24, 12, 9, 13, 5},
    {37, 19, 43, 17, 11},
    {71, 32, 8, 4, 7}};

    cout<< arr [1][3]<< endl<< endl;
    int *x = new int;
    *x = arr [2][1];
    cout<< x<< endl;
    cout<< *x<< endl << endl;
    delete x;
    *x = arr [0][3];
    cout<< x<< endl;
    cout<< *x<< endl;
    delete x;
    delete [] arr;
    return;
}
</code>```

答:
C++ support for multidimension arrays is done through libraries (eg boost). Without classes it really only understands 1D arrays, particularly when you are using pointers, which C/C++ really sees as just a pointer to the first element of the array. To get your example to work without classes you need to define a type that holds one row and then create an array of that type, which you can assign values to as you show.

```<code>#include <iostream>
#include <cstdlib>
using namespace std;

int main () {
    typedef int row_t[5];
    row_t *arr = new row_t[4] {{3, 6, 9, 23, 16},
    {24, 12, 9, 13, 5},
    {37, 19, 43, 17, 11},
    {71, 32, 8, 4, 7}};

    cout<< arr[1][3] << endl<< endl;
    int *x = new int;
    *x = arr [2][1];
    cout<< x<< endl;
    cout<< *x<< endl << endl;

    *x = arr [0][3];
    cout<< x<< endl;
    cout<< *x<< endl;
    delete x;
    delete [] arr;
    return 0;
}
</code>```

Alternatively you can project the 2D array onto a 1D array as:

```<code>#include <iostream>
#include <cstdlib>
using namespace std;

int main () {
    int *arr = new int[20] {3, 6, 9, 23, 16,
    24, 12, 9, 13, 5,
    37, 19, 43, 17, 11,
    71, 32, 8, 4, 7};

    cout<< arr[5*1+3] << endl<< endl;
    int *x = new int;
    *x = arr [5*2+1];
    cout<< x<< endl;
    cout<< *x<< endl << endl;

    *x = arr [5*0+3];
    cout<< x<< endl;
    cout<< *x<< endl;
    delete x;
    delete [] arr;
    return 0;
}
</code>```

To get 2D indexing with dynamic data use something like boost::multi_array

```<code>#include <iostream>
#include <boost/multi_array.hpp>
using namespace std;

int main () {
    boost::multi_array< int, 2 >arr(boost::extents[4][5]);
    int tmp[] { 3, 6, 9, 23, 16,
      24, 12, 9, 13, 5,
      37, 19, 43, 17, 11,
      71, 32, 8, 4, 7 };
    arr = boost::multi_array_ref< int, 2 >( &tmp[0], boost::extents[4][5] );

    cout<< arr [1][3]<< endl << endl;
    int *x = new int;
    *x = arr [2][1];
    cout<< x<< endl;
    cout<< *x<< endl << endl;
    *x = arr [0][3];
    cout<< x<< endl;
    cout<< *x<< endl;
    delete x;
    // delete [] arr;
    return 0;
}
</code>```

Body:
Apparently I'm misunderstanding this, but I'm trying to simply set specific numbers to a dynamic memory array.

#include <iostream>
#include <cstdlib>
using namespace std;

int main () {
    int *arr = new int [4][5]
    {{3, 6, 9, 23, 16},
    {24, 12, 9, 13, 5},
    {37, 19, 43, 17, 11},
    {71, 32, 8, 4, 7}};

    cout<< arr [1][3]<< endl<< endl;
    int *x = new int;
    *x = arr [2][1];
    cout<< x<< endl;
    cout<< *x<< endl << endl;
    delete x;
    *x = arr [0][3];
    cout<< x<< endl;
    cout<< *x<< endl;
    delete x;
    delete [] arr;
    return;
}

Body:
C++ support for multidimension arrays is done through libraries (eg boost). Without classes it really only understands 1D arrays, particularly when you are using pointers, which C/C++ really sees as just a pointer to the first element of the array. To get your example to work without classes you need to define a type that holds one row and then create an array of that type, which you can assign values to as you show.

#include <iostream>
#include <cstdlib>
using namespace std;

int main () {
    typedef int row_t[5];
    row_t *arr = new row_t[4] {{3, 6, 9, 23, 16},
    {24, 12, 9, 13, 5},
    {37, 19, 43, 17, 11},
    {71, 32, 8, 4, 7}};

    cout<< arr[1][3] << endl<< endl;
    int *x = new int;
    *x = arr [2][1];
    cout<< x<< endl;
    cout<< *x<< endl << endl;

    *x = arr [0][3];
    cout<< x<< endl;
    cout<< *x<< endl;
    delete x;
    delete [] arr;
    return 0;
}

Alternatively you can project the 2D array onto a 1D array as:

#include <iostream>
#include <cstdlib>
using namespace std;

int main () {
    int *arr = new int[20] {3, 6, 9, 23, 16,
    24, 12, 9, 13, 5,
    37, 19, 43, 17, 11,
    71, 32, 8, 4, 7};

    cout<< arr[5*1+3] << endl<< endl;
    int *x = new int;
    *x = arr [5*2+1];
    cout<< x<< endl;
    cout<< *x<< endl << endl;

    *x = arr [5*0+3];
    cout<< x<< endl;
    cout<< *x<< endl;
    delete x;
    delete [] arr;
    return 0;
}

To get 2D indexing with dynamic data use something like boost::multi_array

#include <iostream>
#include <boost/multi_array.hpp>
using namespace std;

int main () {
    boost::multi_array< int, 2 >arr(boost::extents[4][5]);
    int tmp[] { 3, 6, 9, 23, 16,
      24, 12, 9, 13, 5,
      37, 19, 43, 17, 11,
      71, 32, 8, 4, 7 };
    arr = boost::multi_array_ref< int, 2 >( &tmp[0], boost::extents[4][5] );

    cout<< arr [1][3]<< endl << endl;
    int *x = new int;
    *x = arr [2][1];
    cout<< x<< endl;
    cout<< *x<< endl << endl;
    *x = arr [0][3];
    cout<< x<< endl;
    cout<< *x<< endl;
    delete x;
    // delete [] arr;
    return 0;
}


问:
Looping through JSON with node.js
I have a JSON file which I need to iterate over, as shown below...

```<code>{
    "device_id": "8020",
    "data": [{
        "Timestamp": "04-29-11 05:22:39 pm",
        "Start_Value":  0.02,
        "Abstract": 18.60,
        "Editor": 65.20
    }, {
        "Timestamp": "04-29-11 04:22:39 pm",
        "End_Value":  22.22,
        "Text": 8.65,
        "Common": 1.10,
        "Editable": "true",
        "Insert": 6.0
    }]
}
</code>```

The keys in data will not always be the same (i've just used examples, there are 20 different keys), and as such, I cannot set up my script to statically reference them to get the values.

Otherwise I could state

```<code>var value1 = json.data.Timestamp;
var value2 = json.data.Start_Value;
var value3 = json.data.Abstract;
etc
</code>```

In the past i've used a simple foreach loop on the data node...

```<code>foreach ($json->data as $key => $val) {
    switch($key) {
        case 'Timestamp':
            //do this;
        case: 'Start_Value':
            //do this
    }
}
</code>```

But don't want to block the script. Any ideas?

答:
My most preferred way is,</p>

```<code>var objectKeysArray = Object.keys(yourJsonObj)
objectKeysArray.forEach(function(objKey) {
    var objValue = yourJsonObj[objKey]
})
</code>```

Title: Looping through JSON with node.js

Body:
I have a JSON file which I need to iterate over, as shown below...

{
    "device_id": "8020",
    "data": [{
        "Timestamp": "04-29-11 05:22:39 pm",
        "Start_Value":  0.02,
        "Abstract": 18.60,
        "Editor": 65.20
    }, {
        "Timestamp": "04-29-11 04:22:39 pm",
        "End_Value":  22.22,
        "Text": 8.65,
        "Common": 1.10,
        "Editable": "true",
        "Insert": 6.0
    }]
}

The keys in data will not always be the same (i've just used examples, there are 20 different keys), and as such, I cannot set up my script to statically reference them to get the values.

Otherwise I could state

var value1 = json.data.Timestamp;
var value2 = json.data.Start_Value;
var value3 = json.data.Abstract;
etc

In the past i've used a simple foreach loop on the data node...

foreach ($json->data as $key => $val) {
    switch($key) {
        case 'Timestamp':
            //do this;
        case: 'Start_Value':
            //do this
    }
}

But don't want to block the script. Any ideas?

Body:
My most preferred way is,

var objectKeysArray = Object.keys(yourJsonObj)
objectKeysArray.forEach(function(objKey) {
    var objValue = yourJsonObj[objKey]
})