问:
null is not an object(evaluating this.state.count)
I am facing the above mentioned error when i am trying to set a count for everytime the button is pressed. </p>

```<code>export default class ViewIdeas extends Component{
get InitialState(){
  return {
  count : 0
  }
}
render(){
    return(
   .......
 <Button transparent>
             <Icon name='ios-thumbs-up-outline' style={{fontSize:21}}
              onPress={() => this.setState({count: ++this.state.count})}/>
              <Text>{'Like' + this.state.count}</Text>
    </Button>
</code>```

答:
Please set state like this

```<code>constructor(props){
   super(props);

   this.state = {
      count: 0,
   }
}
</code>```

And then you can do this.state.count

Body:
I am facing the above mentioned error when i am trying to set a count for everytime the button is pressed.

export default class ViewIdeas extends Component{
get InitialState(){
  return {
  count : 0
  }
}
render(){
    return(
   .......
 <Button transparent>
             <Icon name='ios-thumbs-up-outline' style={{fontSize:21}}
              onPress={() => this.setState({count: ++this.state.count})}/>
              <Text>{'Like' + this.state.count}</Text>
    </Button>

Body:
Please set state like this

constructor(props){
   super(props);

   this.state = {
      count: 0,
   }
}

And then you can do this.state.count


来源: stackexchange

问:
How to write laravel model based in this query with pagination?
```<code>for ($i = 0; $i < count($keyskill); $i++) {
                    if ($i == count($keyskill) - 1) {
                        $key .= "skills like '%" . $keyskill[$i] . "%' ";
                    } else {
                        $key .= "skills like '%" . $keyskill[$i] . "%' or ";
                    }
                }
</code>```

Hear my Query is

```<code>$jobs = DB::select("SELECT * from post where ( $key ) and status=1 order by id desc");
</code>```

How to write laravel model based in this query with pagination???

答:
try this for dynamic array:</p>

```<code>Post::where(function ($query)  use ($keyskill) {
  for ($i = 0; $i < count($keyskill); $i++) {
                if ($i == 0) {
                    $query->where('skills' , 'like' ,"%$keyskill[$i]%");
                } else {
                     $query->orWhere('skills' , 'like' , "%$keyskill[$i]%");
                }
            }
})->where('status' , 1)->orderBy('id' , 'desc')->paginate(10);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
for ($i = 0; $i < count($keyskill); $i++) {
                    if ($i == count($keyskill) - 1) {
                        $key .= "skills like '%" . $keyskill[$i] . "%' ";
                    } else {
                        $key .= "skills like '%" . $keyskill[$i] . "%' or ";
                    }
                }

Hear my Query is

$jobs = DB::select("SELECT * from post where ( $key ) and status=1 order by id desc");

How to write laravel model based in this query with pagination???

Body:
try this for dynamic array:

Post::where(function ($query)  use ($keyskill) {
  for ($i = 0; $i < count($keyskill); $i++) {
                if ($i == 0) {
                    $query->where('skills' , 'like' ,"%$keyskill[$i]%");
                } else {
                     $query->orWhere('skills' , 'like' , "%$keyskill[$i]%");
                }
            }
})->where('status' , 1)->orderBy('id' , 'desc')->paginate(10);


问:
solution of Pell equation with continued fraction
we know that Pell equation is  expressed  as

which in  case of  D is not perfect square, can be approximated by continued  fraction expansion of D, for instance let  us consider such kind of equation

square root of 61  can be approximated by  following matlab code

```<code>>> b=sqrt(61);
>> format rat
>> b

b =

    1523/195
</code>```

but i have  question : how can i  assign result in two separate variable ?namely

```<code>x=1523
y=195
</code>```

from this site
https://www.quora.com/What-is-the-fast-way-to-solve-the-fundamental-solution-of-Pell-equation

i understood that solution are based on  numerator and denumerator, how  can i  assign  fraction parts to x and y  during  the code in matlab? thanks in advance

答:
While, by definition, an irrational number can never be exactly represented as a ratio of integers, it can approximately represented via such a ratio in finite precision arithmetic.  This can be done through the rat function to varying degrees of approximation:

```<code>>> [n,d] = rat(sqrt(61),1E-4);  (n/d) - sqrt(61)
ans =
   9.5152e-05
>> [n,d] = rat(sqrt(61),1E-8);  (n/d) - sqrt(61)
ans =
  -4.4218e-09
>> [n,d] = rat(sqrt(61),1E-16);  (n/d) - sqrt(61)
ans =
     0
</code>```

It is noted that the final 0 does not indicate true equality of the terms; just equality to the limits of double precision arithmetic.

Body:
we know that Pell equation is  expressed  as

which in  case of  D is not perfect square, can be approximated by continued  fraction expansion of D, for instance let  us consider such kind of equation

square root of 61  can be approximated by  following matlab code

>> b=sqrt(61);
>> format rat
>> b

b =

    1523/195

but i have  question : how can i  assign result in two separate variable ?namely

x=1523
y=195

from this site
https://www.quora.com/What-is-the-fast-way-to-solve-the-fundamental-solution-of-Pell-equation

i understood that solution are based on  numerator and denumerator, how  can i  assign  fraction parts to x and y  during  the code in matlab? thanks in advance

Body:
While, by definition, an irrational number can never be exactly represented as a ratio of integers, it can approximately represented via such a ratio in finite precision arithmetic.  This can be done through the rat function to varying degrees of approximation:

>> [n,d] = rat(sqrt(61),1E-4);  (n/d) - sqrt(61)
ans =
   9.5152e-05
>> [n,d] = rat(sqrt(61),1E-8);  (n/d) - sqrt(61)
ans =
  -4.4218e-09
>> [n,d] = rat(sqrt(61),1E-16);  (n/d) - sqrt(61)
ans =
     0

It is noted that the final 0 does not indicate true equality of the terms; just equality to the limits of double precision arithmetic.


问:
xhr is not defined | mithril js
I have recently started experimenting with Mithril js and stumbled upon a basic requirement of sending some Authorization and other headers along with the request. After reading documentation and some examples online I understood that this is how it can be done -

```<code>m.request({
  method: "GET"
  url: "/some/url/"
  config: function(xhr) {
    xhr.setRequestHeader("Authorization", "".concat("Token ", API_TOKEN));
  }
});
</code>```

My question here is where is the xhr being passed? Because this will obviously through error: Uncaught ReferenceError: xhr is not defined

I m unable to set headers. If I have to declare XMLHTTPRequest instance and use open() there then what would be the need of m.request()?

What am I doing wrong? Directions would help.

答:
Actually, all you need to do (according to the Mithril documentation) to set custom headers is this:</p>

```<code>m.request({
    method: "GET",
    url: "/some/url/",
    headers: {
        "Authorization": "Token <token_placeholder>",
    },
})
</code>```

Title: xhr is not defined | mithril js

Body:
I have recently started experimenting with Mithril js and stumbled upon a basic requirement of sending some Authorization and other headers along with the request. After reading documentation and some examples online I understood that this is how it can be done -

m.request({
  method: "GET"
  url: "/some/url/"
  config: function(xhr) {
    xhr.setRequestHeader("Authorization", "".concat("Token ", API_TOKEN));
  }
});

My question here is where is the xhr being passed? Because this will obviously through error: Uncaught ReferenceError: xhr is not defined

I m unable to set headers. If I have to declare XMLHTTPRequest instance and use open() there then what would be the need of m.request()?

What am I doing wrong? Directions would help.

Body:
Actually, all you need to do (according to the Mithril documentation) to set custom headers is this:

m.request({
    method: "GET",
    url: "/some/url/",
    headers: {
        "Authorization": "Token <token_placeholder>",
    },
})


问:
HttpWebRequest for ShoutCast on Windows Phone7
I tring to stream shoutcast stream in my window phone 7 app

I start an async HttpWebRequest like this

```<code>//Init Request

HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://ACommonoShoutCastUrl:8000");

myHttpWebRequest.Headers["Icy-MetaData"] = "1";

myHttpWebRequest.UserAgent = "WinampMPEG/5.09";

myHttpWebRequest.AllowReadStreamBuffering = true;

//Call

 // Create an instance of the RequestState and assign the previous myHttpWebRequest object to its request field.

RequestState myRequestState = new RequestState();

 myRequestState.request = myHttpWebRequest;

 // Start the asynchronous request.

 IAsyncResult result = (IAsyncResult)myHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallBack), myRequestState);
</code>```

The problem is that the CallBack->RespCallBack is never called...

This code worked for me normally in other environments but not on the phone...

I tired also to use WebClient that seems to stream data,

the problem in this case is that it never call the end  OpenReadCompleted because of endelss shoutcast stream

Thanks for support

any help would be appreciated

答:
The callback gets called if you disable read stream buffering:</p>

```<code>webRequest.AllowReadStreamBuffering = false;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I tring to stream shoutcast stream in my window phone 7 app

I start an async HttpWebRequest like this

//Init Request

HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://ACommonoShoutCastUrl:8000");

myHttpWebRequest.Headers["Icy-MetaData"] = "1";

myHttpWebRequest.UserAgent = "WinampMPEG/5.09";

myHttpWebRequest.AllowReadStreamBuffering = true;

//Call

 // Create an instance of the RequestState and assign the previous myHttpWebRequest object to its request field.

RequestState myRequestState = new RequestState();

 myRequestState.request = myHttpWebRequest;

 // Start the asynchronous request.

 IAsyncResult result = (IAsyncResult)myHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallBack), myRequestState);

The problem is that the CallBack->RespCallBack is never called...

This code worked for me normally in other environments but not on the phone...

I tired also to use WebClient that seems to stream data,

the problem in this case is that it never call the end  OpenReadCompleted because of endelss shoutcast stream

Thanks for support

any help would be appreciated

Body:
The callback gets called if you disable read stream buffering:

webRequest.AllowReadStreamBuffering = false;


问:
How to pass value to another activity with id of the option clicked from dialog box
I have a ListView which is display several String when i click on a categories it will call and pop out a dialog options menu which has the options of English, Hindi and Cancel. The onClicklistener will be triggered when the user Click one of the category from the Listview such as "Novel", "Book" or "Plays".
What I want to do here is, when the user clicks "Book" and choose language English option, I want to pass category_id and language_id to the next activity.the category_id and language_id are the json object that i got from the server response. So I need to get the category_id selected from listview and pass it to the next activity along with the language_id as seleceted in dialog box.

if this is possible then how? Thanks in advance for your help.

```<code>holder.imageView.setImageUrl(Config.TAG_IMAGE_URL+category.getImage(), imageLoader);
    holder.textViewName.setText(category.getName());
    category_id = category.getId();
    language_id = category.getLanguage_id();
    holder.imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            handleLanguageDialog();

            }

    });

}

private AlertDialog handleLanguageDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("Select Language")
            .setItems(R.array.lang, new DialogInterface.OnClickListener()                 {
                public void onClick(DialogInterface dialog, int which) {
                    // The 'which' argument contains the index position
                    // of the selected item
                    switch(which)
                    {
                        case 0:// English

                            break;
                        case 1://Bengali

                            break;
                    }
                }
            });
    return builder.create().show();
}
</code>```

categ.java

