text:
Q: Sqlite Agregar una llave foránea a una tabla ya existene Voy adicionar una llave foránea en la tabla participa. Pero me arroja el error:
(sqlite3.OperationalError) near "FOREIGN": syntax error
El codigo de alteración que estoy ejecutando es
ALTER TABLE Participa ADD FOREIGN KEY(rut) REFERENCES Persona(rut);

A: Aunque la sintaxis para agregar una restrcción de clave foránea a una tabla que ya existe en SQL-92 es:
ALTER TABLE NombreTabla
ADD CONSTRAINT NombreRestriccion
FOREIGN KEY (Columna1, ... ,ColumnaN)
REFERENCES NombreTablaReferencia(ColumnaF1, ..., ColumbaFN);

Sqlite no soporta la creación de restricciones de clave foranea mediante sentencia de alteración (ALTER TABLE) https://www.sqlite.org/omitted.html
Por lo que para obtener una clave foranea debe:

*

*Crear en una tabla temporal una copia de los datos de la tabla sobre la cual desea crear la clave foránea (Esto, si tiene ya datos en dicha tabla).

*Eliminar (DROP TABLE) la tabla sobre la cual desea crear la clave foranea

*Crear una nueva tabla con el mismo nombre de la tabla en la que deseaba crear la foranea inicialmente; ahora agregando la definición de la clave foranea durante la creación con la siguiente sintaxis

CREATE TABLE NombreTabla (
   -- Definición de Colomnas
   , CONSTRAINT NombreRestriccionGoranea
     FOREIGN KEY (Columna1, ..., ColumnaN)
     REFERENCES NombreTablaReferencia(ColumnaF1, ..., ColumnFN)
)

Con lo que se crea una restricción de clave foránea en la tabla NombreTabla que garantiza que para cada fila de dicha tabla que tiene valores no nulos en sus columnas Columna1 a ColumnaN existe una fila en  la tabla NombreTablaReferencia cuyas columnas ColumnaF1 a ColulimnaFN contienen los mismos valores.
Para cumplirse esta última condiciòn solo se requiere que la tabla NombreTablaReferencia tenga una clave primaria (PRIMARY KEY) , clave única (UNIQUE) o índice único (UNIQUE INDEX) sobre el conjunto de columnas ColunnaF1 a ColumnaFN de la tabla NombreTablaReferencia
Para su caso particular la re-reación de la tabla:
CREATE TABLE Participa (
    --Definicion de Columnas
    , CONSTRAINT NombreForanea
      FOREIGN KEY(rut)
      REFERENCES Persona(rut)
);

*Volver a poblar los datos de la nueva tabla con los datos de la tabla temporal que se obtuvo como copia inicialmente

Cabe anotar que si la tabla que referencia (en su caso particular Persona) no cumple las condiciones de que sea clave única, debe proceder a re-crearla del mismo modo porque la creación de claves primarias por alteración tampoco es sopprtado por Sqlite


text:
Q: Bundle enterprise library instead of installing does anybody know if it's possible (or have experience doing so) to simply bundle the microsoft enterprise library components in a .net solution instead of performing the installation?  I'm trying to avoid putting a customer through the installation step.
Thanks for your response!!  :-)

A: Yes, it's possible. If you look at SCSF you will see that SCSF wizards creates a /Lib directory full of entlib dlls and all of the project of this solution references they.
There is the list of /Lib (of course you should exclude SmartClient assemblies):
Microsoft.Practices.CompositeUI.dll
Microsoft.Practices.CompositeUI.WinForms.dll
Microsoft.Practices.CompositeUI.WPF.dll
Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.EnterpriseLibrary.Data.dll
Microsoft.Practices.EnterpriseLibrary.Data.SqlCe.dll
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.dll
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.dll
Microsoft.Practices.EnterpriseLibrary.Logging.dll
Microsoft.Practices.ObjectBuilder.dll
Microsoft.Practices.SmartClient.ConnectionMonitor.dll
Microsoft.Practices.SmartClient.DisconnectedAgent.dll
Microsoft.Practices.SmartClient.EndpointCatalog.dll
Microsoft.Practices.SmartClient.EnterpriseLibrary.dll

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set theme in fragment extends BottomSheetDialogFragment? I have an app in which i have a MainActivity which contains a fragment that extends BottomSheetDialogFragment. What I want to set fragment theme but it remains same.Pls help
Code for fragment that extends BottomSheetDialogFragment:-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/bottomSheet"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:theme="@style/CoffeeDialog">

<de.hdodenhof.circleimageview.CircleImageView
    android:id="@+id/img_Camera"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_gravity="center_horizontal|bottom"
    android:layout_marginTop="10dp"
    android:src="@drawable/amazon"
    app:civ_border_color="@color/textColor"
    app:civ_border_width="5dp"
    app:civ_fill_color="@color/colorPrimary" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/notification_list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="8dp" />

<FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="30dp">

</FrameLayout>

here i am using android:theme="@style/CoffeeDialog" but it's not working.
Code for theme:-
  <style name="CoffeeDialog" parent="Theme.Design.Light.BottomSheetDialog">
    <item name="android:windowCloseOnTouchOutside">false</item>
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:colorBackground">@android:color/transparent</item>
    <item name="android:backgroundDimEnabled">true</item>
    <item name="android:backgroundDimAmount">0.3</item>
    <item name="android:windowFrame">@null</item>
    <item name="android:windowIsFloating">true</item>
</style>

Note:- I only want to change fragment theme, not MainActivity.

A: In your fragment add your theme with the getTheme method
like this:
override fun getTheme(): Int {
        return R.style.CustomBottomSheetDialog
    }

A: Try below-given code
 public class CustomDialogFragment extends BottomSheetDialogFragment {

      @Override
      public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NORMAL, R.style.CoffeeDialog);
      }

      ...
    }

CoffeeDialog will be the theme added to your styles.xml


text:
Q: How to get the inializers of global variables with LLVM API I'm writing an LLVM pass which works on the LLVM IR code. A part of the objective is to read the initial values of global variables, where global variables could be of any type, from basic types to structs and classes. How do I achieve that?

A: If you invoke getInitializer on a GlobalVariable instance you get the initializer, of type Constant (though make sure you call hasInitializer or one of its sister methods first, to verify there's an initializer at all). Also IIRC global variables and constant are implemented as the same thing, so use isConstant to filter out the constants if you don't want them.
Of course, a Constant is the abstract base class; the actual type will be one of its children, which you can see in the diagram presented on the documentation page. You can query and get the actual constant type in the usual way, via isa / cast / dyn_cast, or you can use getType on it (a constant is a Value after all) and work from there.
Finally, to get all the global variables from a Module use either the global_begin/global_end iterators, or just use getGlobalList on it (it has its own iterator).


text:
Q: How to add html code to $newnode->setAttribute How can i add some html code to a $newnode->setAttribute
This is the code of my node
$newnode->setAttribute("name",$row2['sitename']);

Now i want something like this
$newnode->setAttribute("name",$row2['sitename']);

Thanks for any help or links to sites where i can search for an solution

A: The 'name' attribute is used for form controls (e.g. an input element), but it looks like you want to actually create a link element instead. Here's an example of that, where $doc is your document object:
$newNode = $doc->createElement("a",$row2['sitename']);
$newNode->setAttribute("href","link.php?id=".$row2['id']);

Once appended to your DOM tree, the expected output of the element would be something like:
yoursitename

A: Thanks for all the help.
I have now the solution and here is it complete
xml.php
    // ADD TO XML DOCUMENT NODE
  $node = $dom->createElement("marker");
  $newnode = $parnode->appendChild($node);
  $newnode->setAttribute("name",$row2['sitename']);
  $newnode->setAttribute("address", $row['formatted_adress']);
  $newnode->setAttribute("lat", $row['lat']);
  $newnode->setAttribute("lng", $row['longi']);
  $newnode->setAttribute("id", $row2['id']);
}

javascript google maps code
downloadUrl("xml.php", function(data) {
    var xml = data.responseXML;
    var markers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) {
      var name = markers[i].getAttribute("name");
      var address = markers[i].getAttribute("address");
      var type = markers[i].getAttribute("type");
      var site_id = markers[i].getAttribute("id");
      var point = new google.maps.LatLng(
          parseFloat(markers[i].getAttribute("lat")),
          parseFloat(markers[i].getAttribute("lng")));
      var html = "" + name + "
" + address + "
 more...
";
      var icon = customIcons[type] || {};
      var marker = new google.maps.Marker({
        map: map,
        position: point,
        icon: icon.icon
      });
      bindInfoWindow(marker, map, infoWindow, html);
    }
  });
}


text:
Q: How do I call a method from a different class in my current class. AS3 I have a class, my document class, called SilkRoadTweeter.as
I also have a class called User.as
In my User class I need to call a method called nonce()
I have tried this,
trace(SilkRoadTweeter(root).nonce());

But I get the error,
TypeError: Error #1009: Cannot access a property or method of a null object reference.

A: Edit
I actually forgot one of the most important one, you could dispatch en event!
     //In the Document class
     var user:User = new User();
     user.addEventListener( "nonce" , nonceEventListener );

     //define your listener
     private function nonceEventListener(event:Event):void
     {
        user.result = this.nonce();
     }

     //In the User class
     public function result(value:Number):void
     {
        //here you deal the generated Number
      }

      //somewhere in the Class
     this.dispatch( new Event("nonce") );

End of Edit
You should pass your instance of SilkRoadTweeter in the User class
For instance:
    //In the Document class
    var user:User = new User( this );

    //In the User class
    var srt:SilkRoadTweeter;

    public function User( srt:SilkRoadTweeter )
    {
       this.srt = srt;
       srt.nonce();
    }

If the User class instance is added as a child of the SilkRoadTweeter class, you could also
do this
    //In the User class
    var srt:SilkRoadTweeter;

    public function User()
    {
        addEventListener(Event.ADDED , addedListener );
    }

    protected function addedListener(event:Event ):void
    {
         srt = this.parent as SilkRoadTweeter;
         srt.nonce();
    }

A: You said that the nonce() function is in the SilkRoadTweeter class and you need to call it from the User class. You must have a reference to the SilkRoadTweeter in order to call functions on it. The error is saying it doesn't know what a SilkRoadTweeter is.  Using root to get a reference is messy in my opinion and should be avoided. I would suggest passing a reference to the User class when you create it. If that is not an option, making the function nonce() on the SilkRoadTweeter class static would solve your problem, so long as the function doesn't need to access non-static properties of the SilkRoadTweeter. You said all it does is return a generated number so I would guess it doesn't need to access non-static properties. I can elaborate further on what I've said if your still confused.

A: In this case "root" is probably null.
Try debugging it to check.

A: try:
trace(root is SilkRoadTweeter)

I have feeling you need to do:
trace((root.getChildAt(0) as SilkRoadTweeter).nonce());


text:
Q: ReactJS : Edit Textbox which has already value in it I am new to ReactJS. I am stuck in one problem. I get textbox value from calling API which has predefined value. but When I try to edit its value then it is not letting me to edit.

class TextEditor extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      emailIdValue: ""
    };
  }

  onKeyPress = e => {
    const regEx = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

    if (e.target.value === "" || !regEx.test(e.target.value)) {

    } else {
      this.setState({
        emailIdValue: e.target.value
      });
    }
  };

  render() {
    return (

        <input
          type="text"
          value="this.props.getValue"
          onChange={e => this.keyPress(e)}
        />

    );
  }
}

