问:
Magento 1.9 create new Hello World module

 Hello, guys!

I really hope someone will help me with this.

I trying to make new module in magento 1.9.3.2, which show "Hello world!" from phtml file. I  created that step by step by this rules. Module is created, but when I open module (127.0.0.1/magento/helloworld) in browser, nothing appear, just empty this template.
opened module in browser - screenshot

Here is steps by what i guided:

1. Module declaration:
     Create new xml file in  app/etc/modules/M4U_HelloWorld.xml

    <?xml version="1.0"?>
                 <config>
                       <modules>
                          <M4U_HelloWorld>
                               <active>true</active>
                               <codePool>local</codePool>
                          </M4U_HelloWorld>
                       </modules>
                 </config>

Module configuration

    2.1. Create controller class in app/code/local/M4U/HelloWorld/controllers/IndexController.php

class M4U_HelloWorld_IndexController extends  Mage_Core_Controller_Front_Action
                    {
                      public function indexAction()
                      {
                         $this->loadLayout(array('default'));
                         $this->renderLayout();
                      }
                    }

2.2. Create Block class in app/code/local/M4U/HelloWorld/Block/HelloWorld.php

```<code>class M4U_HelloWorld_Block_HelloWorld extends Mage_Core_Block_Template
                  {
                       // necessary methods
                  }
</code>```

2.3. Create configuration xml in app/code/local/M4U/HelloWorld/etc/config.xml

```<code><?xml version="1.0"?>
<config>
<global>
    <modules>
            <m4u_helloworld>
                    <version>0.1.0</version>
            </m4u_helloworld>
    </modules>
<blocks>
        <helloworld>
            <rewrite>
     <helloworld>M4U_HelloWorld_Block_HelloWorld</helloworld>
    </rewrite>
        </helloworld>
 </blocks>
    </global>
   <frontend>
            <routers>
                    <helloworld>
                            <use>standard</use>
                            <args>
                                  <module>M4U_HelloWorld</module>
                                  <frontName>helloworld</frontName>
                            </args>
                    </helloworld>
            </routers>
    <layout>
        <updates>
            <helloworld>
                  <file>helloworld.xml</file>
            </helloworld>
        </updates>
        </layout>
    </frontend>
</code>```

Define frontend template

3.1. Define page layout in app/design/frontend/default/default/layout/helloworld.xml

<?xml version="1.0"?>
<layout version="0.1.0">
    <helloworld_index_index>
        <reference name="root">
            <action method="setTemplate">                  <template>page/1column.phtml</template></action>
        </reference>
        <reference name="content">
            <block type="helloworld/helloworld" name="hello" template="helloworld/helloworld.phtml"/>
        </reference>
    </helloworld_index_index>
</layout>

Create template file in   app/design/frontend/default/default/template/helloworld/helloworld.phtml

答:
For create HelloWorld module in Magento 1.9 please follow below tutorial URL.

URL: http://blog.iyngaran.info/create-custom-module-helloworld-in-magento

Body:
 Hello, guys!

I really hope someone will help me with this.

I trying to make new module in magento 1.9.3.2, which show "Hello world!" from phtml file. I  created that step by step by this rules. Module is created, but when I open module (127.0.0.1/magento/helloworld) in browser, nothing appear, just empty this template.
opened module in browser - screenshot

Here is steps by what i guided:

1. Module declaration:
     Create new xml file in  app/etc/modules/M4U_HelloWorld.xml

    <?xml version="1.0"?>
                 <config>
                       <modules>
                          <M4U_HelloWorld>
                               <active>true</active>
                               <codePool>local</codePool>
                          </M4U_HelloWorld>
                       </modules>
                 </config>

Module configuration

    2.1. Create controller class in app/code/local/M4U/HelloWorld/controllers/IndexController.php

class M4U_HelloWorld_IndexController extends  Mage_Core_Controller_Front_Action
                    {
                      public function indexAction()
                      {
                         $this->loadLayout(array('default'));
                         $this->renderLayout();
                      }
                    }

2.2. Create Block class in app/code/local/M4U/HelloWorld/Block/HelloWorld.php

class M4U_HelloWorld_Block_HelloWorld extends Mage_Core_Block_Template
                  {
                       // necessary methods
                  }

2.3. Create configuration xml in app/code/local/M4U/HelloWorld/etc/config.xml

<?xml version="1.0"?>
<config>
<global>
    <modules>
            <m4u_helloworld>
                    <version>0.1.0</version>
            </m4u_helloworld>
    </modules>
<blocks>
        <helloworld>
            <rewrite>
     <helloworld>M4U_HelloWorld_Block_HelloWorld</helloworld>
    </rewrite>
        </helloworld>
 </blocks>
    </global>
   <frontend>
            <routers>
                    <helloworld>
                            <use>standard</use>
                            <args>
                                  <module>M4U_HelloWorld</module>
                                  <frontName>helloworld</frontName>
                            </args>
                    </helloworld>
            </routers>
    <layout>
        <updates>
            <helloworld>
                  <file>helloworld.xml</file>
            </helloworld>
        </updates>
        </layout>
    </frontend>

Define frontend template

3.1. Define page layout in app/design/frontend/default/default/layout/helloworld.xml

<?xml version="1.0"?>
<layout version="0.1.0">
    <helloworld_index_index>
        <reference name="root">
            <action method="setTemplate">                  <template>page/1column.phtml</template></action>
        </reference>
        <reference name="content">
            <block type="helloworld/helloworld" name="hello" template="helloworld/helloworld.phtml"/>
        </reference>
    </helloworld_index_index>
</layout>

Create template file in   app/design/frontend/default/default/template/helloworld/helloworld.phtml


来源: stackexchange

问:
VBA - split cells with value like =31+44-756+688-7433-899 into multiple cels
I have cells with formulas like below.

```<code>=31+44-756+688-7433-899
</code>```

Need a macro or an approach, using which I can separate the numbers into diff cells.

And shuld be like:

```<code>31, 44, -756, 688, -7433, -899.
</code>```

I can't use split as split can be used for only one delimiter.

答:
Try using RegEx, it's a powerful tool.

Let's say you have =31+44-756+688-7433-899 in Range("E2"), then you can read the text from it using Formula.

Afterwards, use the RegEx to look for any set of digits up to 16 digits in a row, with .Pattern = "[0-9]{1,16}".

In the code below, I am putting the result one row below Range("E2").

Code

