text:
Q: Many-to-many tag filter query with a junction table get slower with more tags. Can it be faster? Part 1
I have this query to find some videos containing all given tags. Here with tags 1,9,27,13,67 as an example.
SELECT *
FROM video v
WHERE v.id IN (
    SELECT tr1.vid as video_id FROM (SELECT video_id vid FROM tag_rel WHERE tag_id=1) tr1
    INNER JOIN (SELECT video_id vid FROM tag_rel WHERE tag_id=9) tr2 USING (vid)
    INNER JOIN (SELECT video_id vid FROM tag_rel WHERE tag_id=27) tr3 USING (vid)
    INNER JOIN (SELECT video_id vid FROM tag_rel WHERE tag_id=13) tr4 USING (vid)
    INNER JOIN (SELECT video_id vid FROM tag_rel WHERE tag_id=67) tr5 USING (vid)
    -- more joins if more tags --
)
AND is_x=0
AND is_y=0
AND deleted IS NULL
LIMIT 0, 60

It executes in ~1.6 seconds.
If I run the inner select alone, it executes in ~0.8 seconds, and the result is 77 video ids.
Now, if I replace the inner select with these (example) video ids:
SELECT *
FROM video v
WHERE v.id IN (
    1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77
)
AND is_x=0
AND is_y=0
AND deleted IS NULL
LIMIT 0, 60

This query executes in ~0.06 seconds.
Question 1: Why is this the case, and why doesn't the full query run in ~0.86 seconds, which is the sum of the two operations (get video ids by tags and get videos by video ids)?
Part 2
For my application, I can't inject the ids because the inner select might return millions of ids. So I need them in one query, together with the support of checking is_x, is_y and deleted, and offsetting the limit for pagination.
I have spent months going back and forth, and this is the fastest query for most cases.
Question 2: Can this whole query be done faster/better with other techniques?
Question 3: By adding more tags, the query gets drastically slower, but isn't more joins just filtering down the number of possible results for the engine, so it should be faster with more tags?
Info
tag_rel contains about half a billion rows with about .5 million unique tag ids. The video table has around 30 million rows.
Full query explain:
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
| id | select_type | table   | partitions | type   | possible_keys            | key     | key_len | ref                           | rows    | filtered | Extra       |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
|  1 | SIMPLE      | tag_rel | NULL       | ref    | tag_id,video_id          | tag_id  | 4       | const                         | 1847596 |   100.00 | Using index |
|  1 | SIMPLE      | tag_rel | NULL       | eq_ref | tag_id,video_id          | tag_id  | 8       | const,db.tag_rel.video_id     |       1 |   100.00 | Using index |
|  1 | SIMPLE      | tag_rel | NULL       | eq_ref | tag_id,video_id          | tag_id  | 8       | const,db.tag_rel.video_id     |       1 |   100.00 | Using index |
|  1 | SIMPLE      | tag_rel | NULL       | eq_ref | tag_id,video_id          | tag_id  | 8       | const,db.tag_rel.video_id     |       1 |   100.00 | Using index |
|  1 | SIMPLE      | tag_rel | NULL       | eq_ref | tag_id,video_id          | tag_id  | 8       | const,db.tag_rel.video_id     |       1 |   100.00 | Using index |
|  1 | SIMPLE      | v       | NULL       | eq_ref | PRIMARY,is_x_2,deleted   | PRIMARY | 4       | db.tag_rel.video_id           |       1 |    50.00 | Using where |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------

Indexes:
tag_rel.tag_id      = unique(tag_id, video_id)
tag_rel.video_id    = unique(video_id, tag_id)
video.is_x_2        = (is_x, is_y, deleted)

A: Let's compare your two queries in part 1. Assume you have 100 videos and 10 tags evenly distributed. Every:
SELECT video_id vid FROM tag_rel WHERE tag_id=...

then produces 10 rows. If you join n of those the amount of rows that have to be examined is 10^n. In your example, n is 5 so 100000 rows. The result is then filtered down to whatever amount of videos that have all those tags, and compared with the videos that satisfy the other predicates. This comparison once again multiplies the numbers of rows that have to be compared.
For second query it is sufficient to examine 1000 rows given the assumptions above. This is of course greatly simplified but should give you an idea of the amount of extra work that has to be done in the first case.
What you want to do is to find the videos that have all tags, i.e.:
FORALL x:p(x)
FORALL is the universal quantifier (see for example: https://en.wikipedia.org/wiki/Quantifier_(logic)). Unfortenate, there is no operator in SQL that directly implements this. One way to overcome this is to translate it to an existential quantifier:
FORALL x:p(x) <=> NOT EXISTS x:NOT p(x)
This can be implemented in SQL, however most people find it more intuitive to count the distinct number of tags per movie and compare it to the length of tag list. Your query would then become:
SELECT video_id vid
FROM tag_rel
WHERE tag_id in (1,9,27,13,67)
GROUP BY video_id
HAVING COUNT(tag_id) = 5 -- 5 is the number of tags

Now we can simply join this back with videos:
SELECT v.* -- dont use * in your code
FROM video v
JOIN (
    SELECT video_id vid
    FROM tag_rel
    WHERE tag_id in (1,9,27,13,67)
    GROUP BY video_id
    HAVING COUNT(tag_id) = 5 -- 5 is the number of tags
) t
    ON t.video_id = v.video_id
WHERE is_x=0
  AND is_y=0
  AND deleted IS NULL;

The list of tags can easily be replaced by a select.
Apparently this question is not as efficient as the original, but I'll still add a possible optimization:
SELECT v.* -- dont use * in your code
FROM video v
JOIN (
    SELECT video_id vid
    FROM tag_rel
    WHERE tag_id in (1,9,27,13,67)
    GROUP BY video_id
    HAVING COUNT(tag_id) = 5 -- 5 is the number of tags
    LIMIT 0, 60
) t
    ON t.video_id = v.video_id
WHERE is_x=0
  AND is_y=0
  AND deleted IS NULL
LIMIT 0, 60;

A: I don't get why the subqueries are doubly nested. That combined with the   x IN <subquery> structure - which is known to be not well optimized in older versions of MySQL - is probably the issue. Even though you use 5.7, where there have been improvements on the optimizer, I'd prefer a JOIN over an IN (SELECT ..), especially if the SELECT is quite complex.
Suggestion: try to rewrite without any subqueries / derived tables.
SELECT v.*
FROM video AS v
   JOIN tag_rel AS tr1
     ON tr1.tag_id = 1  AND tr1.video_id = v.id
   JOIN tag_rel AS tr2
     ON tr2.tag_id = 9  AND tr2.video_id = v.id
   JOIN tag_rel AS tr3
     ON tr3.tag_id = 27 AND tr3.video_id = v.id
   JOIN tag_rel AS tr4
     ON tr4.tag_id = 13 AND tr4.video_id = v.id
   JOIN tag_rel AS tr5
     ON tr5.tag_id = 67 AND tr5.video_id = v.id
    -- more joins if more tags --
WHERE
    v.is_x = 0
AND v.is_y = 0
AND v.deleted IS NULL
LIMIT 60 ;

Add indexes (no need, it seems you already have these):

*

*a (unique) index on tag_rel (tag_id, video_id)

*an index on video (deleted, is_x, is_y, id)

A: Without an ORDER BY, the 60 rows chosen is somewhat arbitrary.  Is that OK?
Here comes another approach.  First see if this gives you a list of ids that match tag_rel:
SELECT  video_id
    FROM  tag_rel
    WHERE  tag_id IN (1, 9, 27, 13, 67)
    GROUP BY  video_id
    HAVING  COUNT(*) = 5   -- 5 elements in the IN list

Then do
SELECT  v.*
    FROM
        ( SELECT  video_id
            FROM  tag_rel
            WHERE  tag_id IN (1, 9, 27, 13, 67)
            GROUP BY  video_id
            HAVING  COUNT(*) = 5
        ) AS x
    JOIN  video AS v  ON v.id = x.video_id
    WHERE  v.is_x = 0
      AND  v.is_y = 0
      AND  v.deleted IS NULL
    LIMIT  60 ;

Indexes:
tag_rel:  (tag_id, video_id)
video:  PRIMARY KEY(id) -- I assume you have this


text:
Q: Spring Boot Cannot load data.sql into h2 database I tried to implement an example of Spring Batch processing. After starting the app, I wanted all values defined in data.sql loaded to the h2 database but it didn't work.
Here is the application.properties file shown below.
server.port=2121

spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

spring.batch.job.enabled=false

Here is the data.sql file
DROP TABLE IF EXISTS USERS ;

CREATE TABLE USERS (
    "ID" BIGINT auto_increment NOT NULL PRIMARY KEY,
    "AGE" INTEGER NOT NULL,
    "BIRTHDAY" DATE,
    "COUNTRY" CHARACTER VARYING(255),
    "EMAIL" CHARACTER VARYING(255),
    "FIRST_NAME" CHARACTER VARYING(255),
    "GENDER" CHARACTER VARYING(255),
    "LAST_NAME" CHARACTER VARYING(255),
    "PERSON_ID" CHARACTER VARYING(255)
);

INSERT INTO USERS VALUES (1, 22, DATE '2000-08-15', 'China', 'gspearing0@flickr.com', 'Ginnie', 'FEMALE', 'Spearing', 'fa26fa96-97d3-4e8e-856a-fdf07499e13e');
INSERT INTO USERS VALUES (2, 23, DATE '1999-01-25', 'Panama', 'nloynes2@woothemes.com', 'Natala', 'FEMALE', 'Loynes', '24be24e6-525f-42de-855d-52d4fef21608');
INSERT INTO USERS VALUES (3, 9, DATE '2013-04-15', 'Japan', 'jheino3@mayoclinic.com', 'Jard', 'MALE', 'Heino', '87cdda81-45d0-451a-a62f-f8450eae1b64');
INSERT INTO USERS VALUES (4, 8, DATE '2014-05-09', 'Indonesia', 'jcarlaw1@t.co', 'Jilleen', 'FEMALE', 'Carlaw', 'c722e6d5-9024-49c5-80e0-c2555f1eb9cc');
INSERT INTO USERS VALUES (5, 22, DATE '2000-03-18', 'Indonesia', 'rgillino6@china.com.cn', 'Rainer', 'MALE', 'Gillino', '5302a199-f313-4a24-9550-d643001d9faf');
INSERT INTO USERS VALUES (6, 9, DATE '2013-02-16', 'China', 'rcossans4@harvard.edu', 'Roseline', 'FEMALE', 'Cossans', '06f70b0d-2c98-4f46-b933-528499ab91b3');

How can I fix the issue?
Here is the example link : Link

A: Here is the solution
Add
spring.jpa.defer-datasource-initialization=true

into application.properties file.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Created 3 UITextField in UIAlertView but not getting action I have created an UIAlertView with three (3) UITextField. How i can get the action of UIAlertView. The clickedButtonAtIndex delegate method is working.
But not getting the text i input in the field. Any idea ? Thanks in advance.
UIView *v_alert = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 250, 100)];
    v_alert.tag=10;

