问:
Reversing a string operation
So I was fiddling with my encryption algorithms when this problem caught my attention:

Suppose you have a string operation given by the following pseudocode:

```<code>string go_wacky(string input, int reps)
{
    string result = input;
    foreach (0..reps)
    {
        result = insert_substring_at(result, input, random_from_to(0, length(result));
    }
    return result;
}
</code>```

Or, in point-and-click terminology, copy the string, then reps times do the following: move the cursor to a random position within the string and hit paste.

Given the output string and reps, how to extract the input string (other than "reverse brute force" based on reconstructing the character list of the original string using reps and output length)?

答:
We can find the chars of the input string, by counting the frequencies of all the chars and dividing by rep count + 1. For example, if a is 12 times in the output, and rep count is 2. Then the input string is contained 2+1 times in the output and thus contains 12/3 = 4 a's.

Next, look at the first char of the output, that is the first char of the input aswell. Subtract one from its frequency.

For the next char, we do a branch.

It is the start of the input: Just continue.

or, it is the second char of the input. Decrease the frequency and continue.

Pretty much the same procedure for the following chars.

For example, if the output starts with aa.... When reading the second a, the input can be a... and aa.... (Unless, the frequency of a is 1.)

I think this should be quite fast. In the case the frequencies are all one, this is O(n) with n size of the output string.

Title: Reversing a string operation

Body:
So I was fiddling with my encryption algorithms when this problem caught my attention:

Suppose you have a string operation given by the following pseudocode:

string go_wacky(string input, int reps)
{
    string result = input;
    foreach (0..reps)
    {
        result = insert_substring_at(result, input, random_from_to(0, length(result));
    }
    return result;
}

Or, in point-and-click terminology, copy the string, then reps times do the following: move the cursor to a random position within the string and hit paste.

Given the output string and reps, how to extract the input string (other than "reverse brute force" based on reconstructing the character list of the original string using reps and output length)?


来源: stackexchange

问:
Cannot add a child that doesn't have a YogaNode to parent
"Cannot add a child that doesn't have a YogaNode to a parent without a meassure function!" Error in React-Native Expo. Has something to do with my map in a component I believe, I was just returning an h2 tag with the info, then I realized it needed to be a Text, put it in a Text instead and got this new error. People online said it needed to be a View as well, that didn't seem to fix it though.</p>

```<code>import React from "react";
import { StyleSheet, Text, View } from "react-native";

export default function ListTasks(props) {
  return (
    <View style={styles.container}>
      <Text>
        {" "}
        {props.tasks.map(task => {
          return (
            <View style={styles.container}>
              <Text>{task.Task}</Text>
            </View>
          );
        })}{" "}
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  }
});

</code>```

```<code>
export default class TodoList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tasks: [
        { Completed: false, Task: "Drink water" },
        { Completed: false, Task: "Work on React-Native app" },
        { Completed: false, Task: "Clean bedroom" }
      ]
    };
  }
  render() {
    return (
      <View style={styles.container}>
        <ListTasks tasks={this.state.tasks} />
      </View>
    );
  }
}
</code>```

答:
It was the simple ";" at the end of the return in the map that prettier was auto putting in.. </p>

```<code><Text>
        {" "}
        {props.tasks.map(task => {
          return (
            <View style={styles.container}>
              <Text>{task.Task}</Text>
            </View>
          )
        })}{" "}
      </Text>

</code>```

ContentLicense: CC BY-SA 4.0

Body:
"Cannot add a child that doesn't have a YogaNode to a parent without a meassure function!" Error in React-Native Expo. Has something to do with my map in a component I believe, I was just returning an h2 tag with the info, then I realized it needed to be a Text, put it in a Text instead and got this new error. People online said it needed to be a View as well, that didn't seem to fix it though.

import React from "react";
import { StyleSheet, Text, View } from "react-native";

export default function ListTasks(props) {
  return (
    <View style={styles.container}>
      <Text>
        {" "}
        {props.tasks.map(task => {
          return (
            <View style={styles.container}>
              <Text>{task.Task}</Text>
            </View>
          );
        })}{" "}
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  }
});

export default class TodoList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tasks: [
        { Completed: false, Task: "Drink water" },
        { Completed: false, Task: "Work on React-Native app" },
        { Completed: false, Task: "Clean bedroom" }
      ]
    };
  }
  render() {
    return (
      <View style={styles.container}>
        <ListTasks tasks={this.state.tasks} />
      </View>
    );
  }
}

Body:
It was the simple ";" at the end of the return in the map that prettier was auto putting in..

<Text>
        {" "}
        {props.tasks.map(task => {
          return (
            <View style={styles.container}>
              <Text>{task.Task}</Text>
            </View>
          )
        })}{" "}
      </Text>


问:
How to call Wordpress Elementor Popup from Code
I want to call an Elementor Popup from custom code (HTML, CSS, Javascript).
Does anyone know how to do that?
Thanks in advance!</p>

答:
Here's how to call the popup via javascript:

```<code>$(document).ready(function(){
    elementorProFrontend.modules.popup.showPopup( {id:2041}, event);
});
</code>```

Make sure to replace the id with yours.

Body:
Here's how to call the popup via javascript:

$(document).ready(function(){
    elementorProFrontend.modules.popup.showPopup( {id:2041}, event);
});

Make sure to replace the id with yours.


问:
What is the better choice: A wide neural network or a deep neural network?
I am really new to deep learning, I wonder that if we build a wide NN which has just only one hidden layer but it has much more units than a NN which has more hidden layers but has less units on hidden layers than the other one.

What is the NN which will give us the best performance?

Thanks in advance!

答: Generally speaking, deep NNs will generalize better, hence most cutting edge networks go deeper and not wider, which at some point introduces problems as well. The optimal solution depends on your problem though. You can find a detailed answer here.</p>


问:
Location updates update only the marker but not the map. Flutter
I'm receiving a stream of Positions , I than update a _positionvariable that is used both in center: to set the map position, and in the Marker I use to show user position.
The problem is that the marker gets updated, but not the map position.
The expected behaviour is that the Marker, stays steady on the centre of the screen while the map moves underneath it, but it happen the opposite. Can you see where I set things wrong?
many thanks for your time and help.

```<code>class HomeScreen extends StatefulWidget {
  final String name;

  HomeScreen({
    Key key,
    @required this.name,
  }) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  Geolocator _geolocator;
  Position _position;

  FlutterMap _flutterMap;
  MapOptions _mapOptions;
  MapController _controller;
  void checkPermission() {
    _geolocator.checkGeolocationPermissionStatus().then((status) {
      print('status: $status');
    });
    _geolocator
        .checkGeolocationPermissionStatus(
            locationPermission: GeolocationPermission.locationAlways)
        .then((status) {
      print('always status: $status');
    });
    _geolocator.checkGeolocationPermissionStatus(
        locationPermission: GeolocationPermission.locationWhenInUse)
      ..then((status) {
        print('whenInUse status: $status');
      });
  }

  @override
  void initState() {
    super.initState();
    _geolocator = Geolocator();
    checkPermission();
    updateLocation();
  }

  void setMap() {
    _controller = MapController();
    _mapOptions = MapOptions(
      center: LatLng(_position.latitude, _position.longitude),
      minZoom: 16.0,
      maxZoom: 19.0,
    );
    _flutterMap = FlutterMap(
      options: _mapOptions,
      mapController: _controller,
      layers: [
//        PolygonLayer(polygonOpts, map, stream)
//                    PolygonLayerOptions(
//                      polygons:
//                    ),
        TileLayerOptions(
//        urlTemplate:'https://api.openrouteservice.org/mapsurfer/{z}/{x}/{y}.png?api_key=5b3ce3597851110001cf62484c4b65d85bc844eca3a2c6b9f300ddf4',
            urlTemplate: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
            subdomains: ['a', 'b', 'c'],
            keepBuffer: 20),
        new MarkerLayerOptions(
          markers: [
            Marker(
              point: LatLng(_position.latitude, _position.longitude),
              height: 200,
              width: 200,
              builder: (context) => IconButton(
                icon: Icon(Icons.location_on),
                color: Colors.red,
                iconSize: 60,
                onPressed: () {
                  print('icon tapped');
                },
              ),
            ),
          ],
        ),
      ],
    );
  }

  void startTracking() {
    LocationOptions locationOptions =
        LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 0);

    StreamSubscription positionStream = _geolocator
        .getPositionStream(locationOptions)
        .listen((Position position) {
      setState(() {
        _position = position;
        if (_position != null) {
//          _controller.move(LatLng(_position.latitude, _position.longitude), 16);
          setMap();
        }
      });
      print(
          _position.latitude.toString() + ',' + _position.longitude.toString());
    });
  }

  void updateLocation() async {
    try {
      Position newPosition = await _geolocator
          .getCurrentPosition(
            desiredAccuracy: LocationAccuracy.bestForNavigation,
          )
          .timeout(new Duration(seconds: 5));
      print(
          'updateLocation(): ${newPosition.latitude.toString() + ',' + newPosition.longitude.toString()}');

      setState(() {
        _position = newPosition;
        setMap();
      });
    } catch (error) {
      print('Error updating location: ${error.toString()}');
    }
  }

  void postRequest() async {
    print('postRequest called');

    // working properly
//    final request =
//    'http://router.project-osrm.org/trip/v1/driving/44.5018645003438,11.340018709036542;44.501342559233315,11.336182647230146?exclude=motorway';
//    final request = 'http://router.project-osrm.org/trip/v1/driving/44.5018645003438,11.340018709036542;44.501342559233315,11.33618264723014?source=first&destination=last&roundtrip=false&exclude=motorway&generate_hints=false&geometries=geojson&overview=full';
//    final request =
//        'http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&v=bicycle&fast=0&layer=mapnik&flat=44.5018645003438&flon=11.340018709036542&tlat=44.501342559233315&tlon=11.336182647230146&geometry=1&instructions=1&lang=it';

    // GOOOD
    final request =
        'http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&v=bicycle&fast=0&layer=mapnik&flat=44.5018645003438&flon=11.340018709036542&tlat=44.502138&tlon=11.340402&geometry=1&instructions=1&lang=it';

    // only driving
//    final request =
//        'http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&flat=52.215676&flon=5.963946&tlat=52.2573&tlon=6.1799&v=motorcar&fast=1&layer=mapnik';

//    final request =
//        'https://routing.openstreetmap.de/routed-foot/route/v1/driving/13.7807085453224,51.0536161;13.7835429,51.0515885?overview=false&geometries=polyline&steps=true';

    // Await the http get response, then decode the json-formatted response.
    var response = await get(request);
    if (response.statusCode == 200) {
      var jsonResponse = convert.jsonDecode(response.body);
      print('${jsonResponse.runtimeType} : $jsonResponse');
      List<dynamic> coordinates = jsonResponse['coordinates'];
      print('coordinates are : $coordinates');
      print('coordinates are: ${coordinates.length}');
      Map<String, dynamic> properties = jsonResponse['properties'];
//      print('properties are $properties');
      String distance = properties['distance'];
      print('Route is $distance Km long.');
      String instructions = properties['description'];
      print('instructions are $instructions');

      List<LatLng> suggestedRoute = [];
      for (int i = 0; i < (coordinates.length); i++) {
        dynamic coordinate = coordinates[i];
        LatLng position = LatLng(coordinate[1], coordinate[0]);
        suggestedRoute.add(position);
        print('position is $position');
        print(i);
      }
      print('suggestedRoute is $suggestedRoute');
    } else {
      print('Request failed with status: ${response.statusCode}.');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        title: Text(
          'Home',
          style: TextStyle(color: Colors.orangeAccent, fontSize: 40),
        ),
        actions: <Widget>[
          IconButton(
            icon: Icon(
              Icons.exit_to_app,
              color: Colors.orange,
              size: 35,
            ),
            onPressed: () {
              BlocProvider.of<AuthenticationBloc>(context).add(
                LoggedOut(),
              );
            },
          ),
        ],
      ),
      backgroundColor: Colors.white,
      body: SafeArea(
        minimum: EdgeInsets.symmetric(horizontal: 20),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                height: 670,
                width: 370,
                child: _flutterMap,

              ),
              SizedBox(
                height: 10,
              ),
              RaisedButton(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(5)),
                onPressed: () {
                  startTracking();
//                  setState(() {
////                    updateLocation();
//                  });
//
                },
                color: Colors.red,
                child: Padding(
                  padding: EdgeInsets.all(8.0),
                  child: Text(
                    'alert',
                    style: TextStyle(color: Colors.white, fontSize: 30),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

答:
There is GoogleMapController with moveCamera / animateCamera methods. They accept CameraUpdate parameter with CameraPosition as new target.

class LocationLabPage extends StatefulWidget {
  @override
  _LocationLabPageState createState() => _LocationLabPageState();
}

class _LocationLabPageState extends State<LocationLabPage> {
  GoogleMapController _mapController;
  StreamSubscription _streamSubscription;

  @override
  void initState() {
    _streamSubscription = LocationService().locationStream.listen((event) {
      _mapController.moveCamera(CameraUpdate.newLatLng(LatLng(event.latitude, event.longitude)));
    });
    super.initState();
  }

  @override
  void dispose() {
    _streamSubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: GoogleMap(
        myLocationEnabled: true,
        myLocationButtonEnabled: true,
        initialCameraPosition: CameraPosition(target: LatLng(37.7, -122.2), zoom: 9.0),
        onMapCreated: (GoogleMapController controller) {
          _mapController = controller;
        },
      ),
    );
  }
}
```

