问:
Unable to locate Registered client Asterisk - Kamailio
Problem: My main issue is that when I “REGISTER” a client via Kamailio, and I attempt to “Dial” a different endpoint within an Asterisk Dial Plan, Asterisk throws an error stating that the endpoint (the number I am dialing via “Dial”) is not registered or reachable. However, commands like “Playback” do work correctly for the client I “REGISTERED” via Kamailio.
   E.g. I register client 10001 in Kamailio, I then register another client 10002 in Kamalio; both 10001 and 10002 can exercise an Asterisk Dial Plan which will play videos/audio (No Problem).  But, now I want 10001 to Call (Dial) 10002; it is at this point that Asterisk throws the error “10002 is not registered or reachable”.

I have tried many of the suggestion on many different help boards (several times) but I am still unable to forward a registration from Kamailio to Asterisk.

With my current Kamailio configuration (I do use dispatching), I see , via tcpdump, Asterisk receiving a “REGISTER” request, and Asterisk sends back the “unauthorized” as expected, however, Kamailio does not re-send the “REGISTER” as is customary.  I am not sure of the next step to take, but I feel I have a couple of options.

-   I can continue to try and figure out why Kamailio is not sending the second “REGISTER” (I have not yet been able to figure this out).
-   Tell Asterisk to not require authentication.  (I am using pjsip and do not know how to not require authentication in Asterisk when the request is from Kamailio).

I have put a lot of time into this one, and I am at a sticking point.  Any help or suggestions would be very much appreciated.

Thank you,

答:
Kamailio is proxy. It SHOULD NOT do send second register unless you EXPLICTLY ask it do that in dialplan.

Dispatcher module is fast processing module. It should not do for you all staff, it just give you suggestion for dispatch.

You should not do check on asterisk for registration, you have send request to kamailio, and kamailio SHOULD do that work(it do much faster and HAVE info).

Main issue is:

asterisk main goal - give easy to understand platform for begginers. So anyone can get working pbx for free. It work on top level, with calls.

kamailio main goal is PERFOMANCE. It is not for begginer, you need have solid understanding of sip protocol, not just know that you want call. You have define what to do on packets level.


来源: stackexchange

问:
klocwork:Suspicious dereference of object reference 'dt' before null check
I am getting Suspicious dereference of object reference 'dt' before null check error with `Klocwork' code analysis. What could be the solution? Thanks!

```<code>using (DataTable dt = new DataTable())
        {
            dt.TableName = "Hello";
            dt.Columns.Add("HEllo1", typeof(string));
            if (dt != null)
            {
            }
            return dt;
        }
</code>```

Getting error at below line,

if (dt != null)

答:
the line

```<code>if (dt != null)
</code>```

obviously, checks if dt is null. From this, your analyzer assumes that dt might be null at this point. However, immediately before that, you have the following line:

```<code>dt.Columns.Add("HEllo1", typeof(string));
</code>```

which would produce NullReferenceException if dt is null.
That's why your analyzer warns you that something is wrong here: it is either dt can't be null so the null check is redundant or your code might throw a sudden NullReferenceException and you should add more null checks.

ContentLicense: CC BY-SA 3.0

Body:
I am getting Suspicious dereference of object reference 'dt' before null check error with `Klocwork' code analysis. What could be the solution? Thanks!

using (DataTable dt = new DataTable())
        {
            dt.TableName = "Hello";
            dt.Columns.Add("HEllo1", typeof(string));
            if (dt != null)
            {
            }
            return dt;
        }

Getting error at below line,

if (dt != null)

Body:
the line

if (dt != null)

obviously, checks if dt is null. From this, your analyzer assumes that dt might be null at this point. However, immediately before that, you have the following line:

dt.Columns.Add("HEllo1", typeof(string));

which would produce NullReferenceException if dt is null.
That's why your analyzer warns you that something is wrong here: it is either dt can't be null so the null check is redundant or your code might throw a sudden NullReferenceException and you should add more null checks.


问:
How to create navigation bar item in the custom Navigation Bar in iPhone?
I have created one custom view and added a web view as subview of that custom view. And i have created one navigation bar in programmatically. Now i want to create one Left or Right navigation bar buttons in that view.

```<code>navigBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];

navigBar.tintColor = [UIColor blackColor];

[self.view addSubview:navigBar];

UIBarButtonItem *homeButton = [[UIBarButtonItem alloc] initWithTitle:@"Home" style:UIBarButtonSystemItemAction target:self action:@selector(homeButtonAction)];

navigBar.rightBarButtonItem = homeButton; // it's not supports
</code>```

How can i create navigation bar item in the custom navigation bar?, i want to remove the custom view. So please Help me out!

Thanks.

答:
On your navigationbar reference you could invoke the two methods:

```<code>- (void)pushNavigationItem:(UINavigationItem *)item animated:(BOOL)animated
- (UINavigationItem *)popNavigationItemAnimated:(BOOL)animated
</code>```

In your custom view controller class write something like this:

```<code>self.navigationItem.leftBarButtonItem = yourButton;
self.navigationItem.rightBarButtonItem = yourSecondButton;
</code>```

So you could write something like this:

```<code>[myNavBarReference pushNavigationItem:self.navigationItem animated:NO];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have created one custom view and added a web view as subview of that custom view. And i have created one navigation bar in programmatically. Now i want to create one Left or Right navigation bar buttons in that view.

navigBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];

navigBar.tintColor = [UIColor blackColor];

[self.view addSubview:navigBar];

UIBarButtonItem *homeButton = [[UIBarButtonItem alloc] initWithTitle:@"Home" style:UIBarButtonSystemItemAction target:self action:@selector(homeButtonAction)];

navigBar.rightBarButtonItem = homeButton; // it's not supports

How can i create navigation bar item in the custom navigation bar?, i want to remove the custom view. So please Help me out!

Thanks.

Body:
On your navigationbar reference you could invoke the two methods:

- (void)pushNavigationItem:(UINavigationItem *)item animated:(BOOL)animated
- (UINavigationItem *)popNavigationItemAnimated:(BOOL)animated

In your custom view controller class write something like this:

self.navigationItem.leftBarButtonItem = yourButton;
self.navigationItem.rightBarButtonItem = yourSecondButton;

So you could write something like this:

[myNavBarReference pushNavigationItem:self.navigationItem animated:NO];


问:
Sqlite3 in angular4 electron desktop Application
In angular 4 , electron desktop project,i wants to implement sqlite ,tried few packages and resources without any luck.I need to get sqlite to access from app.component.ts .Any help would be greatly appreciated.</p>

答: You need to make a rest API. Try out expressjs.</p>


问:
I want to enable textbox when checkbox is checked in jquery or javascript
I want to enable textbox when checkbox is checked form content load from ajax page in modal popup but its not working and not showing any error in browser console.

function cash(cash) {
  if ($(cash).is(':checked')) {
    $('#cashAmount').attr("disabled", false);
  } else {
    alert("checkbox is not checked");
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12 field-option">
  <strong>Cash</strong> <input type="checkbox" name="cash" id="cash" onclick="cash(this)">
</div>
<div class="col-md-6 col-sm-6 custom_field">
  <!-- custom_field -->
  <span><strong>Amount <i>*</i></strong></span>
  <input type="text" name="cashAmount" id="cashAmount" class="form-control" disabled>
</div></code>```

