问:
How to add static text inside an input form
How can I put this static text in an input form?

It's there all the time.

This is my code:

```<code><label for="subdomain">Subdomain:</label>
<input type="text" placeholder="ExampleDomain" id="subdomain"/>
</code>```

答:
You can achieve this with the following approach:

place the <input> in a  with position:relative

give the  an ::after pseudo-element with position:absolute

set box-sizing of the <input> to border-box

give the <input> a padding-right equal to the width of the ::after pseudo-element

Working Example:

label, input {
    position: relative;
    display: block;
    padding-right: 76px;
    width: 174px;
    box-sizing: border-box;
}

label::after {
    content: '.' attr(data-domain);
    position: absolute;
    top: 4px;
    left: 96px;
    font-family: arial, helvetica, sans-serif;
    font-size: 12px;
    display: block;
    color: rgba(0, 0, 0, 0.6);
    font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label data-domain="domain.com">
<input type="text" placeholder="exampledomain" />
<label></code>```

Body:
How can I put this static text in an input form?

It's there all the time.

This is my code:

Subdomain:
<input type="text" placeholder="ExampleDomain" id="subdomain"/>

Body:
You can achieve this with the following approach:

place the <input> in a <label> with position:relative

give the <label> an ::after pseudo-element with position:absolute

set box-sizing of the <input> to border-box

give the <input> a padding-right equal to the width of the ::after pseudo-element

Working Example:

label, input {
    position: relative;
    display: block;
    padding-right: 76px;
    width: 174px;
    box-sizing: border-box;
}

label::after {
    content: '.' attr(data-domain);
    position: absolute;
    top: 4px;
    left: 96px;
    font-family: arial, helvetica, sans-serif;
    font-size: 12px;
    display: block;
    color: rgba(0, 0, 0, 0.6);
    font-weight: bold;
}

<label data-domain="domain.com">
<input type="text" placeholder="exampledomain" />
<label>


来源: stackexchange

问:
sum of field in different id's
```<code>Table frounds:

ID   |  oname                         | fraised
----- ------------ -----------------------------
1    | linkedcare                     | $15,000,000
2    | Shankai Sports International   | $45,000,000
3    | Puma                           | $95,000,000
4    | Nike Women                     | $75,000,000
</code>```

PHP Code

```<code>$result = mysqli_query($con,'SELECT SUM(fraised) AS SUM FROM frounds');
$row1 = mysqli_fetch_assoc($result);
$sum = $row1['SUM'];
echo $sum;
</code>```

Above out put is '0'

What I want result

the sum of 'fraised' field as an example here '230,000,000'
but I get output is '0'

Where I wrong?

答:
Not best practice, but you can strip the currency symbol and commas, cast fraised to a number, and then sum:

```<code>SELECT
    SUM(CAST(REPLACE(SUBSTRING(fraised, 2), ',', '') AS UNSIGNED)) AS SUM
FROM frounds;
</code>```

Moving forward, use a number column, possibly decimal, to store your currency information.  You should view the above query as a temporary hack until you can fix your table design.

Demo

ContentLicense: CC BY-SA 3.0

Title: sum of field in different id's

Body:
Table frounds:

ID   |  oname                         | fraised
----- ------------ -----------------------------
1    | linkedcare                     | $15,000,000
2    | Shankai Sports International   | $45,000,000
3    | Puma                           | $95,000,000
4    | Nike Women                     | $75,000,000

PHP Code

$result = mysqli_query($con,'SELECT SUM(fraised) AS SUM FROM frounds');
$row1 = mysqli_fetch_assoc($result);
$sum = $row1['SUM'];
echo $sum;

Above out put is '0'

What I want result

the sum of 'fraised' field as an example here '230,000,000'
but I get output is '0'

Where I wrong?

Body:
Not best practice, but you can strip the currency symbol and commas, cast fraised to a number, and then sum:

SELECT
    SUM(CAST(REPLACE(SUBSTRING(fraised, 2), ',', '') AS UNSIGNED)) AS SUM
FROM frounds;

Moving forward, use a number column, possibly decimal, to store your currency information.  You should view the above query as a temporary hack until you can fix your table design.

Demo


问:
Dot Emacs: Can frame-title-format show preceding directories?
I'm new to Emacs and loving it so far.
In my .emacs I have the line:

(setq frame-title-format "%b - GNU Emacs")

How can I get it to show the two preceding directories? I tend to have multiple files open with the same name and knowing the directory it is in would be very helpful.

答: I think uniquify is a more complete solution to your problem. See http://www.gnu.org/software/emacs/manual/html_node/emacs/Uniquify.html

ContentLicense: CC BY-SA 2.5


答:
There are two ways to do that.

First : If you want to keep the format of fraised in your table then use php code to do sum for you.

```<code>$result = mysqli_query($con, 'SELECT fraised FROM frounds');
$sum = 0;
while ($row1 = mysqli_fetch_assoc($result)) {
    $sum += str_replace('$','',$row1['fraised']);
}
echo $sum;
</code>```

Second : change the data type in table to int in that case you can not store data in $15,000,000 format but you can use php number format to show the data in desire format

Title: sum of field in different id's

Body:
There are two ways to do that.

First : If you want to keep the format of fraised in your table then use php code to do sum for you.

$result = mysqli_query($con, 'SELECT fraised FROM frounds');
$sum = 0;
while ($row1 = mysqli_fetch_assoc($result)) {
    $sum += str_replace('$','',$row1['fraised']);
}
echo $sum;

Second : change the data type in table to int in that case you can not store data in $15,000,000 format but you can use php number format to show the data in desire format


问:
Implicitly calling a method in a class from main
I am new to Java and I am trying to solve an exercise given by my professor.
He has given this class

```<code>public class MioPunto {
public int x;
public int y;
public String toString() {
    return ("[" + x + "," + y + "]");
  }
}
</code>```

and I am supposed to write another class with a main method. Into the main I have to print the coordinates without explicitly calling the "toString" method.
I unconsciously solved it in this way

```<code>public class TestMioPunto{
public static void main(String[] args){
    MioPunto inizio = new MioPunto();
    MioPunto fine = new MioPunto();
    inizio.x=10;
    inizio.y=10;
    fine.x=20;
    fine.y=30;
    System.out.println("Inizio: " + inizio + "\n" + "Fine: " + fine);
  }
}
</code>```

and the output is
I can't understand how Java automatically called the toString method (brackets and commas), can you please explain?

答:
Java calls toString when you use + on a String and an object.

So your

```<code>System.out.println("Inizio: " + inizio + "\n" + "Fine: " + fine);
</code>```

is the same as

```<code>System.out.println("Inizio: " + inizio.toString() + "\n" + "Fine: " + fine.toString());
</code>```

except that if inizio or fine is null, the first won't give you an error (you'll see null in the string instead) but the second will.

From the JLS's section on the String Concatenation operator:

If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.

which refers to the String Conversion section, which says (after discussing converting primitives to string):

...

Now only reference values need to be considered:

If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).

Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.

Body:
I am new to Java and I am trying to solve an exercise given by my professor.
He has given this class

public class MioPunto {
public int x;
public int y;
public String toString() {
    return ("[" + x + "," + y + "]");
  }
}

and I am supposed to write another class with a main method. Into the main I have to print the coordinates without explicitly calling the "toString" method.
I unconsciously solved it in this way

public class TestMioPunto{
public static void main(String[] args){
    MioPunto inizio = new MioPunto();
    MioPunto fine = new MioPunto();
    inizio.x=10;
    inizio.y=10;
    fine.x=20;
    fine.y=30;
    System.out.println("Inizio: " + inizio + "\n" + "Fine: " + fine);
  }
}

and the output is
I can't understand how Java automatically called the toString method (brackets and commas), can you please explain?

Body:
Java calls toString when you use + on a String and an object.

So your

System.out.println("Inizio: " + inizio + "\n" + "Fine: " + fine);

is the same as

System.out.println("Inizio: " + inizio.toString() + "\n" + "Fine: " + fine.toString());

except that if inizio or fine is null, the first won't give you an error (you'll see null in the string instead) but the second will.

From the JLS's section on the String Concatenation operator:

If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.

which refers to the String Conversion section, which says (after discussing converting primitives to string):

...

Now only reference values need to be considered:

If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).

Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.


答:
Because you using a string instead of a number.you have to change the data type or need to remove $ and , from the string instead.
Query:

```<code>SELECT SUM(cast(REPLACE(substring(fraised,2),',','') as decimal)) AS SUM FROM frounds;
</code>```

you can use the following code :

```<code>$result = mysqli_query($con,"SELECT SUM(cast(REPLACE(substring(fraised,2),',','') as decimal)) AS SUM FROM frounds;");
$row1 = mysqli_fetch_assoc($result);
$sum = $row1['SUM'];
echo $sum;
</code>```

Title: sum of field in different id's

Body:
Because you using a string instead of a number.you have to change the data type or need to remove $ and , from the string instead.
Query:

SELECT SUM(cast(REPLACE(substring(fraised,2),',','') as decimal)) AS SUM FROM frounds;

you can use the following code :

$result = mysqli_query($con,"SELECT SUM(cast(REPLACE(substring(fraised,2),',','') as decimal)) AS SUM FROM frounds;");
$row1 = mysqli_fetch_assoc($result);
$sum = $row1['SUM'];
echo $sum;


问:
React router, how to restore state after browser back button?
I'm trying to figure out how to make my React SPA app maintain state when the user navigates with the back/forward browser buttons. E.g. the user is filling a form, then he moves back and forward and the form is automatically restored.

I reviewed many JavaScript routers around but none seem to address this issue properly... (or even at all).

Currently I'm using React Router 4 and this is the pattern I'm adopting:

when programmatically leaving the page, I first save current page's state with history.replace(this.state); then I move out of the page with history.push(newLocation)

when a page component is created (componentWillMount) I check for this.props.location.state !== undefined and if so, I restore it with this.setState(this.props.location.state)

My question is: is the above pattern correct? suggested? Is there any better and widely adopted way?

答:
after a while I found a reasonable workaround:

in react, after every this.setState() I keep state synchronized with history using window.history.replaceState({ key: history.location.key, state: this.state})

when a "page" component is mounted or refreshed (willMount and willReceiveProps) I check for state in props.params.location.state: if there is one, I do restore it; if there is none I create a fresh new state.

when navigating on the same page, I do not use routes, I just use this.setState and window.history.pushState

when navigating outside of the page, I just use routes and avoid to pass anything in the state

This solution seems to work nicely, the only minor cons are:

state must be serializable

this.setState is a pitfall because it's asynchronous, you cannot use this.state after it, unless you do trickery.

initial empty state must be provided by a function to be used during the restore or init phase, it can't just stay in the constructor() of the Component

in Firefox, automatic scroll restoration after the back button works randomly, don't know why, but Chrome and Edge are ok.

Overall I have written a PageComponent that extends Component that does all the init/restoration work; it also overrides this.setState to make it syncs automatically with history and avoids the asynchronous annoyances.


问:
Algorithm for fairly assigning tasks to workers based on skills
(Before anyone asks, this is not homework.)

I have a set of workers with interests, i.e.:

Bob: Java, XML, Ruby

Susan: Java, HTML, Python

Fred: Python, Ruby

Sam: Java, Ruby

etc.

(There are actually somewhere in the range of 10-25 "interests" for each worker, and I have around 40-50 workers)

At the same time, I have a very large set of tasks that need to be distributed among the workers. Each task has to be assigned to at least 3 workers, and the workers must match at least one of the tasks' interests:

Task 1: Ruby, XML
Task 2: XHTML, Python

and so on. So Bob, Fred, or Sam could get Task 1; Susan or Fred could get Task 2.

This is all stored in a database thusly:

```<code>Task
    id integer primary key
    name varchar

TaskInterests
    task_id integer
    interest_id integer

Workers
    id integer primary key
    name varchar
    max_assignments integer

WorkerInterests
    worker_id
    interest_id

Assignments
    task_id
    worker_id
    date_assigned
</code>```

Each worker has a maximum number of assignments they will do, around 10. Some interests are more rare than others (i.e. only 1 or 2 workers have listed them as a interest), some interests are more common (i.e. half of the workers list them).

The algorithm must:

Assign every task to 3 workers (it is
assumed that at least 3 of the
workers are interested in one of the
interests of the task).

Assign every worker 1 or more tasks

Ideally, the algorithm will:

Assign each worker a number of tasks proportional to their maximum assignments and the total number of tasks. For example, if Susan says she will do 20 tasks and most people will only do 10 tasks and there are 50 workers and 300 tasks, she should be assigned 12 tasks (20/10*(300/50)).

Assign a variety of tasks to each worker, so if Susan lists 4 interests she gets tasks that include 4 interests (rather than getting 10 tasks all with the same interest)

The most difficult aspect so far has been dealing with theses issues:

tasks having interests with few corresponding workers

workers who have few interests, especially

workers who have a few interests, for which there are relatively few tasks

答:
Try mapping your task to the stable marriage problem. Tasks become prospective wives `, and your staff become suitors.

You might want to add some extra algorithm for assigning preferences of each task to the staff, and vice-versa - you could assign some ideal proficiency neccessary for the components of each task, and then allow your staff to rank each task. You could assign a proficiency for each component that each staff member posses and use that to get each tasks preference in staff members.

Once you have the preferences then run the algorithm, post the results, then allow people to apply in pairs to you to swap assignments - after all this is a people problem and people work better when they have a degree of control.

Body:
(Before anyone asks, this is not homework.)

I have a set of workers with interests, i.e.:

Bob: Java, XML, Ruby

Susan: Java, HTML, Python

Fred: Python, Ruby

Sam: Java, Ruby

etc.

(There are actually somewhere in the range of 10-25 "interests" for each worker, and I have around 40-50 workers)

At the same time, I have a very large set of tasks that need to be distributed among the workers. Each task has to be assigned to at least 3 workers, and the workers must match at least one of the tasks' interests:

Task 1: Ruby, XML
Task 2: XHTML, Python

and so on. So Bob, Fred, or Sam could get Task 1; Susan or Fred could get Task 2.

This is all stored in a database thusly:

Task
    id integer primary key
    name varchar

TaskInterests
    task_id integer
    interest_id integer

Workers
    id integer primary key
    name varchar
    max_assignments integer

WorkerInterests
    worker_id
    interest_id

Assignments
    task_id
    worker_id
    date_assigned

Each worker has a maximum number of assignments they will do, around 10. Some interests are more rare than others (i.e. only 1 or 2 workers have listed them as a interest), some interests are more common (i.e. half of the workers list them).

The algorithm must:

Assign every task to 3 workers (it is
assumed that at least 3 of the
workers are interested in one of the
interests of the task).

Assign every worker 1 or more tasks

Ideally, the algorithm will:

Assign each worker a number of tasks proportional to their maximum assignments and the total number of tasks. For example, if Susan says she will do 20 tasks and most people will only do 10 tasks and there are 50 workers and 300 tasks, she should be assigned 12 tasks (20/10*(300/50)).

Assign a variety of tasks to each worker, so if Susan lists 4 interests she gets tasks that include 4 interests (rather than getting 10 tasks all with the same interest)

The most difficult aspect so far has been dealing with theses issues:

tasks having interests with few corresponding workers

workers who have few interests, especially

workers who have a few interests, for which there are relatively few tasks


问:
How can I use JSON data to populate the options of a select box?
I need to feed cities based on country of selection. I did it programmically but have no idea how to put JSON data into the select box. I tried several ways using jQuery, but none of them worked.

The response I am getting (I can format this differently if necessary):

```<code>["<option value='Woodland Hills'>Woodland Hills<\/option>","<option value='none'>none<\/option>","<option value='Los Angeles'>Los Angeles<\/option>","<option value='Laguna Hills'>Laguna Hills<\/option>"]
</code>```

But how can I put this data as options inside a HTML <select></select> tag?

The code I tried:

```<code><form action="" method="post">
<input id="city" name="city" type="text" onkeyup="getResults(this.value)"/>
<input type="text" id="result" value=""/>
<select id="myselect" name="myselect" ><option selected="selected">blank</option></select>
</form>
</div>

<script>
function getResults(str) {
  $.ajax({
        url:'suggest.html',
        type:'POST',
        data: 'q=' + str,
        dataType: 'json',
        success: function( json ) {
            $('#myselect').append(json);

        }
    });
};

$( '.suggest' ).keyup( function() {
   getResults( $( this ).val() );
} );
</script>
</code>```

I also tried to use this tutorial on auto-populating select boxes using jQuery and AJAX, but this never did anything except filling my select with "UNDEFINED" for me even though I got the response in the format the tutorial suggested.

```<code><script type="text/javascript" charset="utf-8">
$(function(){
  $("select#city").change(function(){
    $.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){
      var options = '';
      for (var i = 0; i < j.length; i++) {
        options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
      }
      $("select#myselect").html(options);
    })
  })
})
</script>
</code>```

答:
Take a look at JQuery view engine and just load the array into a dropdown:

```<code>$.ajax({
    url:'suggest.html',
    type:'POST',
    data: 'q=' + str,
    dataType: 'json',
    success: function( json ) {
          // Assumption is that API returned something like:["North","West","South","East"];
          $('#myselect').view(json);
    }
});
</code>```

See details here: https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown

Body:
I need to feed cities based on country of selection. I did it programmically but have no idea how to put JSON data into the select box. I tried several ways using jQuery, but none of them worked.

The response I am getting (I can format this differently if necessary):

["<option value='Woodland Hills'>Woodland Hills<\/option>","<option value='none'>none<\/option>","<option value='Los Angeles'>Los Angeles<\/option>","<option value='Laguna Hills'>Laguna Hills<\/option>"]

But how can I put this data as options inside a HTML <select></select> tag?

The code I tried:

<form action="" method="post">
<input id="city" name="city" type="text" onkeyup="getResults(this.value)"/>
<input type="text" id="result" value=""/>
<select id="myselect" name="myselect" ><option selected="selected">blank</option></select>
</form>

I also tried to use this tutorial on auto-populating select boxes using jQuery and AJAX, but this never did anything except filling my select with "UNDEFINED" for me even though I got the response in the format the tutorial suggested.

Body:
Take a look at JQuery view engine and just load the array into a dropdown:

$.ajax({
    url:'suggest.html',
    type:'POST',
    data: 'q=' + str,
    dataType: 'json',
    success: function( json ) {
          // Assumption is that API returned something like:["North","West","South","East"];
          $('#myselect').view(json);
    }
});

See details here: https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown


问:
rotate the marker with move direction
Iam developing android app with google map implemented. I have tried to make the marker rotate with the direction of moving (like navigation in google maps) but all tried codes failed. Below are the code. Any suggestion. Note(Iam getting the bearing from method that returns the location, speed and bering and I can see the float value of the bearing changes while changing the direction.</p>

```<code>                float bearing = setterandGetter.getBearing();
                double lat = setterandGetter.getLatitude();
                double lon = setterandGetter.getLongitude();
                LatLng currentPosition = new LatLng(latitudelongitude);

                googleMap.moveCamera(CameraUpdateFactory.newLatLng(currentPosition));

Marker marker = googleMap.addMarker(new MarkerOptions().position(currentPosition).icon(BitmapDescriptorFactory.fromBitmap(blueIcon)).flat(true).rotation(bearing));
</code>```

答:
Try this:

First of all declare marker varialble globally and initialise it i onCreate with following line :

```<code>marker = googleMap.addMarker(new MarkerOptions().position(currentPosition).icon(BitmapDescriptorFactory.fromBitmap(blueIcon)).flat(true).rotation(0));
</code>```

Now add following code in onLocationChanged():

```<code>map.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
       @Override
       public void onMyLocationChange(final Location location) {
       marker.setPosition(new LatLng(location.getLatitude(),location.getLongitude()))
       marker.setRotation(location.getBearing());
    }
});
</code>```

Title: rotate the marker with move direction

Body:
Iam developing android app with google map implemented. I have tried to make the marker rotate with the direction of moving (like navigation in google maps) but all tried codes failed. Below are the code. Any suggestion. Note(Iam getting the bearing from method that returns the location, speed and bering and I can see the float value of the bearing changes while changing the direction.

                float bearing = setterandGetter.getBearing();
                double lat = setterandGetter.getLatitude();
                double lon = setterandGetter.getLongitude();
                LatLng currentPosition = new LatLng(latitudelongitude);

                googleMap.moveCamera(CameraUpdateFactory.newLatLng(currentPosition));

Marker marker = googleMap.addMarker(new MarkerOptions().position(currentPosition).icon(BitmapDescriptorFactory.fromBitmap(blueIcon)).flat(true).rotation(bearing));

Body:
Try this:

First of all declare marker varialble globally and initialise it i onCreate with following line :

marker = googleMap.addMarker(new MarkerOptions().position(currentPosition).icon(BitmapDescriptorFactory.fromBitmap(blueIcon)).flat(true).rotation(0));

Now add following code in onLocationChanged():

map.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
       @Override
       public void onMyLocationChange(final Location location) {
       marker.setPosition(new LatLng(location.getLatitude(),location.getLongitude()))
       marker.setRotation(location.getBearing());
    }
});


问:
Making div background same height as body
i have been trying to solve this for like 2 hours now.. tried multiple guides, nothing worked.

Here is my css:

```<code>body {
margin:0;
background:url('chalk.jpeg');
}

html, body {
  height: 100%;
}

.welcome{
    text-align: center;
    position:relative;
    height:100%;
    background:rgba(38, 36, 15, 0.7);
}
</code>```

However, for some reason, the page looks like this: https://i.imgur.com/iPvMTk1.jpg

I want the welcome div background to be on top of the body background image until the end of the page. Tried many solutions but nothing would work.

答:
You can do it with viewport units where the body element takes 100% of the viewport height with the height: 100vh, then just stretch the .welcome div with height: 100%:

html, body {
  width: 100%;
  height: 100vh; /* 100% of the viewport height */
  margin: 0;
}

body {
  background: url('http://placehold.it/1600x900') no-repeat center center; /* modified */
  background-size: cover; /* recommended / also try the "contain" */
}

.welcome {
  text-align: center;
  position: relative;
  height: 100%;
  background: rgba(38, 36, 15, 0.7);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="welcome">welcome div</div></code>```

Body:
i have been trying to solve this for like 2 hours now.. tried multiple guides, nothing worked.

Here is my css:

body {
margin:0;
background:url('chalk.jpeg');
}

html, body {
  height: 100%;
}

.welcome{
    text-align: center;
    position:relative;
    height:100%;
    background:rgba(38, 36, 15, 0.7);
}

However, for some reason, the page looks like this: https://i.imgur.com/iPvMTk1.jpg

I want the welcome div background to be on top of the body background image until the end of the page. Tried many solutions but nothing would work.

Body:
You can do it with viewport units where the body element takes 100% of the viewport height with the height: 100vh, then just stretch the .welcome div with height: 100%:

html, body {
  width: 100%;
  height: 100vh; /* 100% of the viewport height */
  margin: 0;
}

body {
  background: url('http://placehold.it/1600x900') no-repeat center center; /* modified */
  background-size: cover; /* recommended / also try the "contain" */
}

.welcome {
  text-align: center;
  position: relative;
  height: 100%;
  background: rgba(38, 36, 15, 0.7);
}

<div class="welcome">welcome div</div>

ContentLicense: CC BY-SA 4.0


答:
Since java.lang.Object is an implicit base class of MioPunto (because it is a base class of all Java objects), method MioPunto.toString() is an override of Object.toString() method.

Since all objects have an implementation of toString(), Java compiler can freely add an invocation of toString() on any object in a chain of string concatenations performed with the + operator:

The string concatenation operator + (§15.18.1), which, when given a String operand and a reference, will convert the reference to a String by invoking the toString method of the referenced object (using "null" if either the reference or the result of toString is a null reference), and then will produce a newly created String that is the concatenation of the two strings.

Title: Implicitly calling a method in a class from main


问:
What are the advantages of installing programs in AppData like Google Chrome?
I just noticed that Chromium was installed in AppData in both Vista and XP. If Google does that and if other applications does this, than is that becuase there is some form of protection? Should we write installers that does the same thing as Google?</p>

答:
Frankly, I have yet to see the first installer that really allows both per-user and per-machine installations. Many installers offer this option in their GUI, but the setting only affects where the shortcuts etc. go -- the binaries always fo to %ProgramFiles%.

In fact, it is pretty hard to create Windows Installer packages that allow both kinds of installs, to say the least. With the advent of UAC, I'd say its is impossible: Per user installations must not require elevation, per machine installations have to. But whether an MSI package requires elevation is controlled via a bit in the summary information stream -- there is no way to have user input have impact on that.

Whether per-user or per-machine is the better choice greatly deoends on the application. For small packages, however, I tend to prefer per-user installations. Besides being slightly more user-friendly by not requiring an UAC prompt or runas, they also signalize the user that the setup will not do much harm to the computer (assuming he is a non-admin).

OwnerDisplayName: Ravi Chhabra

LastEditorDisplayName: charlesroper

OwnerDisplayName: JP

LastEditorDisplayName: JP


问:
display AM/PM format in time_select tag in rails
I am using

```<code><%= f.time_select :time_from ,  :minute_step => 15 %>
</code>```

to display time select option with a step of 15 mins.

Its showing 24hours clock. I want to show 12hour clock in display section (user view) and 24hour clock in value section (for back ground processing.).

答:
Here is 12 hour plugin for this.

http://code.google.com/p/rails-twelve-hour-time-plugin/

Body:
I am using

<%= f.time_select :time_from ,  :minute_step => 15 %>

to display time select option with a step of 15 mins.

Its showing 24hours clock. I want to show 12hour clock in display section (user view) and 24hour clock in value section (for back ground processing.).


答:
Try this query it will work for you

```<code>select SUM(REPLACE(REPLACE(fraised,'$',''), ',' , '')) as sum from frounds
</code>```

After updating you query your code will be

```<code>$result = mysqli_query($con,'select SUM(REPLACE(REPLACE(fraised,'$',''), ',' , '')) as sum from frounds');
$row1 = mysqli_fetch_assoc($result);
$sum = $row1['sum'];
echo $sum;
</code>```

Reason: you are getting zero due to the datatype of your column fraised which have values in the following format '$15,000,000'. In my solution, I relaced $ and comms.

Title: sum of field in different id's

Body:
Try this query it will work for you

select SUM(REPLACE(REPLACE(fraised,'$',''), ',' , '')) as sum from frounds

After updating you query your code will be

$result = mysqli_query($con,'select SUM(REPLACE(REPLACE(fraised,'$',''), ',' , '')) as sum from frounds');
$row1 = mysqli_fetch_assoc($result);
$sum = $row1['sum'];
echo $sum;

Reason: you are getting zero due to the datatype of your column fraised which have values in the following format '$15,000,000'. In my solution, I relaced $ and comms.


问:
Returning Wingdings characters within a text with an Excel formula
I want return appropriated Wingdings character at end of a string, with a formula as shown below:

enter image description here

Which formula can I write to return the shown Wingdings characters at the end of the regular string in a cell? (Instead of "?" character): Solid circle character for return in true situation of formula and hollow circle character return in false situation, so these two characters are in green range.

答:
A formula alone cannot change the font of part of a cell.

The best you could do is have a VBA function to make the change as needed, which you could run manually, or perhaps assign to a button, timer, event, etc.

This sub changes the last character of the currently active cell to Wingdings:

```<code>Sub LastLettWingding_Active()
    'changes the font for the last character of the **active** cell
    ActiveCell.Characters(Start:=Len(ActiveCell), Length:=1).Font.Name = "Wingdings"
End Sub
</code>```

...and this one does the same thing, but to the currently selected cell or range of cells:

```<code>Sub LastLettWingding_Selection()
    'changes the font for the last character of the all selected cells
    Dim c As Range
    For Each c In Application.Selection
        c.Characters(Start:=Len(c), Length:=1).Font.Name = "Wingdings"
    Next c
End Sub
</code>```

Edit:

I didn't realize it's a formula result that you're trying to format part of.

Unfortunately, Neither a formula nor VBA can change the font of part of a formula result.

My only suggestion would be to automate a Copy + Paste Values to a different cell, change the partial-formatting of that cell with the function above, and perhaps "hide" the original (formula) cell.

Edit #2:

Oh yeah-- @TomSharpe's also made the think that Unicode symbols might be an easier solution (included in most fonts, instead of using a separate font without the alphabet).

✂ ✃ ✄ ✅ ✆ ✇ ✈ ✉ ✊ ✋ ✌ ✍ ✎ ✏ ✐ ✲ ✳ ✴ ✵ ✶ ✷ ✸ ✹ ✺ ✻ ✼ ✽ ✾ ✿ ❀ ❁ ❂ ❃ ❄ ❅ ❆ ❇ ❈ ❉ ❊ ❋ ❌ ➮ ➯ ➰ ➱ ➲ ➳ ➴ ➵ ➶ ➷ ➸ ⌚ ⌛ ❶ ❷ ❸ ❹ ❺ ● ◌ ○ ◊ ◦ □ ┘ ⌂ ⅕⃝ Ω ℗ Ө Ӂ Φ ʘ ʘ ① ② ③ ④ ⑤ etc.

Click an empty cell and then on the Insert tab, click Symbol.  Make sure you're on a "regular" font (like Calibri) and scroll way down the list.

Double click the one(s) you want, then Insert.

Highlight the symbol now showing in the formula bar, copy from there, and now you can paste it into your IF formula.

(Or, just copy copy the symbols from above right into an Excel formula...)

Body:
A formula alone cannot change the font of part of a cell.

The best you could do is have a VBA function to make the change as needed, which you could run manually, or perhaps assign to a button, timer, event, etc.

This sub changes the last character of the currently active cell to Wingdings:

Sub LastLettWingding_Active()
    'changes the font for the last character of the **active** cell
    ActiveCell.Characters(Start:=Len(ActiveCell), Length:=1).Font.Name = "Wingdings"
End Sub

...and this one does the same thing, but to the currently selected cell or range of cells:

Sub LastLettWingding_Selection()
    'changes the font for the last character of the all selected cells
    Dim c As Range
    For Each c In Application.Selection
        c.Characters(Start:=Len(c), Length:=1).Font.Name = "Wingdings"
    Next c
End Sub

Edit:

I didn't realize it's a formula result that you're trying to format part of.

Unfortunately, Neither a formula nor VBA can change the font of part of a formula result.

My only suggestion would be to automate a Copy + Paste Values to a different cell, change the partial-formatting of that cell with the function above, and perhaps "hide" the original (formula) cell.

Edit #2:

Oh yeah-- @TomSharpe's also made the think that Unicode symbols might be an easier solution (included in most fonts, instead of using a separate font without the alphabet).

✂ ✃ ✄ ✅ ✆ ✇ ✈ ✉ ✊ ✋ ✌ ✍ ✎ ✏ ✐ ✲ ✳ ✴ ✵ ✶ ✷ ✸ ✹ ✺ ✻ ✼ ✽ ✾ ✿ ❀ ❁ ❂ ❃ ❄ ❅ ❆ ❇ ❈ ❉ ❊ ❋ ❌ ➮ ➯ ➰ ➱ ➲ ➳ ➴ ➵ ➶ ➷ ➸ ⌚ ⌛ ❶ ❷ ❸ ❹ ❺ ● ◌ ○ ◊ ◦ □ ┘ ⌂ ⅕⃝ Ω ℗ Ө Ӂ Φ ʘ ʘ ① ② ③ ④ ⑤ etc.

Click an empty cell and then on the Insert tab, click Symbol.  Make sure you're on a "regular" font (like Calibri) and scroll way down the list.

Double click the one(s) you want, then Insert.

Highlight the symbol now showing in the formula bar, copy from there, and now you can paste it into your IF formula.

(Or, just copy copy the symbols from above right into an Excel formula...)


问:
creating module-info for automatic modules with jdeps in java 9
I have 3 jar of jackson library

jackson-core-2.8.10.jar

jackson-annotations-2.8.0.jar

jackson-databind-2.8.10.jar

I created module-info.java for both core and annotation successfully and converted them to Named maodule using jdeps.

for databind , I tried following command:

jdeps --generate-module-info . --module-path %JAVA_HOME%\jomds;jackson.core;jackson.annotations existingmods\jackson-databind-2.8.10.jar

Now following error is occuring :

```<code>Missing dependence: .\jackson.databind\module-info.java not generated
Error: missing dependencies
   com.fasterxml.jackson.databind.AnnotationIntrospector -> com.fasterxml.jackson.annotation.JsonCreator       not found
   com.fasterxml.jackson.databind.AnnotationIntrospector -> com.fasterxml.jackson.annotation.JsonCreator$Mode  not found
   com.fasterxml.jackson.databind.AnnotationIntrospector -> com.fasterxml.jackson.annotation.JsonFormat        not found
   com.fasterxml.jackson.databind.AnnotationIntrospector -> com.fasterxml.jackson.annotation.JsonFormat$Value  not found
   com.fasterxml.jackson.databind.AnnotationIntrospector -> com.fasterxml.jackson.annotation.JsonIgnoreProperties not found
   com.fasterxml.jackson.databind.AnnotationIntrospector -> com.fasterxml.jackson.annotation.JsonIgnoreProperties$Value not found.
</code>```

How can I generate module-info.java for jackson-databind ?

答:
The short answer is that, yes, you'll have to convert the libraries to explicit modules.

The jlink tool is intended to provide a trimmed binary image that has only the required modules. The issue is that automatic modules have access to the classpath (aka the unnamed module) which can read all JDK modules. So nothing would be trimmed.

This thread states this as well, with a link to a YouTube video.

This example converts commons-lang3-3.5.jar to an explict module for a jlink demo.

Edit: to be more specific, here is an example script that converts, in order, jackson-core, jackson-annotations, and jackson-databind legacy jars to modular jars.

The idea is:

run jdeps --generate-module-info on the legacy jar

unzip the legacy jar into a folder, add module-info.java from above, re-compile, and re-zip

The trick is that modular jars with dependencies will require those dependencies as command-line parameters. For example, here is jackson-databind (abstracted somewhat):

```<code># here, jackson-core and jackson-annotations have been built
# jackson-databind

jdeps --module-path $ROOT_DIR/modules \
--add-modules jackson.annotations,jackson.core \
--generate-module-info work $JACKSON_DATABIND_JAR

javac --module-path $ROOT_DIR/modules \
--add-modules jackson.annotations,jackson.core \
-d $ROOT_DIR/classes module-info.java
</code>```

Body:
I have 3 jar of jackson library

jackson-core-2.8.10.jar

jackson-annotations-2.8.0.jar

jackson-databind-2.8.10.jar

I created module-info.java for both core and annotation successfully and converted them to Named maodule using jdeps.

for databind , I tried following command:

jdeps --generate-module-info . --module-path %JAVA_HOME%\jomds;jackson.core;jackson.annotations existingmods\jackson-databind-2.8.10.jar

Now following error is occuring :

Missing dependence: .\jackson.databind\module-info.java not generated
Error: missing dependencies
   com.fasterxml.jackson.databind.AnnotationIntrospector -> com.fasterxml.jackson.annotation.JsonCreator       not found
   com.fasterxml.jackson.databind.AnnotationIntrospector -> com.fasterxml.jackson.annotation.JsonCreator$Mode  not found
   com.fasterxml.jackson.databind.AnnotationIntrospector -> com.fasterxml.jackson.annotation.JsonFormat        not found
   com.fasterxml.jackson.databind.AnnotationIntrospector -> com.fasterxml.jackson.annotation.JsonFormat$Value  not found
   com.fasterxml.jackson.databind.AnnotationIntrospector -> com.fasterxml.jackson.annotation.JsonIgnoreProperties not found
   com.fasterxml.jackson.databind.AnnotationIntrospector -> com.fasterxml.jackson.annotation.JsonIgnoreProperties$Value not found.

How can I generate module-info.java for jackson-databind ?

Body:
The short answer is that, yes, you'll have to convert the libraries to explicit modules.

The jlink tool is intended to provide a trimmed binary image that has only the required modules. The issue is that automatic modules have access to the classpath (aka the unnamed module) which can read all JDK modules. So nothing would be trimmed.

This thread states this as well, with a link to a YouTube video.

This example converts commons-lang3-3.5.jar to an explict module for a jlink demo.

Edit: to be more specific, here is an example script that converts, in order, jackson-core, jackson-annotations, and jackson-databind legacy jars to modular jars.

The idea is:

run jdeps --generate-module-info on the legacy jar

unzip the legacy jar into a folder, add module-info.java from above, re-compile, and re-zip

The trick is that modular jars with dependencies will require those dependencies as command-line parameters. For example, here is jackson-databind (abstracted somewhat):

# here, jackson-core and jackson-annotations have been built
# jackson-databind

jdeps --module-path $ROOT_DIR/modules \
--add-modules jackson.annotations,jackson.core \
--generate-module-info work $JACKSON_DATABIND_JAR

javac --module-path $ROOT_DIR/modules \
--add-modules jackson.annotations,jackson.core \
-d $ROOT_DIR/classes module-info.java


问:
Which context should i use in a service?
I have two services in my application - lA_svc & lB_svc.

The MainActivity lauches lA_svc - which context should I use for launching the service from the activity?

Now lA_svc sends an intent to launch lB_svc - which context should I use here in the startService() method?

After a while, lB_svc sends an intent to launch lA_svc, which context do I use here?

Can you please link any gist(s), example(s) to understand the context as per which the services are to be launched?

答:
which context should I use for launching the service from the
  activity?

A Service can be started from every component. Since you are in an Activity I assume that you have access to two Context:

Activity context

Application context

It doesn't matter which one you use, but it makes more sense to me, to use the one of your enclosing component, so the Activity context (use this).

Now lA_svc sends an intent to launch lB_svc. - which context should I
  use here in the startService() method?

Again, you are allowed to start a service from every components, and again it makes sense to use the Context of your enclosing component, so Service context (just use this in your service).

After a while, lB_svc sends an intent to launch lA_svc, which context
  do I use here?

The problem here is the same: you want to start a Service from another Service. So just use your Service context.

The best article I have ever read about Context is this from Dave Smith.


问:
Facebook Login works only from API 24 - Local module descriptor class for com.google.firebase.auth not found. error
I added facebook login with firebase authentication on my application, but the login authentication works only from the Android API 24.

When I try to use a lower level API the screen freezes and the application stops working.

It is too high, most of the users have a lower API level.

Indeed I intend to release the application for lower API levels.

The code I am using is bellow.

```<code>public class ConfigurationActivity extends Activity {

    Button b_v_mm,b_som;
    LoginButton loginButton;
    CallbackManager callbackManager;

    // [START declare_auth]
    private FirebaseAuth mAuth;
    // [END declare_auth]

    private void handleFacebookAccessToken(AccessToken token) {
        Log.d("FireBase", "handleFacebookAccessToken:" + token);

        AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            Log.d("FireBase", "signInWithCredential:success");
                            FirebaseUser user = mAuth.getCurrentUser();
                            //updateUI(user);
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w("FireBase", "signInWithCredential:failure", task.getException());
                            //Toast.makeText(FacebookLoginActivity.this, "Authentication failed.",
                             //       Toast.LENGTH_SHORT).show();
                            //updateUI(null);
                        }

                        // ...
                    }
                });
    }

    // [START on_start_check_user]
    @Override
    public void onStart() {
        super.onStart();
        Log.d("FireBase", "onStart");
        // Check if user is signed in (non-null) and update UI accordingly.
        FirebaseUser currentUser = mAuth.getCurrentUser();
        //updateUI(currentUser);
    }
    // [END on_start_check_user]

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("LoginFace", "LoginFace - onActivityResult");
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("LoginFace", "LoginFace - onActivityResult");
        callbackManager.onActivityResult(requestCode, resultCode, data);
        Log.d("LoginFace", "LoginFace - After callbackManager");
