问:
href doesn't add url after adding class with .click() jquery
CSS work properly. Buttons become active, when I click on it. BUT in the end of URL the data of href's doesn't add. It also works bad if I delete e.preventDefault();

Thank you in advance.

(function() {
  'use strict';

  $("#header-navigation ul li").click(function(e) {
    e.preventDefault();
    $("#header-navigation ul li").removeClass("current-menu-item menu-item-has-children");
    $(this).addClass("current-menu-item menu-item-has-children");
  });

})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="header-navigation-wrap col-md-8">
  <div id="extended-bg">
    <nav id="header-navigation" class="header-navigation clearfix">
      <ul class="header-menu clearfix">
        <li class="current-menu-item menu-item-has-children">
          Home
        </li>
        <li>Category</li>
        <li>About</li>
        <li>Feedback</li>
      </ul>
    </nav>
  </div>
</div></code>```

答:
Finally...

JS

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

$('ul.header-menu li').click(function(){
    window.sessionStorage.activeMenuItem = this.id;
});

if (window.sessionStorage.activeMenuItem) {
    $("#"+sessionStorage.activeMenuItem).addClass('current-menu-item menu-item-has-children');
}
})();
</code>```

HTML

```<code><ul class="header-menu clearfix">
     <li id="liHome"><a href="/">Home</a></li>
     <li id="liCategory"><a href="/category">Category</a></li>
     <li id="liAbout"><a href="/about">About</a></li>
     <li id="liFeedback"><a href="/feedback">Feedback</a></li>
</ul>
</code>```

Body:
CSS work properly. Buttons become active, when I click on it. BUT in the end of URL the data of href's doesn't add. It also works bad if I delete e.preventDefault();

Thank you in advance.

(function() {
  'use strict';

  $("#header-navigation ul li").click(function(e) {
    e.preventDefault();
    $("#header-navigation ul li").removeClass("current-menu-item menu-item-has-children");
    $(this).addClass("current-menu-item menu-item-has-children");
  });

})();

          Home

Category

About

Feedback

Body:
Finally...

JS

(function () {
'use strict';

$('ul.header-menu li').click(function(){
    window.sessionStorage.activeMenuItem = this.id;
});

if (window.sessionStorage.activeMenuItem) {
    $("#"+sessionStorage.activeMenuItem).addClass('current-menu-item menu-item-has-children');
}
})();

HTML

<ul class="header-menu clearfix">
     <li id="liHome"><a href="/">Home</a></li>
     <li id="liCategory"><a href="/category">Category</a></li>
     <li id="liAbout"><a href="/about">About</a></li>
     <li id="liFeedback"><a href="/feedback">Feedback</a></li>
</ul>


来源: stackexchange

问:
Devise Ruby Gem NameError when installing
I was trying to install the Ruby Gem Devise and I stupidly overlooked a step. I included the gem in my gemfile then ran the bundle install on the prompt. Then I forgot to run the generator rails generate devise:install.

Then when I went to generate my User model it came up with the following error C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activesupport-5.1.4/lib/active_support/inflector/methods.rb:269:inconst_get': uninitialized constant User (NameError)`

I've tried uninstalling the gem and removing anything that refers to Users and reinstalling the gem but it keeps coming up with the same error.

I'm hoping someone can maybe shine a bit of light on this issue

答: I've just fixed the issue. When you run the bundle install command, it automatically configures the routes folder, so I've removed any reference to devise and it's worked now</p>

ContentLicense: CC BY-SA 3.0


问:
How to find out which port number a process is using and the process using a specific port number
I'm beginner with openhab, after launching the server /etc/init.d/openhab2 start i got that [ ok ] Starting openhab2 (via systemctl): openhab2.service, but I still have no access to the platform via http://localhost:8080/
I want to know :

which process is using port 8080

which port openhab runs on

thanks

答:
you can use lsof,

lsof | grep TCP | grep 8080 and lsof | grep openhab | grep TCP

if a process forks and the child process is the one that is using a port it may not work as expected


问:
Accessing properties across pages in AEM HTL (Sightly)
I have a carousel component, whose slide content will be the content from another page, accessed via reference component. I want to get some properties authored in the carousel to be accessible inside the referenced page. i.e. I have Page A- with a Carousel accessing PageB through reference component. I want to get proeprties from PageA in PageB. Can this be achieved?</p>

答: The solution could be adding a query parameter or setting a request parameter. But then again, this depends on the requirement. For me, this worked!!</p>


问:
Name convention on Java Swing components(prefix)
An question that was brought to my mind when programming with Swing in Java was, is it a recommendation or an "official"/most used naming convention(prefix) on Swing components.

Such as(even though other may prefer other naming conventions this is what I am currently using):

txt for JTextField

btn for JButton

lbl for JLabel

pnl for JPanel

But then my list ends..

I think such prefixes enhance the readability in my code so, but I do not have any names for components such as JComboBox, JList, JRadioButton, JCheckButton and so the list goes on.

Thanks in advance.

答:
People will tell you that using prefixes is bad, because that is Hungarian notation and nowadays, Hungarian notation is considered a big no-no in programming. Personally, as somebody who has done a certain amount of GUI work, I can tell you that, whereas Hungarian notation should definitely be avoided in non-GUI programming, when doing GUIs it's a very good practice.

Consider, for example, a simple form with a textbox which is to be used to enter the user's name. In front of this textbox should be a label prompting the user to enter his name in the textbox. Now, how are you going to name the textbox? 'Name'? What about the label?
A good practice should be prefixing the textbox with txt, and label with label, which is what Hungarian notation is all about. Thus, the textbox is now named 'txtName' and the corresponding label is named 'lblName'. This gives you the additional benefit of easily accessing your textboxes, combo boxes and other widgets when in your IDE's editor. For example, typing 'txt' and pressing CTRL+Space in Eclipse opens up a context menu listing all of your textboxes, if you follow this notation.

Now, to answer your question. The usual way to define what three letters you should use for a prefix is to remove all the vowels from the widget's name and also all repeating consonants. If there are more then three consonants left, they should be ignored. Therefore, a textbox (or TextField, or whatever this widget is called in your preferred widget toolkit) becomes 'txt', a label 'lbl', a combo box 'cmb', a table 'tbl' and so on.

ContentLicense: CC BY-SA 2.5


问:
Shared data between projects.. create one shared database?
I have three projects and all three projects have certain information which are shared.  For instance, lets say a table of vehicles (basic info: year, make, model) and a table of vehicle owners (again basic info: name, address, age).  The vehicle and owner information would need to be accessible by the three projects.  What are the pros and cons of creating a separate Database for a single access point  (2 tables total) versus creating a vehicle and owner table for each of the respective databases for the three projects (6 tables total)?  Is there a best practice for this?

Thanks!

答:
The best practice is to have all related data in one database. You cannot enforce referential integrity across databases except through complex methods such as triggers. Within a database you can easily use foreign keys to enforce referential integrity.

A best practice since 2005 has been to enforce user/schema separation as well, so you do NOT put everything into [dbo], you have a relevant schema for each set of objects. This classification of objects makes it realistic to have thousands of tables or procedures in a single database.

In a modern database such as SQL 2005 and later there is no need to separate objects across databases. You have tools such as filegroups, partitioning, user/schema separation, etc., that allow you to easily work within one database and it's more efficient.

As an example of why using a single database and segregating objects by schemas is a preferred approach, consider portability of the application. In either the case where you want to move code from development to test to qa then production, or in the case where you want to move code from client to customer, if you have database names embedded in your code this becomes difficult.

Perhaps you have a monthly sales report that is used by accounting to get aggregates. If it is in the same database, the sales report is called as [].[] and you can move from [_dev] to [_prod] and the call is the same. If you are using different databases then the call to the sales report is as [sales].[dbo].[get_monthly_report] (for example). Now, to move to a different set of databases with different names you need to be on a completely separate instance with databases set up exactly the same. In some cases, such as when you're moving code to a client site, this can be very difficult.

Having all the code in one database allows you to NOT use the database name in calls to tables, views, procedures, etc., and your code is much more portable and flexible.


问:
Angular1 sibling Controllers how can access each others data
I am trying to get FirstCtrl data in SecondCtrl, but there is no response in SecondCtrl, Please help me to solve this

I Have tried to use $broadcast and $emit on $rootscope. but there is not data coming on $on

```<code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var myApp = angular.module('myApp', []);

myApp.controller('FirstCtrl', function( $scope,  $rootScope) {
    $scope.firstName = 'Ganpat';
    //$rootScope.$emit('firstName', $scope.firstName);
    $rootScope.$broadcast('firstName:broadcast', $scope.firstName);
});

myApp.controller('SecondCtrl', function( $scope,  $rootScope){
  $rootScope.$on('firstName:broadcast', function(event,data){
    $scope.firstName = data;
    console.log(data);
  });
});
</script>
<body>

  <div ng-app="myApp">
    <div ng-controller="FirstCtrl">
      <input type="text" ng-model="firstName">
      <br>Input is : <strong>{{firstName}}</strong>
    </div>
    <hr>
    <div ng-controller="SecondCtrl">
      Input should also be here: {{firstName}}
    </div>
  </div>
</body>
</html>
</code>```

答:
Code now compiles and runs properly. You can cut and past this into fiddler and run.

```<code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
    var myApp = angular.module('myApp', []);

    myApp.factory('UserService', function () {
        var self = this;
        var firstName = '';
        self.SetFirstName = function (name) { firstName = name; }
        self.GetFirstName = function () { return firstName; }
        return self;
    });

    myApp.controller('FirstCtrl', ['$scope', 'UserService', function ($scope, UserService) {

        UserService.SetFirstName("coolMan");
    }]);

    myApp.controller('SecondCtrl', ['$scope', 'UserService', function ($scope, UserService) {
        $scope.firstNameTest = '';
        $scope.service = UserService;
        $scope.$watch('service.GetFirstName()', function (newVal) {
            console.log("New Data", newVal)
            $scope.firstNameTest = newVal;
        });
    }]);

</script>
<body>

    <div ng-app="myApp">
        <div ng-controller="FirstCtrl">
            <input type="text" ng-model="firstName">
            <br>
            Input is : <strong>{{firstName}}</strong>
        </div>
        <hr>
        <div ng-controller="SecondCtrl">
            Input should also be here: {{firstNameTest}}
        </div>
    </div>
</body>
</html>
</code>```

EDIT

Addressing OPS comment.

I know this method will work and it will give a correct result, but i
  have studied the $rootscope and event $emiter and $broadcast will do
  this trick, so if you know about that then please tell me, thank you
  for your answer.

What you want to do is a bad idea. Your method forces a tighter coupling between controllers. By working on the rootscope you are forcing all controllers to rely on a certain Item being in rootscope. This is bad because controllers are not self contained modules.

By passing around a service you can decouple the controllers. Meaning that they can be used as view controllers, directive controllers, pretty much anything that requires an isolated module.

Also using a service you can now cache the result, perform centralized business logic on it, and encapsulate how you get the data. This cannot be done easily on the rootscope.

To sum it up, I will not show you a terrible way of doing what you want done. It is not good and will let other people whom look at this post use bad practices.

Body:
I am trying to get FirstCtrl data in SecondCtrl, but there is no response in SecondCtrl, Please help me to solve this