UITextField *textField1 = [[UITextField alloc] initWithFrame:CGRectMake(10,0,252,25)];
textField1.borderStyle = UITextBorderStyleRoundedRect;
textField1.placeholder = @"Your Previous Password";
textField1.keyboardAppearance = UIKeyboardAppearanceAlert;
textField1.delegate = self;
textField1.tag=1;

[v_alert addSubview:textField1];

UITextField *textField2 = [[UITextField alloc] initWithFrame:CGRectMake(10,30,252,25)];
textField2.placeholder = @"Your New Password";
textField2.borderStyle = UITextBorderStyleRoundedRect;
textField2.keyboardAppearance = UIKeyboardAppearanceAlert;
textField2.delegate = self;
textField2.tag=2;

[v_alert addSubview:textField2];

UITextField *textField3 = [[UITextField alloc] initWithFrame:CGRectMake(10,60,252,25)];
textField3.placeholder = @"Email";
textField3.borderStyle = UITextBorderStyleRoundedRect;
textField3.keyboardAppearance = UIKeyboardAppearanceAlert;
textField3.delegate = self;
textField3.tag=3;

[v_alert addSubview:textField3];

alertV = [[UIAlertView alloc] initWithTitle:@"Change Password" message:@"" delegate:self cancelButtonTitle:@"NO" otherButtonTitles:@"YES", nil];
[alertV setValue:v_alert  forKey:@"accessoryView"];
alertV.tag==100;
alertV.delegate=self;

[alertV show];

In delegate :
  - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
 {
NSLog(@"didDismissWithButtonIndex");

       UITextField*txt1=[[[self.view viewWithTag:100] viewWithTag:10] viewWithTag:0];
     UITextField*txt2= [[[self.view viewWithTag:100] viewWithTag:10] viewWithTag:1];
     UITextField*txt3= [[[self.view viewWithTag:100] viewWithTag:10] viewWithTag:2];

     NSLog(@"%@--%@--%@",txt1.text,txt2.text,txt3.text);
 }

A: First set textField delegate
<UITextFieldDelegate>

Then I tried the below code
    NSString *strAddress = @"14 UPPER CIRCULAR ROAD, Singapore 058412";

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:strAddress delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];

    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 250, 100)];

    UITextField *textField1 = [[UITextField alloc] initWithFrame:CGRectMake(10,0,252,25)];
    textField1.borderStyle = UITextBorderStyleRoundedRect;
    textField1.placeholder = @"Username";
    textField1.keyboardAppearance = UIKeyboardAppearanceAlert;
    textField1.delegate = self;
    [v addSubview:textField1];

    UITextField *textField2 = [[UITextField alloc] initWithFrame:CGRectMake(10,30,252,25)];
    textField2.placeholder = @"Password";
    textField2.borderStyle = UITextBorderStyleRoundedRect;
    textField2.keyboardAppearance = UIKeyboardAppearanceAlert;
    textField2.delegate = self;
    [v addSubview:textField2];

    UITextField *textField3 = [[UITextField alloc] initWithFrame:CGRectMake(10,60,252,25)];
    textField3.placeholder = @"Address";
    textField3.borderStyle = UITextBorderStyleRoundedRect;
    textField3.keyboardAppearance = UIKeyboardAppearanceAlert;
    textField3.delegate = self;
    [v addSubview:textField3];

    [alert setValue:v  forKey:@"accessoryView"];

    [alert show];

TextField Delegate method
 - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
 {
    NSLog(@"The delegate method is called");
    return YES;
 }

Also see my screen shot

The output result is
  The delegate method is called

A: Declare Your 3 TextField
UITextField *textField1, *textField2, *textField3;

Then replace this code with your code.
 UIView *alertview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 250, 250)];
    alertview.backgroundColor = [UIColor whiteColor];
    alertview.tag=10;
    textField1 = [[UITextField alloc] initWithFrame:CGRectMake(10,0,252,25)];
    textField1.borderStyle = UITextBorderStyleRoundedRect;
    textField1.placeholder = @"Your Previous Password";
    textField1.secureTextEntry = YES;
    textField1.keyboardAppearance = UIKeyboardAppearanceAlert;
    textField1.delegate = self;
    textField1.tag=1;

    [alertview addSubview:textField1];

    textField2 = [[UITextField alloc] initWithFrame:CGRectMake(10,30,252,25)];
    textField2.placeholder = @"Your New Password";
    textField2.secureTextEntry = YES;
    textField2.borderStyle = UITextBorderStyleRoundedRect;
    textField2.keyboardAppearance = UIKeyboardAppearanceAlert;
    textField2.delegate = self;
    textField2.tag=2;

    [alertview addSubview:textField2];

    textField3 = [[UITextField alloc] initWithFrame:CGRectMake(10,60,252,25)];
    textField3.placeholder = @"Email";
    textField3.borderStyle = UITextBorderStyleRoundedRect;
    textField3.keyboardAppearance = UIKeyboardAppearanceAlert;
    textField3.delegate = self;
    textField3.tag=3;

    [alertview addSubview:textField3];

    UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"Change Password" message:@"" delegate:self cancelButtonTitle:@"NO" otherButtonTitles:@"YES", nil];
    [alertV setValue:alertview  forKey:@"accessoryView"];
    alertV.tag==100;
    alertV.delegate=self;

    [alertV show];

Now your UIAlertView Button Method
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        NSLog(@"Button No click");
    }
    if (buttonIndex == 1) {
         NSLog(@"Button Yes Cancel");
    }
    NSLog(@"%@--%@--%@",textField1.text,textField2.text,textField3.text);
}

Output :
Gems--Moradiya--Himmoradiya@gmail.com

A: That's the trick i accepted. But the standard way is for latest iOS:
 UIAlertController * alert=   [UIAlertController
                              alertControllerWithTitle:@"Change Password"
                              message:@""
                              preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction* ok = [UIAlertAction
                     actionWithTitle:@"OK"
                     style:UIAlertActionStyleDefault
                     handler:^(UIAlertAction * action)
                     {

                          UITextField *alertText1 = [alert.textFields objectAtIndex:0];
                         UITextField *alertText2 = [alert.textFields objectAtIndex:1];
                         UITextField *alertText3 = [alert.textFields objectAtIndex:2];

                         if(alertText1.text.length>0&&alertText1.text.length>0)
                         {
                             NSLog(@"Resolving UIAlert Action for tapping OK Button:%@-%@-%@",alertText1.text,alertText2.text,alertText3.text);

                             oldpPass=alertText1.text;

                             NewPass=alertText2.text;

                            [self update_password];

                         }

                         [alert dismissViewControllerAnimated:YES completion:nil];

                     }];
UIAlertAction* cancel = [UIAlertAction
                         actionWithTitle:@"Cancel"
                         style:UIAlertActionStyleDefault
                         handler:^(UIAlertAction * action)
                         {
                             NSLog(@"Resolving UIAlertActionController for tapping cancel button");
                             [alert dismissViewControllerAnimated:YES completion:nil];

                         }];

[alert addAction:ok];
[alert addAction:cancel];

[alert addTextFieldWithConfigurationHandler:^(UITextField * textField) {
    textField.placeholder = @"Enter old password";
    textField.accessibilityIdentifier = @"paswordTextField";
    textField.accessibilityLabel = @"passwordLabel";
}];

[alert addTextFieldWithConfigurationHandler:^(UITextField * textField) {
    textField.placeholder = @"Enter New password";
    textField.accessibilityIdentifier = @"paswordTextField";
    textField.accessibilityLabel = @"passwordLabel";
}];

[alert addTextFieldWithConfigurationHandler:^(UITextField * textField) {
    textField.accessibilityIdentifier = @"usernameTextField";
    textField.placeholder = @"Enter email";
    textField.text=self.emailTF.text;//
    textField.accessibilityLabel = @"usernameLabel";
}];

[self presentViewController:alert animated:YES completion:nil];


text:
Q: Failing to train SkipGram word embedding in Pytorch I am training the skipgram word embeddings using the famous model described in https://arxiv.org/abs/1310.4546. I want to train it in PyTorch but I am getting errors and I can't figure out where they are coming from. Below I have provided my model class, training loop, and batching method. Does anyone have any insight into whats going on?
I am getting an error on the output = loss(data, target) line. It is having a problem with <class 'torch.LongTensor'> which is weird because CrossEntropyLoss takes a long tensor. The output shape might be wrong which is: torch.Size([1000, 100, 1000]) after the feedforward.
I have my model defined as:
import torch
import torch.nn as nn

torch.manual_seed(1)

class SkipGram(nn.Module):

    def __init__(self, vocab_size, embedding_dim):
        super(SkipGram, self).__init__()
        self.embeddings = nn.Embedding(vocab_size, embedding_dim)
        self.hidden_layer = nn.Linear(embedding_dim, vocab_size)

        # Loss needs to be input: (minibatch (N), C) target: (minibatch, 1), each label is a class
        # Calculate loss in training

    def forward(self, x):
        embeds = self.embeddings(x)
        x = self.hidden_layer(embeds)
        return x

My training is defined as:
import torch.optim as optim
from torch.autograd import Variable

net = SkipGram(1000, 300)
optimizer = optim.SGD(net.parameters(), lr=0.01)

batch_size = 100
size = len(train_ints)

batches = batch_index_gen(batch_size, size)
inputs, targets = build_tensor_from_batch_index(batches[0], train_ints)

for i in range(100):
    running_loss = 0.0

    for batch_idx, batch in enumerate(batches):
        data, target = build_tensor_from_batch_index(batch, train_ints)
#         if (torch.cuda.is_available()):
#             data, target = data.cuda(), target.cuda()
#             net = net.cuda()
        data, target = Variable(data), Variable(target)
        optimizer.zero_grad()
        output = net.forward(data)
        loss = nn.CrossEntropyLoss()
        output = loss(data, target)
        output.backward()
        optimizer.step()
        running_loss += loss.data[0]
        optimizer.step()

        print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                i, batch_idx * len(batch_size), len(size),
                100. * (batch_idx * len(batch_size)) / len(size), loss.data[0]))

If useful my batching is:
def build_tensor_from_batch_index(index, train_ints):
    minibatch = []
    for i in range(index[0], index[1]):
        input_arr = np.zeros( (1000,1), dtype=np.int )
        target_arr = np.zeros( (1000,1), dtype=np.int )
        input_index, target_index = train_ints[i]
        input_arr[input_index] = 1
        target_arr[input_index] = 1

        input_tensor = torch.from_numpy(input_arr)
        target_tensor = torch.from_numpy(target_arr)

        minibatch.append( (input_tensor, target_tensor) )

    # Concatenate all tensors into a minibatch
    #x = [tensor[0] for tensor in minibatch]
    #print(x)
    input_minibatch = torch.cat([tensor[0] for tensor in minibatch], 1)
    target_minibatch = torch.cat([tensor[1] for tensor in minibatch], 1)

    #target_minibatch = minibatch[0][1]
    return input_minibatch, target_minibatch