答:
$("#cash").on('change', function(){
     $('#cashAmount').attr("disabled", !$(this).is(':checked'));
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12 field-option">
  <strong>Cash</strong> <input type="checkbox" name="cash" id="cash">
</div>
<div class="col-md-6 col-sm-6 custom_field">
  <!-- custom_field -->
  <span><strong>Amount <i>*</i></strong></span>
  <input type="text" name="cashAmount" id="cashAmount" class="form-control" disabled>
</div></code>```

Body:
I want to enable textbox when checkbox is checked form content load from ajax page in modal popup but its not working and not showing any error in browser console.

function cash(cash) {
  if ($(cash).is(':checked')) {
    $('#cashAmount').attr("disabled", false);
  } else {
    alert("checkbox is not checked");
  }
}

  Cash <input type="checkbox" name="cash" id="cash" onclick="cash(this)">

  Amount *
  <input type="text" name="cashAmount" id="cashAmount" class="form-control" disabled>

Body:
$("#cash").on('change', function(){
     $('#cashAmount').attr("disabled", !$(this).is(':checked'));
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12 field-option">
  <strong>Cash</strong> <input type="checkbox" name="cash" id="cash">
</div>
<div class="col-md-6 col-sm-6 custom_field">
  <!-- custom_field -->
  <span><strong>Amount <i>*</i></strong></span>
  <input type="text" name="cashAmount" id="cashAmount" class="form-control" disabled>
</div>


问:
Jackson and java.sql.Time serialization / deserialization
Consider this property in an Hibernate-managed entity:

```<code>@JsonFormat(pattern = "HH:mm")
@Column(name = "start_time")
private java.sql.Time startTime;
</code>```

I post a JSON-object as @RequestBody to a Spring Controller which Jackson is supposed to map into an instance of the entity (pojo).

Jackson does apparently not manage to de-serialize the time-string into a  java.sql.Time, because I am getting this Exception:

```<code>.w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message:
org.springframework.http.converter.HttpMessageNotReadableException:
Could not read document: Can not construct instance of java.sql.Time,
problem: null
</code>```

How can I instruct Jackson to understand what to do?

答:
You should try hh:mm:ss time format of java.sql.Time instead of hh:mm format.
This will be better way to handle exception instead of overriding JsonDeserializer method.

Body:
Consider this property in an Hibernate-managed entity:

@JsonFormat(pattern = "HH:mm")
@Column(name = "start_time")
private java.sql.Time startTime;

I post a JSON-object as @RequestBody to a Spring Controller which Jackson is supposed to map into an instance of the entity (pojo).

Jackson does apparently not manage to de-serialize the time-string into a  java.sql.Time, because I am getting this Exception:

.w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message:
org.springframework.http.converter.HttpMessageNotReadableException:
Could not read document: Can not construct instance of java.sql.Time,
problem: null

How can I instruct Jackson to understand what to do?


问:
Use suggested method parameters in Visual Studio Code
Visual Studio Code suggests the right parameters for well defined methods as you type them. Is there a way to take them over / insert them straight away? Doesn't feel right to write the parameters with their types by hand...

答:
Something like that exists for javascript & typescript files:

settings.json Ctrl+,

"typescript.suggest.completeFunctionCalls": true,
"javascript.suggest.completeFunctionCalls": true,
```

ContentLicense: CC BY-SA 4.0


问:
Using parameters in form data?
How can I get the data that I send with formData in the method I wrote in the web API. here I can only get the name of the image file.

My Component >>

my parameters in formdata:

1- image file

2-siparisid

3-dokumantipi

4- aciklama

```<code>@ViewChild('ufile') ufile: ElementRef;

fileUploadKaydet() {
const formData = new FormData();
let headers = new Headers();

formData.append('ufile', this.ufile.nativeElement.files[0]);
formData.append('siparisid', this.siparis.siparisid);
formData.append('dokumantipi', this.form.controls.belgeTipiFormController.value);
formData.append('aciklama', this.form.controls.aciklamaFormController.value);
let options = new RequestOptions({ headers: headers });

this.http.post('http://localhost:64478/api/dokumanlar/ResimKaydet', formData, options)
.map(res => res.json()).subscribe(
  data => console.log('success'),
  error => console.log(error)
  )
}
</code>```

Web Api >>

HttpFileCollection files = HttpContext.Current.Request.Files in the line of code; I can only get the image file with. How do I get the parameters I sent with FormData? for example, how to get "siparisid"

```<code>public class SiparisDokumanController : ApiController
{
    [HttpPost]
    [AllowAnonymous]
    [Route("ResimKaydet")]
    public async Task<IHttpActionResult> ResimKaydet()
    {
        int uploadCount = 0;
        string sPath = HostingEnvironment.MapPath("");
        HttpFileCollection files = HttpContext.Current.Request.Files;

        for (int i = 0; i < files.Count; i++)
        {
            HttpPostedFile file = files[i];
            string fileName = new FileInfo(file.FileName).Name;

            if (file.ContentLength > 0)
            {

                string modifiedFileName =
               Guid.NewGuid().ToString().Replace("-", "") + "_" + fileName;
              if (!File.Exists(sPath + Path.GetFileName(modifiedFileName)))
                {
                    file.SaveAs(sPath + Path.GetFileName(modifiedFileName));
                    uploadCount++;
          //Context.Galeri.Add(new Galeri() { Id=id, FileName =
          "/Galeri/"+modifiedFileName, Title=fileName });
                }
            }
        }

        if (uploadCount > 0)
        {
            // db ye kaydedecek kod
            //Context.SaveChange();
            //return Ok("kayıt başarılı");
        }
        return Ok("Kayıt Başarılı");

    }
}
</code>```

how can I read the last saved image file? as an example, I could not find a line of code. I need to write this code with web api 2. Thanks for your help

答:
I researched. it is being taken this way.</p>

```<code>   HttpFileCollection files = HttpContext.Current.Request.Files;
   string _siparisid = HttpContext.Current.Request["siparisid"];
   string _dokumanTipi = HttpContext.Current.Request["dokumantipi"];
   string _aciklama = HttpContext.Current.Request["aciklama"];
</code>```

Title: Using parameters in form data?

Body:
How can I get the data that I send with formData in the method I wrote in the web API. here I can only get the name of the image file.

My Component >>

my parameters in formdata:

1- image file

2-siparisid

3-dokumantipi

4- aciklama

@ViewChild('ufile') ufile: ElementRef;

fileUploadKaydet() {
const formData = new FormData();
let headers = new Headers();

formData.append('ufile', this.ufile.nativeElement.files[0]);
formData.append('siparisid', this.siparis.siparisid);
formData.append('dokumantipi', this.form.controls.belgeTipiFormController.value);
formData.append('aciklama', this.form.controls.aciklamaFormController.value);
let options = new RequestOptions({ headers: headers });

this.http.post('http://localhost:64478/api/dokumanlar/ResimKaydet', formData, options)
.map(res => res.json()).subscribe(
  data => console.log('success'),
  error => console.log(error)
  )
}

Web Api >>

HttpFileCollection files = HttpContext.Current.Request.Files in the line of code; I can only get the image file with. How do I get the parameters I sent with FormData? for example, how to get "siparisid"

public class SiparisDokumanController : ApiController
{
    [HttpPost]
    [AllowAnonymous]
    [Route("ResimKaydet")]
    public async Task<IHttpActionResult> ResimKaydet()
    {
        int uploadCount = 0;
        string sPath = HostingEnvironment.MapPath("");
        HttpFileCollection files = HttpContext.Current.Request.Files;

        for (int i = 0; i < files.Count; i++)
        {
            HttpPostedFile file = files[i];
            string fileName = new FileInfo(file.FileName).Name;

            if (file.ContentLength > 0)
            {

                string modifiedFileName =
               Guid.NewGuid().ToString().Replace("-", "") + "_" + fileName;
              if (!File.Exists(sPath + Path.GetFileName(modifiedFileName)))
                {
                    file.SaveAs(sPath + Path.GetFileName(modifiedFileName));
                    uploadCount++;
          //Context.Galeri.Add(new Galeri() { Id=id, FileName =
          "/Galeri/"+modifiedFileName, Title=fileName });
                }
            }
        }

        if (uploadCount > 0)
        {
            // db ye kaydedecek kod
            //Context.SaveChange();
            //return Ok("kayıt başarılı");
        }
        return Ok("Kayıt Başarılı");

    }
}

how can I read the last saved image file? as an example, I could not find a line of code. I need to write this code with web api 2. Thanks for your help

Body:
I researched. it is being taken this way.

   HttpFileCollection files = HttpContext.Current.Request.Files;
   string _siparisid = HttpContext.Current.Request["siparisid"];
   string _dokumanTipi = HttpContext.Current.Request["dokumantipi"];
   string _aciklama = HttpContext.Current.Request["aciklama"];


问:
R - Error in summarise_impl(.data, dots) : Column `center` must be length 1 (a summary value), not 2
I'm trying to calculate the center of each group, by running the calc_center function with dplyr's group_by_ and summarise functions. However, I received an error saying that the column must be 1 column not two. What can I do to bypass it? This is my code.

```<code>library(dplyr)
library(car)

calc_center <- function(x,y){
  MASS::cov.trob(cbind(x, y)$center
}

results <- data %>%
  group_by(group) %>%
  summarise(center=calc_center(Latitude, Longitude))
</code>```

This is my error

```<code>Error in summarise_impl(.data, dots) :
</code>```

Column center must be length 1 (a summary value), not 2

答:
In the future, it'd be nice if you included at least a brief example of your data for troubleshooting/reproducibility purposes.

The issue is likely because you'd like to apply the function to each row for the Latitude and Longitude columns.
In this case, using dplyr::rowwise() should solve the issue:

E.g.;

```<code>results <- data %>%
  group_by(group) %>%
  rowwise() %>%
  summarise(center=calc_center(Latitude, Longitude)) %>%
  ungroup()
</code>```

You could also probably get away with using mutate instead of summarise.

Hope that was helpful!

Body:
I'm trying to calculate the center of each group, by running the calc_center function with dplyr's group_by_ and summarise functions. However, I received an error saying that the column must be 1 column not two. What can I do to bypass it? This is my code.

library(dplyr)
library(car)