```<code>    private String id;
private String name;
private String description;
private String image;
private String parent_id;
private String language_id;
private String created;
private String modified;

@Override
public String toString() {
    return "Categ{" +
            "id='" + id + '\'' +
            ", name='" + name + '\'' +
            ", description='" + description + '\'' +
            ", image='" + image + '\'' +
            ", parent_id='" + parent_id + '\'' +
            ", language_id='" + language_id + '\'' +
            ", created='" + created + '\'' +
            ", modified='" + modified + '\'' +
            '}';
}

public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description = description;
}
public String getImage() {
    return image;
}
public void setImage(String image) {
    this.image = image;
}
public String getParent_id() {
    return parent_id;
}
public void setParent_id(String parent_id) {
    this.parent_id = parent_id;
}
public String getLanguage_id() {
    return language_id;
}
public void setLanguage_id(String language_id) {
    this.language_id = language_id;
}
public String getCreated() {
    return created;
}
public void setCreated(String created) {
    this.created = created;
}
public String getModified() {
    return modified;
}
public void setModified(String modified) {
    this.modified = modified;
}
</code>```

}

答:
Pass like this inside your switch case</p>

```<code>case 0:
Intent intent = new Intent(YourCurrentActivity.this, Destination.class);
intent.putExtra("category_key", category_id);
intent.putExtra("language_key", language_id);
startActivity(intent);
</code>```

Body:
I have a ListView which is display several String when i click on a categories it will call and pop out a dialog options menu which has the options of English, Hindi and Cancel. The onClicklistener will be triggered when the user Click one of the category from the Listview such as "Novel", "Book" or "Plays".
What I want to do here is, when the user clicks "Book" and choose language English option, I want to pass category_id and language_id to the next activity.the category_id and language_id are the json object that i got from the server response. So I need to get the category_id selected from listview and pass it to the next activity along with the language_id as seleceted in dialog box.

if this is possible then how? Thanks in advance for your help.

holder.imageView.setImageUrl(Config.TAG_IMAGE_URL+category.getImage(), imageLoader);
    holder.textViewName.setText(category.getName());
    category_id = category.getId();
    language_id = category.getLanguage_id();
    holder.imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            handleLanguageDialog();

            }

    });

}

private AlertDialog handleLanguageDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("Select Language")
            .setItems(R.array.lang, new DialogInterface.OnClickListener()                 {
                public void onClick(DialogInterface dialog, int which) {
                    // The 'which' argument contains the index position
                    // of the selected item
                    switch(which)
                    {
                        case 0:// English

                            break;
                        case 1://Bengali

                            break;
                    }
                }
            });
    return builder.create().show();
}

categ.java

    private String id;
private String name;
private String description;
private String image;
private String parent_id;
private String language_id;
private String created;
private String modified;

@Override
public String toString() {
    return "Categ{" +
            "id='" + id + '\'' +
            ", name='" + name + '\'' +
            ", description='" + description + '\'' +
            ", image='" + image + '\'' +
            ", parent_id='" + parent_id + '\'' +
            ", language_id='" + language_id + '\'' +
            ", created='" + created + '\'' +
            ", modified='" + modified + '\'' +
            '}';
}

public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description = description;
}
public String getImage() {
    return image;
}
public void setImage(String image) {
    this.image = image;
}
public String getParent_id() {
    return parent_id;
}
public void setParent_id(String parent_id) {
    this.parent_id = parent_id;
}
public String getLanguage_id() {
    return language_id;
}
public void setLanguage_id(String language_id) {
    this.language_id = language_id;
}
public String getCreated() {
    return created;
}
public void setCreated(String created) {
    this.created = created;
}
public String getModified() {
    return modified;
}
public void setModified(String modified) {
    this.modified = modified;
}

}

Body:
Pass like this inside your switch case

case 0:
Intent intent = new Intent(YourCurrentActivity.this, Destination.class);
intent.putExtra("category_key", category_id);
intent.putExtra("language_key", language_id);
startActivity(intent);


问:
Load new a new component onKeyPress - reactjs
I'm trying to load a new component i have made when i press the button 'Enter'. I have implemented the onKeyPress function successfully as follows.

```<code>    class SearchBar extends Component {

        constructor(props) {

            super(props);

            this.handleKeyPress = this.handleKeyPress.bind(this);

        }

        handleKeyPress(e) {

            if (e.key === 'Enter') {

                console.log("load new page");

            }
        }

        render() {

            return (

                <div className="search_bar_div">

                    <div className="search_bar_internal_div">

                        {/* Search bar for desktop and tablets */}
                        <span className="Rev_logo">Revegator</span>

                        <input type="search" placeholder="Search here" className="search_bar"
                               onKeyPress={this.handleKeyPress}/>

                    </div>

                 </div>
}
</code>```

I get the console log correctly but the problem i have is how to load the component when i press Enter.

答: How are you handling the route in your Router definitions in the index? It might not work if you don't have a parent route that then renders it's children, rather than having just a bunch of named routes. </p>