I Have tried to use $broadcast and $emit on $rootscope. but there is not data coming on $on

<!DOCTYPE html>

      <input type="text" ng-model="firstName">

Input is : {{firstName}}

      Input should also be here: {{firstName}}

Body:
Code now compiles and runs properly. You can cut and past this into fiddler and run.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
    var myApp = angular.module('myApp', []);

    myApp.factory('UserService', function () {
        var self = this;
        var firstName = '';
        self.SetFirstName = function (name) { firstName = name; }
        self.GetFirstName = function () { return firstName; }
        return self;
    });

    myApp.controller('FirstCtrl', ['$scope', 'UserService', function ($scope, UserService) {

        UserService.SetFirstName("coolMan");
    }]);

    myApp.controller('SecondCtrl', ['$scope', 'UserService', function ($scope, UserService) {
        $scope.firstNameTest = '';
        $scope.service = UserService;
        $scope.$watch('service.GetFirstName()', function (newVal) {
            console.log("New Data", newVal)
            $scope.firstNameTest = newVal;
        });
    }]);

</script>
<body>

    <div ng-app="myApp">
        <div ng-controller="FirstCtrl">
            <input type="text" ng-model="firstName">
            <br>
            Input is : <strong>{{firstName}}</strong>
        </div>
        <hr>
        <div ng-controller="SecondCtrl">
            Input should also be here: {{firstNameTest}}
        </div>
    </div>
</body>
</html>

EDIT

Addressing OPS comment.

I know this method will work and it will give a correct result, but i
  have studied the $rootscope and event $emiter and $broadcast will do
  this trick, so if you know about that then please tell me, thank you
  for your answer.

What you want to do is a bad idea. Your method forces a tighter coupling between controllers. By working on the rootscope you are forcing all controllers to rely on a certain Item being in rootscope. This is bad because controllers are not self contained modules.

By passing around a service you can decouple the controllers. Meaning that they can be used as view controllers, directive controllers, pretty much anything that requires an isolated module.

Also using a service you can now cache the result, perform centralized business logic on it, and encapsulate how you get the data. This cannot be done easily on the rootscope.

To sum it up, I will not show you a terrible way of doing what you want done. It is not good and will let other people whom look at this post use bad practices.


问:
Calculate hour difference between given date and current date in C#
I want to check to see how many hours difference there are between a given date and the current date. I'm looking for a date that's less then 24 hours away!

I thought this would work but it's giving me a true statement when the EventDateTime is Sunday which is greater then 24 hours out!

```<code>bool lessThen24Hours = (spaceEvent.EventDateTime - DateTime.Now).Hours < 24 ? true : false;
</code>```

答:
you want the TotalHours property rather than Hours:

```<code> bool lessThen24Hours = (spaceEvent.EventDateTime - DateTime.Now).TotalHours < 24;
</code>```

Body:
I want to check to see how many hours difference there are between a given date and the current date. I'm looking for a date that's less then 24 hours away!

I thought this would work but it's giving me a true statement when the EventDateTime is Sunday which is greater then 24 hours out!

bool lessThen24Hours = (spaceEvent.EventDateTime - DateTime.Now).Hours < 24 ? true : false;

Body:
you want the TotalHours property rather than Hours:

 bool lessThen24Hours = (spaceEvent.EventDateTime - DateTime.Now).TotalHours < 24;


问:
null in kafka streams need to be removed
Just removing --property print.key=true this on my kafka-cosole-consumer command works for not displaying null on console....but the thing is it is not just for the display purpose i am using....my outputs from kafka streams need to go directly to the stream reactor,  then from there to influxdb.... my stream reactor will accept

```<code>{"timestamp":"2017-10-04T10:43:56.614451246+05:30","namespace":"/intel/psutil/load/load1","data":0.42,"unit":"Load/1M","version":0,"last_advertised_time":"2017-10-04T10:43:56.669248345+05:30"}
{"timestamp":"2017-10-04T10:43:56.61445546+05:30","namespace":"/intel/psutil/load/load5","data":0.44,"unit":"Load/5M","version":0,"last_advertised_time":"2017-10-04T10:43:56.669251145+05:30"}
</code>```

only this much.....it cannot accept

```<code>null    {"timestamp":"2017-12-05T13:52:43.560588466+05:30","namespace":"/intel/procfs/meminfo/active_anon","data":4183900160,"unit":"","tags":{"plugin_running_on":"AELAB110"},"version":4,"last_advertised_time":"2017-12-05T13:52:43.560658038+05:30"}
null    {"timestamp":"2017-12-05T13:52:43.560618652+05:30","namespace":"/intel/procfs/meminfo/mem_free","data":49385746432,"unit":"","tags":{"plugin_running_on":"AELAB110"},"version":4,"last_advertised_time":"2017-12-05T13:52:43.560660098+05:30"}
</code>```

so what can be the solution for this? plzz help me

答:
You can either filter those messages:

```<code>stream.filter(...).to(...);
</code>```

Or you put a surrogate value that replaces null:

```<code>stream.map(...).to(...);
</code>```

Body:
Just removing --property print.key=true this on my kafka-cosole-consumer command works for not displaying null on console....but the thing is it is not just for the display purpose i am using....my outputs from kafka streams need to go directly to the stream reactor,  then from there to influxdb.... my stream reactor will accept

{"timestamp":"2017-10-04T10:43:56.614451246+05:30","namespace":"/intel/psutil/load/load1","data":0.42,"unit":"Load/1M","version":0,"last_advertised_time":"2017-10-04T10:43:56.669248345+05:30"}
{"timestamp":"2017-10-04T10:43:56.61445546+05:30","namespace":"/intel/psutil/load/load5","data":0.44,"unit":"Load/5M","version":0,"last_advertised_time":"2017-10-04T10:43:56.669251145+05:30"}

only this much.....it cannot accept

null    {"timestamp":"2017-12-05T13:52:43.560588466+05:30","namespace":"/intel/procfs/meminfo/active_anon","data":4183900160,"unit":"","tags":{"plugin_running_on":"AELAB110"},"version":4,"last_advertised_time":"2017-12-05T13:52:43.560658038+05:30"}
null    {"timestamp":"2017-12-05T13:52:43.560618652+05:30","namespace":"/intel/procfs/meminfo/mem_free","data":49385746432,"unit":"","tags":{"plugin_running_on":"AELAB110"},"version":4,"last_advertised_time":"2017-12-05T13:52:43.560660098+05:30"}

so what can be the solution for this? plzz help me

Body:
You can either filter those messages:

stream.filter(...).to(...);

Or you put a surrogate value that replaces null:

stream.map(...).to(...);


问:
Excel VBA Extracting Inner Text from href Tag
the HTML CODE look like this:

Your request has been scheduled. Job # 221816. Click here To monitor Schedule
There are 0 job(s) already in the queue.

```

Desired result: Extract the text "Job # 221816..."

here is the code im trying to use but i am getting "object is no supported" error msg
Set foo = objIE.document.getElementsByClassName("Message").getElementsByTagName("a").innerText

Any help would be great
Thanks and happy holidays : )

答:
It's because you are attempting to Set a string (innerText) to an Object. Also, you need to specify which Class Name "Message" you want and which tag name "a" you want.

You have two options:

Option 1: Set the object first, then grab string from foo

```<code>Dim foo As Object, myStr As String
Set foo = objIE.document.getElementsByClassName("Message")(0).getElementsByTagName("a")(0)
myStr = foo.InnerText
</code>```

Option 2: Don't assign the object to a variable and just grab the string directly.

```<code>Dim myStr As String
myStr = objIE.document.getElementsByClassName("Message")(0).getElementsByTagName("a")(0).innerText
</code>```

Notice how I placed (0) after the ClassName and TagName? That is subject to change dependent entirely on your full HTML code. Best method would be using a For Each...Next statement to iterate through all the ClassNames or TagNames, but you can specify which Class/Tag Names you want specifically by placing (i) after. Notice the 's' after getElements...? That's because class and a tag names are not unique. The only unique element is the ID (notice no 's' in getElementByID().

Body:
the HTML CODE look like this:

Your request has been scheduled. Job # 221816. Click here To monitor Schedule
There are 0 job(s) already in the queue.

Desired result: Extract the text "Job # 221816..."

here is the code im trying to use but i am getting "object is no supported" error msg
Set foo = objIE.document.getElementsByClassName("Message").getElementsByTagName("a").innerText

Any help would be great
Thanks and happy holidays : )

Body:
It's because you are attempting to Set a string (innerText) to an Object. Also, you need to specify which Class Name "Message" you want and which tag name "a" you want.

You have two options:

Option 1: Set the object first, then grab string from foo

Dim foo As Object, myStr As String
Set foo = objIE.document.getElementsByClassName("Message")(0).getElementsByTagName("a")(0)
myStr = foo.InnerText

Option 2: Don't assign the object to a variable and just grab the string directly.

Dim myStr As String
myStr = objIE.document.getElementsByClassName("Message")(0).getElementsByTagName("a")(0).innerText

Notice how I placed (0) after the ClassName and TagName? That is subject to change dependent entirely on your full HTML code. Best method would be using a For Each...Next statement to iterate through all the ClassNames or TagNames, but you can specify which Class/Tag Names you want specifically by placing (i) after. Notice the 's' after getElements...? That's because class and a tag names are not unique. The only unique element is the ID (notice no 's' in getElementByID().


问:
How to properly delete pointers when using abstract classes
Suppose I have the following classes and objects:

```<code>#include <iostream>

class Animal
{
public:
    virtual void makeNoise() = 0;

    void eat()
    {
        std::cout << "Eating..." << "\n";
    }

    void sleep()
    {
        std::cout << "Sleeping..." << "\n";
    }
};

class Cat: public Animal
{
public:
    void makeNoise()
    {
        std::cout << "Miow..." << "\n";
    }
};

class Cow: public Animal
{
public:
    void makeNoise()
    {
        std::cout << "Mooo..." << "\n";
    }
};

