text:
Q: Rails 3.0.3 resource route no index mapped? I am trying to use a very simple resource route for my Buildings Controller.
resource :buildings

This results in the following mappings
buildings POST   /buildings(.:format) {:controller=>"buildings", :action=>"create"}
         new_buildings GET    /buildings/new(.:format)          {:controller=>"buildings", :action=>"new"}
        edit_buildings GET    /buildings/edit(.:format)         {:controller=>"buildings", :action=>"edit"}
                       GET    /buildings(.:format)              {:controller=>"buildings", :action=>"show"}
                       PUT    /buildings(.:format)              {:controller=>"buildings", :action=>"update"}
                       DELETE /buildings(.:format)              {:controller=>"buildings", :action=>"destroy"}

Anyone know why there is no index action mapped for the default /buildings GET request? I'm using rails 3.0.3

A: I think you want to use resources instead of resource. You can read about the difference here: http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Resources.html#method-i-resource


text:
Q: jQuery: Add click functionality to images to open/close a menu I'm building Javascript-based menu and have gotten somewhat stuck with my jQuery code, which goes as follows:
// Add <img> tags
$(".menu-block-wrapper").find('li').not('.leaf').prepend('<img src="plus-sign.png"/>');

// Add clicking functionality to images
$(".menu-block-wrapper").find('li').not('.leaf > img').click(
     function(event) {
       $('ul', this).first().toggle();

       var ul = $('ul', this).first();

       if (ul.is(":hidden")) {
        $('img', this).first().attr( "src", "plus-sign.png" );
       } else {
        $('img', this).first().attr( "src", "minus-sign.png" );
       }

       event.stopPropagation();
    });