A: I'm not sure about that since I did not read the paper, but seems weird that you are computing the loss with the original data and the targets:
output = loss(data, target)

Considering that the output of the network is output = net.forward(data) I think you should compute your loss as:
error = loss(output, target)

If this doesn't help, briefly point me out what the paper says about the loss function.


text:
Q: How to order WP_Query with multiple posts by multiple ordering parameters? Does anyone know if it is possible to order a wordpress loop with multiple post types, but have each post type be ordered differently?
Say I have blog posts and events. Events have a start date and they should be in ascending order. The blog posts should be in descending order.
Suppose we're using pre_get_posts to try to filter this for the page loop.
You can specify anything you would use in a new WP_Query request, so we can set things like...
$query->set('post_type', array('posts', 'events'));

That much is working.
But as far as I know, there's no way to specify how to order an individual post type. Just the collection as a whole...
$query->set( 'orderby', 'title' );
$query->set( 'order', 'ASC' );

And I can't run a meta query on all results because only events have the start_date field populated...
So is it possible to do this within this hook?
I know how to do it by using multiple wp_query requests and merging the results, or by writing a manual query with $wpdb. I was just curious if you could do this with only the pre_get_posts hook.


text:
Q: error: cast to 'string' (aka 'char *') from smaller integer type 'int' [-Werror,-Wint-to-pointer-cast] I was solving caesar problem from CS50, and I got this error.
What does this error means?
I was expecting to print the key (which is type casted from string to int)
Help me to get the answer.......
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>

bool isnotdigit(string inp_key);
int main(int argc, string argv[])
{

   int key;
   if (argc > 2 || isnotdigit(argv[1]))
   {
    printf("Usage: ./caesar key\n");
   }
   else{
    key = (int) argv[1];
    printf("%i\n", key);
   }
}
bool isnotdigit(string inp_key)
{

 int uac = 0;
    for (int k = 0; k != strlen(inp_key); k++)
    {
        if (isalpha(inp_key[k]) || isblank(inp_key[k]) || isspace(inp_key[k]))
        {
            uac++;
        }
        else
        {
            uac += 0;
        }
    }

   if (uac > 0)
   {
    return true;
   }
   else
   {
    return false;
   }

}

A: The error comes from this line:
key = (int) argv[1];

Try instead:
key = atoi(argv[1]);

Edit 1: As a side note, your isnotdigit function is a bit buggy in the for loop k != strlen(inp_key), and you could achieve the same result in your function without the uac variable by exiting the for loop if detected a char that is not a number.


text:
Q: Calculating Sinuosity Using ArcGIS Field Calculator Trying to calculate sinuosity via Field Calculator (ArcGIS v 10.2.2); VBA
Pre-Logic Script Code:
Dim dblLe as double
Dim dblLf as double
Dim dblS as double
Dim pCurve as Icurve
Dim pFPoint as IPoint
Dim pTPoint as IPoint
Set pCurve = [Shape]
Set pFPoint = pCurve.FromPoint
Set pTPoint = pCurve.ToPoint
dblLe = Sqr((pFPoint.X - pTPoint.X)^2 + (pFPoint.Y - pTPoint.Y)^2)
dblLf  = pCurve.Length
dblS = dblLe/dblLf

Variable =
dblS

I know ESRI has a python script put I am try to run via Field Calculator.  Anyone see my error?

A: If done in Python:
Expression parameter:
getSinuosity(!shape!)

Codeblock parameter:
import math
def getSinuosity(shape):
    length = shape.length
    d = math.sqrt((shape.firstPoint.X - shape.lastPoint.X) ** 2 +
                  (shape.firstPoint.Y - shape.lastPoint.Y) ** 2)
    return d / length

Make sure to use an expression type of PYTHON_9.3.
Also take a look at this tool here. I wrote this a couple of years ago as part of a demo. Under the hood, it's using CalculateField like I've described above.


text:
Q: Как растянуть игру вверх для нестандартного соотношения экрана телефона? Нужна формула для растягивания вверх на нестандартных экранах без потери качества.
Такая, чтобы она растягивала верхнюю часть игры от стандартов в 16:9 до 21:9 (телефоны sony)
без использования viewport

A: realWidth - реальная высота у телефона
Width используется для масштабирования элементов по x
HEIGHT по y
public static float WIDTH;
public static float HEIGHT;
public static float realHeight;

{
    WIDTH = 720f;
    HEIGHT = 1280f;
}

public GameField(Main main) {
    this.main = main;

    realHeight = Gdx.app.getGraphics().getHeight() / (Gdx.app.getGraphics().getWidth() / WIDTH);

    camera = new OrthographicCamera(WIDTH, realHeight);
    stage = new Stage(new StretchViewport(WIDTH, realHeight, camera));}


text:
Q: Why is a folder named ".dist" automatically created in VS Code? Everytime I open a folder or create a workspace, VS Code automatically generates a ".dist" folder and it has been bugging me for quite a long time now and I still do not understand why it even exits in the first place.
It does not seem like there is any problem in deleting the folder.
For me, it is just some bloat that automatically generates when said conditions are met.
I would really like to find if there is a setting which I can toggle ON that disables the auto-generation of the ".dist" folder.

A: This is due to an extension you have installed which makes it to help with compliling or running. Sass/Less/Typescript/Jade/Pug Compile Hero Plugin is probably the extension that does this.


text:
Q: jqgrid 2 span elements within one custom cell? Within my custom cell there are 2 span-elements.

    BER01_CN_045_002

Is there a way to avoid this?
See the demo, I am talking about cell "code".

A: I think, that you should don't spend your time in such kind of code optimization. Like I tried to explain in my previous answer the first  will be inserted by jqGrid for all form elements having the option edittype:'custom'. The second  you inserted yourself in the code of your custom formatter. It is permitted to have nested  elements like to have nested
 elements. I recommend you better to follows the jqGrid standard code as trying to make any kind of optimization which nobody will see at the end except you.
Moreover if you look more in the HTML code of your page generated by jqGrid you will see that the form itself (the form with id="FrmGrid_grid" in your example) are placed inside of . In the same way in the code of the column headers you will also find  which has another two  elements as the children. Would you like to try to "optimize" also the code? So I repeat my advice just to hold jqGrid standards and not trying to optimize such small pieces of code like nested  elements.


text:
Q: How can I open csv files and read them and sort them based on the data inside it? So I'm trying to find how to open csv files and sort all the details in it...
so an example of data contained in a CSV file is...
2,8dac2b,ewmzr,jewelry,phone0,9759243157894736,us,69.166.231.58,vasstdc27m7nks3
1,668d39,aeqok,furniture,phone1,9759243157894736,in,50.201.125.84,jmqlhflrzwuay9c
3,622r49,arqek,doctor,phone2,9759544365415694736,in,53.001.135.54,weqlhrerreuert6f

and so I'm trying to let a function sortCSV(File) to open the CSV file and sort it based on the very first number, which is 0, 1 ....
so the output should be
1,668d39,aeqok,furniture,phone1,9759243157894736,in,50.201.125.84,jmqlhflrzwuay9c
2,8dac2b,ewmzr,jewelry,phone0,9759243157894736,us,69.166.231.58,vasstdc27m7nks3
3,622r49,arqek,doctor,phone2,9759544365415694736,in,53.001.135.54,weqlhrerreuert6f

Here is my code so far, which clearly doesn't work....
import csv
def CSV2List(csvFilename: str):
    f = open(csvFilename)
    q = list(f)
    return q.sort()

What changes should I make to my code to make sure my code works??

A: using pandas, set the first column as index and use sort_index to sort based on your index column:
import pandas as pd
file_path = '/data.csv'
df = pd.read_csv(file_path,header=None,index_col=0)
df = df.sort_index()
print(df)

A: This is not the best way to deal with CSV files but:
def CSV2List(csvFilename: str):
    f = open(csvFilename,'r')
    l = []
    for line in f:
        l.append(line.split(','))

    for item in l:
        item[0] = int(item[0])

    return sorted(l)

print(CSV2List('data.csv'))

However I would probably use pandas instead, it is a great module

A: There's a number of ways you could handle this but one of the easiest would be to install Pandas (https://pandas.pydata.org/).
First off you most likely will need some titles of each column which should be on the first row of you CSV file. When you've added the column titles and installed pandas:
With pandas:
import pandas as pd

dataframe = pd.read_csv(filepath, index=0)

This will set the first column as the index column and will be sorting on the index.

