问:
Using Stacks In C++ for infix and postfix expressions
I'm writing a program that takes user input and uses stacks to convert an infix expression into a postfix expression based on precedence, with operands always going before operators. For example, if a user inputs:

(a+b*c)

then the program should display:

abc*+

so far, I have this:

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

using namespace std;

int main()
{
    stack<char> s;
    char input;
    while (cin.get(input) && input != '\n')
        {
            if (isalnum(input))
                cout << input << "\n";
            else if (input == '(')
                s.push(input);
            else if (input == ')')
            {
        while (!s.empty() && s.top() != '(')
            {
            cout << s.top();
            s.pop();
        }
            if(!s.empty())
                    s.pop();
            else
                cout << "ERROR: No Matching ( \n";
        }
     else if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input) // Error Begins Here?
     {
         char a = '*';
         char b = '/';
         char c = '+';
         char d = '-';
         bool prec (char a, char b, char c, char d);
             return ('*' > '/' > '+' > '-');
             s.push(input);
     }
         else if (input == '*'||'/'||'+'||'-' && s.top() >= input)
             while (!s.empty())
          {
              cout << s.top();
          s.pop();
                  s.push(input);
          }
        }
    while (!s.empty())
    {
        cout << s.top();
        s.pop();
    }
}
</code>```

Which compiles and runs but is not functioning as it should. When an expression like "ab" is input, the program will display "ab" as it should but if I input "a+b+c", then only "a" will be displayed. This means the program is not placing the operators into the stack to be displayed later on. What I need help with is modifying the program so that when an operator is input, it should be added onto the stack and then displayed based on it's precedence (*>/>+>-) after the operands, when the input is done.

I'm quite new to C++ and programming in general, so any suggestions would be great.

答:
Falmarri is right just wanted to post that my self , and it compiles I tried it , but there is another thing : you said
else if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input) // Error Begins Here?
 Are you sure that even reached that point because when I runn it , it just stops on the :

```<code>while (cin.get(input) && input != '\n')
</code>```

until I hit enter and even more you can enter more then one char from consol while in cin.get(input) but the input will contain only the first char you entered . To solve this I just put an
#include <conio.h>at the beginning an used

```<code>while ((input = getch()) && input != (char)13) in staid of you're code
</code>```

short explanation

```<code>getch()
</code>```

returns after you press only one character and

input != (char)13
is required in staid of
input != '\n'
because getch() return (char)13 for ENTER see ASCII table for more info.

Body:
I'm writing a program that takes user input and uses stacks to convert an infix expression into a postfix expression based on precedence, with operands always going before operators. For example, if a user inputs:

(a+b*c)

then the program should display:

abc*+

so far, I have this:

#include <iostream>
#include <stack>
#include <string>

using namespace std;

int main()
{
    stack<char> s;
    char input;
    while (cin.get(input) && input != '\n')
        {
            if (isalnum(input))
                cout << input << "\n";
            else if (input == '(')
                s.push(input);
            else if (input == ')')
            {
        while (!s.empty() && s.top() != '(')
            {
            cout << s.top();
            s.pop();
        }
            if(!s.empty())
                    s.pop();
            else
                cout << "ERROR: No Matching ( \n";
        }
     else if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input) // Error Begins Here?
     {
         char a = '*';
         char b = '/';
         char c = '+';
         char d = '-';
         bool prec (char a, char b, char c, char d);
             return ('*' > '/' > '+' > '-');
             s.push(input);
     }
         else if (input == '*'||'/'||'+'||'-' && s.top() >= input)
             while (!s.empty())
          {
              cout << s.top();
          s.pop();
                  s.push(input);
          }
        }
    while (!s.empty())
    {
        cout << s.top();
        s.pop();
    }
}

Which compiles and runs but is not functioning as it should. When an expression like "ab" is input, the program will display "ab" as it should but if I input "a+b+c", then only "a" will be displayed. This means the program is not placing the operators into the stack to be displayed later on. What I need help with is modifying the program so that when an operator is input, it should be added onto the stack and then displayed based on it's precedence (*>/>+>-) after the operands, when the input is done.

I'm quite new to C++ and programming in general, so any suggestions would be great.

Body:
Falmarri is right just wanted to post that my self , and it compiles I tried it , but there is another thing : you said
else if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input) // Error Begins Here?
 Are you sure that even reached that point because when I runn it , it just stops on the :

while (cin.get(input) && input != '\n')

until I hit enter and even more you can enter more then one char from consol while in cin.get(input) but the input will contain only the first char you entered . To solve this I just put an
#include <conio.h>at the beginning an used

while ((input = getch()) && input != (char)13) in staid of you're code

short explanation

getch()

returns after you press only one character and

input != (char)13
is required in staid of
input != '\n'
because getch() return (char)13 for ENTER see ASCII table for more info.


来源: stackexchange

问:
Where do I create my ssh directory?
So I want to generate an SSH key for my Digital Ocean droplet. Do I create the SSH directory/file in my project directory? Or do I just create it in Desktop? E.g. say the project I'm working on is in Desktop/project. Do I just cd to that folder and then create the SSH directory? (and then create the actual ssh file in that ssh directory)

答: Normally ~/.ssh it the location of public/private keys on a Mac or Linux machine for ssh related commands.

ContentLicense: CC BY-SA 3.0

Title: Where do I create my ssh directory?


问:
How to use the intersection construction to form a DFA?
I'm doing a homework assignment for my theory of computation class and am a bit confused how to combine 2 DFAs. The book says it uses the "intersection construction" to do so, but I'm not sure what that is. Here are 2 examples:

答:
These are:
{s∈{a,b,c}∗:every a in s is immediately followed by a b}
{s∈{a,b,c}∗:every a in s is immediately followed by a b}
and
{s∈{a,b,c}∗: every c in s is immediately preceded by a b}

In front and another automaton, you can join states "0" and "2".

and you need to retain that ...

There is a precise way for performing automatons for the crossing of languages. Let AA and BB be the input automatons. The cases of new automaton will be all pairs of states of AA and BB, that is SA∩B=SA×SBSA∩B=SA×SB, the initial state will be iA∩B=⟨iA,iB⟩iA∩B=⟨iA,iB⟩, where iAiA and iBiB are the initial states of AA and BB, and FA∩B=FA×FBFA∩B=FA×FB where FXFX denotes the set of accepting states of XX. Finally, the transition function δA∩BδA∩B is defined as follows for any letter α∈Σα∈Σ and states p1,p2∈SAp1,p2∈SA, q1,q2∈SBq1,q2∈SB:

⟨p1,q1⟩−→−−A∩B α ⟨p2,q2⟩ iff p1−→A α p2andq1−→B α q2
⟨p1,q1⟩→A∩B α ⟨p2,q2⟩ iff p1→A α p2andq1→B α q2
Please note, that such automaton usually is not minimal (e.g. the intersection might be just an empty language). Also, it might be useful (but it is not necessary) to make input automatons minimal since the output is quadratic in size.
// Reference: math.stackexchange.com
Happy Coding ...


问:
Incorrect usage of stategy pattern?
Is the following an incorrect usage of the strategy

```<code>interface FilterStrategy {
  public void filter();
}

class OldProductsStrategy implements FilterStrategy {
  public filter();
}

class NewProductsStrategy implements FilterStrategy {
  public filter();
}

class ProductsFilterStrategy {
  public getFilter(a) {
   if(a) {
     return new NewProductsStrategy();
   } else {
     return new OldProductsStrategy();
   }
}

class Client {
  new ProductsFilterStrategy().getFilter(true).filter();
}
</code>```

Is delegating the selection of the strategy implementation part of the strategy pattern?

答:
It's up to you how to adopt the pattern. But there is many advantages in keep the pattern way in mind when adopting and implementing the pattern.

Based on the pattern definition you should have a Context class that:

is configured with a ConcreteStrategy object

maintains a reference to a Strategy object

may define an interface that lets Strategy access its data.

So that you can provide a usage like this:

```<code>  context = new Context(new ConcreteStrategyA());
  context.ContextInterface();

  context = new Context(new ConcreteStrategyB());
  context.ContextInterface();