I get abc@xyz.com in this.props.getValue .
How can I edit the textbox value.
Any help would be great.
Thank You.

A: You can put the this.props.getValue value in the TextEditor component state when you create it and change that instead:
class TextEditor extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      emailIdValue: props.getValue
    };
  }

  // ...

  render() {
    return (

        <input
          type="text"
          value={this.state.emailIdValue}
          onChange={this.onKeyPress}
        />

    );
  }
}

A: I guess you've found the answer. But I created this small fiddle to help anyone who have same problem. You have following problems in your code.
value="this.props.getValue" this is not right way to do this. You are setting value equal to string not equal to expression. It should be like this value={this.props.getValue}
secondly, you were referring wrong function name on onChange event. It should be like this onChange={e => this.onKeyPress(e)}
In the end, like @Tholle said, you can set your state value with your props. And then set the value of text box from state so that whenever you'll write something, state will udpate and so will be your textbox value.
Following Code Sand Box will help you.
CodeSandBox


text:
Q: Is there a way to plot two cartopy maps as subplots in the same figure? I have attempted to achieve this following the code provided at the end of this page.
What I have tried is the following:
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(24, 10))
fig.suptitle('Comparison of 1970-2000 and 2070-2100 Soil Moisture Content')
ax1 = plt.axes(projection=ccrs.PlateCarree())
ax1.set_title('Under SSP245 Scenario')
cf1 = ax1.contourf(lon_hist, lat_hist, mrsos_change45, transform=ccrs.PlateCarree(), cmap='BrBG')
fig.colorbar(cf1, ax=ax1)
ax1.set_aspect('equal', adjustable=None)
ax1.add_feature(ctp.feature.BORDERS, linestyle='-', alpha=1)
ax1.coastlines(resolution='10m')
ax1.add_feature(ctp.feature.OCEAN, zorder=100, edgecolor='k')
ax1.coastlines()
ax1.gridlines(draw_labels=True)

ax2 = plt.axes(projection=ccrs.PlateCarree())
ax2.set_title('Under SSP585 Scenario')
cf2 = ax2.contourf(lon_hist, lat_hist, mrsos_change85, cf1.levels, transform=ccrs.PlateCarree(), cmap='BrBG')
fig.colorbar(cf2, ax=ax2)
ax2.set_aspect('equal')
ax2.add_feature(ctp.feature.BORDERS, linestyle='-', alpha=1)
ax2.coastlines(resolution='10m')
ax2.add_feature(ctp.feature.OCEAN, zorder=100, edgecolor='k')
ax2.coastlines()
ax2.gridlines(draw_labels=True)

plt.show()

But this only produces one the second of the two cartopy maps that I am trying to produce.
Unfortunately, I am unable to provide the data I am using as it is very large data files. But can anyone see mistakes in the code that stops it from producing the first one?

A: You create ax1 and ax2 then destroy/redefine both ax1 and ax2 in your code. The solution is creating them correctly in the first place, and do not redefine them.
# modified code (relevant parts only)

import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import cartopy

# Use subplot_kw to declare the projection
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(24, 7), subplot_kw={"projection": ccrs.PlateCarree()})
fig.suptitle('Comparison of 1970-2000 and 2070-2100 Soil Moisture Content')

#ax1 = plt.axes(projection=ccrs.PlateCarree())  #this destroys/redefines ax1
ax1.set_title('Under SSP245 Scenario')
#cf1 = ax1.contourf(lon_hist, lat_hist, mrsos_change45, transform=ccrs.PlateCarree(), cmap='BrBG')
#fig.colorbar(cf1, ax=ax1)
ax1.set_aspect('equal', adjustable=None)
ax1.add_feature(cartopy.feature.BORDERS, linestyle='-', alpha=1)
#ax1.coastlines(resolution='10m')
ax1.add_feature(cartopy.feature.OCEAN, zorder=100, edgecolor='k')
ax1.coastlines()
ax1.gridlines(draw_labels=True)

#ax2 = plt.axes(projection=ccrs.PlateCarree())  #this destroys/redefines ax2
ax2.set_title('Under SSP585 Scenario', fontsize=14, va='bottom', backgroundcolor="white")
#cf2 = ax2.contourf(lon_hist, lat_hist, mrsos_change85, cf1.levels, transform=ccrs.PlateCarree(), cmap='BrBG')
#fig.colorbar(cf2, ax=ax2)
#ax2.set_aspect('equal')
ax2.add_feature(cartopy.feature.BORDERS, linestyle='-', alpha=1)
#ax2.coastlines(resolution='10m')
ax2.add_feature(cartopy.feature.OCEAN, zorder=100, edgecolor='k')
ax2.coastlines()
ax2.gridlines(draw_labels=True)

plt.show()


text:
Q: Decompress GZIP string response from a PHP server in NodeJS I have an existing PHP code that is doing a curl request to a 3rd-party PHP server.
The 3rd-party server returns a GZIP string.
In PHP, I can use gzdecode to decode the gzip string.
How can I do it in NodeJS/Javascript? I tried using decompress-response with no avail.
Also tried using got instead of request, enabled auto-decompress, also doesn't work.
Edit: Also tried zlib and pako, also doesn't work.
Sample Code [ PHP ]
$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => $params,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 3000000,
    CURLOPT_ENCODING  => '',
    CURLOPT_CUSTOMREQUEST => "GET",
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);
if ($err) {
   echo false;
} else {
   $response = gzdecode($response);
   echo $response;
}

A: This is the solution that works for me.
I used got instead of axios because I can't get it to work there.
I set my request options:
const requestOptions = {
    encoding: null, // this is important
    headers: {
        "Accept-Encoding": "gzip",
    }
    ...
};

Don't forget that encoding: null line, because without that, the response will be automatically converted to a string. ( We need a buffer to make this work )
Then I created a function like this to handle my request:
const zlib = require("zlib");

async function performRequest(url, options) {
    try {
        const response = await got(url, options);
        if (response.headers["content-encoding"] === "gzip") {
            const body = response.body;
            try {
                const dezziped = zlib.gunzipSync(response.body);
                response.body = JSON.parse(dezziped.toString());
            } catch (error) {
                response.body = body;
            }
        }
        return response.body;
    } catch (error) {
        return error;
    }
}

Note: This is a synchronous operation, you can use gunzip instead if you want to do the async way.


text:
Q: Laravel 5.1: Scheduled Job Output mixed with all job Using Laravel 5 schedule job I noticed that when there is more than one job working at the same time, the output of the jobs, is mixed!
Something weird, because if they run for several minutes and each has simple output like:
Job X, step 1: complete
Job X, step 2: complete
Job X, step 3: complete

The output that I get in an "Scheduled Job Output" email will be:
Job 1, step 1: complete
Job 2, step 1: complete
Job 2, step 2: complete
Job 1, step 2: complete
Job 1, step 3: complete

In additional sometimes I get more than an email for a job, like 2 or more emails incompleted. Only the last one is full of the output.
like:
1° email:
Job 1, step 1: complete

2° email:
Job 1, step 1: complete
Job 1, step 2: complete

3° email:
Job 1, step 1: complete
Job 1, step 2: complete
Job 1, step 3: complete

I know for sure that are the same jobs, because at the top of the output I print timestamp and name of the job.
Why?

A: Because to send the output email, laravel saves the job with ->sendOutputTo($FILE_PATH)
If you use the same $FILE_PATH for multiple jobs that works concurrently, the output will be messy as described.


text:
Q: Check an element existence in table rows via jQuery I have a table tag on my page. I'm adding dynamically a new set of rows, where some of them can contain a <button class="btn btn-primary"></button> tag. I'm wondering, how to check the information via JQuery, if that table contains any rows with that button ?

A: Just try:
var buttons = $table.find('.btn.btn-primary');
var buttonExists = buttons.length > 0;

Table has to be a jQuery object containing your table.

A: You can use length to check the existence of an element. Try this:
var buttonExists = $("table .btn-primary").length != 0;

A: if ($('tr:contains(".btn")')){
  alert('has button')
}


text:
Q: Enter click does not trigger JQuery dialog open Me and a few co-workers are slightly puzzled by this issue. We have an onclick event in Javascript which opens a JQuery dialog box. This works when you actually click the designated button. However, when you press enter, it will trigger the onclick event and also perform the other required functions. But when it hits the dialog, it does not open. Strangely, if you insert an alert before the dialog code, it will open the alert and then open the dialog. Any fixes?
JQuery:
$(document).ready(function () {
    $('#applyFilter').click(function () {
        console.log('event triggered');
        var suppString = $('#FK_SupplierID').val();
        var carryOn = true;
        //if the supplier ID fields is showing and populated:
        //check if supplier ID values are all numeric, if not show message and modal form
        if (suppString != null) {
            suppString.split(",").forEach(function (item) {
                if (item != '') {
                    if (!isInt(item)) {
                        //invalid value - set carryOn to false and exit the loop
                        carryOn = false;
                        return false;
                    }
                }
            });

            if (!carryOn) {
                alert("The Supplier ID field must only have a whole number, or a comma-separated list of whole numbers.  Please type in a valid value or click the ellipsis button to select the required suppliers from the supplier list.")
                return false;
            } else {
                //check if supplier label is populated - if not, populate it
                if (suppString != '' && $('#suppliersShown').text() == '') {

                    //GetSupplierNames
                    $.getJSON("./GetSupplierNames", { ids: suppString },
                            function (data) {
                                $('#suppliersShown').text("Supplier(s):" + data);
                                $('#suppliersShown').show();
                            }
                        );
                }
            }
        }

        $('#dialog-processing').dialog({
            closeOnEscape: false,
            //open: function (event, ui) {
            //    $(".ui-dialog-titlebar-close").hide();
            //},
            autoOpen: false,
            width: 400,
            resizable: false,
            modal: true
        });

        $('#dialog-processing').dialog('open');

        var table = $('#invoiceTable').on('processing.dt', function (e, settings, processing) {

            //    $('#dialog-processing').dialog('close');

        }

).DataTable({
    retrieve: true,
});
        table.ajax.url('./FilterData/?filterString=' + FilterParams()).load(function (json) { console.log(json); });

    });
});able({
                retrieve: true,
            });
            table.ajax.url('./FilterData/?filterString=' + FilterParams()).load(function (json) { console.log(json); });

});

HTML:
<button id="applyFilter">click</button>


text:
Q: How can I debug this node / phantomjs issue further? I can run my script containing portscanner.findAPortNotInUse() locally(OSX) without error but when running on a bitnami EC2 instance I get:
events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: listen EADDRINUSE
    at errnoException (net.js:901:11)
    at Server._listen2 (net.js:1039:14)
    at listen (net.js:1061:10)
    at Server.listen (net.js:1127:5)
    at Object.module.exports.create (/home/bitnami/applications/tennistracker/node_modules/phantom/phantom.js:90:18)
    at /home/bitnami/applications/tennistracker/main.js:114:25
    at /home/bitnami/applications/tennistracker/node_modules/portscanner/lib/portscanner.js:136:7
    at /home/bitnami/applications/tennistracker/node_modules/portscanner/node_modules/async/lib/async.js:578:28
    at /home/bitnami/applications/tennistracker/node_modules/portscanner/lib/portscanner.js:119:9
    at Socket.<anonymous> (/home/bitnami/applications/tennistracker/node_modules/portscanner/lib/portscanner.js:96:5)

code is
var startPort = 50000;

