问:
How to get biweekly dates per month in a year in SQL Server?
I am trying to generate biweekly dates when I set a start year and end year.

```<code>DECLARE @StartYear DATETIME
DECLARE @EndYear DATETIME

SET @StartYear = '01/01/2017'
SET @EndYear = '12/31/2017'
</code>```

The T-SQL should then compute the biweekly dates, example: 03/15/2017 and 03/30/2017 are the paydays.

Also if the dates fall on Saturday and Sunday, then it will generate the dates to its 1st Friday.

Hope someone could help me with this. Or someone would like to share his/her knowledge and formula about this.

UPDATE: my expected result as follows:

when I enter 01/01/2017, then it will automatically generates every 15th day.

Example:

```<code>@StartYear: 01/01/2017
</code>```

Result should be:

```<code>DatesBiweeklyPerMonthInAYear
-------------------------------
01/13/2017 (since the 15th day falls on sunday)
01/30/2017
02/15/2017
02/28/2017 (since no 30th day)
</code>```

If 15th day falls on sun or sat it will fall on Friday of that specific week.
so on... until the end of the year.

Is this achievable? Or not?

Thanks!

答:
your business rule is not 100% clear.

I think there can be more than one correct result.

In one place it is hard coded,because i want to be 100% sure of requirement.
I am not using cursor.Its only 24 loops.

```<code>declare @StartYear datetime='2017-01-01'
declare @endYear datetime ='2017-12-31'

declare @gap int =14 --Bimonthly means gap of 14 days or 15 days whatever

;With CTE as
(
select dateadd(day,@gap, @StartYear) Bimonthly
,1 rn

UNION ALL

select
case

when (rn+1)%2=0 and datename(m, Bimonthly)='February' THEN
      '2017-02-28'
      when (rn+1)%2=0 and datename(m, Bimonthly)!='February'

then dateadd(day,@gap, Bimonthly)
else
dateadd(day,@gap, dateadd(month, datediff(month,0,dateadd(month,1,Bimonthly)),0))
END
,rn+1
from cte
where rn< (datediff(month,@StartYear, @endYear)+1)*2

)
select
case WHEN datename(dw, Bimonthly)='Saturday' THEN
      dateadd(day,-1, Bimonthly)
      WHEN datename(dw, Bimonthly)='Sunday' THEN
      dateadd(day,-2, Bimonthly)
     else
      Bimonthly
     end

     ,rn

from cte
</code>```

Body:
I am trying to generate biweekly dates when I set a start year and end year.

DECLARE @StartYear DATETIME
DECLARE @EndYear DATETIME

SET @StartYear = '01/01/2017'
SET @EndYear = '12/31/2017'

The T-SQL should then compute the biweekly dates, example: 03/15/2017 and 03/30/2017 are the paydays.

Also if the dates fall on Saturday and Sunday, then it will generate the dates to its 1st Friday.

Hope someone could help me with this. Or someone would like to share his/her knowledge and formula about this.

UPDATE: my expected result as follows:

when I enter 01/01/2017, then it will automatically generates every 15th day.

Example:

@StartYear: 01/01/2017

Result should be:

DatesBiweeklyPerMonthInAYear
-------------------------------
01/13/2017 (since the 15th day falls on sunday)
01/30/2017
02/15/2017
02/28/2017 (since no 30th day)

If 15th day falls on sun or sat it will fall on Friday of that specific week.
so on... until the end of the year.

Is this achievable? Or not?

Thanks!

Body:
your business rule is not 100% clear.

I think there can be more than one correct result.

In one place it is hard coded,because i want to be 100% sure of requirement.
I am not using cursor.Its only 24 loops.

declare @StartYear datetime='2017-01-01'
declare @endYear datetime ='2017-12-31'

declare @gap int =14 --Bimonthly means gap of 14 days or 15 days whatever

;With CTE as
(
select dateadd(day,@gap, @StartYear) Bimonthly
,1 rn

UNION ALL

select
case

when (rn+1)%2=0 and datename(m, Bimonthly)='February' THEN
      '2017-02-28'
      when (rn+1)%2=0 and datename(m, Bimonthly)!='February'

then dateadd(day,@gap, Bimonthly)
else
dateadd(day,@gap, dateadd(month, datediff(month,0,dateadd(month,1,Bimonthly)),0))
END
,rn+1
from cte
where rn< (datediff(month,@StartYear, @endYear)+1)*2

)
select
case WHEN datename(dw, Bimonthly)='Saturday' THEN
      dateadd(day,-1, Bimonthly)
      WHEN datename(dw, Bimonthly)='Sunday' THEN
      dateadd(day,-2, Bimonthly)
     else
      Bimonthly
     end

     ,rn

from cte


来源: stackexchange

问:
How to remove repeated foreach values in jquery
I am working now wordpress this is my code

```<code>jQuery(document).ready(function () {

 <?php
 $var= $product->get_available_variations();
 foreach ($var as $key => $test)
 {

$check=$test['display_price'];
 ?>
 var check='<?php echo $check;?>';

 jQuery('<p>'+check+'</p>').appendTo('.variation_buttons_wrapper');

 <?php
 }
 ?>
</code>```

Actually my task is split foreach values and append another div.But my answer is again and again repeated.My out put is there,

```<code>53.95
39.95
29.95
27.95
53.95
39.95
29.95
27.95
53.95
39.95
29.95
27.95
53.95
39.95
29.95
27.95
</code>```

But i want out put

```<code> 53.95
39.95
29.95
27.95
</code>```

this only.please help me.

答:
//  try this patch

```<code><script type="text/javascript">

jQuery(document).ready(function () {

    <?php
    $var = array_unique($product->get_available_variations());
    foreach ($var as $key => $test)
    {
        $check = $test['display_price'];
    ?>
        var check = "<?php echo $check;?>";

        jQuery('<p>'+check+'</p>').appendTo('.variation_buttons_wrapper');

    <?php  }  ?>

});

</script>
</code>```

try also this.