int main()
{
    Animal *animal;
    Cat *cat = new Cat();
    Cow *cow = new Cow();

    animal = cat;
    animal->eat();
    animal->sleep();
    animal->makeNoise();

    animal = cow;
    animal->eat();
    animal->sleep();
    animal->makeNoise();

    return 0;
}
</code>```

Note that animal is an abstract class.

How can I properly delete the pointers animal, cat and cow?

When I try to delete animal; I get the following warning message:

warning: deleting object of abstract class type 'Animal' which has
  non-virtual destructor will cause undefined behaviour.

In the other hand, when I try to delete cat; I get the following message:

warning: deleting object of polymorphic class type 'Cat' which has
  non-virtual destructor might cause undefined behaviour.

答: It's exactly what the compiler is warning you about.  You need to define and implement your own destructors for each class, and make sure they are defined as virtual for inheritance.

Body:
Suppose I have the following classes and objects:

#include <iostream>

class Animal
{
public:
    virtual void makeNoise() = 0;

    void eat()
    {
        std::cout << "Eating..." << "\n";
    }

    void sleep()
    {
        std::cout << "Sleeping..." << "\n";
    }
};

class Cat: public Animal
{
public:
    void makeNoise()
    {
        std::cout << "Miow..." << "\n";
    }
};

class Cow: public Animal
{
public:
    void makeNoise()
    {
        std::cout << "Mooo..." << "\n";
    }
};

int main()
{
    Animal *animal;
    Cat *cat = new Cat();
    Cow *cow = new Cow();

    animal = cat;
    animal->eat();
    animal->sleep();
    animal->makeNoise();

    animal = cow;
    animal->eat();
    animal->sleep();
    animal->makeNoise();

    return 0;
}

Note that animal is an abstract class.

How can I properly delete the pointers animal, cat and cow?

When I try to delete animal; I get the following warning message:

warning: deleting object of abstract class type 'Animal' which has
  non-virtual destructor will cause undefined behaviour.

In the other hand, when I try to delete cat; I get the following message:

warning: deleting object of polymorphic class type 'Cat' which has
  non-virtual destructor might cause undefined behaviour.


答:
Try (spaceEvent.EventDateTime - DateTime.Now).TotalHours.
It gives you all the hours distance between two dates

Title: Calculate hour difference between given date and current date in C#


问:
Will TelephonyManger.getDeviceId() return device id for Tablets like Galaxy Tab...?
I want to get the device id that will be unique for each Android device. I am presently developing for a Tablet device. Want to get unique device id and store the corresponding values...

So, i want to know whether Tablet devices will return a value if i use TelephonyManager.getDeviceId()...???Or is there any other value that is unique for each device???

答:
Since Android 8 everything's changed. You should use Build.getSerial(), to get the serial number of the device and add the permission READ_PHONE_STATE.

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    serial = Build.getSerial(); // Requires permission READ_PHONE_STATE
} else {
    serial = Build.SERIAL; // Will return 'unknown' for device >= Build.VERSION_CODES.O
}
</code>```

And get the IMEI or MEID this way:

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    String imei = tm.getImei(); // Requires permission READ_PHONE_STATE
    serial = imei == null ? tm.getMeid() : imei; // Requires permission READ_PHONE_STATE
} else {
    serial = tm.getDeviceId(); // Requires permission READ_PHONE_STATE
}
</code>```

Body:
Since Android 8 everything's changed. You should use Build.getSerial(), to get the serial number of the device and add the permission READ_PHONE_STATE.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    serial = Build.getSerial(); // Requires permission READ_PHONE_STATE
} else {
    serial = Build.SERIAL; // Will return 'unknown' for device >= Build.VERSION_CODES.O
}

And get the IMEI or MEID this way:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    String imei = tm.getImei(); // Requires permission READ_PHONE_STATE
    serial = imei == null ? tm.getMeid() : imei; // Requires permission READ_PHONE_STATE
} else {
    serial = tm.getDeviceId(); // Requires permission READ_PHONE_STATE
}


问:
Shouldn't "hg outgoing" use default:pushurl instead of default?
I have in my .hg/hgrc the following configuration:

```<code>[paths]
default         = ssh://remote//path/to/pull/repo
default:pushurl = ssh://remote//path/to/push/repo
</code>```

And as expected, default is used when pull-ing and in-ing and default:pushurl is used when push-ing:

```<code>$ hg pull
pulling from ssh://remote//path/to/pull/repo

$ hg in
comparing with ssh://remote//path/to/pull/repo

$ hg push
pushing to ssh://remote//path/to/push/repo
</code>```

Though, when using the outgoing command, the default path is used, not the default:pushurl:

```<code>$ hg outgoing
comparing with ssh://remote//path/to/pull/repo
</code>```

This Mercurial BugTracker issue exists for some time now and there are arguments to both cases. If addressed, the issue would seem to have a simple fix, so my question is:

Is this behavior actually a feature or a bug?

答:
This is a bug. It looks like the last word on this was a patch sent to mercurial-devel that had some test failures:

https://www.mercurial-scm.org/pipermail/mercurial-devel/2017-November/108236.html

I suspect that if someone fixed those failures and resent the patch that it would be merged.

Body:
I have in my .hg/hgrc the following configuration:

[paths]
default         = ssh://remote//path/to/pull/repo
default:pushurl = ssh://remote//path/to/push/repo

And as expected, default is used when pull-ing and in-ing and default:pushurl is used when push-ing:

$ hg pull
pulling from ssh://remote//path/to/pull/repo

$ hg in
comparing with ssh://remote//path/to/pull/repo

$ hg push
pushing to ssh://remote//path/to/push/repo

Though, when using the outgoing command, the default path is used, not the default:pushurl:

$ hg outgoing
comparing with ssh://remote//path/to/pull/repo

This Mercurial BugTracker issue exists for some time now and there are arguments to both cases. If addressed, the issue would seem to have a simple fix, so my question is:

Is this behavior actually a feature or a bug?


问:
Having the scrollbar handle sized in relation to the content height
I'm having a bit of trouble with this logic. My setup is typical, with a content MC and a handle MC the runs along a track with specified bounds. All I want to do is have the handle height adjust based on content height but in relation to the track height?

I'm just not sure how to tackle this idea.

答:
if :

contentHeight = 200 (height of the content)

visibleAreaHeight = 100 (height of the visible area)

scrollBarHeight = 100 (height of the Scrollbar)

then the height of the scrollbar handle is :

```<code>handleHeight = (visibleAreaHeight / contentHeight) * scrollBarHeight // 50
</code>```

The height of the handle represents the visible tip of contents.

Body:
if :

contentHeight = 200 (height of the content)

visibleAreaHeight = 100 (height of the visible area)

scrollBarHeight = 100 (height of the Scrollbar)

then the height of the scrollbar handle is :

handleHeight = (visibleAreaHeight / contentHeight) * scrollBarHeight // 50

The height of the handle represents the visible tip of contents.


问:
two-way binding - nested object - angular - Cannot read property of undefined
I want to use [(ngModel)] for a nested object, but is giving me an error

Cannot read property 'mxn' of undefined

these are the data structure of my models:

company.model.ts

```<code>import Currency from './currency.model';

class Company {
_id: string;
name: string;
maxLimit: number;
source: [string];
deliveryMethod: [string];
currency: Currency;
date: Date;

constructor() {
    this.name = '';
    this.date = new Date();
    this.maxLimit = 0;
    this.source = [''];
    this.deliveryMethod = [''];
    this.currency.mxn = 0;
    this.currency.php = 0;
    }
}

export default Company;
</code>```

currency.model.ts

```<code>class Currency {
mxn: number;
php: number;

constructor() {
    this.mxn = 0;
    this.php = 0;
}
}

export default Currency;
</code>```

and this is part of company.ts

```<code>public newCompany: Company = new Company();
companiesList: Company[];
editcompanies: Company[] = [];
</code>```

and HTML

in HTML page I'm able to show the mxn value by just using :

```<code><tr class="companies" *ngFor="let company of companiesList">
{{company.currency.mxn}}
</code>```

but when I want to use it with ngModel two-way binding for updating the value and sending it to the database it doesn't work.

[(ngModel)] = "newCompany.currency.mxn"
it produces the mentioned error above.
if I use
[(ngModel)] = "newCompany.currency" it doesn't give me an error but the code it's useless since i can't assign any value to mxn.

I have to say that [(ngModel)] = "newCompany.name" it works fine with this and I can update the name.

the backend works fine as I tried it with Postman. the problem is angular side.

so the question is if my data structure is correct how can I use two-way binding for the nested object?

答:
```<code>currency: Currency;
...
constructor() {
  ...
  this.currency.mxn = 0;
  this.currency.php = 0;
}
</code>```

mxn and php do not exist yet until you instantiate an instance of Currency. The instance currency is null. It doesn't contain any properties.

```<code>currency: Currency;
...
constructor() {
  ...
  this.currency = new Currency(); // invoke Currency constructor, create mxn and php with value 0, therefore you dont need this.currency.mxn = 0 and same to php
}
</code>```

Body:
I want to use [(ngModel)] for a nested object, but is giving me an error

Cannot read property 'mxn' of undefined

these are the data structure of my models:

company.model.ts

import Currency from './currency.model';

class Company {
_id: string;
name: string;
maxLimit: number;
source: [string];
deliveryMethod: [string];
currency: Currency;
date: Date;

constructor() {
    this.name = '';
    this.date = new Date();
    this.maxLimit = 0;
    this.source = [''];
    this.deliveryMethod = [''];
    this.currency.mxn = 0;
    this.currency.php = 0;
    }
}

export default Company;

currency.model.ts

class Currency {
mxn: number;
php: number;

constructor() {
    this.mxn = 0;
    this.php = 0;
}
}

export default Currency;

and this is part of company.ts

public newCompany: Company = new Company();
companiesList: Company[];
editcompanies: Company[] = [];

and HTML

in HTML page I'm able to show the mxn value by just using :

{{company.currency.mxn}}

but when I want to use it with ngModel two-way binding for updating the value and sending it to the database it doesn't work.

[(ngModel)] = "newCompany.currency.mxn"
it produces the mentioned error above.
if I use
[(ngModel)] = "newCompany.currency" it doesn't give me an error but the code it's useless since i can't assign any value to mxn.

I have to say that [(ngModel)] = "newCompany.name" it works fine with this and I can update the name.

the backend works fine as I tried it with Postman. the problem is angular side.

so the question is if my data structure is correct how can I use two-way binding for the nested object?

Body:
currency: Currency;
...
constructor() {
  ...
  this.currency.mxn = 0;
  this.currency.php = 0;
}

mxn and php do not exist yet until you instantiate an instance of Currency. The instance currency is null. It doesn't contain any properties.

currency: Currency;
...
constructor() {
  ...
  this.currency = new Currency(); // invoke Currency constructor, create mxn and php with value 0, therefore you dont need this.currency.mxn = 0 and same to php
}


问:
Apply the same git command to all projects inside one folder
I usually have like 5 or more git projects open inside Netbeans (they are also stored at the same folder). I want to be able to do a "git pull", and then "git checkout master", and sometimes "git push" for all of them at once. Without having to click on each one of them.

It can be command line based or Netbeans plugin... anything!

答:
You can write a bash script to do this, I did something similar a while back using below script</p>

```<code>#!/bin/bash

REPOSITORIES=`pwd`

IFS=$'\n'

for REPO in `ls "$REPOSITORIES/"`
do
  if [ -d "$REPOSITORIES/$REPO" ]
  then
    echo "Updating $REPOSITORIES/$REPO at `date`"
    if [ -d "$REPOSITORIES/$REPO/.git" ]
    then
      cd "$REPOSITORIES/$REPO"
      echo "Pulling"
      git pull
    else
      echo "Skipping because it doesn't look like it has a .git folder."
    fi
    echo "Done at `date`"
    echo
  fi
