text:
Q: Microsoft Sculpt mobile keyboard reverse Fn keys I have just got my new Microsoft sculpt mobile keyboard, and it works fine.
However the Fn keys are reversed by design.
I mean by pressing F6 for example, the Search charm appears on Windows 8, and i can use F6 if i press the Fn key together with it. Is there any way i can change how it works? It would be verry important for me, i lost many hotkey combination this way :\
Its a bluetooth wireless keyboard, i could not finy any bios setting for it (like some laptops, but i'm on desktop PC). i have

A: The hardwiring of the Windows 8 Keys as the default keys instead of the more often used Function Keys drove me nuts.  I have far more use for the F1 to F12 keys than the Windows 8 Keys, particularly in Mac OS X.
This is a hardwired feature of the Microsoft Sculpt Mobile Keyboard.
The only solution which works is to sacrifice the Windows 8 keys by permanently setting the Fn in the down position.
I did this by popping off the Fn Key and taping the switch in the down position.  I used double-stick permanent mounting tape for adhesion which was then covered by black gaffers tape.
I love that my Function Keys now work as I want them to.
Sure, I no longer have keyboard support for volume - compared to the Microsoft Bluetooth Mobile Keyboard 6000.  But I do gain a hardwired Home and End Keys.  And I can easily create a macro to control the volume.
Since the Sculpt Keyboard is also half the price of the Keyboard 6000, this hardware modification saves me $20 every time I wear out the keyboard.
I wouldn't worry about battery life from keeping the Fn key pressed down since usually I turn off the keyboard when not used - when the keyboard is used as a mobile keyboard.  When used as a desktop keyboard, we will have to see if battery life is reduced.

A: As per @AkA Kin and @Yuji it seems that AutoHotKey is the solution. Found this great script by tehshane that "remaps the F1-F12 function keys on the Microsoft Sculpt Mobile keyboard to be pressed without having to use the Fn key":
https://gist.github.com/tehshane/8765405

A: There's no solution... yet. See this thread:
http://social.technet.microsoft.com/Forums/windows/en-US/bdb36756-b0d3-49f7-932a-ca9d6108192a/sculpt-mobile-keyboard-is-not-recognized-by-mouse-and-keyboard-center

A: I installed AutoHotKey and the following script worked for me. I'm using Windows 7 though... Don't know if that matters.
Media_Play_Pause::F1
Volume_Mute::F2
return
Volume_Down::F3
Volume_Up::F4
<+<#F21::F5
<!<#F21::
Send,{F6}
return
<^<#F21::
Send,{F7}
return
<#F21::
Send,{Blind}{F8}
return
<^<#BS::
Send,{F9}
return
<^<#Tab::
Send,{F10}
return
<!<#F22::
Send,{F11}
return
<^<#F23::
Send,{F12}
return

A: There's a keyboard shortcut for this on the keyboard covers for the Surface (which is also locked in "media key" mode by default): Fn+CapsLock.  It's worth a try.

A: After A long time search
I find Autohotkey can resolve F1-F4, but for F5-F12 It's not very easy to use.
I don't want to wast my time to learn how to use that.
The easiest way is past a Scotch tape on the FN key I think....


text:
Q: Getting data based on location and a specified radius Scenario: I have a large dataset, with each entry containing a location (x,y - coordinates).
I want to be able to request every entry from this dataset that is within 100m within this dataset and have it returned as an array.
How does one go about implementing something like this? Are there any patterns or framework that recommended? I've previously only worked with relational or simple key-value type data.

A: The data structure that solves this problem efficiently is a k-d tree. There are many implementations available, including a node.js module.

A: Put your  data set into PostgreSQL and use an R-Tree index. You can then do a bounding box  query to get all points with +-100 miles of any locations.  Then calculate the radial distance and accept points within 100 miles. You can roll your own schema and queries or use PostGIS.
Unlike R-Trees KD-trees are not inherently balanced.  So depending on how a KD-Tree is built you can get inconsistent performance due to unbalanced trees and the longest path.

redpajama_set_name: RedPajamaStackExchange


text:
Q: calling custom and delegate method from another class I am a beginner in objective c. I have two classes Connectivity and SignInViewController, and what i want is to call the methods defined in a class on a single call from another class. I came to know that, i can achieve it through protocol or delegation, but still wondering if there would be any simple way to do this. when i debug the code, i can see that the control is going to the SigninViewController after executing the +(void)connectWithURL:(NSURL *)URL withData:(NSString *)postedData method. But what i want is to execute all the method(delegation methods defined below) of connectivity class first and after that control should go back to the SigninViewController. Hope, i asked it clearly.
`// connectivity.h
 #import<Foundation/Foundation.h>
@interface Connectivity : NSObject<NSURLConnectionDelegate, NSURLConnectionDelegate>
+(void)connectWithURL:(NSURL *)URL withData:(NSString *)postedData;
@end

//connectivity.m
#import "Connectivity.h"
NSMutableData *_receivedData;
@implementation Connectivity
+(void)connectWithURL:(NSURL *)URL withData:(NSString *)postedData
{
//Create the Request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
NSLog(@"posted url %@", URL);
//Create The Method "POST"
[request setHTTPMethod:@"POST"];
//header
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded"   forHTTPHeaderField:@"Content-Type"];

//Pass the String to the Server
NSString *postString = [NSString stringWithString:postedData];

//Check the Passed Value
NSLog(@"post string =%@", postedData);
//Convert the String to Data
NSData *data1 = [postedData dataUsingEncoding:NSUTF8StringEncoding];
//Apply the Data to the Body
[request setHTTPBody:data1];
//connection to the webserver

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
                                                              delegate:self];
[connection start];
}
#pragma mark NSURLConnection Delegate Methods

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{

[_receivedData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.

[_receivedData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// do something with the data

NSLog(@"Succeeded! Received %lul bytes of data",[_receivedData length]);
NSString *responeString = [[NSString alloc] initWithData:_receivedData
                                                encoding:NSUTF8StringEncoding];

connection = nil;
_receivedData = nil;
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{

connection = nil;
_receivedData = nil;

// inform the user

NSLog(@"Connection failed! Error - %@ %@",
      [error localizedDescription],
      [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
@end

//I am calling the method in
    (SignInViewController.m)
#import "SignInViewController.h"
#import "AlertMessageViewController.h"
#import "Connectivity.h"

@interface SignInViewController ()

@end

@implementation SignInViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
-(void)loginCustomUser
{

if([[self.emailTextField text] isEqualToString:@""] || [[self.passwordTextField text] isEqualToString:@""])
{
  [self presentViewController:[AlertMessageViewController alertWithTitle:@"Error" withMessage:@"Enter email and Password" preferredStyle:UIAlertControllerStyleAlert] animated:YES completion:nil];
}
else
{
NSString *data = [NSString stringWithFormat:@"{\"rqBody\":{\"emailId\":\"%@\",\"password\":\"%@\",\"userId\":\"%@\",\"idType\":\"%@\",\"firstName\":\"%@\",\"lastName\":\"%@\",\"contactNumber\":\"%@\",\"firstLineOfAddress\":\"%@\",\"localityName\":\"%@\",\"city\":\"%@\",\"state\":\"%@\",\"country\":\"%@\",\"roleType\":\"%@\",\"paymentProfile\":\"%@\",\"paymentDate\":\"%@\",\"registerationStatus\":\"%@\",\"loggedStatus\":\"%@\",\"lastLoggedInDate\":\"%@\",\"registerationDate\":\"%@\",\"profileStatus\":\"%@\"}}",[self.emailTextField text],[self.passwordTextField text],@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",nil];

    NSURL *mainUrl= [NSURL URLWithString:@"http://192.168.1.5:8080/referamaid/app/noauth/signin"];

    [Connectivity connectWithURL:mainUrl withData:data];

}
}
@end`

A: - (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    NSString *response = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];

//      NSLog(@"%@",response);
//    NSLog(@"TAG== %d",  self.tag);

    NSDictionary *responseJson = [response JSONValue];

    NSError *error;

    JSONDecoder *jsonKitDecoder = [JSONDecoder decoderWithParseOptions:JKParseOptionValidFlags];

    NSDictionary *dictionary;
    if ([[jsonKitDecoder objectWithData:receivedData] valueForKey:@"d"])
    {
        dictionary = [[[jsonKitDecoder objectWithData:receivedData] valueForKey:@"d"] objectFromJSONString];
    }
    else
    {
        dictionary = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions | NSJSONReadingAllowFragments |NSJSONReadingMutableContainers error:&error];
    }

    //      NSLog(@"responseJson== %@",  [responseJson valueForKeyPath:@"data.WorkCell.label"]);

//    NSLog(@"%@",_delegate);

        if(_delegate){
            if ([_delegate respondsToSelector:@selector(requestFinished:withInfo:)]) {

                [_delegate requestFinished:self withInfo:dictionary];
                isRequest = FALSE;
            }
        }
    }

@protocol RequestDelegate <NSObject>

@optional
-(void)requestStarted:(Request *)request;
-(void)requestFailed:(Request *)request withError:(NSError *)error;

@required
-(void)requestFinished:(Request *)request withInfo:(NSDictionary *)info;

@end

Not perfect answer, but you can match by declaring a delegate in Connectivity.m class. Implement the methods of delegates in SignInViewController, by this way you can achieve this.
Do not for get to assign the delegate to SignInViewController.


text:
Q: Why does my JS object end up having "undefined" values? var testRuleInput = {
    "ruleName" : "renderDataVerificationFields",
    "dependencies" : [
        {
            "fieldName" : "mailingStreetAddress",
            "resource" : "verificationResults",
            "attribute" : "verifyStreetAddress"
        }
    ]
};

However, when I later call console.log(testRuleInput.dependencies.attribute); I get undefined. Confused!

A: dependencies is an array of objects.
Update your code with:
console.log(testRuleInput.dependencies[0].attribute)

Or drop the array syntax:
"dependencies": {
    "fieldName": "mailingStreetAddress",
    "resource": "verificationResults",
    "attribute": "verifyStreetAddress"
}

A: This is because dependencies is an array. I think you're looking for testRuleInput.dependencies[0].attribute.

A: You're using an array.
testRuleInput.dependencies[0].attribute

Remove the square brackets if you only want 1 dependency or index it properly like the above.
var testRuleInput = {
                        "ruleName" : "renderDataVerificationFields",
                        "dependencies" : {
                            "fieldName" : "mailingStreetAddress",
                            "resource" : "verificationResults",
                            "attribute" : "verifyStreetAddress"
                        }
                   };

A: testRuleInput.dependencies is an array. If you use testRuleInput.dependencies[0].attribute you'll get what you're expecting.


text:
Q: What happens to the reputation associated with a question if it is removed? If a question is flagged to be removed, but it has some reputation associated with it, what happens to that reputation?
If the user has reputation from up votes on the question, will the user loose that reputation?
Does removing questions with down votes return lost reputation to affected users?

A: There are a lot of useful questions, however the large majority of questions are not suitable for asking on stackoverflow. Read the FAQ and this page, then I'm sure you'll understand why the community chose to close your question. In short, it falls out of the scope of SO. If it is a good question about something technical, there are probably other stackexchange sites that will entertain it.

A: Removing a question has nothing to with Upvotes and Downvotes. Its still valid to close the question though it is Upvoted/Downvoted.
Check Deleted question link (Page Not Found Page)  it states:
This question was removed from Stack Overflow for reasons of moderation. Please refer to the FAQ for possible explanations why a question might be removed
From the Deletion FAQ:

Questions that are extremely off topic, or of very low quality,
     may be removed at the discretion of the community and moderators.
