问:
Rails: Relation does not exist for reference with class name in production
I created two references in a migration that are aliases for a reference to my User table:

```<code>class CreateInvitations < ActiveRecord::Migration[5.0]
  def change
    create_table :invitations do |t|
      t.references :owner, references: :user, foreign_key: true # the owner
      t.references :invitee, references: :user, foreign_key: true # the invitee
      t.references :core_bot, foreign_key: true # the associated page (core_bot_active)
      t.string :email
      t.string :token

      t.timestamps

    end
  end
end
</code>```

In my User model:

```<code>  has_many :invitations, foreign_key: :owner_id
  has_many :invitations, foreign_key: :invitee_id, dependent: :destroy
</code>```

In my Invitation model:

```<code>  belongs_to :owner, class_name: :User
  belongs_to :invitee, class_name: :User
</code>```

Everything works well in development but when I try to migrate in production with Heroku heroku run rake db:migrate, I get the following error:

PG::UndefinedTable: ERROR:  relation "owners" does not exist : CREATE
  TABLE "invitations" ("id" serial primary key, "owner_id" integer,
  "invitee_id" integer, "core_bot_id" integer, "email" character
  varying, "token" character varying, "created_at" timestamp NOT NULL,
  "updated_at" timestamp NOT NULL, CONSTRAINT "fk_rails_59e24979a9"
  FOREIGN KEY ("owner_id")   REFERENCES "owners" ("id") , CONSTRAINT
  "fk_rails_00204dc74b" FOREIGN KEY ("invitee_id")   REFERENCES
  "invitees" ("id") , CONSTRAINT "fk_rails_34505bdb65" FOREIGN KEY
  ("core_bot_id")   REFERENCES "core_bots" ("id") )

I tried without references: :user but I get the same error.

Any idea what's wrong here?

答:
I don't how to fix your problem. But I allways creating migrations for Postgres DB with foreign keys like this:</p>

```<code>  def change
    create_table :invitations do |t|
      t.integer :owner_id
      t.integer :invitee_id
      t.references :core_bot, foreign_key: true # the associated page (core_bot_active)
      t.string :email
      t.string :token

      t.timestamps
    end
    add_index :invitations, :owner_id
    add_foreign_key :invitations, :users, column: :owner_id
    add_index :invitations, :invitee_id
    add_foreign_key :invitations, :users, column: :invitee_id
  end
</code>```

Body:
I created two references in a migration that are aliases for a reference to my User table:

class CreateInvitations < ActiveRecord::Migration[5.0]
  def change
    create_table :invitations do |t|
      t.references :owner, references: :user, foreign_key: true # the owner
      t.references :invitee, references: :user, foreign_key: true # the invitee
      t.references :core_bot, foreign_key: true # the associated page (core_bot_active)
      t.string :email
      t.string :token

      t.timestamps

    end
  end
end

In my User model:

  has_many :invitations, foreign_key: :owner_id
  has_many :invitations, foreign_key: :invitee_id, dependent: :destroy

In my Invitation model:

  belongs_to :owner, class_name: :User
  belongs_to :invitee, class_name: :User

Everything works well in development but when I try to migrate in production with Heroku heroku run rake db:migrate, I get the following error:

PG::UndefinedTable: ERROR:  relation "owners" does not exist : CREATE
  TABLE "invitations" ("id" serial primary key, "owner_id" integer,
  "invitee_id" integer, "core_bot_id" integer, "email" character
  varying, "token" character varying, "created_at" timestamp NOT NULL,
  "updated_at" timestamp NOT NULL, CONSTRAINT "fk_rails_59e24979a9"
  FOREIGN KEY ("owner_id")   REFERENCES "owners" ("id") , CONSTRAINT
  "fk_rails_00204dc74b" FOREIGN KEY ("invitee_id")   REFERENCES
  "invitees" ("id") , CONSTRAINT "fk_rails_34505bdb65" FOREIGN KEY
  ("core_bot_id")   REFERENCES "core_bots" ("id") )

I tried without references: :user but I get the same error.

Any idea what's wrong here?

Body:
I don't how to fix your problem. But I allways creating migrations for Postgres DB with foreign keys like this:

  def change
    create_table :invitations do |t|
      t.integer :owner_id
      t.integer :invitee_id
      t.references :core_bot, foreign_key: true # the associated page (core_bot_active)
      t.string :email
      t.string :token

      t.timestamps
    end
    add_index :invitations, :owner_id
    add_foreign_key :invitations, :users, column: :owner_id
    add_index :invitations, :invitee_id
    add_foreign_key :invitations, :users, column: :invitee_id
  end


来源: stackexchange

问:
Jquery click function with image src
I have an image which is as below

```<code> <img alt="" style="cursor: pointer" src="images/plus.png" width="20" height="20" />
</code>```

And I'm changing this img src alternatively by using the below code

```<code>1. $("[src*=plus]").click( function () {
                    $(this).attr("src", "images/minus.png");
                });
2.  $("[src*=minus]").click(function () {
                $(this).attr("src", "images/plus.png");
            });
</code>```

The first function is working as expected- when I click on the button for the first time the image is changing to 'minus',but when I click on this changed  'minus' image  the function call is going again to the same first function.
What am I doing wrong here.
Please help.

Referred  following link Changing the image source using jQuery

答:
You need to use

```<code>$(document).on('click', '[src*=plus]', function(event) {
    $(event.target).attr("src", "https://png.icons8.com/color/100/minus");
});
$(document).on('click', '[src*=minus]', function() {
    $(event.target).attr("src", "https://png.icons8.com/color/100/plus");
});
</code>```

The img with src*=minus doesn't exist initially when the event handlers are attached, hence we need to use $(document).on('click', 'selector', handler) thereby attaching handlers on the document.

Working Fiddle:
https://jsfiddle.net/wrfscfw1/1/

ContentLicense: CC BY-SA 3.0

Title: Jquery click function with image src

Body:
I have an image which is as below

And I'm changing this img src alternatively by using the below code

1. $("[src*=plus]").click( function () {
                    $(this).attr("src", "images/minus.png");
                });
2.  $("[src*=minus]").click(function () {
                $(this).attr("src", "images/plus.png");
            });

The first function is working as expected- when I click on the button for the first time the image is changing to 'minus',but when I click on this changed  'minus' image  the function call is going again to the same first function.
What am I doing wrong here.
Please help.

Referred  following link Changing the image source using jQuery

Body:
You need to use

$(document).on('click', '[src*=plus]', function(event) {
    $(event.target).attr("src", "https://png.icons8.com/color/100/minus");
});
$(document).on('click', '[src*=minus]', function() {
    $(event.target).attr("src", "https://png.icons8.com/color/100/plus");
});

The img with src*=minus doesn't exist initially when the event handlers are attached, hence we need to use $(document).on('click', 'selector', handler) thereby attaching handlers on the document.

Working Fiddle:
https://jsfiddle.net/wrfscfw1/1/


问:
Importing a weather snapshot/image
I'm working on cube satellite project where I've got a code in python, that can translate the Two Line Element codes of satellites and project it's current location on a globe and Mercator map. So far so good. However I need to implement a few more functions for this project, and one of them is the ability to add a most current weather map of the longitude/latitude position of the satellite.

So for now I've decided to go with openweathermap.org since its easy to pull up the map with long/lat parameters.

Such as seen here: Open Map

However this is obviously not a image I can call out by standard imaging load in techniques. So how would you suggest I go about "snapping" out the picture here? Or is there another approach you may recommend? I'm still quite new to Python and therefore I'm not sure of how best approach this.

Thanks for your time and advice.
Best regards.

答:
I had a similar task, basically you want to use a webdriver and one of the most popular one is called selenium.

1) You have to install selenium via pip

```<code>pip install selenium
</code>```

2) Additionally you need to install a webdriver, In the example I am showing I've used chromedriver, which you can download from here. Extract and put it some place where it is seen by your path variables in your Operating System.

```<code>from selenium import webdriver
import time
browser = webdriver.Chrome()
browser.get('http://openweathermap.org/weathermap?basemap=satellite&cities=false&layer=precipitation&lat=39.3003&lon=4.9219&zoom=6')
time.sleep(5)             #Give it some time to load the images
browser.save_screenshot('screenie.png')
browser.quit()
</code>```

Title: Importing a weather snapshot/image

Body:
I had a similar task, basically you want to use a webdriver and one of the most popular one is called selenium.

1) You have to install selenium via pip

pip install selenium

2) Additionally you need to install a webdriver, In the example I am showing I've used chromedriver, which you can download from here. Extract and put it some place where it is seen by your path variables in your Operating System.

from selenium import webdriver
import time
browser = webdriver.Chrome()
browser.get('http://openweathermap.org/weathermap?basemap=satellite&cities=false&layer=precipitation&lat=39.3003&lon=4.9219&zoom=6')
time.sleep(5)             #Give it some time to load the images
browser.save_screenshot('screenie.png')
browser.quit()


问:
Dispatching new action after global state changes in react redux
Lets say i have a form where user is about to click on combination of buttons.