Body:
I'm receiving a stream of Positions , I than update a _positionvariable that is used both in center: to set the map position, and in the Marker I use to show user position.
The problem is that the marker gets updated, but not the map position.
The expected behaviour is that the Marker, stays steady on the centre of the screen while the map moves underneath it, but it happen the opposite. Can you see where I set things wrong?
many thanks for your time and help.

class HomeScreen extends StatefulWidget {
  final String name;

  HomeScreen({
    Key key,
    @required this.name,
  }) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  Geolocator _geolocator;
  Position _position;

  FlutterMap _flutterMap;
  MapOptions _mapOptions;
  MapController _controller;
  void checkPermission() {
    _geolocator.checkGeolocationPermissionStatus().then((status) {
      print('status: $status');
    });
    _geolocator
        .checkGeolocationPermissionStatus(
            locationPermission: GeolocationPermission.locationAlways)
        .then((status) {
      print('always status: $status');
    });
    _geolocator.checkGeolocationPermissionStatus(
        locationPermission: GeolocationPermission.locationWhenInUse)
      ..then((status) {
        print('whenInUse status: $status');
      });
  }

  @override
  void initState() {
    super.initState();
    _geolocator = Geolocator();
    checkPermission();
    updateLocation();
  }

  void setMap() {
    _controller = MapController();
    _mapOptions = MapOptions(
      center: LatLng(_position.latitude, _position.longitude),
      minZoom: 16.0,
      maxZoom: 19.0,
    );
    _flutterMap = FlutterMap(
      options: _mapOptions,
      mapController: _controller,
      layers: [
//        PolygonLayer(polygonOpts, map, stream)
//                    PolygonLayerOptions(
//                      polygons:
//                    ),
        TileLayerOptions(
//        urlTemplate:'https://api.openrouteservice.org/mapsurfer/{z}/{x}/{y}.png?api_key=5b3ce3597851110001cf62484c4b65d85bc844eca3a2c6b9f300ddf4',
            urlTemplate: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
            subdomains: ['a', 'b', 'c'],
            keepBuffer: 20),
        new MarkerLayerOptions(
          markers: [
            Marker(
              point: LatLng(_position.latitude, _position.longitude),
              height: 200,
              width: 200,
              builder: (context) => IconButton(
                icon: Icon(Icons.location_on),
                color: Colors.red,
                iconSize: 60,
                onPressed: () {
                  print('icon tapped');
                },
              ),
            ),
          ],
        ),
      ],
    );
  }

  void startTracking() {
    LocationOptions locationOptions =
        LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 0);

