答:
You can't. At least not with Execute remaining type safe.

What you can do is create another base class or an interface that declares an Execute method that receives and returns an object:

public interface IAction {
    object Execute(object input);
}

public abstract class Action<TInput, TOutput> : IAction {
    public object Execute(object input) {
        return Execute((TInput) input);
    }

    public virtual TOutput Execute(TInput input)
    {
        throw new NotImplementedException();
    }
}
```

<p>This will then work (it will compile):</p>

<pre class="lang-cs prettyprint-override"><code>List<IAction> actions = new List<IAction>();
actions.Add(new Foo());
actions.Add(new Bar());

object obj;

foreach(var item in actions)
    obj = item.Execute(obj);
</code>```

However! Keep in mind that this will compile but produce a runtime error:

IAction action = new Foo(); // Expects an integer
action.Execute("I'm not an integer");
```

The string will be cast to object and then to int, which won't work.

Title: Is there a Collection that hold implementations to an abstract generic class with multiple types

Body:
You can't. At least not with Execute remaining type safe.

What you can do is create another base class or an interface that declares an Execute method that receives and returns an object:

public interface IAction {
    object Execute(object input);
}

public abstract class Action<TInput, TOutput> : IAction {
    public object Execute(object input) {
        return Execute((TInput) input);
    }

    public virtual TOutput Execute(TInput input)
    {
        throw new NotImplementedException();
    }
}

This will then work (it will compile):

List<IAction> actions = new List<IAction>();
actions.Add(new Foo());
actions.Add(new Bar());

object obj;

foreach(var item in actions)
    obj = item.Execute(obj);

However! Keep in mind that this will compile but produce a runtime error:

IAction action = new Foo(); // Expects an integer
action.Execute("I'm not an integer");

The string will be cast to object and then to int, which won't work.


来源: stackexchange

问:
Transform translate3d on scroll
I want to add a second functionality to some vanilla js code. It now changes opacity on scroll but should also change the value of transform translate 3d on scroll

```<code>window.onscroll = function() {
  var target = document.getElementById("target");

  var height = window.innerHeight;

  var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;

  // Change this if you want it to fade faster
  height = height / 1;

  target.style.opacity = (height - scrollTop) / height;

};
</code>```

Besides changing the opacity it should also change the transform translate3d value. The second value.

Example:

```<code>transform: translate3d(0px, 1px, 0px);
transform: translate3d(0px, 2px, 0px);
transform: translate3d(0px, 3px, 0px);
transform: translate3d(0px, 4px, 0px);
</code>```

Etc.

What should be added to also change the transform style?

答:
You are going to do the same thing as the opacity except with the transform property.

```<code>  target.style.opacity = (height - scrollTop) / height;
  target.style.transform = "translate3d(0px, 1px, 0px)";

};
</code>```

Replace 1px with the variable you want it to change to on each scroll.

Keep in mind that this will not work cross-browser in it's current state.

Edit: Seems like the closing semi-colon broke that code, it's fixed now.

ContentLicense: CC BY-SA 4.0

Title: Transform translate3d on scroll

Body:
I want to add a second functionality to some vanilla js code. It now changes opacity on scroll but should also change the value of transform translate 3d on scroll

window.onscroll = function() {
  var target = document.getElementById("target");

  var height = window.innerHeight;

  var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;

  // Change this if you want it to fade faster
  height = height / 1;

  target.style.opacity = (height - scrollTop) / height;

};

Besides changing the opacity it should also change the transform translate3d value. The second value.

Example:

transform: translate3d(0px, 1px, 0px);
transform: translate3d(0px, 2px, 0px);
transform: translate3d(0px, 3px, 0px);
transform: translate3d(0px, 4px, 0px);

Etc.

What should be added to also change the transform style?

Body:
You are going to do the same thing as the opacity except with the transform property.

  target.style.opacity = (height - scrollTop) / height;
  target.style.transform = "translate3d(0px, 1px, 0px)";

};

Replace 1px with the variable you want it to change to on each scroll.

Keep in mind that this will not work cross-browser in it's current state.

Edit: Seems like the closing semi-colon broke that code, it's fixed now.


问:
Create a list that can be accessed from multiple classes
I'm trying to create a list that is populated in one class and read in another class. I have a number of things, right now I'm getting the error shown below. I show only one class where the list is read, but there will be others.

How do I do this?

ReadDatabase.py

```<code>class ReadDatabase(object):

    f_type_list = ReadDatabase.getFTypes() ## 'ReadDatabase' not defined

    @staticmethod
    def getFTypes():
        <reads from database>
        return my_list
</code>```

MyTreeView.py

```<code>from ReadDatabase import *
class MyTreeView (ttk.Treeview):

    def __init__(self,  frame=None, list=[], column_headers=[]):
        for f_type in ReadDatabase.f_type_list:
           <do stuff>
</code>```

答:
You can separate it into two different classes in two different ways.

Example 1: Using two classes, one class (A) creates & updates the list and the other class (B) creates an instance of A and controls it:

```<code>class A:
    """
    Create and updates the list
    """
    def __init__(self):
        self.my_list = []
        self._read_from_database()

    def _read_from_database(self):
        # some database update logic
        self.my_list.append(3)

class B:
    """
    Creates an instance of A and can read from it.
    """
    def __init__(self):
        self.a = A()
    def print_list(self):
        for index, element in enumerate(self.a.my_list):
            print(f"Index: {index} Element: {element}")

b_object = B()
b_object.print_list() # Prints: Index: 0 Element: 3
</code>```

or

Example 2: You can just create a method in class B and just pass it the lst from class A:

```<code>class A:
    """
    Create and updates the list
    """
    def __init__(self):
        self.my_list = []
        self._read_from_database()

    def _read_from_database(self):
        # some database update logic
        self.my_list.append(3)

class B:
    def __init__(self):
        pass
    def print_list(self, lst):
        for index, element in enumerate(lst):
            print(f"Index: {index} Element: {element}")

a_object = A()
b_object = B()
b_object.print_list(a_object.my_list)
</code>```

You can also pass the entire instance of A to B for it to use if you wanted to do it that way.

Body:
I'm trying to create a list that is populated in one class and read in another class. I have a number of things, right now I'm getting the error shown below. I show only one class where the list is read, but there will be others.

How do I do this?

ReadDatabase.py

class ReadDatabase(object):

    f_type_list = ReadDatabase.getFTypes() ## 'ReadDatabase' not defined

    @staticmethod
    def getFTypes():
        <reads from database>
        return my_list

MyTreeView.py

from ReadDatabase import *
class MyTreeView (ttk.Treeview):

    def __init__(self,  frame=None, list=[], column_headers=[]):
        for f_type in ReadDatabase.f_type_list:
           <do stuff>

Body:
You can separate it into two different classes in two different ways.

Example 1: Using two classes, one class (A) creates & updates the list and the other class (B) creates an instance of A and controls it:

class A:
    """
    Create and updates the list
    """
    def __init__(self):
        self.my_list = []
        self._read_from_database()

    def _read_from_database(self):
        # some database update logic
        self.my_list.append(3)

class B:
    """
    Creates an instance of A and can read from it.
    """
    def __init__(self):
        self.a = A()
    def print_list(self):
        for index, element in enumerate(self.a.my_list):
            print(f"Index: {index} Element: {element}")

b_object = B()
b_object.print_list() # Prints: Index: 0 Element: 3

or

Example 2: You can just create a method in class B and just pass it the lst from class A:

class A:
    """
    Create and updates the list
    """
    def __init__(self):
        self.my_list = []
        self._read_from_database()

    def _read_from_database(self):
        # some database update logic
        self.my_list.append(3)

class B:
    def __init__(self):
        pass
    def print_list(self, lst):
        for index, element in enumerate(lst):
            print(f"Index: {index} Element: {element}")

a_object = A()
b_object = B()
b_object.print_list(a_object.my_list)

You can also pass the entire instance of A to B for it to use if you wanted to do it that way.


问:
Receiving "Cannot read property 'value' of undefined" in formControlName property
I am using Angular 7 and Google Material Design, and I followed this tutorial for Reactive forms: https://angular.io/guide/reactive-forms#step-1-creating-a-formgroup-instance.

I have used a formGroup, along with formControlName. Here is my login.component.ts file:

```<code>import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor() { }

  loginForm = new FormGroup({
    email: new FormControl(''),
    password: new FormControl(''),
  });

  ngOnInit() {
  }

  onSubmit() : void {
    console.log(this.loginForm.value);
  }
}
</code>```

Here is my login.component.html:

```<code><mat-card class="login-card">
    <mat-card-header>
        <mat-card-title>Login</mat-card-title>
    </mat-card-header>
    <mat-card-content>
        <form [formGroup]="loginForm" class="login-form" (ngSubmit)="onSubmit()">
            <table class="login-full-width" cellspacing="0">
                <tr>
                    <td>
                        <mat-form-field class="login-full-width">
                            <input matInput type="text" formControlName="email" placeholder="Email" required>
                        </mat-form-field>
                    </td>
                </tr>
                <p>
                    Value: {{email.value}}
                </p>
                <tr>
                    <td>
                        <mat-form-field class="login-full-width">
                            <input matInput formControlName="password" placeholder="Password" type="password" required>
                        </mat-form-field>
                    </td>
                </tr>
            </table>
        </form>
        <mat-spinner [style.display]="showSpinner ? 'block' : 'none'"></mat-spinner>
    </mat-card-content>
    <mat-card-actions>
        <button mat-raised-button [disabled]="!loginForm.valid" color="primary">Login</button>
    </mat-card-actions>
