text:
Q: Android, How to remove all markers from Google Map V2? I have map view in my fragment. I need to refresh map and add different markers based on condition. So, I should remove last markers from map before add new markers.
Actually, some weeks ago app was working fine and suddenly it happened. My code is like this:
private void displayData(final List<Venue> venueList) {

        // Removes all markers, overlays, and polylines from the map.
        googleMap.clear();
.
.
.
}

Last time it was working fine (before new Google Map API announce by Android team in I/O 2013). However, after that I adapted my code to use this new API. Now, I don't know why this  method googleMap.clear(); doesn't work!
Any suggestion would be appreciated. Thanks
=======
Update
=======
Complete code:
private void displayData(final List<Venue> venueList) {

        // Removes all markers, overlays, and polylines from the map.
        googleMap.clear();

        // Zoom in, animating the camera.
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(ZOOM_LEVEL), 2000, null);

        // Add marker of user's position
        MarkerOptions userIndicator = new MarkerOptions()
                .position(new LatLng(lat, lng))
                .title("You are here")
                .snippet("lat:" + lat + ", lng:" + lng);
        googleMap.addMarker(userIndicator);

        // Add marker of venue if there is any
        if(venueList != null) {
            for(int i=0; i < venueList.size(); i++) {
                Venue venue = venueList.get(i);
                String guys = venue.getMaleCount();
                String girls= venue.getFemaleCount();
                String checkinStatus = venue.getCan_checkin();
                if(checkinStatus.equalsIgnoreCase("true"))
                    checkinStatus = "Checked In - ";
                else
                    checkinStatus = "";

                MarkerOptions markerOptions = new MarkerOptions()
                        .position(new LatLng(Double.parseDouble(venue.getLatitude()), Double.parseDouble(venue.getLongitude())))
                        .title(venue.getName())
                        .snippet(checkinStatus + "Guys:" + guys + " and Girls:" + girls)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_orange_pin));

                googleMap.addMarker(markerOptions);
            }
        }

        // Move the camera instantly to where lat and lng shows.
        if(lat != 0  && lng != 0)
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), ZOOM_LEVEL));

        googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
            @Override
            public View getInfoWindow(Marker marker) {
                return null;
            }

            @Override
            public View getInfoContents(Marker marker) {
                return null;
            }
        });

        googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {
                String str = marker.getId();
                Log.i(TAG, "Marker id: " + str);
                str = str.substring(1);
                int markerId = Integer.parseInt(str);
                markerId -= 1; // Because first item id of marker is 1 while list starts at 0
                Log.i(TAG, "Marker id " + markerId + " clicked.");

                // Ignore if User's marker clicked
                if(markerId < 0)
                    return;

                try {
                    Venue venue = venueList.get(markerId);
                    if(venue.getCan_checkin().equalsIgnoreCase("true")) {
                        Fragment fragment = VenueFragment.newInstance(venue);
                        if(fragment != null)
                            changeFragmentLister.OnReplaceFragment(fragment);
                        else
                            Log.e(TAG, "Error! venue shouldn't be null");
                    }
                } catch(NumberFormatException e) {
                    e.printStackTrace();
                } catch(IndexOutOfBoundsException e) {
                    e.printStackTrace();
                }
            }
        });

A: Okay finally I found a replacement way to solve my problem. The interesting problem is when you assign a marker to map, it's id is 'm0'. When you remove it from map and assign new marker you expect the id should be 'm0' but it's 'm1'. Therefore, it showed me the id is not trustable. So I defined List<Marker> markerList = new ArrayList<Marker>(); somewhere in onActivityCreated() of my fragment.
Then changed above code with following one. hope it helps others if they have similar issue with markers.
private void displayData(final List<Venue> venueList) {
        Marker marker;

        // Removes all markers, overlays, and polylines from the map.
        googleMap.clear();
        markerList.clear();

        // Zoom in, animating the camera.
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(ZOOM_LEVEL), 2000, null);

        // Add marker of user's position
        MarkerOptions userIndicator = new MarkerOptions()
                .position(new LatLng(lat, lng))
                .title("You are here")
                .snippet("lat:" + lat + ", lng:" + lng);
        marker = googleMap.addMarker(userIndicator);
//        Log.e(TAG, "Marker id '" + marker.getId() + "' added to list.");
        markerList.add(marker);

        // Add marker of venue if there is any
        if(venueList != null) {
            for (Venue venue : venueList) {
                String guys = venue.getMaleCount();
                String girls = venue.getFemaleCount();
                String checkinStatus = venue.getCan_checkin();
                if (checkinStatus.equalsIgnoreCase("true"))
                    checkinStatus = "Checked In - ";
                else
                    checkinStatus = "";

                MarkerOptions markerOptions = new MarkerOptions()
                        .position(new LatLng(Double.parseDouble(venue.getLatitude()), Double.parseDouble(venue.getLongitude())))
                        .title(venue.getName())
                        .snippet(checkinStatus + "Guys:" + guys + " and Girls:" + girls)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_orange_pin));

                marker = googleMap.addMarker(markerOptions);
//                Log.e(TAG, "Marker id '" + marker.getId() + "' added to list.");
                markerList.add(marker);
            }
        }

        // Move the camera instantly to where lat and lng shows.
        if(lat != 0  && lng != 0)
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), ZOOM_LEVEL));

        googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
            @Override
            public View getInfoWindow(Marker marker) {
                return null;
            }

            @Override
            public View getInfoContents(Marker marker) {
                return null;
            }
        });

        googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {
                int markerId = -1;

                String str = marker.getId();
                Log.i(TAG, "Marker id: " + str);
                for(int i=0; i<markerList.size(); i++) {
                    markerId = i;
                    Marker m = markerList.get(i);
                    if(m.getId().equals(marker.getId()))
                        break;
                }

                markerId -= 1; // Because first item of markerList is user's marker
                Log.i(TAG, "Marker id " + markerId + " clicked.");

                // Ignore if User's marker clicked
                if(markerId < 0)
                    return;

                try {
                    Venue venue = venueList.get(markerId);
                    if(venue.getCan_checkin().equalsIgnoreCase("true")) {
                        Fragment fragment = VenueFragment.newInstance(venue);
                        if(fragment != null)
                            changeFragmentLister.OnReplaceFragment(fragment);
                        else
                            Log.e(TAG, "Error! venue shouldn't be null");
                    }
                } catch(NumberFormatException e) {
                    e.printStackTrace();
                } catch(IndexOutOfBoundsException e) {
                    e.printStackTrace();
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
            }
        });
    }

A: If you want to clear "all markers, overlays, and polylines from the map", use clear() on your GoogleMap.

A: Use map.clear() to remove all markers from Google map

A: Suppose there is an ArrayList of 2 locations. Now, you display markers on the map based on that array. There will be two markers. When you click on the first marker it gives you a marker index m0 and the second is m1.
Say that you refresh location array and now you got an array with 3 locations. You got 3 markers. But when you click on the first one, it gives you marker index m2 (as if it continues counting from the first location arraw) the second is m3 and the third is m4. What you actually want is to make it as m0, m1, m2.
Now, when you build you location array you probably call location.add("you location")... and when you rebuild it (refresh it) you call location.clear() first and then build it again.
SOLUTION:
First, make another dummy array similar to location array and build it in for loop together with a real location array: locaionDummy.add(i) but don't you EVER refresh it - that way it keeps building and you will know how many locations you've ever had from the very beginning.
Second, do something like this (example of setting image) with mIndex as int variable:
void locatePins() {

mIndex = locationDummy.size()-location.size();

for (int i = 0; i < userID.size(); i++) {

    LatLng pgLocation = new LatLng(Double.parseDouble(latArr.get(i)), Double.parseDouble(lngArr.get(i)));

    myMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
        @Override
        public View getInfoWindow(Marker marker) {

        View view = getLayoutInflater().inflate(R.layout.map_marker_info, null);

        RelativeLayout markerInfo= view.findViewById(R.id.markerInfo);
        TextView name = view.findViewById(R.id.userName);
        TextView details = view.findViewById(R.id.userInfo);
        ImageView img = view.findViewById(R.id.userImg);

        name.setText(marker.getTitle());
        details.setText(marker.getSnippet());

        img.setImageBitmap (bmImg.get(Integer.parseInt(marker.getId().replaceAll("[^\\d.]", ""))-mIndex));

        return view;
    }

    @Override
    public View getInfoContents(Marker marker) {

         return null;
    }

    // ... the rest of the code
}
}

The key is to subtract the real location.size() from a locationDummy.size() to get a number int mIndex that you will subtract later on from marker.getId()

A: If you need to remove only the markers, and leave other things such as ground overlay,etc there, use:
 marker.remove();

or if you have many:
 if(markers!=null&&mMap!=null){
      for(int i=0;i<markers.size();i++){
             markers.get(i).remove();
      }
 }

where
List<Marker> markers = new ArrayList<>();


text:
Q: How to set DrawerItem on top of Drawer Screens I created a drawer with screens but wanted to add also an image of the user at the top of the drawer. I used in the Drawer.Navigator the drawerContent option and used a custom function and called it. The problem is that the image is set on the bottom and not in the top. I've tried searching in the web but I didn't find a way to set it on top. Here is the code:
const Drawer = createDrawerNavigator()

const CustomDrawerContent=(props) =>{
  return (
    <DrawerContentScrollView {...props}>
      <DrawerItemList {...props} />
      <DrawerItem
        icon={({color})=> <Image style={{ width: 90, height: 90, borderRadius: 400 / 2 }} source={{ uri: auth.currentUser.photoURL }}></Image>}
        label=""
      />

    </DrawerContentScrollView>
  );
}