    StreamSubscription positionStream = _geolocator
        .getPositionStream(locationOptions)
        .listen((Position position) {
      setState(() {
        _position = position;
        if (_position != null) {
//          _controller.move(LatLng(_position.latitude, _position.longitude), 16);
          setMap();
        }
      });
      print(
          _position.latitude.toString() + ',' + _position.longitude.toString());
    });
  }

  void updateLocation() async {
    try {
      Position newPosition = await _geolocator
          .getCurrentPosition(
            desiredAccuracy: LocationAccuracy.bestForNavigation,
          )
          .timeout(new Duration(seconds: 5));
      print(
          'updateLocation(): ${newPosition.latitude.toString() + ',' + newPosition.longitude.toString()}');

      setState(() {
        _position = newPosition;
        setMap();
      });
    } catch (error) {
      print('Error updating location: ${error.toString()}');
    }
  }

  void postRequest() async {
    print('postRequest called');

    // working properly
//    final request =
//    'http://router.project-osrm.org/trip/v1/driving/44.5018645003438,11.340018709036542;44.501342559233315,11.336182647230146?exclude=motorway';
//    final request = 'http://router.project-osrm.org/trip/v1/driving/44.5018645003438,11.340018709036542;44.501342559233315,11.33618264723014?source=first&destination=last&roundtrip=false&exclude=motorway&generate_hints=false&geometries=geojson&overview=full';
//    final request =
//        'http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&v=bicycle&fast=0&layer=mapnik&flat=44.5018645003438&flon=11.340018709036542&tlat=44.501342559233315&tlon=11.336182647230146&geometry=1&instructions=1&lang=it';

    // GOOOD
    final request =
        'http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&v=bicycle&fast=0&layer=mapnik&flat=44.5018645003438&flon=11.340018709036542&tlat=44.502138&tlon=11.340402&geometry=1&instructions=1&lang=it';

    // only driving
//    final request =
//        'http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&flat=52.215676&flon=5.963946&tlat=52.2573&tlon=6.1799&v=motorcar&fast=1&layer=mapnik';

//    final request =
//        'https://routing.openstreetmap.de/routed-foot/route/v1/driving/13.7807085453224,51.0536161;13.7835429,51.0515885?overview=false&geometries=polyline&steps=true';

    // Await the http get response, then decode the json-formatted response.
    var response = await get(request);
    if (response.statusCode == 200) {
      var jsonResponse = convert.jsonDecode(response.body);
      print('${jsonResponse.runtimeType} : $jsonResponse');
      List<dynamic> coordinates = jsonResponse['coordinates'];
      print('coordinates are : $coordinates');
      print('coordinates are: ${coordinates.length}');
      Map<String, dynamic> properties = jsonResponse['properties'];
//      print('properties are $properties');
      String distance = properties['distance'];
      print('Route is $distance Km long.');
      String instructions = properties['description'];
      print('instructions are $instructions');

      List<LatLng> suggestedRoute = [];
      for (int i = 0; i < (coordinates.length); i++) {
        dynamic coordinate = coordinates[i];
        LatLng position = LatLng(coordinate[1], coordinate[0]);
        suggestedRoute.add(position);
        print('position is $position');
        print(i);
      }
      print('suggestedRoute is $suggestedRoute');
    } else {
      print('Request failed with status: ${response.statusCode}.');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        title: Text(
          'Home',
          style: TextStyle(color: Colors.orangeAccent, fontSize: 40),
        ),
        actions: <Widget>[
          IconButton(
            icon: Icon(
              Icons.exit_to_app,
              color: Colors.orange,
              size: 35,
            ),
            onPressed: () {
              BlocProvider.of<AuthenticationBloc>(context).add(
                LoggedOut(),
              );
            },
          ),
        ],
      ),
      backgroundColor: Colors.white,
      body: SafeArea(
        minimum: EdgeInsets.symmetric(horizontal: 20),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                height: 670,
                width: 370,
                child: _flutterMap,

              ),
              SizedBox(
                height: 10,
              ),
              RaisedButton(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(5)),
                onPressed: () {
                  startTracking();
//                  setState(() {
////                    updateLocation();
//                  });
//
                },
                color: Colors.red,
                child: Padding(
                  padding: EdgeInsets.all(8.0),
                  child: Text(
                    'alert',
                    style: TextStyle(color: Colors.white, fontSize: 30),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


问:
How to check for the existence of values after splitting in object, and then assign them if only the last one does not exist
There is a question about sorting and adding an object, more precisely for example:

I have a string a1/b1/c1/d1 that
spl = "a1/b1/c1/d1".split ("/") and at the output I get an array of 4 elements.
I have an object - obj, I need to cycle through the spl array and each new turn I added values, right now I'll tell you

```<code>for(var i = 0; i < spl.length(); i++){
    // and here's the code I don't know how to write
}

/* there must be something like this
//if obj[spl[0]] is existing then do
i = 0: obj[spl[0]] = {};

//if obj[spl[0]][spl[1]] is existing then do
i = 1: obj[spl[0]][spl[1]] = {};

//if obj[spl[0]][spl[1]][spl[2]] is existing then do
i = 2: obj[spl[0]][spl[1]][spl[2]] = {};

//and if the last element of the massiv is not existing then do
i = 3: obj[spl[0]][spl[1]][spl[2]][spl[3]] = {};

/if the last element of the massiv is existing then do nothing
the end of the cycle*/
</code>```

that is, each scroll is added as long as i is less than the length of the array
it should work like this

```<code>obj {
    a1:{
        b1:{
            c1:{
                d1:{}
            }
        }
    }
};
</code>```

For example, if I have 2 elements in spl, the loop will add only 2 times as in the example, if 5, then 5

答:
let spl = "a1/b1/c1/d1".split ("/")
let obj = {}
let temp = obj
for(let i = 0; i < spl.length; i++) {
  temp[spl[i]] = {}
  temp = temp[spl[i]]
}

console.log(obj)```

For every iteration, temp is updated.
So, initially temp is obj but in the first iteration temp["a1"] is set to an empty object and then temp's value is updated to temp["a1"]. At this point again temp is an empty object. And for the next iteration temp["b1"] set to an empty object and the loop continues.

Since objects are passed by reference, obj is being updated throughout the process which results in the required output format.

Body:
There is a question about sorting and adding an object, more precisely for example:

I have a string a1/b1/c1/d1 that
spl = "a1/b1/c1/d1".split ("/") and at the output I get an array of 4 elements.
I have an object - obj, I need to cycle through the spl array and each new turn I added values, right now I'll tell you

for(var i = 0; i < spl.length(); i++){
    // and here's the code I don't know how to write
}

/* there must be something like this
//if obj[spl[0]] is existing then do
i = 0: obj[spl[0]] = {};

//if obj[spl[0]][spl[1]] is existing then do
i = 1: obj[spl[0]][spl[1]] = {};

//if obj[spl[0]][spl[1]][spl[2]] is existing then do
i = 2: obj[spl[0]][spl[1]][spl[2]] = {};

//and if the last element of the massiv is not existing then do
i = 3: obj[spl[0]][spl[1]][spl[2]][spl[3]] = {};

/if the last element of the massiv is existing then do nothing
the end of the cycle*/

that is, each scroll is added as long as i is less than the length of the array
it should work like this

obj {
    a1:{
        b1:{
            c1:{
                d1:{}
            }
        }
    }
};

For example, if I have 2 elements in spl, the loop will add only 2 times as in the example, if 5, then 5

Body:
let spl = "a1/b1/c1/d1".split ("/")
let obj = {}
let temp = obj
for(let i = 0; i < spl.length; i++) {
  temp[spl[i]] = {}
  temp = temp[spl[i]]
}

console.log(obj)

For every iteration, temp is updated.
So, initially temp is obj but in the first iteration temp["a1"] is set to an empty object and then temp's value is updated to temp["a1"]. At this point again temp is an empty object. And for the next iteration temp["b1"] set to an empty object and the loop continues.

Since objects are passed by reference, obj is being updated throughout the process which results in the required output format.


问:
C# WCF - ConfigurationErrorsException
I have created (using an online example) a custom binding and I'm trying to use it. Unfortunately I need to register the new binding.

Here is my app.config file.

```<code><?xml version="1.0"?>
<configuration>
   <configSections>
      <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <section name="WCFServiceHost.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false"/>
    </sectionGroup>
  </configSections>
  <appSettings>
    <add key="ThreadPoolSize" value="10"/>
    <add key="ChunkLength" value="60"/>
    <add key="ClientSettingsProvider.ServiceUri" value=""/>
  </appSettings>
  <system.web>
    <compilation debug="true">
      <assemblies>
        <add assembly="UdpBinding, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
      </assemblies>
    </compilation>
    <membership defaultProvider="ClientAuthenticationMembershipProvider">
      <providers>
        <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri=""/>
      </providers>
    </membership>
    <roleManager defaultProvider="ClientRoleProvider" enabled="true">
      <providers>
        <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400"/>
      </providers>
    </roleManager>
  </system.web>
  <system.serviceModel>
    <client>
      <metadata>
        <wsdlImporters>
          <extension type="UdpTransportBinding.UdpTransportElement, UdpTransportBinding, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
        </wsdlImporters>
        <policyImporters>
          <extension type="UdpTransportBinding.UdpBindingCollectionElement, UdpTransportBinding, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
        </policyImporters>
      </metadata>
    </client>
    <services>
      <service name="TransportService.TransportProtocol" behaviorConfiguration="MyBehavior">
        <endpoint name="NetTcpEndPoint" address="" binding="netTcpBinding" contract="TransportService.ITransportProtocol">
        </endpoint>
        <endpoint name="BasicHttpBinding" address="" binding="basicHttpBinding" contract="TransportService.ITransportProtocol">
        </endpoint>
         <endpoint name="NetUdpEndpoint" address="" binding="udpTransportBinding" bindingConfiguration="config" contract="TransportService.ITransportProtocol">
         </endpoint>
       </service>
    </services>
    <behaviors>
  <serviceBehaviors>
    <behavior name="MyBehavior">
      <serviceMetadata httpGetEnabled="True"/>
      <serviceDebug includeExceptionDetailInFaults="True"/>
    </behavior>
  </serviceBehaviors>
</behaviors>
<extensions>
  <bindingElementExtensions>
    <add name="udpTransport" type="UdpTransportBinding.UdpTransportElement, UdpTransportBinding, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  </bindingElementExtensions>
  <bindingExtensions>
    <add name="udpTransportBinding" type="UdpTransportBinding.UdpBindingCollectionElement, UdpTransportBinding, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  </bindingExtensions>
</extensions>
<bindings>
  <udpTransportBinding>
    <binding name="config"/>
    <udpTransport/>
  </udpTransportBinding>
</bindings>
</code>```

I've an app.config like this, but when I ran the old algorithm I got this error:

Configuration binding extension
  system.serviceModel/bindings/udpTransportBinding
  could not be found. Verify that this
  binding extension is properly
  registered in
  system.serviceModel/extensions/bindingExtensions
  and that it is spelled correctly.

Can someone help me to solve this problem?

答:
First, are you absolutely sure this is the proper type/assembly information for your class?

UdpTransportBinding.UdpBindingCollectionElement,
  UdpTransportBinding, Version=4.0.0.0,
  Culture=neutral,
  PublicKeyToken=31bf3856ad364e35

One way you can find out exactly where WCF is having a problem is to turn on handling of first chance exceptions and seeing what kind of WCF is getting internally before it reports its nice error. To do this you can disabled "Just My Code" in settings and check off handling of exceptions in the Debug->Exceptions menu.

Second, this config can't be right:

```<code><udpTransportBinding>
    <binding name="config"/>
    <!-- this can't be outside the binding -->
    <udpTransport/>
</udpTransportBinding>
</code>```

Are you sure that's exactly what you have? Also why are you creating a binding extension explicitly for udpTransportBinding, but then explicitly declaring that is uses udpTransport inside of it? The whole point of having a predefined binding is that it would automatically select that transport by default. You would really only want users to specify the udpTransport binding element if they defined a custom binding.

ContentLicense: CC BY-SA 3.0

Title: C# WCF - ConfigurationErrorsException

Body:
I have created (using an online example) a custom binding and I'm trying to use it. Unfortunately I need to register the new binding.

Here is my app.config file.

<?xml version="1.0"?>
<configuration>
   <configSections>
      <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">

    </sectionGroup>
  </configSections>
  <appSettings>
    <add key="ThreadPoolSize" value="10"/>
    <add key="ChunkLength" value="60"/>
    <add key="ClientSettingsProvider.ServiceUri" value=""/>
  </appSettings>
  <system.web>
    <compilation debug="true">
      <assemblies>
        <add assembly="UdpBinding, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
      </assemblies>
    </compilation>
    <membership defaultProvider="ClientAuthenticationMembershipProvider">
      <providers>
        <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri=""/>
      </providers>
    </membership>
    <roleManager defaultProvider="ClientRoleProvider" enabled="true">
      <providers>
        <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400"/>
      </providers>
    </roleManager>
  </system.web>
  <system.serviceModel>
    <client>
      <metadata>
        <wsdlImporters>
          <extension type="UdpTransportBinding.UdpTransportElement, UdpTransportBinding, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
        </wsdlImporters>
        <policyImporters>
          <extension type="UdpTransportBinding.UdpBindingCollectionElement, UdpTransportBinding, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
        </policyImporters>
      </metadata>
    </client>
    <services>
      <service name="TransportService.TransportProtocol" behaviorConfiguration="MyBehavior">
        <endpoint name="NetTcpEndPoint" address="" binding="netTcpBinding" contract="TransportService.ITransportProtocol">
        </endpoint>
        <endpoint name="BasicHttpBinding" address="" binding="basicHttpBinding" contract="TransportService.ITransportProtocol">
        </endpoint>
         <endpoint name="NetUdpEndpoint" address="" binding="udpTransportBinding" bindingConfiguration="config" contract="TransportService.ITransportProtocol">
         </endpoint>
       </service>
    </services>
    <behaviors>
  <serviceBehaviors>
    <behavior name="MyBehavior">
      <serviceMetadata httpGetEnabled="True"/>
      <serviceDebug includeExceptionDetailInFaults="True"/>
    </behavior>
  </serviceBehaviors>
</behaviors>
<extensions>
  <bindingElementExtensions>
    <add name="udpTransport" type="UdpTransportBinding.UdpTransportElement, UdpTransportBinding, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  </bindingElementExtensions>
  <bindingExtensions>
    <add name="udpTransportBinding" type="UdpTransportBinding.UdpBindingCollectionElement, UdpTransportBinding, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  </bindingExtensions>
</extensions>
<bindings>
  <udpTransportBinding>
    <binding name="config"/>
    <udpTransport/>
  </udpTransportBinding>
</bindings>

I've an app.config like this, but when I ran the old algorithm I got this error:

Configuration binding extension
  system.serviceModel/bindings/udpTransportBinding
  could not be found. Verify that this
  binding extension is properly
  registered in
  system.serviceModel/extensions/bindingExtensions
  and that it is spelled correctly.

Can someone help me to solve this problem?

Body:
First, are you absolutely sure this is the proper type/assembly information for your class?

UdpTransportBinding.UdpBindingCollectionElement,
  UdpTransportBinding, Version=4.0.0.0,
  Culture=neutral,
  PublicKeyToken=31bf3856ad364e35

One way you can find out exactly where WCF is having a problem is to turn on handling of first chance exceptions and seeing what kind of WCF is getting internally before it reports its nice error. To do this you can disabled "Just My Code" in settings and check off handling of exceptions in the Debug->Exceptions menu.

Second, this config can't be right:

<udpTransportBinding>
    <binding name="config"/>
    <!-- this can't be outside the binding -->
    <udpTransport/>
</udpTransportBinding>

Are you sure that's exactly what you have? Also why are you creating a binding extension explicitly for udpTransportBinding, but then explicitly declaring that is uses udpTransport inside of it? The whole point of having a predefined binding is that it would automatically select that transport by default. You would really only want users to specify the udpTransport binding element if they defined a custom binding.


问:
cannot copy command line argument to character pointer in C
I am taking command line argument which I am copying to my character pointer. but its giving me an error.

```<code>int main(int argc, char *argv[])
{
    char *cmdarg;
    if(argc>1)
            strcpy(cmdarg, argv[1]);
    else
            cmdarg = NULL;
    return 0;
}
</code>```

This gives me

```<code>Segmentation fault (core dumped)
</code>```

答:
You did not allocate memory where you are going to copy the argument pointed to by the expression argv[1].

Try the following

```<code>#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    char *cmdarg = NULL;

    if( argc > 1 )
    {
        cmdarg = malloc( strlen( argv[1] ) + 1 );
        if ( cmdarg != NULL ) strcpy( cmdarg, argv[1] );
    }

    // ...    Some other code

    free( cmdarg );

    return 0;
}
</code>```

If you want just to store the value of the pointer argv[1] then write

```<code>#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    char *cmdarg = NULL;

    if( argc > 1 )
    {
        cmdarg = argv[1];
    }

    // ...    Some other code

    return 0;
}
</code>```

Body:
I am taking command line argument which I am copying to my character pointer. but its giving me an error.

int main(int argc, char *argv[])
{
    char *cmdarg;
    if(argc>1)
            strcpy(cmdarg, argv[1]);
    else
            cmdarg = NULL;
    return 0;
}

This gives me

Segmentation fault (core dumped)

Body:
You did not allocate memory where you are going to copy the argument pointed to by the expression argv[1].

Try the following

#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    char *cmdarg = NULL;

    if( argc > 1 )
    {
        cmdarg = malloc( strlen( argv[1] ) + 1 );
        if ( cmdarg != NULL ) strcpy( cmdarg, argv[1] );
    }

    // ...    Some other code

    free( cmdarg );

    return 0;
}

If you want just to store the value of the pointer argv[1] then write

#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    char *cmdarg = NULL;

    if( argc > 1 )
    {
        cmdarg = argv[1];
    }

    // ...    Some other code

    return 0;
}


问:
android - how to get the image edge x/y position inside imageview
If i have an ImageView that fills the screen.

The ImageView background is set to green color.

I place a bitmap in the ImageView, keeping bitmap proportions.

A portrait photo in this layout will show green on both left and right side

(Phone orientation= portrait).

Now, How do i get the left side x/y position of the edge when the green ends and bitmap begins.

The background for this endeavor project is that i want to write text on the image and save   the image back to a new image with the text. The problem is..

Since I scale the image inSampleSize = 4; and the ImageView shrinking it even more, saving this new picture will give a small small approx 250x350 image.

What i want is to use the x/y positions and transfer the written text to the original inSampleSize = 4 image or to the sdcard 1500x3000 image

I know and read other questions about this that i have to "Do the math calculations" myself
I just need this small answer.

I forgot i can take a screenshot to clarify.

this is what it look like: (I get a new pen on pressing the button "pen" each pen hold its own unique text and position on the screen

Here is the imageview

```<code>    import java.util.HashMap;
    import java.util.UUID;
    import android.app.Activity;
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.graphics.Point;
    import android.graphics.Rect;
    import android.graphics.Typeface;
    import android.graphics.drawable.BitmapDrawable;
    import android.graphics.drawable.Drawable;
    import android.os.Environment;
    import android.util.AttributeSet;
    import android.view.Display;
    import android.view.MotionEvent;
    import android.widget.EditText;
    import android.widget.ImageView;

    public class DrawView2 extends ImageView {

        private HashMap<String, ColorBall2> HashBall ;
        private String balID = ""; // variable to know what ball is being dragged
        public final String PTPPSERVICE_DERECTORY = "/PTPPservice/";
        private Bitmap bitmap;
        private EditText ed;
        private Paint paint = new Paint();
        private Paint paint2 = new Paint();
        private Paint pTouch = new Paint();
        private EditText addtext;
        private Context ctx;
        private String imagePath;
        private boolean removeBall = false;
      int viewWidth = 0;
        int viewHeight = 0;
        double bitmapHight =0;
        double bitmapWidth =0;
        double ratio =0;

        double startX = 0;
        double endX= 0;
        double startY= 0;
        double endY = 0;

        public DrawView2(Context context, AttributeSet atts,String image1) {

            super(context, atts);
            this.ctx = context;
            this.imagePath = image1;
            setFocusable(true);

            paint.setStyle(Paint.Style.FILL_AND_STROKE);
            paint.setColor(Color.BLACK);
            paint.setTypeface(Typeface.DEFAULT_BOLD);

            paint2.setStyle(Paint.Style.FILL_AND_STROKE);
            paint2.setColor(Color.RED);

          addtext = (EditText) ((Activity) ctx).findViewById(R.id.edittextaddtext);

            String filePath = Environment.getExternalStorageDirectory().toString() + imagePath;
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 4;

            bitmap = BitmapFactory.decodeFile(filePath,options);
            // SAVE RATIO
            int x = bitmap.getWidth();
            int y = bitmap.getHeight();
            if(y>x)
                ratio = ((double)y)/x;
            if(x>y)
                ratio = ((double)x)/y;
            if(y==x)
                ratio = 1;
            Drawable bit = new BitmapDrawable(bitmap);
            setImageDrawable(bit);

        }
        public double getRatio() {
            return ratio;
        }
        public HashMap<String, ColorBall2> getHashBall() {
            return HashBall;
        }
        // RETURN THE ON SCREEN RESIZED BITMAP
        public double getOnScreenBitmapHight(){

            return bitmapHight;
        }
        public double getOnScreenBitmapWidth(){

            return  bitmapWidth;
        }
        // BITMAP SIZE
        public int getBitmapHight(){

            return bitmap.getHeight();
        }
        public int getBitmapWidth(){

            return  bitmap.getWidth();
        }
        // GET IMAGEVIEW HIGHT WIDTH
        public int getViewWidth() {
            return viewWidth;
        }
        public int getViewHeight() {
            return viewHeight;
        }
        // START END X Y
        public double getStartX() {
            return startX;
        }
        public double getEndX() {
            return endX;
        }
        public double getStartY() {
            return startY;
        }
        public double getEndY() {
            return endY;
        }
        // SET BALL TEXT
        public void addTextToBall(String text) {
            if(balID != "")
            HashBall.get(balID).setText(text);
        }
        // PATH
        public String getImagePath() {
            return imagePath;
        }
        // THE ORIGINAL INSAMPELSIZE=4 BITMAP
        public Bitmap getBitmap() {
            return bitmap;
        }
        // STOP DRAWAING THE BALL
        public void removeBall(boolean value) {
           removeBall = value;
        }
        // THE RECT THAT RETURN WRONG VALUE
        public Rect getRect(){

            Rect r = getDrawable().copyBounds();

            int drawLeft = r.left;
            int drawTop = r.top;
            int drawRight = r.right;
            int drawBottom = r.bottom;
            return r;
        }

        @Override
        protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld){
            super.onSizeChanged(xNew, yNew, xOld, yOld);
            viewWidth = xNew;
            viewHeight = yNew;
        }

        public void addBall(){

// HERE I TRY TO CALCULATE THE BOUNDS LEFT,RIGHT,TOP AND BOTTOM EDGE OF THE BITMAP
//NOT GOING THAT GOOD
            if(HashBall == null)
                HashBall = new HashMap<String,ColorBall2>();

            //X
            double drawAbleWidth = viewWidth/ratio;
            startX = (viewWidth-drawAbleWidth)/2;

            double drawAbleHight = viewHeight/ratio;
            startY = drawAbleHight/2;

            int ballY = (viewHeight/2);
            int ballX = (viewWidth/2);

            Point point1 = new Point();
            point1.x = (int) ballX;
            point1.y = (int) ballY;
            String uuId = UUID.randomUUID().toString();
            HashBall.put(uuId,(new ColorBall2(ctx,R.drawable.pen1, point1,uuId)));

        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);

            //canvas.drawCircle(10,10,10,null);
            if(!removeBall && HashBall != null){
                for (String key : HashBall.keySet()) {
                    //System.out.println("Key: " + key + ", Value: " + map.get(key));
                    if(addtext!=null)
                        //canvas.drawCircle(HashBall.get(key).getX(),      HashBall.get(key).getY(), 10, paint2);
                        canvas.drawBitmap(HashBall.get(key).getBitmap(), HashBall.get(key).getX()-10, HashBall.get(key).getY()-80, null);
                      canvas.drawText  (HashBall.get(key).getText() + "  X="+HashBall.get(key).getX() + "  Y="+HashBall.get(key).getY()
                                , HashBall.get(key).getX(), HashBall.get(key).getY(), paint);
                }

            }

        }

        // events when touching the screen
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            int eventaction = event.getAction();

            int X = (int)event.getX();
            int Y = (int)event.getY();

            switch (eventaction )
            {

            case MotionEvent.ACTION_DOWN: // touch down so check if the finger is on a ball
                balID = "";
                for (String key : HashBall.keySet()) {

                    // check if inside the bounds of the ball (circle)
                    // get the center for the ball
                    int centerX = HashBall.get(key).getX() + 15;
                    int centerY = HashBall.get(key).getY() + 15;

                    // calculate the radius from the touch to the center of the ball
                    double radCircle  = Math.sqrt( (((centerX-X)*(centerX-X)) + (centerY-Y)*(centerY-Y)));

                    // if the radius is smaller then 23 (radius of a ball is 22), then it must be on the ball
                    if (radCircle < 33){
                        balID = HashBall.get(key).getID();
                        addtext.setText(HashBall.get(key).getText());
                        break;
                    }
                }

                break;

            case MotionEvent.ACTION_MOVE:   // touch drag with the ball
                // move the balls the same as the finger
                if (balID != "") {
                    HashBall.get(balID).setX(X-25);
                    HashBall.get(balID).setY(Y-25);

                }
                break;

            case MotionEvent.ACTION_UP:
                // touch drop - just do things here after dropping

                break;
            }
            // redraw the canvas
            invalidate();
            return true;
        }
    }