/*
        if (AccessToken.getCurrentAccessToken() != null) {
            Log.d("AjudaFace", "AjudaFace - logout");
            LoginManager.getInstance().logOut();
        }*/
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_configuration);

        //Botãp da barra de ferramentas que faz retornar para o Menu principal.
        b_v_mm = (Button) findViewById(com.cerveja.qof.pedro.qof_cerveja.R.id.b_v_mm);
        b_v_mm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ConfigurationActivity.this, MainMenu.class);
                startActivity(intent);
                finish();
            }
        });

        b_som = (Button) findViewById(com.cerveja.qof.pedro.qof_cerveja.R.id.b_som);
        //Altera opções de som.
        b_som.setOnClickListener(new View.OnClickListener() {
                                      @Override
                                      public void onClick(View v) {

                                          //Carrega opções de texto do botão, armazenadas no repositório de strings
                                          String s_som_on = getString(R.string.b_som_on);
                                          String s_som_off = getString(R.string.b_som_off);

                                          //Caso o som esteja desligado, o desliga.
                                          if(b_som.getText().equals(s_som_on)) {
                                              b_som.setText(s_som_off);
                                          }
                                          else //Caso o som esteja desligado, o liga.
                                              if (b_som.getText().equals(s_som_off)){
                                                  b_som.setText(s_som_on);
                                              }
                                      }
                                  }
        );

        callbackManager = CallbackManager.Factory.create();