portscanner.findAPortNotInUse(startPort, 50100, 'localhost', function(error, freeport) {
                console.log('freeport value: '+freeport);
            if(error) {
                console.log('portscanner error: '+error);
            }...

Additonal output:
freeport value: undefined
portscanner error: true
freeport value: undefined
portscanner error: true

I've disabled ufw on the server and also allowed the port range 50000 - 60000 in AWS. startPort is set to 50000. How can I debug this issue further? I've tried running strace but can't see anything obvious.

A: Turns out this was an issue with portscanner.js, in combination with my server setup (bitnami node stack on EC2). Editing the following line to set the host to '127.0.0.1' resolved the issue for me.
https://github.com/baalexander/node-portscanner/blob/master/lib/portscanner.js#L65
If anyone knows why, please post a further answer and I will accept. FWIW, my hosts file DOES already contain an entry pointing 127.0.0.1 to localhost


text:
Q: Searching by username doesn't work very well Why does the search on this site find posts I made three months ago using my user name as the search criteria, but not the one I posted three hours ago? Very frustrating.
Then I have to play the "what is the CAPTCHA" game 20 times, along with the "you can't add a new tag" game. As you can probably tell, I'm not having a fun time right now.

A: Here's your recent question: MySQL refuses to work with Apache 2.2 and PHP 5.2 on Windows 7 or Win3k
Here's your older one: PHPMailer question
Normally, I'd tell you to just look in the list of your questions in your profile, but it looks like those posts weren't made by the same account. You posted with the same e-mail address, which is why the identicon (that colorful crazy geometric icon thing) is the same on both posts, but you didn't register. If you use a different computer, or the same computer with the cookies cleared, the system can't tell you're the same person.
You actually have at least three accounts: here's one, here's another and here's the third. There are five other users named Beauford, too. If you have more than one e-mail address, some of them may also be you.
The reason the search doesn't find you is that you only have your name in one of the posts. Search doesn't look at author names, just the post bodies. Even if you type your name into the body every time, other people may edit it out; it's even encouraged for them to do so. We don't like "Hi guys," or "Thanks, [name]" here; it's just clutter.

A: If you enter user:516947 into the search box, you should have more luck. Although, since you only have one question there, it's probably more to do with you not necessarily having a proper OpenID account.
And, if you want to get rid of the captchas and be able to add tags, I think that just requires a little more rep.
As with all worthwhile things, it takes a little effort :-)


text:
Q: Forcing two WPF controls to have the same width while maintaining auto sizing from xaml (Both controls have greater of two width) I am trying to define a 1x3 grid where the first and third  columns widths auto-size to fit their contents but maintain equal widths. I figured I could achieve this by binding each ColumnDefinition's MinWidth property to be the other columns ActualWidth. But it does not seem to work. Can someone explain why the following code does not work?
'''
<DataTemplate DataType="{x:Type edvm:NodeViewModel}">
   <Grid">
      <Grid.ColumnDefinitions>
        <ColumnDefinition
             x:Name="inCol"
             Width="Auto"
             MinWidth="{Binding ElementName=outCol, Path=ActualWidth}" />
        <ColumnDefinition
            Width="*"
            MinWidth="25" />
        <ColumnDefinition
            x:Name="outCol"
            Width="Auto"
            MinWidth="{Binding ElementName=inCol, Path=ActualWidth}" />
     </Grid.ColumnDefinitions>
   </Grid>
</DataTemplate>

'''

A: Set the SharedSizeGroup property of both ColumnDefinitions. That would implicitly also set Width="Auto".
<Grid Grid.IsSharedSizeScope="True">
    <Grid.ColumnDefinitions>
        <ColumnDefinition SharedSizeGroup="OuterColumns"/>
        <ColumnDefinition MinWidth="25"/>
        <ColumnDefinition SharedSizeGroup="OuterColumns"/>
    </Grid.ColumnDefinitions>
    ...
</Grid>


text:
Q: EventBus comunication between two fragments shows No subscribers registered for event class..? First Time I'm trying to implement EventBus to comunicate two fragments of MyActivity (to change button.setEnabled)
my SDK 21
this is my POJO event
public class ButtonEvent {

public final boolean status;
public ButtonEvent(boolean status){

    this.status=status;
}

}
this is the fragment that fire the event...
Fragment A
...//some code
 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_a, container, false);
...//more code inside onCreateView
  btnChange.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
//HERE I POST THE EVENT
            EventBus.getDefault().post(new ButtonEvent(true));
}

here is the fragmentB wich receives (listen) the event...
FragmentB extends Fragment{
...//some code
@Override
// in method onCreate I register the subscriber
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(!EventBus.getDefault().hasSubscriberForEvent(ButtonEvent.class)) {
        EventBus.getDefault().register(this);
    }

}
 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_b, container, false);
//...some other code
}
//HERE IS MI SUBSCRIBER
@Subscribe
public void onEvent(ButtonEvent event){

    btnNuevoMed.setEnabled(event.status);
    btnNuevoMed.setText("hELLOOO");
}

this is my output but the app doesn't stop, but doesn't make any change on my fragmentB button:
D/EventBus: No subscribers registered for event class ar.com.titaves.consultoriosapp.servicios.ButtonEvent
D/EventBus: No subscribers registered for event class org.greenrobot.eventbus.NoSubscriberEvent

my eventbus version:
compile 'org.greenrobot:eventbus:3.0.0'

there are similiar questions but some of them haven't got the right answer and the other are different situations Activity-fragment are not the same implementation than fragment to frament.
Is my code right? I am missing something? Why it is not working an how can i Solve the problem? thanks in advance...

A: Here is a sample..
          Fragment A
            ...//some code
             @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
                View rootView = inflater.inflate(R.layout.fragment_a, container, false);
            ...//more code inside onCreateView
              btnChange.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
            //HERE I POST THE EVENT
                        EventBus.getDefault().post(new ButtonEvent(true));
            }
});
}

        @Subscribe
        public void onEvent(ButtonEvent event){

        }

    @Override
      public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(getActivity())) {
          EventBus.getDefault().register(this);
        }
      }

      @Override
      public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
      }

Fragment B:
    FragmentB extends Fragment{
    ...//some code
    @Override
    // in method onCreate I register the subscriber
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }
     @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_b, container, false);
    //...some other code
    }
    //HERE IS MI SUBSCRIBER
    @Subscribe
    public void onEvent(ButtonEvent event){

        btnNuevoMed.setEnabled(event.status);
        btnNuevoMed.setText("hELLOOO");
    }
 @Override
      public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(getActivity())) {
          EventBus.getDefault().register(this);
        }
      }

      @Override
      public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
      }


text:
Q: Softerra LDAP SQL Query for duplicate values failing I am using Softerra LDAP Browser 4.5 and it is failing on the most basic SQL Query. I cannot figure out any mistakes in the query. I am sure it is correct.
It is throwing an unexpected COUNT error which is super strange as it doesn't make any sense at all.
SELECT COUNT(*) Queries work fine with same ldap path.
I have tried with and without the $ symbol. Didn't help.
Do the Wizards of Stack Overflow see what exactly the problem here might be?

Regards


text:
Q: jQuery Ajax / Modal admin event not firing since 3.6. Seems to not recognize "a" tag This came up immediately after upgrading to wordpress 3.6.
Upon clicking the modal "anchor" tag, an ajax event fires to refresh the content in the box.
It was working before, then ceased afterward. I noticed some small changes have been made to jQuery in the admin regarding plugins, but I'm not sure it affects my situation.
I guess the question is, why doesn't this event get recognized/fired.
Here is the modal example: http://codex.wordpress.org/ThickBox
Here is my link that fires it up:
» Edit 6617

Then here's the function that it should fire based on link with class:
//get_image_ajax
$(document).on('click', '.edit-image', function (e) {

    e.preventDefault();

    var data = {
        action: 'ss_professional_ajax',
        security: '<?php echo $ajax_nonce; ?>',
        image_id: $(this).attr('id'),
    };

    $.post(ajaxurl, data, function (response) {
        $('#ss-edit-image-box-content').empty();
        $('#' + loading_icon).show();
        $('#ss-edit-image-box-content').append(response);
        $('#' + loading_icon).hide();
    });
    return false;
});

EDIT: The ajax itself / the function is not firing. The modal window does pop up. Its also worth noting that this is "live" content delivered by ajax.


text:
Q: Installing nvm in aws Error: UNABLE_TO_GET_ISSUER_CERT_LOCALLY I tried to install one module with npm in AWS but I'm getting Error:

UNABLE_TO_GET_ISSUER_CERT_LOCALLY

I tried to set the registry with npm config set registry http://registry.npmjs.org/ and disabling the ssl with npm config set strict-ssl false
Also using the var export NODE_EXTRA_CA_CERTS=/etc/pki/tls/certs/
But when I try to install de package after of that, is still looking for in the HTTPS repository:
ec2-user:~/environment/dapp $ sudo npm install -g ganache-cli
npm http GET https://registry.npmjs.org/ganache-cli
And getting the SSL error.
Do you know how to disable it in an AWS ec2 running in cloud9?
Thanks

A: In EC2, try the installation command with out sudo in front
example, $ npm install package-name


text:
Q: Projection onto closed subspace with finite codimension
Let $X$ be a $\mathbb K \in \{\mathbb R, \mathbb C\}$ Banach space and $U \le X$ closed with finite codimension. Show that there exists a continuous projection onto $U$.

So finite codimension means $dim(X/U)=n<\infty$. Hence I can find a basis $\{x_1+U,...,x_n+U\}$. Now consider $V:= span\{x_1,...,x_n\} \le X$. It can be shown that there is a continous projection $P$ onto $V$. And then $1-P$ should project onto $U$, right? Does that work?

A: There exists $e_1,..,e_n$ such that $U\oplus Vect(e_1,...,e_n)=X$. Let $U_i=U+Vect(e_1,..,\hat {e_i},..,e_n)$, it is a closed subset of codimension $1$, the form $f_i$ defined by $f_{\mid U_i}=0, f(e_i)=1$ is continuous.
Denote $p:X\rightarrow X$ defined by $p(x)=x-\sum_{i=1}^{i=n}f_i(x)e_i$, show that $p$ is a projection onto $U$.