</code>```

答:
You should be able to get the (x, y) coordinates of the drawable inside, if that's what you're looking for. Try this:

```<code>ImageView img = (ImageView)findViewById(R.id.img);
Rect r = img.getDrawable().getBounds();

int drawLeft = r.left;
int drawTop = r.top;
int drawRight = r.right;
int drawBottom = r.bottom;
</code>```

drawLeft is your X value.

drawTop is your Y value.

Body:
If i have an ImageView that fills the screen.

The ImageView background is set to green color.

I place a bitmap in the ImageView, keeping bitmap proportions.

A portrait photo in this layout will show green on both left and right side

(Phone orientation= portrait).

Now, How do i get the left side x/y position of the edge when the green ends and bitmap begins.

The background for this endeavor project is that i want to write text on the image and save   the image back to a new image with the text. The problem is..

Since I scale the image inSampleSize = 4; and the ImageView shrinking it even more, saving this new picture will give a small small approx 250x350 image.

What i want is to use the x/y positions and transfer the written text to the original inSampleSize = 4 image or to the sdcard 1500x3000 image

I know and read other questions about this that i have to "Do the math calculations" myself
I just need this small answer.

I forgot i can take a screenshot to clarify.

this is what it look like: (I get a new pen on pressing the button "pen" each pen hold its own unique text and position on the screen

Here is the imageview

    import java.util.HashMap;
    import java.util.UUID;
    import android.app.Activity;
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.graphics.Point;
    import android.graphics.Rect;
    import android.graphics.Typeface;
    import android.graphics.drawable.BitmapDrawable;
    import android.graphics.drawable.Drawable;
    import android.os.Environment;
    import android.util.AttributeSet;
    import android.view.Display;
    import android.view.MotionEvent;
    import android.widget.EditText;
    import android.widget.ImageView;

    public class DrawView2 extends ImageView {

        private HashMap<String, ColorBall2> HashBall ;
        private String balID = ""; // variable to know what ball is being dragged
        public final String PTPPSERVICE_DERECTORY = "/PTPPservice/";
        private Bitmap bitmap;
        private EditText ed;
        private Paint paint = new Paint();
        private Paint paint2 = new Paint();
        private Paint pTouch = new Paint();
        private EditText addtext;
        private Context ctx;
        private String imagePath;
        private boolean removeBall = false;
      int viewWidth = 0;
        int viewHeight = 0;
        double bitmapHight =0;
        double bitmapWidth =0;
        double ratio =0;

        double startX = 0;
        double endX= 0;
        double startY= 0;
        double endY = 0;

        public DrawView2(Context context, AttributeSet atts,String image1) {

            super(context, atts);
            this.ctx = context;
            this.imagePath = image1;
            setFocusable(true);

            paint.setStyle(Paint.Style.FILL_AND_STROKE);
            paint.setColor(Color.BLACK);
            paint.setTypeface(Typeface.DEFAULT_BOLD);

            paint2.setStyle(Paint.Style.FILL_AND_STROKE);
            paint2.setColor(Color.RED);

          addtext = (EditText) ((Activity) ctx).findViewById(R.id.edittextaddtext);

            String filePath = Environment.getExternalStorageDirectory().toString() + imagePath;
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 4;

            bitmap = BitmapFactory.decodeFile(filePath,options);
            // SAVE RATIO
            int x = bitmap.getWidth();
            int y = bitmap.getHeight();
            if(y>x)
                ratio = ((double)y)/x;
            if(x>y)
                ratio = ((double)x)/y;
            if(y==x)
                ratio = 1;
            Drawable bit = new BitmapDrawable(bitmap);
            setImageDrawable(bit);

        }
        public double getRatio() {
            return ratio;
        }
        public HashMap<String, ColorBall2> getHashBall() {
            return HashBall;
        }
        // RETURN THE ON SCREEN RESIZED BITMAP
        public double getOnScreenBitmapHight(){

            return bitmapHight;
        }
        public double getOnScreenBitmapWidth(){

            return  bitmapWidth;
        }
        // BITMAP SIZE
        public int getBitmapHight(){

            return bitmap.getHeight();
        }
        public int getBitmapWidth(){

            return  bitmap.getWidth();
        }
        // GET IMAGEVIEW HIGHT WIDTH
        public int getViewWidth() {
            return viewWidth;
        }
        public int getViewHeight() {
            return viewHeight;
        }
        // START END X Y
        public double getStartX() {
            return startX;
        }
        public double getEndX() {
            return endX;
        }
        public double getStartY() {
            return startY;
        }
        public double getEndY() {
            return endY;
        }
        // SET BALL TEXT
        public void addTextToBall(String text) {
            if(balID != "")
            HashBall.get(balID).setText(text);
        }
        // PATH
        public String getImagePath() {
            return imagePath;
        }
        // THE ORIGINAL INSAMPELSIZE=4 BITMAP
        public Bitmap getBitmap() {
            return bitmap;
        }
        // STOP DRAWAING THE BALL
        public void removeBall(boolean value) {
           removeBall = value;
        }
        // THE RECT THAT RETURN WRONG VALUE
        public Rect getRect(){

            Rect r = getDrawable().copyBounds();

            int drawLeft = r.left;
            int drawTop = r.top;
            int drawRight = r.right;
            int drawBottom = r.bottom;
            return r;
        }

        @Override
        protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld){
            super.onSizeChanged(xNew, yNew, xOld, yOld);
            viewWidth = xNew;
            viewHeight = yNew;
        }

        public void addBall(){

// HERE I TRY TO CALCULATE THE BOUNDS LEFT,RIGHT,TOP AND BOTTOM EDGE OF THE BITMAP
//NOT GOING THAT GOOD
            if(HashBall == null)
                HashBall = new HashMap<String,ColorBall2>();

            //X
            double drawAbleWidth = viewWidth/ratio;
            startX = (viewWidth-drawAbleWidth)/2;

            double drawAbleHight = viewHeight/ratio;
            startY = drawAbleHight/2;

            int ballY = (viewHeight/2);
            int ballX = (viewWidth/2);

            Point point1 = new Point();
            point1.x = (int) ballX;
            point1.y = (int) ballY;
            String uuId = UUID.randomUUID().toString();
            HashBall.put(uuId,(new ColorBall2(ctx,R.drawable.pen1, point1,uuId)));

        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);

            //canvas.drawCircle(10,10,10,null);
            if(!removeBall && HashBall != null){
                for (String key : HashBall.keySet()) {
                    //System.out.println("Key: " + key + ", Value: " + map.get(key));
                    if(addtext!=null)
                        //canvas.drawCircle(HashBall.get(key).getX(),      HashBall.get(key).getY(), 10, paint2);
                        canvas.drawBitmap(HashBall.get(key).getBitmap(), HashBall.get(key).getX()-10, HashBall.get(key).getY()-80, null);
                      canvas.drawText  (HashBall.get(key).getText() + "  X="+HashBall.get(key).getX() + "  Y="+HashBall.get(key).getY()
                                , HashBall.get(key).getX(), HashBall.get(key).getY(), paint);
                }

            }

        }

        // events when touching the screen
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            int eventaction = event.getAction();

            int X = (int)event.getX();
            int Y = (int)event.getY();

            switch (eventaction )
            {

            case MotionEvent.ACTION_DOWN: // touch down so check if the finger is on a ball
                balID = "";
                for (String key : HashBall.keySet()) {

                    // check if inside the bounds of the ball (circle)
                    // get the center for the ball
                    int centerX = HashBall.get(key).getX() + 15;
                    int centerY = HashBall.get(key).getY() + 15;

                    // calculate the radius from the touch to the center of the ball
                    double radCircle  = Math.sqrt( (((centerX-X)*(centerX-X)) + (centerY-Y)*(centerY-Y)));

                    // if the radius is smaller then 23 (radius of a ball is 22), then it must be on the ball
                    if (radCircle < 33){
                        balID = HashBall.get(key).getID();
                        addtext.setText(HashBall.get(key).getText());
                        break;
                    }
                }

                break;

            case MotionEvent.ACTION_MOVE:   // touch drag with the ball
                // move the balls the same as the finger
                if (balID != "") {
                    HashBall.get(balID).setX(X-25);
                    HashBall.get(balID).setY(Y-25);

                }
                break;

            case MotionEvent.ACTION_UP:
                // touch drop - just do things here after dropping

                break;
            }
            // redraw the canvas
            invalidate();
            return true;
        }
    }

Body:
You should be able to get the (x, y) coordinates of the drawable inside, if that's what you're looking for. Try this:

ImageView img = (ImageView)findViewById(R.id.img);
Rect r = img.getDrawable().getBounds();

int drawLeft = r.left;
int drawTop = r.top;
int drawRight = r.right;
int drawBottom = r.bottom;

drawLeft is your X value.

drawTop is your Y value.


问:
Replace New Lines in Node?
I'm trying to create a script to filter through a lot of lyric files. Here's the code I have:

Node.js

fs.readFile(filePath, 'utf-8', (err, data)=>{
    if (err) {
        console.log(err)
        return
    }
    data = data.replace(/\n[0-9]\n/, "Verse " + /\n[0-9]\n/)
    console.log(data)
    fs.writeFile(path.join(newDir, file), data, ()=>{
        console.log(file)
    })
})
```
<h2>Original Text File</h2>
```Title

1
Some lyrics

2
Some lyrics
```
<h2>What the new text file SHOULD look like</h2>
```Title

Verse 1
Some lyrics

Verse 2
Some lyrics
```