```<code><script type="text/javascript">

        jQuery(document).ready(function () {

            <?php
            $var = array_map("unserialize", array_unique(array_map("serialize", $product->get_available_variations())));
            foreach ($var as $key => $test)
            {
                $check = $test['display_price'];
            ?>
                var check = "<?php echo $check;?>";
                jQuery('<p>'+check+'</p>').appendTo('.variation_buttons_wrapper');

            <?php  }  ?>

        });
 </script>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am working now wordpress this is my code

jQuery(document).ready(function () {

 <?php
 $var= $product->get_available_variations();
 foreach ($var as $key => $test)
 {

$check=$test['display_price'];
 ?>
 var check='<?php echo $check;?>';

 jQuery('
'+check+'
').appendTo('.variation_buttons_wrapper');

 <?php
 }
 ?>

Actually my task is split foreach values and append another div.But my answer is again and again repeated.My out put is there,

53.95
39.95
29.95
27.95
53.95
39.95
29.95
27.95
53.95
39.95
29.95
27.95
53.95
39.95
29.95
27.95

But i want out put

 53.95
39.95
29.95
27.95

this only.please help me.

Body:
//  try this patch

<script type="text/javascript">

jQuery(document).ready(function () {

    <?php
    $var = array_unique($product->get_available_variations());
    foreach ($var as $key => $test)
    {
        $check = $test['display_price'];
    ?>
        var check = "<?php echo $check;?>";

        jQuery('<p>'+check+'</p>').appendTo('.variation_buttons_wrapper');

    <?php  }  ?>

});

</script>

try also this.

<script type="text/javascript">

        jQuery(document).ready(function () {

            <?php
            $var = array_map("unserialize", array_unique(array_map("serialize", $product->get_available_variations())));
            foreach ($var as $key => $test)
            {
                $check = $test['display_price'];
            ?>
                var check = "<?php echo $check;?>";
                jQuery('<p>'+check+'</p>').appendTo('.variation_buttons_wrapper');

            <?php  }  ?>

        });
 </script>


问:
How do I specify the zoom level when using an MKUserTrackingBarButtonItem?
I am using a MKUserTrackingBarButtonItem button to allow the user to automatically track their location on a map. The problem is that when they tap this button, it is zoomed too far out. I want it to start at a specified zoom level (i.e. span). How can I achieve this?

When the user taps the button to change to MKUserTrackingModeFollow, it seems to use the same zoom level that the user last manually changed to (i.e. using gestures on the map). Attempting to specify a different zoom level via setRegion or setVisibleMapRect does not affect what zoom level will be used when the mode is changed to MKUserTrackingModeFollow.

Attempting to override mapView:didChangeUserTrackingMode: to set the region causes the mode to be changed back to MKUserTrackingModeNone. Example:

```<code>- (void)mapView:(MKMapView *)mapView didChangeUserTrackingMode:(MKUserTrackingMode)mode animated:(BOOL)animated {
    if (mode == MKUserTrackingModeFollow) {
        CLLocationCoordinate2D center = mapView.userLocation.location.coordinate;
        MKCoordinateSpan span = MKCoordinateSpanMake(0.002306, 0.001717);
        [mapView setRegion:MKCoordinateRegionMake(center, span) animated:YES];
        // [mapView setUserTrackingMode:MKUserTrackingModeFollow animated:NO];
    }
}
</code>```

If I attempt to reset the mode immediately after setting the region, it works fine if the user is stationary, but zooms back out if the user is moving.

The simplest solution would be if there was a way to simply specify something like a zoom level for MKUserTraking by sending it my span value. However, since that doesn't seem to exist, what else can I do?

答:
According to apple documentation used here

https://developer.apple.com/reference/mapkit/mkmapview/1616208-usertrackingmode

Setting the tracking mode to follow or followWithHeading causes the map view to center the map on that location and begin tracking the user’s location. If the map is zoomed out, the map view automatically zooms in on the user’s location, effectively changing the current visible region.

Here changing the region does not effect your visible region due to that reason.

```<code>- (void)mapView:(MKMapView *)mapView didChangeUserTrackingMode:(MKUserTrackingMode)mode animated:(BOOL)animated {
if (mode == MKUserTrackingModeFollow) {
    CLLocationCoordinate2D center = mapView.userLocation.location.coordinate;
    MKCoordinateSpan span = MKCoordinateSpanMake(0.002306, 0.001717);
    [mapView setRegion:MKCoordinateRegionMake(center, span) animated:YES];
    // [mapView setUserTrackingMode:MKUserTrackingModeFollow animated:NO];
 }
}
</code>```

So you just need to change center coordinate on didChangeUserTrackingMode instead of changing the whole region

```<code>- (void)mapView:(MKMapView *)mapView didChangeUserTrackingMode:(MKUserTrackingMode)mode animated:(BOOL)animated {
if (mode == MKUserTrackingModeFollow) {
   [self.mapView setCenterCoordinate:mapView.userLocation.location.coordinate animated:YES];
   }
 }

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
  [self.mapView setCenterCoordinate:mapViewuserLocation.location.coordinate animated:YES];
}
</code>```

on click of MKUserTrackingBarButtonItem change the zoom level

```<code> CLLocationCoordinate2D center = mapView.userLocation.location.coordinate;
MKCoordinateSpan span = MKCoordinateSpanMake(0.002306, 0.001717);
[mapView setRegion:MKCoordinateRegionMake(center, span) animated:YES];
</code>```

Body:
I am using a MKUserTrackingBarButtonItem button to allow the user to automatically track their location on a map. The problem is that when they tap this button, it is zoomed too far out. I want it to start at a specified zoom level (i.e. span). How can I achieve this?

When the user taps the button to change to MKUserTrackingModeFollow, it seems to use the same zoom level that the user last manually changed to (i.e. using gestures on the map). Attempting to specify a different zoom level via setRegion or setVisibleMapRect does not affect what zoom level will be used when the mode is changed to MKUserTrackingModeFollow.

Attempting to override mapView:didChangeUserTrackingMode: to set the region causes the mode to be changed back to MKUserTrackingModeNone. Example:

- (void)mapView:(MKMapView *)mapView didChangeUserTrackingMode:(MKUserTrackingMode)mode animated:(BOOL)animated {
    if (mode == MKUserTrackingModeFollow) {
        CLLocationCoordinate2D center = mapView.userLocation.location.coordinate;
        MKCoordinateSpan span = MKCoordinateSpanMake(0.002306, 0.001717);
        [mapView setRegion:MKCoordinateRegionMake(center, span) animated:YES];
        // [mapView setUserTrackingMode:MKUserTrackingModeFollow animated:NO];
    }
}

If I attempt to reset the mode immediately after setting the region, it works fine if the user is stationary, but zooms back out if the user is moving.

The simplest solution would be if there was a way to simply specify something like a zoom level for MKUserTraking by sending it my span value. However, since that doesn't seem to exist, what else can I do?

Body:
According to apple documentation used here

https://developer.apple.com/reference/mapkit/mkmapview/1616208-usertrackingmode

Setting the tracking mode to follow or followWithHeading causes the map view to center the map on that location and begin tracking the user’s location. If the map is zoomed out, the map view automatically zooms in on the user’s location, effectively changing the current visible region.

Here changing the region does not effect your visible region due to that reason.

- (void)mapView:(MKMapView *)mapView didChangeUserTrackingMode:(MKUserTrackingMode)mode animated:(BOOL)animated {
if (mode == MKUserTrackingModeFollow) {
    CLLocationCoordinate2D center = mapView.userLocation.location.coordinate;
    MKCoordinateSpan span = MKCoordinateSpanMake(0.002306, 0.001717);
    [mapView setRegion:MKCoordinateRegionMake(center, span) animated:YES];
    // [mapView setUserTrackingMode:MKUserTrackingModeFollow animated:NO];
 }
}

So you just need to change center coordinate on didChangeUserTrackingMode instead of changing the whole region

- (void)mapView:(MKMapView *)mapView didChangeUserTrackingMode:(MKUserTrackingMode)mode animated:(BOOL)animated {
if (mode == MKUserTrackingModeFollow) {
   [self.mapView setCenterCoordinate:mapView.userLocation.location.coordinate animated:YES];
   }
 }

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
  [self.mapView setCenterCoordinate:mapViewuserLocation.location.coordinate animated:YES];
}

on click of MKUserTrackingBarButtonItem change the zoom level

 CLLocationCoordinate2D center = mapView.userLocation.location.coordinate;
MKCoordinateSpan span = MKCoordinateSpanMake(0.002306, 0.001717);
[mapView setRegion:MKCoordinateRegionMake(center, span) animated:YES];


问:
Navigation Bar Transparency
Could Anybody help me with that, I have found this code here in this website, That code helps me to transparent the navigation bar:

```<code>self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.view.backgroundColor = .clear
</code>```

The problem is how could I get the default navigation bar?
I have two ViewController The first I want it with normal navigation bar and the second with transparent navigation bar, and when I get back to the first I need to get default navigation bar back :).

答:
I got it, In the second view I used this code:

```<code>self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.view.backgroundColor = .clear
</code>```

,And in first view this code:

```<code>self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: ""), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.view.backgroundColor = .clear
</code>```

Thank you all for your help guys :)

Title: Navigation Bar Transparency

Body:
Could Anybody help me with that, I have found this code here in this website, That code helps me to transparent the navigation bar:

self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.view.backgroundColor = .clear

The problem is how could I get the default navigation bar?
I have two ViewController The first I want it with normal navigation bar and the second with transparent navigation bar, and when I get back to the first I need to get default navigation bar back :).

Body:
I got it, In the second view I used this code:

self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.view.backgroundColor = .clear

,And in first view this code:

self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: ""), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.view.backgroundColor = .clear

Thank you all for your help guys :)


问:
Cocoon link_to_add_association not working
Have followed video tutorials, searched over and over, don't get it. Would appreciate help.

My main issue is that the link_to_add_association isn't working and I keep getting a missing template error.

"ActionView::MissingTemplate in Applications#new"

It says:
Missing partial applications/_question_fields, application/_question_fields with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :coffee, :jbuilder]}. Searched in:
  * "/Users/AndyAir/projects/friends-app/app/views"
  * "/Users/AndyAir/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/devise-4.2.1/app/views"

model

```<code>class Application < ApplicationRecord
 belongs_to :user

 has_many :questions

 accepts_nested_attributes_for :questions, reject_if: :all_blank, allow_destroy: true

 validates :name, :description, presence: true
end
</code>```

controller

```<code>class ApplicationsController < ApplicationController
 before_action :find_application, only: [:show, :edit, :update, :destroy]
 before_action :authenticate_user!

 def index
    @applications = Application.all.order("created_at DESC").limit(3)
 end

 def new
  @application = Application.new
  @application.questions.build
 end

 def create
    @application = Application.new(application_params)

    if @application.save
        redirect_to @application
    else
        render 'new'
    end
 end

 def show
 end

 def edit
 end

 def update
    if @application.update(application_params)
        redirect_to @application
    else
        render 'edit'
    end
 end

 def destroy
    @application.destroy
    redirect_to root_path
 end

 private

 def find_application
    @application = Application.find(params[:id])
 end

 def application_params
    params.require(:application).permit(:name, :description, questions_attributes: [:id, :name, :_destroy])
 end

 def after_sign_out_path_for(resource_or_scope)
  redirect_to root_path
 end
end
</code>```

views/applications/new

```<code><%= form_for @application do |f| %>
    <% if @application.errors.any? %>
      <div id="errors">
        <p><%= @application.errors.count %> Prevented this application from saving</p>
        <ul>
          <% @application.errors.full_messages.each do |msg| %>
            <li><%= msg %></li>
          <% end %>
        </ul>
      </div>
    <% end %>
    <div class="field">
        <%= f.label :title %><br>
        <%= f.text_field :name, placeholder: "Name of Your Friend Test", class: "form-control" %><br>
        <%= f.label :description %><br>
        <%= f.text_field :description, placeholder: "Write a witty tagline for your test.", class: "form-control" %><br>
    </div>
    <h3>Questions</h3>
        <%= f.fields_for :questions do |question| %>
            <div id="questions">
                <div class="field">
                <%= render 'questions_fields', f: question %>
             <div class="links">
                <%= link_to_add_association 'Add Question', f, :questions %>
               </div>
              </div>
            </div>
        <% end %>
    <br>
    <div class="form-actions">
        <%= f.button :submit %>
    </div>
<% end %>
</code>```

views/applications/_questions_fields.html.erb

```<code><div class="nested-fields">
  <%= f.text_field :question %>
  <%= link_to_remove_association "remove task", f %>
</div>
</code>```

答:
Please try to take link_to_add_association out of fields_for.As there are no questions yet, the link_to_add_association is never shown.</p>

```<code><%= f.fields_for :questions do |question| %>
    <div id="questions">
        <div class="field">
            <%= render 'questions_fields', f: question %>
        </div>
    </div>
<% end %>
<div class="links">
    <%= link_to_add_association 'Add Question', f, :questions %>
</div>
</code>```

Body:
Have followed video tutorials, searched over and over, don't get it. Would appreciate help.

My main issue is that the link_to_add_association isn't working and I keep getting a missing template error.

"ActionView::MissingTemplate in Applications#new"

It says:
Missing partial applications/_question_fields, application/_question_fields with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :coffee, :jbuilder]}. Searched in:
  * "/Users/AndyAir/projects/friends-app/app/views"
  * "/Users/AndyAir/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/devise-4.2.1/app/views"

model

class Application < ApplicationRecord
 belongs_to :user

 has_many :questions

 accepts_nested_attributes_for :questions, reject_if: :all_blank, allow_destroy: true

 validates :name, :description, presence: true
end

controller

class ApplicationsController < ApplicationController
 before_action :find_application, only: [:show, :edit, :update, :destroy]
 before_action :authenticate_user!

 def index
    @applications = Application.all.order("created_at DESC").limit(3)
 end

 def new
  @application = Application.new
  @application.questions.build
 end

 def create
    @application = Application.new(application_params)

    if @application.save
        redirect_to @application
    else
        render 'new'
    end
 end

 def show
 end

 def edit
 end

 def update
    if @application.update(application_params)
        redirect_to @application
    else
        render 'edit'
    end
 end

 def destroy
    @application.destroy
    redirect_to root_path
 end

 private

 def find_application
    @application = Application.find(params[:id])
 end

 def application_params
    params.require(:application).permit(:name, :description, questions_attributes: [:id, :name, :_destroy])
 end

 def after_sign_out_path_for(resource_or_scope)
  redirect_to root_path
 end
end

views/applications/new

<%= form_for @application do |f| %>
    <% if @application.errors.any? %>

<%= @application.errors.count %> Prevented this application from saving

          <% @application.errors.full_messages.each do |msg| %>

<%= msg %>

          <% end %>

    <% end %>

        <%= f.label :title %>

        <%= f.text_field :name, placeholder: "Name of Your Friend Test", class: "form-control" %>

        <%= f.label :description %>

        <%= f.text_field :description, placeholder: "Write a witty tagline for your test.", class: "form-control" %>

Questions

        <%= f.fields_for :questions do |question| %>

                <%= render 'questions_fields', f: question %>

                <%= link_to_add_association 'Add Question', f, :questions %>

        <% end %>

        <%= f.button :submit %>

<% end %>

views/applications/_questions_fields.html.erb

  <%= f.text_field :question %>
  <%= link_to_remove_association "remove task", f %>

Body:
Please try to take link_to_add_association out of fields_for.As there are no questions yet, the link_to_add_association is never shown.

<%= f.fields_for :questions do |question| %>
    <div id="questions">
        <div class="field">
            <%= render 'questions_fields', f: question %>
        </div>
    </div>
<% end %>
<div class="links">
    <%= link_to_add_association 'Add Question', f, :questions %>
</div>


问:
How to get individual values from JSON object
I'm using PubNub API in android to fetch real time data but I need some particular value instead of whole. How can I get value for example c7 & c9. I want them to plot a real time graph.

```<code> @Override
        public void message(PubNub pubnub, PNMessageResult message) {
            System.out.println(message);
        }