Over time, closed questions that are not useful as signpoints to other questions
     may also be removed, as well as questions which have no significant activity over
     a very long period after being asked.


text:
Q: If motion relative to a frame of reference is purely relative, how do we account for the work done to move relative to the frame of reference? I get the idea that everything is in motion, and there's no absolute reference frame for everything.
But when we consider local events, like a train passing through a town, I have trouble accepting the notion that we have no principled way of asserting the perspective that the train is moving relative to the town over the perspective that it's the train that is stationary and it's the town (and the rest of the Earth) that is moving relative to the train.   The thing that to my mind privileges the perspective that it is the train that is moving is the history of the event, i.e., the fueling of the train, the starting  of the engine, the releasing of the brake, etc.
Are we saying that that work history, and the history and purpose of those who caused it to happen, could just as easily be said to have caused the town and the rest of the earth to move past the train, that that work history modified the earth's orbit just enough to create the illusion that the train moves past the town?

A: As you point out, it's only your own knowledge of the fueling of the train, etc. that biases your perspective. Imagine for a moment that someone built a very large and elaborate treadmill for the train, so that the train really did stand still with respect to the earth, and that it was actually the landscape passing by instead. The equivalence principle tells us that all inertial frames are equivalent, so you have absolutely no means of telling whether you're on a fueled-up train that propels itself down the track, or a train filled with dummy coal that's on a treadmill with the landscape speeding by.
When you talk about the train accelerating, you now have a non-inertial reference frame, which is not equivalent to inertial frames. When the train starts moving and lurches forward, people on the train naturally take a step backwards to balance themselves. You can't treat this as equivalent to the rest of the world lurching backwards - you don't see people in the station balance themselves as the train leaves!

A:
Are we saying that that work history, and the history and purpose of those who caused it to happen, could just as easily be said to have caused the town and the rest of the earth to move past the train, that that work history modified the earth's orbit just enough to create the illusion that the train moves past the town?

Yes, exactly. If you think about it, that should not be terribly surprising. After all, work, energy, and other physical principles simultaneously describe the town at rest and the train moving, as well as the sun at rest and the town moving (with the earth), as well as the galaxy at rest and the sun moving, ...
In one case the simplest frame is the one where the town is stationary, but in another case it is one where the sun is stationary. Both cases are equally valid. So if both of those cases are equally valid then it shouldn't be surprising that the case where the train is stationary is also valid.
There is no physical significance to the choice of reference frame. It is a mathematical convenience only. So we always should seek to choose the most convenient frame to work with, knowing that our choice has no physical significance.

A: No. The idea of relativity is that locally the laws of physics are always the same in an inertial (constant linear velocity) reference frame.   Meaning if you are in a sealed box with no access to the outside (Einstein used the example of an elevator), no experiment you can do will let you distinguish your state of motion.  In fact, the size of "local" might get very small, becoming an infinitesimal, in the presence of gravity gradients or other geometrically changing environments.
Your are correct that looking at the global environment and history of an object, one can establish a sensible idea of what is "really" moving.  But that is for our benefit.   The laws of physics do not care.

A: The principle of relativity says that the laws of physics on the train right now are exactly the same as on the station platform, and so there is no way to logically conclude from observations made right now that one is moving and the other is not. It says nothing about how they came to be in relative motion. Maybe the train started out from this station or another station an hour ago. Or maybe it has always been moving at the same speed relative to the station. We don't know, and the laws of physics cannot tell us.

A: You are misunderstanding what it means to say that all motion is relative. Motion just means changes in positions and distances. If you say the train is moving at thirty miles per hour relative to the station, you mean that the gap between the station and the train is growing at thirty miles every hour. It doesn't matter whether you consider that the train is moving or that the station is- the gap is growing at the same rate either way.
When you say 'we have no way of knowing whether the train is moving relative to the town or the town is moving relative to the train', the reality is that by definition both are happening. 'The town is moving relative to the train' is perfectly correct- you are simply describing events from a particular frame of reference.
Yes, you know for sure that the train was formerly stationary with respect to the town and has been accelerated to its present speed, rather than the town having been accelerated to 30mph in the other direction. But so what? In the reference frame of a spaceship passing the Earth at 30mph, the train now seems to be stationary and the Earth is moving at 30mph the other way.


text:
Q: Android: custom shaped button I'm looking the best way to create a group of four buttons.

Each button is an image. So, I think about just create a "big" square from four small images-buttons and then rotate them.

The question is: how to rotate layout in xml? Is it possible?

Is there any better way to create such group of buttons?

Thank you!

A: One way to do this is to create a single ImageButton, then use trigonometry to work out where the user has clicked on the circle, using data from an onClick() event and the centre of the button. This question may help:
Get the co-ordinates of a touch event on Android

A: The ultimate answer is to use a pathshape button. Then it handles everything for you.
Create the paths with Path the shapes with Shape and the composite pathshape with
Pathshape.
That way you can do it even in XML.
And there's a variety of arc path methods.
Check it out!


text:
Q: get amount between range This a simple my table
+-----------+----------------+-----------+
|     id    |       date     |   meter   |
------------+----------------+-----------+
|      1    |  2103-11-01    |   5       |
|      2    |  2103-11-10    |   8       |
|      4    |  2103-11-14    |   10      |
|      6    |  2103-11-20    |   18      |
|      7    |  2103-11-25    |   25      |
|      10   |  2103-11-29    |   30      |
+-----------+----------------+-----------+

how do I get the results to the use of meters between two ranges of the results of recording time,
like bellow
+----------------+----------------+-------+-----+--------+
|    date1       |    date2       | start | end | amount |
+----------------+----------------+-------+-----+--------+
|    2013-11-01  |    2013-11-10  |  5    |  8  |  3     |
|    2013-11-10  |    2013-11-14  |  8    | 10  |  2     |
|    2013-11-14  |    2013-11-20  | 10    | 18  |  8     |
|    2013-11-20  |    2013-11-25  | 18    | 25  |  7     |
|    2013-11-25  |    2013-11-29  | 25    | 30  |  5     |
+----------------+----------------+-------+-----+--------+

A: Edit:
I got it:
select meters1.date as date1, min(meters2.date) as date2, meters1.meter as start,
  meters2.meter as end, (meters2.meter - meters1.meter) as amount
  from meters meters1, meters meters2 where meters1.date < meters2.date
   group by date1;

Outputs:
+------------+------------+-------+-----+--------+
| date1      | date2      | start | end | amount |
+------------+------------+-------+-----+--------+
| 2013-11-01 | 2013-11-10 |     5 |   8 |      3 |
| 2013-11-10 | 2013-11-14 |     8 |  10 |      2 |
| 2013-11-14 | 2013-11-20 |    10 |  18 |      8 |
| 2013-11-20 | 2013-11-25 |    18 |  25 |      7 |
| 2013-11-25 | 2013-11-29 |    25 |  30 |      5 |
+------------+------------+-------+-----+--------+

Original Post:
This is most of the way there:
select meters1.date as date1, meters2.date as date2, meters1.meter as start,
  meters2.meter as end, (meters2.meter - meters1.meter) as amount
  from meters meters1, meters meters2 having date1 < date2 order by date1;

It outputs:
+------------+------------+-------+-----+--------+
| date1      | date2      | start | end | amount |
+------------+------------+-------+-----+--------+
| 2013-11-01 | 2013-11-10 |     5 |   8 |      3 |
| 2013-11-01 | 2013-11-20 |     5 |  18 |     13 |
| 2013-11-01 | 2013-11-29 |     5 |  30 |     25 |
| 2013-11-01 | 2013-11-14 |     5 |  10 |      5 |
| 2013-11-01 | 2013-11-25 |     5 |  25 |     20 |
| 2013-11-10 | 2013-11-20 |     8 |  18 |     10 |
| 2013-11-10 | 2013-11-29 |     8 |  30 |     22 |
| 2013-11-10 | 2013-11-14 |     8 |  10 |      2 |
| 2013-11-10 | 2013-11-25 |     8 |  25 |     17 |
| 2013-11-14 | 2013-11-25 |    10 |  25 |     15 |
| 2013-11-14 | 2013-11-20 |    10 |  18 |      8 |
| 2013-11-14 | 2013-11-29 |    10 |  30 |     20 |
| 2013-11-20 | 2013-11-25 |    18 |  25 |      7 |
| 2013-11-20 | 2013-11-29 |    18 |  30 |     12 |
| 2013-11-25 | 2013-11-29 |    25 |  30 |      5 |
+------------+------------+-------+-----+--------+

A: If it's SQL server try it this way
WITH cte AS
(
  SELECT *, ROW_NUMBER() OVER (ORDER BY date) rnum
    FROM table1
)
SELECT c.date date1, p.date date2, c.meter [start], p.meter [end], p.meter - c.meter amount
  FROM cte c JOIN cte p
    ON c.rnum = p.rnum - 1

Here is SQLFiddle demo

If it's MySQL then you can do
SELECT date1, date2, meter1, meter2, meter2 - meter1 amount
  FROM
(
  SELECT @d date2, date date1, @m meter2, meter meter1, @d := date, @m := meter
    FROM table1 CROSS JOIN (SELECT @d := NULL, @m := NULL) i
   ORDER BY date DESC
) q
 WHERE date2 IS NOT NULL
 ORDER BY date1

Here is SQLFiddle demo
Output in both cases:

|      DATE1 |      DATE2 | START | END | AMOUNT |
|------------|------------|-------|-----|--------|
| 2103-11-01 | 2103-11-10 |     5 |   8 |      3 |
| 2103-11-10 | 2103-11-14 |     8 |  10 |      2 |
| 2103-11-14 | 2103-11-20 |    10 |  18 |      8 |
| 2103-11-20 | 2103-11-25 |    18 |  25 |      7 |
| 2103-11-25 | 2103-11-29 |    25 |  30 |      5 |

A: MySql
SELECT DATES.date1,
       DATES.date2,
       m1.meter as start,
       m2.meter as end,
       m2.meter - m1.meter as amount
FROM
  (SELECT date as date1,
       (SELECT min(date)
        FROM tableName t2
        WHERE t2.date > t1.date) as date2
   FROM tableName t1
  )DATES,
  tableName m1,
  tableName m2
WHERE DATES.date2 IS NOT NULL
  AND m1.date = DATES.date1
  AND m2.date = DATES.date2
ORDER BY DATES.date1

sqlFiddle here
in MS-SQL SERVER 2002 change the word end to "end" as it complains about syntax near end

A: If you're using MySQL, then a self-join will work well here. Join the table to itself, using an ON clause to make sure you don't join the same record to itself. This will give you ((N * N) - N) permutations of your data, where N is the number of original rows.
SELECT
    ...
FROM
    tableName first
JOIN
    tableName second
    ON first.id != second.id

Then, it's all about SELECTing the right stuff (including the calculation of the difference between the two meter values). To get the columns in the result set you posted, you'd probably want to SELECT:
first.date AS date1,
second.date AS date2,
first.meter AS start,
second.meter AS end,
ABS(first.meter - second.meter) AS amount

Edit
Ah, I see. I'd envisioned something like a inter-city mileage chart that you used to see on road maps (where you'd have the same cities in the rows and columns, and the cell in the intersection would indicate the number of miles between those two cities.
But it looks like you just want to compare values from one date to the next. If that's the case, you can take advantage of the way MySQL handles GROUPing and ORDERing... but be careful, because I'm not sure this is guaranteed:
mysql> SELECT
    table1.date AS date1,
    table2.date AS date2,
    table1.meter AS start,
    table2.meter AS end,
    ABS(table1.meter - table2.meter) AS amount