It can't seem to find the \n (newline), a verse number, \n (newline). Also, obvious problem I'm not sure how to fix, the third parameter in .replace() probably isn't the same as the first parameter. Can anyone guide me on how could I filter through these?

答:
You can make sure replace method 2nd argument replacement function.  Following is example usage.

let data = "1";
data = data.replace(/([0-9])/, match => "Verse " + match);

console.log(data)```

Title: Replace New Lines in Node?

Body:
I'm trying to create a script to filter through a lot of lyric files. Here's the code I have:

Node.js

fs.readFile(filePath, 'utf-8', (err, data)=>{
    if (err) {
        console.log(err)
        return
    }
    data = data.replace(/\n[0-9]\n/, "Verse " + /\n[0-9]\n/)
    console.log(data)
    fs.writeFile(path.join(newDir, file), data, ()=>{
        console.log(file)
    })
})

Original Text File

Title

1
Some lyrics

2
Some lyrics

What the new text file SHOULD look like

Title

Verse 1
Some lyrics

Verse 2
Some lyrics

It can't seem to find the \n (newline), a verse number, \n (newline). Also, obvious problem I'm not sure how to fix, the third parameter in .replace() probably isn't the same as the first parameter. Can anyone guide me on how could I filter through these?


问:
How to make accordion menu using react & styled components
I'm trying to create an accordion menu like the one from Bootstrap https://getbootstrap.com/docs/4.3/components/collapse/

I have managed to get it to open and close fine, but I'm missing the smooth transition :/

It's like the transition is just not being applied.

import React, { useState } from 'react';
import styled from 'styled-components';
import { Button } from './common/button';

const AccordionWrapper = styled.div`
    display: flex;
    flex-direction: column;
    justify-content: center;
    background-color: var(--Secondary-color-dark);
    border-radius: 10px;
    height: auto;
    padding: 2%;
    text-align: center;
    transition: all 0.6s ease-in-out;