// ...
// Initialize Firebase Auth
        mAuth = FirebaseAuth.getInstance();

        loginButton = (LoginButton) findViewById(R.id.login_button);
        loginButton.setReadPermissions("email","public_profile");
        Log.d("LoginFace", "LoginFace - Button Created");

        // Callback registration
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                handleFacebookAccessToken(loginResult.getAccessToken());
                Log.d("LoginFace", "LoginFace - Sucesso");
                Toast.makeText(getApplicationContext(),
                        "LOGIN REALIZADO", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancel() {
                Log.d("LoginFace", "LoginFace - Cancelado");
                Toast.makeText(getApplicationContext(),
                        "LOGIN CANCELADO", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(FacebookException exception) {
                Log.d("LoginFace", "LoginFace - Erro");
                Toast.makeText(getApplicationContext(),
                        "LOGIN Erro", Toast.LENGTH_LONG).show();
                Log.d("LoginFace", exception.toString());
            }
        });

    }
}
</code>```

Objects used in MyApplication activity

```<code>import android.app.Application;
import android.content.Context;
</code>```

**All objects used in the project are listed above

API 23 log:

12-02 17:22:26.900 2668-2745/? D/EGL_emulation: eglMakeCurrent:
  0xaa9ba4e0: ver 2 0 (tinfo 0xac3853a0)

```<code>                                            [ 12-02 17:22:26.949  2668: 3361 D/         ]
                                            HostConnection::get() New Host Connection established 0xa19c5800, tid 3361

                                            [ 12-02 17:22:26.950  2668: 3361 W/         ]
                                            Unrecognized GLES max version string in extensions: ANDROID_EMU_CHECKSUM_HELPER_v1