</mat-card>
</code>```

This is the error I get when navigating to the login page:

LoginComponent.html:11 ERROR TypeError: Cannot read property 'value' of undefined

      at Object.eval [as updateRenderer] (LoginComponent.html:15)

      at Object.debugUpdateRenderer [as updateRenderer] (core.js:23937)

      at checkAndUpdateView (core.js:23312)

      at callViewAction (core.js:23548)

      at execComponentViewsAction (core.js:23490)

      at checkAndUpdateView (core.js:23313)

      at callViewAction (core.js:23548)

      at execEmbeddedViewsAction (core.js:23511)

      at checkAndUpdateView (core.js:23308)

      at callViewAction (core.js:23548)

This is line 11 of login.component.html:

```<code><input matInput type="text" formControlName="email" placeholder="Email" required>
</code>```

I followed the tutorial step by step, and it was very simple to follow. Did I miss something here that is causing the error?

答:
You are trying to access a variable that you haven't defined in your LoginComponent class. If you only want to map the value of your input for debugging purposes you can use template variables. You simply add one in your input tag as follow: #email

Check this official Angular documentation

Body:
I am using Angular 7 and Google Material Design, and I followed this tutorial for Reactive forms: https://angular.io/guide/reactive-forms#step-1-creating-a-formgroup-instance.

I have used a formGroup, along with formControlName. Here is my login.component.ts file:

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor() { }

  loginForm = new FormGroup({
    email: new FormControl(''),
    password: new FormControl(''),
  });

  ngOnInit() {
  }

  onSubmit() : void {
    console.log(this.loginForm.value);
  }
}

Here is my login.component.html:

<mat-card class="login-card">
    <mat-card-header>
        <mat-card-title>Login</mat-card-title>
    </mat-card-header>
    <mat-card-content>
        <form [formGroup]="loginForm" class="login-form" (ngSubmit)="onSubmit()">

                        <mat-form-field class="login-full-width">
                            <input matInput type="text" formControlName="email" placeholder="Email" required>
                        </mat-form-field>

                    Value: {{email.value}}

                        <mat-form-field class="login-full-width">
                            <input matInput formControlName="password" placeholder="Password" type="password" required>
                        </mat-form-field>

        </form>
        <mat-spinner [style.display]="showSpinner ? 'block' : 'none'"></mat-spinner>
    </mat-card-content>
    <mat-card-actions>
        <button mat-raised-button [disabled]="!loginForm.valid" color="primary">Login</button>
    </mat-card-actions>
</mat-card>

This is the error I get when navigating to the login page:

LoginComponent.html:11 ERROR TypeError: Cannot read property 'value' of undefined

      at Object.eval [as updateRenderer] (LoginComponent.html:15)

      at Object.debugUpdateRenderer [as updateRenderer] (core.js:23937)

      at checkAndUpdateView (core.js:23312)

      at callViewAction (core.js:23548)

      at execComponentViewsAction (core.js:23490)

      at checkAndUpdateView (core.js:23313)

      at callViewAction (core.js:23548)

      at execEmbeddedViewsAction (core.js:23511)

      at checkAndUpdateView (core.js:23308)

      at callViewAction (core.js:23548)

This is line 11 of login.component.html:

<input matInput type="text" formControlName="email" placeholder="Email" required>

I followed the tutorial step by step, and it was very simple to follow. Did I miss something here that is causing the error?


问:
Issues with Swing timers
I have 3 timers running on my application which takes care of different action. Timer 1 will deals with automatic logout of the application, timer 2 deals with updating a table, timer 3 deals with updating the color of swing buttons. First timer uses the calculation based on the variables and its values, second and third timers works out of MYSQL queries.

Now when i run this application on an average performance machine the application is not moving .I need to wait for few seconds to a normal click to happen or a window to open. Is it something to do with the timers ? If yes do I have any alternative suggestions to get rid of this timer problem?

答:
Is it OK if I run 5 timers at the same time?

All instances of javax.swing.Timer "perform their waiting using a single, shared thread." The limit occurs when the tread becomes saturated. As a practical matter, each Timer may have multiple listeners, but "the handlers must execute quickly to keep the GUI responsive."

ContentLicense: CC BY-SA 3.0

Title: Issues with Swing timers


问:
How to handle dispose in RxJava without InterruptedException
In the below code snipped when dispose() is called, then the emitter thread is interrupted (InterruptedException is thrown out of sleep method).

```<code>    Observable<Integer> obs = Observable.create(emitter -> {
        for (int i = 0; i < 10; i++) {
            if (emitter.isDisposed()) {
                System.out.println("> exiting.");
                emitter.onComplete();
                return;
            }

            emitter.onNext(i);
            System.out.println("> calculation = " + i);

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        emitter.onComplete();
    });

    Disposable disposable = obs
            .subscribeOn(Schedulers.computation())
            .subscribe(System.out::println);

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    disposable.dispose();
</code>```

From debugging session I see that the interrupt origins from FutureTask which is cancelled during disposal. In there, the thread that is calling dispose() is checked against runner thread, and if it does not match, the emitter is interrupted. The thread is different since I used computation Scheduler.

Is there any way to make dispose not interrupt such emitter or is it how this actually should always be handled? An issue I see with this approach is when I would have an interruptible operation (simulated here by sleep) that I would want to complete normally before calling onComplete().

答:
Please refer to What's different in 2.0 - Error handling.

One important design requirement for 2.x is that no Throwable errors should be swallowed. This means errors that can't be emitted because the downstream's lifecycle already reached its terminal state or the downstream cancelled a sequence which was about to emit an error.

So you can either wrap everything inside a try/catch and properly emit the error:

```<code>Observable<Integer> obs = Observable.create(emitter -> {
   try {
      // ...
   } catch (InterruptedException ex) {
      // check if the interrupt is due to cancellation
      // if so, no need to signal the InterruptedException
      if (!disposable.isDisposed()) {
         observer.onError(ex);
      }
   }
});
</code>```

or setup a global error consumer to ignore it:

```<code>RxJavaPlugins.setErrorHandler(e -> {
    // ..
    if (e instanceof InterruptedException) {
        // fine, some blocking code was interrupted by a dispose call
        return;
    }
    // ...
    Log.warning("Undeliverable exception received, not sure what to do", e);
});
</code>```

Body:
In the below code snipped when dispose() is called, then the emitter thread is interrupted (InterruptedException is thrown out of sleep method).

    Observable<Integer> obs = Observable.create(emitter -> {
        for (int i = 0; i < 10; i++) {
            if (emitter.isDisposed()) {
                System.out.println("> exiting.");
                emitter.onComplete();
                return;
            }

            emitter.onNext(i);
            System.out.println("> calculation = " + i);

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        emitter.onComplete();
    });

    Disposable disposable = obs
            .subscribeOn(Schedulers.computation())
            .subscribe(System.out::println);

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    disposable.dispose();

From debugging session I see that the interrupt origins from FutureTask which is cancelled during disposal. In there, the thread that is calling dispose() is checked against runner thread, and if it does not match, the emitter is interrupted. The thread is different since I used computation Scheduler.

Is there any way to make dispose not interrupt such emitter or is it how this actually should always be handled? An issue I see with this approach is when I would have an interruptible operation (simulated here by sleep) that I would want to complete normally before calling onComplete().

Body:
Please refer to What's different in 2.0 - Error handling.

One important design requirement for 2.x is that no Throwable errors should be swallowed. This means errors that can't be emitted because the downstream's lifecycle already reached its terminal state or the downstream cancelled a sequence which was about to emit an error.

So you can either wrap everything inside a try/catch and properly emit the error:

Observable<Integer> obs = Observable.create(emitter -> {
   try {
      // ...
   } catch (InterruptedException ex) {
      // check if the interrupt is due to cancellation
      // if so, no need to signal the InterruptedException
      if (!disposable.isDisposed()) {
         observer.onError(ex);
      }
   }
});

or setup a global error consumer to ignore it:

RxJavaPlugins.setErrorHandler(e -> {
    // ..
    if (e instanceof InterruptedException) {
        // fine, some blocking code was interrupted by a dispose call
        return;
    }
    // ...
    Log.warning("Undeliverable exception received, not sure what to do", e);
});


问:
How to extract the alias from a table with regex?
I need to get the alias of a table in java, using for this regex.

For example, for this string: FROM lineitem A INNER JOIN orders B ON (B.O_ORDERKEY = A.L_ORDERKEY) INNER JOIN customer C ON (C.C_CUSTKEY = B.O_ORDERKEY) I should get A, B, C.

How can I do this using regex in java?

答:
If all our inputs are similar to the question, we would start with a simple expression and test it later with more inputs:

```<code>\s+([A-Z])\s+
</code>```

DEMO

Test

```<code>import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "\\s+([A-Z])\\s+";
final String string = "FROM lineitem A INNER JOIN orders B ON (B.O_ORDERKEY = A.L_ORDERKEY) INNER JOIN customer C ON (C.C_CUSTKEY = B.O_ORDERKEY)";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}
</code>```

RegEx Circuit

jex.im visualizes regular expressions:

Body:
If all our inputs are similar to the question, we would start with a simple expression and test it later with more inputs:

\s+([A-Z])\s+

DEMO

Test

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "\\s+([A-Z])\\s+";
final String string = "FROM lineitem A INNER JOIN orders B ON (B.O_ORDERKEY = A.L_ORDERKEY) INNER JOIN customer C ON (C.C_CUSTKEY = B.O_ORDERKEY)";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}

RegEx Circuit

jex.im visualizes regular expressions:


问:
Google maps showing blank screen, earlier it was working fine but after reinstalling android studio it stopped
I'm trying to display a google maps in a very simple application. In this project i want to show user's location taking GPS location. This is the manifest file:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hamzah.locationtracker">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <!--
             The API key for Google Maps-based APIs is defined as a string
resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to
sign the APK.
             You need a different API key for each encryption key, including
the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in
src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

I have a valid key in @string/google_maps_key, as i told that it was working fine earlier.
Main Activity:

```<code>package com.hamzah.locationtracker;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
    final static int PERMISSION_ALL = 1;
    final static String[] PERMISSIONS = {android.Manifest.permission.ACCESS_COARSE_LOCATION,

        Manifest.permission.ACCESS_FINE_LOCATION};
private GoogleMap mMap;
MarkerOptions mo;
Marker marker;
LocationManager locationManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);

    mapFragment.getMapAsync(this);
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    mo = new MarkerOptions().position(new LatLng(0, 0)).title("My Current Location");
    if (Build.VERSION.SDK_INT >= 23 && !isPermissionGranted()) {
        requestPermissions(PERMISSIONS, PERMISSION_ALL);
    } else requestLocation();
    if (!isLocationEnabled())
        showAlert(1);
}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    marker = mMap.addMarker(mo);
    /**
     * LatLng sydney =  new LatLng(-34,151);
     * mMap.addMarker(newMarkerOptions().positions)
     */
}

@Override
public void onLocationChanged(Location location) {
    LatLng myCoordinates = new LatLng(location.getLatitude(), location.getLongitude());
    marker.setPosition(myCoordinates);
    int zoom = 15;
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myCoordinates, zoom));
}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

}

@Override
public void onProviderEnabled(String s) {

}

@Override
public void onProviderDisabled(String s) {

}

private void requestLocation() {
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setPowerRequirement(Criteria.POWER_HIGH);
    String provider = locationManager.getBestProvider(criteria, true);
    if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    locationManager.requestLocationUpdates(provider, 1000, 10, this);
}

private boolean isLocationEnabled() {
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
            locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private boolean isPermissionGranted(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
                == PackageManager.PERMISSION_GRANTED || checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v("myLog", "Permission is Granted");
            return true;
        }else {
            Log.v("myLog", "Permission not Granted");
            return false;
        }
    }
    return false;
}
    private void showAlert(final int status) {
    String message, title, btnText;
    if (status == 1) {
        message = "Your Location Setting is set to 'Off'\nPlease Enable Location to " +
                "use this app";
        title = "Enable Location";
        btnText = "Location Settings";
    } else {
        message = "Please Allow this app to access location!";
        title =  "Permission Access";
        btnText = "Grant";
    }
    final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.setCancelable(false);
    dialog.setTitle(title)
            .setMessage(message)
            .setPositiveButton(btnText, new DialogInterface.OnClickListener() {
                @RequiresApi(api = Build.VERSION_CODES.M)
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    if (status == 1) {
                        Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(myIntent);
                    } else
                        requestPermissions(PERMISSIONS, PERMISSION_ALL);
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    finish();
                }
            });
    dialog.show();
    }
}
</code>```

The layout file is untouched

This is the gradle file:

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

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.hamzah.locationtracker"
        minSdkVersion 16
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.google.android.gms:play-services-maps:15.0.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
</code>```