calc_center <- function(x,y){
  MASS::cov.trob(cbind(x, y)$center
}

results <- data %>%
  group_by(group) %>%
  summarise(center=calc_center(Latitude, Longitude))

This is my error

Error in summarise_impl(.data, dots) :

Column center must be length 1 (a summary value), not 2

Body:
In the future, it'd be nice if you included at least a brief example of your data for troubleshooting/reproducibility purposes.

The issue is likely because you'd like to apply the function to each row for the Latitude and Longitude columns.
In this case, using dplyr::rowwise() should solve the issue:

E.g.;

results <- data %>%
  group_by(group) %>%
  rowwise() %>%
  summarise(center=calc_center(Latitude, Longitude)) %>%
  ungroup()

You could also probably get away with using mutate instead of summarise.

Hope that was helpful!


问:
Connecting to a Ghost User in Flex RTMFP
I have a simple Flex RTMFP P2P video app in the same mold as the Adobe Cirrus VideoPhone Sample application. A problem I've been encountering in developing this app (the same problem occurs in the sample) is when you try to connect to a ghost Stratus instance i.e you try to call someone whose Stratus id is in the database but who is no longer on the page. So here's an example of what I mean:

Let's say you go to the Adobe Stratus sample and connect as Dan. Then open up a new tab, go to the sample again and connect as Fred. If from this point, you (as Fred) call Dan everything will work fine. But, if you close the tab in which you connected as Dan, and then from the Fred tab try to connect to Dan the program will just hang.

I would have thought there would be a NetStream event that would be triggered if you tried to connect to a Stratus instance that is not longer online but I can't seem to find anything besides NetStream.Connect.Rejected which doesn't seem to be called.

Any help is much appreciated!

答:
Did you try NetStream.Connect.Failed?

You should also add an event listener to the incoming stream and watch for the NetStream.Connect.Closed to see if it is disconnected during conversation. If it is fired any time; remove that peer from your db.


问:
error in installing statsmodels for python 3.6.1
I'm trying to install the statistics model in Python 3.6.1, but I get the following exception error.

Does anyone have any idea what it can be?

I have installed Visual C++. I do not know if I should install something else.

```<code> Microsoft Windows [Versión 10.0.15063]
(c) 2017 Microsoft Corporation. Todos los derechos reservados.

C:\Users\Sebastián>cd C:\Users\Sebastián\AppData\Local\Programs\Python\Python36

C:\Users\Sebastián\AppData\Local\Programs\Python\Python36>cd Scripts

C:\Users\Sebastián\AppData\Local\Programs\Python\Python36\Scripts>pip install statsmodels
Collecting statsmodels
  Using cached statsmodels-0.8.0.tar.gz
Installing collected packages: statsmodels
  Running setup.py install for statsmodels ... error
Exception:
Traceback (most recent call last):
  File "c:\users\sebastián\appdata\local\programs\python\python36\lib\site-packages\pip\compat\__init__.py", line 73, in console_to_str
    return s.decode(sys.__stdout__.encoding)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 148: invalid continuation byte

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\users\sebastián\appdata\local\programs\python\python36\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
  File "c:\users\sebastián\appdata\local\programs\python\python36\lib\site-packages\pip\commands\install.py", line 342, in run
    prefix=options.prefix_path,
  File "c:\users\sebastián\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_set.py", line 784, in install
    **kwargs
  File "c:\users\sebastián\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_install.py", line 878, in install
    spinner=spinner,
  File "c:\users\sebastián\appdata\local\programs\python\python36\lib\site-packages\pip\utils\__init__.py", line 676, in call_subprocess
    line = console_to_str(proc.stdout.readline())
  File "c:\users\sebastián\appdata\local\programs\python\python36\lib\site-packages\pip\compat\__init__.py", line 75, in console_to_str
    return s.decode('utf_8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 148: invalid continuation byte

C:\Users\Sebastián\AppData\Local\Programs\Python\Python36\Scripts>
</code>```

答: I'm guessing you installed "Microsoft Visual C++ Compiler for Python 2.7" (https://www.microsoft.com/en-us/download/details.aspx?id=44266).  According to this (https://wiki.python.org/moin/WindowsCompilers) you need Microsoft Visual C++ 14.0 which is in either Visual Studio 2015 or 2017.  I used Visual Studio Community 2015 with the install option "Programming Languages\Visual C++\Common Tools for Visual C++ 2015" and got it to install</p>

Body:
I'm trying to install the statistics model in Python 3.6.1, but I get the following exception error.

Does anyone have any idea what it can be?

I have installed Visual C++. I do not know if I should install something else.

 Microsoft Windows [Versión 10.0.15063]
(c) 2017 Microsoft Corporation. Todos los derechos reservados.

C:\Users\Sebastián>cd C:\Users\Sebastián\AppData\Local\Programs\Python\Python36

C:\Users\Sebastián\AppData\Local\Programs\Python\Python36>cd Scripts

C:\Users\Sebastián\AppData\Local\Programs\Python\Python36\Scripts>pip install statsmodels
Collecting statsmodels
  Using cached statsmodels-0.8.0.tar.gz
Installing collected packages: statsmodels
  Running setup.py install for statsmodels ... error
Exception:
Traceback (most recent call last):
  File "c:\users\sebastián\appdata\local\programs\python\python36\lib\site-packages\pip\compat\__init__.py", line 73, in console_to_str
    return s.decode(sys.__stdout__.encoding)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 148: invalid continuation byte

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\users\sebastián\appdata\local\programs\python\python36\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
  File "c:\users\sebastián\appdata\local\programs\python\python36\lib\site-packages\pip\commands\install.py", line 342, in run
    prefix=options.prefix_path,
  File "c:\users\sebastián\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_set.py", line 784, in install
    **kwargs
  File "c:\users\sebastián\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_install.py", line 878, in install
    spinner=spinner,
  File "c:\users\sebastián\appdata\local\programs\python\python36\lib\site-packages\pip\utils\__init__.py", line 676, in call_subprocess
    line = console_to_str(proc.stdout.readline())
  File "c:\users\sebastián\appdata\local\programs\python\python36\lib\site-packages\pip\compat\__init__.py", line 75, in console_to_str
    return s.decode('utf_8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 148: invalid continuation byte

C:\Users\Sebastián\AppData\Local\Programs\Python\Python36\Scripts>


问:
Deleting an element from an array in PHP
Is there an easy way to delete an element from an array using PHP, such that foreach ($array) no longer includes that element?

I thought that setting it to null would do it, but apparently it does not work.

答:
unset() multiple, fragmented elements from an array

While unset() has been mentioned here several times, it has yet to be mentioned that unset() accepts multiple variables making it easy to delete multiple, noncontiguous elements from an array in one operation:

```<code>// Delete multiple, noncontiguous elements from an array
$array = [ 'foo', 'bar', 'baz', 'quz' ];
unset( $array[2], $array[3] );
print_r($array);
// Output: [ 'foo', 'bar' ]
</code>```

unset() dynamically

unset() does not accept an array of keys to remove, so the code below will fail (it would have made it slightly easier to use unset() dynamically though).

```<code>$array = range(0,5);
$remove = [1,2];
$array = unset( $remove ); // FAILS: "unexpected 'unset'"
print_r($array);
</code>```

Instead, unset() can be used dynamically in a foreach loop:

```<code>$array = range(0,5);
$remove = [1,2];
foreach ($remove as $k=>$v) {
    unset($array[$v]);
}
print_r($array);
// Output: [ 0, 3, 4, 5 ]
</code>```

Remove array keys by copying the array

There is also another practice that has yet to be mentioned.
Sometimes, the simplest way to get rid of certain array keys is to simply copy $array1 into $array2.

```<code>$array1 = range(1,10);
foreach ($array1 as $v) {
    // Remove all even integers from the array
    if( $v % 2 ) {
        $array2[] = $v;
    }
}
print_r($array2);
// Output: [ 1, 3, 5, 7, 9 ];
</code>```

Obviously, the same practice applies to text strings:

```<code>$array1 = [ 'foo', '_bar', 'baz' ];
foreach ($array1 as $v) {
    // Remove all strings beginning with underscore
    if( strpos($v,'_')===false ) {
        $array2[] = $v;
    }
}
print_r($array2);
// Output: [ 'foo', 'baz' ]
</code>```

OwnerDisplayName: Ben

Body:
unset() multiple, fragmented elements from an array

While unset() has been mentioned here several times, it has yet to be mentioned that unset() accepts multiple variables making it easy to delete multiple, noncontiguous elements from an array in one operation:

// Delete multiple, noncontiguous elements from an array
$array = [ 'foo', 'bar', 'baz', 'quz' ];
unset( $array[2], $array[3] );
print_r($array);
// Output: [ 'foo', 'bar' ]

unset() dynamically

unset() does not accept an array of keys to remove, so the code below will fail (it would have made it slightly easier to use unset() dynamically though).

$array = range(0,5);
$remove = [1,2];
$array = unset( $remove ); // FAILS: "unexpected 'unset'"
print_r($array);

Instead, unset() can be used dynamically in a foreach loop:

$array = range(0,5);
$remove = [1,2];
foreach ($remove as $k=>$v) {
    unset($array[$v]);
}
print_r($array);
// Output: [ 0, 3, 4, 5 ]

Remove array keys by copying the array

There is also another practice that has yet to be mentioned.
Sometimes, the simplest way to get rid of certain array keys is to simply copy $array1 into $array2.

$array1 = range(1,10);
foreach ($array1 as $v) {
    // Remove all even integers from the array
    if( $v % 2 ) {
        $array2[] = $v;
    }
}
print_r($array2);
// Output: [ 1, 3, 5, 7, 9 ];

Obviously, the same practice applies to text strings:

$array1 = [ 'foo', '_bar', 'baz' ];
foreach ($array1 as $v) {
    // Remove all strings beginning with underscore
    if( strpos($v,'_')===false ) {
        $array2[] = $v;
    }
}
print_r($array2);
// Output: [ 'foo', 'baz' ]


问:
fetching multiple API requests in componentDidMount() function react native
I want to fetch multiple API requests in componentDidMount() function. I have a picker which take items from API call. I have another API which returns a picker value. Now i want to set selected the value received in latter API in the picker. I am trying to fetch both API in componentDidMount function

Here is my code. Please suggest where i am missing.

```<code>import React, { Component } from 'react';

import { AppRegistry, StyleSheet, View, Platform, Picker, ActivityIndicator, Button, Alert} from 'react-native';

export default class FirstProject extends Component {

 constructor(props)
 {

   super(props);

   this.state = {

   isLoading: true,

   PickerValueHolder : ''

  }
 }

 componentDidMount() {

  const base64 = require('base-64');

// my  API which fetches picker items
      return fetch('https://reactnativecode.000webhostapp.com/FruitsList.php')
        .then((response) => response.json())
        .then((responseJson) => {
          this.setState({
            isLoading: false,
            dataSource: responseJson
          }, function() {
            // In this block you can do something with new state.
          });
        })
        .catch((error) => {
          console.error(error);
        });

  // another api which fetches a particular fruit_id from database which i ave to set selected in picker.
fetch('http://my_api_url', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "fruit_id":"123"
  })
}).then((response) => response.json())
    .then((responseJson) => {
      this.setState({
        isLoading: false,
        PickerValueHolder: responseJson,
      }, function() {
        // In this block you can do something with new state.
      });
    })
    .catch((error) => {
      console.error(error);
    });
    }

    GetPickerSelectedItemValue=()=>{

      Alert.alert(this.state.PickerValueHolder);

    }

 render() {

   if (this.state.isLoading) {
     return (
       <View style={{flex: 1, paddingTop: 20}}>
         <ActivityIndicator />
       </View>
     );
   }

   return (

    <View style={styles.MainContainer}>

          <Picker
            selectedValue={this.state.PickerValueHolder}

            onValueChange={(itemValue, itemIndex) => this.setState({PickerValueHolder: itemValue})} >

            { this.state.dataSource.map((item, key)=>(
            <Picker.Item label={item.fruit_name} value={item.fruit_name} key={key} />)
            )}

          </Picker>

          <Button title="Click Here To Get Picker Selected Item Value" onPress={ this.GetPickerSelectedItemValue } />

    </View>

   );
 }
}

const styles = StyleSheet.create({

MainContainer :{

justifyContent: 'center',
flex:1,
margin: 10
}

});
</code>```

答:
As you said in comment, your second API response:

[{"fruit_id": "123","fruit_name":"Strwaberry"}]
```

<p>So it might work with minor changes:</p>

<pre class="lang-js prettyprint-override"><code>.then((responseJson) => {
  this.setState({
    isLoading: false,
    PickerValueHolder: responseJson[0].fruit_name,
  }, function() {
    // In this block you can do something with new state.
  });
})
</code>```

Body:
I want to fetch multiple API requests in componentDidMount() function. I have a picker which take items from API call. I have another API which returns a picker value. Now i want to set selected the value received in latter API in the picker. I am trying to fetch both API in componentDidMount function

Here is my code. Please suggest where i am missing.

import React, { Component } from 'react';

import { AppRegistry, StyleSheet, View, Platform, Picker, ActivityIndicator, Button, Alert} from 'react-native';

export default class FirstProject extends Component {

 constructor(props)
 {

   super(props);

   this.state = {

   isLoading: true,

   PickerValueHolder : ''

  }
 }

 componentDidMount() {

  const base64 = require('base-64');

// my  API which fetches picker items
      return fetch('https://reactnativecode.000webhostapp.com/FruitsList.php')
        .then((response) => response.json())
        .then((responseJson) => {
          this.setState({
            isLoading: false,
            dataSource: responseJson
          }, function() {
            // In this block you can do something with new state.
          });
        })
        .catch((error) => {
          console.error(error);
        });

  // another api which fetches a particular fruit_id from database which i ave to set selected in picker.
fetch('http://my_api_url', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "fruit_id":"123"
  })
}).then((response) => response.json())
    .then((responseJson) => {
      this.setState({
        isLoading: false,
        PickerValueHolder: responseJson,
      }, function() {
        // In this block you can do something with new state.
      });
    })
    .catch((error) => {
      console.error(error);
    });
    }

    GetPickerSelectedItemValue=()=>{

      Alert.alert(this.state.PickerValueHolder);

    }

 render() {

   if (this.state.isLoading) {
     return (
       <View style={{flex: 1, paddingTop: 20}}>
         <ActivityIndicator />
       </View>
     );
   }

   return (

    <View style={styles.MainContainer}>

          <Picker
            selectedValue={this.state.PickerValueHolder}

            onValueChange={(itemValue, itemIndex) => this.setState({PickerValueHolder: itemValue})} >

            { this.state.dataSource.map((item, key)=>(
            <Picker.Item label={item.fruit_name} value={item.fruit_name} key={key} />)
            )}

          </Picker>

          <Button title="Click Here To Get Picker Selected Item Value" onPress={ this.GetPickerSelectedItemValue } />

    </View>

   );
 }
}

