问:
Calculate difference between two non-adjacent rows
How can I calculate time difference between two rows in a table, based on a value in another field in the table.
Table (simplified) look like;

```<code>Unit  Date              Status
0001  17.11.2017 09:52  INSPECTED
0001  17.11.2017 09:48  CLEAN
0001  17.11.2017 09:45  CLEANING
0001  17.11.2017 09:43  DIRTY
0001  16.11.2017 14:55  INSPECTED
0001  16.11.2017 14:54  CLEAN
0001  16.11.2017 12:54  CLEANING
0001  16.11.2017 12:22  DIRTY
0001  16.11.2017 12:20  CLEAN
0001  15.11.2017 10:48  CLEAN
0001  15.11.2017 10:27  CLEANING
0001  15.11.2017 09:03  DIRTY
</code>```

Date field is of type DATE, Unit and Status values are from parent tables.

Based on a column Status, I have to calculate difference between status DIRTY and next status CLEAN, for each day and each unit. Example data should produce;

```<code>0001  17.11.2017  00:05
0001  16.11.2017  02:32
0001  15.11.2017  01:45
</code>```

The query is the source for the chart in Oracle APEX.

答:
Try this.</p>

```<code>  SELECT a.unit,
         TRUNC (a.Date_t),
            TO_CHAR (
               EXTRACT (HOUR FROM NUMTODSINTERVAL (a.Date_t - b.Date_t, 'DAY')),
               'FM00')
         || ':'
         || TO_CHAR (
               EXTRACT (
                  MINUTE FROM NUMTODSINTERVAL (a.Date_t - b.Date_t, 'DAY')),
               'FM00')
            diff
    FROM (SELECT *
            FROM yourtable
           WHERE status = 'CLEAN') a
         JOIN (SELECT *
                 FROM yourtable
                WHERE status = 'DIRTY') b
            ON a.unit = b.unit AND TRUNC (a.Date_t) = TRUNC (b.Date_t)
ORDER BY 2 DESC;
</code>```

Body:
How can I calculate time difference between two rows in a table, based on a value in another field in the table.
Table (simplified) look like;

Unit  Date              Status
0001  17.11.2017 09:52  INSPECTED
0001  17.11.2017 09:48  CLEAN
0001  17.11.2017 09:45  CLEANING
0001  17.11.2017 09:43  DIRTY
0001  16.11.2017 14:55  INSPECTED
0001  16.11.2017 14:54  CLEAN
0001  16.11.2017 12:54  CLEANING
0001  16.11.2017 12:22  DIRTY
0001  16.11.2017 12:20  CLEAN
0001  15.11.2017 10:48  CLEAN
0001  15.11.2017 10:27  CLEANING
0001  15.11.2017 09:03  DIRTY

Date field is of type DATE, Unit and Status values are from parent tables.

Based on a column Status, I have to calculate difference between status DIRTY and next status CLEAN, for each day and each unit. Example data should produce;

0001  17.11.2017  00:05
0001  16.11.2017  02:32
0001  15.11.2017  01:45

The query is the source for the chart in Oracle APEX.

Body:
Try this.

  SELECT a.unit,
         TRUNC (a.Date_t),
            TO_CHAR (
               EXTRACT (HOUR FROM NUMTODSINTERVAL (a.Date_t - b.Date_t, 'DAY')),
               'FM00')
         || ':'
         || TO_CHAR (
               EXTRACT (
                  MINUTE FROM NUMTODSINTERVAL (a.Date_t - b.Date_t, 'DAY')),
               'FM00')
            diff
    FROM (SELECT *
            FROM yourtable
           WHERE status = 'CLEAN') a
         JOIN (SELECT *
                 FROM yourtable
                WHERE status = 'DIRTY') b
            ON a.unit = b.unit AND TRUNC (a.Date_t) = TRUNC (b.Date_t)
ORDER BY 2 DESC;


来源: stackexchange

问:
Visual Studio add-in for validating string.Format method
string.Format is a very risky method. There are a lot of thing that could go wrong, without any compilation errors:

```<code>string.Format("{0{", text);
string.Format("{1}", text);
string.Format("(0)", text);
string.Format("{0}", text1, text2);
</code>```

I'm looking for a way to find this problems in compilation time. If I remember correctly, Resharper find some of those errors, but it's too rich for my blood.

答: Resharper will help you identify it But it is very heavy and have to be use with care if you are work on existing application.</p>

ContentLicense: CC BY-SA 2.5

Body:
string.Format is a very risky method. There are a lot of thing that could go wrong, without any compilation errors:

string.Format("{0{", text);
string.Format("{1}", text);
string.Format("(0)", text);
string.Format("{0}", text1, text2);

I'm looking for a way to find this problems in compilation time. If I remember correctly, Resharper find some of those errors, but it's too rich for my blood.


问:
Creating a progressively enhanced form submission experience for clients with non-uniform JS/HTML5 support
I'm a web developer and need help on enabling progressive enhancement.

Background:
I'm dealing with a web app where many users originate from a forward proxy that strips out JS.

Moreover, some users also use browsers that don't support HTML5, or browsers that can't run JS conventionally (e.g. Opera Mini).

Overall, HTML5 has more coverage than JS for this userbase.

Current scenario: Currently, this app uses no JS or HTML5 at all. Form submissions lead to full page refreshes. A typical form simply looks like this:

```<code><form action="{% url 'submit_comment' %}" method="POST">
    {% csrf_token %}
    {{ my_form.comment }}
    <button type="submit">OK</button>
</form>
</code>```

Ignore the {{ }} nomenclature. That's Django syntax and is simply used to render - in this case - a text field where a user can write a comment.

The question: For clients that can support JS or HTML5, how do I progressively enhance the form submission experience?

E.g., there's a section of this app where users leave comments for others to read. Currently, they press a 'reply' button and get redirected to a new page. The code for such a button is simply:

```<code><form action="{% url 'response_page' %}" method="POST">
    {% csrf_token %}
    <input type="hidden" name="comment_id" value="{{ comment_id }}">
    <button type="submit">reply</button>
</form>
</code>```

Now I need the following to happen:

1) If the client supports JS/HTML5, the DOM changes and a text field bound to a form appears right below the button. No refresh takes place.

2) If the client does not support JS/HTML5, the user is redirected to a new page as before.

How would one program this in a way that nothing breaks for unsupported users, and is as lightweight as possible? There's a lot of 'reply' buttons stacked together per page, so performance is critical as well.

I'm hoping there'd be established patterns to handle this kind of a thing. Being a web developer, I'm not privy to those. Would be great to get an illustrative answer.

Note: I'd prefer to do it in HTML5, but open to JS solutions as well - and I prefer plain vanilla JS instead of anything fancier.

答:
This is a very basic answer which prevents the form submission if javascript is available and adds the required input as suggested above.