FROM tableName table1
JOIN tableName table2
    WHERE table2.date > table1.date
GROUP BY table1.date
ORDER BY table2.date - table1.date;
+---------------------+---------------------+-------+------+--------+
| date1               | date2               | start | end  | amount |
+---------------------+---------------------+-------+------+--------+
| 2103-11-25 00:00:00 | 2103-11-29 00:00:00 |    25 |   30 |      5 |
| 2103-11-10 00:00:00 | 2103-11-14 00:00:00 |     8 |   10 |      2 |
| 2103-11-20 00:00:00 | 2103-11-25 00:00:00 |    18 |   25 |      7 |
| 2103-11-14 00:00:00 | 2103-11-20 00:00:00 |    10 |   18 |      8 |
| 2103-11-01 00:00:00 | 2103-11-10 00:00:00 |     5 |    8 |      3 |
+---------------------+---------------------+-------+------+--------+
5 rows in set (0.00 sec)

A: You haven't made it clear whether you're really using mySQL or SQL Server but I'm posting a solution that works for SQL 2008 and above.  Might work for 2005 but I can't test that.
-- Set up a temp table with sample data
DECLARE @testData AS TABLE(
    id int,
    dt date,
    meter int)

INSERT @testData(id, dt, meter) VALUES
     (1, '2013-11-01', 5)
    ,(2, '2013-11-10', 8)
    ,(4, '2013-11-14', 10)
    ,(6, '2013-11-20', 18)
    ,(7, '2013-11-25', 25)
    ,(10, '2013-11-29',30)
---------------------------------------------

-- Begin SQL Server solution
;WITH cte AS (
    SELECT
        ROW_NUMBER() OVER (ORDER BY id) AS rownum
        ,id
        ,dt
        ,meter
    FROM
        @testData AS [date2]
)

SELECT
     t1.id
    ,t1.dt AS [date1]
    ,t2.dt AS [date2]
    ,t1.meter AS [start]
    ,t2.meter AS [end]
    ,t2.meter - t1.meter AS [amount]
FROM
    cte t1
    LEFT OUTER JOIN cte t2 ON (t2.rownum = t1.rownum + 1)
WHERE
    t2.dt IS NOT NULL


text:
Q: Why does the Wizarding World have a binary perspective on Muggle interactions? As I get older, the more I struggle to understand the Wizarding World's relationship to muggles. The Wizarding World seems to have two chief perspectives on how to interact with muggles.

*

*Go to extreme lengths to hide the existence of wizards from muggles, in hopes to protect wizard and muggle alike.

*Reveal wizarding existence to muggles, and dominate over muggles.

I understand there exists historical reasoning behind both of these perspectives, but what strikes me is their extremely binary nature. From my perspective, there seems to be a clear middle ground that is left out of the discussion...
Reveal wizarding existence to muggles, and attempt peaceful coexistence with one another.
To be clear, I am not arguing that this position would work out (though it may), but the lack of advocacy is bizarre IMO. Particularly because it is easy to imagine that witches and wizards with ties to the muggle world (and many without) would feel a moral imperative to use their talents for the betterment of the world as a whole.
Surely a witch like Hermione would have feelings about the fact that she could fix dental fillings in seconds by uttering the word "repairo", and it took her parents years of schooling to do the same in a two-hour torture session?
Dentistry jokes aside, the use of magic outside the magical world would have profound implications. Human conflict, famine, climate change, crime, medical suffering, economics...
To be fair, I do feel like the separation of wizarding and muggle worlds helps make the story immersive, but I do wish there was more explanation as to why these two positions dominate wizarding culture.
Is there something in canon I am missing?

A: To start, you don't sound to be missing any canon that I'm aware of. I've read and watched the series numerous times. Two of the reasons Rowling has her characters state for the separation of the worlds could also explain the two stances toward muggles.

*

*"In Harry Potter and the Prisoner of Azkaban, Harry writes an essay on medieval witch burning, which was cited as the reason behind the introduction of the International Statute of Wizarding Secrecy, and wizards going into hiding from the Muggle world."

*"A great deal of effort is expended in keeping the Muggles unaware of magic. Originally the two worlds co-existed; however, persecution of those with magic meant laws have been put in place over the centuries, designed to keep the existence of the magical world hidden from Muggles. The first and most important statute is the International Statute of Wizarding Secrecy of 1692. Enchantment of Muggle artefacts is forbidden; underage wizards are restricted from using magic outside the school, and any deliberate revelation of magical ability to the Muggle community is punishable."
These are both from Wikipedia and are derived from the books.
The way that the two worlds have developed parallel to one another has only served to reinforce either A. the wizarding world's parent-like, mild derision toward the muggles, or B. the wizarding world's resentment toward having to remain hidden from an arguably inferior side of humanity.
However, there are those idealists in the wizarding world who believe in a third path (Dumbledore, some of the other professors, some of the students, some members of Order of the Phoenix) and they are generally depicted as the background heroes, or voices of reason, in the series.

A: Your proposal is roughly discussed between Harry and Hagrid in The Philosopher's Stone:

"But what does a Ministry of Magic do?"
"Well, their main job is to
keep it from the Muggles that there's still witches an' wizards up an'
down the country."
"Why?"
"Why? Blimey, Harry, everyone'd be wantin'
magic solutions to their problems. Nah, we're best left alone."

The point is that magical power would be revolutionary for Muggle economy.
Extending your example of "Reparo teeth!" - it means the end of dentistry and connected industries. On one hand lots of Muggles would demand Wizards to fix their teeth immediately and costless. On the other hand the dentists and business owners would really hate Wizards.
That applies to most of Muggle professions and industries. So in a natural way, with no bad intentions, the Wizards would dominate Muggle world. And probably would be hated by most of the Muggles which might lead to repeated medieval witch burning.


text:
Q: In MongoDB how to use "$expr" with an array? Let's say I have the below document:
{
 MyField1: 'A',
 MyArray: [
  {
   MyArrayField1: 'C';
  },
  {
   MyArrayField1: 'A';
  }
 ]
}

How can I select all documents in MyArray an object with MyArrayField1 = MyField1?
I tried

db.find({$expr: {$eq: ["$MyArray.MyArrayField1",
  "$MyField1"]}})

even

db.find({$expr: {$eq: ["$MyArray.MyArrayField1",
  "A"]}})

but it's not working :(

A: You can use $in operator
db.col.find({
    $expr: {
        $in: [ "$MyField1", "$MyArray.MyArrayField1" ]
    }
})

In this case MyArray.MyArrayField1 will represent an array of two values A and C


text:
Q: Send images using parse and sinch I  am working on an android Instant messaging application using parse and sinch so far I am able to send text messages between users (one on one). I would like to know if theres a way that I can send media files like images,videos, etc. Thank you in advance.

A: Currently you can not have attachments on an IM message with sinch.


text:
Q: Hardening authorized_keys used in rsync backup
*

*I'm trying to make a rootfs backup from ServerA on to ServerB.

*The connection is one way and is initialized from ServerB using rsnapshot.

*I have made a backup account on ServerA and enabled paswordless sudo only for rsync
What I'm trying to accomplish:

*

*Change the authorized_keys file on ServerA, so only the rsync command can be used via ssh.

On ServerB - /etc/rsnapshot.conf is setup to run rsync with the following args:

*

*rsync_long_args --rsync-path="sudo rsync" --delete --numeric-ids --relative --delete-excluded

I have tried the following on ServerA:

*

*from="ServerB",command="sudo rsync *" ssh-ed25519 SSH-KEY
But rsnapshot keeps crashing and giving IO error codes for rsync.
What am I missing here?

A: !! Problem Solved !!
Found out about rrsync --- /usr/share/doc/rsync/scripts/rrsync, copy it to wherever.

*

*ServerA:authorized_keys --- command="sudo /usr/local/bin/rrsync -ro /backup"
Since I'm keeping a copy of the backups on ServerA, I might as well rsync from them instead of using rsnapshot on ServerB. (This was my initial idea, but it doesn't work since there are duplicate files because of links that rsnapshot creates, I ended up having rsnapshot running both on ServerA and ServerB, to save backups from ServerA to a localDir on ServerA and also make remote snapshots from ServerA to ServerB.)

*

*Also changed the sudoers file on ServerA:

Defaults!/usr/local/bin/rrsync env_keep += "SSH_ORIGINAL_COMMAND"
backup ALL = (root) NOPASSWD: /usr/local/bin/rrsync

*

*rsync -ax --delete --numeric-ids --relative ServerA:/ /ServerB-backup/
Now works as expected.
Note that the path on ServerA in the command above is relative to the rule set in authorized_keys.


text:
Q: check if EndExecuteNonQuery was successful  insComment.EndExecuteNonQuery();

Am trying to insert values into a database. What I need is to know if the code was succesfull then I display a success message.
if(insComment.EndExecuteNonQuery()){
show some message

}

Is that a workable option?

A: if the record is successfully inserted, then it will return 1 and you can prompt message accordingly
Should be like...
if(insComment.EndExecuteNonQuery() == 1)
{
  show some message
}


text:
Q: What will happen if I reconnect 2 halves of two-way RAID mirror after using them independently? Suppose I have a storage space with two-way mirror based on 2 physical USB drives a and b.
Then I disconnect b and connect it to another computer.
Then I use—write some data—to both degraded storage spaces on both computers.
Then I connect drive b back together with drive a on the same computer.

*

*Will "Repairing" cycle happen after this procedure?

*Will data from drive a take preference after "Repairing" cycle?

*Will it make difference if before reconnecting them together, I disconnect both a and b?

*Will data from last disconnected drive take preference after "Repairing" cycle?

*Will data from last written drive take preference after "Repairing" cycle?

*Will data be merged by taking last modified 256Mb slabs from both drives?

*Will data be merged by taking last modified file system cluster from both drives?

Same question about the same procedure with hardware RAIDs.

A: These are some interesting questions, mixed with some odd ones... But this seems to be getting outside the intended use of Storage Spaces. This is really something you should consider just experimenting with if you can.
RE "same thing for hardware RAID": for almost all hardware RAID, the "current configuration" is stored on the controller and the drives. Once 1 drive is removed from a mirror, the config on the controller and remaining drive are updated to reflect that the other disk is a "failed" member of the mirror. If you take that drive elsewhere and try to make changes on it, then bring it back and reconnect it, its config will have been modified by the alternate controller and the original will mark it as "foreign". With a foreign configuration, you are forced to choose 1: clear the foreign config to keep the original config, or "import" to take the modified drive's config as the new good one, which would invalidate the original config on the other drive (and clear it).