Running this code in my test page (jQuery Test Page), I get satisfactory results. (Note that other functionality, such as giving expanded menu items the proper icon, is handled by other code, so don't worry about that.)
However, the clicking functionality is applied to the entire <li> tag. I want the clicking functionality to only apply to the <img> tag. My lack of knowledge of jQuery seems to be limiting me here, as everything I have tried broke the clicking functionality.
It may be handy to use my jQuery Test Page to assert your proposed changes. Thanks for your time.

A: I think you want:
$(".menu-block-wrapper").find('li img').not('.leaf > img').click( ...

This will define the click function on images nested inside list-items that are not immediate-childen of an element with class-name "leaf"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Type inference surprising behaviour Say I define the following class
class X[K, T](create: K => T) {

}

and then I defining the following:
class A {

    val cb = new X[Int, B](i => new B(i))  // infers type fine
    val cc = new X[Int, C](i => new C(0, i))  // cannot infer type and requires parameter type

    class B(i: Int) {}

    class C(i1: Int, i2: Int) {}
}

I am wondering why the compiler cannot infer the type for i in the creation of cc?
Thanks
Des

A: I think it is a typo:
val cc = new X[Int, C](i => new C(0, i))

With new X[Int, B](i => new C(0, i)) you are telling compiler that X is of type X[Int, B] but rather providing the constructor argument create as => C (which should be => B).
Hence it throws an error that it expects B but you provided C

A: I think the error message is incorrect. C is not a subtype of B, so you cannot instantiate an X[Int, B] with new C() unless C extends B.
For example, this code works fine:
class A {

  val cb = new X[Int, B](i => new B(i))
  val cc = new X[Int, B](i => new C(0, i))

  class B(i: Int) {}

  class C(i1: Int, i2: Int) extends B(i1){}
}


text:
Q: IsTabStop="False" has no effect on my WPF app I'm having a really hard time with something that should be trivial. I just want to remove a few buttons from the tab order on a UserControl. I've tried adding IsTabStop="False" and KeyboardNavigation.IsTabStop="False" attributes to their xaml declarations, as well as setting myButton.IsTabStop = false; in the Loaded event handler for the UserControl. None of these additions had any effect, I could still tab to the controls I did this for.
Setting the TabIndex in the xaml works fine. The UserControl is being displayed in a WPFElementHost if that might make a difference. The other thought I had was that I might need to specify the TabIndex for all the other controls, but I haven't read that anywhere and I'd prefer to not state that explicitly if possible. Does anyone have a guess as to what might be going wrong?

A: Try setting KeyboardNavigation.TabNavigation ="None" in the parent control.

A: You need also employ
KeyboardNavigation.TabNavigation ="Continue" for the parent controls, and
"Focusable=False"


text:
Q: Como achar números primos num determinado intervalo? Preciso de uma ajuda nesse programa, na parte do for. Seguinte, preciso imprimir os números primos dentro desse intervalo A e B determinado pelo usuário, o problema é que o programa só imprimi um numero dentro desse intervalo.E tbm mostrar se tem ou não número primo dentro do intervalo. Agradeço caso alguem posso ajudar.
#include<stdlib.h>
#include<stdio.h>
main(){
int a, b, div=0;
printf("Digite o numero a:\n");
scanf("%d",&a);
if (a>=0 && a<=100){
    printf("Numero a esta entre 0 e 100\n",a);
}else{
    printf("Nao esta entre 0 e 100, digite novamente:\n", a);
    while(a>100){
        printf("Numero ivalido, digite novamente: \n");
        scanf("%d", &a);

    }
}
printf("Digite o numero b:\n");
scanf("%d",&b);
if (b>=0 && b<=100){
    printf("Numero b esta entre 0 e 100\n",b);

}else{
    printf("Nao estao entre 0 e 100, digite novamente:\n",b);
    while(b>100){
        printf("Numero invalido, digite novamente: \n");
        scanf("%d",&b);

    }

}
for(int i=a+1;i<b;i++){
    if(div%i==0){
        div++;
        printf("%d\n",i);

    }

}
if(div==2){
    printf("Sem numeros primos no intervalo");
}

}

A: Fiz um pequeno exemplo funcional para você analisar, lembrando que os números primos so podem ser divididos por ele mesmo e por um, por isso é necessário mais de uma estrutura de repetição no código, qualquer duvida me contate :)
int primo=0;
int a = 0;
int b = 1;
int tem_primo = 0;

printf("Numeros primos::.\n");

for(int i = a; i<=b; i++){

  //Inicia o verificador sempre como zero
  primo=0;

  for (int x = 1; x <=i; x++) {

    if(i % x == 0){
      primo++;
    }

  }
  if(primo==2){

    //Mostra na tela os numeros primos um a um
    printf("%d; ", i);
    tem_primo = 1;
  }
}

//Verifica se há primos no intervalo
if(tem_primo == 0){
  printf("\nNao possui primos no intervalo");
}


text:
Q: Discrete mathematics. Just an impression, or this is always true? I feel that the following is always true:
$$ \frac{2^k-1}{3} \equiv 1 ~(\text{mod }2) \text{ if }k \equiv 0 ~(\text{mod }2) \wedge k \geq 2$$
I've just tried it using a "brute force" approach, but I'm not able to prove it in a formal way.
Where can I start?

A: $$
\frac{2^k-1}{3} \equiv 1 ~(\text{mod }2) \hspace{10mm}\Leftrightarrow\hspace{10mm} 2^k-1 \equiv 3 \equiv 1~(\text{mod }2) \hspace{10mm}\Leftrightarrow\hspace{10mm} 2^k \equiv 0 ~(\text{mod }2).
$$
The last claim is certainly true. By the way, it is true for all $k\ge 1$.

A: $$\frac{2^k-1}3=\frac{0-1}1\pmod 2=-1=1\pmod2$$

A: When k is even,
 $$ 2^k = 2^{2n} = 4^n $$
Factoring (when n > 0):
$$
    4^n - 1 = (4-1) \times (1 + 4 + ... + 4^{n-1})
    = 3 \times (1 + 4x)
$$
(for some integer x), which gives us:
$$
{{2^k-1}\over 3} = {{(4^n -1)}\over{3}} = 1 + 4x = 1\mod 2
$$
When k is odd, k = (2n+1)
$$
    2^k - 1 = 2^{2 n + 1} - 1 = 4^n\times 2 - 1 = 4^n + 4^n - 1 = 4^n + 3\times(1+4x)
$$
and
$$
    {{2^k-1}\over 3} = {{4^n + 3\times(1+4x)}\over 3} = {{4^n}\over 3} + (1+4x)
$$
Since
$$
4^n \neq 0 \mod 3,
$$
this is never an integer, so
$$
{{2^k-1}\over 3} \neq  1\mod 2
$$


text:
Q: return datetime in c# in class - Invalid cast from 'DateTime' to 'Int64' It is such that I have to have a date from tablen which has Date Hours,
I'll show something when I have an offer on the page which will be displayed on some dates,
I have tried to do like this
In my class RabatHelper.cs
public static long DatoFrom()
{
    DataClassesDataContext db = new DataClassesDataContext();

    var RabatPriser = db.RabatPrisers.FirstOrDefault(A => A.Id == 1);
    if (RabatPriser != null)
    {
        return Convert.ToInt64(RabatPriser.fromdato);
    }
    return 0;
}

and in my packages should I have date forward to where I need it,
DateTime DatoFrom = new DateTime(RabatHelper.DatoFrom());

What it gives errors is this:
Invalid cast from 'DateTime' to 'Int64'.
if (RabatPriser != null)
{
return Convert.ToInt64(RabatPriser.fromdato);
}
return 0;

What I expect it to be able to do it's like it can do something like this here
DateTime DatoFrom = new DateTime(2015, 6, 24);

A: You cannot directly convert a DateTime to a long. Why not keep your DateTime as is:
public static DateTime DatoFrom()
{
    DataClassesDataContext db = new DataClassesDataContext();

    var RabatPriser = db.RabatPrisers.FirstOrDefault(A => A.Id == 1);
    if (RabatPriser != null)
    {
        return RabatPriser.fromdato;
    }
    //Instead of 0, return the minimum value?
    return DateTime.MinValue;
}


text:
Q: How to run protractor tests with "ng e2e" against node server instead of webpack-dev-server Running e2e tests against prod bundle with webpack-dev-server
In Angular one can run protractor tests against the prod build using
"e2e:prod": "ng e2e --prod"

This will build the prod bundle, start the webpack-dev-server and run protractor. Once this is done, the webpack-dev-server will be shutdown. Anyhow this is not what we are looking for... see below
How to shutdown node server once protractor is finished ?
For our continous integration we want the e2e tests to run against a node server and not the webpack-dev-server. So we tried starting the node server and then running the protractor tests.
For this purpose we introduced a new script in our package.json that our ci server executes:
npm run e2e:ci

Solution 1 - use concurrently (not working):
"e2e:ci": "concurrently -k \"npm:e2e:ci:serve\" \"npm:e2e:ci:protractor\"",
"e2e:ci:serve": "node server.js",
"e2e:ci:protractor": "ng e2e --base-url=http://localhost:8080/ --dev-server-target="

This solution almost works. Having --dev-server-target= without target will stop angular to build the bundle (we are on angular 7). e2e:ci:serve starts the node server, assuming the prod bundle was build before so it can be served. BUT - once protractor is finished it will kill the node server so it exists with code 1:
--> Sending SIGTERM to other processes..
[serve:server] npm run serve:server exited with code 1
npm ERR! code ELIFECYCLE

Since I used concurrenlty with -k (kill) the node server stops once protractor is finished. But with exit code 1, so our ci assumes the e2e test failed.
Solution 2 - use npm-run-all (not working)
we also tried npm-run-all instead of concurrently with the race flag -r:
"e2e:ci": "npm-run-all -p -r e2e:ci:serve e2e:ci:protractor",

But this will leave the server running once protractor is finished. So the e2e test never stops.
Anybody has a clue how to do this correctly? Either shutdown the node server gracefully or maybe another approach to archieve running e2e tests against node server?

A: Ok, we finally figured it out to make it run with npm-run-all -r, at least under linux. Our express server needed to listen to SIGTERM signal. Here all together:
package.json
"e2e:ci": "npm-run-all -p -r e2e:ci:serve e2e:ci:protractor",
"e2e:ci:serve": "node server.js",
"e2e:ci:protractor": "ng e2e --base-url=http://localhost:8080/ --dev-server-target="

server.js
var app = express();
var server = require('http').createServer(app);
server.listen(8080);

process.on('SIGTERM', function () {
    server.close(function () {
        process.exit(0);
    });
});


text:
Q: Access container page of a component in .net based CT We are developing a .net based CT based on Broker query Mechanism (filter):
ComponentPresentationAssembler  cpAssembler = new ComponentPresentationAssembler(Page ID,Page object);

In order to pass the page ID, I need to get the access of page on which the component is present.
How can I access the page from package? Since this a CT, a component object would be available in page and not a page object.
Tried the following piece of code, but without success:
string pageURI = _package.GetValue("Page.ID");
Page objPage = (Page)_engine.GetSession().GetObject(pageURI);

This is not working as there is no page object. What are the alternatives so that we can access the parent page of component from CT?

A: To address this I created an AddPageToComponentPresentation TBB. Here's the code:
using System;
using System.Collections.Generic;
using System.Text;

using Tridion.ContentManager;
using Tridion.ContentManager.Templating;
using Tridion.ContentManager.Templating.Assembly;

namespace Tridion.Extensions.ContentManager.Templating {
    [TcmTemplateTitle("Add Page To ComponentPresentation")]
    class AddPageToComponentPresentation : TemplateBase {
        public override void Transform(Engine engine, Package package) {
            if (engine.PublishingContext.RenderContext.ContextItem != null) {
                Item pageItem = package.CreateTridionItem(ContentType.Page, engine.PublishingContext.RenderContext.ContextItem.Id);
                package.PushItem("Page", pageItem);
                Logger.Debug("Page Item added to Package");
            } else {
                Logger.Debug("No Context Item found");
            }
        }
    }
}

A: Thanks a lot Jeremy.
I tried this code, but was not able to use the interface TemplateBase
With hints from your code, I tried
Page page = _engine.PublishingContext.RenderContext.ContextItem as Page;

and this worked well. Also I could get publication object as:
Publication pub = (Publication)page.ContextRepository;

Thank you very much.


text:
Q: No properties to serialize found on class com.google.firebase.firestore.FieldValue$ServerTimestampFieldValue I'm using React Native Firebase Firestore to store Server Timestamp. I have following code to add to store data in Firestore.
const data = {
        userid: this.props.user.id,
        created_at: firebase.firestore.FieldValue.serverTimestamp()
    }

firebase.firestore().collection('users').add(data).then(function (docRef) {
        alert('Successfully sent friend request!');
    }).catch(function (error) {
        alert(error);
    });

But I have an error after executing this code. Error screenshot


text:
Q: Get Labels of binary tree I'm struggling with my assignment.
First we had to define the predicate tree/1, where node(leaf(1), node(leaf(2), leaf(3))).  should return true
tree(leaf(_)).
tree(node(X,Y)) :- tree(X), tree(Y).

Pretty simple.
Now I have to write two predicates, which should essentially work the same. label/2 and labels/2.
label(B,X) checks whether X is a label in B and should print X=1;X=2;X=3. for the example given above.(B is a binary Tree)
labels(B,Y) is the same as label/2 except that Y is a list containing all the labels. (Y=[1,2,3]).
What I have right now:
label(leaf(Y),X) :-
    %print X?
label(node(Y,Z),X) :-
    label(Y,X), label(Z,X).

and
labels(leaf(Y),X) :-
    %append Y to X
labels(node(Y,Z),X) :-
    labels(Y,X), labels(Z,X).

I just can't wrap my head around when prolog prints just true and when it provides a solution for X/Y.

A: You're not far.
First: label/2.
For the leaf/1 case, you have simply to unify the second argument with the content of the label; that is
label(leaf(X), X).

For the node/2 case, it's wrong (if I understan your requirements)
label(Y,X), label(Z,X)

because you're asking that X is a value present in node Y and in node Z. You should ask that X is present in node Y or in node Z. That is (using "or" operator ";")
label(node(Y,Z),X) :-
    label(Y,X) ; label(Z,X).

or better (IMHO) developing two separate clauses
label(node(Y, _), X) :-
    label(Y, X).

label(node(_, Y), X) :-
    label(Y, X).

Second: labels/2
The leaf/1 case is similar to the label with the difference that you have to unify the second argument not with the content of label/1 (the first argument) but with a list contain that content. It's really simple
labels(leaf(X), [X]).

The node/2 case is different.
Your solution
labels(Y,X), labels(Z,X).

is wrong because you're asking that the subnode Y and the subnode Z are containing the same list of labels.
You have to collect the sublist of Y, collect the sublist of Z and concatenate they obtaining X; that is
labels(node(Y, Z), X) :-
    labels(Y, X1),
    labels(Z, X2),
    append(X1, X2, X).

Summarizing, I propose the following label/2 and labels/2
label(leaf(X), X).

label(node(Y, _), X) :-
    label(Y, X).

label(node(_, Y), X) :-
    label(Y, X).

labels(leaf(X), [X]).

labels(node(Y, Z), X) :-
    labels(Y, X1),
    labels(Z, X2),
    append(X1, X2, X).


text:
Q: Dynamic Drop Down lists using ajax, sql and php I have a code which is working well. It populates the dropdowns dependent upon the previous list but there is a problem.
In the html form in the <option value =""> field it displays "id" which is a numeric value instead of "name". Can someone please tell me how it can display "name" instead of the value. The actual problem is that it when it saves data in the sql database, it stores the corresponding "id" of the country or the state or city rather than its "name".
This is the code that I am using. I have tried changing the last line in ajax.php echo "<option value='$entity_id'>$enity_name</option>"; to echo "<option value='$entity_name'>$enity_name</option>"; but then the dynamic dropdowns do not work as they are dependent upon "id". Many thanks for your help.
ajax.php
<?php
    /* File : ajax.php
     * Author : Manish Kumar Jangir
    */
    class AJAX {

        private $database = NULL;
        private $_query = NULL;
        private $_fields = array();
        public  $_index = NULL;
        const DB_HOST = "localhost";
        const DB_USER = "admin";
        const DB_PASSWORD = "admin";
        const DB_NAME = "disciples";

        public function __construct(){
            $this->db_connect();                    // Initiate Database connection
            $this->process_data();
        }

        /*
         *  Connect to database
        */
        private function db_connect(){
            $this->database = mysql_connect(self::DB_HOST,self::DB_USER,self::DB_PASSWORD);
            if($this->database){
                $db =  mysql_select_db(self::DB_NAME,$this->database);
            } else {
                echo mysql_error();die;
            }
        }

        private function process_data(){
            $this->_index = ($_REQUEST['index'])?$_REQUEST['index']:NULL;
            $id = ($_REQUEST['id'])?$_REQUEST['id']:NULL;
            switch($this->_index){
                case 'country':
                    $this->_query = "SELECT * FROM countries";
                    $this->_fields = array('id','country_name');
                    break;
                case 'state':
                    $this->_query = "SELECT * FROM states WHERE country_id=$id";
                    $this->_fields = array('id','state_name');
                    break;
                case 'city':
                    $this->_query = "SELECT * FROM cities WHERE state_id=$id";
                    $this->_fields = array('id','city_name');
                    break;
                default:
                    break;
            }
            $this->show_result();
        }

        public function show_result(){
            echo '<option value="">Select '.$this->_index.'</option>';
            $query = mysql_query($this->_query);
            while($result = mysql_fetch_array($query)){
                $entity_id = $result[$this->_fields[0]];
                $enity_name = $result[$this->_fields[1]];
                echo "<option value='$entity_id'>$enity_name</option>";
            }
        }
    }

    $obj = new AJAX;

?>

index.html

<title>Country State City Dependent Dropdown using Ajax</title>

Country,State,City dynamic dependent dropdown using Ajax and Jquery

<form>
        Select Country
        <select id="country" name="country" onchange="load_options(this.value,'state');">
            <option value="">Select country</option>
        </select>

        Select State
        <select id="state" name="state" onchange="load_options(this.value,'city');">
            <option value="">Select state</option>
        </select>

        Select city
        <select id="city" name="city">
            <option value="">Select City</option>
        </select>

</form>

A: You could get the script to do what you want by

*

*showing the id as a data attribute. --> Ajax->show_result()

*using that attribute for the id parameter in the ajax call. --> load_options()

*pass the whole <option> element to load_options()

this.value is wrong for the ajax query with the cahages blow because it is a name, but this still has the id as a data attribute.
<select id="country" name="country"
        onchange="load_options(this, 'state');">
    <option value="">Select country</option>
</select>

since the id parameter is the option element from the form, we need to compensate to get the id correct.
function load_options(id,index){
...
that = $(id).find(":selected");
id = that.data('realid');

$.ajax({
    url: "ajax.php?index="+index+"&id="+id,
...

let the value attribute hold name, but keep the id.
public function show_result(){
...
    while ($result = mysql_fetch_array($query)){
        ...
        printf( '<option data-realid="%s" value="%s">%s</option>',
               $entity_id,
               $enity_name,
               $enity_name );

This should answer your question, and depending on how the form is submitted and stored, it may solve your problem. I doubt it however, because the part you neglected to show us is likely to expect an id for the state and city and not their names.

A: My english is not good ,so i will just write some things i have got from you.
1: You want to get a dropdown list depend on the index
2: You want to shown selected options depend on the id

FirstLy , Your codes is terrible. The php codes just try to get the data you need, why did you mixed with html?
Let us try to solve the first proplem, get a dropdown list.
You should just let the php code to get the data you need, so you'd better modified your php function show_result, I would like to write like this:
public function show_result(){
        $tmpData = array();
        $i = 0;
        $query = mysql_query($this->_query);
        while($result = mysql_fetch_array($query)){
            $id = $result[$this->_fields[0]];
            $enity_name = $result[$this->_fields[1]];
            $tmpData[$i]['id'] = $id;
            $tmpData[$i]['name'] = $enity_name;
        }
        return $tmpData;   //here it saves data which you want to shown in drop down list
    }

then in the end of file ajax.php,
 $obj = new AJAX;
 echo json_encode($obj->show_result());

Then in the js script, try to parse the data which you get from ajax.php and it is a json string,
it contains the ids and names. produce the options of the dropdown selector here.
    function load_options(id,index){
    $("#loading").show();
    if(index=="state"){
        $("#city").html('<option value="">Select city</option>');
    }
    $.ajax({
        url: "ajax.php?index="+index,  //do not pass id
        complete: function(){$("#loading").hide();},
        success: function(data) {
            var jsonObj = eval('('+data+')');
            var selected = false;
            var options = '';
            for(jsonObj in eachData){
             if(eachData.id == id)
               selected = true;  //  shown selected if it's the right option you want to see
             options +=  '<option                                                 value="'+eachData.id+'"'+selcted?"selected":""+'>'+eachData.name+'</option>';
             selected = false;
            }
            $("#"+index).html(options);
        }
    })
}

then you will get a drop down list as your wish. I just write these codes to guide you and i did not debug and test them , just try the ways: get data from php, shown them as html in page.
So that's all. And again sorry for my terrible english( I speak chinese well :) )


text:
Q: SQL Server : first time connect fails I installed SQL Server Management Studio and at server name put a dot and at first time I try to connect I get an error:

TITLE: Connect to Server
Cannot connect to ..
ADDITIONAL INFORMATION:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 2)
The system cannot find the file specified


text:
Q: Letsencrypt how to use --preferred-challenges This command:
$ letsencrypt certonly --manual --preferred-challenges dns --email foo@bar.com --domains test001.bar.com

outputs:
letsencrypt: error: unrecognized arguments: --preferred-challenges dns

From the documentation here: https://certbot.eff.org/docs/using.html#certbot-command-line-options
I find:
  --preferred-challenges PREF_CHALLS
                        A sorted, comma delimited list of the preferred
                        challenge to use during authorization with the most
                        preferred challenge listed first (Eg, "dns" or "tls-
                        sni-01,http,dns"). Not all plugins support all
                        challenges. See
                        https://certbot.eff.org/docs/using.html#plugins for
                        details. ACME Challenges are versioned, but if you
                        pick "http" rather than "http-01", Certbot will select
                        the latest version automatically. (default: [])

Why do I get this error?

A: Found the answer, although the website states that letsencrypt and certbot are the same. It seems to not be the case.
$ apt-get install letsencrypt
$ apt-get install python-pip
$ pip install --upgrade pip
$ pip install certbot
$ certbot certonly --manual --preferred-challenges dns --email foo@bar.com --domains test001.bar.com

Does the trick


text:
Q: Debugging node.js apps in WebStorm 7 I am having a strange issue debugging node.js apps in WebStorm 7.
The first time I start the debugger I get the application running:
/usr/bin/node --debug-brk=34041 app.js
debugger listening on port 34041
Current Environment: development
Express server listening on port 3000

But, after the first time (or if I restart the debugger), I get the debugger running but not the app, like below:
/usr/bin/node --debug-brk=42140 app.js
debugger listening on port 42140

or
/usr/bin/node --debug-brk=51341 app.js
debugger listening on port 51341

I need to restart the WebStorm itself in order to debug the app again.
Is it a bug in WebStorm?
Is it a bug in Node.js?
Is there a way to make it work properly?

A: After contacting the support, I found that it was a bug in the WebStorm, already fixed in version 7.0.1.


text:
Q: Are there any code coverage analysis tools for Intersystems Cache object script? If there is some sort of debugging API that would allow someone to write his own code coverage analysis tools that would be acceptable as well.  I don't believe this is a poll question because the exhaustive list of such tools is probably quite small.

A: There are no readymade coverage tools (afaik). However, you might be able to utilize the MONLBL facilities (here). These were introduced to be able to identify performance hotspots.
It would be interesting to look into the code of these, as the necessary hooks to create a code coverage tool are quite similar to the ones you need to create the performance monitoring. If you have access to the WRC I strongly recommend to raise this with ISC, it definitely sounds like something many people could use!
HTH
edit: come to think of it, since monlbl gives you the # of times a line is executed, it's a code coverage with benefits ;) So, the answer is: yes, there are

A: debuging in Cache' Studio.
there is also ^PERFMON


text:
Q: Reset AD user account password using a privileged account I am trying to code a way to let a help desk person with an account that does not have sufficient permissions to reset passwords to do that by embedding another account in the code.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim RootDSE As New DirectoryServices.DirectoryEntry("LDAP://something.com/OU=COW,DC=spmething,DC=com")
    Dim DomainDN As String = RootDSE.Properties("DefaultNamingContext").Value
    Dim ADEntry As New DirectoryServices.DirectoryEntry("LDAP://" & "DC=something,DC=com")
    Dim ADSearch As New System.DirectoryServices.DirectorySearcher(ADEntry)

    If RadioButton1.Checked = True Then
        ADSearch.Filter = ("(samAccountName=" & Loginnames.Text & ")")
        ADSearch.SearchScope = SearchScope.Subtree
        Dim UserFound As SearchResult = ADSearch.FindOne()
        If Not IsNothing(UserFound) Then
            Dim UserDirectoryEntry As DirectoryEntry = UserFound.GetDirectoryEntry
            UserDirectoryEntry.Invoke("SetPassword", New Object() {TextBox2.Text})
            '...
            email = UserFound.GetDirectoryEntry.Properties("userPrincipalName").Value
            MsgBox("Password has been rest!")

        End If
    End If

I need to do that using a user other than the helpdesk because the helpdesk user does not have permission to do that. And we do not want to delegate anything to him.
The error he is getting now is: 0x80070005 (E_ACCESSDENIED)

A: I did this once (long time ago) in VB6 using
Dim objDSO     As IADsOpenDSObject
Dim objUser    As IADsUser

Set objDSO = GetObject("LDAP:")
Set objUser = objDSO.OpenDSObject("LDAP://" & strUser, DELEGATE_ACCOUNTNAME, DELEGATE_PASSWORD, ADS_SECURE_AUTHENTICATION)

so it must also be doable in VB.Net since the IADs interface defines the basic object (properties and methods) of any ADSI object.
Both DirectoryEntry and DirectorySearcher use the Active Directory Services Interfaces (ADSI) technology according to this
Indeed, the DirectoryEntry constructor can be extended with a username and password to use for the binding, other than the user that is currently running the script or application. So instead of
Dim ADEntry As New DirectoryServices.DirectoryEntry("LDAP://" & "DC=something,DC=com")

try this
Dim ADEntry As New DirectoryServices.DirectoryEntry("LDAP://" & "DC=something,DC=com", DELEGATE_ACCOUNTNAME, DELEGATE_PASSWORD, 1)

where '1' is the value for the System.DirectoryServices AuthenticationType "Secure".
This DELEGATE is a user you set up in your domain where you make sure he/she/it has permisions to reset passwords and unlock user accounts (see the Note below).
The DELEGATE_PASSWORD is given in plain text, so you'll need some way of hiding that from the helpdesk user!
Now the rest of the code in your Button1_Click sub should use this delegate's credentials to find and set the password.
Note: Users generally call the helpdesk about their password only after they have tried too many times and their account has been locked. Your function should therefore also unlock the account before setting a new password. You can check if the account is locked by inspecting the (int64) lockoutTime ldap attribute of the user.  To unlock the account, just set this value to 0L


text:
Q: dbGetQuery and dbReadTable failing to return a really large table DBI I have a really large table (8M rows) that I need to import in R on which I will be doing some processing. Problem is when I try to bring it in R using the DBI package I get an error
My code is below
options(java.parameters = "-Xmx8048m")
psql.jdbc.driver <- "../postgresql-42.2.1.jar"
jdbc.url <- "jdbc:postgresql://server_url:port"
pgsql <- JDBC("org.postgresql.Driver", psql.jdbc.driver, "`")
con <- dbConnect(pgsql, jdbc.url, user="", password= '')
tbl <- dbGetQuery(con, "SELECT * FROM my_table;")

And the error I get is
Error in .verify.JDBC.result(r, "Unable to retrieve JDBC result set for ",  :
Unable to retrieve JDBC result set for SELECT * FROM my_table; (Ran out of memory retrieving query results.)

I can understand its because the result set is too big but I am not sure how to retrieve it by batches instead of all of it together. I have tried using dBSendQuery, dbReadTable and dbGetQuery all of them give the same error.
Any help would be appreciated!

A: I got it to work by using the RPostgreSQL package instead of the default RJDBC and DBI package.
It was able to do a sendQuery and then used fetch recursively to get the data in chunks of 10,000.
main_tbl <- dbFetch(postgres_query, n=-1) #didnt work so tried in chunks
df<- data.frame()
while (!dbHasCompleted(postgres_query)) {
  chunk <- dbFetch(postgres_query, 10000)
  print(nrow(chunk))
  df = rbind(df, chunk)
}


text:
Q: retrieve only n elements for each category in a django queryset I am trying to return n articles for each category. here is my models
class Category(models.Model):
    name = models.CharField(max_length=20)

class Article(models.Model):
    name = models.CharField(max_length=100)
    category = models.ForeignKey(Category, on_delete=models.PROTECT)
    updated = models.DateField(auto_now=True)

    class Meta:
       ordering = ['-updated']

I think something like this will work but is it optimal ?!
articles = []
categories = Category.objects.all()
for c in categories:
     articles.append(Article.objects.filter(category=c)[:5])

is there another way to retrieve only the n last articles for each category ?


text:
Q: Python: действия с элементами списка с условием Как правильно написать условие: если в листе найдется отрицательное число, к нему добавляем число g?
import numpy as np
a = [-2,-1,0,1,2]
b = [-6,-5,1,2,3]
g = 1
for i,j in zip(a,b):
    if i and j < 0:
    # !тут проблема!
        i + g
        j + g
print(a,b)

Чтобы результат был таким:
[-1,0,0,1,2] [-5,-4,1,2,3]

A: если я правильно понял условие:
In [11]: a = np.array([-2,-1,0,1,2])

In [12]: b = np.array([-6,-5,1,2,3])

In [13]: a[a < 0] += g

In [14]: b[b < 0] += g

In [15]: a
Out[15]: array([-1,  0,  0,  1,  2])

In [16]: b
Out[16]: array([-5, -4,  1,  2,  3])


text:
Q: How do I use handle_cast and handle_call in Erlang gen_server? As far as I understand, I should use handle_cast for asynchronous requests, by sending messages, then react to response via receive..end on client side.
Here is an example:
Pid ! {auth_user, {User, Password}}.

For synchronous requests, when I want to wait when gen_server sends a response, I must explicitly call the respective function from the module like this:
{ok, Result} = auth_server:auth_user({User, Password}).

Are the statements from above are correct?
If the latter is correct, why then I need a construction like this if I already have an exported function auth_user?
handle_call({authenticate_user, {Login, Password}}, _From, _) ->
    {reply, {}, {}}.

A: You don't interact with a gen_server by sending messages directly like that. You should use gen_server:call or gen_server:cast like this:
Response = gen_server:call(Pid, {auth_user, {User, Password}})

call / cast will handle sending the message to the Pid (and receiving a response for call) itself, along with many edge cases like the process crashing before responding to your request, etc.

If the latter is correct, why then I need a construction like this if I already have an exported function auth_user?

gen_server is useful when you want to keep some state stored between multiple calls. For example, if you want to keep a global counter of the number of pageviews in your app in memory, you should use gen_server, store the counter as the state of the and make a cast or call to it on each request. If you don't have a state to keep, you should use normal functions.


text:
Q: Unable to get width of I am trying to access last "rect" so that I can get its width and height. I tried following jquery $(".highcharts-plot-background").width() but all I get in answer is 0. Also tried to use $(".highcharts-plot-background")[0].width() but then I get the following error

Uncaught TypeError: $(...).width() is not a function.

I am open to suggestions.

<svg version="1.1" class="highcharts-root" xmlns="http://www.w3.org/2000/svg" width="710" viewBox="0 0 710 325" height="325">
  <desc>Created with Highcharts 5.0.0</desc>
  <defs>
    <clipPath id="highcharts-1">
      <rect x="0" y="0" width="636" height="238" fill="none"></rect>    </clipPath>
  </defs>
  <rect fill="#ffffff" class="highcharts-background" x="0" y="0" width="710" height="325" rx="0" ry="0"></rect>
  <rect fill="none" class="highcharts-plot-background" x="64" y="50" width="636" height="238" style="margin:0px;"></rect>
</svg>

A: Use attr("width") instead of width(). If you would have been declaring the width in the css then width() would work just fine.
See the snippet below.

console.log($(".highcharts-plot-background").attr("width"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<svg version="1.1" class="highcharts-root" xmlns="http://www.w3.org/2000/svg" width="710" viewBox="0 0 710 325" height="325">
  <desc>Created with Highcharts 5.0.0</desc>
  <defs>
    <clipPath id="highcharts-1">
      <rect x="0" y="0" width="636" height="238" fill="none"></rect>    </clipPath>
  </defs>
  <rect fill="#ffffff" class="highcharts-background" x="0" y="0" width="710" height="325" rx="0" ry="0"></rect>
  <rect fill="none" class="highcharts-plot-background" x="64" y="50" width="636" height="238" style="margin:0px;"></rect>
</svg>


text:
Q: XDocument Load on Inherited Class - Unable to cast Perhaps I am going about this the wrong way, but until I hit this problem it seemed a fairly elegant way to implement my requirement, I have a load of xpath based code that modifies a word document. It's pretty old and I am upgrading it now to make it more manageable while adding some extra functionality.
I thought, it would make sense to make a DocxDocument class and have it inherit the XDocument class so I can use System.Xml.Linq and System.Xml.Xpath to edit the underlying xml document.
I wrongly thought, that XDocument could be cast as DocXDocument if it inherited the type. So, looking at the code below how the hell do I load and XDocument to a DocXDocument?
Public Class DocXDocument2
    Inherits XDocument

    Public Sub New()
        MyBase.New()
    End Sub

    Public Overloads Function Load(DocumentPath As String) As XDocument
        Using pkg = WordprocessingDocument.Open(DocumentPath, True)
            Return XDocument.Load(pkg.MainDocumentPart.GetStream())
        End Using
    End Function

End Class

I just want to be able to load the doc something like:
dim docx = DocXDocument.load("C:\temp.docx")

A: The best way is: You don't overwrite the XDocument. You rather create a wrapper around the XDocument that stores the reference to the loaded document and allows you do access it in the way you want to. I highly recommend doing it like this.
Your class could look like this:
Public Class DocXDocument2
    Private ReadOnly _doc As XDocument

    Private Sub New(doc As XDocument)
        _doc = doc
    End Sub

    Public Shared Function Load(DocumentPath As String) As XDocument
        Using pkg = WordprocessingDocument.Open(DocumentPath, True)
            Return New DocXDocument2(XDocument.Load(pkg.MainDocumentPart.GetStream()))
        End Using
    End Function

    Public Function Descendants As IEnumerable(Of XElement)
        Return _doc.Descendants
    End Function
End Class

Note that the original XDocument exposes the load function as a Shared function. So I changed that here.
How ever there is a way to get it done with inheritance. But it is not pretty. You have to Shadow the load method to force your method to be used and you have to use the Copy-Constructor of XDocument to get your document in properly. So it could look like this:
Public Class DocXDocument2
    Inherits XDocument

    Private Sub New(doc As XDocument)
        MyBase.New(doc)
    End Sub

    Public Shared Shadows Function Load(DocumentPath As String) As XDocument
        Using pkg = WordprocessingDocument.Open(DocumentPath, True)
            Return New DocXDocument2(XDocument.Load(pkg.MainDocumentPart.GetStream()))
        End Using
    End Function
End Class

This is only for the sake of sticking as close to your approach as possible. I really recommend to use the first method. It is cleaner code and it gives you better control over what is done with the document and what is not. Inheriting XDocument after all exposes every single public method of XDocument to who ever uses your class.
To your initial question, why the cast of XDocument to DocXDocument2 failed. The reason simply is that the XDocument.Load function creates a XDocument and not a DocXDocument2. You can easily cast a instance of a specific class to any class or interface that is implemented by the object. But you can't cast it to a object that narrows the implementation of the specific object. You have to construct the instance as a DocXDocument2 to get a instance of this type.


text:
Q: How to install C# App from one computer to another My scenario is that I have two computers A and B.  Computer A has an installed C# windows forms application on it.  Pretending that I dont have the source code to publish onto B, is it possible to move the app from A to B?  If so, what files do I need in order to copy it over?

A: You have to check if the C# application requires files found in the local appdata directory, if so you'll need to copy them.
It can be difficult when apps require a certain DLL then you'll need to find the dependencies for the application and install them on Computer B.
After you've done that you can copy all the files that are in the programs directory and you MIGHT be good to go.
Best thing to do is make sure you have the installer handy :)

A: Can't answer without knowing the application.
Sometimes it's enough to just copy the files over. However, if the app relies on registry entries, databases or some other prerequisites copying files is not enough.


text:
Q: Restrict loading two same fragments I'm using BottomNavigationView. When I click on an option twice then same fragment also loaded twice. How to prevent loading same fragment?
 btnNavBar.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.action_item1:
                   loadFragment(fragmentManager, new HomeFragment(), "Home");
                    break;

                case R.id.action_item2:
                        loadFragment(fragmentManager, new SearchFragment(), "Search");
                     break;

                case R.id.action_item3:
                   loadFragment(fragmentManager, new AccountFragment(), "Account");
                    break;

            }
            return true;
        }
    });

 public static void loadFragment(FragmentManager fragmentManager, Fragment fragment, String tag) {

    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.frameLayoutContainer, fragment);
    fragmentTransaction.commit();
}

A: the easiest approach is tracking current fragment which is displayed at BottomNavigationView:
int currentTabSelected;
...
btnNavBar.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_item1:
               if(currentTabSelected == R.id.action_item1) return true;
               loadFragment(fragmentManager, new HomeFragment(), "Home");
                break;

            case R.id.action_item2:
                    if(currentTabSelected == R.id.action_item2) return true;
                    loadFragment(fragmentManager, new SearchFragment(), "Search");
                 break;

            case R.id.action_item3:
               if(currentTabSelected == R.id.action_item3) return true;
               loadFragment(fragmentManager, new AccountFragment(), "Account");
                break;

        }
        currentTabSelected = item.getItemId();
        return true;
    }
});