window.onload = function(){
  var input = document.createElement("input");
  input.type ='text';
  input.name = "comment";
  input.style.display = 'block';
  document.getElementById('myForm').appendChild(input);
  document.getElementById("submit").addEventListener("click", function(event){
    event.preventDefault();
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="http://example.com" method="POST" aria-live="polite" id="myForm">
  <input type="hidden" name="comment_id" value="">
  <button id="submit" type="submit">reply</button>
</form></code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm a web developer and need help on enabling progressive enhancement.

Background:
I'm dealing with a web app where many users originate from a forward proxy that strips out JS.

Moreover, some users also use browsers that don't support HTML5, or browsers that can't run JS conventionally (e.g. Opera Mini).

Overall, HTML5 has more coverage than JS for this userbase.

Current scenario: Currently, this app uses no JS or HTML5 at all. Form submissions lead to full page refreshes. A typical form simply looks like this:

<form action="{% url 'submit_comment' %}" method="POST">
    {% csrf_token %}
    {{ my_form.comment }}
    <button type="submit">OK</button>
</form>

Ignore the {{ }} nomenclature. That's Django syntax and is simply used to render - in this case - a text field where a user can write a comment.

The question: For clients that can support JS or HTML5, how do I progressively enhance the form submission experience?

E.g., there's a section of this app where users leave comments for others to read. Currently, they press a 'reply' button and get redirected to a new page. The code for such a button is simply:

<form action="{% url 'response_page' %}" method="POST">
    {% csrf_token %}
    <input type="hidden" name="comment_id" value="{{ comment_id }}">
    <button type="submit">reply</button>
</form>

Now I need the following to happen:

1) If the client supports JS/HTML5, the DOM changes and a text field bound to a form appears right below the button. No refresh takes place.

2) If the client does not support JS/HTML5, the user is redirected to a new page as before.

How would one program this in a way that nothing breaks for unsupported users, and is as lightweight as possible? There's a lot of 'reply' buttons stacked together per page, so performance is critical as well.

I'm hoping there'd be established patterns to handle this kind of a thing. Being a web developer, I'm not privy to those. Would be great to get an illustrative answer.

Note: I'd prefer to do it in HTML5, but open to JS solutions as well - and I prefer plain vanilla JS instead of anything fancier.

Body:
This is a very basic answer which prevents the form submission if javascript is available and adds the required input as suggested above.

window.onload = function(){
  var input = document.createElement("input");
  input.type ='text';
  input.name = "comment";
  input.style.display = 'block';
  document.getElementById('myForm').appendChild(input);
  document.getElementById("submit").addEventListener("click", function(event){
    event.preventDefault();
  });
}

<form action="http://example.com" method="POST" aria-live="polite" id="myForm">
  <input type="hidden" name="comment_id" value="">
  <button id="submit" type="submit">reply</button>
</form>


问:
Using limit parameter in paginate function
Is it possible to use 'limit' parameter in paginate() function?

I'm trying this:

```<code>$users->where(...)->limit(50)->paginate($page)
</code>```

...and now, if I have 100 users in the database then the response from paginate function will be all 100 users instead of 50 (or number of users defined with limit parameter).

So, my question is: is it possible to implement limit parameter when I use paginate function?

答:
Use LengthAwarePaginator.

Example:

```<code>$total = 50;
$perPage = 10;
$users = $users->where(...)->paginate($page);

$users = new LengthAwarePaginator(
    $users->toArray()['data'],
    $users->total() < $total ? $users->total() : $total,
    $perPage,
    $page
);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Is it possible to use 'limit' parameter in paginate() function?

I'm trying this:

$users->where(...)->limit(50)->paginate($page)

...and now, if I have 100 users in the database then the response from paginate function will be all 100 users instead of 50 (or number of users defined with limit parameter).

So, my question is: is it possible to implement limit parameter when I use paginate function?

Body:
Use LengthAwarePaginator.

Example:

$total = 50;
$perPage = 10;
$users = $users->where(...)->paginate($page);

$users = new LengthAwarePaginator(
    $users->toArray()['data'],
    $users->total() < $total ? $users->total() : $total,
    $perPage,
    $page
);


问:
MySQL Equivalent of RAISERROR
What is the MySQL equivalent of RAISERROR in SQL Server?

```<code>CREATE procedure GetallFiles()
as
begin
if not exists(select files.Files,Users.FirstName,Users.LastName,Users.EmailAddress from files,Users
where files.UserID = Users.UserID)
raiserror('cannot find files records',16,1)
end
begin

select files.Files,Users.firstname,Users.lastname,Users.EmailAddress from files,Users
where files.UserID = Users.UserID
end
return
</code>```

答:
```<code>    SET @s = 'Unknown condition type  !';
    SIGNAL SQLSTATE '45001' SET MESSAGE_TEXT = @s;
</code>```

Title: MySQL Equivalent of RAISERROR

Body:
What is the MySQL equivalent of RAISERROR in SQL Server?

CREATE procedure GetallFiles()
as
begin
if not exists(select files.Files,Users.FirstName,Users.LastName,Users.EmailAddress from files,Users
where files.UserID = Users.UserID)
raiserror('cannot find files records',16,1)
end
begin

select files.Files,Users.firstname,Users.lastname,Users.EmailAddress from files,Users
where files.UserID = Users.UserID
end
return


问:
Xamarin.Forms Master/Detail edge swipe on iOS
There is a difference in the swipe gesture to present the master page (drawer menu) on Android and iOS.
On Android it only swipes from screen edge, while on iOS swipe from any point on the screen does it.
The problem with full-screen swipe is that one of my detail pages is a Map and user can't do any left-to-right scrolls because the master detail gesture overrides the map gesture handler.
I worked around it with a simple check

```<code>IsGestureEnabled = page.DetailPage != MenuItemViewModel.Detail.Map || Device.RuntimePlatform != Device.iOS;
</code>```

Which effectively disables the left menu swipe but what I would really would like to have is a swipe from edge like it happens on Android.

Is there a simple way (i.e. no custom renderers) to do the menu edge swipe on iOS in Xamarin Forms?

答:
Simplest is to get Mr Gestures plug-in, then on Swipe or Panning event open  menu from the root page</p>

```<code>//---------------------------------------------------------
public void ShowMenu()
//---------------------------------------------------------
{
    Debug.WriteLine("Root ShowMenu");
    IsPresented = true;
}
</code>```

Body:
There is a difference in the swipe gesture to present the master page (drawer menu) on Android and iOS.
On Android it only swipes from screen edge, while on iOS swipe from any point on the screen does it.
The problem with full-screen swipe is that one of my detail pages is a Map and user can't do any left-to-right scrolls because the master detail gesture overrides the map gesture handler.
I worked around it with a simple check

IsGestureEnabled = page.DetailPage != MenuItemViewModel.Detail.Map || Device.RuntimePlatform != Device.iOS;

Which effectively disables the left menu swipe but what I would really would like to have is a swipe from edge like it happens on Android.

Is there a simple way (i.e. no custom renderers) to do the menu edge swipe on iOS in Xamarin Forms?

Body:
Simplest is to get Mr Gestures plug-in, then on Swipe or Panning event open  menu from the root page

//---------------------------------------------------------
public void ShowMenu()
//---------------------------------------------------------
{
    Debug.WriteLine("Root ShowMenu");
    IsPresented = true;
}


问:
Azure automation, PowerShell to fetch a file in private blob container
I have an azure blob container set to private. I want to download files in this container using PowerShell.

This is what I put, however it is giving me ResourceNotFound error every time. Even when I put -Credential and my user name/access key. When I switch the container to public access, it always works. So am I missing anything?

```<code>Invoke-WebRequest -Uri $uri -OutFile $filePath
</code>```

答:
Using Invoke-WebRequest is analogous to opening a link in your browser.  It's a legitimate way to download files from Azure Storage, however to do that you'll need the URI to include a SAS (Shared Access Signature), which you'll have to have generated before you use it in your code.  The PowerShell to achieve this is:

```<code>#Download via URI using SAS
$BlobUri = 'https://yourstorageaccount.blob.core.windows.net/yourcontainer/yourfile.txt'
$Sas = '?sv=2015-04-05&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D'
$OutputPath = 'C:\Temp\yourfile.txt'
$FullUri = "$BlobUri$Sas"
(New-Object System.Net.WebClient).DownloadFile($FullUri, $OutputPath)
</code>```

Alternatively, if you have the Azure PowerShell module installed, you can do it without any of that added pain:

```<code># Download via Azure PowerShell
$StorageAccountName = 'yourstorageaccount'
$StorageAccountKey = Get-AzureStorageKey -StorageAccountName $StorageAccountName
$StorageContext = New-AzureStorageContext $StorageAccountName -StorageAccountKey $StorageAccountKey.Primary
$FileName = 'yourfile.txt'
$OutputPath = 'C:\Temp'
$ContainerName  = 'yourcontainer'
Get-AzureStorageBlobContent -Blob $FilebName -Container $ContainerName -Destination $OutputPath -Context $StorageContext
</code>```

Body:
I have an azure blob container set to private. I want to download files in this container using PowerShell.

This is what I put, however it is giving me ResourceNotFound error every time. Even when I put -Credential and my user name/access key. When I switch the container to public access, it always works. So am I missing anything?

Invoke-WebRequest -Uri $uri -OutFile $filePath

Body:
Using Invoke-WebRequest is analogous to opening a link in your browser.  It's a legitimate way to download files from Azure Storage, however to do that you'll need the URI to include a SAS (Shared Access Signature), which you'll have to have generated before you use it in your code.  The PowerShell to achieve this is:

#Download via URI using SAS
$BlobUri = 'https://yourstorageaccount.blob.core.windows.net/yourcontainer/yourfile.txt'
$Sas = '?sv=2015-04-05&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D'
$OutputPath = 'C:\Temp\yourfile.txt'
$FullUri = "$BlobUri$Sas"
(New-Object System.Net.WebClient).DownloadFile($FullUri, $OutputPath)

Alternatively, if you have the Azure PowerShell module installed, you can do it without any of that added pain:

# Download via Azure PowerShell
$StorageAccountName = 'yourstorageaccount'
$StorageAccountKey = Get-AzureStorageKey -StorageAccountName $StorageAccountName
$StorageContext = New-AzureStorageContext $StorageAccountName -StorageAccountKey $StorageAccountKey.Primary
$FileName = 'yourfile.txt'
$OutputPath = 'C:\Temp'
$ContainerName  = 'yourcontainer'
Get-AzureStorageBlobContent -Blob $FilebName -Container $ContainerName -Destination $OutputPath -Context $StorageContext


问:
Does it make sense to modify an object as a whole using one of its behavior? Say inside the assignment operator overloading using this pointer?
I see a question on this operator (What does assignment to *this do (*this = val)?)

but is it logical to modify an object as a whole from within one of its behavior? Does it makes sense in OOP world?

答:
It makes sense when it makes sense from a design perspective.  I'd expect Rect, Size and Point classes, for example, to support assignment.  In this sense, these kinds of types (to me) should behave like plain-old-datatypes (PODs).

But if I was modelling a traffic simulation with cars and trucks, I certainly would not have an assignment operator.  Setting one car to equal another just doesn't make any sense.  I might clone a car (Make a new one that looks just like the another one), but once a car is created it will always be that car.  It can't become another kind of car.

As a further example, consider a Person object:

```<code>class Person
{
private:
    std::string m_Name;
};
</code>```

Would you expect a Person to have an assignment operator?  No.  A Person cannot become another person.  However, what about his name?  Sure!  A Person can change his name, so an assignment operator on the name makes perfect sense.

So to answer your question, it makes sense to do it where it makes sense to do it :)

Body:
It makes sense when it makes sense from a design perspective.  I'd expect Rect, Size and Point classes, for example, to support assignment.  In this sense, these kinds of types (to me) should behave like plain-old-datatypes (PODs).

But if I was modelling a traffic simulation with cars and trucks, I certainly would not have an assignment operator.  Setting one car to equal another just doesn't make any sense.  I might clone a car (Make a new one that looks just like the another one), but once a car is created it will always be that car.  It can't become another kind of car.

As a further example, consider a Person object:

class Person
{
private:
    std::string m_Name;
};

Would you expect a Person to have an assignment operator?  No.  A Person cannot become another person.  However, what about his name?  Sure!  A Person can change his name, so an assignment operator on the name makes perfect sense.

So to answer your question, it makes sense to do it where it makes sense to do it :)


问:
How to decrease the size of the legend in a figure?
The following code plots a figure. The code should work on Matlab >= R2014b. I want to remove the space within the legend. How to do this?

```<code>x = 0:0.5:10;
figure; hold on;
plot(x,sin(x), 'Marker', 'o');
plot(x,cos(x), 'Marker', 's');
[leg, objs] = legend({'sin', 'cos'}, 'Location', 'SouthWest');
line_start_end = [0.01, 0.4];
line_text_step = 0.01;
% for each line, text object, adjust their position in legend
for i = 1:numel(objs)
  if strcmp(get(objs(i), 'Type'), 'line')
    % line object
    if 2 == numel(get(objs(i), 'XData')) % line
      set(objs(i), 'XData', line_start_end);
    else % marker on line
      set(objs(i), 'XData', sum(line_start_end)/2);
    end
  else
    %text object
    text_pos = get(objs(i), 'Position');
    text_pos(1) = line_start_end(2) + line_text_step;
    set(objs(i), 'Position', text_pos);
  end
end
</code>```

See the following result:

What I want is :

答:
As @Sardar Usama suggested, I put my solution here. I hope it is useful for you.

The first answer is nice. However, I finally use the following code to do this task.

```<code>close all

x = 0:0.5:10;
figure; hold on;
ph(1) = plot(x,sin(x), 'Marker', 'o');
ph(2) = plot(x,cos(x), 'Marker', 's');

ax = gca;
ax.Box = 'on';

bx = axes('position', [ax.Position(1:2), 0.3, 0.4], 'Box', 'on', 'XTick', [], 'YTick', []);%, 'Color', [0.8549,0.7020,1.0000]);
cx = axes('position', [ax.Position(1:2), 0.3, 0.4], 'Box', 'on', 'XTick', [], 'YTick', []);%, 'Color', [0.8549,0.5020,1.0000]);

[legb, objsb] = legend(bx, ph, {'sin', 'cos'}, 'Location', 'SouthWest');
[legc, objsc] = legend(cx, ph, {'sin', 'cos'}, 'Location', 'SouthWest');

line_start_end = [0.01, 0.3];
line_text_step = 0.05;

legendshrink(ax.Position(1:2), legb, objsb, bx, line_start_end, line_text_step);
legendshrink(ax.Position(1:2), legc, objsc, cx, line_start_end, line_text_step);

% you need only to adjust cx' position.
cx.Position(1:2) = [ax.Position(1)+ax.Position(3)-cx.Position(3), ax.Position(2)];
legc.Position(1:2) = cx.Position(1:2);
</code>```

where legendshrink is defined as:

```<code>function legendshrink(leg_pos_xy, leg, objs, bx, line_start_end, line_text_step)

% leg_post_xy = ax.Position(1:2);
% [leg, objs] = legend(bx, line_handles, text_cell);
% line_start_end = [0.01, 0.4];
% line_text_step = 0.01;