</code>```

ANDROID_EMU_dma_v1  12-02 17:22:26.977 2668-3361/? D/EGL_emulation:
  eglCreateContext: 0xaa9ba900: maj 2 min 0 rcv 2 12-02 17:22:26.978
  2668-3361/? D/EGL_emulation: eglMakeCurrent: 0xaa9ba900: ver 2 0
  (tinfo 0xa23bf7e0) 12-02 17:22:26.980 2668-3361/? E/eglCodecCommon:
  glUtilsParamSize: unknow param 0x00008cdf 12-02 17:22:26.980
  2668-3361/? E/eglCodecCommon: glUtilsParamSize: unknow param
  0x00008824 12-02 17:22:26.980 2668-3361/? E/eglCodecCommon:
  glUtilsParamSize: unknow param 0x00008cdf 12-02 17:22:26.980
  2668-3361/? E/eglCodecCommon: glUtilsParamSize: unknow param
  0x00008824 12-02 17:22:27.135 2668-3361/? D/EGL_emulation:
  eglCreateContext: 0xaa9ba9c0: maj 2 min 0 rcv 2 12-02 17:22:27.136
  2668-3361/? D/EGL_emulation: eglMakeCurrent: 0xaa9ba9c0: ver 2 0
  (tinfo 0xa23bf7e0) 12-02 17:22:29.740
  2668-2668/com.cerveja.qof.pedro.qof_cerveja W/BindingManager: Cannot
  call determinedVisibility() - never saw a connection for the pid: 2668
  12-02 17:22:32.649 2668-2745/com.cerveja.qof.pedro.qof_cerveja
  D/EGL_emulation: eglMakeCurrent: 0xaa9ba4e0: ver 2 0 (tinfo
  0xac3853a0) 12-02 17:22:32.650
  2668-2745/com.cerveja.qof.pedro.qof_cerveja E/Surface:
  getSlotFromBufferLocked: unknown buffer: 0xb40bdc00 12-02 17:22:32.676
  2668-3361/com.cerveja.qof.pedro.qof_cerveja D/EGL_emulation:
  eglMakeCurrent: 0xaa9ba900: ver 2 0 (tinfo 0xa23bf7e0) 12-02
  17:22:32.687 2668-3361/com.cerveja.qof.pedro.qof_cerveja
  D/EGL_emulation: eglMakeCurrent: 0xaa9ba9c0: ver 2 0 (tinfo
  0xa23bf7e0) 12-02 17:22:32.704
  2668-2745/com.cerveja.qof.pedro.qof_cerveja D/EGL_emulation:
  eglMakeCurrent: 0xaa9ba4e0: ver 2 0 (tinfo 0xac3853a0) 12-02
  17:22:32.716 2668-2745/com.cerveja.qof.pedro.qof_cerveja
  E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf 12-02
  17:22:32.767 2668-3361/com.cerveja.qof.pedro.qof_cerveja
  D/EGL_emulation: eglMakeCurrent: 0xaa9ba900: ver 2 0 (tinfo
  0xa23bf7e0) 12-02 17:27:05.115
  2668-2711/com.cerveja.qof.pedro.qof_cerveja W/DynamiteModule: Local
  module descriptor class for com.google.firebase.auth not found.

This final one is probably the error cause:

12-02 17:27:05.115 2668-2711/com.cerveja.qof.pedro.qof_cerveja W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.

What can I do to lower the API level required?

答:
Try resync your client with your Firebase app, and add again the .json file.

In android studio 2.3 just click on tools>firebase and in the assistant check if your app is connected to.

And also make sure that the package name is correct in both facebook developers account and firebase console.

Use the latest Firebase library

Can you check your Google Play Services version?

The Android device should have Google Play services 9.0.0 or later

One of the reason for this problem could be, your Sign In Method inside Firebase > Auth Dashboard might be disabled

Body:
I added facebook login with firebase authentication on my application, but the login authentication works only from the Android API 24.

When I try to use a lower level API the screen freezes and the application stops working.

It is too high, most of the users have a lower API level.

Indeed I intend to release the application for lower API levels.

The code I am using is bellow.

public class ConfigurationActivity extends Activity {

    Button b_v_mm,b_som;
    LoginButton loginButton;
    CallbackManager callbackManager;

    // [START declare_auth]
    private FirebaseAuth mAuth;
    // [END declare_auth]

    private void handleFacebookAccessToken(AccessToken token) {
        Log.d("FireBase", "handleFacebookAccessToken:" + token);

        AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            Log.d("FireBase", "signInWithCredential:success");
                            FirebaseUser user = mAuth.getCurrentUser();
                            //updateUI(user);
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w("FireBase", "signInWithCredential:failure", task.getException());
                            //Toast.makeText(FacebookLoginActivity.this, "Authentication failed.",
                             //       Toast.LENGTH_SHORT).show();
                            //updateUI(null);
                        }

                        // ...
                    }
                });
    }

    // [START on_start_check_user]
    @Override
    public void onStart() {
        super.onStart();
        Log.d("FireBase", "onStart");
        // Check if user is signed in (non-null) and update UI accordingly.
        FirebaseUser currentUser = mAuth.getCurrentUser();
        //updateUI(currentUser);
    }
    // [END on_start_check_user]

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("LoginFace", "LoginFace - onActivityResult");
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("LoginFace", "LoginFace - onActivityResult");
        callbackManager.onActivityResult(requestCode, resultCode, data);
        Log.d("LoginFace", "LoginFace - After callbackManager");
/*
        if (AccessToken.getCurrentAccessToken() != null) {
            Log.d("AjudaFace", "AjudaFace - logout");
            LoginManager.getInstance().logOut();
        }*/
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_configuration);

        //Botãp da barra de ferramentas que faz retornar para o Menu principal.
        b_v_mm = (Button) findViewById(com.cerveja.qof.pedro.qof_cerveja.R.id.b_v_mm);
        b_v_mm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ConfigurationActivity.this, MainMenu.class);
                startActivity(intent);
                finish();
            }
        });

        b_som = (Button) findViewById(com.cerveja.qof.pedro.qof_cerveja.R.id.b_som);
        //Altera opções de som.
        b_som.setOnClickListener(new View.OnClickListener() {
                                      @Override
                                      public void onClick(View v) {

                                          //Carrega opções de texto do botão, armazenadas no repositório de strings
                                          String s_som_on = getString(R.string.b_som_on);
                                          String s_som_off = getString(R.string.b_som_off);

                                          //Caso o som esteja desligado, o desliga.
                                          if(b_som.getText().equals(s_som_on)) {
                                              b_som.setText(s_som_off);
                                          }
                                          else //Caso o som esteja desligado, o liga.
                                              if (b_som.getText().equals(s_som_off)){
                                                  b_som.setText(s_som_on);
                                              }
                                      }
                                  }
        );

        callbackManager = CallbackManager.Factory.create();

// ...
// Initialize Firebase Auth
        mAuth = FirebaseAuth.getInstance();

        loginButton = (LoginButton) findViewById(R.id.login_button);
        loginButton.setReadPermissions("email","public_profile");
        Log.d("LoginFace", "LoginFace - Button Created");

        // Callback registration
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                handleFacebookAccessToken(loginResult.getAccessToken());
                Log.d("LoginFace", "LoginFace - Sucesso");
                Toast.makeText(getApplicationContext(),
                        "LOGIN REALIZADO", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancel() {
                Log.d("LoginFace", "LoginFace - Cancelado");
                Toast.makeText(getApplicationContext(),
                        "LOGIN CANCELADO", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(FacebookException exception) {
                Log.d("LoginFace", "LoginFace - Erro");
                Toast.makeText(getApplicationContext(),
                        "LOGIN Erro", Toast.LENGTH_LONG).show();
                Log.d("LoginFace", exception.toString());
            }
        });

    }
}

Objects used in MyApplication activity

import android.app.Application;
import android.content.Context;

**All objects used in the project are listed above

API 23 log:

12-02 17:22:26.900 2668-2745/? D/EGL_emulation: eglMakeCurrent:
  0xaa9ba4e0: ver 2 0 (tinfo 0xac3853a0)

                                            [ 12-02 17:22:26.949  2668: 3361 D/         ]
                                            HostConnection::get() New Host Connection established 0xa19c5800, tid 3361

                                            [ 12-02 17:22:26.950  2668: 3361 W/         ]
                                            Unrecognized GLES max version string in extensions: ANDROID_EMU_CHECKSUM_HELPER_v1

ANDROID_EMU_dma_v1  12-02 17:22:26.977 2668-3361/? D/EGL_emulation:
  eglCreateContext: 0xaa9ba900: maj 2 min 0 rcv 2 12-02 17:22:26.978
  2668-3361/? D/EGL_emulation: eglMakeCurrent: 0xaa9ba900: ver 2 0
  (tinfo 0xa23bf7e0) 12-02 17:22:26.980 2668-3361/? E/eglCodecCommon:
  glUtilsParamSize: unknow param 0x00008cdf 12-02 17:22:26.980
  2668-3361/? E/eglCodecCommon: glUtilsParamSize: unknow param
  0x00008824 12-02 17:22:26.980 2668-3361/? E/eglCodecCommon:
  glUtilsParamSize: unknow param 0x00008cdf 12-02 17:22:26.980
  2668-3361/? E/eglCodecCommon: glUtilsParamSize: unknow param
  0x00008824 12-02 17:22:27.135 2668-3361/? D/EGL_emulation:
  eglCreateContext: 0xaa9ba9c0: maj 2 min 0 rcv 2 12-02 17:22:27.136
  2668-3361/? D/EGL_emulation: eglMakeCurrent: 0xaa9ba9c0: ver 2 0
  (tinfo 0xa23bf7e0) 12-02 17:22:29.740
  2668-2668/com.cerveja.qof.pedro.qof_cerveja W/BindingManager: Cannot
  call determinedVisibility() - never saw a connection for the pid: 2668
  12-02 17:22:32.649 2668-2745/com.cerveja.qof.pedro.qof_cerveja
  D/EGL_emulation: eglMakeCurrent: 0xaa9ba4e0: ver 2 0 (tinfo
  0xac3853a0) 12-02 17:22:32.650
  2668-2745/com.cerveja.qof.pedro.qof_cerveja E/Surface:
  getSlotFromBufferLocked: unknown buffer: 0xb40bdc00 12-02 17:22:32.676
  2668-3361/com.cerveja.qof.pedro.qof_cerveja D/EGL_emulation:
  eglMakeCurrent: 0xaa9ba900: ver 2 0 (tinfo 0xa23bf7e0) 12-02
  17:22:32.687 2668-3361/com.cerveja.qof.pedro.qof_cerveja
  D/EGL_emulation: eglMakeCurrent: 0xaa9ba9c0: ver 2 0 (tinfo
  0xa23bf7e0) 12-02 17:22:32.704
  2668-2745/com.cerveja.qof.pedro.qof_cerveja D/EGL_emulation:
  eglMakeCurrent: 0xaa9ba4e0: ver 2 0 (tinfo 0xac3853a0) 12-02
  17:22:32.716 2668-2745/com.cerveja.qof.pedro.qof_cerveja
  E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf 12-02
  17:22:32.767 2668-3361/com.cerveja.qof.pedro.qof_cerveja
  D/EGL_emulation: eglMakeCurrent: 0xaa9ba900: ver 2 0 (tinfo
  0xa23bf7e0) 12-02 17:27:05.115
  2668-2711/com.cerveja.qof.pedro.qof_cerveja W/DynamiteModule: Local
  module descriptor class for com.google.firebase.auth not found.

This final one is probably the error cause:

12-02 17:27:05.115 2668-2711/com.cerveja.qof.pedro.qof_cerveja W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.

What can I do to lower the API level required?


问:
Asking for a fix for R backtick operator
I am trying to import data from in xls format in R, but it reads the header incorrectly, instead of

```<code>X1
</code>```

R interprets the data as

```<code>`X1 `
</code>```

that makes writing complicated R syntax impossible.

How this issue can be resolved ?

答:
One can skip the header record and give your own column names with any number of R packages that read excel data. Here is an example with readxl::read_excel().

```<code>library(readxl)
data <- read_excel("./data/anExcelWorksheet.xlsx",
                   col_names=FALSE,
                   skip=1)