  context = new Context(new ConcreteStrategyC());
  context.ContextInterface();
</code>```

You can provide the strategy instance using a factory or IoC container. It is not part of Context.

Title: Incorrect usage of stategy pattern?

Body:
Is the following an incorrect usage of the strategy

interface FilterStrategy {
  public void filter();
}

class OldProductsStrategy implements FilterStrategy {
  public filter();
}

class NewProductsStrategy implements FilterStrategy {
  public filter();
}

class ProductsFilterStrategy {
  public getFilter(a) {
   if(a) {
     return new NewProductsStrategy();
   } else {
     return new OldProductsStrategy();
   }
}

class Client {
  new ProductsFilterStrategy().getFilter(true).filter();
}

Is delegating the selection of the strategy implementation part of the strategy pattern?

Body:
It's up to you how to adopt the pattern. But there is many advantages in keep the pattern way in mind when adopting and implementing the pattern.

Based on the pattern definition you should have a Context class that:

is configured with a ConcreteStrategy object

maintains a reference to a Strategy object

may define an interface that lets Strategy access its data.

So that you can provide a usage like this:

  context = new Context(new ConcreteStrategyA());
  context.ContextInterface();

  context = new Context(new ConcreteStrategyB());
  context.ContextInterface();

  context = new Context(new ConcreteStrategyC());
  context.ContextInterface();

You can provide the strategy instance using a factory or IoC container. It is not part of Context.


问:
How to cheat and avoid cheating in Flash games?
I'm writing a small online flash game that keeps high scores of players. Obviously I'd like to keep the players from cheating and getting an arbitrarily high score.

What are the most common methods for cheating in flash games and what can I do to make it hard to use them?

答:
The most common way to cheat is to use Cheat Engine.

See it in action on YouTube, along with 100s of tutorials on cheating in the most popular games.

Keeping people from cheating is going to be nearly impossible. But there are several methods for securing the high scores table, which could be applicable to cheating in general.

OwnerDisplayName: Shy

LastEditorDisplayName: Spoike

OwnerDisplayName: David Thomas Garcia

ContentLicense: CC BY-SA 2.5


问:
How do programs like mathematica draw graphs and how can I make such a program?
I've been wondering how programs like mathematica and mathlab, and so on, plot graphs of functions so gracefully and fast. Can anyone explain to me how they do this and, furthermore, how I can do this? Is it related to an aspect or course in Computer Programming or Math? Which then?</p>

答:
For MATLAB, because of its cross-platform requirement there is no alternatives as using OpenGL. MATLAB runtime is written in C++ and non-axis GUI uses Java Swing. Therefore MATLAB Plot is probably a C++/OpenGL/Swing mixture.

In reality MATLAB graphics is much less complex then a video game graphics. I think it is easier to find tutorials on video game graphics and then "downsize" it to MATLAB functionality, like drawing a single line with the same color.

The most important concept is probably Transformation Matrix.


问:
Primefaces Poll only if browser tab is focused
In implementing primefaces poll, I want to execute poll only if the browser tab is active/focused

Otherwise it should not poll data from backing bean as if multiple browser tabs are open, all the browser tabs will execute the poll regardless of being focused.

答:
Effectively, this question is a duplicate of a combination of two other questions. I'll answer it here anyway to emphasize the relevance (need!) to always try to break down your problem in more generic and hence manageable parts for which you can find answers. In this case the 'two' questions are:

Can I stop/start a poll from the client-side via e.g. javascript

Can I detect if a browser tab  focus.

Both are more easily solvable via search engines than the combined one.

I put the google searches behind the 'list items' above.

This results in

How to correctly start/stop a PrimeFaces Ajax Poll from javascript

Is there a way to detect if a browser window is not currently active?

Which combined will give you the solution you need.


问:
Loopback event stream track changes in a model on server side
I have stuck in a situation that I want to sync two mongoDB one is at local machine and second is at the remote (on a mlab sandbox). for sync I am doing as:

first I dump the collection which have changes using mongodump
next by using mongorestore I am restoring that collection on a remote MongoDB.

But there are two problems which I am facing.

First is how can I update the collection on a remote mongoDB.
for example : on change collection should I replace the whole collection on remote side or use other way ? and what is best way for doing this.

And the second one problem is how can I detect changes in a collection. or in a whole database. I am using loopback framework and event-stream npm module for sending changes to the client side. but I unable to read change stream on server side.

my server\boot\realtime.js is :

```<code>var es = require('event-stream');
var sync = require('../sync');

module.exports = function(app) {

  var completeOrder = app.models.completeOrder;

  completeOrder.createChangeStream(function(err, changes) {

   sync('completeOrder',function(data){

      console.log(data);
    },function(err){

      console.log(err);
    });
   changes.pipe(es.stringify()).pipe(process.stdout);
  });

}
</code>```

答: On second problem LoopBack doesn’t send events when there is change in data in underlying DB but only when there is change in model. Mongo 3.6 provides change stream functionality and you can use it to trigger model change/perform your functionality.</p>

Body:
I have stuck in a situation that I want to sync two mongoDB one is at local machine and second is at the remote (on a mlab sandbox). for sync I am doing as:

first I dump the collection which have changes using mongodump
next by using mongorestore I am restoring that collection on a remote MongoDB.

But there are two problems which I am facing.

First is how can I update the collection on a remote mongoDB.
for example : on change collection should I replace the whole collection on remote side or use other way ? and what is best way for doing this.

And the second one problem is how can I detect changes in a collection. or in a whole database. I am using loopback framework and event-stream npm module for sending changes to the client side. but I unable to read change stream on server side.

my server\boot\realtime.js is :

var es = require('event-stream');
var sync = require('../sync');

module.exports = function(app) {

  var completeOrder = app.models.completeOrder;

  completeOrder.createChangeStream(function(err, changes) {

   sync('completeOrder',function(data){

      console.log(data);
    },function(err){

      console.log(err);
    });
   changes.pipe(es.stringify()).pipe(process.stdout);
  });

}


问:
Why Pastry DHT has an efficient routing
Recently I read some articles about Pastry DHT.The articles said that Pastry DHT has an efficient routing.In Pastry's routing,each step's node ID has a longer common prefix with the destination node,but node IDs are assigned randomly so it is possible that message travel a very very long distance before it arrive the destination and as a result the routing is not efficient.

For example,a Pastry routing,the destination node ID is d467c4,the starting node ID is 65a1fc,the routing process is 65a1fc->d13da3->d4213f->d462ba->d46702->d467c4.It is possible that nodes on this routing are all over the world（IDs are assigned randomly）.The message will travel around the world before it arrive the final node.So this routing is not efficient.

So why Pastry DHT has an efficient routing?

答:
That depends on your notion of efficiency. When designing overlay networks the first concern usually is to bound the total number of hops relative to the network size. In other words if there are n nodes you don't want O(n) routes, O(log n) is the usual goal because it can be achieved without total network awareness.

Route length in terms of latency, path cost or minimum bandwidth along the link are second-rank concerns. That are often achieved by adding some sort of locality-awareness or clustering after the hop-length has been optimized.

Pastry is efficient for the hop metric.

Title: Why Pastry DHT has an efficient routing


问:
Wordpress administrative panel customization
In the wordpress ADM panel I have a menu item that is called the client area. I have put category types for when the user is going to publish some document. He / she reports what type of document is Ex: Financial, Plants, Announcements, Contracts etc. The customer asked for these categories to appear as a sub-menu and from there he chose the category of the document. Example in the image I have Client Area and as submenus add Documents and Categories Documents

Image

I will need to customize so that the menu is as follows
add documents Categories Financial Documents Plants Press Releases Contracts
And from these submenus it will sign each item if it is financial all financial and so on.

Is there a way to customize this in Wordpress?

答:
You can add and mange wp admin menu.

For example you will need add links to terms posts filter.
You can get the relavante url structure from a category posts link go to taxonomy of category (Categories Documents) you see all categories with number count eg: "Category Name (2)".

Just click on the number counting and you get page with category filter.

For example on tax named "product_category", term named "gadgets" and "products" cpt:
/wp-admin/edit.php?product-category=gadgets&post_type=product


问:
What is the quickest way to store attachments in an outlook mailbox mails?
Suppose i have my mailbox configured and i have a special folder for mails with attachments in outlook 2007. What i want to do is
i. either configure outlook to save the attachment of mails coming in a specified folder (Mails with Attachments) to specific folder in my computer drive in a desired folder

ii. Or if i can write some macro or script to copy those all to my computer location. If so can you please give me quick overview or refer me some where.

答:
This subroutine will save all attachments found in a user specified Outlook folder to a user specified directory on the file system. It also updates each message with a link to the purged files.

It also contains extra comments to help highlight how the .Delete method will shrink Attachment containers dynamically (search for "~~" in the comments).

This macro is only tested on Outlook 2010.

```<code>' ------------------------------------------------------------
' Requires the following references:
'
' Visual Basic for Applications
' Microsoft Outlook 14.0 Object Library
' OLE Automation
' Microsoft Office 14.0 Object Library
' Microsoft Shell Controls and Automation
' ------------------------------------------------------------

Public Sub SaveOLFolderAttachments()

  ' Ask the user to select a file system folder for saving the attachments
  Dim oShell As Object
  Set oShell = CreateObject("Shell.Application")
  Dim fsSaveFolder As Object
  Set fsSaveFolder = oShell.BrowseForFolder(0, "Please Select a Save Folder:", 1)
  If fsSaveFolder Is Nothing Then Exit Sub
  ' Note:  BrowseForFolder doesn't add a trailing slash

  ' Ask the user to select an Outlook folder to process
  Dim olPurgeFolder As Outlook.MAPIFolder
  Set olPurgeFolder = Outlook.GetNamespace("MAPI").PickFolder
  If olPurgeFolder Is Nothing Then Exit Sub

  ' Iteration variables
  Dim msg As Outlook.MailItem
  Dim att As Outlook.attachment
  Dim sSavePathFS As String
  Dim sDelAtts As String

  For Each msg In olPurgeFolder.Items

    sDelAtts = ""

    ' We check each msg for attachments as opposed to using .Restrict("[Attachment] > 0")
    ' on our olPurgeFolder.Items collection.  The collection returned by the Restrict method
    ' will be dynamically updated each time we remove an attachment.  Each update will
    ' reindex the collection.  As a result, it does not provide a reliable means for iteration.
    ' This is why the For Each loops will not work.
    If msg.Attachments.Count > 0 Then