```<code>Sub ExtractNumbers()

Dim Col As Long
Dim Reg1 As Object
Dim RegMatches As Variant
Dim Match As Variant

Set Reg1 = CreateObject("VBScript.RegExp")
With Reg1
    .Global = True
    .IgnoreCase = True
    .Pattern = "[0-9]{1,16}" ' Match up to 16-digits
End With

Set RegMatches = Reg1.Execute(Range("E2").Formula)
If RegMatches.Count >= 1 Then ' <-- at least one match of digits
    Col = 1
    For Each Match In RegMatches
        Range("E2").Offset(1, Col).Value = Match
        Col = Col + 1
    Next Match
End If

End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have cells with formulas like below.

=31+44-756+688-7433-899

Need a macro or an approach, using which I can separate the numbers into diff cells.

And shuld be like:

31, 44, -756, 688, -7433, -899.

I can't use split as split can be used for only one delimiter.

Body:
Try using RegEx, it's a powerful tool.

Let's say you have =31+44-756+688-7433-899 in Range("E2"), then you can read the text from it using Formula.

Afterwards, use the RegEx to look for any set of digits up to 16 digits in a row, with .Pattern = "[0-9]{1,16}".

In the code below, I am putting the result one row below Range("E2").

Code

Sub ExtractNumbers()

Dim Col As Long
Dim Reg1 As Object
Dim RegMatches As Variant
Dim Match As Variant

Set Reg1 = CreateObject("VBScript.RegExp")
With Reg1
    .Global = True
    .IgnoreCase = True
    .Pattern = "[0-9]{1,16}" ' Match up to 16-digits
End With

Set RegMatches = Reg1.Execute(Range("E2").Formula)
If RegMatches.Count >= 1 Then ' <-- at least one match of digits
    Col = 1
    For Each Match In RegMatches
        Range("E2").Offset(1, Col).Value = Match
        Col = Col + 1
    Next Match
End If

End Sub


问:
WARNING: Can't verify CSRF token authenticity rails
I am sending data from view to controller with AJAXand I got this error:

WARNING: Can't verify CSRF token authenticity

I think I have to send this token with data.

Does anyone know how can I do this ?

Edit: My solution

I did this by putting the following code inside the AJAX post:

```<code>headers: {
  'X-Transaction': 'POST Example',
  'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
</code>```

答:
Use jquery.csrf (https://github.com/swordray/jquery.csrf).

Rails 5.1 or later

$ yarn add jquery.csrf
```

```//= require jquery.csrf
```</li>
<li><p>Rails 5.0 or before</p>

```source 'https://rails-assets.org' do
  gem 'rails-assets-jquery.csrf'
end
```

```//= require jquery.csrf
```</li>
<li><p>Source code</p>

```(function($) {
  $(document).ajaxSend(function(e, xhr, options) {
    var token = $('meta[name="csrf-token"]').attr('content');
    if (token) xhr.setRequestHeader('X-CSRF-Token', token);
  });
})(jQuery);
```

Body:
I am sending data from view to controller with AJAXand I got this error:

WARNING: Can't verify CSRF token authenticity

I think I have to send this token with data.

Does anyone know how can I do this ?

Edit: My solution

I did this by putting the following code inside the AJAX post:

headers: {
  'X-Transaction': 'POST Example',
  'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},

Body:
Use jquery.csrf (https://github.com/swordray/jquery.csrf).

Rails 5.1 or later

$ yarn add jquery.csrf

//= require jquery.csrf

Rails 5.0 or before

source 'https://rails-assets.org' do
  gem 'rails-assets-jquery.csrf'
end

//= require jquery.csrf

Source code

(function($) {
  $(document).ajaxSend(function(e, xhr, options) {
    var token = $('meta[name="csrf-token"]').attr('content');
    if (token) xhr.setRequestHeader('X-CSRF-Token', token);
  });
})(jQuery);


问:
How to hide angular element on click event
I have a situation somewhat like this below code. I have a delete button on view cart page when it is pressed an API is called to delete the product and I just hide the product div tag to avoid page reload initially. How to hide multiple products one by one

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.hide = function(){
  //WHAT SHOULD GO HERE
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl" >

<h5 ng-click="hide()" ng-repeat="x in [0,1,2,3,4,5,6]">{{x}}<!-- HOW TO USE ng-hide HERE --></h5>

</div>

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

答:
You can have following in your HTML:

```<code><h5 ng-hide="hide{{$index}}" ng-click="hide($index)"
    ng-repeat="x in [0,1,2,3,4,5,6]">{{x}}</h5>
</code>```

Now, your hide() function would look like this,

```<code>$scope.hide = function(index){
  $scope['hide'+index] = true
}
</code>```

That should hide numbers on click.

Here's working example!

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.hide = function(index){
    $scope['hide'+index] = true
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl" >

<h5 ng-hide="hide{{$index}}" ng-click="hide($index)" ng-repeat="x in [0,1,2,3,4,5,6]">{{x}}<!-- HOW TO USE ng-hide HERE --></h5>

</div>

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

Body:
I have a situation somewhat like this below code. I have a delete button on view cart page when it is pressed an API is called to delete the product and I just hide the product div tag to avoid page reload initially. How to hide multiple products one by one

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.hide = function(){
  //WHAT SHOULD GO HERE
  }
});

{{x}}

Body:
You can have following in your HTML:

<h5 ng-hide="hide{{$index}}" ng-click="hide($index)"
    ng-repeat="x in [0,1,2,3,4,5,6]">{{x}}</h5>

Now, your hide() function would look like this,

$scope.hide = function(index){
  $scope['hide'+index] = true
}

That should hide numbers on click.

Here's working example!

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.hide = function(index){
    $scope['hide'+index] = true
  }
});

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl" >

<h5 ng-hide="hide{{$index}}" ng-click="hide($index)" ng-repeat="x in [0,1,2,3,4,5,6]">{{x}}<!-- HOW TO USE ng-hide HERE --></h5>

</div>

</body>
</html>


问:
Ionic iOS App store upload error NSPhotoLibraryUsageDescription Key
I have developed an Ionic 2 application. When I try to upload it to the Apple store they reject it with the following message:

Missing Info.plist key - This app attempts to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSPhotoLibraryUsageDescription key with a string value explaining to the user how the app uses this data.

I added the NSPhotoLibraryUsageDescription key in config.xml

```<code><plugin name="cordova-plugin-camera" spec="https://github.com/apache/cordova-plugin-camera">
                <variable name="CAMERA_USAGE_DESCRIPTION" value="App would like to access the camera." />
                <variable name="PHOTOLIBRARY_USAGE_DESCRIPTION" value="App would like to access the library." />
</plugin>
</code>```

But still they rejected the app with same message. Do I need to add this key in all the plugin variables? I mean I have used image-picker plugin also. Do I need to add this key in this plugin also? I have added that but still they rejected with same error.

答:
Apple's review team and their validation checks whether your file is safe or not. So you need to add description on those lines in your Info.plist file.

Like I have done the following:

Body:
I have developed an Ionic 2 application. When I try to upload it to the Apple store they reject it with the following message:

Missing Info.plist key - This app attempts to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSPhotoLibraryUsageDescription key with a string value explaining to the user how the app uses this data.

I added the NSPhotoLibraryUsageDescription key in config.xml

<plugin name="cordova-plugin-camera" spec="https://github.com/apache/cordova-plugin-camera">
                <variable name="CAMERA_USAGE_DESCRIPTION" value="App would like to access the camera." />
                <variable name="PHOTOLIBRARY_USAGE_DESCRIPTION" value="App would like to access the library." />
</plugin>

But still they rejected the app with same message. Do I need to add this key in all the plugin variables? I mean I have used image-picker plugin also. Do I need to add this key in this plugin also? I have added that but still they rejected with same error.


问:
How to get values from input types using this.refs in reactjs?
Not able to get values of input type using this.refs...
how to get that values from input type</p>

```<code>   export class BusinessDetailsForm extends Component {
      submitForm(data) {
        console.log(this.refs.googleInput.value)
        }
      }
      reder() {
        return(
          <form onSubmit={this.submitForm}>
            <Field type="text"
              name="location"
              component={GoogleAutoComplete}
              id="addressSearchBoxField"
              ref="googleInput"
            />
          </form>
        )
      }
    }
</code>```

答:
```<code>getValue: function() {
    return this.refs.googleInput.value;
  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Not able to get values of input type using this.refs...
how to get that values from input type

   export class BusinessDetailsForm extends Component {
      submitForm(data) {
        console.log(this.refs.googleInput.value)
        }
      }
      reder() {
        return(
          <form onSubmit={this.submitForm}>
            <Field type="text"
              name="location"
              component={GoogleAutoComplete}
              id="addressSearchBoxField"
              ref="googleInput"
            />
          </form>
        )
      }
    }


问:
SQL date comparision in yyyy/mm/dd
Not being that great at sql, i've reached my limit.
I have a date in the yyyy/mm/dd format and i need to get all records "from a week ago"
I think i need some conversion stuff to be done cause this

```<code>d.date_begin >= DATEADD(day,-7, GETDATE())
</code>```

is not working :), i'm TERRIBLE at convert and data type..

答:
You should store date/time values using native formats.  Ok, sometimes we cannot.  But you can easily convert your values to the correct format:

```<code>where cast(replace(d.date_begin, '/', '') as date) >= DATEADD(day, -7, GETDATE())
</code>```

I should note that SQL Server is pretty good about conversions, so your initial code should not generate any errors -- unless you have unusual internationalization settings.

Or, actually, a better way to do this is to convert the current value to a string:

```<code>where d.date_begin >= format(dateadd(day, -7, getdate()), 'yyyy/MM/dd')
</code>```

This is better because it is "sargable", meaning that SQL Server can use an index on the column if available.

Title: SQL date comparision in yyyy/mm/dd

Body:
Not being that great at sql, i've reached my limit.
I have a date in the yyyy/mm/dd format and i need to get all records "from a week ago"
I think i need some conversion stuff to be done cause this

d.date_begin >= DATEADD(day,-7, GETDATE())

is not working :), i'm TERRIBLE at convert and data type..

Body:
You should store date/time values using native formats.  Ok, sometimes we cannot.  But you can easily convert your values to the correct format:

where cast(replace(d.date_begin, '/', '') as date) >= DATEADD(day, -7, GETDATE())

I should note that SQL Server is pretty good about conversions, so your initial code should not generate any errors -- unless you have unusual internationalization settings.

Or, actually, a better way to do this is to convert the current value to a string:

where d.date_begin >= format(dateadd(day, -7, getdate()), 'yyyy/MM/dd')

This is better because it is "sargable", meaning that SQL Server can use an index on the column if available.


问:
Ignore DST on Rails Timzone
I receive time-stamped data from some equipments, who are configured with a timezone (Europe/Paris, for example).

Problem is that some of them are not aware of DST (Daylight Saving Time) change, and some are, which causes us to have a offset problem when we're in DST (like right now).

Today I have the following code to parse this data:

def parse_timestamp(timestamp, format=nil)
  case timestamp
  when String then @timezone.local_to_utc(Time.strptime(timestamp, format))
  when Integer then @timezone.local_to_utc(@timezone.at(timestamp))
  else raise Etl::Parsers::TimeConversionError, "Can't parse timestamp #{timestamp.inspect}"
  end
end
```

The @timezone variable is created like this: ActiveSupport::TimeZone[timezone].

I'm looking for a way to ignore the DST when the equipment have a @dst property (let's say) that tells wether its timestamps are DST aware.

答:
ActiveSupport::TimeWithZone has a useful dst? method to check if the time is within Daylight Savings Time for the specified time zone:

```<code>Time.zone = 'Eastern Time (US & Canada)'    # => 'Eastern Time (US & Canada)'
Time.zone.parse("2012-5-30").dst?           # => true
Time.zone.parse("2012-11-30").dst?          # => false
</code>```

You can read more at http://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html#method-i-dst-3F

So you can just check if time is within DST, or extend TimeWithZone, as explained here Make Rails ignore daylight saving time when displaying a date by @zeantsoi:

```<code>class ActiveSupport::TimeWithZone
  def no_dst
    self.dst? ? self - 1.hour : self
  end
end
</code>```

and use it this way always getting the time without DST:

```<code>time.in_time_zone("Eastern Time (US & Canada)").no_dst
</code>```

Title: Ignore DST on Rails Timzone

Body:
I receive time-stamped data from some equipments, who are configured with a timezone (Europe/Paris, for example).

Problem is that some of them are not aware of DST (Daylight Saving Time) change, and some are, which causes us to have a offset problem when we're in DST (like right now).

Today I have the following code to parse this data:

def parse_timestamp(timestamp, format=nil)
  case timestamp
  when String then @timezone.local_to_utc(Time.strptime(timestamp, format))
  when Integer then @timezone.local_to_utc(@timezone.at(timestamp))
  else raise Etl::Parsers::TimeConversionError, "Can't parse timestamp #{timestamp.inspect}"
  end
end

The @timezone variable is created like this: ActiveSupport::TimeZone[timezone].

I'm looking for a way to ignore the DST when the equipment have a @dst property (let's say) that tells wether its timestamps are DST aware.

Body:
ActiveSupport::TimeWithZone has a useful dst? method to check if the time is within Daylight Savings Time for the specified time zone:

Time.zone = 'Eastern Time (US & Canada)'    # => 'Eastern Time (US & Canada)'
Time.zone.parse("2012-5-30").dst?           # => true
Time.zone.parse("2012-11-30").dst?          # => false

You can read more at http://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html#method-i-dst-3F

So you can just check if time is within DST, or extend TimeWithZone, as explained here Make Rails ignore daylight saving time when displaying a date by @zeantsoi:

class ActiveSupport::TimeWithZone
  def no_dst
    self.dst? ? self - 1.hour : self
  end
end

and use it this way always getting the time without DST:

time.in_time_zone("Eastern Time (US & Canada)").no_dst


问:
Fullpage.js navbar active on slides not sections
Hi everyone just started learning Fullpage.js here and i was wondering if i can let's say divide my page into 3 sections 1 for header 1 for section and 1 for footer. Then set 4-5 sliders in the Section part. what i want is for the navbar to highlight only the current slider in that section not all 4-5 of them at once...
like so:

Then when i go to the sections it does this:

and the last section:

how do i make it only active on the current slider and not all of them?
Thank you in advance ^^

答:
I would recommend you to make use of the fullPage.js state classes for that. Probably the easiest way.

Using the fp-viewing-x-y class added to the body should be quite easy. For example:

```<code>.fp-viewing-home-0 #menu li:nth-child(1){
    background:red;
}
.fp-viewing-home-1 #menu li:nth-child(2){
    background:red;
}
.fp-viewing-home-2 #menu li:nth-child(3){
    background:red;
}
</code>```

Reproduction online

If you prefer to use jQuery or JavaScript, you can make use of fullpage.js callbacks such as onLeave.
See another of my answers and the example online.

Body:
I would recommend you to make use of the fullPage.js state classes for that. Probably the easiest way.

Using the fp-viewing-x-y class added to the body should be quite easy. For example:

.fp-viewing-home-0 #menu li:nth-child(1){
    background:red;
}
.fp-viewing-home-1 #menu li:nth-child(2){
    background:red;
}
.fp-viewing-home-2 #menu li:nth-child(3){
    background:red;
}

Reproduction online

If you prefer to use jQuery or JavaScript, you can make use of fullpage.js callbacks such as onLeave.
See another of my answers and the example online.


问:
assign value as per ratio defined
I have one scenario here. Let me explain by small example.

I have 10 pens, I have to give it to 3 people. Those person's ratio are like 6:6:1 means if I am giving 1 pen to Person C I have to give 6-6 pens to Person A and Person B.

I have tried to solve it by using simple calculation which I have described below.

```<code>PerPersonPen = (TotalCountofPens * PerPersonRatio)/(SumofAllPersonsRatio)

Person A =(Int) (10*6)/13 = 4
Person B = (Int) (10*6)/13 = 4
Person C = (Int) (10*1)/13 = 0
</code>```

Here, Person C will get 0 pens, but it shouldn't happen. I would like that Person A & B are getting 4 pens, which are right. But Person C should get 1 pen also which remains.

This happens in a case of any person have 1 ratio count compare to others.

Can anybody help me to sort out this? Or How can I achieve it?

答:
Laurent G has given a very useful link to Math Stack Exchange in the comment section, How to round numbers fairly

This post implicitely suggests the following algorithm :

For each person, compute the ratio x_i she should get (x_i = her share/sum of shares)

Set C_min = numberOfPens and C_max large enough such that sum_i (floor(x_i*C_max)) > numberOfPens (C_max = numberOfPens + 1/(min x_i) should work)

Do a dichotomic search between C_min and C_max until you find a C such that sum_i (floor(x_i*C)) = numberOfPens

This, however, might not work when there are ties (like in your example, where two ratios are of value 6/13). But what you can do is add a very little random noise (you add or substract less than half the smallest non-zero gap that exists between your original ratios) to your ratios to break ties and get a result in general, which will be "almost fair".

EDIT : I noticed that my initial choice of C_max was wrong, so I fixed it to something that works. However I think there is room for improvement. It is also possible to find the initial C_max by increasing k in 2^k numberOfPens until the criterion (sum_i(floor(x_i*C_max)) > numberOfPens) is satisfied.

Title: assign value as per ratio defined

Body:
I have one scenario here. Let me explain by small example.

I have 10 pens, I have to give it to 3 people. Those person's ratio are like 6:6:1 means if I am giving 1 pen to Person C I have to give 6-6 pens to Person A and Person B.

I have tried to solve it by using simple calculation which I have described below.

PerPersonPen = (TotalCountofPens * PerPersonRatio)/(SumofAllPersonsRatio)

Person A =(Int) (10*6)/13 = 4
Person B = (Int) (10*6)/13 = 4
Person C = (Int) (10*1)/13 = 0

Here, Person C will get 0 pens, but it shouldn't happen. I would like that Person A & B are getting 4 pens, which are right. But Person C should get 1 pen also which remains.

This happens in a case of any person have 1 ratio count compare to others.

Can anybody help me to sort out this? Or How can I achieve it?


问:
How to fix my: TypeError: 'int' object does not support item assignment
New to python and I keep getting this error when I try running my code. This is the code I'm trying to run

```<code>table=[0]*3
column=0
n=0
with open('matrix.txt','r') as f:
    numbers=f.read()
    numbers=[int(x) for x in numbers.split()]
    for i in range(3):
        table[column]=[0]*3
        for j in range(3):
            table[i][j]=numbers[n]
            n+=1
    column+=1
print(table)
</code>```

I want to make a 3x3 table of the contents in my file. the file contents are;

```<code>2 3 4 1 2 6 9 8 9
</code>```

I keep getting the error message when I run it. Any ideas on how to fix it?

答:
how about:

```<code>import numpy as np
with open('matrix.txt','r') as f:
    numbers=f.read()
    table =np.array([int(x) for x in numbers.split()]).reshape((3,3))
print(table)
</code>```

if you really insist that your table is not a numpy array just convert it to a list:

```<code>table = table.tolist()
</code>```

Body:
New to python and I keep getting this error when I try running my code. This is the code I'm trying to run

table=[0]*3
column=0
n=0
with open('matrix.txt','r') as f:
    numbers=f.read()
    numbers=[int(x) for x in numbers.split()]
    for i in range(3):
        table[column]=[0]*3
        for j in range(3):
            table[i][j]=numbers[n]
            n+=1
    column+=1
print(table)

I want to make a 3x3 table of the contents in my file. the file contents are;

2 3 4 1 2 6 9 8 9

I keep getting the error message when I run it. Any ideas on how to fix it?

Body:
how about:

import numpy as np
with open('matrix.txt','r') as f:
    numbers=f.read()
    table =np.array([int(x) for x in numbers.split()]).reshape((3,3))
print(table)

if you really insist that your table is not a numpy array just convert it to a list:

table = table.tolist()


答:
You make it more complicated than it has to be:</p>

```<code>numbers = [2, 3, 4, 1, 2, 6, 9, 8, 9]
table = [numbers[i:i+3] for i in range(0, len(numbers), 3)]
</code>```

Title: How to fix my: TypeError: 'int' object does not support item assignment

Body:
You make it more complicated than it has to be:

numbers = [2, 3, 4, 1, 2, 6, 9, 8, 9]
table = [numbers[i:i+3] for i in range(0, len(numbers), 3)]


问:
Move a view up only when the keyboard covers an input field
I am trying to build an input screen for the iPhone. The screen has a number of input fields. Most of them on the top of the screen, but two fields are at the bottom.
When the user tries to edit the text on the bottom of the screen, the keyboard will pop up and it will cover the screen.
I found a simple solution to move the screen up when this happens, but the result is that the screen always moves up and the fields on top of the screen move out of reach when the user tries to edit those.

Is there a way to have the screen only move when the bottom fields are edited?

I have used this code I found here:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWillShow(sender: NSNotification) {
    self.view.frame.origin.y -= 150
}

func keyboardWillHide(sender: NSNotification) {
    self.view.frame.origin.y += 150
}
</code>```

答:
Swift 4 (**updated) with extension**

add the buttons in one container

connect bottom constraint of the container with IBOutlet containerBtmConstrain

inViewDidLoad

```<code>self.containerDependOnKeyboardBottomConstrain = containerBtmConstrain
self.watchForKeyboard()
</code>```

add the following extension

```<code>import UIKit

private var xoAssociationKeyForBottomConstrainInVC: UInt8 = 0

extension UIViewController {

    var containerDependOnKeyboardBottomConstrain :NSLayoutConstraint! {
        get {
            return objc_getAssociatedObject(self, &xoAssociationKeyForBottomConstrainInVC) as? NSLayoutConstraint
        }
        set(newValue) {
            objc_setAssociatedObject(self, &xoAssociationKeyForBottomConstrainInVC, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
    }

    func watchForKeyboard() {
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWasShown(notification:)), name:UIResponder.keyboardWillShowNotification, object: nil);
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(notification:)), name:UIResponder.keyboardWillHideNotification, object: nil);
    }

    @objc func keyboardWasShown(notification: NSNotification) {
        let info = notification.userInfo!
        guard let keyboardFrame: CGRect = (info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
          return
        }

        UIView.animate(withDuration: 0.3, animations: { () -> Void in
            self.containerDependOnKeyboardBottomConstrain.constant = -keyboardFrame.height
            self.view.layoutIfNeeded()
        })
    }

    @objc func keyboardWillHide(notification: NSNotification) {
        UIView.animate(withDuration: 0.3, animations: { () -> Void in
            self.containerDependOnKeyboardBottomConstrain.constant = 0
            self.view.layoutIfNeeded()
        })
    }
}
</code>```

Body:
I am trying to build an input screen for the iPhone. The screen has a number of input fields. Most of them on the top of the screen, but two fields are at the bottom.
When the user tries to edit the text on the bottom of the screen, the keyboard will pop up and it will cover the screen.
I found a simple solution to move the screen up when this happens, but the result is that the screen always moves up and the fields on top of the screen move out of reach when the user tries to edit those.

Is there a way to have the screen only move when the bottom fields are edited?

I have used this code I found here:

override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWillShow(sender: NSNotification) {
    self.view.frame.origin.y -= 150
}

func keyboardWillHide(sender: NSNotification) {
    self.view.frame.origin.y += 150
}

Body:
Swift 4 (**updated) with extension**

add the buttons in one container

connect bottom constraint of the container with IBOutlet containerBtmConstrain

inViewDidLoad

self.containerDependOnKeyboardBottomConstrain = containerBtmConstrain
self.watchForKeyboard()

add the following extension

import UIKit

private var xoAssociationKeyForBottomConstrainInVC: UInt8 = 0

extension UIViewController {

    var containerDependOnKeyboardBottomConstrain :NSLayoutConstraint! {
        get {
            return objc_getAssociatedObject(self, &xoAssociationKeyForBottomConstrainInVC) as? NSLayoutConstraint
        }
        set(newValue) {
            objc_setAssociatedObject(self, &xoAssociationKeyForBottomConstrainInVC, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
    }

    func watchForKeyboard() {
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWasShown(notification:)), name:UIResponder.keyboardWillShowNotification, object: nil);
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(notification:)), name:UIResponder.keyboardWillHideNotification, object: nil);
    }

    @objc func keyboardWasShown(notification: NSNotification) {
        let info = notification.userInfo!
        guard let keyboardFrame: CGRect = (info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
          return
        }

        UIView.animate(withDuration: 0.3, animations: { () -> Void in
            self.containerDependOnKeyboardBottomConstrain.constant = -keyboardFrame.height
            self.view.layoutIfNeeded()
        })
    }

    @objc func keyboardWillHide(notification: NSNotification) {
        UIView.animate(withDuration: 0.3, animations: { () -> Void in
            self.containerDependOnKeyboardBottomConstrain.constant = 0
            self.view.layoutIfNeeded()
        })
    }
}


问:
Iterator function for IDisposable items
Suppose I want to create an iterator function that yields IDisposable items.

```<code>IEnumerable<Disposable> GetItems()
{
    yield return new Disposable();
    yield return new Disposable();
}
</code>```

This does not seem ideal for the client code:

```<code>foreach (var item in source.GetItems())
{
    using (item)
    {
        // ...
    }
}
</code>```

Intuitively, the using comes too late. Things could get moved around. One could accidentally insert code between the foreach and the using. Not ideal.

I am looking for a better alternative!

One approach that comes to mind is creating the following API instead of an iterator function:

```<code>// Client
while (source.HasItem)
{
    using (var item = source.GetNextItem())
    {
        // ...
    }
}