Another way I've had to handle CSV:s with difficult formatting (aka exporting form excel etc) is by reading the file as a regular file and then iterating the rows to handle them on my own.
final_data = []
with open (filepath, "r") as f:
    for row in f:
        # Split the row
        row_data = row.split(",")
        # Add to final data array
        final_data.append(row_data

# This sorts the final data based on first row
final_data.sort(key = lambda row: row[0])

# This returns a sorted list of rows of your CSV
return final_data

A: try csv.reader(Filename)
import csv
def CSV2List(csvFilename: str):
    f = open(csvFilename)
    q = csv.reader(f)
    return q.sort(key=lambda x: x[0])

A: Using the csv module:
import csv

def csv_to_list(filename: str):
   # use a context manager here
    with open(filename) as fh:
        reader = csv.reader(fh)
        # convert the first item to an int for sorting
        rows = [[int(num), *row] for num, *row in reader]

    # sort the rows based on that value
    return sorted(rows, key=lambda row: row[0])


text:
Q: Change parameters in Convolution neural network I'm praticing CNNs. I read some papers about training MNIST dataset use CNNs.size of image is 28x28 and use architecture 5 layers: input>conv1-maxpool1>conv2-maxpool2>fully connected>output
Convolutional Layer #1
- Computes 32 features using a 5x5 filter with ReLU activation.
- Padding is added to preserve width and height.
- Input Tensor Shape: [batch_size, 28, 28, 1]
- Output Tensor Shape: [batch_size, 28, 28, 32]
Pooling Layer #1
- First max pooling layer with a 2x2 filter and stride of 2
- Input Tensor Shape: [batch_size, 28, 28, 32]
- Output Tensor Shape: [batch_size, 14, 14, 32]
Convolutional Layer #2
- Computes 64 features using a 5x5 filter.
- Padding is added to preserve width and height.
- Input Tensor Shape: [batch_size, 14, 14, 32]
- Output Tensor Shape: [batch_size, 14, 14, 64]
Pooling Layer #2
- Second max pooling layer with a 2x2 filter and stride of 2
- Input Tensor Shape: [batch_size, 14, 14, 64]
- Output Tensor Shape: [batch_size, 7, 7, 64]
Flatten tensor into a batch of vectors
- Input Tensor Shape: [batch_size, 7, 7, 64]
- Output Tensor Shape: [batch_size, 7 * 7 * 64]
Fully Connected Layer
- Densely connected layer with 1024 neurons
- Input Tensor Shape: [batch_size, 7 * 7 * 64]
- Output Tensor Shape: [batch_size, 1024] Output layer
- Input Tensor Shape: [batch_size, 1024]
- Output Tensor Shape: [batch_size, 10]

In conv1, with 1 input computates 32 features using a 5x5 filter and in conv2 with 32 input from conv1 computates 64 features using same filter. What are parameters such as 32,64,2x2 filter chosen based on? Do they based on size of image?
If size of images is larger than 28x28 such as 128x128. Should I increse the number of layers over 5 layers? How are above parameters changed with other size of images?
Thank advance

A: At it's base level, those inputs are called HyperParameters and are not typically defined by any particular set of rules. That said, often we use rules of thumb (heuristics) to choose a set of hyper parameters and then use hyperparameter optimisation to increase performance or efficiency etc.
A great explanation of this is Here
Edit:
Further info in this paper - it's a widely studied problem, look into Arxiv and Stats.Stackexchange for more info but here is a great paper I used when I was learning Here

A:
What are parameters such as 32,64,2x2 filter chosen based on? Do they
based on size of image?

The parameters that you have mentioned (32,64,2x2) are number of filters for a convolutional layer and a filter size. They are the hyperparameters that you can select and adjust as you train your models. Depending on your dataset, application and model performance you can control them.
For a number of filters, you use it to control number of features that your model learns. In your model, your filter number increase from 32 to 64 after maxpooling layer. Maxpooling layer with 2x2 filter will reduce the number of features by half. And by increasing the filter numbers by double, it will keep the same number of features in the model. In convention, after a 2x2 maxpooling layer, the filter number will double for this reason.
And for the filter size, if it's for maxpooling layer, it will determine the size of feature reduction. If it's for convolutional layer, it will determine how detail the input images are learned. For example, if you are trying to work with images where small pixels or features differciate objects, you would choose small filter size such as 3x3 or 5x5. And vise versa for large filter size.
One way of understanding these hyperparameters is that understand how these affect learning of the model and you will know how to control them depending on each case. And another way is to look at how these are set for models used by other people. You may find some conventions such as filter number increasing after maxpooling layer.

If size of images is larger than 28x28 such as 128x128. Should I
increse the number of layers over 5 layers? How are above parameters
changed with other size of images?

And about layers, having more layers will make your model deeper and will result in more parameters. This means that your model will become more complex and become able to learn more about image features. So, having a deep architecture can benefit learning images with large resolutions. Because large resolution means there are many features to learn. However, this also will depend case by case. Good approach to this would be starting with simple model with few layers and gradually increase your layers while it benefits your model.


text:
Q: Single Page App without URL I'm joining a team that is currently working on a single page app. It is written with AngularJS, but it doesn't matter for the topic.
The App is so complex (many independant views with complex different states within each) that they completly removed the router (well, excerpt the default route).
I'm googling around but I can see no example of webapp that is not trying to work properly with URLs. Is there any risk of not using any URL, beyond the fact that "it is not the elegant way" ?
EDIT : ui-router does not fit, because of this issue : https://github.com/christopherthielen/ui-router-extras/issues/90

A: It sounds like you want to look into something like UI-Router which works on states.
https://github.com/angular-ui/ui-router
I can't imagine any significant issues with your app if you do it this way, but I can see massively bloated controllers and code to try and get around any issues you find.

A: as @Varedis said, you can use ui-router, but to answer your actual question, consider the use case for urls.
If you have only one url, there's only one entry point into your app. This can be annoying if the user expects to be able to quickly go to a certain area (state) within your app. Only one url means that the user can't bookmark, directly go to, or find with a search engine, any specific part of your application.
You can use other mechanisms like cookies or LocalStorage to keep track of state, but these are less user-visible.

A: I work on the project and i founded a month ago, ui-router-extras which provide parralel states but it can't instiante more than one state instance.
Is there another solution to do that ?


text:
Q: Fire event observer when product is enabled I want to fire event observer when products are enabled from admin, I can not find any event for this please help on this.
I want to do below things

*

*Once the product is enabled or disabled need to mail admin.

*I want to do it from the Observer or any other method.

Please help!

A: For making a call on product save you can create a plugin to call it on product save.
For that, you have to add code in etc/adminhtml/di.xml
<type name="Magento\Catalog\Controller\Adminhtml\Product\Save">
    <plugin name="supplier_plugin_product_save_after" type="Vendor\Module\Plugin\Adminhtml\ProductSave" sortOrder="1" />
</type>

And in ProductSave.php file in Plugin/Adminhtml and add the code as per your need in code given below
<?php
namespace Vendor\Module\Plugin\Adminhtml;

use Magento\Catalog\Controller\Adminhtml\Product\Save;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Registry;
use Magento\Framework\Exception\LocalizedException;

class ProductSave
{
    /**
     * @var ManagerInterface
     */
    private $messageManager;

    /**
     * @var RequestInterface
     */
    private $request;

    /**
     * @var Registry
     */
    private $registry;

    public function __construct(
        ManagerInterface $messageManager,
        RequestInterface $request,
        Registry $registry
    ) {
        $this->messageManager = $messageManager;
        $this->request = $request;
        $this->registry = $registry;
    }

    /**
     * @param Save $subject
     * @param $result
     * @return mixed
     *
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function afterExecute(Save $subject, $result)
    {
        $product = $this->registry->registry('current_product');

        $productId = $product->getId();

        $params = $this->request->getParams();

        /****  ADD YOUR LOGIC HERE ****/
    }
}


text:
Q: How do I know if I've copied a photo from camera roll to album? Let's say I have 500 images that can be categorized in 5 albums: cars, houses, vacations, family. So I went to my camera roll, selected about 100 images related to "cars" and added them to folder "cars". Now I go back to the camera roll and I notice another picture of a car, but I'm not sure if I selected that one and copied it to the album.
Is there a way to know what pictures in camera roll were added to an album?
I have iPhone 5C, iOS 8.4.1.

A: They won't be duplicated. Albums only reference the pictures in your Camera Roll, they aren't actually copied.


text:
Q: Get PIDs of all open windows on MacOS I tried to use the following AppleScript to get the PIDs of all the windows (including ones that are minimized). This script doesn't get the PIDs of windows on other desktops.
Is there any workaround for this so I can still get a list of opened windows across all desktops without having to activate individual processes and checking if they have windows?
tell application "System Events"
    repeat with proc in (every process)
        if exists(first window of proc) then
            set pid to unix id of proc
            log pid
        end if
    end repeat
end tell

PS, I'm not too proficient with AppleScript. I've managed to hack this together using StackOverflow. This might not be the most efficient way to do what I'm trying to do.

A: Looks like I got this to work with this ugly bash-applescript hack
osascript -e "tell application \"System Events\"
    repeat with proc in (processes where background only is false)
        set pname to name of proc
        log pname
    end repeat
end tell" 2>&1 |
while read line
do
    echo "process " $line
    pgrep $line
done

This prints something like
process  Finder
818
process  Google Chrome
3730
3734
3740
5838
process  iTerm2
3750
4210
process  Sublime Text
3822

Where PID 818 belongs to the Finder process and so on.


text:
Q: IIS application gets error "Loading managed Windows PowerShell failed with error 80070005" executing powershell, but other app on same host works? I have two web apps hosted on the same Windows 2012 R2 server (an AWS EC2 instance). IIS version 8.5.9600.16384.
Both web apps call the same library function to execute the same Powershell script file on the C: drive. Both web apps' app pools run under Network Service.
However, only web app A is able to successfully execute the Powershell script. Web app B hit the following error when executing that same script:
I n t e r n a l   W i n d o w s   P o w e r S h e l l   e r r o r .    L o a d i n g   m a n a g e d   W i n d o w s   P o w e r S h e l l   f a i l e d   w i t h   e r r o r   8 0 0 7 0 0 0 5 .

80070005 suggests a permissions problem.
I have tried the following without luck:

*

*Have web app B use the same app pool as web app A

*Run procmon.exe and compared entries generated by both A and B and found no difference. Both A and B have "process start" events for the script that returned "SUCCESS" status. No "ACCESS DENIED" error found.

Example of such "SUCCESS" event which failed in the end:
Event Class:    Process Operation:  Process Start Event Class:  Process Operation:  Process Start Result:   SUCCESS Path:    TID:   3568 Duration:  0.0000000 Parent PID:   1748 Command line:  "powershell.exe" -NoProfile -ExecutionPolicy unrestricted -file "C:\scripts\dostuff.ps1" -arg1 "sometext" Current directory:    c:\windows\system32\inetsrv\

What could cause this permissions problem with executing Powershell?

A: I found a way to workaround it, which is to use LocalSystem instead of Network Service.


text:
Q: keychain config in xamarin forms I am using xamarin forms
I am trying to use xamarin.Auth to save some informations in the database...and when I did it in android all happend ok ...
But in ios I receive this error...
> Xamarin.Auth.AccountStoreException: SaveAsync error = error = Could not save account to KeyChain: -34018
Add Empty Entitlements.plist
 File /+ New file /+ iOS /+ Entitlements.plist
SecKeyChain.Add returned : -34018
1. Add Keychain Access Groups to the Entitlements file.
2. Turn on the Keychain Sharing switch in the Capabilities section in the app.

I am using these lines in my pcl code behind:
        account.Properties.Add("teste2", "1");
        account.Properties.Add("teste1", "usereee");
        AccountStore.Create().Save(account, "clastech_montana");

It's all I did... and I searched a lot and I don't know how to turn on the keychain or if it all I did is right..
Please, If you can, help me!

there is not a place to enable

A: in your iOS project, open Entitlements.plist, and check "Enable Keychain"


text:
Q: Rotate an object right or left 90 degrees and move forward on a grid I have the following scenario for which i need to create a java program. Any ideas how to implement this:
A small robot which can move on a grid, controlled by simple commands.
In this example, it will move on a 5x5 grid with a simple co-ordinate system - 0,0 is the bottom left, 4,4 is the top right.
We can control the robot by sending it a string consisting of commands, such as the following: RFLFFRF
R means rotate right 90 degrees, L rotate left 90 degrees, and F means move forward one square in the direction the Rover is currently facing. The Rover starts at 0,0 facing North ("up" the grid).
I need to write a program which will accept strings of commands and return the grid position of the obot after those commands