      ' This While loop is controlled via the .Delete method
      ' which will decrement msg.Attachments.Count by one each time.
      While msg.Attachments.Count > 0

        ' Save the file
        sSavePathFS = fsSaveFolder.Self.Path & "\" & msg.Attachments(1).FileName
        msg.Attachments(1).SaveAsFile sSavePathFS

        ' Build up a string to denote the file system save path(s)
        ' Format the string according to the msg.BodyFormat.
        If msg.BodyFormat <> olFormatHTML Then
            sDelAtts = sDelAtts & vbCrLf & "<file://" & sSavePathFS & ">"
        Else
            sDelAtts = sDelAtts & "<br>" & "<a href='file://" & sSavePathFS & "'>" & sSavePathFS & "</a>"
        End If

        ' Delete the current attachment.  We use a "1" here instead of an "i"
        ' because the .Delete method will shrink the size of the msg.Attachments
        ' collection for us.  Use some well placed Debug.Print statements to see
        ' the behavior.
        msg.Attachments(1).Delete

      Wend

      ' Modify the body of the msg to show the file system location of
      ' the deleted attachments.
      If msg.BodyFormat <> olFormatHTML Then
        msg.Body = msg.Body & vbCrLf & vbCrLf & "Attachments Deleted:  " & Date & " " & Time & vbCrLf & vbCrLf & "Saved To:  " & vbCrLf & sDelAtts
      Else
        msg.HTMLBody = msg.HTMLBody & "<p></p><p>" & "Attachments Deleted:  " & Date & " " & Time & vbCrLf & vbCrLf & "Saved To:  " & vbCrLf & sDelAtts & "</p>"
      End If

      ' Save the edits to the msg.  If you forget this line, the attachments will not be deleted.
      msg.Save

    End If