`;

const InternalWrapper = styled.div`
    width: 100%;
    max-height: ${(props) => (props.open ? '100%' : '0')};
    transition: all 1s ease-in-out;
    overflow: hidden;
`;

const Accordion = ({ title, subTitle, btnText }) => {
    const [ open, setOpen ] = useState(false);
    const handleClick = () => {
        setOpen(!open);
    };
    return (
        <AccordionWrapper>

{title}

{subTitle}

            <InternalWrapper open={open}>

Hello

            </InternalWrapper>
            <Button padding="5px" onClick={handleClick}>
                {btnText}
            </Button>
        </AccordionWrapper>
    );
};

Accordion.defaultProps = {
    title    : 'title',
    subTitle : 'subtitle',
    btnText  : 'Read more >>'
};

export default Accordion;

```

Here is a codepen reproduction.
https://codepen.io/hichihachi/pen/MWwKZEO?editors=0010

Any help would be appreciated, thanks.

答:
Max-height transition doesn't work when you set it in percentage and in some other units. To make the transition work you can define something like

max-height: ${(props) => (props.open ? '100px' : '0')};

https://codepen.io/alonabas/pen/PoqNYLR?editors=1111

But if your content is more than 100px in height, when you open the Accordion the content will be cut. In this case you can use jQuery to calculate the exact size of your content or use some maximal possible value of max-height.

Both options are described here:
https://stackoverflow.com/a/8331169/2916925

Body:
I'm trying to create an accordion menu like the one from Bootstrap https://getbootstrap.com/docs/4.3/components/collapse/

I have managed to get it to open and close fine, but I'm missing the smooth transition :/

It's like the transition is just not being applied.

import React, { useState } from 'react';
import styled from 'styled-components';
import { Button } from './common/button';

const AccordionWrapper = styled.div`
    display: flex;
    flex-direction: column;
    justify-content: center;
    background-color: var(--Secondary-color-dark);
    border-radius: 10px;
    height: auto;
    padding: 2%;
    text-align: center;
    transition: all 0.6s ease-in-out;
`;

const InternalWrapper = styled.div`
    width: 100%;
    max-height: ${(props) => (props.open ? '100%' : '0')};
    transition: all 1s ease-in-out;
    overflow: hidden;
`;

const Accordion = ({ title, subTitle, btnText }) => {
    const [ open, setOpen ] = useState(false);
    const handleClick = () => {
        setOpen(!open);
    };
    return (
        <AccordionWrapper>

{title}

{subTitle}

            <InternalWrapper open={open}>

Hello

            </InternalWrapper>
            <Button padding="5px" onClick={handleClick}>
                {btnText}
            </Button>
        </AccordionWrapper>
    );
};

Accordion.defaultProps = {
    title    : 'title',
    subTitle : 'subtitle',
    btnText  : 'Read more >>'
};

export default Accordion;

Here is a codepen reproduction.
https://codepen.io/hichihachi/pen/MWwKZEO?editors=0010

Any help would be appreciated, thanks.


问:
Unity ARFoundation - Augmented Objects does not register collisions
I'm currently stuck with my remote control app in terms of collisions.
I'm using Arcore XR plugin and AR Foundation.

I've placed a building and added mesh collider on it and my car.
My car has a rigidbody component so when I play it in the editor the car stops when hitting the building as intended.
However, when building the app to my android device it just drives through it as if there were no colliders/as if my phone has no collisipn dtection.

I've tried adding rigidbody on my building and ticking on and off convex.

Right now I'm out of ideas.

What am I missing?

答:
Resolved:

If you're experiencing the same problems, if you've imported any FBX file, make sure to have Read/Write enabled.

Go to your Project Folder in Unity, find your .fbx models and click on it.
Then in the inspector, click Model then make sure that Read/Write is enabled.

Mesh Colliders should now work.


问:
import module in Class, but NameError when using module in class method
In my python script, I'm trying to import module in class and use the imported module in the class method.

```<code>class test:
    import urllib.parse

    def __init__(self, url):
        urlComponents = urllib.parse.urlsplit(url)
</code>```

Howerver, when I try to use the test class, such as

```<code>test("http://test.com")
</code>```

I get the error:

NameError: name 'urllib' is not defined

Why import statement in class body do not take effect?

I use python 3.8.1 in windows 10.

答:
The import statement performs a name binding, but names inside the class scope are not directly visible inside methods. This is the same as for any other class name.

```<code>>>> class Test:
...     a = 2   # bind name on class
...     def get_a(self):
...         return a  # unqualified reference to class attribute
...
>>> Test().get_a()
NameError: name 'a' is not defined
</code>```

You can refer to any class attribute either through the class or the instance instead. This works for imported names as well.

```<code>class test:
    import urllib.parse

    def __init__(self, url):
        #               V refer to attribute in class
        urlComponents = self.urllib.parse.urlsplit(url)
</code>```

Note that there isn't any advantage to binding a module inside a class, with the exception of hiding the name from the global scope. Usually, you should import at the global scope.

```<code>import urllib.parse

class test:

    def __init__(self, url):
        #               V refer to global module
        urlComponents = urllib.parse.urlsplit(url)
</code>```

Body:
In my python script, I'm trying to import module in class and use the imported module in the class method.

class test:
    import urllib.parse

    def __init__(self, url):
        urlComponents = urllib.parse.urlsplit(url)

Howerver, when I try to use the test class, such as

test("http://test.com")

I get the error:

NameError: name 'urllib' is not defined

Why import statement in class body do not take effect?

I use python 3.8.1 in windows 10.

Body:
The import statement performs a name binding, but names inside the class scope are not directly visible inside methods. This is the same as for any other class name.

>>> class Test:
...     a = 2   # bind name on class
...     def get_a(self):
...         return a  # unqualified reference to class attribute
...
>>> Test().get_a()
NameError: name 'a' is not defined

You can refer to any class attribute either through the class or the instance instead. This works for imported names as well.

class test:
    import urllib.parse

    def __init__(self, url):
        #               V refer to attribute in class
        urlComponents = self.urllib.parse.urlsplit(url)

Note that there isn't any advantage to binding a module inside a class, with the exception of hiding the name from the global scope. Usually, you should import at the global scope.

import urllib.parse

class test:

    def __init__(self, url):
        #               V refer to global module
        urlComponents = urllib.parse.urlsplit(url)