// Source
private IEnumerator<Disposable> Enumerator { get; }
private bool? _hasItem;
bool HasItem
{
    get
    {
        if (this._hasItem == null) this._hasItem = this.Enumerator.MoveNext();
        return this._hasItem;
    }
}
Disposable GetNextItem()
{
    if (!this.HasItem) throw new IndexOutOfBoundsException();
    this._hasItem = null;
    return this.Enumerator.Current;
}
</code>```

But now it seems that the source has to become IDisposable! How else would it know when to dispose Enumerator? That can be an unpleasant side-effect.

I am looking for an alternative that feels solid in the client, but that keeps the source from becoming IDisposable too.

Edit - Clarification: I forgot to mention that some of the content that we need comes from an iterator. Concretely, imagine that we are returning IDbCommand instances, which are IDisposable. Before returning each command, we need to populate it with some query data, which in turn comes from a simple iterator method.

答:
If I understand correctly, the following pattern works for you

```<code>foreach (var item in source.GetItems())
{
    using (item)
    {
        // ...
    }
}
</code>```

but the potential problem is putting some code outside the using block. So why don't you just wrap that logic in a custom extensions method:

```<code>public static class EnumerableExtennisons
{
    public static IEnumerable<T> WithUsing<T>(this IEnumerable<T> source)
        where T : IDisposable
    {
        foreach (var item in source)
        {
            using (item)
                yield return item;
        }
    }
}
</code>```

This way you ensure the item is wrapped in using block *before** returning it to the caller, so there is no way the caller to insert code before/after it. The C# compiler generated code ensures the item.Dispose is called in either MoveNext or Dispose method of the IEnumerator<T> (in case the iteration ends earlier).

The usage would be to append .WithUsing() call instead of using block where needed:

```<code>foreach (var item in source.GetItems().WithUsing())
{
    // ...
}
</code>```

Title: Iterator function for IDisposable items

Body:
Suppose I want to create an iterator function that yields IDisposable items.

IEnumerable<Disposable> GetItems()
{
    yield return new Disposable();
    yield return new Disposable();
}

This does not seem ideal for the client code:

foreach (var item in source.GetItems())
{
    using (item)
    {
        // ...
    }
}

Intuitively, the using comes too late. Things could get moved around. One could accidentally insert code between the foreach and the using. Not ideal.

I am looking for a better alternative!

One approach that comes to mind is creating the following API instead of an iterator function:

// Client
while (source.HasItem)
{
    using (var item = source.GetNextItem())
    {
        // ...
    }
}

// Source
private IEnumerator<Disposable> Enumerator { get; }
private bool? _hasItem;
bool HasItem
{
    get
    {
        if (this._hasItem == null) this._hasItem = this.Enumerator.MoveNext();
        return this._hasItem;
    }
}
Disposable GetNextItem()
{
    if (!this.HasItem) throw new IndexOutOfBoundsException();
    this._hasItem = null;
    return this.Enumerator.Current;
}

But now it seems that the source has to become IDisposable! How else would it know when to dispose Enumerator? That can be an unpleasant side-effect.

I am looking for an alternative that feels solid in the client, but that keeps the source from becoming IDisposable too.

Edit - Clarification: I forgot to mention that some of the content that we need comes from an iterator. Concretely, imagine that we are returning IDbCommand instances, which are IDisposable. Before returning each command, we need to populate it with some query data, which in turn comes from a simple iterator method.

Body:
If I understand correctly, the following pattern works for you

foreach (var item in source.GetItems())
{
    using (item)
    {
        // ...
    }
}

but the potential problem is putting some code outside the using block. So why don't you just wrap that logic in a custom extensions method:

public static class EnumerableExtennisons
{
    public static IEnumerable<T> WithUsing<T>(this IEnumerable<T> source)
        where T : IDisposable
    {
        foreach (var item in source)
        {
            using (item)
                yield return item;
        }
    }
}

This way you ensure the item is wrapped in using block *before** returning it to the caller, so there is no way the caller to insert code before/after it. The C# compiler generated code ensures the item.Dispose is called in either MoveNext or Dispose method of the IEnumerator<T> (in case the iteration ends earlier).

The usage would be to append .WithUsing() call instead of using block where needed:

foreach (var item in source.GetItems().WithUsing())
{
    // ...
}


问:
how to select a specific value from the <option value> in <select> tag in a dropdown list
i have a Select tag that includes in the option tag   3 values

```<code><option value = '".$row ->ownerID.", ".$row ->companyID.",".$row ->siteNAME."'>".$row->siteNAME."</option>";
</code>```

example: 161, 3,Burj El Brajneh

i need in the SQL query to just compare the third element.

tables:

site_info:

```<code>siteID

siteNAME

ownerID

companyID
</code>```

owner_info:

```<code>ownerID

ownerNAME
</code>```

company_info:

```<code>companyID

companyNAME
</code>```

select tag:

```<code>             <?php

                 $query_site_name =$wpdb->get_results("select DISTINCT siteNAME, ownerID, companyID  from site_info");
                  foreach($query_site_name as $row)
                  {
                   echo "<option value = '".$row ->ownerID.", ".$row ->companyID.",".$row ->siteNAME."'>".$row->siteNAME."</option>";
                  }

             ?>

            </select></td>
</code>```

php check:

```<code>if(isset($_POST['site_name']))
          {
           $site_name=$_POST['site_name'];

          }
          else { $site_name=""; }