</code>```

The result I'm getting :-

PNMessageResult (message={"c1":27,"c2":3,"c3":2017,"c4":15,"c5":56,"c6":52,"c7":15.07,"c8":"P&Q","c9":24.86,"c10":82,"c11":32.74}`

答:
```<code>Make json object and parse specific value:

{
"c1":27,
"c2":3,
"c3":2017,
"c4":15,
"c5":56,
"c6":52,
"c7":15.07,
"c8":"P&Q",
"c9":24.86,
"c10":82,
"c11":32.74
}

try{
  JSONObject jsonObject = new JSONObject("your string");
  double c7 = jsonObject.getDouble("c7");
  double c9 = jsonObject.getDouble("c9");
}
catch(JSONException e){
  e.printStackTrace()
}
</code>```

Body:
I'm using PubNub API in android to fetch real time data but I need some particular value instead of whole. How can I get value for example c7 & c9. I want them to plot a real time graph.

 @Override
        public void message(PubNub pubnub, PNMessageResult message) {
            System.out.println(message);
        }

The result I'm getting :-

PNMessageResult (message={"c1":27,"c2":3,"c3":2017,"c4":15,"c5":56,"c6":52,"c7":15.07,"c8":"P&Q","c9":24.86,"c10":82,"c11":32.74}`


问:
PL/SQL procedure to inset data from one table to another table but need to insert those record which column 3 have null
I am trying to create pl/sql procedure to insert data from one table to another table , but i need to  filter those record from one column which is not null in column.

Example :-

```<code>C1 | C2| C3|
------------
1  | 2 |   |
3  | 4 | 5 |
6  | 7 |   |
-------------
</code>```

I want to filter column c3 second record and insert the remaining record to another table.

Please help me

Thanks

答:
You can use a simple insert-as-select query, with no need for PLSQL:</p>

```<code>insert into table2(c1, c2, c3)
select c1, c2, c3
from table1
where c3 is null
</code>```

Body:
I am trying to create pl/sql procedure to insert data from one table to another table , but i need to  filter those record from one column which is not null in column.

Example :-

C1 | C2| C3|
------------
1  | 2 |   |
3  | 4 | 5 |
6  | 7 |   |
-------------

I want to filter column c3 second record and insert the remaining record to another table.

Please help me

Thanks

Body:
You can use a simple insert-as-select query, with no need for PLSQL:

insert into table2(c1, c2, c3)
select c1, c2, c3
from table1
where c3 is null


问:
Count the number of occurrences of certain choices in models
I have the following models:

```<code>class Team(models.Model):
    # stuff
class Event(models.Model):
    # stuff
class Award(models.Model):
    award_type_choices = (
        (1, "some string"), # a lot of these
        (2, "some other str"),
    )
    award_type = models.CharField(choices=award_type_choices)
    specific_choices = (
        (1, "some string"), # etc
        # only a few of these, but all of these can be found inside award_type_choices.
    )

    event = models.ForeignKey(Event)
    recipients = models.ManyToManyField(Team)
</code>```

I'm trying to count/annotate the number of times a Team has won an award that fits under the specific_choices sequence. I can filter the teams that have won an award through this bit of code:

```<code>reversed_choices = dict((v, k) for k, v in Award.specific_choices)
Team.objects.filter(award__award_type__in=reversed_choices.values())
</code>```

However, I am not sure how I should approach counting these. I have used Count, F, and ExpressionWrapper a little bit before, but not extensively to know how to do this right off the bat.

I figured I could approach it by throwing the same parameters as filter into a Count object, but as soon as I typed it I realized it wouldn't work, ie:

```<code>Team.objects.annotate(num_specifics=Count('award__award_type__in=Award.specific_choices'))
</code>```

Any help with this would be appreciated.

答:
Following code will find number of choices in certain field of a given model:</p>

```<code>my_field=Model._meta.get_field('field_name')

length=len(my_field.choices._display_map)
</code>```

Body:
I have the following models:

class Team(models.Model):
    # stuff
class Event(models.Model):
    # stuff
class Award(models.Model):
    award_type_choices = (
        (1, "some string"), # a lot of these
        (2, "some other str"),
    )
    award_type = models.CharField(choices=award_type_choices)
    specific_choices = (
        (1, "some string"), # etc
        # only a few of these, but all of these can be found inside award_type_choices.
    )

    event = models.ForeignKey(Event)
    recipients = models.ManyToManyField(Team)

I'm trying to count/annotate the number of times a Team has won an award that fits under the specific_choices sequence. I can filter the teams that have won an award through this bit of code:

reversed_choices = dict((v, k) for k, v in Award.specific_choices)
Team.objects.filter(award__award_type__in=reversed_choices.values())

However, I am not sure how I should approach counting these. I have used Count, F, and ExpressionWrapper a little bit before, but not extensively to know how to do this right off the bat.

I figured I could approach it by throwing the same parameters as filter into a Count object, but as soon as I typed it I realized it wouldn't work, ie:

Team.objects.annotate(num_specifics=Count('award__award_type__in=Award.specific_choices'))

Any help with this would be appreciated.

Body:
Following code will find number of choices in certain field of a given model:

my_field=Model._meta.get_field('field_name')

length=len(my_field.choices._display_map)


问:
Edge extendsion chrome.storage.local 1MB limit
Porting an existing extension from chrome to edge and I'm having issues with the 1mb limit on chrome.storage.local.  I used the function in this topic String length in bytes in JavaScript to find he size of the string and found if the json string is over 1mB it will throw a "over 1mB" exception, but if the json string was between 250kB and 1mB I get a message in chrome.runtime.lastError saying the data is over 1mB, no exception is thrown and the data is not stored.

I tried switching to browser.storage but I'm getting the same results.  Is this a bug or is the byte size function I'm using wrong?

Also I'm using lz-string to compress the data to try and increase my storage.

```<code>tmp = JSON.stringify(tmp);
tmpAsString = LZString.compressToUTF16(tmp);

var compresskey = 'compressedJSExtension';
try {
    chrome.storage.local.set({[compresskey] : tmp }, function () {
        if (chrome.runtime.lastError) console.error(chrome.runtime.lastError);
    });
}
catch (f) {
    //Handle if the string is over 1mB

}
</code>```

答:
According to the Extension API Roadmap (https://learn.microsoft.com/en-us/microsoft-edge/extensions/api-support/extension-api-roadmap), Microsoft Edge supports the unlimitedStorage permission in builds 14986 and above (currently only available to Windows Insiders, though it will be available publicly once the Windows 10 Creators Update launches). Using this should let you get around the 1MB size limitations, but since Edge's namespace is browser, you'll have to change the above code to browser.storage.local

If you need to sign up for the Windows Insider Preview program, you can do so here: https://insider.windows.com

Body:
Porting an existing extension from chrome to edge and I'm having issues with the 1mb limit on chrome.storage.local.  I used the function in this topic String length in bytes in JavaScript to find he size of the string and found if the json string is over 1mB it will throw a "over 1mB" exception, but if the json string was between 250kB and 1mB I get a message in chrome.runtime.lastError saying the data is over 1mB, no exception is thrown and the data is not stored.

I tried switching to browser.storage but I'm getting the same results.  Is this a bug or is the byte size function I'm using wrong?

Also I'm using lz-string to compress the data to try and increase my storage.

tmp = JSON.stringify(tmp);
tmpAsString = LZString.compressToUTF16(tmp);

var compresskey = 'compressedJSExtension';
try {
    chrome.storage.local.set({[compresskey] : tmp }, function () {
        if (chrome.runtime.lastError) console.error(chrome.runtime.lastError);
    });
}
catch (f) {
    //Handle if the string is over 1mB

}


问:
sort array of objects by defined list of values
Ok, I am sure that this has already been answered somewhere and I apologise for posting such a fundamental question, but I can't seem to find the answer anywhere... I'm only just dipping my big toe into php for the first time and spend most of my time in Javascript, so be nice to me :-)

I have an array of objects that is of the structure:

```<code>[
  {
    title: 'one',
    type: 'cat'
  },
  {
    title: 'two',
    type: 'dog'
  },
  {
    title: 'three',
    type: 'snake'
  },
  {
    title: 'four',
    type: 'dog'
  }
]
</code>```

And I'd like to order them in the order ['dog', 'snake', 'cat] so I get:

```<code>[
  {
    title: 'two',
    type: 'dog'
  }
  {
    title: 'four',
    type: 'dog'
  },
  {
    title: 'three',
    type: 'snake'
  },
  {
    title: 'one',
    type: 'cat'
  }
]
</code>```

How do I do this?

答:
PHP code demo

```<code><?php
ini_set("display_errors", 1);
$json ='[
  {
    "title": "one",
    "type": "cat"
  },
  {
    "title": "two",
    "type": "dog"
  },
  {
    "title": "three",
    "type": "snake"
  },
  {
    "title": "four",
    "type": "dog"
  }
]';
$dataArray=json_decode($json,true);
$sortFormat=['dog', 'snake', 'cat'];
$result=array();
while(count($dataArray)>0)
{
    foreach($sortFormat as $object)
    {
        foreach($dataArray as $key => $objectData)
        {
            if($objectData["type"]==$object)
            {
                $result[]=$objectData;
                unset($dataArray[$key]);
            }
        }
    }
}
print_r($result);
</code>```

Output:

```<code>Array
(
    [0] => Array
        (
            [title] => two
            [type] => dog
        )

    [1] => Array
        (
            [title] => four
            [type] => dog
        )

    [2] => Array
        (
            [title] => three
            [type] => snake
        )

    [3] => Array
        (
            [title] => one
            [type] => cat
        )

)
</code>```

Body:
Ok, I am sure that this has already been answered somewhere and I apologise for posting such a fundamental question, but I can't seem to find the answer anywhere... I'm only just dipping my big toe into php for the first time and spend most of my time in Javascript, so be nice to me :-)

I have an array of objects that is of the structure:

[
  {
    title: 'one',
    type: 'cat'
  },
  {
    title: 'two',
    type: 'dog'
  },
  {
    title: 'three',
    type: 'snake'
  },
  {
    title: 'four',
    type: 'dog'
  }
]

And I'd like to order them in the order ['dog', 'snake', 'cat] so I get:

[
  {
    title: 'two',
    type: 'dog'
  }
  {
    title: 'four',
    type: 'dog'
  },
  {
    title: 'three',
    type: 'snake'
  },
  {
    title: 'one',
    type: 'cat'
  }
]

How do I do this?

Body:
PHP code demo

<?php
ini_set("display_errors", 1);
$json ='[
  {
    "title": "one",
    "type": "cat"
  },
  {
    "title": "two",
    "type": "dog"
  },
  {
    "title": "three",
    "type": "snake"
  },
  {
    "title": "four",
    "type": "dog"
  }
]';
$dataArray=json_decode($json,true);
$sortFormat=['dog', 'snake', 'cat'];
$result=array();
while(count($dataArray)>0)
{
    foreach($sortFormat as $object)
    {
        foreach($dataArray as $key => $objectData)
        {
            if($objectData["type"]==$object)
            {
                $result[]=$objectData;
                unset($dataArray[$key]);
            }
        }
    }
}
print_r($result);

Output:

Array
(
    [0] => Array
        (
            [title] => two
            [type] => dog
        )

    [1] => Array
        (
            [title] => four
            [type] => dog
        )

    [2] => Array
        (
            [title] => three
            [type] => snake
        )

    [3] => Array
        (
            [title] => one
            [type] => cat
        )

)


问:
Set discount based on number of orders in WooCommerce
In WooCommerce, how to set discount based on number of order?

For example I would like to apply a discount based on customer orders:

first order discount $50

second order discount $30

third order discount $10?

I've search internet but not found any solution or plugins available.

Thanks.

答:
Here is a custom function hooked in woocommerce_cart_calculate_fees that will add to cart a custom discount based on customer orders count, this way:

```<code>add_action('woocommerce_cart_calculate_fees' , 'discount_based_on_customer_orders', 10, 1);
function discount_based_on_customer_orders( $cart_object ){

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Getting "completed" customer orders
    $customer_orders = get_posts( array(
        'numberposts' => -1,
        'meta_key'    => '_customer_user',
        'meta_value'  => get_current_user_id(),
        'post_type'   => 'shop_order', // WC orders post type
        'post_status' => 'wc-completed' // Only orders with status "completed"
    ) );

    // Orders count
    $customer_orders_count = count($customer_orders);

    // The cart total
    $cart_total = WC()->cart->get_total(); // or WC()->cart->get_total_ex_tax()

    // First customer order
    if( empty($customer_orders) || $customer_orders_count == 0 ){
        $discount_text = __('First Order Discount', 'woocommerce');
        $discount = -50;
    }
    // 2nd orders discount
    elseif( $customer_orders_count == 1 ){
        $discount_text = __('2nd Order Discount', 'woocommerce');
        $discount = -30;
    }
    // 3rd orders discount
    elseif( $customer_orders_count == 2 ){
        $discount_text = __('3rd Order Discount', 'woocommerce');
        $discount = -10;
    }

    // Apply discount
    if( ! empty( $discount ) ){
        // Note: Last argument is related to applying the tax (false by default)
        $cart_object->add_fee( $discount_text, $discount, false);
    }
}
</code>```

The Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.

The only problem can be if customer is not logged in.

You may add, at the beginning, in first condition ! is_user_logged_in() this way:

```<code>    if ( is_admin() && ! defined( 'DOING_AJAX' ) && ! is_user_logged_in() )
        return;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is a custom function hooked in woocommerce_cart_calculate_fees that will add to cart a custom discount based on customer orders count, this way:

add_action('woocommerce_cart_calculate_fees' , 'discount_based_on_customer_orders', 10, 1);
function discount_based_on_customer_orders( $cart_object ){

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Getting "completed" customer orders
    $customer_orders = get_posts( array(
        'numberposts' => -1,
        'meta_key'    => '_customer_user',
        'meta_value'  => get_current_user_id(),
        'post_type'   => 'shop_order', // WC orders post type
        'post_status' => 'wc-completed' // Only orders with status "completed"
    ) );

    // Orders count
    $customer_orders_count = count($customer_orders);

    // The cart total
    $cart_total = WC()->cart->get_total(); // or WC()->cart->get_total_ex_tax()

    // First customer order
    if( empty($customer_orders) || $customer_orders_count == 0 ){
        $discount_text = __('First Order Discount', 'woocommerce');
        $discount = -50;
    }
    // 2nd orders discount
    elseif( $customer_orders_count == 1 ){
        $discount_text = __('2nd Order Discount', 'woocommerce');
        $discount = -30;
    }
    // 3rd orders discount
    elseif( $customer_orders_count == 2 ){
        $discount_text = __('3rd Order Discount', 'woocommerce');
        $discount = -10;
    }

    // Apply discount
    if( ! empty( $discount ) ){
        // Note: Last argument is related to applying the tax (false by default)
        $cart_object->add_fee( $discount_text, $discount, false);
    }
}

The Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.

The only problem can be if customer is not logged in.

You may add, at the beginning, in first condition ! is_user_logged_in() this way:

    if ( is_admin() && ! defined( 'DOING_AJAX' ) && ! is_user_logged_in() )
        return;


问:
About Removing Malware Scripts
I am working on a php website and it gets regularly infected by Malware. I've gone through all the security steps but failed. But I know how it every time infect my code. It comes at the starting of my php index file as following.

```<code><script>.....</script><?
</code>```

Can anybody please help me how can I remove the starting block code of every index file at my server folders? I will use a cron for this.

I already gone through regex question for removal of javascript malware but did not found what I want.

答: Don't look for the pattern that tells you it is malware, just patch all your software, close unused ports, follow what people told you here already instead of trying to clean the code with regex or signatures...</p>

Title: About Removing Malware Scripts

Body:
I am working on a php website and it gets regularly infected by Malware. I've gone through all the security steps but failed. But I know how it every time infect my code. It comes at the starting of my php index file as following.

<?

Can anybody please help me how can I remove the starting block code of every index file at my server folders? I will use a cron for this.

I already gone through regex question for removal of javascript malware but did not found what I want.


问:
How to format the date in HTML in dd-MM-YYYY format using ng-model
I would like to format the date in HTML as dd-mm-yyyy format in ng-model but the result which I am getting is in the form of mm-dd-yyyy.I have tried using interpolator where it worked fine and I would like to know to get the output in a dd-mm-yyyy format in HTML itself using ng-model.</p>

```<code><label class="item item-input">
  <input placeholder="Date" type="date" date="dd-MM-yyyy" ng-model="vm.advance.date"></input>
</label>
</code>```