text:
Q: Conic Section Intuition I am able to follow the procedure of rewriting a general conic section in standard form but have a question concerning what is actually happening geometrically at each step. I will break these down into several parts:
1, The general equation of the conic section is $ax^2 + bxy + cy^2 + dx + ey + f =0$. How can we understand this as being a slice of a cone by a plane? When I google the picture of the various conic sections available, we have this double cone whose equation is presumably $X^2+Y^2=|Z|$ where I've introduced $(X,Y,Z)$ as coordinates on an ambient 3d space whilst $(x,y)$ are coordinates on the 2d plane. The equation of the plane in the ambient 3d space is going to be like $AX+BY+CZ=Q$. Now, if I substitute $Z=\frac{1}{C(Q-AX-BY)}$ into the cone equation and relabel the constants, I can get something like $X^2+Y^2+DX+EY+F=0$ but this has no $XY$ cross term, nor do I understand how to get it in terms of the $(x,y)$ coordinates that exist on the 2d planar surface (and thus that actually describe the conic section).
TLDR: Where does the general equation of the conic section come from? Can somebody convince me that it is indeed the intersection of a cone and a plane?
2, We can then rewrite $ax^2+bxy+cy^2+dx+ey+f=0$ as $\vec{x}^T A \vec{x} + \vec{v}^T \cdot \vec{x} + f=0$. My question here is what does each part describe? Intuitively I thought that $\vec{v}^T \cdot \vec{x}$ represents a translation of the cone within the ambient 3d space such that we get the same conic section but "off=centre" in terms of the 2d coordinates $(x,y)$. Is this true? If I have $b=0$ and keep the plane in the same place but move the cone then surely their intersection will not only have a different centre, but it will also have a different size i.e. it will be the same shape of section but either scaled up or down - do people agree with this? Then surely this term needs to describe more than just a translation but also a scaling - does this happen?
3, What about the case where $b \neq 0$. In this case, I have read that this represents a rotation of the conic section. What causes this - does the cone rotate or the plane? This is a part that I really struggle to get my head around since the matrix $A$ does not have unit determinant and therefore doesn't represent a rotation matrix, does it? Typically we would construct the matrix of orthonormal eigenvectors $P$ which would have unit determinant and use this to describe a rotation to a new coordinate system $(x',y')$ in which the conic section assumes the standard form. As I understand it, the symmetry of $A$ means that there will always exist such a $P$ that orthogonally diagonalises $A$ (spectral theorem) and thus $P$ describes a rotation from $(x,y)$ to $(x',y')$ where $x'$ and $y'$ point in the eigendirections of $A$ i.e. the eigendirections are the new major and minor axes for the conic section when written in $(x',y')$ coordinates. BUT if that's true, then P describes a rotation and A describes WHAT EXACTLY????
4, How can I understand why the eigendirections of $A$ will be the major and minor axes of the conic section in the $(x',y')$ coordinates?
THank you very much for your help. I am just struggling to visualise what's actually happening behind the relatively straightforward mathematics here.

A: I'm going to address this one:
$$
x^T A x + v^T \cdot x + f=0
$$
In this, $f$ is proportional to the amount of offset from the axis of the double-cone. That's pretty easy. (The constant of proportion comes from the fact that you can double everything here and still get the same conic, etc.)
The vector $v$ tells you the normal vector to your slicing plane. It's probably a good idea to rescale everything so that the vector $v$ is a unit vector; this removes some of the "proportional" ambiguity from $f$.
What about the matrix $A$? It represents two things: the non-roundness of the cone you're slicing, and the orientation of the resulting conic in the slice plane.
Because $A$ is a symmetric matrix, it can be diagonalized. That means that there are unit vectors $u_1, u_2$ in the plane so that when you form the matrix $U = [u_1, u_2]$ that has those as its columns, the matrix
$$
M = U A U^t
$$
is diagonal. What this says is that if you use the directions $u_1$ and $u_2$ as your "axes" in the plane, then your conic will have no cross-term -- it'll be "axis aligned", like a parabola whose directrix is horizontal or vertical, or an ellipse whose axes are vertical/horizontal.
So $M$ now has zeros on the off-diagonal entries, and the two diagonal entries might be zero or nonzero. If they're both 0, then your original cone has cone-angle zero, and a slice of it is either a single line or is empty.
If one is nonzero, ... uhh... I'm not sure, and I don't have time to write a lot more, so I'm skipping this case.
If both are positive or both negative, you get a cone that (broadly) looks like $z^2 = x^2 + y^2$; if one's positive and one negative, you get a cone that looks like $z^2 = x^2 - y^2$, which is just $x^2 = y^2 + z^2$, i.e., it's the former case, but with the axes swapped around a bit.
Back to $u_1, u_2$: if you're willing to let these NOT be unit vectors, i.e., to say "I'm going to scale the world up or down along these two perpendicular directions", then $A$ ends up with $0, \pm 1$ on the diagonal, and saying "broadly looks like" becomes "is exactly".
When you do that, it's a good idea to express the vector $v$ in that same coordinate system, i.e., you replace $x$ with $Up$, to get an equation that looks like
$$
p^t U^t A U p + v^t \cdot Up + f = 0
$$
which becomes
$$
p^t M p + (v^t U^t) \cdot p + f = 0
$$
which becomes
$$
p^t M p + w^t \cdot p + f = 0
$$
where $w = Uv$.
So by a change of coordinates, we're looking at slices of the standard double-cone by some plane whose normal vector is $w$.
Does this all help even slightly?


text:
Q: Monitor displays fuzzy text on Windows 7 I have just bought a SyncMaster 2330HD and installed it as a second monitor.
With 1920x1080 resolution (60 Hz refresh rate) I have two problems:

*

*the text appears with a bit of an aura around it.

*the image does not stretch to the end of the screen. I can't find the option that streches it.

In the following picture you can see the aura and the gap on the top monitor, with the old monitor that doesn't have this problem below it.

BTW, I'm not seeing this problem with other resolutions, but I want 1920x1080.

A: In your video card control panel (Nvidia/ATI Catalyst/Intel Graphics/etc.), there's an option usually called "GPU scaling" which you should disable (use native) to avoid any stretching. Also disable any other scaling or zoom options, such as Underscan/Overscan which may also prevent a native resolution image.
If all scaling options are disabled AND the resolution is set to 1920x1080, no stretching of any kind should occur, the picture should fill the screen and the image should look crisp.
Note: Posted for reference, after having discussing it in your other question.

A: First thing I would do is try to update the drivers for your monitor. Usually windows uses a plug n play driver. The only other cause could be your graphics card drivers in my opinion

A: *

*Update graphics driver.

*Configure windows cleartype text.

*Connect display using HDMI(no VGA/DVI)

*Install drivers for your. diplay(not display drivers. you can find them in optional updates for windows.)

*Use auto-adjust on your display.

btw, by second display, you mean you are using both displays simultaneously??

A: Another important issue has to do with cables and the different resolutions supported by the different connection standards (VGA, DVI, HDMI, DisplayPort). Many people are trying to use a single-link DVI cable with a very high resolution monitor, but this type of cable maxes out at 1920x1200. To get higher resolutions that display properly, they need a double-link DVI cable, which maxes out at 2560x1600. You won't know that the cable is causing a problem because your graphics card may show it is producing an output resolution that exceeds the specs for a single-link cable, but you will get a bad picture with blurry text. DisplayPort is the best option if available because it maxes out at 3840x2160. Next best would be to use double-link DVI cable matched to a graphics card and monitor that support the high resolution the user is trying to achieve. This is a common problem.