const styles = StyleSheet.create({

MainContainer :{

justifyContent: 'center',
flex:1,
margin: 10
}

});

Body:
As you said in comment, your second API response:

[{"fruit_id": "123","fruit_name":"Strwaberry"}]

So it might work with minor changes:

.then((responseJson) => {
  this.setState({
    isLoading: false,
    PickerValueHolder: responseJson[0].fruit_name,
  }, function() {
    // In this block you can do something with new state.
  });
})


问:
OverlappingMarkerSpiderfier with angular4
I am trying to use OverlappingMarkerSpiderfier with leaflet in my angular 4 app.
The module works fine in plain js and with angular 1.

But when i try to use it with angular 4, it gives me the error

```<code>ERROR ReferenceError: OverlappingMarkerSpiderfier is not defined
</code>```

It was solved when I installed the overlapping-marker-spiderfier

```<code>npm i overlapping-marker-spiderfier
</code>```

But then it gave an another error that

```<code>Uncaught ReferenceError: google is not defined
</code>```

What should I do to get it working

答:
First I assume that you have script tag with your google maps api included into index.html.

Do you have @types/googlemaps installed? If not try to install it with

```<code>npm install --save @types/googlemaps
</code>```

and then include folowing import into your component

```<code>import {} from '@types/googlemaps';
</code>```

I hope this solves your problem. If not then try to declare this in your component

```<code>declare var google: any;
@Component({
    ...
})
</code>```

Body:
I am trying to use OverlappingMarkerSpiderfier with leaflet in my angular 4 app.
The module works fine in plain js and with angular 1.

But when i try to use it with angular 4, it gives me the error

ERROR ReferenceError: OverlappingMarkerSpiderfier is not defined

It was solved when I installed the overlapping-marker-spiderfier

npm i overlapping-marker-spiderfier

But then it gave an another error that

Uncaught ReferenceError: google is not defined

What should I do to get it working

Body:
First I assume that you have script tag with your google maps api included into index.html.

Do you have @types/googlemaps installed? If not try to install it with

npm install --save @types/googlemaps

and then include folowing import into your component

import {} from '@types/googlemaps';

I hope this solves your problem. If not then try to declare this in your component

declare var google: any;
@Component({
    ...
})


问:
Firebase query delete specific uid Real Time Database (Javascript)
I have this data on my firebase:

```<code>transportation: {
    "car" : {
        "bus" : {
          "toyota" : true,
          "bmw" : true
        },
        "suv" : {
          "honda" : true,
          "toyota" : true,
        }
      }
    }
</code>```

I want to delete all "toyota" data so that my data looks like this:

```<code>transportation: {
"car" : {
    "bus" : {

      "bmw" : true
    },
    "suv" : {
      "honda" : true,

    }
  }
}
</code>```

答:
The best possible way to do is check the value using loop in Javascript manually and delete if it's "toyota".</p>

```<code>    var firebaseRef= firebase.database().ref('transportation/');
        firebaseRef.on("value", function(data)){
            var datKey=data.key;
            firebase.database().ref('transportation/'+datKey).on("value",function(childData)){
            var childDataKey=childData.key;
            firebase.database().ref('transportation/'+datKey+'/'+childDataKey+'/').on("value",function(data)){
             firebase.database().ref('transportation/'+dataKey+'/'+childDataKey+'toyota').remove();
        }
    }
}
</code>```

Body:
I have this data on my firebase:

transportation: {
    "car" : {
        "bus" : {
          "toyota" : true,
          "bmw" : true
        },
        "suv" : {
          "honda" : true,
          "toyota" : true,
        }
      }
    }

I want to delete all "toyota" data so that my data looks like this:

transportation: {
"car" : {
    "bus" : {

      "bmw" : true
    },
    "suv" : {
      "honda" : true,

    }
  }
}

Body:
The best possible way to do is check the value using loop in Javascript manually and delete if it's "toyota".

    var firebaseRef= firebase.database().ref('transportation/');
        firebaseRef.on("value", function(data)){
            var datKey=data.key;
            firebase.database().ref('transportation/'+datKey).on("value",function(childData)){
            var childDataKey=childData.key;
            firebase.database().ref('transportation/'+datKey+'/'+childDataKey+'/').on("value",function(data)){
             firebase.database().ref('transportation/'+dataKey+'/'+childDataKey+'toyota').remove();
        }
    }
}


问:
How to convert String to TimeStamp
I want to convert a string to Timestamp. Here is the sample code.

```<code>I want to parse the string to Timestamp..
</code>```

I have tried to convert it like
     String date format is "18/01/11";

```<code>String date = "25/07/2017";
Timestamp ts =Timestamp.valueOf(date);
DateUtil.convertDate(ts.toString());
</code>```

convertDate:-

```<code>SimpleDateFormat inputFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        Date d = null;
        try {
            d = inputFormat.parse(input);
        } catch (ParseException e) {
            System.out.println("Date Format Not Supported");
            e.printStackTrace();
        }
        SimpleDateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy");

        return outputFormat.format(d).toString();
</code>```

if I write like that i am getting the following error

```<code>Date Format Not Supported
Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
</code>```

答:
I think you are using just opposite formats if your input format is dd/MM/yyyy:

//date format of input

```<code>SimpleDateFormat inputFormat = new SimpleDateFormat("dd/MM/yyyy");
Date d = null;
try {
    //convert string to date
    d = inputFormat.parse(input);
} catch (ParseException e) {
    System.out.println("Date Format Not Supported");
    e.printStackTrace();
}
</code>```

//output date format

```<code>SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
</code>```

//convert date to timestamp

```<code>return  outputFormat.format(d).toString();
</code>```

Title: How to convert String to TimeStamp

Body:
I want to convert a string to Timestamp. Here is the sample code.

I want to parse the string to Timestamp..

I have tried to convert it like
     String date format is "18/01/11";

String date = "25/07/2017";
Timestamp ts =Timestamp.valueOf(date);
DateUtil.convertDate(ts.toString());

convertDate:-

SimpleDateFormat inputFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        Date d = null;
        try {
            d = inputFormat.parse(input);
        } catch (ParseException e) {
            System.out.println("Date Format Not Supported");
            e.printStackTrace();
        }
        SimpleDateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy");

        return outputFormat.format(d).toString();

if I write like that i am getting the following error

Date Format Not Supported
Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]

Body:
I think you are using just opposite formats if your input format is dd/MM/yyyy:

//date format of input

SimpleDateFormat inputFormat = new SimpleDateFormat("dd/MM/yyyy");
Date d = null;
try {
    //convert string to date
    d = inputFormat.parse(input);
} catch (ParseException e) {
    System.out.println("Date Format Not Supported");
    e.printStackTrace();
}

//output date format

SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

//convert date to timestamp

return  outputFormat.format(d).toString();


答:
Please check this fiddle

https://jsfiddle.net/bimalkumarh/d1qxv247/

```<code>$("#cash").on('change',function() {
    if (this.checked) {
      $('#cashAmount').attr("disabled", false);
    } else {
      alert("checkbox is not checked");
    }
  });
</code>```

Hope this helps.

Title: I want to enable textbox when checkbox is checked in jquery or javascript

Body:
I want to enable textbox when checkbox is checked form content load from ajax page in modal popup but its not working and not showing any error in browser console.

function cash(cash) {
  if ($(cash).is(':checked')) {
    $('#cashAmount').attr("disabled", false);
  } else {
    alert("checkbox is not checked");
  }
}

  Cash <input type="checkbox" name="cash" id="cash" onclick="cash(this)">

  Amount *
  <input type="text" name="cashAmount" id="cashAmount" class="form-control" disabled>

Body:
Please check this fiddle