Each button triggers an action of type T and reducer R then updates its state and new combination is rendered on a website.

Now comes the tricky part:
I have my business logic implemented in reducer which applies new state which is about to be rendered. What i need now is when that state accepts a condition, i want to dispatch new action (api request).

What is the right approach to accomplish this kind of problem?

Set a flag into state, and call new action in component after?
Somehow dispatch a function in reducer?

...?

答:
In this case you could use library redux-saga.
Using redux-saga, you'll be able to create a saga that you call from a component like actions. In the saga you will be able to call several redux-actions. If your state will be valid from the saga, you can call the API request.
A popular alternative to redux-saga is also redux-thunk.</p>


问:
Printing only the duplicates from an int array and how many times they occur
I am trying to print only the duplicate elements from an array and how many times each of them appear.

Example:

```<code>Number 0 appears 3 times;
Number 12 appears 2 times;
Number 43 appears 2 times
</code>```

My code prints all the elements of the array rather than printing only duplicate elements.

I must mention that i cannot use HashMap, only conditional statments.

 Thanks
Below is the code :

```<code>    int[] array = new int[] { 12, 0, -22, 0, 43, 545, -4, -55, 12, 43, 0, -999, -87 };
    int counter = 0, temp = 0;// variable that holds the temporary value of each element
    Arrays.sort(array);
    for (int i = 0; i < array.length; i++) {
        temp = array[i];
        counter = 0;
        for (int j = 0; j < array.length; j++) {
            if (temp == array[j]) {
                counter++;
            }
        }
        System.out.println("Number:" + array[i] + "occurs :" + counter + " times");
    }
</code>```

答:
Try this: </p>

```<code>package com.stackoverflow.java;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class DuplicatesAndCount {
    public static void main(String[] args) {
    int[] array = new int[]{12, 0, -22, 0, 43, 545, -4, -55, 12, 43, 0, -999, -87};

    // taking hashmap to accumulate corresponding couter of each number
     HashMap<Integer, Integer> ht = new HashMap<Integer, Integer>();
     for (Integer newNumber : array) {
        if (ht.get(newNumber) == null) {
            ht.put(newNumber, 1);
        } else {
            ht.put(newNumber, ht.get(newNumber) + 1);
         }

    }

  System.out.println(ht);
 // now iterate the map
 for (Map.Entry<String, Integer> entry : map.entrySet()) {
    Integer number = entry.getKey();
    Integer count = entry.getValue();
    if (count > 1) {
        System.out.println("Number: " + number + "count: " + count);
    }
  }
}
}
</code>```

Body:
I am trying to print only the duplicate elements from an array and how many times each of them appear.

Example:

Number 0 appears 3 times;
Number 12 appears 2 times;
Number 43 appears 2 times

My code prints all the elements of the array rather than printing only duplicate elements.

I must mention that i cannot use HashMap, only conditional statments.

 Thanks
Below is the code :

    int[] array = new int[] { 12, 0, -22, 0, 43, 545, -4, -55, 12, 43, 0, -999, -87 };
    int counter = 0, temp = 0;// variable that holds the temporary value of each element
    Arrays.sort(array);
    for (int i = 0; i < array.length; i++) {
        temp = array[i];
        counter = 0;
        for (int j = 0; j < array.length; j++) {
            if (temp == array[j]) {
                counter++;
            }
        }
        System.out.println("Number:" + array[i] + "occurs :" + counter + " times");
    }

Body:
Try this:

package com.stackoverflow.java;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class DuplicatesAndCount {
    public static void main(String[] args) {
    int[] array = new int[]{12, 0, -22, 0, 43, 545, -4, -55, 12, 43, 0, -999, -87};

    // taking hashmap to accumulate corresponding couter of each number
     HashMap<Integer, Integer> ht = new HashMap<Integer, Integer>();
     for (Integer newNumber : array) {
        if (ht.get(newNumber) == null) {
            ht.put(newNumber, 1);
        } else {
            ht.put(newNumber, ht.get(newNumber) + 1);
         }

    }

  System.out.println(ht);
 // now iterate the map
 for (Map.Entry<String, Integer> entry : map.entrySet()) {
    Integer number = entry.getKey();
    Integer count = entry.getValue();
    if (count > 1) {
        System.out.println("Number: " + number + "count: " + count);
    }
  }
}
}


问:
Does JSON 'officially' Support Conversion of Native Types?
In PHP, you can use json_encode to encode an object as a json string.

```<code>$string = json_encode($some_object);
</code>```

However, PHP has the standard slew of datatypes which are not considered objects (ints, strings, etc.)  If you pass in a string to json_encode, this returns a string that contains a javascript statement that could be used to define the string.

In less awkward phrasing, this

```<code>echo json_encode("Hello
world, please don't " . '"' . "misuse quote's for emphasis " .  "or possessive apostrophes' ");
</code>```

will output this (a javascript ready string)

```<code>"Hello \n\tworld, please don't \"misuse quote'sor possessive apostrophes' "
</code>```

Is this behavior part of the JSON specification?  That is, does JSON define or recommend how an implementation should handle conversion of native, non-object, datatypes?  Or even have an opinion on conversion at all?  My reading of the RFC left this as ambiguous, but I'm crap at interpreting these things.

I ask because I'm interested in the likelihood of this behavior disappearing from a future version of the function.  i.e. If it's codified in a specification somewhere, it's less likely to disappear than if it was a one off someone thought to add on during development.

答:
You are right alan, the RFC is not clear enough on this issue.

On one hand, on the link to the RFC that you provide it says on the second paragraph of the introduction:

JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).

But on the other hand when you continue to the paragraph That talks about the actual JSON grammar it says:

A JSON text is a serialized object or array.

  JSON-text = object / array

So based on the grammar you can say that 'a string' does not qualify as valid JSON-text.

Personally I would prefer to see the grammar "fixed" to say
JSON-text = value  thus making any of false / null / true / object / array / number / string become valid JSON-text.

If you want to be strict for now, I would go with the semantics of the grammar.

I will send Douglas Crockford a link to this question maybe he can add some useful info.

ContentLicense: CC BY-SA 2.5

Body:
In PHP, you can use json_encode to encode an object as a json string.

$string = json_encode($some_object);

However, PHP has the standard slew of datatypes which are not considered objects (ints, strings, etc.)  If you pass in a string to json_encode, this returns a string that contains a javascript statement that could be used to define the string.

In less awkward phrasing, this