  Next

End Sub
</code>```

Body:
This subroutine will save all attachments found in a user specified Outlook folder to a user specified directory on the file system. It also updates each message with a link to the purged files.

It also contains extra comments to help highlight how the .Delete method will shrink Attachment containers dynamically (search for "~~" in the comments).

This macro is only tested on Outlook 2010.

' ------------------------------------------------------------
' Requires the following references:
'
' Visual Basic for Applications
' Microsoft Outlook 14.0 Object Library
' OLE Automation
' Microsoft Office 14.0 Object Library
' Microsoft Shell Controls and Automation
' ------------------------------------------------------------

Public Sub SaveOLFolderAttachments()

  ' Ask the user to select a file system folder for saving the attachments
  Dim oShell As Object
  Set oShell = CreateObject("Shell.Application")
  Dim fsSaveFolder As Object
  Set fsSaveFolder = oShell.BrowseForFolder(0, "Please Select a Save Folder:", 1)
  If fsSaveFolder Is Nothing Then Exit Sub
  ' Note:  BrowseForFolder doesn't add a trailing slash

  ' Ask the user to select an Outlook folder to process
  Dim olPurgeFolder As Outlook.MAPIFolder
  Set olPurgeFolder = Outlook.GetNamespace("MAPI").PickFolder
  If olPurgeFolder Is Nothing Then Exit Sub

  ' Iteration variables
  Dim msg As Outlook.MailItem
  Dim att As Outlook.attachment
  Dim sSavePathFS As String
  Dim sDelAtts As String

  For Each msg In olPurgeFolder.Items

    sDelAtts = ""

    ' We check each msg for attachments as opposed to using .Restrict("[Attachment] > 0")
    ' on our olPurgeFolder.Items collection.  The collection returned by the Restrict method
    ' will be dynamically updated each time we remove an attachment.  Each update will
    ' reindex the collection.  As a result, it does not provide a reliable means for iteration.
    ' This is why the For Each loops will not work.
    If msg.Attachments.Count > 0 Then

      ' This While loop is controlled via the .Delete method
      ' which will decrement msg.Attachments.Count by one each time.
      While msg.Attachments.Count > 0

        ' Save the file
        sSavePathFS = fsSaveFolder.Self.Path & "\" & msg.Attachments(1).FileName
        msg.Attachments(1).SaveAsFile sSavePathFS

        ' Build up a string to denote the file system save path(s)
        ' Format the string according to the msg.BodyFormat.
        If msg.BodyFormat <> olFormatHTML Then
            sDelAtts = sDelAtts & vbCrLf & "<file://" & sSavePathFS & ">"
        Else
            sDelAtts = sDelAtts & "<br>" & "<a href='file://" & sSavePathFS & "'>" & sSavePathFS & "</a>"
        End If

        ' Delete the current attachment.  We use a "1" here instead of an "i"
        ' because the .Delete method will shrink the size of the msg.Attachments
        ' collection for us.  Use some well placed Debug.Print statements to see
        ' the behavior.
        msg.Attachments(1).Delete

      Wend

      ' Modify the body of the msg to show the file system location of
      ' the deleted attachments.
      If msg.BodyFormat <> olFormatHTML Then
        msg.Body = msg.Body & vbCrLf & vbCrLf & "Attachments Deleted:  " & Date & " " & Time & vbCrLf & vbCrLf & "Saved To:  " & vbCrLf & sDelAtts
      Else
        msg.HTMLBody = msg.HTMLBody & "<p></p><p>" & "Attachments Deleted:  " & Date & " " & Time & vbCrLf & vbCrLf & "Saved To:  " & vbCrLf & sDelAtts & "</p>"
      End If

      ' Save the edits to the msg.  If you forget this line, the attachments will not be deleted.
      msg.Save

    End If

  Next

End Sub


问:
Json.NET Schema: Custom ErrorType when using a custom JSON validation rule
I'm using Json.NET Schema .NET library.

Let's say I have defined a JSON schema like:

```<code>JSchema schema = JSchema.Parse(@"{
    'type': 'object',
    'required' : ['name'],
    'properties': {
        'name': {'type':'string'},
        'roles': {'type': 'array'}
    }
}");
</code>```

Now I'm validating a JSON object (note that I'm not defining the name property):

```<code>JObject user = JObject.Parse(@"{
  'roles': ['Developer', 'Administrator']
}");

user.IsValid(schema, out IList<ValidationError> errors);

Debug.WriteLine(errors[0].ErrorType);
</code>```

The output of the last line will be Required. This way I know the specific error type at run time and I can make decisions according this error type programmatically.

My problem is that when I'm working with custom validations rules I'm not able to define a custom error type. So all my custom validators will create an error instance with the ErrorType property equal to Validator, like in the following example:

Defining a custom validation rule:

```<code>class MyCustomValidator : JsonValidator
{
    public override void Validate(JToken value, JsonValidatorContext context)
    {
        var s = value.ToString();
        if (s != "valid")
        {
            context.RaiseError($"Text '{s}' is not valid.");
        }

    }

    public override bool CanValidate(JSchema schema)
    {
        return schema.Type == JSchemaType.String;
    }
}
</code>```

and running the validation using the custom validation rule:

```<code>JSchema schema = JSchema.Parse(@"{
  'type': 'object',
  'required' : ['name'],
  'properties': {
    'name': {'type':'string'},
    'roles': {'type': 'array'}
  }
}");

JObject user = JObject.Parse(@"{
  'name': 'Ivalid',
  'roles': ['Developer', 'Administrator']
}");

schema.Validators.Add(new MyCustomValidator()); // adding custom validation rule

user.IsValid(schema, out IList<ValidationError> errors);

Debug.WriteLine(errors[0].ErrorType);
</code>```

The output will be Validator.

My question is: Is there a workaround for this case? How can I differentiate the errors produced by my custom validation rules between them and from each other standard errors type?

Thanks!

答:
I received a feedback from the Json.NET Schema's author in a Github issue opened by me. The author says:

Hi

ErrorType is an enum so there isn't a way to define new values at
  runtime. You will need to embed the information about what the error
  is in the message and test the content.

That is: currently has no way to customize the error type property at runtime.

Body:
I'm using Json.NET Schema .NET library.

Let's say I have defined a JSON schema like:

JSchema schema = JSchema.Parse(@"{
    'type': 'object',
    'required' : ['name'],
    'properties': {
        'name': {'type':'string'},
        'roles': {'type': 'array'}
    }
}");

Now I'm validating a JSON object (note that I'm not defining the name property):

JObject user = JObject.Parse(@"{
  'roles': ['Developer', 'Administrator']
}");

user.IsValid(schema, out IList<ValidationError> errors);

Debug.WriteLine(errors[0].ErrorType);

The output of the last line will be Required. This way I know the specific error type at run time and I can make decisions according this error type programmatically.

My problem is that when I'm working with custom validations rules I'm not able to define a custom error type. So all my custom validators will create an error instance with the ErrorType property equal to Validator, like in the following example:

Defining a custom validation rule:

class MyCustomValidator : JsonValidator
{
    public override void Validate(JToken value, JsonValidatorContext context)
    {
        var s = value.ToString();
        if (s != "valid")
        {
            context.RaiseError($"Text '{s}' is not valid.");
        }

    }

    public override bool CanValidate(JSchema schema)
    {
        return schema.Type == JSchemaType.String;
    }
}

and running the validation using the custom validation rule:

JSchema schema = JSchema.Parse(@"{
  'type': 'object',
  'required' : ['name'],
  'properties': {
    'name': {'type':'string'},
    'roles': {'type': 'array'}
  }
}");

JObject user = JObject.Parse(@"{
  'name': 'Ivalid',
  'roles': ['Developer', 'Administrator']
}");

schema.Validators.Add(new MyCustomValidator()); // adding custom validation rule

user.IsValid(schema, out IList<ValidationError> errors);

Debug.WriteLine(errors[0].ErrorType);

The output will be Validator.

My question is: Is there a workaround for this case? How can I differentiate the errors produced by my custom validation rules between them and from each other standard errors type?

Thanks!


问:
Indexes in oracle:
Which of the below would be the best way to create an Index, so that my query gives faster results?

My query is:

```<code>select emp_name,emp_last_name, salary
from employees_table
where salary <=2000;

1. create index emp_index on employees_table (salary);

2. create index emp_index on employees_table (emp_name,emp_last_name,salary);
</code>```

答:
In principle create index emp_index on employees_table (emp_name,emp_last_name,salary); would be the better one, because for your query Oracle has to read only the index but not any table data.

However, this means you create a separate index for each particular query which is certainly an overkill.

Title: Indexes in oracle:

Body:
Which of the below would be the best way to create an Index, so that my query gives faster results?

My query is:

select emp_name,emp_last_name, salary
from employees_table
where salary <=2000;

1. create index emp_index on employees_table (salary);

2. create index emp_index on employees_table (emp_name,emp_last_name,salary);


问:
The infinite monkey theorem in Java
I have an exercise where are given a list of 850 basic words in English in the file basicWords.txt. I need to compose a text of 10000 words by randomly selecting words from the basic words list and write it to another file. I generated successfully the words, but I have a problem: I get an exception when the words are generated: ArrayIndexOutOfBoundsException at line 35. Also, how can I print the result into another text file?
I have a final solution for this:

```<code>    package randomstring;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
 *
 * @author robi1
 */

public class RandomString {

public static void main(String[] args){
     List<String> dictionary = readDictionaryFrom("basicWordsInEnglish.txt");
        List<String> monkeyText = generateTextFrom(dictionary);
        writeTextToFile(monkeyText, "final.txt");
    String letters = "abcdefghijklmnopqrstuvwxyz ";
    Object[] wrds = readFile("basicWordsInEnglish.txt");

    int x = wrds.length;
    String[] words = new String[x];
    for(int i =0;i<x;i++){
        words[i] = wrds[i].toString();
    }
    char[] let = letters.toCharArray();
    String n ="";

    Random r = new Random();
    char t;

}

public static Object[] readFile(String name){

    ArrayList<String> al = new ArrayList<String>();
    FileInputStream fstream;
    try {
        fstream = new FileInputStream(name);

    DataInputStream in = new DataInputStream(fstream);

    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;

    while((strLine=br.readLine())!=null){
        if(strLine.length()>4)
            al.add(strLine);

    }
    fstream.close();

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Object[] array  = al.toArray();

    return array;

}
public static List<String> readDictionaryFrom(String path) {
    try {
            return Files.readAllLines(new File(path).toPath());
        } catch(IOException e) {
            throw new RuntimeException(e);
        }
}

public RandomString(List<String> text, String path) {
    try(BufferedWriter file = new BufferedWriter(new FileWriter(new File(path)))){
        for(String word : text) {
            file.write(word+" ");
        }
    } catch(IOException e) {
        throw new RuntimeException(e);
    }
}

public static List<String> generateTextFrom(List<String> words) {
       Random generator = new Random();
        List<String> result = new ArrayList<>();
        for(int i = 0; i < 10000; i++) {
            int random = generator.nextInt(words.size());
            result.add(words.get(random));
        }
        return result;
}

    public static void writeTextToFile(List<String> text, String path) {
        try(BufferedWriter file = new BufferedWriter(new FileWriter(new File(path)))){
            for(String word : text) {
                file.write(word+" ");
            }
        } catch(IOException e) {
            throw new RuntimeException(e);
        }
    }

}
</code>```

答:
Use the debugging feature of your favorite IDE (might be Eclipse), set an exception breakpoint on ArrayIndexOutOfBoundsException, run your program in debug mode.

When it hits the exception, Eclipse will halt your program. Look at your variable values, especially which array you are accessing and what value the index has, and why it got a value outside of the array size.

By the way, your code line if(n.length()>4){ cannot produce an ArrayIndexOutOfBoundsException, as there's no array indexing in that line.

Title: The infinite monkey theorem in Java

Body:
I have an exercise where are given a list of 850 basic words in English in the file basicWords.txt. I need to compose a text of 10000 words by randomly selecting words from the basic words list and write it to another file. I generated successfully the words, but I have a problem: I get an exception when the words are generated: ArrayIndexOutOfBoundsException at line 35. Also, how can I print the result into another text file?
I have a final solution for this:

    package randomstring;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
 *
 * @author robi1
 */

public class RandomString {

public static void main(String[] args){
     List<String> dictionary = readDictionaryFrom("basicWordsInEnglish.txt");
        List<String> monkeyText = generateTextFrom(dictionary);
        writeTextToFile(monkeyText, "final.txt");
    String letters = "abcdefghijklmnopqrstuvwxyz ";
    Object[] wrds = readFile("basicWordsInEnglish.txt");

    int x = wrds.length;
    String[] words = new String[x];
    for(int i =0;i<x;i++){
        words[i] = wrds[i].toString();
    }
    char[] let = letters.toCharArray();
    String n ="";

    Random r = new Random();
    char t;

}

public static Object[] readFile(String name){

    ArrayList<String> al = new ArrayList<String>();
    FileInputStream fstream;
    try {
        fstream = new FileInputStream(name);

    DataInputStream in = new DataInputStream(fstream);

    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;

    while((strLine=br.readLine())!=null){
        if(strLine.length()>4)
            al.add(strLine);

    }
    fstream.close();

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Object[] array  = al.toArray();

    return array;

}
public static List<String> readDictionaryFrom(String path) {
    try {
            return Files.readAllLines(new File(path).toPath());
        } catch(IOException e) {
            throw new RuntimeException(e);
        }
}

public RandomString(List<String> text, String path) {
    try(BufferedWriter file = new BufferedWriter(new FileWriter(new File(path)))){
        for(String word : text) {
            file.write(word+" ");
        }
    } catch(IOException e) {
        throw new RuntimeException(e);
    }
}

public static List<String> generateTextFrom(List<String> words) {
       Random generator = new Random();
        List<String> result = new ArrayList<>();
        for(int i = 0; i < 10000; i++) {
            int random = generator.nextInt(words.size());
            result.add(words.get(random));
        }
        return result;
}

    public static void writeTextToFile(List<String> text, String path) {
        try(BufferedWriter file = new BufferedWriter(new FileWriter(new File(path)))){
            for(String word : text) {
                file.write(word+" ");
            }
        } catch(IOException e) {
            throw new RuntimeException(e);
        }
    }

}


问:
how can i make a threadsafe progress bar in C#? what am i doing wrong?
Hey everyone, can someone let me know what they see wrong with this code ?

it throws "Cross-thread operation not valid" exception, on

```<code>_DialogueThread.Start();
</code>```

but if i remove "owner" from

```<code>_progressDialogue = new Progresser{Owner = _owner, StartPosition = FormStartPosition.CenterParent};
</code>```

the exception wont be thrown but the progressDialouge will be shown then hidden right away .

now i understand why this the error is thrown if i set the progressDialouge.Owner to a parent form that was created on a different thread. but why dose the form disappears when i dont ?  what am i doing wrong ?

thanks

```<code>class Sampleer : BackgroundWorker
{
    private Progresser _progressDialogue;
    private Thread _DialogueThread;
    private Form _owner;
    private bool _SampleSuccess;

    public Sampleer(Form owner)
    {
        _owner = owner;
        _progressDialogue = new Progresser{Owner = _owner, StartPosition = FormStartPosition.CenterParent};
        _progressDialogue.Closed += ProgressDialogueClosed;
        WorkerReportsProgress = true;
        WorkerSupportsCancellation = true;
        DoWork += Sampleer_DoWork;
        RunWorkerCompleted += Sampleer_RunWorkerCompleted;
        ProgressChanged += Sampleer_ProgressChanged;
    }

    private void Sampleer_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {

       //UPDATE STATUS CODE IS HERE

    }

    void ProgressDialogueClosed(object sender, EventArgs e)
    {
        CancelAsync();
        Dispose();
    }

    void Sampleer_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        //FINISH PROCESS
    }