https://jsfiddle.net/bimalkumarh/d1qxv247/

$("#cash").on('change',function() {
    if (this.checked) {
      $('#cashAmount').attr("disabled", false);
    } else {
      alert("checkbox is not checked");
    }
  });

Hope this helps.


问:
IPHONE UIIMAGEVIEW can't release?
guys.i'm new to iphone.
i encounter a problem.the uiimageview can't release...here is the code.

```<code>    #import <UIKit/UIKit.h>
@interface imageNavView : UIImageView {

    int index;
}
@property int index;

@end
#import "imageNavView.h"

    @implementation imageNavView
    @synthesize index;
    - (id)initWithFrame:(CGRect)frameRect{
        self = [super initWithFrame:frameRect];
        if (self) {
            // Custom initialization.
            self.userInteractionEnabled=YES;
            self.multipleTouchEnabled=YES;
            self.opaque=YES;
            self.autoresizingMask=(UIViewAutoresizingFlexibleHeight|
                                   UIViewAutoresizingFlexibleWidth|
                                   UIViewAutoresizingFlexibleRightMargin
                                   |UIViewAutoresizingFlexibleLeftMargin
                                   |UIViewAutoresizingFlexibleTopMargin
                                   |UIViewAutoresizingFlexibleBottomMargin);
            index=0;
        }
        return self;
    }

    - (void)dealloc {
        NSLog(@"before image dealloc %i",[self retainCount]);-------- log is 1
            [super dealloc];
        NSLog(@"after image dealloc %i",[self retainCount]);-------- log is 1,why itn't bad access?
    }

    @end
</code>```

why does the second log NSLog(@"after image dealloc %i",[self retainCount]); is 1,not a bad access,so the imageview is not released.
i can't understand,any possible way can make this happen?...any advice will be gratefull.thanks in advance!

答:
This is an excellent example of exactly why you should
never call retainCount
.   The absolute retain count of an object is an implementation detail and it will often be of a value that makes no sense.

The behavior of calling a method after something is deallocated is entirely undefined.  In this case, it may crash, it may not.  If you turned on zombie detection, it would definitely crash.

Since there is absolutely no way that retainCount could ever return 0, there is no reason for object deallocation to decrement the retain count to 0.

Title: IPHONE UIIMAGEVIEW can't release?

Body:
guys.i'm new to iphone.
i encounter a problem.the uiimageview can't release...here is the code.

    #import <UIKit/UIKit.h>
@interface imageNavView : UIImageView {

    int index;
}
@property int index;

@end
#import "imageNavView.h"

    @implementation imageNavView
    @synthesize index;
    - (id)initWithFrame:(CGRect)frameRect{
        self = [super initWithFrame:frameRect];
        if (self) {
            // Custom initialization.
            self.userInteractionEnabled=YES;
            self.multipleTouchEnabled=YES;
            self.opaque=YES;
            self.autoresizingMask=(UIViewAutoresizingFlexibleHeight|
                                   UIViewAutoresizingFlexibleWidth|
                                   UIViewAutoresizingFlexibleRightMargin
                                   |UIViewAutoresizingFlexibleLeftMargin
                                   |UIViewAutoresizingFlexibleTopMargin
                                   |UIViewAutoresizingFlexibleBottomMargin);
            index=0;
        }
        return self;
    }

    - (void)dealloc {
        NSLog(@"before image dealloc %i",[self retainCount]);-------- log is 1
            [super dealloc];
        NSLog(@"after image dealloc %i",[self retainCount]);-------- log is 1,why itn't bad access?
    }

    @end

why does the second log NSLog(@"after image dealloc %i",[self retainCount]); is 1,not a bad access,so the imageview is not released.
i can't understand,any possible way can make this happen?...any advice will be gratefull.thanks in advance!


问:
Blogger: How do I hide widgets in specific pages in mobile?
I want to hide widgets in pages like privacy policy and disclaimer.
I tried
But this hides it only in desktop view.
I want to hide it both in desktop and mobile.</p>

答:
Use display to none to hiding your specific element/widgets for all page or visibility to hidden for hiding only a text or whatever stuff indeed. Try put this:

```<code>display: none;
</code>```

Or

```<code>visibility: hidden;
</code>```

To your ID or class.
Hope this help.

Body:
Use display to none to hiding your specific element/widgets for all page or visibility to hidden for hiding only a text or whatever stuff indeed. Try put this:

display: none;

Or

visibility: hidden;

To your ID or class.
Hope this help.


问:
Set input value in form from another Input , dynamically
I trying to upload image to website with its title . I want user to see image before uploading .

HTML

```<code><div class="container">
                <h1>Image Uploader</h1>
                <input type="file" name="images[]" id="images" multiple>
                <br>
                <div id="images-to-upload" class="row">
                </div>
                <br>
                <div class="col-md-12">
                    <button id="upload_button" class="btn btn-sm btn-success col-md-4 col-xs-12">Upload all images</button>
                </div>
            </div>
</code>```

When user select some images , Jquery add image with form in DIV .
Jquery

```<code><script>
    var fileCollection = new Array();

    $('#images').on('change', function(e) {

        var files = e.target.files;

        $.each(files, function(i, file) {

            fileCollection.push(file);

            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function(e) {
                var template = '<form enctype="multipart/form-data" class="upload_form col-md-6 col-xs-12" action="/upload">' +
                    '<img id="img_xx" name="images" class="col-md-4 col-xs-4" src="' + e.target.result + '"> ' +
                    '<input style="width:90px; height:28px" class="col-md-2 col-xs-4"  type="number" name="table" id="table" >' +
                    '<input style="width:90px; height:28px" class="col-md-2 col-xs-4"  type="file" name="images" value="' + e.target.result + '" >' +
                    '<button style="margin:0px 5px 0px 5px; width:95px" class="btn btn-sm btn-primary col-md-3 col-xs-3 submit_form" value="Upload" name="submit_weight">Upload</button>' +
                    '<button type="button" class="btn btn-sm btn-danger remove_form col-md-2 col-xs-6">Cancel</button>' +
                    '<div style="height: 30px; font-size: 20px; margin: 0px 0px 10px 0px; padding: 0px; text-align: center;" class="progress col-md-7 col-xs-6 progress-stripped active"><div class="progress-bar" style="font-size: 15px; width:0%"></div></div> ' +
                    '</form>';

                $('#images-to-upload').append(template);
            };

        });

    });

    $(document).on('submit', 'form', function(e) {

        e.preventDefault();
        var formdata = new FormData(this);
        $form = $(this);

        var request = new XMLHttpRequest();
        request.open('post', 'script/file_upload_admin.php', true);
        request.send(formdata);

        $form.on('click', '.remove_form', function() {
            console.log("Cancel");
            alert("hello");
            $(this).hide();
        });
    });

    $("#upload_button").on('click', function(event) {
        event.preventDefault();
        $(".submit_form").click();
    });
</script>
</code>```

My problem is how i set value of input from FileReader , so image can be send in form data . I tried below method but its not working.

```<code>$(document).on('submit','form',function(e){

        e.preventDefault();
        //this form index
        var index = $(this).index();

        var formdata = new Formdata($(this)[0]); //direct form not object

        //append the file relation to index
        formdata.append(fileCollection[index]);

        var request = new XMLHttpRequest();
        request.open('post', 'script/file_upload_admin.php', true);

        request.send(formdata);

    });
</code>```

答:
maybe this can help you.

```<code><div class="container">
    <h1>Image Uploader</h1>
    <input id="fileItem" type="file" name="images[]" id="images" multiple>
    <br>
    <div id="images-to-upload" class="row">
    </div>
    <br>
    <div class="col-md-12">
     <button id="upload_button" class="btn btn-sm btn-success col-md-4 col-xs-12">Upload all images</button>
    </div>
 </div>
</code>```

Javascript

```<code>$('#upload_button').click(function(){
    var files = document.getElementById('fileItem').files;
    console.log(files)
    $.each(files, function(index, item) {
       //console.log(index, item);
       console.log(item.name);
       // here you can do anything with name of file.
      // maybe here you can create your form
    });

  });
</code>```

test it jsfiddle

Body:
I trying to upload image to website with its title . I want user to see image before uploading .

HTML

Image Uploader

                <input type="file" name="images[]" id="images" multiple>

                    <button id="upload_button" class="btn btn-sm btn-success col-md-4 col-xs-12">Upload all images</button>

When user select some images , Jquery add image with form in DIV .
Jquery

My problem is how i set value of input from FileReader , so image can be send in form data . I tried below method but its not working.

$(document).on('submit','form',function(e){

        e.preventDefault();
        //this form index
        var index = $(this).index();

        var formdata = new Formdata($(this)[0]); //direct form not object

        //append the file relation to index
        formdata.append(fileCollection[index]);

        var request = new XMLHttpRequest();
        request.open('post', 'script/file_upload_admin.php', true);

        request.send(formdata);

    });

Body:
maybe this can help you.

<div class="container">
    <h1>Image Uploader</h1>
    <input id="fileItem" type="file" name="images[]" id="images" multiple>
    <br>
    <div id="images-to-upload" class="row">
    </div>
    <br>
    <div class="col-md-12">
     <button id="upload_button" class="btn btn-sm btn-success col-md-4 col-xs-12">Upload all images</button>
    </div>
 </div>

Javascript

$('#upload_button').click(function(){
    var files = document.getElementById('fileItem').files;
    console.log(files)
    $.each(files, function(index, item) {
       //console.log(index, item);
       console.log(item.name);
       // here you can do anything with name of file.
      // maybe here you can create your form
    });

  });

test it jsfiddle


问:
How do I create an expression tree to represent 'String.Contains("term")' in C#?
I am just getting started with expression trees so I hope this makes sense. I am trying to create an expression tree to represent:

```<code>t => t.SomeProperty.Contains("stringValue");
</code>```

So far I have got:

```<code>    private static Expression.Lambda<Func<string, bool>> GetContainsExpression<T>(string propertyName, string propertyValue)
    {
        var parameterExp = Expression.Parameter(typeof(T), "type");
        var propertyExp = Expression.Property(parameter, propertyName);
        var containsMethodExp = Expression.*SomeMemberReferenceFunction*("Contains", propertyExp) //this is where I got lost, obviously :)
        ...
        return Expression.Lambda<Func<string, bool>>(containsMethodExp, parameterExp); //then something like this
    }
</code>```

I just don't know how to reference the String.Contains() method.

Help appreciated.

答:
Here is how to create an expression tree of string.Contains.

```<code>var method = typeof(Enumerable)
    .GetRuntimeMethods()
    .Single(m => m.Name == nameof(Enumerable.Contains) && m.GetParameters().Length == 2);
var containsMethod = method.MakeGenericMethod(typeof(string));
var doesContain = Expression
.Call(containsMethod, Expression.Constant(criteria.ToArray()),
 Expression.Property(p, "MyParam"));
</code>```

Actual usage at https://raw.githubusercontent.com/xavierjohn/Its.Cqrs/e44797ef6f47424a1b145d69889bf940b5581eb8/Domain.Sql/CatchupEventFilter.cs

OwnerDisplayName: manwood

Body:
I am just getting started with expression trees so I hope this makes sense. I am trying to create an expression tree to represent:

t => t.SomeProperty.Contains("stringValue");

So far I have got:

    private static Expression.Lambda<Func<string, bool>> GetContainsExpression<T>(string propertyName, string propertyValue)
    {
        var parameterExp = Expression.Parameter(typeof(T), "type");
        var propertyExp = Expression.Property(parameter, propertyName);
        var containsMethodExp = Expression.*SomeMemberReferenceFunction*("Contains", propertyExp) //this is where I got lost, obviously :)
        ...
        return Expression.Lambda<Func<string, bool>>(containsMethodExp, parameterExp); //then something like this
    }

I just don't know how to reference the String.Contains() method.

Help appreciated.

Body:
Here is how to create an expression tree of string.Contains.

var method = typeof(Enumerable)
    .GetRuntimeMethods()
    .Single(m => m.Name == nameof(Enumerable.Contains) && m.GetParameters().Length == 2);
var containsMethod = method.MakeGenericMethod(typeof(string));
var doesContain = Expression
.Call(containsMethod, Expression.Constant(criteria.ToArray()),
 Expression.Property(p, "MyParam"));

Actual usage at https://raw.githubusercontent.com/xavierjohn/Its.Cqrs/e44797ef6f47424a1b145d69889bf940b5581eb8/Domain.Sql/CatchupEventFilter.cs


问:
Moving UIImage Up and Down with Animation in Swift
I have just recently started with Xcode and Swift and I am trying to get my image to move up and down and have it switch directions when the user taps the screen. My image just will not move at all and the app will either crash or just freeze.

```<code>import UIKit
import SpriteKit
import Darwin

let startButton = UIButton(frame: CGRect(x: 200, y: 100, width: 100, height: 50))
let screenSize = UIScreen.main.bounds
let gameButton = UIButton(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height))

var dot: UIImage = UIImage(named: "dot")!
var dotPic = UIImageView(image: dot)

public var goingUp = true

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = .white

    startButton.addTarget(self, action: #selector(startButtonAction), for: .touchUpInside)
    startButton.setImage(UIImage.init(named: "startButton"), for: .normal)

    self.view.addSubview(startButton)
}

func startButtonAction(sender: UIButton!) {
    print("button clicked")
    startButton.isEnabled = false
    startButton.setImage(UIImage.init(named: "nothing"), for: .normal)
    self.view.backgroundColor = .gray
    dotPic.frame = CGRect(x: 50, y: 300, width: 20, height: 20)

    self.view.addSubview(dotPic)
    self.view.addSubview(gameButton)

    playGame()
}

func playGame(){
    gameButton.addTarget(self, action: #selector(gameButtonAction), for: .touchUpInside)
    gameButton.setImage(UIImage.init(named: "nothing"), for: .normal)
}

func gameButtonAction(sender: UIButton!) {
    goingUp = !goingUp
    print(goingUp)
    print("clicked up/down")

    func rep(){
        repeat{
            dotPic.frame = CGRect(x: 50, y: 300-1, width: 20, height: 20)
            sleep(UInt32(0.3))
        }while goingUp==true
        repeat{
            dotPic.frame = CGRect(x: 50, y: 300-1, width: 20, height: 20)
            sleep(UInt32(0.3))
        }while goingUp==false
    }
    rep()
}

}
</code>```

I have tried using animateWithDuration() too but it has always frozen the app. What am I doing wrong?

答:
Here, Try this, instead of func rep() in your gameButtonAction :

```<code>[UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveLinear  animations:^{
        //code with animation
dotPic.frame = CGRect(x: 50, y: 300-1, width: 20, height: 20)
    } completion:^(BOOL finished) {
        //code for completion
dotPic.frame = CGRect(x: 50, y: 300, width: 20, height: 20)
    }];
</code>```

and avoid using nested function rep() in your target. Probably it is running continuously causing your application to hang.

Body:
I have just recently started with Xcode and Swift and I am trying to get my image to move up and down and have it switch directions when the user taps the screen. My image just will not move at all and the app will either crash or just freeze.

import UIKit
import SpriteKit
import Darwin

let startButton = UIButton(frame: CGRect(x: 200, y: 100, width: 100, height: 50))
let screenSize = UIScreen.main.bounds
let gameButton = UIButton(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height))

var dot: UIImage = UIImage(named: "dot")!
var dotPic = UIImageView(image: dot)

public var goingUp = true

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = .white

    startButton.addTarget(self, action: #selector(startButtonAction), for: .touchUpInside)
    startButton.setImage(UIImage.init(named: "startButton"), for: .normal)

    self.view.addSubview(startButton)
}

func startButtonAction(sender: UIButton!) {
    print("button clicked")
    startButton.isEnabled = false
    startButton.setImage(UIImage.init(named: "nothing"), for: .normal)
    self.view.backgroundColor = .gray
    dotPic.frame = CGRect(x: 50, y: 300, width: 20, height: 20)

    self.view.addSubview(dotPic)
    self.view.addSubview(gameButton)

    playGame()
}

func playGame(){
    gameButton.addTarget(self, action: #selector(gameButtonAction), for: .touchUpInside)
    gameButton.setImage(UIImage.init(named: "nothing"), for: .normal)
}

func gameButtonAction(sender: UIButton!) {
    goingUp = !goingUp
    print(goingUp)
    print("clicked up/down")

    func rep(){
        repeat{
            dotPic.frame = CGRect(x: 50, y: 300-1, width: 20, height: 20)
            sleep(UInt32(0.3))
        }while goingUp==true
        repeat{
            dotPic.frame = CGRect(x: 50, y: 300-1, width: 20, height: 20)
            sleep(UInt32(0.3))
        }while goingUp==false
    }
    rep()
}

}

I have tried using animateWithDuration() too but it has always frozen the app. What am I doing wrong?

Body:
Here, Try this, instead of func rep() in your gameButtonAction :

[UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveLinear  animations:^{
        //code with animation
dotPic.frame = CGRect(x: 50, y: 300-1, width: 20, height: 20)
    } completion:^(BOOL finished) {
        //code for completion
dotPic.frame = CGRect(x: 50, y: 300, width: 20, height: 20)
    }];

and avoid using nested function rep() in your target. Probably it is running continuously causing your application to hang.


问:
how to set local time in project irrespective of server location
I have my project based in India and my hosting server located somewhere that is at a difference of -5:30 HRs from Indian time.

So my time being stored in database is coming as based on there timings. How can I rectify this in PHP so that the time actually gets stored on India.

I tried using date_default_timezone_set('Asia/Kolkata');

but still the time gets stored with a difference of -30mins to -45mins. What could be possible code fort his so that the time sets exactly according to Indian timings. Any advice will be very helpful.

答:
You can set the timezone in the database.

Few more threads of the same topic are here:

MySQL Time Zones

Set MySQL database timezone to GMT

MySQL timezone change?


问:
RNSound.IsAndroid error (React Native)
Am getting this error- undefined is not an object(evaluating RNSound.IsAndroid)

I have already used this- react-native link react-native-sound

```<code>my index.android.js code is-

import React from 'react';
import { TouchableWithoutFeedback, Text } from 'react-native';
import Sound from 'react-native-sound';

class MyComponent extends Component {
  playSound() {
    const mySound = new Sound('x.mp3', Sound.MAIN_BUNDLE, (e) => {
      if (e) {
        console.log('error', e);
      } else {
        console.log('duration', mySound.getDuration());
        mySound.play();
      }
    });
  }

  render() {
    return (
      <TouchableWithoutFeedback onPress={this.playSound.bind(this)}>
         <Text>Play Sound!</Text>
      </TouchableWithoutFeedback>
    );
  }
}
</code>```

答:
Solved it:

Delete node_modules folder of your project.

Update the react-native-sound dependency in the package.json file as :

```<code>"react-native-sound": "git+ssh://git@github.com:zmxv/react-native-sound.git#HEAD"
</code>```

fire npm install.

Title: RNSound.IsAndroid error (React Native)

Body:
Am getting this error- undefined is not an object(evaluating RNSound.IsAndroid)

I have already used this- react-native link react-native-sound

my index.android.js code is-

import React from 'react';
import { TouchableWithoutFeedback, Text } from 'react-native';
import Sound from 'react-native-sound';

class MyComponent extends Component {
  playSound() {
    const mySound = new Sound('x.mp3', Sound.MAIN_BUNDLE, (e) => {
      if (e) {
        console.log('error', e);
      } else {
        console.log('duration', mySound.getDuration());
        mySound.play();
      }
    });
  }

  render() {
    return (
      <TouchableWithoutFeedback onPress={this.playSound.bind(this)}>
         <Text>Play Sound!</Text>
      </TouchableWithoutFeedback>
    );
  }
}

Body:
Solved it:

Delete node_modules folder of your project.

Update the react-native-sound dependency in the package.json file as :

"react-native-sound": "git+ssh://git@github.com:zmxv/react-native-sound.git#HEAD"