When i execute the app i just get a screen with a blank screen and the Google logo in the left bottom corner. I am using an emulator Google XL API level 25, and also a physical device Samsung S4 API level 22.

答: Just Regenerate the Maps Api key from console and replace the old one with the new one in your project</p>

Body:
I'm trying to display a google maps in a very simple application. In this project i want to show user's location taking GPS location. This is the manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hamzah.locationtracker">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I have a valid key in @string/google_maps_key, as i told that it was working fine earlier.
Main Activity:

package com.hamzah.locationtracker;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
    final static int PERMISSION_ALL = 1;
    final static String[] PERMISSIONS = {android.Manifest.permission.ACCESS_COARSE_LOCATION,

        Manifest.permission.ACCESS_FINE_LOCATION};
private GoogleMap mMap;
MarkerOptions mo;
Marker marker;
LocationManager locationManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);

    mapFragment.getMapAsync(this);
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    mo = new MarkerOptions().position(new LatLng(0, 0)).title("My Current Location");
    if (Build.VERSION.SDK_INT >= 23 && !isPermissionGranted()) {
        requestPermissions(PERMISSIONS, PERMISSION_ALL);
    } else requestLocation();
    if (!isLocationEnabled())
        showAlert(1);
}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    marker = mMap.addMarker(mo);
    /**
     * LatLng sydney =  new LatLng(-34,151);
     * mMap.addMarker(newMarkerOptions().positions)
     */
}

@Override
public void onLocationChanged(Location location) {
    LatLng myCoordinates = new LatLng(location.getLatitude(), location.getLongitude());
    marker.setPosition(myCoordinates);
    int zoom = 15;
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myCoordinates, zoom));
}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

}

@Override
public void onProviderEnabled(String s) {

}

@Override
public void onProviderDisabled(String s) {

}

private void requestLocation() {
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setPowerRequirement(Criteria.POWER_HIGH);
    String provider = locationManager.getBestProvider(criteria, true);
    if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    locationManager.requestLocationUpdates(provider, 1000, 10, this);
}

private boolean isLocationEnabled() {
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
            locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private boolean isPermissionGranted(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
                == PackageManager.PERMISSION_GRANTED || checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v("myLog", "Permission is Granted");
            return true;
        }else {
            Log.v("myLog", "Permission not Granted");
            return false;
        }
    }
    return false;
}
    private void showAlert(final int status) {
    String message, title, btnText;
    if (status == 1) {
        message = "Your Location Setting is set to 'Off'\nPlease Enable Location to " +
                "use this app";
        title = "Enable Location";
        btnText = "Location Settings";
    } else {
        message = "Please Allow this app to access location!";
        title =  "Permission Access";
        btnText = "Grant";
    }
    final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.setCancelable(false);
    dialog.setTitle(title)
            .setMessage(message)
            .setPositiveButton(btnText, new DialogInterface.OnClickListener() {
                @RequiresApi(api = Build.VERSION_CODES.M)
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    if (status == 1) {
                        Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(myIntent);
                    } else
                        requestPermissions(PERMISSIONS, PERMISSION_ALL);
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    finish();
                }
            });
    dialog.show();
    }
}

The layout file is untouched

This is the gradle file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.hamzah.locationtracker"
        minSdkVersion 16
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.google.android.gms:play-services-maps:15.0.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

When i execute the app i just get a screen with a blank screen and the Google logo in the left bottom corner. I am using an emulator Google XL API level 25, and also a physical device Samsung S4 API level 22.


问:
How to read constants from a shell script in python
I have a bash script which has:

```<code>SUCCESS="0"
FAIL="1"
DEBUG="TRUE"
</code>```

Is it possible to read this in a python script? Something like source.

答:
A similar question has already been: enter link description here

```<code>>>> with open("C:/.../tmp.sh") as f:
        content = f.readlines()
>>> content = [x.strip() for x in content]
</code>```

Insert into the dictionary and remove quotes if necessary:

```<code>>>> import re
>>> divInDict = [{x.split("=")[0]:re.findall(r'"(.*?)"', x.split("=")[1])[0]} for x in content]
</code>```

Output:

```<code>>>> divInDict
[{'SUCCESS': '0'}, {'FAIL': '1'}, {'DEBUG': 'TRUE'}]
</code>```

P.S.
I only have python 3 so I additionally tested it in python 2 online:
enter link description here

Body:
I have a bash script which has:

SUCCESS="0"
FAIL="1"
DEBUG="TRUE"

Is it possible to read this in a python script? Something like source.

Body:
A similar question has already been: enter link description here

>>> with open("C:/.../tmp.sh") as f:
        content = f.readlines()
>>> content = [x.strip() for x in content]

Insert into the dictionary and remove quotes if necessary:

>>> import re
>>> divInDict = [{x.split("=")[0]:re.findall(r'"(.*?)"', x.split("=")[1])[0]} for x in content]

Output:

>>> divInDict
[{'SUCCESS': '0'}, {'FAIL': '1'}, {'DEBUG': 'TRUE'}]

P.S.
I only have python 3 so I additionally tested it in python 2 online:
enter link description here


问:
How should I read the message a git fetch returns?
I just did

```<code>get fetch origin feature/8067
</code>```

and below it I got 3 columns:

```<code> * branch                feature/8067 -> FETCH_HEAD
 * [new branch]          feature/8067 -> origin/feature/8067
</code>```

Trying to process this...reading from here I just learned that FETCH_HEAD basically means the tip of where I last did a fetch. The file will contain a commit.

Does that [new branch] refer to the new branch created under my refs/remote?

I'm not sure if my reading of the following is correct: feature/8067 -> origin/feature/8067

Is the 2nd column the <nameOfBranchOnRemoteRepo> while the 3rd column is <repoName/nameOfBranchOnRemoteRepo> and it says my fetched remote branch in the refs is pointing to that in the remote?

答:
The first line tells you that the fetch yielded a new branch on your local repo, and that you have its HEAD. The second says that the new branch is set up to track the remote branch. (You can have a local branch with the same name as a remote branch, but not be tracking the remote.)

The remote branch wasn't created there necessarily, but may have been pushed up from another developer, for example.

Body:
I just did

get fetch origin feature/8067

and below it I got 3 columns:

 * branch                feature/8067 -> FETCH_HEAD
 * [new branch]          feature/8067 -> origin/feature/8067

Trying to process this...reading from here I just learned that FETCH_HEAD basically means the tip of where I last did a fetch. The file will contain a commit.

Does that [new branch] refer to the new branch created under my refs/remote?

I'm not sure if my reading of the following is correct: feature/8067 -> origin/feature/8067

Is the 2nd column the <nameOfBranchOnRemoteRepo> while the 3rd column is <repoName/nameOfBranchOnRemoteRepo> and it says my fetched remote branch in the refs is pointing to that in the remote?


问:
Modifying a data structure while iterating over it
What happens when you add elements to a data structure such as a vector while
iterating over it. Can I not do this?

I tried this and it breaks:

```<code>int main() {
    vector<int> x = { 1, 2, 3 };

    int j = 0;
    for (auto it = x.begin(); it != x.end(); ++it) {
        x.push_back(j);
        j++;
        cout << j << " .. ";
    }
}
</code>```

答:
It's not a good idea to do it.

You could think about the case where your vector would need to be resized after a push_back. It would then need to be moved to a bigger memory spot and your iterators would now be invalid.

Body:
What happens when you add elements to a data structure such as a vector while
iterating over it. Can I not do this?

I tried this and it breaks:

int main() {
    vector<int> x = { 1, 2, 3 };

    int j = 0;
    for (auto it = x.begin(); it != x.end(); ++it) {
        x.push_back(j);
        j++;
        cout << j << " .. ";
    }
}


问:
Converting a repeating binary number to decimal
How do I represent 0.1011111.... or 0.10(1) as a fraction a/b?
With a & b being integers.

I have being trying this method

x = 0.10(1)
x = 10.(1) / 4

Now y = 10.(1)

2y = 101.(1)

which implies 2y - y = 91
y = 91

x = 91/4
But a = 91 & b = 4 is wrong.

How do I go about to solve this?

答:
You could do it as follows:

x = (0.1011111)2

Representing above binary term in decimal gives us:

x = 1/21 + 0/22 + 1/23 + 1/24 + ... )

x = 1/2 + 1/22*(1/21 + 1/22 + 1/23 + ... )

If we ignore the term marked in bold in above equation, the term in parenthesis becomes x, so we can say the term in parenthesis is equal to (x+1/22)

x = 1/2 + 1/22*(x+1/22)

x = 1/2 + x/4 + 1/16

Solve above equation

3x/4 = 9/16

x = 3/4


问:
Embeding an OLE object in PowerPoint from Excel VBA - size and position does not work
I am using an Excel VBA to update PowerPoint presentation. I am trying to embed two excel files into one of the slides and I have set all the parameters but the size and position bit does not seem to be working.

```<code>MyPresentation.Slides(9).Shapes.AddOLEObject Left:=142, Top:=142, Width:=200, Height:=170, Filename:=Met2FactSheet, _
DisplayAsIcon:=msoTrue, IconLabel:="Metro2 Fact Sheet"
</code>```

The object is embedded but with no sizing at all (as if I have omitted that part of the code).

答:
Try assigning it to an object variable first, and then try setting the properties.  For example...

```<code>Set ppShape = MyPresentation.Slides(9).Shapes.AddOLEObject( _
    Filename:=Met2FactSheet, _
    DisplayAsIcon:=msoTrue, _
    IconLabel:="Metro2 Fact Sheet")

With ppShape
    .Left = 142
    .Top = 142
    .Width = 200
    .Height = 170
End With
</code>```

If you're using early binding, you can declare ppShape as PowerPoint.Shape.  Otherwise, if you're using late binding, you can declare ppShape as Object.

Hope this helps!

Body:
I am using an Excel VBA to update PowerPoint presentation. I am trying to embed two excel files into one of the slides and I have set all the parameters but the size and position bit does not seem to be working.

MyPresentation.Slides(9).Shapes.AddOLEObject Left:=142, Top:=142, Width:=200, Height:=170, Filename:=Met2FactSheet, _
DisplayAsIcon:=msoTrue, IconLabel:="Metro2 Fact Sheet"