答:
cmdarg is a Uninitialized pointer by declaration. We have to allocate dynamic memory for cmdarg to point to. Below is a sample code

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    char *cmdarg;

    cmdarg = malloc( 5 * sizeof(char));
    if(argc>1)
    {
            strcpy(cmdarg, argv[1]);
            printf("%s\n", cmdarg);
    }
    else
            cmdarg = NULL;
    free(cmdarg);
    return 0;
}
</code>```

Output while running with argument ./a.out yes is yes.

Note: Size allocated should not be lesser while using strcpy(). Make sure to use strncpy()

Title: cannot copy command line argument to character pointer in C

Body:
cmdarg is a Uninitialized pointer by declaration. We have to allocate dynamic memory for cmdarg to point to. Below is a sample code

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    char *cmdarg;

    cmdarg = malloc( 5 * sizeof(char));
    if(argc>1)
    {
            strcpy(cmdarg, argv[1]);
            printf("%s\n", cmdarg);
    }
    else
            cmdarg = NULL;
    free(cmdarg);
    return 0;
}

Output while running with argument ./a.out yes is yes.

Note: Size allocated should not be lesser while using strcpy(). Make sure to use strncpy()


问:
how to find duplicate array value on document mongodb
I got question might be many of you can help me.

so I have data on mongodb.

first data

```<code> {
    "name" : 'david'
    contacts : [
    {
    "name" : 'john',
    "phone" : '123456'
    },
    {
    "name" : 'george',
    "phone" : '0987654'
    }
    ]
    }
</code>```

second data

```<code>{
    "name" : 'anita',
    "contacts" : [
    {
    "name" : 'harry',
    "phone" : '123456'
    },
    {
    "name" : 'kurita',
    "phone" : '323434'
    }
    ]
    }
</code>```

the problem is,
can I query to find data that have duplicate contacts.phone.
so the result whill show like this.

```<code>{
"name" : 'david',
"contacts" : [
{
"name" : 'john',
"phone" : '123456'
}
]
}

{
"name" : 'anita',
"contacts" : [
{
"name" : 'harry',
"phone" : '123456'
}
]
}
</code>```

data john and anita will show because they have similar data on contacts.phone

sorry for my english btw,
I hope you all understand what I mean.

thank you so much

答:
There are a few steps involved to get the results you need.
We are going to write an aggregate pipeline to get the work done.

First you need to unwind your array values with the following:

```<code>{
    $unwind: "$contacts"
}
</code>```

Doc: https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/

This would result into:

```<code>[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "contacts": {
      "name": "john",
      "phone": "123456"
    },
    "name": "david"
  },
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "contacts": {
      "name": "george",
      "phone": "0987654"
    },
    "name": "david"
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "contacts": {
      "name": "harry",
      "phone": "123456"
    },
    "name": "anita"
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "contacts": {
      "name": "kurita",
      "phone": "323434"
    },
    "name": "anita"
  }
]
</code>```

This would be much easier for us to group by field.

Doc: https://docs.mongodb.com/manual/reference/operator/aggregation/group/

```<code>{
    $group: {
        _id: {
            phone: "$contacts.phone"
        },
        name: {
            $addToSet: "$name"
        },
        contacts: {
            $addToSet: "$contacts.name"
        },
        count: {
            $sum: 1
        }
    }
}
</code>```

That gives the following output:

```<code>[
    {
        "_id": {
            "phone": "323434"
        },
        "contacts": [
          "kurita"
        ],
        "count": 1,
        "name": [
            "anita"
        ]
    },
    {
        "_id": {
          "phone": "123456"
        },
        "contacts": [
            "john",
            "harry"
        ],
        "count": 2,
        "name": [
            "david",
            "anita"
        ]
    },
    {
        "_id": {
            "phone": "0987654"
        },
        "contacts": [
            "george"
        ],
        "count": 1,
        "name": [
            "david"
        ]
    }
]
</code>```

Based on the output we need to match the count greater then 1 like:

Doc: https://docs.mongodb.com/manual/reference/operator/aggregation/match/

```<code>{
    $match: {
        count: {
            "$gt": 1
        }
    }
}
</code>```

Result is:

```<code>[
    {
        "_id": {
            "phone": "123456"
        },
        "contacts": [
            "john",
            "harry"
        ],
        "count": 2,
        "name": [
            "david",
            "anita"
        ]
    }
]
</code>```

The query would look like:

Doc: https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/

```<code>db.collection.aggregate([
    {
        $unwind: "$contacts"
    },
    {
        $group: {
            _id: {
                phone: "$contacts.phone"
            },
            name: {
                $addToSet: "$name"
            },
            contacts: {
                $addToSet: "$contacts.name"
            },
            count: {
                $sum: 1
            }
        }
    },
    {
        $match: {
            count: {
                "$gt": 1
            }
        }
    }
])
</code>```

MongoPlayground: https://mongoplayground.net/p/qSvhcYyAcQO

I hope this gives you a small idea what is possible with the aggregation pipeline.

Update / fix
According to your requirements you wish to have 2 objects foreach name that has duplicate contacts then you could use unwind again after the match.

```<code>[
    {
        "_id": {
            "phone": "123456"
        },
        "contacts": [
            "harry",
            "john"
        ],
        "count": 2,
        "name": "david"
    },
    {
        "_id": {
            "phone": "123456"
        },
        "contacts": [
            "harry",
            "john"
        ],
        "count": 2,
        "name": "anita"
    }
]
</code>```

Cheers, Kevin

Body:
I got question might be many of you can help me.

so I have data on mongodb.

first data

 {
    "name" : 'david'
    contacts : [
    {
    "name" : 'john',
    "phone" : '123456'
    },
    {
    "name" : 'george',
    "phone" : '0987654'
    }
    ]
    }

second data

{
    "name" : 'anita',
    "contacts" : [
    {
    "name" : 'harry',
    "phone" : '123456'
    },
    {
    "name" : 'kurita',
    "phone" : '323434'
    }
    ]
    }

the problem is,
can I query to find data that have duplicate contacts.phone.
so the result whill show like this.

{
"name" : 'david',
"contacts" : [
{
"name" : 'john',
"phone" : '123456'
}
]
}

{
"name" : 'anita',
"contacts" : [
{
"name" : 'harry',
"phone" : '123456'
}
]
}

data john and anita will show because they have similar data on contacts.phone

sorry for my english btw,
I hope you all understand what I mean.

thank you so much

Body:
There are a few steps involved to get the results you need.
We are going to write an aggregate pipeline to get the work done.

First you need to unwind your array values with the following:

{
    $unwind: "$contacts"
}

Doc: https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/

This would result into:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "contacts": {
      "name": "john",
      "phone": "123456"
    },
    "name": "david"
  },
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "contacts": {
      "name": "george",
      "phone": "0987654"
    },
    "name": "david"
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "contacts": {
      "name": "harry",
      "phone": "123456"
    },
    "name": "anita"
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "contacts": {
      "name": "kurita",
      "phone": "323434"
    },
    "name": "anita"
  }
]

This would be much easier for us to group by field.

Doc: https://docs.mongodb.com/manual/reference/operator/aggregation/group/

{
    $group: {
        _id: {
            phone: "$contacts.phone"
        },
        name: {
            $addToSet: "$name"
        },
        contacts: {
            $addToSet: "$contacts.name"
        },
        count: {
            $sum: 1
        }
    }
}

That gives the following output:

[
    {
        "_id": {
            "phone": "323434"
        },
        "contacts": [
          "kurita"
        ],
        "count": 1,
        "name": [
            "anita"
        ]
    },
    {
        "_id": {
          "phone": "123456"
        },
        "contacts": [
            "john",
            "harry"
        ],
        "count": 2,
        "name": [
            "david",
            "anita"
        ]
    },
    {
        "_id": {
            "phone": "0987654"
        },
        "contacts": [
            "george"
        ],
        "count": 1,
        "name": [
            "david"
        ]
    }
]

Based on the output we need to match the count greater then 1 like:

Doc: https://docs.mongodb.com/manual/reference/operator/aggregation/match/

{
    $match: {
        count: {
            "$gt": 1
        }
    }
}

Result is:

[
    {
        "_id": {
            "phone": "123456"
        },
        "contacts": [
            "john",
            "harry"
        ],
        "count": 2,
        "name": [
            "david",
            "anita"
        ]
    }
]

The query would look like:

Doc: https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/

db.collection.aggregate([
    {
        $unwind: "$contacts"
    },
    {
        $group: {
            _id: {
                phone: "$contacts.phone"
            },
            name: {
                $addToSet: "$name"
            },
            contacts: {
                $addToSet: "$contacts.name"
            },
            count: {
                $sum: 1
            }
        }
    },
    {
        $match: {
            count: {
                "$gt": 1
            }
        }
    }
])

MongoPlayground: https://mongoplayground.net/p/qSvhcYyAcQO

I hope this gives you a small idea what is possible with the aggregation pipeline.

Update / fix
According to your requirements you wish to have 2 objects foreach name that has duplicate contacts then you could use unwind again after the match.

[
    {
        "_id": {
            "phone": "123456"
        },
        "contacts": [
            "harry",
            "john"
        ],
        "count": 2,
        "name": "david"
    },
    {
        "_id": {
            "phone": "123456"
        },
        "contacts": [
            "harry",
            "john"
        ],
        "count": 2,
        "name": "anita"
    }
]

Cheers, Kevin


问:
Resolving a Proxy Authentication Required Issue
I've written a Delphi application which requires communication with a remote web server. I pass INTERNET_OPEN_TYPE_PRECONFIG flag into the InternetOpen function to initialise my app's use of the WinINet functions and by doing so my app to retrieve the user's Internet configuration from the registry.

```<code>  NetHandle := InternetOpen('WebTool', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
  if Assigned(NetHandle) then
  begin
    try
      hConnect := InternetConnect(NetHandle, PChar(ServerName), ServerPort,
                      nil, nil, INTERNET_SERVICE_HTTP, 0, 1);
      if Assigned(hConnect) then
      begin
        try
          // Open the request
          hRequest := HttpOpenRequest(hConnect, PChar('POST'),
                          PChar(ServerScript), nil, nil, nil,
                          HTTPOpenRequestFlags, 0);
          if Assigned(hRequest) then
          begin
</code>```

Perhaps due to my ignorance, I believed this enabled communication with the remote web server using the user's particular Internet settings whether direct connection or via a proxy. It certainly works via my company's proxy server.

However, I've now encountered one customer for whom the above does not allow him access. He sees a "Proxy Authentication Required" (HTTP status code 407) instead.

Is this something that my app should be handling (e.g. provide a form to enter proxy authentication details and pass them with my HTTP requests)? Is there a way of picking up this information automatically?

Or is this simply down to a configuration issue that the customer's IT department can easily resolve?

Any pointers would be much appreciated.

答: You may need to handle authentication, depending on what auth methods the proxy supports (it will tell you in the 407 response). See http://msdn.microsoft.com/en-us/library/aa384220(VS.85).aspx</p>

Body:
I've written a Delphi application which requires communication with a remote web server. I pass INTERNET_OPEN_TYPE_PRECONFIG flag into the InternetOpen function to initialise my app's use of the WinINet functions and by doing so my app to retrieve the user's Internet configuration from the registry.

  NetHandle := InternetOpen('WebTool', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
  if Assigned(NetHandle) then
  begin
    try
      hConnect := InternetConnect(NetHandle, PChar(ServerName), ServerPort,
                      nil, nil, INTERNET_SERVICE_HTTP, 0, 1);
      if Assigned(hConnect) then
      begin
        try
          // Open the request
          hRequest := HttpOpenRequest(hConnect, PChar('POST'),
                          PChar(ServerScript), nil, nil, nil,
                          HTTPOpenRequestFlags, 0);
          if Assigned(hRequest) then
          begin

Perhaps due to my ignorance, I believed this enabled communication with the remote web server using the user's particular Internet settings whether direct connection or via a proxy. It certainly works via my company's proxy server.

However, I've now encountered one customer for whom the above does not allow him access. He sees a "Proxy Authentication Required" (HTTP status code 407) instead.

Is this something that my app should be handling (e.g. provide a form to enter proxy authentication details and pass them with my HTTP requests)? Is there a way of picking up this information automatically?

Or is this simply down to a configuration issue that the customer's IT department can easily resolve?

Any pointers would be much appreciated.


问:
Departments not showing in Laravel
I have two tables ,departments and users.One department has many users.One user belongs to one department.Im trying to write a foreach loop to display the names of the departments with its users but i get this error.

Facade\Ignition\Exceptions\ViewException
  Undefined variable: departments (View: C:\xampp\htdocs\Laravel\blog2\resources\views\admin\dashboard.blade.php)

create_users_table

```<code>
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            //$table->text('avatar');
            $table->string('name');
            $table->string('lastname');
            $table->string('phone');
            $table->string('jobtitle');
            $table->integer('department_id');
            $table->timestamps();
            $table->string('usertype')->nullable();
            $table->string('email');
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();

        });
    }