A: Write a robot class containing a position and an orientation, then implement the three commands (R, L and F) on it. Finally, write code to parse the command sequence and run the commands. Create a new robot, run the command sequence on it and output the position when you're done.

A: Function:
     public int Robot(int input1,int input2,String input3,String input4)
     {
        int flag=0;
        String s[]=input3.spilt("-");
        int x=Integer.parseInt(s[0]);
        int y=Integer.parseInt(s[1]);
        String curface=s[2];
         for(int i=0;i0){x--;}else{flag=1;break;}break;
                    case "E":if(x0){y--;}else{flag=1;break;};
                }
          }
        }
        String out="";
        if(flag==0)
        {
            out=""+x+"-"+y+"-"+curface;
        }
        else
        {
           out=""+x+"-"+y+"-"+curface+"-ER";
        =
        }
        return out;
    }


text:
Q: Вопрос по sql, можно ли это сделать одним SELECT запросом? таблица пользователей:
users
----------
`id` int(11)
`email` varchar(55)
`login` varchar(55)

и таблица заказов
orders
--------
`id` int(11)
`user_id` int(11)
`price` int(11)

Нужно вывести список logino'в-пользователей, которые сделали более двух заказов.
можно ли это сделать одним SELECT запросом ?

A: *

*считаем количество заказов:
SELECT `user_id` FROM `orders` GROUP BY `user_id` HAVING COUNT(*) > 2;

*делаем SELECT из users
SELECT `users`.`login`
FROM `users`
WHERE `users`.`id` IN (
    SELECT `user_id` FROM `orders` GROUP BY `user_id` HAVING COUNT(*) > 2
);

Здесь можно увидеть пример исполнения: PHPize.online
Возможен вариант используя JOIN:
SELECT `users`.`login`
FROM `users`
JOIN (
    SELECT `user_id` FROM `orders` GROUP BY `user_id` HAVING COUNT(*) > 2
) `more2orders` ON `more2orders`.`user_id` = `users`.`id`;

или
SELECT `users`.`login`
FROM `users`
JOIN `orders` ON `orders`.`user_id` = `users`.`id`
GROUP BY `users`.`login`
HAVING COUNT(*) > 2;

PHPize.online


text:
Q: Disable time ranges in jquery timepicker dynamically var eachTime = "11.00 am,11.15 am,11.30 am,11.45 am,11.45 am,12.00 pm,12:00  pm,12.15 pm,12:15  pm,12.30 pm";

How to make an array whose value is ['11.00 am','11.15 am'],['11.30 am','11.45 am'], ...,['12:15  pm','12.30 pm']
I need to make such array to pass to timepicker for disabling this time.
Any one please help me

A: Though there's a doubled items in your string, I can suggest the solution for converting  the string into array of consecutive "time" pairs(used functions: String.split, Array.forEach and Array.push):
var eachTime = "11.00 am,11.15 am,11.30 am,11.45 am,11.45 am,12.00 pm,12:00  pm,12.15 pm,12:15  pm,12.30 pm",
    time_arr = eachTime.split(","), new_arr = [];

time_arr.forEach(function(v, k , arr){
    if (k % 2 & 1) new_arr.push([arr[k-1], arr[k]]);  // check for odd keys
})

console.log(JSON.stringify(new_arr, 0, 4));

The output:
[
    [
        "11.00 am",
        "11.15 am"
    ],
    [
        "11.30 am",
        "11.45 am"
    ],
    [
        "11.45 am",
        "12.00 pm"
    ],
    [
        "12:00  pm",
        "12.15 pm"
    ],
    [
        "12:15  pm",
        "12.30 pm"
    ]
]

demo link


text:
Q: Transform values of a column in particular format I have a data frame df with a column called "Name". I have stored it separately as:
list = df.Name

This gives me result like
0    Christine
1    Alex
2    Brian
3    Thomas
4    Tom

I want to transform above output into the below form:
["Christine","Alex","Brian","Thomas","Tom"]

How can I perform this task using pandas?

A: Try this:
In [18]: df.Name.tolist()
Out[18]: [u'Christine', u'Alex', u'Brian', u'Thomas', u'Tom']

In [19]: df.Name.str.encode('latin-1', 'ignore').tolist()
Out[19]: ['Christine', 'Alex', 'Brian', 'Thomas', 'Tom']

PS but be careful with this solution - it won't work properly for "special" unicode characters...


text:
Q: Manually setting Flutter Validation Error After validating a form and sending a request from flutter to the server backend: I want to set any potential error message from the server to be displayed in the original form. Preferably exactly like a validation error.
For instance:
Widget build(BuildContext context) {
...
  TextFormField(
    onFieldSubmitted: (value) => _signIn(),
    validator: (input) {
      if (input.length < 6)
        return 'Your password is too short';
      return null;
    },
    onSaved: (input) => _password = input,
    decoration: InputDecoration(
      labelText: 'Password',
    ),
    obscureText: true,
  )
...
}

Future<void> _signIn() async {
  final formState = _formKey.currentState;
  if (!formState.validate()) return;
  formState.save();

  try {
    ... // do fancy request stuff
  } catch (e) {
    // this is where I want to set the "validation" error
  }
}

A: It's actually super simple and the validation error still works aswell.
String? _errorMsg;

Widget build(BuildContext context) {
...
  TextFormField(
    onFieldSubmitted: (value) => _signIn(),
    validator: (input) {
      if (input.length < 6)
        // will set the errorText directly, no need for a variable here
        return 'Your password is too short';
      return null;
    },
    onSaved: (input) => _password = input,
    decoration: InputDecoration(
      labelText: 'Password',
      errorText: _errorMsg,
    ),
    obscureText: true,
  )
...
}

Future<void> _signIn() async {
  setState(() {
    _errorMsg = null; // clear any existing errors
  });

  final formState = _formKey.currentState;
  if (!formState.validate()) return;
  formState.save();

  try {
    ... // do fancy request stuff
  } catch (e) {
    setState(() {
      _errorMsg = 'Wrong password.';
    });
  }
}

A: I suppose, I could think of a solution, but I think it's kind of ugly.
I could have an "error" variable, that is set when the request fails.
I would then call formState.validate() a second time, in there: check the error variable and return it if it's not null.

A: You can use flutter_form_bloc and use addError method of TextFieldBloc.
usernameField.addError('That username is taken. Try another.');

Keep in mind that you can also use asynchronous validators.
This is a complete example:
dependencies:
  flutter:
    sdk: flutter
  flutter_bloc: ^0.21.0
  form_bloc: ^0.5.0
  flutter_form_bloc: ^0.4.1+1

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_bloc/flutter_form_bloc.dart';
import 'package:form_bloc/form_bloc.dart';

void main() {
  runApp(MaterialApp(home: SignUpForm()));
}

class SignUpFormBloc extends FormBloc<String, String> {
  final usernameField = TextFieldBloc();
  final passwordField =
      TextFieldBloc(validators: [Validators.passwordMin6Chars]);

  @override
  List<FieldBloc> get fieldBlocs => [usernameField, passwordField];

  @override
  Stream<FormBlocState<String, String>> onSubmitting() async* {
    // Form logic...
    try {
      await _signUp(
        throwException: true,
        username: usernameField.value,
        password: passwordField.value,
      );
      yield currentState.toSuccess();
    } catch (e) {
      // When get the error from the backend you can
      // add the error to the field:
      usernameField.addError('That username is taken. Try another.');

      yield currentState
          .toFailure('The error was added to the username field.');
    }
  }

  Future<void> _signUp({
    @required bool throwException,
    @required String username,
    @required String password,
  }) async {
    print(username);
    print(password);
    await Future<void>.delayed(Duration(seconds: 2));
    if (throwException) throw Exception();
  }
}