</code>```

Body:
I am trying to import data from in xls format in R, but it reads the header incorrectly, instead of

X1

R interprets the data as

`X1 `

that makes writing complicated R syntax impossible.

How this issue can be resolved ?

Body:
One can skip the header record and give your own column names with any number of R packages that read excel data. Here is an example with readxl::read_excel().

library(readxl)
data <- read_excel("./data/anExcelWorksheet.xlsx",
                   col_names=FALSE,
                   skip=1)


问:
`undefined reference to `sgtsv_'` when compiling a tridiagonal solver
I'm working on a problem for one of my computing courses and I was getting stuck in an error after trying to work through it for some time.

Specifically, I'm working on this Fortran routine:

```<code>program linsolve_sgtsv
implicit none
integer, parameter :: lda=10,ldb=lda,nrhs=1
real :: dl(lda-1),d(lda),du(lda-1),b(ldb,nrhs)
integer :: n,info

n = 10
dl(1:n-1) = 1+(1/11); d(1:n) = 2; du(1:n-1) = 1-(1/11)
b(1:n,1) = (/1,1,1,1,1,1,1,1,1,1/)
call sgtsv(n,nrhs,dl,d,du,b,ldb,info)
if (info==0) then
    print *, '--- x is ----------------'
    print '(g22.16)', b(1:n,1)
else
    print *, 'info = ',info
end if

end program linsolve_sgtsv
</code>```