echo json_encode("Hello
world, please don't " . '"' . "misuse quote's for emphasis " .  "or possessive apostrophes' ");

will output this (a javascript ready string)

"Hello \n\tworld, please don't \"misuse quote'sor possessive apostrophes' "

Is this behavior part of the JSON specification?  That is, does JSON define or recommend how an implementation should handle conversion of native, non-object, datatypes?  Or even have an opinion on conversion at all?  My reading of the RFC left this as ambiguous, but I'm crap at interpreting these things.

I ask because I'm interested in the likelihood of this behavior disappearing from a future version of the function.  i.e. If it's codified in a specification somewhere, it's less likely to disappear than if it was a one off someone thought to add on during development.


问:
Multiple datasets on the same scatter plot
I want to plot multiple data sets on the same scatter plot:

```<code>cases = scatter(x[:4], y[:4], s=10, c='b', marker="s")
controls = scatter(x[4:], y[4:], s=10, c='r', marker="o")

show()
</code>```

The above only shows the most recent scatter()

I've also tried:

```<code>plt = subplot(111)
plt.scatter(x[:4], y[:4], s=10, c='b', marker="s")
plt.scatter(x[4:], y[4:], s=10, c='r', marker="o")
show()
</code>```

答:
I came across this question as I had exact same problem. Although accepted answer works good but with matplotlib version 2.1.0, it is pretty straight forward to have two scatter plots in one plot without using a reference to Axes

```<code>import matplotlib.pyplot as plt

plt.scatter(x,y, c='b', marker='x', label='1')
plt.scatter(x, y, c='r', marker='s', label='-1')
plt.legend(loc='upper left')
plt.show()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to plot multiple data sets on the same scatter plot:

cases = scatter(x[:4], y[:4], s=10, c='b', marker="s")
controls = scatter(x[4:], y[4:], s=10, c='r', marker="o")

show()

The above only shows the most recent scatter()

I've also tried:

plt = subplot(111)
plt.scatter(x[:4], y[:4], s=10, c='b', marker="s")
plt.scatter(x[4:], y[4:], s=10, c='r', marker="o")
show()

Body:
I came across this question as I had exact same problem. Although accepted answer works good but with matplotlib version 2.1.0, it is pretty straight forward to have two scatter plots in one plot without using a reference to Axes

import matplotlib.pyplot as plt

plt.scatter(x,y, c='b', marker='x', label='1')
plt.scatter(x, y, c='r', marker='s', label='-1')
plt.legend(loc='upper left')
plt.show()


答:
You can it either with HashMap or with Simple sorting, as your per comments simple method is as below

```<code>  int[] array = new int[]{12, 0, -22, 0, 43, 545, -4, -55, 12, 43, 0, -999, -87};
                int counter = 0,
                temp = 0;//variable that holds the temporary value of each element
                Arrays.sort(array);
                temp=array[0];
                int count=1;
                for(int i=1;i<array.length;i++)
                {
                    //System.out.println(array[i]);
                    if(temp==array[i])
                    {
                        count++;
                    }
                    else
                    {
                        if(count==1)
                        {
                            count=1;

                        }
                        else{
                        System.out.println(array[i-1]+" "+count);
                        count=1;
                        }
                        temp=array[i];
                    }
                }
</code>```

Title: Printing only the duplicates from an int array and how many times they occur

Body:
You can it either with HashMap or with Simple sorting, as your per comments simple method is as below

  int[] array = new int[]{12, 0, -22, 0, 43, 545, -4, -55, 12, 43, 0, -999, -87};
                int counter = 0,
                temp = 0;//variable that holds the temporary value of each element
                Arrays.sort(array);
                temp=array[0];
                int count=1;
                for(int i=1;i<array.length;i++)
                {
                    //System.out.println(array[i]);
                    if(temp==array[i])
                    {
                        count++;
                    }
                    else
                    {
                        if(count==1)
                        {
                            count=1;

                        }
                        else{
                        System.out.println(array[i-1]+" "+count);
                        count=1;
                        }
                        temp=array[i];
                    }
                }


问:
Applet: connect to other host
Hallo,

Now, in my one site applet loads from A host and it should work with
B host. But When I tried to do it I got

java.security.AccessControlException: access denied (java.net.SocketPermission MY_URL:443 connect,resolve)

exception. Applet is signed. I have added crossdomain.xml to B host too, but it is not help.

Are there any solution of this issue?

crossdomain.xml:

```<code><?xml version="1.0"?>
<!-- http://192.168.0.199/crossdomain.xml -->
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
  <allow-access-from domain="*"/>
  <allow-http-request-headers-from domain="*" headers="Authorization,X-HTTP-Method-Override"/>
</cross-domain-policy>
</code>```

答: I dont think there is a solution. An applet is allowed to contact only the server that it has been downloaded from. Regards, - M.S.</p>

Title: Applet: connect to other host

Body:
Hallo,

Now, in my one site applet loads from A host and it should work with
B host. But When I tried to do it I got

java.security.AccessControlException: access denied (java.net.SocketPermission MY_URL:443 connect,resolve)

exception. Applet is signed. I have added crossdomain.xml to B host too, but it is not help.

Are there any solution of this issue?

crossdomain.xml:

<?xml version="1.0"?>

<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
  <allow-access-from domain="*"/>
  <allow-http-request-headers-from domain="*" headers="Authorization,X-HTTP-Method-Override"/>
</cross-domain-policy>


问:
Julia interrupt model solver and resume it
I'm running an optimization problem on Atom, using Julia.

The solver I use is Gurobi:

```<code>m=Model(solver=GurobiSolver())
...
solve(m)
</code>```

My model may need hours to days of computation to reach the optimal value, so I would like to know if I can do the following when solve() is running :

```<code>1. Interrupt upon interrupting/stopping Julia
2. Interrupt if the objective function returns a sufficiently good result
3. Interrupt after a set time
</code>```

and then display and save the current state reached so I can resume the computation later.

答: Set SolutionLimit or TimeLimit as GurobiSolver parameters</p>

Body:
I'm running an optimization problem on Atom, using Julia.

The solver I use is Gurobi:

m=Model(solver=GurobiSolver())
...
solve(m)

My model may need hours to days of computation to reach the optimal value, so I would like to know if I can do the following when solve() is running :

1. Interrupt upon interrupting/stopping Julia
2. Interrupt if the objective function returns a sufficiently good result
3. Interrupt after a set time

and then display and save the current state reached so I can resume the computation later.


问:
Plot line from pandas dataframe in Python
I have the dataframe below in pandas currently

```<code>|  x  | ID   | Num
|-----|------|-----
|  1  | 100  | 35
|  2  | 100  | 50
|  3  | 150  | 34
|  4  | 150  | 25
|  5  | 150  | 46
|  6  | 200  | 13
|  7  | 200  | 75
|  8  | 100  | 37
|  9  | 150  | 61
</code>```

I'm trying to create a multi-line graph where the 'x' column is the index and on the x-axis, while the ID and Num columns form the lines.

I tried to do a single line version with just x and ID with the following code, but it returns nothing, and I'm not sure how to upgrade to a two line graph.

```<code>s1 = df_iter.resample('LowestAcceptedValue')
s2 = df_iter.resample('SwapsValue')
df = pd.concat([s1, s2], axis=1)
df.plot()
</code>```

答:
Try this:</p>

```<code>import pandas as pd
import matplotlib.pyplot as plt

df = {'ID': [100, 100,150], 'Num': [35,50,34]}
df = pd.DataFrame(data=df)

df.plot()
plt.xticks(df.index.values )
plt.show()
</code>```

Body:
I have the dataframe below in pandas currently

|  x  | ID   | Num
|-----|------|-----
|  1  | 100  | 35
|  2  | 100  | 50
|  3  | 150  | 34
|  4  | 150  | 25
|  5  | 150  | 46
|  6  | 200  | 13
|  7  | 200  | 75
|  8  | 100  | 37
|  9  | 150  | 61

I'm trying to create a multi-line graph where the 'x' column is the index and on the x-axis, while the ID and Num columns form the lines.

I tried to do a single line version with just x and ID with the following code, but it returns nothing, and I'm not sure how to upgrade to a two line graph.

s1 = df_iter.resample('LowestAcceptedValue')
s2 = df_iter.resample('SwapsValue')
df = pd.concat([s1, s2], axis=1)
df.plot()

Body:
Try this:

import pandas as pd
import matplotlib.pyplot as plt

df = {'ID': [100, 100,150], 'Num': [35,50,34]}
df = pd.DataFrame(data=df)

df.plot()
plt.xticks(df.index.values )
plt.show()


问:
Return variable from class defined in another thread
I'm programming an audio visualizer. To sync the data that is to be displayed to the music itself, I need to get the clip's/player's current position in the audio file by calling clip.getMicrosecondPosition() / player.getPosition(). This is working fine for the clip. The problem is that I need to define the player object in another thread since calling player.play() halts all execution in the current thread until the file is played until the end. Player is a class from the MP3SPI library (javazoom.jl.player.Player).

Code:

```<code>public class AudioTools implements Runnable {

public File file;
public boolean isMP3 = false;
public Player player;
public Clip clip;

public AudioTools(File file) {
    this.file = file;
    determineFilyType();
}

private void determineFileType() {
    if (file.getAbsolutePath().endsWith(".mp3")) {
        this.isMP3 = true;
    } else if (file.getAbsolutePath().endsWith(".wav")) {
        this.isMP3 = false;
    } else {
        System.err.println("Invalid File Type!");
        System.exit(0);
    }

}

public void play() {
    if (isMP3) {
        Thread t = new Thread(this);
        t.start(); // play MP3 using Player class
    } else {
        playWav(file); // play WAV using Clip class
    }

}

protected void playMP3(File file){
    try {
        player = new Player(new FileInputStream(file));
        player.play();
    } catch (Exception e) {
        System.out.println("Invalid MP3 File!");
        e.printStackTrace();
        System.exit(0);
    }

}

@Override
public void run() {
    playMP3(file);
}

private void playWav(File file) {
    try {
        AudioInputStream ais = AudioSystem.getAudioInputStream(file);
        DataLine.Info dataInfo = new DataLine.Info(Clip.class, null);
        clip = (Clip) AudioSystem.getLine(dataInfo);
        clip.open(ais);
        clip.start();
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Invalid .wav file!");
        System.exit(0);
    }
}
</code>```

}

Main class:

```<code>public static void main(String[] args) {

File file = new File(/*PATH_TO_FILE_HERE*/);
AudioTools at = new AudioTools(file);
at.play();
// at.clip.getMicrosecondPosition() works here if loaded file is .wav.
// at.player.getPosition() returns null if loaded file is .mp3.
}
</code>```

From the main class, I'd like to be able to get the player's current position. Currently, trying this will return null.

Any helpful comments are appreciated. I've asked a similar question before, this edit made the question a bit more clear and shorter.

EDIT: Should contain all code necissary to run the example.

答:
I am not sure if i completed understood your question but i will try to explain some things to you.

Lets say you have a class Clip where at a random time of 300ms to 1000ms (just for example) plays one second of the clip and sets the variable currentLength which is what you want to get from other thread.

```<code>public class Clip implements Runnable {

    private int clipLength;

    private volatile int currentLength;

    public Clip(int clipLength) {
        this.clipLength = clipLength;
    }

    public void run() {

        while (currentLength <= clipLength) {
            try {
                currentLength += 1;
                Thread.sleep(ThreadLocalRandom.current().nextInt(300, 1000 + 1));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public int getCurrentLength() {
        return currentLength;
    }

    public void setCurrentLength(int currentLength) {
        this.currentLength = currentLength;
    }

}
</code>```

Also lets say you have a class Player and what it does is that takes the clip object and after some time it requests the current length of it.

```<code>public class Player implements Runnable {

    private Clip clip;

    public Player(Clip clip) {
        this.clip = clip;
    }

    public void run() {
        try {
            Thread.sleep(1000);
            System.out.println(clip.getCurrentLength());
            Thread.sleep(2000);
            System.out.println(clip.getCurrentLength());
            Thread.sleep(1000);
            System.out.println(clip.getCurrentLength());
            Thread.sleep(3000);
            System.out.println(clip.getCurrentLength());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Also we have a Main class containg the start of the program where we create a Clip object and pass it to the to runnable class.

```<code>public class Main {
    public static void main(String[] args) {
        Clip clip = new Clip(60);
        Thread thread = new Thread(clip);
        thread.start();
        Thread threadPlayer = new Thread(new Player(clip));
        threadPlayer.start();

    }

}
</code>```

I think this is what you asked for but before implement it to your program you should read about atomic access and volatile keyword and also is good to know about the Java memory model.

Body:
I'm programming an audio visualizer. To sync the data that is to be displayed to the music itself, I need to get the clip's/player's current position in the audio file by calling clip.getMicrosecondPosition() / player.getPosition(). This is working fine for the clip. The problem is that I need to define the player object in another thread since calling player.play() halts all execution in the current thread until the file is played until the end. Player is a class from the MP3SPI library (javazoom.jl.player.Player).

Code:

public class AudioTools implements Runnable {

public File file;
public boolean isMP3 = false;
public Player player;
public Clip clip;

public AudioTools(File file) {
    this.file = file;
    determineFilyType();
}

private void determineFileType() {
    if (file.getAbsolutePath().endsWith(".mp3")) {
        this.isMP3 = true;
    } else if (file.getAbsolutePath().endsWith(".wav")) {
        this.isMP3 = false;
    } else {
        System.err.println("Invalid File Type!");
        System.exit(0);
    }

}

public void play() {
    if (isMP3) {
        Thread t = new Thread(this);
        t.start(); // play MP3 using Player class
    } else {
        playWav(file); // play WAV using Clip class
    }

}

protected void playMP3(File file){
    try {
        player = new Player(new FileInputStream(file));
        player.play();
    } catch (Exception e) {
        System.out.println("Invalid MP3 File!");
        e.printStackTrace();
        System.exit(0);
    }

}

@Override
public void run() {
    playMP3(file);
}

private void playWav(File file) {
    try {
        AudioInputStream ais = AudioSystem.getAudioInputStream(file);
        DataLine.Info dataInfo = new DataLine.Info(Clip.class, null);
        clip = (Clip) AudioSystem.getLine(dataInfo);
        clip.open(ais);
        clip.start();
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Invalid .wav file!");
        System.exit(0);
    }
}

}

Main class:

public static void main(String[] args) {

File file = new File(/*PATH_TO_FILE_HERE*/);
AudioTools at = new AudioTools(file);
at.play();
// at.clip.getMicrosecondPosition() works here if loaded file is .wav.
// at.player.getPosition() returns null if loaded file is .mp3.
}

From the main class, I'd like to be able to get the player's current position. Currently, trying this will return null.

Any helpful comments are appreciated. I've asked a similar question before, this edit made the question a bit more clear and shorter.

EDIT: Should contain all code necissary to run the example.

Body:
I am not sure if i completed understood your question but i will try to explain some things to you.

Lets say you have a class Clip where at a random time of 300ms to 1000ms (just for example) plays one second of the clip and sets the variable currentLength which is what you want to get from other thread.

public class Clip implements Runnable {

    private int clipLength;

    private volatile int currentLength;

    public Clip(int clipLength) {
        this.clipLength = clipLength;
    }

    public void run() {

        while (currentLength <= clipLength) {
            try {
                currentLength += 1;
                Thread.sleep(ThreadLocalRandom.current().nextInt(300, 1000 + 1));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public int getCurrentLength() {
        return currentLength;
    }

    public void setCurrentLength(int currentLength) {
        this.currentLength = currentLength;
    }

}

Also lets say you have a class Player and what it does is that takes the clip object and after some time it requests the current length of it.

public class Player implements Runnable {

    private Clip clip;

    public Player(Clip clip) {
        this.clip = clip;
    }

    public void run() {
        try {
            Thread.sleep(1000);
            System.out.println(clip.getCurrentLength());
            Thread.sleep(2000);
            System.out.println(clip.getCurrentLength());
            Thread.sleep(1000);
            System.out.println(clip.getCurrentLength());
            Thread.sleep(3000);
            System.out.println(clip.getCurrentLength());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Also we have a Main class containg the start of the program where we create a Clip object and pass it to the to runnable class.

public class Main {
    public static void main(String[] args) {
        Clip clip = new Clip(60);
        Thread thread = new Thread(clip);
        thread.start();
        Thread threadPlayer = new Thread(new Player(clip));
        threadPlayer.start();

    }

}

I think this is what you asked for but before implement it to your program you should read about atomic access and volatile keyword and also is good to know about the Java memory model.


问:
Manifest sync error
I wanted to go back and continue my android app after 4 month, what happend is that manifest doesn't sync with the following error:

```<code>Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(26.1.0) from [com.android.support:support-v13:26.1.0] AndroidManifest.xml:28:13-35
    is also present at [com.android.support:design:26.0.1] AndroidManifest.xml:28:13-35 value=(26.0.1).
    Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml:26:9-28:38 to override.
</code>```

and my manifest is:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.arnick.bazim"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 7
        versionName "0.9.5"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        manifestPlaceholders = [onesignal_app_id               : #the one signal app id,

                                onesignal_google_project_number: "REMOTE"]
    }
    applicationVariants.all { variant ->
        variant.resValue "string", "versionName", variant.versionName
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:support-v13:26.1.0'
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:cardview-v7:26.0.1'
    compile 'com.android.support:design:26.0.1'
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.android.support:customtabs:26.1.0'
    compile 'com.google.firebase:firebase-auth:11.6.2'
    compile 'com.google.android.gms:play-services-auth:11.6.2'

    compile('io.socket:socket.io-client:1.0.0') {
        // excluding org.json which is provided by Android
        exclude group: 'org.json', module: 'json'
    }
    compile 'com.onesignal:OneSignal:3.6.5'
    compile 'com.android.volley:volley:1.0.0'

    testCompile 'junit:junit:4.12'
}
</code>```

if that matters, I'm using local gralde version 4.2.1
I have also checked gradle 4.3.1 and non-local gradle but the error is still there.
Is there anything I am missing?
I remember about 5 6 months ago I faced the same issue I guess, and that was related to onesignal version but I do not remember what happened I just know I changed the version and error disappeared.

答:
use same version as at top of gradle file 26.0.2

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.arnick.bazim"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 7
        versionName "0.9.5"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        manifestPlaceholders = [onesignal_app_id               : #the one signal app id,

                                onesignal_google_project_number: "REMOTE"]
    }
    applicationVariants.all { variant ->
        variant.resValue "string", "versionName", variant.versionName
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:support-v13:26.0.2'
    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:cardview-v7:26.0.2'
    compile 'com.android.support:design:26.0.2'
    compile 'com.android.support:support-v4:26.0.2'
    compile 'com.android.support:customtabs:26.0.2'
    compile 'com.google.firebase:firebase-auth:11.6.2'
    compile 'com.google.android.gms:play-services-auth:11.6.2'

    compile('io.socket:socket.io-client:1.0.0') {
        // excluding org.json which is provided by Android
        exclude group: 'org.json', module: 'json'
    }
    compile 'com.onesignal:OneSignal:3.6.5'
    compile 'com.android.volley:volley:1.0.0'

    testCompile 'junit:junit:4.12'
}
</code>```

clean and rebuild this may help...

Title: Manifest sync error

Body:
I wanted to go back and continue my android app after 4 month, what happend is that manifest doesn't sync with the following error:

Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(26.1.0) from [com.android.support:support-v13:26.1.0] AndroidManifest.xml:28:13-35
    is also present at [com.android.support:design:26.0.1] AndroidManifest.xml:28:13-35 value=(26.0.1).
    Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml:26:9-28:38 to override.

and my manifest is:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.arnick.bazim"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 7
        versionName "0.9.5"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        manifestPlaceholders = [onesignal_app_id               : #the one signal app id,

                                onesignal_google_project_number: "REMOTE"]
    }
    applicationVariants.all { variant ->
        variant.resValue "string", "versionName", variant.versionName
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:support-v13:26.1.0'
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:cardview-v7:26.0.1'
    compile 'com.android.support:design:26.0.1'
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.android.support:customtabs:26.1.0'
    compile 'com.google.firebase:firebase-auth:11.6.2'
    compile 'com.google.android.gms:play-services-auth:11.6.2'

    compile('io.socket:socket.io-client:1.0.0') {
        // excluding org.json which is provided by Android
        exclude group: 'org.json', module: 'json'
    }
    compile 'com.onesignal:OneSignal:3.6.5'
    compile 'com.android.volley:volley:1.0.0'

    testCompile 'junit:junit:4.12'
}

if that matters, I'm using local gralde version 4.2.1
I have also checked gradle 4.3.1 and non-local gradle but the error is still there.
Is there anything I am missing?
I remember about 5 6 months ago I faced the same issue I guess, and that was related to onesignal version but I do not remember what happened I just know I changed the version and error disappeared.

Body:
use same version as at top of gradle file 26.0.2

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.arnick.bazim"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 7
        versionName "0.9.5"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        manifestPlaceholders = [onesignal_app_id               : #the one signal app id,

                                onesignal_google_project_number: "REMOTE"]
    }
    applicationVariants.all { variant ->
        variant.resValue "string", "versionName", variant.versionName
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:support-v13:26.0.2'
    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:cardview-v7:26.0.2'
    compile 'com.android.support:design:26.0.2'
    compile 'com.android.support:support-v4:26.0.2'
    compile 'com.android.support:customtabs:26.0.2'
    compile 'com.google.firebase:firebase-auth:11.6.2'
    compile 'com.google.android.gms:play-services-auth:11.6.2'

    compile('io.socket:socket.io-client:1.0.0') {
        // excluding org.json which is provided by Android
        exclude group: 'org.json', module: 'json'
    }
    compile 'com.onesignal:OneSignal:3.6.5'
    compile 'com.android.volley:volley:1.0.0'

    testCompile 'junit:junit:4.12'
}

clean and rebuild this may help...


问:
How to insert data to MySQL database in asp.net page?
i am trying to use MySQL 5 and asp.net 4

i succeed withe the linking and display the data from MySQL DB but the problem is within the DML Commands !!

please take a look to my code

```<code>Imports System.Data.SqlClient
Imports MySql.Data.MySqlClient

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim MyConnection As String = "server=localhost;User Id=root;password=123;database=cms"

        Dim Connection As New MySqlConnection(MyConnection)

        Connection.Open()

        Dim Sql As String = "INSERT INTO [CMS.tbimages] ( Title,Description) VALUES (parm2,parm3);"
        Dim cmd As New MySqlCommand(Sql, Connection)

        cmd.Parameters.Add(New MySqlParameter("parm2", "hajjaj"))
        cmd.Parameters.Add(New MySqlParameter("parm3", "hajjaj"))

        cmd.ExecuteNonQuery()
        cmd.Connection.Close()
    End Sub
End Class
</code>```

what i did is a simple page for testing the insert command , I added a button when i click on it it should do the insert command!!

but when i click it it gives me error :

#42000 You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server
  version for the right syntax to use
  near '[CMS.tbimages] (
  Title,Description) VALUES
  (parm2,parm3)' at line 1

not : i tried many other ways to change the insert statement :

"INSERT INTO [tbimages] ( [Title], [Description]) VALUES ( ? , ?)"

"INSERT INTO [tbimages] ([Title], [Description])

 VALUES (?Title , ?Description)"

INSERT INTO [tbimages] ( [Title], [Description]) VALUES (Title, Description)

答:
Try this:

```<code>Dim Sql As String = "INSERT INTO CMS.tbimages ( Title,Description) VALUES (?parm2,?parm3);"
Dim cmd As New MySqlCommand(Sql, Connection)

cmd.Parameters.Add(New MySqlParameter("?parm2", "hajjaj"))
cmd.Parameters.Add(New MySqlParameter("?parm3", "hajjaj"))
</code>```

Also, this tutorial may be of help.

Body:
i am trying to use MySQL 5 and asp.net 4

i succeed withe the linking and display the data from MySQL DB but the problem is within the DML Commands !!

please take a look to my code

Imports System.Data.SqlClient
Imports MySql.Data.MySqlClient

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim MyConnection As String = "server=localhost;User Id=root;password=123;database=cms"

        Dim Connection As New MySqlConnection(MyConnection)

        Connection.Open()

        Dim Sql As String = "INSERT INTO [CMS.tbimages] ( Title,Description) VALUES (parm2,parm3);"
        Dim cmd As New MySqlCommand(Sql, Connection)

        cmd.Parameters.Add(New MySqlParameter("parm2", "hajjaj"))
        cmd.Parameters.Add(New MySqlParameter("parm3", "hajjaj"))

        cmd.ExecuteNonQuery()
        cmd.Connection.Close()
    End Sub
End Class

what i did is a simple page for testing the insert command , I added a button when i click on it it should do the insert command!!

but when i click it it gives me error :

#42000 You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server
  version for the right syntax to use
  near '[CMS.tbimages] (
  Title,Description) VALUES
  (parm2,parm3)' at line 1

not : i tried many other ways to change the insert statement :

"INSERT INTO [tbimages] ( [Title], [Description]) VALUES ( ? , ?)"

"INSERT INTO [tbimages] ([Title], [Description])

 VALUES (?Title , ?Description)"

INSERT INTO [tbimages] ( [Title], [Description]) VALUES (Title, Description)

Body:
Try this:

Dim Sql As String = "INSERT INTO CMS.tbimages ( Title,Description) VALUES (?parm2,?parm3);"
Dim cmd As New MySqlCommand(Sql, Connection)

cmd.Parameters.Add(New MySqlParameter("?parm2", "hajjaj"))
cmd.Parameters.Add(New MySqlParameter("?parm3", "hajjaj"))

Also, this tutorial may be of help.


问:
"Error using newLatLngBounds(LatLngBounds, int): Map size can't be zero...." using react-native-maps on Android
I get an error:
"Error using newLatLngBounds(LatLngBounds, int): Map size can't be zero. Most likely layout has not yet occured for the map view. Either wait until layout has occurred or use newLatLngBounds(LatLngBounds, int, int, int) which allows you to specify the map's dimensions".

But I set up an alert for getCurrentPosition and I'm receiving coordinates from getCurrentPosition().

import React, { Component } from 'react';
import { View, Dimensions } from 'react-native';
import MapView from 'react-native-maps';

const {width, height} = Dimensions.get('window')

const SCREEN_HEIGHT = height
const SCREEN_WIDTH = width
const ASPECT_RATIO = width / height
const LATITUDE_DELTA = 0.0922
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO

class Map extends Component {

 constructor(props) {
  super(props)

  this.state = {
   isMapReady: false,
   initialPosition: {
    longitude: 0,
    latitude: 0,
    longitudeDelta: 0,
    latitudeDelta: 0
   },

   markerPosition: {
    longitude: 0,
    latitude: 0
   }

  }
 }

 watchID: ?number = null

 componentDidMount() {
  navigator.geolocation.getCurrentPosition((position) => {

   alert(JSON.stringify(position))

   var lat = parseFloat(position.coords.latitude)
   var long = parseFloat(position.coords.longitude)

   var initialRegion = {
    latitude: lat,
    longitude: long,
    latitudeDelta: LATITUDE_DELTA,
    longitudeDelta: LONGITUDE_DELTA
   }

   this.setState({initialPosition: initialRegion})
   this.setState({markerPosition: initialRegion})
  },

  (error) => alert(JSON.stringify(error)))

  this.watchID = navigator.geolocation.watchPosition((position) => {
   var lat = parseFloat(position.coords.latitude)
   var long = parseFloat(position.coords.longitude)

   var lastRegion = {
    latitude: lat,
    longitude: long,
    longitudeDelta: LONGITUDE_DELTA,
    latitudeDelta: LATITUDE_DELTA
   }

   this.setState({initialPosition: lastRegion})
   this.setState({markerPosition: lastRegion})
  })

 }

 componentWillUnmount() {
  navigator.geolocation.clearWatch(this.watchID)
 }

 onMapLayout = () => {
    this.setState({ isMapReady: true });
  }

 render() {

  return (

   <View style={styles.containerStyle}>
    <MapView style={styles.mapStyle} initialRegion={this.state.initialPosition} onLayout={this.onMapLayout}>
     { this.state.isMapReady &&
      <MapView.Marker coordinate={this.state.markerPosition}>
      </MapView.Marker>
     }
    </MapView>
   </View>

   )

 }

}

const styles = {
 containerStyle: {
  flex:1,
  justifyContent: 'center',
  alignItems: 'center',
  backgroundColor: 'lightblue'
 },

 mapStyle: {
  left: 0,
  right: 0,
  top: 0,
  bottom: 0,
  position: 'absolute'
 }

}

export default Map;```

I have no idea what's going wrong to be honest... would really appreciate some help! Thank you!!

答:
In you Map Styles you Should Provide Screen Width and Height or Flex :1 </p>

```<code>mapStyle: {
       width : SCREEN_WIDTH | SomeValue ,
       height : SCREEN_HEIGHT | SomeValue
    }
</code>```

Body:
I get an error:
"Error using newLatLngBounds(LatLngBounds, int): Map size can't be zero. Most likely layout has not yet occured for the map view. Either wait until layout has occurred or use newLatLngBounds(LatLngBounds, int, int, int) which allows you to specify the map's dimensions".

But I set up an alert for getCurrentPosition and I'm receiving coordinates from getCurrentPosition().

import React, { Component } from 'react';
import { View, Dimensions } from 'react-native';
import MapView from 'react-native-maps';

const {width, height} = Dimensions.get('window')

const SCREEN_HEIGHT = height
const SCREEN_WIDTH = width
const ASPECT_RATIO = width / height
const LATITUDE_DELTA = 0.0922
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO

class Map extends Component {

 constructor(props) {
  super(props)

  this.state = {
   isMapReady: false,
   initialPosition: {
    longitude: 0,
    latitude: 0,
    longitudeDelta: 0,
    latitudeDelta: 0
   },

   markerPosition: {
    longitude: 0,
    latitude: 0
   }

  }
 }

 watchID: ?number = null

 componentDidMount() {
  navigator.geolocation.getCurrentPosition((position) => {

   alert(JSON.stringify(position))

   var lat = parseFloat(position.coords.latitude)
   var long = parseFloat(position.coords.longitude)

   var initialRegion = {
    latitude: lat,
    longitude: long,
    latitudeDelta: LATITUDE_DELTA,
    longitudeDelta: LONGITUDE_DELTA
   }

   this.setState({initialPosition: initialRegion})
   this.setState({markerPosition: initialRegion})
  },

  (error) => alert(JSON.stringify(error)))

  this.watchID = navigator.geolocation.watchPosition((position) => {
   var lat = parseFloat(position.coords.latitude)
   var long = parseFloat(position.coords.longitude)

   var lastRegion = {
    latitude: lat,
    longitude: long,
    longitudeDelta: LONGITUDE_DELTA,
    latitudeDelta: LATITUDE_DELTA
   }

   this.setState({initialPosition: lastRegion})
   this.setState({markerPosition: lastRegion})
  })

 }

 componentWillUnmount() {
  navigator.geolocation.clearWatch(this.watchID)
 }

 onMapLayout = () => {
    this.setState({ isMapReady: true });
  }

 render() {

  return (

   <View style={styles.containerStyle}>
    <MapView style={styles.mapStyle} initialRegion={this.state.initialPosition} onLayout={this.onMapLayout}>
     { this.state.isMapReady &&
      <MapView.Marker coordinate={this.state.markerPosition}>
      </MapView.Marker>
     }
    </MapView>
   </View>

   )

 }

}

const styles = {
 containerStyle: {
  flex:1,
  justifyContent: 'center',
  alignItems: 'center',
  backgroundColor: 'lightblue'
 },

 mapStyle: {
  left: 0,
  right: 0,
  top: 0,
  bottom: 0,
  position: 'absolute'
 }

}

export default Map;

I have no idea what's going wrong to be honest... would really appreciate some help! Thank you!!

Body:
In you Map Styles you Should Provide Screen Width and Height or Flex :1

mapStyle: {
       width : SCREEN_WIDTH | SomeValue ,
       height : SCREEN_HEIGHT | SomeValue
    }


问:
Lists in python 3
So the problem is that I have a list which is made of pairs of numbers [ (0,0),(0,1)(0,2) ...etc  and I would like to know how to delete from this list all pairs with the same numbers . List was created by this function. </p>

```<code> l1 = []
 def fun2(x,y):
    for x in range(x+1):
        for y in range(y+1):
            l1.append((x,y))
    return l1
</code>```

答:
You can avoid duplicate tuple elements while generating the list. Just add an if:

```<code>def fun2(x, y):
    result = []
    for a in range(x+1):
        for b in range(y+1):
            if a != b:
                result.append((a,b))
    return result
</code>```

This could also be written more succinctly as a list comprehension:

```<code>result = [(a, b) for a in range(x+1) for b in range(y+1) if a != b]
</code>```

Yet another option is to use itertools.product():

```<code>from itertools import product

result = [(a, b) for a, b in product(range(x+1), range(y+1)) if a != b]
</code>```

Removing items afterwards is also possible with a list comprehension:

```<code>result = [pair for pair in result if pair[0] != pair[1]]
</code>```

which creates a new list without the duplicate items then rebinds it to result. You can overwrite the list in place with:

```<code>result[:] = [pair for pair in result if pair[0] != pair[1]]
</code>```

Title: Lists in python 3

Body:
So the problem is that I have a list which is made of pairs of numbers [ (0,0),(0,1)(0,2) ...etc  and I would like to know how to delete from this list all pairs with the same numbers . List was created by this function.

 l1 = []
 def fun2(x,y):
    for x in range(x+1):
        for y in range(y+1):
            l1.append((x,y))
    return l1

Body:
You can avoid duplicate tuple elements while generating the list. Just add an if:

def fun2(x, y):
    result = []
    for a in range(x+1):
        for b in range(y+1):
            if a != b:
                result.append((a,b))
    return result

This could also be written more succinctly as a list comprehension:

result = [(a, b) for a in range(x+1) for b in range(y+1) if a != b]

Yet another option is to use itertools.product():

from itertools import product

result = [(a, b) for a, b in product(range(x+1), range(y+1)) if a != b]

Removing items afterwards is also possible with a list comprehension:

result = [pair for pair in result if pair[0] != pair[1]]

which creates a new list without the duplicate items then rebinds it to result. You can overwrite the list in place with:

result[:] = [pair for pair in result if pair[0] != pair[1]]


问:
How do I create a link using JavaScript?
I have a string for a title and a string for a link.  I'm not sure how to put the two together to create a link on a page using JavaScript.  Any help is appreciated.

The reason I'm trying to figure this out is because I have an RSS feed and have a list of titles ands URLs.  I would like to link the titles to the URL to make the page useful.

I am using jQuery but am completely new to it and wasn't aware it could help in this situation.

答:
```<code><html>
  <head></head>
  <body>
    <script>
      var a = document.createElement('a');
      var linkText = document.createTextNode("my title text");
      a.appendChild(linkText);
      a.title = "my title text";
      a.href = "http://example.com";
      document.body.appendChild(a);
    </script>
  </body>
</html>
</code>```


答:
Here is my version:

```<code> Integer[] arr = {1,2,2,2,1,3,5,4,1};
 Arrays.stream(arr).distinct()
                   .forEach(x -> System.out.println(x + " appears " + Collections.frequency(Arrays.asList(arr), x) + " times."));
</code>```

We remove duplicates from the game so we are left with unique elements, then for each unique element in our stream we print out how many time it appears in original array.

Body:
I am trying to print only the duplicate elements from an array and how many times each of them appear.

Example:

Number 0 appears 3 times;
Number 12 appears 2 times;
Number 43 appears 2 times

My code prints all the elements of the array rather than printing only duplicate elements.

I must mention that i cannot use HashMap, only conditional statments.

 Thanks
Below is the code :

    int[] array = new int[] { 12, 0, -22, 0, 43, 545, -4, -55, 12, 43, 0, -999, -87 };
    int counter = 0, temp = 0;// variable that holds the temporary value of each element
    Arrays.sort(array);
    for (int i = 0; i < array.length; i++) {
        temp = array[i];
        counter = 0;
        for (int j = 0; j < array.length; j++) {
            if (temp == array[j]) {
                counter++;
            }
        }
        System.out.println("Number:" + array[i] + "occurs :" + counter + " times");
    }

Body:
Here is my version:

 Integer[] arr = {1,2,2,2,1,3,5,4,1};
 Arrays.stream(arr).distinct()
                   .forEach(x -> System.out.println(x + " appears " + Collections.frequency(Arrays.asList(arr), x) + " times."));

We remove duplicates from the game so we are left with unique elements, then for each unique element in our stream we print out how many time it appears in original array.


问:
Writing a big text file fast
How can I write a big text file very fast on Android?

I made some tests using a PrintWriter, a BufferedWriter and a FileWriter, but there are no significative time difference, and writing takes about three times the time of reading.

答:
Each memory has a specific block and page size. Due to how writes are done on Flash memories, it matters if you write it in small chunks.

Here is a benchmark with dd run in adb shell:

```<code>sailfish:/storage/emulated/0 $ dd if=/dev/zero of=test bs=4k count=$((32*1024))
32768+0 records in
32768+0 records out
134217728 bytes transferred in 0.521 secs (257615600 bytes/sec)
</code>```

Another one for 1k block:

```<code>sailfish:/storage/emulated/0 $ dd if=/dev/zero of=test bs=1k count=$((128*1024))
131072+0 records in
131072+0 records out
134217728 bytes transferred in 1.369 secs (98040707 bytes/sec)
</code>```

Writing data in small chunks makes it almost 3x slower.
I encourage you to benchmark your memory to see if you hit a hardware limitation. Experiment with write buffer sizes. If your memory is genuinely slower during writes, there is nothing more you can do.

Title: Writing a big text file fast

Body:
Each memory has a specific block and page size. Due to how writes are done on Flash memories, it matters if you write it in small chunks.

Here is a benchmark with dd run in adb shell:

sailfish:/storage/emulated/0 $ dd if=/dev/zero of=test bs=4k count=$((32*1024))
32768+0 records in
32768+0 records out
134217728 bytes transferred in 0.521 secs (257615600 bytes/sec)

Another one for 1k block:

sailfish:/storage/emulated/0 $ dd if=/dev/zero of=test bs=1k count=$((128*1024))
131072+0 records in
131072+0 records out
134217728 bytes transferred in 1.369 secs (98040707 bytes/sec)

Writing data in small chunks makes it almost 3x slower.
I encourage you to benchmark your memory to see if you hit a hardware limitation. Experiment with write buffer sizes. If your memory is genuinely slower during writes, there is nothing more you can do.


答:
The question has many solutions. I will list a few of them as  a starting point but leave the  coding up to you.

Use a HashMap and store the <Number, Frequency> in the map.

If you are not allowed to use maps, you could do a double loop and check for all occurrences. That would be O(n2).

A slightly better modification would be to sort the array first and then compare the consecutive elements. This would be O(n log n).

You could use Collections.frequency() but that would operate on a list so convert your data structures (by Streams maybe).

Once you have used any of these methods, you can then filter out the numbers which have a frequency of 1.


问:
Date of Joining calculation not working with moment 2.19.1
Below code not working with "moment": "^2.19.1",

```<code>var a = moment([2017, 12, 09]);
var b = moment([2011, 02, 17]);

var years = a.diff(b, 'year');
b.add(years, 'years');

var months = a.diff(b, 'months');
b.add(months, 'months');

var days = a.diff(b, 'days');
console.log(years + ' years ' + months + ' months ' + days + ' days');
</code>```

Please help.

答:
You can use moment duration format.

Include moment duration format plugin, and then..

```<code>var duration = moment.duration(a.diff(b));
console.log(duration.format('y [years] m [months] d [days]'));
</code>```

Body:
Below code not working with "moment": "^2.19.1",

var a = moment([2017, 12, 09]);
var b = moment([2011, 02, 17]);

var years = a.diff(b, 'year');
b.add(years, 'years');

var months = a.diff(b, 'months');
b.add(months, 'months');

var days = a.diff(b, 'days');
console.log(years + ' years ' + months + ' months ' + days + ' days');

Please help.

Body:
You can use moment duration format.

Include moment duration format plugin, and then..

var duration = moment.duration(a.diff(b));
console.log(duration.format('y [years] m [months] d [days]'));


问:
Unable to run import scikit-image in jupyter notebook despite successful installation of scikit-image in Anaconda
First, I'm a Windows user. There's a a conflict between Skimage and Tensorflow installs. Each installs ok but they don't run when installed in the same environment. I did
" pip install scikit-image" and the computer says it's already installed. When I ran import skimage.data in jupyter notebook, I keep getting the error "no module named skimage" although I have scikit-image installed.

答:
I suggest a Microsoft’s way for you are using Anaconda in windows.

```<code>Open Anaconda Navigator
</code>```

You can find your installed and Not-installed packages. You can reinstall them.

Body:
I suggest a Microsoft’s way for you are using Anaconda in windows.

Open Anaconda Navigator

You can find your installed and Not-installed packages. You can reinstall them.


问:
Rails: Relation does not exist for reference with class name in production
I created two references in a migration that are aliases for a reference to my User table:

```<code>class CreateInvitations < ActiveRecord::Migration[5.0]
  def change
    create_table :invitations do |t|
      t.references :owner, references: :user, foreign_key: true # the owner
      t.references :invitee, references: :user, foreign_key: true # the invitee
      t.references :core_bot, foreign_key: true # the associated page (core_bot_active)
      t.string :email
      t.string :token

      t.timestamps

    end
  end
end
</code>```

In my User model:

```<code>  has_many :invitations, foreign_key: :owner_id
  has_many :invitations, foreign_key: :invitee_id, dependent: :destroy
</code>```

In my Invitation model:

```<code>  belongs_to :owner, class_name: :User
  belongs_to :invitee, class_name: :User
</code>```

Everything works well in development but when I try to migrate in production with Heroku heroku run rake db:migrate, I get the following error:

PG::UndefinedTable: ERROR:  relation "owners" does not exist : CREATE
  TABLE "invitations" ("id" serial primary key, "owner_id" integer,
  "invitee_id" integer, "core_bot_id" integer, "email" character
  varying, "token" character varying, "created_at" timestamp NOT NULL,
  "updated_at" timestamp NOT NULL, CONSTRAINT "fk_rails_59e24979a9"
  FOREIGN KEY ("owner_id")   REFERENCES "owners" ("id") , CONSTRAINT
  "fk_rails_00204dc74b" FOREIGN KEY ("invitee_id")   REFERENCES
  "invitees" ("id") , CONSTRAINT "fk_rails_34505bdb65" FOREIGN KEY
  ("core_bot_id")   REFERENCES "core_bots" ("id") )

I tried without references: :user but I get the same error.

Any idea what's wrong here?

答:
try removing foreign_key: true from the options, since we are giving it a references, I think we don't need a foreign_key: true option</p>

```<code>class CreateInvitations < ActiveRecord::Migration[5.0]
  def change
    create_table :invitations do |t|
      t.references :owner, # the owner
      t.references :invitee, # the invitee
      t.references :core_bot # the associated page (core_bot_active)
      t.string :email
      t.string :token

      t.timestamps

    end
  end
end
</code>```

Body:
I created two references in a migration that are aliases for a reference to my User table:

class CreateInvitations < ActiveRecord::Migration[5.0]
  def change
    create_table :invitations do |t|
      t.references :owner, references: :user, foreign_key: true # the owner
      t.references :invitee, references: :user, foreign_key: true # the invitee
      t.references :core_bot, foreign_key: true # the associated page (core_bot_active)
      t.string :email
      t.string :token

      t.timestamps

    end
  end
end

In my User model:

  has_many :invitations, foreign_key: :owner_id
  has_many :invitations, foreign_key: :invitee_id, dependent: :destroy

In my Invitation model:

  belongs_to :owner, class_name: :User
  belongs_to :invitee, class_name: :User

Everything works well in development but when I try to migrate in production with Heroku heroku run rake db:migrate, I get the following error:

PG::UndefinedTable: ERROR:  relation "owners" does not exist : CREATE
  TABLE "invitations" ("id" serial primary key, "owner_id" integer,
  "invitee_id" integer, "core_bot_id" integer, "email" character
  varying, "token" character varying, "created_at" timestamp NOT NULL,
  "updated_at" timestamp NOT NULL, CONSTRAINT "fk_rails_59e24979a9"
  FOREIGN KEY ("owner_id")   REFERENCES "owners" ("id") , CONSTRAINT
  "fk_rails_00204dc74b" FOREIGN KEY ("invitee_id")   REFERENCES
  "invitees" ("id") , CONSTRAINT "fk_rails_34505bdb65" FOREIGN KEY
  ("core_bot_id")   REFERENCES "core_bots" ("id") )

I tried without references: :user but I get the same error.

Any idea what's wrong here?

Body:
try removing foreign_key: true from the options, since we are giving it a references, I think we don't need a foreign_key: true option

class CreateInvitations < ActiveRecord::Migration[5.0]
  def change
    create_table :invitations do |t|
      t.references :owner, # the owner
      t.references :invitee, # the invitee
      t.references :core_bot # the associated page (core_bot_active)
      t.string :email
      t.string :token

      t.timestamps

    end
  end
end


问:
Trying to understand indentations in haskell
I am trying to make a program that solves the tower of hanoi. I made it a bit complicated just for exercise:

```<code>hanoi :: [Int] -> String
hanoi n
    | n > 0     = hanoi' n "1" "2" "3"
                    where hanoi' n a b c
                            | n == 0    = "|"
                            | otherwise = let pre   = hanoi' (n-1) a c b
                                              posle = hanoi' (n-1) b c a
                                              in pre ++ a ++ " ~~> " ++ c ++ posle
    | otherwise = "Number must be greater than 0!!!"
</code>```

But i get:

```<code>hanoi.hs:7:97: parse error on input ‘=’
</code>```

Can someone please explain to me what is going on? I see now that i don't understand an important part of the language.

答:
Your where has to come after all guards.

```<code>hanoi :: [Int] -> String
hanoi n
    | n > 0     = hanoi' n "1" "2" "3"
    | otherwise = "Number must be greater than 0!!!"
  where hanoi' n a b c
         | n == 0    = "|"
         | otherwise = let pre   = hanoi' (n-1) a c b
                           posle = hanoi' (n-1) b c a
                       in pre ++ a ++ " ~~> " ++ c ++ posle
</code>```

This is stated in 4.4.3, although it's somewhat hidden if you're not used to BNF-like syntax:

```<code>decl    →   (funlhs | pat) rhs

funlhs  →   var apat { apat }
    |   pat varop pat
    |   ( funlhs ) apat { apat }

rhs     →   = exp [where decls]
    |   gdrhs [where decls]

gdrhs   →   guards = exp [gdrhs]

guards  →   | guard1, …, guardn         (n ≥ 1)

guard   →   pat <- infixexp         (pattern guard)
    |   let decls       (local declaration)
    |   infixexp        (boolean guard)
</code>```

rhs is the important token. It's the only part that contains the optional where. A guard may only contain expressions and be followed by other guards.

Body:
I am trying to make a program that solves the tower of hanoi. I made it a bit complicated just for exercise:

hanoi :: [Int] -> String
hanoi n
    | n > 0     = hanoi' n "1" "2" "3"
                    where hanoi' n a b c
                            | n == 0    = "|"
                            | otherwise = let pre   = hanoi' (n-1) a c b
                                              posle = hanoi' (n-1) b c a
                                              in pre ++ a ++ " ~~> " ++ c ++ posle
    | otherwise = "Number must be greater than 0!!!"

But i get:

hanoi.hs:7:97: parse error on input ‘=’

Can someone please explain to me what is going on? I see now that i don't understand an important part of the language.

Body:
Your where has to come after all guards.

hanoi :: [Int] -> String
hanoi n
    | n > 0     = hanoi' n "1" "2" "3"
    | otherwise = "Number must be greater than 0!!!"
  where hanoi' n a b c
         | n == 0    = "|"
         | otherwise = let pre   = hanoi' (n-1) a c b
                           posle = hanoi' (n-1) b c a
                       in pre ++ a ++ " ~~> " ++ c ++ posle

This is stated in 4.4.3, although it's somewhat hidden if you're not used to BNF-like syntax:

decl    →   (funlhs | pat) rhs

funlhs  →   var apat { apat }
    |   pat varop pat
    |   ( funlhs ) apat { apat }

rhs     →   = exp [where decls]
    |   gdrhs [where decls]

gdrhs   →   guards = exp [gdrhs]

guards  →   | guard1, …, guardn         (n ≥ 1)

guard   →   pat <- infixexp         (pattern guard)
    |   let decls       (local declaration)
    |   infixexp        (boolean guard)

rhs is the important token. It's the only part that contains the optional where. A guard may only contain expressions and be followed by other guards.


问:
Mechanism similar to SQL to filter and sort objects
Firstly,let me say, that the example I show here is very simple and very far from the real situation. However this example shows the core of the problem well enough.

I have a class Person

```<code>public class Person{
private int Id;
private String firstName;
private String lastName;
private Date birthDate;
private int age;
//+ getters and setters
}
</code>```

And I have for example list of 2000 java(!) objects of this class. I mean I have 2000 persons. Now I need to filter and sort them using sql query. For example I would like to get the persons from these 2000 WHERE birthDate BETWEEN 1920-04-05 AND 2000-08-10 ORDER BY lastName,firstName.

I understand that sql language is part of sql database.s So I could save my objects to mem database,for example H2, after that do select with the necessary WHERE and ORDER clauses. However, the problem is that I this case lose performance as I already have these objects. What I need is just to get the list of the ID of these objects and that's all as I get the interval and order.

So my question - are there any solutions (libs etc) to make filtering and sorting on java objects including all common types? Maybe there are some,that even support sql language?

答:
Why not use Java 8 Stream API?

```<code> List<Integer> ids = listOfPerson.stream()
            .filter(person -> person.getBirthDate().isAfter(from) && person.getBirthDate().isBefore(to))
            .sorted(Comparator.comparing(Person::getLastName).thenComparing(Person::getFirstName))
            .map(Person::getId)
            .collect(Collectors.toList());
</code>```

I believe JoSQL or other libraries like it are using reflection behind, so it won't be very performant. And what happens when you change name of a field?
Also, in Stream API you can use parallel processing as easy as listOfPerson.parallelStream()

For more info: Use stream operations to express sophisticated data processing queries

Body:
Firstly,let me say, that the example I show here is very simple and very far from the real situation. However this example shows the core of the problem well enough.

I have a class Person

public class Person{
private int Id;
private String firstName;
private String lastName;
private Date birthDate;
private int age;
//+ getters and setters
}

And I have for example list of 2000 java(!) objects of this class. I mean I have 2000 persons. Now I need to filter and sort them using sql query. For example I would like to get the persons from these 2000 WHERE birthDate BETWEEN 1920-04-05 AND 2000-08-10 ORDER BY lastName,firstName.

I understand that sql language is part of sql database.s So I could save my objects to mem database,for example H2, after that do select with the necessary WHERE and ORDER clauses. However, the problem is that I this case lose performance as I already have these objects. What I need is just to get the list of the ID of these objects and that's all as I get the interval and order.

So my question - are there any solutions (libs etc) to make filtering and sorting on java objects including all common types? Maybe there are some,that even support sql language?

Body:
Why not use Java 8 Stream API?

 List<Integer> ids = listOfPerson.stream()
            .filter(person -> person.getBirthDate().isAfter(from) && person.getBirthDate().isBefore(to))
            .sorted(Comparator.comparing(Person::getLastName).thenComparing(Person::getFirstName))
            .map(Person::getId)
            .collect(Collectors.toList());

I believe JoSQL or other libraries like it are using reflection behind, so it won't be very performant. And what happens when you change name of a field?
Also, in Stream API you can use parallel processing as easy as listOfPerson.parallelStream()

For more info: Use stream operations to express sophisticated data processing queries


问:
Unpacking values from list in Python 2.7
Python Newbie here:
Given a list and a value, how can I unpack the list into separate objects and prepend a value.  Length of the array isn't known, unlike in code below:

```<code>x = [1,2,3,4]
y = 0,x
y
</code>```

Current Output:

```<code>(0, [1, 2, 3, 4])
</code>```

Desired Output:

```<code>(0, 1, 2, 3, 4)
</code>```

I know it can be done easily in Python 3 using y = 0,*x but how can it be done in Python 2.7?

Thanks

答:
You shouldn't use unpacking here, but just concatenation.</p>

```<code>y = [0] + x
</code>```

Body:
Python Newbie here:
Given a list and a value, how can I unpack the list into separate objects and prepend a value.  Length of the array isn't known, unlike in code below:

x = [1,2,3,4]
y = 0,x
y

Current Output:

(0, [1, 2, 3, 4])

Desired Output:

(0, 1, 2, 3, 4)

I know it can be done easily in Python 3 using y = 0,*x but how can it be done in Python 2.7?

Thanks

Body:
You shouldn't use unpacking here, but just concatenation.

y = [0] + x


问:
MatLab Quadratic Equation With ln
How to solve the function f(x)=ln(x^2)-0.7=0 with a known Matlab command?

```<code>clc;clear all;close all;

f(x)=ln(x^2)-0.7=0
B=sqrt f(x)
</code>```

答:
You can define equations in matlab as such:

```<code>f = @(x) log(x^2)-0.7;
B = @(x) sqrt(f(x));
</code>```

If you want to find the value of x satisfying a constraint you can design a function that will be equal to zero when the constraint is respecte, then call fminsearch to find x:

```<code>f_constraint = @(x) abs(f(x)-0);
x_opt = fminsearch(f_constraint, 1.3); % function handle, initial estimate
</code>```

In your example, B(x_opt) should be equal to zero. This is not exactly the case as fminsearch estimated a solution.

Title: MatLab Quadratic Equation With ln

Body:
How to solve the function f(x)=ln(x^2)-0.7=0 with a known Matlab command?

clc;clear all;close all;

f(x)=ln(x^2)-0.7=0
B=sqrt f(x)

Body:
You can define equations in matlab as such:

f = @(x) log(x^2)-0.7;
B = @(x) sqrt(f(x));

If you want to find the value of x satisfying a constraint you can design a function that will be equal to zero when the constraint is respecte, then call fminsearch to find x:

f_constraint = @(x) abs(f(x)-0);
x_opt = fminsearch(f_constraint, 1.3); % function handle, initial estimate

In your example, B(x_opt) should be equal to zero. This is not exactly the case as fminsearch estimated a solution.


答:
Dynamically create a hyperlink with raw JavaScript:</p>

```<code>   var anchorElem = document.createElement('a');
   anchorElem.setAttribute("href", yourLink);
   anchorElem.innerHTML = yourLinkText;

   document.body.appendChild(anchorElem); // append your new link to the body
</code>```

Title: How do I create a link using JavaScript?

Body:
I have a string for a title and a string for a link.  I'm not sure how to put the two together to create a link on a page using JavaScript.  Any help is appreciated.

The reason I'm trying to figure this out is because I have an RSS feed and have a list of titles ands URLs.  I would like to link the titles to the URL to make the page useful.

I am using jQuery but am completely new to it and wasn't aware it could help in this situation.

Body:
Dynamically create a hyperlink with raw JavaScript:

   var anchorElem = document.createElement('a');
   anchorElem.setAttribute("href", yourLink);
   anchorElem.innerHTML = yourLinkText;

   document.body.appendChild(anchorElem); // append your new link to the body