答:
angular.module('app', ['ui.bootstrap']).controller('MyController', function() {
    this.advance = {
       date: new Date()
    };
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>
  <link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

<body ng-app="app">
  <div ng-controller="MyController as vm">
    <label class="item item-input">
        <input ng-model="vm.advance.date" ng-value="vm.advance.date | date : 'dd-MM-yyyy'" ng-disabled="true"/>
    </label>
    <p class="input-group">
        <input type="text" class="form-control" is-open="vm.opened" ng-model="vm.advance.date" uib-datepicker-popup="dd-MM-yyyy" ng-required="true" />
        <span class="input-group-btn">
            <button type="button" class="btn btn-default" ng-click="vm.opened = true"><i class="glyphicon glyphicon-calendar"></i></button>
        </span>
    </p>
  </div>
</body></code>```

Body:
I would like to format the date in HTML as dd-mm-yyyy format in ng-model but the result which I am getting is in the form of mm-dd-yyyy.I have tried using interpolator where it worked fine and I would like to know to get the output in a dd-mm-yyyy format in HTML itself using ng-model.

  <input placeholder="Date" type="date" date="dd-MM-yyyy" ng-model="vm.advance.date"></input>

Body:
angular.module('app', ['ui.bootstrap']).controller('MyController', function() {
    this.advance = {
       date: new Date()
    };
})

<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>
  <link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

<body ng-app="app">
  <div ng-controller="MyController as vm">
    <label class="item item-input">
        <input ng-model="vm.advance.date" ng-value="vm.advance.date | date : 'dd-MM-yyyy'" ng-disabled="true"/>
    </label>
    <p class="input-group">
        <input type="text" class="form-control" is-open="vm.opened" ng-model="vm.advance.date" uib-datepicker-popup="dd-MM-yyyy" ng-required="true" />
        <span class="input-group-btn">
            <button type="button" class="btn btn-default" ng-click="vm.opened = true"><i class="glyphicon glyphicon-calendar"></i></button>
        </span>
    </p>
  </div>
</body>


问:
Using jquery, how to populate my table rows with matching pictures using img src="javascript:?
Consider I have a table, like below, that I am trying to populate with many jpegs for each row, like say BillSmith.jpg and NancyClinton.jpg.

Example Table to be populated with pics:

NY | Smith, Bill (trying to put 'BillSmith.jpg' here)

NY | Clinton, Nancy (trying to put 'NancyClinton.jpg' here)

I am confused with what to put after this part <img src="javascript: in the 2nd to last line of the below code snippet.

```<code>$("#html_table tbody td:nth-child(2)").each(function(){
        var the_name = $(this).html();

        // Creates the string of file names ( BillSmith.jpg ) matching the file names of jpeg pics

        var nameList = the_name.split(",");
        var firstLast = nameList[1] + nameList[0];
        var source_foto = "staff_jpegs/"+firstLast+".jpg";

        $(this).html( the_name +'<br><div class="fotos" style="text-align:center"><img src="javascript:source_foto" height="80" width="80"/></div>');
        });
</code>```

The above code doesnt work because I am assuming a function not a variable can only be after javascript: .

Looking the easy way to get many fotos into their corresponding table rows using more or less this structure.

答: ```<code>$(this).html( the_name +'<br><div class="fotos" style="text-align:center"><img src="'+ source_foto +'" height="80" width="80"/></div>');```</code></p>

ContentLicense: CC BY-SA 2.5

Body:
Consider I have a table, like below, that I am trying to populate with many jpegs for each row, like say BillSmith.jpg and NancyClinton.jpg.

Example Table to be populated with pics:

NY | Smith, Bill (trying to put 'BillSmith.jpg' here)

NY | Clinton, Nancy (trying to put 'NancyClinton.jpg' here)

I am confused with what to put after this part <img src="javascript: in the 2nd to last line of the below code snippet.

$("#html_table tbody td:nth-child(2)").each(function(){
        var the_name = $(this).html();

        // Creates the string of file names ( BillSmith.jpg ) matching the file names of jpeg pics

        var nameList = the_name.split(",");
        var firstLast = nameList[1] + nameList[0];
        var source_foto = "staff_jpegs/"+firstLast+".jpg";

        $(this).html( the_name +'

');
        });

The above code doesnt work because I am assuming a function not a variable can only be after javascript: .

Looking the easy way to get many fotos into their corresponding table rows using more or less this structure.


答:
You could to use value with filter:

```<code>{{vm.advance.date | date:'dd-MM-yyyy'}}
</code>```

Actual better to use datepicker for it. There is more flexiable tools for it.

Title: How to format the date in HTML in dd-MM-YYYY format using ng-model

Body:
You could to use value with filter:

{{vm.advance.date | date:'dd-MM-yyyy'}}

Actual better to use datepicker for it. There is more flexiable tools for it.


问:
What C datatype should be used for an array which will contain 2-digit HEXADECIMAL values?
I have the following array in a program I am trying to debug:

```<code>static u8 info3[LEN] = {
  06,
  07,
  04,
  00,
  00,
  01,
  00,
  0e,
  03
};
</code>```

and I am getting the following error:

```<code>test.c(45): error C2021: expected exponent value, not ','
</code>```

and line#45 is the line containing 0e,. According to this MSDN resource,

expected exponent value, not 'character'

The character used as the exponent of a floating-point constant is not
  a valid number. Be sure to use an exponent that is in range.

This tells me that the compiler thinks that the compiler thinks that info3 contains Floating Point values. But the values there are actually 2-digit hexadecimal numbers.

So the question is that which datatype should be used here for the values stored in this array?

答:
In C any constant preceded by 0 is an octal constant.  So, 015 is octal 15 and is decimal 13. Also 08 is invalid as no octal no can have a value greater than 8.

If you want hexadecimal constants, you should use 0x08, 0x0a etc.

Body:
I have the following array in a program I am trying to debug:

static u8 info3[LEN] = {
  06,
  07,
  04,
  00,
  00,
  01,
  00,
  0e,
  03
};

and I am getting the following error:

test.c(45): error C2021: expected exponent value, not ','

and line#45 is the line containing 0e,. According to this MSDN resource,

expected exponent value, not 'character'

The character used as the exponent of a floating-point constant is not
  a valid number. Be sure to use an exponent that is in range.

This tells me that the compiler thinks that the compiler thinks that info3 contains Floating Point values. But the values there are actually 2-digit hexadecimal numbers.

So the question is that which datatype should be used here for the values stored in this array?


问:
How to send selected cell to another view controller?
Hey guys so I'm working on an application where I have imported a contacts list from my device and I am given the option to "add" the contact but it really doesn't do much when it comes to functionality. I'm not the best coder so try to hear me out. what I am trying to do is take the data/ selected table view cell and display it on another page. I "think" that this is what I should do because I have tried to display the data on another page but get an error when I move my OVERRIDE function. that makes me believe that I need to take the data, which I believe is newContact? and set that as a variable and then display it on a new page where I can create a new view controller and add the code without error.

I essentially need to figure out what my JSON data is saved as, then set that equivalent to a string if that is possible, so I can send it to my new view controller or and send it to my database with code I already have created.

I am just not sure where to enter the statements because of errors that I am getting and what the exact code would be.

Sorry for the awful description of what I am trying to perform, I have a grasp of what is needed to be done but I am a beginner.

My Master View Controller that takes the contacts from my phone and accesses them.

```<code>import UIKit
import Contacts
import ContactsUI

class MainViewController: UIViewController {

@IBOutlet weak var textField: UITextField!
@IBOutlet weak var tableView: UITableView!

var store = CNContactStore()
var contacts: [CNContact] = []

override func viewDidLoad() {
    super.viewDidLoad()
}

//MARK: - User Actions

@IBAction func contactListPressed(_ sender: AnyObject) {
    let contactPickerViewController = CNContactPickerViewController()
    contactPickerViewController.delegate = self
    present(contactPickerViewController, animated: true, completion:      nil)
}

@IBAction func addContactPressed(_ sender: AnyObject) {
    let newContact = CNMutableContact()

    newContact.givenName = "Apps"
    newContact.familyName = "Foundations"
    newContact.nickname = "AF"

    if let image = UIImage(named: "logo-apps-foundation.jpg"),
        let data = UIImagePNGRepresentation(image){
        newContact.imageData = data
    }

    let phone = CNLabeledValue(label: CNLabelWork, value:   CNPhoneNumber(stringValue: "+441234567890"))
    newContact.phoneNumbers = [phone]

    let email = "" //Your Input goes here
    let Email = CNLabeledValue(label:CNLabelWork, value: email as NSString)
    newContact.emailAddresses = [Email]

    newContact.jobTitle = "Apps Foundation"
    newContact.organizationName = "Apps Foundation"
    newContact.departmentName = "IT"

    let facebookProfile = CNLabeledValue(label: "Facebook", value:   CNSocialProfile(urlString: "https://www.facebook.com/appsfoundation", username: "AppsFoundation", userIdentifier: "appsfoundation", service: CNSocialProfileServiceFacebook))
    let twitterProfile = CNLabeledValue(label: "Twitter", value: CNSocialProfile(urlString: "https://twitter.com/AppsFoundation", username: "AppsFoundation", userIdentifier: "appsfoundation", service: CNSocialProfileServiceTwitter))
    newContact.socialProfiles = [facebookProfile, twitterProfile]

    let skypeProfile = CNLabeledValue(label: "Skype", value: CNInstantMessageAddress(username: "AppsFoundation", service: CNInstantMessageServiceSkype))
    newContact.instantMessageAddresses = [skypeProfile]

    var birthday = DateComponents()
    birthday.year = 1991
    birthday.month = 1
    birthday.day = 1
    newContact.birthday = birthday

    let request = CNSaveRequest()
    request.add(newContact, toContainerWithIdentifier: nil)
    do {
        try store.execute(request)
        let alert = UIAlertController(title: "Contacts iOS 9", message: "New contact has been created", preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        present(alert, animated: true, completion: nil)
    } catch let error{
        print(error)
    }
}

@IBAction func textFieldValueChanged(_ sender: AnyObject) {
    if let query = textField.text {
        findContactsWithName(query)
    }
}

//MARK: - Private Methods

func findContactsWithName(_ name: String) {
    AppDelegate.sharedDelegate().checkAccessStatus({ (accessGranted) -> Void in
        if accessGranted {
            DispatchQueue.main.async(execute: { () -> Void in
                do {
                    let predicate: NSPredicate = CNContact.predicateForContacts(matchingName: name)
                    let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactBirthdayKey, CNContactViewController.descriptorForRequiredKeys()] as [Any]
                    self.contacts = try self.store.unifiedContacts(matching: predicate, keysToFetch:keysToFetch as! [CNKeyDescriptor])
                    self.tableView.reloadData()
                }
                catch {
                    print("Unable to refetch the selected contact.")
                }
            })
        }
    })
}

func updateContact(_ contactIdentifier: String) {
    do {
        let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactBirthdayKey, CNContactPhoneNumbersKey, CNContactViewController.descriptorForRequiredKeys()] as [Any]
        let contact = try store.unifiedContact(withIdentifier:  contactIdentifier, keysToFetch:keysToFetch as! [CNKeyDescriptor])

        let contactToUpdate = contact.mutableCopy() as! CNMutableContact
        contactToUpdate.phoneNumbers = [CNLabeledValue(label: CNLabelWork, value: CNPhoneNumber(stringValue: "+440987654321"))]

        let saveRequest = CNSaveRequest()
        saveRequest.update(contactToUpdate)
        try store.execute(saveRequest)
    } catch let error{
        print(error)
    }
}

}

 //MARK: - UITableViewDataSource

extension MainViewController: CNContactPickerDelegate {

func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
    let selectedContactID = contact.identifier
    updateContact(selectedContactID)
}

}

 //MARK: - UITableViewDataSource

    extension MainViewController: UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return contacts.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let CellIdentifier = "MyCell"
    let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier)
    cell!.textLabel!.text = contacts[indexPath.row].givenName + " " + contacts[indexPath.row].familyName

    if let birthday = contacts[indexPath.row].birthday {
        let formatter = DateFormatter()
        formatter.dateStyle = DateFormatter.Style.long
        formatter.timeStyle = .none

        cell!.detailTextLabel?.text = formatter.string(from: ((birthday as NSDateComponents).date)!)
    }
    return cell!
}

 }

//MARK: - UITableViewDelegate

 extension MainViewController: UITableViewDelegate {

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let controller = CNContactViewController(for: contacts[indexPath.row])
    controller.contactStore = self.store
    controller.allowsEditing = false
    self.navigationController?.pushViewController(controller, animated: true)
}

}
</code>```

I know I need to incorporate something like this but I am not sure where or how to set the JSON data to a variable or the correct type and then incorporate code of this type

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
    if let indexPath = self.tableView.indexPathForSelectedRow {
        let controller = segue.destination as! ViewControllerB
        controller.selectedName = objects[indexPath.row]
    }
}
}
</code>```

sorry for the awful explanation. any help possible would be appreciated, I have been struggling for quite some time.

答:
First of all, you need to have the other view controller that you are trying to pass data to. It can either be on the Interface Builder or done programmatically (I'll assume it's on the IB for now). Then you'll need to setup a segue between the Main VC and the Details VC and give it an identifier e.g. showDetail.

Next would be to determine the data that Details VC needs for it to work properly. You can have individual variables for each data item (e.g. name, age, phone, email, etc) but usually if there is a lot of info, it's best to use a data model. In your case, since you are trying to display contact info, you can simply reuse CNContact.

So you simply need a CNContact in your Details VC that you'll set before transitioning from Main VC in the prepareForSegue function. And to initiate the segue, all you have to do is call performSegue function.

Hope that at least gives you some direction

Body:
Hey guys so I'm working on an application where I have imported a contacts list from my device and I am given the option to "add" the contact but it really doesn't do much when it comes to functionality. I'm not the best coder so try to hear me out. what I am trying to do is take the data/ selected table view cell and display it on another page. I "think" that this is what I should do because I have tried to display the data on another page but get an error when I move my OVERRIDE function. that makes me believe that I need to take the data, which I believe is newContact? and set that as a variable and then display it on a new page where I can create a new view controller and add the code without error.

I essentially need to figure out what my JSON data is saved as, then set that equivalent to a string if that is possible, so I can send it to my new view controller or and send it to my database with code I already have created.

I am just not sure where to enter the statements because of errors that I am getting and what the exact code would be.

Sorry for the awful description of what I am trying to perform, I have a grasp of what is needed to be done but I am a beginner.

My Master View Controller that takes the contacts from my phone and accesses them.

import UIKit
import Contacts
import ContactsUI