This routine solves linear systems using gaussian elimination when the matrices are tridiagonal.

However, when I try to create a makefile using:

```<code>gfortran linsolve_sgtsv.f90 -o linsolve.f90
</code>```

I get the following errors:

```<code>tmp/ccCiRHve.o: In function `MAIN__':
linsolve_sgtsv.f90:(.text+0x100): undefined reference to `sgtsv_'
collect2: error: ld returned 1 exit status
</code>```

答:
I can't find any direct duplicate. Many people have similar problems, but they usually know a bit more and your question is more basic.

The tridiagonal solver sgtsv() is not a Fortran built-in subroutine. It is provided in a library called LAPACK and many other implementations (e.g., MKL). That means you must tell the compiler it should include (link) that library.

That is done by adding -llapack (-l means "link" and lapack is the name of the library which is stored in a file called liblapack.so or liblapack.a) at the end of the compile command.

You must have his library installed in your computer for the link flag to work. In many Linux distributions it is included in the repositories.

The correct line would be

```<code>gfortran linsolve_sgtsv.f90 -o linsolve -llapack
</code>```

If the library (liblapack.a or liblapack.so) is installed in some directory the compiler can't see, you must use

```<code>gfortran linsolve_sgtsv.f90 -o linsolve -L/path/to/liblapack -llapack
</code>```

See also gfortran LAPACK "undefined reference" error and your compiler's manual for more.

Notice I did -o linsolve instead of -o linsolve.f90. It is a very bad idea to name your executable file with a .f90 extension. Only Fortran source files should be named .f90.

There will be more problems in your code. They will appear when you start to test it. For example, yoy do

```<code> (1/11)
</code>```

this will not return the mathematical result of 1.0/11.0, it will return 0. Learn about integer division in Fortran. See Why are the elements of an array formatted as zeros when they are multiplied by 1/2 or 1/3? and Simple program, that only produce zeros, bug?

If you will find more problems after you can run your code, you can ask a new question.