</code>```

in order to select the third element as i want i added to the SQL query  this statement $site_name->siteNAME    but it seems not working

if i write just $site_name in the query the result will be:

site_name='161, 3,Burj El Brajneh'

SQL query:

```<code> $sql = $wpdb->prepare("select i.siteID
         , i.siteNAME
         , i.equipmentTYPE
         , c.latitude
         , c.longitude
         , c.height
         , o.ownerNAME
         , o.ownerCONTACT
         , x.companyNAME
         , y.subcontractorCOMPANY
         , y.subcontractorNAME
         , y.subcontractorCONTACT
      from site_info i
      LEFT
      JOIN owner_info o
        on i.ownerID = o.ownerID
      LEFT
      JOIN company_info x
        on i.companyID = x.companyID
      LEFT
      JOIN subcontractor_info y
        on i.subcontractorID = y.subcontractorID
        LEFT JOIN site_coordinates2 c
        on i.siteID=c.siteID
        where
        i.siteNAME = %s
        AND
        o.ownerNAME = %s
        AND
        x.companyNAME = %s
       ",$site_name->siteNAME,$owner_name,$company_name);

     $query_submit =$wpdb->get_results($sql, OBJECT);
</code>```

答:
like this in php

```<code>IF ($row[$i]['abc'] == 'A'){
$a[$i]='<option value="A" selected="selected">A</option>';
$b[$i]='<option value="B" >B</option>';
}
IF ($row[$i]['abc'] == 'B'){
$a[$i]='<option value="A" >A</option>';
$b[$i]='<option value="B" selected="selected" B</option>';
}
</code>```

in html

```<code><select>
    <php? echo $a[$i]; ?>
    <php? echo $b[$i]; ?>
 </select>
</code>```

you just check if the value is same then echo it as selected="selected"

and your if statement question

```<code>if (empty($_POST["site_name"])) {
        $site_name='';
        }
           else {
           $site_name=$_POST['site_name'];
           }
</code>```

Body:
i have a Select tag that includes in the option tag   3 values

<option value = '".$row ->ownerID.", ".$row ->companyID.",".$row ->siteNAME."'>".$row->siteNAME."</option>";

example: 161, 3,Burj El Brajneh

i need in the SQL query to just compare the third element.

tables:

site_info:

siteID

siteNAME

ownerID

companyID

owner_info:

ownerID

ownerNAME

company_info:

companyID

companyNAME

select tag:

             <?php

                 $query_site_name =$wpdb->get_results("select DISTINCT siteNAME, ownerID, companyID  from site_info");
                  foreach($query_site_name as $row)
                  {
                   echo "<option value = '".$row ->ownerID.", ".$row ->companyID.",".$row ->siteNAME."'>".$row->siteNAME."</option>";
                  }

             ?>

            </select>

php check:

if(isset($_POST['site_name']))
          {
           $site_name=$_POST['site_name'];

          }
          else { $site_name=""; }

in order to select the third element as i want i added to the SQL query  this statement $site_name->siteNAME    but it seems not working

if i write just $site_name in the query the result will be:

site_name='161, 3,Burj El Brajneh'

SQL query:

 $sql = $wpdb->prepare("select i.siteID
         , i.siteNAME
         , i.equipmentTYPE
         , c.latitude
         , c.longitude
         , c.height
         , o.ownerNAME
         , o.ownerCONTACT
         , x.companyNAME
         , y.subcontractorCOMPANY
         , y.subcontractorNAME
         , y.subcontractorCONTACT
      from site_info i
      LEFT
      JOIN owner_info o
        on i.ownerID = o.ownerID
      LEFT
      JOIN company_info x
        on i.companyID = x.companyID
      LEFT
      JOIN subcontractor_info y
        on i.subcontractorID = y.subcontractorID
        LEFT JOIN site_coordinates2 c
        on i.siteID=c.siteID
        where
        i.siteNAME = %s
        AND
        o.ownerNAME = %s
        AND
        x.companyNAME = %s
       ",$site_name->siteNAME,$owner_name,$company_name);

     $query_submit =$wpdb->get_results($sql, OBJECT);

Body:
like this in php

IF ($row[$i]['abc'] == 'A'){
$a[$i]='<option value="A" selected="selected">A</option>';
$b[$i]='<option value="B" >B</option>';
}
IF ($row[$i]['abc'] == 'B'){
$a[$i]='<option value="A" >A</option>';
$b[$i]='<option value="B" selected="selected" B</option>';
}

in html

<select>
    <php? echo $a[$i]; ?>
    <php? echo $b[$i]; ?>
 </select>

you just check if the value is same then echo it as selected="selected"

and your if statement question

if (empty($_POST["site_name"])) {
        $site_name='';
        }
           else {
           $site_name=$_POST['site_name'];
           }


问:
Remove component from palette
I've been using an ActiveX control for VNC Viewer support in a legacy application for a few years now. The ActiveX control is called Smartcode ViewerX VNC Viewer. After a bit of trouble connecting to one of our systems, I decided to update to the latest version (which was available on the Smartcode website). This didn't resolve the issue and moreover had a nag dialog because I had forgotten our 1-year upgrade license had lapsed.

After uninstalling the latest version I would now like to start again but try as I might, I cannot re-install the previous version because there is already a TCSC_ViewerControl component on the ActiveX palette. How do I remove this so I can start again?

When I select control, there is no option to delete it.

UPDATE

I tried moving the component to a separate page (ie. removing it from the ActiveX page). Then I tried deleting this page, but I get the message:

```<code>A page must be empty before it can be deleted.
</code>```

答: You have installed this component into the dclusr70 package. You will need to open up that package file (open its .dpr file) and remove the units that relate to this file. Then compile the package and install it again.

Title: Remove component from palette

Body:
I've been using an ActiveX control for VNC Viewer support in a legacy application for a few years now. The ActiveX control is called Smartcode ViewerX VNC Viewer. After a bit of trouble connecting to one of our systems, I decided to update to the latest version (which was available on the Smartcode website). This didn't resolve the issue and moreover had a nag dialog because I had forgotten our 1-year upgrade license had lapsed.

After uninstalling the latest version I would now like to start again but try as I might, I cannot re-install the previous version because there is already a TCSC_ViewerControl component on the ActiveX palette. How do I remove this so I can start again?

When I select control, there is no option to delete it.

UPDATE

I tried moving the component to a separate page (ie. removing it from the ActiveX page). Then I tried deleting this page, but I get the message:

A page must be empty before it can be deleted.


问:
Android Gradle build error while running the project
I have mentioned my gradle below please let me know what is the solution for that question and have used the api level 25 in my project

apply plugin: 'com.android.application'
apply plugin: 'realm-android'

android {
    signingConfigs {
        config {
            keyAlias 'yaksha'
            keyPassword '123456'
            storeFile file('/home/abhinav/Downloads/yaksha.jks')
            storePassword '123456'
        }
    }
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.tene.yaksha"
        minSdkVersion 17
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testApplicationId "com.tene.yaksha1"
        testInstrumentationRunner "android.test.InstrumentationTestRunner"
        testHandleProfiling true
        testFunctionalTest true

    }
    testOptions {
        reportDir "$rootDir/test-reports"
        resultsDir "$rootDir/test-results"
    }

    dataBinding {
        enabled = true
    }
    dexOptions {
        //incremental = true;
        preDexLibraries = false
        javaMaxHeapSize "4g"

    }
    lintOptions {
//        lintConfig file("$project.rootDir/tools/rules-lint.xml")
        abortOnError false
        htmlOutput file("$project.buildDir/outputs/lint/lint.html")
        warningsAsErrors false
        xmlReport true
    }

    buildTypes {
        release {
            minifyEnabled true
            debuggable false
            jniDebuggable true
            signingConfig signingConfigs.config
            renderscriptDebuggable true
            shrinkResources true
            proguardFile '/home/abhinav/Android/Sdk/tools/proguard/yakshaproguard.txt'
        }
        debug {
            minifyEnabled false
            proguardFile '/home/abhinav/Android/Sdk/tools/proguard/yakshaproguard.txt'
            multiDexKeepFile file('multidex-config.txt')
        }

    }

    packagingOptions
            {
                exclude 'META-INF/DEPENDENCIES.txt'
                exclude 'META-INF/LICENSE.txt'
                exclude 'META-INF/NOTICE.txt'
                exclude 'META-INF/NOTICE'
                exclude 'META-INF/LICENSE'
                exclude 'META-INF/DEPENDENCIES'
                exclude 'META-INF/notice.txt'
                exclude 'META-INF/license.txt'
                exclude 'META-INF/dependencies.txt'
                exclude 'META-INF/LGPL2.1'
            }
    testOptions {
        unitTests.returnDefaultValues = true
        unitTests {

            all {
                jvmArgs '-XX:MaxPermSize=256m'
                if (it.name == 'testDebug') {
                    systemProperty 'debug', 'true'
                }
                if (it.name == 'connectedDebugAndroidTest') {

                }
            }
        }
    }
    configurations {
    }
}

dependencies {

    //    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.3.0'
    compile 'com.android.support:design:25.3.0'
    compile 'com.google.code.gson:gson:2.7'
    compile 'com.google.android.gms:play-services:10.2.1'
    compile project(':realmtenedbservice')
    compile project(':tenewsrestlib')
    compile project(':TeneLocationLib')
    compile project(':SecurityYsc')
    compile project(':library')
    debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
    releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
    testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:recyclerview-v7:25.3.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.birbit:android-priority-jobqueue:2.0.1'
    compile 'com.fasterxml.jackson.core:jackson-core:2.7.3'
    compile 'com.fasterxml.jackson.core:jackson-databind:2.7.3'
    compile 'io.reactivex:rxjava:1.1.0'
    compile 'org.greenrobot:eventbus:3.0.0'
    compile 'com.google.maps.android:android-maps-utils:0.4+'
    compile 'com.loopj.android:android-async-http:1.4.9'
    compile 'io.realm:android-adapters:1.4.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.sromku:simple-storage:1.2.0'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'joda-time:joda-time:2.9.7'
    compile 'id.zelory:compressor:1.0.4'
    compile 'io.reactivex:rxandroid:1.2.1'
}```
</div>
</div>
</p>

<p>I'm getting this error while running the project,can you anybody give suggesions why this is coming </p>

```Information:Gradle tasks [:app:assembleDebug]
Warning:Using incompatible plugins for the annotation processing: android-apt. This may result in an unexpected behavior.
Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: org/apache/commons/io/CopyUtils.class
Information:BUILD FAILED
Information:Total time: 18.768 secs
Information:1 error
Information:1 warning
Information:See complete output in console
```

答:
You can exclude that class, which is showing duplicate like as </p>

```<code>configurations {
all*.exclude group: 'org.apache.commons'
}
</code>```

Body:
I have mentioned my gradle below please let me know what is the solution for that question and have used the api level 25 in my project

apply plugin: 'com.android.application'
apply plugin: 'realm-android'

android {
    signingConfigs {
        config {
            keyAlias 'yaksha'
            keyPassword '123456'
            storeFile file('/home/abhinav/Downloads/yaksha.jks')
            storePassword '123456'
        }
    }
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.tene.yaksha"
        minSdkVersion 17
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testApplicationId "com.tene.yaksha1"
        testInstrumentationRunner "android.test.InstrumentationTestRunner"
        testHandleProfiling true
        testFunctionalTest true

    }
    testOptions {
        reportDir "$rootDir/test-reports"
        resultsDir "$rootDir/test-results"
    }

    dataBinding {
        enabled = true
    }
    dexOptions {
        //incremental = true;
        preDexLibraries = false
        javaMaxHeapSize "4g"

    }
    lintOptions {
//        lintConfig file("$project.rootDir/tools/rules-lint.xml")
        abortOnError false
        htmlOutput file("$project.buildDir/outputs/lint/lint.html")
        warningsAsErrors false
        xmlReport true
    }

    buildTypes {
        release {
            minifyEnabled true
            debuggable false
            jniDebuggable true
            signingConfig signingConfigs.config
            renderscriptDebuggable true
            shrinkResources true
            proguardFile '/home/abhinav/Android/Sdk/tools/proguard/yakshaproguard.txt'
        }
        debug {
            minifyEnabled false
            proguardFile '/home/abhinav/Android/Sdk/tools/proguard/yakshaproguard.txt'
            multiDexKeepFile file('multidex-config.txt')
        }

    }

    packagingOptions
            {
                exclude 'META-INF/DEPENDENCIES.txt'
                exclude 'META-INF/LICENSE.txt'
                exclude 'META-INF/NOTICE.txt'
                exclude 'META-INF/NOTICE'
                exclude 'META-INF/LICENSE'
                exclude 'META-INF/DEPENDENCIES'
                exclude 'META-INF/notice.txt'
                exclude 'META-INF/license.txt'
                exclude 'META-INF/dependencies.txt'
                exclude 'META-INF/LGPL2.1'
            }
    testOptions {
        unitTests.returnDefaultValues = true
        unitTests {

            all {
                jvmArgs '-XX:MaxPermSize=256m'
                if (it.name == 'testDebug') {
                    systemProperty 'debug', 'true'
                }
                if (it.name == 'connectedDebugAndroidTest') {

                }
            }
        }
    }
    configurations {
    }
}

dependencies {

    //    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.3.0'
    compile 'com.android.support:design:25.3.0'
    compile 'com.google.code.gson:gson:2.7'
    compile 'com.google.android.gms:play-services:10.2.1'
    compile project(':realmtenedbservice')
    compile project(':tenewsrestlib')
    compile project(':TeneLocationLib')
    compile project(':SecurityYsc')
    compile project(':library')
    debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
    releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
    testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:recyclerview-v7:25.3.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.birbit:android-priority-jobqueue:2.0.1'
    compile 'com.fasterxml.jackson.core:jackson-core:2.7.3'
    compile 'com.fasterxml.jackson.core:jackson-databind:2.7.3'
    compile 'io.reactivex:rxjava:1.1.0'
    compile 'org.greenrobot:eventbus:3.0.0'
    compile 'com.google.maps.android:android-maps-utils:0.4+'
    compile 'com.loopj.android:android-async-http:1.4.9'
    compile 'io.realm:android-adapters:1.4.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.sromku:simple-storage:1.2.0'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'joda-time:joda-time:2.9.7'
    compile 'id.zelory:compressor:1.0.4'
    compile 'io.reactivex:rxandroid:1.2.1'
}