% for each line, text object, adjust their position in legend
for i = 1:numel(objs)
  if strcmp(get(objs(i), 'Type'), 'line')
    % line object
    if 2 == numel(get(objs(i), 'XData')) % line
      set(objs(i), 'XData', line_start_end);
    else % marker on line
      set(objs(i), 'XData', sum(line_start_end)/2);
    end
  else
    %text object
    text_pos = get(objs(i), 'Position');
    text_pos(1) = line_start_end(2) + line_text_step;
    set(objs(i), 'Position', text_pos);
  end
end

% get minimum possible width and height
legend_width_no_right = 0;
for i = 1:numel(objs)
  % legend margin left
  if strcmp(get(objs(i), 'Type'), 'line')
    if numel(get(objs(i), 'XData')) == 2
      leg_margin_x = get(objs(i), 'XData');
      leg_margin_x = leg_margin_x(1)*leg.Position(3);
    end
  else
    cur_right = get(objs(i), 'Extent');
    cur_right = (cur_right(1)+cur_right(3))*leg.Position(3);
    if cur_right > legend_width_no_right
      legend_width_no_right = cur_right;
    end
  end
end
legend_width  = legend_width_no_right + leg_margin_x;
legend_height = leg.Position(4);

bx.Position = [leg_pos_xy, legend_width, legend_height];
leg.Position(1:2) = bx.Position(1:2);
leg.Box = 'off';

end
</code>```

resulting

Body:
The following code plots a figure. The code should work on Matlab >= R2014b. I want to remove the space within the legend. How to do this?

x = 0:0.5:10;
figure; hold on;
plot(x,sin(x), 'Marker', 'o');
plot(x,cos(x), 'Marker', 's');
[leg, objs] = legend({'sin', 'cos'}, 'Location', 'SouthWest');
line_start_end = [0.01, 0.4];
line_text_step = 0.01;
% for each line, text object, adjust their position in legend
for i = 1:numel(objs)
  if strcmp(get(objs(i), 'Type'), 'line')
    % line object
    if 2 == numel(get(objs(i), 'XData')) % line
      set(objs(i), 'XData', line_start_end);
    else % marker on line
      set(objs(i), 'XData', sum(line_start_end)/2);
    end
  else
    %text object
    text_pos = get(objs(i), 'Position');
    text_pos(1) = line_start_end(2) + line_text_step;
    set(objs(i), 'Position', text_pos);
  end
end

See the following result:

What I want is :

Body:
As @Sardar Usama suggested, I put my solution here. I hope it is useful for you.

The first answer is nice. However, I finally use the following code to do this task.

close all

x = 0:0.5:10;
figure; hold on;
ph(1) = plot(x,sin(x), 'Marker', 'o');
ph(2) = plot(x,cos(x), 'Marker', 's');

ax = gca;
ax.Box = 'on';

bx = axes('position', [ax.Position(1:2), 0.3, 0.4], 'Box', 'on', 'XTick', [], 'YTick', []);%, 'Color', [0.8549,0.7020,1.0000]);
cx = axes('position', [ax.Position(1:2), 0.3, 0.4], 'Box', 'on', 'XTick', [], 'YTick', []);%, 'Color', [0.8549,0.5020,1.0000]);

[legb, objsb] = legend(bx, ph, {'sin', 'cos'}, 'Location', 'SouthWest');
[legc, objsc] = legend(cx, ph, {'sin', 'cos'}, 'Location', 'SouthWest');

line_start_end = [0.01, 0.3];
line_text_step = 0.05;

legendshrink(ax.Position(1:2), legb, objsb, bx, line_start_end, line_text_step);
legendshrink(ax.Position(1:2), legc, objsc, cx, line_start_end, line_text_step);

% you need only to adjust cx' position.
cx.Position(1:2) = [ax.Position(1)+ax.Position(3)-cx.Position(3), ax.Position(2)];
legc.Position(1:2) = cx.Position(1:2);

where legendshrink is defined as:

function legendshrink(leg_pos_xy, leg, objs, bx, line_start_end, line_text_step)

% leg_post_xy = ax.Position(1:2);
% [leg, objs] = legend(bx, line_handles, text_cell);
% line_start_end = [0.01, 0.4];
% line_text_step = 0.01;

% for each line, text object, adjust their position in legend
for i = 1:numel(objs)
  if strcmp(get(objs(i), 'Type'), 'line')
    % line object
    if 2 == numel(get(objs(i), 'XData')) % line
      set(objs(i), 'XData', line_start_end);
    else % marker on line
      set(objs(i), 'XData', sum(line_start_end)/2);
    end
  else
    %text object
    text_pos = get(objs(i), 'Position');
    text_pos(1) = line_start_end(2) + line_text_step;
    set(objs(i), 'Position', text_pos);
  end
end

% get minimum possible width and height
legend_width_no_right = 0;
for i = 1:numel(objs)
  % legend margin left
  if strcmp(get(objs(i), 'Type'), 'line')
    if numel(get(objs(i), 'XData')) == 2
      leg_margin_x = get(objs(i), 'XData');
      leg_margin_x = leg_margin_x(1)*leg.Position(3);
    end
  else
    cur_right = get(objs(i), 'Extent');
    cur_right = (cur_right(1)+cur_right(3))*leg.Position(3);
    if cur_right > legend_width_no_right
      legend_width_no_right = cur_right;
    end
  end
end
legend_width  = legend_width_no_right + leg_margin_x;
legend_height = leg.Position(4);

bx.Position = [leg_pos_xy, legend_width, legend_height];
leg.Position(1:2) = bx.Position(1:2);
leg.Box = 'off';

end

resulting


问:
Convert Binary BIT to an Index Number for Array - Swift
I need a way of determining or mapping a Binary BIT when set to an Index number for an array in Swift.

For example, I have have a uInt64 that has a BIT set 0b0010 0000 0000 ..., I would like to translate it in terms of an Index number for an array that ranges  from 0 to 39.

So the msb would be 0 and the lsb would be 39

Also, I need a way of identifying the most recent bit that has been switched.

For example, say the first is: 0b0010 0000 0000 .... and the second is 0x0010 0010 0000 .... until the integer is at its highest value i.e. 0xFFFFFFFF..

UPDATE:

After much helpful feedback, I have another problem which is identifying as to whether a variable has changed in Swift:

```<code>var changedValue: UInt64? {
                        willSet(newValue : UInt64) {
                            guard let oldValue = value, new = newValue else { return }
                            if oldValue != new { oldValue ^ newValue }
                            }
                        }
</code>```

It doesn't work with UInt64

答:
One basic approach would be to right shift the number until it becomes zero, keeping track of how many times it takes to do that:

```<code>func maskToIndex(_ mask: UInt64) -> Int {
    var mask = mask
    var result = 40

    repeat {
        mask >>= 1
        result -= 1
    } while mask != 0

    return result
}

print(maskToIndex(0x0000000001))  // 39
print(maskToIndex(0x0000000002))  // 38
print(maskToIndex(0x0000000004))  // 37

print(maskToIndex(0x8000000000))  // 0
print(maskToIndex(0x4000000000))  // 1
print(maskToIndex(0x2000000000))  // 2
</code>```

To identify the most recent bit switched on, apply exclusive-OR to the previous and current values to isolate the new bit:

```<code>let previous = 0b100
let current = 0b110
let newbit = previous ^ current  // newbit = 2 = 0b010
</code>```

Body:
I need a way of determining or mapping a Binary BIT when set to an Index number for an array in Swift.

For example, I have have a uInt64 that has a BIT set 0b0010 0000 0000 ..., I would like to translate it in terms of an Index number for an array that ranges  from 0 to 39.

So the msb would be 0 and the lsb would be 39

Also, I need a way of identifying the most recent bit that has been switched.

For example, say the first is: 0b0010 0000 0000 .... and the second is 0x0010 0010 0000 .... until the integer is at its highest value i.e. 0xFFFFFFFF..

UPDATE:

After much helpful feedback, I have another problem which is identifying as to whether a variable has changed in Swift:

var changedValue: UInt64? {
                        willSet(newValue : UInt64) {
                            guard let oldValue = value, new = newValue else { return }
                            if oldValue != new { oldValue ^ newValue }
                            }
                        }

It doesn't work with UInt64

Body:
One basic approach would be to right shift the number until it becomes zero, keeping track of how many times it takes to do that:

func maskToIndex(_ mask: UInt64) -> Int {
    var mask = mask
    var result = 40

    repeat {
        mask >>= 1
        result -= 1
    } while mask != 0

    return result
}

print(maskToIndex(0x0000000001))  // 39
print(maskToIndex(0x0000000002))  // 38
print(maskToIndex(0x0000000004))  // 37

print(maskToIndex(0x8000000000))  // 0
print(maskToIndex(0x4000000000))  // 1
print(maskToIndex(0x2000000000))  // 2

To identify the most recent bit switched on, apply exclusive-OR to the previous and current values to isolate the new bit:

let previous = 0b100
let current = 0b110
let newbit = previous ^ current  // newbit = 2 = 0b010


问:
Draw line between two given points (OpenCV, Python)
I am struggling with this problem for an hour by now...

I have an image with a rectangle inside:

This is the code I wrote to find the points for the corners:

```<code>import cv2
import numpy as np