I recommend to compile your programs with -g -fcheck=all -Wall to find more bugs and errors more easily.

Body:
I'm working on a problem for one of my computing courses and I was getting stuck in an error after trying to work through it for some time.

Specifically, I'm working on this Fortran routine:

program linsolve_sgtsv
implicit none
integer, parameter :: lda=10,ldb=lda,nrhs=1
real :: dl(lda-1),d(lda),du(lda-1),b(ldb,nrhs)
integer :: n,info

n = 10
dl(1:n-1) = 1+(1/11); d(1:n) = 2; du(1:n-1) = 1-(1/11)
b(1:n,1) = (/1,1,1,1,1,1,1,1,1,1/)
call sgtsv(n,nrhs,dl,d,du,b,ldb,info)
if (info==0) then
    print *, '--- x is ----------------'
    print '(g22.16)', b(1:n,1)
else
    print *, 'info = ',info
end if

end program linsolve_sgtsv

This routine solves linear systems using gaussian elimination when the matrices are tridiagonal.

However, when I try to create a makefile using:

gfortran linsolve_sgtsv.f90 -o linsolve.f90

I get the following errors:

tmp/ccCiRHve.o: In function `MAIN__':
linsolve_sgtsv.f90:(.text+0x100): undefined reference to `sgtsv_'
collect2: error: ld returned 1 exit status

Body:
I can't find any direct duplicate. Many people have similar problems, but they usually know a bit more and your question is more basic.

The tridiagonal solver sgtsv() is not a Fortran built-in subroutine. It is provided in a library called LAPACK and many other implementations (e.g., MKL). That means you must tell the compiler it should include (link) that library.

That is done by adding -llapack (-l means "link" and lapack is the name of the library which is stored in a file called liblapack.so or liblapack.a) at the end of the compile command.

You must have his library installed in your computer for the link flag to work. In many Linux distributions it is included in the repositories.

The correct line would be

gfortran linsolve_sgtsv.f90 -o linsolve -llapack

If the library (liblapack.a or liblapack.so) is installed in some directory the compiler can't see, you must use

gfortran linsolve_sgtsv.f90 -o linsolve -L/path/to/liblapack -llapack

See also gfortran LAPACK "undefined reference" error and your compiler's manual for more.

Notice I did -o linsolve instead of -o linsolve.f90. It is a very bad idea to name your executable file with a .f90 extension. Only Fortran source files should be named .f90.

There will be more problems in your code. They will appear when you start to test it. For example, yoy do

 (1/11)

this will not return the mathematical result of 1.0/11.0, it will return 0. Learn about integer division in Fortran. See Why are the elements of an array formatted as zeros when they are multiplied by 1/2 or 1/3? and Simple program, that only produce zeros, bug?

If you will find more problems after you can run your code, you can ask a new question.

I recommend to compile your programs with -g -fcheck=all -Wall to find more bugs and errors more easily.


问:
Error installing mysql2: Failed to build gem native extension
I am having some problems when trying to install mysql2 gem for Rails. When I try to install it by running bundle install or gem install mysql2 it gives me the following error:

Error installing mysql2: ERROR: Failed to build gem native extension.

How can I fix this and successfully install mysql2?

答:
I have several computers, 32 and 64 bits processor, they run on Ubuntu Linux, Maverick (10.10) release.

I had the same problem, and for me, the
sudo apt-get install libmysql-ruby libmysqlclient-dev
did the job!!!


问:
How to reduce gif quality using wand?
I have the following code

```<code>from wand.image import Image

def saveSizes(f, filename):
    scaled_width = 400
    scaled_hight = 400
    with Image() as finalImage:
        with Image(filename=f) as img:
            for frame in img.sequence:
                #frame.transform(resize="%dx%d" % (scaled_width, scaled_hight))
                frame.compression_quality = 75
                finalImage.sequence.append(frame)
        filename += '.gif'
        finalImage.save(filename = filename)
saveSizes('source_file.gif', 'dest_file')
</code>```

But the size of 'source_file.gif' is same as that of 'dest_file.gif'. Why is the "compression_quality" attribute not working?

Is there a better way to reduce the size of gif using wand or some other python lib.?

Also I am getting the following log in the console for every frame in the gif.

```<code>Exception ignored in: <bound method Resource.__del__ of <wand.sequence.SingleImage: 901eb12 (200x150)>>
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/site-packages/wand/resource.py", line 232, in __del__
    self.destroy()
  File "/usr/local/lib/python3.5/site-packages/wand/sequence.py", line 331, in destroy
    self.container.sequence[self.index] = self
  File "/usr/local/lib/python3.5/site-packages/wand/sequence.py", line 304, in index
    assert image
AssertionError:
</code>```

答:
compression_quality works fine with the source (whole file).

my working example with pdfs:

```<code>def ConvertFewPagePdfToPngs(pdf):
    with wand.image.Image(filename = pdf, resolution = 200) as source:

        source.compression_quality = 99
        imagess = source.sequence
        for i in range(len(imagess)):
            imagess[i].format = 'png'
            destFileName = r'path' # depends on i
            wand.image.Image(imagess[i]).save(filename=destFileName)
</code>```

When i tried apply compression_quality to one page i got same error as you show

Title: How to reduce gif quality using wand?

Body:
I have the following code

from wand.image import Image

def saveSizes(f, filename):
    scaled_width = 400
    scaled_hight = 400
    with Image() as finalImage:
        with Image(filename=f) as img:
            for frame in img.sequence:
                #frame.transform(resize="%dx%d" % (scaled_width, scaled_hight))
                frame.compression_quality = 75
                finalImage.sequence.append(frame)
        filename += '.gif'
        finalImage.save(filename = filename)
saveSizes('source_file.gif', 'dest_file')

But the size of 'source_file.gif' is same as that of 'dest_file.gif'. Why is the "compression_quality" attribute not working?

Is there a better way to reduce the size of gif using wand or some other python lib.?

Also I am getting the following log in the console for every frame in the gif.

Exception ignored in: <bound method Resource.__del__ of <wand.sequence.SingleImage: 901eb12 (200x150)>>
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/site-packages/wand/resource.py", line 232, in __del__
    self.destroy()
  File "/usr/local/lib/python3.5/site-packages/wand/sequence.py", line 331, in destroy
    self.container.sequence[self.index] = self
  File "/usr/local/lib/python3.5/site-packages/wand/sequence.py", line 304, in index
    assert image
AssertionError:

Body:
compression_quality works fine with the source (whole file).

my working example with pdfs:

def ConvertFewPagePdfToPngs(pdf):
    with wand.image.Image(filename = pdf, resolution = 200) as source:

        source.compression_quality = 99
        imagess = source.sequence
        for i in range(len(imagess)):
            imagess[i].format = 'png'
            destFileName = r'path' # depends on i
            wand.image.Image(imagess[i]).save(filename=destFileName)

When i tried apply compression_quality to one page i got same error as you show


问:
How to fetch data in Angular
can someone help me with getting number from http response in Angular 5 ? I don't now how to do it, I was searching at internet but Angular grow very fast so it doesn't help me. Thanks for any help !

My code:

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { User } from '../entities/User';

@Injectable()
export class UserService {

  private usersurl: 'http://localhost:8080/api/users';

  user: User;
  id: number;

  constructor(private http: HttpClient) {}

  isLoggedIn() {
    return this.user != null;
  }

  isAdmin() {
    return this.user.isAdmin;
  }

  unLoggin() {
    this.user = null;
  }

  login(username: string, password: string) {
    this.id = null;
    this.http.get<number>(`${this.usersurl}/verify?username=${username}&password=${password}`).subscribe(id => this.id = id);
    alert(this.id);
    if (this.id != null) {
      return true;
    } else {
      return false;
    }
  }

}
</code>```

It alert [object Object]
localhost:8080/api/users/verify returns for example 8 only 8 no json formated 8

答:
To make a Http call inside of Angular we can use the HttpClient. This requires us to import the HttpClientModule inside of our root module (app.module.ts):

```<code>import { HttpClientModule } from '@angular/common/http';
import { DataService } from './data.service';

// Omitted other dependencies for brevity
@NgModule({
  imports: [HttpClientModule],
  providers: [DataService],
})
export class AppModule {}
</code>```

Inside of our service (i.e. data.service.ts) which we've registered as a provider, we can inject HttpClient and use the get method:

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class DataService {
  ROOT_URL = 'http://your-api.com';

  constructor(private http: HttpClient) {}

  getUserId(username: string, password: string) {
    return this.http
      .get<number>(`${this.ROOT_URL}/verify?username=${username}&password=${password}`)
  }
}
</code>```

Inside of our Component we can then subscribe to the Observable emitted from our service:

```<code>import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-root',
  template: `
    <h1>UserId: {{userId}}</h1>
  `,
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  userId: number;

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.dataService
      .getUserId('test', 'password')
      .subscribe(id => this.userId = id);
  }
}
</code>```

Alternatively, we can use the Async pipe to let Angular handle the subscription:

```<code>import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-root',
  template: `
    <h1>UserId: {{userId$ | async}}</h1>
  `,
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  userId$: Observable<Number>;

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.userId$ = this.dataService.getUserId('test', 'password');
  }
}
</code>```

Title: How to fetch data in Angular

Body:
can someone help me with getting number from http response in Angular 5 ? I don't now how to do it, I was searching at internet but Angular grow very fast so it doesn't help me. Thanks for any help !

My code:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { User } from '../entities/User';

@Injectable()
export class UserService {

  private usersurl: 'http://localhost:8080/api/users';

  user: User;
  id: number;

  constructor(private http: HttpClient) {}

  isLoggedIn() {
    return this.user != null;
  }

  isAdmin() {
    return this.user.isAdmin;
  }

  unLoggin() {
    this.user = null;
  }