done
</code>```

Body:
You can write a bash script to do this, I did something similar a while back using below script

#!/bin/bash

REPOSITORIES=`pwd`

IFS=$'\n'

for REPO in `ls "$REPOSITORIES/"`
do
  if [ -d "$REPOSITORIES/$REPO" ]
  then
    echo "Updating $REPOSITORIES/$REPO at `date`"
    if [ -d "$REPOSITORIES/$REPO/.git" ]
    then
      cd "$REPOSITORIES/$REPO"
      echo "Pulling"
      git pull
    else
      echo "Skipping because it doesn't look like it has a .git folder."
    fi
    echo "Done at `date`"
    echo
  fi
done


问:
set custom path for script in MATLAB
I have a lot of folders each containing a lot of .txt files which i need to process with matlab.

i have a script finished which does it, it reads all .txt files in 1 folder and does some computing.

so if i want to process those files i move the script into the desired folder and run it, it is kinda lame to move the script every time.

is it possile to start a script in a standard directory, then make the script to ask me to browse for the desired directory to run the script in that directory? because it doesnt write any files, it just reads. after it finishes it should reset it, so i could browse to different folders every time. like save the path in a value and clear it at the end...

i use "fopen" in that script to open the .txt files, so it could be possible to assign the full path to that function, but its important to me to being able to browse the right folder every time i run the script.

答:
i use

```<code>path=uigetdir;
fileid=fopen([path filesep 'file.txt']);
</code>```

and it works just the way i wanted.

thanks @excaza and @Laure for a quick reply

Title: set custom path for script in MATLAB

Body:
i use

path=uigetdir;
fileid=fopen([path filesep 'file.txt']);

and it works just the way i wanted.

thanks @excaza and @Laure for a quick reply


问:
Remove Duplicate Data in bigquery
Sorry  a new-bie SQL question here ,I have the a DB containing data in a similar form

```<code> U1 Program_Id  A_ID    Date
 x1    A         1       1
 x1    A         2       1
 x1    A         3       1
 x1    B         1       1
 x1    B         2       1
 x1    B         3       1
 x2    B         1       1
 x2    B         2       1
</code>```

I would like to de duplicate the data considering all the four columns ,such that my final output will be like below

```<code>U1  Program_Id  A_ID    Date
x1  A        1       1
x1  A        2       1
x1  A        3       1
x2  B        1       1
x2  B        2       1
</code>```

ie X1 A exists and X1 B also exist ,for the same Date hence those are duplicates that need to be removed , keeping just X1 A rows , X1 B rows are the duplicates here.

答:
Below is for BigQuery Standard SQL

```<code>#standardSQL
SELECT U1, MIN(Program_Id) Program_Id, A_ID, DATE
FROM `project.dataset.table`
GROUP BY U1, A_ID, DATE
</code>```

You can test / play with above using dummy data from your question

```<code>#standardSQL
WITH `project.dataset.table` AS (
  SELECT 'x1' U1, 'A' Program_Id, 1 A_ID, 1 DATE UNION ALL
  SELECT 'x1', 'A', 2, 1 UNION ALL
  SELECT 'x1', 'A', 3, 1 UNION ALL
  SELECT 'x1', 'B', 1, 1 UNION ALL
  SELECT 'x1', 'B', 2, 1 UNION ALL
  SELECT 'x1', 'B', 3, 1 UNION ALL
  SELECT 'x2', 'B', 1, 1 UNION ALL
  SELECT 'x2', 'B', 2, 1
)
SELECT U1, MIN(Program_Id) Program_Id, A_ID, DATE
FROM `project.dataset.table`
GROUP BY U1, A_ID, DATE
ORDER BY DATE, U1, A_ID
</code>```

result is

```<code>U1  Program_Id  A_ID    DATE
x1  A           1       1
x1  A           2       1
x1  A           3       1
x2  B           1       1
x2  B           2       1
</code>```

Title: Remove Duplicate Data in bigquery

Body:
Sorry  a new-bie SQL question here ,I have the a DB containing data in a similar form

 U1 Program_Id  A_ID    Date
 x1    A         1       1
 x1    A         2       1
 x1    A         3       1
 x1    B         1       1
 x1    B         2       1
 x1    B         3       1
 x2    B         1       1
 x2    B         2       1

I would like to de duplicate the data considering all the four columns ,such that my final output will be like below

U1  Program_Id  A_ID    Date
x1  A        1       1
x1  A        2       1
x1  A        3       1
x2  B        1       1
x2  B        2       1

ie X1 A exists and X1 B also exist ,for the same Date hence those are duplicates that need to be removed , keeping just X1 A rows , X1 B rows are the duplicates here.

Body:
Below is for BigQuery Standard SQL

#standardSQL
SELECT U1, MIN(Program_Id) Program_Id, A_ID, DATE
FROM `project.dataset.table`
GROUP BY U1, A_ID, DATE

You can test / play with above using dummy data from your question

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 'x1' U1, 'A' Program_Id, 1 A_ID, 1 DATE UNION ALL
  SELECT 'x1', 'A', 2, 1 UNION ALL
  SELECT 'x1', 'A', 3, 1 UNION ALL
  SELECT 'x1', 'B', 1, 1 UNION ALL
  SELECT 'x1', 'B', 2, 1 UNION ALL
  SELECT 'x1', 'B', 3, 1 UNION ALL
  SELECT 'x2', 'B', 1, 1 UNION ALL
  SELECT 'x2', 'B', 2, 1
)
SELECT U1, MIN(Program_Id) Program_Id, A_ID, DATE
FROM `project.dataset.table`
GROUP BY U1, A_ID, DATE
ORDER BY DATE, U1, A_ID

result is

U1  Program_Id  A_ID    DATE
x1  A           1       1
x1  A           2       1
x1  A           3       1
x2  B           1       1
x2  B           2       1


问:
Open-source Java-based framework that has many of the common features built in out-of-the-box?
I am looking for something like Drupal in Java -- not Drupal as a CMS but rather as an application programming framework.

For example I would like to get out the the box:

A Login screen

The ability to define new roles

The ability to tie permissions (capabilities) to roles

The ability to assign roles to specific users (and revoke roles)

The ability to self-service passwords (reset ones own password)

An ability to generate a CRUD app

A menu system (that allows you to define menus)

My understanding is that Ruby-on-Rails provides this type of stuff.

Thanks.

答:
If it is for Web development, go take a look at the Play! framework.

http://www.playframework.org/


问:
Xcode 9: "An error occurred uploading to the iTunes Store."
Right after upgrading to Xcode 9, I was trying to upload my app and got this error:

```<code>iTunes Store Operation Failed
An error occurred uploading to the iTunes Store.
</code>```

No error was specified. I couldn't find a rumor for what went wrong.

So I exported the IPA and used Application Loader (Xcode->Open Developer Tool->Application Loader).

This time I got a bunch of very strange messages:

```<code>An error occurred while starting bundles for the software update process.  Transporter will try to continue.  Unresolved constraint in bundle com.apple.transporter.asperasupport [5]: Unable to resolve 5.0: missing requirement [5.0] package; (&(package=com.apple.transporter.transport.service)(version>=1.9.6)(version<=1.9.6)) [caused by: Unable to resolve 8.0: missing requirement [8.0] package; (&(package=org.springframework.util.backoff)(version>=4.1.0)(!(version>=5.0.0)))]
An error occurred while starting bundles for the software update process.  Transporter will try to continue.  Unresolved constraint in bundle com.apple.transporter.asperasupport [6]: Unable to resolve 6.0: missing requirement [6.0] package; (&(package=com.apple.transporter.transport.service)(version>=1.9.3)(version<=1.9.3)) [caused by: Unable to resolve 9.0: missing requirement [9.0] package; (&(package=com.apple.itunes.epubtoolkit)(version>=1.0.4)(version<=1.0.4))]
An error occurred while starting bundles for the software update process.  Transporter will try to continue.  Unresolved constraint in bundle com.apple.transporter.commlink [7]: Unable to resolve 7.0: missing requirement [7.0] package; (&(package=com.apple.transporter.foundation)(version>=1.9.6)(version<=1.9.6)) [caused by: Unable to resolve 8.0: missing requirement [8.0] package; (&(package=org.springframework.util.backoff)(version>=4.1.0)(!(version>=5.0.0)))]
An error occurred while starting bundles for the software update process.  Transporter will try to continue.  Unresolved constraint in bundle com.apple.transporter.itmstransporter [8]: Unable to resolve 8.0: missing requirement [8.0] package; (&(package=org.springframework.util.backoff)(version>=4.1.0)(!(version>=5.0.0)))
An error occurred while starting bundles for the software update process.  Transporter will try to continue.  Unresolved constraint in bundle com.apple.transporter.itmstransporter [9]: Unable to resolve 9.0: missing requirement [9.0] package; (&(package=com.apple.itunes.epubtoolkit)(version>=1.0.4)(version<=1.0.4))
An error occurred while starting bundles for the software update process.  Transporter will try to continue.  Unresolved constraint in bundle com.apple.transporter.mediatoolkit [12]: Unable to resolve 12.0: missing requirement [12.0] package; (&(package=com.apple.itunes.epubtoolkit)(version>=1.0.4)(version<=1.0.4))
An error occurred while starting bundles for the software update process.  Transporter will try to continue.  Unresolved constraint in bundle com.apple.transporter.softwaresupport [13]: Unable to resolve 13.0: missing requirement [13.0] package; (&(package=com.apple.transporter.log)(version>=1.9.6)(version<=1.9.6)) [caused by: Unable to resolve 8.0: missing requirement [8.0] package; (&(package=org.springframework.util.backoff)(version>=4.1.0)(!(version>=5.0.0)))]
An error occurred while starting bundles for the software update process.  Transporter will try to continue.  Unresolved constraint in bundle com.apple.transporter.softwaresupport [14]: Unable to resolve 14.0: missing requirement [14.0] package; (&(package=com.apple.jingle.leghorn.fileformat)(version>=1.9.3)(version<=1.9.3)) [caused by: Unable to resolve 12.0: missing requirement [12.0] package; (&(package=com.apple.itunes.epubtoolkit)(version>=1.0.4)(version<=1.0.4))]
An error occurred while starting bundles for the software update process.  Transporter will try to continue.  Unresolved constraint in bundle com.apple.transporter.updater [15]: Unable to resolve 15.0: missing requirement [15.0] package; (&(package=com.apple.transporter.log)(version>=1.9.6)(version<=1.9.6)) [caused by: Unable to resolve 8.0: missing requirement [8.0] package; (&(package=org.springframework.util.backoff)(version>=4.1.0)(!(version>=5.0.0)))]
An error occurred while starting bundles for the software update process.  Transporter will try to continue.  Unresolved constraint in bundle com.apple.transporter.updater [16]: Unable to resolve 16.0: missing requirement [16.0] package; (&(package=com.apple.transporter.log)(version>=1.9.3)(version<=1.9.3)) [caused by: Unable to resolve 9.0: missing requirement [9.0] package; (&(package=com.apple.itunes.epubtoolkit)(version>=1.0.4)(version<=1.0.4))]
An error occurred while trying to start the updater service. Exception's name: java.lang.NullPointerException, Exception's message: serviceReferences parameter cannot be null
An error occurred while trying to start transporter. Exception's name: java.lang.NullPointerException, Exception's message: serviceReferences parameter cannot be null
</code>```

What can be done to solve it?

答: Some updates of MacOs and iTunes were pending in the App Store. I just updated all of them and the problem was resolved for me.</p>

Body:
Right after upgrading to Xcode 9, I was trying to upload my app and got this error:

iTunes Store Operation Failed
An error occurred uploading to the iTunes Store.

No error was specified. I couldn't find a rumor for what went wrong.

So I exported the IPA and used Application Loader (Xcode->Open Developer Tool->Application Loader).

This time I got a bunch of very strange messages:

An error occurred while starting bundles for the software update process.  Transporter will try to continue.  Unresolved constraint in bundle com.apple.transporter.asperasupport [5]: Unable to resolve 5.0: missing requirement [5.0] package; (&(package=com.apple.transporter.transport.service)(version>=1.9.6)(version<=1.9.6)) [caused by: Unable to resolve 8.0: missing requirement [8.0] package; (&(package=org.springframework.util.backoff)(version>=4.1.0)(!(version>=5.0.0)))]
An error occurred while starting bundles for the software update process.  Transporter will try to continue.  Unresolved constraint in bundle com.apple.transporter.asperasupport [6]: Unable to resolve 6.0: missing requirement [6.0] package; (&(package=com.apple.transporter.transport.service)(version>=1.9.3)(version<=1.9.3)) [caused by: Unable to resolve 9.0: missing requirement [9.0] package; (&(package=com.apple.itunes.epubtoolkit)(version>=1.0.4)(version<=1.0.4))]
An error occurred while starting bundles for the software update process.  Transporter will try to continue.  Unresolved constraint in bundle com.apple.transporter.commlink [7]: Unable to resolve 7.0: missing requirement [7.0] package; (&(package=com.apple.transporter.foundation)(version>=1.9.6)(version<=1.9.6)) [caused by: Unable to resolve 8.0: missing requirement [8.0] package; (&(package=org.springframework.util.backoff)(version>=4.1.0)(!(version>=5.0.0)))]
An error occurred while starting bundles for the software update process.  Transporter will try to continue.  Unresolved constraint in bundle com.apple.transporter.itmstransporter [8]: Unable to resolve 8.0: missing requirement [8.0] package; (&(package=org.springframework.util.backoff)(version>=4.1.0)(!(version>=5.0.0)))
An error occurred while starting bundles for the software update process.  Transporter will try to continue.  Unresolved constraint in bundle com.apple.transporter.itmstransporter [9]: Unable to resolve 9.0: missing requirement [9.0] package; (&(package=com.apple.itunes.epubtoolkit)(version>=1.0.4)(version<=1.0.4))
An error occurred while starting bundles for the software update process.  Transporter will try to continue.  Unresolved constraint in bundle com.apple.transporter.mediatoolkit [12]: Unable to resolve 12.0: missing requirement [12.0] package; (&(package=com.apple.itunes.epubtoolkit)(version>=1.0.4)(version<=1.0.4))
An error occurred while starting bundles for the software update process.  Transporter will try to continue.  Unresolved constraint in bundle com.apple.transporter.softwaresupport [13]: Unable to resolve 13.0: missing requirement [13.0] package; (&(package=com.apple.transporter.log)(version>=1.9.6)(version<=1.9.6)) [caused by: Unable to resolve 8.0: missing requirement [8.0] package; (&(package=org.springframework.util.backoff)(version>=4.1.0)(!(version>=5.0.0)))]
An error occurred while starting bundles for the software update process.  Transporter will try to continue.  Unresolved constraint in bundle com.apple.transporter.softwaresupport [14]: Unable to resolve 14.0: missing requirement [14.0] package; (&(package=com.apple.jingle.leghorn.fileformat)(version>=1.9.3)(version<=1.9.3)) [caused by: Unable to resolve 12.0: missing requirement [12.0] package; (&(package=com.apple.itunes.epubtoolkit)(version>=1.0.4)(version<=1.0.4))]
An error occurred while starting bundles for the software update process.  Transporter will try to continue.  Unresolved constraint in bundle com.apple.transporter.updater [15]: Unable to resolve 15.0: missing requirement [15.0] package; (&(package=com.apple.transporter.log)(version>=1.9.6)(version<=1.9.6)) [caused by: Unable to resolve 8.0: missing requirement [8.0] package; (&(package=org.springframework.util.backoff)(version>=4.1.0)(!(version>=5.0.0)))]
An error occurred while starting bundles for the software update process.  Transporter will try to continue.  Unresolved constraint in bundle com.apple.transporter.updater [16]: Unable to resolve 16.0: missing requirement [16.0] package; (&(package=com.apple.transporter.log)(version>=1.9.3)(version<=1.9.3)) [caused by: Unable to resolve 9.0: missing requirement [9.0] package; (&(package=com.apple.itunes.epubtoolkit)(version>=1.0.4)(version<=1.0.4))]
An error occurred while trying to start the updater service. Exception's name: java.lang.NullPointerException, Exception's message: serviceReferences parameter cannot be null
An error occurred while trying to start transporter. Exception's name: java.lang.NullPointerException, Exception's message: serviceReferences parameter cannot be null

What can be done to solve it?


问:
HorizontalBarChart Value Highlighting
I am currently using Charts cocoapod and I can't figure out how to implement the following functionality: when selecting a DataEntry from HorizontalBarChartDatSet I want to highlight it by just changing the borderColor of the bar. Is this possible with the current version of the pod and if not, can you please at least give me some information regarding where to look at in order to override this functionality?

At the moment I am able to highlight the DataEntry like this:

```<code>dataSet.highlightColor = UIColor.lightGray
dataSet.highlightAlpha = 1
</code>```

However, I want to only make a border around the selected DataEntry not change its color.

I have already overriden the library for few specific functionalities but cannot seem to be able to figure this one out.

Thank you in advance!

答:
As I know, the current version of the Chart library has no properties for highlight border around a selected bar. But you could inherit your own class from BarChartRenderer class, override function drawHighlighted(context: indices:) and use an instance of your new renderer class as custom renderer for your chart.

Custom renderer class:

```<code>class MyBarChartRenderer: BarChartRenderer {

    // New properties for the border
    var highlightBorderColor: UIColor = .red
    var highlightBorderWidth: CGFloat = 2

    open override func drawHighlighted(context: CGContext, indices: [Highlight])
    {
        guard
            let dataProvider = dataProvider,
            let barData = dataProvider.barData
            else { return }

        context.saveGState()

        var barRect = CGRect()

        for high in indices
        {
            guard
                let set = barData.getDataSetByIndex(high.dataSetIndex) as? IBarChartDataSet,
                set.isHighlightEnabled
                else { continue }

            if let e = set.entryForXValue(high.x, closestToY: high.y) as? BarChartDataEntry
            {
                let trans = dataProvider.getTransformer(forAxis: set.axisDependency)

                // Setting color and width for the border
                context.setStrokeColor(highlightBorderColor.cgColor)
                context.setLineWidth(highlightBorderWidth)

                let isStack = high.stackIndex >= 0 && e.isStacked

                let y1: Double
                let y2: Double

                if isStack
                {
                    if dataProvider.isHighlightFullBarEnabled
                    {
                        y1 = e.positiveSum
                        y2 = -e.negativeSum
                    }
                    else
                    {
                        let range = e.ranges?[high.stackIndex]

                        y1 = range?.from ?? 0.0
                        y2 = range?.to ?? 0.0
                    }
                }
                else
                {
                    y1 = e.y
                    y2 = 0.0
                }

                prepareBarHighlight(x: e.x, y1: y1, y2: y2, barWidthHalf: barData.barWidth / 2.0, trans: trans, rect: &barRect)
                // Drawing the border
                context.stroke(barRect)
            }
        }

        context.restoreGState()
    }
}
</code>```

Using of new renderer:

```<code>myBarChartView.renderer = MyBarChartRenderer(
    dataProvider: self.barChartView,
    animator: self.barChartView.chartAnimator,
    viewPortHandler: self.barChartView.viewPortHandler)