text:
Q: returning an int array I have created the following program which is supposed to return an int array to the main function, which will then display it on the screen.
#include <iostream.h>
int* returnArray(){
    int* arr;
    arr[0]=1;
    arr[1]=2;
    arr[2]=3;
    return arr;
}
int main(){
    int* res = returnArray();
    for(int i=0; i<3; i++){
        cout<<res[i]<<" ";
    }
    return 0;
}

And i was expecting it to print

1 2 3

but instead, it prints 3 someNumberWhichLooksLikeAPointer 0
Why is that? what can i do to return an int array from my function? Thank you very much!

A: You forgot to allocate your array:
int* arr = new int[3];

You also need to return it, and free the memory inside main after you finish with the loop in order to avoid a memory leak:
delete[] res;

Although this approach works, it is not ideal. If you have an option of returning a container, say, std::vector<int> it would be a much better choice.
If you must stay with plain arrays, another solution for filling an array inside an API is to pass it in, along with its size:
void fillArray(int *arr, size_t s){
    if (s > 0) arr[0]=1;
    if (s > 1) arr[1]=2;
    if (s > 2) arr[2]=3;
}

int main(){
    int res[3];
    fillArray(res, 3);
    for(int i=0; i<3; i++){
        cout<<res[i]<<" ";
    }
    return 0;
}