class MainViewController: UIViewController {

@IBOutlet weak var textField: UITextField!
@IBOutlet weak var tableView: UITableView!

var store = CNContactStore()
var contacts: [CNContact] = []

override func viewDidLoad() {
    super.viewDidLoad()
}

//MARK: - User Actions

@IBAction func contactListPressed(_ sender: AnyObject) {
    let contactPickerViewController = CNContactPickerViewController()
    contactPickerViewController.delegate = self
    present(contactPickerViewController, animated: true, completion:      nil)
}

@IBAction func addContactPressed(_ sender: AnyObject) {
    let newContact = CNMutableContact()

    newContact.givenName = "Apps"
    newContact.familyName = "Foundations"
    newContact.nickname = "AF"

    if let image = UIImage(named: "logo-apps-foundation.jpg"),
        let data = UIImagePNGRepresentation(image){
        newContact.imageData = data
    }

    let phone = CNLabeledValue(label: CNLabelWork, value:   CNPhoneNumber(stringValue: "+441234567890"))
    newContact.phoneNumbers = [phone]

    let email = "" //Your Input goes here
    let Email = CNLabeledValue(label:CNLabelWork, value: email as NSString)
    newContact.emailAddresses = [Email]

    newContact.jobTitle = "Apps Foundation"
    newContact.organizationName = "Apps Foundation"
    newContact.departmentName = "IT"

    let facebookProfile = CNLabeledValue(label: "Facebook", value:   CNSocialProfile(urlString: "https://www.facebook.com/appsfoundation", username: "AppsFoundation", userIdentifier: "appsfoundation", service: CNSocialProfileServiceFacebook))
    let twitterProfile = CNLabeledValue(label: "Twitter", value: CNSocialProfile(urlString: "https://twitter.com/AppsFoundation", username: "AppsFoundation", userIdentifier: "appsfoundation", service: CNSocialProfileServiceTwitter))
    newContact.socialProfiles = [facebookProfile, twitterProfile]

    let skypeProfile = CNLabeledValue(label: "Skype", value: CNInstantMessageAddress(username: "AppsFoundation", service: CNInstantMessageServiceSkype))
    newContact.instantMessageAddresses = [skypeProfile]

    var birthday = DateComponents()
    birthday.year = 1991
    birthday.month = 1
    birthday.day = 1
    newContact.birthday = birthday

    let request = CNSaveRequest()
    request.add(newContact, toContainerWithIdentifier: nil)
    do {
        try store.execute(request)
        let alert = UIAlertController(title: "Contacts iOS 9", message: "New contact has been created", preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        present(alert, animated: true, completion: nil)
    } catch let error{
        print(error)
    }
}

@IBAction func textFieldValueChanged(_ sender: AnyObject) {
    if let query = textField.text {
        findContactsWithName(query)
    }
}

//MARK: - Private Methods

func findContactsWithName(_ name: String) {
    AppDelegate.sharedDelegate().checkAccessStatus({ (accessGranted) -> Void in
        if accessGranted {
            DispatchQueue.main.async(execute: { () -> Void in
                do {
                    let predicate: NSPredicate = CNContact.predicateForContacts(matchingName: name)
                    let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactBirthdayKey, CNContactViewController.descriptorForRequiredKeys()] as [Any]
                    self.contacts = try self.store.unifiedContacts(matching: predicate, keysToFetch:keysToFetch as! [CNKeyDescriptor])
                    self.tableView.reloadData()
                }
                catch {
                    print("Unable to refetch the selected contact.")
                }
            })
        }
    })
}

func updateContact(_ contactIdentifier: String) {
    do {
        let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactBirthdayKey, CNContactPhoneNumbersKey, CNContactViewController.descriptorForRequiredKeys()] as [Any]
        let contact = try store.unifiedContact(withIdentifier:  contactIdentifier, keysToFetch:keysToFetch as! [CNKeyDescriptor])

        let contactToUpdate = contact.mutableCopy() as! CNMutableContact
        contactToUpdate.phoneNumbers = [CNLabeledValue(label: CNLabelWork, value: CNPhoneNumber(stringValue: "+440987654321"))]

        let saveRequest = CNSaveRequest()
        saveRequest.update(contactToUpdate)
        try store.execute(saveRequest)
    } catch let error{
        print(error)
    }
}

}

 //MARK: - UITableViewDataSource

extension MainViewController: CNContactPickerDelegate {

func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
    let selectedContactID = contact.identifier
    updateContact(selectedContactID)
}

}

 //MARK: - UITableViewDataSource

    extension MainViewController: UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return contacts.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let CellIdentifier = "MyCell"
    let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier)
    cell!.textLabel!.text = contacts[indexPath.row].givenName + " " + contacts[indexPath.row].familyName

    if let birthday = contacts[indexPath.row].birthday {
        let formatter = DateFormatter()
        formatter.dateStyle = DateFormatter.Style.long
        formatter.timeStyle = .none

        cell!.detailTextLabel?.text = formatter.string(from: ((birthday as NSDateComponents).date)!)
    }
    return cell!
}

 }

//MARK: - UITableViewDelegate

 extension MainViewController: UITableViewDelegate {

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let controller = CNContactViewController(for: contacts[indexPath.row])
    controller.contactStore = self.store
    controller.allowsEditing = false
    self.navigationController?.pushViewController(controller, animated: true)
}

}

I know I need to incorporate something like this but I am not sure where or how to set the JSON data to a variable or the correct type and then incorporate code of this type

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
    if let indexPath = self.tableView.indexPathForSelectedRow {
        let controller = segue.destination as! ViewControllerB
        controller.selectedName = objects[indexPath.row]
    }
}
}

sorry for the awful explanation. any help possible would be appreciated, I have been struggling for quite some time.


问:
Mongoose using subquery in aggregation to sum data
I am new in mongoose. I have model like this.

```<code>var ForumSchema = new mongoose.Schema({
User_id             : {type : Schema.Types.ObjectId, ref : 'User'},
Title               : {type : String},
Content             : {type : String},
Tags                : [{type : String}],
isPublic            : {type : Boolean, default : false},
Vote                : [{
    User_id         : {type : Schema.Types.ObjectId, ref : 'User'},
    Kind            : {type : Boolean}
}],
Rate                : [{
    User_id         : {type : Schema.Types.ObjectId, ref : 'User'},
    Count           : {type : Number}
}],
Comment             : [{
    User_id         : {type : Schema.Types.ObjectId, ref : 'User'},
    Content         : String,
    Created_at      : {type : Date, required : true, default : Date.now}
}],
Created_at          : {type : Date, required : true, default : Date.now},
Updated_at          : {type : Date}
</code>```

});

I want to get Forum data with sum of Vote that value is true. Like this json.

```<code>{
[
    _id         : <Some object id>,
    User_id     : <Some object id from User Model>,
    Title       : <Title>,
    Content     : <Content>,
    Tags        : [Some array],
    isPublic    : true,
    UpVote      : 23,
    ....
    ....
    ....
]
</code>```

}

In mysql I can do this by using subquery. How can I do it in mongoose?

答:
you can use aggregate in mongodb

```<code>db.getCollection('forum').aggregate([{
        $unwind: "$Vote"
    },
    {
        $match: {
            "Vote. Kind": true
        }
    },
    {
        $group: {
            _id: '$_id',
            "User_id": {
                '$first': '$User_id'
            },
            "Title": {
                '$first': '$Title'
            },
            UpVote: {
                $sum: 1
            }
        }
    }
])
</code>```

you can use this same query in mongoose also, finally you get number of up votes

Body:
I am new in mongoose. I have model like this.

var ForumSchema = new mongoose.Schema({
User_id             : {type : Schema.Types.ObjectId, ref : 'User'},
Title               : {type : String},
Content             : {type : String},
Tags                : [{type : String}],
isPublic            : {type : Boolean, default : false},
Vote                : [{
    User_id         : {type : Schema.Types.ObjectId, ref : 'User'},
    Kind            : {type : Boolean}
}],
Rate                : [{
    User_id         : {type : Schema.Types.ObjectId, ref : 'User'},
    Count           : {type : Number}
}],
Comment             : [{
    User_id         : {type : Schema.Types.ObjectId, ref : 'User'},
    Content         : String,
    Created_at      : {type : Date, required : true, default : Date.now}
}],
Created_at          : {type : Date, required : true, default : Date.now},
Updated_at          : {type : Date}

});

I want to get Forum data with sum of Vote that value is true. Like this json.

{
[
    _id         : <Some object id>,
    User_id     : <Some object id from User Model>,
    Title       : <Title>,
    Content     : <Content>,
    Tags        : [Some array],
    isPublic    : true,
    UpVote      : 23,
    ....
    ....
    ....
]

}

In mysql I can do this by using subquery. How can I do it in mongoose?

Body:
you can use aggregate in mongodb

db.getCollection('forum').aggregate([{
        $unwind: "$Vote"
    },
    {
        $match: {
            "Vote. Kind": true
        }
    },
    {
        $group: {
            _id: '$_id',
            "User_id": {
                '$first': '$User_id'
            },
            "Title": {
                '$first': '$Title'
            },
            UpVote: {
                $sum: 1
            }
        }
    }
])

you can use this same query in mongoose also, finally you get number of up votes


问:
Insert into same table avoiding duplicate
```<code>Table enrollments
-----------------

id      classId     userId
--      -------     ------
1         1           1
--      -------     ------
</code>```

after this stats: want to reject inserting whenever again inserting { classId=1, userId=1 }

If user inserts same classId and userId then it should rejects inserting.
I've already tried:

```<code>INSERT INTO enrollments(classId, userId)
    VALUES('{$classId}', '{$userId}')
    WHERE
    NOT EXISTS(SELECT NULL FROM
                enrollments WHERE
                    classId='{$classId}' AND userId='{$userId}')
</code>```

答:
```<code>create table enrollments
(
classId int,
userId int
)

ALTER TABLE enrollments
ADD CONSTRAINT UC_Person UNIQUE (classId,userId);

INSERT INTO enrollments(classId, userId)
    VALUES(1, 1);
</code>```

where clause cannot be entered in insert statement, try this code .the above table structure will not be allow to insert  duplicate entry

Body:
Table enrollments
-----------------

id      classId     userId
--      -------     ------
1         1           1
--      -------     ------

after this stats: want to reject inserting whenever again inserting { classId=1, userId=1 }

If user inserts same classId and userId then it should rejects inserting.
I've already tried:

INSERT INTO enrollments(classId, userId)
    VALUES('{$classId}', '{$userId}')
    WHERE
    NOT EXISTS(SELECT NULL FROM
                enrollments WHERE
                    classId='{$classId}' AND userId='{$userId}')

Body:
create table enrollments
(
classId int,
userId int
)

ALTER TABLE enrollments
ADD CONSTRAINT UC_Person UNIQUE (classId,userId);

INSERT INTO enrollments(classId, userId)
    VALUES(1, 1);

where clause cannot be entered in insert statement, try this code .the above table structure will not be allow to insert  duplicate entry


问:
Error incrementing crosstab dataset
I have a data source that is composed of object { groupName, rowName, colName, value }. I'm trying to put the fields row,col,val in a crosstab, separated by group [the group has headers]. A collection of the data objects is being stored as the main datasource.

I'm gettting the error when I try to do this:

```<code>net.sf.jasperreports.engine.JRRuntimeException: Error incrementing crosstab dataset
    net.sf.jasperreports.engine.fill.JRFillCrosstab$JRFillCrosstabDataset.customIncrement(JRFillCrosstab.java:762)
    net.sf.jasperreports.engine.fill.JRFillElementDataset.increment(JRFillElementDataset.java:193)
    net.sf.jasperreports.engine.fill.JRCalculator.calculateVariables(JRCalculator.java:162)
    net.sf.jasperreports.engine.fill.JRVerticalFiller.fillDetail(JRVerticalFiller.java:747)
</code>```

Does anyone have suggestions to why this is happening or how to fix it?

答:
put the CrossTab in the summery section and remove all other Bands to correctly align the CrossTab.
I am working with jasperstudio and this method fixed the issue.</p>

Title: Error incrementing crosstab dataset

Body:
I have a data source that is composed of object { groupName, rowName, colName, value }. I'm trying to put the fields row,col,val in a crosstab, separated by group [the group has headers]. A collection of the data objects is being stored as the main datasource.

I'm gettting the error when I try to do this:

net.sf.jasperreports.engine.JRRuntimeException: Error incrementing crosstab dataset
    net.sf.jasperreports.engine.fill.JRFillCrosstab$JRFillCrosstabDataset.customIncrement(JRFillCrosstab.java:762)
    net.sf.jasperreports.engine.fill.JRFillElementDataset.increment(JRFillElementDataset.java:193)
    net.sf.jasperreports.engine.fill.JRCalculator.calculateVariables(JRCalculator.java:162)
    net.sf.jasperreports.engine.fill.JRVerticalFiller.fillDetail(JRVerticalFiller.java:747)

Does anyone have suggestions to why this is happening or how to fix it?


问:
angularjs ng-change function not fire poperly in html input
```<code><input name="maxSalary" id="MaxSalary" type="number" min="0" class="form-control" ng-model="dp.maximumSalary" ng-change="minMaxSalaryComparision()" />
</code>```

this is my html input. when I add a integer value, its work properly. but if I add 0000 ng-change only fire with first entered 0. this is my java script.

```<code> $scope.minMaxSalaryComparision = function () {
        alert($scope.dp.maximumSalary);
    };
</code>```

any idea?

答:
Use ng-keyup or ng-keydown instead of ng-change

```<code><input name="maxSalary" id="MaxSalary" type="number" min="0" class="form-control" ng-model="dp.maximumSalary" ng-keyup="minMaxSalaryComparision()" />
</code>```

DEMO

angular.module("Demoapp",[])
.controller("Democtrl",function($scope){

 $scope.minMaxSalaryComparision = function () {
        alert($scope.dp.maximumSalary);
    };
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="Demoapp" ng-controller="Democtrl">
 <input  min="0" class="form-control" ng-model="dp.maximumSalary" ng-keyup="minMaxSalaryComparision()" />

</div></code>```

Body:
<input name="maxSalary" id="MaxSalary" type="number" min="0" class="form-control" ng-model="dp.maximumSalary" ng-change="minMaxSalaryComparision()" />

this is my html input. when I add a integer value, its work properly. but if I add 0000 ng-change only fire with first entered 0. this is my java script.

 $scope.minMaxSalaryComparision = function () {
        alert($scope.dp.maximumSalary);
    };

any idea?

Body:
Use ng-keyup or ng-keydown instead of ng-change

<input name="maxSalary" id="MaxSalary" type="number" min="0" class="form-control" ng-model="dp.maximumSalary" ng-keyup="minMaxSalaryComparision()" />

DEMO

angular.module("Demoapp",[])
.controller("Democtrl",function($scope){

 $scope.minMaxSalaryComparision = function () {
        alert($scope.dp.maximumSalary);
    };
})

 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="Demoapp" ng-controller="Democtrl">
 <input  min="0" class="form-control" ng-model="dp.maximumSalary" ng-keyup="minMaxSalaryComparision()" />

</div>


问:
File.Exists returning true for a file that doesn't exist
I'm working on an app that saves a file in Path.GetDirectoryName(FilePath) where FilePath = Application.ExecutablePath that contains some information about licensing. If I run the program from VS it works OK but if I make an installer and install and then run it, the program thinks that the file already exists. I changed my program to show on a message box my FilePath and whether File.Exists(FilePath) returns true or false. So I looked in that path, enabled showing hidden and system files, F5'd several times and nothing. The file doesn't exist, but File.Exists(FilePath) returns true. Any idea why cold this be happening and how can I work around it?

I'm using Windows Vista, Visual Studio 2010, C# and created my installer with VS's Setup Project.

Edit: My path is: C:\Program Files (x86)\Helium\License.xml.

This is part of my code:

```<code>        MessageBox.Show("LicenseFileName: " + LicenseFileName); // LicenseFileName: C:\Program Files (x86)\Helium\License.xml
        System.Diagnostics.Process.Start(LicenseFileName);      // Nothing happens
        MessageBox.Show("File.Exists(LicenseFileName): " + File.Exists(LicenseFileName)); // File.Exists(LicenseFileName): true
</code>```

Forgot to say that I already had the application installed before so the file used to exist. I uninstalled using Control Panel.

答: If you are installing to a system folder, it is possible that Windows file virtualization kicked in and created a per user copy of the files. So your files may be located somewhere in %userprofile%\AppData\Local\VirtualStore folder </p>

Body:
I'm working on an app that saves a file in Path.GetDirectoryName(FilePath) where FilePath = Application.ExecutablePath that contains some information about licensing. If I run the program from VS it works OK but if I make an installer and install and then run it, the program thinks that the file already exists. I changed my program to show on a message box my FilePath and whether File.Exists(FilePath) returns true or false. So I looked in that path, enabled showing hidden and system files, F5'd several times and nothing. The file doesn't exist, but File.Exists(FilePath) returns true. Any idea why cold this be happening and how can I work around it?

I'm using Windows Vista, Visual Studio 2010, C# and created my installer with VS's Setup Project.

Edit: My path is: C:\Program Files (x86)\Helium\License.xml.

This is part of my code:

        MessageBox.Show("LicenseFileName: " + LicenseFileName); // LicenseFileName: C:\Program Files (x86)\Helium\License.xml
        System.Diagnostics.Process.Start(LicenseFileName);      // Nothing happens
        MessageBox.Show("File.Exists(LicenseFileName): " + File.Exists(LicenseFileName)); // File.Exists(LicenseFileName): true

Forgot to say that I already had the application installed before so the file used to exist. I uninstalled using Control Panel.


问:
Phone calls using the mobile network are blocked by your administrator blackberry
BB z10  giving me error of

phone calls using the mobile network are blocked by your administrator

i also try to flash again with this latest firmware with auto loader. How to solve this issue?.

答: I have updated my phone over wifi and its solved my problem.</p>


问:
MongoDB "Unrecognized option: net.ssl.PEMKeyFile"
I'm using MongoDB v3.0.0 with the following configuration file:

```<code>storage:
   dbPath: "/home/vagrant/backend/mongodata"
   engine: wiredTiger

systemLog:
   destination: file
   path: "/home/vagrant/backend/log/mongo.log"
   logAppend: true

net:
   port: 27017
   # Enable the HTTP interface (Defaults to port 28017).
   http:
      enabled: false
   ssl:
      mode: requireSSL
      PEMKeyFile: /home/vagrant/backend/keys/privKeys.pem

security:
   authorization: 'enabled'
</code>```

But when I start it up, I get the following error:

Unrecognized option: net.ssl.PEMKeyFile
try '/home/vagrant/backend/mongo/bin/mongod --help' for more information

It looks like I have it set up pretty much exactly like they recommend in the docs: https://docs.mongodb.com/manual/tutorial/configure-ssl/ . The docs say this is new in mongo 3.0, so it should support this option. It does say certain distributions still don't support it (bizarrely), so I should include that I installed mongo via this: https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.0.0.tgz . The closest info I could find is the MongoDB Download Center saying version 3.0.14 for linux "has been compiled with SSL enabled and dynamically linked. This requires that SSL libraries be installed seperately. See here for more information on installing OpenSSL."

Any idea what might be going wrong here?

答:
Since MongoDB v3.0.x most MongoDB distributions include support for SSL, but not all. As you have figured out, most likely the distribution that you have does not support SSL.

If you're starting a new MongoDB deployment, I would recommend to install the latest stable release, currently at MongoDB v3.4.x which have more (if not all) distributions supporting SSL. See Release Notes for MongoDB 3.4

Body:
I'm using MongoDB v3.0.0 with the following configuration file:

storage:
   dbPath: "/home/vagrant/backend/mongodata"
   engine: wiredTiger

systemLog:
   destination: file
   path: "/home/vagrant/backend/log/mongo.log"
   logAppend: true

net:
   port: 27017
   # Enable the HTTP interface (Defaults to port 28017).
   http:
      enabled: false
   ssl:
      mode: requireSSL
      PEMKeyFile: /home/vagrant/backend/keys/privKeys.pem

security:
   authorization: 'enabled'

But when I start it up, I get the following error:

Unrecognized option: net.ssl.PEMKeyFile
try '/home/vagrant/backend/mongo/bin/mongod --help' for more information

It looks like I have it set up pretty much exactly like they recommend in the docs: https://docs.mongodb.com/manual/tutorial/configure-ssl/ . The docs say this is new in mongo 3.0, so it should support this option. It does say certain distributions still don't support it (bizarrely), so I should include that I installed mongo via this: https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.0.0.tgz . The closest info I could find is the MongoDB Download Center saying version 3.0.14 for linux "has been compiled with SSL enabled and dynamically linked. This requires that SSL libraries be installed seperately. See here for more information on installing OpenSSL."

Any idea what might be going wrong here?


问:
Flashing label in javafx gui
I'm looking to make a label blink in and out ever 0.1 seconds in javafx. The text appears on top of an ImageView gif that is running in the background. How would I go about doing this or if you have any suggestions on the best method?

Thanks

答:
Use a timeline:</p>

```<code>Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(0.05), evt -> label.setVisible(false)),
                                 new KeyFrame(Duration.seconds( 0.1), evt -> label.setVisible(true)));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
</code>```

Title: Flashing label in javafx gui

Body:
Use a timeline:

Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(0.05), evt -> label.setVisible(false)),
                                 new KeyFrame(Duration.seconds( 0.1), evt -> label.setVisible(true)));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();


问:
Vector Map Iteration forward / reverse
I have an ordered set of key/value maps in a vector I'm iterating through.  I know a unique key, and based on that, I need to get the key/value pairs before and after it until I hit a limit.  For instance:

```<code>QVector < QMap < QString, QString > > map;
QMap < QString, QString > temp;

temp.insert("key1", "parent");
map.append(temp);
temp.clear();
temp.insert("key2", "value1");
map.append(temp);
temp.clear();
temp.insert("key3", "value2");
map.append(temp);
temp.clear();
temp.insert("key4", "value3");
map.append(temp);
temp.clear();
temp.insert("key5", "parent");
map.append(temp);
</code>```

Let's say I have a value "key3", and I want to get the key/value pairs before "key3" until "parent" is reached, and after it until "parent" is reached (not including "parent"), how do I do this?  I can't think of an easy way.

```<code>QMap < QString, QString > newMap;