</code>```

And result:

Title: HorizontalBarChart Value Highlighting

Body:
I am currently using Charts cocoapod and I can't figure out how to implement the following functionality: when selecting a DataEntry from HorizontalBarChartDatSet I want to highlight it by just changing the borderColor of the bar. Is this possible with the current version of the pod and if not, can you please at least give me some information regarding where to look at in order to override this functionality?

At the moment I am able to highlight the DataEntry like this:

dataSet.highlightColor = UIColor.lightGray
dataSet.highlightAlpha = 1

However, I want to only make a border around the selected DataEntry not change its color.

I have already overriden the library for few specific functionalities but cannot seem to be able to figure this one out.

Thank you in advance!

Body:
As I know, the current version of the Chart library has no properties for highlight border around a selected bar. But you could inherit your own class from BarChartRenderer class, override function drawHighlighted(context: indices:) and use an instance of your new renderer class as custom renderer for your chart.

Custom renderer class:

class MyBarChartRenderer: BarChartRenderer {

    // New properties for the border
    var highlightBorderColor: UIColor = .red
    var highlightBorderWidth: CGFloat = 2

    open override func drawHighlighted(context: CGContext, indices: [Highlight])
    {
        guard
            let dataProvider = dataProvider,
            let barData = dataProvider.barData
            else { return }

        context.saveGState()

        var barRect = CGRect()

        for high in indices
        {
            guard
                let set = barData.getDataSetByIndex(high.dataSetIndex) as? IBarChartDataSet,
                set.isHighlightEnabled
                else { continue }

            if let e = set.entryForXValue(high.x, closestToY: high.y) as? BarChartDataEntry
            {
                let trans = dataProvider.getTransformer(forAxis: set.axisDependency)

                // Setting color and width for the border
                context.setStrokeColor(highlightBorderColor.cgColor)
                context.setLineWidth(highlightBorderWidth)

                let isStack = high.stackIndex >= 0 && e.isStacked

                let y1: Double
                let y2: Double

                if isStack
                {
                    if dataProvider.isHighlightFullBarEnabled
                    {
                        y1 = e.positiveSum
                        y2 = -e.negativeSum
                    }
                    else
                    {
                        let range = e.ranges?[high.stackIndex]

                        y1 = range?.from ?? 0.0
                        y2 = range?.to ?? 0.0
                    }
                }
                else
                {
                    y1 = e.y
                    y2 = 0.0
                }

                prepareBarHighlight(x: e.x, y1: y1, y2: y2, barWidthHalf: barData.barWidth / 2.0, trans: trans, rect: &barRect)
                // Drawing the border
                context.stroke(barRect)
            }
        }

        context.restoreGState()
    }
}

Using of new renderer:

myBarChartView.renderer = MyBarChartRenderer(
    dataProvider: self.barChartView,
    animator: self.barChartView.chartAnimator,
    viewPortHandler: self.barChartView.viewPortHandler)

And result:


问:
If the type of objects in a collection is known, should I specify the type of the iterating variable when using fast enumeration?
For example, say I have an NSArray that contains a bunch of NSString objects:

```<code>NSArray *games = [NSArray arrayWithObjects:@"Space Invaders", @"Dig Dug", @"Galaga", nil];
</code>```

What are the pros and cons of doing this:

```<code>for (id object in games) {
    NSLog(@"The name of the game is: %@", object);
    NSLog(@"The name is %d characters long.", [object length]);
    // Do some other stuff...
}
</code>```

versus:

```<code>for (NSString *name in games) {
    NSLog(@"The name of the game is: %@", name);
    NSLog(@"The name is %d characters long.", [name length]);
    // Do some other stuff...
}
</code>```

答:
It's not strictly necessary, and will force a cast to the specified type on every iteration, so unless you are calling methods specific to NSString inside of your loop, then I don't see why this could be beneficial.

So, in your case I would do it, because you're invoking -length (an NSString method) on every object. In order to avoid compiler warnings, you'd cast the object to the specific type - which is what NSFastEnumeration does for you when you specify a non-id type. So yeah, use your second example.

Body:
For example, say I have an NSArray that contains a bunch of NSString objects:

NSArray *games = [NSArray arrayWithObjects:@"Space Invaders", @"Dig Dug", @"Galaga", nil];

What are the pros and cons of doing this:

for (id object in games) {
    NSLog(@"The name of the game is: %@", object);
    NSLog(@"The name is %d characters long.", [object length]);
    // Do some other stuff...
}

versus:

for (NSString *name in games) {
    NSLog(@"The name of the game is: %@", name);
    NSLog(@"The name is %d characters long.", [name length]);
    // Do some other stuff...
}


问:
Making changes to an existing table?
I just had a quick question. Once you've ran a change migration like say you needed to add a column to an existing table, so you create a change migration. If I've already ran that change migration, and wanted to add a different new column in that table, can i just edit the code in the change migration to add the second new column or do i have to create a whole new change migration?</p>

答:
To implement changes to the same migration file:

1) Go one step back using ROLLBACK

```<code>rake db:rollback STEP=1
</code>```

2) Implement the changes:

```<code># add new column
</code>```

3) Run db migrate:

```<code>rake db:migrate
</code>```

Title: Making changes to an existing table?

Body:
To implement changes to the same migration file:

1) Go one step back using ROLLBACK

rake db:rollback STEP=1

2) Implement the changes:

# add new column

3) Run db migrate:

rake db:migrate


问:
case statement with multiple cases doing same operation
I need to use a case statement with the control signal being 4 bits. I have multiple cases of those 4 bits doing the same operation, how do I make the code more concise?

For ex:

```<code>  casez (fbe)  //fbe is defined as logic [3:0] fbe;
   4'b0000: begin
    // operation a
   end
   4'b???1 : begin
    // operation b
   end