A: You have tagged the question with C++. You Yous should consider to use the C++ solution: use a vector of int
#include <iostream>
#include <vector>

std::vector<int> returnArray(){
    std::vector<int> arr(3);
    arr[0]=1;
    arr[1]=2;
    arr[2]=3;
    return arr;
}
int main(){
    std::vector<int> res = returnArray();
    for(int i=0; i<3; i++){
        std::cout<<res[i]<<" ";
    }
    return 0;
}


text:
Q: how to insert variable into SQL query i have test scripts, the productId is stored in text file which I can use the read method to retrieve it.
import static org.assertj.core.api.Assertions.*
import groovy.json.JsonOutput as JsonOutput
import groovy.json.JsonSlurper as JsonSlurper
import internal.GlobalVariable as GlobalVariable
import internal.GlobalVariable
import com.kms.katalon.core.configuration.RunConfiguration
import java.sql.*
import java.io.File

//Read productId
def productId = new File(RunConfiguration.getProjectDir() + "/Data Files/productId.txt")

//SQL statement
String dbQuery2 = /SELECT * FROM db.table1 where productId= @productId order by lastmodificationdateutc desc/

how do i use the @ as variable and replace it with the "productId.text" ?
i have tried below codes but it does not work
please correct me if this method can be used?
    String dbQuery2 = "SELECT * FROM db.table1 where productId = ?"
    def productId = new File(RunConfiguration.getProjectDir() + "/Data Files/productId.txt")
    PreparedStatement stmt = con.prepareStatement(dbQuery2)
    stmt.setString(1, productId.text)
    ResultSet resultSet = preparedStatement.executeQuery()

ResultSet resultSet = stmt.executeQuery()

//Connect to PostgresSQL, global variable is stored at profile
List resultSet = CustomKeywords.'test.database.getPostgresSQLResults'(GlobalVariable.dbConnString2 , GlobalVariable.dbUsername2 , GlobalVariable.dbPassword2 ,GlobalVariable.dbDriver2 ,dbQuery2 )

below is codes which is working without preparedstatement
the connection string in the script
//to connect PostgresSQL server
    @Keyword
    def List getPostgresSQLResults (String dbConnString2 , String dbUsername2 , String dbPassword2 , String dbDriver2 , String dbQuery2){

        Sql sql = Sql.newInstance(dbConnString2,dbUsername2,dbPassword2,dbDriver2)

        List results = sql.rows(dbQuery2)

        return results

        sql.close()
    }

A: I managed to use this syntax to act as variable
def productId = new File(RunConfiguration.getProjectDir() + "/Data Files/productId.txt")
dbQuery2 = /SELECT * FROM db.table1 where productId = '$productId.text}'/


text:
Q: Should I give users the ability to 'unreport' on a forum (I really hope this is the appropriate place for a question like this. Nevertheless, I hope some of you can give me your opinions, regardless).
I am building a forum with Laravel. Progress has been great and I love how it is turning out.
I have just added the ability for users to report topics and posts. (Posts are replies to a single topic).
Everything is working fine; I just have a question about best practice.
Should the user have the ability to 'unreport' a post or topic that he or she has reported? Actually doing it is easy. I just wanted to hear some opinions from other people.
Eventually, moderators and administrators can manage posts and topics. They will be able to see which were reported and perform any actions in return (delete or update the post or topic).
Thank you in advance for any responses.

A: The ability to undo is very comforting to users.
Put me in an environment where I can bang on things without them breaking and I'll play around like an exploring child.
Put me in an environment where every mistake is set in stone and held up for the world to see and I'll sit in the corner and cry.
There are two good reasons I can imagine you'd even ask this question.

*

*You're wondering if it's worth the effort to implement.

*

*It is.

*You're wondering if you're losing important information.

*

*You don't have to be.  You can log what happened privately.