fire npm install.


问:
How would I make this credit card validator /identifier output to an array
I'm working on a project for credit card identification and validation, I'm trying to use nodes fs to write to another file and my goal to do that is use an array, fill with each line that this function outputs. Here is my full code block:

```<code>import { createReadStream } from 'fs'
import { createInterface } from 'readline'
import { getCompanyName } from './cardType'
import cardValidator from './cardValidator'
import * as fs from 'fs'

const lineReader = createInterface({
input: createReadStream('data/input.txt')
})

const output: string[] = []

lineReader.on('line', (creditCard: string) => {
var company = `${getCompanyName(creditCard)}: ${creditCard} (${
cardValidator(creditCard) ? 'valid' : 'invalid'
})`

//make company output an array called results then use results to
//wright lines to the output file

fs.writeFile('./data/output.txt', results[0, 1, 2, 3, etc], err => {
if (err) throw err && console.log('it broke as heck')
console.log('The file has been saved!')
})
})
</code>```

How would I make this happen?

答:
Here is the full code block now It is done and working:

```<code>import { createReadStream } from 'fs'
import { createInterface } from 'readline'
import { getCompanyName } from './cardType'
import cardValidator from './cardValidator'
import * as fs from 'fs'

const lineReader = createInterface({
input: createReadStream('data/input.txt')
})

const output: string[] = []

lineReader.on('line', (creditCard: string) => {
output.push(
`${getCompanyName(creditCard)}: ${creditCard} (${
  cardValidator(creditCard) ? 'valid' : 'invalid'
})`
)
})

lineReader.on('close', () => {
fs.writeFile('./data/output.txt', output.join('\n'), err => {
if (err) throw err
console.log('The file has been saved!')
})
})
</code>```

I added in the event processing the cards into output.push then created a new lineReader function writing the processed cards into output.txt

Body:
I'm working on a project for credit card identification and validation, I'm trying to use nodes fs to write to another file and my goal to do that is use an array, fill with each line that this function outputs. Here is my full code block:

import { createReadStream } from 'fs'
import { createInterface } from 'readline'
import { getCompanyName } from './cardType'
import cardValidator from './cardValidator'
import * as fs from 'fs'

const lineReader = createInterface({
input: createReadStream('data/input.txt')
})

const output: string[] = []

lineReader.on('line', (creditCard: string) => {
var company = `${getCompanyName(creditCard)}: ${creditCard} (${
cardValidator(creditCard) ? 'valid' : 'invalid'
})`

//make company output an array called results then use results to
//wright lines to the output file

fs.writeFile('./data/output.txt', results[0, 1, 2, 3, etc], err => {
if (err) throw err && console.log('it broke as heck')
console.log('The file has been saved!')
})
})

How would I make this happen?

Body:
Here is the full code block now It is done and working:

import { createReadStream } from 'fs'
import { createInterface } from 'readline'
import { getCompanyName } from './cardType'
import cardValidator from './cardValidator'
import * as fs from 'fs'

const lineReader = createInterface({
input: createReadStream('data/input.txt')
})

const output: string[] = []

lineReader.on('line', (creditCard: string) => {
output.push(
`${getCompanyName(creditCard)}: ${creditCard} (${
  cardValidator(creditCard) ? 'valid' : 'invalid'
})`
)
})

lineReader.on('close', () => {
fs.writeFile('./data/output.txt', output.join('\n'), err => {
if (err) throw err
console.log('The file has been saved!')
})
})

I added in the event processing the cards into output.push then created a new lineReader function writing the processed cards into output.txt


问:
I want to enable textbox when checkbox is checked in jquery or javascript
I want to enable textbox when checkbox is checked form content load from ajax page in modal popup but its not working and not showing any error in browser console.