    void Sampleer_DoWork(object sender, DoWorkEventArgs e)
    {

        _DialogueThread = new Thread(_progressDialogue.Show);
        _DialogueThread.Start();

        //DO LONG PROCESS HERE
    }
}
</code>```

答:
Yes decyclone is right, there are many mistakes in the code and in your approach to solution.

You are inherting BackgroundWorker type but subscribing to its own events?
Instead override the methods that are responsible for raising the event in your class.
ex: Instead of subscribing to DoWork, override OnDoWork method.

I've created a sample application, in which a Form (when performing a background task) shows  another Form (BackgroundWorkUINotification) and starts the background task in BackgroundWorker thread. The BackgroundWorkUINotification notifies the main form when the Form's CancelButton is clicked.

The main Form when notified, closes the notifier and cancels the background task.

Code below: BackgroundWorkUINotification  Form

```<code>public partial class BackgroundWorkUINotification : Form
    {
        public event EventHandler CancelClicked;

    public BackgroundWorkUINotification()
    {
        InitializeComponent();

        // call code to animate progress bar..
        // probably in another BackgroundWorker that reports progress..

        this.cancelButton.Click += HandleCancelButtonOnClick;
    }

    protected virtual void OnCancelClicked()
    {
        if (CancelClicked != null)
            this.CancelClicked(this, EventArgs.Empty);
    }

    private void HandleCancelButtonOnClick(Object sender, EventArgs e)
    {
        this.OnCancelClicked();
    }
}
</code>```

Main Form

```<code>public partial class Form1 : Form
{
    private BackgroundWorker backgroundWorker;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.backgroundWorker = new BackgroundWorker();
        this.backgroundWorker.DoWork += HandleBackgroundWorkerOnDoWork;
        this.backgroundWorker.RunWorkerCompleted += HandleBackgroundWorkerOnRunWorkerCompleted;
        this.backgroundWorker.WorkerSupportsCancellation = true;
    }

    private void HandleDataRequest()
    {
        // show UI notification...
        BackgroundWorkUINotification backgroundWorkUINotification = new BackgroundWorkUINotification();
        backgroundWorkUINotification.CancelClicked += HandleBackgroundWorkUINotificationOnCancelClicked;
        backgroundWorkUINotification.Show(this);

        // start the background worker
        this.backgroundWorker.RunWorkerAsync();
    }

    private void HandleBackgroundWorkUINotificationOnCancelClicked(Object sender, EventArgs e)
    {
        // UI notification Form, Cancelled
        // close the form...
        BackgroundWorkUINotification backgroundWorkUINotification = (BackgroundWorkUINotification)sender;
        backgroundWorkUINotification.Close();

        // stop the background worker thread...
        if (backgroundWorker.IsBusy)
            backgroundWorker.CancelAsync();
    }

    private void HandleBackgroundWorkerOnRunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e)
    {

    }

    private void HandleBackgroundWorkerOnDoWork(Object sender, DoWorkEventArgs e)
    {
        // do some work here..
        // also check for CancellationPending property on BackgroundWorker
    }
}
</code>```

Body:
Hey everyone, can someone let me know what they see wrong with this code ?

it throws "Cross-thread operation not valid" exception, on

_DialogueThread.Start();

but if i remove "owner" from

_progressDialogue = new Progresser{Owner = _owner, StartPosition = FormStartPosition.CenterParent};

the exception wont be thrown but the progressDialouge will be shown then hidden right away .

now i understand why this the error is thrown if i set the progressDialouge.Owner to a parent form that was created on a different thread. but why dose the form disappears when i dont ?  what am i doing wrong ?

thanks

class Sampleer : BackgroundWorker
{
    private Progresser _progressDialogue;
    private Thread _DialogueThread;
    private Form _owner;
    private bool _SampleSuccess;

    public Sampleer(Form owner)
    {
        _owner = owner;
        _progressDialogue = new Progresser{Owner = _owner, StartPosition = FormStartPosition.CenterParent};
        _progressDialogue.Closed += ProgressDialogueClosed;
        WorkerReportsProgress = true;
        WorkerSupportsCancellation = true;
        DoWork += Sampleer_DoWork;
        RunWorkerCompleted += Sampleer_RunWorkerCompleted;
        ProgressChanged += Sampleer_ProgressChanged;
    }

    private void Sampleer_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {

       //UPDATE STATUS CODE IS HERE

    }

    void ProgressDialogueClosed(object sender, EventArgs e)
    {
        CancelAsync();
        Dispose();
    }

    void Sampleer_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        //FINISH PROCESS
    }

    void Sampleer_DoWork(object sender, DoWorkEventArgs e)
    {

        _DialogueThread = new Thread(_progressDialogue.Show);
        _DialogueThread.Start();

        //DO LONG PROCESS HERE
    }
}

Body:
Yes decyclone is right, there are many mistakes in the code and in your approach to solution.

You are inherting BackgroundWorker type but subscribing to its own events?
Instead override the methods that are responsible for raising the event in your class.
ex: Instead of subscribing to DoWork, override OnDoWork method.

I've created a sample application, in which a Form (when performing a background task) shows  another Form (BackgroundWorkUINotification) and starts the background task in BackgroundWorker thread. The BackgroundWorkUINotification notifies the main form when the Form's CancelButton is clicked.

The main Form when notified, closes the notifier and cancels the background task.

Code below: BackgroundWorkUINotification  Form

public partial class BackgroundWorkUINotification : Form
    {
        public event EventHandler CancelClicked;

    public BackgroundWorkUINotification()
    {
        InitializeComponent();

        // call code to animate progress bar..
        // probably in another BackgroundWorker that reports progress..

        this.cancelButton.Click += HandleCancelButtonOnClick;
    }

    protected virtual void OnCancelClicked()
    {
        if (CancelClicked != null)
            this.CancelClicked(this, EventArgs.Empty);
    }

    private void HandleCancelButtonOnClick(Object sender, EventArgs e)
    {
        this.OnCancelClicked();
    }
}

Main Form

public partial class Form1 : Form
{
    private BackgroundWorker backgroundWorker;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.backgroundWorker = new BackgroundWorker();
        this.backgroundWorker.DoWork += HandleBackgroundWorkerOnDoWork;
        this.backgroundWorker.RunWorkerCompleted += HandleBackgroundWorkerOnRunWorkerCompleted;
        this.backgroundWorker.WorkerSupportsCancellation = true;
    }

    private void HandleDataRequest()
    {
        // show UI notification...
        BackgroundWorkUINotification backgroundWorkUINotification = new BackgroundWorkUINotification();
        backgroundWorkUINotification.CancelClicked += HandleBackgroundWorkUINotificationOnCancelClicked;
        backgroundWorkUINotification.Show(this);

        // start the background worker
        this.backgroundWorker.RunWorkerAsync();
    }

    private void HandleBackgroundWorkUINotificationOnCancelClicked(Object sender, EventArgs e)
    {
        // UI notification Form, Cancelled
        // close the form...
        BackgroundWorkUINotification backgroundWorkUINotification = (BackgroundWorkUINotification)sender;
        backgroundWorkUINotification.Close();

        // stop the background worker thread...
        if (backgroundWorker.IsBusy)
            backgroundWorker.CancelAsync();
    }

    private void HandleBackgroundWorkerOnRunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e)
    {

    }

    private void HandleBackgroundWorkerOnDoWork(Object sender, DoWorkEventArgs e)
    {
        // do some work here..
        // also check for CancellationPending property on BackgroundWorker
    }
}


问:
R - gsub() for to remove dates from data set
I am using the gsub() function to remove the unwanted text from the data. I just want to have the age in the brackets, not the dates of birth. However, this is in a large data set with differing birth days. </p>

<p>Example of the data: </p>

```<code>Test1$Age