text:
Q: how to redirect subdomain to non-www I want to remove www. from start of my URL it tried this :
I have found this work for mydomain.com
RewriteCond %{HTTP_HOST} ^mydomain\.com$ [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RewriteCond %{HTTP_HOST} ^www\.([^.]+\.mydomain\.com)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

If i use mydomain.net.in it doesn't work how to get it done?
RewriteCond %{HTTP_HOST} ^mydomain\.net\.in$ [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RewriteCond %{HTTP_HOST} ^www\.([^.]+\.mydomain\.net\.in)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

A: I am not sure why you first appending www and then removing try with below, it will work for both.
RewriteCond %{HTTP_HOST} ^www\.(.+)
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

Clear cache beforehand.


text:
Q: Пропадает .htaccess Здравствуйте, сделал архив на винде (winrar) с сайтом, разархивирую его в ubuntu 16.04 и пропадает папка .git, но это не беда, также пропали все файлики .htaccess. Подскажите как можно разархивировать без потери файлов?

A: Точка в начале файла или каталога по умолчанию его скроет.
В стандартном файловом менеджере Nautilus показать скрытые файлы или папки можно сочетанием клавиш Ctrl+H или View -> Show hidden files


text:
Q: Ant 1.8.1 showing incorrect java version? I'm running Ant 1.8.1 under Win 7. And my Java version is 1.7_17.
I add the following 2 lines in my build file for diagnosing.
<echo message="java.version  = ${ant.java.version}"                   />
<echo message="java.home     = ${java.home}"                          />

And the result is
 [echo] java.version  = 1.6
 [echo] java.home     = C:\Program Files\Java\jre7

Any idea on what's going on?
Is it hardcoded in Ant 1.8.1 that the highest java version it can show is 1.6?

A: I found this from Ant website. It's hardcoded actually.
ant.java.version    the JVM version Ant detected; currently it can hold
                    the values "1.2", "1.3",
                    "1.4",  "1.5" and "1.6".

After I update my Ant to 1.9.0, the issue is solved.
 [echo] java.version  = 1.7
 [echo] java.home     = C:\Program Files\Java\jdk1.7.0_17\jre

It's kind of funny. :)

A: It looks like you have JAVA_HOME set correctly, but do you have %JAVA_HOME%\bin included in your PATH environment variable ?  It looks like you're currently picking up the java.exe from a Java 6 installation.

A: I think ant.java.version shows the Java version your Ant was built with. The actual version of your java installation is stored in java.version.


text:
Q: "Creating" a ground pin for my laptop I am building a sensor using an Arduino connected to a laptop; I noticed that the readout is much more noisy when I use a non-grounded laptop (either running on battery or connected to a power socket without ground prong) compared to when I use my grounded power supply. Some kind of high-frequency noise appears the second I disconnect the grounded power supply.
I assume that it is a floating ground problem: all the components are connected to the Earth (including the USB cable ground) - would there be some kind of floating ground in the laptop?
Only one of my laptops has a ground prong, and I would like to use the others for the same purpose, so I am wondering if there is a "canonical way" to ground a laptop to the Earth. I thought properly grounding the USB cable would be enough, but apparently not...
Should I create a ground pin for my arudino laptop?

A: Yes, grounding the chassis GND of your notebook to the Protective Earth terminal in your wall socket often yields good results. Either use an additional wire with some suitabe connectors, or get a replacement external power module (black brick) that has the wall socket's PE connected to the output GND.
The EMI that you're observing may be RF or mains 50/60 Hz seeping from the SMPS. An important keyword here is the Y-cap. Let me give you two references to previous debates here at electronics.stackexchange .

A: Solving EMI problems can be tricky. The first thing would be to find out the source of the noise. Is it coming from the arudino or external to the arudino? Once you find out where it's coming from you can take steps to isolate the noise.
Noise is usually conducted along cables, or radiated (like radio waves). The ideal sensor setup is shown below with shielding to stop radiated noise coming from other sources.

Source: https://www.electronic.nu/2016/05/30/shielded-cables-their-role-in-reducing-emi-susceptibilty-and-emissions/
If the noise is conducted, usually a ferrite to block noise from coming up the cable is best.
The change in noise might also be caused by the way your device behaves, not from grounding (sometimes connecting a usb device turns whatever is on the end of the cable in to an antenna\radiator).
If you have an oscilloscope, you could use it to probe the source of the noise (like on the ADC pins from the sensor, or the sensor itself) and find the frequencies of the noise source. Once you have found the frequency you could look at other noise sources like clocks or processors and try an isolate them from the sensor.


text:
Q: Unable to call method implementing recursive call I'm a python beginner. When I tried to implement the BinarySearchTree below, I got the following error
exec(code, run_globals)
  File "binarysearchtree.py", line 23, in <module>
    print(BinarySearchTree.contains(n2,3))
TypeError: contains() missing 1 required positional argument: 'value'

Any help would be greatly appreciated. Thank you!
import collections

class BinarySearchTree:

    Node = collections.namedtuple('Node', ['left', 'right', 'value'])

    @staticmethod
    def contains(self,root, value):
        if (root is None):
            return None
        elif (root.value==value):
            return root
        elif (root.value < value):
            self.contains(root.right,value)
        else:
            self.contains(root.left,value)

n1 = BinarySearchTree.Node(value=1, left=None, right=None)
n3 = BinarySearchTree.Node(value=3, left=None, right=None)
n2 = BinarySearchTree.Node(value=2, left=n1, right=n3)

print(BinarySearchTree.contains(n2,3))

A: The problem is that you've defined your method as a staticmethod, but then you're trying to use it as a normal method.
With a normal method, when you do obj.meth(a, b), it callsCls.meth(obj, a, b), giving you that obj value as a self argument.
With a static method, obj.meth(a, b) just calls Cls.meth(a, b). There is no self argument.

So, the error is because you're asking for self, root, value but only passing root, value. Just as the exception says, you're one argument short.
And meanwhile, you're trying to use that self within the method body, so you can't just get rid of it.
If you really want this to be a staticmethod on the tree, since the only thing you're actually doing with self is calling a staticmethod on the class, you can use the class name explicitly, like this:
@staticmethod
def contains(root, value):
    if (root is None):
        return None
    elif (root.value==value):
        return root
    elif (root.value < value):
        BinarySearchTree.contains(root.right,value)
    else:
        BinarySearchTree.contains(root.left,value)

And then your code will work. Well, it'll get rid of that exception; it still has other bugs (like not returning the result of the recursive call back up the chain).

But I don't understand why you wanted a staticmethod in the first place.
My guess is that you're trying to port what's basically a ML-translated-to-Java design. In Java, putting a bunch of free functions in a useless class counts as OO. In Python, you don't need to do that; you just have free functions on the module. A staticmethod doesn't really give you anything extra here except confusion.
Or you can actually translate this to OO. For example, if you merge the tree and node types (or turn the tree into a node handle for the root that passes the method through), you can make contains a perfectly normal method. Then you have to put the None check before each recursive call instead of at the top, but that's it.


text:
Q: Swi Prolog, unloading source files Is there a built-in predicate or a easy way to remove from the knowledge database of prolog a source files that has already been consulted? I've gone through the reference manual and didn't find any thing that could do that.

A: You can do it with these procedures which use source_file/1 and source_file/2:
unload_last_source:-
  findall(Source, source_file(Source), LSource),
  reverse(LSource, [Source|_]),
  unload_source(Source).

unload_source(Source):-
  ground(Source),
  source_file(Pred, Source),
  functor(Pred, Functor, Arity),
  abolish(Functor/Arity),
  fail.
unload_source(_).

unload_source/1 abolishes all predicates defined by the input Source file name. Be warned that it needs to be an absolute path.
unload_last_source/0 will retrieve the last consulted file name and unload it.

A: After a file has been consulted, it become 'irrelevant' to Prolog. So I think that generally to answer should be no. But SWI-Prolog has a rich set of builtins that allows you to control your prolgram. For instance
?- [stackoverflow].

?- predicate_property(P, file('/home/carlo/prolog/stackoverflow.pl')).
P = yield(_G297, _G298) ;
P = now _G297 ;
P = x(_G297) ;
...

?- abolish(yield/2).
true.

?- predicate_property(P, file('/home/carlo/prolog/stackoverflow.pl')).
P = now _G297 ;
P = x(_G297) ;
...

Note that abolish doesn't require the file name to work, you could delete predicates loaded from other sources files.
clause, clause_property and erase should give more control, but I get an error I don't understand (it's undocumented) when attempting to use erase:
?- clause(strip_spaces(_G297, _G298),X,Y),erase(Y).
ERROR: erase/1: No permission to clause erase `<clause>(0x29acc30)'

A: if you know the name of the predicate, for example fact/2, you can use:
retractall(fact(_,_)).

A: This will work.

unload_file(+File)

Remove all clauses loaded from File. If File loaded a module, clear
the module's export list and disassociate it from the file. File is a
canonical filename or a file indicator that is valid for load_files/2.
This predicate should be used with care. The multithreaded nature of
SWI-Prolog makes removing static code unsafe. Attempts to do this
should be reserved for development or situations where the application
can guarantee that none of the clauses associated to File are active.


text:
Q: The eye comand of Matlab in Python In Matlab I can create a rectangular "identity" matrix by, for example, eye(2, 3). What would be the python equivalent in Python?

A: Unlike np.identity, the np.eye function accepts an optional second argument as well:
>>> np.eye(2, 3)
array([[1., 0., 0.],
       [0., 1., 0.]])

You can also do the operation more manually, using a method similar to what np.diagonal uses. You can't use np.diagonal directly because it creates a copy or a read-only view. This method manually creates the same view, but writable:
a = np.zeros((2, 3))
a.ravel()[::a.shape[1] + 1] = 1

You can make a view like a.ravel()[::a.shape[1] + 1] even in cases where a.ravel would return a copy using np.lib.stride_tricks.as_strided:
a = np.zeros((2, 3))
np.lib.stride_tricks.as_strided(a, shape=(min(a.shape),), strides=(sum(a.strides),))[:] = 1


text:
Q: Fatal error: Uncaught Error: Call to a member function query() on null Здраствуйте, не могу сделать SQL-запрос. Мне нужно выбрать столбец film_name из базы данных. Но произошла ошибка  - Fatal error: Uncaught Error: Call to a member function query() on null in C:\OSPanel\domains\localhost\index.php:23 Stack trace: #0 {main} thrown in C:\OSPanel\domains\localhost\index.php on line 23
index.php
<?php
      require_once 'includes/config.php';
    ?>

   <!DOCTYPE html>

     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <meta http-equiv="X-UA-Compatible" content="ie=edge">
     <title><?php echo $config['title']; ?></title>
     <link rel="stylesheet" href="css/style.css">
     <link rel="stylesheet" href="css/media.css">
     <link href="https://fonts.googleapis.com/css?family=Revalia" rel="stylesheet">

   <?php require_once "includes/header.php"; ?>

       <?php
             $stmt = $pdo->query('SELECT film_name FROM new_film');
             while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
               echo $row['film_name'];
             };
        ?>

connection.php
<?php

      $host = 'localhost';
      $username = 'root';
      $password = '';
      $dbname = 'main';

      try {
        $dsn = "mysql:host = $host; dbname = $dbname";

        $opt = [
          PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
          PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
          PDO::ATTR_EMULATE_PREPARES   => false,
        ];

        $pdo = new PDO($dsn, $username, $password, $opt);
      }
      catch (PDOException $e) {
        die('Not connect: ' . $e->getMessage());
      }

      $pdo = null;
    ?>


text:
Q: How to access elements in the same iframe? I want to access elements in a same iframe (they're even in same user control), but the only way I know is:
<div>
...
    <asp:Button CssClass="enoPlaceOrderButton enoHidden" runat="server" ID="SubmitButton" OnClick="SubmitButton_OnClick" Text="" />

<script type="text/javascript">
jQuery(document).ready(function() {
    jQuery("body").bind("checkout.onStepChanged", function (event, data) {
        if (data.currentStep == "PaymentStep") {
            var temp = jQuery("#paymentMethodsFrame").contents().find('#<%=SubmitButton.ClientID %>');
        }
    });
});
</script>
</div>

This is in the paymentMethodsFrame.
Is there a better way to do this?
Thank you.

A: Can't you use
jQuery('#SubmitButton');


text:
Q: How to use custom source model in eav_attribute Ho can I use a custom source in the source_model of the eav_attribute table?
Thats my source
*
* @category  Mcas
* @package   Mcas_Industries
* @copyright Copyright (c) 2019
* @license   http://opensource.org/licenses/mit-license.php MIT License
*/
namespace Mcas\Industries\Source;

class Industry implements \Magento\Framework\Option\ArrayInterface
{
/**
 * Industry repository
 *
 * @var \Mcas\Industries\Api\IndustryRepositoryInterface
 */
protected $industryRepository;

/**
 * Search Criteria Builder
 *
 * @var \Magento\Framework\Api\SearchCriteriaBuilder
 */
protected $searchCriteriaBuilder;

/**
 * Filter Builder
 *
 * @var \Magento\Framework\Api\FilterBuilder
 */
protected $filterBuilder;

/**
 * Options
 *
 * @var array
 */
protected $options;

/**
 * constructor
 *
 * @param \Mcas\Industries\Api\IndustryRepositoryInterface $industryRepository
 * @param \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
 * @param \Magento\Framework\Api\FilterBuilder $filterBuilder
 */
public function __construct(
    \Mcas\Industries\Api\IndustryRepositoryInterface $industryRepository,
    \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
    \Magento\Framework\Api\FilterBuilder $filterBuilder
) {
    $this->industryRepository    = $industryRepository;
    $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    $this->filterBuilder         = $filterBuilder;
}

/**
 * Retrieve all Industries as an option array
 *
 * @return array
 * @throws StateException
 */
public function getAllOptions()
{
    if (empty($this->options)) {
        $options = [];
        $searchCriteria = $this->searchCriteriaBuilder->create();
        $searchResults = $this->industryRepository->getList($searchCriteria);
        foreach ($searchResults->getItems() as $industry) {
            $options[] = [
                'value' => $industry->getIndustryId(),
                'label' => $industry->getIndustry(),
            ];
        }
        $this->options = $options;
    }

    return $this->options;
}

/**
 * @return array
 */
public function toOptionArray()
{
    return $this->getAllOptions();
}
}

A: Add Source Model When You Create Attribute
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
       $eavSetup->addAttribute(
               \Magento\Catalog\Model\Product::ENTITY,
           'international',
           [
               'group' => 'General',
               'type' => 'int',
               'label' => 'International',
               'backend' => '',
               'input' => 'select',
               'wysiwyg_enabled'   => false,
               'source' => 'Namespace\ModuleName\Model\Config\Source\YesNo',
               'required' => true,
               'sort_order' => 15,
               'global' => \Magento\Catalog\Model\ResourceModel\Eav\Attribute::SCOPE_GLOBAL,
               'used_in_product_listing' => false,
               'visible_on_front' => false,
       ]
   );


text:
Q: Work by friction I'm having trouble calculating the work done by friction over a surface. Here is a picture I've drawn of my problem:

I'm tasked with finding the work done on the box (which has a mass of 6 kg) after it goes over a surface with friction. The initial velocity is 14 m/s.
I'm aware work by friction would be equal to $Fd$, but the formula for friction is $\mu_kv$. As the net force is the friction force, I don't know how to find work by friction if the friction force varies as the box slows down. How do I find this?
Edit: Sorry, I for some reason thought the friction force was given by $\mu_kv$, when it should really be $\mu_kN$. That's probably why it wasn't making sense. I assume the work by friction would then just be $\mu_kNd$?

A: The general (scalar) version of the work formula is
$$W= \int F \; dx$$
If the force is constant, this does indeed reduce down to $W=Fx$. If not, then you have to use the integral version. In any case, you must know $F$. So, if $F$ is varying with speed, called $F(v)$, you have to know an expression/function/formula of $F(v)$ to put into the work formula.
If you are not given (or cannot find in another way) such an expression, then this question doesn't seem possible to solve.
If on the other hand the force is just usual friction, which is constant regardless of e.g. speed, then we can quickly find the work without the integral as:
$$W=Fx=\mu n x$$
Where $n$ is the normal force (which you must find with a separate calculation).

A: If the force is indeed dependent on velocity then you cannot calculate the work unless you know the explicit dependence F(v). However, in many textbook problems the friction force is considered independent of v. What is the context of your problem? Where does it come from?


text:
Q: Python Kernel Crash I am a school student taking AP computer science and we are learning python currently. Now my problem starts with Enthought Canopy, when I open the code editor up the kernel it states that the kernel needs to be connected

After I click that I click on use local managed kernel. After 5 seconds of trying to connect it tells gives me that the kernel has crashed and says the following:
The ipython kernel (user Python environment) has terminated with error code 1. This may be due to a bug in your code or in the kernel itself.

The output captured from the kernel process is shown below:

It says on the Ipython session that it is trying connect to the kernel but nothing happens
 Connecting to Kernel: c:\users\diptip~1\appdata\local\temp\tmpgmbhng.json

I have a win 10 laptop 64bit, and my user name is all ASCII letters. Please if someone can help me resolve this issue. I read an article about this in a previous post but the person apparently got the error because his name was non-ASCII, and my canopy version is 2.1.9
second image

A: sorry that you're having problems. When the kernel crashes on startup, it's likely because of either blockage from security (AV or firewall) software, or having conflicting environment variables. Try temporarily disabling your security software, then resetting both the configuration and the Python environment from the Canopy Tools => Troubleshoot menu. If that doesn't help, then you can submit a feedback report from the Canopy Help menu, though with holiday schedules I'm not sure how soon we'd reply to it.


text:
Q: Javascript algorithm error 3 I have written down this code, for like a minigame with a password, and I want that if he writes the password right, or writes end, then it really ends, showing us a message, but in case he writes other stuff or nothing that it continues to ask, but It is not completely right.

 do{
                    var password = prompt("What is the password? Just give up by typing end, you won't find it, heheeh.")
                    if(password == "I11I1II1I"){
                        window.alert("Ok, ahha, so fun, going to the code, and searching for the password, yes yes yes good job, you won, yey")
                    }
                    else if(password == "end"){
                        window.alert("Bye Bye, ehhe.")
                    }
                    else{
                        window.alert("I don't know how you found me, but hey, you won't find the password, eehhehe.")
                    }
                }
                while((password == "") || (password != "I11I1II1I") || (password != "end"))

A: You can use break (https://www.w3schools.com/js/js_break.asp):
while(true) {

    var password = prompt("What is the password? Just give up by typing end, you won't find it, heheeh.")

    if(password == "" || password == null) {
          // No password, just break or do something else
          break;
    }
    if(password === "I11I1II1I") {
          window.alert("Ok, ahha, so fun, going to the code, and searching for the password, yes yes yes good job, you won, yey");
          break;
    }
    else if(password === "end") {
          window.alert("Bye Bye, ehhe.");
          break;
    }
    else {
          window.alert("I don't know how you found me, but hey, you won't find the password, eehhehe.")
    }
}

A: You while logic is wrong, you should the prompt when password is "" or (password != "I11I1II1I" && password != "end")

do{
                password = prompt("What is the password? Just give up by typing end, you won't find it, heheeh.")
                if(password == "I11I1II1I"){
                    window.alert("Ok, ahha, so fun, going to the code, and searching for the password, yes yes yes good job, you won, yey") ;
                }
                else if(password == "end"){
                    window.alert("Bye Bye, ehhe.")  ;
                }
                else{
                    window.alert("I don't know how you found me, but hey, you won't find the password, eehhehe.");
                }

            }
            while((password == "") || (password != "I11I1II1I" && password != "end"))


text:
Q: Django | twilio to send SMS I'm using twilio as for a mobile verification mechanism,  I have no prior experience in using twilio but looking at the sample PHP code I used this one in my code but apparently it's giving me an 400 Bad request HTTP error. Here's the code:
    d = {
        'TO' : '*** *** ****',
        'FROM' : '415-555-1212',
        'BODY' : 'Hello user, please verify your device using                    this code %s' % verNumber
    }
    try:
        print account.request('/%s/Accounts/%s/SMS/Messages' % \
                            (API_VERSION, ACCOUNT_SID), 'POST', d)
    except Exception, e:
        return HttpResponse('Error %s' % e)

verNumber is randomly generated and the receiver's  number is validated in twilio.
I follow the exception and found this error
Error 400 The source 'From' phone number is required to send an SMS

What does this mean.?
Thanks.

A: Looking at some of the twilio examples from the python libraries I notice that the dictionaries containing the payload are typed in MixedCase whereas you've used UPPERCASE.
The error might be quite straight forward rather than
d = {
    'TO' : '*** *** ****',
    'FROM' : '415-555-1212',
    'BODY' : 'Hello user, please verify your device using this code %s' % verNumber
}

try
d = {
    'To' : '*** *** ****',
    'From' : '415-555-1212',
    'Body' : 'Hello user, please verify your device using this code %s' % verNumber
}

The SMS Quickstart ( in the documentation) supports this idea.
Hope this helps.

A: Try http://bitbucket.org/vgavro/django-smsgate/ , you may need to write backend for twilio - but the rest is done for you already.


text:
Q: Windows 7 - not able to login - not able to enter password I am using Windows 7 home premium. I am not able to enter the password to login.
But the space key and the back key are working fine. Even the touch pad is working fine.
Please help
Thanks

A: Try clicking the little accessibility button in the bottom left corner and bring up the virtual keyboard. You may be able to enter the password using that.


text:
Q: How to optimize nested for loops in pandas? EDIT 27/01/2022
I will test solution of @hpchavaz
part of slow issue came from function called during loop. 2 of these function load csv files (pd.read_csv). I optimize by loading only columns needed (and not the all file).
And after, I tried to avoid loop:

*

*by using pd.melt to 'transpose' columns in rows

*by using apply wth lambda

I have divided execution time by 5 (227 minutes -> 45 minutes)
pd.set_option("display.max_rows", None, "display.max_columns", None)
# pd.set_option('max_colwidth', None)

# page 332 of SDTMIG3.3 Guidelines
# Finding About
domain = 'FA'
print(f'Domain {domain}')
print(datetime.datetime.now().strftime('%Y-%m-%d - %H:%M:%S'))
start = datetime.datetime.now()

# Données sources
df_randomisation = pd.read_csv(f'./csv/source/randomisation.csv',delimiter=",")
df_randomisation = df_randomisation.loc[:, df_randomisation.columns!='redcap_repeat_instance'] # exclude column redcap_repeat_instance as randomisation form are unique
df_randomisation = df_randomisation.loc[:, df_randomisation.columns!='redcap_event_name'] # exclude column redcap_repeat_name as randomisation form are unique
df_randomisation = df_randomisation.loc[:, df_randomisation.columns!='ID'] # exclude column redcap_repeat_name as randomisation form are unique

df_clinical_exam = pd.read_csv(f'./csv/source/examen_clinique_symptomes.csv',delimiter=",")
df = pd.merge(df_randomisation,df_clinical_exam, left_on='pat_ide', right_on='pat_ide', how='outer').sort_values(by=['pat_ide','sym_dat'])

# filtre sur un patient pour les tests
# df = df[(df['pat_ide'] == 'BFBO001')]

# print(df)

# Transformation des données sources : évènements en colonnes => évènements en lignes
df1 = pd.melt(df, id_vars=['pat_ide','sym_dat','redcap_event_name'], value_vars=['sym_tou', 'sym_gra','sym_ete','sym_fie','sym_fat','sym_dys','sym_mya','sym_cep','sym_gor','sym_cut','sym_ore','sym_nez','sym_odo','sym_gou','sym_ver','sym_vis','sym_aud','sym_tho','sym_pal','sym_nau','sym_vom','sym_dia','sym_abd','sym_mal','sym_con'],var_name='symptome', value_name='intensite')
df2 = pd.melt(df, id_vars=['pat_ide','sym_dat'], value_vars=['sym_tou_del','sym_gra_del','sym_ete_del','sym_fie_del','sym_fat_del','sym_dys_del','sym_mya_del','sym_cep_del','sym_gor_del','sym_cut_del','sym_ore_del','sym_nez_del','sym_odo_del','sym_gou_del','sym_ver_del','sym_vis_del','sym_aud_del','sym_tho_del','sym_pal_del','sym_nau_del','sym_vom_del','sym_dia_del','sym_abd_del','sym_mal_del','sym_con_del'],var_name='symptome', value_name='delai')
df2['symptome'] = df2.apply(lambda row: row['symptome'][:-4],axis=1)
# print(df1)
# print(df2)

# list of 25 monitored clinical signs
signs = {
    'sym_tou' : 'Dry cough',
    'sym_gra' : 'Fatty cough',
    'sym_ete' : 'Sneezing',
    'sym_fie' : 'Fever',
    'sym_fat' : 'Tiredness',
    'sym_dys' : 'Dyspnea',
    'sym_mya' : 'Muscle aches (Myalgia)',
    'sym_cep' : 'Headache',
    'sym_gor' : 'Sore throat',
    'sym_cut' : 'Skin rash',
    'sym_ore' : 'Earache',
    'sym_nez' : 'Runny nose (Rhinorrhea)',
    'sym_odo' : 'Loss of smell (Anosmia)',
    'sym_gou' : 'Loss of taste (Ageusia)',
    'sym_ver' : 'Feeling dizzy',
    'sym_vis' : 'Acute vision impairment',
    'sym_aud' : 'Acute hearing impairment',
    'sym_tho' : 'Chest pain',
    'sym_pal' : 'Palpitations',
    'sym_nau' : 'Nausea',
    'sym_vom' : 'Vomiting',
    'sym_dia' : 'Diarrhea',
    'sym_abd' : 'Abdominal pain',
    'sym_mal' : 'Inexplicated tiredness',
    'sym_con' : 'Conjunctivitis'
    }

dataframe = pd.DataFrame()
dataframe = pd.merge(df1,df2, left_on=['pat_ide','sym_dat','symptome'], right_on=['pat_ide','sym_dat','symptome'], how='outer').fillna('NULL')
dataframe['symptome'] = dataframe.apply(lambda row: signs[row['symptome']],axis=1)
dataframe = dataframe.sort_values(by=['pat_ide','sym_dat'])
# print(dataframe)
# print(len(dataframe.index))

# FA
sdtm_variables = ['STUDYID','DOMAIN','USUBJID','FASEQ','FATESTCD','FATEST','FAOBJ','FACAT','FAORRES','FAORRESU','FASTRESC','FASTRESN','FASTAT','VISITNUM','VISIT','VISITDY','EPOCH','FADTC','FADY','SYM_DAT','DEL','pat_ide']
df_fa = pd.DataFrame(columns = sdtm_variables)

df_fa['pat_ide'] = dataframe.apply(lambda row: row['pat_ide'],axis=1)
df_fa['STUDYID'] = dataframe.apply(lambda row: '01-COV',axis=1)
df_fa['DOMAIN'] = dataframe.apply(lambda row: 'FA',axis=1)
df_fa['USUBJID'] = dataframe.apply(lambda row: Patient_icon_format(row['pat_ide']),axis=1)  # index of df
df_fa['FASEQ'] = dataframe.apply(lambda row: 1,axis=1) # pd.RangeIndex(stop=dataframe.shape[0]) + 1
df_fa['FATESTCD'] = dataframe.apply(lambda row:'OCCUR',axis=1)
df_fa['FATEST'] = dataframe.apply(lambda row:'Occurrence Indicator',axis=1)
df_fa['FAOBJ'] = dataframe.apply(lambda row: row['symptome'],axis=1)
df_fa['FACAT'] = dataframe.apply(lambda row: 'COVID-19 SYMPTOMS',axis=1)
df_fa['FAORRES'] = dataframe.apply(lambda row: Clinical_result(row['intensite']),axis=1)
df_fa['FAORRESU'] = dataframe.apply(lambda row: '',axis=1)
df_fa['FASTRESC'] = dataframe.apply(lambda row: Clinical_standard_result(row['intensite']),axis=1)
df_fa['FASTRESN'] = dataframe.apply(lambda row: np.nan,axis=1)
df_fa['FASTAT'] = dataframe.apply(lambda row: 'NOT DONE' if Clinical_result(row['intensite']) == '' else '',axis=1)
df_fa['VISITNUM'] = dataframe.apply(lambda row: str(Visit_numbering(row['pat_ide'],row['sym_dat'],row['redcap_event_name'])),axis=1)
df_fa['VISIT'] = dataframe.apply(lambda row: Visit_name(row['pat_ide'],row['sym_dat'],row['redcap_event_name']),axis=1)
df_fa['VISITDY'] = dataframe.apply(lambda row: '-1' if Visit_numbering(row['pat_ide'],row['sym_dat'],row['redcap_event_name']) == 1 else str(round((Visit_numbering(row['pat_ide'],row['sym_dat'],row['redcap_event_name']) - 1))),axis=1)
df_fa['EPOCH'] = dataframe.apply(lambda row: Get_epoch(row['pat_ide'],row['sym_dat'],row['redcap_event_name']),axis=1)
df_fa['FADTC'] = dataframe.apply(lambda row: pd.to_datetime(row['sym_dat']).strftime('%Y-%m-%dT%H:%M:%S') if row['sym_dat'] != 'NULL' else None,axis=1)
df_fa['FADY'] = dataframe.apply(lambda row: Number_of_day_since_the_subject_start_the_study(dataframe,row['sym_dat'],Patient_study_start_date(row['pat_ide'])),axis=1)
df_fa['SYM_DAT'] = dataframe.apply(lambda row: row['sym_dat'],axis=1)
df_fa['DEL'] = dataframe.apply(lambda row: row['delai'],axis=1)

# add line numbers of event (based on pat_ide and date of event) => use of redacp_repeat_instance variable of the event form
df_fa = df_fa.sort_values(by=['pat_ide','FADTC'])
df_fa = Sequence(df_fa,'FASEQ','FADTC')
df_fa = df_fa.sort_values(by=['pat_ide','FADTC'])
print(df_fa)

# SUPPFA

# creation of empty dataframes
# 2 dataframes because 2 'SUPP' variables are necessary for SUPPFA (FASTDTC et FAPRESP)
df_suppfa1 = pd.DataFrame(columns = ['STUDYID','RDOMAIN','USUBJID','IDVAR','IDVARVAL','QNAM','QLABEL','QVAL','QORIG','QEVAL','pat_ide'])
df_suppfa2 = pd.DataFrame(columns = ['STUDYID','RDOMAIN','USUBJID','IDVAR','IDVARVAL','QNAM','QLABEL','QVAL','QORIG','QEVAL','pat_ide'])

df_suppfa1['pat_ide'] = df_fa.apply(lambda row: row['pat_ide'],axis=1)
df_suppfa1['STUDYID'] = '01-COV'
df_suppfa1['RDOMAIN'] = 'FA'
df_suppfa1['USUBJID'] = df_fa.apply(lambda row: row['USUBJID'],axis=1)
df_suppfa1['IDVAR'] = 'FASEQ'
df_suppfa1['IDVARVAL'] = df_fa.apply(lambda row: row['FASEQ'],axis=1)
df_suppfa1['QNAM'] = 'FASTDTC'
df_suppfa1['QLABEL'] = 'COVID-19 Symptom Start Date'
df_suppfa1['QVAL'] = df_fa.apply(lambda row: (pd.to_datetime(row['SYM_DAT']) + timedelta(days = - int(row['DEL']))).strftime('%Y-%m-%d') if row['DEL'] != 'NULL' else row['SYM_DAT'],axis=1)
df_suppfa1['QORIG'] = 'CRF'
df_suppfa1['QEVAL'] = ''

df_suppfa2['pat_ide'] = df_fa.apply(lambda row: row['pat_ide'],axis=1)
df_suppfa2['STUDYID'] = '01-COV'
df_suppfa2['RDOMAIN'] = 'FA'
df_suppfa2['USUBJID'] = df_fa.apply(lambda row: row['USUBJID'],axis=1)
df_suppfa2['IDVAR'] = 'FASEQ'
df_suppfa2['IDVARVAL'] = df_fa.apply(lambda row: row['FASEQ'],axis=1)
df_suppfa2['QNAM'] = 'FAPRESP'
df_suppfa2['QLABEL'] = 'Prespecified'
df_suppfa2['QVAL'] = 'Y'
df_suppfa2['QORIG'] = 'CRF'
df_suppfa2['QEVAL'] = ''

dataframes = [df_suppfa1,df_suppfa2]
df_suppfa = pd.concat(dataframes)

df_suppfa = df_suppfa.drop(['pat_ide',], axis=1, errors='ignore')
# print(df_suppfa)

#-----------------------------------------------------------------------------------------------------------------------

sdtm_variables.remove('pat_ide')
sdtm_variables.remove('SYM_DAT')
sdtm_variables.remove('DEL')
# print(sdtm_variables)
df_fa = df_fa[sdtm_variables]
df_fa = df_fa.replace('NULL','')

# 3. Export data to csv
df_fa.to_csv(f'./xpt/{domain.lower()}_refactored.csv',index=False)
df_suppfa.to_csv(f'./xpt/supp{domain.lower()}_refactored.csv',index=False)

print(datetime.datetime.now().strftime('%Y-%m-%d - %H:%M:%S'))
print('Execution time',datetime.datetime.now() - start)

EDIT
normally, there 25 monitored clinical signs (and not only 4) and 2713 row in source dataframe

I have a Python code using the pandas library that works but is too slow because I use nested for-loops, and raw data become more important.
# initial dataframe: return 9 rows
df = pd.DataFrame([
        ['PAT001','2022-01-23',1,2,0,0,2,3,3,1],
        ['PAT001','2022-01-24',1,2,0,0,2,3,3,1],
        ['PAT001','2022-01-25',1,2,0,0,2,3,3,1],
        ['PAT002','2022-01-23',1,2,0,0,2,3,3,1],
        ['PAT002','2022-01-24',1,2,0,0,2,3,3,1],
        ['PAT002','2022-01-25',1,2,0,0,2,3,3,1],
        ['PAT002','2022-01-26',1,2,0,0,2,3,3,1],
    ], columns=['pat_ide','sym_dat','sym_tou','sym_gra','sym_ete','sym_fie','sym_tou_del','sym_gra_del','sym_ete_del','sym_fie_del'])

tmp_df_exams = pd.DataFrame(columns = ['pat_ide','DOMAIN','USUBJID','FAOBJ','SYM_DAT','DEL'])

# list of 4 monitored clinical signs
signs = {
    'sym_tou' : 'Dry cough',
    'sym_gra' : 'Fatty cough',
    'sym_ete' : 'Sneezing',
    'sym_fie' : 'Fever'
}

for index, row in df.iterrows():
    for k,v in signs.items():
        tmp_df_exams = tmp_df_exams.append({
            'pat_ide': row['pat_ide'],
            'DOMAIN' : 'FA',
            'USUBJID' : Patient_icon_format(row['pat_ide']),
            'FAOBJ' : v,
            'SYM_DAT' : row['sym_dat'],
            'DEL' : row[f'{k}_del']
        },ignore_index=True)

Currently, it takes hours to end on entire raw data.
To have an idea, if I filter the initial dataframe (9 rows) it takes between 68s and 81s.
How can I improve performance?
OUTPUT

A: Strategy : build a multilevel column index to more easily manipulate the data

*

*Create a mapping of tuples for the columns names
columns_map = dict()
for e in sorted(df.columns):
    e_header = e.replace('_del','')
    if e_header in signs:
        tuple = (signs[e_header], "del" if 'del' in e else 'sym')
        columns_map[e] = tuple

>>> columns_map
{'sym_ete': ('Sneezing', 'sym'),
 'sym_ete_del': ('Sneezing', 'del'),
 'sym_fie': ('Fever', 'sym'),
 'sym_fie_del': ('Fever', 'del'),
 'sym_gra': ('Fatty cough', 'sym'),
 'sym_gra_del': ('Fatty cough', 'del'),
 'sym_tou': ('Dry cough', 'sym'),
 'sym_tou_del': ('Dry cough', 'del')}

*Build the multilevel dataframe
dfh = df.set_index(['pat_ide','sym_dat']).rename(columns = columns_map)
dfh.columns = pd.MultiIndex.from_tuples(dfh.columns, names=['FAOBJ', 'data_name'])
dfh = dfh.sort_index(axis=1)

>>>dfh

FAOBJ              Dry cough     Fatty cough     Fever     Sneezing
data_name            del sym         del sym   del sym      del sym
pat_ide sym_dat
PAT001  2022-01-23     2   1           3   2     1   0        3   0
...

*Data juggling
dfh = (dfh.swaplevel(axis=1)                # put data_name level a the top
          .drop(['sym'], axis = 1)          # drop (unused data)
          .droplevel('data_name', axis=1)   # level 0 as now only 'del"
          .stack()                          # rows to column
          .rename('DEL', axis=1)            # rename the data
          .reset_index()                    # get rid ov the multilevel index
      )

*Inserting missing data ad tyding
dfh = dfh.rename(columns={"sym_dat": "SYM_DAT"})
dfh['DOMAIN'] = 'FA'
dfh['USUBJID'] = '01-COV'+ dfh['pat_ide']     # mock up
dfh = dfh.reindex(['pat_ide', 'DOMAIN', 'USUBJID', 'FAOBJ', 'SYM_DAT', 'DEL'], axis=1)

Result:
>>> dfh
   pat_ide DOMAIN       USUBJID        FAOBJ     SYM_DAT  DEL
0   PAT001     FA  01-COVPAT001    Dry cough  2022-01-23    2
1   PAT001     FA  01-COVPAT001  Fatty cough  2022-01-23    3
2   PAT001     FA  01-COVPAT001        Fever  2022-01-23    1
3   PAT001     FA  01-COVPAT001     Sneezing  2022-01-23    3
4   PAT001     FA  01-COVPAT001    Dry cough  2022-01-24    2
5   PAT001     FA  01-COVPAT001  Fatty cough  2022-01-24    3
6   PAT001     FA  01-COVPAT001        Fever  2022-01-24    1
7   PAT001     FA  01-COVPAT001     Sneezing  2022-01-24    3
8   PAT001     FA  01-COVPAT001    Dry cough  2022-01-25    2
9   PAT001     FA  01-COVPAT001  Fatty cough  2022-01-25    3
10  PAT001     FA  01-COVPAT001        Fever  2022-01-25    1
11  PAT001     FA  01-COVPAT001     Sneezing  2022-01-25    3
12  PAT002     FA  01-COVPAT002    Dry cough  2022-01-23    2
13  PAT002     FA  01-COVPAT002  Fatty cough  2022-01-23    3
14  PAT002     FA  01-COVPAT002        Fever  2022-01-23    1
15  PAT002     FA  01-COVPAT002     Sneezing  2022-01-23    3
16  PAT002     FA  01-COVPAT002    Dry cough  2022-01-24    2
17  PAT002     FA  01-COVPAT002  Fatty cough  2022-01-24    3
18  PAT002     FA  01-COVPAT002        Fever  2022-01-24    1
19  PAT002     FA  01-COVPAT002     Sneezing  2022-01-24    3
20  PAT002     FA  01-COVPAT002    Dry cough  2022-01-25    2
21  PAT002     FA  01-COVPAT002  Fatty cough  2022-01-25    3
22  PAT002     FA  01-COVPAT002        Fever  2022-01-25    1
23  PAT002     FA  01-COVPAT002     Sneezing  2022-01-25    3
24  PAT002     FA  01-COVPAT002    Dry cough  2022-01-26    2
25  PAT002     FA  01-COVPAT002  Fatty cough  2022-01-26    3
26  PAT002     FA  01-COVPAT002        Fever  2022-01-26    1
27  PAT002     FA  01-COVPAT002     Sneezing  2022-01-26    3


text:
Q: QuantumGrid Master-detail I have a QuantumGrid with two levels (let us say, lvCountries and lvCities) and two views (tvCountries and tvCities respectfully).
All properties in both views are set correctly and grid display as it should:

*

*France

*

*Paris

*Marseille

*Lyon

*Germany

*

*Dresden

*Hamburg

etc.
Up to this moment everything has been fine.
But I also have an edit form (activated by a button on a form with the master-detail grid).
I'd like to display on this form a new grid with data from current Detail. If in main form France selected, edit form should display only french cities in its grid:

*

*Paris

*Marseille

*Lyon

I attached the same datasource to edit form's grid as I used for detail view in main form, but it displays all the cities from all the countries.

*

*Paris

*Marseille

*Lyon

*Dresden

*Hamburg

As I understand, this happens because detail data are filtered not in their datasource, but in their view, and datasource displays all the values from its dataset (I use ADODatasets, by the way).
Is there a way to display detail data on another form only for current master record?

A: Add a property to your detail form that is set to the key value of the selected record. e.g.
TFormDetail= Class(TForm)
..
Public
  Property CountryID : String Read FCountryID Write FCountryID;
End;

In FormShow
Procedure TFormDetail.FormShow(Sender : TObject);
Begin
// Add your filter/where clause to CountryID
  End;

When you call FormDetail :-
    lFrm := TFormDetail.Create(Nil);
    Try
      lFrm.CountryID := // whatever
      lFrm.ShowModal;
    Finally
      FreeAndNil(lFrm);
    End;


text:
Q: Removing excess spacing for Masonry container using fluid layout I'm trying to create an image gallery using Masonry and the images are re-ordered when the browser is resized.
However, as I am using a fixed width of 150px for the thumbnail images (hence actual large image file is not loaded), but I'm unable to remove the access spacing for the sides of the image container as it will scale based on the screen size as percentage is used for the width.
The site layout is as shown below:
Layout
Actual Layout
Note that there's excess spacing on the right of the image container. In summary,

*

*How do I make the container scale to the size of Masonry image grid, as the image container is calculated based on width via percentage?

*Does it make sense to fix the image to a width of 150 px? If not, which is the preferred method of displaying thumbnails for screens with varying sizes?
html
 <!DOCTYPE html>

    <meta charset="utf-8">
    <title>App</title>
    <link rel="stylesheet" href="/static/css/style.css" />
    <link rel="stylesheet" href="/static/css/reset.css" />

Navigation1

Navigation2

Sidebar

Footer

css
#wrapper {
    margin-right: auto;
    margin-left: auto;
    width: 96%;
}
#header {
    margin-right: 1.0416667%; /* 10 div 960 */
    margin-left: 1.0416667%; /* 10 div 960 */
    width: 97.9166667%; /* 940 div 960 */
    background-color: #779307;
}
#navigation {
    padding-bottom: 25px;
    margin-top: 26px;
    margin-left: -1.0416667%; /* 10 div 960 */
    padding-right: 1.0416667%; /* 10 div 960 */
    padding-left: 1.0416667%; /* 10 div 960 */
    width: 97.9166667%; /* 940 div 960 */
}
#navigation ul li {
    display: inline;
    margin-right: 2.6595745%; /* 25 div 940 */
}
#navigation ul li a {
    height: 42px;
    line-height: 42px;
    text-decoration: none;
    text-transform: uppercase;
    font-family: Arial, "Lucida Grande", Verdana, sans-serif;
    font-size: 27px;
    color: black;
}
#content {
    margin-top: 58px;
    margin-right: 1.0416667%; /* 10 div 960 */
    float: right;
    background-color: #dedede;
    width: 72.7083333%; /* 698 div 960 */
}
#sidebar {
    border-right-color: #e8e8e8;
    border-right-style: solid;
    border-right-width: 2px;
    margin-top: 58px;
    padding-right: 1.0416667%; /* 10 div 960 */
    margin-right: 1.0416667%; /* 10 div 960 */
    float: left;
    width: 22.7083333%; /* 218 div 960 */
    background-color: #fe9c00;
}
#footer {
    float: left;
    margin-top: 20px;
    margin-right: 1.0416667%; /* 10 div 960 */
    margin-left: 1.0416667%; /* 10 div 960 */
    clear: both;
    width: 97.9166667%; /* 940 div 960 */
    background-color: #663300;
}
#gallery_container {
    list-style-type: none;
    padding: 0px;
    margin: 0px;
    background-color: #302200;
}
#gallery_container ul li {
    display: inline;
}
#gallery_container ul li img {
    padding-top: 10px;
}

A: I think your fiddle isn't working properly... Anyway, there is the option "isFitWidth": true to hint masonry to fill all the horizontal space. Try it.


text:
Q: what is the best method to connect with database on server ? I am developing JSF project which connect to mySql Database and I have for example two ways to delete element like
// deletePerson()
    People p = selectedPerson;

1- direct access to the database using entity manager
    ut.begin();
    p = em.merge(p);
    em.remove(p);
    ut.commit();

2- using restful web service to access the data
 PeopleClient client = new PeopleClient();
 client.remove(p.getId().toString());

which is the better way to do that with reasons?

A: I would say it depends on the bigger picture for your data.
If you want to some day build more applications around your data (mobile application, web application, client side application), then I would go with the RESTful web service. You can more easily leverage that in other codebases.
If you just need the data for this one application, then I would go with the direct database approach.
The big thing to keep in mind is how many network hops you have. The REST service is going to have to access the database directly. REST = two network trips (one from application to REST service, one from REST service to database). Database = one network trip.


text:
Q: If an Activity takes long time to Load, it asks for force close, how to solve this? Almost all the activities in my application need to interact with a web server to get data and then load the Activity screens. So at any moment if the internet is slow, it takes a lot of time and after some 12-15 secs it says "unable to load, ForceClose/Wait". How does applications avoid this? What is the solution they follow, when 1st 3-4 activities work fine (when net is good) then some Activity takes long(because of bad internet/ if internet is gone)

A: By Optimizing your code, Secondly do your Network/Internet work on a separate thread(like AsynTask).
Link: http://developer.android.com/reference/android/os/AsyncTask.html
This will not block your UI.
Hope This Help

A: Its a problem of slow internet connections. I have also faced it earlier while making an app which used to fetch data from a web server. So there are 4 things which can help you in this matter:
(1) Check if there is any internet connection or not:
    ConnectivityManager cm = (ConnectivityManager)   getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    if (ni!=null && ni.isAvailable() && ni.isConnected()) {
        return true;
    } else {
        return false;
    }

If there is no internet connection then you can inform the user about it by a Dialog.
(2) If there is an internet connection but its very slow, then you can put some code for waiting for the response for a certain time and then showing a Dialog to user for waiting or aborting the request.
(3) One more thing which is very useful - use slide_in_left and slide_out_right anim styles in place of fade_in and fade_out for transitions between intents. It helps a lot, the screen goes black very rarely.
     try    {
        Intent yourIntent = new Intent(view.getContext(), YourActivity.class);
        startActivityForResult(yourIntent, 0);
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    } catch(Exception ex) {
    }

(4) Use AsyncTask for sending the requests to web.

A: You could check to see if there is an existing internet or data connection prior to making the call. You should also be able to specify a certain length of time to try and load the file, then display an error or try again as desired.


text:
Q: Tkinter programs opening 2 windows problem I am trying to create a bank program in tkinter where you login and register, but a problem happens when I try to run it. When I run the first file, it opens the window 2 times, which is what I do not want.
This is my main file:
from Login import *
from time import *
from tkinter import *

#Frame Setup########
root = Tk()
root.title("Main_File")
root.configure(bg="SeaGreen")
var = Frame(root)
var.configure(bg=var.master['bg'])
var.grid()

Login(var)

def LogClicked():
    print("Log")

def RegClicked():
    print("Reg")

This is my second file:
from tkinter import *

def Login(Log):
    import Main_File
    #First Name#########
    L1 = Label(Log, text="First Name:")
    L1.configure(font=("Courier", 35),bg=L1.master['bg'], fg="Gold")
    L1.grid(row=0, column=0, padx=(50, 0), pady=(100, 0))
    FirstN = Entry(Log)
    FirstN.configure(width=50)
    FirstN.grid(row=0, column=1, pady=(100, 0))

    #Last Name##########
    L2 = Label(Log, text="Last Name:")
    L2.configure(font=("Courier", 35),bg=L2.master['bg'], fg="Gold")
    L2.grid(row=1, column=0, padx=(50, 0), sticky=W)
    LastN = Entry(Log)
    LastN.configure(width=50)
    LastN.grid(row=1, column=1)

    #Login Button#######
    LogB = Button(Log, text="Login", command = lambda : Main_File.LogClicked())
    LogB.configure(font=("Courier", 15),bg=LogB.master['bg'],     activebackground=LogB.master['bg'], width=25)
    LogB.grid(row=3, column=1)

    #Register Button####
    RegB = Button(Log, text="Register", command = lambda : Main_File.RegClicked())
    RegB.configure(font=("Courier", 15),bg=RegB.master['bg'], activebackground=RegB.master['bg'], width=25)
    RegB.grid(row=4, column=1)

Now no matter what, I always have to run the main file first. Any help will be appreciated. Thank you.

A: The problem is import Main_File from Login.py. You are importing the whole module which includes the creation of Tk(), hence the added window. Also it is much preferred to use import tkinter as tk instead of the global import from tkinter import *.
If you must retain Main_file and Login as separate files, you can try the below:
from Login import Login
from time import *
from tkinter import *

#Frame Setup########
root = Tk()
root.title("Main_File")
root.configure(bg="SeaGreen")
var = Frame(root)
var.configure(bg=var.master['bg'])
var.grid()

Login(var)

root.mainloop()

2nd file:
from tkinter import *

def Login(Log):
    #First Name#########
    L1 = Label(Log, text="First Name:")
    L1.configure(font=("Courier", 35),bg=L1.master['bg'], fg="Gold")
    L1.grid(row=0, column=0, padx=(50, 0), pady=(100, 0))
    FirstN = Entry(Log)
    FirstN.configure(width=50)
    FirstN.grid(row=0, column=1, pady=(100, 0))

    #Last Name##########
    L2 = Label(Log, text="Last Name:")
    L2.configure(font=("Courier", 35),bg=L2.master['bg'], fg="Gold")
    L2.grid(row=1, column=0, padx=(50, 0), sticky=W)
    LastN = Entry(Log)
    LastN.configure(width=50)
    LastN.grid(row=1, column=1)

    def LogClicked():
        print("Log")

    def RegClicked():
        print("Reg")

    #Login Button#######
    LogB = Button(Log, text="Login", command = lambda : LogClicked())
    LogB.configure(font=("Courier", 15),bg=LogB.master['bg'],     activebackground=LogB.master['bg'], width=25)
    LogB.grid(row=3, column=1)

    #Register Button####
    RegB = Button(Log, text="Register", command = lambda : RegClicked())
    RegB.configure(font=("Courier", 15),bg=RegB.master['bg'], activebackground=RegB.master['bg'], width=25)
    RegB.grid(row=4, column=1)