function cash(cash) {
  if ($(cash).is(':checked')) {
    $('#cashAmount').attr("disabled", false);
  } else {
    alert("checkbox is not checked");
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12 field-option">
  <strong>Cash</strong> <input type="checkbox" name="cash" id="cash" onclick="cash(this)">
</div>
<div class="col-md-6 col-sm-6 custom_field">
  <!-- custom_field -->
  <span><strong>Amount <i>*</i></strong></span>
  <input type="text" name="cashAmount" id="cashAmount" class="form-control" disabled>
</div></code>```

答:
Following code using Javascript

function cash(x) {

  if (document.getElementById('cash').checked) {

    document.getElementById("cashAmt").disabled = false;

  } else {

    document.getElementById("cashAmt").disabled = true;

  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-md-12 field-option">
  <strong>Cash</strong> <input type="checkbox" id="cash" onclick="cash(this)">
</div>
<div class="col-md-6 col-sm-6 custom_field">
  <!-- custom_field -->
  <span><strong>Amount <i>*</i></strong></span>
  <input type="text" id="cashAmt" class="form-control" disabled>
</div></code>```

Following code uses jquery

function cash(cash) {
  if ($(cash).is(':checked')) {
    $('#cashAmt').attr("disabled", false);
  }
  else{
    $('#cashAmt').attr("disabled", true);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="col-md-12 field-option">
    <strong>Cash</strong> <input type="checkbox" id="cash" onclick="cash(this)">
  </div>
  <div class="col-md-6 col-sm-6 custom_field"> <!-- custom_field -->
    <span><strong>Amount <i>*</i></strong></span>
    <input type="text" id="cashAmt" class="form-control" disabled>
  </div><!-- End custom_field--></code>```

Body:
Following code using Javascript

function cash(x) {

  if (document.getElementById('cash').checked) {

    document.getElementById("cashAmt").disabled = false;

  } else {

    document.getElementById("cashAmt").disabled = true;

  }

}

<div class="col-md-12 field-option">
  <strong>Cash</strong> <input type="checkbox" id="cash" onclick="cash(this)">
</div>
<div class="col-md-6 col-sm-6 custom_field">
  <!-- custom_field -->
  <span><strong>Amount <i>*</i></strong></span>
  <input type="text" id="cashAmt" class="form-control" disabled>
</div>

Following code uses jquery

function cash(cash) {
  if ($(cash).is(':checked')) {
    $('#cashAmt').attr("disabled", false);
  }
  else{
    $('#cashAmt').attr("disabled", true);
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="col-md-12 field-option">
    <strong>Cash</strong> <input type="checkbox" id="cash" onclick="cash(this)">
  </div>
  <div class="col-md-6 col-sm-6 custom_field"> <!-- custom_field -->
    <span><strong>Amount <i>*</i></strong></span>
    <input type="text" id="cashAmt" class="form-control" disabled>
  </div><!-- End custom_field-->


问:
Copy construction in OCaml?
OCaml values are passed by reference as opposed by value. When the values are constant, there is no observable difference between references and values. However, when the value is mutable (such as a struct with mutable fields), I may want to copy it such that when one variable mutates the value, another variable that was set to the former variable is not mutated as well. Can I do this in OCaml?</p>

答:
I am afraid there is no automatic easy way for it.  You have to make a copy of a value by writing some code by yourself.  For example,

```<code>type t = { x : int option; mutable y : int option }

let copy t = { t with x = t.x }

let () =
  let t = { x = None; y = Some 1 } in
  let t' = copy t in
  t.y <- None;
  assert (t'.y <> None) (* check t'.y is not shared *)
</code>```

There are also copy functions for primitive mutable types, such as Bytes.copy and Array.copy.

If your value is nested then your copy function may or may not take care of the copying of the internal values.

There is a magical function Obj.dup which creates a deep copy of an argument, but I believe you will not want to use it, since it duplicates all the value nodes recursively, including the immutables, which is very bad for the space efficiency.

Title: Copy construction in OCaml?

Body:
I am afraid there is no automatic easy way for it.  You have to make a copy of a value by writing some code by yourself.  For example,

type t = { x : int option; mutable y : int option }

let copy t = { t with x = t.x }

let () =
  let t = { x = None; y = Some 1 } in
  let t' = copy t in
  t.y <- None;
  assert (t'.y <> None) (* check t'.y is not shared *)

There are also copy functions for primitive mutable types, such as Bytes.copy and Array.copy.

If your value is nested then your copy function may or may not take care of the copying of the internal values.

There is a magical function Obj.dup which creates a deep copy of an argument, but I believe you will not want to use it, since it duplicates all the value nodes recursively, including the immutables, which is very bad for the space efficiency.


问:
java.lang.NoSuchMethodError: No static method getFont
I am using Calligraphy Library by ChrisJenx. Suddenly today morning my project has started throwing weird error. Anyone got any idea about this? I also tried looking at TintTypedArray.java:119. The one in gradle cache has getFont method which is v26.0.2 but in sdk/extras doesn't have which is v25.3.1. I think gradle cache code would be used for this but still it is throwing error. Please help.

Logcat:

12-06 16:52:40.516 18533-18533/com.nabta E/AndroidRuntime: FATAL
  EXCEPTION: main
                                                                 Process: com.nabta, PID: 18533
                                                                 java.lang.NoSuchMethodError: No static method
  getFont(Landroid/content/Context;ILandroid/util/TypedValue;ILandroid/widget/TextView;)Landroid/graphics/Typeface;
  in class Landroid/support/v4/content/res/ResourcesCompat; or its super
  classes (declaration of
  'android.support.v4.content.res.ResourcesCompat' appears in
  /data/app/com.nabta-2/base.apk:classes13.dex)
                                                                     at android.support.v7.widget.TintTypedArray.getFont(TintTypedArray.java:119)
                                                                     at android.support.v7.widget.AppCompatTextHelper.updateTypefaceAndStyle(AppCompatTextHelper.java:208)
                                                                     at android.support.v7.widget.AppCompatTextHelper.loadFromAttributes(AppCompatTextHelper.java:110)
                                                                     at android.support.v7.widget.AppCompatTextHelperV17.loadFromAttributes(AppCompatTextHelperV17.java:38)
                                                                     at android.support.v7.widget.AppCompatTextView.(AppCompatTextView.java:81)
                                                                     at android.support.v7.widget.AppCompatTextView.(AppCompatTextView.java:71)
                                                                     at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:103)
                                                                     at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1024)
                                                                     at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1081)
                                                                     at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater$WrapperFactory2.onCreateView(CalligraphyLayoutInflater.java:280)
                                                                     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:776)
                                                                     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:734)
                                                                     at android.view.LayoutInflater.rInflate(LayoutInflater.java:865)
                                                                     at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
                                                                     at android.view.LayoutInflater.rInflate(LayoutInflater.java:873)
                                                                     at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
                                                                     at android.view.LayoutInflater.inflate(LayoutInflater.java:525)
                                                                     at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(CalligraphyLayoutInflater.java:60)
                                                                     at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
                                                                     at android.view.LayoutInflater.inflate(LayoutInflater.java:378)
                                                                     at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                                                                     at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                                                                     at com.nabta.activity.MainActivity.onCreate(MainActivity.java:47)
                                                                     at android.app.Activity.performCreate(Activity.java:6977)
                                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3064)
                                                                     at android.app.ActivityThread.-wrap14(ActivityThread.java)
                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1659)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                     at android.os.Looper.loop(Looper.java:154)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:6816)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1563)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1451)

答: I solved the bug. After running studio 3.0.0 I had encountered this bug. Upgrading build tools version as suggested here solved it : https://stackoverflow.com/a/47126127/3484668</p>


问:
PYTHON : Which is the best way to find distance between two points based on latitude/longitude using python?
I Am developing a location based app using python django. I want to find the distance between two points based on latitude/longitude. I found several answers but the final result(distance) is different in each. Please find me the best way to find the distance. Thanks</p>

答:
From your comments, i am assuming you need to calculate a short distance less than 50 miles,
The easiest less accurate method would be to coordinate point distance formula, `aka, pythagorean distance formula

where a,b is obviously the latitude, longitude pair. Now one degree of latitude = 68~69miles or 111km. Remember this is just an approximation.
Just multiply the result of the equation with the latitude miles. This gives a rather crude filter when coming to short distance, i use this to filter by distance when i need to make to make to many calculations, using google api to show results can be rather expensive(time, bandwidth, quota wise) considering my application needs to filter about 100 results per search. Also i suggest to add in a 20~30% variation to include actual road distance.

Ok. If your still reading this then you need more accurate result.

Then use this, remember to convert this code to python format. I just used the javascript code with me.

```<code>  function getDistanceLatLong(lat1,Long1,lat2,Long2) {
  var RK = 6371; // Radius of the earth in km
  var RM = 3959;
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLong = deg2rad(Long2-Long1);

  var a =  Math.sin(dLat/2) * Math.sin(dLat/2) +
           Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
           Math.sin(dLong/2) * Math.sin(dLong/2);

  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = RK * c; // Distance in kiloMeters choose this or
  var d = RM * c; // Distance in Miles
  return d;
}

function deg2rad(deg) {
  return deg * (Math.PI/180)
}
</code>```

Body:
From your comments, i am assuming you need to calculate a short distance less than 50 miles,
The easiest less accurate method would be to coordinate point distance formula, `aka, pythagorean distance formula

where a,b is obviously the latitude, longitude pair. Now one degree of latitude = 68~69miles or 111km. Remember this is just an approximation.
Just multiply the result of the equation with the latitude miles. This gives a rather crude filter when coming to short distance, i use this to filter by distance when i need to make to make to many calculations, using google api to show results can be rather expensive(time, bandwidth, quota wise) considering my application needs to filter about 100 results per search. Also i suggest to add in a 20~30% variation to include actual road distance.

Ok. If your still reading this then you need more accurate result.

Then use this, remember to convert this code to python format. I just used the javascript code with me.

  function getDistanceLatLong(lat1,Long1,lat2,Long2) {
  var RK = 6371; // Radius of the earth in km
  var RM = 3959;
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLong = deg2rad(Long2-Long1);

  var a =  Math.sin(dLat/2) * Math.sin(dLat/2) +
           Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
           Math.sin(dLong/2) * Math.sin(dLong/2);

  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = RK * c; // Distance in kiloMeters choose this or
  var d = RM * c; // Distance in Miles
  return d;
}

function deg2rad(deg) {
  return deg * (Math.PI/180)
}


问:
What are the best versions to react now?
I'm new in React and NPM. I'm studying React/React-router and practicing it, but that React just give me errors and more errors. My question here is: which versions to react and their dependencies are suitable/stable for now, 2017 year, I don't know if that question is on the suitable place, but thanks for the attention.

Below are my React dependencies versions

```<code>package.json
{
  "name": "first",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "history": "^3.3.0",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-router": "^3.2.0",
    "react-router-dom": "^4.2.2",
    "react-scripts": "1.0.17",
    "webpack": "^3.9.1"
  },
  "scripts": {
    "build": "webpack",
    "build:prod": "webpack" //I would change that after
  },
  "devDependencies": {
    "babel-loader": "^7.1.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-2": "^6.24.1",
    "webpack-dev-server": "^2.9.5"
  }
}
</code>```

The repository is here: Repository, that repo is using react-router

Some errors that occur:

```<code>Cannot read property 'pathname' of undefined
</code>```

答:
What errors are you getting?

Couple of things:

instead of using babel-preset-2015 try using babel-preset-env (im pretty sure they are transitioning to just using env.)

Also you need to add babel-core to dev dependencies yarn add -D babel-core.

But you would need to post the errors in order for someone to really pinpoint where you are going wrong.

Cheers

Body:
I'm new in React and NPM. I'm studying React/React-router and practicing it, but that React just give me errors and more errors. My question here is: which versions to react and their dependencies are suitable/stable for now, 2017 year, I don't know if that question is on the suitable place, but thanks for the attention.

Below are my React dependencies versions

package.json
{
  "name": "first",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "history": "^3.3.0",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-router": "^3.2.0",
    "react-router-dom": "^4.2.2",
    "react-scripts": "1.0.17",
    "webpack": "^3.9.1"
  },
  "scripts": {
    "build": "webpack",
    "build:prod": "webpack" //I would change that after
  },
  "devDependencies": {
    "babel-loader": "^7.1.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-2": "^6.24.1",
    "webpack-dev-server": "^2.9.5"
  }
}

The repository is here: Repository, that repo is using react-router

Some errors that occur:

Cannot read property 'pathname' of undefined


问:
CKEditor protect content (widgets?)
So, I have articles in a database, and I want to see if I can make use of CKEditor to edit them.

Some of them have "keyword" that in turn is expanded by PHP to something else. For instance, if I write "[FAQLIST:12,34,56]" it will show a UL of all the FAQ's with ID 12, 34 and 56. But I obviously don't want CKEditor to edit this resulting code. So I've read about widgets and wonder whether this is something I can use that for. Or is there some code I can wrap my HTML in to make CKEditor treat it is non-editable content within a contenteditable area?

答:
I read another your question, you want to use it with inline ckeditor.

As option you can specify contenteditable="false" attribute on ul tag (or which tag surrounds [FAQLIST:12,34,56])

Title: CKEditor protect content (widgets?)


问:
ERROR: Permission to user1/repo.git denied to user2
Someone I know is trying to clone my github repo and make changes directly to it. It's a public repo. He's cloned it with my read-write access link and he can pull from the repo. The problem is when he tries to push anything he gets the error

ERROR: Permission to user1/repo.git denied to user2

Where he's user2 and I'm user1. I've allowed other people to use different repos before and I've never had this problem. Am I missing something to allow him access or did github change? I've seen this on the help page for github:

This error occurs when you attach your key as a deploy key on repo1.
  You can push and pull from that repo without issue, but you won’t have
  access to any other repo with your key. To solve this, remove the key
  from repo1’s deploy keys and attach it on your account page instead.
  This key will now have access to all repos your account has access to.

We haven't messed with the deploy keys, but I can't find any other solution on the web.

答:
Updating your credentials via Keychain Access in macOS

In Finder, search for the Keychain Access app.

In Keychain Access, search for github.com.

GitHub Password Entry in KeychainFind the "internet password" entry for github.com.

Edit or delete the entry accordingly.


问:
Designing a div on real time fetch data HTML, CSS, Php, JavaScript and MySql
I'm having a problem of putting a design for a div in my real time fetch data. Can you please give me some ideas or tricks how can i embed html and css in this type of codes so i can put some responsive designs for my website.

Here's my code for index.php

```<code><div id="getdata"></div>
</code>```

```
</div>
</div>
</p>

<p>and here's my php and mysql for database connection <strong>select.php</strong> filename</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
$link=mysqli_connect("localhost","root","password");
mysqli_select_db($link,"autorefresh");
$res=mysqli_query($link,"select * from table1");
while($row=mysqli_fetch_array($res))
{
 echo $row["name"]." ".$row["city"];
 echo "<br>";

}

?></code>```

-->

I am looking the best way how to embed html and css in my fetch data. like for example how can i put a code for table so that the rows of name and city is properly arrange

答:
You could try sending the data back wrapped in pre tags ~ adding a class too if required perhaps

```<code>echo '<pre class="dyndata">';
while($row=mysqli_fetch_array($res)){
    echo "{$row["name"]}  {$row["city"]}\n";
}
echo '```';
```

Body:
I'm having a problem of putting a design for a div in my real time fetch data. Can you please give me some ideas or tricks how can i embed html and css in this type of codes so i can put some responsive designs for my website.

Here's my code for index.php

and here's my php and mysql for database connection select.php filename

<?php
$link=mysqli_connect("localhost","root","password");
mysqli_select_db($link,"autorefresh");
$res=mysqli_query($link,"select * from table1");
while($row=mysqli_fetch_array($res))
{
 echo $row["name"]." ".$row["city"];
 echo "
";

}

?>

-->

I am looking the best way how to embed html and css in my fetch data. like for example how can i put a code for table so that the rows of name and city is properly arrange

Body:
You could try sending the data back wrapped in pre tags ~ adding a class too if required perhaps

echo '<pre class="dyndata">';
while($row=mysqli_fetch_array($res)){
    echo "{$row["name"]}  {$row["city"]}\n";
}
echo '</pre>';