Sep 10, 1990(27)
Mar 26, 1987(30
Feb 24, 1997(20)
</code>```

答:
There seems to be two problems:

the date prior to the left parenthesis is not wanted

the right parenthesis is sometimes missing and it needs to be inserted

1) sub These can be addressed with sub.  Match

any number of characters .* followed by

a literal left parenthesis [(] followed by

digits in a capture group (\\d+) followed by

an optional right parenthesis [)]?

and then replace that with a left parenthesis, the match to the capture group \\1 and a right parenthesis.

No packages are used.

```<code>pat <- ".*[(](\\d+)[)]?"
transform(test, Age = sub(pat, "(\\1)", Age))
</code>```

If, instead, you wanted the age as a numeric field then:

```<code>transform(test, Age = as.numeric(sub(pat, "\\1", Age)))
</code>```

2) substring/sub  Another possibility is to take the 13th character onwards which gives everything from the left parenthesis to the end of the string and insert a ) if missing.  )?$ matches a right parenthesis at the end of the string or just the end of the string if none.  That is replaced with a right parenthesis.  Again, no packages are used.

```<code>transform(test, Age = sub(")?$", ")", substring(Age, 13))
</code>```

A variation of this if we wanted a numeric Age instead would be to take everything from the 14th character and remove the final ) if present.

```<code>transform(test, Age = as.numeric(sub(")", "", substring(Age, 14))))
</code>```

3) read.table  Use read.table to read the Age field with sep = "(" and comment.char = ")" and pick off the second column read.  This will give the numeric age and we can use sprintf to surround that with parentheses.  If Age were character (as opposed to factor) then as.character(Age) could optionally be written as just Age.

Again, no packages are used.  This one does not use regular expressions.

```<code>transform(test, Age =
  sprintf("(%s)", read.table(text = as.character(Age), sep = "(", comment.char = ")")$V2)
</code>```

Note: The input in reproducible form is:

```<code>test <- data.frame(Age = c("Sep 10, 1990(27)", "Mar 26, 1987(30", "Feb 24, 1997(20)"))
</code>```

Body:
I am using the gsub() function to remove the unwanted text from the data. I just want to have the age in the brackets, not the dates of birth. However, this is in a large data set with differing birth days.

Example of the data:

Test1$Age

Sep 10, 1990(27)
Mar 26, 1987(30
Feb 24, 1997(20)

Body:
There seems to be two problems:

the date prior to the left parenthesis is not wanted

the right parenthesis is sometimes missing and it needs to be inserted

1) sub These can be addressed with sub.  Match

any number of characters .* followed by

a literal left parenthesis [(] followed by

digits in a capture group (\\d+) followed by

an optional right parenthesis [)]?

and then replace that with a left parenthesis, the match to the capture group \\1 and a right parenthesis.

No packages are used.

pat <- ".*[(](\\d+)[)]?"
transform(test, Age = sub(pat, "(\\1)", Age))

If, instead, you wanted the age as a numeric field then:

transform(test, Age = as.numeric(sub(pat, "\\1", Age)))

2) substring/sub  Another possibility is to take the 13th character onwards which gives everything from the left parenthesis to the end of the string and insert a ) if missing.  )?$ matches a right parenthesis at the end of the string or just the end of the string if none.  That is replaced with a right parenthesis.  Again, no packages are used.

transform(test, Age = sub(")?$", ")", substring(Age, 13))

A variation of this if we wanted a numeric Age instead would be to take everything from the 14th character and remove the final ) if present.

transform(test, Age = as.numeric(sub(")", "", substring(Age, 14))))

3) read.table  Use read.table to read the Age field with sep = "(" and comment.char = ")" and pick off the second column read.  This will give the numeric age and we can use sprintf to surround that with parentheses.  If Age were character (as opposed to factor) then as.character(Age) could optionally be written as just Age.

Again, no packages are used.  This one does not use regular expressions.

transform(test, Age =
  sprintf("(%s)", read.table(text = as.character(Age), sep = "(", comment.char = ")")$V2)

Note: The input in reproducible form is:

test <- data.frame(Age = c("Sep 10, 1990(27)", "Mar 26, 1987(30", "Feb 24, 1997(20)"))


问:
storing a string and manipulating it in ASM language on ATmega168V (first homework assignment)
I am trying to store a string in memory, access that string and change the lower case letters to upper case and visa versa.  What I do not understand is how to reference the address of the string and ascii value at that address.  I believe I can figure the logic out, just having problems with data and address manipulation. How do I differentiate the two?  NOTE: This is a homework coding assignment.</p>

答:
Hint. Flip the "32" bit with a xor value,0x20 to toggle case.

On the Z80 assembler it would be something like

```<code>SRC:    DB      'Press A Key To Continue', 0; Our source string
DST:    DB      'Press A Key To Continue', 0; Where we will put our string. make sure its big enough so we don't over write our program.
;load MSG+0 to working regist
;flip the 32 bit
;move the working register to DST + 0
;load MSG+1 and repeat
</code>```

Body:
Hint. Flip the "32" bit with a xor value,0x20 to toggle case.

On the Z80 assembler it would be something like

SRC:    DB      'Press A Key To Continue', 0; Our source string
DST:    DB      'Press A Key To Continue', 0; Where we will put our string. make sure its big enough so we don't over write our program.
;load MSG+0 to working regist
;flip the 32 bit
;move the working register to DST + 0
;load MSG+1 and repeat


问:
How to get data from mysql and group them in weeks, also separating by month
I have mysql database and is full of over 2 years of data.  How can I make a query in a way that it will get the result as below?:

```<code>January
   Week 1
      ...
      data rows here
      ....
   Week 2
      ...
      ...
   Week 3
      ...
      ...
   Week 4
      ...
      ...

February (same as above)
</code>```

These are the field structures:

```<code>- date (in yyyy-mm-dd format)
- job (integer autoincrement)
- person (varchar)
</code>```

答:
SELECT
    MONTH(created_datetime) AS month,
    WEEK(created_datetime) AS week,
    DATE(created_datetime) AS date,
    COUNT(id) AS count
 FROM  users
 WHERE date(created_datetime) BETWEEN '2017-05-01' AND '2017-12-31'
 GROUP BY month
 ORDER BY created_datetime

If you want records date wise that you need to use GROUP BY date.

If you want records weekly that you need to use GROUP BY week.

If you want records monthly that you need to use GROUP BY month.

Body:
I have mysql database and is full of over 2 years of data.  How can I make a query in a way that it will get the result as below?:

January
   Week 1
      ...
      data rows here
      ....
   Week 2
      ...
      ...
   Week 3
      ...
      ...
   Week 4
      ...
      ...

February (same as above)

These are the field structures:

- date (in yyyy-mm-dd format)
- job (integer autoincrement)
- person (varchar)


问:
Save sensitive data in React Native
I am building a React Native application and I need to save some sensitive data like a token and a refresh token. The obvious solution is to save that information using AsyncStorage. The problem is the security level of the AsyncStorage.

AsyncStorage provides a way to locally store tokens and data. It can
  be, in some ways, compared to a LocalStorage option. In full
  production applications, it is recommended to not access AsyncStorage
  directly, but instead, to use an abstraction layer, as AsyncStorage is
  shared with other apps using the same browser, and thus an
  ill-conceieved removal of all items from storage could impair the
  functioning of neighboring apps.

https://auth0.com/blog/adding-authentication-to-react-native-using-jwt/

In a native app, I would go for Keychain in iOS and Shared Preferences in private mode in Android.

For what I read in the documentation provided by React Native:

On iOS, AsyncStorage is backed by native code that stores small values
  in a serialized dictionary and larger values in separate files. On
  Android, AsyncStorage will use either RocksDB or SQLite based on what
  is available.

https://facebook.github.io/react-native/docs/asyncstorage.html

They never talk about the security of that data.

It is the best solution create a module for Android (that uses Shared Preferences in private mode) and another for iOS (that uses Keychain) to save the sensible data? Or it is safe to use the AsyncStorage methods provided?

答:
I really recommand you to use a library like react-native-keychain to store private data in react-native

For Android API level:

16-22 use Facebook Conceal

23+ use Android Keystore

You can use it like that:

```<code>// Generic Password, service argument optional
Keychain
  .setGenericPassword(username, password)
  .then(function() {
    console.log('Credentials saved successfully!');
  });

// service argument optional
Keychain
  .getGenericPassword()
  .then(function(credentials) {
    console.log('Credentials successfully loaded for user ' + credentials.username);
  }).catch(function(error) {
    console.log('Keychain couldn\'t be accessed! Maybe no value set?', error);
  });
</code>```

Title: Save sensitive data in React Native

Body:
I really recommand you to use a library like react-native-keychain to store private data in react-native

For Android API level:

16-22 use Facebook Conceal

23+ use Android Keystore

You can use it like that:

// Generic Password, service argument optional
Keychain
  .setGenericPassword(username, password)
  .then(function() {
    console.log('Credentials saved successfully!');
  });

// service argument optional
Keychain
  .getGenericPassword()
  .then(function(credentials) {
    console.log('Credentials successfully loaded for user ' + credentials.username);
  }).catch(function(error) {
    console.log('Keychain couldn\'t be accessed! Maybe no value set?', error);
  });


问:
Mixing futures and vectors in a for comprehension
I'd like to iterate over a vector that I get from a future.  I'd like the following to work, but it gives a type mismatch compiler error on the user <- usersToReview line.

```<code>import scala.concurrent.{Await, Future}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Await
import scala.concurrent.duration._

object Main3 {
  var counter = 0

  val fUsersToReview: Future[Vector[String]] = Future {Vector("u1", "u2", "u3")}

  def doIt(user: String): Future[Int] = {
    counter = counter + 1
    Future.successful(counter)
  }

  def main(args: Array[String]): Unit = {
    val result:Future[Vector[Int]] = for {
      usersToReview ← fUsersToReview
      user ← usersToReview
      msg_id ← doIt(user)
    } yield {
      msg_id
    }

    println(Await.result(result, 1.second))
  }
}
</code>```

The following works, but seems very clunky.  Suggestions on how to improve this?

```<code>  def main(args: Array[String]): Unit = {
    val result:Future[Vector[Int]] = (for {
      usersToReview ← fUsersToReview
    } yield {

      Future.sequence(
        for (u ← usersToReview) yield {
          doIt(u)
        }
      )
    }).flatMap(identity)

    println(Await.result(result, 1.second))
  }
}
</code>```

答:
Thanks to the insights from thinking about adrice727's answer, I've got a solution to the problem.  It involves refactoring doIt to take the vector.
 By shifting the handling of the vector to doIt, the vector comes out of the for-comprehension.  Once it handles only futures, it works as expected.

I had simplified my original post a bit, so the following includes one more level in the for-comprehension and has doIt actually do something with the data it's passed.  The background on this is that fMaintainers, fUsersToReview, and doIt are all acting on a database.

```<code>val fMaintainers: Future[Vector[String]] = Future {Vector("m1", "m2", "m3")}

val fUsersToReview: Future[Vector[String]] = Future {Vector("u1", "u2", "u3")}

def doIt(users: Vector[String], maintainers: Vector[String]): Future[Vector[(String, String)]] = {
  Future.sequence(for (u ← users) yield {
    Future.successful((u, maintainers.head))
  })
}

val result: Future[Vector[(String, String)]] = for {
  maintainers ← fMaintainers
  usersToReview ← fUsersToReview
  msg_id ← doIt(usersToReview, maintainers)
} yield {
  msg_id
}

println(Await.result(result, 1.second))
</code>```

Finally, following up on adrice727's suggestion that sometimes for-comprehensions aren't the right tool, here it is with maps:

```<code>val result:Future[Vector[(String, String)]] =
      fMaintainers.flatMap { m ⇒ fUsersToReview.flatMap { u ⇒ doIt(u, m) } }
</code>```

Body:
I'd like to iterate over a vector that I get from a future.  I'd like the following to work, but it gives a type mismatch compiler error on the user <- usersToReview line.

import scala.concurrent.{Await, Future}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Await
import scala.concurrent.duration._

object Main3 {
  var counter = 0

  val fUsersToReview: Future[Vector[String]] = Future {Vector("u1", "u2", "u3")}

  def doIt(user: String): Future[Int] = {
    counter = counter + 1
    Future.successful(counter)
  }

  def main(args: Array[String]): Unit = {
    val result:Future[Vector[Int]] = for {
      usersToReview ← fUsersToReview
      user ← usersToReview
      msg_id ← doIt(user)
    } yield {
      msg_id
    }

    println(Await.result(result, 1.second))
  }
}

The following works, but seems very clunky.  Suggestions on how to improve this?

  def main(args: Array[String]): Unit = {
    val result:Future[Vector[Int]] = (for {
      usersToReview ← fUsersToReview
    } yield {

      Future.sequence(
        for (u ← usersToReview) yield {
          doIt(u)
        }
      )
    }).flatMap(identity)

    println(Await.result(result, 1.second))
  }
}

Body:
Thanks to the insights from thinking about adrice727's answer, I've got a solution to the problem.  It involves refactoring doIt to take the vector.
 By shifting the handling of the vector to doIt, the vector comes out of the for-comprehension.  Once it handles only futures, it works as expected.

I had simplified my original post a bit, so the following includes one more level in the for-comprehension and has doIt actually do something with the data it's passed.  The background on this is that fMaintainers, fUsersToReview, and doIt are all acting on a database.

val fMaintainers: Future[Vector[String]] = Future {Vector("m1", "m2", "m3")}

val fUsersToReview: Future[Vector[String]] = Future {Vector("u1", "u2", "u3")}

def doIt(users: Vector[String], maintainers: Vector[String]): Future[Vector[(String, String)]] = {
  Future.sequence(for (u ← users) yield {
    Future.successful((u, maintainers.head))
  })
}

val result: Future[Vector[(String, String)]] = for {
  maintainers ← fMaintainers
  usersToReview ← fUsersToReview
  msg_id ← doIt(usersToReview, maintainers)
} yield {
  msg_id
}

println(Await.result(result, 1.second))

Finally, following up on adrice727's suggestion that sometimes for-comprehensions aren't the right tool, here it is with maps:

val result:Future[Vector[(String, String)]] =
      fMaintainers.flatMap { m ⇒ fUsersToReview.flatMap { u ⇒ doIt(u, m) } }


问:
How to save the order of a struct?
I created an app which randomly displays different Strings from an array. To make sure that no array gets repeated I created a struct which only shows the Strings which haven´t already been displayed.

That works pretty well, but my problem is that as soon as I switch scenes the struct gets reset although I tried to save it to user defaults.
Does someone know where I made a mistake when I tried to apply UserDefaults?

Here is my struct containing the saving methods:

```<code> struct RandomItems: Codable
{
    var items : [String]
    var seen  = 0

    init(items:[String], seen: Int)
    {
        self.items = items
        self.seen = seen
    }
    init(_ items:[String])
    { self.init(items: items, seen: 0) }

    mutating func next() -> String
    {
        let index = Int(arc4random_uniform(UInt32(items.count - seen)))
        let item  = items.remove(at:index)
        items.append(item)
        seen = (seen + 1) % items.count
        return item
    }
    func toPropertyList() -> [String: Any] {
        return [
            "items": items,
            "seen": seen]
       }
      }
override func viewDidLoad() {
    let defaults = UserDefaults.standard
    if let quotes = defaults.codable(RandomItems.self, forKey: "quotes") as? RandomItems {
        self.quotes = quotes
    }
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    NotificationCenter.default.addObserver(self, selector:Selector(("saveData:")), name: Notification.Name.UIApplicationWillTerminate, object:nil)
}
func storeQuotes() {
    // Code to save struct
    let defaults = UserDefaults.standard
    if let quotes = quotes {
        defaults.set(codable: quotes, forKey: "quotes")
    }
}
override func viewDidAppear(_ animated: Bool) {
    // Code to load the struct again after the view appears.

}

override func viewWillDisappear(_ animated: Bool) {

     storeQuotes()
}
func saveData(notification: Notification) {
    // Save your data here when app is closed
    print("Saving data...")
    storeQuotes()
  }

 }

extension UserDefaults {

func set<T: Encodable>(codable: T, forKey key: String) {
    let encoder = JSONEncoder()
    do {
        let data = try encoder.encode(codable)
        let jsonString = String(data: data, encoding: .utf8)!
        print("Saving \"\(key)\": \(jsonString)")
        self.set(jsonString, forKey: key)
    } catch {
        print("Saving \"\(key)\" failed: \(error)")
    }
  }
 func codable<T: Decodable>(_ codable: T.Type, forKey key: String) -> T? {
    guard let jsonString = self.string(forKey: key) else { return nil }
    guard let data = jsonString.data(using: .utf8) else { return nil }
    let decoder = JSONDecoder()
    print("Loading \"\(key)\": \(jsonString)")
    return try? decoder.decode(codable, from: data)
}
</code>```

答:
You can check in your viewDidLoad if you already have a value stored in UserDefaults, and you can remove your code in viewDidAppear:

```<code>override func viewDidLoad() {
    let defaults = UserDefaults.standard
    if let quotes = defaults.codable(RandomItems.self, forKey: "quotes") as? RandomItems {
        self.quotes = quotes
    }
}
</code>```

EDIT:

And if you want to store your quotes when your app moves to background:

Add the notification observer in viewWillAppear:

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    NotificationCenter.default.addObserver(self, selector: #selector(saveData), name: Notification.Name.UIApplicationDidEnterBackground, object:nil)
}

func storeQuotes() {
    // Code to save struct
    let defaults = UserDefaults.standard
    if let quotes = quotes {
        defaults.set(codable: quotes, forKey: "quotes")
    }
}

override func viewWillDisappear(_ animated: Bool) {
    // Code to save struct before the view disappears.
    storeQuotes()
}

func saveData() {
    // Save your data here when app is closed
    print("Saving data...")
    storeQuotes()
}
</code>```

Title: How to save the order of a struct?

Body:
I created an app which randomly displays different Strings from an array. To make sure that no array gets repeated I created a struct which only shows the Strings which haven´t already been displayed.

That works pretty well, but my problem is that as soon as I switch scenes the struct gets reset although I tried to save it to user defaults.
Does someone know where I made a mistake when I tried to apply UserDefaults?

Here is my struct containing the saving methods:

 struct RandomItems: Codable
{
    var items : [String]
    var seen  = 0

    init(items:[String], seen: Int)
    {
        self.items = items
        self.seen = seen
    }
    init(_ items:[String])
    { self.init(items: items, seen: 0) }

    mutating func next() -> String
    {
        let index = Int(arc4random_uniform(UInt32(items.count - seen)))
        let item  = items.remove(at:index)
        items.append(item)
        seen = (seen + 1) % items.count
        return item
    }
    func toPropertyList() -> [String: Any] {
        return [
            "items": items,
            "seen": seen]
       }
      }
override func viewDidLoad() {
    let defaults = UserDefaults.standard
    if let quotes = defaults.codable(RandomItems.self, forKey: "quotes") as? RandomItems {
        self.quotes = quotes
    }
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    NotificationCenter.default.addObserver(self, selector:Selector(("saveData:")), name: Notification.Name.UIApplicationWillTerminate, object:nil)
}
func storeQuotes() {
    // Code to save struct
    let defaults = UserDefaults.standard
    if let quotes = quotes {
        defaults.set(codable: quotes, forKey: "quotes")
    }
}
override func viewDidAppear(_ animated: Bool) {
    // Code to load the struct again after the view appears.

}

override func viewWillDisappear(_ animated: Bool) {

     storeQuotes()
}
func saveData(notification: Notification) {
    // Save your data here when app is closed
    print("Saving data...")
    storeQuotes()
  }

 }

extension UserDefaults {

func set<T: Encodable>(codable: T, forKey key: String) {
    let encoder = JSONEncoder()
    do {
        let data = try encoder.encode(codable)
        let jsonString = String(data: data, encoding: .utf8)!
        print("Saving \"\(key)\": \(jsonString)")
        self.set(jsonString, forKey: key)
    } catch {
        print("Saving \"\(key)\" failed: \(error)")
    }
  }
 func codable<T: Decodable>(_ codable: T.Type, forKey key: String) -> T? {
    guard let jsonString = self.string(forKey: key) else { return nil }
    guard let data = jsonString.data(using: .utf8) else { return nil }
    let decoder = JSONDecoder()
    print("Loading \"\(key)\": \(jsonString)")
    return try? decoder.decode(codable, from: data)
}

Body:
You can check in your viewDidLoad if you already have a value stored in UserDefaults, and you can remove your code in viewDidAppear:

override func viewDidLoad() {
    let defaults = UserDefaults.standard
    if let quotes = defaults.codable(RandomItems.self, forKey: "quotes") as? RandomItems {
        self.quotes = quotes
    }
}

EDIT:

And if you want to store your quotes when your app moves to background:

Add the notification observer in viewWillAppear:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    NotificationCenter.default.addObserver(self, selector: #selector(saveData), name: Notification.Name.UIApplicationDidEnterBackground, object:nil)
}

func storeQuotes() {
    // Code to save struct
    let defaults = UserDefaults.standard
    if let quotes = quotes {
        defaults.set(codable: quotes, forKey: "quotes")
    }
}

override func viewWillDisappear(_ animated: Bool) {
    // Code to save struct before the view disappears.
    storeQuotes()
}

func saveData() {
    // Save your data here when app is closed
    print("Saving data...")
    storeQuotes()
}


问:
github-like comment thread for each git commit
Is there a tool out there that mimicks the github feature of allowing
other developers to start a comments thread for each git commit? I find this very useful, and would like to have it in my company dev environment. We use gitosis to manage
the repo, and redmine to track issues.

Thanks!

答:
We are using gerrit for code review. It might be addressed to part of your question. But, it's pre-commit review system, so comments are truly associated with commits before they go into master.

See:
http://code.google.com/p/gerrit/


问:
Unit test with Mocha, I can not make it work
I am creating a unit test, this test consists of using the twitter API to obtain data of any profile (Name, number of tweets, followers, date of registration, etc). The point is that I'm using the Mocha library for this task, but I run into the problem, that when executing the assert, the twitter request takes more than 2 seconds (Mocha's default timeout), therefore my test always fails. Could someone give me a hand? What should I do, so that the comparison of the assert is executed after receiving all the data of the request to twitter?

code.js

```<code>class extractCode {
    verificarUsername(a) {
        if (a) {
            var nombre;
            var Twitter = require('twitter');
            var client = new Twitter({
              consumer_key: 'XSpj4nEB5IOLgIvyZXiDAhBLt',
              consumer_secret: 'dPjYUTih6n0ynt1y9C7bE0g0gyx6KSJgrGTeDEa3yH5flsdJPL',
              access_token_key: '900532686-4sOwDfOFZm1fKmtZZhSMPH04REXMjqnugTOn3o1j',
              access_token_secret: 'ghNtHt7VyjwNHXvXnZM5hFKaDH62bX7LEFqUBZ9SSb5Lg'
            });

            client.get('users/show', {screen_name: a}, function(error, response) {
              if(error) throw error;
              if(response.name) {
                nombre = true
              } else {
                nombre = false
              };
              console.log(`
                Nombre: '${response.name}'
                ID: ${response.id_str}
                Localidad: ${response.location}
                Descripción del perfil: ${response.description}
                Seguidores: ${response.followers_count}
                Sigue a: ${response.friends_count}
                Perfil creado el: ${response.created_at}\n`);
            });
            return nombre;
        }

    }
}

module.exports = extractCode;
</code>```

test/prueba.js

```<code>var assert = require('assert');
var extractCode = require('../code.js');

describe('Pruebas de perfil de Twitter', function() {
    this.timeout(5000);
    var c = new extractCode();
    it('Verifica si se le pasó un username válido', function(done) {

            assert.equal(c.verificarUsername('pedrofumero'),true, 'El username proporcionado no es válido');
            done();

    })

})
</code>```

答:
your test and code is wrong and probably 5s its not really an timeout value when testing third party api requests. I've had requests to other third party apis take more than an minute(s) to respond.

here is an basic approach rewriting your code with promises

test.js

```<code>var assert = require('assert');
var extractCode = require('./code.js');
describe('Twitter profile', function() {
    it('Twitter username verification, expect an actual response', function(done) {
        var c = new extractCode();
        c.verificarUsername('pedrofumero')
        .then(function(response){
            //console.log(response)
            done()
        })
        .catch(function(err){
          throw err;
        });
    })
    it('Twitter username verification, expect an error response', function(done) {
        var c = new extractCode();
        c.verificarUsername('')
        .then(function(response){
            //console.log(response)
            //assert.equal(response.verified,true,'Valid username');
        })
        .catch(function(err){
          assert.equal(err[0].message,'User not found.');
          done()
        });
    })
    it('Twitter username verification, expect an verified profile', function(done) {
        var c = new extractCode();
        c.verificarUsername('pedrofumero')
        .then(function(response){
            assert.equal(response.verified,true,'Valid username');
            done();
        })
        .catch(function(err){
          done(err);
        });
    })
})
</code>```

code.js

```<code>var Twitter = require('twitter');
var client = new Twitter({
  consumer_key: '',
  consumer_secret: '',
  access_token_key: '',
  access_token_secret: ''
});
class extractCode {
    verificarUsername(Username) {
        return client.get('users/show', {   screen_name: Username })
    }
}
module.exports = extractCode;
</code>```

output

```<code>Twitter profile
  √ Twitter username verification, expect an actual response (610ms)
  √ Twitter username verification, expect an error response (391ms)
  1) Twitter username verification, expect an verified profile

2 passing (1s)
1 failing

1) Twitter profile
     Twitter username verification, expect an verified profile:

    AssertionError [ERR_ASSERTION]: Valid username
    + expected - actual

    -false
    +true

    at test.js:32:11
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
</code>```

Body:
I am creating a unit test, this test consists of using the twitter API to obtain data of any profile (Name, number of tweets, followers, date of registration, etc). The point is that I'm using the Mocha library for this task, but I run into the problem, that when executing the assert, the twitter request takes more than 2 seconds (Mocha's default timeout), therefore my test always fails. Could someone give me a hand? What should I do, so that the comparison of the assert is executed after receiving all the data of the request to twitter?