  login(username: string, password: string) {
    this.id = null;
    this.http.get<number>(`${this.usersurl}/verify?username=${username}&password=${password}`).subscribe(id => this.id = id);
    alert(this.id);
    if (this.id != null) {
      return true;
    } else {
      return false;
    }
  }

}

It alert [object Object]
localhost:8080/api/users/verify returns for example 8 only 8 no json formated 8

Body:
To make a Http call inside of Angular we can use the HttpClient. This requires us to import the HttpClientModule inside of our root module (app.module.ts):

import { HttpClientModule } from '@angular/common/http';
import { DataService } from './data.service';

// Omitted other dependencies for brevity
@NgModule({
  imports: [HttpClientModule],
  providers: [DataService],
})
export class AppModule {}

Inside of our service (i.e. data.service.ts) which we've registered as a provider, we can inject HttpClient and use the get method:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class DataService {
  ROOT_URL = 'http://your-api.com';

  constructor(private http: HttpClient) {}

  getUserId(username: string, password: string) {
    return this.http
      .get<number>(`${this.ROOT_URL}/verify?username=${username}&password=${password}`)
  }
}

Inside of our Component we can then subscribe to the Observable emitted from our service:

import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-root',
  template: `
    <h1>UserId: {{userId}}</h1>
  `,
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  userId: number;

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.dataService
      .getUserId('test', 'password')
      .subscribe(id => this.userId = id);
  }
}

Alternatively, we can use the Async pipe to let Angular handle the subscription:

import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-root',
  template: `
    <h1>UserId: {{userId$ | async}}</h1>
  `,
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  userId$: Observable<Number>;

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.userId$ = this.dataService.getUserId('test', 'password');
  }
}


问:
How to delay an image swap in DrRacket?
i am trying to make aan animation for my game in DrRacket, when i press the left button i want my image to do a running animation (legs open --> legs closed). Is there a way i can delay the image swap? The computer does the swap soo fast that you dont see the swap happening. -->

```<code>(define (keyboard-function key)
  (cond ((eq? key 'left) (tekenaar 'mario-next!)
                       ((mario-adt 'move) 'left)
                       (tekenaar 'mario-next!))
      ((eq? key 'right) ((mario-adt 'move) 'right)
                        (tekenaar 'mario-next!))
      (else (void))))
</code>```

Thanks

答:
You can't really make the computer delay the swap itself. What you can do is delay it yourself.

You could do this by keeping a counter you increment every frame. When that counter reaches a certain number, you swap the images. This way, instead of swapping them every frame, you swap them every x frames.

An easy way to do this is as follows:

```<code>(define counter 0)
(set! counter (modulo (+ counter 1) 50))
(if (= counter 0)
    ; start drawing the other image)
</code>```

Title: How to delay an image swap in DrRacket?

Body:
i am trying to make aan animation for my game in DrRacket, when i press the left button i want my image to do a running animation (legs open --> legs closed). Is there a way i can delay the image swap? The computer does the swap soo fast that you dont see the swap happening. -->

(define (keyboard-function key)
  (cond ((eq? key 'left) (tekenaar 'mario-next!)
                       ((mario-adt 'move) 'left)
                       (tekenaar 'mario-next!))
      ((eq? key 'right) ((mario-adt 'move) 'right)
                        (tekenaar 'mario-next!))
      (else (void))))

Thanks

Body:
You can't really make the computer delay the swap itself. What you can do is delay it yourself.

You could do this by keeping a counter you increment every frame. When that counter reaches a certain number, you swap the images. This way, instead of swapping them every frame, you swap them every x frames.

An easy way to do this is as follows:

(define counter 0)
(set! counter (modulo (+ counter 1) 50))
(if (= counter 0)
    ; start drawing the other image)


问:
UITabbar items not showing until click following upgrade to Xcode 7
I have a UITabBar that was functioning well prior to my upgrade to Xcode 7 and now I can't figure out what's going on for the life of me. I've tried several solutions including setting the imageWithRenderingMode for each tab I create, trying to change the background color of the UITabBar to see if maybe the items were just white, and updating the icons themselves to new versions. My default selected tab shows up just fine, and then when I select another tab, the text shows up, but no image. ( The text persists and changes to the default gray when moving to another tab as well. )

I've attached a screenshot of what I'm seeing, and here's how I'm currently implementing the tabbar.

Function to create tabbar:

```<code>void MakeTabBar(id target)
{
    PFUser *currentUser = [PFUser currentUser];

    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.recentView = [[RecentView alloc] init];
    appDelegate.groupsView = [[GroupsView alloc] init];
    appDelegate.settingsView = [[SettingsView alloc] init];
    appDelegate.homeView = [[HomeView alloc] init];

    NavigationController *navController1 = [[NavigationController alloc] initWithRootViewController:appDelegate.recentView];
    NavigationController *navController2 = [[NavigationController alloc] initWithRootViewController:appDelegate.groupsView];
    NavigationController *navController4 = [[NavigationController alloc] initWithRootViewController:appDelegate.settingsView];
    NavigationController *navController5 = [[NavigationController alloc] initWithRootViewController:appDelegate.homeView];

    appDelegate.tabBarController = [[UITabBarController alloc] init];
    appDelegate.tabBarController.tabBar.translucent = NO;
    appDelegate.tabBarController.selectedIndex = DEFAULT_TAB;
    [[UITabBar appearance] setTintColor:COLOR_OUTGOING];

    NSMutableDictionary *customAttributes = [NSMutableDictionary dictionary];
    BOOL isAdmin = [currentUser[@"isAdmin"] boolValue];
    if(isAdmin){
        [customAttributes setObject:currentUser[@"isAdmin"] forKey:@"isAdmin"];
        appDelegate.peopleView = [[PeopleView alloc] init];
        NavigationController *navController3 = [[NavigationController alloc] initWithRootViewController:appDelegate.peopleView];
        appDelegate.tabBarController.viewControllers = @[navController5, navController1, navController2, navController3, navController4];
    } else{
        appDelegate.tabBarController.viewControllers = @[navController5, navController1, navController2, navController4];
    }

    BOOL isTester = [currentUser[@"isTestData"] boolValue];
    if(isTester){
        [customAttributes setObject:currentUser[@"isTestData"] forKey:@"isTestData"];
    }

    [appDelegate.window setRootViewController:appDelegate.tabBarController];
}
</code>```

Code in each view to create tab:

```<code>- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    {
        [self.tabBarItem setImage:[UIImage imageNamed:@"tab_consultants"]];
        self.tabBarItem.title = @"Consultants";
    }
    return self;
}
</code>```

答:
Even I faced the same issue.
I solved it by writing following code

```<code>let storyboard   = UIStoryboard.init(name: "Main", bundle: Bundle.main)
let vc1          = storyboard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
vc1.tabBarItem   = ESTabBarItem.init(ExampleIrregularityBasicContentView(), title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1"))
</code>```

Hope it will help you

Body:
I have a UITabBar that was functioning well prior to my upgrade to Xcode 7 and now I can't figure out what's going on for the life of me. I've tried several solutions including setting the imageWithRenderingMode for each tab I create, trying to change the background color of the UITabBar to see if maybe the items were just white, and updating the icons themselves to new versions. My default selected tab shows up just fine, and then when I select another tab, the text shows up, but no image. ( The text persists and changes to the default gray when moving to another tab as well. )

I've attached a screenshot of what I'm seeing, and here's how I'm currently implementing the tabbar.

Function to create tabbar:

void MakeTabBar(id target)
{
    PFUser *currentUser = [PFUser currentUser];

    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.recentView = [[RecentView alloc] init];
    appDelegate.groupsView = [[GroupsView alloc] init];
    appDelegate.settingsView = [[SettingsView alloc] init];
    appDelegate.homeView = [[HomeView alloc] init];

    NavigationController *navController1 = [[NavigationController alloc] initWithRootViewController:appDelegate.recentView];
    NavigationController *navController2 = [[NavigationController alloc] initWithRootViewController:appDelegate.groupsView];
    NavigationController *navController4 = [[NavigationController alloc] initWithRootViewController:appDelegate.settingsView];
    NavigationController *navController5 = [[NavigationController alloc] initWithRootViewController:appDelegate.homeView];

    appDelegate.tabBarController = [[UITabBarController alloc] init];
    appDelegate.tabBarController.tabBar.translucent = NO;
    appDelegate.tabBarController.selectedIndex = DEFAULT_TAB;
    [[UITabBar appearance] setTintColor:COLOR_OUTGOING];

    NSMutableDictionary *customAttributes = [NSMutableDictionary dictionary];
    BOOL isAdmin = [currentUser[@"isAdmin"] boolValue];
    if(isAdmin){
        [customAttributes setObject:currentUser[@"isAdmin"] forKey:@"isAdmin"];
        appDelegate.peopleView = [[PeopleView alloc] init];
        NavigationController *navController3 = [[NavigationController alloc] initWithRootViewController:appDelegate.peopleView];
        appDelegate.tabBarController.viewControllers = @[navController5, navController1, navController2, navController3, navController4];
    } else{
        appDelegate.tabBarController.viewControllers = @[navController5, navController1, navController2, navController4];
    }

    BOOL isTester = [currentUser[@"isTestData"] boolValue];
    if(isTester){
        [customAttributes setObject:currentUser[@"isTestData"] forKey:@"isTestData"];
    }

    [appDelegate.window setRootViewController:appDelegate.tabBarController];
}

Code in each view to create tab:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    {
        [self.tabBarItem setImage:[UIImage imageNamed:@"tab_consultants"]];
        self.tabBarItem.title = @"Consultants";
    }
    return self;
}

Body:
Even I faced the same issue.
I solved it by writing following code

let storyboard   = UIStoryboard.init(name: "Main", bundle: Bundle.main)
let vc1          = storyboard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
vc1.tabBarItem   = ESTabBarItem.init(ExampleIrregularityBasicContentView(), title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1"))

Hope it will help you