text:
Q: how to write an interface for such an object? I have a complex object which shows:
const styles = {
       base: {
           position: 'absolute',
           userSelect: 'none',
        //    backgroundColor: '#4323ba'
       },
       top: {
        width: '100%',
        height: '10px',
        top: '-5px',
        left: '0px',
        cursor: 'row-resize'
       },
       bottom: {
        width: '100%',
        height: '10px',
        bottom: '-5px',
        left: '0px',
        cursor: 'row-resize'
       },
       left: {
        width: '10px',
        height: '100%',
        left: '-5px',
        top: '0px',
        cursor: 'col-resize'
       },
       right: {
        height: '100%',
        width: '10px',
        right: '-5px',
        top: '0',
        cursor: 'col-resize'
       },
       topLeft: {
        width: '20px',
        height: '20px',
        top: '-10px',
        left: '-10px',
        cursor: 'nwse-resize'
       },
       topRight: {
        width: '20px',
        height: '20px',
        top: '-10px',
        right: '-10px',
        cursor: 'nesw-resize'
       },
       bottomLeft: {
        width: '20px',
        height: '20px',
        bottom: '-10px',
        left: '-10px',
        cursor: 'nesw-resize'
       },
       bottomRight: {
        width: '20px',
        height: '20px',
        bottom: '-10px',
        right: '-10px',
        cursor: 'nwse-resize'
       },
     }

I tried to wrote like this:
interface IPosition<T> {
   width: string,
   height: string,
   cursor: Cursor[T]
}
enum Cursor {
top = 'row-resize',
bottom = 'row-resize',
left = 'col-resize',
right = 'col-resize',
topLeft = 'nwse-resize',
topRight = 'nesw-resize',
bottomLeft = 'nesw-resize',
bottomRight = 'nwse-resize'
   }
interface IStyle {
    base: object,
    [propName: string]: IPosition<propName>
}

I can not continue writing IStyle...
Apparently I cannot refer the type parameter T in IPosition with Cursor.
I am a new bee with typescript.
I want to practice writing precise typings and  don not want to use any to bypass it.But I can not really figure out a better way for this.
Hope anyone may give me some suggestions.
Thx.

A: You are trying to pass a value of a property as a type parameter. That's not quite what the type system is made for. The types specify what possible values a property can have (and yes, you can restrict to specific string values); they are not designed to specify specific values.
Another problem is the mixture of a specified property with a mapped type. In this case the additional property must be of the same type as the mapped property. The solution is to specify the properties individually.
You can define these types to fully type your data structure:
enum Cursor {
    top = 'row-resize',
    bottom = 'row-resize',
    left = 'col-resize',
    right = 'col-resize',
    topLeft = 'nwse-resize',
    topRight = 'nesw-resize',
    bottomLeft = 'nesw-resize',
    bottomRight = 'nwse-resize'
}

interface Position {
   width: string;
   height: string;
   cursor: Cursor;
}

interface LeftPos {
    left: string;
}

interface RightPos {
    right: string;
}

interface TopPos {
    top: string;
}

interface BottomPos {
    bottom: string;
}

interface Style {
    base: { [key: string]: string };
    top: Position & TopPos;
    bottom: Position & BottomPos;
    left: Position & LeftPos;
    right: Position & RightPos;
    topLeft: Position & TopPos & LeftPos;
    topRight: Position & TopPos & RightPos;
    bottomLeft: Position & BottomPos & LeftPos;
    bottomRight: Position & BottomPos & RightPos;
}


text:
Q: errors using default for switch statement c# im trying to use default at the end of my switch statement and i keep getting errors! im getting frustrated please help
im very new to programming and its quite confusing lol
case "d":

    Console.WriteLine("Please enter your option here:");
    Console.WriteLine("First number");
    double firstNum = Int32.Parse(Console.ReadLine());
    Console.WriteLine("Second number:");
    double secondNum = Int32.Parse(Console.ReadLine());
    double sum = firstNum / secondNum;
    Console.WriteLine("Result:" + sum);
    Console.WriteLine("\n");
    Console.ReadKey();
    break;
}
default:

    else if (number == 2)

    {

        Console.WriteLine("Exiting the code");
        Console.WriteLine("Please press any key to exit");
        Console.ReadLine();
        break;
    }

    else
    {

        Console.WriteLine("Wrong selection");
        Console.WriteLine("Please press any key to go to the main menu");
        Console.ReadLine();

Active
Error   CS1002  ; expected  ConsoleApp50        69  Active
Error   CS1513  } expected  ConsoleApp50        69  Active
Error   CS1513  } expected  ConsoleApp50        98  Active

A: When the code is that weird, sometimes the error messages don't make sense :)
A few problems I see:

*

*At the end of your case "d": block, you have a } where there was no previous {. Unless there is code in your case "d": block that you're not showing us, then you can just delete that }.

*In your default: block, you're starting with an else if, where there was no if before that. You can only use else if after an if. Unless there's code you're not showing us, then you can change the else if to just if.

*There's no } at the end, to close the else block.

*You still need a break; at the end of the default: block.


text:
Q: TextCtrl -> Truncate a float in Erlang My last question leads me to this one:
wxTextCtrl:setValue( TcGrossProfit, io_lib:format("~.2f",[NewGrossProfit])),

generates an error from wxTextCtrl,  with a bad arg.
I know this is the culprit
NewGrossProfit = 5.45333,

io_lib:format("~.2f",[NewGrossProfit])

Thanks for the last one, hope this one's easier
-B
EDIT
Last Question:
   Truncate a float in Erlang

A: The problem is that io_lib:format("~.2f",[NewGrossProfit]) returns an iolist: ["5.45"], but wxTextCtrl:setValue seems to need a string ("5.45"). So
wxTextCtrl:setValue( TcGrossProfit, lists:flatten(io_lib:format("~.2f",[NewGrossProfit])))

should work.


text: Q: Detect key up and key down python3 I am doing a program with python 3 that should print "w pressed" when I press and release a key. I tried, and when I press the key it prints all the time without being released.


text:
Q: Theorem 9.13 in Rudin's Real and Complex Analysis
9.13 Theorem One can associate to each $f \in L^{2}$ a function $\hat{f} \in L^{2}$ so that the following properties hold:
(a) If $f \in L^{1} \cap L^{2},$ then $\hat{f}$ is the previously defined Fourier transform of $f .$
(b) For every $f \in L^{2},\|\hat{f}\|_{2}=\|f\|_{2}$.
(c) The mapping $f \rightarrow \hat{f}$ is a Hilbert space isomorphism of $L^{2}$ onto $L^{2}$.
(d) The following symmetric relation exists between $f$ and $\hat{f}:$ If
$$
\varphi_{A}(t)=\int_{-A}^{A} f(x) e^{-i x t} d m(x) \quad \text { and } \quad \psi_{A}(x)=\int_{-A}^{A} \hat{f}(t) e^{i x t} d m(t), $$
then $\left\|\varphi_{A}-\hat{f}\right\|_{2} \rightarrow 0 \text { and }\left\|\psi_{A}-f\right\|_{2} \rightarrow 0 \text { as } A \rightarrow \infty$.
To prove $(d),$ let $k_{A}$ be the characteristic function of $[-A, A] .$ Then $k_{A} f \in L^{1} \cap L^{2}$ if $f \in L^{2},$ and
$$
\varphi_{A}=\left(k_{A} f\right)^{\wedge}
$$
since $\left\|f-k_{A} f\right\|_{2} \rightarrow 0$ as $A \rightarrow \infty,$ it follows from $(b)$ that
$$
\left\|\hat{f}-\varphi_{A}\right\|_{2}=\|\left(f-k_{A} f\right) \hat{\|}_{2} \rightarrow 0
$$
as $A \rightarrow \infty$.
The other half of $(d)$ is proved the same way.$\qquad\qquad\qquad\qquad  ////$

Transcribed from this image
This is Theorem 9.13 in Rudin's Real and Complex Analysis, and a part of its proof. I have understood the first half of the proof of (d), but I can't see how the other half of (d) follows. Am I missing something? Thanks in advance.

A: Let $\check{f}:=\mathscr{F}^{-1}(f)$ denote the inverse Fourier transform. By (c) it follows that $||f||_2=||\check{f}||_2$ for all $f\in L^2$. Observe that
$k_A \hat{f}\in L^1\cap L^2$ and
$\psi_A=(k_A \hat{f})^\vee$ for all $f\in L^2$. It follows that
$$||f-\psi_A||_2=||\hat{f}^\vee-(k_A \hat{f})^\vee||_2=||\hat{f}-(k_A \hat{f})||_2\rightarrow 0$$
as $A\rightarrow \infty$.
Before someone jumps at me for forgetting the nuisance factor $2\pi$, please observe that the measure $dm$ in Rudin's book is a scaling of the Lebesgue measure so that the factor is not needed in the argument above.


text:
Q: Adding array into excel using openpyxl (formatting issue) I am using "openpyxl" to put an array into an excel file for users to download on a django site.
The data goes into the excel  fine using the following loop:
for row_num, row in enumerate(matrix, 3):
 for col_num, item in enumerate(row, col_start - 12):
        ws.cell(column=col_num, row=row_num, value=item)
wb.save(excel_file_path_from_db)

My problem is that when the data enters the excel is is not in number format.  I think it could be because i am getting my atix values from a user input via:
matrix = ast.literal_eval(list(request.GET)[0])
print(matrix)

Any ideas how I can make my matrix come into the excel file in number format?

A: Sounds like you have string values.  The cell() function will set the data_type property of the resulting openpyxl.cell.cell.Cell object to try and match that.
If you assign the output of cell() to a variable (cell, for example):
cell = ws.cell(column=col_num, row=row_num, value=item)
And then print(cell.data_type), you will likely get "t" for text.
You should be able to use a cast operator on item when you invoke ws.cell():
for row_num, row in enumerate(matrix, 3):
 for col_num, item in enumerate(row, col_start - 12):
    ws.cell(column=col_num, row=row_num, value=float(item))
wb.save(excel_file_path_from_db)

Another option that worked for me:
for row_num, row in enumerate(matrix, 3):
 for col_num, item in enumerate(row, col_start - 12):
    cell = ws.cell(column=col_num, row=row_num, value=item)
    cell.data_type = "n"
wb.save(excel_file_path_from_db)


text:
Q: Purpose of voltage amplifier (VAS) in three stage amplifier design Can someone explain me benefits of this design (found in Douglas Self's book) in comparison with "classic" npn-based long-tailed pair? What second stage actually does?

A: The second stage obviously provides additional voltage amplification.  However, it has an additional function as well.  The capacitor from collector to base provides the dominant pole compensation that makes the amplifier stable (in general from unity gain to very high closed-loop gain.)
Since this is likely an integrated op-amp, where capacitance take a lot of area, the compensation takes advantage of the Miller effect to multiply the effective capacitance by approximately the gain of the stage.
The Miller Effect
Also, the PNP input stage allows the common mode voltage range to get much closer to the negative rail.  Could be useful for single-supply application.

A: The 2nd stage takes the output of the diff pair and applies a lot of voltage gain. It also rolls off the high frequencies (the miller capacitor) so that negative feedback applied externally does not cause instability or oscillations.
An op-amp should have lots of open-loop gain, be stable (closed loop), provide a low output impedance and a high input impedance thus, the 2nd stage greatly enhances the gain whilst providing stability when negative feedback is added.
Regards the use of PNP transistors, this is of no consequence to what stage 2 does. An NPN input pair will still have a stage 2 but, it might be a PNP transistor.

A: There is an additional task the second stage must fulfill: Correction of unsymmetry caused by the first differential stage.
The problem is that the npn current mirror cannot be fully symmetric (cannot provide two equal DC currents). The current through the most right pnp transistor (with the "-" sign) is larger than the current through the left pnp transistor. The difference is caused by the two base currents (IB1+IB2) of the current mirror npn transistors.
However, balancing the currents through the diff. amplifier is important for the performance of the diff. pair. That means: Without any input signal, the quiescent DC currents of the pnp´s should be equal!
Now - this problem can be solved when the current gain and the operational point of the second-stage npn transistor is selected properly: Its base current must be identical to (IB1+IB2). In this case, the quiescent DC collecor currents of both pnp transistors can be made equal. Then, the diff. stage is fully symmetric and delivers a signal to the second stage which depends on the diff. input signal only.
EDIT(comment): There is an additional aspect - as far as the second stage transistor is concerned: Further improvement of symmetrical properties of the differential stage.
The collector-emitter voltage VCE1 of the left npn current mirror transistor is identical to VBE of the second stage transistor (app. 0.7V). Hence, we can assume that VCE1 is practically identical to the coll.-emitter voltage VCE2 of the other (right) current mirror npn transiustor (VCE1=VCE2=VBE2).
Therefore, the quiescent DC voltages VCE of both diff. stage pnp transistors are alo equal. This symmetry improvement eliminates variations that would result from larger voltage swings within the diff. stage as well as at the collector of the second stage transistor (VCE only ap. 0.7V).


text:
Q: PHP GET variable with dash The URL is something.php?id=123-10-1
If I echo it, it only prints out 123 but I need it to say 123-10-1.
I suppose the solution is very simple but I'm not seeing it.

A: Of course, You will have the full argument stored in GET array. You are not doing anything wrong. The mistake should be somewhere else. Try to use:
var_dump($_GET);
$equal = ('123-10-1' == $_GET['id']);
var_dump($equal);

To see what is wrong... Echo is not the best printing functino here, however, it also should print the full argument...

UPDATE - note
After we know what was wrong:
$id = isset($_GET['id']) ? (int)$_GET['id'] : '';

I would suggest something like that:
// Set part of the code
$id = isset($_GET['id']) ? $_GET['id'] : '';

// Verification part of the code
if (!is_numeric($id) && $id != '') {
    throw new Exception('ID must be numeric.');
}
if ($id == '') {
    // ID was not set in the url. Maybe there should be another action here?
}

IN that case, You are in full control of what is happening here. Modyfing GET values or POST values "on the fly" is not the good practice.
I hope it helps.

A: Use php urlencode and urldecode functions.

A: Try using an anchor tag like <a href="something.php?id=123-10-1"> and it will echo 123-10-1

A: You are searching for the function urlencode which  encoding a string to be used in a query part of a URL.

A: This was my code.
$id = $_GET['id']

echo $id; //123

and it printed '123' only.
But
echo $_GET['id']; //123-10-1

printed it all. Seems weird stuff as it should work in the first place, but it works now.
Gotta check my php.ini to see what's this all about.

A: *

*I have try your code it giving me correct response
-<?php echo    $_GET['id']; ?>
Output 123-10-1


text:
Q: Padding not working So I was recommended not to use tables for my layout and I tried that and it's giving me this annoying problem of not working the way I want it to.
Here's my final result that I currently have:

However, I want to move that hello in the bottom right box to the same left margin/padding as the text in Home right above it.
Here's my code.

@import url('https://fonts.googleapis.com/css?family=Lobster+Two');
#Cogna {
  float: left;
  font-family: 'Lobster Two', cursive;
  font-size: 60px;
  font-weight: bold;
  border: 2px solid black;
  padding: 40px 20px 10px 20px;
  margin-right: 0.5em;
  width: 20%;
  height: 20%;
}

h1 {
  font-family: 'Lobster Two';
  vertical-align: text-bottom;
  font-size: 20px;
  border: 2px solid black;
  height: 20%;
  padding: 4em 1em 1em 1em;
}

.maintext {
  padding: 1.58em;
  height: 46em;
  display: block;
  border: 2px solid black;
  min-width: 80%;
}

nav {
  float: left;
  font-family: 'Lobster Two', cursive;
  font-size: 1em;
  padding: 40px 20px 10px 20px;
  overflow-y: scroll;
  width: 20%;
  height: 46em;
  border: 2px solid black;
}

nav ul {
  list-style: none;
}

Cogna

Home

Home

a

a

a

a

a

a

a

      Hello.

However, I can't seem to properly accomplish that task. I've change the margin and padding of both the nav and the maintext id in my CSS to and it still won't seem to budge. I then tried a variety of display style changes (though not all, as I'm new to CSS and idk which one would do the job). Most of them didn't seem to work.
Also, if anyone could reduce that gap between the top two boxes and the bottom two, that would also be great, but not entirely necessary.
The div element maintext should capture all the paragraphs in the bottom-left box, so I want all of the text in that element to have that padding.
Any help would be great. Thanks.