code.js

class extractCode {
    verificarUsername(a) {
        if (a) {
            var nombre;
            var Twitter = require('twitter');
            var client = new Twitter({
              consumer_key: 'XSpj4nEB5IOLgIvyZXiDAhBLt',
              consumer_secret: 'dPjYUTih6n0ynt1y9C7bE0g0gyx6KSJgrGTeDEa3yH5flsdJPL',
              access_token_key: '900532686-4sOwDfOFZm1fKmtZZhSMPH04REXMjqnugTOn3o1j',
              access_token_secret: 'ghNtHt7VyjwNHXvXnZM5hFKaDH62bX7LEFqUBZ9SSb5Lg'
            });

            client.get('users/show', {screen_name: a}, function(error, response) {
              if(error) throw error;
              if(response.name) {
                nombre = true
              } else {
                nombre = false
              };
              console.log(`
                Nombre: '${response.name}'
                ID: ${response.id_str}
                Localidad: ${response.location}
                Descripción del perfil: ${response.description}
                Seguidores: ${response.followers_count}
                Sigue a: ${response.friends_count}
                Perfil creado el: ${response.created_at}\n`);
            });
            return nombre;
        }

    }
}

module.exports = extractCode;

test/prueba.js

var assert = require('assert');
var extractCode = require('../code.js');