</code>```

create_departments_table

```<code>public function up()
    {
        Schema::create('departments', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        });
    }
</code>```

Department.php

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Department extends Model
{

    protected $table = 'departments';
    protected $fillable = [
        'name',
    ];
    protected $primaryKey = 'id';

public function department()
{
    return $this->belongsTo(Department::class);
}

}

</code>```

User.php

```<code><?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{

    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
     public function department()
    {
        return $this->belongsTo(Department::class);
    }

}
</code>```

dashboard.blade.php

```<code> @extends ('layouts.master')

@section('title')
DASHBOARD | Admin
@endsection

@section('content')

<div class="row">
  <div class="col-md-12">
    <div class="card">
      @if (session('status'))
      <div class="alert alert-success" role="alert">
        {{ session('status') }}
      </div>
      @endif
      <div class="card-header">
        <h4 class="card-title"> DASHBOARD </h4>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table">
            <thead class=" text-primary">
              <th>ID</th>
              <th>Name</th>
              <th>Last Name</th>
              <th>Department</th>
            </thead>
            <tbody>
            @foreach($departments as $department)
              <td> {{$department->name}}</td>
              @endforeach
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  @endsection

  @section('scripts')

  @endsection
</code>```

DashboardController.php

```<code>class DashboardController extends Controller
{  public function index()
    {
      $users= User::all();
      foreach($users as $user)
      {
        echo $user->department->name;
        echo $user->name;
      }
   }
}
</code>```

web.php

```<code>
Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::group(['middleware' => ['auth','admin']], function  () {

    Route::get('/dashboard', function () {
        $users= User::all();
        $departments = Department::with('users')->get();
        dd($departments);
        return view('admin.dashboard',compact('departments','users'));
    });
    //Route::get('/dashboard', "Admin\DashboardController@index");
   // Route::get('/dashboard{id}', "Admin\DashboardController@index");
    Route::get('/role-register','Admin\DashboardController@registered');
    Route::get('/role-edit/{id}', 'Admin\DashboardController@registeredit');
    Route::put('/role-register-update/{id}', 'Admin\DashboardController@registerupdate');
    Route::delete('/role-delete/{id}', 'Admin\DashboardController@registerdelete');
    Route::post('/save-user', 'Admin\DashboardController@store');

    Route::get('/department', 'Admin\DepartmentController@index');
    Route::post('/save-department', 'Admin\DepartmentController@store');
    Route::get('/department-edit/{id}', 'Admin\DepartmentController@edit');
    Route::put('/department-update/{id}', 'Admin\DepartmentController@update');
    Route::delete('/department-delete/{id}', 'Admin\DepartmentController@delete');

});
Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
</code>```

I have tried this too but still the same.

```<code><td> {{$department->name}}</td>

</code>```

```<code>@foreach($departments->name as $department)
<td> {{$department}}</td>
@endforeach
</code>```

答:
can you try this? see if it changes the error?

use App\User;
use App\Department;

Route::get('/dashboard', function () {
    $users= User::all();
    $departments = Department::with('users')->get();
    return view('admin.dashboard',compact('departments','users'));
});
```

<p>comment out this.</p>

<pre class="lang-php prettyprint-override"><code>// Route::get('/dashboard', 'Admin\DashboardController@index' );
</code>```

Also in you balde file you need to chenge to this, this will give you all the department.

              @foreach($departments as $department)
               {{$department->name}}
              @endforeach
```

<p><strong>Update</strong></p>

<pre class="lang-php prettyprint-override"><code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Department extends Model
{

    protected $table = 'departments';
    protected $fillable = [
        'name',
    ];
    protected $primaryKey = 'id';

public function users()
{
    return $this->belongsTo(User::class);
}

}
</code>```

Title: Departments not showing in Laravel

Body:
I have two tables ,departments and users.One department has many users.One user belongs to one department.Im trying to write a foreach loop to display the names of the departments with its users but i get this error.

Facade\Ignition\Exceptions\ViewException
  Undefined variable: departments (View: C:\xampp\htdocs\Laravel\blog2\resources\views\admin\dashboard.blade.php)

create_users_table

    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            //$table->text('avatar');
            $table->string('name');
            $table->string('lastname');
            $table->string('phone');
            $table->string('jobtitle');
            $table->integer('department_id');
            $table->timestamps();
            $table->string('usertype')->nullable();
            $table->string('email');
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();

        });
    }

create_departments_table

public function up()
    {
        Schema::create('departments', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        });
    }

Department.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Department extends Model
{

    protected $table = 'departments';
    protected $fillable = [
        'name',
    ];
    protected $primaryKey = 'id';

public function department()
{
    return $this->belongsTo(Department::class);
}

}

User.php

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{

    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
     public function department()
    {
        return $this->belongsTo(Department::class);
    }

}

dashboard.blade.php

 @extends ('layouts.master')

@section('title')
DASHBOARD | Admin
@endsection

@section('content')

      @if (session('status'))

        {{ session('status') }}

      @endif

 DASHBOARD

              ID
              Name
              Last Name
              Department

            @foreach($departments as $department)
               {{$department->name}}
              @endforeach

  @endsection

  @section('scripts')

  @endsection

DashboardController.php

class DashboardController extends Controller
{  public function index()
    {
      $users= User::all();
      foreach($users as $user)
      {
        echo $user->department->name;
        echo $user->name;
      }
   }
}

web.php

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::group(['middleware' => ['auth','admin']], function  () {

    Route::get('/dashboard', function () {
        $users= User::all();
        $departments = Department::with('users')->get();
        dd($departments);
        return view('admin.dashboard',compact('departments','users'));
    });
    //Route::get('/dashboard', "Admin\DashboardController@index");
   // Route::get('/dashboard{id}', "Admin\DashboardController@index");
    Route::get('/role-register','Admin\DashboardController@registered');
    Route::get('/role-edit/{id}', 'Admin\DashboardController@registeredit');
    Route::put('/role-register-update/{id}', 'Admin\DashboardController@registerupdate');
    Route::delete('/role-delete/{id}', 'Admin\DashboardController@registerdelete');
    Route::post('/save-user', 'Admin\DashboardController@store');

    Route::get('/department', 'Admin\DepartmentController@index');
    Route::post('/save-department', 'Admin\DepartmentController@store');
    Route::get('/department-edit/{id}', 'Admin\DepartmentController@edit');
    Route::put('/department-update/{id}', 'Admin\DepartmentController@update');
    Route::delete('/department-delete/{id}', 'Admin\DepartmentController@delete');

});
Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

I have tried this too but still the same.

 {{$department->name}}

@foreach($departments->name as $department)
 {{$department}}
@endforeach

Body:
can you try this? see if it changes the error?

use App\User;
use App\Department;

Route::get('/dashboard', function () {
    $users= User::all();
    $departments = Department::with('users')->get();
    return view('admin.dashboard',compact('departments','users'));
});

comment out this.

// Route::get('/dashboard', 'Admin\DashboardController@index' );

Also in you balde file you need to chenge to this, this will give you all the department.

              @foreach($departments as $department)
              <td> {{$department->name}}</td>
              @endforeach

Update

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Department extends Model
{

    protected $table = 'departments';
    protected $fillable = [
        'name',
    ];
    protected $primaryKey = 'id';

public function users()
{
    return $this->belongsTo(User::class);
}

}