const DrawerNavigator = () => {
   return (

    <Drawer.Navigator initialRouteName='TabNavigator' drawerContent={CustomDrawerContent}>
        <Drawer.Screen name='Início' component={TabNavigator}/>[enter image description here][1]
        <Drawer.Screen name="Lista de Espera" component={PermissionsStackScreen} />
        <Drawer.Screen name="Comunidade" component={CommunityStackScreen} />
        <Drawer.Screen name='Análises em Espera' component={AwaitingStackScreen}/>
        <Drawer.Screen name='Confirmar Análises' component={VerifyStackScreen}/>
        <Drawer.Screen name='Análises Rejeitadas' component={RejectedStackScreen}/>
        <Drawer.Screen name='Gerir Reagentes' component={ReagentStackScreen}/>
        <Drawer.Screen name='Gerir Equipamentos' component={EquipmentStackScreen}/>
    </Drawer.Navigator>
  );

}

export default DrawerNavigator

I have also added the link of the how the code looks like.
[1]: https://i.stack.imgur.com/9b9f5.jpg
Any help would be useful!

A: Just simply change the order of the component here :
const CustomDrawerContent=(props) =>{
  return (
    <DrawerContentScrollView {...props}>
      {/* Render image item first */}
      <DrawerItem
        icon={({color})=> <Image style={{ width: 90, height: 90, borderRadius: 400 / 2 }} source={{ uri: auth.currentUser.photoURL }}></Image>}
        label=""
      />
      {/* then render others menu item */}
      <DrawerItemList {...props} />
    </DrawerContentScrollView>
  );
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Repeating a Click Event in jQuery Without Removing The Previous Click Effect

$(document).ready(function() {
    $('img').click(function(e) {
       var offset = $(this).offset();
       /*alert("X: " + (e.pageX - offset.left) + " / Y: " + (e.pageY - offset.top));*/
       $(this).after('
Label
');

       $('.label').offset({ top: e.pageY - offset.top, left: e.pageX - offset.left });

    });
  });
.label {
 position: absolute;
}

Thanks for helping me out.
Let me clarify what I am trying to achieve, I have an image of a living room with various objects (TV, Sofa, etc) and when I click on say the TV area I want to add a Image Label right next to it, now I have achieved this part but when I click again on any other area say if I clicked on the Sofa then the Image Label disappears from the TV area and shows near the Sofa area, so basically I want this functionality to loop and should be able to add multiple Image Labels.
Please check the script and kindly let me know how to fix it.
$(document).ready(function() {
      $('img').click(function(e) {
            var offset = $(this).offset();
            $(this).after('');

            $('.label').offset({ top: e.pageY - offset.top, left: e.pageX - offset.left });

      });
    });

Thanks

A: The issue is because although you append a new img, your selector of .label is changing the position of all img elements - even those previously added. You need to amend your code to relate to only the new img element being added. Try this:
$('img').click(function(e) {
    var offset = $(this).offset();
    $('')
        .insertAfter(this)
        .offset({
            top: e.pageY - offset.top,
            left: e.pageX - offset.left
        });
  });

UPDATE
Given your updated HTML example and requirements, this should work for you:
$('img').click(function (e) {
    var offset = $(this).offset();
    $('
Label
')
        .insertAfter(this)
        .css({
            top: e.pageY - offset.top,
            left: e.pageX - offset.left
        });
});

Example fiddle


text:
Q: How to execute raw queries using sqlx? Using sqlx as my database adapter, I'd like to run queries on user profiles based on user-submitted POST data. There are several parameters like age, sex and location and many more.
So for example if only age value is submitted by the user, the query should looks like:
var profiles []model.Profile
q:= "SELECT *  FROM profile WHERE age = ?"
err = database.SQL.Select(&profiles, q, age)
if err != nil {
    log.Println(err)
}

As you can see, since the query can not be built dynamically, this method is not flexible enough and becomes so verbose to account for all possible variations.
What I want is to construct query based on the input data then just feed the raw query to sqlx.
Something like this pseudo code:
q:= `SELECT *  FROM profile WHERE
      age > 25   AND sex="f" AND location="London"`
    err = database.SQL.ExecRaw(&profiles, q)

How can I achieve this in sqlx?
I have looked at the docs but could not figure out how to do so.

A: If you don't want to use parameters, don't use parameters. Select doesn't prevent you from putting literals in your query.


text:
Q: Separating html and JavaScript in Flask Hey I've got the following problem:
I am building a little flask app, and usually i just stick with bootstrap and jinja templates to get what I want, but this time I needed a bit more customised version. In order to get a grip I started with a simple example of using custom js and flask to get the basic right. But lets go into detail:
Assume I have a simple flask web app called app.py located in my_app/ which looks like this
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(port=8080, debug=True)

and the corresponding index.html, which is located in my_app/templates, is simply
<!DOCTYPE html>

Clicking here will make me dissapear

then I see the expected result, that is, i can click on the paragraph to make it disappear.
BUT: I would like to put the javascript part into a main.js file under static/js/. like so:
$(document).ready(function() {
    $("p").click(function(event){
        $(this).hide();
    });
});

and the index.html becomes:
<!DOCTYPE html>

Clicking here will make me dissapear

Unfortunately nothing will happen. I have tried other ways of referencing the script file as well but until now nothing works. I have the impression im missing something really simple. Thanks in advance!

A: Simply invoke the url_for function within the template, referencing the special static endpoint so that the correct url to the desired target resource be created.  As the desired target is the main.js file inside static/js, this would lead to the following:

The rest of the quickstart guide contains additional useful information.


text:
Q: Firebase getting the reference The full path for my reference looks like this
data/-KdWI6HAF0_wh9-NTEpe/films/thelobster/rating

and I can set it with
firebase.database().ref('data/-KdWI6HAF0_wh9-NTEpe/films/thelobster/rating')
  .set(5);

The problem is that both the keys -KdWI6HAF0_wh9-NTEpe and thelobster are dynamic.
It makes it more difficult than it should be, is there any way to build this with just the -KdWI6HAF0_wh9-NTEpe key and make the film name a wildcard? Oris there a better way I am missing?

A: You can use Firebase's child() method:
firebase.database().ref('data').child(key).child('films').child(filmKey).child('rating').set(5);

Alternatively you can use ES6 string interpolation:
firebase.database().ref(`data/${key}/films/${filmKey}/rating`).set(5);

A: Firebase returns 'key' which is the id used to reference your object. Something like this.
var ref = firebase.database().ref("users/ada");
ref.once("value")
  .then(function(snapshot) {
    var key = snapshot.key; // "ada"
    var childKey = snapshot.child("name/last").key; // "last"
  });

You can read more about it here.
For 'thelobster', you can console.log() the data that comes from firebase, check the location of the dynamically changing 'thelobster', set it to a variable, and use the variable in your url.
Because I don't know how your incoming data looks like, I can't provide you with that code.


text:
Q: How do I use DAX to filter a fact table where a value in one dimension table is greater than a value in a different dimension table I have a fact table with two linked dimension tables.
I am trying to write a DAX filter that filters the fact table based on whether a date in one dimension table is greater than
Something along the lines of this (although obviously this doesn't work).
CALCULATE ( SUM ( factFinancial[Value] ), dimOne[Date1] > dimTwo[Date2] )

Any help would be greatly appreciated

A: It's hard to answer without a specific example to work with but I suspect you can find a solution along these lines:
CALCULATE (
    SUM ( factFinancial[Value] ),
    FILTER ( factFinancial, RELATED ( dimOne[Date1] ) > RELATED ( dimTwo[Date2] ) )
)

A: The calculate function can not evaluate your expression, The reasons are:

*

*During its evaluation algorithm, CALCULATE cannot determine whether the condition should replace any existing filter on dimOne [Date1], on dimTwo [Date2], or on none of them.

*Row context does not interact automatically with relationships, means that the expression dimOne[Date1] > dimTwo[Date2] is evaluated in row context and the two columns [Date1] and [Date2] are from two different tables, there since we cannot access the corresponding date from [Date2] to each date on [Date1] automatically. In this situation you must use RELATED and RELATEDTABLE DAX functions.
In order to achieve your aim you must use filter and RELATED functions.
Use this code  instead to create the measure in factFinancial table :
CALCULATE(SUM (factFinancial[Value]),
FILTER(factFinancial,RELATED(dimOne[Date1]) > RELATED(dimTwo[Date2])))

Visit : https://www.sqlbi.com/blog/marco/2010/01/03/how-calculate-works-in-dax/
Visit : https://www.microsoftpressstore.com/articles/article.aspx?p=2449191&seqNum=5


text:
Q: Attempting to save todo list items to local storage I have a pretty simple to do app that creates to dos and displays them to the screen. However, I wan't to save these to local storage so if someone leaves the page and returns, reloads the page, etc. the to do items remain.
I'm having trouble wrapping my head around how to use local storage though. I know relatively what I need to do, represented in pseudo code in my JavaScript document, but I can't seem to make it work. Any guidance would be greatly appreciated.
https://codepen.io/constequalsexcel/pen/GRJpzoE

function addTodo() {
  let todoItem = document.createElement('li');
  todoItem.setAttribute('class', 'list-item');
  let text = document.getElementById('todo-input').value;
  if (text.length < 1) return;
  let textnode = document.createElement('span');
  textnode.innerText = text;
  // Create delete todo button
  let deleteButton = document.createElement('button');
  let deleteButtonX = document.createTextNode('X');
  deleteButton.appendChild(deleteButtonX);
  deleteButton.addEventListener('click', removeNode);
  // Create strike through radio input
  let StrikeThroughRadio = document.createElement('input');
  StrikeThroughRadio.setAttribute('id', 'checkbox-styles');
  StrikeThroughRadio.setAttribute('type', 'checkbox');
  StrikeThroughRadio.addEventListener('click', function(e) {
    StrikeThroughRadio.checked ?
      e.target.nextElementSibling.classList.add('strike-text') :
      e.target.nextElementSibling.classList.remove('strike-text');
  });

  todoItem.appendChild(StrikeThroughRadio);
  todoItem.appendChild(textnode);
  todoItem.appendChild(deleteButton);
  enter code here

  document.getElementById('display').appendChild(todoItem);

// get saved todos from local storage and save it in a variable
// if saved todos variable is null then re-assign saved todoso variable equal to an empty array
// add current todo text to the saved todos array variable
// re-save saved todos into local storage (using the setItem() method)
    }
    function removeNode(e) {
      e.target.parentElement.remove();
    }
    `enter code here`

    function ClearInputOnSubmit() {
      document.getElementById('todo-input').value = '';
    }
    <!DOCTYPE html>

      <meta charset="utf-8" />

      <title>To-Do App</title>

      <link rel="stylesheet" href="styles.css" />
      <link href="https://fonts.googleapis.com/css?family=Roboto+Mono&display=swap" rel="stylesheet" />
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" />

TO DO LIST

        <form class="container" class="needs-validation" novalidate>

            <input type="text" id="todo-input" class="form-control input-group shadow-lg" aria-describedby="button-addon2" required />
            <input type="button" value="Add ToDo" id="todo-button" id="button-addon2" class="btn btn-info btn-sm" onclick="addTodo(); ClearInputOnSubmit()" />

        </form>

TODOS

A: The local storage runs as a way to store JavaScript objects. However, if the user clears their browser data, the objects will be lost.
localStorage.setItem("storage", todoitem)
localStorage.getItem("storage")
Looking at the need you have here, you may want to make a loop or array to store all of the todoitems an user creates. If you are stuck on how you would do that, I can help. I actually started a project related to this issue.
Here is a good reference if you are looking for more information.

A: You can save only strings to the localStorage, and you can't stringify element nodes. But innerHTML gets the node as a string, so you can save it in the localStorage.
//to save the todo-list as a text in the local storage
localStorage.setItem('todoItem', todoItem.innerHTML);

//if you save single todo item at a time in the local storage,
//get the saved text(innerHTML) of the todo-list and append it to the container
todoItem = localStorage.getItem('todoItem');

document.getElementById('display').insertAdjacentHTML('afterend', todoItem);

//or if you save all of the todo-list at once, set the innerHTML of the container
document.getElementById('display').innerHTML = todoItem;

A: When ever you in your code step, you ready to store/update data to the local storage, just call
localStorage.setItem("toItem", todoitem);

And when you want to read the stored item you can call the below method to get data
localStorage.getItem("todoItem");

Here is the document that that document

A: You could save each item to localStorage (not sessionStorage!!!) or you could batch them into a JSON object then store the entire thing as a string by first converting to as string JSON.stringify(your_json_object).
Scenario 1. save each item to local storage. one after another.
localStorage.setItem('item1', 'value1')

or
Scenario 2. build a JSON object first and save everything.
your_json_object = {item1: 'value1', item2: 'value2' ...};
localStorage.setItem(all_info: JSON.stringify(your_json_object));


text:
Q: Do Ethereum have API for Etherscan's label word cloud As the title asked, recently I want to download the classified address from Etherscan's label word cloud. So I went to check whether Ethereum has provided such API, but have not found it yet.
If there is no API with such functionality, the only way is to crawl them down using python, but I'm afraid etherscan won't allow me to do this. Do you guys have other methods to get those addresses if Etherscan doesn't provide the API?


text:
Q: Failed handling of the snapd snap I'm attempting to setup ubuntu on a Dell Precision 690. I flashed an image of ubuntu onto a flash drive and followed the instructions on the site to get it running. I got to the stage where it asked me to restart and remove the flash drive when I ran into this error. I got some text popping up before The ubuntu loading screen appeared but then quickly switched back to a black screen with the error messages as follows:
[FAILED] Failed to start Network Time Synchronization.
[FAILED] Failed to start Userspace Out-Of-Memory (OOM) Killer.
[FAILED] Failed to start Userspace Out-Of-Memory (OOM) Killer.
[FAILED] Failed to start Failure handling of the snapd snap.
The last error is what I'm focusing on as it appeared only after the ubuntu loading screen stopped. I've searched the problem elsewhere as well on this site, but it seems to happen in much different scenarios than this. I'm very new to working with computers in this way so please be patient with me if I don't know what something is.


text:
Q: ClassNotFoundException while trying to run vertx aplication I'm trying to run a sample Vert.x program with below code:
public class MyFirstVerticle extends AbstractVerticle {

  @Override
  public void start(Future<Void> fut) {
    vertx
        .createHttpServer()
        .requestHandler(r -> {
          r.response().end("
Hello from my first " +
              "Vert.x 3 application
");
        })
        .listen(8080, result -> {
          if (result.succeeded()) {
            fut.complete();
          } else {
            fut.fail(result.cause());
          }
        });
  }
}

Here down the Maven pom file:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                      http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>io.vertx.blog</groupId>
    <artifactId>MyFirstVertxMicroservices</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-core</artifactId>
            <version>3.3.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.4</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-unit</artifactId>
            <version>3.0.0</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>com.fasterxml.jackson.core</groupId>
                        <artifactId>jackson-databind</artifactId>
                        <version>2.9.4</version>
                    </dependency>
                </dependencies>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.3</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <manifestEntries>
                                        io.vertx.core.Starter
                                        com.inet.vertex.verticle.MyFirstVerticle
                                    </manifestEntries>
                                </transformer>
                            </transformers>
                            <artifactSet/>
                            <outputFile>${project.build.directory}/${project.artifactId}-${project.version}-fat.jar</outputFile>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>

</project>

When I try to run the program using the below command:
java -jar target/MyFirstVertxMicroservices-1.0-SNAPSHOT-fat.jar

I get the following error:
SEVERE: Failed in deploying verticle
java.lang.ClassNotFoundException: com.inet.vertex.verticle.MyFirstVerticle
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
 at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)

I tried to unzip the fat jar file and I can see that MyfirstVerticle.class is there inside folder com/inet/vertex/verticle/MyfirstVerticle.class.
Am I missing something?

A: Assuming it's a standard directory structure for Java project.
Update your Pom to match Vert.X examples pom. https://github.com/vert-x3/vertx-examples/blob/master/maven-verticles/maven-verticle/pom.xml
Specifically shade plugin section. You're missing AppendingTransformer section.
   <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>2.3</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <manifestEntries>
                    io.vertx.core.Launcher
                    ${main.verticle}
                  </manifestEntries>
                </transformer>
                <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                  <resource>META-INF/services/io.vertx.core.spi.VerticleFactory</resource>
                </transformer>
              </transformers>
              <artifactSet>
              </artifactSet>
              <outputFile>${project.build.directory}/${project.artifactId}-${project.version}-fat.jar</outputFile>
            </configuration>
          </execution>
        </executions>
      </plugin>


text:
Q: How I can create a User in AD with Powershell in a ASP.NET Webapplication I have a question to C# and Powershell in a ASP.NET Application.
I want to create a User in our Active Directory and I want/must use a powershell for this. I had built a Webapllication that could add a mailcontact in the Exchange Server one year ago. For this I used the System.Management.Automation Namespace with the Powershell Classes. But I don't know how I can do it for the Active Directory.
the ps command that I must use:
New-ADUser %prefix-%name
-SamAccountName "%name"
-UserPrincipalName "%name@test-company.com"
-GivenName "%text1"
-SurName "%text2"
-displayname "%name"
-enabled $true
-Path '%OU'
-AllowReversiblePasswordEncryption $true
-PasswordNeverExpires $true
-AccountPassword (ConvertTo-Securestring "%name" -asplaintext -Force)

and here my cs code:
public void CreateRemoteConnectionToActiveDirectory(string Username, string password//,...comming)
        {
            SecureString securePassword = new SecureString();

            str_password = password;
            str_username = Username;

            foreach (char x in str_password)
            {
                securePassword.AppendChar(x);
            }

            PSCredential cred = new PSCredential(str_username, securePassword);

          //  connection?
        }

My Old Code for the exchange Server:
public string CreateRemoteConnectionToExchange(string UserName, string Password, string Mailbox)
        {
                SecureString SecurePassword = new SecureString();

                string str_password = Password;
                string str_username = UserName;

                foreach (char x in str_password)
                {
                    SecurePassword.AppendChar(x);
                }

                PSCredential cred = new PSCredential(str_username, SecurePassword);

                WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(ExchangeServer), Schema, cred);

                connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Default;

                Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);

                PowerShell powershell = PowerShell.Create();
                PSCommand command = new PSCommand();

                command.AddCommand("New-MailContact");
                command.AddParameter("ExternalEmailAddress", "SMTP:" + Mailbox + MailExtension);
                command.AddParameter("Name", Mailbox);
                command.AddParameter("Alias", Mailbox);
                command.AddParameter("FirstName", Mailbox);
                command.AddParameter("Initials", "");
                command.AddParameter("LastName", "");
                command.AddParameter("OrganizationalUnit", OrganizationalUnit);
                command.AddParameter("DomainController", configDC);

                powershell.Commands = command;

                try
                {
                    runspace.Open();

                    powershell.Runspace = runspace;

                    powershell.Invoke();

                    return "Der Kontakt wurde Erfolgreich erstellt";
                }
                catch (Exception ex)
                {
                 ///...
                }
                finally
                {
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                }

        }

How I can do this. A Example,tutorial or a tipp would me help.

A: Looks like your connection just needs to connect to either your AD server or another server that can actually execute the command.


text:
Q: flash capture image from webcam we have the below code and it captured the video but not the actual video which displayed in the webcam . It only captured one third of the image like from x 100 and y 40 something like not
Could some one help to how to capture the whole image displayed in the webcam like 320*250
below is the code
import flash.geom.*;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.display.LoaderInfo;
import flash.display.Bitmap;
import flash.display.BitmapData;

import com.adobe.images.JPGEncoder;

var nc:NetConnection = null;
var camera:Camera;
var microphone:Microphone;
var nsPublish:NetStream = null;
var nsPlay:NetStream = null;

function startCamera()
{
 // get the default Flash camera and microphone
 camera = Camera.getCamera();
 microphone = Microphone.getMicrophone();

 // here are all the quality and performance settings that we suggest
 camera.setMode(160, 120, 12, false);
 camera.setQuality(0, 88);
 camera.setKeyFrameInterval(24);
 microphone.rate = 11;
 microphone.setSilenceLevel(0);

// subscribeName.text = "testing";
 publishName.text = "testing";
// publishName.text  = root.loaderInfo.parameters.streamname ;

 connect.connectButton.addEventListener(MouseEvent.CLICK, doConnect);
 doPublish.addEventListener(MouseEvent.CLICK, publish);
 doSubscribe.addEventListener(MouseEvent.CLICK, subscribe);
 enablePlayControls(false);
}

function ncOnStatus(infoObject:NetStatusEvent)
{
 trace("nc: "+infoObject.info.code+" ("+infoObject.info.description+")");
 if (infoObject.info.code == "NetConnection.Connect.Failed")
  prompt.text = "Connection failed: Try rtmp://[server-ip-address]/videochat";
 else if (infoObject.info.code == "NetConnection.Connect.Rejected")
  prompt.text = infoObject.info.description;
}

function doConnect(event:MouseEvent)
{
 // connect to the Wowza Media Server
 if (nc == null)
 {
  // create a connection to the wowza media server
  nc = new NetConnection();
  nc.connect(connect.connectStr.text);

  // get status information from the NetConnection object
  nc.addEventListener(NetStatusEvent.NET_STATUS, ncOnStatus);

  connect.connectButton.label = "Stop";

  // uncomment this to monitor frame rate and buffer length
  //setInterval(updateStreamValues, 500);

  videoCamera.clear();
  videoCamera.attachCamera(camera);

  enablePlayControls(true);
 }
 else
 {
  nsPublish = null;
  nsPlay = null;

  videoCamera.attachCamera(null);
  videoCamera.clear();

  //videoRemote.attachNetStream(null);
  //videoRemote.clear();

  nc.close();
  nc = null;

  enablePlayControls(false);

  doSubscribe.label = 'Play';
  doPublish.label = 'Go Live';

  connect.connectButton.label = "Connect";
  prompt.text = "";
 }
}

function doConnect12()
{
 // connect to the Wowza Media Server
 if (nc == null)
 {
  // create a connection to the wowza media server
  nc = new NetConnection();
  nc.connect(connect.connectStr.text);

  // get status information from the NetConnection object
  nc.addEventListener(NetStatusEvent.NET_STATUS, ncOnStatus);

  connect.connectButton.label = "Stop";

  // uncomment this to monitor frame rate and buffer length
  //setInterval(updateStreamValues, 500);

  videoCamera.clear();
  videoCamera.attachCamera(camera);

  enablePlayControls(true);
 }
 else
 {
  nsPublish = null;
  nsPlay = null;

  videoCamera.attachCamera(null);
  videoCamera.clear();

  //videoRemote.attachNetStream(null);
  //videoRemote.clear();

  nc.close();
  nc = null;

  enablePlayControls(false);

  doSubscribe.label = 'Play';
  doPublish.label = 'Go Live';

  connect.connectButton.label = "Connect";
  prompt.text = "";
 }
}

function enablePlayControls(isEnable:Boolean)
{
 doPublish.enabled = isEnable;
 doSubscribe.enabled = isEnable;
 publishName.enabled = isEnable;
 subscribeName.enabled = isEnable;
}

// function to monitor the frame rate and buffer length
function updateStreamValues()
{
 if (nsPlay != null)
 {
  fpsText.text = (Math.round(nsPlay.currentFPS*1000)/1000)+" fps";
  bufferLenText.text = (Math.round(nsPlay.bufferLength*1000)/1000)+" secs";
 }
 else
 {
  fpsText.text = "";
  bufferLenText.text = "";
 }
}

function nsPlayOnStatus(infoObject:NetStatusEvent)
{
 trace("nsPlay: "+infoObject.info.code+" ("+infoObject.info.description+")");
 if (infoObject.info.code == "NetStream.Play.StreamNotFound" || infoObject.info.code == "NetStream.Play.Failed")
  prompt.text = infoObject.info.description;
}

function subscribe(event:MouseEvent)
{
 if (doSubscribe.label == 'Play')
 {
  // create a new NetStream object for video playback
  nsPlay = new NetStream(nc);

  // trace the NetStream status information
  nsPlay.addEventListener(NetStatusEvent.NET_STATUS, nsPlayOnStatus);

  var nsPlayClientObj:Object = new Object();
  nsPlay.client = nsPlayClientObj;
  nsPlayClientObj.onMetaData = function(infoObject:Object)
  {
   trace("onMetaData");

   // print debug information about the metaData
   for (var propName:String in infoObject)
   {
    trace("  "+propName + " = " + infoObject[propName]);
   }
  };

  // set the buffer time to zero since it is chat
  nsPlay.bufferTime = 0;

  // subscribe to the named stream
  nsPlay.play(subscribeName.text);

  // attach to the stream
  //videoRemote.attachNetStream(nsPlay);

  doSubscribe.label = 'Stop';
 }
 else
 {
  // here we are shutting down the connection to the server
  //videoRemote.attachNetStream(null);
  nsPlay.play(null);
  nsPlay.close();

  doSubscribe.label = 'Play';
 }
}

function nsPublishOnStatus(infoObject:NetStatusEvent)
{
 trace("nsPublish: "+infoObject.info.code+" ("+infoObject.info.description+")");
 if (infoObject.info.code == "NetStream.Play.StreamNotFound" || infoObject.info.code == "NetStream.Play.Failed")
  prompt.text = infoObject.info.description;
}

function publish(event:MouseEvent)
{
 if (doPublish.label == 'Go Live')
 {

 var jpgSource:BitmapData = new BitmapData (camera.height, camera.width);

 jpgSource.draw(videoCamera);
 var jpgEncoder:JPGEncoder = new JPGEncoder();
 var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);

 var header:URLRequestHeader = new URLRequestHeader ("Content-type", "application/octet-stream");

 //Make sure to use the correct path to jpg_encoder_download.php
 jpgURLRequest.requestHeaders.push(header);
 jpgURLRequest.method = URLRequestMethod.POST;
 jpgURLRequest.data = jpgStream;

 var jpgURLLoader:URLLoader = new URLLoader();
// navigateToURL(jpgURLRequest, "_blank");
 sendToURL(jpgURLRequest);
  // create a new NetStream object for video publishing
  nsPublish = new NetStream(nc);

  nsPublish.addEventListener(NetStatusEvent.NET_STATUS, nsPublishOnStatus);

  // set the buffer time to zero since it is chat
  nsPublish.bufferTime = 0;

  // publish the stream by name
  nsPublish.publish(publishName.text);

  // add custom metadata to the stream
  var metaData:Object = new Object();
  metaData["description"] = "Chat using VideoChat example."
  nsPublish.send("@setDataFrame", "onMetaData", metaData);

  // attach the camera and microphone to the server
  nsPublish.attachCamera(camera);
  nsPublish.attachAudio(microphone);

  doPublish.label = 'Stop';
 }
 else
 {
  // here we are shutting down the connection to the server
  nsPublish.attachCamera(null);
  nsPublish.attachAudio(null);
  nsPublish.publish("null");
  nsPublish.close();

  doPublish.label = 'Go Live';
 }
}

stage.align = "TL";
stage.scaleMode = "noScale";

startCamera();
doConnect12();
stop();

A: Looks like you are setting the camera to a size smaller than you need to capture:
camera.setMode(160, 120, 12, false);

That is 160 x 120 but you need
camera.setMode(320, 250, 12, false);

See the api docs for a detailed explanation of the parameters of this call.
http://www.adobe.com/livedocs/flex/3/langref/flash/media/Camera.html#setMode%28%29


text:
Q: Handling Dynamic List/dropdowns in Appium(Android) Screenshot of the scenarioThis is not the exact screen, but the scenario is similar except that this is auto complete list. Any suggestions, as i am unable to interact with the highlighted part.
In appium(1.4.13) with java in win 7, unable to identify the items in a static list/dropdown through UI Automator Viewer. So can we automate the elements which are not identified in this viewer.Tried using the text property, but in vain.
Even tried using appium inspector record option, the issue which i observed here is that the elements behind the list are selected.
Able to automate this scenario in calabash based on text property, with which the properties are found and tried using the classname in appium.

A: Take a list and add the visible elements in the list. Select the next element one by one from the added list. This will help you in viewing the next item. It will take time but will work fine.

in this case the suggestion is  displaying from the list.
first get all the suggestions in the list ,then use scrollto() method to find the element in the list view. Then select the element. Hope this works


text:
Q: Rotating Text in WPF TextBox without rotating control itself The question is: how could I rotate text inside WPF TextBox without rotating TextBox itself? (Rotate text only)
I have tried different RenderTransforms, LayoutTransforms but this did not help me.

A: Found answer myself: put TextBox inside other control, i.e. in RIchTextBox:
  <RichTextBox>
    <FlowDocument>
        <Paragraph>
          <TextBlock Text="Stacked text!">
          <TextBlock.LayoutTransform>
            <RotateTransform Angle="-90"></RotateTransform>
          </TextBlock.LayoutTransform>
          </TextBlock>
        </Paragraph>
      </FlowDocument>
  </RichTextBox>

A: I would say that the correct solution to your question would be to define a custom ControlTemplate for the TextBox and apply the RotateTransform to the ScrollViewer element:
<TextBox Background="Yellow" Text="test">
    <TextBox.Template>
        <ControlTemplate TargetType="{x:Type TextBox}">
            <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                <ScrollViewer x:Name="PART_ContentHost" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden">
                    <ScrollViewer.LayoutTransform>
                        <RotateTransform Angle="-90"></RotateTransform>
                    </ScrollViewer.LayoutTransform>
                </ScrollViewer>
            </Border>
            <ControlTemplate.Triggers>
                <Trigger Property="IsEnabled" Value="false">
                    <Setter Property="Opacity" TargetName="border" Value="0.56"/>
                </Trigger>
                <Trigger Property="IsMouseOver" Value="true">
                    <Setter Property="BorderBrush" TargetName="border" Value="#FF7EB4EA"/>
                </Trigger>
                <Trigger Property="IsKeyboardFocused" Value="true">
                    <Setter Property="BorderBrush" TargetName="border" Value="#FF569DE5"/>
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </TextBox.Template>
</TextBox>


text:
Q: Which version of MPI is in MS-MPI v9.0.1 I have been searching the internet to find the version of MPI in the Microsoft's MSMPI v9.0.1.
Is it MPICH1 (1.0, 1.1, 1.2 etc) or MPICH2 (2.1, 2.2) ? Does anybody know the full version number?
Thanks!


text:
Q: Making my first discord bot, unable to add anything besides basic commands I'm using discord.js as well as javascript to code. I'm just trying to work out this test bot I have made and despite all the step-by-step guides that I have pretty much followed to a T, I am only able to get the bot to work with basic "ping pong" like commands. Every time I try to add anything more or less, the bot completely stops working.
Here is an example of the code I have so far. It's a little 'gaggy' some friends and I, as I said, are just trying to work out how to make the test bot first. Maybe it's just completely going over my head and I'm just not doing it the correct way. Either way, some assistance would be helpful. Thanks.
        /*
  A ping pong bot, whenever you send "ping", it replies "pong".
*/

// Import the discord.js module
const Discord = require('discord.js');

// Create an instance of a Discord client
// This is sometimes called 'bot', but 'client' is prefered
const client = new Discord.Client();

const token = 'MY_BOT_TOKEN';

client.on('ready', () => {
  console.log('I am ready!');
});

// Create an event listener for messages
client.on('message', message => {
  // If the message is "ping"
  if (message.content === 'silas!ping') {
    // Send "pong" in the same channel
    message.channel.send('pong');
  }
});

// Log our bot in
client.login(token);

What I am also trying to do is add a "SAY" command, this is what I have been using, and once I add it, it completely breaks the bot. As well as adding in a prefix.
client.on('message', message => {
  if (message.channel.type != 'text' || message.author.bot || !message.startsWith('*'))
    return;

  if (message.content === '*ping') {
    message.channel.send('pong');
  }
});
client.on('message', message => {
  if (message.channel.type != 'text' || message.author.bot || !message.startsWith('*'))
    return;

  if (message.content === '*ping') {
    message.channel.send('pong');
  }

  else if (message.content === '*say') {
    message.channel.send(message.content);
  }
});

Im not sure if this means anything to get help, but this is the error i recieve when trying to add the following code given to me for help
if (!message.content.startsWith(prefix)) return;
^
ReferenceError: message is not defined
at Object. (C:\Users\my location files\index.js:23:1)
[90m    at Module._compile (internal/modules/cjs/loader.js:1137:30)[39m
[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)[39m
[90m    at Module.load (internal/modules/cjs/loader.js:985:32)[39m
[90m    at Function.Module._load (internal/modules/cjs/loader.js:878:14)[39m
[90m    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)[39m
[90m    at internal/main/run_main_module.js:17:47[39m

A: Another, little more advanced, way would be to seperate the prefix and the command.
This allows you to define a prefix without changing all .startsWith() conditions.
With Array.split() you can seperate each following word if they have whitespaces between each other.
This would end up like this:
let prefix = "*";

// Prevents any unnecessary condition checks if the message does not contain the prefix
if (!message.content.startsWith(prefix)) return;

const args = message.content.toLowerCase().split(' ');

let command = args[0];
command = command.slice(prefix.length);

if(command === "say"){
   // do whatevery you want :)
}

After it was checked that the message starts with the prefix, you split each word and then take the first one. With slicing the prefix out, you end up with only having the plain command. This allows an even better approach for checking commands since the condition doesn't include the prefix anymore.
Everything after args[0] would be additional arguments you can use for any case you want.

A: you could make a config.json.
inside your config.json
{
   "TOKEN": "",
   "PREFIX": "",
}

and then require on you bot main file and also define the client.commands and client.aliases
const config = require("./config.json");
client.commands = new Discord.Collection();
client.aliases = new Discord.Collection();

on your message event you wanna add a command handler
client.on("message", async(message) => {
    if (message.author.bot) return;
    if (!message.guild) return;
    if (!message.content.startsWith(config.PREFIX)) return;
    if (!message.member) message.member = await message.guild.fetchMember(message);

    const args = message.content.slice(config.PREFIX.length).trim().split(/ +/g);
    const cmd = args.shift().toLowerCase();

    if (cmd.length === 0) return;

    let command = client.commands.get(cmd);
    if (!command) command = client.commands.get(client.aliases.get(cmd));
    try {
    if (command)
        command.run(client, message, args);
    } catch(error) {
        console.log(error)
    }
})

after that, add a new folder call handlers and inside the handlers folder make a new file call command.js
const { readdirSync } = require("fs");

const ascii = require("ascii-table");

let table = new ascii("Command");
table.setHeading("Command", "Load Status");

module.exports = (client) => {
    readdirSync("./commands/").forEach(dir => {
        const commands = readdirSync(`./commands/${dir}/`).filter(file => file.endsWith(".js"));

        for (let file of commands) {
            let pull = require(`../commands/${dir}/${file}`);

            if (pull.name) {
                client.commands.set(pull.name, pull);
                table.addRow(file, '✅');
            } else {
                table.addRow(file, `❌  -> missing a help.name, or help.name is not a string.`);
                continue;
            }

            if (pull.aliases && Array.isArray(pull.aliases)) pull.aliases.forEach(alias => client.aliases.set(alias, pull.name));
        }
    });

    console.log(table.toString());
}

and then require on the bot main file
["command"].forEach(handler => {
    require(`./handlers/${handler}`)(client);
});

make a new folder call commands inside add new folder command category such as info
simple ping command
module.exports = {
   name: "ping",
   aliases: ["pong"],
   description: "Check Bot Ping",
   usage: "",
   run: async(client, message, args) => {
       messsage.channel.send("PONG")
   },
};

hope this guide is helpful :)


text:
Q: Reattaching to spawned process via nodejs I am creating a small proprietary game server manager in Node.js; currently it runs the game by spawning via child_process:
var server = spawn(cmd, args, { cwd: 'something' });

So long as the manager continues to run I can pipe commands and deal with the child as I would like. However, consider the possibility that my manager crashes or is closed. How would I then reattach  to the previously spawned child process (which was still running while the manager was down)? I can store pidfiles to try and reconnect based on pid; but I'm not sure how to get a child_process object with  access to the child's stdio objects.
I really would like this to be recoverable; any help is appreciated, thanks!

Please note: The game servers are proprietary, some examples are Minecraft, Source DS, etc. Assume i do not have access to the sever source.

EDIT
After reading some source code from node's child_process it looks like if you specify a property in the options called stdinStream, stdoutStream, or stderrStream it should just open a socket to it. (See lines 428 - 496). So the issue then is, how do I stop spawn from actually doing a spawn and instead just settings its values based on a specified pid and streams I pass. (I would get my stdinStream by doing fs.createWriteStream('/proc/PID/fd/0'); which should work since that fd is created as a pipe.)

A: To extend what someone said in a comment above, you may be able to use http://nodejs.org/api/net.html where each child process creates a server (net.createServer()) and you keep a list of what children are listening at what ports somewhere, and then when your master restarts, it goes and finds that list of children and connects to each their servers. The Sockets that you get from net.createConnection() replace the child_process objects in your master.
net servers and sockets implement the same Readable and Writable Stream interfaces as stdio, so after setting up and connecting, you should be able to write(...) and pipe() events like you've been doing.
This may not be the best solution but I believe it will work.

A: After speaking with some of the guys on the node project, it looks like the only way I can accomplish this is by dealing with the raw file descriptors in the proc fs. I will probably mock up something similar to a child_process object and create its streams like:
var child = {};
child.stdin = fs.createWriteStream('/proc/PID/fd/0');
child.stdout = fs.createReadStream('/proc/PID/fd/1');
child.stderr = fs.createReadStream('/proc/PID/fd/2');


text:
Q: Game Modes and Learning Curve What's the recommended learning curve on League of Legends? I mean, I'm in level 16, and for me Beginner Co-op vs AI is very easy, I can win even with a bad team.
So, I tried Normal Game (PVP), and I get a mix of wins and loses. Some players say to  touch the PVP only when I get the level 30... I thought fair because maybe I was weakening my team because I'm learning yet. In the end, I tried Intermediate Co-op vs AI and all battles were harder (IMO) than Normal Games (PVP).
In the end, I'm confused about what can I do to advance summoner levels and improve myself. It's better play Intermediate Co-op vs AI up to I find it "easy" and then tring PVP, or it's better skip it and go right to PVP? Or there are some better route to self-improve on League of Legends?

A: I'd say mix it up and keep in mind that learning a game is different process for each player. So there is no better way to do it.
To learn the game you have to:

*

*Understand the Game Mechanics as well as each Champion's mechanics.

*Understand and predict opponent player tendencies and playstyles.

*Learn to build each champion correctly.

*Learn to cooperate with your teammates.

Its obvious that by just playing coop until you get to higher levels you miss out on many of those things.
And on the other hand coop is very useful for learning your champion, trying out builds and learning to understand game mechanics.
As far as building your champion is concerned, I'd say spend some time reading guides and builds by more experienced players. Good guides always give you alternative item paths depending on your opponents. That's the main thing you have to keep in mind. You buy items to beat your opponents not to improve your champion. There's a thin line there.
Also I think it's a good tactic when you're low level to not play different champs all the time. Try to learn a champion before moving on to the next one. If you think you're doing badly with someone just leave him and try another one until you find someone that suits your playstyle. Then play lots of games with him. The reason for that is that in the beginning you want to focus on learning other stuff in game rather than a certain champion. It's better to focus on what your opponents are doing and you can't do that if you think too much about what skill to use and when.
When you think you've mastered a champion and your scores are usually good with him or you just win games with him then you can go on and find a new one.

A: From personal experience of over 6 years of MOBA gaming;
Easy AI matches are great to learn HOW to play the game. (For the super beginners)
They are also great way to easily and quickly take "First Win of The Day" Influence Points bonus.
Intermediate AI matches are a good platform to learn how to play a new hero. Use these games to learn how to perform the proper combo's with your hero of choice. To figure out just exactly how Elise's Rappel works, or Urgots Lock-On Missle Attack. These matchups are good also for map awareness and lane control. The bots perform ganking extremly well, linking together combo's with a precision that most humans have a hard time accomplishing. These matches are also good practice for warding, as if you ward properly you'll see the ganks coming and know your doing it correctly.
All bot matches are also good practice for last hitting minions.
Once those skills are down, I would move into Blind Pick games, which don't usually follow the meta, but will help you get used to playing against real people who can come up with new alternative stradegies on the fly.
AS SOON as your comfortable with all the previously mentioned factors, and have enough of a hero pool\ skill level to play ANY lane position, I would move into Draft games. Draft games are pretty much Softcore Ranked. They don't carry elo, but other than that they tend to follow meta-rules, and the players usually take themselves much more seriously. Draft games include bans, and round-robin hero picks. This allows players to learn how to counter-pick opposing heroes and how to properly ban heroes that either screw your team comp six ways to sunday or otherwise bring factors that you don't want to deal with into your game.
Obviously the final step is full on Ranked play, and you'll know when your ready for that. Or, you'll think your ready, and find out the hard way your not.
TL:DR;
Play Bots on easy to learn how to play the game, and to earn IP points for first win of the day if you don't have a lot of time.
Play Bots on intermediate how to learn play specific heroes and last hit well.
Play Blind Pick to improve your game.
Play Draft Pick to polish your game.
Play Ranked to show others they need to play Draft some more. ;-)


text:
Q: Printing html page with fixed footer with Firefox and Chrome Good afternoon people. I sux with css son I wish someone can give me a hand with this. I'm trying to print some kind of html text taken from a html page with a header and a footer. This footer has to stays on the bottom of the page, if is there a second page it should appear on the bottom on that page. Anyway, I got this fiddle to show. The html looks great but when I print the page with a pdf printer, the text overlaps the footer, but only in Firefox, if a run the fiddle on Chrome, it prints the footer below the last paragraph on the second page.
Any idea how to implement this idea?

A: In your final div, remove the position:absolute, left and top css styles. You are positioning the footer overtop of everything. The value for top would have to be manually adjusted for each browser and you probably want to stay away from that.
Here is an updated fiddle with those css styles removed from your footer div: http://jsfiddle.net/BumbleB2na/F3kSQ/2/


text:
Q: Entity Framework DateTime defaults Is there a way to automagically map a DateTime.MinValue to a null value in the data layer and vice-versa?
I am trying out EF6.  I want to eventually target SQL Server 2005 servers, so the DATETIME2 type is something I want to avoid.

A: EF does not support mapping min/max/specific values to null through mapping/fluent API. You could override SaveChanges() and inspect/update entities on save but it would be more involved

A: There two way to solve it:

*

*You can set Default Value=DateTime.MinValue for your datetime
field in model editor.

*You can set StoreGeneratedPattern=Identity for your datetime field in model editor and set default value for that field in SQL table.


text:
Q: Opening multiple Iframe in IE using javascript I have a page, where you can download files from a list. What I do to download the file, is insert an Iframe into the page, then set the source of the frame to point to the URL of the content which is to be downloaded, which of course has a content disposition depending on the file type to be downloaded, which will force the Iframe to prompt the download file dialog box.
Doing this works fine in all browsers. The problem is when inserting multiple Iframe. This is brought by the case, that the user is allowed to select a couple of files to download, then download them.
What I do to do this is insert multiple Iframe, which all have a unique source corresponding to the URL of the file they want to download. It works fine in all browsers, except in IE. What happens in IE, is that in most cases, for example, when i select 4 files to download, and I insert 4 Iframe, only 3 downloads are prompted.
What may be causing this? What could be a solution to solve this? Thank you.

A: Microsoft's Internet Explorer typically limits you to download between 2 and 4 files simultaneously, not any more. This can be quite annoying:
Internet Explorer 7 and earlier versions limit the number of files that you can download at one time to two.
Internet Explorer 8 limits the number of files that you can download at one time to six.
Internet Explorer 9 increases the connections-per-proxy limit to 12.
This is an issue on the browser it self, and can be dealt-with by the user changing the configuration:
See How do I configure Internet Explorer to download more than two files at one time?

Additionally, a .reg file can be used to set other limitations:

*

*Save this inside a file named change_ie_file_download_limit.reg.
REGEDIT4

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings]
"MaxConnectionsPer1_0Server"=dword:00000010
"MaxConnectionsPerServer"=dword:00000008

*Right click on the .reg file and click on Merge.

*Click on Run, Yes, Yes, and OK when prompted.
Note: this is applied to Windows 7, earlier versions may have different steps, but the basis is the same.


text:
Q: Using Browsersync via a Gulp Task with DDEV-local I am using DDEV as my local hosting environment, and many of my projects implement front end automation via Gulp. Browsersync is a major component to our front end set-up, and requires ports to be exposed by the DDEV container to the host machine. The problem at hand is two fold, what is the best way to expose a port to the host machine from the container, and what is the best set-up for a Browser-Sync Gulp task in a DDEV environment?

A: Exposing the Necessary Ports
Part one of this situation requires using a Docker Compose file to expose your container's port to the hose machine. Based on this Answer you need to create a docker-compose.browsersync.yaml file in your .ddev directory.
An example of that file for Browser-Sync would be as follows:
# Override the web container's standard HTTP_EXPOSE and HTTPS_EXPOSE
# This is to expose the browsersync port.
version: '3.6'
services:
  web:
    # ports are a list of exposed *container* ports
    expose:
      - '3000'
    environment:
      - HTTP_EXPOSE=${DDEV_ROUTER_HTTP_PORT}:80,${DDEV_MAILHOG_PORT}:8025,3001:3000
      - HTTPS_EXPOSE=${DDEV_ROUTER_HTTPS_PORT}:80,${DDEV_MAILHOG_HTTPS_PORT}:8025,3000:3000

We expose Port 3000 here because it is the default for Browser-Sync, but could be updated to reflect the needs of your projects.
Note: After adding this file to your .ddev directory you should restart your ddev project.
For more information on defining new services with docker compose, read the DDEV docs.
Setting-Up Browser-Sync in Gulp
This assumes you have a working gulpfile.js ready to do with your other required packages included already. If you're not fully familiar with Browser-Sync and Gulp, please refer to their docs for full details.
const browserSync = require('browser-sync').create();

/*
* Set 'url' (the host and proxy hostnames) to match the canonical url of your ddev project.
* Do not include the http/s protocol in the url. The ddev-router will route the
* host machine's request to the appropriate protocol.
*
* ex: yoursite.ddev.site
*/
const url = 'yoursite.ddev.site';

/*
* This function only includes the most basic browser-sync settings needed
* to get a watch server running. Please refer to the browser-sync docs for other
* available options.
*/
const startServer = function (done) {
    // Initialize BrowserSync
    browserSync.init({
        proxy: url,
        host: url,
        port: 3000,
    });
    done();
};

exports.startServer = startServer;

You can test this using gulp startServer after initial set-up. Gulp will output a http as the External URL for testing. However thanks to the ddev-router it can be accessed via http or https.

A: Exposing Port 3000 for HTTP & HTTPS for BrowserSync
piggy-backing on the answer from @TXChetG and the answer from @Mario Hernandez
create a file called "docker-compose.browsersync.yaml" inside your hidden /.ddev/ config folder with code below, tabbed properly (which is very important), then run the command "ddev restart"
# Override the web container standard HTTP_EXPOSE and HTTPS_EXPOSE
# This is to expose the browsersync port.
version: '3.6'
services:
  web:
    # ports are a list of exposed *container* ports
    expose:
      - '3000'
    environment:
      - HTTP_EXPOSE=${DDEV_ROUTER_HTTP_PORT}:80
      - HTTPS_EXPOSE=${DDEV_ROUTER_HTTPS_PORT}:80

A: If you are a mac user and browsersync still doesn't work with the above solution, you might need to update your /etc/hosts file as I had to.
You can check more details in this answer.

A: I was unable to run browsersync from within the container.  I updated my local system and ran browsersync locally
I used Stephen's solution elsewhere on this page (https://stackoverflow.com/a/70190271/18779 for quick reference).
I am running a Mac so I also did the following:

*

*Upgrade homebrew

*Use brew to install nvm

*Use nvm to install node 12 (I had to try a few versions to eliminate errors.  12 worked for me.

*Use npm to rebuild node-sass.  I got sass errors before I did this.

*run browsersync.  I am using Drupal and Radix subtheme so, for me, that was cd [subtheme dir] and npm run watch

A: The above tips and from other posts like:
Using Docker Compose to expose DDEV web container ports to host machine
Chrome can't open localhost:3000 with Gulp / BrowserSync
may be fine for a website on the HTTP protocol but not for one on HTTPS.
Specifically, I am testing a CMS installation in DDEV, with secure URLs in the Frontend/Backend. After running the ddev start command, it is displayed that I access it in the browser using https://myproject.ddev.site or https://127.0.0.1:62751 (the socket changes with each run of DDEV).
I didn't install drud/ddev-browsersync package because it doesn't proxy to HTTPS, in my case it didn't help me at all.
In a directory I created the gulpfile.js file to perform complex tasks on scss, js, css, html files. In order not to manually reload the page in the browser, I obviously need BrowserSync. The only configuration that worked is the following:
const browserSync = require('browser-sync').create();

function startServer () {

    browserSync.init({
      proxy: 'https://127.0.0.1:62751',
    });
};

exports.startServer = startServer;

When I run the gulp startServer command, first https://localhost:3002 is displayed in the address bar, then after a while it redirects to https://myproject.ddev.site. From this moment on, I make any changes to the files.
The only issue I have is that after each run of the ddev start command I have to manually change the port in the line https://127.0.0.1:XXXXX. If DDEV provides this value I could use it and then the issue is solved.


text:
Q: I want to make photo near my text putted in square, how can center it? I want to make the part of my site centered,there is one img and text putted in square,but also it should be responsive, here is my css and html codes:
#part1{
    padding-bottom:100px;
    margin:auto;
    overflow:hidden;
    width:80%;
}

#part1 h1{
    text-align:center;
    font-size:250%;
    padding-top:35px;
}

#part1 p{
    text-align:center;
    font-size:110%;
    padding:30px;
    background-color:#F0F8FF;
    margin-top:60px;
    width: 40%;
    height: 60%;
    float:left;
}

#part2 h1{
    text-align:center;
    font-size:250%;
}

and html:

About

Accommodation in comfortable guest houses made of river stone on the shore of the lake, the possibility of constant communication with animals,
 horseback riding through endless meadows, the possibility of developing a life, ecological food from the products of one's own farm and unity with the spirit of the village, this is agro-tourism in Zagatala.
 Those who wish can walk to domestic cows, cook cottage cheese, mow hay and much more.

Eco-farm "Lake of Hope" is, first of all, an ecologically clean, healthy and congenial holiday, which highly appreciates the level of noise and bustle of the general population.

A: I believe the site you've posted uses css flexbox to deal with responsive design and div alignment. You can learn about this here https://css-tricks.com/snippets/css/a-guide-to-flexbox/.
.about-center {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

This should do the trick.
To make it responsive you can use flex-wrap property to make the content inside the .about-center class wrap so that the text will be on top of the image when the width of the screen shrinks.

A: using CSS grid, we don't need a lot of code, and it will also be responsive always!
useful docs:

*

*CSS grid: https://developer.mozilla.org/en-US/docs/Web/CSS/grid

*grid-template-columns: https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-columns

*object-fit: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

*place-items: https://developer.mozilla.org/en-US/docs/Web/CSS/place-items

.about-center {
  display: grid;
  /* 50% 50% */
  grid-template-columns: 1fr 1fr;
  /* centering */
  place-items: center;
  /* 1gap between items */
  gap: 1rem;
  /* padding */
  padding: 0.5rem;
  /* for debugging purposes, delete this */
  border: 1px solid red;
}

/* responsive image */

.about-center img {
  width: 100%;
  height: 100%;
  /* make image not stretch */
  object-fit: cover;
}

About

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Est eaque aspernatur soluta non, pariatur adipisci labore? Voluptatibus quis repellat placeat ex debitis. Quia, perspiciatis commodi tempora odio saepe praesentium beatae!


text:
Q: Maya Python error new to python. Just started a rigging class that is starting to get into scripting. I found a practice for python and I am having trouble with an error.
import maya.cmds as cmds
stockPath = "C:\Users\Dryan\Desktop\table.csv"
f = open(stockPath)
data = f.read()
f.close()
print data

This is the error I get.
> # Error: line 1: IOError: file <maya console> line 4: 22 #

Again this is just a practice to get the file of number to print in the script editor. Thank you for any help.

A: The likeliest problem is that you're using backslashes in your file name, so they get interpreted as control characters.  The IO error is because the filename is mangled.
try
stockPath = "C:\\Users\\Dryan\\Desktop\\table.csv"  # double slashes to get single slashes in the string

or
stockPath = "C:/Users/Dryan/Desktop/table.csv"  # it's more python-y to always use right slashes.

A: As joojaa said, try to avoid using backslashes when you can. I try to always convert any incoming path to a forward slashes version, and just before outputting it I normalize it using os.path.normpath.
clean_path = any_path_i_have_to_deal_with.replace("\\", "/")
# do stuff with it
# (concat, XML save, assign to a node attribute...)
print os.path.normpath(clean_path) # back to the OS version


text:
Q: How to import from custom Python modules on new Lego Mindstorms Robot Inventor I have been using the new LEGO® MINDSTORMS® Robot Inventor.
When creating a new "Project", the said project seems to contain a single file. However, at the start of every sample code file, one can see that the mindstorm modules are imported, like so:
from mindstorms import MSHub, Motor, MotorPair, ColorSensor, DistanceSensor, App
from mindstorms.control import wait_for_seconds, wait_until, Timer
from mindstorms.operator import greater_than, greater_than_or_equal_to, less_than, less_than_or_equal_to, equal_to, not_equal_to
import math

Does anybody know how can I create my own modules, and import them into a given project? Is it possible?

A: Update 2022-02-21
After getting back into this, the original solution no longer works. Lego changed the directory structure for projects. Each upload creates:

*

*a random number directory with projects

*a __init__.mpy file which is the compiled version of your sent code

The above means that we can no longer read from the uploaded code to run. What we can do instead is create files elsewhere on the file system to get our code to persist.
For example, this MVP will achieve what you need:

*

*Upload the following:
content = """
__version__ = "0.1.1-20220221"

def hello() -> None:
    print("hello from {}".format(__version__))
"""

f = open("mindstorms/custom.py", "w")
f.write(content)
f.close()

*Create a second project with the following:
from mindstorms.custom import hello

hello()

The previous solution was brittle, and I'm unsure when the change that broke it actually occurred. I've tested this on Hub OS 3.1.43 and it works. I do not like this solution, since you're just writing out the file and it makes it a little worse for editing, but at least this is fine.
Why mindstorms.custom? That seems like a fine place to put your own custom functionality, it is unlikely to be overwritten by the official Mindstorms distribution, and centralizes all of the code in one place. You could create your own directory off of root and put the file(s) there, but for the sake of ease-of-use, let's just do this.
As before, keeping the older answers below.

EDIT: spent some more time on this, and figured it out! I'm keeping the original answer below. Here's a short reproducible solution. Tested working with (taken from os.uname)
sysname='LEGO Technic Large Hub'
nodename='LEGO Learning System Hub'
release='1.11.0'
version='v1.11-1139-gf7407e5a0 on 2020-06-19'
machine='LEGO Technic Large Hub with STM32F413xx'

*

*Create a new python project with this content:
import os
import sys

def example() -> None:
    print("imported")

# EOF

# upload the module to the Hub
print("beginning upload from {}...".format(__name__))
os.chdir("projects")
open("__init__.py", "w").close()
filename = "{}.py".format(__name__.split("/")[-1])
new_filename = "mystorms.py"
try:
    os.remove(new_filename)
except:
    print("{} does not exists".format(new_filename))
os.rename(filename, new_filename)
# remove everything after EOF
with open(new_filename, "r") as f:
    content = f.read()
content = content.split("# EOF")[0]
with open(new_filename, "w") as f:
    f.write(content)
print(os.listdir())

sys.exit()

The stuff after # EOF does the actual "uploading" and ensures that when you try to import this elsewhere, you don't re-"upload" it. Note that, in regular python, you'd wrap this in if __name__ == "__main__", but Mindstorms doesn't use that convention when it's running.

*Send that project to your Hub and run it. Note that you'll have those files that persist on your Hub, and I have no idea if there are memory constraints that you'll need to worry about.

*Create a new python project with the following:
import os

import projects.mystorms as ms

print(os.uname())
ms.example()

The above should work. Note that if you need to update the file, you'll have to adjust the module code to delete the original if it exists, but that's a minor change. I have not done anything beyond the above, but this could lead to a way to get missing stdlib stuff into Mindstorms as well.

Haven't found a solution, but I did go through most of the standard library to see what else you can import which is kind of related... The below did not throw an error, but I have not yet attempted anything with the packages themselves.
import array
import builtins
import cmath
import ctypes
import errno
import gc
import hashlib
import heapq
import io
import json
import math
import os
import random
import re
import select
import struct
import sys
import time

The underlying theme seems to be limiting access to the filesystem and forcing any async operations to be done with the actual Mindstorms methods (e.g. hub.speaker.start_beep() and the like). There is some directory structure (the 0-19 files), but I haven't figured out if that can be used to achieve what you need.
Also interesting to note is that you can't import typing, but you can use type hints in your functions. I also strongly dislike that you can't copy-paste from the console.


text:
Q: unable to print single record instead of getting multiple records in crystal report and Linq i want to print 1 single record or single registered student details in the crystal report. but here im getting multiple records. how to write code to get single record/ latest record of the table
    StudentDBEntities db = new StudentDBEntities();
    CrystalReportProduct cr = new CrystalReportProduct();
    cr.SetDataSource(db.Students.Select(p => new
    {
        sno = p.sno,
        name =p.sname,
        phone=p.phone,
        email = p.email,
        course = p.course,
        date=p.date,
        paymentmode=p.paymentMode,
        amount=p.amount

    }));

    this.CrystalReportViewerProduct.ReportSource = cr;
    this.CrystalReportViewerProduct.DataBind();

A: Use OrderByDescending(p => p.sno) to sort by sno, and then Take(1):
cr.SetDataSource(db.Students.Select(p => new
{
    sno = p.sno,
    name =p.sname,
    phone=p.phone,
    email = p.email,
    course = p.course,
    date=p.date,
    paymentmode=p.paymentMode,
    amount=p.amount

}).OrderByDescending(p => p.sno).Take(1));


text:
Q: How to run a Flask command from Python code and capture output? I have a bunch of custom commands in a Flask project. Those can be run from shell, e.g.
$ flask create-user admin

I also need to run the commands (and capture any output) directly from Python code. How can I do that? I would like to avoid spawning subprocesses, if possible.


text:
Q: JS replace() returns ,,,,,,, instead of a number with a comma the following code is a converter from euro to dollar in JS. It is a JS function.
eingabe = input, ausgabe = output.
If I execute this code I get ,,,,,,,, as an output instead of 1,37.
eingabe = eingabe.replace(/,/g, ".");
eingabe = parseFloat(eingabe);
var kurs_euro = 1.37 // 1 euro = 1,37 dollar
var ausgabe = 0;
ausgabe = eingabe * kurs_euro;
ausgabe = Math.round((ausgabe + 0.00001) * 100)/100 + " Dollar";
ausgabe = ausgabe.toString();
ausgabe = ausgabe.replace(/./g, ",");
alert(ausgabe);

A: /./ means that you use regex and . replaces any character. Try without regex:
ausgabe.replace('.', ',');

Or escape .:
ausgabe.replace(/\./g, ',');


text:
Q: npx create-react-app myapp not creating project Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

core-js@2.6.11 postinstall C:\Users\HI\appvid\node_modules\babel-runtime\node_modules\core-js
  node -e "try{require('./postinstall')}catch(e){}"
core-js@3.6.5 postinstall C:\Users\HI\appvid\node_modules\core-js
  node -e "try{require('./postinstall')}catch(e){}"
core-js-pure@3.6.5 postinstall C:\Users\HI\appvid\node_modules\core-js-pure
  node -e "try{require('./postinstall')}catch(e){}"

*

*react@16.13.1

*react-scripts@3.4.1

*react-dom@16.13.1

*cra-template@1.0.3
added 1606 packages from 750 contributors and audited 931196 packages in 626.818s

58 packages are looking for funding
  run npm fund for details
found 0 vulnerabilities

A: Have you tried using the create-react-app (folder-name) command instead of using the npx create app command? Is it installed globally? What exactly do you write on the terminal?


text:
Q: How can I specify with flexbox that two divs have to break line together? How can I specify with flexbox that two divs have to break line together? What I'd like in the example bellow is that, when screen gets smaller, the green and the black divs always jump to a new line together without having to nest them in a new div which will complicate and extend the code.

.categories-home-block {
        display:flex;
        width: 100%;
        flex-direction: row;
        flex-wrap: wrap;
        align-content: space-between;
        justify-content: space-between;
        align-items: center;
        margin: 10px -8px;
    }
    .category-home-card {
        flex-grow: 1;
    }
    .category-home-pic{
        width: auto;
        margin: 25px 5px;
        height: 400px;
        min-width: 200px;
        background-repeat: no-repeat;
        background-position: center;
        background-size: cover;
    }
    .category-home-pic-1 {
        margin-left: 0;
        background-color:red;
    }
    .category-home-pic-2 {
        background-color:blue;
    }
    .category-home-pic-3 {
        background-color:yellow;
    }
    .category-home-pic-4 {
        background-color:green;
    }
    .category-home-pic-5 {
        margin-right: 0;
        background-color:black;
    }
    .category-home-link {
        justify-content: center;
        text-align: center;
    }
    .category-home-link a {
        font: normal 400 18px/22px Montserrat, sans-serif;
        text-decoration: none;
        color: #252a32;
    }

A:

.categories-home-block {
        display:flex;
        width: 100%;
        flex-direction: row;
        flex-wrap: wrap;
        align-content: space-between;
        justify-content: space-between;
        align-items: center;
        margin: 10px -8px;
    }
    .category-home-card {
        flex-grow: 1;
    }
    .category-home-pic{
        width: auto;
        margin: 25px 5px;
        height: 400px;
        min-width: 200px;
        background-repeat: no-repeat;
        background-position: center;
        background-size: cover;
    }
    .category-home-pic-1 {
        margin-left: 0;
        background-color:red;
    }
    .category-home-pic-2 {
        background-color:blue;
    }
    .category-home-pic-3 {
        background-color:yellow;
    }
    .category-home-pic-4 {
        background-color:green;
    }
    .category-home-pic-5 {
        margin-right: 0;
        background-color:black;
    }
    .category-home-link {
        justify-content: center;
        text-align: center;
    }
    .category-home-link a {
        font: normal 400 18px/22px Montserrat, sans-serif;
        text-decoration: none;
        color: #252a32;
    }
    /* shaping flex-green-black  */
    .flex-green-black {
        display: flex;
        flex-wrap:wrap;
    }


text:
Q: Does golang support TCP simultaneous open? Does go standard "net" package support TCP simultaneous open? I mean two hosts actively open a tcp connection to each other and build one connection. I used net.Dialer and Dial but got connection refused.

A: Simultaneous open isn't a feature, but rather something that can happen if two clients try connecting to each other at the same time. So Go supports this just by virtue of supporting the normal TCP operations. The reason you're probably getting connection refused is that the timing has to be very precise. Both sides have to register their handlers with the kernel before the other side's SYN arrives. For two clients on the same network (say in the same building or on the same campus), this latency will be incredibly low, and the window will thus be very small (a few tens of milliseconds at most).


text:
Q: How do I execute another script using command handler? I've been struggling on this for a while, now but I'm struggling at executing child process JavaScript file.
Basically, I've created a command handler for my discord bot  so, every command has its on file which it executes, which looks like this.

module.exports = {
  name: 'bot',
    description: "Executes bot.js",
    execute(message, args) {   //I want to execute bot.js in same directory in another folder
      }
}

There's another JavaScript in the same directory in another folder called bot.js. I basically want to call that function and execute and bring back a variable.
Unsure how to do that.

A: Nodejs has a built-in module called VM.


text:
Q: Angular prevent multiple token refresh on asynchronous requests All my http requests go through the custom HttpService. This service refreshes the token when it's expired before sending the request.
It works fine but it refreshes the token multiple times if the loaded page has multiple http requests. For example, if the page has 10 requests through the services, this means 10 times token refresh.
I've tried to describe this by sample code:
loaded page and used services
export class Page1 implements OnInit {
    constructor(
        private service1: Service1,
        private service2: Service2
    ) { }

    ngOnInit() {
        this.service1.getData...
        this.service2.getData...
    }
}

@Injectable()
export class Service1 {
    constructor(
        private httpService: HttpService
    ) {}

    getData(): Observable<any> {
        return this.httpService.get(.....)
            .map((response: Response) => {
                return response.json();
            });
    }
}
@Injectable()
export class Service2 {
    constructor(
        private httpService: HttpService,
        private service1: Service1
    ) {}

    getData(): Observable<any> {
        return this.httpService.get(.....)
            .map((res: Response) => res.json().response)
            .flatMap((newItem: Item) => {
                    this.service1.getData(...)
            });
    }
}

custom http service
@Injectable()
export class HttpService extends Http {

    constructor (backend: XHRBackend, options: RequestOptions) {
        .............
    }

    request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {

        ................

        if(tokenNotExpired('access_token')){ // if token is NOT expired

            return super.request(url, options);

        }else{  // if token is expired

            return this.updateToken()
                .flatMap((result: boolean) => {
                    return this.request(url, options);
            });
        }
    }

    updateToken(): Observable<boolean> {

        // set the new token
        .....

    }
}

How can I perevent the token refresh per request by setting these requests in que and send them only when the new token is ready?
Note: I don't know if it's matter but the service requests can be combined by flatMap or forkJoin....
Update 1
I've updated my code according to @bviale's answer.
request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {

    ................

    if(tokenNotExpired('access_token')){ // if token is NOT expired

        return super.request(url, options);

    } else {  // if token is expired

        // There is already a call to updateToken() in progress,
        // wait for it to finish then process the request
        if (this.updateTokenPromise) {
            return Observable.fromPromise(return this.updateTokenPromise.then(() => {
                return this.request(url, options);
            }));
        }
        // Start to call updateToken(), then resolve the promise
        else {
            this.updateTokenPromise = new Promise((resolve, reject) => {
                this.updateToken().toPromise()
                    .then((result: boolean) => {
                        resolve(result);
                    });
            });

            return Observable.fromPromise(return this.updateTokenPromise.then(() => {
                return this.request(url, options);
            }));
        }
    }
}

My updated request() method perfectly stops the requests, invokes the updateToken() only one time, gets the token, and then calls the requests but for each request I get the following error now:

I've noticed that the service calls returns the following response which ofcourse will cause e.json is not a function exception:
Object { _isScalar: false, source: Object, operator: Object }

I think this is also something I need to cast?

A: You can create your own Promise when you call updateToken() like this :
@Injectable()
export class HttpService extends Http {

    private updateTokenPromise: Promise<any>;

    constructor (backend: XHRBackend, options: RequestOptions) {
        .............
    }

    request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {

        ................

        if(tokenNotExpired('access_token')){ // if token is NOT expired

            return super.request(url, options);

        } else {  // if token is expired

            // There is already a call to updateToken() in progress,
            // wait for it to finish then process the request
            if (this.updateTokenPromise) {
                return this.updateTokenPromise.then(() => {
                    return this.request(url, options);
                });
            }
            // Start to call updateToken(), then resolve the promise
            else {
                this.updateTokenPromise = new Promise((resolve, reject) => {
                    this.updateToken()
                        .then((result: boolean) => {
                            resolve(result);
                        });
                });

                return this.updateTokenPromise.then(() => {
                    return this.request(url, options);
                });
            }
        }
    }

    updateToken(): Observable<boolean> {

        // set the new token
        .....

    }
}

This way you won't have multiple parallel calls of updateToken()