img = cv2.imread('rect.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)

points = cv2.goodFeaturesToTrack(gray, 100, 0.01, 10)
points = np.int0(points)

for point in points:
    x, y = point.ravel()
    cv2.circle(img, (x, y), 3, (0, 255, 0), -1)

print(points[0])
print(points[1])
print(points[2])
print(points[3])

cv2.imshow('img', img)
cv2.waitKey(0)
cv2.imwrite('rect.png', img)
</code>```

This is the result:

As you can see, it works perfect. What I want is to draw a line along the upper/lower points (x1,x2 - x3,x4).

What I produced since now is this...

```<code>cv2.line(img, (points[0]), (points[1]), (0, 255, 0), thickness=3, lineType=8)

cv2.imshow('img', img)
cv2.waitKey(0)
</code>```

But it doesn't work.

Any idea ?

The result should be like this:

The two lines must pass along the coordinates of the points. print(points[0]) above give the next output, as example:

```<code>[[561 168]]
[[155 168]]
[[561  53]]
[[155  53]]
</code>```

Thanks

答:
So first of all, let'S look at your print, it says that points[0] is

```<code>[[561 168]]
</code>```

but opencv point is like

```<code>(561, 168)
</code>```

You can unpack it like you did with the circle and then do the tuple

```<code>x, y = points[0].ravel()
(x,y)
</code>```

or you can use

```<code>tuple(points[0].ravel())
</code>```

or

```<code>tuple(points[0][0])
</code>```

Edit

You wanted from one side of the screen to the other one, that is also easy. What you need to do is change the x value to be 0 in one point and column value in the other point. I think the easiest way is to do it like this:

```<code>y = points[0].ravel()[1]
cv2.line(img, (0, y), (img.shape[1], y), (0, 255, 0), thickness=3, lineType=8)
</code>```

Two things to note here:

As you can see I did not care about the second point, since I assumed
that it will be in the same horizontal line, if not, it will get a
little bit more complicated, but not hard.

img.shape returns the
tuple with the image details as (rows, cols, channels), since we
need cols we took [1].

Body:
I am struggling with this problem for an hour by now...

I have an image with a rectangle inside:

This is the code I wrote to find the points for the corners:

import cv2
import numpy as np

img = cv2.imread('rect.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)

points = cv2.goodFeaturesToTrack(gray, 100, 0.01, 10)
points = np.int0(points)

for point in points:
    x, y = point.ravel()
    cv2.circle(img, (x, y), 3, (0, 255, 0), -1)

print(points[0])
print(points[1])
print(points[2])
print(points[3])

cv2.imshow('img', img)
cv2.waitKey(0)
cv2.imwrite('rect.png', img)

This is the result:

As you can see, it works perfect. What I want is to draw a line along the upper/lower points (x1,x2 - x3,x4).

What I produced since now is this...

cv2.line(img, (points[0]), (points[1]), (0, 255, 0), thickness=3, lineType=8)

cv2.imshow('img', img)
cv2.waitKey(0)

But it doesn't work.

Any idea ?

The result should be like this:

The two lines must pass along the coordinates of the points. print(points[0]) above give the next output, as example:

[[561 168]]
[[155 168]]
[[561  53]]
[[155  53]]

Thanks

Body:
So first of all, let'S look at your print, it says that points[0] is

[[561 168]]

but opencv point is like

(561, 168)

You can unpack it like you did with the circle and then do the tuple

x, y = points[0].ravel()
(x,y)

or you can use

tuple(points[0].ravel())

or

tuple(points[0][0])

Edit

You wanted from one side of the screen to the other one, that is also easy. What you need to do is change the x value to be 0 in one point and column value in the other point. I think the easiest way is to do it like this:

y = points[0].ravel()[1]
cv2.line(img, (0, y), (img.shape[1], y), (0, 255, 0), thickness=3, lineType=8)

Two things to note here:

As you can see I did not care about the second point, since I assumed
that it will be in the same horizontal line, if not, it will get a
little bit more complicated, but not hard.

img.shape returns the
tuple with the image details as (rows, cols, channels), since we
need cols we took [1].


问:
Errors after updating to Android 3.0 and SDK 27
After Android Studio was released to 3.0 I was forced to update my SDK from 25 to 27 (couple libraries problems).

But now when try to build my app I get next error messages:

```<code>>Information:Gradle tasks [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:mockableAndroidJar]
C:\Users\Alice\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.0.0.aar\63ec32742d97434c1d2e0dbe96345ab9\res\values\values.xml
Error:(252, 5) error: resource android:attr/foregroundInsidePadding is private.
C:\Users\Alice\AndroidStudioProjects\Ghiduldrumetului cu Loco\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml
Error:(941) resource android:attr/foregroundInsidePadding is private.
Error:failed linking references.
Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:Execution failed for task ':app:processDebugResources'.
> Failed to execute aapt
Information:BUILD FAILED in 16s
Information:7 errors
Information:0 warnings
Information:See complete output in console
</code>```

Any suggestion how to fix it?

答:
Check if you're using "android:attr/foregroundInsidePadding" anywhere in your resources. It should be "attr/foregroundInsidePadding" instead.

More info: https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html#aapt2

Body:
After Android Studio was released to 3.0 I was forced to update my SDK from 25 to 27 (couple libraries problems).

But now when try to build my app I get next error messages:

>Information:Gradle tasks [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:mockableAndroidJar]
C:\Users\Alice\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.0.0.aar\63ec32742d97434c1d2e0dbe96345ab9\res\values\values.xml
Error:(252, 5) error: resource android:attr/foregroundInsidePadding is private.
C:\Users\Alice\AndroidStudioProjects\Ghiduldrumetului cu Loco\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml
Error:(941) resource android:attr/foregroundInsidePadding is private.
Error:failed linking references.
Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:Execution failed for task ':app:processDebugResources'.
> Failed to execute aapt
Information:BUILD FAILED in 16s
Information:7 errors
Information:0 warnings
Information:See complete output in console

Any suggestion how to fix it?


问:
Webcam resolution detection
I just can't believe I've found NOTHING on google, I'm starting to think that may be a DUMB question, but I have to ask.

I WANT to get the MAXIMUM RESOLUTION supported by a webcam, how can I do that?

This is my actual code:

```<code> // Maximum amount of bandwidth that the current
 // outgoing video feed can use, in bytes per second.
 var bandwidth:int = 0;
 var quality:int = 100; // This value is 0-100 with 1 being the lowest quality.

 var cam:Camera = Camera.getCamera();
 if(cam==null)
  writeErrorPopup(NOCAMERA_ERR);
 else
 {
  cam.addEventListener(StatusEvent.STATUS,statusHandler);
  function statusHandler(evt:StatusEvent):void
  {
   if(cam.muted)
   {
    writeErrorPopup(CAMPERMISSION_ERR);
   }
   else
   {
    trace(cam.width);
   }
  }

 cam.setQuality(bandwidth, quality);
 //cam.setMode(640,480,30,false);
 // setMode(videoWidth, videoHeight, video fps, favor area)
</code>```

What I have understood is:

default setMode of any webcam sets its resolution to 160x120, and infact the trace returns me the 160x120 value.

if I uncomment the 640x480 setmode the trace returns me the 640x480 value, which is OK, but this is a static value, I want to understand WHICH is the webcam resolution..

any hint?

答:
There's one way to find out:

Camera.setMode sets the height and width of the camera to the nearest possible value matching your requested resolution.  So if you pick a 4:3 aspect ratio and set the size to, say, 8192x6144, you should be able to get the highest possible resolution of the camera.  Just to make sure, you could also try a 16:9 or 16:10 ratio and see which returns the best result.

Title: Webcam resolution detection

Body:
I just can't believe I've found NOTHING on google, I'm starting to think that may be a DUMB question, but I have to ask.

I WANT to get the MAXIMUM RESOLUTION supported by a webcam, how can I do that?

This is my actual code:

 // Maximum amount of bandwidth that the current
 // outgoing video feed can use, in bytes per second.
 var bandwidth:int = 0;
 var quality:int = 100; // This value is 0-100 with 1 being the lowest quality.

 var cam:Camera = Camera.getCamera();
 if(cam==null)
  writeErrorPopup(NOCAMERA_ERR);
 else
 {
  cam.addEventListener(StatusEvent.STATUS,statusHandler);
  function statusHandler(evt:StatusEvent):void
  {
   if(cam.muted)
   {
    writeErrorPopup(CAMPERMISSION_ERR);
   }
   else
   {
    trace(cam.width);
   }
  }

 cam.setQuality(bandwidth, quality);
 //cam.setMode(640,480,30,false);
 // setMode(videoWidth, videoHeight, video fps, favor area)

What I have understood is:

default setMode of any webcam sets its resolution to 160x120, and infact the trace returns me the 160x120 value.

if I uncomment the 640x480 setmode the trace returns me the 640x480 value, which is OK, but this is a static value, I want to understand WHICH is the webcam resolution..

any hint?


问:
Right Clicking Properties and Arithmetic overflow error converting expression to data type int appears
I know there are posts and answers to the above error, however my error comes up when I am right clicking and selecting properties on my database, rather than executing a script/query, which is what the rest of the posters have put on here.

In actual fact there are no tables in my database (after deleting them) and the message still appears.

Before i deleted my tables i did convert any int to big int

```<code>SELECT
CAST(Math AS BIGINT) AS Math1
FROM MyTable
</code>```

and thought that might do the trick but it hasn't, neither has deleting the table(s) from the database.

Does anyone have a clue as to what it might be?

答:
however my error comes up when I am right clicking and selecting
  properties on my database, rather than executing a script/query, which
  is what the rest of the posters have put on here.

When you ask SSMS for database properties it does execute some code, even if you don't see it.
To find out what exact code is causing this error, use SQL Server Profiler.

Here you'll find what events you should pick and how to narrow down the statement that caused the error:
How to trace SQL Server database errors and exceptions with SQL Profiler

Body:
I know there are posts and answers to the above error, however my error comes up when I am right clicking and selecting properties on my database, rather than executing a script/query, which is what the rest of the posters have put on here.

In actual fact there are no tables in my database (after deleting them) and the message still appears.

Before i deleted my tables i did convert any int to big int

SELECT
CAST(Math AS BIGINT) AS Math1
FROM MyTable

and thought that might do the trick but it hasn't, neither has deleting the table(s) from the database.

Does anyone have a clue as to what it might be?


问:
keypress, ctrl+c (or some combo like that)
I'm trying to create shortcuts on the website I'm making. I know I can do it this way:

```<code>if(e.which == 17) isCtrl=true;
if(e.which == 83 && isCtrl == true) {
    alert('CTRL+S COMBO WAS PRESSED!')
    //run code for CTRL+S -- ie, save!
    e.preventDefault();
}
</code>```

But the example below is easier and less code, but it's not a combo keypress event:

```<code>$(document).keypress("c",function() {
  alert("Just C was pressed..");
});
</code>```

So I want to know if by using this second example, I could do something like:

```<code>$(document).keypress("ctrl+c",function() {
  alert("Ctrl+C was pressed!!");
});
</code>```

is this possible? I've tried it and it didn't work, what am I doing wrong?

答:
In my case, I was looking for a keydown ctrl key and click event.
My jquery looks like this:

```<code>$('.linkAccess').click( function (event) {
  if(true === event.ctrlKey) {

    /* Extract the value */
    var $link = $('.linkAccess');
    var value = $link.val();

    /* Verified if the link is not null */
    if('' !== value){
      window.open(value);
    }
  }
});
</code>```

Where "linkAccess" is the class name for some specific fields where I have a link and I want to access it using my combination of key and click.

Body:
I'm trying to create shortcuts on the website I'm making. I know I can do it this way:

if(e.which == 17) isCtrl=true;
if(e.which == 83 && isCtrl == true) {
    alert('CTRL+S COMBO WAS PRESSED!')
    //run code for CTRL+S -- ie, save!
    e.preventDefault();
}

But the example below is easier and less code, but it's not a combo keypress event:

$(document).keypress("c",function() {
  alert("Just C was pressed..");
});

So I want to know if by using this second example, I could do something like:

$(document).keypress("ctrl+c",function() {
  alert("Ctrl+C was pressed!!");
});

is this possible? I've tried it and it didn't work, what am I doing wrong?

Body:
In my case, I was looking for a keydown ctrl key and click event.
My jquery looks like this:

$('.linkAccess').click( function (event) {
  if(true === event.ctrlKey) {

    /* Extract the value */
    var $link = $('.linkAccess');
    var value = $link.val();

    /* Verified if the link is not null */
    if('' !== value){
      window.open(value);
    }
  }
});

Where "linkAccess" is the class name for some specific fields where I have a link and I want to access it using my combination of key and click.


问:
Beginning python for the web
I'm looking for a nice tutorial or framework for developing Python written web applications.

I've done lots in PHP, but very little in Python or Ruby and figured I'd start with the first one alphabetically.

答:
I just started Python for web myself. I also came from a PHP background and felt that PHP is fine when it comes to making regular stuff like forums, blogs and stuff like that. Sadly though I didn't like PHP when it came to create more complex systems.

I looked at a few of the different frameworks out there and came to the conclusion if I want to use a Framework that applies as much to web as to client and server side programming Turbogears2 would suit med best.

Seems like one of the "newer" frameworks and looks like they got a solid community that will keep they going for years to come.

Oh, lol this post sounds like and ad. Sorry ;)

Anyway, I like to use webpages that you can work with the hardware on the server, which means CGI/WSGI or just Turbogears :)

Title: Beginning python for the web


问:
ForegroundTint "overrides" backgroundTint on button?
I'm working on android app and I need a button with both background and foreground, which are some icons.

I want to set backgroundTint and foregroundTint to different colors, because it will be needed when I write the selectors for colors.

The problem is that when I set foregroundTint:

foregroundTintMode=multiply - background tint is ok, but foreground icon is not changing it's color

foregroundTintMode!=multiply - foreground tint is ok, but background icon is changing it's color to foregroundTint, not backgroundTint

I've tried all of the combinations for foregroundTintMode and backgroundTintMode, but got no results.

Here is my test file:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="euroicc.testfb.MainActivity"
    android:background="@color/colorPrimary">

    <Button
        android:id="@+id/button"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="@drawable/icon_background"
        android:backgroundTint="@android:color/holo_blue_dark"
        android:foreground="@drawable/icon_settings"
        android:foregroundTint="@android:color/white"
        tools:layout_editor_absoluteX="105dp"
        tools:layout_editor_absoluteY="141dp" />

</RelativeLayout>
</code>```

Note: I was initially working with API lvl 17, but changed to 21. I would like for this app to support as many devices as possible.

答:
Not sure why you are using a normal Button and foreground, use an ImageButton instead:

```<code><ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/icon_settings"
    android:tint="@android:color/red"
    android:background="@drawable/icon_background"
    android:backgroundTint="@android:color/black"
    />
</code>```

Body:
I'm working on android app and I need a button with both background and foreground, which are some icons.

I want to set backgroundTint and foregroundTint to different colors, because it will be needed when I write the selectors for colors.

The problem is that when I set foregroundTint:

foregroundTintMode=multiply - background tint is ok, but foreground icon is not changing it's color

foregroundTintMode!=multiply - foreground tint is ok, but background icon is changing it's color to foregroundTint, not backgroundTint

I've tried all of the combinations for foregroundTintMode and backgroundTintMode, but got no results.

Here is my test file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="euroicc.testfb.MainActivity"
    android:background="@color/colorPrimary">

    <Button
        android:id="@+id/button"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="@drawable/icon_background"
        android:backgroundTint="@android:color/holo_blue_dark"
        android:foreground="@drawable/icon_settings"
        android:foregroundTint="@android:color/white"
        tools:layout_editor_absoluteX="105dp"
        tools:layout_editor_absoluteY="141dp" />

</RelativeLayout>

Note: I was initially working with API lvl 17, but changed to 21. I would like for this app to support as many devices as possible.

Body:
Not sure why you are using a normal Button and foreground, use an ImageButton instead:

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/icon_settings"
    android:tint="@android:color/red"
    android:background="@drawable/icon_background"
    android:backgroundTint="@android:color/black"
    />


问:
Save query string in cookie
On every request to my page i want to store the query string value in cookie. I mean when:

```<code>$_GET['id'] = 28 to get 28.
</code>```

Next time when:

```<code>$_GET['id'] is 36.
</code>```

I want to get 36 and add it to 28. How can I achieve that?

答:
You can use cookies as you mentioned, but depending on the workflow, you may want to use $_SESSION since it is generally more secure. Cookies can be modified by the client, and persist between visits. If that is your desired behavior, then setcookie() will be your best bet.

```<code><?php
// The intval() function helps to ensure that numbers are being used, floatval() could work too
// Get current cookie value
$currentValue = intval($_COOKIE['CookieCounter']);
// Get new passed value
$incrementBy = intval($_GET['id']);
// Set the cookie and have it saved for 30 days
setcookie('CookieCounter', str($currentValue + $incrementBy), time()+60*60*24*30);
</code>```

An alternative way of doing it is to use sessions.

Sessions are a simple way to store data for individual users against a
  unique session ID. This can be used to persist state information
  between page requests. Session IDs are normally sent to the browser
  via session cookies and the ID is used to retrieve existing session
  data. The absence of an ID or session cookie lets PHP know to create a
  new session, and generate a new session ID.

```<code><?php
// Start the session
session_start();
// Check if the session value is already set
if (!isset($_SESSION['count'])) {
  $_SESSION['count'] = intval($_GET['id']);
} else {
// Increment the session value
  $_SESSION['count'] += intval($_GET['id']);
}
</code>```

However, cookies are changeable, and also can get removed by browser settings, etc. If you want it to be more secure and persist, I would use a database or other persistent data store.

Title: Save query string in cookie

Body:
On every request to my page i want to store the query string value in cookie. I mean when:

$_GET['id'] = 28 to get 28.

Next time when:

$_GET['id'] is 36.

I want to get 36 and add it to 28. How can I achieve that?

Body:
You can use cookies as you mentioned, but depending on the workflow, you may want to use $_SESSION since it is generally more secure. Cookies can be modified by the client, and persist between visits. If that is your desired behavior, then setcookie() will be your best bet.

<?php
// The intval() function helps to ensure that numbers are being used, floatval() could work too
// Get current cookie value
$currentValue = intval($_COOKIE['CookieCounter']);
// Get new passed value
$incrementBy = intval($_GET['id']);
// Set the cookie and have it saved for 30 days
setcookie('CookieCounter', str($currentValue + $incrementBy), time()+60*60*24*30);

An alternative way of doing it is to use sessions.

Sessions are a simple way to store data for individual users against a
  unique session ID. This can be used to persist state information
  between page requests. Session IDs are normally sent to the browser
  via session cookies and the ID is used to retrieve existing session
  data. The absence of an ID or session cookie lets PHP know to create a
  new session, and generate a new session ID.

<?php
// Start the session
session_start();
// Check if the session value is already set
if (!isset($_SESSION['count'])) {
  $_SESSION['count'] = intval($_GET['id']);
} else {
// Increment the session value
  $_SESSION['count'] += intval($_GET['id']);
}

However, cookies are changeable, and also can get removed by browser settings, etc. If you want it to be more secure and persist, I would use a database or other persistent data store.


答:
it completely depends on the logic of your code. by modifying object "as a whole" you're sure that you don't brake its invariants. usually if class provide operator= nothing wrong to use it.

in referred questions it's pretty logical way to call overloaded assignment operator, so it's a good example.

Title: Does it make sense to modify an object as a whole using one of its behavior? Say inside the assignment operator overloading using this pointer?

Body:
I see a question on this operator (What does assignment to *this do (*this = val)?)

but is it logical to modify an object as a whole from within one of its behavior? Does it makes sense in OOP world?


问:
How to change the attributes of the
```

<p>How can i change the value of <code>data-amount="100"</code> to my desired value</p>

<p>I tried like</p>

```document.getElementById("paymentWidget").attr("data-amount") = total
```

<p>But it is showing error like </p>

```document.getElementById(...).attr is not a function
```

How can i fix this and set values dynamically ?

答:
You can use the dataset. Data set is used when your attribute begins with data-.

In your example:

document.getElementById("paymentWidget").dataset.amount = total;

Support for this is IE>11

For more support use the element.setAttribute("attribute", "value")

Read more on MDN:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset

Title: How to change the attributes of the <script> tag

Body:
Here is my script tag

How can i change the value of data-amount="100" to my desired value

I tried like

document.getElementById("paymentWidget").attr("data-amount") = total

But it is showing error like

document.getElementById(...).attr is not a function

How can i fix this and set values dynamically ?


问:
defining default values
Im a new SAS User and I have a small problem

I have one large empty table A with lets say 100 columns that I have created with a simple proc sql; create table

I have another table B with lets say 40 columns and table C with 55 columns.
I want to add these two tables into table A, basically I want a table with 100 columns containing the data from table B & C and I'm doing this with a Union command.

Since I dont have values for all 100 variables I have to set default values.
Lets say I have a column named nourishment in table A, food in table B and has no equivalent in table C. I have rules like "If the data comes from table B then value =xxx if its from table C then Value="DefaultValue"

I'd do this easily with R or python but Im struggling with sas.

I'm using SAS sql commands (a Union command)

How do you set default values ? (for all data types : character, numeric or dateI'm using SAS sql commands )

答:
Dates in SAS are actually just numeric values.  Often they have a date format applied to make them readable.

So you could just assign a missing value by default like so:

```<code>. as ColumnName
</code>```

or any default date like so

```<code>'17NOV2017'd as ColumnName
</code>```

Title: defining default values

Body:
Dates in SAS are actually just numeric values.  Often they have a date format applied to make them readable.

So you could just assign a missing value by default like so:

. as ColumnName

or any default date like so

'17NOV2017'd as ColumnName


问:
Windows batch: replace strings in a file case sensitively
I've spent a lot of time writing a script to generate new files using a "template" (coding env.) project.

While on Unix the shell script is laughably easy I spent days doing the same on Windows...

My current batch file does almost everything I need, except that the string replacement is case-insensitive... That is, it replaces "emptyproject" with "EMPTYPROJECT", being the first statement...

Code:

```<code>@echo off & setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION

set argc=0
for %%x in (%*) do set /A argc+=1

if /I "%argc%" EQU "0" (
 echo Usage: %0 PROJECT_NAME >&2
 exit /B 1
)

set curr_dir=%~dp0
set project_name=%1
set project_name_lower=%1
set project_name_upper=%1
set project_file="vstudio\projects\%project_name%.vcxproj"
set project_filters="vstudio\projects\%project_name%.vcxproj.filters"

call :toupper project_name_upper
call :tolower project_name_lower

if not exist %project_file% (
 copy /y "vstudio\projects\EmptyProject.vcxproj" %project_file% >nul
 copy /y "vstudio\projects\EmptyProject.vcxproj.filters" %project_filters% >nul
)

set project_source_dir=..\projects\source\%project_name_lower%

if not exist %project_source_dir% (
 mkdir %project_source_dir%

 call :copy_and_replace_strings "..\projects\source\emptyproject\main.cpp" "%project_source_dir%\main.cpp" %project_name% %project_name_lower% %project_name_upper%
 call :copy_and_replace_strings "..\projects\source\emptyproject\emptyproject.h" "%project_source_dir%\%project_name_lower%.h" %project_name% %project_name_lower% %project_name_upper%
 call :copy_and_replace_strings "..\projects\source\emptyproject\emptyproject_main.cpp" "%project_source_dir%\%project_name_lower%_main.cpp" %project_name% %project_name_lower% %project_name_upper%
 call :copy_and_replace_strings "..\projects\source\emptyproject\emptyproject_eventhandlers.cpp" "%project_source_dir%\%project_name_lower%_eventhandlers.cpp" %project_name% %project_name_lower% %project_name_upper%
)

endlocal
goto :EOF

REM functions
:toupper
 for %%L IN (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) DO SET %1=!%1:%%L=%%L!
 goto :EOF

:tolower
 for %%L IN (a b c d e f g h i j k l m n o p q r s t u v w x y z) DO SET %1=!%1:%%L=%%L!
 goto :EOF

:copy_and_replace_strings <source_file> <target_file> <name> <lower> <upper>
 for /f "tokens=1,* delims=]" %%a in ('find /n /v "" ^< %1') do (
  set token1=%%a
  set token2=%%b

  if defined token2 (
REM not case sensitive
   set token2=!token2:EMPTYPROJECT=%5!
   set token2=!token2:EmptyProject=%3!
   set token2=!token2:emptyproject=%4!
   echo !token2!>>%2
  ) else (
   echo[>>%2
  )
 )
 goto :EOF
</code>```

I read a lot about this on this forum, but couldn't find a suitable solution. Could someone help me please?

答:
To be rather honest, your quickest method to keep it pure batch is to trick the system and use powershell in the background.

```<code>@echo off
setlocal enabledelayedexpansion
set "input=i want this upper case"
for /f "usebackq delims=" %%a in (`powershell "\"%input%\".toUpper()"`) do set "lower=%%~a"

set "input=I WANT THIS LOWER CASE"
for /f "usebackq delims=" %%a in (`powershell "\"%input%\".toLower()"`) do set "upper=%%~a"
echo !lower!
echo !upper!
</code>```

RESULT

I WANT THIS UPPER CASE

i want this lower case

Body:
I've spent a lot of time writing a script to generate new files using a "template" (coding env.) project.

While on Unix the shell script is laughably easy I spent days doing the same on Windows...

My current batch file does almost everything I need, except that the string replacement is case-insensitive... That is, it replaces "emptyproject" with "EMPTYPROJECT", being the first statement...

Code:

@echo off & setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION

set argc=0
for %%x in (%*) do set /A argc+=1

if /I "%argc%" EQU "0" (
 echo Usage: %0 PROJECT_NAME >&2
 exit /B 1
)

set curr_dir=%~dp0
set project_name=%1
set project_name_lower=%1
set project_name_upper=%1
set project_file="vstudio\projects\%project_name%.vcxproj"
set project_filters="vstudio\projects\%project_name%.vcxproj.filters"

call :toupper project_name_upper
call :tolower project_name_lower

if not exist %project_file% (
 copy /y "vstudio\projects\EmptyProject.vcxproj" %project_file% >nul
 copy /y "vstudio\projects\EmptyProject.vcxproj.filters" %project_filters% >nul
)

set project_source_dir=..\projects\source\%project_name_lower%

if not exist %project_source_dir% (
 mkdir %project_source_dir%

 call :copy_and_replace_strings "..\projects\source\emptyproject\main.cpp" "%project_source_dir%\main.cpp" %project_name% %project_name_lower% %project_name_upper%
 call :copy_and_replace_strings "..\projects\source\emptyproject\emptyproject.h" "%project_source_dir%\%project_name_lower%.h" %project_name% %project_name_lower% %project_name_upper%
 call :copy_and_replace_strings "..\projects\source\emptyproject\emptyproject_main.cpp" "%project_source_dir%\%project_name_lower%_main.cpp" %project_name% %project_name_lower% %project_name_upper%
 call :copy_and_replace_strings "..\projects\source\emptyproject\emptyproject_eventhandlers.cpp" "%project_source_dir%\%project_name_lower%_eventhandlers.cpp" %project_name% %project_name_lower% %project_name_upper%
)

endlocal
goto :EOF

REM functions
:toupper
 for %%L IN (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) DO SET %1=!%1:%%L=%%L!
 goto :EOF

:tolower
 for %%L IN (a b c d e f g h i j k l m n o p q r s t u v w x y z) DO SET %1=!%1:%%L=%%L!
 goto :EOF

:copy_and_replace_strings <source_file> <target_file> <name> <lower> <upper>
 for /f "tokens=1,* delims=]" %%a in ('find /n /v "" ^< %1') do (
  set token1=%%a
  set token2=%%b

  if defined token2 (
REM not case sensitive
   set token2=!token2:EMPTYPROJECT=%5!
   set token2=!token2:EmptyProject=%3!
   set token2=!token2:emptyproject=%4!
   echo !token2!>>%2
  ) else (
   echo[>>%2
  )
 )
 goto :EOF

I read a lot about this on this forum, but couldn't find a suitable solution. Could someone help me please?

Body:
To be rather honest, your quickest method to keep it pure batch is to trick the system and use powershell in the background.

@echo off
setlocal enabledelayedexpansion
set "input=i want this upper case"
for /f "usebackq delims=" %%a in (`powershell "\"%input%\".toUpper()"`) do set "lower=%%~a"

set "input=I WANT THIS LOWER CASE"
for /f "usebackq delims=" %%a in (`powershell "\"%input%\".toLower()"`) do set "upper=%%~a"
echo !lower!
echo !upper!

RESULT

I WANT THIS UPPER CASE

i want this lower case


问:
Doctrine Tell me "new Entity was found" when i set a relationship ManyToOne but is not

I have a Project with Symfony

Create a form for a ner entity.

```<code>class EquipoType extends AbstractType{
/**
 * {@inheritdoc}
 */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
    $equipo = new Equipo();

    $builder
    ->add('unidades', IntegerType::class)
    ->add('accionComercial', EntityType::class, array(
        'class' => 'AppBundle\Entity\IndicoGpt\adelantoequipos\AccionComercial',
        'em' => 'adeq',
        'choices' => $equipo->getAccionComercial(),
        'choice_label' => 'nombre',
        'placeholder' => 'Elija Accion Comercial'
    ))
    ->add('modelo', TextType::class)
    ->add('save', SubmitType::class, array(
            'label' => 'Guardar Equipo',
            'attr' => array(
                'class' => "btn btn-info",
                'style' => "margin-top: 7px; margin-left:40%;"
            ))
    );

    $builder->get('modelo')
        ->addModelTransformer(new CallbackTransformer(
            function ($modelo) {
                return $modelo ? $modelo->getModDescModelo() :  $modelo;
            },
            function ($modelo) use ($options) {
                return $modelo ? $options['em']->getRepository(ModModelo::class)->findOneBy(array(
                    'modDescModelo' => $modelo
                )) : $modelo;
            }
        ));
 public function configureOptions(OptionsResolver $resolver)
 {
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\IndicoGpt\adelantoequipos\Equipo',
        'em' => "adeq"
    ));
 }

 /**
  * {@inheritdoc}
  */
 public function getBlockPrefix()
 {
    return 'appbundle_indicogpt_adelantoequipos_equipo';
 }
}
</code>```

This Entity has a relatuionship.
(Equipo has Modelo[oneToMany], Modelo has Many Equipos[oneToMany] )

```<code>    class Equipo
{
    /**
 * @var \AppBundle\Entity\IndicoGpt\catalogo\ModModelo
 *
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\IndicoGpt\catalogo\ModModelo")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="modelo_id", referencedColumnName="MOD_ID_MODELO")
 * })
 */
private $modelo;
</code>```

The entity Modelo is full of rows (in db) with types of equip models. Ergo an Equipo only need to save an existing Id of a Modelo row.

The problem appears when i do $emAedq->flush() Here is my controller:

```<code>    public function crearEquipo(Request $request){

     $emAdeq = $this->getDoctrine()->getManager('adeq');
     $emCatalogo = $this->getDoctrine()->getManager('catalogo');

     $equipo = new Equipo();
     $form = $this->createForm(EquipoType::class, $equipo, array(
        'action' => "crearEquipo",
        'em' =>  $emCatalogo,
        'attr' => array(
            'class' => "form"
        )
     ));

     $form->handleRequest($request);

     if ($form->isSubmitted()) {

         $equipo = $form->getData();

         $emAdeq->persist($equipo);

         $emAdeq->flush();

         $this->addFlash('exito', $equipo->getId());

         return $this->redirectToRoute('portadaAdelantoEquipos');
     }
    ...
</code>```

When I go to save the new Equipo it tells me that it was found a new entity in the relationship and should be saved (reffering to Modelo associated), but that entity is not new, it is an existing Modelo that is now related to the Equipo.

As shown in the image, I choose a Modelo of the existing ones through an autocomplete field.

Just before doin the $emAdeq->persist($equipo) of the entity, i can see in the debugger the object that I am going to save it appears well composed:

The Error is the next:

A new entity was found through the relationship 'AppBundle\Entity\IndicoGpt\adelantoequipos\Equipo#modelo' that was not configured to cascade persist operations for entity: AppBundle\Entity\IndicoGpt\catalogo\ModModelo@0000000011088ca600000000661c7dca. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem implement 'AppBundle\Entity\IndicoGpt\catalogo\ModModelo#__toString()' to get a clue.

I dont understand why thinks that is a new entity and why give me this string refering to modelo:

Why this happends?
How can i save the Equipo with his relationship?
Without make a persist of the Modelo because i can not save the Modelo that allready exist!

I have seen other example here. But this does not work to me...

I run this command php bin/console doctrine:schema:validate and everything is right.

答:
The problem is that I was using two entityManager because the relationship is made in two different databases.

But I have not realized that the related entity has his database established, so I only need one EntityManager.

With one entityManager i can ask for one entity and the relations without other EntityManagers

By having two entityManagers I was asked to saved twice.

Solution:

Establish in the entity his DB: * @ ORM \ Table (name = "advanced equipment.") Where I have used $emCatalgo replace it with $emAdeq and eliminate the catalog because it is unusable.

Thanks to @Alessandro Minoccheri because his answer is also valid but that make my realize what im doing wrong with 2 EntittyManagers.

Body:
I have a Project with Symfony

Create a form for a ner entity.

class EquipoType extends AbstractType{
/**
 * {@inheritdoc}
 */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
    $equipo = new Equipo();

    $builder
    ->add('unidades', IntegerType::class)
    ->add('accionComercial', EntityType::class, array(
        'class' => 'AppBundle\Entity\IndicoGpt\adelantoequipos\AccionComercial',
        'em' => 'adeq',
        'choices' => $equipo->getAccionComercial(),
        'choice_label' => 'nombre',
        'placeholder' => 'Elija Accion Comercial'
    ))
    ->add('modelo', TextType::class)
    ->add('save', SubmitType::class, array(
            'label' => 'Guardar Equipo',
            'attr' => array(
                'class' => "btn btn-info",
                'style' => "margin-top: 7px; margin-left:40%;"
            ))
    );

    $builder->get('modelo')
        ->addModelTransformer(new CallbackTransformer(
            function ($modelo) {
                return $modelo ? $modelo->getModDescModelo() :  $modelo;
            },
            function ($modelo) use ($options) {
                return $modelo ? $options['em']->getRepository(ModModelo::class)->findOneBy(array(
                    'modDescModelo' => $modelo
                )) : $modelo;
            }
        ));
 public function configureOptions(OptionsResolver $resolver)
 {
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\IndicoGpt\adelantoequipos\Equipo',
        'em' => "adeq"
    ));
 }

 /**
  * {@inheritdoc}
  */
 public function getBlockPrefix()
 {
    return 'appbundle_indicogpt_adelantoequipos_equipo';
 }
}

This Entity has a relatuionship.
(Equipo has Modelo[oneToMany], Modelo has Many Equipos[oneToMany] )

    class Equipo
{
    /**
 * @var \AppBundle\Entity\IndicoGpt\catalogo\ModModelo
 *
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\IndicoGpt\catalogo\ModModelo")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="modelo_id", referencedColumnName="MOD_ID_MODELO")
 * })
 */
private $modelo;

The entity Modelo is full of rows (in db) with types of equip models. Ergo an Equipo only need to save an existing Id of a Modelo row.

The problem appears when i do $emAedq->flush() Here is my controller:

    public function crearEquipo(Request $request){

     $emAdeq = $this->getDoctrine()->getManager('adeq');
     $emCatalogo = $this->getDoctrine()->getManager('catalogo');

     $equipo = new Equipo();
     $form = $this->createForm(EquipoType::class, $equipo, array(
        'action' => "crearEquipo",
        'em' =>  $emCatalogo,
        'attr' => array(
            'class' => "form"
        )
     ));

     $form->handleRequest($request);

     if ($form->isSubmitted()) {

         $equipo = $form->getData();

         $emAdeq->persist($equipo);

         $emAdeq->flush();

         $this->addFlash('exito', $equipo->getId());

         return $this->redirectToRoute('portadaAdelantoEquipos');
     }
    ...

When I go to save the new Equipo it tells me that it was found a new entity in the relationship and should be saved (reffering to Modelo associated), but that entity is not new, it is an existing Modelo that is now related to the Equipo.

As shown in the image, I choose a Modelo of the existing ones through an autocomplete field.

Just before doin the $emAdeq->persist($equipo) of the entity, i can see in the debugger the object that I am going to save it appears well composed:

The Error is the next:

A new entity was found through the relationship 'AppBundle\Entity\IndicoGpt\adelantoequipos\Equipo#modelo' that was not configured to cascade persist operations for entity: AppBundle\Entity\IndicoGpt\catalogo\ModModelo@0000000011088ca600000000661c7dca. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem implement 'AppBundle\Entity\IndicoGpt\catalogo\ModModelo#__toString()' to get a clue.

I dont understand why thinks that is a new entity and why give me this string refering to modelo:

Why this happends?
How can i save the Equipo with his relationship?
Without make a persist of the Modelo because i can not save the Modelo that allready exist!

I have seen other example here. But this does not work to me...

I run this command php bin/console doctrine:schema:validate and everything is right.


问:
When i try to build apk(s) on android studio 3 it gives me error
I'm trying to make LPR app on android studio. I'm using OpenCV 3.1.0 and Tesseract for recognition and when i try to build apk it gives me this

Error: Flag android.useDeprecatedNdk is no longer supported and will be
   removed in the next version of Android Studio.  Please switch to a supported
   build system.
   Consider using CMake or ndk-build integration. For more information, go to:
    https://d.android.com/r/studio-ui/add-native-code.html#ndkCompile
    To get started, you can use the sample ndk-build script the Android
    plugin generated for you at:
    C:\Users\m\Desktop\TestTmp\LPR\app\build\intermediates\ndk\debug\Android.mk
   Alternatively, you can use the experimental plugin:
    https://developer.android.com/r/tools/experimental-plugin.html
   To continue using the deprecated NDK compile for another 60 days, set
   android.deprecatedNdkCompileLease=1510879276001 in gradle.properties

Does anyone know how to fix this error?

答:
If you still want to use deprecated NDK version add following into your gradle.properties

```<code>android.useDeprecatedNdk=true
</code>```

you will be able to build the project and APK file.

Body:
If you still want to use deprecated NDK version add following into your gradle.properties

android.useDeprecatedNdk=true

you will be able to build the project and APK file.


问:
Accessing another projects app.config properties?
I have two projects within my solution, for this example I will call them project A and B.

Project B references A. Can Project B access the app.config properties of project A?

I wish to access an app key string within the app.config of A.

```<code>string tfsUri = ConfigurationManager.AppSettings["TfsUri"];
</code>```

答:
```<code>       var path = @"C:\Users\Stephen\source\repos\SensurityConfigurationTool\Configuration.UI\App.config";
        string directory = Path.GetDirectoryName(path);
        var pathRoot = Path.GetPathRoot(directory);
        string file = Path.GetFileName(path);

        ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap
        {
            ExeConfigFilename = Path.Combine(Path.GetFullPath(directory + "\\" + file))
        };

        System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
</code>```

You basically get the relative path, then convert this to an absolute path

Body:
I have two projects within my solution, for this example I will call them project A and B.

Project B references A. Can Project B access the app.config properties of project A?

I wish to access an app key string within the app.config of A.

string tfsUri = ConfigurationManager.AppSettings["TfsUri"];

Body:
       var path = @"C:\Users\Stephen\source\repos\SensurityConfigurationTool\Configuration.UI\App.config";
        string directory = Path.GetDirectoryName(path);
        var pathRoot = Path.GetPathRoot(directory);
        string file = Path.GetFileName(path);

        ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap
        {
            ExeConfigFilename = Path.Combine(Path.GetFullPath(directory + "\\" + file))
        };

        System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

You basically get the relative path, then convert this to an absolute path


问:
C++: Forward iterator interface of a member container to class interface
I'm dealing with a class that has a std::array<double, 2> data member and I am trying to implement a few basic iterator mechanics for my class by simply passing everything onto std::array (begin() and end() shall suffice for now).

I am using decltype and std::declval to infer the return type of std::array's begin().

class myCont {
    public:
    myCont() : data({{-1, 1}}) {}

    /* Pass to iterator mechanism of std::array */
    auto begin() -> decltype(declval<array<double, 2>>().begin()){return data.begin();}
    auto cbegin() -> decltype(declval<array<double, 2>>().cbegin()){return data.cbegin();}
    auto end() -> decltype(declval<array<double, 2>>().end()){return data.end();}
    auto cend() -> decltype(declval<array<double, 2>>().cend()){return data.cend();}

    private:
    array<double, 2> data;
};
```

<p>Using <code>myCont</code> as a const ref argument yields errors concerning const correctness: <em>passing 'const myCont' as 'this' argument discards qualifiers</em>,</p>

<pre class="lang-cpp prettyprint-override"><code>void myContainerFunc(const myCont& c){
    for(auto it = c.cbegin(); it != c.cend(); it++) // Error
        cout << *it << ' ' << endl;
}
</code>```

while the exact same function taking a std::array works just fine.

void myContainerFunc(const myCont& c){
    for(auto it = c.cbegin(); it != c.cend(); it++) // works perfectly fine
        cout << *it << ' ' << endl;
}
```

Why don't myCont::begin() etc. behave like std::array's implementations, which they are supposed to call? Could anybody point out my error to me? Does decltype throw away constness or something similar?

Thank you.

答:
Your methods cbegin() and cend() should be const-qualified:

```<code>auto cbegin() const -> decltype(declval<array<double, 2>>().cbegin()) {return data.cbegin();}
</code>```

If you check std::array you will notice that the corresponding methods are const-qualified.

Body:
I'm dealing with a class that has a std::array<double, 2> data member and I am trying to implement a few basic iterator mechanics for my class by simply passing everything onto std::array (begin() and end() shall suffice for now).

I am using decltype and std::declval to infer the return type of std::array's begin().

class myCont {
    public:
    myCont() : data({{-1, 1}}) {}

    /* Pass to iterator mechanism of std::array */
    auto begin() -> decltype(declval<array<double, 2>>().begin()){return data.begin();}
    auto cbegin() -> decltype(declval<array<double, 2>>().cbegin()){return data.cbegin();}
    auto end() -> decltype(declval<array<double, 2>>().end()){return data.end();}
    auto cend() -> decltype(declval<array<double, 2>>().cend()){return data.cend();}

    private:
    array<double, 2> data;
};

Using myCont as a const ref argument yields errors concerning const correctness: passing 'const myCont' as 'this' argument discards qualifiers,

void myContainerFunc(const myCont& c){
    for(auto it = c.cbegin(); it != c.cend(); it++) // Error
        cout << *it << ' ' << endl;
}

while the exact same function taking a std::array works just fine.

void myContainerFunc(const myCont& c){
    for(auto it = c.cbegin(); it != c.cend(); it++) // works perfectly fine
        cout << *it << ' ' << endl;
}

Why don't myCont::begin() etc. behave like std::array's implementations, which they are supposed to call? Could anybody point out my error to me? Does decltype throw away constness or something similar?

Thank you.

Body:
Your methods cbegin() and cend() should be const-qualified:

auto cbegin() const -> decltype(declval<array<double, 2>>().cbegin()) {return data.cbegin();}

If you check std::array you will notice that the corresponding methods are const-qualified.


问:
Bring activity front if it is running or create new one with backpress

Let me explain detailed; I have notification and this notification opens B activity with two cases.

Cases :

If app is closed. (not running on background)

If app is opened. (on background or front)

Case-1

I click to the notification and it opens the B activity with case-1. When i press back i want to go to the A activity and kill B activity. I dont need B activity anymore. Everything easy from here without using flags. When I'm on B activity and press back two times from here, it goes A activity and then closes the app. My trouble here is, if i open the app from navigation buttons of phone (can't remember the name of this button) app is opening from B activity. That's not what i expected. I want to open A activity. Don't want to see B activity anymore.

Case-2

I click to the notification and it opens the B activity with case-2.When i press back i want to bring A activity to the front, without creating anything new. If i press back on B activity, two times and close the app and then again re-open app from navigation button of phone, want to open app from A activity.

So how can i make this correctly, i tried to use flags (i already read docs) but couldn't get work.
What flags should i use when i open the B activity and onBackPress method of B activity to go A activity as i wanted

答:
try this</p>

```<code>android:launchMode="singleTask" in android manifest file
</code>```

Body:
try this

android:launchMode="singleTask" in android manifest file


问:
pandas locate value from 2 lists and store 3º value
I've 2 lists of items like this:

List 1:

```<code>Type;Color;Weight;
Apples;Red;15gr;
Bananas;Yellow;10gr;
Oranges;Orange;15gr;
</code>```

List 2:

```<code>Type;Color;Price;
Bananas;Yellow;1;
Oranges;Orange;0.85;
Apples;Red;0.50;
</code>```

What i need to acomplish is add to the first list a new column with the price values of the 2 list:

List 1:

```<code>Type;Color;Weight;Price;
Apples;Red;15gr;1;
Bananas;Yellow;10gr;0.85;
Oranges;Orange;15gr;0.50;

#!/usr/bin/python
# -*- coding: utf-8 -*-
import pandas as pd
firstList = 'list1.csv'
secondList = 'list2.csv'

class Fruits:
    def Unify(self):
        List1 = pd.read_csv(firstList,encoding='utf-8',delimiter=';')
        List2 = pd.read_csv(secondList,encoding='utf-8',delimiter=',') # Yes, delimiter it's different
        for row in List1:
            if List1[List1.Type.isin[List2['Type']]] == True:
                List1['Price'] = pd.Series(List2['Price'], index=data.index)
                print List1['Type'], List1['Price']
Test = Fruits()
Test.Unify()
</code>```

But when i run the code it gives me this error:

```<code>TypeError: 'instancemethod' object has no attribute '__getitem__'
</code>```

Any idea how i can fix it ?

Thanks in advance.

答:
It seems you need merge if need match types with colors and only common columns names for join on parameter should be omit:

```<code>df = pd.merge(df1,df2)
#if more common columns names
#df = pd.merge(df1,df2, on=['Type','Color'])
print (df)
      Type   Color Weight  Price
0   Apples     Red   15gr   0.50
1  Bananas  Yellow   10gr   1.00
2  Oranges  Orange   15gr   0.85
</code>```

Body:
I've 2 lists of items like this:

List 1:

Type;Color;Weight;
Apples;Red;15gr;
Bananas;Yellow;10gr;
Oranges;Orange;15gr;

List 2:

Type;Color;Price;
Bananas;Yellow;1;
Oranges;Orange;0.85;
Apples;Red;0.50;

What i need to acomplish is add to the first list a new column with the price values of the 2 list:

List 1:

Type;Color;Weight;Price;
Apples;Red;15gr;1;
Bananas;Yellow;10gr;0.85;
Oranges;Orange;15gr;0.50;

#!/usr/bin/python
# -*- coding: utf-8 -*-
import pandas as pd
firstList = 'list1.csv'
secondList = 'list2.csv'

class Fruits:
    def Unify(self):
        List1 = pd.read_csv(firstList,encoding='utf-8',delimiter=';')
        List2 = pd.read_csv(secondList,encoding='utf-8',delimiter=',') # Yes, delimiter it's different
        for row in List1:
            if List1[List1.Type.isin[List2['Type']]] == True:
                List1['Price'] = pd.Series(List2['Price'], index=data.index)
                print List1['Type'], List1['Price']
Test = Fruits()
Test.Unify()

But when i run the code it gives me this error:

TypeError: 'instancemethod' object has no attribute '__getitem__'

Any idea how i can fix it ?

Thanks in advance.

Body:
It seems you need merge if need match types with colors and only common columns names for join on parameter should be omit:

df = pd.merge(df1,df2)
#if more common columns names
#df = pd.merge(df1,df2, on=['Type','Color'])
print (df)
      Type   Color Weight  Price
0   Apples     Red   15gr   0.50
1  Bananas  Yellow   10gr   1.00
2  Oranges  Orange   15gr   0.85


问:
scrapy spider: output in chronological order
I am programming a web crawler in python with Scrapy. The purpose is to monitor changes to a webpage at pre-determined time intervals.
After logging in to the website, the spider requests a web page every X minutes and certain data is extracted from the page and saved to a text file.
It turns out that the text file is written only when the spider closes, and the lines in the text files are not in chronological order. I can't figure it out what is happening. Maybe it's a specific way of working of the Scrapy module? Any ideas?</p>

```<code>import scrapy
from scrapy.http import Request
from scrapy.http import FormRequest
from scraping_example.loginform import fill_login_form
from datetime import datetime
import time

class ExampleSpiderSpider(scrapy.Spider):
    name = 'example_spider'
    allowed_domains = ['example.com']
    start_urls = ['http:/www.example.com/login']
    login_user = 'edging780'
    login_pass = ''

    def parse(self, response):
        (args, url, method) = fill_login_form(response.url,
                response.body, self.login_user, self.login_pass)
        return FormRequest(url, method=method, formdata=args,
                           callback=self.after_login)

    def after_login(self, response):
        for i in range(0,6):
            request = Request('https://www.example.com/page_to_scrape', callback=self.get_table, dont_filter = True)
            request.meta['dateTime'] = str(datetime.now())
            request.meta['order'] = str(i)
            yield request
            time.sleep(600)
        return

    def get_table(self, response):
        table = response.xpath('//table[@class="example_table"]/tbody/tr[not(contains(@class,"thead"))]')
        Data=[]
        for n_row in range(0,len(table)):
            row = table[n_row]
            Data.append(row.xpath('td[1]/text()').extract())

        dictionary = {'Time': response.meta['dateTime'],
                 'Order': response.meta['order'],
                 'Data': Data}
        with open('output.txt', 'a') as f:
            f.write(str(dictionary) + '\n')
        return
</code>```

答:
You might want to read this: https://doc.scrapy.org/en/latest/faq.html#does-scrapy-crawl-in-breadth-first-or-depth-first-order

and this: LIFO (last in, first out)

Scrapy don't handle the requests in the order you give to him, but you can change this behaviour (you have the option described in the link above).

Also, you might want to consider using the Items and the feed exporters instead of handling your items like you do...

Edit:
On top of:

```<code>DEPTH_PRIORITY = 1
SCHEDULER_DISK_QUEUE = 'scrapy.squeues.PickleFifoDiskQueue'
SCHEDULER_MEMORY_QUEUE = 'scrapy.squeues.FifoMemoryQueue'
</code>```

I also needed to set

```<code>CONCURRENT_REQUESTS = 1
</code>```

The latter setting is to make requests one by one

Body:
I am programming a web crawler in python with Scrapy. The purpose is to monitor changes to a webpage at pre-determined time intervals.
After logging in to the website, the spider requests a web page every X minutes and certain data is extracted from the page and saved to a text file.
It turns out that the text file is written only when the spider closes, and the lines in the text files are not in chronological order. I can't figure it out what is happening. Maybe it's a specific way of working of the Scrapy module? Any ideas?

import scrapy
from scrapy.http import Request
from scrapy.http import FormRequest
from scraping_example.loginform import fill_login_form
from datetime import datetime
import time

class ExampleSpiderSpider(scrapy.Spider):
    name = 'example_spider'
    allowed_domains = ['example.com']
    start_urls = ['http:/www.example.com/login']
    login_user = 'edging780'
    login_pass = ''

    def parse(self, response):
        (args, url, method) = fill_login_form(response.url,
                response.body, self.login_user, self.login_pass)
        return FormRequest(url, method=method, formdata=args,
                           callback=self.after_login)

    def after_login(self, response):
        for i in range(0,6):
            request = Request('https://www.example.com/page_to_scrape', callback=self.get_table, dont_filter = True)
            request.meta['dateTime'] = str(datetime.now())
            request.meta['order'] = str(i)
            yield request
            time.sleep(600)
        return

    def get_table(self, response):
        table = response.xpath('//table[@class="example_table"]/tbody/tr[not(contains(@class,"thead"))]')
        Data=[]
        for n_row in range(0,len(table)):
            row = table[n_row]
            Data.append(row.xpath('td[1]/text()').extract())

        dictionary = {'Time': response.meta['dateTime'],
                 'Order': response.meta['order'],
                 'Data': Data}
        with open('output.txt', 'a') as f:
            f.write(str(dictionary) + '\n')
        return

Body:
You might want to read this: https://doc.scrapy.org/en/latest/faq.html#does-scrapy-crawl-in-breadth-first-or-depth-first-order

and this: LIFO (last in, first out)

Scrapy don't handle the requests in the order you give to him, but you can change this behaviour (you have the option described in the link above).

Also, you might want to consider using the Items and the feed exporters instead of handling your items like you do...

Edit:
On top of:

DEPTH_PRIORITY = 1
SCHEDULER_DISK_QUEUE = 'scrapy.squeues.PickleFifoDiskQueue'
SCHEDULER_MEMORY_QUEUE = 'scrapy.squeues.FifoMemoryQueue'

I also needed to set

CONCURRENT_REQUESTS = 1

The latter setting is to make requests one by one


问:
How to use Git credential store on WSL (Ubuntu on Windows)?
I've tried following these instructions: https://stackoverflow.com/a/40312117/21728 which basically do this:

```<code>sudo apt-get install libsecret-1-0 libsecret-1-dev
cd /usr/share/doc/git/contrib/credential/libsecret
sudo make
git config --global credential.helper /usr/share/doc/git/contrib/credential/libsecret/git-credential-libsecret
</code>```

But when I do any network operation, I get this error:

```<code>** (process:7902): CRITICAL **: could not connect to Secret Service: Cannot autolaunch D-Bus without X11 $DISPLAY
</code>```

That's logical I guess as there is indeed no X11 display.

How to make Git credentials caching work on Ubuntu on Windows (WSL)?

答:
If you installed Git for Windows there is a windows integrated credential manager installed on your system.

You can run windows executables from WSL as found here.

To use it you can run the following command (assuming that your git for windows is installed on C:\Program Files\Git)

```<code>git config --global credential.helper "/mnt/c/Program\ Files/Git/mingw64/bin/git-credential-manager.exe"
</code>```

Body:
I've tried following these instructions: https://stackoverflow.com/a/40312117/21728 which basically do this:

sudo apt-get install libsecret-1-0 libsecret-1-dev
cd /usr/share/doc/git/contrib/credential/libsecret
sudo make
git config --global credential.helper /usr/share/doc/git/contrib/credential/libsecret/git-credential-libsecret

But when I do any network operation, I get this error:

** (process:7902): CRITICAL **: could not connect to Secret Service: Cannot autolaunch D-Bus without X11 $DISPLAY

That's logical I guess as there is indeed no X11 display.

How to make Git credentials caching work on Ubuntu on Windows (WSL)?

Body:
If you installed Git for Windows there is a windows integrated credential manager installed on your system.

You can run windows executables from WSL as found here.

To use it you can run the following command (assuming that your git for windows is installed on C:\Program Files\Git)

git config --global credential.helper "/mnt/c/Program\ Files/Git/mingw64/bin/git-credential-manager.exe"


问:
Delete first two characters of elements in a list of lists
Let's say I have the following list of lists:

```<code>final_list = [[1,'pppizza',3,4],[1,'mmmonkey',9,10],[1,'dddoublerainbow',8,2]]
</code>```

Now I need to remove the first 2 characters of the second element of every list, so the result will be:

```<code>final_list = [[1,'pizza',3,4],[1,'monkey',9,10],[1,'doublerainbow',8,2]]
</code>```

答:
use double list comprehensions:

```<code>final_list = [[x if hasattr(x, '__len__') and i == 1 else x[2:] for i, x in enumerate(y)] for y in my_list]
</code>```

this will trim the first 2 elements of the second element, even if the element is not a string

If you want it for strings only then the statement becomes:

```<code>final_list = [[x if type(x) == str and i == 1 else x[2:] for i, x in enumerate(y)] for y in my_list]
</code>```

Body:
Let's say I have the following list of lists:

final_list = [[1,'pppizza',3,4],[1,'mmmonkey',9,10],[1,'dddoublerainbow',8,2]]

Now I need to remove the first 2 characters of the second element of every list, so the result will be:

final_list = [[1,'pizza',3,4],[1,'monkey',9,10],[1,'doublerainbow',8,2]]

Body:
use double list comprehensions:

final_list = [[x if hasattr(x, '__len__') and i == 1 else x[2:] for i, x in enumerate(y)] for y in my_list]

this will trim the first 2 elements of the second element, even if the element is not a string

If you want it for strings only then the statement becomes:

final_list = [[x if type(x) == str and i == 1 else x[2:] for i, x in enumerate(y)] for y in my_list]