class SignUpForm extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider<SignUpFormBloc>(
      builder: (context) => SignUpFormBloc(),
      child: Builder(
        builder: (context) {
          final formBloc = BlocProvider.of<SignUpFormBloc>(context);

          return Scaffold(
            appBar: AppBar(title: Text('Sign Up Form')),
            body: FormBlocListener<SignUpFormBloc, String, String>(
              onSubmitting: (context, state) {
                // Show the progress dialog
                showDialog(
                  context: context,
                  barrierDismissible: false,
                  builder: (_) => WillPopScope(
                    onWillPop: () async => false,
                    child: Center(
                      child: Card(
                        child: Container(
                          width: 80,
                          height: 80,
                          padding: EdgeInsets.all(12.0),
                          child: CircularProgressIndicator(),
                        ),
                      ),
                    ),
                  ),
                );
              },
              onSuccess: (context, state) {
                // Hide the progress dialog
                Navigator.of(context).pop();
                // Navigate to success screen
                Navigator.of(context).pushReplacement(
                    MaterialPageRoute(builder: (_) => SuccessScreen()));
              },
              onFailure: (context, state) {
                // Hide the progress dialog
                Navigator.of(context).pop();
                // Show snackbar with the error
                Scaffold.of(context).showSnackBar(
                  SnackBar(
                    content: Text(state.failureResponse),
                    backgroundColor: Colors.red[300],
                  ),
                );
              },
              child: ListView(
                children: <Widget>[
                  TextFieldBlocBuilder(
                    textFieldBloc: formBloc.usernameField,
                    decoration: InputDecoration(labelText: 'Username'),
                  ),
                  TextFieldBlocBuilder(
                    textFieldBloc: formBloc.passwordField,
                    decoration: InputDecoration(labelText: 'Password'),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: RaisedButton(
                      onPressed: formBloc.submit,
                      child: Center(child: Text('SUBMIT')),
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}

class SuccessScreen extends StatelessWidget {
  const SuccessScreen({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.green[300],
      body: Center(
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              Icon(
                Icons.sentiment_satisfied,
                size: 100,
              ),
              RaisedButton(
                color: Colors.green[100],
                child: Text('Sign out'),
                onPressed: () => Navigator.of(context).pushReplacement(
                    MaterialPageRoute(builder: (_) => SignUpForm())),
              )
            ],
          ),
        ),
      ),
    );
  }
}

A: A simple solution:
Make a key for the widgets state:
GlobalKey<_CustomErrorTextField> _passwordTextFieldState = GlobalKey();

Set the Error message using the key:
_passwordTextFieldState.currentState.updateError(errorMsg);

Reset the error after 2 seconds:
Future.delayed(Duration(seconds: 2), () {
   // Runs after duration sec
   _passwordTextFieldState.currentState.updateError(null);
});

Set up the widget (be sure to set the key):
CustomErrorTextField(
   key: _passwordTextFieldState,
   label: "Password",
   currentPassword: password,
   validator: yourValidator,
   callback: passwordCallback,
   obscureText: hidePassword.value - a bool value show/hide password
)

Here is the Widget:
class CustomErrorTextField extends StatefulWidget {

  CustomErrorTextField({
    Key key,
    this.label,
    this.currentPassword,
    this.validator,
    this.callback,
    this.obscureText = false
  }): super(key: key);

  final String label;
  final String currentPassword;
  final FormFieldValidator<String> validator;
  final Function callback;
  final obscureText;

  @override
  _CustomErrorTextField createState() => _CustomErrorTextField();
}

class _CustomErrorTextField extends State<CustomErrorTextField> {

  String errorMsg;

  updateError(String errorMsg){
    setState(() {
      this.errorMsg = errorMsg;
    });
  }

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      decoration: InputDecoration(
          labelText: widget.label,
          errorText: errorMsg
      ),
      initialValue: widget.currentPassword,
      keyboardType: TextInputType.visiblePassword,
      validator: widget.validator,
      onSaved: (String val) {
        widget.callback(val);
      },
      obscureText: widget.obscureText,
    );
  }
}


text:
Q: C# PhantomJSDriver with Fiddler proxy and HTTP authentication: traffic not captured I am trying to navigate to an application on a localhost site that requires authentication using PhantomJSDriver and passing username:password into the URL. In order to capture response codes I'm using a Fiddler proxy from Jim Evan's example https://github.com/jimevans/WebDriverProxyExamples.
PhantomJSDriver navigates successfully (using NTLM/Basic auth) but Fiddler doesn't capture the traffic.
public static int NavigateTo(this IWebDriver driver, string targetUrl, TimeSpan timeout, bool printDebugInfo)
{
    int responseCode = 0;
    DateTime endTime = DateTime.Now.Add(timeout);
    SessionStateHandler responseHandler = delegate(Session targetSession)
    {
        if (targetSession.responseCode >= 300 && targetSession.responseCode < 400)
        {
            targetUrl = targetSession.GetRedirectTargetURL();
        }
        else
            responseCode = targetSession.responseCode;
    };

    // Attach the event handler, perform the navigation, and wait for
    // the status code to be non-zero, or to timeout. Then detach the
    // event handler and return the response code.
    FiddlerApplication.AfterSessionComplete += responseHandler;
    driver.Url = targetUrl;
    while (responseCode == 0 && DateTime.Now < endTime)
    {
        System.Threading.Thread.Sleep(100);
    }

    FiddlerApplication.AfterSessionComplete -= responseHandler;
    return responseCode;
}

I was able to capture the traffic when using ChromeDriver with the same application and also for a website that didn't require authentication using PhanotmJSDriver. The only scenario it doesn't work in is PhantomJSDriver + authentication website.
Update:
I discovered the issue thanks to Dead Link
http://docs.telerik.com/fiddler/observe-traffic/troubleshooting/notraffictolocalhost/. It was nothing to do with authentication rather getting traffic from localhost.
The solution was to use the local machine name in place of localhost in the URL.

A: I discovered the issue thanks to http://docs.telerik.com/fiddler/observe-traffic/troubleshooting/notraffictolocalhost/. It was nothing to do with authentication rather getting traffic from localhost. I'm not sure why, but it seems the combination of using PhantomJSDriver to navigate to a localhost url and Fiddler to capture the traffic did not work.
The solution was to use the local MACHINE NAME in place of 'localhost' in the URL.


text:
Q: xp_md5.dll for 64-bit I am right now using this extended stored procedure in one of the test database on sql server 2008 and it works fine. I tried to do the same on a different sql server and it did not work on that. Then I got an explaination that the former was a 32 bit processor and latter was a 64 bit processor. Is there anyway to make use of this extended stored procedure on a 64-bit processor!!!
I need recompile version of xp_md5.dll for 64-bit.
Thanks in advance

A: If you want an MD5 why not use 2008's built in HASHBYTES()?
DECLARE @IN  NVARCHAR(4000) = N'Hello'
DECLARE @OUT VARBINARY(16)

SET @OUT = HASHBYTES('MD5', @IN)

SELECT @OUT


text:
Q: Scripting dockutil What am I doing wrong?
I try to configure the dock with a shell script containing dockutil commands.
it works without problems for System Preferences, Safari, TextEdit,
Applications and ~/Downloads.
However App Store as well ~/Documents wont be attached...
If the commandos for App Store and ~/Document are given directly in the terminal the problem does not occur.
Does anyone have an Idea?
#!/bin/bash

#
# set Dock items
#

dockutil=/usr/local/bin/dockutil
$dockutil --remove all --allhomes
$dockutil --add '/Applications/System Preferences.app' --allhomes
$dockutil --add '/Applications/App Store.app' --allhomes
$dockutil --add '/Applications/Safari.app' --allhomes
$dockutil --add '/Applications/TextEdit.app' --allhomes
$dockutil --add '/Applications' --allhomes
$dockutil --add '~/Downloads' --allhomes
$dockutil --add '~/Documents' --allhomes

exit 0


text:
Q: Not able to copy entity in ManyToMany relationship I have an Entity Class Which has ManyToMany relationship with the other class.I want to create a new entry in the table of this instance by just changing its name property.
Employee.java`
@Entity
@Table(name = "employee")
public class Employee {
    public Employee() {
        super();
    }

    public Employee(String name, List<Address> address) {
        super();
        this.name = name;
        this.setAddress(address);
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;
    @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.REMOVE,CascadeType.DETACH },fetch=FetchType.EAGER)
    @JoinTable(name = "employee_address", joinColumns = { @JoinColumn(name = "employee_id") }, inverseJoinColumns = {
            @JoinColumn(name = "address_id") })
    private List<Address> address;

    @OneToOne
    private Department department;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public List<Address> getAddress() {
        return address;
    }

    public void setAddress(List<Address> address) {
        this.address = address;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }
}

Address.java
@Entity
@Table(name = "Address")
public class Address {
    public Address() {
        super();
    }

    public Address(String address) {
        super();
        this.address = address;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String address;

    @ManyToMany(mappedBy = "address", cascade = CascadeType.REMOVE)
    private List<Employee> employee;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

DataRetrivalServiceImpl.java
@Service
public class DataServiceImpl {
    @Autowired
    private EntityManager entityManager;
@Transactional
    public void copyEmpoyee() {
        Employee e = employeeRepo.findOneById(15);
        entityManager.detach(e);
        e.setId(0);
        e.setName("new Name");
        //employeeRepo.save(e);
        entityManager.persist(e);
    }

When i run the code a new entry is made in the employee table but not in the Address table. Can anyone please explain where am i doing wrong!
The Entire Code can be found at - https://github.com/iftekharkhan09/JPAHibernateProject


text:
Q: Initializing a Go map in a single statement This is my code:
var keys map[int]string
keys = make(map[int]string)

keys[1] = "aa"
keys[2] = "ab"
keys[3] = "ac"
keys[4] = "ba"
keys[5] = "bb"
keys[6] = "bc"
keys[7] = "ca"
keys[8] = "cb"
keys[9] = "cc"

Can I do the same thing in one statement and/or in one line?

A: When there is logic between keys and values, you may also use a loop to initialize the map. "Put" the logic into the loop body. This may be significantly shorter than using a composite literal enumerating all key-value pairs, especially if the number of key-value pairs is big.
Your example can be implemented with this:
m := map[int]string{}
for i := 0; i < 9; i++ {
    m[i+1] = string("abc"[i/3]) + string("abc"[i%3])
}
fmt.Println(m)

Output (try it on the Go Playground):
map[5:bb 8:cb 4:ba 2:ab 3:ac 6:bc 7:ca 9:cc 1:aa]

A variant of this solution (using a different logic implementation):
m := map[int]string{}
for i := 0; i < 9; i++ {
    m[i+1] = "abc"[i/3:i/3+1] + "abc"[i%3:i%3+1]
}
fmt.Println(m)

Output is the "same". Try this variant on the Go Playground.
And even more solutions, now posting only the loop body (Playground links:  another #1, another #2):
// Another #1:
m[i+1] = fmt.Sprintf("%c%c", "abc"[i/3], "abc"[i%3])
// Another #2:
m[i+1] = fmt.Sprintf("%c%c", 'a'+i/3, 'a'+i%3)

A different approach might use 2 loops (embedded) which generate the value, and calculates the key from the value:
for i := 'a'; i <= 'c'; i++ {
    for j := 'a'; j <= 'c'; j++ {
        m[int((i-'a')*3+j-'a'+1)] = string(i) + string(j)
    }
}

Try this on the Go Playground.
If the number of values is not big, another viable approach can be to enumerate all the elements in one string value, and use subslicing (which is efficient as no new backing arrays will be created, the backing array of the strings is shared):
const s = "aaabacbabbbccacbcc"

m := map[int]string{}
for i := 0; i < 9; i++ {
    m[i+1] = s[i*2 : i*2+2]
}
fmt.Println(m)

Output (try this on the Go Playground):
map[9:cc 1:aa 2:ab 5:bb 8:cb 3:ac 4:ba 6:bc 7:ca]

Also note that if the key is of type int and the set of keys is (more or less) contiguous, often it is more efficient (both memory and performance-wise) to use a slice instead:
m := make([]string, 10)
for i := 0; i < 9; i++ {
    m[i+1] = fmt.Sprintf("%c%c", 'a'+i/3, 'a'+i%3)
}
fmt.Printf("%q\n", m)

m2 := []string{"", "aa", "ab", "ac", "ba", "bb", "bc", "ca", "cb", "cc"}
fmt.Printf("%q\n", m2)

m3 := []string{1: "aa", "ab", "ac", "ba", "bb", "bc", "ca", "cb", "cc"}
fmt.Printf("%q\n", m3)

Output (try it on the Go Playground):
["" "aa" "ab" "ac" "ba" "bb" "bc" "ca" "cb" "cc"]
["" "aa" "ab" "ac" "ba" "bb" "bc" "ca" "cb" "cc"]
["" "aa" "ab" "ac" "ba" "bb" "bc" "ca" "cb" "cc"]

As you can see in the third example m3, you can use optional indices in the composite literal to specify the index of the value following. More about this here: Keyed items in golang array initialization

A: Yes, you can create a map with a single statement (called a composite literal in the spec):
var keys = map[int]string{
    1: "aa",
    2: "ab",
    3: "ac",
    4: "ba",
    5: "bb",
    6: "bc",
    7: "ca",
    8: "cb",
    9: "cc",
}

Or, if you are inside of a function, you can use a short variable declaration:
keys := map[int]string{
    1: "aa",
    2: "ab",
    3: "ac",
    4: "ba",
    5: "bb",
    6: "bc",
    7: "ca",
    8: "cb",
    9: "cc",
}

A: My preferred approach is a composite literal in a short variable declaration. In some cases a function might help to reduce clutter.
package main

import (
    "fmt"
)

// initMap initializes a map with an integer key starting at 1
func initMap(sa []string) map[int]string {
    m := make(map[int]string, len(sa))
    for k, v := range sa {
        m[k+1] = v // add 1 to k as it is starting at base 0
    }
    return m
}

// main is the entry point of any go application
func main() {
    // My preferred approach is a composite literal in a short variable declaration
    keys := map[int]string{1: "aa", 2: "ab", 3: "ac", 4: "ba", 5: "bb", 6: "bc", 7: "ca", 8: "cb", 9: "cc"}
    fmt.Println(keys)

    // Using a function to initialize the map might help to avoid clutter
    keys2 := initMap([]string{"aa", "ab", "ac", "ba", "bb", "bc", "ca", "cb", "cc"})
    fmt.Println(keys2)
}

See it in action at https://play.golang.org/p/Rrb9ChBkXW


text:
Q: Animating a Border control's width I'm trying to animate a Border control's width in a Windows 8 Metro app. I've managed to animate other properties on the Border, such as Opacity:
private void Item_Tapped(object sender, RoutedEventArgs e)
{
    var border = sender as Border;

    var animation = new DoubleAnimation();
    animation.To = 0.0;
    animation.Duration = new Duration(TimeSpan.FromSeconds(1));

    var storyboard = new Storyboard();
    storyboard.Children.Add(animation);

    Storyboard.SetTarget(animation, border);
    Storyboard.SetTargetProperty(animation, "Opacity");

    storyboard.Begin();
}

But when I try to animate the width of the control:
private void Item_Tapped(object sender, RoutedEventArgs e)
{
    var border = sender as Border;

    var animation = new DoubleAnimation();
    animation.To = 600.0;
    animation.Duration = new Duration(TimeSpan.FromSeconds(1));

    var storyboard = new Storyboard();
    storyboard.Children.Add(animation);

    Storyboard.SetTarget(animation, border);
    Storyboard.SetTargetProperty(animation, "Width");

    storyboard.Begin();
}

Nothing happens.
I am able to do this in WPF, but not in Windows 8. Is this a limitation or bug of Metro, or am I doing something wrong?
Thanks

A: I was able to make it work by enabling EnableDependentAnimation
    public static async Task Width(FrameworkElement obj, double doubleValue, int milliseconds)
    {
        var animation= new DoubleAnimation
        {
            To = doubleValue,
            Duration = TimeSpan.FromMilliseconds(milliseconds),
            EnableDependentAnimation = true// <== here
        };

        Storyboard.SetTarget(animation, obj);
        Storyboard.SetTargetProperty(animation, "Width");

        var sb = new Storyboard();
        sb.Children.Add(animation);
        await sb.BeginAsync();
    }

Enjoy!

A: I'm not sure how you have it working in WPF.  According to http://msdn.microsoft.com/en-us/library/system.windows.media.animation.storyboard.targetproperty, the target property must be a dependency property.  According to http://msdn.microsoft.com/en-us/library/system.windows.controls.border, Width is not a dependency property.


text:
Q: Horizontal or Vertical stand for cooling a Macbook? I have a Macbook Pro (2010 model) that I like to connect an external monitor, keyboard, and mouse too. I like to keep the lid down, and have it running almost all the time, 24/7.
There are several laptop stands and cooling pads out there, most of which I've seen the laptop is placed horizontally on. But there are some that hold the Macbook vertically.
My question is: Which is better to help cool the Macbook, a vertical or horizontal stand? Is it negligible?
If it helps, say the Macbook is being used for something graphics intensive where it heats up quite a bit. My concern is that when the lid is down, and the heat can't escape as easily.

A: Bookarc looks great, but closing the lid means thermal problems. It's not meant to be used that way, and under full load, this probably will lead to noise and overheating. I was planning to buy a stand (since I use my MacBook Pro with external monitor and keyboard), but inadequate cooling stops me, however keeping it open all the time accumulates dust.
Here is my "Reverse V" method

*

*Connect all cables (video) and close the lid.

*Wake from external mouse/keyboard. This will force using only the external display.

*Open the lid to about 20-40 degrees. Internal display will remain off. The Macbook will be in a "V" like shape.

*Put it on the desktop in reversed "V" form on something soft. I recommend old polyurethane mouse pad or shaped polystyrene.

    /\\
   /  \\     - MacBook
  /    \\
===========  - mat/soft mousepad

Pros

*

*Perfect cooling. Warm air gets up, there are no obstructions to the vents and all parts are exposed to colder air.

*Cooler means less fan noise under load.

*Takes less space than fully opened notebook.

*Better bluetooth/wifi reception because lid is not fully closed (compared to fully closed one).

*Less dust accumulation.

Cons

*

*You cannot use your internal IR receiver.

*Some people will not be comfortable to run their HDDs from this position (10-20 degrees vertical inclination). I think it's perfectly safe.. and I have trustworthy backup system.

*If computer sleeps, you should do the steps from 2-4 again or the internal display will be on.

*Looks kinda strange compared to the great looking vertical stands available.

A: If you close the lid on your MacBook and have a look at the black section on the back of your device you will notice a small gap on the lower end.
This gap is designed as the primary heat exhaust in clamshell mode. This is where the fans (which are running all the time, even when you don't hear them) blow the air out of the device.
If you add the fact that hot air travels up, it is quite obvious that the optimal way to position your device is vertically.

A: According to this company, vertical is better.
I use horizontal myself. I need the screen estate and the speaker (and occasionally the keyboard/trackpad when my bluetooth peripherals are out of battery). I'd say it's almost negligible. Aluminum is very good in dissipating heat.

A: I think that in the absence of some kind of surprising physics formula, most of us would have roughly the same answer to that question. Namely, "to get your answer, you would not necessarily consider vertical versus horizontal, but simply look at the stands and see which one allows the most air to circulate, unblocked, around the macbook."
One could guess that a truly vertical stand would only be blocking one of the thin edges of the macbook, while a horizontal one would block part of a large flat surface. if so, there you go...
Note that I didn't even know you could keep the macbook running with the lid closed. I know that past mac laptops (that "killer whale" powerbook G3 I had so long ago) explicitly stated that the keyboard was one of the primary cooling elements, therefore there was no bypassing the automatic sleep-on-close.
I own the Rain Design mStand, which holds it mostly horizontal, though angled. therefore it blocks part of the bottom.  Anyway, the macbook is pretty darn cool, but I'm not doing your "close the lid while cranking the processor" plan. BUT, I'd just say, the mStand looks pretty darn cool both when the mac is open and closed.

A: Vertical exposes the most surface area and is best for convection moving the hot air away from the mac operating in clamshell mode.
In practice, a 5 or 10 degree tilt with a minimum of one inch clearance of air under the mac gets just as much airflow and cooling as vertical as long as the air temperature isn't too hot (<85 degrees).
On my four year old MacBook Pro - the internal temperatures and fan speeds are climbing and running it vertically rather than on a Griffin Elevator in clamshell mode. When my room temperature gets hot, vertical helps the fans stay at idle in clamshell mode.
Do make or buy something secure to hold your mac and know that having the lid closed does insulate half of the surface area very well. Glass and trapped air is a very good insulator.
And you can experiment with books or DIY and chart your mac's temperature using all sorts of programs. You can make the best noise, space, security, cost and temperature decision for your situation.
Also, 4 years and a few months down the road, we have custom cooling stands designed to help people with vertically oriented, cooling airflow for your MacBook operating in closed clamshell mode.

*

*http://www.svalt.com


text:
Q: Remove portion of text from a txt file I need to remove portion of text from a very big text file.
The text file is something like that:
Abcdefghijk
LOCK TABLES `core_log` WRITE; <----
(DATA - over 1 Gb of text data)
UNLOCK TABLES;  <----
lmnopqrstuvxyz

I need to create a script (Windows or Unix) that remove all content from "LOCK TABLES" to "UNLOCK TABLES;" and preserve rest of file. After the script will run I need to have
Abcdefghijk
lmnopqrstuvxyz

I can save the extracted data in another file or I can overwrite the same file.
Thanks for help.

A: This is best done with awk:
$ awk '/^LOCK TABLE/{f=1} /^UNLOCK TABLE/{f=0} f' file

A: With GNU sed:
sed -i '/^LOCK TABLES/,/^UNLOCK TABLES/d' file

Output to file:

Abcdefghijk
lmnopqrstuvxyz


text:
Q: sep=' ' is not working. what is the reason? In the print function, sep is not working as my output shows all the sequential numbers all together. But the desired output will be organized with a space among every number.
num=0
for row in range(10):
    for column in range(10):
        print (num,sep=' ', end="")
        num+=1
    print("\r")

my desired output should be:
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
.....................

every two numbers should have a space between them. But instead I am getting this:
0123456789
10111213141516171819
20212223242526272829

A: You use sep (which already has a default value of ' ' anyway) when you're printing all the numbers in a single print statement (print(1, 2, 3, ..., sep = '-')  =>  '1-2-3-...'), but since you're printing each on its own, you should utilize the end parameter instead (whose value is printed after all the arguments of the print function are printed):
num = 0
for row in range(10):
    for column in range(10):
        print(num, end = ' ')
        num += 1
    print('\r')

Output:
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
60 61 62 63 64 65 66 67 68 69
70 71 72 73 74 75 76 77 78 79
80 81 82 83 84 85 86 87 88 89
90 91 92 93 94 95 96 97 98 99


text:
Q: MS Access 2007 queries does't run on SQL Server 2008 I am developing an application in C# VS 2010 past 4 months. I used MS Access 2007 to store my nearly 20 tables successfully.
Today I realized that my data base cannot be handled consistently by MS Access 2007. Hence I decided to go for SQL Server 2008 R2 Express with Upsizing wizard and it worked really great!
However, when I tried to run various options of my already well developed application, It kept throwing error each time when a query is fired to SQL Server.
I understood that Many of the stuffs of SQL supported by MS Access are not supported by MS SQL Server
For example: query with date, for representing date format when we use '#', SQL Server 2008 won' t recognize it.
Also, for Bool value, MS Access stores it as True and False where as SQL Server uses 0.
These all queries worked perfect with Access 07
I am sure that there must be some method so that SQL Server can understand MS access queries.
Or will I have to edit my whole application?? It will be as good as digging a mine for earning gold..
I have changed all data access objects such as reader, adapter, command, connection to SQL data objects using System.Data.SqlClient.
So, It is not the problem.
Please help me asap.
Thank you.

A: You cannot force SQL Server to run the MS Access queries.  These queries will need to be rewritten to use T-SQL instead of the query language that MS Access uses.
I feel your pain, I just had to rewrite a large MS Access application (over 1k queries) that needed to be recreated to be used in SQL Server.
There will be some queries that might be able to be ported over directly but as you noticed queries with date, and even some of the aggregate functions (First(), etc) are not used in SQL Server and those queries will need to be changed.
Here is a link with some info on converting Access to SQL
Converting Access Queries to SQL Server

A: You are right that, most of the time, you cannot just take the SQL of a query from Access and run it within SQL Server. It may work for very simple queries, but usually you need to tweak them.
There are a few steps I would take:

*

*Extract your queries (which I presume are in your code), and re-create them in your Access database. Make sure they work there as normal Access queries.
(you can for instance simply add some code to your app to print all queries to files so you don't have to mess with parameters, then just copy/paste them in your Access DB).
The point is simply to have working queries within Access.

*Use SSMA from Microsoft for helping you to move your queries to SQL Server. It does a good job of translating them into T-SQL.
You may still have to convert some troublesome queries by hand, but it shouldn't be that many and usually the conversion is not difficult.

*Once converted to T-SQL, just re-inject these working queries into your code, or keep the complex queries in SQL Server as views (which it usually be faster as SQL Server will have already created its execution plan, rather than your application sending raw SQL that the server needs to analyse).

*As you pointed out, there could be some issues if your fields use some features that don't cross-over to SQL Server properly.
Look at your tables in Access and do some cleanup before attempting to convert:

*

*For booleans fields:
Make sure you set their default values to 0 or 1 (they should not be empty).

*Required fields must be non-null:
Make sure that any fields that you have set as 'Required' does not contain any NULL values in its data.

*Unique indexes cannot ignore Null:
Check that your indexes are not set to be both 'Unique' and 'Ignore null'.

*All tables must have clean primary keys:
Make sure all your tables have a unique primary key that doesn't have Null values in their data.


text:
Q: Counting Records In Swift From Firebase With A Where Statement I am trying to return the count of posts for a specific user where a field contains a certain value. The structure I am using in Firebase is here:
{
  "posts" : {
    "-Lyzpsb1hH4LUPvcXE3H" : {
      "beverageCategory" : "Beer",
      "beverageName" : "Dortmunder",
      "beveragePrice" : "3.99",
      "beverageRating" : 3,
      "beverageType" : "Lager",
      "imageUrl" : "https://firebasestorage.googleapis.com/v0/b/socialspirit-37cae.appspot.com/o/post-pics%2F3C23E923-A3BD-4393-B3EF-8F939D8B08B8?alt=media&token=ac80cb98-f2a1-4197-b328-2a69a2ac1fd1",
      "wineVintage" : ""
    }
  },
  "user" : "sdkjvksdjf",
  "users" : {
    "0hyN8N2klJWqPi2lkRqNK3vg7z63" : {
      "posts" : {
        "-Ly6ciYHm7v5JFy1VmVY" : true,
        "-Ly6cyLukI6aRRki5yna" : true
      },
      "provider" : "Firebase"
    },
    "26OUuaRZEVWUmkLJp13LzirGbs13" : {
      "posts" : {
        "-Ly6fGmQEMZz3c-azMnJ" : true
      },
      "provider" : "Firebase"
    },
    "5r6FulsvIRap7pLK5D3zV8qyPVv1" : {
      "provider" : "Firebase"
    },
    "gQpktBMh97hTqiysHBwvVLZl70y1" : {
      "posts" : {
        "-Lyzpsb1hH4LUPvcXE3H" : true,
        "-LyzqFgvmrBgdsgKSt_5" : true,
        "-Lz-fIMDal00ex3_viQo" : true,
        "-Lz-lXsSBqKlcf8hBext" : true,
        "-Lz2eNLfk1PFEVkEgmwa" : true,
        "-Lz2etF0UqFqLkdGOR13" : true,
        "-Lz2fGUi0qzJtniNr5LX" : true,
        "-Lz2gP5c47yHDO2g0ljr" : true,
        "-Lz2gdhfedZfTtzjP2ee" : true,
        "-Lz2gllC3caXgPf2VAPU" : true,
        "-Lz2hH8FbNmBEOLcHCJz" : true,
        "-Lz2jzkXuEZ3Cfe96eGW" : true,
        "-Lz3RvuW4fMXarhW7vLv" : true,
        "-Lz3S8YA0vgk4ZrjL_Kk" : true
      },
      "provider" : "Firebase"
    }
  }
}

I am using the following code to get the count of records that have a beverageCategory of "Beer".
DataService.ds.REF_USERS.child("\(uid)").child("posts").child("beverageCategory")
.queryOrderedByValue().queryEqual(toValue: "Beer")
.observe(DataEventType.value, with: { (snapshot)     in
    print("SNAP - \(snapshot.childrenCount)")
})

The childrenCount returns 0, however. Any idea what I'm doing wrong here? Thanks!
EDIT: I added the JSON for the data structure and I think I left an important detail out. The data structure actually has users that have posts and the associated postid that links back to posts. I think what I have to do is first find the user's posts and then of those posts get a total count for each category. I'm guessing that is slightly different than the methods I tried. Any ideas on that?
EDIT 2: So my issues is that users and posts are in different structures. I need to find all of the user's posts and iterate through them to see if what the beverageCategory is. I have done that with the following code. The issue with the code below is that the count is doubled when I add a post and then open the menu. But when I exit the menu and re-open the count is correct. Why is it double-counting?
func myFirebaseNetworkDataRequest(finished: @escaping () -> Void) {
    beerCountArray.removeAll()
    wineCountArray.removeAll()
    liquorCountArray.removeAll()

    print("BEER ARRAY \(beerCountArray.count)")

    guard let uid = Auth.auth().currentUser?.uid else {
        return
    }
    let newPost = DataService.ds.REF_USERS.child("\(uid)").child("posts")

    newPost.observe(.value, with: { (snapshot) in
         if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
             //print("SNAPSHOT - \(snapshot)")
             for snap in snapshot {
                 let postData = DataService.ds.REF_POSTS.child(snap.key)
                 //print("SNAP KEY - \(snap.key)")
                 let bevCat = DataService.ds.REF_POSTS.child(snap.key).child("beverageCategory")
                 //print("BEV CAT - \(bevCat)")
                 postData.observe(.value, with: { (snapshot) in
                     if let postDict = snapshot.value as? Dictionary<String, AnyObject> {
                         let key = snapshot.key
                         let post = Post(postKey: key, postData: postDict)
                         //print("POST DICT - \(String(describing: postDict["beverageCategory"]!))")
                        if postDict["beverageCategory"]! as! String == "Beer" {
                            self.beerCountArray.append(1)
                            //print("BEER ARRAY LOOP - \(self.beerCountArray)")
                         }
                        if postDict["beverageCategory"]! as! String == "Wine"{
                            self.wineCountArray.append(1)
                         }
                        if postDict["beverageCategory"]! as! String == "Liquor" {
                            self.liquorCountArray.append(1)
                        }
                         //self.posts.append(post)
                     }
                     finished()
                 })
             }
         }

     })

}

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

        beerCountArray.removeAll()
        wineCountArray.removeAll()
        liquorCountArray.removeAll()

        myFirebaseNetworkDataRequest {

            //print("BEER ARRAY - \(self.beerCountArray.count)")
            self.beerCount.text = String(self.beerCountArray.count)
            self.liquorCount.text = String(self.liquorCountArray.count)
            self.wineCount.text = String(self.wineCountArray.count)
        }
}

A: Your query is not correct. Since you're trying to filter on a child property of each node under posts, you should call queryOrdered(byChild:).
So:
DataService.ds.REF_USERS.child("posts")
  .queryOrdered(byChild: "beverageCategory")
  .queryEqual(toValue: "Beer")
  .observe(DataEventType.value, with: { (snapshot)     in
    print("SNAP - \(snapshot.childrenCount)")
  })

Also see the Firebase documentation on ordering and filtering data.


text:
Q: Problems to make webapp with maven Actually, i am making a webproject with maven in command line.
mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-webapp -DarchetypeVersion=1.0 -DgroupOd=ar.com -DartifactId=RETOP
then i write  mvn -Dwtpversion=2.0 eclipse:eclipse
1) in the project when I import I do not see the folder src / main / java why not?
2) the eclipse not take me M2_REPO variable (in another workspace it works) I have added the variable and the jar.
3) Description  Resource    Path    Location    Type
Java compiler level does not match the version of the installed Java project facet. PropiedadesArg      Unknown Faceted Project Problem (Java Version Mismatch)
thanks

A:
2) the eclipse not take me M2_REPO
  variable (in another workspace it
  works) I have added the variable and
  the jar.

For every workspace, you need to call mvn eclipse:configure-workspace once. This initializes the M2_REPO variable.

3) Description Resource Path Location
  Type Java compiler level does not
  match the version of the installed
  Java project facet. PropiedadesArg
  Unknown Faceted Project Problem (Java
  Version Mismatch)

The compiler level is taken from the pom configuration of the maven compiler plugin.
Example (for 1.6 compliance):
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
        <source>1.6</source>
        <target>1.6</target>
    </configuration>
</plugin>

But apart from that: mvn eclipse:eclipse shouldn't be used any more, m2eclipse is the way to go for Eclipse + Maven. It uses an embedded Maven installation to actually run the maven build (or parts of it) in Eclipse, whereas the Maven Eclipse Plugin just configures Eclipse from the outside. Here's a thread were the Maven founders discuss this topic.

Also:
mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes
-DarchetypeArtifactId=maven-archetype-webapp -DarchetypeVersion=1.0
-DgroupOd=ar.com -DartifactId=RETOP
  ^^^^^^^

here's a typo, it's groupId, not groupOd

Oh, now I get it. eclipse:eclipse uses the variable MAVEN_REPO, not M2_REPO (M2_REPO is created and maintained by m2eclipse). Anyway, in Eclipse, select Window > Preferences > Java > Build Path > Classpath Variables, add or edit the M2_REPO variable and set it to <path to your home directory>/.m2/repository, e.g. C://users/yournamehere/.m2/repository


text:
Q: using binding to center a circle Here is a program that attempt to center a circle using binding:
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

/**
 *
 * @author
 */
public class Test extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {

        Circle c = new Circle();
        Group root = new Group(c);
        Scene scene = new Scene(root, 100, 100);
        c.centerXProperty().bind(scene.widthProperty().divide(2));
        c.centerYProperty().bind(scene.heightProperty().divide(2));
        c.radiusProperty().bind(Bindings.min(scene.widthProperty(),
                scene.heightProperty())
                .divide(2));
        c.radiusProperty().addListener((obs, old, nw) -> {
            System.out.println(" oldRadius = "+old + ", newRadius = "+nw );
        });
        stage.setTitle("Binding in JavaFX");
        stage.setScene(scene);
        stage.sizeToScene();
        stage.show();

    }

}

Here is the screen when the program is initially run:

notice that the circumference of the circle touches only the top, left, and bottom sides not the right side.
Here is the screen when the screen for the program is maximized and then restored:

Here the circumference of the circle touches only the top and bottom sides.

*

*the screens shown above are normal?

*How do I explain this behavior for that program?