</code>```

Operation a and operation b are exactly identical. How do I collapse these 2 into a single case? Something like (fbe == 4'b0000) | (fbe == 4'b???1) into a single case?

答:
You can use commas to separate all case expressions that will perform the operations. The default condition cannot be in this list (because it would be redundant).

Example:

```<code>casez(fbe)
  4'b0000, 4'b???1 : begin /* do same stuff */ end
  4'b??10 : begin /* do other stuff */ end
  default : begin ... end
endcase
</code>```

This is documented in IEEE Verilog and SystemVerilog LRMs with examples. Such as IEEE1364-1995 § 9.5 Case statement and IEEE1800-2012 § 12.5 Case statement.

Body:
I need to use a case statement with the control signal being 4 bits. I have multiple cases of those 4 bits doing the same operation, how do I make the code more concise?

For ex:

  casez (fbe)  //fbe is defined as logic [3:0] fbe;
   4'b0000: begin
    // operation a
   end
   4'b???1 : begin
    // operation b
   end

Operation a and operation b are exactly identical. How do I collapse these 2 into a single case? Something like (fbe == 4'b0000) | (fbe == 4'b???1) into a single case?

Body:
You can use commas to separate all case expressions that will perform the operations. The default condition cannot be in this list (because it would be redundant).

Example:

casez(fbe)
  4'b0000, 4'b???1 : begin /* do same stuff */ end
  4'b??10 : begin /* do other stuff */ end
  default : begin ... end
endcase

This is documented in IEEE Verilog and SystemVerilog LRMs with examples. Such as IEEE1364-1995 § 9.5 Case statement and IEEE1800-2012 § 12.5 Case statement.


问:
"rotating" columns and unique_together
I have a django model:

```<code>class ShortestRoads2(models.Model):
    start_node = models.ForeignKey('Nodes', related_name='start_node2', null=True)
    end_node = models.ForeignKey('Nodes', related_name='end_node2', null=True)
    map = models.ForeignKey('project.MapProject', null=True)

    def __str__(self):
        return str(self.start_node) + ' to ' + str(self.end_node)

    class Meta:
        unique_together =(("start_node", "end_node", "map"),)

class Nodes(models.Model):
    number = models.IntegerField(null=True, unique=True)
    geom_node = models.PointField(spatial_index=True)
</code>```

Is it possible to create another unique_together contraint, where "start_node" and "end_node"  fields are switched?

Explained:

```<code>obj = ShortestRoads2()
obj.start_node = Nodes.objects.create(number=x1)
obj.end_node = Nodes.objects.create(number=x2)
obj.save() # Object created

obj2 = ShortestRoads2()
obj2.start_node = Nodes.objects.create(number=x1)
obj2.end_node = Nodes.objects.create(number=x2)
obj2.save()  # Raising as expected: IntegrityError

obj3 = ShortestRoads2()
obj3.start_node = Nodes.objects.create(number=x2) #Notice varible change
obj3.end_node = Nodes.objects.create(number=x1)  #Notice variable change
obj3.save() # Object created
</code>```

I want a exception raised when I'm saving obj3. But how to?

答:
I did an overwrite of clean() method and asked the class for the other combinations, if it existed it would raise a IntegrityError</p>

```<code>class ShortestRoads2(models.Model):
    start_node = models.ForeignKey('Nodes', related_name='start_node2', null=True)
    end_node = models.ForeignKey('Nodes', related_name='end_node2', null=True)
    map = models.ForeignKey('project.MapProject', null=True)

    def __str__(self):
        return str(self.start_node) + ' to ' + str(self.end_node)

    def clean(self):
        if ShortestRoads2.objects.filter(start_node=self.end_node, end_node=self.start_node).exists():
            raise IntegrityError({'end_node': ['combinations allready exist', ]})

    def save(self, *args, **kwargs):
        self.clean_fields(exclude='length')
        self.clean()
        self.validate_unique()
        super(ShortestRoads2, self).save(*args, **kwargs)

    class Meta:
        unique_together =(("start_node", "end_node", "map"),)