I'm getting this error while running the project,can you anybody give suggesions why this is coming

Information:Gradle tasks [:app:assembleDebug]
Warning:Using incompatible plugins for the annotation processing: android-apt. This may result in an unexpected behavior.
Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: org/apache/commons/io/CopyUtils.class
Information:BUILD FAILED
Information:Total time: 18.768 secs
Information:1 error
Information:1 warning
Information:See complete output in console

Body:
You can exclude that class, which is showing duplicate like as

configurations {
all*.exclude group: 'org.apache.commons'
}


问:
Design Patterns for a SuperMarket system
I'm a Software Developer I who is beginning to think like a Software Developer II. I am tasked with a relatively simple Use Case for a coding challenge following as part of an interview:build a Supermarket Pricing System.

Rules and Requirements: Each item at Super Foods is identified by a
  unique four-digit code. Today, pricing schemes at Super Foods use the
  following pricing categories, but beware: prices are constantly
  changing, and the sales department is always creating new incentives
  and deals, such as buy one-get-one free.

EG: Chips and salsa (items #6732 and #4900) cost $4.99 together, but
  they cost $2.49 and $3.49 alone, respectively.

EG2: Buy two toothbrushes $1.99 each, get one free.

EG3: A bottle of wine (item #0923) costs $15.49 and is taxed an
  additional 9.25%

Having read through Design Patterns, this looks like a natural place for some form of Decorator Pattern for totaling the sales of objects. A SQLite database, with schema <ID, ObjectName, Price> will also be useful somehow, though I'm rusty on how we go about making the data access objects in all this.

I'm trying to wrap my mind around this in a full stack MVC mindset, I feel like I might be rusty on something. Is this what the Spring Framework is renowned for? Maybe an even better API for this use case can be recommended?

Thank you for anyone helping me to brainstorm the design of this system out.

答:
I allowed myself to add a little more than design patterns. I treated it as an exercise for me as well :)
Let's break it down, and go thru my thought process:

Numbers and names representation in system as types

ID - four digits number - unsigned short int - we only need numbers from 0 - 9999 which means we need just 14 bits (2^14 = 16384)
  and unsigned short int uses 16 bits. That gives us space in case we
  would like to increase the number of items to 65536 (2^16)

Name - string UTF-16, usually is good enough. However we have to remember that some products might come from far countries and use
  various characters. UTF-16 has only 16 bits per a character (again
  65536), so we have to remember in our implementation, that if we need
  more bits we need to use different encoding (like UTF-32)

Price or Discount - is float good enough? I think it's not. In many languages performing various arithmetic operations lead to not fully
  correct answers (try in JavaScript 0.2 * 0.4 - you can use your
  browser's console). When it comes to money you don't want to increase
  prices or loose money. There are special libraries and types
  implementations to be safe, when it comes to dealing with money

Data structures and classes

Item - class/structure with following fields: ID, Name, Original price (types described above)

Item Collection - array - As we use short unsigned int for IDs, we can also use it to index the array. We can even initialize
  the whole array and load all items into memory when the app starts
  up.

PriceModifier - ID - short unsigned int, Type - ENUM to represent type of discount (or tax) and to know what do to in the
  case, it is applied, Name - String UTF-16 (just to inform an user),
  Value - short signed int percentage modifier

PairPriceModifier - class - extends PriceModifier and adds pair of item IDs.

PriceModifier Collection - here we need to use a structure with quick search, as we use ID as a short usigned int, we can use an
  array of array. That list won't change frequently. When we need to add/remove a modifier, we can do that in a linear time
  O(1)*O(m), where m is Modifier length of an Item. We  won't copy
  physically Modifiers as we can use references to PriceModifier
  objects.

Shopping Cart Collection - the key functionality of each shop is a shopping cart, it has to be optimized to: add/remove items and to list
  saved items. We need to frequently add/remove elements and check for
  already added items to apply various discounts, but also we want to
  list all saved items (for instance in the cart view). We can use
  hash table with coupled array [to have O(1) when searching/adding/removing items and O(n) when listing] We update the
  final price when we add/remove an item. In the array we save a
  reference to object of a class, which represents an item from shopping
  cart to know which PriceModifier was applied

CartItem - class with fields: ItemID - short unsigned int, Quantity - unsigned int , AppliedPriceModifier Collection -
  hash table to easy access applied PriceModifiers with coupled array to list them in Cart view.

AppliedPriceModifier - class with fields: PriceModifierID, Quantity

Interesting case: In case we add some element into Shopping Cart
  Collection we need to check the PriceModifier Collection. In O(1)
  we can access the right list of PriceModifiers we have to apply.
  Then in case we spot PairPriceModifier we need to check Shopping
  Cart Collection againm, if we don't have an paired item there. The
  whole operation takes:

O(1) - to obtain array of PriceModifier of length m

O(m) - to go thru the array and apply modifiers

O(1) - in case we've found PairPriceModifier we access existing item from Shopping Cart Collection

O(k)+O(m) - to update collections of AppliedPriceModifier for both items in the Shopping Cart Collection

O(1) - to update final price (explained below)

Design patterns

For the whole APP structure I think it's good to use some framework with Inversion of Control. To keep our code modulerized and easier to unit test we
  can use a dependecy injection pattern.

For presentation layer we can use either MVC or its mutation - MVVM. It will give us dual binding ability to quickly update UI. Information
  about final price, deals and applied discounts or taxes is essential.

For updating final price, we can use Observer
  pattern. We observe the Shopping Cart Collection and when
  something goes in or goes out, we can update final price in constant
  time

To keep our code compact we can use chaining(Cascade)

You can use Decorator
  pattern to add extra functionality to PriceModifiers without
  changes in classes (for instnace when one situation prevents from
  applying an another PriceModifier)

To keep the CartItems Collection safe from changes outside of the cart, we can use Mediator design pattern. That mediator service would be responsible for applying PriceModifiers, only when an Item is being added or removed from the Cart Collection

Another questions

We can expand the topic and ask:

How to represent your data in DB

What if we would like to increase number of items and represent them as 10.000 of alpha-numeral characters

What to do, if we would like to keep our shopping app 99.9% stable and running

How can we handle many requests

What happens if a client has a discount applied in his cart, but system administrator removes that discount from the system and many
  more.

Please add some comments, as it's an interesting topic for me as well. What could I improve/change? What I didn't think through?


问:
JS - deep map function
Underscore.js has a very useful map function.

```<code>_.map([1, 2, 3], function(num){ return num * 3; });
=> [3, 6, 9]
_.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });
=> [3, 6, 9]
</code>```

I am looking for a similar function that can iterate through nested objects, or deep mapping. After a ton of searching I can't really find this. What I can find is something to pluck a deep object, but not iterate through every value of a deep object.

Something like this:

```<code>deepMap({
  one: 1,
  two: [
    { foo: 'bar' },
    { foos: ['b', 'a', 'r', 's'] },
  ],
  three: [1, 2, 3]
}, function(val, key) {
  return (String(val).indexOf('b') > -1) ? 'bobcat' : val;
})
</code>```

How would one do this?

Sample Output

```<code>{
  one: 1,
  two: [
    { foo: 'bobcat' },
    { foos: ['bobcat', 'a', 'r', 's'] },
  ],
  three: [1, 2, 3]
}
</code>```

答:
es5 underscore.js version, supports arrays (integer keys) and objects:</p>

```<code>_.recursiveMap = function(value, fn) {
    if (_.isArray(value)) {
        return _.map(value, function(v) {
            return _.recursiveMap(v, fn);
        });
    } else if (typeof value === 'object') {
        return _.mapObject(value, function(v) {
            return _.recursiveMap(v, fn);
        });
    } else {
        return fn(value);
    }
};
</code>```

Title: JS - deep map function

Body:
Underscore.js has a very useful map function.

_.map([1, 2, 3], function(num){ return num * 3; });
=> [3, 6, 9]
_.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });
=> [3, 6, 9]

I am looking for a similar function that can iterate through nested objects, or deep mapping. After a ton of searching I can't really find this. What I can find is something to pluck a deep object, but not iterate through every value of a deep object.

Something like this:

deepMap({
  one: 1,
  two: [
    { foo: 'bar' },
    { foos: ['b', 'a', 'r', 's'] },
  ],
  three: [1, 2, 3]
}, function(val, key) {
  return (String(val).indexOf('b') > -1) ? 'bobcat' : val;
})

How would one do this?

Sample Output

{
  one: 1,
  two: [
    { foo: 'bobcat' },
    { foos: ['bobcat', 'a', 'r', 's'] },
  ],
  three: [1, 2, 3]
}

Body:
es5 underscore.js version, supports arrays (integer keys) and objects:

_.recursiveMap = function(value, fn) {
    if (_.isArray(value)) {
        return _.map(value, function(v) {
            return _.recursiveMap(v, fn);
        });
    } else if (typeof value === 'object') {
        return _.mapObject(value, function(v) {
            return _.recursiveMap(v, fn);
        });
    } else {
        return fn(value);
    }
};


问:
importing tbl file to monetDB on windows 10
I am having trouble importing the data of the TPCH-Benchmark (generated with dbgen) into my monetDB-Database.
I've already created all the tables and I'm trying to import using the following command:

COPY RECORDS INTO region FROM "PATH\region.tbl" DELIMITERS tuple_seperator '|' record_seperator '\r\n';

And I get the following error message:

syntax error, unexpected RECORDS, expecting BINARY or INTO in: "copy records"

I also found out this one on the internet:

COPY INTO sys.region 'PATH/region.tbl' using delimiters '|','\n';

But I get the following error message:

syntax error, unexpected IDENT, expecting FROM in: "copy into sys.region "C:\ProgramData\MySQL\MySQL Server 5.7\Uploads\region."

Because I'm a new monetDB user I'm not getting

What I'm doing wrong ?

Any help will be appreciate :)

答:
The RECORDS construct expects a number, specifically how many records you are to load. I usually do this:

```<code>COPY 5 RECORDS INTO region FROM '/path/to/region.tbl' USING DELIMITERS '|', '|\n' LOCKED;
</code>```

Also in the second attempt you are missing a FROM before the path to the file like

```<code>COPY INTO sys.region FROM '/path/to/region.tbl' USING DELIMITERS '|', '\n';
</code>```

See here for more information: https://www.monetdb.org/Documentation/Manuals/SQLreference/CopyInto

Body:
The RECORDS construct expects a number, specifically how many records you are to load. I usually do this:

COPY 5 RECORDS INTO region FROM '/path/to/region.tbl' USING DELIMITERS '|', '|\n' LOCKED;

Also in the second attempt you are missing a FROM before the path to the file like

COPY INTO sys.region FROM '/path/to/region.tbl' USING DELIMITERS '|', '\n';

See here for more information: https://www.monetdb.org/Documentation/Manuals/SQLreference/CopyInto


问:
Which Native iOS API can be used to stream and play audio data in my application?
I'm interested in building a iOS application similar to wynk.The app will be having a list of songs. On clicking any option, it will start streaming that music file from the server. I don't want to use any third Party API. Any help/ suggestion will be of great help. I'm using xCode 8.0 with swift 3.</p>

答:
Apple provides HTTP Live Streaming (HLS) for audio/video streaming:
https://developer.apple.com/streaming/,

At the start of the streaming session, the client downloads a master .m3u8 playlist file containing the metadata for the various sub-streams which are available. Then decides what to download from the media files available, based on predefined factors such as device type, resolution, data rate, size, etc.

Apple provides sample code on how to play and persist HTTP Live Streams hosted on remote servers:
https://developer.apple.com/library/content/samplecode/HLSCatalog/Listings/HLSCatalog_AssetListTableViewCell_swift.html#//apple_ref/doc/uid/TP40017320-HLSCatalog_AssetListTableViewCell_swift-DontLinkElementID_4

also check this answer on HLS here, you'll get the whole picture: HTTP LIve Streaming

AVFoundation for playback
https://developer.apple.com/av-foundation/

```<code>import AVFoundation
import UIKit

class ViewController: UIViewController {

    override func viewDidAppear(animated: Bool) {
        let videoURL = NSURL(string: "your_video_url")
        guard let player = AVPlayer(URL: videoURL) else { return }
        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = self.view.bounds
        self.view.layer.addSublayer(playerLayer)
        player.play()
    }
}
</code>```

Body:
Apple provides HTTP Live Streaming (HLS) for audio/video streaming:
https://developer.apple.com/streaming/,

At the start of the streaming session, the client downloads a master .m3u8 playlist file containing the metadata for the various sub-streams which are available. Then decides what to download from the media files available, based on predefined factors such as device type, resolution, data rate, size, etc.

Apple provides sample code on how to play and persist HTTP Live Streams hosted on remote servers:
https://developer.apple.com/library/content/samplecode/HLSCatalog/Listings/HLSCatalog_AssetListTableViewCell_swift.html#//apple_ref/doc/uid/TP40017320-HLSCatalog_AssetListTableViewCell_swift-DontLinkElementID_4

also check this answer on HLS here, you'll get the whole picture: HTTP LIve Streaming

AVFoundation for playback
https://developer.apple.com/av-foundation/

import AVFoundation
import UIKit

class ViewController: UIViewController {

    override func viewDidAppear(animated: Bool) {
        let videoURL = NSURL(string: "your_video_url")
        guard let player = AVPlayer(URL: videoURL) else { return }
        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = self.view.bounds
        self.view.layer.addSublayer(playerLayer)
        player.play()
    }
}


问:
Move project from Tomcat localhost to "real" server
Ive been developing a Web-project with Java as backend, ive been using Tomcat to host the server. How do I move the project from my local "localhost" to the real external server?</p>

答:
First of all, you need a server with a static IP. It can be VDS/VPS or cloud like AWS.

Then you install and configure Tomcat at the server of your choice.

Then you deploy your app. I can think of a few ways: manually upload app to your remote server via FTP, deploy app to your remote server using IDE tools, push your app to remote Git repository and pull it on your server.
Hope it helps.


问:
Call google chart from partial view in mvc
I'm trying to call google chart from a partial view to a view but the chart is not loading. It was working fine in the view, but when converted to partial view it is not rendering. Anyone please check and help me if anything wrong.

My View

```<code>@model HeathAppDesign.Model.ChartModel
@{
    ViewBag.Title = "Index";
}
<h2>
    Index</h2>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $('#ChartTypes').change(function () {

            var selectedID = $(this).val();
            $.ajax({
                url: '/charts/GetChart/4',
                type: 'GET',
                success: function (result) {
                    debugger;
                    var res = JSON.stringify(result);
                    $('#div-Graph').append(res);
                    alert($('#div-Graph').html());
                }
            });

        });
    });
</script>
<div>

    <select id="ChartTypes">
        <option id="Chart1" value="0">Projected Annual Cost per Member</option>
        <option id="Chart2" value="1">Projected Annual Cost to Employer by Plan</option>
        <option id="Chart3" value="2">Total Projected Cost</option>
        <option id="Chart4" value="3">Renewal Year PMPM Cost</option>
        <option id="Chart5" value="4">Paid Or Allowed Ratio by Plan</option>
        <option id="Chart6" value="5">Impact of Plan Design Changes on 2017 Costs</option>
        <option id="Chart7" value="6">5 Year Projected Plan Change Impact</option>
        <option id="Chart8" value="7">Impact of Trend Over Time</option>
    </select>
    <div id="div-Graph">

    </div>
</div>
</code>```

My PartialView

```<code>@model IEnumerable<HeathAppDesign.Model.ChartModel>

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<script type="text/javascript">
    google.load("visualization", "1", { packages: ["corechart"] });

</script>
<script type="text/javascript">
    $(function () {

        chartsdata = '@Model'
        alert(chartsdata);
        google.charts.load('current', { 'packages': ['bar'] });
        google.charts.setOnLoadCallback(drawStuff);

        function drawStuff() {
            var data = new google.visualization.DataTable();

            data.addColumn('string', '');
            data.addColumn('number', '');

            for (var i = 0; i < chartsdata.length; i++) {
                data.addRow([chartsdata[i].XCoordinates, chartsdata[i].YCoordinates]);
            }

            var options = {
                title: 'Paid/Allowed Ratio by Plan',
                width: 500,
                legend: { position: 'none' },
                trendlines: { 0: {} },
                bars: 'vertical', // Required for Material Bar Charts
                vAxis: { viewWindow: { min: 90, max: 100 }, gridlines: { count: 11} },

                bar: { groupWidth: "20%" }
            };

            var chart = new google.charts.Bar(document.getElementById('chartdiv'));
            chart.draw(data, options);
        };

    });

</script>
<h2>
    Chart5</h2>
<div id="chartdiv" style="width: 600px; height: 350px; margin: 0 auto;">
</div>
</code>```

My ActionMethod

```<code> [HttpGet]
        public ActionResult GetChart(int id)
        {
            return PartialView("_PaidOrAllowedRatio",
                      objChartService.GetChartCoordinates(ChartTypes.PaidOrAllowedRatioByPlan));
        }
</code>```

My result is like this

"\r\n\r\n
\r\n Chart5

\r\n
\r\n
\r\n"
Design table Area

I have multiple charts in the same view and that is why using partial view.

Anyone please help?

答:
Finally I found an answer, really taken lots of time to fix this. I moved all script references to my view file from my partial view and then called the google.load in view

ie,

```<code>google.load("visualization", "1", { packages: ["corechart"] });
</code>```

So my view became like below

```<code>@model HeathAppDesign.Model.ChartModel
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<script type="text/javascript">
    **google.load("visualization", "1", { packages: ["corechart"] });**

    $(document).ready(function () {
        $('#ChartTypes').change(function () {
            var selectedID = $(this).val();
            $.ajax({
                url: '/charts/GetChart/',
                data: {id:4},
                type: 'GET',
                success: function (result) {

                    $('#div-Graph').append(result);

                }
            });

        });
    });
</script>
<div>

    <select id="ChartTypes">
        <option id="Chart1" value="0">Projected Annual Cost per Member</option>
        <option id="Chart2" value="1">Projected Annual Cost to Employer by Plan</option>
        <option id="Chart3" value="2">Total Projected Cost</option>
        <option id="Chart4" value="3">Renewal Year PMPM Cost</option>
        <option id="Chart5" value="4">Paid Or Allowed Ratio by Plan</option>
        <option id="Chart6" value="5">Impact of Plan Design Changes on 2017 Costs</option>
        <option id="Chart7" value="6">5 Year Projected Plan Change Impact</option>
        <option id="Chart8" value="7">Impact of Trend Over Time</option>
    </select>
    <div id="div-Graph">

    </div>
</div>
<div>
    Design table Area
</div>
</code>```

Thanks everyone for your time!

Body:
I'm trying to call google chart from a partial view to a view but the chart is not loading. It was working fine in the view, but when converted to partial view it is not rendering. Anyone please check and help me if anything wrong.

My View

@model HeathAppDesign.Model.ChartModel
@{
    ViewBag.Title = "Index";
}

    Index

    <select id="ChartTypes">
        <option id="Chart1" value="0">Projected Annual Cost per Member</option>
        <option id="Chart2" value="1">Projected Annual Cost to Employer by Plan</option>
        <option id="Chart3" value="2">Total Projected Cost</option>
        <option id="Chart4" value="3">Renewal Year PMPM Cost</option>
        <option id="Chart5" value="4">Paid Or Allowed Ratio by Plan</option>
        <option id="Chart6" value="5">Impact of Plan Design Changes on 2017 Costs</option>
        <option id="Chart7" value="6">5 Year Projected Plan Change Impact</option>
        <option id="Chart8" value="7">Impact of Trend Over Time</option>
    </select>

My PartialView

@model IEnumerable<HeathAppDesign.Model.ChartModel>

    Chart5

My ActionMethod

 [HttpGet]
        public ActionResult GetChart(int id)
        {
            return PartialView("_PaidOrAllowedRatio",
                      objChartService.GetChartCoordinates(ChartTypes.PaidOrAllowedRatioByPlan));
        }

My result is like this

"\r\n\r\n
\r\n Chart5

\r\n
\r\n
\r\n"
Design table Area