A: By induction on the co-dimension of $U.$
(I). If $U$ is of co-dimension $1$ let $0\ne x_1\in X$ \ $U.$ For $k\in \Bbb K$ and $y\in U$ let $P(kx_1+y)=y.$
Then $P$ is well-defined because if $kx_1+y=k'x_1+y'$ with $k,k'\in \Bbb K$ and $y,y'\in U$ then $(k-k')x=y'-y\in U\implies k-k'=0 \implies y'-y=0.$
If a sequence $(k_nx_1+y_n)_n$ converges, its limit is $kx_1+y$ for some $k\in \Bbb K$ and some $y\in U$ (because $\{kx_1:k\in \Bbb K\}+U=X$).
And $|k_n-k|\cdot \inf_{z\in U}\|x_1-z\|\leq \|(k_n-k)x_1+(y_n-y)\|\to 0,$ so $k_n\to k$ (because $\inf_{z\in U}\|x_1-z\|>0$  because $x_1\not \in U=\bar U$).
Hence  $\|y_n-y\|\leq \|(k_n-k)x_1+(y_n-y)\|+\|-(k_n-k)x_1\|\to 0$ implies $y_n\to y.$ So $(P(k_nx_1+y_n))_n=(y_n)_n$ converges to $y=P(kx_1+y).$
So $P$ is continuous. Obviously $P$ is linear and $P|_U=id_U$, and $P(P(x))=P(x)$ for all $x\in X.$
(II). If $U$ is of co-dimension $n>1,$ suppose the result holds for any closed linear subspace of co-dimension $n-1.$ Let $\{x_1,...,x_n\}\subset X$ be a vector-space basis for $V$ such that $U+V=X.$ Let $V'$ be the vector space  generated by $\{x_2,...,x_n\}.$ Then $U+V'$ is a closed vector subspace of $X$  (because $U=\bar U$ and $V'$ is finite-dimensional) and $U+V'$ is of co-dimension $1$ in $X$. So by (I) there is a continuous projection $P'$ from  $X$ onto $U+V'.$
Now $U +V'$ is a Banach space  and $U$ is a closed linear subspace  of co-dimension $n-1$ in the space $U+V'.$ By the inductive supposition there is a continuous projection $P''$ from the Banach space $U+V'$ onto $U,$ so let $P=P''P'.$


text:
Q: Given a connected directed graph D, show $\sum_{v\in V_{D}} |deg^{+}(v)-deg^{-}(v)|\le 2(|V_{D}|-1).$ Given a simple connected directed graph $D$, show that:
$$\sum_{v\in V_{D}} |d^{+}_{v}-d^{-}_{v}| \le 2(|V_{D}|-1).$$
$V_{D}$ is the vertex-set and $A_{D}$ is the arc-set of $D$. $d^{+}_{v}$ and $d^{-}_{v}$ are the out-degree and in-degree of vertex $v$.
I have been trying to solve this mostly with the properties that this equality brings $\sum_{v\in V_{D}} |d^{+}_{v}-d^{-}_{v}| = \sum_{v\in V_{D}} max(d^{+}_{v},d^{-}_{v})-min(d^{+}_{v},d^{-}_{v})$. But so far I've been hitting brick walls, so I thought maybe one of you wizards could enlighten me.
Updated on 23.4.2017
Although there's nothing really to add here since the conjecture was disproven. I'd like to prove the actual greatest value $\sum_{v\in V_{D}} |d^{+}_{v}-d^{-}_{v}|$ can have, for some simple connected directed graph.
$(T1)$ $2(\sum_{v\in V_{D}}max(d^+_{v}, d^-_{v})+|V_{D}|-1)\ge \sum_{v\in V_{D}} |d^{+}_{v}-d^{-}_{v}|$.
$(L1)$ If a simple directed graph is connected then $|A_{D}| \ge |V_{D}|-1,$
$(L2)$ $2|A_{D}| = \sum_{v\in V_{D}} max(d^{+}_{v},d^{-}_{v})+min(d^{+}_{v},d^{-}_{v})$.
$(P1)$ Let $D$ be a simple connected directed graph, then
$$|A_{D}| \ge |V_{D}|-1 \tag*{(by P1 and L1)}$$
$$\frac{1}{2}\left(\sum_{v\in V_{D}}max(d^+_{v}, d^-_{v}) + min(d^+_{v}, d^-_{v})\right) \ge |V_{D}|-1  \tag*{(by L2)}$$
$$-|V_{D}|-1\ge -\frac{1}{2}\left(\sum_{v\in V_{D}}max(d^+_{v}, d^-_{v}) + min(d^+_{v}, d^-_{v})\right)$$
$$-2(|V_{D}|-1)\ge \sum_{v\in V_{D}}-max(d^+_{v}, d^-_{v}) - min(d^+_{v}, d^-_{v})$$
$$2\left(\sum_{v\in V_{D}}max(d^+_{v}, d^-_{v})-|V_{D}|+1\right) \ge \sum_{v\in V_{D}}max(d^+_{v}, d^-_{v}) - min(d^+_{v}, d^-_{v})$$
$$2\left(\sum_{v\in V_{D}}max(d^+_{v}, d^-_{v})-|V_{D}|+1\right)\ge \sum_{v\in V_{D}} |d^{+}_{v}-d^{-}_{v}| \tag*{($\therefore P1$)  $\blacksquare$.}$$
Let's also prove the trivial greatest value of $\sum_{v\in V_{D}}|d^{+}_{v}-d^{-}_{v}|$, that is $2|A_{D}|$.
$(T2)$ $\sum_{v\in V_{D}}|d^{+}_{v}-d^{-}_{v}| \le 2|A_{D}|$.
$(L3)$ $2|A_{D}| \ge \sum_{v\in V_{D}}max(d^{+}_{v},d^{-}_{v}) \ge |A_{D}| \ge \sum_{v\in V_{D}}min(d^{+}_{v},d^{-}_{v}) \ge 0.$
$$2|A_{D}| \ge \sum_{v\in V_{D}}max(d^{+}_{v},d^{-}_{v}) \tag*{(by L3)}$$
$$2|A_{D}|-\sum_{v\in V_{D}}min(d^{+}_{v},d^{-}_{v}) \ge \sum_{v\in V_{D}}max(d^{+}_{v},d^{-}_{v})-min(d^{+}_{v},d^{-}_{v})$$
$$2|A_{D}| \ge 2|A_{D}|-\sum_{v\in V_{D}}min(d^{+}_{v},d^{-}_{v})\tag*{(by L3)}$$
$$2|A_{D}| \ge \sum_{v\in V_{D}}max(d^{+}_{v},d^{-}_{v})-min(d^{+}_{v},d^{-}_{v}) \tag*{($\therefore P2$)  $\blacksquare$.}$$

A: The following seems to be a counterexample.
Consider a complete bipartite directed graph with partition $A,B$, where $|A|=|B|=n$ (there are all possible edges from $A$ to $B$). Add one additional vertex $c$ and all possible edges from $B$ to $c$ and from $c$ to $A$. Thus obtained graph $D$ is connected.
We calculate that $\mathrm{LHS} = 2n \cdot (n-1)$ grows quadratically and $\mathrm{RHS} = 2 ((2n+1)-1)$ grows linearly with respect to $n$.
For this particular $D$, the claim would work for $|A_D|$ instead of $|V_D|$ - this is why I asked about it in the comments.


text:
Q: Strongest axiomatic systems accepted as consistent by math community As I understand it, most math is done implicitly within $ZFC$, but sometimes stronger systems are used--for instance, the initial proof of Fermat's Last Theorem used Grothendieck universes, which imply the existence of large cardinals.
I am curious how powerful axioms you could use before a proof of some $\Pi_1$ statement (so that only consistency, not soundness, need be considered) using them wouldn't be generally accepted by the math community. If there were a proof of, say, the Riemann Hypothesis in $ZFC+X$, how weak would $X$ need to be for the authors to get the Millenium Prize money?


text:
Q: Extensions in Kotlin I want to use extensions for variables and method for my custom class.
I am trying below code but getting error

Local extension properties are not allowed

val Double.km: Double get() = this * 1000
val Double.m: Double get() = this
val Double.cm: Double get() = this / 100
val Double.mm: Double get() = this / 1000
val Double.ft: Double get() = this / 3.28084

val oneInch = 25.4.mm
println("One inch is $oneInch meters")
// prints "One inch is 0.0254 meters"
val threeFeet = 3.0.ft
println("Three feet is $threeFeet meters")
// prints "Three feet is 0.914399970739201 meters"

How to use extensions? Can we use extensions in interface?

A: You have to move these declarations from the function body to the class body. Like the error states, it's not allowed to define extension properties locally, while local extension methods are ok.
So in your case you could do:
class MainClass {
    val Double.km: Double get() = this * 1000
    val Double.m: Double get() = this
    val Double.cm: Double get() = this / 100
    val Double.mm: Double get() = this / 1000
    val Double.ft: Double get() = this / 3.28084

    fun run() {
        val oneInch = 25.4.mm
        println("One inch is $oneInch meters")
    }
}

You can use the extension properties from within your MainClass, while outside usage is not possible.


text:
Q: R chisquare outlier test while loop I am new to R. I want to do a chi-square outlier test, using outliers library on a variable x$indel until the returned p.value is > 0.01 (after removing the outlier from the data).
Here is what I tried:
while(chisq.out.test(x$indel)$p.value < 0.01)
{
    # str: string contains the outlier value and some text
    #   n: extract the outlier value and transform to numeric
    str <- chisq.out.test(x$indel)$alternative
    print(str)

    n <- as.numeric(unlist(regmatches(str,
             gregexpr("[[:digit:]]+\\.*[[:digit:]]*",str))))
    x <- x[x$indel < n,]
    print(nrow(x))
}

Below is the x$indel column
    c(0.287749287749, 0.324786324786, 0.330484330484, 0.293447293447,
0.293447293447, 0.31339031339, 0.31339031339, 0.327635327635,
0.344729344729, 0.327635327635, 0.304843304843, 0.296296296296,
0.433048433048, 0.700854700855, 0.467236467236, 0.31339031339,
0.373219373219, 0.293447293447, 0.304843304843, 0.293447293447,
0.407407407407, 0.301994301994, 0.307692307692, 0.301994301994,
0.381766381766, 0.307692307692)

When I paste this command to the console nothing happens, what's wrong?

A: Generate some data with "outliers"
x = round(rnorm(100, 100, 100), 2)

Replaced all x$indel with x. The problem with using a data.frame is that when you remove values from the column and try to replace the original list, you'll get a complaint about dimension mismatch.
Also improved the regex to handle negative numbers, and improved the subset logic to deal with "highest value" and "lowest value" cases.
while(chisq.out.test(x)$p.value < 0.01)
{
  # str: string contains the outlier value and some text
  #   n: extract the outlier value and transform to numeric
  str <- chisq.out.test(x)$alternative
  print(str)
  n <- as.numeric(unlist(regmatches(str,
                                    gregexpr("(?<=value)(.*)(?=is an outlier)", str, perl = T))))
  x <- x[x != n]
  print(length(x))
}


text:
Q: "Invalid signature": oAuth provider with Django-piston I'm working with django-piston to attempt to create an API that supports oAuth.
I started out using the tutorial at:
http://blog.carduner.net/2010/01/26/django-piston-and-oauth/
I added a consumer to piston's admin interface with key and secret both set to "abcd" for test purposes.
The urls are successfully wired-up and the oAuth provider is called.
However, running my get request token tests with tripit (python get_request_token.py "http://127.0.0.1:8000/api" abcd abcd), I receive the following error:

Invalid signature. Expected signature
  base string:
  GET&http%3A%2F%2F127.0.0.1%3A8000%2Fapi%2Foauth%2Frequest_token%2F&oauth_consumer_key%3Dabcd%26oauth_nonce%3D0c0bdded5b1afb8eddf94f7ccc672658%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1275135410%26oauth_version%3D1.0

The problem seems to lie inside the _check_signature method of Piston's oauth.py, where
valid_sig = signature_method.check_signature(oauth_request, consumer, token, signature)

is returning false. I can't, however, work out how to get the signature validated.
Any ideas?
Update:
If I remove the test consumer from piston's backend, the response returned is correctly set to "Invalid consumer", so this lookup appears to be working.

A: The eventual answer I found was to install a working copy of oauth_consumer into the application directory. Once I had added my consumer inside this application, everything worked as expected.

A: @Ricardo and anyone else having problems with this error (sorry for the "answer", I don't have commenting as of yet), I was able to avoid this error by generating my signature from following the test cases provided in piston's code. Example:
>>> from piston.oauth import *
>>> from piston.models import *
>>> consumer = Consumer.objects.get(id=1)
>>> oaconsumer = OAuthConsumer(consumer.key, consumer.secret)
>>> request = OAuthRequest.from_consumer_and_token(oaconsumer, http_url='http:
    //localhost:8000/api/oauth/request_token/')
>>> signature_method = OAuthSignatureMethod_HMAC_SHA1()
>>> request.sign_request(signature_method, oaconsumer, None)
>>> request.sign_request(signature_method, oaconsumer, None)
>>> request.parameters
{'oauth_nonce': '64379482', 'oauth_timestamp': 1297147940, 'oauth_consumer_key': u'8aZSFj3W54h8J8sCpx', 'oauth_signature_method': 'HMAC-SHA1', 'oauth_version': '1.0', 'oauth_signature': 'kGSLCZjYzAHXsa8f9sL52Kq1F2w='}

From here, just use these parameters in a browser e.g.
http://localhost:8000/api/oauth/request_token/?oauth_nonce=64379482&oauth_timestamp=1297147940&oauth_consumer_key=8aZSFj3W54h8J8sCpx&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_signature=kGSLCZjYzAHXsa8f9sL52Kq1F2w=
Which generates "oauth_token_secret=37VZKRV3fXRLAw5tekZD2bwnMhXqGwgx&oauth_token=LRnexBGTNC4nDXpv9M&oauth_callback_confirmed=true"
As Martin pointed out, leaving out a "/" in either the sample code or the URL will render the signature "invalid".


text:
Q: How to convert callback code to async/await? I am working with Mongoose ODM for MongoDB in a node express-based web application which provides its API in a callback fashion. This fashion creates a callback hell to populate documents.
Edit 1: I have added the current working code.
User.remove({}, (err) => {
  if (err) return console.error(err)

  let admin = new User({
    email: 'admin@dap.com',
    password: 'dapdap'
  })

  admin.save((err, admin) => {
    if (err) return console.error(err)

    console.info('Success')
    mongoose.disconnect()
  })

})

Is there an elegant way to convert the callbacks into async/await fashion in javascript in general? And in mongoose environment?

A: Would you be able to configure mongoose to use bluebird?
mongoose.Promise = require('bluebird');
Then you could get fancy and do:
User.remove().then(() => {
    let admin = new User({ ... });

    admin.save().then((admin) => {

    }).catch((err) => {
      //Saving admin error handling
    });
}).catch((err) {
  //User remove error handling
});

A: The same code you wrote above can be written as a promise. From the original docs,
"Mongoose queries are not promises. However, they do have a .then() function for yield and async/await. If you need a fully-fledged promise, use the .exec() function."
Thus you can use the async await pattern as follows,
async function removeUser () {
    // Surround the following call with a try catch
    await User.remove({});
}

EDIT:
One answer here says about plugging in blue bird promises. While this is a good approach, it is optional. You can do the same without plugging in your own Promise library.

A: You can use a Promise:
const userRemovePromise = new Promise((resolve, reject) => {
    User.remove({}, (err) => {
      if (err) reject();

      let admin = new User({
        email: 'admin@dap.com',
        password: 'dapdap'
      })

      admin.save((err, admin) => {
        if (err) reject();

        resolve();
      })

    });

});

userRemovePromise.then(function(){
    mongoose.disconnect();
});

A: As mongoose's default promise library mpromise is now deprecated so you can plugin your own promise library to make mongoose's operations work with await/async.
Mongoose queries are not promises. However, they do have a .then() function for yield and async/await. If you need a fully-fledged promise, use the .exec() function.
mongoose.Promise = require('bluebird'); bluebird promise
// mongoose.Promise = global.Promise; // default js promise - 4x- time slower than bluebird

async function removeUser () {
  try {
    await User.remove({}).exec();
    let admin = new User({
      email: 'admin@dap.com',
      password: 'dapdap'
    })
    await admin.save();
    } catch (e) {
        console.log(e);
    }
}

Official Doc: mongoosejs.com/docs/promises.html

A: Recent versions of Mongoose returns a Promise as well as providing the regular callback-style pattern. Since async functions are syntatic sugar over Promises, you can await calls to Mongoose methods.
async function clearUsers () {
  try {
    await User.remove({})
    let admin = new User({
      email: 'admin@dap.com',
      password: 'dapdap'
    })
    await admin.save()
    console.info('Success')
    mongoose.disconnect()
  } catch (e) {
    console.error(e)
  }
}

Some things to keep in mind:

*

*async functions always returns a Promise. If you don't return anything from an async function, it will still return a Promise that resolves when execution of that function finishes, but will not resolve with any value.

*try/catch in an async function works the same as for regular, synchronous code. If any function call in the try body throw or return a Promise that rejects, execution stops right on that line and proceeds to the catch body.

*Rejected promises "trickle" up the function call chain. This means that the top-most callee can handle errors. See the below example:

This is an anti-pattern that should be avoided unless you absolutely need to handle an error in a specific function, possibly to provide a return value from a different source:
async function fn1 () {
  throw new Error("Something went wrong")
}

async function fn2 () {
  try {
    await fn1()
  } catch (e) {
    throw e
  }
}

async function fn3 () {
  try {
    await fn2()
  } catch (e) {
    throw e
  }
}

async function run () {
  try {
    await fn3()
  } catch (e) {
    console.error(e)
  }
}

The above could rather be implemented like the below and still catch the error, not resulting in a runtime panic/crash:
async function fn1 () {
  throw new Error("Something went wrong")
}

function fn2 () {
  return fn1()
}

function fn3 () {
  return fn2()
}

async function run () {
  try {
    await fn3()
  } catch (e) {
    console.error(e)
  }
}

There are multiple ways to write the above code that will all be valid, so I recommend that you explore these.
Keeping the above examples in mind, your function clearUsers() could then be rewritten to this:
async function clearUsers () {
  await User.remove({})
  let admin = new User({
    email: 'admin@dap.com',
    password: 'dapdap'
  })
  await admin.save()
  mongoose.disconnect()
}

And then possibly called in two different ways;
By interacting with the Promise returned directly:
clearUsers()
  .then(() => {
    console.log('Success')
  })
  .catch((e) => {
    console.error(e)
  })

Or from within another async function:
(async function () {
  try {
    await clearUsers()
    console.log('Success')
  } catch (e) {
    console.error(e)
  }
})()

If any function call within the clearUsers() function throws, for example await admin.save(), execution will stop on that line and return a rejected Promise which will be caught in the corresponding catch blocks in both variants.

A: Using Bluebird is a good option to handle callbacks in promises, It makes it easier to understand to an extent.
However I would recommend you to try
Async.js
It is built particularly for managing asynchronous nature of javascript.
This particular function of the library would do exactly what you want.


text:
Q: Multi threading in Modbus? How can send query at 500 ms keeping response time as 1 second? I have implemented MODBUS master slave communication. I have
implemented fun 6, 16 & 3. I set 1 minute as response time. Now
problem is that I want to send query at 500 ms. But because of this 1
second response time, I need to wait till 1 sec to send the second
query. How I can send query at every 500 ms keeping response time as 1
sec.
Is it possible to send new query, if we are still waiting for response of our previous query as well?
How to communicate with slower device over MODBUS?

A: See section 2.1 of the MODBUS over serial line specification and implementation guide V1.02 where

The master node initiates only one MODBUS transaction at the same
  time.

This should inform any decision on how you sequence the commands. The other specification documents on the site are also helpful to ensure your implementation is conforming.
You would probably save yourself several person-months by using an existing open implementation. There are a number described at Modbus Technical Resources.


text:
Q: How to train a CNN model? When trying to train the CNN model, I came across a code shown below:
def train(n_epochs, loaders, model, optimizer, criterion):

    for epoch in range(1,n_epochs):
        train_loss = 0
        valid_loss = 0

        model.train()
        for i, (data,target) in enumerate(loaders['train']):

            # zero the parameter (weight) gradients
            optimizer.zero_grad()
            # forward pass to get outputs
            output = model(data)
            # calculate the loss
            loss = criterion(output, target)
            # backward pass to calculate the parameter gradients
            loss.backward()
            # update the parameters
            optimizer.step()

Can someone please tell me why is the second for loop used?
i.e; for i, (data,target) in enumerate(loaders['train']):
And why optimizer.zero_grad() and optimizer.step() is used?

A: Optimizer is used first to load the params like this (missing in your code):
optimizer = optim.Adam(model.parameters(), lr=0.001, momentum=0.9)

This code
loss = criterion(output, target)

Is used to calculate the loss of a single batch where targets is what you got from a tuple (data,target) and data is used as the input for the model, where we got the output.
This step:
optimizer.zero_grad()

Will zero all the gradients found in the optimizer, which is very important on initialization.
The part
loss.backward()

Calculates the gradients, and the optimizer.step() updates our model weights and biases (parameters).
In PyTorch you typically use DataLoader class to load the trainging and validation sets.
loaders['train']

Is probable the full train set, which represents a single epoch.

A: *

*torch.utils.data.DataLoader comes in handy when you need to prepare data batches (and perhaps shuffle them before every run).
data_train_loader = DataLoader(data_train, batch_size=64, shuffle=True)
In the above code, first for-loop iterates through the number of epochs while second loop iterates through the training dataset converted into batches via above code. For example:
for batch_idx, samples in enumerate(data_train_loader):
    # samples will be a 64 x D dimensional tensor
    # batch_idx is each batch index

Learn more about torch.utils.data.DataLoader from here.

*Optimizer.zero_gradient(): Before the backward pass, use the optimizer object to zero all of the gradients for the tensors it will update (which are the learnable weights of the model)

*optimizer.step(): We generally use optimizer.step() to make the gradient descent step. Calling the step function on an Optimizer makes an update to its parameters.
Learn more about these from here.


text:
Q: How to fix "initializer-string for array of chars is too long" and "excess elements in char array initializer" when setting up a 2D character array I'm attempting to make a 2D array which would store a question and an answer in each row of the array, what do I need to do to set this up, as well as be able to call rows from this array.
I have tried to change the brackets to the right of the array name (eg. [15][2], [15], no brackets), and looked at a few stackoverflow problems which don't quite work for my problem. I am also getting the "subscripted value is neither array nor pointer nor vector" error when on the 'H' case of the switch statement. I am also getting several "braces around scalar initializer", "excess elements in scalar initializer" and "makes integer from pointer without a cast [-Wint-conversion]" warnings during loading. I apologize if I made any obvious mistakes I'm coming to C from Python and still trying to wrap my head around it.
int trivia() {
    char history[15] = { {"Which English king was \"mad\"?","George III",}
                        {"Who started the Protestant Reformation?","Martin Luther"},
                        {"Who was the first person to see the moons of Jupiter?","Galileo"},
                        {"What Viking group settled in France before conquering England, Sicily, and Malta?","The Normans"},
                        {"What group sacked Baghdad in 1258, ending the Islamic Golden Age?","The Mongols"},
                        {"Against what city did Rome fight the Punic Wars?","Carthage"},
                        {"What yellow gas was famously used in WWI?","Mustard Gas"},
                        {"What epic poem is thought to be the oldest in the English language?","Beowulf"},
                        {"What ancient empire was led by Xerxes, Cyrus, and Darius?","Persia"},
                        {"Who was the most notorious member of the Ba'ath Party?","Saddam Hussein"},
                        {"What Italian adventurer wrote about his 24 year journey from Venice to China and back?","Marco Polo"},
                        {"What young pharaoh's tomb was discovered in 1922?","Tutankhamun"},
                        {"Before becoming king of England, what country was James I the king of?","Scotland"},
                        {"What was the primary language of the Byzantine Empire?","Greek"},
                        {"For what crime was Al Capone convicted of in 1931?","Tax Evasion"}
                        };
char sport[15] = { {"Which English king was \"mad\"?","George III"},
                        {"Who started the Protestant Reformation?","Martin Luther"},
                        {"Who was the first person to see the moons of Jupiter?","Galileo"},
                        {"What Viking group settled in France before conquering England, Sicily, and Malta?","The Normans"},
                        {"What group sacked Baghdad in 1258, ending the Islamic Golden Age?","The Mongols"},
                        {"Against what city did Rome fight the Punic Wars?","Carthage"},
                        {"What yellow gas was famously used in WWI?","Mustard Gas"},
                        {"What epic poem is thought to be the oldest in the English language?","Beowulf"},
                        {"What ancient empire was led by Xerxes, Cyrus, and Darius?","Persia"},
                        {"Who was the most notorious member of the Ba'ath Party?","Saddam Hussein"},
                        {"What Italian adventurer wrote about his 24 year journey from Venice to China and back?","Marco Polo"},
                        {"What young pharaoh's tomb was discovered in 1922?","Tutankhamun"},
                        {"Before becoming king of England, what country was James I the king of?","Scotland"},
                        {"What was the primary language of the Byzantine Empire?","Greek"},
                        {"For what crime was Al Capone convicted of in 1931?","Tax Evasion"}
                        };
char geography[15] = { {"Which English king was \"mad\"?","George III"},
                        {"Who started the Protestant Reformation?","Martin Luther"},
                        {"Who was the first person to see the moons of Jupiter?","Galileo"},
                        {"What Viking group settled in France before conquering England, Sicily, and Malta?","The Normans"},
                        {"What group sacked Baghdad in 1258, ending the Islamic Golden Age?","The Mongols"},
                        {"Against what city did Rome fight the Punic Wars?","Carthage"},
                        {"What yellow gas was famously used in WWI?","Mustard Gas"},
                        {"What epic poem is thought to be the oldest in the English language?","Beowulf"},
                        {"What ancient empire was led by Xerxes, Cyrus, and Darius?","Persia"},
                        {"Who was the most notorious member of the Ba'ath Party?","Saddam Hussein"},
                        {"What Italian adventurer wrote about his 24 year journey from Venice to China and back?","Marco Polo"},
                        {"What young pharaoh's tomb was discovered in 1922?","Tutankhamun"},
                        {"Before becoming king of England, what country was James I the king of?","Scotland"},
                        {"What was the primary language of the Byzantine Empire?","Greek"},
                        {"For what crime was Al Capone convicted of in 1931?","Tax Evasion"}
                        };
char technology[15] = { {"Which English king was \"mad\"?","George III"},
                        {"Who started the Protestant Reformation?","Martin Luther"},
                        {"Who was the first person to see the moons of Jupiter?","Galileo"},
                        {"What Viking group settled in France before conquering England, Sicily, and Malta?","The Normans"},
                        {"What group sacked Baghdad in 1258, ending the Islamic Golden Age?","The Mongols"},
                        {"Against what city did Rome fight the Punic Wars?","Carthage"},
                        {"What yellow gas was famously used in WWI?","Mustard Gas"},
                        {"What epic poem is thought to be the oldest in the English language?","Beowulf"},
                        {"What ancient empire was led by Xerxes, Cyrus, and Darius?","Persia"},
                        {"Who was the most notorious member of the Ba'ath Party?","Saddam Hussein"},
                        {"What Italian adventurer wrote about his 24 year journey from Venice to China and back?","Marco Polo"},
                        {"What young pharaoh's tomb was discovered in 1922?","Tutankhamun"},
                        {"Before becoming king of England, what country was James I the king of?","Scotland"},
                        {"What was the primary language of the Byzantine Empire?","Greek"},
                        {"For what crime was Al Capone convicted of in 1931?","Tax Evasion"}
                        };
char y;
char a[2];
char answer;
int g, i = 0, points = 0;
printf("This is a trivia game, choose from History, Geography, Sport or Technology \nThere will be 5 random questions, and the user will have to enter the correct answer.\nThe user will be scored out of 5 at the end. \nPlease enter G, H, S, or T to choose which set of questions.");
scanf("%c", &y);
switch(y){
    case 'H' :
        while (i<5){
            g = (rand() % (15 + 1 - 1) + 1);
            a[1] = history[g][1];
            a[2] = history[g][2];
            printf("%c", a[1]);
            printf("What is your answer");
            scanf("%c", &answer);
            if (answer == a[2]){
                printf("Correct! 1 point");
                points++;
            } else {
                printf("Incorrect! 0 points");
            }
            i++;
        }
        printf("You got %d points.", &points);
        menu();
        break;
    case 'G' :
        break;
    case 'S' :
        break;
    case 'T' :
        break;
    default:
        printf("That was an incorrect input.");
        trivia();
return 0;

I am expecting the program to build, then to be able to run through the H case and give me points based on how many correct answers I got.

A: Like @usr mentioned in its Answer, probably it is better for you to use an Array of Pointers for this task.
Here is an Example of one of your Arrays:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

#define GETLEN(array) sizeof array / sizeof array[ 0 ]
const char *separator   ( const size_t num );

int main( void )
{
    const char *history[] =
    {
        "Which English king was \"mad\"?","George III",
        "Who started the Protestant Reformation?","Martin Luther",
        "Who was the first person to see the moons of Jupiter?","Galileo",
        "What Viking group settled in France before conquering England, Sicily, and Malta?","The Normans",
        "What group sacked Baghdad in 1258, ending the Islamic Golden Age?","The Mongols",
        "Against what city did Rome fight the Punic Wars?","Carthage",
        "What yellow gas was famously used in WWI?","Mustard Gas",
        "What epic poem is thought to be the oldest in the English language?","Beowulf",
        "What ancient empire was led by Xerxes, Cyrus, and Darius?","Persia",
        "Who was the most notorious member of the Ba'ath Party?","Saddam Hussein",
        "What Italian adventurer wrote about his 24 year journey from Venice to China and back?","Marco Polo",
        "What young pharaoh's tomb was discovered in 1922?","Tutankhamun",
        "Before becoming king of England, what country was James I the king of?","Scotland",
        "What was the primary language of the Byzantine Empire?","Greek",
        "For what crime was Al Capone convicted of in 1931?","Tax Evasion",
    };
    for ( size_t i = 0 ; i < GETLEN( history ) ; i++ )
    {
        printf("%s%s\n", separator(i), history[i] );
    }
}

const char *separator ( const size_t num )
{
    if ( num % 2 == 0 )
    {
        return "Question:\t";
    }
    return "Answer:\t\t";
}

Output:
Question:   Which English king was "mad"?
Answer:     George III
Question:   Who started the Protestant Reformation?
Answer:     Martin Luther
Question:   Who was the first person to see the moons of Jupiter?
Answer:     Galileo
Question:   What Viking group settled in France before conquering England, Sicily, and Malta?
Answer:     The Normans
Question:   What group sacked Baghdad in 1258, ending the Islamic Golden Age?
Answer:     The Mongols
Question:   Against what city did Rome fight the Punic Wars?
Answer:     Carthage
Question:   What yellow gas was famously used in WWI?
Answer:     Mustard Gas
Question:   What epic poem is thought to be the oldest in the English language?
Answer:     Beowulf
Question:   What ancient empire was led by Xerxes, Cyrus, and Darius?
Answer:     Persia
Question:   Who was the most notorious member of the Ba'ath Party?
Answer:     Saddam Hussein
Question:   What Italian adventurer wrote about his 24 year journey from Venice to China and back?
Answer:     Marco Polo
Question:   What young pharaoh's tomb was discovered in 1922?
Answer:     Tutankhamun
Question:   Before becoming king of England, what country was James I the king of?
Answer:     Scotland
Question:   What was the primary language of the Byzantine Empire?
Answer:     Greek
Question:   For what crime was Al Capone convicted of in 1931?
Answer:     Tax Evasion

A: you are initializing a char array with a list of string literals. What you want is an array of pointers.
For example:
   char *history[15] = { "Which English king was \"mad\"?","George III",
                         "Who started the Protestant Reformation?","Martin Luther",
                         ...

And the same for other arrays.


text:
Q: Spring security: is the user logged in or anonymous? I need a public restful endpoint that can tell me if the current user is logged in or not. Since the user may be authenticated as anonymousUser, I can't just do this:
if (SecurityContextHolder.getContext().getAuthentication().isAuthenticated())
...

From looking at some other posts, it looks like I might need to do something clumsy like actually look for the anonymous role in granted authorities. Is there an easier way?

A: Here's what I believe is the simplest solution:
// permitAll
@RequestMapping(method = RequestMethod.GET, value = "/isAuthorized")
public String isAuthorized(Principal user) {
    return user != null ? "Y" : "N";
}

A: You can also use (not nice, but works):
SecurityContextHolder.getContext().getAuthentication() != null &&
SecurityContextHolder.getContext().getAuthentication().isAuthenticated() &&
//when Anonymous Authentication
!(SecurityContextHolder.getContext().getAuthentication()
          instanceof AnonymousAuthenticationToken)


text:
Q: Why am I getting "Failed to request resource" when posting to a users wall on Facebook? I'm using artdarek/oauth-4-laravel so the user can login via Facebook and post to their feed. I'm able to login in via Facebook using the following bit of code
// get data from input
    $code = Input::get( 'code' );

    // get fb service
    $fb = OAuth::consumer( 'Facebook' );

    // check if code is valid

    // if code is provided get user data and sign in
    if ( !empty( $code ) ) {

        $token = $fb->requestAccessToken( $code );

        $_SESSION['facebook_access_token'] = $token->getAccessToken();

        // Send a request with it
        $user = json_decode( $fb->request( '/me' ), true );

...
And everything works as expected. In the App I also have a share button, but when I try and share I get the following error
{"error":{"type":"OAuth\\Common\\Http\\Exception\\TokenResponseException","message":"Failed to request resource.","file":"\/var\/www\/html\/myApp\/vendor\/lusitanian\/oauth\/src\/OAuth\/Common\/Http\/Client\/StreamClient.php","line":68}}

Here is the code that I'm using for posting
if ( isset($_SESSION['facebook_access_token']) ) {

        $fb = OAuth::consumer( 'Facebook' );

        // $user = json_decode( $fb->request( "/me?access_token={$_SESSION['facebook_access_token']}" ), true );

        $postMessage = json_decode( $fb->request
            (
                'POST',
                "/me/feed?access_token={$_SESSION['facebook_access_token']}",
                array (
                    'message' => 'This is a test message'
                )
            ),
        true );

        return $postMessage;
    }

I know that the $_SESSION[] is set because I ran the commented out line first and it was returning what I expected. But the code for posting on the wall is giving me that error mentioned earlier.
Please help.
Thanks

A: I found the mistake ... The call is supposed to be as follows
$postMessage = json_decode( $fb->request
            (

                "/me/feed?access_token={$_SESSION['facebook_access_token']}",
                'POST',
                array (
                    'message' => 'This is a test message'
                )
            ),
        true );

The route is supposed to be first and then the POST.


text:
Q: zendframework 2 route match is not picking up values i have a router that should provide me with several params . However the router is not returning the messId.
the config:
'messages' => array(
            'type'    => 'segment',
            'options' => array(
                'route'       => '/message[/:action][/:id][/:senderId][/:messId]',
                'constraints' => array(
                    'action'     => '[a-zA-Z][a-zA-Z0-9_-]*',
                    'id'         => '[0-9]+',
                    'senderId'   => '[0-9]+',
                    'messId'   => '[0-9]+',
                ),
                'defaults' => array(
                    'controller' => 'Messages\Controller\MessController',
                    'action'     => 'index',
                ),
            ),
        ),

the values returned from the route match:
object(Zend\Mvc\Router\Http\RouteMatch)[346]
  protected 'length' => int 42
  protected 'params' =>
    array (size=4)
      'controller' => string 'Messages\Controller\MessController' (length=36)
      'action' => string 'read-message' (length=12)
      'id' => string '4' (length=1)
      'senderId' => string '3' (length=1)
  protected 'matchedRouteName' => string 'messages' (length=15)

you will note above that the route match for messId is missing;
below i my URL
url('messages', array('action'=>'read-message','senderId'=>$this->escapeHtml($user['id']), 'messId'=>$this->escapeHtml($user[0]['id']) ))}'>Read Message

thank you for your kind assitance.

A: The issue is ambiguity in your route. :id, :senderId and :messId are all optional, and they're all numbers. So given a URL like http://testingzend2/send-message/read-message/7/2 how can ZF know which variable each number relates to?
You either need to make these not optional, or change the route so there's no ambiguity. For example you could do this instead:
'route' => '/message[/:action][/id/:id][/senderId/:senderId][/messId/:messId]',

Which would give you a URL like http://testingzend2/send-message/senderId/7/messId/2


text:
Q: Developing Talking Map? I need to develop a prototype of a web application that speaks :
When you click on a city (point) it says the city name (Audio files are ready)
I want to use ArcGIS Javascript API. do you have any idea how can I implement this idea ?

A: You probably want to start with something like this example:
require(["esri/map", ...], function(Map, ...) {
  var map = new Map("mapDiv"),
  mapOnLoad = map.on("load", function(){
    map.graphics.on("click", myGraphicsClickHandler);
  });
  map.addLayer(...);

  function myGraphicsClickHandler(evt) {
    alert("User clicked on " + evt.graphic);
  }
});

(from Working with Events)


text:
Q: Matching a format string defining colour codes I want to match a format string (e.g. \033[1;42;35m) in a bash function, so the function can accept different colour setting when printing text.
Example for format is \033[1;42;35m, in general \033[NA;NB;NCm
and want to match the [NA;NB;NCm part.
Am playing with
if [[ "$1" =~ \[[0123456789]+;[0123456789]+;[0123456789]+m ]] ; then

The problem is the following errors
./mosc.rc: line 480: syntax error in conditional expression: unexpected token `;'
./mosc.rc: line 480: syntax error near `;['
./mosc.rc: line 480: `if [[ "\033[1;42;35m" =~ \[[0123456789]+;[0123456789]+;[0123456789]+m ]] ; then'

Escaping the ; seems to work.
if [[ "$1" =~ \[[0123456789]+\;[0123456789]+\;[0123456789]+m ]] ; then


text:
Q: Can't connect to MongoDB Atlas inside a Docker container I have a Spring Boot application running in a Docker container which is deployed on Google Cloud Run. For a few months this works perfectly fine. But now, without any action, my application can't connect to the MongoDB Atlas cluster anymore. I get the following error message:
com.mongodb.MongoSocketOpenException: Exception opening socket at com.mongodb.connection.netty.NettyStream$OpenChannelFutureListener.operationComplete(NettyStream.java:416)

If I run the application locally it works fine again. But if I run it inside a Docker container (also locally) I get the same error message.
Has anyone an idea what the problem can be? I've whitelist 0.0.0.0/0 on MongoDB Atlas so that the connection should work from everywhere.


text:
Q: Having trouble with dynamic controls on my ASP.Net web site I have an asp.net web page which is giving me some problems. I developed the following classes to generate search filters for the page. The search process is not important as it already works. I want to dynamically generate the search filters.
Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports MEI.SPDocuments.Type

Public Class SearchFilter
    Private WithEvents _genreDropDown As DropDownList
    Private WithEvents _subGenreDropDown As DropDownList
    Private WithEvents _txtValue As TextBox
    Private _txtBoxAutoCompleteExtender As AjaxControlToolkit.AutoCompleteExtender
    Private _filterGenres As Collection(Of String)
    Private _programSubGenres() As String = {"Program ID,GetPrograms", "Territory ID,GetTerritories", _
                                             "Rep Name,GetRepNames", "District ID,GetDistricts", "DM Name,GetDMNames", "Region ID,GetRegions", _
                                             "RM Name,GetRMNames", "Speaker Counter,GetSpeaker", "Vedor ID,GetVendors", "Vendor Name,GetVendorName", _
                                             "Date Range,", "City,", "State,", "Pay To,", "Expense Range,", "PIF ID,GetPifs"}
    Private _speakerSubGenres() As String = {"Speaker Counter,GetSpeaker", "Speaker Last Name,GetSpeakerLNames", "Speaker First Name,GetSpeakerFNames"}
    Private _expenseSubGenres() As String = {"Expense Counter,GetExpenses"}
    Private _vendorSubGenres() As String = {"Vendor ID,GetVendors", "Vendor Name,GetVendorName"}
    Private _trackSubGenres() As String = {"Track Number,GetTracks", "HCP First Name,GetHCPFName", "HCP Last NameGetHCPLName"}

    Public Sub New(ByVal company As CompanyCode, ByVal year As DocumentYearCode)
        _filterGenres = New Collection(Of String)

    _txtValue = New TextBox
    _txtValue.ID = Guid.NewGuid.ToString

    _txtBoxAutoCompleteExtender = New AjaxControlToolkit.AutoCompleteExtender
    With _txtBoxAutoCompleteExtender
        .ID = "AC__" + _txtValue.ID
        .MinimumPrefixLength = 1
        .EnableCaching = False
        .ServicePath = "~/AutoComplete.asmx"
        .ServiceMethod = "PlaceHolder"
        .TargetControlID = _txtValue.ID
        .CompletionListCssClass = "CompletionList"
        .CompletionListHighlightedItemCssClass = "ItemHighlighted"
        .CompletionListItemCssClass = "ListItem"
        .DelimiterCharacters = ""
        .Enabled = True
    End With

    Select Case company
        Case CompanyCode.AbbottAnimalHealth, CompanyCode.AbbottDiabetesCare, CompanyCode.AbbottDiagnosticsDivision, CompanyCode.AbbottMedicalOptics, CompanyCode.AbbottMolecular, _
            CompanyCode.AbbottPointOfCare, CompanyCode.AbbottVascular, CompanyCode.Corporate, CompanyCode.DivAbbottNutrition, CompanyCode.EstablishedProductsDivision, _
            CompanyCode.GlobalPharmaceuticalResearchAndDevelopment, CompanyCode.GlobalStrategicMarketingAndServices, CompanyCode.PharmaseuticalProductsGroup, _
            CompanyCode.ProprietaryPharmaceuticalsDivision, CompanyCode.RegulatoryAffairsPPG
            _filterGenres.Add("Div Docs")
        Case Else
            _filterGenres.Add("Program")
            _filterGenres.Add("Speaker")
            _filterGenres.Add("Expense")
            _filterGenres.Add("Vendor")
    End Select
    _genreDropDown = New DropDownList
    _genreDropDown.AutoPostBack = True
    _genreDropDown.Attributes.Add("runat", "server")
    AddHandler _genreDropDown.SelectedIndexChanged, AddressOf _genreDropDown_ItemChanged

    _subGenreDropDown = New DropDownList
    _subGenreDropDown.AutoPostBack = True
    _subGenreDropDown.Attributes.Add("runat", "server")
    AddHandler _subGenreDropDown.SelectedIndexChanged, AddressOf _subGenreDropDown_ItemChanged
    PopulateDDls()
End Sub

Private Sub PopulateDDls()
    _genreDropDown.Items.Add("")
    For Each s As String In _filterGenres
        _genreDropDown.Items.Add(s)
    Next
End Sub

Private Sub _genreDropDown_ItemChanged(ByVal sender As Object, ByVal e As System.EventArgs)
    _subGenreDropDown.Items.Clear()
    _subGenreDropDown.Items.Add("")
    Select Case _genreDropDown.SelectedItem.ToString
        Case "Program"
            For Each s As String In _programSubGenres
                Dim li As New ListItem(s.Split(CChar(","))(0), s.Split(CChar(","))(1))

                _subGenreDropDown.Items.Add(li)
            Next
        Case "Speaker"
            For Each s As String In _speakerSubGenres
                Dim li As New ListItem(s.Split(CChar(","))(0), s.Split(CChar(","))(1))

                _subGenreDropDown.Items.Add(li)
            Next
        Case "Expense"
            For Each s As String In _expenseSubGenres
                Dim li As New ListItem(s.Split(CChar(","))(0), s.Split(CChar(","))(1))

                _subGenreDropDown.Items.Add(li)
            Next
        Case "Vendor"
            For Each s As String In _vendorSubGenres
                Dim li As New ListItem(s.Split(CChar(","))(0), s.Split(CChar(","))(1))

                _subGenreDropDown.Items.Add(li)
            Next
        Case "Div Docs"
            For Each s As String In _trackSubGenres
                Dim li As New ListItem(s.Split(CChar(","))(0), s.Split(CChar(","))(1))

                _subGenreDropDown.Items.Add(li)
            Next
    End Select
End Sub

Private Sub _subGenreDropDown_ItemChanged(ByVal Sender As Object, ByVal e As System.EventArgs)
    _txtBoxAutoCompleteExtender.ServiceMethod = _subGenreDropDown.SelectedValue.ToString
    If _subGenreDropDown.SelectedValue.ToString = String.Empty Then _txtBoxAutoCompleteExtender.ServiceMethod = "PlaceHolder"
End Sub

Public Function createMyTableRow() As HtmlTableRow
    Dim myRow As New HtmlTableRow

    myRow.Cells.Add(New HtmlTableCell())
    myRow.Cells.Add(New HtmlTableCell())
    myRow.Cells.Add(New HtmlTableCell())

    myRow.Cells(0).Controls.Add(_genreDropDown)
    myRow.Cells(1).Controls.Add(_subGenreDropDown)
    myRow.Cells(2).Controls.Add(_txtValue)
    myRow.Cells(2).Controls.Add(_txtBoxAutoCompleteExtender)

    Return myRow
End Function

Private Sub newAutoCompleteExtender(ByVal genre As String)
    If _txtValue.Parent.Controls.Count = 2 Then
        _txtValue.Parent.Controls.RemoveAt(1)
    End If

    _txtValue.Parent.Controls.Add(_txtBoxAutoCompleteExtender)
End Sub

End Class

Public Class SearchFilterGroup

Private _searchFilterCollection As Collection(Of SearchFilter)
Private _tableContainer As HtmlTable
Private _company As CompanyCode
Private _year As DocumentYearCode
Public WithEvents _addFilterButton As New Button

Public Sub New(ByVal company As CompanyCode, ByVal year As DocumentYearCode)
    _searchFilterCollection = New Collection(Of SearchFilter)
    _tableContainer = New HtmlTable
    _company = company
    _year = year

    _addFilterButton.Text = "Add Filter"
    _addFilterButton.Attributes.Add("runat", "server")
    _addFilterButton.ID = "btnAddFilter"
    AddHandler _addFilterButton.Click, AddressOf _addFilterButton_Click
End Sub

Public Sub _addFilterButton_Click(ByVal Sender As Object, ByVal e As System.EventArgs)
    _searchFilterCollection.Add(New SearchFilter(_company, _year))
    _tableContainer.Rows.Add(_searchFilterCollection(_searchFilterCollection.Count - 1).createMyTableRow)
End Sub

Public Function table() As HtmlTable
    _tableContainer.Rows.Add(New HtmlTableRow)
    _tableContainer.Rows(0).Cells.Add(New HtmlTableCell)
    _tableContainer.Rows(0).Cells(0).ColSpan = 3

    _tableContainer.Rows(0).Cells(0).Controls.Add(_addFilterButton)
    _addFilterButton_Click(Nothing, Nothing)
    _addFilterButton_Click(Nothing, Nothing)

    Return _tableContainer
End Function
End Class

I am having problems devising a way to persist the generate controls. Any help would be appreciated.

A: Basically, for task which you do is better to create custom server control. In ASP.NET exist CompositeControl class which simplifies developing your own server controls which for example should include some other server controls (like panels, texboxes and etc) as children.
A very good link to start with creating your own server controls is Dino Esposito article: A Crash Course on ASP.NET Control Development: Building Composite Controls


text: Q: How can I determine when a commit in the Flutter engine repo is available on a given Flutter SDK channel? I'd like to be able to find out how I can tell when a specific merge commit on the Flutter engine repo (eg. this PR's: https://github.com/flutter/engine/pull/10434  had an "engine roll" merge of https://github.com/flutter/flutter/pull/37531) is available of a specific Flutter SDK channel, ie. when its in the engine used on current version of the Flutter SDK in the dev, beta, stable channels.


text:
Q: Use invocable variable of type List in Process Builder I have an invocable method:
@InvocableMethod(Label = 'Submit Privacy Source')
public static void action(ActionRequest[] requestActionInList) {...}

ActionRequest is:
public with sharing class ActionRequest {
    @InvocableVariable(Label = 'Data Subject ID' Required = true)
    public Id dataSubjectId;

    @InvocableVariable(Label = 'Privacy Source Name' Required = true)
    public String privacySourceName;

    @InvocableVariable(Label = 'Consent Request Names')
    public String[] consentRequestNames;
}

When I try to set values for consentRequestNames variable in Process Builder it allows to set it as a single string only.

How to set a list of strings instead of a single string for consentRequestNames variable?

A: It's not possible to pass list as what you want. Try another way of getting list. You can pass multiple parameters but not the list.


text:
Q: Infinite For Loop issue in Python I need to extract an ID from a JSON string that is needed for loading information into a MySQL database. The ID is a 5 or 6 digit number, but the JSON key that contains this number is the URL net_devices resource string that has the number at the end like this example:
{u'router': u'https://www.somecompany.com/api/v2/routers/123456/'}

Since there is not a key with just the ID, I have used the following to return just the ID from the JSON key string:
url = 'https://www.somecompany.com/api/v2/net_devices/?fields=router,service_type'

r = json.loads(s.get((url), headers=headers).text)
status = r["data"]

for item in status:
    type = item['service_type']
    router_url = item['router']
    router_id = router_url.replace("https://www.somecompany.com/api/v2/routers/", "")
    id = router_id.replace("/", "")
    print id

This does indeed return just the ID values I want, and it doesn't matter if the result varies in the number of digits.
The problem: This code creates an infinite loop when I include the two lines above the print statement.
How can I change the syntax to allow the loop to run through all the returned IDs once, but still strip out everything except the numerical ID?
I am new to Python, and just starting to write code again after a very long hiatus since college. Any help would be greatly appreciated!
UPDATE
Thanks everyone for the feedback! With the help from David and Gerrat, I was able to find the issue that was causing the infinite loop and it was not this segment of the code, but another segment that was not properly indented. I am learning how to properly indent loops in Python, and this was one of my silly mistakes! Thanks again for the help!


text:
Q: Sharing keyboard and mouse between two boxes I have a Mac and PC that I need to share the USB keyboard and mouse connections with.  They each have a separate monitor.
I think a regular KVM switch is overkill because of the separate monitors, but the USB switches I've seen appear to only allow for one device to be split-- I've looked at Amazon and other reputable dealers and haven't seen different at least?
Will I need to buy two USB switches, or are there creative ways I can share the keyboard and mouse via USB with one switch?

A: One possible way is a "Software KVM" like Synergy. Lifehacker has a nice write-up on the setup and requirements, but it will probably solve your problem.

A: I used a KVM switch in this setup, just don't use the monitor plug on the switch. Leave the monitors directly connected to the computers and use the KVM switch for the keyboard and mouse only. Plug both the keyboard and mouse into a small USB splitter and you'll only need one switch.


text:
Q: How can I detect my graphics card with no driver installed? I have no idea what graphics card hardware do I have, and have no driver installed. How can I detect what graphics card do I have to install the right driver?

A: For Windows I would see if Slimdrivers can autodetect it first otherwise try this.
Device Manger->Display Adapter
Right click on the device and click properties.
Click on the details tab.
Use the drop down to select:"Hardware Ids"
Ven is short for vendor so ATI/AMD, nvidia, Intel are the most common.
Dev is the device ID.
google   Dev #### and Ven ####
You should be able to find it.

A: Have a look at the output of dmesg or lspci or lsusb (if it is a USB video card).
For me, I get the following:
> lspci | grep -i vga
03:00.0 VGA compatible controller: NVIDIA Corporation GT218 [ION] (rev a2)


text:
Q: NSURLSession in For Loop to Download Image Data then add to NSMutableArray My application has a UITableView with a cell that contains a UICollectionView subview (not reused). The collectionView's cells have a single UIImageView to hold a picture. I am trying to download all of the images at once, store them in an array, and then display the contents of the array in the collectionView cell once the images are all downloaded. In ObjC I have done this many times using NSURLConnection but I am trying to use Swift and NSURLConnection to achieve this but I'm running into what I believe may either be concurrency or semantics issues. Maybe one of you guys could point me in the right direction because I feel like I'm spending too much time on this.
In my UITableView's cell subclass that contains the collectionView I am calling
func downloadPhotosWithURLs(urls: [String]) {

    var imagesMutableArray = NSMutableArray()

    for url in urls {

        NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)!, completionHandler: { (data, repsonse, err) -> Void in

            if let imgData = data {

                if let image = UIImage(data: imgData) {

                    imagesMutableArray.addObject(image)

                }

                else {

                    // PUT IN "Photo Unavailable" Pic
                }
            }

            else {

                // PUT IN "Photo Unavailable" Pic
            }

        }).resume()

    }

    // UPDATE (but async op not done)
    if let downloadedImages: [UIImage] = imagesMutableArray as NSArray as? [UIImage] {

        self.images = downloadedImages

        dispatch_async(dispatch_get_main_queue(), { () -> Void in

            self.collectionView.reloadData()
        })

    }

}

Problem is by the time I call for the collectionView to be reloaded, the images have not been fetched. The asynchronous operations in the for loop are certainly to blame. How to I call my // UPDATE code after the images are all downloaded?

A: If you want to wait for a series of asynchronous tasks to finish, create a dispatch_group_t, enter the group before starting each request, leave the group in the completion block, and then you can rely on dispatch_group_notify to be called when each "enter" is matched with a "leave"
func downloadPhotosWithURLs(urls: [String]) {
    var images = [UIImage]()

    let group = dispatch_group_create()

    for url in urls {
        dispatch_group_enter(group)
        NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)!, completionHandler: { data, response, error in

            if let imgData = data {
                if let image = UIImage(data: imgData) {
                    dispatch_sync(dispatch_get_main_queue()) {
                        images.append(image)
                    }
                } else {
                    // PUT IN "Photo Unavailable" Pic
                }
            } else {
                // PUT IN "Photo Unavailable" Pic
            }

            dispatch_group_leave(group)
        }).resume()
    }

    // UPDATE
    dispatch_group_notify(group, dispatch_get_main_queue()) {
        self.images = images
        self.collectionView.reloadData()
    }
}

Note, you really should synchronize your updates of the array of images (mutable arrays are not thread safe).
--
Having hopefully answered the question, I must confess that I would probably advise two further, yet significant changes:

*

*You shouldn't hold images in an array (because if there are too many, you can run out of memory). The JPEG or PNG files might not look too large, but when the images are uncompressed in RAM, they can take a lot of memory and you can easily get memory warnings.
You might consider downloading the images to persistent storage, not into memory. If you want to hold images in memory, use a NSCache for performance reasons (but purge it upon memory warning).
If you don't have too many images, or they're all small this may not be critical. But if you're looking for a scalable solution, don't require your app to hold all of the images in an array.

*You might not want to wait for all of the images before reloading the collection view. Generally people would advise lazy loading. So if you have 1000 images and only 20 are visible at a time, why wait for 1000 images? Focus on loading the images for the visible cells. Also, you might want to see the images pop into the collection view as they're downloaded (so rather than waiting for the first 20 visible images to be downloaded, show them as they come in).
You generally accomplish this by having cellForItemAtIndexPath initiate the image download asynchronously and update the cell when it's done.


text:
Q: WSO2APIM is case sensitive I had a problem with api manager, the context that I created it's all in lower case, but some clients send request the context with capital letters, and api manager don't recognize these calls, but in the publiser interface is case insensitive, the context application.api is the same Application.Api, there some way to fix this, create some sequence to fix requests or api manager follow the the RFC 2616 section 3.2.3, where clients needs to request uri in case sensitive?
Thank you

A: Yes, As stated in the HTTP/1.1 specification, RFC2621 section 3.2.3 [1] the path in HTTP URLs are required to be case-sensitive.
[1] https://www.rfc-editor.org/rfc/rfc2616#section-3.2.3


text:
Q: Unable to unalias rm and let it to be a function in Zsh I run unsuccessfully in my .zshrc
unalias rm
rm() { mv $* /tmp/wastebasket }

I get at the startup
/Users/Masi/.zshrc:unalias:34: no such hash table element: rm

I noticed that the hash table problem has been an unresolved bug in Ubuntu for run-help.
I am not sure whether the bug applies to Mac and to rm -command too.
How can you get the notification off at the startup?

A: You should only try to remove an alias that exists.
Creating an alias that is unaliased right away strikes me as ugly.
My recommendation is to test for rm being an alias and unaliasing if so.
 case $(type rm) in
     (*alias*) unalias rm;;
 esac

Or use brute force and ignore stderr with
 unalias rm 2>/dev/null

A: Everyone else is right that you simply didn't have an alias.  More importantly:
DON'T do this.  Some day you will be at another POSIX machine that follows POSIX standards (deleting without "recycling"), and you will casually delete something and have no way to undo it.  Learn rm discipline now.

A: That error message is because you're trying to unalias rm and there is no such alias.
Since you can alias something more than once without an error, I would change your code to be:
alias rm=x
unalias rm
rm() { mv $* /tmp/wastebasket }

That guarantees that rm exists as an alias before you try to unalias it.

A: I'm not very familiar with zsh, but perhaps it is because rm is not an alias, but is actually a standard utility residing in /bin.
You could just alias it without attempting to unalias it first, overriding any previous alias.