QMap < QString, QString >::iterator i;
for (int i = 0; i < map.size(); ++i) {

     QMap < QString, QString > vectorMap = map.at(i);
     for (j = vectorMap.begin(); j != vectorMap.end(); ++j) {

          if (j.key() == "key3") {

               //set a bool to true and
               //get j.key() and j.value() before and after until "parent" is reached
               newMap.insert(j.key(), j.value());

          }
     }
}
</code>```

The newMap would have key/value pairs ("key2/value1", "key3/value2", "key4/value3");

Edited for what I'm trying now:

```<code>QString selection = "key3";

 //for going backwards, still need to go forward
 for (int i = 0; i < map.size(); ++i) {

    QMap < QString, QString > vectorMap = map.at(i);
    QMapIterator < QString, QString > iter(vectorMap);

    while (iter.hasNext()) {

        iter.next();

        if (iter.key() == selection &&  iter.value() != "parent") {

            do {

                previousText = iter.previous();

                tempMap.insert(iter.key(), iter.value());
                newMap.append(tempMap);
                tempMap.clear();

                qDebug() << "previousText" << previousText;
                iter.previous();

            } while (previousText != "parent");

        }

    }

 }
</code>```

答: How about this: use your map's "find" function (or whatever) to get an iterator that points to the item you're looking for ("key3"). Construct a reverse iterator from that "key3" iterator. In two separate loops advance each of those two iterators until what it points at contains "parent". Within each loop collect the elements as you go.</p>

Title: Vector Map Iteration forward / reverse

Body:
I have an ordered set of key/value maps in a vector I'm iterating through.  I know a unique key, and based on that, I need to get the key/value pairs before and after it until I hit a limit.  For instance:

QVector < QMap < QString, QString > > map;
QMap < QString, QString > temp;

temp.insert("key1", "parent");
map.append(temp);
temp.clear();
temp.insert("key2", "value1");
map.append(temp);
temp.clear();
temp.insert("key3", "value2");
map.append(temp);
temp.clear();
temp.insert("key4", "value3");
map.append(temp);
temp.clear();
temp.insert("key5", "parent");
map.append(temp);

Let's say I have a value "key3", and I want to get the key/value pairs before "key3" until "parent" is reached, and after it until "parent" is reached (not including "parent"), how do I do this?  I can't think of an easy way.

QMap < QString, QString > newMap;

QMap < QString, QString >::iterator i;
for (int i = 0; i < map.size(); ++i) {

     QMap < QString, QString > vectorMap = map.at(i);
     for (j = vectorMap.begin(); j != vectorMap.end(); ++j) {

          if (j.key() == "key3") {

               //set a bool to true and
               //get j.key() and j.value() before and after until "parent" is reached
               newMap.insert(j.key(), j.value());

          }
     }
}

The newMap would have key/value pairs ("key2/value1", "key3/value2", "key4/value3");

Edited for what I'm trying now:

QString selection = "key3";

 //for going backwards, still need to go forward
 for (int i = 0; i < map.size(); ++i) {

    QMap < QString, QString > vectorMap = map.at(i);
    QMapIterator < QString, QString > iter(vectorMap);

    while (iter.hasNext()) {

        iter.next();

        if (iter.key() == selection &&  iter.value() != "parent") {

            do {

                previousText = iter.previous();

                tempMap.insert(iter.key(), iter.value());
                newMap.append(tempMap);
                tempMap.clear();

                qDebug() << "previousText" << previousText;
                iter.previous();

            } while (previousText != "parent");

        }

    }

 }


问:
Contains search using lodash.js
```<code>var codes = [
{id: 1, code: '123'},
{id: 2, code: '14123'},
{id: 3, code: '556'},
{id: 4, code: '71239'},
{id: 5, code: '289'},
];

var filterCodes = _.filter(codes, function (o) {
  return o.code ? _.includes(o.code, '123') : false
});
</code>```

Output will be : '123','14123','71239'

答:
Why even bother with Lodash for this? Also, I think you're missing a map step...

const codes = [{"id":1,"code":"123"},{"id":2,"code":"14123"},{"id":3,"code":"556"},{"id":4,"code":"71239"},{"id":5,"code":"289"}]

const filterCodes = codes
  .filter(o => typeof o.code === 'string' && o.code.includes('123'))
  .map(o => o.code)
console.info(filterCodes)```

Title: Contains search using lodash.js

Body:
var codes = [
{id: 1, code: '123'},
{id: 2, code: '14123'},
{id: 3, code: '556'},
{id: 4, code: '71239'},
{id: 5, code: '289'},
];

var filterCodes = _.filter(codes, function (o) {
  return o.code ? _.includes(o.code, '123') : false
});

Output will be : '123','14123','71239'


问:
Overlay ImageView on Toolbar
I have this code for my custom toolbar:

```<code> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/login_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:src="@drawable/new_logo"
                android:adjustViewBounds="true"
                android:padding="5dp"
                android:id="@+id/app_logo" />

        </android.support.v7.widget.Toolbar>
</code>```

Now it looks like this:

What I need to do is this one:

How will I implement that?

答:
try this: </p>

```<code><RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.Toolbar
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/login_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary"/>

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="90dp"
            android:src="@mipmap/ic_launcher"
            android:layout_centerHorizontal="true"
            android:id="@+id/app_logo" />

    </RelativeLayout>
</code>```

Title: Overlay ImageView on Toolbar

Body:
I have this code for my custom toolbar:

 <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/login_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:src="@drawable/new_logo"
                android:adjustViewBounds="true"
                android:padding="5dp"
                android:id="@+id/app_logo" />

        </android.support.v7.widget.Toolbar>

Now it looks like this:

What I need to do is this one:

How will I implement that?

Body:
try this:

<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.Toolbar
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/login_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary"/>

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="90dp"
            android:src="@mipmap/ic_launcher"
            android:layout_centerHorizontal="true"
            android:id="@+id/app_logo" />

    </RelativeLayout>


问:
On reboot command router resets Openwrt Caos Calmer 15.05
I m using tplink wr841n v11 and made bin(CC-15.05) file for it using source code, but the issue is I m running 1 script, which downloads file and edits chilli file and then I wrote reboot after all happens. After reboot everything changes to default router(like router is reset to default) and when I comment to reboot command, then it changes in files, but then I manually reboots router it automatically resets, all the settings like ssid, lan ip, pppoe settings etc. changes to default one. Plz, help me in this situation
Thanks in advance.</p>

答: Hi and thanks for ur response amine ahd, I got my answer and I found what was the problem. Basically, I had made own luci and there was to many files in /www/cg-bin/ there was no space left and thats why after any command from my gui or manually it works and edit also but when u reboots, it resets router. After deleting files from cgi-bin folder and build again, now it works superb. At a time of building openwrt I gave permission to /etc/ to 777, so no issues for read only file system.</p>


问:
How to find the prime factors of a number in Python?
I just started to open for myself programming in python. I know how to find factors for example of 30. I will get [1,2,3,5,6,10,15,30].
But I need this output 30 = 2 * 3 * 5. Thank you in advance!</p>

答:
Since you're trying to find all prime, unique factors, I'd use the following function:</p>

```<code>def factor(numberToFactor, arr=list()):
    i = 2
    maximum = numberToFactor / 2 + 1
    while i < maximum:
        if numberToFactor % i == 0:
            return factor(numberToFactor/i,arr + [i])
        i += 1
    return list(set(arr + [numberToFactor]))

print(factor(59511555)) # [3, 5, 1747, 757]
</code>```

Body:
Since you're trying to find all prime, unique factors, I'd use the following function:

def factor(numberToFactor, arr=list()):
    i = 2
    maximum = numberToFactor / 2 + 1
    while i < maximum:
        if numberToFactor % i == 0:
            return factor(numberToFactor/i,arr + [i])
        i += 1
    return list(set(arr + [numberToFactor]))

print(factor(59511555)) # [3, 5, 1747, 757]


问:
remove some elements if no children
i need to remove some elements if no children...

this will work...

```<code>$$('*').each(function() {
    ($$(this).text().trim() === '') && $$(this).remove()
});
</code>```

but it will look for all elements... i need to limit to some elements.. so i made this..

```<code>elements.forEach(element => {
    $$(element).each(function() {
        ($$(this).text().trim() === '') && $$(this).remove()
    });
})
</code>```

but it doesn't work..

答:
You can use :empty pseudo selector to collect all the empty elements:

```<code>$(':empty').remove(); // removes all the empty elements
</code>```

If you target some specific elements then either give it a class name and use both in conjuction:

```<code>$('.theClass:empty').remove();
</code>```

Or just use the tagnames of specific elements:

```<code>$('div:empty').remove(); // removes all the empty divs
</code>```

Title: remove some elements if no children

Body:
i need to remove some elements if no children...

this will work...

$$('*').each(function() {
    ($$(this).text().trim() === '') && $$(this).remove()
});

but it will look for all elements... i need to limit to some elements.. so i made this..

elements.forEach(element => {
    $$(element).each(function() {
        ($$(this).text().trim() === '') && $$(this).remove()
    });
})

but it doesn't work..

Body:
You can use :empty pseudo selector to collect all the empty elements:

$(':empty').remove(); // removes all the empty elements

If you target some specific elements then either give it a class name and use both in conjuction:

$('.theClass:empty').remove();

Or just use the tagnames of specific elements:

$('div:empty').remove(); // removes all the empty divs


问:
How to set a Image Button's image xcode aplescript OBJC
I am trying to change an Image Button's image object with this code using applescript.

I have tried this:

property theButton : missing Value

on button_(sender)
set newImage to "example.png"
changeImage(newImage)
end button_

on changeImage(newImage)
set theImage to current application's NSImage's imageNamed_(newImage)
theButton's setImage_(theImage)
end changeImage

答:
First clarify a few things:
Is the button connected properly? Do you want to change the image on click or before? That's what your code says. If you want to change image before do it in IB or in awakeFromNib method.

Is the buttons action linked properly? Either in IB if your on XCode or pure applescript objc:

```<code>theButton's setTarget:me
theButton's setAction:"changeImage:"
</code>```

If linked you may use a log message to see if it works:

```<code>log "works"
</code>```

This should bring you forward - otherwise please post more code

Body:
First clarify a few things:
Is the button connected properly? Do you want to change the image on click or before? That's what your code says. If you want to change image before do it in IB or in awakeFromNib method.

Is the buttons action linked properly? Either in IB if your on XCode or pure applescript objc:

theButton's setTarget:me
theButton's setAction:"changeImage:"

If linked you may use a log message to see if it works:

log "works"

This should bring you forward - otherwise please post more code