问:
Forcing input through validation check
We created a validation check so that input can only be alphabetical character. While it is working as intended, my friend and I both came across an odd symptom where you can force through the validation even though the code clearly (at least to us) would not allow them to.

Running the following code, then pressing [enter] or random junk about dozen time and entering unacceptable input such as 321- would cause the program to quit validation. Is it some kind of inherent limit or did we miss a code?

Even after stripping down the code to bare validation caused the symptom, though it did seems to have different limit depending on machine. Some computer let it sneak by after 3-4 brute forcing, while c9.io withstood roughly a dozen.

My validation loop does look messy, but I experienced before on smaller for loop as well. Only similarities I 've noticed so far is getline()

```<code>#include<iostream>
#include<string>
#include<fstream>

using namespace std;

//prototypes
void validateUserName(string &name);//validate name

//main function
int main()
{

    //initialize
    ifstream file;

    string username; //holds username which serve as file name

    //first prompt
    cout<< "Enter your name and press <ENTER>";
    getline(cin, username);

    //call functions
    validateUserName(username);
    //begin shutdown
    cout << "good-bye" << endl;
    cin.get();
}

void validateUserName(string &name){
    int errCount = 0;
    int i=0;
    do
    {
        errCount = 0;
        i=0;
        //go thru each character of the name to count non-alphabetic character
        while (name[i])
            {
            if ( !isalpha(name[i]) )
            errCount++;
            i++;
            }

        if (errCount > 0 || name.empty() )
        {
            //prompt user again alerting them of error
            cout << "Invalid entry, try again" << endl;
            getline(cin, name);
        }

    }
    while (errCount > 0 || name.empty() );//the validation loop doesn't end until user enters acceptable entry
    name+=".txt"; //appended file type
}
</code>```

答:
When you come out of your second cin name is no longer empty. So the second condition is not met and you exit the main while loop. A quick fix would be to increment errCount in the final conditional:

```<code>if (errCount > 0 || name.empty() )
{
   errCount++;
   cout << "Invalid entry, try again" << endl;
   getline(cin, name);
}
</code>```

While it was not part of your question I would suggest you use string::size() instead of checking for the null character. I don't think getline adds this, so you could possibly be dealing with undefined behavior.

```<code>void validateUserName(string &name)
{
    int errCount = 0;
    do
    {
        errCount = 0;
        //go thru each character of the name to count non-alphabetic character
        for (int i = 0; i < name.size() && !name.empty(); i++)
        {
            if ( !isalpha(name[i]) )
            {
                errCount++;
                break;
            }
        }

        if (errCount > 0 || name.empty() )
        {
            errCount++;
            //prompt user again alerting them of error
            cout << "Invalid entry, try again" << endl;
            getline(cin, name);
        }

     }
    while (errCount > 0 || name.empty() );//the validation loop doesn't end until user enters acceptable entry

}
</code>```

Title: Forcing input through validation check

Body:
We created a validation check so that input can only be alphabetical character. While it is working as intended, my friend and I both came across an odd symptom where you can force through the validation even though the code clearly (at least to us) would not allow them to.

Running the following code, then pressing [enter] or random junk about dozen time and entering unacceptable input such as 321- would cause the program to quit validation. Is it some kind of inherent limit or did we miss a code?

Even after stripping down the code to bare validation caused the symptom, though it did seems to have different limit depending on machine. Some computer let it sneak by after 3-4 brute forcing, while c9.io withstood roughly a dozen.

My validation loop does look messy, but I experienced before on smaller for loop as well. Only similarities I 've noticed so far is getline()

#include<iostream>
#include<string>
#include<fstream>

using namespace std;

//prototypes
void validateUserName(string &name);//validate name

//main function
int main()
{

    //initialize
    ifstream file;

    string username; //holds username which serve as file name

    //first prompt
    cout<< "Enter your name and press <ENTER>";
    getline(cin, username);

    //call functions
    validateUserName(username);
    //begin shutdown
    cout << "good-bye" << endl;
    cin.get();
}

void validateUserName(string &name){
    int errCount = 0;
    int i=0;
    do
    {
        errCount = 0;
        i=0;
        //go thru each character of the name to count non-alphabetic character
        while (name[i])
            {
            if ( !isalpha(name[i]) )
            errCount++;
            i++;
            }

        if (errCount > 0 || name.empty() )
        {
            //prompt user again alerting them of error
            cout << "Invalid entry, try again" << endl;
            getline(cin, name);
        }

    }
    while (errCount > 0 || name.empty() );//the validation loop doesn't end until user enters acceptable entry
    name+=".txt"; //appended file type
}

Body:
When you come out of your second cin name is no longer empty. So the second condition is not met and you exit the main while loop. A quick fix would be to increment errCount in the final conditional:

if (errCount > 0 || name.empty() )
{
   errCount++;
   cout << "Invalid entry, try again" << endl;
   getline(cin, name);
}

While it was not part of your question I would suggest you use string::size() instead of checking for the null character. I don't think getline adds this, so you could possibly be dealing with undefined behavior.

void validateUserName(string &name)
{
    int errCount = 0;
    do
    {
        errCount = 0;
        //go thru each character of the name to count non-alphabetic character
        for (int i = 0; i < name.size() && !name.empty(); i++)
        {
            if ( !isalpha(name[i]) )
            {
                errCount++;
                break;
            }
        }

        if (errCount > 0 || name.empty() )
        {
            errCount++;
            //prompt user again alerting them of error
            cout << "Invalid entry, try again" << endl;
            getline(cin, name);
        }

     }
    while (errCount > 0 || name.empty() );//the validation loop doesn't end until user enters acceptable entry

}


来源: stackexchange

问:
git pull and push specific files without the repository saved locally
I have a couple questions but I'll put them together given they look quite similar.

Let's say I have a repository called Repo, and it contains two folders, A and B.