The object is embedded but with no sizing at all (as if I have omitted that part of the code).

Body:
Try assigning it to an object variable first, and then try setting the properties.  For example...

Set ppShape = MyPresentation.Slides(9).Shapes.AddOLEObject( _
    Filename:=Met2FactSheet, _
    DisplayAsIcon:=msoTrue, _
    IconLabel:="Metro2 Fact Sheet")

With ppShape
    .Left = 142
    .Top = 142
    .Width = 200
    .Height = 170
End With

If you're using early binding, you can declare ppShape as PowerPoint.Shape.  Otherwise, if you're using late binding, you can declare ppShape as Object.

Hope this helps!


问:
Best practices for generating N of a component in React (without data)
Let's say I have a component, like:

```<code><FormInput label="Phone Number" />
</code>```

and I want to draw N number of them on the UI. What would the best practice for accomplishing this be? My initial thought is to create an array of N members so I can use map, like:

```<code>var myMapTrigger = [0,0,0,0,0]
myMapTrigger.map(function(){
  return (<FormInput label="Phone Number" />)
}
</code>```

This is of course a little hacky though.Is there a more idiomatic way that is more "thinking React"?

答:
This hack is pretty concise.

Array.from(Array(N)).map(() => {...})
```

Disclaimer: don't do this if N approaches infinity.

Body:
Let's say I have a component, like:

<FormInput label="Phone Number" />

and I want to draw N number of them on the UI. What would the best practice for accomplishing this be? My initial thought is to create an array of N members so I can use map, like:

var myMapTrigger = [0,0,0,0,0]
myMapTrigger.map(function(){
  return (<FormInput label="Phone Number" />)
}

This is of course a little hacky though.Is there a more idiomatic way that is more "thinking React"?

Body:
This hack is pretty concise.

Array.from(Array(N)).map(() => {...})

Disclaimer: don't do this if N approaches infinity.


问:
Django: form is not displaying
After the user registers, I am using signals to create a user profile, so they can fill in additional details (like country or website) that the standard registration form can't offer. The problem is the form is not displaying the contents. However I can fill in the same form on admin site easily, but I want to allow users to do it by themselves.

On Chrome I tried to inspect the problem, and where there is a form it says input='hidden'. What might be the problem?
Thank you in advance.

my views:

```<code>def edit_profile(request):
    if request.method == 'POST':
     edit_form = EditProfileForm(request.POST,
     instance=request.user.profile)

      if edit_form.is_valid():
        edit_form.save()
        messages.success(request, 'Your account has been updated!')
        return redirect(profile)
    else:
      edit_form = EditProfileForm(instance=request.user.profile)
context = {'edit_form': edit_form}
return render(request, 'profile.html', context)
</code>```

my profile.html:

```<code><form method='POST'>
        {% csrf_token %}
        {{ edit_form }}
        <button type="submit">Update</button>
</form>
</code>```

models:

```<code>class Profile(models.Model):
  user = models.OneToOneField(User)
  description = models.CharField(max_length=100, default='')
  country = models.CharField(max_length=100, default='')
  website = models.URLField(default='')
  image = models.ImageField(default='images/profile.jpg',
  upload_to='images')

def __str__(self):
    return self.user.username

def create_profile(sender, **kwargs):
  if kwargs['created']:
    profile = Profile.objects.create(user=kwargs['instance'])

post_save.connect(create_profile, sender=User)
</code>```

forms.py:

```<code>class EditProfileForm(forms.ModelForm):

  class Meta:
    model = Profile
    fields = ('status', 'website', 'description', 'country', 'user', )
</code>```

答:
Do you get an indentation error when you run your code?
If not can you please update your question with the correct indentation so that the SO people can help you troubleshoot.

Next up, do you have any group permissions in place for standard users vs non-standard user(admin)? I would check to see if they have the capability to modify their User objects freely.

Errors for the form are usually displayed by
 FormsAPI, I would check for those. If none, then I would double check that the form being returned isn't actually blank by debugging it and looking at the __dict__ definition of that object. I can't give you any more suggestions until the indentation part is fixed so I can rule out any logic errors.

Found the problem: edit_form = EditProfileForm(instance=request.user.profile)

What you want to do is query the Profile object that belongs to the user, bold then pass it in as an instance to your EditProfileForm.

```<code>class EditProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('status', 'website', 'description', 'country', 'user', )
</code>```

Your form's Meta is the Profile object not the User object.

Hope that helps, good luck!

Title: Django: form is not displaying

Body:
After the user registers, I am using signals to create a user profile, so they can fill in additional details (like country or website) that the standard registration form can't offer. The problem is the form is not displaying the contents. However I can fill in the same form on admin site easily, but I want to allow users to do it by themselves.

On Chrome I tried to inspect the problem, and where there is a form it says input='hidden'. What might be the problem?
Thank you in advance.

my views:

def edit_profile(request):
    if request.method == 'POST':
     edit_form = EditProfileForm(request.POST,
     instance=request.user.profile)

      if edit_form.is_valid():
        edit_form.save()
        messages.success(request, 'Your account has been updated!')
        return redirect(profile)
    else:
      edit_form = EditProfileForm(instance=request.user.profile)
context = {'edit_form': edit_form}
return render(request, 'profile.html', context)

my profile.html:

<form method='POST'>
        {% csrf_token %}
        {{ edit_form }}
        <button type="submit">Update</button>
</form>

models:

class Profile(models.Model):
  user = models.OneToOneField(User)
  description = models.CharField(max_length=100, default='')
  country = models.CharField(max_length=100, default='')
  website = models.URLField(default='')
  image = models.ImageField(default='images/profile.jpg',
  upload_to='images')

def __str__(self):
    return self.user.username

def create_profile(sender, **kwargs):
  if kwargs['created']:
    profile = Profile.objects.create(user=kwargs['instance'])

post_save.connect(create_profile, sender=User)

forms.py:

class EditProfileForm(forms.ModelForm):

  class Meta:
    model = Profile
    fields = ('status', 'website', 'description', 'country', 'user', )

Body:
Do you get an indentation error when you run your code?
If not can you please update your question with the correct indentation so that the SO people can help you troubleshoot.

Next up, do you have any group permissions in place for standard users vs non-standard user(admin)? I would check to see if they have the capability to modify their User objects freely.

Errors for the form are usually displayed by <ul class="errorlist"> FormsAPI, I would check for those. If none, then I would double check that the form being returned isn't actually blank by debugging it and looking at the __dict__ definition of that object. I can't give you any more suggestions until the indentation part is fixed so I can rule out any logic errors.

Found the problem: edit_form = EditProfileForm(instance=request.user.profile)

What you want to do is query the Profile object that belongs to the user, bold then pass it in as an instance to your EditProfileForm.

class EditProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('status', 'website', 'description', 'country', 'user', )

Your form's Meta is the Profile object not the User object.

Hope that helps, good luck!


问:
How to create a json column from multiple columns?
The table which needs to be converted to a json field.

```<code>ID,  product, line_item, createdDate

123,  valA,    valB,    '2019-02-02'
</code>```

The JSON table would be like.

```<code>ID,  json_column

123, { valA :
             {valB : '2019-02-02'}}