A: I would add box-sizing: border-box to nav and .maintext, then add width: 80%; overflow: auto; to .maintext to get it to sit beside nav, then just use the same padding .maintext as you applied to the h1 if you want it to match that padding.

@import url('https://fonts.googleapis.com/css?family=Lobster+Two');
#Cogna {
  float: left;
  font-family: 'Lobster Two', cursive;
  font-size: 60px;
  font-weight: bold;
  border: 2px solid black;
  padding: 40px 20px 10px 20px;
  margin-right: 0.5em;
  width: 20%;
  height: 20%;
}

h1 {
  font-family: 'Lobster Two';
  vertical-align: text-bottom;
  font-size: 20px;
  border: 2px solid black;
  height: 20%;
  padding: 4em 1em 1em 1em;
}

.maintext {
  padding: 1.58em;
  height: 46em;
  display: block;
  border: 2px solid black;
  width: 80%;
  overflow: auto;
  padding-left: 1em;
}

nav {
  float: left;
  font-family: 'Lobster Two', cursive;
  font-size: 1em;
  padding: 40px 20px 10px 20px;
  overflow-y: scroll;
  width: 20%;
  height: 46em;
  border: 2px solid black;
}

nav ul {
  list-style: none;
}

nav, .maintext {
  box-sizing: border-box;
}
<!DOCTYPE html>

    <title>Cogna</title>
    <link rel="stylesheet" type="text/css" href="Home.css">

Cogna

Home

Home

a

a

a

a

a

a

a

            Hello.


text:
Q: plot the bars from starttime not from zero for example i have the values
starTime1 = 1.5
starTime2 = 3
starTime3 = 2.3

and i have three bars horizantal, for example with name:
bar1
bar2
bar3
i have "x" scale = 24 hours(range0,24)
So how to plot the bars from values "startTime", not from zero.
There is my code. variable "rankings" it's the endtime of bar.
import csv
import datetime
import time
import numpy as np
import matplotlib.pyplot as plt
import pylab
from matplotlib.ticker import MaxNLocator

numCp = 10
cpNames = [data[4][6], data[5][6], data[6][6], data[7][6],
         data[8][6], data[9][6], data[10][6], data[11][6],
         data[12][6], data[13][6]]
testMeta = ['UOL/sec' , 'UOL/sec', 'UOL/sec', 'UOL/sec', 'UOL/sec', 'UOL/sec',     'UOL/sec', 'UOL/sec', 'UOL/sec', 'UOL/sec' ]
scores = [data[4][4], data[5][4], data[6][4], data[7][4], data[8][4],
      data[9][4], data[10][4], data[11][4], data[12][4], data[13][4]]
rankings = intAllCpMin

fig, ax1 = plt.subplots(figsize=(9, 7)) #height and width of chart
plt.subplots_adjust(left=0.115, right=0.88)
fig.canvas.set_window_title('Eldorado K-8 Fitness Chart')
pos = np.arange(numCp)+0.5   # Center bars on the Y-axis ticks
rects = ax1.barh(pos, rankings, align='center', height=0.5, color='m')

ax1.axis([0, 100, 0, 10]) # to display all CP bars correctly change last number on     numbers of CP
pylab.yticks(pos, cpNames)
ax1.set_title('Non Functional Test Results')
plt.text(50, -0.5, 'Hours',
     horizontalalignment='center', size='small')

ax2 = ax1.twinx()
ax2.plot([totalRunTime, totalRunTime], [0, 5], 'white', alpha=0.1) #width of X
ax2.xaxis.set_major_locator(MaxNLocator(totalRunTime))
xticks = pylab.setp(ax2, xticklabels=[lowestStartTime," "," "," "," "," ",     higherStartTime])
ax2.xaxis.grid(True, linestyle='--', which='major', color='grey',
alpha=0.25)

def withnew(i, scr):
    if testMeta[i] != '':
        return '%s\n' % scr
    else:
        return scr

scoreLabels = [withnew(i, scr) for i, scr in enumerate(scores)]
scoreLabels = [i+j for i, j in zip(scoreLabels, testMeta)]
ax2.set_yticks(pos)
ax2.set_yticklabels(scoreLabels)
ax2.set_ylim(ax1.get_ylim())

ax2.set_ylabel('Test Scores')

suffixes = sorted([str(data[4][14][5:12]), data[5][14][5:12], data[6][14][5:12], data[7][14][5:12], data[8][14][5:12],
               data[9][14][5:12],data[10][14][5:12], data[11][14][5:12], data[12][14]    [5:12], data[13][14][5:12]])

    width = int(rect.get_width())

    rankStr = ""
    if (width < 2):        # The bars aren't wide enough to print the ranking inside
        xloc = width+0.1  # Shift the text to the right side of the right edge
        clr = 'black'      # Black against white background
        align = 'left'
        rankStr += suffixes[1] + " Total Run Time"
    else:
        xloc = 0.50*width  # Shift the text to the left side of the right edge
        clr = 'white'      # White on magenta
        align = 'center'
        rankStr += suffixes[1] + " Total Run Time"

        yloc = rect.get_y()+rect.get_height()/2.0
        ax1.text(xloc, yloc,  suffixes[1], horizontalalignment=align,
        verticalalignment='center', color=clr, weight='bold')

plt.show()

A: You can use the left keyword to barh (or the bottom keyword for vertical bars) to change the starting position of a bar.  You'll have to subtract the same amount from the bar length though.
Example:
pylab.barh( [1,2,3], [10,20,30], left=20 )


text:
Q: How to make the content of a dropdown menu part of the parent-element? What I want to do:
I have a dropdown menu inside a .slideDown()-div that initially triggers on hover.
The Problem: When the user enters the content of the dropdown menu the div slides up.
So far I figured out that the menu-element is left (hovered out), when the user enters the content of the dropdown menu.
I made this fiddle to illustrate the point of my problem.
http://jsfiddle.net/nx70oavr/
Here is the code:

<form role="form">

    <select class="form-control">
      <option>a</option>
      <option>b</option>
    </select>

</form>

no action done

$("#container").hover(function() {
    $("#info").text("element entered");
}, function() {
    $("#info").text("element left");
});

How to make the dropdown-menus content part of its parent? Or prevent triggering the hoverout/mouseout?

A: Might be you want this. If I understand you correctly.
$("#container select").hover(function() {
    $("#info").text("element entered");
}, function() {
    $("#info").text("element left");
});

Demo

A: So I ended up with a little bit of jQuery and a little bit of CSS.
This will only be a reference for you. You can, of course use it and modify it as you like.
One advantage here is that you control everything, and you can change the colors and everything just as you like to fit you theme. Once you have the logic in place it is quite easy to add even more of your self-created dropdowns.
So here we go:
The HTML:

    Selected Item: None

    Select

 Item 1

 Item 2

 Item 3

 Item 4