</code>```

Title: "rotating" columns and unique_together

Body:
I have a django model:

class ShortestRoads2(models.Model):
    start_node = models.ForeignKey('Nodes', related_name='start_node2', null=True)
    end_node = models.ForeignKey('Nodes', related_name='end_node2', null=True)
    map = models.ForeignKey('project.MapProject', null=True)

    def __str__(self):
        return str(self.start_node) + ' to ' + str(self.end_node)

    class Meta:
        unique_together =(("start_node", "end_node", "map"),)

class Nodes(models.Model):
    number = models.IntegerField(null=True, unique=True)
    geom_node = models.PointField(spatial_index=True)

Is it possible to create another unique_together contraint, where "start_node" and "end_node"  fields are switched?

Explained:

obj = ShortestRoads2()
obj.start_node = Nodes.objects.create(number=x1)
obj.end_node = Nodes.objects.create(number=x2)
obj.save() # Object created

obj2 = ShortestRoads2()
obj2.start_node = Nodes.objects.create(number=x1)
obj2.end_node = Nodes.objects.create(number=x2)
obj2.save()  # Raising as expected: IntegrityError

obj3 = ShortestRoads2()
obj3.start_node = Nodes.objects.create(number=x2) #Notice varible change
obj3.end_node = Nodes.objects.create(number=x1)  #Notice variable change
obj3.save() # Object created

I want a exception raised when I'm saving obj3. But how to?

Body:
I did an overwrite of clean() method and asked the class for the other combinations, if it existed it would raise a IntegrityError

class ShortestRoads2(models.Model):
    start_node = models.ForeignKey('Nodes', related_name='start_node2', null=True)
    end_node = models.ForeignKey('Nodes', related_name='end_node2', null=True)
    map = models.ForeignKey('project.MapProject', null=True)

    def __str__(self):
        return str(self.start_node) + ' to ' + str(self.end_node)

    def clean(self):
        if ShortestRoads2.objects.filter(start_node=self.end_node, end_node=self.start_node).exists():
            raise IntegrityError({'end_node': ['combinations allready exist', ]})

    def save(self, *args, **kwargs):
        self.clean_fields(exclude='length')
        self.clean()
        self.validate_unique()
        super(ShortestRoads2, self).save(*args, **kwargs)

    class Meta:
        unique_together =(("start_node", "end_node", "map"),)


问:
Sending two AJAX requests at the same time
I am probably missing something very simple here, but what I am trying to do is update two divs on my page with AJAX requests that are called at the same time when an item is clicked.

I have looked at here
but unfortunately I am still missing something in the code.

I have the following JavaScript code:

```<code>$(document.body).on('click', '.details', function(event) {
    //  $(this) = your current element that clicked.
    // additional code
    var id = event.target.id;
    //alert(id);
    //alert($(this));
    _formurl = "home_stocktake_locations_list_group.php";
    _formdata = {
        'store_id': id
    };
    _formurl2 = "home_stocktake_list.php";
    $.ajax({
            type: "GET",
            url: _formurl,
            data: _formdata,
            success: function(xhrResponse) {
                $('#current').html(xhrResponse);
                var rowCount = $('#locations').length;
                row_count = parseInt(rowCount);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $('#alert_msg').html(errorThrown);
                $('#alert_msg').fadeIn("slow");
            }
        }),
        $.ajax({

            type: "GET",
            url: _formurl2,
            data: _formdata,
            success: function(xhrResponse) {
                $('#previous').html(xhrResponse);
                var rowCount = $('#dd_home_stocktake').length;
                row_count = parseInt(rowCount);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $('#alert_msg').html(errorThrown);
                $('#alert_msg').fadeIn("slow");
            }
        });

});
</code>```

When I look at what happens in the console, only home_stocktake_locations_list_group.php file gets called, the second AJAX call is completely ignored. What is causing this?

In the console I can only see the following:

答:
Rodrigo has it right.  Lose the , after the first $.ajax and replace with a ;

ie

```<code>}),
$.ajax({
</code>```

becomes

```<code>});
$.ajax({
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am probably missing something very simple here, but what I am trying to do is update two divs on my page with AJAX requests that are called at the same time when an item is clicked.

I have looked at here
but unfortunately I am still missing something in the code.

I have the following JavaScript code:

$(document.body).on('click', '.details', function(event) {
    //  $(this) = your current element that clicked.
    // additional code
    var id = event.target.id;
    //alert(id);
    //alert($(this));
    _formurl = "home_stocktake_locations_list_group.php";
    _formdata = {
        'store_id': id
    };
    _formurl2 = "home_stocktake_list.php";
    $.ajax({
            type: "GET",
            url: _formurl,
            data: _formdata,
            success: function(xhrResponse) {
                $('#current').html(xhrResponse);
                var rowCount = $('#locations').length;
                row_count = parseInt(rowCount);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $('#alert_msg').html(errorThrown);
                $('#alert_msg').fadeIn("slow");
            }
        }),
        $.ajax({

            type: "GET",
            url: _formurl2,
            data: _formdata,
            success: function(xhrResponse) {
                $('#previous').html(xhrResponse);
                var rowCount = $('#dd_home_stocktake').length;
                row_count = parseInt(rowCount);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $('#alert_msg').html(errorThrown);
                $('#alert_msg').fadeIn("slow");
            }
        });

});

When I look at what happens in the console, only home_stocktake_locations_list_group.php file gets called, the second AJAX call is completely ignored. What is causing this?

In the console I can only see the following:

Body:
Rodrigo has it right.  Lose the , after the first $.ajax and replace with a ;

ie

}),
$.ajax({

becomes

});
$.ajax({


问:
Fractional y-var in ggplot
How can I easily create a fractional y-value when using ggplot?

```<code>t <- as.factor(test=sample(seq(0,100,10),1000,rep=T))
d <- as.factor(sample(c(0,1),1000,rep=T)
p <- data.frame(t,d)
</code>```

My best shot was:

```<code>ggplot(p,aes(x=t,y=prop.table(table(t,d),1)[,1])) + geom_point()
</code>```

However this doesnt work and I guess there is an easier way around this...

答:
If I understood your question correctly, this should get you what you want using the formatFraction function from @jthetzel above</p>

```<code>plotData <- data.frame(prop.table(table(t,d),1))

#Plot only non-zero values
plotData <- plotData[plotData$d == 1 , ]

ggplot(data = plotData, aes(x = t, y = Freq)) + geom_point() +
scale_y_continuous(formatter = "formatFraction")
</code>```

Title: Fractional y-var in ggplot

Body:
How can I easily create a fractional y-value when using ggplot?

t <- as.factor(test=sample(seq(0,100,10),1000,rep=T))
d <- as.factor(sample(c(0,1),1000,rep=T)
p <- data.frame(t,d)

My best shot was:

ggplot(p,aes(x=t,y=prop.table(table(t,d),1)[,1])) + geom_point()

However this doesnt work and I guess there is an easier way around this...

Body:
If I understood your question correctly, this should get you what you want using the formatFraction function from @jthetzel above

plotData <- data.frame(prop.table(table(t,d),1))

#Plot only non-zero values
plotData <- plotData[plotData$d == 1 , ]

ggplot(data = plotData, aes(x = t, y = Freq)) + geom_point() +
scale_y_continuous(formatter = "formatFraction")


问:
simple fetch api example not working
I'm new in react-native,Here is my code:

```<code>import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View
} from 'react-native';

class FetchExample extends Component {
    constructor() {
        super();
        this.state = {
            date: ''
        }
    }
    render() {
        return (
            <View style={styles.container}>
                <Text>{}</Text>
            </View>
        );
    }
    componentWillMount() {
        fetch("http://date.jsontest.com/")
            .then((response) => response.json())
            .then((responseData) => {
                console.log('a');
                this.setState({date: responseData.date});
            })
            .done();
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    }
});

AppRegistry.registerComponent('ak', () => FetchExample);
</code>```

And here is the log Error:

10:53:38 PM: Warning: React.createElement: type is invalid -- expected
  a string (for built-in components) or a class/function (for composite
  components) but got: object. You likely forgot to export your
  component from the file it's defined in. Check the render method of
  AwakeInDevApp.
      in AwakeInDevApp (at registerRootComponent.js:36)
      in RootErrorBoundary (at registerRootComponent.js:35)
      in ExpoRootComponent (at renderApplication.js:35)
      in RCTView (at View.js:113)
      in View (at AppContainer.js:102)
      in RCTView (at View.js:113)
      in View (at AppContainer.js:126)
      in AppContainer (at renderApplication.js:34)
  - node_modules/fbjs/lib/warning.js:33:20 in printWarning
  - ... 24 more stack frames from framework internals

答:
You'll need to export your component. like this</p>

```<code>export default class FetchExample extends Component {
</code>```

Title: simple fetch api example not working

Body:
I'm new in react-native,Here is my code:

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View
} from 'react-native';

class FetchExample extends Component {
    constructor() {
        super();
        this.state = {
            date: ''
        }
    }
    render() {
        return (
            <View style={styles.container}>
                <Text>{}</Text>
            </View>
        );
    }
    componentWillMount() {
        fetch("http://date.jsontest.com/")
            .then((response) => response.json())
            .then((responseData) => {
                console.log('a');
                this.setState({date: responseData.date});
            })
            .done();
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    }
});

AppRegistry.registerComponent('ak', () => FetchExample);

And here is the log Error:

10:53:38 PM: Warning: React.createElement: type is invalid -- expected
  a string (for built-in components) or a class/function (for composite
  components) but got: object. You likely forgot to export your
  component from the file it's defined in. Check the render method of
  AwakeInDevApp.
      in AwakeInDevApp (at registerRootComponent.js:36)
      in RootErrorBoundary (at registerRootComponent.js:35)
      in ExpoRootComponent (at renderApplication.js:35)
      in RCTView (at View.js:113)
      in View (at AppContainer.js:102)
      in RCTView (at View.js:113)
      in View (at AppContainer.js:126)
      in AppContainer (at renderApplication.js:34)
  - node_modules/fbjs/lib/warning.js:33:20 in printWarning
  - ... 24 more stack frames from framework internals

Body:
You'll need to export your component. like this

export default class FetchExample extends Component {


问:
Sql query to cakephp query using associations
Here is my correct sql query:

```<code>SELECT * FROM `messages` WHERE ( (sender_id=3 AND user_id=40) OR (sender_id=40 AND user_id=3)) AND offer_id=1
</code>```

I want to use this in Cakephp syntax:

```<code>$this->Message->find('all',array('conditions'=>array(

                'AND'=>array(
                    'OR'=>array(
                        'Message.offer_id'=>$offer_id,
                        'Message.sender_id'=>$sender_id,
                        'Message.user_id'=>$this->Auth->user('id'),
                    ),
                    'OR'=>array(
                        'Message.offer_id'=>$offer_id,
                        'Message.user_id'=>$sender_id,
                        'Message.sender_id'=>$this->Auth->user('id')
                    )
                )

                ),
                'recursive'=>2
                ));
</code>```

Is there anyone who can help me to figure out the issue. Basically I want to get all the messages whether I sent or received for an particular offer.

答:
You should move $offer_id out of or conditions and move it to and conditions.

Why? Lets look at your first or array:
That conditions will return true if:

sender_id is 3

OR user_id is 40

OR offer_id is 1

So, that condition may return true event if offer_id != 1

That should be written this way (as precisely as possible according to original query):

```<code>$query = $this
    ->Messages
    ->find('all' , [
        'conditions' => [
            'or' => [
                [
                    'sender_id' => $sender_id,
                    'user_id' => $this->Auth->user('id')
                ], [
                    'sender_id' => $this->Auth->user('id'),
                    'user_id' => $sender_id
                ]
            ],
            'offer_id' => $offer_id,
        ]
    ]);
    dump($query);
</code>```

In dump we can see something like this:

```<code>"SELECT * FROM messages Messages WHERE (((sender_id = :c0 AND user_id = :c1) OR (sender_id = :c2 AND user_id = :c3)) AND offer_id = :c4)
</code>```

asterisk in sql query dump for more readability

Body:
Here is my correct sql query:

SELECT * FROM `messages` WHERE ( (sender_id=3 AND user_id=40) OR (sender_id=40 AND user_id=3)) AND offer_id=1

I want to use this in Cakephp syntax:

$this->Message->find('all',array('conditions'=>array(

                'AND'=>array(
                    'OR'=>array(
                        'Message.offer_id'=>$offer_id,
                        'Message.sender_id'=>$sender_id,
                        'Message.user_id'=>$this->Auth->user('id'),
                    ),
                    'OR'=>array(
                        'Message.offer_id'=>$offer_id,
                        'Message.user_id'=>$sender_id,
                        'Message.sender_id'=>$this->Auth->user('id')
                    )
                )

                ),
                'recursive'=>2
                ));

Is there anyone who can help me to figure out the issue. Basically I want to get all the messages whether I sent or received for an particular offer.

Body:
You should move $offer_id out of or conditions and move it to and conditions.

Why? Lets look at your first or array:
That conditions will return true if:

sender_id is 3

OR user_id is 40

OR offer_id is 1

So, that condition may return true event if offer_id != 1

That should be written this way (as precisely as possible according to original query):

$query = $this
    ->Messages
    ->find('all' , [
        'conditions' => [
            'or' => [
                [
                    'sender_id' => $sender_id,
                    'user_id' => $this->Auth->user('id')
                ], [
                    'sender_id' => $this->Auth->user('id'),
                    'user_id' => $sender_id
                ]
            ],
            'offer_id' => $offer_id,
        ]
    ]);
    dump($query);

In dump we can see something like this:

"SELECT * FROM messages Messages WHERE (((sender_id = :c0 AND user_id = :c1) OR (sender_id = :c2 AND user_id = :c3)) AND offer_id = :c4)

asterisk in sql query dump for more readability


问:
check List <int> A contains elements from list B, with repeated values

I'm trying to check if List<int> A contains all values available on List<int> B

But I need to be sure that not only values are correct but also their count, if A is real subset of B.

I found solution like this, but both gives wrong answer:

```<code>List <int> A = new List <int>(){1,1,2,3};
List <int> B = new List <int>(){1,2,3,5,6,7,8,9};

bool c = A.All(B.Contains);
bool d = !A.Except(B).Any();
Console.WriteLine(c); //True
Console.WriteLine(d); //True
</code>```

List A can't be subset of list B, because it contains double value 1;

How can I handle with repeated values?

More examples

```<code>A = {1,2,3};
B = {1,2,3,4,5};
A is a subset of B => True

A = {1,1,2,3,2};
B = {1,1,2,2,3,4,5};
A is a subset of B => True

A = {1,2,3};
B = {1,1,2,2,3,4,5};
A is a subset of B => True
</code>```

but:

```<code>A = {1,2,2,3};
B = {1,2,3,4,5};
A is not a subset of B => False
</code>```

答:
Based on your samples, I understood that you want to preserve duplicates....
Try as said below....

```<code> List<int> a = new List<int> { 1, 2, 2, 3 };
 List<int> b = new List<int> { 1, 2, 3, 4, 5,2};

 IEnumerable<int> both = Intersect2(a,b);

 if (a.Count() == both.Count())
 {
    int i1 = 0;
     //Subset
 }
</code>```

And the Intersect2 method looks as shown below

```<code>public static IEnumerable<T> Intersect2<T>(IEnumerable<T> source, IEnumerable<T> target)
    {
         List<T> list = target.ToList();
         foreach (T item in source)
         {
             if (list.Contains(item))
             {
                list.Remove(item);
                yield return item;
             }
          }
    }
</code>```

Body:
I'm trying to check if List<int> A contains all values available on List<int> B

But I need to be sure that not only values are correct but also their count, if A is real subset of B.

I found solution like this, but both gives wrong answer:

List <int> A = new List <int>(){1,1,2,3};
List <int> B = new List <int>(){1,2,3,5,6,7,8,9};

bool c = A.All(B.Contains);
bool d = !A.Except(B).Any();
Console.WriteLine(c); //True
Console.WriteLine(d); //True

List A can't be subset of list B, because it contains double value 1;

How can I handle with repeated values?

More examples

A = {1,2,3};
B = {1,2,3,4,5};
A is a subset of B => True

A = {1,1,2,3,2};
B = {1,1,2,2,3,4,5};
A is a subset of B => True

A = {1,2,3};
B = {1,1,2,2,3,4,5};
A is a subset of B => True

but:

A = {1,2,2,3};
B = {1,2,3,4,5};
A is not a subset of B => False

Body:
Based on your samples, I understood that you want to preserve duplicates....
Try as said below....

 List<int> a = new List<int> { 1, 2, 2, 3 };
 List<int> b = new List<int> { 1, 2, 3, 4, 5,2};

 IEnumerable<int> both = Intersect2(a,b);

 if (a.Count() == both.Count())
 {
    int i1 = 0;
     //Subset
 }

And the Intersect2 method looks as shown below

public static IEnumerable<T> Intersect2<T>(IEnumerable<T> source, IEnumerable<T> target)
    {
         List<T> list = target.ToList();
         foreach (T item in source)
         {
             if (list.Contains(item))
             {
                list.Remove(item);
                yield return item;
             }
          }
    }


问:
Defining a High Order function that acesses data records
I pretend to create a high order function that uses as one of its parameters a function which belongs to the record of a certain Data Type.

For Example:

```<code>type Debt = Float
type Power = Int

Data State = S String Debt
Data City = C String Power Debt
Data Country = Country
   { states :: [State]
   , cities :: [City] }

upDetail :: (Country -> [a])
         -> ([a] -> b -> [a])
         -> b -> Country -> Country
upDetail f g b country = country { f = new }
         where old = f country
               new = g old b
</code>```

What the function above is supposed to do is pick an element of the record of the Country (with the function type Country -> [a]) and alter it according to a certain function type [a] -> b -> [a] and a certain b

However, when i try to compile this i get an error saying :

‘f’ is not a (visible) constructor field name

Is there any way i can overcome this problem? I thought of using Maybe Country as my result but i don't know how to do this.

答:
As the comments mention, the normal solution to this is to use lenses:

```<code>upDetail :: Lens Country [a]
         -> ([a] -> b -> [a])
         -> b -> Country -> Country
upDetail f g b country = set f country new
         where old = get f country
               new = g old b
</code>```

However, lenses aren't that hard to get a handle on, especially for so simple a purpose.

The simplest way of expressing a lens is as a getter and a setter function:

```<code>data Lens s a = Lens
  { get :: s -> a
  , set :: s -> a -> s
  }

_states :: Lens Country [State]
_states = Lens states $ \c new -> c { states = new }

_cities :: Lens Country [City]
_cities = Lens cities $ \c new -> c { cities = new }
</code>```

This lets us modify the cities or states of a country pretty easily:

```<code>λ Country [] []
Country {states = [], cities = []}
λ upDetail _cities (\cs c -> c:cs) (C "Hereford" 100 3000) it
Country {states = [], cities = [C "Hereford" 100 3000.0]}
λ upDetail _states (\cs c -> c:cs) (S "Delmarva" 4) it
Country {states = [S "Delmarva" 4.0], cities = [C "Hereford" 100 3000.0]}
</code>```

Lens get slightly more complex once you start thinking about composing lenses, which you're not getting into here, but you could.

Body:
I pretend to create a high order function that uses as one of its parameters a function which belongs to the record of a certain Data Type.

For Example:

type Debt = Float
type Power = Int

Data State = S String Debt
Data City = C String Power Debt
Data Country = Country
   { states :: [State]
   , cities :: [City] }

upDetail :: (Country -> [a])
         -> ([a] -> b -> [a])
         -> b -> Country -> Country
upDetail f g b country = country { f = new }
         where old = f country
               new = g old b

What the function above is supposed to do is pick an element of the record of the Country (with the function type Country -> [a]) and alter it according to a certain function type [a] -> b -> [a] and a certain b

However, when i try to compile this i get an error saying :

‘f’ is not a (visible) constructor field name

Is there any way i can overcome this problem? I thought of using Maybe Country as my result but i don't know how to do this.

Body:
As the comments mention, the normal solution to this is to use lenses:

upDetail :: Lens Country [a]
         -> ([a] -> b -> [a])
         -> b -> Country -> Country
upDetail f g b country = set f country new
         where old = get f country
               new = g old b

However, lenses aren't that hard to get a handle on, especially for so simple a purpose.

The simplest way of expressing a lens is as a getter and a setter function:

data Lens s a = Lens
  { get :: s -> a
  , set :: s -> a -> s
  }

_states :: Lens Country [State]
_states = Lens states $ \c new -> c { states = new }

_cities :: Lens Country [City]
_cities = Lens cities $ \c new -> c { cities = new }

This lets us modify the cities or states of a country pretty easily:

λ Country [] []
Country {states = [], cities = []}
λ upDetail _cities (\cs c -> c:cs) (C "Hereford" 100 3000) it
Country {states = [], cities = [C "Hereford" 100 3000.0]}
λ upDetail _states (\cs c -> c:cs) (S "Delmarva" 4) it
Country {states = [S "Delmarva" 4.0], cities = [C "Hereford" 100 3000.0]}

Lens get slightly more complex once you start thinking about composing lenses, which you're not getting into here, but you could.


问:
Entity Framework 4.0 insert new object error
I have a project using Entity Framework 4.0 in Visual Studio 2010. I have the following code:

```<code>using (var db = new MyEntities())
{
    var dbLead = db.Leads.CreateObject();
    dbLead.Email = lead.Email;
    db.Leads.AddObject(dbLead);
    db.SaveChanges();
}
</code>```

where MyEntities is the usual EF object context. Lead is an EF-generated class, which maps to a corresponding table in the database. In addition to the Email property assigned in the code above, the Lead class has an Id property, which I am not explicitly setting here. All the expected stuff, nothing strange yet.

I'm getting an exception on the call to db.SaveChanges(), citing "duplicate primary key" as the problem. However, in the DB, I have the corresponding column marked as a primary key, and in the .edmx designer, the corresponding property is marked with EntityKey as true and StoreGeneratedPattern as Identity.

Couple questions:

Why isn't the designer smart enough to have StoreGeneratedPattern set to Identity by default when it generates the class, assuming the underlying table has the corresponding column set to a primary key? In my case, I had to go into every class in the designer, and set this value myself for every primary key property (though, interestingly, EntityKey is set to true by default, as expected).

It's still not working... Why? I've tried setting the StoreGeneratedPattern to Computed instead, but no luck (expected, otherwise I'd be wondering why setting it to Computed fixed the problem).

答: Try setting the IsIdentity to Yes for the Id column in the Database. I assume that's the problem here, since you mention that EF itself doesn't set StoreGeneratedPattern to Identity.

Body:
I have a project using Entity Framework 4.0 in Visual Studio 2010. I have the following code:

using (var db = new MyEntities())
{
    var dbLead = db.Leads.CreateObject();
    dbLead.Email = lead.Email;
    db.Leads.AddObject(dbLead);
    db.SaveChanges();
}

where MyEntities is the usual EF object context. Lead is an EF-generated class, which maps to a corresponding table in the database. In addition to the Email property assigned in the code above, the Lead class has an Id property, which I am not explicitly setting here. All the expected stuff, nothing strange yet.

I'm getting an exception on the call to db.SaveChanges(), citing "duplicate primary key" as the problem. However, in the DB, I have the corresponding column marked as a primary key, and in the .edmx designer, the corresponding property is marked with EntityKey as true and StoreGeneratedPattern as Identity.

Couple questions:

Why isn't the designer smart enough to have StoreGeneratedPattern set to Identity by default when it generates the class, assuming the underlying table has the corresponding column set to a primary key? In my case, I had to go into every class in the designer, and set this value myself for every primary key property (though, interestingly, EntityKey is set to true by default, as expected).

It's still not working... Why? I've tried setting the StoreGeneratedPattern to Computed instead, but no luck (expected, otherwise I'd be wondering why setting it to Computed fixed the problem).


问:
Is there a builtin identity function in python?
I'd like to point to a function that does nothing:

```<code>def identity(*args)
    return args
</code>```

my use case is something like this

```<code>try:
    gettext.find(...)
    ...
    _ = gettext.gettext
else:
    _ = identity
</code>```

Of course, I could use the identity defined above, but a built-in would certainly run faster (and avoid bugs introduced by my own).

Apparently, map and filter use None for the identity, but this is specific to their implementations.

```<code>>>> _=None
>>> _("hello")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
</code>```

答:
An identity function, as defined in https://en.wikipedia.org/wiki/Identity_function, takes a single argument and returns it unchanged:

```<code>def identity(x):
    return x
</code>```

What you are asking for when you say you want the signature def identity(*args) is not strictly an identity function, as you want it to take multiple arguments. That's fine, but then you hit a problem as Python functions don't return multiple results, so you have to find a way of cramming all of those arguments into one return value.

The usual way of returning "multiple values" in Python is to return a tuple of the values - technically that's one return value but it can be used in most contexts as if it were multiple values. But doing that here means you get

```<code>>>> def mv_identity(*args):
...     return args
...
>>> mv_identity(1,2,3)
(1, 2, 3)
>>> # So far, so good. But what happens now with single arguments?
>>> mv_identity(1)
(1,)
</code>```

And fixing that problem quickly gives other issues, as the various answers here have shown.

So, in summary, there's no identity function defined in Python because:

The formal definition (a single argument function) isn't that useful, and is trivial to write.

Extending the definition to multiple arguments is not well-defined in general, and you're far better off defining your own version that works the way you need it to for your particular situation.

For your precise case,

```<code>def dummy_gettext(message):
    return message
</code>```

is almost certainly what you want - a function that has the same calling convention and return as gettext.gettext, which returns its argument unchanged, and is clearly named to describe what it does and where it's intended to be used. I'd be pretty shocked if performance were a crucial consideration here.

Body:
I'd like to point to a function that does nothing:

def identity(*args)
    return args

my use case is something like this

try:
    gettext.find(...)
    ...
    _ = gettext.gettext
else:
    _ = identity

Of course, I could use the identity defined above, but a built-in would certainly run faster (and avoid bugs introduced by my own).

Apparently, map and filter use None for the identity, but this is specific to their implementations.

>>> _=None
>>> _("hello")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable

Body:
An identity function, as defined in https://en.wikipedia.org/wiki/Identity_function, takes a single argument and returns it unchanged:

def identity(x):
    return x

What you are asking for when you say you want the signature def identity(*args) is not strictly an identity function, as you want it to take multiple arguments. That's fine, but then you hit a problem as Python functions don't return multiple results, so you have to find a way of cramming all of those arguments into one return value.

The usual way of returning "multiple values" in Python is to return a tuple of the values - technically that's one return value but it can be used in most contexts as if it were multiple values. But doing that here means you get

>>> def mv_identity(*args):
...     return args
...
>>> mv_identity(1,2,3)
(1, 2, 3)
>>> # So far, so good. But what happens now with single arguments?
>>> mv_identity(1)
(1,)

And fixing that problem quickly gives other issues, as the various answers here have shown.

So, in summary, there's no identity function defined in Python because:

The formal definition (a single argument function) isn't that useful, and is trivial to write.

Extending the definition to multiple arguments is not well-defined in general, and you're far better off defining your own version that works the way you need it to for your particular situation.

For your precise case,

def dummy_gettext(message):
    return message

is almost certainly what you want - a function that has the same calling convention and return as gettext.gettext, which returns its argument unchanged, and is clearly named to describe what it does and where it's intended to be used. I'd be pretty shocked if performance were a crucial consideration here.