</code>```

Now, I'm not sure what kind of parse_json function can be used to create this column. When I use the column name, it errors out - 'Invalid Identifier'

Query used.

```<code>select ID, parse_json( {product : { line_item : createdDate }};
</code>```

答:
First of all, always try to provide a fully reproducible example

Here's one for your question based on what you wrote

```<code>create or replace table x(id int,
                          product varchar,
                          line_item varchar,
                          createdDate varchar)
as select * from values
    (123,'valA','valB','2019-02-02');

select * from x;
-----+---------+-----------+-------------+
 ID  | PRODUCT | LINE_ITEM | CREATEDDATE |
-----+---------+-----------+-------------+
 123 | valA    | valB      | 2019-02-02  |
-----+---------+-----------+-------------+
</code>```

Now, to get the result you want you can use the OBJECT_CONSTRUCT function, like this:

```<code>select id, object_construct(product, object_construct(line_item, createddate)) from x;
-----+---------------------------------------------------------------------+
 ID  | OBJECT_CONSTRUCT(PRODUCT, OBJECT_CONSTRUCT(LINE_ITEM, CREATEDDATE)) |
-----+---------------------------------------------------------------------+
 123 | {                                                                   |
     |   "valA": {                                                         |
     |     "valB": "2019-02-02"                                            |
     |   }                                                                 |
     | }                                                                   |
-----+---------------------------------------------------------------------+
</code>```

You might also need OBJECT_AGG if you want to group multiple line items together.

Body:
The table which needs to be converted to a json field.

ID,  product, line_item, createdDate

123,  valA,    valB,    '2019-02-02'

The JSON table would be like.

ID,  json_column

123, { valA :
             {valB : '2019-02-02'}}

Now, I'm not sure what kind of parse_json function can be used to create this column. When I use the column name, it errors out - 'Invalid Identifier'

Query used.

select ID, parse_json( {product : { line_item : createdDate }};

Body:
First of all, always try to provide a fully reproducible example

Here's one for your question based on what you wrote

create or replace table x(id int,
                          product varchar,
                          line_item varchar,
                          createdDate varchar)
as select * from values
    (123,'valA','valB','2019-02-02');

select * from x;
-----+---------+-----------+-------------+
 ID  | PRODUCT | LINE_ITEM | CREATEDDATE |
-----+---------+-----------+-------------+
 123 | valA    | valB      | 2019-02-02  |
-----+---------+-----------+-------------+

Now, to get the result you want you can use the OBJECT_CONSTRUCT function, like this:

select id, object_construct(product, object_construct(line_item, createddate)) from x;
-----+---------------------------------------------------------------------+
 ID  | OBJECT_CONSTRUCT(PRODUCT, OBJECT_CONSTRUCT(LINE_ITEM, CREATEDDATE)) |
-----+---------------------------------------------------------------------+
 123 | {                                                                   |
     |   "valA": {                                                         |
     |     "valB": "2019-02-02"                                            |
     |   }                                                                 |
     | }                                                                   |
-----+---------------------------------------------------------------------+

You might also need OBJECT_AGG if you want to group multiple line items together.


问:
Child component props are empty though they're passed from a parent component
I try to get the value of openMenu from Parent to Child function but the props.value is empty in Child function and I don´t understand why.

```<code>function Child({ routes }, props) {

  return (

    <div>{props.value}</div>        /*This is empty*/
  )
}
</code>```

```<code>function Parent() {
  const [isOpen, setOpen] = useState({
    isOpen: false
  });

  const handleClick = e => {
    e.preventDefault();
    setOpen(isOpen => !isOpen);

    if(isOpen === true) {
      const openMenu = 'open';
      return <Child value={openMenu}/>;
    }
    else {
      const openMenu = 'close';
      return <Child value={openMenu} />
    }

  };
}
</code>```

I want to get the value of openMenu, either open or close, to the Child component.

答:
maybe you should have some insight with sending props and destructuring them,

```<code>// suppose props = { val1, val2, val3 }

const Parent = (props) => <Child {...props} />

// in such case you can destructure the values in the paranthesis itself,

const child = ({ val1, val2, val3 }) => {
 <div>
  <div>{val1 && val1}</div>
  <div>{val2 && val2}</div>
  <div>{val3 && val3}</div>
 <div>
}

// which is same as,

const child = (props) => {
 const { val1, val2, val3 } = props
 //rest of the code..
}
</code>```

also you can send multiple props as,

```<code>class Parent extends Component {
 // ..
function1 = () => {..}

function2 = () => {..}

 render () {

 //suppose this.props = { match, dispatch, list, ..}
 const value1 = ..
 const value2 = ..

  return <Child {...{ function1, function2, value1, value2}} {...this.props} />
}
</code>```

and desctructure them in child as,

```<code>const Child = ({
 function1,
 function2,
 value1,
 value2,
 match,
 dispatch,
 list,
 }) => {
  return (
   <div> .. </div>
}
</code>```

now you can see how handy it is, and you won't stumble again..
Note: .. (double dots are fill in the blanks, you know)

Body:
I try to get the value of openMenu from Parent to Child function but the props.value is empty in Child function and I don´t understand why.

function Child({ routes }, props) {

  return (

{props.value}
        /*This is empty*/
  )
}

function Parent() {
  const [isOpen, setOpen] = useState({
    isOpen: false
  });

  const handleClick = e => {
    e.preventDefault();
    setOpen(isOpen => !isOpen);

    if(isOpen === true) {
      const openMenu = 'open';
      return <Child value={openMenu}/>;
    }
    else {
      const openMenu = 'close';
      return <Child value={openMenu} />
    }

  };
}

I want to get the value of openMenu, either open or close, to the Child component.

Body:
maybe you should have some insight with sending props and destructuring them,

// suppose props = { val1, val2, val3 }

const Parent = (props) => <Child {...props} />

// in such case you can destructure the values in the paranthesis itself,

const child = ({ val1, val2, val3 }) => {
 <div>
  <div>{val1 && val1}</div>
  <div>{val2 && val2}</div>
  <div>{val3 && val3}</div>
 <div>
}

// which is same as,

const child = (props) => {
 const { val1, val2, val3 } = props
 //rest of the code..
}

also you can send multiple props as,

class Parent extends Component {
 // ..
function1 = () => {..}

function2 = () => {..}

 render () {

 //suppose this.props = { match, dispatch, list, ..}
 const value1 = ..
 const value2 = ..

  return <Child {...{ function1, function2, value1, value2}} {...this.props} />
}

and desctructure them in child as,

const Child = ({
 function1,
 function2,
 value1,
 value2,
 match,
 dispatch,
 list,
 }) => {
  return (
   <div> .. </div>
}

now you can see how handy it is, and you won't stumble again..
Note: .. (double dots are fill in the blanks, you know)


问:
Sub vs Blocks in Perl6 - aka Roman Numbers Challenge
The Perl Weekly Challenge Number 10 asks us to write an implementation to parse Roman Numbers.

My solution uses reduce. My attempt with a Subroutine works but with a Block it isn't working. What is the difference that makes it failing?

```<code>use Test;
my %roman2num =
    'I'  => 1,
    'V'  => 5,
    'X'  => 10,
    'L'  => 50,
    'C'  => 100,
    'D'  => 500,
    'M'  => 1000;

for test-data().kv -> $roman, $number {
    my $r;
    $r = $roman.comb().reverse.map({%roman2num{$_}}).reduce(
        sub ($sum, $b) {
            state $last = $sum;
            LEAVE { $last = $b };
            return $sum + (($last <= $b)*2-1) * $b;
        }
    );
    is $r, $number, "Roman $roman $r- way 1";

    $r = $roman.comb().reverse.map({%roman2num{$_}}).reduce({
        state $last = $^sum;
        $^b;
        LEAVE { $last = $b };
        $sum + (($last <= $b)*2-1) * $b;
    });
    is $r, $number, "Roman $roman $r- way 2";
}

done-testing;

sub test-data {
    return (
I => 1,
II => 2,
III => 3,
IV => 4,
V => 5,
VI => 6,
VII => 7,
VIII => 8,
IX => 9,
X => 10,
XI => 11,
XII => 12,
XIII => 13,
XIV => 14,
XV => 15,
XVI => 16,
XVII => 17,
XVIII => 18,
XIX => 19,
XX => 20,
XXI => 21,
XXII => 22,
XXIII => 23,
XXIV => 24,
XXV => 25,
XXVI => 26,
XXVII => 27,
XXVIII => 28,
XXIX => 29,
XXX => 30,
XXXI => 31,
XXXII => 32,
XXXIII => 33,
XXXIV => 34,
XXXV => 35,
XXXVI => 36,
XXXVII => 37,
XXXVIII => 38,
XXXIX => 39,
XL => 40,
XLI => 41,
XLII => 42,
XLIII => 43,
XLIV => 44,
XLV => 45,
XLVI => 46,
XLVII => 47,
XLVIII => 48,
XLIX => 49,
L => 50,
LI => 51,
LII => 52,
LIII => 53,
LIV => 54,
LV => 55,
LVI => 56,
LVII => 57,
LVIII => 58,
LIX => 59,
LX => 60,
LXI => 61,
LXII => 62,
LXIII => 63,
LXIV => 64,
LXV => 65,
LXVI => 66,
LXVII => 67,
LXVIII => 68,
LXIX => 69,
LXX => 70,
LXXI => 71,
LXXII => 72,
LXXIII => 73,
LXXIV => 74,
LXXV => 75,
LXXVI => 76,
LXXVII => 77,
LXXVIII => 78,
LXXIX => 79,
LXXX => 80,
LXXXI => 81,
LXXXII => 82,
LXXXIII => 83,
LXXXIV => 84,
LXXXV => 85,
LXXXVI => 86,
LXXXVII => 87,
LXXXVIII => 88,
LXXXIX => 89,
XC => 90,
XCI => 91,
XCII => 92,
XCIII => 93,
XCIV => 94,
XCV => 95,
XCVI => 96,
XCVII => 97,
XCVIII => 98,
XCIX => 99,
C => 100,
CI => 101,
CII => 102,
CIII => 103,
CIV => 104,
CV => 105,
CVI => 106,
CVII => 107,
CVIII => 108,
CIX => 109,
CX => 110,
CXI => 111,
CXII => 112,
CXIII => 113,
CXIV => 114,
CXV => 115,
CXVI => 116,
CXVII => 117,
CXVIII => 118,
CXIX => 119,
CXX => 120,
CXXI => 121,
CXXII => 122,
CXXIII => 123,
CXXIV => 124,
CXXV => 125,
CXXVI => 126,
CXXVII => 127,
CXXVIII => 128,
CXXIX => 129,
CXXX => 130,
CXXXI => 131,
CXXXII => 132,
CXXXIII => 133,
CXXXIV => 134,
CXXXV => 135,
CXXXVI => 136,
CXXXVII => 137,
CXXXVIII => 138,
CXXXIX => 139,
CXL => 140,
CXLI => 141,
CXLII => 142,
CXLIII => 143,
CXLIV => 144,
CXLV => 145,
CXLVI => 146,
CXLVII => 147,
CXLVIII => 148,
CXLIX => 149,
CL => 150,
CLI => 151,
CLII => 152,
CLIII => 153,
CLIV => 154,
CLV => 155,
CLVI => 156,
CLVII => 157,
CLVIII => 158,
CLIX => 159,
CLX => 160,
CLXI => 161,
CLXII => 162,
CLXIII => 163,
CLXIV => 164,
CLXV => 165,
CLXVI => 166,
CLXVII => 167,
CLXVIII => 168,
CLXIX => 169,
CLXX => 170,
CLXXI => 171,
CLXXII => 172,
CLXXIII => 173,
CLXXIV => 174,
CLXXV => 175,
CLXXVI => 176,
CLXXVII => 177,
CLXXVIII => 178,
CLXXIX => 179,
CLXXX => 180,
CLXXXI => 181,
CLXXXII => 182,
CLXXXIII => 183,
CLXXXIV => 184,
CLXXXV => 185,
CLXXXVI => 186,
CLXXXVII => 187,
CLXXXVIII => 188,
CLXXXIX => 189,
CXC => 190,
CXCI => 191,
CXCII => 192,
CXCIII => 193,
CXCIV => 194,
CXCV => 195,
CXCVI => 196,
CXCVII => 197,
CXCVIII => 198,
CXCIX => 199,
CC => 200,
CCI => 201,
CCII => 202,
CCIII => 203,
CCIV => 204,
CCV => 205,
CCVI => 206,
CCVII => 207,
CCVIII => 208,
CCIX => 209,
CCX => 210,
CCXI => 211,
CCXII => 212,
CCXIII => 213,
CCXIV => 214,
CCXV => 215,
CCXVI => 216,
CCXVII => 217,
CCXVIII => 218,
CCXIX => 219,
CCXX => 220,
CCXXI => 221,
CCXXII => 222,
CCXXIII => 223,
CCXXIV => 224,
CCXXV => 225,
CCXXVI => 226,
CCXXVII => 227,
CCXXVIII => 228,
CCXXIX => 229,
CCXXX => 230,
CCXXXI => 231,
CCXXXII => 232,
CCXXXIII => 233,
CCXXXIV => 234,
CCXXXV => 235,
CCXXXVI => 236,
CCXXXVII => 237,
CCXXXVIII => 238,
CCXXXIX => 239,
CCXL => 240,
CCXLI => 241,
CCXLII => 242,
CCXLIII => 243,
CCXLIV => 244,
CCXLV => 245,
CCXLVI => 246,
CCXLVII => 247,
CCXLVIII => 248,
CCXLIX => 249,
CCL => 250,
CCLI => 251,
CCLII => 252,
CCLIII => 253,
CCLIV => 254,
CCLV => 255,
CCLVI => 256,
CCLVII => 257,
CCLVIII => 258,
CCLIX => 259,
CCLX => 260,
CCLXI => 261,
CCLXII => 262,
CCLXIII => 263,
CCLXIV => 264,
CCLXV => 265,
CCLXVI => 266,
CCLXVII => 267,
CCLXVIII => 268,
CCLXIX => 269,
CCLXX => 270,
CCLXXI => 271,
CCLXXII => 272,
CCLXXIII => 273,
CCLXXIV => 274,
CCLXXV => 275,
CCLXXVI => 276,
CCLXXVII => 277,
CCLXXVIII => 278,
CCLXXIX => 279,
CCLXXX => 280,
CCLXXXI => 281,
CCLXXXII => 282,
CCLXXXIII => 283,
CCLXXXIV => 284,
CCLXXXV => 285,
CCLXXXVI => 286,
CCLXXXVII => 287,
CCLXXXVIII => 288,
CCLXXXIX => 289,
CCXC => 290,
CCXCI => 291,
CCXCII => 292,
CCXCIII => 293,
CCXCIV => 294,
CCXCV => 295,
CCXCVI => 296,
CCXCVII => 297,
CCXCVIII => 298,
CCXCIX => 299,
CCC => 300,
CCCI => 301,
CCCII => 302,
CCCIII => 303,
CCCIV => 304,
CCCV => 305,
CCCVI => 306,
CCCVII => 307,
CCCVIII => 308,
CCCIX => 309,
CCCX => 310,
CCCXI => 311,
CCCXII => 312,
CCCXIII => 313,
CCCXIV => 314,
CCCXV => 315,
CCCXVI => 316,
CCCXVII => 317,
CCCXVIII => 318,
CCCXIX => 319,
CCCXX => 320,
CCCXXI => 321,
CCCXXII => 322,
CCCXXIII => 323,
CCCXXIV => 324,
CCCXXV => 325,
CCCXXVI => 326,
CCCXXVII => 327,
CCCXXVIII => 328,
CCCXXIX => 329,
CCCXXX => 330,
CCCXXXI => 331,
CCCXXXII => 332,
CCCXXXIII => 333,
CCCXXXIV => 334,
CCCXXXV => 335,
CCCXXXVI => 336,
CCCXXXVII => 337,
CCCXXXVIII => 338,
CCCXXXIX => 339,
CCCXL => 340,
CCCXLI => 341,
CCCXLII => 342,
CCCXLIII => 343,
CCCXLIV => 344,
CCCXLV => 345,
CCCXLVI => 346,
CCCXLVII => 347,
CCCXLVIII => 348,
CCCXLIX => 349,
CCCL => 350,
CCCLI => 351,
CCCLII => 352,
CCCLIII => 353,
CCCLIV => 354,
CCCLV => 355,
CCCLVI => 356,
CCCLVII => 357,
CCCLVIII => 358,
CCCLIX => 359,
CCCLX => 360,
CCCLXI => 361,
CCCLXII => 362,
CCCLXIII => 363,
CCCLXIV => 364,
CCCLXV => 365,
CCCLXVI => 366,
CCCLXVII => 367,
CCCLXVIII => 368,
CCCLXIX => 369,
CCCLXX => 370,
CCCLXXI => 371,
CCCLXXII => 372,
CCCLXXIII => 373,
CCCLXXIV => 374,
CCCLXXV => 375,
CCCLXXVI => 376,
CCCLXXVII => 377,
CCCLXXVIII => 378,
CCCLXXIX => 379,
CCCLXXX => 380,
CCCLXXXI => 381,
CCCLXXXII => 382,
CCCLXXXIII => 383,
CCCLXXXIV => 384,
CCCLXXXV => 385,
CCCLXXXVI => 386,
CCCLXXXVII => 387,
CCCLXXXVIII => 388,
CCCLXXXIX => 389,
CCCXC => 390,
CCCXCI => 391,
CCCXCII => 392,
CCCXCIII => 393,
CCCXCIV => 394,
CCCXCV => 395,
CCCXCVI => 396,
CCCXCVII => 397,
CCCXCVIII => 398,
CCCXCIX => 399,
CD => 400,
CDI => 401,
CDII => 402,
CDIII => 403,
CDIV => 404,
CDV => 405,
CDVI => 406,
CDVII => 407,
CDVIII => 408,
CDIX => 409,
CDX => 410,
CDXI => 411,
CDXII => 412,
CDXIII => 413,
CDXIV => 414,
CDXV => 415,
CDXVI => 416,
CDXVII => 417,
CDXVIII => 418,
CDXIX => 419,
CDXX => 420,
CDXXI => 421,
CDXXII => 422,
CDXXIII => 423,
CDXXIV => 424,
CDXXV => 425,
CDXXVI => 426,
CDXXVII => 427,
CDXXVIII => 428,
CDXXIX => 429,
CDXXX => 430,
CDXXXI => 431,
CDXXXII => 432,
CDXXXIII => 433,
CDXXXIV => 434,
CDXXXV => 435,
CDXXXVI => 436,
CDXXXVII => 437,
CDXXXVIII => 438,
CDXXXIX => 439,
CDXL => 440,
CDXLI => 441,
CDXLII => 442,
CDXLIII => 443,
CDXLIV => 444,
CDXLV => 445,
CDXLVI => 446,
CDXLVII => 447,
CDXLVIII => 448,
CDXLIX => 449,
CDL => 450,
CDLI => 451,
CDLII => 452,
CDLIII => 453,
CDLIV => 454,
CDLV => 455,
CDLVI => 456,
CDLVII => 457,
CDLVIII => 458,
CDLIX => 459,
CDLX => 460,
CDLXI => 461,
CDLXII => 462,
CDLXIII => 463,
CDLXIV => 464,
CDLXV => 465,
CDLXVI => 466,
CDLXVII => 467,
CDLXVIII => 468,
CDLXIX => 469,
CDLXX => 470,
CDLXXI => 471,
CDLXXII => 472,
CDLXXIII => 473,
CDLXXIV => 474,
CDLXXV => 475,
CDLXXVI => 476,
CDLXXVII => 477,
CDLXXVIII => 478,
CDLXXIX => 479,
CDLXXX => 480,
CDLXXXI => 481,
CDLXXXII => 482,
CDLXXXIII => 483,
CDLXXXIV => 484,
CDLXXXV => 485,
CDLXXXVI => 486,
CDLXXXVII => 487,
CDLXXXVIII => 488,
CDLXXXIX => 489,
CDXC => 490,
CDXCI => 491,
CDXCII => 492,
CDXCIII => 493,
CDXCIV => 494,
CDXCV => 495,
CDXCVI => 496,
CDXCVII => 497,
CDXCVIII => 498,
CDXCIX => 499,
).Hash
}
</code>```

答:
The placeholder variables are sorted in Unicode order ^ twigil . Rename the second variable:

```<code>    $r = $roman.comb().reverse.map({%roman2num{$_}}).reduce({
        state $last = $^sum;
        $^x;
       LEAVE { $last = $x };
       $sum + (($last <= $x)*2-1) * $x;
    });
    is $r, $number, "Roman $roman $r- way 2";
</code>```

Or define the variable in the block signature:

```<code>$r = $roman.comb().reverse.map({%roman2num{$_}}).reduce( -> $sum, $b {
    state $last = $sum;
    $b;
    LEAVE { $last = $b };
    $sum + (($last <= $b)*2-1) * $b;
});
is $r, $number, "Roman $roman $r- way 2";
</code>```

Body:
The Perl Weekly Challenge Number 10 asks us to write an implementation to parse Roman Numbers.

My solution uses reduce. My attempt with a Subroutine works but with a Block it isn't working. What is the difference that makes it failing?

use Test;
my %roman2num =
    'I'  => 1,
    'V'  => 5,
    'X'  => 10,
    'L'  => 50,
    'C'  => 100,
    'D'  => 500,
    'M'  => 1000;

for test-data().kv -> $roman, $number {
    my $r;
    $r = $roman.comb().reverse.map({%roman2num{$_}}).reduce(
        sub ($sum, $b) {
            state $last = $sum;
            LEAVE { $last = $b };
            return $sum + (($last <= $b)*2-1) * $b;
        }
    );
    is $r, $number, "Roman $roman $r- way 1";

    $r = $roman.comb().reverse.map({%roman2num{$_}}).reduce({
        state $last = $^sum;
        $^b;
        LEAVE { $last = $b };
        $sum + (($last <= $b)*2-1) * $b;
    });
    is $r, $number, "Roman $roman $r- way 2";
}

done-testing;

sub test-data {
    return (
I => 1,
II => 2,
III => 3,
IV => 4,
V => 5,
VI => 6,
VII => 7,
VIII => 8,
IX => 9,
X => 10,
XI => 11,
XII => 12,
XIII => 13,
XIV => 14,
XV => 15,
XVI => 16,
XVII => 17,
XVIII => 18,
XIX => 19,
XX => 20,
XXI => 21,
XXII => 22,
XXIII => 23,
XXIV => 24,
XXV => 25,
XXVI => 26,
XXVII => 27,
XXVIII => 28,
XXIX => 29,
XXX => 30,
XXXI => 31,
XXXII => 32,
XXXIII => 33,
XXXIV => 34,
XXXV => 35,
XXXVI => 36,
XXXVII => 37,
XXXVIII => 38,
XXXIX => 39,
XL => 40,
XLI => 41,
XLII => 42,
XLIII => 43,
XLIV => 44,
XLV => 45,
XLVI => 46,
XLVII => 47,
XLVIII => 48,
XLIX => 49,
L => 50,
LI => 51,
LII => 52,
LIII => 53,
LIV => 54,
LV => 55,
LVI => 56,
LVII => 57,
LVIII => 58,
LIX => 59,
LX => 60,
LXI => 61,
LXII => 62,
LXIII => 63,
LXIV => 64,
LXV => 65,
LXVI => 66,
LXVII => 67,
LXVIII => 68,
LXIX => 69,
LXX => 70,
LXXI => 71,
LXXII => 72,
LXXIII => 73,
LXXIV => 74,
LXXV => 75,
LXXVI => 76,
LXXVII => 77,
LXXVIII => 78,
LXXIX => 79,
LXXX => 80,
LXXXI => 81,
LXXXII => 82,
LXXXIII => 83,
LXXXIV => 84,
LXXXV => 85,
LXXXVI => 86,
LXXXVII => 87,
LXXXVIII => 88,
LXXXIX => 89,
XC => 90,
XCI => 91,
XCII => 92,
XCIII => 93,
XCIV => 94,
XCV => 95,
XCVI => 96,
XCVII => 97,
XCVIII => 98,
XCIX => 99,
C => 100,
CI => 101,
CII => 102,
CIII => 103,
CIV => 104,
CV => 105,
CVI => 106,
CVII => 107,
CVIII => 108,
CIX => 109,
CX => 110,
CXI => 111,
CXII => 112,
CXIII => 113,
CXIV => 114,
CXV => 115,
CXVI => 116,
CXVII => 117,
CXVIII => 118,
CXIX => 119,
CXX => 120,
CXXI => 121,
CXXII => 122,
CXXIII => 123,
CXXIV => 124,
CXXV => 125,
CXXVI => 126,
CXXVII => 127,
CXXVIII => 128,
CXXIX => 129,
CXXX => 130,
CXXXI => 131,
CXXXII => 132,
CXXXIII => 133,
CXXXIV => 134,
CXXXV => 135,
CXXXVI => 136,
CXXXVII => 137,
CXXXVIII => 138,
CXXXIX => 139,
CXL => 140,
CXLI => 141,
CXLII => 142,
CXLIII => 143,
CXLIV => 144,
CXLV => 145,
CXLVI => 146,
CXLVII => 147,
CXLVIII => 148,
CXLIX => 149,
CL => 150,
CLI => 151,
CLII => 152,
CLIII => 153,
CLIV => 154,
CLV => 155,
CLVI => 156,
CLVII => 157,
CLVIII => 158,
CLIX => 159,
CLX => 160,
CLXI => 161,
CLXII => 162,
CLXIII => 163,
CLXIV => 164,
CLXV => 165,
CLXVI => 166,
CLXVII => 167,
CLXVIII => 168,
CLXIX => 169,
CLXX => 170,
CLXXI => 171,
CLXXII => 172,
CLXXIII => 173,
CLXXIV => 174,
CLXXV => 175,
CLXXVI => 176,
CLXXVII => 177,
CLXXVIII => 178,
CLXXIX => 179,
CLXXX => 180,
CLXXXI => 181,
CLXXXII => 182,
CLXXXIII => 183,
CLXXXIV => 184,
CLXXXV => 185,
CLXXXVI => 186,
CLXXXVII => 187,
CLXXXVIII => 188,
CLXXXIX => 189,
CXC => 190,
CXCI => 191,
CXCII => 192,
CXCIII => 193,
CXCIV => 194,
CXCV => 195,
CXCVI => 196,
CXCVII => 197,
CXCVIII => 198,
CXCIX => 199,
CC => 200,
CCI => 201,
CCII => 202,
CCIII => 203,
CCIV => 204,
CCV => 205,
CCVI => 206,
CCVII => 207,
CCVIII => 208,
CCIX => 209,
CCX => 210,
CCXI => 211,
CCXII => 212,
CCXIII => 213,
CCXIV => 214,
CCXV => 215,
CCXVI => 216,
CCXVII => 217,
CCXVIII => 218,
CCXIX => 219,
CCXX => 220,
CCXXI => 221,
CCXXII => 222,
CCXXIII => 223,
CCXXIV => 224,
CCXXV => 225,
CCXXVI => 226,
CCXXVII => 227,
CCXXVIII => 228,
CCXXIX => 229,
CCXXX => 230,
CCXXXI => 231,
CCXXXII => 232,
CCXXXIII => 233,
CCXXXIV => 234,
CCXXXV => 235,
CCXXXVI => 236,
CCXXXVII => 237,
CCXXXVIII => 238,
CCXXXIX => 239,
CCXL => 240,
CCXLI => 241,
CCXLII => 242,
CCXLIII => 243,
CCXLIV => 244,
CCXLV => 245,
CCXLVI => 246,
CCXLVII => 247,
CCXLVIII => 248,
CCXLIX => 249,
CCL => 250,
CCLI => 251,
CCLII => 252,
CCLIII => 253,
CCLIV => 254,
CCLV => 255,
CCLVI => 256,
CCLVII => 257,
CCLVIII => 258,
CCLIX => 259,
CCLX => 260,
CCLXI => 261,
CCLXII => 262,
CCLXIII => 263,
CCLXIV => 264,
CCLXV => 265,
CCLXVI => 266,
CCLXVII => 267,
CCLXVIII => 268,
CCLXIX => 269,
CCLXX => 270,
CCLXXI => 271,
CCLXXII => 272,
CCLXXIII => 273,
CCLXXIV => 274,
CCLXXV => 275,
CCLXXVI => 276,
CCLXXVII => 277,
CCLXXVIII => 278,
CCLXXIX => 279,
CCLXXX => 280,
CCLXXXI => 281,
CCLXXXII => 282,
CCLXXXIII => 283,
CCLXXXIV => 284,
CCLXXXV => 285,
CCLXXXVI => 286,
CCLXXXVII => 287,
CCLXXXVIII => 288,
CCLXXXIX => 289,
CCXC => 290,
CCXCI => 291,
CCXCII => 292,
CCXCIII => 293,
CCXCIV => 294,
CCXCV => 295,
CCXCVI => 296,
CCXCVII => 297,
CCXCVIII => 298,
CCXCIX => 299,
CCC => 300,
CCCI => 301,
CCCII => 302,
CCCIII => 303,
CCCIV => 304,
CCCV => 305,
CCCVI => 306,
CCCVII => 307,
CCCVIII => 308,
CCCIX => 309,
CCCX => 310,
CCCXI => 311,
CCCXII => 312,
CCCXIII => 313,
CCCXIV => 314,
CCCXV => 315,
CCCXVI => 316,
CCCXVII => 317,
CCCXVIII => 318,
CCCXIX => 319,
CCCXX => 320,
CCCXXI => 321,
CCCXXII => 322,
CCCXXIII => 323,
CCCXXIV => 324,
CCCXXV => 325,
CCCXXVI => 326,
CCCXXVII => 327,
CCCXXVIII => 328,
CCCXXIX => 329,
CCCXXX => 330,
CCCXXXI => 331,
CCCXXXII => 332,
CCCXXXIII => 333,
CCCXXXIV => 334,
CCCXXXV => 335,
CCCXXXVI => 336,
CCCXXXVII => 337,
CCCXXXVIII => 338,
CCCXXXIX => 339,
CCCXL => 340,
CCCXLI => 341,
CCCXLII => 342,
CCCXLIII => 343,
CCCXLIV => 344,
CCCXLV => 345,
CCCXLVI => 346,
CCCXLVII => 347,
CCCXLVIII => 348,
CCCXLIX => 349,
CCCL => 350,
CCCLI => 351,
CCCLII => 352,
CCCLIII => 353,
CCCLIV => 354,
CCCLV => 355,
CCCLVI => 356,
CCCLVII => 357,
CCCLVIII => 358,
CCCLIX => 359,
CCCLX => 360,
CCCLXI => 361,
CCCLXII => 362,
CCCLXIII => 363,
CCCLXIV => 364,
CCCLXV => 365,
CCCLXVI => 366,
CCCLXVII => 367,
CCCLXVIII => 368,
CCCLXIX => 369,
CCCLXX => 370,
CCCLXXI => 371,
CCCLXXII => 372,
CCCLXXIII => 373,
CCCLXXIV => 374,
CCCLXXV => 375,
CCCLXXVI => 376,
CCCLXXVII => 377,
CCCLXXVIII => 378,
CCCLXXIX => 379,
CCCLXXX => 380,
CCCLXXXI => 381,
CCCLXXXII => 382,
CCCLXXXIII => 383,
CCCLXXXIV => 384,
CCCLXXXV => 385,
CCCLXXXVI => 386,
CCCLXXXVII => 387,
CCCLXXXVIII => 388,
CCCLXXXIX => 389,
CCCXC => 390,
CCCXCI => 391,
CCCXCII => 392,
CCCXCIII => 393,
CCCXCIV => 394,
CCCXCV => 395,
CCCXCVI => 396,
CCCXCVII => 397,
CCCXCVIII => 398,
CCCXCIX => 399,
CD => 400,
CDI => 401,
CDII => 402,
CDIII => 403,
CDIV => 404,
CDV => 405,
CDVI => 406,
CDVII => 407,
CDVIII => 408,
CDIX => 409,
CDX => 410,
CDXI => 411,
CDXII => 412,
CDXIII => 413,
CDXIV => 414,
CDXV => 415,
CDXVI => 416,
CDXVII => 417,
CDXVIII => 418,
CDXIX => 419,
CDXX => 420,
CDXXI => 421,
CDXXII => 422,
CDXXIII => 423,
CDXXIV => 424,
CDXXV => 425,
CDXXVI => 426,
CDXXVII => 427,
CDXXVIII => 428,
CDXXIX => 429,
CDXXX => 430,
CDXXXI => 431,
CDXXXII => 432,
CDXXXIII => 433,
CDXXXIV => 434,
CDXXXV => 435,
CDXXXVI => 436,
CDXXXVII => 437,
CDXXXVIII => 438,
CDXXXIX => 439,
CDXL => 440,
CDXLI => 441,
CDXLII => 442,
CDXLIII => 443,
CDXLIV => 444,
CDXLV => 445,
CDXLVI => 446,
CDXLVII => 447,
CDXLVIII => 448,
CDXLIX => 449,
CDL => 450,
CDLI => 451,
CDLII => 452,
CDLIII => 453,
CDLIV => 454,
CDLV => 455,
CDLVI => 456,
CDLVII => 457,
CDLVIII => 458,
CDLIX => 459,
CDLX => 460,
CDLXI => 461,
CDLXII => 462,
CDLXIII => 463,
CDLXIV => 464,
CDLXV => 465,
CDLXVI => 466,
CDLXVII => 467,
CDLXVIII => 468,
CDLXIX => 469,
CDLXX => 470,
CDLXXI => 471,
CDLXXII => 472,
CDLXXIII => 473,
CDLXXIV => 474,
CDLXXV => 475,
CDLXXVI => 476,
CDLXXVII => 477,
CDLXXVIII => 478,
CDLXXIX => 479,
CDLXXX => 480,
CDLXXXI => 481,
CDLXXXII => 482,
CDLXXXIII => 483,
CDLXXXIV => 484,
CDLXXXV => 485,
CDLXXXVI => 486,
CDLXXXVII => 487,
CDLXXXVIII => 488,
CDLXXXIX => 489,
CDXC => 490,
CDXCI => 491,
CDXCII => 492,
CDXCIII => 493,
CDXCIV => 494,
CDXCV => 495,
CDXCVI => 496,
CDXCVII => 497,
CDXCVIII => 498,
CDXCIX => 499,
).Hash
}

Body:
The placeholder variables are sorted in Unicode order ^ twigil . Rename the second variable:

    $r = $roman.comb().reverse.map({%roman2num{$_}}).reduce({
        state $last = $^sum;
        $^x;
       LEAVE { $last = $x };
       $sum + (($last <= $x)*2-1) * $x;
    });
    is $r, $number, "Roman $roman $r- way 2";

Or define the variable in the block signature:

$r = $roman.comb().reverse.map({%roman2num{$_}}).reduce( -> $sum, $b {
    state $last = $sum;
    $b;
    LEAVE { $last = $b };
    $sum + (($last <= $b)*2-1) * $b;
});
is $r, $number, "Roman $roman $r- way 2";


问:
Problem with BS4 printing only certain parts of the web page
I am having a problem with bs4 only finding some things in html. To be specific when I try to print span.nav2__menu-link-main-text it selects it and prints it without a problem but when I try to select other part of the page it probably selects it but It doesnt want to print it out. Here is the code that prints and the code that doesnt print:

Tried using different parsers other than lxml and none worked.

```<code>#This one prints

from bs4 import BeautifulSoup
import requests
import lxml

url = 'https://osu.ppy.sh/users/18723891'
res = requests.get(url)
soup = BeautifulSoup(res.text, 'lxml')

for i in soup.select('span.nav2__menu-link-main-text'):
    print(i.text)

#This one does not print

from bs4 import BeautifulSoup
import requests
import lxml

url = 'https://osu.ppy.sh/users/https://osu.ppy.sh/users/18723891'
res = requests.get(url)
soup = BeautifulSoup(res.text, 'lxml')

for i in soup.select('div.value-dispaly__value'):
    print(i.text)
</code>```

I expect this program to print the current value of div.value-dispaly__value
but when I start the program it prints nothing even tough I can see the value is 4000 when I inspect the page.

答:
It seems that code you are willing to get is dynamically added to the web page by javascript.
In order to update web js part, you have to use requests render() function.

Body:
I am having a problem with bs4 only finding some things in html. To be specific when I try to print span.nav2__menu-link-main-text it selects it and prints it without a problem but when I try to select other part of the page it probably selects it but It doesnt want to print it out. Here is the code that prints and the code that doesnt print:

Tried using different parsers other than lxml and none worked.

#This one prints

from bs4 import BeautifulSoup
import requests
import lxml

url = 'https://osu.ppy.sh/users/18723891'
res = requests.get(url)
soup = BeautifulSoup(res.text, 'lxml')

for i in soup.select('span.nav2__menu-link-main-text'):
    print(i.text)

#This one does not print

from bs4 import BeautifulSoup
import requests
import lxml

url = 'https://osu.ppy.sh/users/https://osu.ppy.sh/users/18723891'
res = requests.get(url)
soup = BeautifulSoup(res.text, 'lxml')

for i in soup.select('div.value-dispaly__value'):
    print(i.text)

I expect this program to print the current value of div.value-dispaly__value
but when I start the program it prints nothing even tough I can see the value is 4000 when I inspect the page.


问:
How to print table text to md table using showdown.js?
I'd like to print md table by using showdown.js. But, it doesn't seem to convert to markdown table correctly as I expected.

I tried setting options('table option') to be changed 'true' and converting text to md. but, doesn't work.

Below is the functions I implemented, for your information.

setMdConvert() <= As I said, I just tried all options for true.

getTechDescriptionMd() <= A test function for converting arbitary markdown text to markdown table

function setMdConvert() {
    var mdConverter = new showdown.Converter();
    var options = showdown.getOptions();
    var keys = Object.keys(options);

    keys.forEach((key) => {
        if(options[key].constructor === boolConstructor)
            mdConverter.setOption(key, true);
    });

    console.log(mdConverter.getOptions());

    return mdConverter;
}

function getTechDescriptionMd() {
    var text = '| h1    |    h2   |      h3 |' +
               '|:------|:-------:|--------:|' +
               '| 100   | [a][1]  | ![b][2] |' +
               '| *foo* | **bar** | ~~baz~~ |';
    var html = mdConverter.makeHtml(text);

    $('.desc-viewer').html(html);
}
```

<p>result:</p>

```| h1 | h2 | h3 ||:------|:-------:|--------:|| 100 | [a][1] | ![b][2] || foo | bar | baz |
```

Is there any other option that I miss?

答:
Here's a modified version of .getTechDescriptionMd() that works for me. I added the linebreaks that I already mentioned in my comment from yesterday, plus I initialized mdConverter and set its option 'tables' to true (inspired by the documentation).

It looks like this now:

```<code>function getTechDescriptionMd() {
    var text = '| h1    |    h2   |      h3 |\n' +
               '|:------|:-------:|--------:|\n' +
               '| 100   | [a][1]  | ![b][2] |\n' +
               '| *foo* | **bar** | ~~baz~~ |';

    var mdConverter = new showdown.Converter();
    mdConverter.setOption('tables', true);
    var html = mdConverter.makeHtml(text);
    $('.desc-viewer').html(html);
}
</code>```

The result I'm getting is:

```<code><table>
<thead>
<tr>
<th style="text-align:left;">h1</th>
<th style="text-align:center;">h2</th>
<th style="text-align:right;">h3</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left;">100</td>
<td style="text-align:center;">[a][1]</td>
<td style="text-align:right;">![b][2]</td>
</tr>
<tr>
<td style="text-align:left;"><em>foo</em></td>
<td style="text-align:center;"><strong>bar</strong></td>
<td style="text-align:right;">~~baz~~</td>
</tr>
</tbody>
</table>
</code>```

Body:
I'd like to print md table by using showdown.js. But, it doesn't seem to convert to markdown table correctly as I expected.

I tried setting options('table option') to be changed 'true' and converting text to md. but, doesn't work.

Below is the functions I implemented, for your information.

setMdConvert() <= As I said, I just tried all options for true.

getTechDescriptionMd() <= A test function for converting arbitary markdown text to markdown table

function setMdConvert() {
    var mdConverter = new showdown.Converter();
    var options = showdown.getOptions();
    var keys = Object.keys(options);

    keys.forEach((key) => {
        if(options[key].constructor === boolConstructor)
            mdConverter.setOption(key, true);
    });

    console.log(mdConverter.getOptions());

    return mdConverter;
}

function getTechDescriptionMd() {
    var text = '| h1    |    h2   |      h3 |' +
               '|:------|:-------:|--------:|' +
               '| 100   | [a][1]  | ![b][2] |' +
               '| *foo* | **bar** | ~~baz~~ |';
    var html = mdConverter.makeHtml(text);

    $('.desc-viewer').html(html);
}

result:

| h1 | h2 | h3 ||:------|:-------:|--------:|| 100 | [a][1] | ![b][2] || foo | bar | baz |

Is there any other option that I miss?

Body:
Here's a modified version of .getTechDescriptionMd() that works for me. I added the linebreaks that I already mentioned in my comment from yesterday, plus I initialized mdConverter and set its option 'tables' to true (inspired by the documentation).

It looks like this now:

function getTechDescriptionMd() {
    var text = '| h1    |    h2   |      h3 |\n' +
               '|:------|:-------:|--------:|\n' +
               '| 100   | [a][1]  | ![b][2] |\n' +
               '| *foo* | **bar** | ~~baz~~ |';

    var mdConverter = new showdown.Converter();
    mdConverter.setOption('tables', true);
    var html = mdConverter.makeHtml(text);
    $('.desc-viewer').html(html);
}

The result I'm getting is:

<table>
<thead>
<tr>
<th style="text-align:left;">h1</th>
<th style="text-align:center;">h2</th>
<th style="text-align:right;">h3</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left;">100</td>
<td style="text-align:center;">[a][1]</td>
<td style="text-align:right;">![b][2]</td>
</tr>
<tr>
<td style="text-align:left;"><em>foo</em></td>
<td style="text-align:center;"><strong>bar</strong></td>
<td style="text-align:right;">~~baz~~</td>
</tr>
</tbody>
</table>


问:
Why this error on line 3, file "Code" for onEdit(e)?
In Google Sheets, I am wanting to do something like the following:

If B129=I3, then D129 = 1. 1 now is to be held and never forgotten.

Then, if B129=I3 again, then D129 = 2. D129 can now repetitively increase by 1 over and over again as many times as B129=I3.

Thanks to a wonderful member here, I now have a framework for how this can possibly be done. But I am getting an error message that says: TypeError: Cannot read property "range" from undefined. (line 3, file "Code"), using the code down below?

Because of this error, the problem that I am having is that the code does not run on the spreadsheet at all. Nothing happens, even if I were to perform what I need to do on the actual spreadsheet, because the error continues to come up as: Cannot read property "range" from undefined. (Line 3, file code).

```<code>function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("M Numbers");
if  (e.range.getA1Notation() != 'B129')  return; //Something other than the cell you wanted changed
var x = ss.getRange("I3").getValue();
if (e.getValue() != x) return;  //B129 doesn't equal I3
var counter = ss.getRange("D129"); // cell reference
counter.setValue(counter.getValue() + 1);
}
</code>```

答:
This onEdit(e) script is using Event Objects. You can't run these scripts manually, they run automatically when the spreadsheet is edited.

e.range is where you're trying to call the event object to get the edited range of the sheet. Since there's no edited range to pull when you run it manually in script editor, it'll fail with the error you're experiencing.

Body:
In Google Sheets, I am wanting to do something like the following:

If B129=I3, then D129 = 1. 1 now is to be held and never forgotten.

Then, if B129=I3 again, then D129 = 2. D129 can now repetitively increase by 1 over and over again as many times as B129=I3.

Thanks to a wonderful member here, I now have a framework for how this can possibly be done. But I am getting an error message that says: TypeError: Cannot read property "range" from undefined. (line 3, file "Code"), using the code down below?

Because of this error, the problem that I am having is that the code does not run on the spreadsheet at all. Nothing happens, even if I were to perform what I need to do on the actual spreadsheet, because the error continues to come up as: Cannot read property "range" from undefined. (Line 3, file code).

function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("M Numbers");
if  (e.range.getA1Notation() != 'B129')  return; //Something other than the cell you wanted changed
var x = ss.getRange("I3").getValue();
if (e.getValue() != x) return;  //B129 doesn't equal I3
var counter = ss.getRange("D129"); // cell reference
counter.setValue(counter.getValue() + 1);
}


问:
React-Native Remote Debugger not working on iPhone
I'm running a React-Native app on my iPhone, the app seems to load fine but when I shake and enable Remote JS Debugging I get this error:

I've tried following React-Native's docs https://facebook.github.io/react-native/docs/running-on-device-ios.html however it seems outdated.

AppDelegate.m

```<code>#import "AppDelegate.h"
#import "RCTBundleURLProvider.h"
#import "RCTRootView.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application     didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  NSURL *jsCodeLocation;

  [[RCTBundleURLProvider sharedSettings] setDefaults];
  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"abcrn123"
                                           initialProperties:nil
                                                   launchOptions:launchOptions];
  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f     green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen     mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

@end
</code>```

Any help would be greatly appreciated, I'm trying to run and debug a React-Native app on a real device.

Thanks, Doug.

答:
I quit trying to get that to work,
just

npm install -g localtunnel

lt --port 8081

Copy the url that this command outputs, and place it to your AppDelegate.m like so
return [NSURL URLWithString:@"https://blue-termites-13.localtunnel.me/index.bundle?platform=ios&dev=true"];

Body:
I'm running a React-Native app on my iPhone, the app seems to load fine but when I shake and enable Remote JS Debugging I get this error:

I've tried following React-Native's docs https://facebook.github.io/react-native/docs/running-on-device-ios.html however it seems outdated.

AppDelegate.m

#import "AppDelegate.h"
#import "RCTBundleURLProvider.h"
#import "RCTRootView.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application     didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  NSURL *jsCodeLocation;

  [[RCTBundleURLProvider sharedSettings] setDefaults];
  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"abcrn123"
                                           initialProperties:nil
                                                   launchOptions:launchOptions];
  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f     green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen     mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

@end

Any help would be greatly appreciated, I'm trying to run and debug a React-Native app on a real device.

Thanks, Doug.