I have multiple charts in the same view and that is why using partial view.

Anyone please help?

Body:
Finally I found an answer, really taken lots of time to fix this. I moved all script references to my view file from my partial view and then called the google.load in view

ie,

google.load("visualization", "1", { packages: ["corechart"] });

So my view became like below

@model HeathAppDesign.Model.ChartModel
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<script type="text/javascript">
    **google.load("visualization", "1", { packages: ["corechart"] });**

    $(document).ready(function () {
        $('#ChartTypes').change(function () {
            var selectedID = $(this).val();
            $.ajax({
                url: '/charts/GetChart/',
                data: {id:4},
                type: 'GET',
                success: function (result) {

                    $('#div-Graph').append(result);

                }
            });

        });
    });
</script>
<div>

    <select id="ChartTypes">
        <option id="Chart1" value="0">Projected Annual Cost per Member</option>
        <option id="Chart2" value="1">Projected Annual Cost to Employer by Plan</option>
        <option id="Chart3" value="2">Total Projected Cost</option>
        <option id="Chart4" value="3">Renewal Year PMPM Cost</option>
        <option id="Chart5" value="4">Paid Or Allowed Ratio by Plan</option>
        <option id="Chart6" value="5">Impact of Plan Design Changes on 2017 Costs</option>
        <option id="Chart7" value="6">5 Year Projected Plan Change Impact</option>
        <option id="Chart8" value="7">Impact of Trend Over Time</option>
    </select>
    <div id="div-Graph">

    </div>
</div>
<div>
    Design table Area
</div>

Thanks everyone for your time!


问:
Issue with String to Date conversion after Timezone parsing
I am trying to convert a date to a specified timezone and return the converted date. But the code always returns the unconverted date. Can any help with the same.

```<code>public static Date testUserSpecifiedConv(String toTimezone, Date inputDate) {
        System.out.println(inputDate);
        Date convertedDate = null;
        String inputDateStr ;
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        df.setTimeZone(TimeZone.getTimeZone(toTimezone));

        inputDateStr = df.format(inputDate);

        System.out.println("Formatted Date In String Format: " + inputDateStr);
        //Now trying to convert it back to date
        try {
            convertedDate = df.parse(inputDateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return convertedDate;
    }

    public static void main(String args[]) {
        System.out.println("Formatted Date In Date Format: "+testUserSpecifiedConv("EST", new Date()));
    }
</code>```

Output is

```<code>Fri Mar 31 15:58:50 IST 2017
Formatted Date In String Format: 03/31/2017 05:28:50
Formatted Date In Date Format: Fri Mar 31 15:58:50 IST 2017
</code>```

The formatted date in string and date format in output is different.

答:
The class java.util.Date does represent a specific point in time and is timezone independent per se.

Nevertheless you can apply the timezone to the SimpleDateFormat to format your date accordingly to be presented in a certain timezone (e.g. if you want a formatted string to be shown somewhere).

Still, if you now parse back the formatted date, the date object itself will again not contain any information about the timezone.

If you want to work with timezones on an object level you might have a look into ZonedDateTime.

Update:

Assuming you want to convert a given String to an object containing the information about the date in a certain timezone you could do it like that:

```<code>ZonedDateTime dateTime = ZonedDateTime.parse("2007-12-03T10:15:30+01:00[Europe/Paris]");
</code>```

Body:
I am trying to convert a date to a specified timezone and return the converted date. But the code always returns the unconverted date. Can any help with the same.

public static Date testUserSpecifiedConv(String toTimezone, Date inputDate) {
        System.out.println(inputDate);
        Date convertedDate = null;
        String inputDateStr ;
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        df.setTimeZone(TimeZone.getTimeZone(toTimezone));

        inputDateStr = df.format(inputDate);

        System.out.println("Formatted Date In String Format: " + inputDateStr);
        //Now trying to convert it back to date
        try {
            convertedDate = df.parse(inputDateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return convertedDate;
    }

    public static void main(String args[]) {
        System.out.println("Formatted Date In Date Format: "+testUserSpecifiedConv("EST", new Date()));
    }

Output is

Fri Mar 31 15:58:50 IST 2017
Formatted Date In String Format: 03/31/2017 05:28:50
Formatted Date In Date Format: Fri Mar 31 15:58:50 IST 2017

The formatted date in string and date format in output is different.

Body:
The class java.util.Date does represent a specific point in time and is timezone independent per se.

Nevertheless you can apply the timezone to the SimpleDateFormat to format your date accordingly to be presented in a certain timezone (e.g. if you want a formatted string to be shown somewhere).

Still, if you now parse back the formatted date, the date object itself will again not contain any information about the timezone.

If you want to work with timezones on an object level you might have a look into ZonedDateTime.

Update:

Assuming you want to convert a given String to an object containing the information about the date in a certain timezone you could do it like that:

ZonedDateTime dateTime = ZonedDateTime.parse("2007-12-03T10:15:30+01:00[Europe/Paris]");


问:
Can't set value to data attribute with jQuery
From some reason I can't figure out, the $('element').data('data_attribute_name', 'value'); syntax doesn't work here:

HTML:

```<code><ul class="main_menu__list" data-scheme="light">
...
</ul>
</code>```

JS:

```<code>$('.main_menu__list').data('scheme', 'dark');
$('.main_menu__list').css('border', '10px solid yellow');
</code>```

The second line does work (yellow border applied), the second one does nothing. why?

答:
The first line is working fine. The data() method stores the values in an in-memory cache so that it's faster (at least in theory) due to having to query the DOM less often. It does not update the DOM at all.

So long as you also use the getter of data() to retrieve the value this works absolutely fine:

var $list = $('.main_menu__list');

$list.data('scheme', 'dark').css('border', '10px solid yellow');

// to retrieve the attribute:

console.log($list.data('scheme')); // 'dark'```
<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>
<ul class="main_menu__list" data-scheme="light"></ul></code>```

even using attr() as suggested in another answer it still doesn't change it!

Yep, it does. You can check it in the DOM inspector after running this snippet:

var $list = $('.main_menu__list');

$list.attr('data-scheme', 'dark').css('border', '10px solid yellow');

// to retrieve the attribute:

console.log($list.data('scheme')); // 'dark'```
<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>
<ul class="main_menu__list" data-scheme="light"></ul></code>```

Body:
From some reason I can't figure out, the $('element').data('data_attribute_name', 'value'); syntax doesn't work here:

HTML:

...

JS:

$('.main_menu__list').data('scheme', 'dark');
$('.main_menu__list').css('border', '10px solid yellow');

The second line does work (yellow border applied), the second one does nothing. why?

Body:
The first line is working fine. The data() method stores the values in an in-memory cache so that it's faster (at least in theory) due to having to query the DOM less often. It does not update the DOM at all.

So long as you also use the getter of data() to retrieve the value this works absolutely fine:

var $list = $('.main_menu__list');

$list.data('scheme', 'dark').css('border', '10px solid yellow');

// to retrieve the attribute:

console.log($list.data('scheme')); // 'dark'

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="main_menu__list" data-scheme="light"></ul>

even using attr() as suggested in another answer it still doesn't change it!

Yep, it does. You can check it in the DOM inspector after running this snippet:

var $list = $('.main_menu__list');

$list.attr('data-scheme', 'dark').css('border', '10px solid yellow');

// to retrieve the attribute:

console.log($list.data('scheme')); // 'dark'

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="main_menu__list" data-scheme="light"></ul>


问:
ubuntu server pipeline stop process termination when the first exit
The situation is: I have an external application so I don't have the source code and i can't change it. While running, the application writes logs to the stderr. The task is to write a program that check the output of it and separate some part of the output to other file. My solution is to start the app like

```<code>./externalApp 2>&1 | myApp
</code>```

the myApp is a c++ app with the following source:

```<code>using namespace std;

int main ()
{
string str;
ofstream A;
A.open("A.log");

ofstream B;
B.open("B.log");

A << "test start" << endl;

int i = 0;

while (getline(cin,str))
{
    if(str.find("asdasd") != string::npos)
    {
        A << str << endl;
    }
    else
    {
        B << str << endl;
    }
    ++i;
}

A << "test end: " << i << " lines" << endl;
A.close();
B.close();

return 0;
}
</code>```

The externalApp can crash or be terminated. A that moment the myApp gets terminated too and it is don't write the last lines and don't close the files. The file can be 60Gb or larger so saving it and processing it after not a variant.

Correction: My problem is that when the externalApp crash it terminate myApp. That mean any code after while block will never run. So the question is: Is there a way to run myApp even after the externalApp closed?

How can I do this task correctly? I interesed in any other idea to do this task.

答:
So the problem was not that when the first element of the pipe ended it terminate the second. The real problem was that the two app with pipes launched from bash script and when the bash script ended it terminated all of it child process. I solved it using

```<code>signal(SIGHUP,SIG_IGN);
</code>```

that way my app executed to the end.
Thank you for all the answer at least I learned lot about the signals and pipes.

Body:
The situation is: I have an external application so I don't have the source code and i can't change it. While running, the application writes logs to the stderr. The task is to write a program that check the output of it and separate some part of the output to other file. My solution is to start the app like

./externalApp 2>&1 | myApp

the myApp is a c++ app with the following source:

using namespace std;

int main ()
{
string str;
ofstream A;
A.open("A.log");

ofstream B;
B.open("B.log");

A << "test start" << endl;

int i = 0;

while (getline(cin,str))
{
    if(str.find("asdasd") != string::npos)
    {
        A << str << endl;
    }
    else
    {
        B << str << endl;
    }
    ++i;
}

A << "test end: " << i << " lines" << endl;
A.close();
B.close();

return 0;
}

The externalApp can crash or be terminated. A that moment the myApp gets terminated too and it is don't write the last lines and don't close the files. The file can be 60Gb or larger so saving it and processing it after not a variant.

Correction: My problem is that when the externalApp crash it terminate myApp. That mean any code after while block will never run. So the question is: Is there a way to run myApp even after the externalApp closed?

How can I do this task correctly? I interesed in any other idea to do this task.

Body:
So the problem was not that when the first element of the pipe ended it terminate the second. The real problem was that the two app with pipes launched from bash script and when the bash script ended it terminated all of it child process. I solved it using

signal(SIGHUP,SIG_IGN);

that way my app executed to the end.
Thank you for all the answer at least I learned lot about the signals and pipes.