describe('Pruebas de perfil de Twitter', function() {
    this.timeout(5000);
    var c = new extractCode();
    it('Verifica si se le pasó un username válido', function(done) {

            assert.equal(c.verificarUsername('pedrofumero'),true, 'El username proporcionado no es válido');
            done();

    })

})

Body:
your test and code is wrong and probably 5s its not really an timeout value when testing third party api requests. I've had requests to other third party apis take more than an minute(s) to respond.

here is an basic approach rewriting your code with promises

test.js

var assert = require('assert');
var extractCode = require('./code.js');
describe('Twitter profile', function() {
    it('Twitter username verification, expect an actual response', function(done) {
        var c = new extractCode();
        c.verificarUsername('pedrofumero')
        .then(function(response){
            //console.log(response)
            done()
        })
        .catch(function(err){
          throw err;
        });
    })
    it('Twitter username verification, expect an error response', function(done) {
        var c = new extractCode();
        c.verificarUsername('')
        .then(function(response){
            //console.log(response)
            //assert.equal(response.verified,true,'Valid username');
        })
        .catch(function(err){
          assert.equal(err[0].message,'User not found.');
          done()
        });
    })
    it('Twitter username verification, expect an verified profile', function(done) {
        var c = new extractCode();
        c.verificarUsername('pedrofumero')
        .then(function(response){
            assert.equal(response.verified,true,'Valid username');
            done();
        })
        .catch(function(err){
          done(err);
        });
    })
})

code.js

var Twitter = require('twitter');
var client = new Twitter({
  consumer_key: '',
  consumer_secret: '',
  access_token_key: '',
  access_token_secret: ''
});
class extractCode {
    verificarUsername(Username) {
        return client.get('users/show', {   screen_name: Username })
    }
}
module.exports = extractCode;

output

Twitter profile
  √ Twitter username verification, expect an actual response (610ms)
  √ Twitter username verification, expect an error response (391ms)
  1) Twitter username verification, expect an verified profile

2 passing (1s)
1 failing

1) Twitter profile
     Twitter username verification, expect an verified profile:

    AssertionError [ERR_ASSERTION]: Valid username
    + expected - actual

    -false
    +true

    at test.js:32:11
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)