Body:
I'm trying to load a new component i have made when i press the button 'Enter'. I have implemented the onKeyPress function successfully as follows.

    class SearchBar extends Component {

        constructor(props) {

            super(props);

            this.handleKeyPress = this.handleKeyPress.bind(this);

        }

        handleKeyPress(e) {

            if (e.key === 'Enter') {

                console.log("load new page");

            }
        }

        render() {

            return (

                        {/* Search bar for desktop and tablets */}
                        Revegator

                        <input type="search" placeholder="Search here" className="search_bar"
                               onKeyPress={this.handleKeyPress}/>

}

I get the console log correctly but the problem i have is how to load the component when i press Enter.


答:
```<code> Intent intent = new Intent(SourceActivity.this,destinationAvtivity.java);
    intent.putExtra("category_id",109);
    startActivity(theintent);
</code>```

Title: How to pass value to another activity with id of the option clicked from dialog box


问:
Has anyone found a workaround for nesting views in React Native on Android?
Hey I was wondering if there was some kind of workaround for nesting views on React Native on android, it seems that things like

class BlueIsCool extends Component {
  render() {
    return (
      <Text>
        There is a blue square
        <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
        in between my text.
      </Text>
    );
  }
}

is not possible on Android. Is there any way to do something like this on Android using React Native?

答:
You may simply do</p>

```<code><View>
    <Text>
        There is a blue square
    </Text>
    <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
    <Text>
        in between my text.
    </Text>
</View>
</code>```

Body:
You may simply do

<View>
    <Text>
        There is a blue square
    </Text>
    <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
    <Text>
        in between my text.
    </Text>
</View>


问:
Is there an equivalent for getch() in Scala?
I'm looking for a function in Scala that has similar functionality to getch. While using the console, I'd like to have my program display information based on what characters the user inputs (for example, if I was displaying a text, hitting n would show the next page, and p the previous). Right now I'm using readLine or readChar, but they require the user to hit Enter after each input, a bit annoying. Plus, in Eclipse plug-in's interpreter, the input character is shown, although I guess that might be unavoidable.</p>

答:
Use StdIn lib:</p>

```<code>    StdIn.readChar()
</code>```

Body:
Use StdIn lib:

    StdIn.readChar()


问:
How do I plot a bar graph using Pandas?
I have pandas data frame like this

```<code>a  b  c  d  e  f  label
1  3  4  5  6  7    1
2  2  5  7  5  7    0
4  7  9  0  8  7    1
6  9  4  7  3  8    1
7  0  9  8  7  6    0
</code>```

I want a bar graph which looks something like this - :

I have tried using hist() function from pandas but I am not able to figure out how do I include label in the bar graph to get the following graph like the one in the image.

答:
I think you need pivot with counting by cumcount
and last call DataFrame.plot.bar:

```<code>df = pd.pivot(index=df.groupby('label').cumcount(), columns=df.label, values=df.a).fillna(0)
print (df)
label    0    1
0      2.0  1.0
1      7.0  4.0
2      0.0  6.0

df.plot.bar()
</code>```

Or maybe need aggregate size with reshape by unstack:

```<code>df = df.groupby(['label', 'a']).size().unstack(0, fill_value=0)

df.plot.bar()
</code>```

Using piRSquared data for better sample:

Title: How do I plot a bar graph using Pandas?

Body:
I have pandas data frame like this

a  b  c  d  e  f  label
1  3  4  5  6  7    1
2  2  5  7  5  7    0
4  7  9  0  8  7    1
6  9  4  7  3  8    1
7  0  9  8  7  6    0

I want a bar graph which looks something like this - :

I have tried using hist() function from pandas but I am not able to figure out how do I include label in the bar graph to get the following graph like the one in the image.

Body:
I think you need pivot with counting by cumcount
and last call DataFrame.plot.bar:

df = pd.pivot(index=df.groupby('label').cumcount(), columns=df.label, values=df.a).fillna(0)
print (df)
label    0    1
0      2.0  1.0
1      7.0  4.0
2      0.0  6.0

df.plot.bar()

Or maybe need aggregate size with reshape by unstack:

df = df.groupby(['label', 'a']).size().unstack(0, fill_value=0)

df.plot.bar()

Using piRSquared data for better sample:


问:
No legal conversion to 'this' pointer
Please take a look at this code and run it:

I'm getting very strange error:

Error   1   error C2663: 'Allocator::allocate_help' : 2 overloads have no legal conversion for 'this' pointer

```<code>template<class FailureSignal>
class Allocator
{
private:
    template<class Exception,class Argument>
    void allocate_help(const Argument& arg,Int2Type<true>)
    {
    }

    template<class Exception,class Argument>
    std::nullptr_t allocate_help(const Argument& arg,Int2Type<false>)
    {
        return nullptr;
    }

public:
    template<class T>
    void Allocate(signed long int nObjects,T** ptr = 0)const
    {
    allocate_help<std::bad_alloc>(1,Int2Type<true>());
    }

};

int _tmain(int argc, _TCHAR* argv[])
{
    Allocator<int> all;
    all.Allocate<int>(1);
    return 0;
}
</code>```

I absolutely do not understand this err msg. Hope someone can help me with this. Thank you.

答: I noticed Allocate is declared const but allocate_help is not - could that be related to the issue?

Title: No legal conversion to 'this' pointer

Body:
Please take a look at this code and run it:

I'm getting very strange error:

Error   1   error C2663: 'Allocator::allocate_help' : 2 overloads have no legal conversion for 'this' pointer

template<class FailureSignal>
class Allocator
{
private:
    template<class Exception,class Argument>
    void allocate_help(const Argument& arg,Int2Type<true>)
    {
    }

    template<class Exception,class Argument>
    std::nullptr_t allocate_help(const Argument& arg,Int2Type<false>)
    {
        return nullptr;
    }

public:
    template<class T>
    void Allocate(signed long int nObjects,T** ptr = 0)const
    {
    allocate_help<std::bad_alloc>(1,Int2Type<true>());
    }

};

int _tmain(int argc, _TCHAR* argv[])
{
    Allocator<int> all;
    all.Allocate<int>(1);
    return 0;
}

I absolutely do not understand this err msg. Hope someone can help me with this. Thank you.


问:
Mongoose - Independent Unique Constraints
I am trying to get two independent unique constraints on one Schema to work but...

```<code>var Game = new Schema({
    name: String,
    shortName: String
})
Game.index({ name: 1, shortName: 1 }, { unique: true })
</code>```

... always creates a compound index which makes the following table valid:

```<code>name: "Foo", shortName: "Bar";
name: "Foo", shortName: "Foo";
</code>```

Is there any way to make those unique contraints independent?

答:
from unique index documentation :

You can also enforce a unique constraint on compound indexes. These
  indexes enforce uniqueness for the combination of index keys and not
  for either key individually.

so to achieve this you'll need to create a unique index on each field, like this:

var Game = new Schema(
  {
    name: { type: String, unique: true },
    shortName: { type: String, unique: true }
  }
)
```

Body:
I am trying to get two independent unique constraints on one Schema to work but...

var Game = new Schema({
    name: String,
    shortName: String
})
Game.index({ name: 1, shortName: 1 }, { unique: true })

... always creates a compound index which makes the following table valid:

name: "Foo", shortName: "Bar";
name: "Foo", shortName: "Foo";

Is there any way to make those unique contraints independent?


问:
How to decrypt in Python?
I am trying to decrypt a file in Python that I encrypted with another program. Some letters are correctly decrypted while others are not. I am not sure what is going on. All I essentially did was reverse the code for the decryption files. I think it has to do with the way it is iterating through the text, but I am not sure how to fix it.

Here is my decryption code:

```<code>decryption_library = {'%':'A','9':'a','@':'B','#':'b','1':'C','2':'c','3':'D','4':'d',
                      '5':'E','6':'e','7':'F','8':'f','0':'G','}':'g','{':'H',']':'h','[':'I',',':'i',
                      '.':'J','>':'j','<':'K','/':'k','0':'L','\-':'l','\"':'M',':':'m',';':'N',
                      '+':'n','$':'O','-':'o','$':'Q','%':'q','^':'R','&':'r','*':'S',
                      '(':'s',')':'T','~':'t','`':'U','5':'u','\\':'V','+':'v','=':'W','7':'w',
                      '~':'X',')':'x','2':'Y','*':'y',']':'Z','8':'z'}

orig_file = open('ENCRYPTED_Plain_Text_File.txt','r')

file_read = orig_file.read()

orig_file.close()

encrypt_file = open('DECRYPTED_Plain_Text_File.txt','w')

for ch in file_read:
    if ch in decryption_library:
        encrypt_file.write(decryption_library[ch])
    else:
        encrypt_file.write(ch)

encrypt_file.close()

encrypt_file = open('ENCRYPTED_Plain_Text_File.txt','r')

file_read = encrypt_file.read()

encrypt_file.close()

codes_items = decryption_library.items()

for ch in file_read:
    if not ch in decryption_library.values() or ch == '.' or ch == ',' or ch == '!':
        print(ch)
    else:
        for k,v in codes_items:
            if ch == v and ch != '.':
                print(k,end='')
</code>```

Here is the encrypted text:

```<code>)]6 ^-94 ;-~ )9/6+
@2 ^$@5^) 7^$*)
)7- &-94( 4,+6&}64 ,+ 9 *6\-\--7 7--4,
%+4 (-&&* [ 2-5\-4 +-~ ~&9+6\- #-~]
%+4 #6 -+6 ~&9+6\-6&, \--+} [ (~--4
%+4 \---/64 4-7+ -+6 9( 89& 9( [ 2-5\-4
)- 7]6&6 ,~ #6+~ ,+ ~]6 5+46&}&-7~];
</code>```

Here is what it should be:

```<code>The Road Not Taken
BY ROBERT FROST
Two roads diverged in a yellow wood,
And sorry I could not travel both
And be one traveler, long I stood
And looked down one as far as I could
To where it bent in the undergrowth;
</code>```

Here is what it decrypts to:

```<code>xZe Road NoX xakev
BY RQBuRx wRQyx
xwo roads diverged iv a yeVoVoow woodi
qvd sorry I YouVod voX XraveVo boXZ
qvd be ove XraveVoeri Voovg I sXood
qvd Voooked dowv ove as zar as I YouVod
xo wZere iX bevX iv XZe uvdergrowXZN
</code>```

答: Your decryption_library is not correct. F.e for index ')' you have value 'T' and also 'x'</p>

Title: How to decrypt in Python?

Body:
I am trying to decrypt a file in Python that I encrypted with another program. Some letters are correctly decrypted while others are not. I am not sure what is going on. All I essentially did was reverse the code for the decryption files. I think it has to do with the way it is iterating through the text, but I am not sure how to fix it.

Here is my decryption code:

decryption_library = {'%':'A','9':'a','@':'B','#':'b','1':'C','2':'c','3':'D','4':'d',
                      '5':'E','6':'e','7':'F','8':'f','0':'G','}':'g','{':'H',']':'h','[':'I',',':'i',
                      '.':'J','>':'j','<':'K','/':'k','0':'L','\-':'l','\"':'M',':':'m',';':'N',
                      '+':'n','$':'O','-':'o','$':'Q','%':'q','^':'R','&':'r','*':'S',
                      '(':'s',')':'T','~':'t','`':'U','5':'u','\\':'V','+':'v','=':'W','7':'w',
                      '~':'X',')':'x','2':'Y','*':'y',']':'Z','8':'z'}

orig_file = open('ENCRYPTED_Plain_Text_File.txt','r')

file_read = orig_file.read()

orig_file.close()

encrypt_file = open('DECRYPTED_Plain_Text_File.txt','w')

for ch in file_read:
    if ch in decryption_library:
        encrypt_file.write(decryption_library[ch])
    else:
        encrypt_file.write(ch)

encrypt_file.close()

encrypt_file = open('ENCRYPTED_Plain_Text_File.txt','r')

file_read = encrypt_file.read()

encrypt_file.close()

codes_items = decryption_library.items()

for ch in file_read:
    if not ch in decryption_library.values() or ch == '.' or ch == ',' or ch == '!':
        print(ch)
    else:
        for k,v in codes_items:
            if ch == v and ch != '.':
                print(k,end='')

Here is the encrypted text:

)]6 ^-94 ;-~ )9/6+
@2 ^$@5^) 7^$*)
)7- &-94( 4,+6&}64 ,+ 9 *6\-\--7 7--4,
%+4 (-&&* [ 2-5\-4 +-~ ~&9+6\- #-~]
%+4 #6 -+6 ~&9+6\-6&, \--+} [ (~--4
%+4 \---/64 4-7+ -+6 9( 89& 9( [ 2-5\-4
)- 7]6&6 ,~ #6+~ ,+ ~]6 5+46&}&-7~];

Here is what it should be:

The Road Not Taken
BY ROBERT FROST
Two roads diverged in a yellow wood,
And sorry I could not travel both
And be one traveler, long I stood
And looked down one as far as I could
To where it bent in the undergrowth;

Here is what it decrypts to:

xZe Road NoX xakev
BY RQBuRx wRQyx
xwo roads diverged iv a yeVoVoow woodi
qvd sorry I YouVod voX XraveVo boXZ
qvd be ove XraveVoeri Voovg I sXood
qvd Voooked dowv ove as zar as I YouVod
xo wZere iX bevX iv XZe uvdergrowXZN


问:
The proper implementation and using of custom char streams with ANTLR >= 4.7
In ANTLR 4.6 and earlier the following code works fine:

```<code>String code = readFile(args[0]);
ANTLRCustomStream codeStream = new ANTLRCustomStream(code);
MyLexer lexer = new MyLexer(codeStream);
</code>```

I use a CaseInsensitiveInputStream.java for char case ignoring by way of ANTLRCustomStream.

But how can I use case insensitive input stream in ANTLR of version 4.7 and later? ANTLRInputStream is deprecated and I don't want to use it.

```<code>CharStream codeStream = CharStreams.fromFileName(args[0]);
// customCharStream here
MyLexer lexer = new MyLexer(customCharStream);
</code>```

答:
Unfortunately, the CharStreams interface does not allow to use custom streams. You have to create your custom stream just like before (via new CaseInsensitiveInputStream(...)). The CharStreams interfaces is only of limited use (to create optimized streams for standard cases).

Btw. I'd rather recommend to use the typical A: [aA]; B: [bB]; .. approach to implement case insensitivity. That lowercasing trick is just a hack that doesn't work for full Unicode input (e.g. some uppercass letters can have multiple lower case variants). Uppercasing however also does not help here (e.g. in german uppercasing Straße becomes STRASSE).

In general it's very tricky to implement a truly case insensitive parsing for full Unicode input, as it requires to case fold both input and grammar tokens to be able to compare them.

Body:
In ANTLR 4.6 and earlier the following code works fine:

String code = readFile(args[0]);
ANTLRCustomStream codeStream = new ANTLRCustomStream(code);
MyLexer lexer = new MyLexer(codeStream);

I use a CaseInsensitiveInputStream.java for char case ignoring by way of ANTLRCustomStream.

But how can I use case insensitive input stream in ANTLR of version 4.7 and later? ANTLRInputStream is deprecated and I don't want to use it.

CharStream codeStream = CharStreams.fromFileName(args[0]);
// customCharStream here
MyLexer lexer = new MyLexer(customCharStream);


问:
Lower Case Certain Words R
I need to convert certain words to lower case. I am working with a list of movie titles, where prepositions and articles are normally lower case if they are not the first word in the title. If I have the vector:

movies = c('The Kings Of Summer', 'The Words', 'Out Of The Furnace', 'Me And Earl And The Dying Girl')

What I need is this:

movies_updated = c('The Kings of Summer', 'The Words', 'Out of the Furnace', 'Me and Earl and the Dying Girl')

Is there an elegant way to do this without using a long series of gsub(), as in:

```<code>movies_updated = gsub(' In ', ' in ', movies)
movies_updated = gsub(' In', ' in', movies_updated)
movies_updated = gsub(' Of ', ' of ', movies)
movies_updated = gsub(' Of', ' of', movies_updated)
movies_updated = gsub(' The ', ' the ', movies)
movies_updated = gsub(' the', ' the', movies_updated)
</code>```

And so on.

答:
In effect, it appears that you are interested in converting your text to title case. This can be easily achieved with use of the stringi package, as shown below:

```<code>>> stringi::stri_trans_totitle(c('The Kings of Summer', 'The Words', 'Out of the Furnace'))
[1] "The Kings Of Summer" "The Words"           "Out Of The Furnace"
</code>```

Alternative approach would involve making use of the toTitleCase function available in the the tools package:

```<code>>> tools::toTitleCase(c('The Kings of Summer', 'The Words', 'Out of the Furnace'))
[1] "The Kings of Summer" "The Words"           "Out of the Furnace"
</code>```

Title: Lower Case Certain Words R

Body:
I need to convert certain words to lower case. I am working with a list of movie titles, where prepositions and articles are normally lower case if they are not the first word in the title. If I have the vector:

movies = c('The Kings Of Summer', 'The Words', 'Out Of The Furnace', 'Me And Earl And The Dying Girl')

What I need is this:

movies_updated = c('The Kings of Summer', 'The Words', 'Out of the Furnace', 'Me and Earl and the Dying Girl')

Is there an elegant way to do this without using a long series of gsub(), as in:

movies_updated = gsub(' In ', ' in ', movies)
movies_updated = gsub(' In', ' in', movies_updated)
movies_updated = gsub(' Of ', ' of ', movies)
movies_updated = gsub(' Of', ' of', movies_updated)
movies_updated = gsub(' The ', ' the ', movies)
movies_updated = gsub(' the', ' the', movies_updated)

And so on.

Body:
In effect, it appears that you are interested in converting your text to title case. This can be easily achieved with use of the stringi package, as shown below:

>> stringi::stri_trans_totitle(c('The Kings of Summer', 'The Words', 'Out of the Furnace'))
[1] "The Kings Of Summer" "The Words"           "Out Of The Furnace"

Alternative approach would involve making use of the toTitleCase function available in the the tools package:

>> tools::toTitleCase(c('The Kings of Summer', 'The Words', 'Out of the Furnace'))
[1] "The Kings of Summer" "The Words"           "Out of the Furnace"


问:
SELECT COUNT Per Date and Type SQL Server 2012
I have an SQL Query below.

```<code>SELECT sched_date, sched_name, employee_name from tbl_schedule
</code>```

It returns this result:

```<code>    sched_date    sched_name              employee_name

    2017-04-01    09:00 AM - 06:00 PM     M.G.Cave
    2017-04-01    09:00 AM - 06:00 PM     L.C.Manalo
    2017-04-01    11:00 AM - 8:00 PM      R.M.Jakosalem
    2017-04-01    11:00 AM - 8:00 PM      S.D.Dela Cruz
    2017-04-02    Rest Day                M.G.Cave
    2017-04-02    Rest Day                L.C.Manalo
    2017-04-02    Rest Day                R.M.Jakosalem
    2017-04-02    Rest Day                S.D.Dela Cruz
</code>```

I want the employees to be counted per date and per schedule. My desired result is:

```<code>    2017-04-01    09:00 AM - 06:00 PM     2 employees
    2017-04-01    11:00 AM - 8:00 PM      2 employees
    2017-04-02    Rest Day                4 employees
</code>```

Thank you in advance.

答:
Try below query :</p>

```<code> SELECT *
 FROM
 (
    SELECT sched_date, sched_name, COUNT(*) AS employees
    FROM tbl_schedule
    GROUP BY sched_date,sched_name
 ) A
</code>```

Body:
I have an SQL Query below.

SELECT sched_date, sched_name, employee_name from tbl_schedule

It returns this result:

    sched_date    sched_name              employee_name

    2017-04-01    09:00 AM - 06:00 PM     M.G.Cave
    2017-04-01    09:00 AM - 06:00 PM     L.C.Manalo
    2017-04-01    11:00 AM - 8:00 PM      R.M.Jakosalem
    2017-04-01    11:00 AM - 8:00 PM      S.D.Dela Cruz
    2017-04-02    Rest Day                M.G.Cave
    2017-04-02    Rest Day                L.C.Manalo
    2017-04-02    Rest Day                R.M.Jakosalem
    2017-04-02    Rest Day                S.D.Dela Cruz

I want the employees to be counted per date and per schedule. My desired result is:

    2017-04-01    09:00 AM - 06:00 PM     2 employees
    2017-04-01    11:00 AM - 8:00 PM      2 employees
    2017-04-02    Rest Day                4 employees

Thank you in advance.

Body:
Try below query :

 SELECT *
 FROM
 (
    SELECT sched_date, sched_name, COUNT(*) AS employees
    FROM tbl_schedule
    GROUP BY sched_date,sched_name
 ) A


问:
C++ usage: what does " *(new int); " do?
I saw a usage of the * operator in front of the new operator. What does it do?

```<code>int x= *(new int);
</code>```

答:
The expression new int creates an object of type int in allocated memory and returns a pointer to said object. Because no initializer is specified, the object is default-initialized and therefore has an indeterminate value.

The expression int x = *(new int) initializes x with the value of the object referenced by the pointer returned by new int. However, accessing indeterminate values in this way is undefined behaviour. Since standard imposes no requirements on the behaviour of programs containing undefined behaviour, any program containing the expression int x = *(new int) could, in theory, do anything at all.

If your were to initialize the object created by the new expression (e.g. new int()), then x would have whatever value you initialized the original object with. However, since you didn't store the pointer to the original object, there is no way to destroy the object using delete, so you have a memory leak.

Body:
I saw a usage of the * operator in front of the new operator. What does it do?

int x= *(new int);


问:
Strange vim warnings
I'm new to vim, but have been doing my best to get it working reasonably well. However, at some point I started getting this whenever I open VIM:

```<code>!  <D-v>         <C-R>*
i  jk          * <Esc>
</code>```

I then <enter> and get on with my work, but I can't seem to find any documentation on what exactly vim is complaining about. Any insights are appreciated!
Running vim 8.0.515 on xterm/iterm2/macOS Sierra.

Edit: this is my .vimrc file:

```<code>set nocompatible              " required

set splitright
filetype off                  " required
set title
set encoding=utf-8

"split navigations
nnoremap <C-J> <C-W><C-J>
nnoremap <C-K> <C-W><C-K>
nnoremap <C-L> <C-W><C-L>
nnoremap <C-H> <C-W><C-H>

" numbers
set nu

" language
set langmenu=en_US.UTF-8
language messages en_US.UTF-8

" remap jk to escape
inoremap jk <esc>

inoremap
" set leader to ,
let mapleader=","

" nerdtree
inoremap <C-n> :NERDTreeToggle<CR>
vnoremap <C-n> :NERDTreeToggle<CR>
nnoremap <C-n> :NERDTreeToggle<CR>

" save
vnoremap <leader>w <esc>:w<cr>
inoremap <leader>w <esc>:w<cr>
nnoremap <leader>w :w<cr>

" save and quit
vnoremap <leader>q <esc>:wq<cr>
inoremap <leader>q <esc>:wq<cr>
nnoremap <leader>q :wq<cr>

" open .vimrc
vnoremap <leader>v <esc>:e ~/.vimrc<cr>
inoremap <leader>v <esc>:e ~/.vimrc<cr>
nnoremap <leader>v :e ~/.vimrc<cr>

" open supercollider.snippets
vnoremap <leader>s <esc>:e  ~/.vim/mysnippets/UltiSnips/supercollider.snippets<cr
inoremap <leader>s <esc>:e ~/.vim/mysnippets/UltiSnips/supercollider.snippets<cr>
nnoremap <leader>s :e ~/.vim/mysnippets/UltiSnips/supercollider.snippets<cr>

" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()

" plugins
Plugin 'gmarik/Vundle.vim'
Plugin 'scrooloose/nerdtree'
Plugin 'supercollider/scvim'
Plugin 'SirVer/ultisnips'
Plugin 'honza/vim-snippets'
Plugin 'tpope/vim-surround'
Plugin 'vim-airline/vim-airline'
Plugin 'vim-airline/vim-airline-themes'

" All of your Plugins must be added before the following line
call vundle#end()            " required
filetype plugin indent on    " required
syntax on

let g:sclangTerm = "open -a iTerm.app"

let g:UltiSnipsExpandTrigger="<tab>"
let g:UltiSnipsJumpForwardTrigger="<c-b>"
let g:UltiSnipsJumpBackwardTrigger="<c-z>"
let g:UltiSnipsSnippetDirectories=["/Users/kennethflak/mysnippets"]
" If you want :UltiSnipsEdit to split your window.
let g:UltiSnipsEditSplit="vertical"
let g:airline_theme='term'
let g:NERDTreeNotificationThreshold = 500
</code>```

答: There is a dangling (misplaced) 'innoremap' on the line just after innoremap jk <esc> which is causing it to echo that on vim launch.

Title: Strange vim warnings

Body:
I'm new to vim, but have been doing my best to get it working reasonably well. However, at some point I started getting this whenever I open VIM:

!  <D-v>         <C-R>*
i  jk          * <Esc>

I then <enter> and get on with my work, but I can't seem to find any documentation on what exactly vim is complaining about. Any insights are appreciated!
Running vim 8.0.515 on xterm/iterm2/macOS Sierra.

Edit: this is my .vimrc file:

set nocompatible              " required

set splitright
filetype off                  " required
set title
set encoding=utf-8

"split navigations
nnoremap <C-J> <C-W><C-J>
nnoremap <C-K> <C-W><C-K>
nnoremap <C-L> <C-W><C-L>
nnoremap <C-H> <C-W><C-H>

" numbers
set nu

" language
set langmenu=en_US.UTF-8
language messages en_US.UTF-8

" remap jk to escape
inoremap jk <esc>

inoremap
" set leader to ,
let mapleader=","

" nerdtree
inoremap <C-n> :NERDTreeToggle<CR>
vnoremap <C-n> :NERDTreeToggle<CR>
nnoremap <C-n> :NERDTreeToggle<CR>

" save
vnoremap <leader>w <esc>:w<cr>
inoremap <leader>w <esc>:w<cr>
nnoremap <leader>w :w<cr>

" save and quit
vnoremap <leader>q <esc>:wq<cr>
inoremap <leader>q <esc>:wq<cr>
nnoremap <leader>q :wq<cr>

" open .vimrc
vnoremap <leader>v <esc>:e ~/.vimrc<cr>
inoremap <leader>v <esc>:e ~/.vimrc<cr>
nnoremap <leader>v :e ~/.vimrc<cr>

" open supercollider.snippets
vnoremap <leader>s <esc>:e  ~/.vim/mysnippets/UltiSnips/supercollider.snippets<cr
inoremap <leader>s <esc>:e ~/.vim/mysnippets/UltiSnips/supercollider.snippets<cr>
nnoremap <leader>s :e ~/.vim/mysnippets/UltiSnips/supercollider.snippets<cr>

" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()

" plugins
Plugin 'gmarik/Vundle.vim'
Plugin 'scrooloose/nerdtree'
Plugin 'supercollider/scvim'
Plugin 'SirVer/ultisnips'
Plugin 'honza/vim-snippets'
Plugin 'tpope/vim-surround'
Plugin 'vim-airline/vim-airline'
Plugin 'vim-airline/vim-airline-themes'

" All of your Plugins must be added before the following line
call vundle#end()            " required
filetype plugin indent on    " required
syntax on

let g:sclangTerm = "open -a iTerm.app"

let g:UltiSnipsExpandTrigger="<tab>"
let g:UltiSnipsJumpForwardTrigger="<c-b>"
let g:UltiSnipsJumpBackwardTrigger="<c-z>"
let g:UltiSnipsSnippetDirectories=["/Users/kennethflak/mysnippets"]
" If you want :UltiSnipsEdit to split your window.
let g:UltiSnipsEditSplit="vertical"
let g:airline_theme='term'
let g:NERDTreeNotificationThreshold = 500


问:
c# generic can not instead object type
```<code>public class Calculate
{
    public static T Add<T>(T a, T b) where T : struct
    {
        return (T)((object)(Convert.ToDouble(a) + Convert.ToDouble(b)));
    }
}
</code>```

run Calculate.Add(10, 20) will get error,why?

答:
Use this.

```<code> return (T)Convert.ChangeType(Convert.ToDouble(a) + Convert.ToDouble(b), typeof(T));
</code>```

It will convert your result to type "T".

Title: c# generic can not instead object type

Body:
public class Calculate
{
    public static T Add<T>(T a, T b) where T : struct
    {
        return (T)((object)(Convert.ToDouble(a) + Convert.ToDouble(b)));
    }
}

run Calculate.Add(10, 20) will get error,why?

Body:
Use this.

 return (T)Convert.ChangeType(Convert.ToDouble(a) + Convert.ToDouble(b), typeof(T));

It will convert your result to type "T".


问:
Responsive media query not working in Google Chrome
I have written a piece of CSS code to fluidly switch my site layout's width based on the user's screen width. If the user has less screen estate available, the layout's width increases to fill more of the window and leave less whitespace, and if they have more space, the layout shrinks to maintain an appealing look.

I use the following code to achieve this:

```<code>#bg{
    background:-webkit-linear-gradient(90deg, #0f0f0f 0%,#222222 400px);
    background:-moz-linear-gradient(90deg, #0f0f0f 0%,#222222 400px);
    background:-o-linear-gradient(90deg, #0f0f0f 0%,#222222 400px);
    background:linear-gradient(90deg, #0f0f0f 0%,#222222 400px);
    margin-left:auto;
    margin-right:auto;
    margin-bottom:1.6rem;
    border-width:0 0.1rem 0.1rem 0.1rem;
    border-style:solid;
    border-color:#303030 #101010 #000;
    border-radius:0.8rem;
    min-width:94.2rem
}

@media (min-width: 70rem){
    #bg{
        border-radius:4px;
        border-radius:0.4rem;
        width:90%
    }

}

@media (min-width: 91rem){
    #bg{
        width:80%
    }

}

@media (min-width: 112rem){
    #bg{
        width:70%
    }

}
</code>```

This works just fine in Firefox 30, however Google Chrome always displays the element at 70% width.

Previously, I had also used max-width in the queries, in which case Chrome would do the inverse thing; it would always display the element at 90%, no matter how much I resize the browser window.

The rules are compiled using SASS. What exactly is the problem here? How can I alter the query to work in all browsers?

The affected website can be found at this link.

答:
```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body{
            background:green;
        }
        @media only screen and (max-width: 500px) {
            body{
                background:yellow;
            }
        }
    </style>
</head>
<body>

</body>
</html>
</code>```

Body:
I have written a piece of CSS code to fluidly switch my site layout's width based on the user's screen width. If the user has less screen estate available, the layout's width increases to fill more of the window and leave less whitespace, and if they have more space, the layout shrinks to maintain an appealing look.

I use the following code to achieve this:

#bg{
    background:-webkit-linear-gradient(90deg, #0f0f0f 0%,#222222 400px);
    background:-moz-linear-gradient(90deg, #0f0f0f 0%,#222222 400px);
    background:-o-linear-gradient(90deg, #0f0f0f 0%,#222222 400px);
    background:linear-gradient(90deg, #0f0f0f 0%,#222222 400px);
    margin-left:auto;
    margin-right:auto;
    margin-bottom:1.6rem;
    border-width:0 0.1rem 0.1rem 0.1rem;
    border-style:solid;
    border-color:#303030 #101010 #000;
    border-radius:0.8rem;
    min-width:94.2rem
}

@media (min-width: 70rem){
    #bg{
        border-radius:4px;
        border-radius:0.4rem;
        width:90%
    }

}

@media (min-width: 91rem){
    #bg{
        width:80%
    }

}

@media (min-width: 112rem){
    #bg{
        width:70%
    }

}

This works just fine in Firefox 30, however Google Chrome always displays the element at 70% width.

Previously, I had also used max-width in the queries, in which case Chrome would do the inverse thing; it would always display the element at 90%, no matter how much I resize the browser window.

The rules are compiled using SASS. What exactly is the problem here? How can I alter the query to work in all browsers?

The affected website can be found at this link.


问:
What does "+ 3" in while (*(MPcore_private_timer_ptr + 3) == 0) mean?
I am currently reading through DE0-Nano-SoC Computer System
with ARM Cortex-A9 user guide i found a c code in it and i don't understand what does  "+ 3"  in "*(MPcore_private_timer_ptr + 3)" mean?  </p>

```<code>while (1)
{
*HPS_GPIO1_ptr = HPS_LEDG; // turn on/off LEDG
while (*(MPcore_private_timer_ptr + 3) == 0)
; // wait for timer to expire
*(MPcore_private_timer_ptr + 3) = 1; // reset timer flag bit
HPS_LEDG ^= bit_24_pattern; // toggle bit that controls LEDG
}
</code>```

答: Following on for @yar's answer, MPcore_private_timer_ptr is a pointer to the base address of a memory mapped timer, that is the timer's registers all follow on from that address. The +3 offset takes you to a different register (in this case the interrupt status register) for that timer.

Body:
I am currently reading through DE0-Nano-SoC Computer System
with ARM Cortex-A9 user guide i found a c code in it and i don't understand what does  "+ 3"  in "*(MPcore_private_timer_ptr + 3)" mean?

while (1)
{
*HPS_GPIO1_ptr = HPS_LEDG; // turn on/off LEDG
while (*(MPcore_private_timer_ptr + 3) == 0)
; // wait for timer to expire
*(MPcore_private_timer_ptr + 3) = 1; // reset timer flag bit
HPS_LEDG ^= bit_24_pattern; // toggle bit that controls LEDG
}


问:
npm cannot install pm2 or nodemon in Windows 10
I try to install a nodemon for the auto-restart nodejs server when my file has been changed. But I got two warnings so, I try to install other npm packages like forever or pm2, but I still get the same warning.
Here is my warning capture:

答:
Try,

```<code>npm cache clear -f
</code>```

and,

```<code>npm install pm2 -g --unsafe-perm
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Try,

npm cache clear -f

and,

npm install pm2 -g --unsafe-perm


问:
How to use threads in qt
I am new to QT. I need to use threads for some purpose. I searched a lot about threading in QT but all the articles and videos are using same example. They are using dialog and putting a label with 2 buttons to print some data on label. I want to use threads with MainWindow. My application include reading a serial data and then displaying the related information on a label. That information contains a string and an audio file. String and audio file needs to be played at the same time. I have a connected a signal for serial read like below:

```<code>connect(&Serial, SIGNAL(readyRead()), this, SLOT(SerialRead()));

QString MainWindow::SerialRead()
{
  word Words; //
  QString serialData = Serial.readAll();              //Reading Serial Data
  //Now here I want to start the two threads
  //Thread 1 to display string
  //Thread 2 to play audio
  return 0;

}
</code>```

How can I achieve above task. Can anyone please refer me to some usefull links or articles. Thanks

答:
While I very highly recommend that you use std::thread instead of QThread, it's your call. However, on the Qt docs page of QThread there's a very good example that exactly fits what you need. Here it's:

```<code>class Worker : public QObject
{
    Q_OBJECT

public slots:
    void doWork(const QString &parameter) {
        QString result;
        /* ... here is the expensive or blocking operation ... */
        emit resultReady(result);
    }

signals:
    void resultReady(const QString &result);
};

class Controller : public QObject
{
    Q_OBJECT
    QThread workerThread;
public:
    Controller() {
        Worker *worker = new Worker;
        worker->moveToThread(&workerThread);
        connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
        connect(this, &Controller::operate, worker, &Worker::doWork);
        connect(worker, &Worker::resultReady, this, &Controller::handleResults);
        workerThread.start();
    }
    ~Controller() {
        workerThread.quit();
        workerThread.wait();
    }
public slots:
    void handleResults(const QString &);
signals:
    void operate(const QString &);
};
</code>```

Basically, in this example, the Controller is your MainWindow, and the constructor of Controller is your MainWindow::SerialRead(). Be careful with memory and thread management though if you want to do that, because that Controller is made to destroy things when it exists, not when the thread is finished.

So you either use that controller as is (simply instantiate it in your MainWindow::SerialRead()), or change it to include parts of it in your MainWindow.

Title: How to use threads in qt

Body:
I am new to QT. I need to use threads for some purpose. I searched a lot about threading in QT but all the articles and videos are using same example. They are using dialog and putting a label with 2 buttons to print some data on label. I want to use threads with MainWindow. My application include reading a serial data and then displaying the related information on a label. That information contains a string and an audio file. String and audio file needs to be played at the same time. I have a connected a signal for serial read like below:

connect(&Serial, SIGNAL(readyRead()), this, SLOT(SerialRead()));

QString MainWindow::SerialRead()
{
  word Words; //
  QString serialData = Serial.readAll();              //Reading Serial Data
  //Now here I want to start the two threads
  //Thread 1 to display string
  //Thread 2 to play audio
  return 0;

}

How can I achieve above task. Can anyone please refer me to some usefull links or articles. Thanks

Body:
While I very highly recommend that you use std::thread instead of QThread, it's your call. However, on the Qt docs page of QThread there's a very good example that exactly fits what you need. Here it's:

class Worker : public QObject
{
    Q_OBJECT

public slots:
    void doWork(const QString &parameter) {
        QString result;
        /* ... here is the expensive or blocking operation ... */
        emit resultReady(result);
    }

signals:
    void resultReady(const QString &result);
};

class Controller : public QObject
{
    Q_OBJECT
    QThread workerThread;
public:
    Controller() {
        Worker *worker = new Worker;
        worker->moveToThread(&workerThread);
        connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
        connect(this, &Controller::operate, worker, &Worker::doWork);
        connect(worker, &Worker::resultReady, this, &Controller::handleResults);
        workerThread.start();
    }
    ~Controller() {
        workerThread.quit();
        workerThread.wait();
    }
public slots:
    void handleResults(const QString &);
signals:
    void operate(const QString &);
};

Basically, in this example, the Controller is your MainWindow, and the constructor of Controller is your MainWindow::SerialRead(). Be careful with memory and thread management though if you want to do that, because that Controller is made to destroy things when it exists, not when the thread is finished.

So you either use that controller as is (simply instantiate it in your MainWindow::SerialRead()), or change it to include parts of it in your MainWindow.


问:
how to put range and radio button in alert prompt in ionic2?
Using Ionic2 and angular2:

I want to create an alert box having range selector with numbers and radio button. Help?

答:
I think you should look into these 2 things and try to combine them in alertController.

AlertController

Range

NOTE: Not sure if combining <ion-range> with alertOptions will work.  Let me know your findings. If this cannot be done, you need to do this in modal.

EDIT: This does not work. You need to use modal and implement it separately.


问:
How to generate a random 10 digit number in C#?
I'm using C# and I need to generate a random 10 digit number. So far, I've only had luck finding examples indicating min maximum value. How would i go about generating a random number that is 10 digits, which can begin with 0, (initially, I was hoping for random.Next(1000000000,9999999999) but I doubt this is what I want).

My code looks like this right now:

```<code>[WebMethod]
public string GenerateNumber()
{
    Random random = new Random();
    return random.Next(?);
}
</code>```

**Update ended up doing like so,

```<code>[WebMethod]
public string GenerateNumber()
{
    Random random = new Random();
    string r = "";
    int i;
    for (i = 1; i < 11; i++)
    {
        r += random.Next(0, 9).ToString();
    }
    return r;
}
</code>```

答:
I tried to write a fast one:</p>

```<code>private int GetNDigitsRandomNumber(int digits)
{
    var min = 1;
    for (int i = 0; i < digits-1; i++)
    {
          min *= 10;
    }
    var max = min * 10;

    return _rnd.Next(min, max);
}
</code>```

Body:
I'm using C# and I need to generate a random 10 digit number. So far, I've only had luck finding examples indicating min maximum value. How would i go about generating a random number that is 10 digits, which can begin with 0, (initially, I was hoping for random.Next(1000000000,9999999999) but I doubt this is what I want).

My code looks like this right now:

[WebMethod]
public string GenerateNumber()
{
    Random random = new Random();
    return random.Next(?);
}

**Update ended up doing like so,

[WebMethod]
public string GenerateNumber()
{
    Random random = new Random();
    string r = "";
    int i;
    for (i = 1; i < 11; i++)
    {
        r += random.Next(0, 9).ToString();
    }
    return r;
}

Body:
I tried to write a fast one:

private int GetNDigitsRandomNumber(int digits)
{
    var min = 1;
    for (int i = 0; i < digits-1; i++)
    {
          min *= 10;
    }
    var max = min * 10;

    return _rnd.Next(min, max);
}


问:
How to Search an array of object in Swift 3
I am trying to search an array of objects that I'm pulling from a Firebase database. The data is loading fine but when I try to search nothing shows. I've only been learning iOS/Swift development for about 6 weeks now. Below is code I have.

The app was crashing as soon as I clicked into the search bar.
I managed to get the search code to stop crashing but I'm getting no returns in my search. Is this because I'm search a Firebase database? I'm loading the firebase data into an array so it should be searchable right?

```<code>import UIKit
import Firebase

class ServicesTableViewController: UITableViewController, UISearchResultsUpdating {

    var services = [Service]()
    var filteredSearch = [Service]()

    var searchController: UISearchController!
    var resultsController = UITableViewController()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Turn this back on to cache data
        FIRDatabase.database().persistenceEnabled = true

        fetchServices()

        self.resultsController.tableView.dataSource = self
        self.resultsController.tableView.delegate = self

        self.searchController = UISearchController(searchResultsController: self.resultsController)
        self.tableView.tableHeaderView = searchController.searchBar
        self.searchController.searchResultsUpdater = self

        searchController.dimsBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Search services..."
        searchController.searchBar.tintColor = UIColor.white
        searchController.searchBar.barTintColor = UIColor(red: 164.0/255.0, green: 45.0/255.0, blue: 9.0/255.0, alpha: 1.0)

        navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
    }

    // MARK: - Search Controller

    func filterContent(for searchText: String) {
        filteredSearch = services.filter({ (service) -> Bool in
            if let name = service.name {
                let isMatch = name.localizedCaseInsensitiveContains(searchText)
                return isMatch
            }

            return false
        })
    }

    func updateSearchResults(for searchController: UISearchController) {
        if let searchText = searchController.searchBar.text {
            filterContent(for: searchText)
            tableView.reloadData()
        }
    }

    // MARK: Database connection and data fetch

    func fetchServices () {

        FIRDatabase.database().reference().child("services").observe(.childAdded, with: { (snapshot) in

            print(snapshot)

            if let dictionary = snapshot.value as? [String: AnyObject] {

                let service = Service()
                service.setValuesForKeys(dictionary)

                self.services.append(service)

                self.tableView.reloadData()

            }

        })

    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {

        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if searchController.isActive {
            return filteredSearch.count
        } else {
            return services.count
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! ServicesTableViewCell

        // Check to see if the user is searching or not
        let service = (searchController.isActive) ? filteredSearch[indexPath.row] : services[indexPath.row]

//        let service = services[indexPath.row]
        cell.programLabel.text = service.name
        cell.programLabel.font = UIFont(name: "Avenir-Medium", size: 18.0)
        cell.programLabel.textColor = UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0)
        cell.branchLabel.text = service.branch
        cell.branchLabel.font = UIFont(name: "Avenir-Medium", size: 14.0)
        cell.branchLabel.textColor = UIColor(red: 90.0/255.0, green: 86.0/255.0, blue: 92.0/255.0, alpha: 1.0)
        cell.servicesLabel.text = service.shortDesc
        cell.servicesLabel.font = UIFont(name: "Avenir-Light", size: 14.0)
        cell.servicesLabel.textColor = UIColor(red: 164.0/255.0, green: 45.0/255.0, blue: 9.0/255.0, alpha: 1.0)
        cell.thumbnailImageView.image = UIImage(named: service.imageName!)

        return cell
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showServicesDetail" {
            if let indexPath = tableView.indexPathForSelectedRow {
                let destinationController = segue.destination as! ServicesDetailViewController
                destinationController.services = services[indexPath.row]
            }
        }
    }

}
</code>```

Here's my current storyboard. just two views and a nav controller,
enter image description here

答:
if your Service class is as follows

```<code>class Service: NSObject {
    var serviceID: NSInteger!
    var serviceName: String!

}
</code>```

you can retrieve filter services with serviceName containing self.searchController.searchBar.text by

```<code>let fiterServices = services.filter({$0.serviceName.lowercased().range(of: self.searchController.searchBar.text!.lowercased()) != nil})
</code>```

Hope this helps.

Body:
I am trying to search an array of objects that I'm pulling from a Firebase database. The data is loading fine but when I try to search nothing shows. I've only been learning iOS/Swift development for about 6 weeks now. Below is code I have.

The app was crashing as soon as I clicked into the search bar.
I managed to get the search code to stop crashing but I'm getting no returns in my search. Is this because I'm search a Firebase database? I'm loading the firebase data into an array so it should be searchable right?

import UIKit
import Firebase

class ServicesTableViewController: UITableViewController, UISearchResultsUpdating {

    var services = [Service]()
    var filteredSearch = [Service]()

    var searchController: UISearchController!
    var resultsController = UITableViewController()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Turn this back on to cache data
        FIRDatabase.database().persistenceEnabled = true

        fetchServices()

        self.resultsController.tableView.dataSource = self
        self.resultsController.tableView.delegate = self

        self.searchController = UISearchController(searchResultsController: self.resultsController)
        self.tableView.tableHeaderView = searchController.searchBar
        self.searchController.searchResultsUpdater = self

        searchController.dimsBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Search services..."
        searchController.searchBar.tintColor = UIColor.white
        searchController.searchBar.barTintColor = UIColor(red: 164.0/255.0, green: 45.0/255.0, blue: 9.0/255.0, alpha: 1.0)

        navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
    }

    // MARK: - Search Controller

    func filterContent(for searchText: String) {
        filteredSearch = services.filter({ (service) -> Bool in
            if let name = service.name {
                let isMatch = name.localizedCaseInsensitiveContains(searchText)
                return isMatch
            }

            return false
        })
    }

    func updateSearchResults(for searchController: UISearchController) {
        if let searchText = searchController.searchBar.text {
            filterContent(for: searchText)
            tableView.reloadData()
        }
    }

    // MARK: Database connection and data fetch

    func fetchServices () {

        FIRDatabase.database().reference().child("services").observe(.childAdded, with: { (snapshot) in

            print(snapshot)

            if let dictionary = snapshot.value as? [String: AnyObject] {

                let service = Service()
                service.setValuesForKeys(dictionary)

                self.services.append(service)

                self.tableView.reloadData()

            }

        })

    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {

        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if searchController.isActive {
            return filteredSearch.count
        } else {
            return services.count
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! ServicesTableViewCell

        // Check to see if the user is searching or not
        let service = (searchController.isActive) ? filteredSearch[indexPath.row] : services[indexPath.row]

//        let service = services[indexPath.row]
        cell.programLabel.text = service.name
        cell.programLabel.font = UIFont(name: "Avenir-Medium", size: 18.0)
        cell.programLabel.textColor = UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0)
        cell.branchLabel.text = service.branch
        cell.branchLabel.font = UIFont(name: "Avenir-Medium", size: 14.0)
        cell.branchLabel.textColor = UIColor(red: 90.0/255.0, green: 86.0/255.0, blue: 92.0/255.0, alpha: 1.0)
        cell.servicesLabel.text = service.shortDesc
        cell.servicesLabel.font = UIFont(name: "Avenir-Light", size: 14.0)
        cell.servicesLabel.textColor = UIColor(red: 164.0/255.0, green: 45.0/255.0, blue: 9.0/255.0, alpha: 1.0)
        cell.thumbnailImageView.image = UIImage(named: service.imageName!)

        return cell
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showServicesDetail" {
            if let indexPath = tableView.indexPathForSelectedRow {
                let destinationController = segue.destination as! ServicesDetailViewController
                destinationController.services = services[indexPath.row]
            }
        }
    }

}

Here's my current storyboard. just two views and a nav controller,
enter image description here

Body:
if your Service class is as follows

class Service: NSObject {
    var serviceID: NSInteger!
    var serviceName: String!

}

you can retrieve filter services with serviceName containing self.searchController.searchBar.text by

let fiterServices = services.filter({$0.serviceName.lowercased().range(of: self.searchController.searchBar.text!.lowercased()) != nil})

Hope this helps.


问:
Smart can't install...no package provides shared object file

Problem

I'm attempting to create a Bitbake recipe which will install Oracle JRE 8 onto my target OS.

I've tried to use metadata from meta-oracle-java, but had some difficulties due to one of the .inc files which are provided for general JREs has a JRE-7-specific URI.

I've changed some of the metadata from meta-oracle-java and created my own recipe to do this install.

Tests

A Build of the JRE Recipe by Itself

When building the recipe by itself:

```<code>bitbake oracle-jse-jre
</code>```

The build completes without error. I've added a dependency on libav into the oracle-jse-jre recipe, so I can do the following from TMPDIR:

```<code>$ find . -name libavformat*so
./work/core2-64-poky-linux/libav/9.18-r0/sysroot-destdir/usr/lib/libavformat.so.54.20.4
./work/core2-64-poky-linux/libav/9.18-r0/sysroot-destdir/usr/lib/libavformat.so
./work/core2-64-poky-linux/libav/9.18-r0/sysroot-destdir/usr/lib/libavformat.so.54
./sysroots/genericx86-64/usr/lib/libavformat.so.54.20.4
./sysroots/genericx86-64/usr/lib/libavformat.so
./sysroots/genericx86-64/usr/lib/libavformat.so.54
</code>```

Runtime Dependency Success

If I add the default package from the oracle-jse-jre recipe to RDEPENDS_${PN} of another recipe xenoros_0.1.bb, I can run bitbake xenoros and build without errors.

Core Image Failure

If I add xenoros to the IMAGE_INSTALL variable of a core-image-xenoros, the build fails with the following error:

```<code>ERROR: Unable to install packages. Command '/home/presslertj/yocto-OS/poky-jethro-build/build/tmp/sysroots/x86_64-linux/usr/bin/smart --log-level=warning --data-dir=/home/presslertj/yocto-OS/poky-jethro-build/build/tmp/work/genericx86_64-poky-linux/core-image-my-server/1.0-r0/rootfs/var/lib/smart install -y message-generation@core2_64 catkin@core2_64 python-distutils@core2_64 ldd@core2_64 xenoros@core2_64 rosgraph@core2_64 gedit@core2_64 actionlib@core2_64 python-compression@core2_64 dhcp-server@core2_64 libpthread-stubs@core2_64 tf2@core2_64 python-email@core2_64 catkin-dev@core2_64 git@core2_64 rosbash@core2_64 python-json@core2_64 python-wstool@core2_64 connman@core2_64 ros-config@core2_64 packagegroup-core-boot@genericx86_64 libsdl-1.2-0@core2_64 rosjava@core2_64 quagga@core2_64 nginx@core2_64 rospy@core2_64 apt@core2_64 libc6@core2_64 netcat@core2_64 shadow@core2_64 bash@core2_64 roscpp@core2_64 roslaunch@core2_64 run-postinsts@all python-rosinstall@core2_64 elfutils@core2_64 openssl@core2_64 font-alias@all gradle@core2_64 python-catkin-pkg@core2_64 catkin-runtime@core2_64 catkin-runtime-dev@core2_64 pciutils@core2_64 base-passwd@core2_64' returned 1:
Loading cache...
Updating cache...               ######################################## [100%]

Computing transaction...error: Can't install oracle-jse-jre-1.8.0-u77r0@core2_64: no package provides libavformat.so.53(LIBAVFORMAT_53)(64bit)

ERROR: Function failed: do_rootfs
ERROR: Logfile of failure stored in: /home/presslertj/yocto-OS/poky-jethro-build/build/tmip/work/genericx86_64-poky-linux/core-image-my-server/1.0-r0/temp/log.do_rootfs.22073
ERROR: Task 7 (/home/presslertj/yocto-OS/poky-jethro-build/meta-myLayer/recipes-core/images/core-image-my-server.bb, do_rootfs) failed with exit code '1'
</code>```

Looking inside TMPDIR, I can find this:

```<code>/sysroots/genericx86-64/usr/lib/libavformat.so.54
</code>```

It seems there's a version mismatch, where smart expects version 53, but 54 is provided.

Reverting libav's version

Just to test what's going on, I've made a recipe which fetches version 0.8.17 of libav (which uses version 53).  When using this instead of 9.18, I have the exact opposite problem, that smart expects but can't find version 54.

Questions

How does smart determine the version number for these shared object files?

What about the do_rootfs() task causes the build to fail at this specific time?

Is there a simple resolution to my specific problem?

答:
For anyone that still encounter this error: as stated in the README file of the meta-oracle-java repo</p>

```<code>There are some known install problems for JRE packages due to dependencies reported by RPM package manager.
Switching to DEB or IPK packaging temporarily fixes this.
ie:
PACKAGE_CLASSES = "package_deb"
or
PACKAGE_CLASSES = "package_ipk"
in your 'local.conf' file
</code>```

Body:
Problem

I'm attempting to create a Bitbake recipe which will install Oracle JRE 8 onto my target OS.

I've tried to use metadata from meta-oracle-java, but had some difficulties due to one of the .inc files which are provided for general JREs has a JRE-7-specific URI.

I've changed some of the metadata from meta-oracle-java and created my own recipe to do this install.

Tests

A Build of the JRE Recipe by Itself

When building the recipe by itself:

bitbake oracle-jse-jre

The build completes without error. I've added a dependency on libav into the oracle-jse-jre recipe, so I can do the following from TMPDIR:

$ find . -name libavformat*so
./work/core2-64-poky-linux/libav/9.18-r0/sysroot-destdir/usr/lib/libavformat.so.54.20.4
./work/core2-64-poky-linux/libav/9.18-r0/sysroot-destdir/usr/lib/libavformat.so
./work/core2-64-poky-linux/libav/9.18-r0/sysroot-destdir/usr/lib/libavformat.so.54
./sysroots/genericx86-64/usr/lib/libavformat.so.54.20.4
./sysroots/genericx86-64/usr/lib/libavformat.so
./sysroots/genericx86-64/usr/lib/libavformat.so.54

Runtime Dependency Success

If I add the default package from the oracle-jse-jre recipe to RDEPENDS_${PN} of another recipe xenoros_0.1.bb, I can run bitbake xenoros and build without errors.

Core Image Failure

If I add xenoros to the IMAGE_INSTALL variable of a core-image-xenoros, the build fails with the following error:

ERROR: Unable to install packages. Command '/home/presslertj/yocto-OS/poky-jethro-build/build/tmp/sysroots/x86_64-linux/usr/bin/smart --log-level=warning --data-dir=/home/presslertj/yocto-OS/poky-jethro-build/build/tmp/work/genericx86_64-poky-linux/core-image-my-server/1.0-r0/rootfs/var/lib/smart install -y message-generation@core2_64 catkin@core2_64 python-distutils@core2_64 ldd@core2_64 xenoros@core2_64 rosgraph@core2_64 gedit@core2_64 actionlib@core2_64 python-compression@core2_64 dhcp-server@core2_64 libpthread-stubs@core2_64 tf2@core2_64 python-email@core2_64 catkin-dev@core2_64 git@core2_64 rosbash@core2_64 python-json@core2_64 python-wstool@core2_64 connman@core2_64 ros-config@core2_64 packagegroup-core-boot@genericx86_64 libsdl-1.2-0@core2_64 rosjava@core2_64 quagga@core2_64 nginx@core2_64 rospy@core2_64 apt@core2_64 libc6@core2_64 netcat@core2_64 shadow@core2_64 bash@core2_64 roscpp@core2_64 roslaunch@core2_64 run-postinsts@all python-rosinstall@core2_64 elfutils@core2_64 openssl@core2_64 font-alias@all gradle@core2_64 python-catkin-pkg@core2_64 catkin-runtime@core2_64 catkin-runtime-dev@core2_64 pciutils@core2_64 base-passwd@core2_64' returned 1:
Loading cache...
Updating cache...               ######################################## [100%]

Computing transaction...error: Can't install oracle-jse-jre-1.8.0-u77r0@core2_64: no package provides libavformat.so.53(LIBAVFORMAT_53)(64bit)

ERROR: Function failed: do_rootfs
ERROR: Logfile of failure stored in: /home/presslertj/yocto-OS/poky-jethro-build/build/tmip/work/genericx86_64-poky-linux/core-image-my-server/1.0-r0/temp/log.do_rootfs.22073
ERROR: Task 7 (/home/presslertj/yocto-OS/poky-jethro-build/meta-myLayer/recipes-core/images/core-image-my-server.bb, do_rootfs) failed with exit code '1'

Looking inside TMPDIR, I can find this:

/sysroots/genericx86-64/usr/lib/libavformat.so.54

It seems there's a version mismatch, where smart expects version 53, but 54 is provided.

Reverting libav's version

Just to test what's going on, I've made a recipe which fetches version 0.8.17 of libav (which uses version 53).  When using this instead of 9.18, I have the exact opposite problem, that smart expects but can't find version 54.

Questions

How does smart determine the version number for these shared object files?

What about the do_rootfs() task causes the build to fail at this specific time?

Is there a simple resolution to my specific problem?

Body:
For anyone that still encounter this error: as stated in the README file of the meta-oracle-java repo

There are some known install problems for JRE packages due to dependencies reported by RPM package manager.
Switching to DEB or IPK packaging temporarily fixes this.
ie:
PACKAGE_CLASSES = "package_deb"
or
PACKAGE_CLASSES = "package_ipk"
in your 'local.conf' file


问:
foreach not working in opencart custom page
Am creating a page called no.tpl. Here am showing customer firstname and lastname in select dropdown.

here my code no.tpl

```<code><select name="customer_id" id="customer" style="width: 325px;margin-bottom:10px" class="form-control">
    <?php foreach($customerData as $customer){ ?>
        <option value=<?php echo $customer['customer_id']?>><?php echo $customer['customer_name']?></option>
    <?php }?>
</select>
</code>```

This is my controller code

```<code>    <?php

class ControllerSaleno extends Controller {
    private $error = array();
    public function index() {

           $data=$this->request->post;
           $customerId=$data['customer_id'];

        //$this->sendMail($customerId);

        $data['column_left'] = $this->load->controller('common/column_left');
        $data['column_right'] = $this->load->controller('common/column_right');
        $data['content_top'] = $this->load->controller('common/content_top');
        $data['content_bottom'] = $this->load->controller('common/content_bottom');
        $data['footer'] = $this->load->controller('common/footer');
        $data['header'] = $this->load->controller('common/header');

        //$this->response->setOutput($this->load->view('default/template/product/no.tpl', $data));

        $this->response->setOutput($this->load->view('sale/no.tpl', $data));

        //$data['productsData']=$this->getProductData();
         $customers=$this->getCustomerData();

             $data['customerData']=array();

 foreach($customers as $customer)
{
   $data['customerData'][]=array(
'customer_id'=>$customer['customer_id'],
'customer_name'=>$customer['firstname'].' '.$customer['lastname']
);
   //var_dump($data['customerData']);
   //var_dump($customer['firstname']);
}

    }
    public function getCustomerData()
    {

        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer order by firstname asc");
        return $query->rows;
    }

    public function sendMail($customerId)
    {

        $tempArray=array();

      $selectedCustomerId=$customerId;
            $query=$this->db->query("SELECT state FROM " . DB_PREFIX . "customer where customer_id=".$selectedCustomerId);
            $state=$query->row;

            $querySalesEmail=$this->db->query("SELECT email FROM " . DB_PREFIX . "customer where customer_id=".$selectedCustomerId);
            $salesPersonEmail1=$querySalesEmail->row;

            $salesPersonEmail= $salesPersonEmail1['email'];

 $queryCustomerName=$this->db->query("SELECT concat(firstname,' ',lastname) as name FROM " . DB_PREFIX . "customer where customer_id=".$selectedCustomerId);
$customerName=$queryCustomerName->row['name'];

    $To = "radhamani123@gmail.com";
    $Subject = "New Order From " . "'" . $customerName . "'" . date('m/d/Y h:i:s');
    $Headers  = "MIME-Version: 1.0\r\n";
    $Headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
    $Headers .= "From: No ORder<orders@milkymist.in>\r\n";

   $Message = '';

            $Message .= 'No Order Today';

    if(mail($To, $Subject, $Message, $Headers)){
        echo "success";

    }else{
        echo "failure";
    }

 $data['column_left'] = $this->load->controller('common/column_left');
        $data['column_right'] = $this->load->controller('common/column_right');
        $data['content_top'] = $this->load->controller('common/content_top');
        $data['content_bottom'] = $this->load->controller('common/content_bottom');
        $data['footer'] = $this->load->controller('common/footer');
        $data['header'] = $this->load->controller('common/header');

        $this->response->setOutput($this->load->view('default/template/product/no.tpl', $data));

    }

}
</code>```

答:
in controller page i did some changes</p>

```<code><?php

class ControllerSaleno extends Controller {
    private $error = array();
    public function index() {

           $data=$this->request->post;
           $customerId=$data['customer_id'];

        //$this->sendMail($customerId);

        $data['column_left'] = $this->load->controller('common/column_left');
        $data['column_right'] = $this->load->controller('common/column_right');
        $data['content_top'] = $this->load->controller('common/content_top');
        $data['content_bottom'] = $this->load->controller('common/content_bottom');
        $data['footer'] = $this->load->controller('common/footer');
        $data['header'] = $this->load->controller('common/header');

        //$this->response->setOutput($this->load->view('default/template/product/no.tpl', $data));

        $this->response->setOutput($this->load->view('sale/no.tpl', $data));

        //$data['productsData']=$this->getProductData();
         $customers=$this->getCustomerData();

             $data['customerData']=array();

 foreach($customers as $customer)
{
   $data['customerData'][]=array(
'customer_id'=>$customer['customer_id'],
'customer_name'=>$customer['firstname'].' '.$customer['lastname']
);
   //var_dump($data['customerData']);
   //var_dump($customer['firstname']);
}

         $data['NoOrder']=$this->url->link('sale/order/NoOrder', 'token=' . $this->session->data['token'] , 'SSL'); //added code
         $this->response->setOutput($this->load->view('sale/no.tpl', $data)); //added code

    }
    public function getCustomerData()
    {

        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer order by firstname asc");
        return $query->rows;
    }

    /*no order*/
    public function NoOrder()
    {

        $this->sendMail();
        //$this->response->redirect($_SERVER['HTTP_REFERER']);
    }

    public function sendMail()
    {

        $tempArray=array();

      $selectedCustomerId=$customerId;
            $query=$this->db->query("SELECT state FROM " . DB_PREFIX . "customer where customer_id=".$selectedCustomerId);
            $state=$query->row;

            $querySalesEmail=$this->db->query("SELECT email FROM " . DB_PREFIX . "customer where customer_id=".$selectedCustomerId);
            $salesPersonEmail1=$querySalesEmail->row;

            $salesPersonEmail= $salesPersonEmail1['email'];

 $queryCustomerName=$this->db->query("SELECT concat(firstname,' ',lastname) as name FROM " . DB_PREFIX . "customer where customer_id=".$selectedCustomerId);
$customerName=$queryCustomerName->row['name'];

$To = "radhamani123@gmail.com";
   $Subject = "New Order From " . "'" . $customerName . "'" . date('m/d/Y h:i:s');
    $Headers  = "MIME-Version: 1.0\r\n";
    $Headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
    $Headers .= "From: No ORder<orders@milkymist.in>\r\n";

   $Message = '';

            $Message .= 'No Order Today';

    if(mail($To, $Subject, $Message, $Headers)){
        echo "success";

    }else{
        echo "failure";
    }

        //$this->response->setOutput(json_encode($result));
 $data['column_left'] = $this->load->controller('common/column_left');
        $data['column_right'] = $this->load->controller('common/column_right');
        $data['content_top'] = $this->load->controller('common/content_top');
        $data['content_bottom'] = $this->load->controller('common/content_bottom');
        $data['footer'] = $this->load->controller('common/footer');
        $data['header'] = $this->load->controller('common/header');

       $this->response->setOutput($this->load->view('sale/noorder.tpl', $data));
        //$this->response->setOutput($this->load->view('sale/no.tpl', $data));

    }
    /*no order*/

}
</code>```

Body:
Am creating a page called no.tpl. Here am showing customer firstname and lastname in select dropdown.

here my code no.tpl

<select name="customer_id" id="customer" style="width: 325px;margin-bottom:10px" class="form-control">
    <?php foreach($customerData as $customer){ ?>
        <option value=<?php echo $customer['customer_id']?>><?php echo $customer['customer_name']?></option>
    <?php }?>
</select>

This is my controller code

    <?php

class ControllerSaleno extends Controller {
    private $error = array();
    public function index() {

           $data=$this->request->post;
           $customerId=$data['customer_id'];

        //$this->sendMail($customerId);

        $data['column_left'] = $this->load->controller('common/column_left');
        $data['column_right'] = $this->load->controller('common/column_right');
        $data['content_top'] = $this->load->controller('common/content_top');
        $data['content_bottom'] = $this->load->controller('common/content_bottom');
        $data['footer'] = $this->load->controller('common/footer');
        $data['header'] = $this->load->controller('common/header');

        //$this->response->setOutput($this->load->view('default/template/product/no.tpl', $data));

        $this->response->setOutput($this->load->view('sale/no.tpl', $data));

        //$data['productsData']=$this->getProductData();
         $customers=$this->getCustomerData();

             $data['customerData']=array();

 foreach($customers as $customer)
{
   $data['customerData'][]=array(
'customer_id'=>$customer['customer_id'],
'customer_name'=>$customer['firstname'].' '.$customer['lastname']
);
   //var_dump($data['customerData']);
   //var_dump($customer['firstname']);
}

    }
    public function getCustomerData()
    {

        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer order by firstname asc");
        return $query->rows;
    }

    public function sendMail($customerId)
    {

        $tempArray=array();

      $selectedCustomerId=$customerId;
            $query=$this->db->query("SELECT state FROM " . DB_PREFIX . "customer where customer_id=".$selectedCustomerId);
            $state=$query->row;

            $querySalesEmail=$this->db->query("SELECT email FROM " . DB_PREFIX . "customer where customer_id=".$selectedCustomerId);
            $salesPersonEmail1=$querySalesEmail->row;

            $salesPersonEmail= $salesPersonEmail1['email'];

 $queryCustomerName=$this->db->query("SELECT concat(firstname,' ',lastname) as name FROM " . DB_PREFIX . "customer where customer_id=".$selectedCustomerId);
$customerName=$queryCustomerName->row['name'];

    $To = "radhamani123@gmail.com";
    $Subject = "New Order From " . "'" . $customerName . "'" . date('m/d/Y h:i:s');
    $Headers  = "MIME-Version: 1.0\r\n";
    $Headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
    $Headers .= "From: No ORder<orders@milkymist.in>\r\n";

   $Message = '';

            $Message .= 'No Order Today';

    if(mail($To, $Subject, $Message, $Headers)){
        echo "success";

    }else{
        echo "failure";
    }

 $data['column_left'] = $this->load->controller('common/column_left');
        $data['column_right'] = $this->load->controller('common/column_right');
        $data['content_top'] = $this->load->controller('common/content_top');
        $data['content_bottom'] = $this->load->controller('common/content_bottom');
        $data['footer'] = $this->load->controller('common/footer');
        $data['header'] = $this->load->controller('common/header');

        $this->response->setOutput($this->load->view('default/template/product/no.tpl', $data));

    }

}

Body:
in controller page i did some changes

<?php

class ControllerSaleno extends Controller {
    private $error = array();
    public function index() {

           $data=$this->request->post;
           $customerId=$data['customer_id'];

        //$this->sendMail($customerId);

        $data['column_left'] = $this->load->controller('common/column_left');
        $data['column_right'] = $this->load->controller('common/column_right');
        $data['content_top'] = $this->load->controller('common/content_top');
        $data['content_bottom'] = $this->load->controller('common/content_bottom');
        $data['footer'] = $this->load->controller('common/footer');
        $data['header'] = $this->load->controller('common/header');

        //$this->response->setOutput($this->load->view('default/template/product/no.tpl', $data));

        $this->response->setOutput($this->load->view('sale/no.tpl', $data));

        //$data['productsData']=$this->getProductData();
         $customers=$this->getCustomerData();

             $data['customerData']=array();

 foreach($customers as $customer)
{
   $data['customerData'][]=array(
'customer_id'=>$customer['customer_id'],
'customer_name'=>$customer['firstname'].' '.$customer['lastname']
);
   //var_dump($data['customerData']);
   //var_dump($customer['firstname']);
}

         $data['NoOrder']=$this->url->link('sale/order/NoOrder', 'token=' . $this->session->data['token'] , 'SSL'); //added code
         $this->response->setOutput($this->load->view('sale/no.tpl', $data)); //added code

    }
    public function getCustomerData()
    {

        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer order by firstname asc");
        return $query->rows;
    }

    /*no order*/
    public function NoOrder()
    {

        $this->sendMail();
        //$this->response->redirect($_SERVER['HTTP_REFERER']);
    }

    public function sendMail()
    {

        $tempArray=array();

      $selectedCustomerId=$customerId;
            $query=$this->db->query("SELECT state FROM " . DB_PREFIX . "customer where customer_id=".$selectedCustomerId);
            $state=$query->row;

            $querySalesEmail=$this->db->query("SELECT email FROM " . DB_PREFIX . "customer where customer_id=".$selectedCustomerId);
            $salesPersonEmail1=$querySalesEmail->row;

            $salesPersonEmail= $salesPersonEmail1['email'];

 $queryCustomerName=$this->db->query("SELECT concat(firstname,' ',lastname) as name FROM " . DB_PREFIX . "customer where customer_id=".$selectedCustomerId);
$customerName=$queryCustomerName->row['name'];

$To = "radhamani123@gmail.com";
   $Subject = "New Order From " . "'" . $customerName . "'" . date('m/d/Y h:i:s');
    $Headers  = "MIME-Version: 1.0\r\n";
    $Headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
    $Headers .= "From: No ORder<orders@milkymist.in>\r\n";

   $Message = '';

            $Message .= 'No Order Today';

    if(mail($To, $Subject, $Message, $Headers)){
        echo "success";

    }else{
        echo "failure";
    }

        //$this->response->setOutput(json_encode($result));
 $data['column_left'] = $this->load->controller('common/column_left');
        $data['column_right'] = $this->load->controller('common/column_right');
        $data['content_top'] = $this->load->controller('common/content_top');
        $data['content_bottom'] = $this->load->controller('common/content_bottom');
        $data['footer'] = $this->load->controller('common/footer');
        $data['header'] = $this->load->controller('common/header');

       $this->response->setOutput($this->load->view('sale/noorder.tpl', $data));
        //$this->response->setOutput($this->load->view('sale/no.tpl', $data));

    }
    /*no order*/

}


问:
Is there a way to get current activity's layout and views via adb?
For environment reasons I can only use adb commands.

Is there a way to get the current layout attributes like id, position, text etc ?

Similar to what uiautomatorviewer shows.

答:
I used the following on a Mac to print formatted xml to the console:

adb shell uiautomator dump && adb pull /sdcard/window_dump.xml $TMPDIR && more $TMPDIR/window_dump.xml | xmllint --format -

You may need to change the path of the /sdcard/window_dump.xml file to pull based on where the xml file is dumped.


问:
Gradle sync: Connection to the Internet denied
I'm trying to sync a Gradle project, but the next Error emerges:

```<code>Error: Connection to the Internet denied.
</code>```

It also says to check this page but the workaround didn't make it.

答: Its a issue by window firewall, please turn off your window firewall.</p>

Body:
I'm trying to sync a Gradle project, but the next Error emerges:

Error: Connection to the Internet denied.

It also says to check this page but the workaround didn't make it.


问:
How to pass a key from parent JSON into #each loop in handlebars
Following is the JSON over which I am iterating the category key using #each in handlebars.

JSON -

```<code>{
  title: "TEST TITLE",
  body: "This is my first HANDLEBAR",
  category: [{name: 'Button 1', id: 111}, {name: 'Button 2', id: 111}]
}
</code>```

HANDLEBAR TEMPLATE -

```<code>{{#each this.category}}
<button value="{{name}}">{{name}}</button>

{{this.title}}
{{/each}}
</code>```

OUTPUT -

```<code><button value="Button 1">Button 1</button>

<button value="Button 2">Button 2</button>
</code>```

EXPECTED OUTPUT -

```<code><button value="Button 1">Button 1</button>

TEST TITLE
<button value="Button 2">Button 2</button>
</code>```

Let me know how can I reach to the expected output as {{this.title}} is not working.

答: To access the parent key I need to do - {{../title}} and it will print the title then.

Body:
Following is the JSON over which I am iterating the category key using #each in handlebars.

JSON -

{
  title: "TEST TITLE",
  body: "This is my first HANDLEBAR",
  category: [{name: 'Button 1', id: 111}, {name: 'Button 2', id: 111}]
}

HANDLEBAR TEMPLATE -

{{#each this.category}}
<button value="{{name}}">{{name}}</button>

{{this.title}}
{{/each}}

OUTPUT -

<button value="Button 1">Button 1</button>

<button value="Button 2">Button 2</button>

EXPECTED OUTPUT -

<button value="Button 1">Button 1</button>

TEST TITLE
<button value="Button 2">Button 2</button>

Let me know how can I reach to the expected output as {{this.title}} is not working.


问:
Does click lib provide a way to print the builtin help message?
I am using the click lib.

In my code , sometimes I want to print help msg ,
But the only way I know is :

```<code>python xxx --help
</code>```

But I want to print the help msg in my code using a certain function , for example:

```<code>click.print_help_msg()
</code>```

Is there a function like this ?

答:
You can use Command's get_help method</p>

```<code>import click

@click.command()
@click.option('--name', help='The person to greet.')
def hello(name):
    """Simple program that greets NAME."""
    click.echo('Hello %s!' % name)

def print_help_msg(command):
    with click.Context(command) as ctx:
        click.echo(command.get_help(ctx))

>> print_help_msg(hello)
</code>```

Body:
I am using the click lib.

In my code , sometimes I want to print help msg ,
But the only way I know is :

python xxx --help

But I want to print the help msg in my code using a certain function , for example:

click.print_help_msg()

Is there a function like this ?

Body:
You can use Command's get_help method

import click

@click.command()
@click.option('--name', help='The person to greet.')
def hello(name):
    """Simple program that greets NAME."""
    click.echo('Hello %s!' % name)

def print_help_msg(command):
    with click.Context(command) as ctx:
        click.echo(command.get_help(ctx))

>> print_help_msg(hello)