Via terminal (and given I don't have the project in my machine), how can I...

(1) ...clone only folder A from Repo to my machine?

(2) ...send a file/folder C to Repo?

答:
To clone

If you are using git bash
git clone [url]

Example:
https://github.com/mycode

To commit and push

git init

git add [filename]

git commit -m "First commit"

git remote add origin remote repository URL

git push origin master

(This creates a local clone which you can delete later)

Reference

How to add an existing project

How to clone repository

ContentLicense: CC BY-SA 3.0


问:
Calculating the height of a binary tree
I need help with the theory on calculating the height of a binary tree, typically the notation.

I have read the following article:

Calculating height of a binary tree

And one of the posts gives the following notation:

height(node) = max(height(node.L), height(node.R)) + 1

Let's assume I have the following binary tree:

```<code>     10
   /   \
  5    30
 / \   /  \
4  8  28  42
</code>```

Do I therefore calculate the max value on the left node (8) and the max node on the right (42) and then add 1? I don't quite understand how this notation works in order to calculate the height of the tree.

答:
```<code>#include<stdio.h>
#include<stdlib.h>

/* A binary tree node has data, pointer to left child
   and a pointer to right child */
struct node
{
    int data;
    struct node* left;
    struct node* right;
};

/* Compute the "maxDepth" of a tree -- the number of
    nodes along the longest path from the root node
    down to the farthest leaf node.*/
int maxDepth(struct node* node)
{
   if (node==NULL)
       return 0;
   else
   {
       /* compute the depth of each subtree */
       int lDepth = maxDepth(node->left);
       int rDepth = maxDepth(node->right);

       /* use the larger one */
       if (lDepth > rDepth)
           return(lDepth+1);
       else return(rDepth+1);
   }
}

/* Helper function that allocates a new node with the
   given data and NULL left and right pointers. */
struct node* newNode(int data)
{
    struct node* node = (struct node*)
                                malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;

    return(node);
}

int main()
{
    struct node *root = newNode(1);

    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);

    printf("Hight of tree is %d", maxDepth(root));

    getchar();
    return 0;
}
</code>```

Title: Calculating the height of a binary tree

Body:
I need help with the theory on calculating the height of a binary tree, typically the notation.

I have read the following article:

Calculating height of a binary tree

And one of the posts gives the following notation:

height(node) = max(height(node.L), height(node.R)) + 1

Let's assume I have the following binary tree:

     10
   /   \
  5    30
 / \   /  \
4  8  28  42

Do I therefore calculate the max value on the left node (8) and the max node on the right (42) and then add 1? I don't quite understand how this notation works in order to calculate the height of the tree.


问:
How do i start runing a file system mini filter
I'm new to mini filter programming , i compiled the Windows swapBuffers mini filter example (with a bit extra dbgprinting) and tried to run it on windows xp and windows 7.

i tried to use th install option of the inf file and nothing happend (i checked with dbgView - ther is no printing and with fltmc.exe - there is no new mini filtering).

i tried use fltmc.exe load option , i got load failed with error: 0x80070002 The system cannot find the file specified (even thet i in the minifilter folder and double checked the path and the spelling).

i tried to use sc create my_filter type= filesys binPath=... and when i tried sc start my_filter i got a blue screen (got the same results when trying to load with OSR louder).

can sombody please help me to start runing my first "hello world" minifilter?

thank you
pit

答: Please do check file path info in inf file. For your initial error.</p>


问:
query from two tables CAST
I have a query from two tables ...

The first table in which the goods are in the form of tree accounts ....

The second table in which the sale is linked to the first table.

For example, now I have the first table.

Question A sort query is required ..

I get the cars for their condition ... electronics for their condition

Of Table II.

With attachments, I want to create a query.

Database Script :

```<code>USE [To_Test]
GO
/****** Object:  Table [dbo].[Items]    Script Date: 11/10/1438 05:54:35 م ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Items](
    [Id_ItemS] [int] NOT NULL,
    [Name_ar] [nvarchar](50) NULL,
    [Number_Id] [int] NULL,
    [Basic] [bit] NULL,
 CONSTRAINT [PK_Items] PRIMARY KEY CLUSTERED
(
    [Id_ItemS] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Sell_items](
    [Id_Sell] [int] IDENTITY(1,1) NOT NULL,
    [Id_items] [int] NULL,
    [price] [money] NULL,
 CONSTRAINT [PK_Sell_items] PRIMARY KEY CLUSTERED
(
    [Id_Sell] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (1, N'Cars', NULL, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (2, N'electronics', NULL, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (3, N'Toyota', 1, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (4, N'Nissan', 1, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (5, N'Camry', 3, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (6, N'2015', 5, 0)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (7, N'2016', 5, 0)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (8, N'2017', 5, 0)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (9, N'TV', 2, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (10, N'LG', 9, 0)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (11, N'Samsung', 9, 0)
SET IDENTITY_INSERT [dbo].[Sell_items] ON

INSERT [dbo].[Sell_items] ([Id_Sell], [Id_items], [price]) VALUES (1, 11, 2500.0000)
INSERT [dbo].[Sell_items] ([Id_Sell], [Id_items], [price]) VALUES (2, 10, 2300.0000)
INSERT [dbo].[Sell_items] ([Id_Sell], [Id_items], [price]) VALUES (3, 6, 20000.0000)
INSERT [dbo].[Sell_items] ([Id_Sell], [Id_items], [price]) VALUES (4, 7, 270000.0000)
SET IDENTITY_INSERT [dbo].[Sell_items] OFF
ALTER TABLE [dbo].[Items]  WITH CHECK ADD  CONSTRAINT [FK_Items_Items1] FOREIGN KEY([Number_Id])
REFERENCES [dbo].[Items] ([Id_ItemS])
GO
ALTER TABLE [dbo].[Items] CHECK CONSTRAINT [FK_Items_Items1]
GO
ALTER TABLE [dbo].[Sell_items]  WITH CHECK ADD  CONSTRAINT [FK_Sell_items_Items] FOREIGN KEY([Id_items])
REFERENCES [dbo].[Items] ([Id_ItemS])
GO
ALTER TABLE [dbo].[Sell_items] CHECK CONSTRAINT [FK_Sell_items_Items]
GO
</code>```

view

```<code>WITH Recursive_CTE AS (
SELECT        Items.Id_ItemS, Items.Name_ar, Items.Number_Id, 1 AS RecursionLevel, CAST(Items.Id_ItemS AS varchar(100)) AS Hierarchy, Sell_items.Id_Sell
FROM            Items INNER JOIN
                         Sell_items ON Items.Id_ItemS = Sell_items.Id_items
WHERE        (Items.Id_ItemS = 1)
 UNION ALL
SELECT        Items.Id_ItemS, Items.Name_ar, Items.Number_Id, 1 AS RecursionLevel, CAST(Hierarchy + ':' + CAST(Items.Id_ItemS AS varchar(100)) AS varchar(100)) AS Hierarchy, Sell_items.Id_Sell
FROM            Recursive_CTE AS parent INNER JOIN
                         Items ON parent.Id_items = Items.Number_Id INNER JOIN
                         Sell_items ON Items.Id_ItemS = Sell_items.Id_items )
SELECT * FROM Recursive_CTE ORDER BY Hierarchy
</code>```

but The result is null

I wish to modify the query ?

The desired result
enter image description here

答:
I see it as data issue. You don't have any records which satisfy your query.

I don't see any items.Id_ItemS = 1 after Inner join on two tables - Items, Sell_items

```<code>  SELECT
       Items.Id_ItemS,
       Items.Name_ar,
       Items.Number_Id,
       1 AS RecursionLevel,
       CAST(Items.Id_ItemS AS varchar(100)) AS Hierarchy,
       Sell_items.Id_Sell
  FROM  Items INNER JOIN Sell_items ON Items.Id_ItemS = Sell_items.Id_items
       WHERE (Items.Id_ItemS = 1)
</code>```

If you remove the where conditions (Items.Id_ItemS = 1) you will get results.

Hope this helps you!

Title: query from two tables CAST

Body:
I have a query from two tables ...

The first table in which the goods are in the form of tree accounts ....

The second table in which the sale is linked to the first table.

For example, now I have the first table.

Question A sort query is required ..

I get the cars for their condition ... electronics for their condition

Of Table II.

With attachments, I want to create a query.

Database Script :

USE [To_Test]
GO
/****** Object:  Table [dbo].[Items]    Script Date: 11/10/1438 05:54:35 م ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Items](
    [Id_ItemS] [int] NOT NULL,
    [Name_ar] [nvarchar](50) NULL,
    [Number_Id] [int] NULL,
    [Basic] [bit] NULL,
 CONSTRAINT [PK_Items] PRIMARY KEY CLUSTERED
(
    [Id_ItemS] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Sell_items](
    [Id_Sell] [int] IDENTITY(1,1) NOT NULL,
    [Id_items] [int] NULL,
    [price] [money] NULL,
 CONSTRAINT [PK_Sell_items] PRIMARY KEY CLUSTERED
(
    [Id_Sell] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (1, N'Cars', NULL, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (2, N'electronics', NULL, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (3, N'Toyota', 1, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (4, N'Nissan', 1, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (5, N'Camry', 3, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (6, N'2015', 5, 0)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (7, N'2016', 5, 0)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (8, N'2017', 5, 0)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (9, N'TV', 2, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (10, N'LG', 9, 0)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (11, N'Samsung', 9, 0)
SET IDENTITY_INSERT [dbo].[Sell_items] ON

INSERT [dbo].[Sell_items] ([Id_Sell], [Id_items], [price]) VALUES (1, 11, 2500.0000)
INSERT [dbo].[Sell_items] ([Id_Sell], [Id_items], [price]) VALUES (2, 10, 2300.0000)
INSERT [dbo].[Sell_items] ([Id_Sell], [Id_items], [price]) VALUES (3, 6, 20000.0000)
INSERT [dbo].[Sell_items] ([Id_Sell], [Id_items], [price]) VALUES (4, 7, 270000.0000)
SET IDENTITY_INSERT [dbo].[Sell_items] OFF
ALTER TABLE [dbo].[Items]  WITH CHECK ADD  CONSTRAINT [FK_Items_Items1] FOREIGN KEY([Number_Id])
REFERENCES [dbo].[Items] ([Id_ItemS])
GO
ALTER TABLE [dbo].[Items] CHECK CONSTRAINT [FK_Items_Items1]
GO
ALTER TABLE [dbo].[Sell_items]  WITH CHECK ADD  CONSTRAINT [FK_Sell_items_Items] FOREIGN KEY([Id_items])
REFERENCES [dbo].[Items] ([Id_ItemS])
GO
ALTER TABLE [dbo].[Sell_items] CHECK CONSTRAINT [FK_Sell_items_Items]
GO

view

WITH Recursive_CTE AS (
SELECT        Items.Id_ItemS, Items.Name_ar, Items.Number_Id, 1 AS RecursionLevel, CAST(Items.Id_ItemS AS varchar(100)) AS Hierarchy, Sell_items.Id_Sell
FROM            Items INNER JOIN
                         Sell_items ON Items.Id_ItemS = Sell_items.Id_items
WHERE        (Items.Id_ItemS = 1)
 UNION ALL
SELECT        Items.Id_ItemS, Items.Name_ar, Items.Number_Id, 1 AS RecursionLevel, CAST(Hierarchy + ':' + CAST(Items.Id_ItemS AS varchar(100)) AS varchar(100)) AS Hierarchy, Sell_items.Id_Sell
FROM            Recursive_CTE AS parent INNER JOIN
                         Items ON parent.Id_items = Items.Number_Id INNER JOIN
                         Sell_items ON Items.Id_ItemS = Sell_items.Id_items )
SELECT * FROM Recursive_CTE ORDER BY Hierarchy

but The result is null

I wish to modify the query ?

The desired result
enter image description here

Body:
I see it as data issue. You don't have any records which satisfy your query.

I don't see any items.Id_ItemS = 1 after Inner join on two tables - Items, Sell_items

  SELECT
       Items.Id_ItemS,
       Items.Name_ar,
       Items.Number_Id,
       1 AS RecursionLevel,
       CAST(Items.Id_ItemS AS varchar(100)) AS Hierarchy,
       Sell_items.Id_Sell
  FROM  Items INNER JOIN Sell_items ON Items.Id_ItemS = Sell_items.Id_items
       WHERE (Items.Id_ItemS = 1)

If you remove the where conditions (Items.Id_ItemS = 1) you will get results.

Hope this helps you!


问:
Cannot link streams code with gcc
I have a problem compiling the following code:

```<code>// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile ("example.txt");
  if (myfile.is_open())
  {
    myfile << "This is a line.\n";
    myfile << "This is another line.\n";
    myfile.close();
  }
  else cout << "Unable to open file";
  return 0;
}
</code>```

To compile:

```<code>g++ -c -O2 -Wall -Wno-unused -fexceptions  -I. -I../../../stub -D_REENTRANT -D_THREAD_SAFE  -I.  -o t.o ./test.cc

g++ -o t -O2 -Wall -Wno-unused -fexceptions -Wl,-brtl -Wl,-blibpath:/lib:/usr/lib t.o -lpthreads
</code>```

The compile gives some warnings:

```<code>ld: 0711-224 WARNING: Duplicate symbol: .__divdi3
ld: 0711-224 WARNING: Duplicate symbol: .__moddi3
ld: 0711-224 WARNING: Duplicate symbol: .__udivdi3
ld: 0711-224 WARNING: Duplicate symbol: .__umoddi3
ld: 0711-224 WARNING: Duplicate symbol: .__udivmoddi4
ld: 0711-345 Use the -bloadmap or -bnoquiet option to obtain more information.
</code>```

The resulting binary appears to execute OK:

```<code>$ ./t
$ echo $?
0
</code>```

The output file is created but empty !?!

I would be VERY grateful for any pointers as to what the problem might be.

答:
Libpath was set incorrectly, causing the problem. The correct setting should be

LIBPATH=/opt/freeware/lib/gcc/powerpc-ibm-aix6.1.0.0/4.2.0/

ContentLicense: CC BY-SA 2.5

Title: Cannot link streams code with gcc

Body:
I have a problem compiling the following code:

// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile ("example.txt");
  if (myfile.is_open())
  {
    myfile << "This is a line.\n";
    myfile << "This is another line.\n";
    myfile.close();
  }
  else cout << "Unable to open file";
  return 0;
}

To compile:

g++ -c -O2 -Wall -Wno-unused -fexceptions  -I. -I../../../stub -D_REENTRANT -D_THREAD_SAFE  -I.  -o t.o ./test.cc

g++ -o t -O2 -Wall -Wno-unused -fexceptions -Wl,-brtl -Wl,-blibpath:/lib:/usr/lib t.o -lpthreads

The compile gives some warnings:

ld: 0711-224 WARNING: Duplicate symbol: .__divdi3
ld: 0711-224 WARNING: Duplicate symbol: .__moddi3
ld: 0711-224 WARNING: Duplicate symbol: .__udivdi3
ld: 0711-224 WARNING: Duplicate symbol: .__umoddi3
ld: 0711-224 WARNING: Duplicate symbol: .__udivmoddi4
ld: 0711-345 Use the -bloadmap or -bnoquiet option to obtain more information.

The resulting binary appears to execute OK:

$ ./t
$ echo $?
0

The output file is created but empty !?!

I would be VERY grateful for any pointers as to what the problem might be.


问:
ChangeEffectiveUser API (for user impersonation in SSAS) missing from AdomdConnection Class in ADOMD.Net
I've been trying to check the access of a user on a SQL Server Analysis Services (SSAS) server using impersonation.

AdomdConnection class has following instance method to accomplish the same:

```<code>public void ChangeEffectiveUser(string effectiveUserName)
</code>```

Here is the MSDN documentation for the same.

I followed the NuGet package instructions here to add ADOMD.Net in my C# project but when I try to use the API then I don't see the API in intellisense at all.

```<code>try
{
    Console.WriteLine("Going to open ADOMD connection.");
    myconnect.Open();
    //below line doesn't compile
    myconnect.ChangeEffectiveUser(@"mydomainname\otherUserIamTryingToImpersonate");
    adomdCommand.ExecuteNonQuery();
    Console.WriteLine("Query executed successfully");
    Console.ReadLine();
}
catch (Exception ex)
{

    MessageBox.Show("error in connection");
}
</code>```

It is giving compilation failure:

Error CS1061  'AdomdConnection' does not contain a definition for
  'ChangeEffectiveUser' and no extension method 'ChangeEffectiveUser'
  accepting a first argument of type 'AdomdConnection' could be found
  (are you missing a using directive or an assembly reference?)

Am I missing something?

答:
I was able to figure out that MS has changed the NuGet package for the latest ADOMD.Net release which came as part of SQL Server 2016. It is available on NuGet package here in the name of Unofficial.Microsoft.AnalysisServices.AdomdClient. Not sure why MS has taken this strategy to introduce a new package instead when they should have simply added a new version in the already existing NuGet package here in the name of Microsoft.AnalysisServices.AdomdClient.

The moment I took reference of v13.x of Microsoft.AnalysisServices.AdomdClient.dll present in Unofficial.Microsoft.AnalysisServices.AdomdClient NuGet package my compilation error went away and I could see the API.

Body:
I've been trying to check the access of a user on a SQL Server Analysis Services (SSAS) server using impersonation.

AdomdConnection class has following instance method to accomplish the same:

public void ChangeEffectiveUser(string effectiveUserName)

Here is the MSDN documentation for the same.

I followed the NuGet package instructions here to add ADOMD.Net in my C# project but when I try to use the API then I don't see the API in intellisense at all.

try
{
    Console.WriteLine("Going to open ADOMD connection.");
    myconnect.Open();
    //below line doesn't compile
    myconnect.ChangeEffectiveUser(@"mydomainname\otherUserIamTryingToImpersonate");
    adomdCommand.ExecuteNonQuery();
    Console.WriteLine("Query executed successfully");
    Console.ReadLine();
}
catch (Exception ex)
{

    MessageBox.Show("error in connection");
}

It is giving compilation failure:

Error CS1061  'AdomdConnection' does not contain a definition for
  'ChangeEffectiveUser' and no extension method 'ChangeEffectiveUser'
  accepting a first argument of type 'AdomdConnection' could be found
  (are you missing a using directive or an assembly reference?)

Am I missing something?


问:
Package for testing models on unseen data
I am wondering what packages are out there that can split my data.

I would prefer to optimize my model on 2/3rds of the data.
Then run it over the last 1/3rd to see how well it holds up.

Also this might sound like a stupid question... but in order to forward run the optimized model over the last 1/3/rd of data, is there a way to do that? Otherwise I am backtesting again right? Idea is to forward test it over the last 1/3rd of data much like it would be seeing real live data.... if im making sense.

Is there a R package out there that can do this?

**Apprecaite the answers.

It would seem in this case that its a relativley simple task with the following steps:

Optimize the model to the first 2/3rds of the data.

Test those parameters on the last 1/3rd of the data.

This is in contrast to testing and optimizing a model over the entire sample size. This way the model gets to see unseen data.

答:
There are a few packages out that can help with this.  The caTools package has a function called sample.split specifically for splitting a dataset into testing and training sets.

See: sample.split documentation

You pass in a column in your dataset as the first argument (typically the response variable) and it splits the dataset proportionally among the values in that variable.  That's helpful in case you have a response variable that maybe only comes up some value 5% of the time, you would like your training and testing set to both have a similar representation of that value in each.  It can be used like:

```<code>split = sample.split(wikiWords$Vandal, SplitRatio = 2/3)
wikitrain = subset(wikiWords, split == TRUE)
wikitest = subset(wikiWords, split == FALSE)
</code>```

Body:
There are a few packages out that can help with this.  The caTools package has a function called sample.split specifically for splitting a dataset into testing and training sets.

See: sample.split documentation

You pass in a column in your dataset as the first argument (typically the response variable) and it splits the dataset proportionally among the values in that variable.  That's helpful in case you have a response variable that maybe only comes up some value 5% of the time, you would like your training and testing set to both have a similar representation of that value in each.  It can be used like:

split = sample.split(wikiWords$Vandal, SplitRatio = 2/3)
wikitrain = subset(wikiWords, split == TRUE)
wikitest = subset(wikiWords, split == FALSE)


问:
Trying to include both a select statement and user input in an insert statement
So I'm trying to create a small-scale payroll system as practice, utilizing WPF as an interface and connecting to a SQL Server database. I'm setting up the stored procedures, and I'm trying to arrange one to add a new work shift to the database. It takes user input for the employee's first and last name, then inserts a new shift, inputting the manually entered details, along with inserting an employee ID from the tblEmployee table where the employee's first and last name are the same as the user-input first and last name. Problem is that it's giving me an incorrect syntax error for the last line, and I can't seem to figure out why. </p>

```<code>CREATE PROCEDURE NewShift(
@LName varchar(50),
@FName varchar(50),
@Date date,
@ShiftStart time,
@ShiftEnd time,
@HoursWorked decimal(18,2)
)
AS
BEGIN

INSERT INTO tblShifts(
EmpID,
Date,
ShiftStart,
ShiftEnd,
HoursWorked
)

SELECT EmpID, @Date, @ShiftStart, @ShiftEnd, @HoursWorked
FROM tblEmployee WHERE LName=@LName AND FName=@FName
</code>```

答:
DATE is a keyword word and probably reserved (depends on the version and reserved by ODBC), so it is a lousy name for a column:

```<code>INSERT INTO tblShifts(EmpID, [Date], ShiftStart, ShiftEnd, HoursWorked)
    SELECT EmpID, @Date, @ShiftStart, @ShiftEnd, @HoursWorked
    FROM tblEmployee
    WHERE LName = @LName AND FName = @FName;
</code>```

Of course, you also need the END for the end of the stored procedure.

Body:
So I'm trying to create a small-scale payroll system as practice, utilizing WPF as an interface and connecting to a SQL Server database. I'm setting up the stored procedures, and I'm trying to arrange one to add a new work shift to the database. It takes user input for the employee's first and last name, then inserts a new shift, inputting the manually entered details, along with inserting an employee ID from the tblEmployee table where the employee's first and last name are the same as the user-input first and last name. Problem is that it's giving me an incorrect syntax error for the last line, and I can't seem to figure out why.

CREATE PROCEDURE NewShift(
@LName varchar(50),
@FName varchar(50),
@Date date,
@ShiftStart time,
@ShiftEnd time,
@HoursWorked decimal(18,2)
)
AS
BEGIN

INSERT INTO tblShifts(
EmpID,
Date,
ShiftStart,
ShiftEnd,
HoursWorked
)

SELECT EmpID, @Date, @ShiftStart, @ShiftEnd, @HoursWorked
FROM tblEmployee WHERE LName=@LName AND FName=@FName

Body:
DATE is a keyword word and probably reserved (depends on the version and reserved by ODBC), so it is a lousy name for a column:

INSERT INTO tblShifts(EmpID, [Date], ShiftStart, ShiftEnd, HoursWorked)
    SELECT EmpID, @Date, @ShiftStart, @ShiftEnd, @HoursWorked
    FROM tblEmployee
    WHERE LName = @LName AND FName = @FName;

Of course, you also need the END for the end of the stored procedure.


问:
denied: requested access to the resource is denied: docker
I am following this link to create my first docker Image and it went successfully and now I am trying to push this Image into my docker repository from this link. But whenever I am trying to push this Image into repository, I  got this type of error.

```<code>denied: requested access to the resource is denied
</code>```

Note: I have successfully login into docker

答:
I had the same issue, but accepted answer given here did not work for me.
I tried few steps and was able to get around to push it finally.

Here are the steps worked for me:

Login to the docker.

docker login -u sirimalla

Tag your image build

my image name here is mylocalimage and by default it has tag latest

and my username is sirimalla as registered with docker cloud, and I created a public repository named dockerhub

so my personal repository becomes now sirimalla/dockerhub
and I want to push my image with tag myfirstimagepush.

I tagged as below :

```<code>docker tag mylocalimage:latest sirimalla/dockerhub:myfirstimagepush
</code>```

Pushed the image to my personal docker repository as below

docker push sirimalla/dockerhub:myfirstimagepush

And it successfully pushed to my personal docker repo.

ContentLicense: CC BY-SA 4.0

Body:
I am following this link to create my first docker Image and it went successfully and now I am trying to push this Image into my docker repository from this link. But whenever I am trying to push this Image into repository, I  got this type of error.

denied: requested access to the resource is denied

Note: I have successfully login into docker

Body:
I had the same issue, but accepted answer given here did not work for me.
I tried few steps and was able to get around to push it finally.

Here are the steps worked for me:

Login to the docker.

docker login -u sirimalla

Tag your image build

my image name here is mylocalimage and by default it has tag latest

and my username is sirimalla as registered with docker cloud, and I created a public repository named dockerhub

so my personal repository becomes now sirimalla/dockerhub
and I want to push my image with tag myfirstimagepush.

I tagged as below :

docker tag mylocalimage:latest sirimalla/dockerhub:myfirstimagepush

Pushed the image to my personal docker repository as below

docker push sirimalla/dockerhub:myfirstimagepush

And it successfully pushed to my personal docker repo.


问:
How to use the Meego touch theme
I'm new to QT and Meego. I would like to know how to make use of Meego touch theme. I have already cloned the source for it from  git://gitorious.org/meego-handset-ux/meegotouch-theme-meego.git . </p>

<p>I don't see anything helpful though on how to use it.
Can somebody give me a jumpstart or at least tell me how to make use of it? </p>

答:
The MeeGo themes are used by the MeeGoTouch library (which is built on-top of the QGraphicsView/Scene framework), see at http://meego.gitorious.org/meegotouch/libmeegotouch

The latest API docs for the whole stuff are at:
http://apidocs.meego.com/git-tip/mtf/

Styling specifics e.g. at http://apidocs.meego.com/git-tip/mtf/styling.html

Title: How to use the Meego touch theme

Body:
I'm new to QT and Meego. I would like to know how to make use of Meego touch theme. I have already cloned the source for it from  git://gitorious.org/meego-handset-ux/meegotouch-theme-meego.git .

I don't see anything helpful though on how to use it.
Can somebody give me a jumpstart or at least tell me how to make use of it?


问:
How can I read in a file with multiple x, y coordinates pairs and display as scatter points in Python 3
I have a file consist of multiple x,y coordinates pairs/columns :

614749.4    471134.6    614682.35   470996.6

614755.6    471134.1    614685.45   470996.4

614761.8    471133.5    614688.55   470996.1

614768.1    471133      614691.7    470995.85

.......

614767.6    471058.1    614691.45   470958.4

614773.8    471057.6    614694.55   470958.15

614780      471057.1    614697.65   470957.9

614786.2    471056.6    614700.75   470957.65

I would like to use Python to read in the file and display it like what excel can do:

The file could be very big with million of x,y pairs. Excel is too slow to read and display the scatter points. I have numpy and matplotlib package installed. I have trouble to

答:
Last year I had to deal with lots of data and fit it too. So I had written a simple code to do all that. Hope it helps you in some way. You can contact me if needed.

UNDERFed This is the link for the code.

It takes up all the files in a given directory and process the data file by file plots it and fits it with your given function if required and at the end, results are stored in a text file.

you can write something yourself using numpy and matplotlib libraries. you need to use numpy genfromtxt to get the data into a multi-dimensional array and then plot it using matplotlib.


问:
How to get the token attributes in Antlr-4 lexer rule's action
I am new to Antlr-4, but have some idea about Antlr-3, where the lexer could be created without the need of any parser rule; in order to match a lexer rule by matching some tokens like:

```<code>CLASS: 'Class' WS+ id=ID
{
System.out.println($id.text);
}
ID : [a-z]+ ;
WS : [ \r\t\n]+
</code>```

How could I do this in Antlr-4 without any parser, since the Antlr-4 lexer does not allow using attributes in the rule's action?

Any idea/example will be helpful for me!

答: According to the ANTLR4 grammar you can certainly use a label in a lexer rule. Just create your standalone lexer grammar and feed that to ANTLR to have it generate your lexer class.</p>

Body:
I am new to Antlr-4, but have some idea about Antlr-3, where the lexer could be created without the need of any parser rule; in order to match a lexer rule by matching some tokens like:

CLASS: 'Class' WS+ id=ID
{
System.out.println($id.text);
}
ID : [a-z]+ ;
WS : [ \r\t\n]+

How could I do this in Antlr-4 without any parser, since the Antlr-4 lexer does not allow using attributes in the rule's action?

Any idea/example will be helpful for me!


问:
Recent methods for finding semantic similarity between two short sentences or articles (on a concept level)
I'm working on finding similarities between short sentences and articles. I used many existing methods such as tf-idf, word2vec etc but the results are just okay. The most relevant measure which I found was word moving distance, however, its results are not that better than the other measures. I know it's a challenging problem, however, I am wondering if there are any new methods to find an approximate similarity more on a higher or concept level than just matching words.  Especially, any alternative new methods like word moving distance which looks at slightly higher semantic of a sentence or article?</p>

答:
This is the most recent basing on a paper published 4 months ago.

Step 1:

Load the suitable model using gensim and calculate the word vectors for words in the sentence and store them as a word list

Step 2 : Computing the sentence vector

The calculation of semantic similarity between sentences was difficult before but recently a paper named "A SIMPLE BUT TOUGH-TO-BEAT BASELINE FOR SENTENCE EMBEDDINGS" was proposed which suggests a simple approach by computing the weighted average of word vectors in the sentence and then remove the projections of the average vectors on their first principal component.Here the weight of a word w is a/(a + p(w)) with a being a parameter and p(w) the (estimated) word frequency called smooth inverse frequency.this method performing significantly better.

A simple code to calculate the sentence vector using SIF(smooth inverse frequency) the method proposed in the paper has been given here

Step 3: using sklearn cosine_similarity load two vectors for the sentences and compute the similarity.

This is the most simple and efficient method to compute the semantic similarity of sentences.


问:
In Angular 4, Firebase Authentication, Login with Google causes email login to stop working until I refresh
I'm using AngularFire2 authentication. We can log in with email/pass (email has been verified) or log in with Google. If I log in with email everything is fine. I log out, I log in, back and forth no issues. Then I sign in with Google, and log out and also no issues. BUT, if I log in with Google, then log out, I CAN'T log in with email unless I refresh the page! Even tho I'm totally logged out I get "auth/invalid-email" every time I try logging in after logging in with Google and logging out. If I refresh the page I can log in again with email without having any issues. Anyone know what this behavior is?</p>

答:
It is related to this issue: Firebase Overwrites Signin with Google Account

In this particular case, this happens for a security reason.
Here is a common scenario. I sign up an email/password account with your gmail address. The account is unverified (emailVerified is false). You then try to sign in with your Google account using the same email which is a verified Google email. If the password I setup still exists, then I can basically sign-in into your account. To protect against this, Firebase Auth will unlink all providers that are unverified.

You can only keep the old password provider if you verify the account by sending an email verification and completing the verification flow before the Google sign-in.


问:
J string manipulation using only builtins
You are given a string like ))()(())(, and you wish to remove all instances of () from the string, which in this case means these two instances:

```<code>))()(())(
  ^^ ^^
</code>```

leaving only ))()(.

I know you can use the library function stringreplace, or you could load up a regex library, but I want to know is if there is a concise way of accomplishing this the the J builtin operators exclusively?

I should clarify that my own solution was:

```<code>#~(-.@+._1&|.)@('()'&E.)
</code>```

which I consider verbose -- so any similar solutions would not qualify as "concise" in my book.  I'm really asking if there is a way to use a builtin (or maybe a simple combination of 2) to solve this directly.  I expect this answer is no.

答:
I think you are right that there is no ultra-concise way of expressing the operation you want to perform using just J primitives. The version I came up was very much like the one Dan, suggested above.
However given that a built in library verb rplc (based on stringreplace) performs exactly the operation you are after, I'm not sure why it would be better to replace it with a primitive.

```<code>   '))()(())(' rplc '()';''
))()(
</code>```

Having said that, if you can come up with a compelling case, then there is probably no reason it couldn't be added.

Body:
You are given a string like ))()(())(, and you wish to remove all instances of () from the string, which in this case means these two instances:

))()(())(
  ^^ ^^

leaving only ))()(.

I know you can use the library function stringreplace, or you could load up a regex library, but I want to know is if there is a concise way of accomplishing this the the J builtin operators exclusively?

I should clarify that my own solution was:

#~(-.@+._1&|.)@('()'&E.)

which I consider verbose -- so any similar solutions would not qualify as "concise" in my book.  I'm really asking if there is a way to use a builtin (or maybe a simple combination of 2) to solve this directly.  I expect this answer is no.

Body:
I think you are right that there is no ultra-concise way of expressing the operation you want to perform using just J primitives. The version I came up was very much like the one Dan, suggested above.
However given that a built in library verb rplc (based on stringreplace) performs exactly the operation you are after, I'm not sure why it would be better to replace it with a primitive.

   '))()(())(' rplc '()';''
))()(

Having said that, if you can come up with a compelling case, then there is probably no reason it couldn't be added.


问:
finding the maximum number of 1's in a row

A 2d matrix is given filled with 1's and 0's. It is given that all 1's in a row come before all the 0's. We have to find the maximum number of 1's in a row.

I have made the solution that we can apply binary search on every row to get the last index of last 1 in that row before 0's begin and hence the no. of 1's will be its index+1. So we can do this at every row.
So the complexity would be O(mlogn),where m is the no. of rows and n is the no. of columns.
Can there be a better solution to this?

答:
```<code>#include <stdio.h>
#define R 4
#define C 4

/* A function to find the index of first index of 1 in a boolean array arr[] */
int first(bool arr[], int low, int high)
{
  if(high >= low)
  {
    // get the middle index
    int mid = low + (high - low)/2;

    // check if the element at middle index is first 1
    if ( ( mid == 0 || arr[mid-1] == 0) && arr[mid] == 1)
      return mid;

    // if the element is 0, recur for right side
    else if (arr[mid] == 0)
      return first(arr, (mid + 1), high);

    else // If element is not first 1, recur for left side
      return first(arr, low, (mid -1));
  }
  return -1;
}

// The main function that returns index of row with maximum number of 1s.
int rowWithMax1s(bool mat[R][C])
{
    int max_row_index = 0, max = -1; // Initialize max values

    // Traverse for each row and count number of 1s by finding the index
    // of first 1
    int i, index;
    for (i = 0; i < R; i++)
    {
       index = first (mat[i], 0, C-1);
       if (index != -1 && C-index > max)
       {
           max = C - index;
           max_row_index = i;
       }
    }

    return max_row_index;
}

/* Driver program to test above functions */
int main()
{
    bool mat[R][C] = { {0, 0, 0, 1},
        {0, 1, 1, 1},
        {1, 1, 1, 1},
        {0, 0, 0, 0}
    };

    printf("Index of row with maximum 1s is %d n", rowWithMax1s(mat));

    return 0;
}
</code>```


问:
GWT Sending type OBJECT Via RPC
I am trying to do this

Service Interface:

```<code>Boolean SaveObjectIntoDatabase(Object Entity);
</code>```

ServiceAsync:

```<code>void SaveObjectIntoDatabase(Object Entity,AsyncCallback <Boolean> Callback);
</code>```

then implementing it on the serviceimpl

with no success.

Is it that we cannot send a variable of type object via GWT RPC??

stack trace:

```<code>onModuleLoad() threw an exception

Exception while loading module com.BiddingSystem.client.BiddingSystem. See Development Mode for details.
java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.google.gwt.dev.shell.ModuleSpace.onLoad(ModuleSpace.java:396) at com.google.gwt.dev.shell.OophmSessionHandler.loadModule(OophmSessionHandler.java:183) at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:510) at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:352) at java.lang.Thread.run(Thread.java:662) Caused by: java.lang.RuntimeException: Deferred binding failed for 'com.BiddingSystem.client.Service' (did you forget to inherit a required module?) at com.google.gwt.dev.shell.GWTBridgeImpl.create(GWTBridgeImpl.java:53) at com.google.gwt.core.client.GWT.create(GWT.java:97) at com.BiddingSystem.client.BiddingSystem.onModuleLoad(BiddingSystem.java:63) ... 9 more Caused by: com.google.gwt.core.ext.UnableToCompleteException: (see previous log entries) at com.google.gwt.dev.shell.ModuleSpace.rebind(ModuleSpace.java:595) at com.google.gwt.dev.shell.ModuleSpace.rebindAndCreate(ModuleSpace.java:455) at com.google.gwt.dev.shell.GWTBridgeImpl.create(GWTBridgeImpl.java:49) ... 11 more
</code>```

答: make the object class itself implmenets serialisable interface</p>

Title: GWT Sending type OBJECT Via RPC

Body:
I am trying to do this

Service Interface:

Boolean SaveObjectIntoDatabase(Object Entity);

ServiceAsync:

void SaveObjectIntoDatabase(Object Entity,AsyncCallback <Boolean> Callback);

then implementing it on the serviceimpl

with no success.

Is it that we cannot send a variable of type object via GWT RPC??

stack trace:

onModuleLoad() threw an exception

Exception while loading module com.BiddingSystem.client.BiddingSystem. See Development Mode for details.
java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.google.gwt.dev.shell.ModuleSpace.onLoad(ModuleSpace.java:396) at com.google.gwt.dev.shell.OophmSessionHandler.loadModule(OophmSessionHandler.java:183) at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:510) at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:352) at java.lang.Thread.run(Thread.java:662) Caused by: java.lang.RuntimeException: Deferred binding failed for 'com.BiddingSystem.client.Service' (did you forget to inherit a required module?) at com.google.gwt.dev.shell.GWTBridgeImpl.create(GWTBridgeImpl.java:53) at com.google.gwt.core.client.GWT.create(GWT.java:97) at com.BiddingSystem.client.BiddingSystem.onModuleLoad(BiddingSystem.java:63) ... 9 more Caused by: com.google.gwt.core.ext.UnableToCompleteException: (see previous log entries) at com.google.gwt.dev.shell.ModuleSpace.rebind(ModuleSpace.java:595) at com.google.gwt.dev.shell.ModuleSpace.rebindAndCreate(ModuleSpace.java:455) at com.google.gwt.dev.shell.GWTBridgeImpl.create(GWTBridgeImpl.java:49) ... 11 more


问:
Testing vuex action that contains an async
[This is a Vue app, using Vuex, created with vue-cli, using mocha, chai, karma, sinon]

I'm trying to create tests for my vuex state and I DON'T want to use a mock -- one of my big goals for these tests is to also test the API that data is coming from.

I am trying to follow the docs for chai-as-promised.

This is a simplification of the vuex action I'm trying to test:

```<code>const actions = {
  login: (context, payload) => {
    context.commit('setFlashMessage', "");
    axios.get("https://first-api-call")
      .then((response) => {
        axios.post("https://second-api-call")
          .then((response) => {
            router.push({ name: "Home"});
            context.commit('setFlashMessage', "Logged in successfully");
            context.commit('setLogin', response.data);
        });
    },
</code>```

Notice that the login action has two promises and doesn't return anything. The login action does two things: it sets some state and it changes the route.

The example that I've seen that using chai-as-promised expects that the promise is returned. That is:

```<code>var result = systemUnderTest();
return expect(result).to.eventually.equal(blah);
</code>```

But in my case, login() doesn't return anything, and I'm not sure what I would return if it did.

This is what I have so far:

```<code>import store from '@/src/store/store'
describe('login', () => {
  it('bad input', () => {
    store.login({ username: "abcd", password: ""});
    // What is the test I should use?
  }
}
</code>```

答:
My co-worker and I came up with the solution:

The vuex action needs to return the promise, and they can be chained together:

```<code>login: (context, payload) => {
    context.commit('setFlashMessage', "");
    return axios.get("https://first-api-call")
        .then((response) => {
            return axios.post("https://second-api-call")
        })
        .then((response) => {
            // etc...
            router.push({ name: "Home"});
            context.commit('setFlashMessage', "Logged in successfully");
            context.commit('setLogin', response.data);
            return {status: "success"};
        });
},
</code>```

Then we didn't need chai-as-promised because the test looks like this:

```<code>it('bad password', () => {
    const result = store.dispatch("login", { username: userName, password: password + "bad" });
    return result.then((response) => {
        expect(response).to.deep.equal({ status: "failed"});
        store.getters.getFlashMessage.should.equal("Error logging in");
    });
});
</code>```

Body:
[This is a Vue app, using Vuex, created with vue-cli, using mocha, chai, karma, sinon]

I'm trying to create tests for my vuex state and I DON'T want to use a mock -- one of my big goals for these tests is to also test the API that data is coming from.

I am trying to follow the docs for chai-as-promised.

This is a simplification of the vuex action I'm trying to test:

const actions = {
  login: (context, payload) => {
    context.commit('setFlashMessage', "");
    axios.get("https://first-api-call")
      .then((response) => {
        axios.post("https://second-api-call")
          .then((response) => {
            router.push({ name: "Home"});
            context.commit('setFlashMessage', "Logged in successfully");
            context.commit('setLogin', response.data);
        });
    },

Notice that the login action has two promises and doesn't return anything. The login action does two things: it sets some state and it changes the route.

The example that I've seen that using chai-as-promised expects that the promise is returned. That is:

var result = systemUnderTest();
return expect(result).to.eventually.equal(blah);

But in my case, login() doesn't return anything, and I'm not sure what I would return if it did.

This is what I have so far:

import store from '@/src/store/store'
describe('login', () => {
  it('bad input', () => {
    store.login({ username: "abcd", password: ""});
    // What is the test I should use?
  }
}

Body:
My co-worker and I came up with the solution:

The vuex action needs to return the promise, and they can be chained together:

login: (context, payload) => {
    context.commit('setFlashMessage', "");
    return axios.get("https://first-api-call")
        .then((response) => {
            return axios.post("https://second-api-call")
        })
        .then((response) => {
            // etc...
            router.push({ name: "Home"});
            context.commit('setFlashMessage', "Logged in successfully");
            context.commit('setLogin', response.data);
            return {status: "success"};
        });
},

Then we didn't need chai-as-promised because the test looks like this:

it('bad password', () => {
    const result = store.dispatch("login", { username: userName, password: password + "bad" });
    return result.then((response) => {
        expect(response).to.deep.equal({ status: "failed"});
        store.getters.getFlashMessage.should.equal("Error logging in");
    });
});


问:
Regular expression - text between multiple occurences of the same pattern
I need to parse a large number of files and process some content based on certain tokens. In order to do this I have to take each token and the text after it, until the next token (with extra new lines).

```<code>A ---
some text of many lines
B ---

other text with some lines

C ---
more text and tokens and text
</code>```

I've been using regex101 and made it up to splitting them

```<code>(?<token>^([a-zA-Z].--.*))|(?<content>.*)
</code>```

However, I can't get the second match in a single group.
The desired result is to get the token and text following pairs.

Is this possible to accomplish this using a single regex expression ? and how ?

Thanks

答:
Here's what I was able to do to make your regex work.

```<code>/(?<token>[A-Za-z]+)\s*---\s*(?<content>.+?)(?=[A-Za-z]+\s*---\s*|$)/gs
</code>```

https://regex101.com/r/x8tPHN/4

The difference between what I have and what you have is that there is a lookahead that checks for either a new token OR the end of the data.

I have the g(global) and s(dot equals new line) flags enabled.

Body:
I need to parse a large number of files and process some content based on certain tokens. In order to do this I have to take each token and the text after it, until the next token (with extra new lines).

A ---
some text of many lines
B ---

other text with some lines

C ---
more text and tokens and text

I've been using regex101 and made it up to splitting them

(?<token>^([a-zA-Z].--.*))|(?<content>.*)

However, I can't get the second match in a single group.
The desired result is to get the token and text following pairs.

Is this possible to accomplish this using a single regex expression ? and how ?

Thanks

Body:
Here's what I was able to do to make your regex work.

/(?<token>[A-Za-z]+)\s*---\s*(?<content>.+?)(?=[A-Za-z]+\s*---\s*|$)/gs

https://regex101.com/r/x8tPHN/4

The difference between what I have and what you have is that there is a lookahead that checks for either a new token OR the end of the data.

I have the g(global) and s(dot equals new line) flags enabled.


问:
NetworkStream readed message checking
From Server i sending "100"

```<code>NetworkStream sStream = Client.GetStream();
string sMessage = "100";
byte[] sM = Encoding.ASCII.GetBytes(sMessage);
sStream.Write(sM, 0, sM.Length);
</code>```

and my Client have this code.

```<code>sStream.Read(sM, 0, sM.Length);
string FirstCall = Encoding.ASCII.GetString(sM);
// or even
string FirstCall = Encoding.ASCII.GetString(sM).ToString();
if(FirstCall == "100")
{
    MessageBox.Show("Message check.. Message : "+Encoding.ASCII.GetString(sM));
}
else
{
    MessageBox.Show("Error ; " + Encoding.ASCII.GetString(sM));
}
</code>```

End i getting message box says - Error ; 100

At this point i do not know what i missing.. if i already do
Encoding.ASCII.GetString(sM) it should be a string.

答:
Duo my research about bytes, i figure out.., if i want to send and receive 3 digits number i need do byte[] data = new byte[3]; - "use byte size 3 as sending 3 digit number" and then sStream.read(data, 0, data.Lenght); ..

Or if Sending text, but text each time is different bytes, to remove \0 after text can use var new_data = data.TakeWhile((v, index) => data.Skip(index).Any(w => w != 0x00)).ToArray(); but i do not test out if it remove \0 between bytes what you want to keep.

Title: NetworkStream readed message checking

Body:
From Server i sending "100"

NetworkStream sStream = Client.GetStream();
string sMessage = "100";
byte[] sM = Encoding.ASCII.GetBytes(sMessage);
sStream.Write(sM, 0, sM.Length);

and my Client have this code.

sStream.Read(sM, 0, sM.Length);
string FirstCall = Encoding.ASCII.GetString(sM);
// or even
string FirstCall = Encoding.ASCII.GetString(sM).ToString();
if(FirstCall == "100")
{
    MessageBox.Show("Message check.. Message : "+Encoding.ASCII.GetString(sM));
}
else
{
    MessageBox.Show("Error ; " + Encoding.ASCII.GetString(sM));
}

End i getting message box says - Error ; 100

At this point i do not know what i missing.. if i already do
Encoding.ASCII.GetString(sM) it should be a string.


问:
How sort function works on vector of pair of pairs of integer?
Given

```<code>std::vector<std::pair<std::pair<int,int>, std::pair<int,int>> a;
std::sort(a.begin(),a.end());
</code>```

How is std::sort function going to sort this type of vector? Is there any generalization for further cascading of pairs?

答:
std::sort uses operator< unless specified otherwise.

According to the documentation of std::pair:

http://en.cppreference.com/w/cpp/utility/pair/operator_cmp

Comparison operators, such as < are defined as the lexicographical equivalents:

Compares lhs and rhs lexicographically, that is, compares the first elements and only if they are equivalent, compares the second elements.

In your case, this logic will be applied recursively at each pair level.

Body:
Given

std::vector<std::pair<std::pair<int,int>, std::pair<int,int>> a;
std::sort(a.begin(),a.end());

How is std::sort function going to sort this type of vector? Is there any generalization for further cascading of pairs?


问:
how to upload SWF format in php?
My source code is to print upload SWF file tmp_name ?

```<code><?php
echo json_encode($_FILES);
?>
 <form method="POST" action="#" enctype="multipart/form-data" novalidate>
      <input type="file" id="image" name="image" />
       <input id="send" type="submit" name="data" value="Submit" />
</form>
</code>```

But result i'm  getting

```<code>{"image":{"name":"file.swf","type":"","tmp_name":"","error":1,"size":0}}
</code>```

I have tried image uploading method no use on that !

答:
```<code>{"image":{"name":"file.swf","type":"","tmp_name":"","error":1,"size":0}}
                                                    ^^^^^^^^^
</code>```

This error isn't specific to Flash at all. You'd run into the same issue with other formats as well.

Error 1 is UPLOAD_ERR_INI_SIZE. It means that the file you tried to upload was larger than your server's maximum upload size (upload_max_filesize), so the server didn't accept it.

Change this configuration value, or upload a smaller file.

Title: how to upload SWF format in php?

Body:
My source code is to print upload SWF file tmp_name ?

<?php
echo json_encode($_FILES);
?>
 <form method="POST" action="#" enctype="multipart/form-data" novalidate>
      <input type="file" id="image" name="image" />
       <input id="send" type="submit" name="data" value="Submit" />
</form>

But result i'm  getting

{"image":{"name":"file.swf","type":"","tmp_name":"","error":1,"size":0}}

I have tried image uploading method no use on that !

Body:
{"image":{"name":"file.swf","type":"","tmp_name":"","error":1,"size":0}}
                                                    ^^^^^^^^^

This error isn't specific to Flash at all. You'd run into the same issue with other formats as well.

Error 1 is UPLOAD_ERR_INI_SIZE. It means that the file you tried to upload was larger than your server's maximum upload size (upload_max_filesize), so the server didn't accept it.

Change this configuration value, or upload a smaller file.


问:
Python 3: User input random numbers to see if multiples of 5. Then get the sum of all the numbers that were multiples of 5
I spent all day on this code. It failed.

```<code>def output (n):
  n = int(input('Enter a number: ')

while n != 0:
    if n % 5 == 0:
      print(n, 'Yes')
    n = int(input('Enter a number: ')
    if n == 0
      output = range(1, int(input('Enter a number: '))+1)
      print (output)
output (n)
</code>```

Question is:

let user enter integers to determine if multiple of 5.

If it is then keep count that will keep a sum of all numbers that are multiples of 5.

Task done using a loop in a function and the loop will terminate when a value of 0 is entered.

when the loop terminates, return the count of how many numbers that were multiple of 5s.

After complete, NEXT:
pass the variable sum_multiple_five to another function called print_result() and still
print the same message but now the print will be done in its own function.

答:
```<code>def test(n):
    if not n%5:
        print (n,'Yes')
        return n
    else:
        print (n,'No')
        return 0

total = 0
while True:
    n = int(input('Enter a number: '))
    if not n:
        break
    total+=test(n)

print(total)
</code>```

Body:
I spent all day on this code. It failed.

def output (n):
  n = int(input('Enter a number: ')

while n != 0:
    if n % 5 == 0:
      print(n, 'Yes')
    n = int(input('Enter a number: ')
    if n == 0
      output = range(1, int(input('Enter a number: '))+1)
      print (output)
output (n)

Question is:

let user enter integers to determine if multiple of 5.

If it is then keep count that will keep a sum of all numbers that are multiples of 5.

Task done using a loop in a function and the loop will terminate when a value of 0 is entered.

when the loop terminates, return the count of how many numbers that were multiple of 5s.

After complete, NEXT:
pass the variable sum_multiple_five to another function called print_result() and still
print the same message but now the print will be done in its own function.


问:
Load fonts on page load
I have followed an example to implement a spinner when a button is requested. This code loads a font.

My problem is that the button calls an ajax and the font is loaded after the ajax call (despite the button icon change is requested first by javascript). Both ajax and font are called from a local server. This server is not multi-task and the when the ajax is called the font is not loaded until the ajax call finishes.

Is there any way to force the browser to load the font at the beginning when the page loads?

$('.btn').on('click', function() {
    var $this = $(this);
  $this.button('loading');
    setTimeout(function() {
       $this.button('reset');
   }, 800000);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>
<div style="margin:3em;">
<button type="button" class="btn btn-primary btn-lg " id="load" data-loading-text="<i class='fa fa-circle-o-notch fa-spin'></i> Processing Order">Submit Order</button>
<br>
  <br>
<button type="button" class="btn btn-primary btn-lg" id="load" data-loading-text="<i class='fa fa-spinner fa-spin '></i> Processing Order">Submit Order</button>
</div></code>```

UPDATE

My code has such structure:

```<code>$(button).button('loading');

$.post("/my_page",
    JSON.stringify({
            param: "1234",
                    }),
    function(data)
    {
        // ....
        $(button).button('reset');
    }
    )
    .fail(function(xhr, status, error)
    {
        // error handling
        $(button).button('reset');
    });
</code>```

答:
Then this will do..
Once the page loads and the script is ready.. make an ajax call to load your fonts..</p>

```<code>$(document).ready(function(){
    //your ajax.. call here to load the font.
});
</code>```

Title: Load fonts on page load

Body:
I have followed an example to implement a spinner when a button is requested. This code loads a font.

My problem is that the button calls an ajax and the font is loaded after the ajax call (despite the button icon change is requested first by javascript). Both ajax and font are called from a local server. This server is not multi-task and the when the ajax is called the font is not loaded until the ajax call finishes.

Is there any way to force the browser to load the font at the beginning when the page loads?

$('.btn').on('click', function() {
    var $this = $(this);
  $this.button('loading');
    setTimeout(function() {
       $this.button('reset');
   }, 800000);
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>

<button type="button" class="btn btn-primary btn-lg " id="load" data-loading-text=" Processing Order">Submit Order</button>

<button type="button" class="btn btn-primary btn-lg" id="load" data-loading-text=" Processing Order">Submit Order</button>

UPDATE

My code has such structure:

$(button).button('loading');

$.post("/my_page",
    JSON.stringify({
            param: "1234",
                    }),
    function(data)
    {
        // ....
        $(button).button('reset');
    }
    )
    .fail(function(xhr, status, error)
    {
        // error handling
        $(button).button('reset');
    });

Body:
Then this will do..
Once the page loads and the script is ready.. make an ajax call to load your fonts..

$(document).ready(function(){
    //your ajax.. call here to load the font.
});


问:
skype web sdk login failed says "cannot sign in TypeError: Cannot read property '1' of null"
i hope everyone is doing well.
here i am stuck with something that you guys can help me out.
i am using skype web sdk sample code from [GitHub] (http://github/tomorgan/SkypeWebSDKSamples/tree/gh-pages).
i am trying to login using any credentials i got the same error.
Type Error: Cannot read property '1' of null.

what to do?

答:
This is an issue with Skype's API; an issue is logged here:

https://github.com/OfficeDev/skype-docs/issues/338

The problem is that Skype's SDK is expecting a username of the format name@domain, and doesn't handle any other case.


问:
jQuery get the image src
I hope when I click the button, I can get the specific img src and show the img src in the div class img-block block.

HTML

```<code><button class="button">Click</button>
<div class="img1">
    <img src="img.jpg" alt="">
</div>

<div class="img-block"></div>
</code>```

CSS

```<code>.img-block{
    position: absolute;
    top:10%;
    right:10%;
    background-color: red;
    width: 500px;
    height: 500px;
}
.img1 img{
    width: 200px;
}
</code>```

JS

```<code>$('.button').click(function(){
  var images = $('.img1 img').attr(src);
  alert(images);
});
</code>```

But now I face the problem is to get the img src.

So I use alert to make the test, the result is it alert nothing.

答:
This is what you need</p>

```<code> $('img').context.currentSrc
</code>```

Title: jQuery get the image src

Body:
I hope when I click the button, I can get the specific img src and show the img src in the div class img-block block.

HTML

<button class="button">Click</button>

CSS

.img-block{
    position: absolute;
    top:10%;
    right:10%;
    background-color: red;
    width: 500px;
    height: 500px;
}
.img1 img{
    width: 200px;
}

JS

$('.button').click(function(){
  var images = $('.img1 img').attr(src);
  alert(images);
});

But now I face the problem is to get the img src.

So I use alert to make the test, the result is it alert nothing.

Body:
This is what you need

 $('img').context.currentSrc


问:
Nth largest element in a binary search tree
How to find the Nth largest node in a BST?

Do I keep a count variable while doing In Order Traversal of a BST? Return the element when the count = N???

答:
```<code>// C++ program to find k'th largest element in BST
#include<iostream>
using namespace std;

struct Node
{
    int key;
    Node *left, *right;
};

// A utility function to create a new BST node
Node *newNode(int item)
{
    Node *temp = new Node;
    temp->key = item;
    temp->left = temp->right = NULL;
    return temp;
}

// A function to find k'th largest element in a given tree.
void kthLargestUtil(Node *root, int k, int &c)
{
    // Base cases, the second condition is important to
    // avoid unnecessary recursive calls
    if (root == NULL || c >= k)
        return;

    // Follow reverse inorder traversal so that the
    // largest element is visited first
    kthLargestUtil(root->right, k, c);

    // Increment count of visited nodes
    c++;

    // If c becomes k now, then this is the k'th largest
    if (c == k)
    {
        cout << "K'th largest element is "
             << root->key << endl;
        return;
    }

    // Recur for left subtree
    kthLargestUtil(root->left, k, c);
}

// Function to find k'th largest element
void kthLargest(Node *root, int k)
{
    // Initialize count of nodes visited as 0
    int c = 0;

    // Note that c is passed by reference
    kthLargestUtil(root, k, c);
}

/* A utility function to insert a new node with given key in BST */
Node* insert(Node* node, int key)
{
    /* If the tree is empty, return a new node */
    if (node == NULL) return newNode(key);

    /* Otherwise, recur down the tree */
    if (key < node->key)
        node->left  = insert(node->left, key);
    else if (key > node->key)
        node->right = insert(node->right, key);

    /* return the (unchanged) node pointer */
    return node;
}

// Driver Program to test above functions
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80 */
    Node *root = NULL;
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);

    int c = 0;
    for (int k=1; k<=7; k++)
        kthLargest(root, k);

    return 0;
}
</code>```


问:
Add new environment to an existing release-build
I have release build that has been kicked off already, this build was kicked-off it went through QA and staging environment successfully, the users were happy with the app on both these environments. I then added the last environment that is production. Now my question is, is there a way of getting the current build to see that there is an extra environment added, at the moment it looks like the production deployment does not exist yet I know its there, here is the screenshot of the prod environment that was added

The below screen illustrate that the app deployed succcessfully to the other environments but the prod environment does not appear, the area highlighted in red is where I am expecting my prod environment to appear

I understand queuing or kicking off a new build would make the prod environment appear but I wonder if is there a way to let the current release that there is new environment added.

答: I don't think already running releases will have PROD environment aded</p>


问:
Firebird for cloud application?
I will start a POS (point of sale) system that will begin as a regular intranet system (in his initial-beta stage) but I want to scale later to a cloud offering. I will offer it as a hybrid solution.

I want it to use firebird, because the easier deployment, minimal footprint and the ability to use a embedded multithread server. However, I worry if firebird could be used for a cloud service with fault-tolerance, data replication, etc... to be reliable enough to small companies put his business on it (similar to the service of freshbooks).

My other option is use Postgress, but I have not experience with it.

Is FB good enough to be use as SAAS backend? Any successfully implementation?

P.D: I thinking on deploy it on GoGrid or Rackspace...

答:
Excuse me sounding a little harsh here, but hybrid is bullshit. I like the idea of a SaaS POS but don't spoil the fun for yourself by going down the long and windy path of on site software maintenance support.

No on site maintenance is the single most attractive reason for a SaaS solution for both, the customer and you!

Make it a pure SaaS app from the beginning with proper full screen browser support, streamlined usability and SSL encryption. Also think about competitors especially Square, because your system will rather attract small merchants and Square is all over them.

If you don't do on site in the first place go with a proper web framework and ORM right from the start. You can optimize things later, when you have a reason and the experience to do so.

Now this is only my opinion, but think about what I just said and especially think about it not purely from a technology point of view.

Title: Firebird for cloud application?


问:
How to compare current date with a date range or discrete date values in MySQL?
I am saving multiple dates in database in one column separates by comma(,) like

2017-03-05, 2017-03-06, 2017-03-07, 2017-03-08, 2017-03-08.

2017-03-05, 2017-03-08

I just want to know that how I compare current date by these dates. In the first example, its easy, but problem is for the second one.

Can anyone help me out....?

Thanks...

答:
I would definitely use find_in_set() and substring_index(), if I had such a lousy data structure:

```<code>select t.*
from t
where find_in_set(date_format(curdate(), '%Y-%m-%d'), datecol) > 0 or
      (datecol like '%,%' and datecol not like '%,%,%' and
       date_format(curdate(), '%Y-%m-%d') between substring_index(datecol, ',', 1) and substring_index(datecol, ',', -1)
      );
</code>```

Body:
I would definitely use find_in_set() and substring_index(), if I had such a lousy data structure:

select t.*
from t
where find_in_set(date_format(curdate(), '%Y-%m-%d'), datecol) > 0 or
      (datecol like '%,%' and datecol not like '%,%,%' and
       date_format(curdate(), '%Y-%m-%d') between substring_index(datecol, ',', 1) and substring_index(datecol, ',', -1)
      );


问:
How can I create my own "hint" when calling a function in IDLE?
I know my question might be confusing, it's hard to ask something you don't know what it is exactly (I'm going to call it 'hint'), so my apologies for that. Having that said, here it is what I mean (the text in the white box):

My questions are:

How can I make my own hint (and customize it) text when calling a function?

What is it exactly?

What does the text in this example mean?

答:
You are in fact correct about the textbox being called hint, so no quotation needed. What you are seeing is a type hint. It is supported by the typing module inside Python. Refer to the example below:

```<code>def add(a: int, b: int) -> int:
    return a + b
</code>```

Then when you try to call the function you will see a textbox very similar to the one you showed. I encourage you to read the typing module page if you want to learn more about it.

That said, in most cases you will not be needing that type hint because doc strings ("""info about my function""") are usually sought after more.

Body:
You are in fact correct about the textbox being called hint, so no quotation needed. What you are seeing is a type hint. It is supported by the typing module inside Python. Refer to the example below:

def add(a: int, b: int) -> int:
    return a + b

Then when you try to call the function you will see a textbox very similar to the one you showed. I encourage you to read the typing module page if you want to learn more about it.

That said, in most cases you will not be needing that type hint because doc strings ("""info about my function""") are usually sought after more.


问:
Realm Android: Async Transaction affect UI thread
I'm currently using realm to query RealmObjects to show them on a GoogleMap. I am performing the read and getting the RealmResults but I can't find a way to put the markers on the map from the UI thread. I'd prefer to do this with an async call because it causes ~150ms of lag on the UI thread.

```<code>public void loadLocations(final GoogleMap googleMap) {
        try {

        realm.executeTransactionAsync(new Realm.Transaction() {

            @Override
            public void execute(Realm realm) {
                RealmResults<LocationObject> locations = realm.where(LocationObject.class).findAll();
                for (LocationObject location: locations ) {
                        googleMap.addMarker(new MarkerOptions()
                                .position(new LatLng(location.lat, location.long))
                }
            }
        });
}
</code>```

How can I later access the RealmResults on the UI thread? Realm mentions that RealmObjects are thread confined

答:
You can try using RealmChangeListener. The Realm docs illustrate this very clearly using the puppies example.

```<code>RealmResults<LocationObject> locations;

//...
    locations = realm.where(LocationObject.class).findAllAsync();

    locations.addChangeListener(new RealmChangeListener<Person>() {
        @Override
        public void onChange(RealmResults<LocationObject> locations) {
            googleMap.clear();
            for (LocationObject location: locations) {
                googleMap.addMarker(new MarkerOptions()
                            .position(new LatLng(location.lat, location.long));
            }
        }
    }
</code>```

The code above basically do a query asynchronously to the Realm database and the addChangeListener registers a callback method to be invoked when the query is done and will be invoked in future query calls as well (Refer to the realm docs for more info on this).

So, I would suggest running the code above in an onStart or onResume method and don't forget to remove the change listener on onStop or onPause method, like so:

```<code>locations.removeChangeListeners();
</code>```

Lastly, don't forget to close realm. Hope it helps! Don't hesitate to ask if anything is unclear.

Body:
I'm currently using realm to query RealmObjects to show them on a GoogleMap. I am performing the read and getting the RealmResults but I can't find a way to put the markers on the map from the UI thread. I'd prefer to do this with an async call because it causes ~150ms of lag on the UI thread.

public void loadLocations(final GoogleMap googleMap) {
        try {

        realm.executeTransactionAsync(new Realm.Transaction() {

            @Override
            public void execute(Realm realm) {
                RealmResults<LocationObject> locations = realm.where(LocationObject.class).findAll();
                for (LocationObject location: locations ) {
                        googleMap.addMarker(new MarkerOptions()
                                .position(new LatLng(location.lat, location.long))
                }
            }
        });
}

How can I later access the RealmResults on the UI thread? Realm mentions that RealmObjects are thread confined

Body:
You can try using RealmChangeListener. The Realm docs illustrate this very clearly using the puppies example.

RealmResults<LocationObject> locations;

//...
    locations = realm.where(LocationObject.class).findAllAsync();

    locations.addChangeListener(new RealmChangeListener<Person>() {
        @Override
        public void onChange(RealmResults<LocationObject> locations) {
            googleMap.clear();
            for (LocationObject location: locations) {
                googleMap.addMarker(new MarkerOptions()
                            .position(new LatLng(location.lat, location.long));
            }
        }
    }

The code above basically do a query asynchronously to the Realm database and the addChangeListener registers a callback method to be invoked when the query is done and will be invoked in future query calls as well (Refer to the realm docs for more info on this).

So, I would suggest running the code above in an onStart or onResume method and don't forget to remove the change listener on onStop or onPause method, like so:

locations.removeChangeListeners();

Lastly, don't forget to close realm. Hope it helps! Don't hesitate to ask if anything is unclear.


问:
Build Scan not working for Gradle in Android
I am following the Gradle tutorial on https://guides.gradle.org/building-android-apps/ . So the last step of this part is Run a Build Scan. I am doing the exact same thing as it asked me to do, but Android Studio keeps saying "Error:(14, 0) Could not get unknown property 'com' for root project 'HelloWorldGradle' of type org.gradle.api.Project."

Here is my Top-level build file(build.gradle(Project: HelloWorldGradle)):

```<code>// Top-level build file where you can add configuration options common to all        sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        maven { url 'https://plugins.gradle.org/m2' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.4.0-alpha7'
        classpath 'com.gradle:build-scan-plugin:1.7.1'
    }
}

apply plugin: com.gradle.build-scan

buildScan {
    licenseAgreementUrl = 'https://gradle.com/terms-of-service'
    licenseAgree = 'yes'
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

答:
The issue is with the following line in your build.gradle:

apply plugin: com.gradle.build-scan

You need to update as

```<code>apply plugin: 'com.gradle.build-scan'
</code>```

Another thing you need to pay attention is ALWAYS put the com.gradle.build-scan plugin as the very first one, like this:

```<code>apply plugin: 'com.gradle.build-scan'
apply plugin: 'java'
</code>```

Otherwise, you would see this:

WARNING: The build scan plugin was applied after other plugins.     The
  captured data is more comprehensive when the build scan plugin is
  applied first.

Please see https://gradle.com/scans/help/plugin-late-apply for how to
  resolve this problem.

Let me know if this works.

Body:
I am following the Gradle tutorial on https://guides.gradle.org/building-android-apps/ . So the last step of this part is Run a Build Scan. I am doing the exact same thing as it asked me to do, but Android Studio keeps saying "Error:(14, 0) Could not get unknown property 'com' for root project 'HelloWorldGradle' of type org.gradle.api.Project."

Here is my Top-level build file(build.gradle(Project: HelloWorldGradle)):

// Top-level build file where you can add configuration options common to all        sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        maven { url 'https://plugins.gradle.org/m2' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.4.0-alpha7'
        classpath 'com.gradle:build-scan-plugin:1.7.1'
    }
}

apply plugin: com.gradle.build-scan

buildScan {
    licenseAgreementUrl = 'https://gradle.com/terms-of-service'
    licenseAgree = 'yes'
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Body:
The issue is with the following line in your build.gradle:

apply plugin: com.gradle.build-scan

You need to update as

apply plugin: 'com.gradle.build-scan'

Another thing you need to pay attention is ALWAYS put the com.gradle.build-scan plugin as the very first one, like this:

apply plugin: 'com.gradle.build-scan'
apply plugin: 'java'

Otherwise, you would see this:

WARNING: The build scan plugin was applied after other plugins.     The
  captured data is more comprehensive when the build scan plugin is
  applied first.

Please see https://gradle.com/scans/help/plugin-late-apply for how to
  resolve this problem.

Let me know if this works.


问:
find the count of substring in string
I have to find the count of a substring in a string using the C language.
I'm using the function strstr but it only finds the first occurrence.

My idea of the algorithm is something like searching in the string while strstr does not return null and
to substring the main string on each loop.
My question is how to do that?

答:
```<code>/*
 * C Program To Count the Occurence of a Substring in String
 */
#include <stdio.h>
#include <string.h>

char str[100], sub[100];
int count = 0, count1 = 0;

void main()
{
    int i, j, l, l1, l2;

    printf("\nEnter a string : ");
    scanf("%[^\n]s", str);

    l1 = strlen(str);

    printf("\nEnter a substring : ");
    scanf(" %[^\n]s", sub);

    l2 = strlen(sub);

    for (i = 0; i < l1;)
    {
        j = 0;
        count = 0;
        while ((str[i] == sub[j]))
        {
            count++;
            i++;
            j++;
        }
        if (count == l2)
        {
            count1++;
            count = 0;
        }
        else
            i++;
    }
    printf("%s occurs %d times in %s", sub, count1, str);
}
</code>```

Title: find the count of substring in string


问:
Angular component inside of router-outlet on child route will not fill available space
My application's root <router-outlet></router-outlet> will display the following component in a child Module when navigating to the '/child' route:

child.component.ts

```<code>import {Component} from "@angular/core";

@Component({
  template: `
    <div style="display:flex; width: 100%; height: 100%;">
      <custom-sidebar-component></custom-sidebar-component>
      <router-outlet></router-outlet>
    </div>`
})
export class ChildComponent {
}
</code>```

Now this component displays just fine and fills the entire screen as I expected. However, when I attempt to navigate to a child route of this module, say to '/child/home', I expect the following HTML to display in the child <router-outlet></router-outlet> seen in the component template above.

child-home.component.html

```<code><style>
  .parent-style {
    display: flex;
    flex-flow: row wrap;
    width: 100%;
    height: 100%;
  }

  .box-style {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-grow: 1;
    background: red;
    color: white;
    border: 1px solid black;
  }
</style>
<div class="parent-style">
  <div class="box-style">Box 1</div>
  <div class="box-style">Box 2</div>
</div>
</code>```

But this time the contents of the router-outlet do not fill the available space as I was hoping. The only way I have been able to see the results I want is to open dev tools and edit the Angular generated _nghost attribute wrapping my component.  How can I get my component to fill available space?

This is what I expect

This is what I actually get

答:
That's because rendered DOM was as below:

```<code><app-child  _nghost-c1="">
<div _ngcontent-c1="" class="parent-style">
<div _ngcontent-c1="" class="box-style">Box 1</div>
<div _ngcontent-c1="" class="box-style">Box 2</div></div>
</app-child>
</code>```

so the solution was quite simple, add some styles to the host element ,you can use host:{'class':'foo'} or directly add host:{'style':'width:100%'} in the @Component{} of your ChildComponent

Body:
My application's root <router-outlet></router-outlet> will display the following component in a child Module when navigating to the '/child' route:

child.component.ts

import {Component} from "@angular/core";

@Component({
  template: `

      <custom-sidebar-component></custom-sidebar-component>
      <router-outlet></router-outlet>

`
})
export class ChildComponent {
}

Now this component displays just fine and fills the entire screen as I expected. However, when I attempt to navigate to a child route of this module, say to '/child/home', I expect the following HTML to display in the child <router-outlet></router-outlet> seen in the component template above.

child-home.component.html

Box 1

Box 2

But this time the contents of the router-outlet do not fill the available space as I was hoping. The only way I have been able to see the results I want is to open dev tools and edit the Angular generated _nghost attribute wrapping my component.  How can I get my component to fill available space?

This is what I expect

This is what I actually get

Body:
That's because rendered DOM was as below:

<app-child  _nghost-c1="">
<div _ngcontent-c1="" class="parent-style">
<div _ngcontent-c1="" class="box-style">Box 1</div>
<div _ngcontent-c1="" class="box-style">Box 2</div></div>
</app-child>

so the solution was quite simple, add some styles to the host element ,you can use host:{'class':'foo'} or directly add host:{'style':'width:100%'} in the @Component{} of your ChildComponent


问:
How to access mysql server within a server?
I am running mysql on a linux server. I have the linux server IP and mysql runs on localhost on that linux server. Now how do I access mysql running on localhost server remotely?

I can do this by ssh into linux server then running mysql, but how would I do it with in a php script? For example...

```<code><?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
   $conn = new PDO("mysql:host=$servername;dbname=myDB", $username,
           $password);

   // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  echo "Connected successfully";
}
catch(PDOException $e)
{
  echo "Connection failed: " . $e->getMessage();
}
?>
</code>```

(this script only connects to mysql directly which is not possible remotely)

In my script I would need to access linux server then mysql server unless there is a way to access mysql directly (remotely). How is this achievable?

答:
You need change bind address in my.cnf  and restart your mysql service.

Official documentation:

https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_bind_address

If the address is 0.0.0.0, the server accepts TCP/IP connections on all server host IPv4 interfaces.

By default all connections restricted localhost.

Body:
I am running mysql on a linux server. I have the linux server IP and mysql runs on localhost on that linux server. Now how do I access mysql running on localhost server remotely?

I can do this by ssh into linux server then running mysql, but how would I do it with in a php script? For example...

<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
   $conn = new PDO("mysql:host=$servername;dbname=myDB", $username,
           $password);

   // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  echo "Connected successfully";
}
catch(PDOException $e)
{
  echo "Connection failed: " . $e->getMessage();
}
?>

(this script only connects to mysql directly which is not possible remotely)

In my script I would need to access linux server then mysql server unless there is a way to access mysql directly (remotely). How is this achievable?