The CSS:
.dropdown {
    position: absolute;
    top: 100px;
    left: 100px;
    width: 95px; /*Padding makes this 100px in total.*/
    height: 27px;
    line-height: 27px;
    background: #DDDDDD;
    border: 1px solid black;
    border-radius: 3px;
    padding-left: 5px;
    cursor: pointer;
}

.dropdownGroup {
    position: absolute;
    top: 100%;
    left: -1px; /*Account for the border and move 1 to the left (2px / 2 = 1px)*/
    width: 100%;
    background: #909090;
    border-left: 1px solid black;
    border-bottom: 1px solid black;
    border-right: 1px solid black;
    border-radius: 0px 0px 3px 3px;
    overflow: hidden;
    visibility: hidden;
}

.dropdownGroupItem {
    position: relative;
    background: transparent;
}

.dropdownGroupItem:hover {
    background: gray;
}

The jQuery(Javascript):
var selectedItemText; //Use something like this to save your selected values for later use.
$(".dropdown").click(function() {
    var visibility = $(".dropdownGroup").css("visibility");
    if (visibility == "hidden") {
        $(".dropdownGroup").css("visibility", "visible");
    }
});

$(".dropdownGroupItem").click(function(e) {
    e.stopPropagation(); //Prevent $(".dropdown").click() from being executed.
    selectedItemText = $(this).text();
    $(".selectedItem").text("Selected Item: " + selectedItemText);
    $(".dropdownText").text(selectedItemText);
    $(".dropdownGroup").css("visibility", "hidden");
});

I hope this helps :).


text:
Q: cannot find installed package in VS Code with TexLive My OS is win10 enterprise.
VS Code Output: ! LaTeX Error: File `algorithms.sty' not found.
I had set system environment path for me and all users, and found `algorithms.sty' in E:\texlive\2018\texmf-dist\tex\latex\algorithms
Also, I press update filename datebase in TexLive Manager-actions
I have tried many methods but it didn't worked, thank you for your time

% !TEX program = pdflatex
\documentclass{article}
\usepackage{algorithms}
\usepackage{algorithmicx}
\usepackage{lipsum}
\begin{document}
  asdlkjads
\end{document}
\begin{documeasdlkjadsnt}
\section{A section}
\begin{algorithm*}
  \caption{Euclid's algorithm}\label{euclid}
  \begin{algorithmic}[1]
    \Procedure{Euclid}{$a,b$}\Comment{The g.c.d. of a and b}
      \State $r\gets a\bmod b$
      \While{$r\not=0$}\Comment{We have the answer if r is 0}
        \State $a\gets b$
        \State $b\gets r$
        \State $r\gets a\bmod b$
      \EndWhile\label{euclidendwhile}
      \State \textbf{return} $b$\Comment{The gcd is b}
    \EndProcedure
  \end{algorithmic}
\end{algorithm*}

\lipsum[1-15]% dummy text
\end{document}

i can compile that code as shown below
% !TEX program = pdflatex
\documentclass{article}

\usepackage{hyperref}
\usepackage[round]{natbib}
\usepackage{newtxtext,newtxmath}
\author{Dongsheng Deng}
\title{Configuration of Visual Studio Code for \LaTeX{} Users}
\date{\today}

\begin{document}
\maketitle

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, \cite{GraffZivin2018} sunt in culpa qui officia deserunt mollit anim id est laborum.

\begin{equation}
  a^2+b^2=c^2
\end{equation}

\bibliography{info}
\bibliographystyle{plainnat}

\end{document}


text:
Q: Fastest way to get a random value from a string array in C#? What's the fastest way to get a random value from a string array in C# on the .net 2.0 framework? I figured they might have had this:
string[] fileLines = File.ReadAllLines(filePath);
fileLines.GetRandomValue();

Yes, I know GetRandomValue() is not an actual method, is there something similar that's more or less equally short and sweet?

A: Not built in, but easy enough to add...
static readonly Random rand = new Random();
public static T GetRandomValue<T>(T[] values) {
    lock(rand) {
        return values[rand.Next(values.Length)];
    }
}

(the static field helps ensure we don't get repeats if we use it in a tight loop, and the lock keeps it safe from multiple callers)
In C# 3.0, this could be an extension method:
public static T GetRandomValue<T>(this T[] values) {...}

Then you could use it exactly as per your example:
string[] fileLines = File.ReadAllLines(filePath);
string val = fileLines.GetRandomValue();

A: Indeed.
Random m = new Random();
string line = fileLines[m.Next(0, fileLines.Length);

A: Try:
fileLines [new Random ().Next (fileLines.Length)]

A: I don't think arrays support such a function. The easiest way is just to get a random number, and get the corresponding item.
Random rnd = new Random();
String item = fileLines[rnd.next(fileLines.Length);

A: Linq To Sql way
var rFile = fileLines.OrderBy(x => Guid.NewGuid()).FirstOrDefault();

If you see error you should add System.Linq;

A: I'd have used this method to get random item from an array :
string[] str = {"red","blue","pink","yellow","green","brown"};
int i = new Random.Next(0, str.length);
MessageBox.Show(str[i]);


text:
Q: Python: Array is being modified and I don't understand why New to python but with some experience with c# and trying to create a basic script for calculating the standard deviation of a set of randomly generated integers. The two histograms generated in the code below are different, though they should be the same to my knowledge as I never modified the variable 'incomes' between generating the two histograms.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt

npoints = 10000
incomes = np.random.normal(100.0, 50.0, npoints)

################
plt.hist(incomes, 50)
plt.show()
###############

incomestore = incomes

meanincomes = np.mean(incomes)
for i in range(incomes.size):
    incomestore[i] = (incomes[i] - meanincomes)**(2)
standardDeviation = np.sqrt(np.mean(incomestore))

print(standardDeviation)
###############
plt.hist(incomes, 50)
plt.show()
##############

The two histograms generated by the code are different when they should be the same (not a scaling error).

A: incomestore and incomes refer to the same array. You have to make a copy
incomestore = incomes.copy()

But it is better, to use the vector abilities of numpy:
incomestore = (incomes - incomes.mean()) ** 2
standardDeviation = incomestore.mean() ** 0.5


text:
Q: column_spec function in kableExtra in R doesn't work I want co change column width in pdf with kable ( , 'latex') but the fucntion doesn't work. Anybody know why? here is my code:
   table = knitr::kable(jeden, "latex" , row.names = F ,  align = "llrrrrrrrrrr" , escape = F, booktabs = F, caption = '1. Sprzedaz uslug i towarow razem')
   kableExtra::column_spec(table, 1, width = "1cm", bold = TRUE, italic = TRUE)

A: It's not a bug but rather a relatively strange setting for align in knitr::kable(). In xtable you can put align in a string but for kable, you will have to provide a vector. In your case, if you put things like align = c(rep("l", 2), rep("r"), 2), you should be fine.

A: It seems that align breaks your column_spec, but only for LaTeX/PDF output.
Here are two minimal & reproducible examples.
PDF output
---
title: "Untitled"
output:
  pdf_document: default
---

```{r}
library(knitr)
library(kableExtra)
x <- kable(head(mtcars[, 1:4]), "latex", row.names = F, align = "llrr")
column_spec(x, 1:2, width = "4cm", bold = TRUE, italic = TRUE)
```

If you remove align from the PDF RMarkdown document, column_spec works as expected.
HTML output
---
title: "Untitled"
output:
  html_document: default
---

```{r}
library(knitr)
library(kableExtra)
x <- kable(head(mtcars[, 1:4]), "html", row.names = F, align = "llrr")
column_spec(x, 1:2, width = "4cm", bold = TRUE, italic = TRUE)
```

This seems like a bug to me, and I would suggest opening an issue on the kableExtra GitHub site. If you do, you should reference this post, and include a minimal & reproducible example (similar to what I did).


text:
Q: Does this sanitize have any XSS leaks in it I want to make sure my sanitize doesnt have any leaks in it.
And also, im only outputting user-data within hardcoded p tags and h1 tags
eg :
<?php echo htmlspecialchars($user_data); ?>

So is this a safe way to protect me against XSS-injects.
First, im using this function to sanetize the data before it gets inserted into my DB, and while in my DB im using bind_param
function sanitize($str) {
   return strtolower(strip_tags(trim(($str))));
}

sanitize($user_data); - > then gets inserted into db

Then when I grap the data from the DB I am using this to show it.

 <?php echo htmlspecialchars($user_data); ?>

So, is this a safe way to block any XSS?
Thanks!

A: From a security standpoint, there is no need to use your sanitize function as long as you escape / process your data correctly for the medium you are outputting to:

*

*Using htmlspecialchars() is all that is needed for output to html;

*Use json_encode if you need to output to javascript;

*Use prepared statements with bound variables for your database;

*etc.


text:
Q: How to Use a Barcode Scanner with .Net 5.0 I want to develop an app that utilises a barcode scanner ( of various types ) .
I don't want to use the barcode scanner like a keyboard ( intercepting keystrokes etc )
Is there a .net 5 library or part of the framework that I can use in a winfoms app?


text:
Q: How to have radlistview paging maintain it's index when the back button is pressed? The scenario is that i have a list view with paging. If the user is on page 4, then clicks a link, decides that its the wrong link, then hits the back button, the listview need to be displayed with the same sorting on page 4, just like he left it. Currently, it is resetting the sort and displaying on page 1.
I tried storing the current page index in a session when the index is changed, then setting it from the session in the prerender event, but then i get "page expired" errors. Any ideas? TIA

A: The back button operation can only be handled in client-side javascript, as the server-side code does not run.  For what you are trying to do, you'll want to check out these two resources (application history points):

*

*http://msdn.microsoft.com/en-us/library/cc488548.aspx

*http://msdn.microsoft.com/en-us/library/cc488538.aspx


text:
Q: jQuery add class to object with .get() method running into a weird thing and I'm not sure what's going on.
I've grabbed the index of a DOM element via .index(), found a matching element via .get() and I'm trying to add a class to it via .addClass().
My console is returning the error: "Uncaught TypeError: Object #<HTMLLIElement> has no method 'addClass'"... which is especially odd because my Log shows the HTML element just fine (http://cloud.dhut.ch/image/2W3S0R3k2h2U)
Am I missing something? It's not returning in an array or anything. Confused.
Thanks!
JavaScript:
nFLi.get(active).addClass('active');

A: You need to wrap it into a jquery object.
$(nFLi.get(active)).addClass('active');

Or you could use .eq method instead of .get, which returns a jquery object instead of original HTMLElement.
nFLi.eq(active).addClass('active');


text:
Q: multiple web cams in AMCap I built the AMCap sample under direct show in SDK. It is able to handle 2 or more web cam, how do I modify the program for me to use them simultaneously… like press one button that says 'start capture' and make sure that all the cameras start capturing and one button that says 'stop capture' to stop all the cameras. i want the frames from different cameras to be save in different files. I am new to C++ and any kind of help is appreciated ! Thanks for your time!

A: Use GraphEdit tool. There you can build you own graph with all video input devices connected. Please see http://en.wikipedia.org/wiki/GraphEdit

A: If you're just starting out with DirectShow programming, this might be a bit of a hill climb, but I hope it's of some help, or points you in the right direction.
M$DN has a page describing how to select a capture device.  It's a little thin on examples, so I've provided a simple implementation below.
The theory is that you need to enumerate all devices in the CLSID_VideoInputDeviceCategory, and attempt to create a render graph for each valid item in the category.
First I'll show you the code to iterate the names of the devices in the category.  Below are 3 static functions you can use to iterate the devices in a category.  Once you've added these functions to your project, you can list the devices in the Video Input Device category by calling the following function:
ListDevicesInCategory(CLSID_VideoInputDeviceCategory);

Okay, here are the three functions.  ListDevicesInCategory() is where the work happens.  It depends on other two functions, FindDeviceInCategory() and CountDevicesInCategory()
#define RFAIL(x) { HRESULT hr = x; if(FAILED(hr)) {return hr;} }

static HRESULT FindDeviceInCategory(IBaseFilter** pSrc, const IID& cls, wstring& wFilterName,int devNum)
{
    CComPtr<ICreateDevEnum> spDevEnum;
    CComPtr<IEnumMoniker>   spEnum;
    int                     i;

    RFAIL( spDevEnum.CoCreateInstance(CLSID_SystemDeviceEnum) );
    RFAIL( spDevEnum->CreateClassEnumerator(cls, &spEnum, 0) );

    if(spEnum == 0)
        return E_FAIL;

    for(i = 0; i >= 0; i++)
    {
        CComPtr<IMoniker> spiMoniker;

        if( spEnum->Next(1, &spiMoniker, 0) != S_OK )
            return E_FAIL;

        if( devNum == i)
        {
            CComVariant varName;
            CComPtr<IPropertyBag> spiPropBag;
            RFAIL(spiMoniker->BindToStorage(0, 0, IID_IPropertyBag,reinterpret_cast<void**>(&spiPropBag)));
            RFAIL(spiPropBag->Read(L"FriendlyName", &varName, 0));
            RFAIL(spiMoniker->BindToObject(0, 0, IID_IBaseFilter, reinterpret_cast<void**>(pSrc)));
            wFilterName = V_BSTR(&varName);

            varName.Clear();
            return S_OK;
        }
    }

    return E_FAIL;
}

static HRESULT CountDevicesInCategory( int *pCount, const IID& categoryClass )
{
    // pass in a category class like CLSID_VideoInputDeviceCategory, writes the count of the number of filters in that category
    // available on the local machine
    HRESULT hr = S_OK;

    CComPtr<ICreateDevEnum> spIDevEnum;
    CComPtr<IEnumMoniker>   spIEnum;
    CComPtr<IMoniker>       spIMoniker;

    hr = CoCreateInstance(CLSID_SystemDeviceEnum, 0, CLSCTX_INPROC_SERVER, IID_ICreateDevEnum, reinterpret_cast<void**>(&spIDevEnum));
    if( ! SUCCEEDED(hr) || hr == S_FALSE )
    {
        *pCount = 0;
        return hr;
    }

    hr = spIDevEnum->CreateClassEnumerator( categoryClass, &spIEnum, 0 );
    if( ! SUCCEEDED(hr) || hr == S_FALSE )
    {
        *pCount = 0;
        return hr;
    }

    if( spIEnum )
    {
        while( spIEnum->Next(1, &spIMoniker, 0) == S_OK )
        {
            (*pCount) ++;
            spIMoniker.Detach();
        }
    }

    return S_OK;
}

static HRESULT ListDevicesInCategory( const GUID & cls )
{
    CComPtr<IBaseFilter>    spSource;
    wstring *               psNextFilter        = NULL;
    int                     nDeviceNum          = 0;
    int                     nTotalNumDevices    = 0;
    HRESULT                 hr                  = S_OK;
    bool                    bComplete           = false;
    DeviceNames             CaptureDeviceNames;

    if( FAILED(CountDevicesInCategory( &nTotalNumDevices, (IID)cls )) )
        bComplete = TRUE;

    if( nTotalNumDevices == 0 )
        bComplete = TRUE;

    while( ! bComplete )
    {
        psNextFilter = new std::wstring;

        hr = FindDeviceInCategory( &spSource, (IID)cls, *psNextFilter, nDeviceNum++ );

        if( SUCCEEDED(hr) && spSource  )
        {
            if ( *psNextFilter )
            {
                wcout << *psNextFilter << endl;
                delete *psNextFilter;
                psNextFilter = NULL;
            }

            spSource.Release();
            spSource = NULL;
        }
        else
            bComplete = TRUE;
    }

    return S_OK;
}

Once you've identified an item in a category that you're interested in, you can add it to a graph with the IGraphBuilder::AddFilter call.
To add a filter to your graph, you'll first need to get an IBaseFilter* to that filter.  I've got one more function for you to do this with.
Define an IBaseFilter smart pointer:
CComPtr<IBaseFilter> spSource;

Attach to the filter:
m_spSource.Attach(
                GetFilter(CLSID_VideoInputDeviceCategory, CComBSTR(L"Osprey-450e Video Device 1A"))
          );

Here's that last function - GetFilter:
static IBaseFilter * GetFilter( REFCLSID clsidDeviceClass, CComBSTR & sName )
{
    HRESULT             hr;
    IBaseFilter *       pRetFilter      = NULL;
    ICreateDevEnum *    pSysDevEnum     = NULL;
    IEnumMoniker *      pEnum           = NULL;
    IMoniker *          pMoniker        = NULL;
    int                 nSameSrcCounter = 0;

    hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_ICreateDevEnum, (void**)&pSysDevEnum);

    if( pSysDevEnum )
        hr = pSysDevEnum->CreateClassEnumerator(clsidDeviceClass, &pEnum, 0);

    if (hr != S_OK)
        return NULL;

    USES_CONVERSION;

    while ( pEnum->Next(1, &pMoniker, NULL) == S_OK )
    {
        IPropertyBag *pPropBag = NULL;
        VARIANT var;
        VariantInit(&var);

        pMoniker->BindToStorage(0, 0, IID_IPropertyBag, (void **)&pPropBag);

        hr = pPropBag->Read(L"FriendlyName", &var, 0);
        if (SUCCEEDED(hr))
        {
            if(sName == OLE2T(var.bstrVal))
            {
                hr = pMoniker->BindToObject(NULL, NULL, IID_IBaseFilter, (void**)&pRetFilter);
                if (FAILED(hr))
                    pRetFilter = NULL;

                VariantClear(&var);
                pPropBag->Release();
                pMoniker->Release();
                break;
            }
        }

        VariantClear(&var);
        pPropBag->Release();
        pMoniker->Release();
    }

    pSysDevEnum->Release();
    pEnum->Release();

    return pRetFilter;
}


text:
Q: Css canvas circle stroke sharpness I have a circle seek bar on my audio player which draws canvas circle in a timer interval. The problem is that as canvas gets redrawn it looses it sharpness. The code, when the canvas is drawn once, the normal circle is below:
https://jsfiddle.net/0zs2gqxk/
The relevant code in the fiddle is below
for (var i = 0; i < 1; i++) {
  context.beginPath();
  context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  context.lineWidth = 5;
  context.strokeStyle = '#0000ff';
  context.stroke();
}

Here its redrawn 50 times to show the problem:
https://jsfiddle.net/4bf9ka49/
In second example edges get ugly. Is there a way to avoid that?

A: Add context.clearRect(0, 0, canvas.width, canvas.height) to you code to clear the canvas, so it won't make multiple in the same spot.
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 70;

for (var i = 0; i < 50; i++) {

  context.clearRect(0, 0, canvas.width, canvas.height);

  context.beginPath();
  context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);

  context.lineWidth = 5;
  context.strokeStyle = '#0000ff';
  context.stroke();
  context.clearRect(0, 0, canvas.width, canvas.height);
}

Here's a image of the first JSFiddle you shared, and my code's image.

Identical.


text:
Q: Bias-variance decomposition for random variables taking values in a Hilbert space I'm trying to recover the bias-variance decomposition in Hilbert space. Below is my understanding.  Could you have a check on it?

Let $(\Omega, \mathcal F, P)$ be a probability space and $(H, \langle \cdot, \cdot \rangle_H, | \cdot |_H)$ a Hilbert space . It follows that $L_2(\Omega)$ is a Hilbert space with an inner product $\langle \cdot, \cdot \rangle_{L_2}$ defined by
$$
\langle X, Y \rangle_{L_2} := \int_{\Omega} \langle X(\omega), Y(\omega) \rangle_H \mathrm d P(\omega) = \mathbb E_{P} \langle X, Y \rangle_H.
$$
Let $| \cdot |_{L_2}$ be the induced norm of $\langle \cdot, \cdot \rangle_{L_2}$. Then $|X|_{L_2} = [\mathbb E |X|^2_H]^{1/2}$. We define covariance by
$$
\operatorname{Cov} (X,Y) := \langle X, Y \rangle_{L_2} - \langle \mathbb E X, \mathbb EY \rangle_{H}.
$$
Clearly, $\operatorname{Cov}$ is a bilinear form. It follows that $\operatorname{Var} X := \operatorname{Cov} (X,X) = |X|^2_{L_2} - |\mathbb E X|^2_{H}$ and that $\operatorname{Var} X \le \mathbb E |X|^2_H$. Fix $x \in H$. We have $$
\operatorname{Var} [X -x] = |X-x|^2_{L_2} - |\mathbb E X -x|^2_{H},
$$
and thus
$$
|X-x|^2_{L_2} = |\mathbb E X -x|^2_{H} + \operatorname{Var} X.
$$
The bias-variance decomposition then follows, i.e.,
$$
\mathbb E |X-x|^2_H = |\mathbb E X -x|^2_{H} + \operatorname{Var} X.
$$


text:
Q: Tex figures only work in Pandoc with a Markdown image first I use Pandoc's markdown to generate a PDF file. To have more control over figures and images I use inline latex like the following:
## Chapter 12

\begin{figure}[htbp]\includegraphics[width=0.25\textwidth, height=!]{images/castle01.png}\centering\end{figure}

lorem ipsum

This produces following error message:
! Undefined control sequence.
l.80 \begin{figure}[htbp]\includegraphics

But if I use a markdown image once before, the image is rendered.
## Chapter 12

![](castle01.png){width=50%}

\begin{figure}[htbp]\includegraphics[width=0.25\textwidth, height=!]{images/castle01.png}\centering\end{figure}

lorem ipsum

I assume this is some kind of initialization issue that only occurs once for the first image. How can I use the latex way without once Markdown image?

A: Use the YAML metadata block to enable graphics/graphicx like this:
---
graphics: yes
---
## Chapter 12

\begin{figure}[htbp]\includegraphics[width=0.25\textwidth, height=!]{images/castle01.png}\centering\end{figure}

lorem ipsum


text:
Q: Bash won't change variable value I am trying to change the variable reload from 0 to 1 as you can see in my code below:
for d in /home/*; do
  u="${d##*/}";
  reload=0;
  echo "Checking $u";
  if [ -e /home/$u/info/reload.php ]; then
    echo "FOUND!";
    reload=1;
  fi
done
echo $reload;
if [ $reload = 1 ]; then
  service apache2 reload
fi

The problem is that it doesn't get changed, $reload remains as 0, the output is similar to this (apache does not get reloaded):
Checking user1
FOUND!
Checking user2
0 #< this should be 1 not 0 :(

Why won't my bash variable change??

A: You're resetting reload for each user. If the file is not found for the last user, reload will be 0 when you exit the loop.
Suggested fixes (with indentation for readability):
#!/usr/bin/env bash

reload=0
for d in /home/*; do
    u="${d##*/}"
    echo "Checking $u";
    if [ -e /home/$u/info/reload.php ]; then
        echo "FOUND!"
        reload=1
    fi
done
echo $reload
if [ $reload -eq 1 ]; then
    service apache2 reload
fi