text:
Q: Terraform state - change resource position In one of our accounts a long time ago AWS private subnets were created. There are no matching public subnets and no resources in these private subnets. So below, aws_subnet.private_subnets[0] and aws_subnet.private_subnets[1] are the empty subnets
aws_subnet.private_subnets[0]
aws_subnet.private_subnets[1]
aws_subnet.private_subnets[2]
aws_subnet.private_subnets[3]
aws_subnet.private_subnets[4]

The subnets were created using terrform exactly as below:
 resource "aws_subnet" "private_subnets" {
      count      = length(split(",", var.private_subnets))
      cidr_block = element(split(",", var.private_subnets), count.index)

where var.private_subnets is a string containing our 5 different CIDR blocks.
I want to tidy this up but I tried removing the first two CIDR blocks from the string, but it still tries to recreate them, because it wants to change:
aws_subnet.private_subnets[2] to aws_subnet.private_subnets[0],
aws_subnet.private_subnets[3] to aws_subnet.private_subnets[1],
aws_subnet.private_subnets[4] to aws_subnet.private_subnets[2]
I don't want this to happen as then I would need to redeploy all our EC2s again in the new subnets. So what is the best way around this? Is it to remove them from the state, with:
terraform state rm aws_subnet.private_subnets[0]
and then change them with:
terraform state mv 'aws_subnet.private_subnets[2]' 'aws_subnet.private_subnets[0]'
I haven't worked a lot with the state and breaking this could cause a lot of problems, so just want to be sure. Or would a better bet be to delete them manually in AWS and then run the terraform again? - I'm not sure if this would cause the same problem that I currently have

A: If you are changing the source collection in a way that affects which objects belong to which indices then indeed you will need to use a strategy like terraform state mv to explain to Terraform how the index assignments have changed.
In your case it seems like that would be the following:
terraform state rm 'aws_subnet.private_subnets[0]'
terraform state rm 'aws_subnet.private_subnets[1]'
terraform state mv 'aws_subnet.private_subnets[2]' 'aws_subnet.private_subnets[0]'
terraform state mv 'aws_subnet.private_subnets[3]' 'aws_subnet.private_subnets[1]'
terraform state mv 'aws_subnet.private_subnets[4]' 'aws_subnet.private_subnets[2]'

The ordering of these operations is important because Terraform cannot track two different objects at the same address, and so we need to always free up the target index before moving another instance into it.

It seems like your var.private_subnets here is a string containing a comma-separated list of CIDR blocks. In modern Terraform it would typically be better to declare this as a set of strings -- so that each CIDR block is a separate element -- and then use for_each rather than count so that Terraform will track the instances by the CIDR block strings themselves, rather than by their arbitrary positions in a list.
variable "private_subnets" {
  type = set(string)
}

resource "aws_subnet" "private_subnets" {
  for_each = var.private_subnets

  cidr_block = each.value
}

This change will also require some migration work using terraform state mv, so since you'll be doing that work anyway it might be beneficial to make this change at the same time and thus avoid doing migration twice to get to the modern idiom.
You didn't include in your question the actual values of the CIDR addresses, so I'm just going to assume sequential addresses like 10.x.0.0/16 where "x" is the same as the index. Under that scheme, your migration would look something like this instead:
terraform state rm 'aws_subnet.private_subnets[0]'
terraform state rm 'aws_subnet.private_subnets[1]'
terraform state mv 'aws_subnet.private_subnets[2]' 'aws_subnet.private_subnets["10.2.0.0/16"]'
terraform state mv 'aws_subnet.private_subnets[3]' 'aws_subnet.private_subnets["10.3.0.0/16"]'
terraform state mv 'aws_subnet.private_subnets[4]' 'aws_subnet.private_subnets["10.4.0.0/16"]'

Notice that in this case the new addresses have instance keys that are strings containing the actual CIDR prefixes rather than being integer positions in the list.
That means that they no longer have any inherent order and Terraform will understand that if you add something new to the set it means to create a new subnet, and if you remove an item from the set it means to remove the corresponding subnet. If you remove CIDR prefixes in the future, after doing this one-time migration, you won't need to terraform state mv to fix up the positions because they no longer have specific positions.


text:
Q: Can't trigger a function in Vue js This is my JS code
 getItemData:function(e){
            var id = e.target.getAttribute('data-id');
            var uom = e.target.options[e.target.options.selectedIndex].dataset.uom;
            var uomId = e.target.options[e.target.options.selectedIndex].dataset.uomid;

            if(uomId == null || uom == null){
                $('#uom_item'+id).html('<option value="" selected></option>');
            }
            this.GetItemTotalAmount(id);
            this.getItemGroupUOM(id);
            this.getVatStructure(id);
        },
getVatStructure:function (id)
        {
            var trans_sub_type = $('#trans_sub_type').val();
            var prod_type = $('#product_type').val();
            var hsCode = $('#hs_code'+id).val()
            var defaultVatRate = $('#default_vat_rate_id'+id).val()
            $.ajax({
                url:'get-vat-structure-by/item',
                method:'get',
                data:{'tranSubType':trans_sub_type,'prod_type':prod_type,'hs_code':hsCode,'defaultVatRate':defaultVatRate},
                success:function(res){
                    // console.log(res);
                    $('#vat_structure_rate'+id).html(res.result);
                    if (!res.isTrue)
                    {
                        $('#vat_item'+id).val(null);
                        $('#vat_amount_item'+id).val(null);
                    }
                    $('#vat_structure_rate'+id).trigger("change");
                    console.log('trg');

                },
                error:function(err){
                    console.log(err);
                }
            });
        },
        getVatData:function (e)
        {
            console.log('inside');
            var id = e.target.getAttribute('data-id');
            var vat = e.target.options[e.target.options.selectedIndex].dataset.vat;
            $('#vat_item'+id).val(vat);
            this.GetItemTotalAmount(id);
        }

I want to trigger getVatData() which is an on change function declared in HTML  as @change="getVatData" function from getVatStructure function.
How can I do that. I have tried the following but now working.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Socket is closed Exception when trying sslException I am trying to implement a SSL connection using a custom certificate on an Android client. If i try to connect to the same Server using a normal Java program I wrote (where I import the keystore using system parameters) everything works fine. Also if I connect to the server using the android method, but without https it works fine. But once I use the Android method with https (with the method shown below) it gives me this Error:
04-06 20:12:29.234: W/System.err(2328): java.net.SocketException: Socket is closed
04-06 20:12:29.234: W/System.err(2328):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.checkOpen(OpenSSLSocketImpl.java:237)
04-06 20:12:29.234: W/System.err(2328):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:250)
04-06 20:12:29.234: W/System.err(2328):     at libcore.net.http.HttpConnection.setupSecureSocket(HttpConnection.java:209)
04-06 20:12:29.234: W/System.err(2328):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:478)
04-06 20:12:29.234: W/System.err(2328):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:442)
04-06 20:12:29.244: W/System.err(2328):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
04-06 20:12:29.244: W/System.err(2328):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
04-06 20:12:29.244: W/System.err(2328):     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81)
04-06 20:12:29.244: W/System.err(2328):     at libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)
04-06 20:12:29.244: W/System.err(2328):     at libcore.net.http.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:281)
04-06 20:12:29.244: W/System.err(2328):     at john.z.lead.utils.ServerRequest.get_response(ServerRequest.java:497)
04-06 20:12:29.244: W/System.err(2328):     at john.z.lead.utils.ServerRequest.logout(ServerRequest.java:797)
04-06 20:12:29.244: W/System.err(2328):     at john.z.lead.fragments.Logout_Fragment$1$1.run(Logout_Fragment.java:59)
04-06 20:12:29.244: W/System.err(2328):     at java.lang.Thread.run(Thread.java:841)

the code I am using is:
public static JSONObject get_response(List<Parameter> params,
        final String address) throws IOException, JSONException, LeadException {
    // String body = "param1=" + URLEncoder.encode( "value1", "UTF-8" ) +
    // "&" +
    // "param2=" + URLEncoder.encode( "value2", "UTF-8" );

    StringBuilder body = new StringBuilder();
    for (Parameter pa : params) {
        body.append(pa.getKey() + "="
                + URLEncoder.encode(pa.getValue(), "UTF-8") + "&");
    }
    try {

        URL url = new URL(address);

        HttpURLConnection connection = (HttpURLConnection) url
                .openConnection();
        if (connection instanceof HttpsURLConnection) {
            KeyStore trusted = KeyStore.getInstance("BKS");

            // Get the raw resource, which contains the keystore with
            // your trusted certificates (root and any intermediate certs)
            InputStream in = Datastore.getActiv().getResources()
                    .openRawResource(R.raw.truststore);
            // Initialize the keystore with the provided trusted
            // certificates
            // Also provide the password of the keystore
            trusted.load(in, "lead".toCharArray());

            // Create a TrustManager that trusts the CAs in our KeyStore
            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(trusted);

            // Create an SSLContext that uses our TrustManager
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, tmf.getTrustManagers(), null);

            ((HttpsURLConnection) connection)
                    .setSSLSocketFactory(context.getSocketFactory());

        }
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length",
                String.valueOf(body.length()));
        OutputStreamWriter writer = new OutputStreamWriter(
                connection.getOutputStream());

        writer.write(body.toString());
        writer.flush();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));

        StringBuilder build = new StringBuilder();
        for (String line; (line = reader.readLine()) != null;) {
            build.append(line);
        }

        writer.close();
        reader.close();

        return new JSONObject(build.toString());

    } catch (UnknownHostException | FileNotFoundException
            | ConnectException e) {
        Datastore.getActiv().runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(
                        Datastore.getActiv(),
                        "Konnte keine Verbindung zum Server ( "
                                + address
                                + " ) herstellen.\nBitte überprüfen Sie ihre Netzwerkverbindung und / oder\nkontaktieren Sie einen Administrator",
                        Toast.LENGTH_LONG).show();
                ;

            }

        });
        throw e;
    } catch (KeyManagementException|KeyStoreException|NoSuchAlgorithmException|CertificateException e) {
        MessageDialog.showMessageDialog(Datastore.getActiv(), "Es ist ein kritischer Fehler beim Herstellen der sicheren Verbindung aufgetreten");
        e.printStackTrace();
        throw new LeadException(LeadException.Errorcode.UNKNOWN);
    }

}

A: SocketException: socket is closed means that you closed the socket and then continued to use it.
NB You don't need to set the Content-Length header. HttpURLConnection does that automatically for you.


text:
Q: Printer menu different between 2 ubuntu 12.10 I got two samsung new series 9, 13', the very same, with Ubuntu 12.10 installed on it (Erratum : The second one SEEMS to have 13.04 installed on it, but same kernel 3.5.0-23). I installed the MP495 printer driver on both :
$ dpkg -l | grep 495
rc  scangearmp-mp495series 1.60-1 amd64   ScanGear MP for Linux.

But one can print, and the other one cannot. Indeed, I found something weird :

And here is the printer menu on laptop N°2, not working :

What's wrong with this N°2 ? never seen such printing menu before...
So I can't follow the usual procedure to add a new printer, and can't print from this N°2 laptop (wifi printing).
Any help would be much appreciated.

A: The problem was due to ppa:gnome3-team/gnome3. I got it back to normal by running :
sudo apt-get install ppa-purge
sudo ppa-purge ppa:gnome3-team/gnome3

Found the answer in this post.


text:
Q: Crash with UIWebView I have a Xamarin.iOS application that wraps UIWebView. Unfortunately, I'm receiving significant number of crashes in the Firebase console; it occurs only on iPhone with iOS 10, iPad doesn't have this issue.
Personally I can't reproduce the crash, so I have only stacktrace:
EXC_BAD_ACCESS / KERN_INVALID_ADDRESS
1   libobjc.A.dylib     objc_msgSend + 115024
2   UIKit               -[_UIKeyboardTextSelectionController selectTextWithGranularity:atPoint:executionContext:] + 5209476
3   UIKit               -[_UIKeyboardBasedNonEditableTextSelectionGestureController oneFingerForcePan:] + 5624368
4   UIKit               -[UIGestureRecognizerTarget _sendActionWithGestureRecognizer:] + 6166732
5   UIKit               _UIGestureRecognizerSendTargetActions + 6181120
6   UIKit               _UIGestureRecognizerSendActions + 1700016
7   UIKit               -[UIGestureRecognizer _updateGestureWithEvent:buttonEvent:] + 266176
8   UIKit               _UIGestureEnvironmentUpdate + 6116260
9   UIKit               -[UIGestureEnvironment _deliverEvent:toGestureRecognizers:usingBlock:] + 6115188
10  UIKit               -[UIGestureEnvironment _updateGesturesForEvent:window:] + 6111776
11  UIKit               -[UIWindow sendEvent:] + 258892
12  UIKit               -[UIApplication sendEvent:] + 65404
13  UIKit               __dispatchPreprocessedEventFromEventQueue + 8428060
14  UIKit               __handleEventQueue + 8405368
15  UIKit               __handleHIDEventFetcherDrain + 8406436
16  CoreFoundation      __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 898088
17  CoreFoundation      __CFRunLoopDoSources0 + 896408
18  CoreFoundation      __CFRunLoopRun + 887204
19  CoreFoundation      CFRunLoopRunSpecific + 36256
20  GraphicsServices    GSEventRunModal + 49264
21  UIKit               UIApplicationMain + 478360
22  XamarinApp.iOS      (wrapper_managed-to-native)_UIKit.UIApplication:UIApplicationMain (<unknown>:1)
23  XamarinApp.iOS      Main (UIApplication.cs:79)
24  XamarinApp.iOS      XamarinApp_iOS_XamarinApp_iOS_Application_Main_string__ + 39656
25  XamarinApp.iOS      wrapper_runtime_invoke_object_runtime_invoke_dynamic_intptr_intptr_intptr_intptr + 634656
26  Mono                4316120312 + 378104
27  Mono                4316622816 + 880608
28  Mono                4316635652 + 893444
29  Mono                4316004656 + 262448
30  XamarinApp.iOS      xamarin_main (monotouch-main.m:480)
31  XamarinApp.iOS      main (main.m:131)
32  libdyld.dylib       start + 17816

Any help would be highly appreciated. Migrating to WKWebView is not an option for me since the app works quite a lot with cookies.


text:
Q: How to determine the ideality factor (N) of a diode from the datasheet? I have to find Is an N from the datasheet of diodes 1N4004 and 1N4148. I did this by estimating both of these by accomodating a straight line in the log-linear Id vs Vd graph in the datasheet of each diode. Is there a different way of getting to know these two parameters form de datasheet?
Thanks.

A: There are at least three, not two, important parameters when looking at the datasheet. Also, you need to apply as much precision as you can, within the limits available to you in a chart. These are the series resistance, the saturation current, and the (non-)ideality factor. So it takes at least three measurement points to extract these.
At first, it may seem that more points are better, as the fitting process is basically an integration process (the summations indicated by partial derivatives take place) and therefore will tend to better mitigate random errors. But humans reading charts may be more likely to develop systematic errors. So I tend to imagine it is okay to just take your best shot at getting three points from the charts, splitting two end-points by a third point about midway between them.
Here's an example from Vishay's chart for the 1N4148 datasheet:

I've added a blue average curve through their two scattering limit curves and then "red-lined" three selected points.
These points were measured on a pixel basis and the results are:\$\left[\begin{array}{cc}552\:\text{mV}& 200\:\mu\text{A}\\842\:\text{mV}& 20\:\text{mA}\\1.158\:\text{V}& 200\:\text{mA}\end{array}\right]\$
Plugging these into Python code running on Sage, I get: \$R \approx 1.005\:\Omega\$, \$I_\text{SAT}\approx 16.41\:\text{nA}\$, and \$N \approx 2.283\$.
The code I used is:
def diode():
    print( "This program uses 3 diode measurements to extract parameters." )
    print( "You will need to have taken these measurements beforehand." )
    print( "Enter each point as [ <diode current>, <diode voltage> ]." )
    print( "" )
    TA= int( input( "Enter the ambient temperature in Celsius (default is 27 C): " ) or "27" )
    print( "" )
    VT= 8.61733034e-5 * ( 273.15 + TA )
    POINTS= []
    vd, id, N, ISAT, RS= symbols( "vd id N ISAT RS" )
    for i in range(3):
        pid, pvd= input( "Enter point " + str(i) + ": " ).split()
        POINTS.append( { vd: float( pvd ), id: float( pid ) } )
    EQS= []
    for i in range(3):
        EQS.append( Eq( POINTS[i][vd], RS*POINTS[i][id] + N*VT*ln(POINTS[i][id]) - N*VT*ISAT ) )
    print( POINTS )
    print( EQS )
    ANS= solve( EQS, [ RS, N, ISAT ] )[0]
    print( "RS   = " + str(ANS[0]) )
    print( "N    = " + str(ANS[1]) )
    print( "ISAT = " + str(exp(ANS[2])) )

That said, you are free to work out your own method. But I'd strongly recommend that you keep in mind that there is bulk, contact, and lead resistance that should be incorporated in the process you use. The reason is pretty simple. The shape of the curves you see will be impacted by it and if you don't account for it then your other two numbers will be still further apart from reality, than otherwise. It's difficult enough getting decent data points off of a chart, as it is, not to make it worse by neglecting an important parameter.
The above code is actually somewhat more robust on \$N\$ than it is on the other parameters. So it's probably useful for what you want, I think.


text:
Q: When to use active directory? Hi everyone I am looking for the opinion of some experienced Sys Admins out there to know when it is appropriate to use an AD server. For example does 3 - 5 person small business merit the use of AD? If so what are the advantages (other then centralized password database)? If not how many users do merit it?
Thanks!!

A: In my opinion, anything over 3 users merits it. SBS is a great starting point, and is designed for exactly the situation you are describing. It bundles all services, such as Sharepoint, Exchange and AD into one package.
Other things to consider are employee turnover and growth. Setting up a domain will significantly reduce your administrative overhead as things grow.

A: It very much depends on the situation you're at. If all is required is an access to one/two shared folders and a printer, configuring AD might not be required. However, if there will be any future expansion of the company, such as additional users, services, e.t.c - managed environment should be considered. AD gives tremendous additional features and "nice" central tools. Such as, central user management, less security overhead over each and every workstation in the organization, policies, software deployments, central changes to workstations, applying security updates ... the list is practically endless.
I would definitely recommend checking into the topic a bit further.

A: When you have more than a couple of users who need to share files and you don't want to have those shared files stored on their local PC's. You also want to just back up the one server with all the data.  And you don't want to have to go around each machine setting up users & passwords... or, make everything open and public so that all shares are guest with write access.  i.e. you want centralized control and security too.
You might also have a printer attached to it and other services running on this box, more than just AD.
You get the picture.  I think you can easily look at your situation and you'll know the answer.


text:
Q: python build vs wheel packages I am going through python packaging, build and PyPI cycle. My current understanding is that:

*

*using the wheel package, we can create a whl package.

*the build package can also create a whl package.

Which module should be used when? What's the difference between the PYPI modules wheel and build?


text:
Q: ElasticSearch - How much faster is a Term query than a Match query As Term based queries don't have an analysis phase when doing a query and effectively is a retrieval operation rather than a Searching query.
I would assume is would be significantly faster than doing a match or query_string which understand the underlying mapping and also carry out an analysis/tokenization on the input query first.
I cant find any performance statistics around this and the potential performance gain. Does anyone know of any?


text:
Q: Interaction isn't translating input Text to Strings I'm in need of some help. To start with, what I have is an interaction where you fill out 5 text boxes in response to 2 questions. Each of the 5 answers must be filled out as input text and then checked against an array of acceptable responses when the done button is clicked. Also, there are two type differences in the fields. So the first three answer fields belong to a range of acceptable responses in the array: Type A and the next two questions to Type B. It's possible to fill out the correct responses in any order, so long as the typing is correct.
What I can't seem to figure out is why the textFields aren't translating to Strings.
import flash.text.TextField;
import flash.events.MouseEvent;

stop();

//*--------------------------------------------
//
//                  THINGS YOU CAN CHANGE
//
//*--------------------------------------------

var a_inputType:Array = new Array("Doggie Day Spa", "Deb's Dog Walking Service", "Pet Market", "Pampered Pet", "TLC Grooming");     //All recognized type responses, Type A listed before Type B
var n_typeA:Number = new Number(3);                                                                                //Sets the range for Type A

//*--------------------------------------------
//
//                  PAGE SETUP
//
//*--------------------------------------------

var n_typeB:Number = new Number(a_inputType.length - n_typeA +1);       //Finds the range of Type B
var a_testArray:Array = new Array();                                    //Holds push data from submit button

var a_correctArray:Array = new Array();                                 //Creates an array to run a final test against
for(var c = 0; c<=a_inputType.length-1; c++){                           //Loop populates the array
    a_correctArray.push(1);
}

var inputField1:TextField = new TextField();                            //Creates the Text Fields
var inputField2:TextField = new TextField();
var inputField3:TextField = new TextField();
var inputField4:TextField = new TextField();
var inputField5:TextField = new TextField();

var txtString1:String = new String();                                   //Creates the strings for translating the input text
var txtString2:String = new String();
var txtString3:String = new String();
var txtString4:String = new String();
var txtString5:String = new String();

for(var f = 1; f<=a_inputType.length; f++){                             //Assigns them properties, locations, and adds a listener for text
    var fieldBuilder = "inputField"+f;
    var fieldFinder = "txt_pos"+f;
    addChild(this[fieldBuilder]);
    this[fieldBuilder].border = false;
    this[fieldBuilder].width = 290;
    this[fieldBuilder].height = 25;
    this[fieldBuilder].x = this[fieldFinder].x;
    this[fieldBuilder].y = this[fieldFinder].y;
    this[fieldBuilder].type = "input";
    this[fieldBuilder].multiline = true;
    this[fieldBuilder].text = "";
    this[fieldBuilder].addEventListener(TextEvent.TEXT_INPUT, function (){
                             var stringBuilder = "txtString"+f;
                             this[stringBuilder] = this[fieldBuilder].text;
                             });
}

//*--------------------------------------------
//
//                  FUNCTIONS
//
//*--------------------------------------------

function SUBMIT(event:MouseEvent):void{
    for(var t=1; t<=a_inputType.length; t++){                           //Loop establishes checks for each String against an input type
        if(t<=n_typeA){                                                 //if/else divides the textfields into two ranges: typeA and typeB
            checkTypeA(this["txtString"+t], a_inputType);               //sends the array of correct responses and the captured String to checkTypeA
        }else{
            checkTypeB(this["txtString"+t], a_inputType);               //sends the array of correct responses and the captured String to checkTypeB
        }
    }
    var TEMPSELECT = a_testArray.toString();                            //reduces the testArray recieving push data into a String
    var TEMPCORRECT = a_correctArray.toString();                        //reduces the correctArray from scene set-up into a String
    if(TEMPSELECT == TEMPCORRECT){                                      //compares the strings and determines a trace response
        trace("correct");
    }else{
        trace("incorrect");
    }
}

function checkTypeA(value:String, arr:Array){                           //Checks the String against all the array values within the specified range for type A
    for (var a=1; a<=n_typeA; a++){                                     //determines the range
        if (arr[a]==value){                                             //checks the value
            a_testArray.push(1);                                        //if true, generates a push value for a testArray to be checked later
        }
    }
}

function checkTypeB(value:String, arr:Array){
    for (var b = n_typeA; b<=n_typeB; b++){
        if (arr[b-1]==value){
            a_testArray.push(1);
        }
    }
}

//*--------------------------------------------
//
//                  BUTTONS
//
//*--------------------------------------------

done_bttn.addEventListener(MouseEvent.CLICK, SUBMIT);                   //Launches the SUBMIT function when "Done" is pressed.

Upon further investigation I've noticed that the loop isn't terminating when it reaches 5. It keeps regurgitating TextFields over and over again with the same variable names and instancing. Because of this, the addChild is dumping input fields one on top of one another in the flash file (which makes editing a text field impossible since your always clicking on a new field positioned directly on top of the one you just edited).
The trace on the loop comes back like this:
inputField1
txt_pos1
inputField2
txt_pos2
inputField3
txt_pos3
inputField4
txt_pos4
inputField5
txt_pos5
inputField1
txt_pos1
inputField2
txt_pos2
inputField3
txt_pos3
inputField4
txt_pos4
inputField5
txt_pos5
inputField1
txt_pos1
inputField2
txt_pos2

and so on.... how can I stop this looping behavior. I've tried if/else breaking and that's not working.

A: The context of the this keyword changes when you call it from a local function. You can easily verify it if you add trace(this) to your anonymous function. It will trace out [object global].  Two solutions come to mind, store a reference of this in a variable:
var self:MovieClip = this;
for(var f = 1; f<=a_inputType.length; f++){
    //...
    this[fieldBuilder].addEventListener(TextEvent.TEXT_INPUT, function (){
                             var stringBuilder = "txtString"+f;
                             self[stringBuilder] = self[fieldBuilder].text;
                             });
}

Or declare a new function:
for(var f = 1; f<=a_inputType.length; f++){
    //...
    this[fieldBuilder].addEventListener(TextEvent.TEXT_INPUT, myFunction);
}

function myFunction(t:TextEvent){
                         var stringBuilder = "txtString"+f;
                         this[stringBuilder] = (t.target as TextField).text;
}


text:
Q: Artin, Proposition 2.1.4: proof of associative law of composition This is Artin Proposition 1.4 (from his book Algebra)

Suppose there is a associative law of composition given on a set S. There is a unique way to define, for every integer n, a product of n elements $a_1 , . . . a_n$ of S with the following properties:
i) the product of one element is the element itself.
ii) the product $a_1a_2$ is given by the law of composition.
iii) for any natural n, $[a_1a_2...a_n]=[a_1...a_i][a_{i+1}...a_n]$
Proof:
The product is defined by (i) and (ii) for $n≤2$ and satisfies (iii) for $n=2$. Suppose that we have defined the product of $r$ elements when $r≤n-1$ and that it is the unique product satisfying (iii). We then define the product of $n$ elements by the rule$$[a_1...a_n]=[a_1...a_{n-1}][a_n]$$
where the terms on the right side are those already defined. If a product satisfying (iii) exists, then this formula gives the product because it is (iii) when $i =n-1$.
   So if it exists, the product is unique.
We must now check (iii) for $i< n-1$:
  \begin{align} [a_1...a_n]&=[a_1...a_{n-1}][a_n] &&\text{(our definition)}\\
&=([a_1...a_i][a_{i+1}...a_{n-1}])[a_n] &&\text{(induction hypothesis)}\\
&=[a_1...a_i]([a_{i+1}...a_{n-1}][a_n]) &&\text{(associative law)} \\
&=[a_1\cdots a_i][a_{i+1}\cdots a_n] &&\text{(induction hypothesis)}
\end{align}
  This completes the proof.

why is it necessary to prove the case for $i< n-1$, since normally in inductive proofs we only prove the case for $i=n$?
Is it because we want to end with the formula in that particular format $(a_1 . . . a_i)(a_{i+1}. . .a_n)$
or is it because it is a inductive proof where we assumed the product exists for all   $i< n-1$ as or inductive step (instead of just existing for n-1)?

A: Let us reformulate statement and proof. This will make clear what is going on.
Suppose there is a associative law of composition given on a set $S$. There is a unique way to define, for every integer $n$, a product of n elements $a_1 , \dots, a_n$ of $S$, denoted by $[a_1\dots a_n]$, with the following properties:
(1) $[a_1] = a_1$.
(2) For any $n > 1$ the following property is satisfied:
$P(n) \quad$ $[a_1a_2...a_n]=[a_1...a_i]\cdot[a_{i+1}...a_n]$ for all $i$ with $0 < i < n$.
Note that the orginal (ii) is nothing else than $P(2)$ since in this case $i=1$ is the only possible choice.
Proof:
The product is defined by (1) for $n = 1$.
For $n > 1$ the product is defined by induction.
Suppose that we have defined the product of $r$ elements for $r =1,\dots,n-1$ and that it is the unique product satisfying $P(r)$ for all these $r$.  If a product of $n$ elements satisfying $P(n)$ exists, then it must satisfy the equation
$$D(n) \quad [a_1...a_n]=[a_1...a_{n-1}] \cdot [a_n]$$
because this is $P(n)$ when $i =n-1$. Hence it will be unique because $[a_1...a_{n-1}]$ is unique.
Now let us define $ [a_1...a_n]$ by equation $D(n)$. We must check that $P(n)$ holds true. For $i = n-1$ this is nothing else than the definition. For $0 < i < n-1$ we have
\begin{align} [a_1...a_n]&=[a_1...a_{n-1}][a_n] &&\text{(our definition)}\\
&=([a_1...a_i][a_{i+1}...a_{n-1}])[a_n] &&\text{(induction hypothesis)}\\
&=[a_1...a_i]([a_{i+1}...a_{n-1}][a_n]) &&\text{(associative law)} \\
&=[a_1\cdots a_i][a_{i+1}\cdots a_n] &&\text{(induction hypothesis)}
\end{align}
This completes the proof.


text:
Q: Why does MSAL loginPopup respond with "the application client asked for scope that doesn't exist on the resource"? (Continuation of question: Why is my SPA, which is calling my WebAPI, using Azure Active Directory, receiving "Authorization has been denied for this request."?)
My client SPA is trying to call a protected WebAPI (service). The client uses MSAL (Micosoft Authentication Libraries). The problem happens before calling the API, i.e. in the picture below somewhere between 1 and 2.

Here is the client
<!DOCTYPE html>

    <title>Quickstart for MSAL JS</title>

            <button id="GetTodos" onclick="getTodos()">Get Todos</button>

Both client and service are registered apps on Azure Active Directory

The client has API permissions to access the service.

And the service does expose an API with the scope access_as_user

However the call
myMSALObj.loginPopup(requestObj)

causes
ServerError: "AADSTS650053: The application 'ClientSPA' asked for scope 'access_as_user' that doesn't exist on the resource '00000003-0000-0000-c000-000000000000'.

And when using Chrome I get this message

Further Investigation
Instead of asking for scope "access_as_user", I ask for "user.read"
This gives me an access token. But this causes the WebAPI to respond with
Authorization has been denied for this request

And when I decode the access token I see that the audience is https://graph.microsoft.com. But I am expecting the audience to be "https://my.tenant/TodoListService-NativeDotNet". See picture below (the obfuscated lines do contain information that is specific to my user and my registered app)

Questions

*

*Where does the resource '00000003-0000-0000-c000-000000000000' ID come from (it is mentioned in the error message)? It is not the application ID of the client nor of the service.

*What have I done incorrectly, either in the configuration on Azure Active Directory or in the client?

*Could CORS be a problem? I have setup the service to allow CORS.

A: The scope should include the exposing resource's identifier (the Application ID URI). You can find the full value by going to "Expose an API" -> Edit a Scope -> Copy the label at the top...
var requestObj = {
    // scopes: ["https://graph.microsoft.com/user.read"]
    scopes: ["https://ServiceWebAPI/TodoListService-NativeDotNet-access_as_user"]
};

Further reading on individual scopes here: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#requesting-individual-user-consent


text:
Q: How do I edit the RGBA values of a texture in WebGL? I have a fragment shader like so:
<script id="shader-fs" type="x-shader/x-fragment">
    precision mediump float;
    uniform sampler2D uSampler;
    varying vec2 vTextureCoord;
    void main() {
        gl_FragColor = texture2D(uSampler, vTextureCoord).rgba;
    }
</script>

and here is the JavaScript code that handles textures:
function handleLoadedTexture(texture) {
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.image);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    gl.bindTexture(gl.TEXTURE_2D, null);
}

function initTexture(source) {
    var newTexture = gl.createTexture();
    newTexture.image = new Image();
    objectTextures.push(newTexture);
    var index = objectTextures.length - 1;
    objectTextures[objectTextures.length - 1].image.onload = function() {
        handleLoadedTexture(objectTextures[index])
    }
    objectTextures[objectTextures.length - 1].image.src = source;
}

the "source" parameter is just the url to the image, "example.png" could be a source. I am trying to change the color of the texture to a different one. Is it possible to just reassign every pixel in the texture to a certain color? Is it also possible to tint a texture? Can I add another parameter in the initTexture function called "color" and have that be an array of 4 values (RGBA), or 3 if the alpha channel isn't possible to edit, then use that array somehow to change the color of the texture to one solid color or tint it?
objectTextures is just an array that holds all the WebGLTextures that are created.

A: I recently found out something that might be ideal for what you try to accomplish. You probably know how to create a vertex buffer, like you already do for the positions of your vertices (and probably also for texture coordinates). Add an additional one for colors in your shaders.
add to your vertex shader ( however it looks like ):
attribute vec4 aColors;
varying vec4 vColors;

void main ( void ) {
    vColors = aColors; //basically the same as you do with texture coordinates
}

and your fragment shader now looks like this:
precision mediump float;

uniform sampler2D uSampler;

varying vec4 vColor;
varying vec2 vTextureCoord;
void main() {
    gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;
}

Ok that's how basic per vertex colors are set up. But now comes the slightly unusual part: Instead of going through the business of setting up a buffer and filling it with colors for every vertex, as you'd usually do, you just set it to a constant value for all vertices, basically a "default value" used when no vertexAttribArray is enabled for that location.
var colorLocation = gl.getAttribLocation( yourProgram, "aColors" );
var yourColor = [1,0,1,1];
gl.vertexAttrib4fv( colorLocation, yourColor );

That way you can "tint" either in a constant color or a different color per vertex ( it's not the only way to accomplish coloring stuff, there are like infinite alternatives, but I feel doing it this way is elegant and flexible :)


text:
Q: AFNetworking 2.5.3 Serialization of array to send indexes explicitely I use
AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];

and this sends out the call to the server when having an array in the format:
payments[]
payments[][email]=0&
payments[][category]=&

payments[][email]=1&
payments[][category]=&

I need the indexes for the server like.
payments[]
payments[0][email]=0&
payments[0][category]=&

payments[1][email]=1&
payments[1][category]=&

How can I achieve that?
Thanks.

A: AFHTTPRequestSerializer has a method setQueryStringSerializationWithBlock which allows you to provide your own block for serializing the parameters.
Unfortunately, the internal AF* functions for serialization are private, but you can copy them and make a small modification in these lines to add the indexes.
To set your own serialization block:
[serializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, id parameters, NSError *__autoreleasing *error) {
    return ZAFQueryStringFromParametersWithEncoding(parameters, serializer.stringEncoding);
}];

Including the code, where the AFNetworking functions have been copied and prefixed with a Z to ZAF:
static NSString * const kAFCharactersToBeEscapedInQueryString = @":/?&=;+!@#$()',*";

static NSString * AFPercentEscapedQueryStringKeyFromStringWithEncoding(NSString *string, NSStringEncoding encoding) {
    static NSString * const kAFCharactersToLeaveUnescapedInQueryStringPairKey = @"[].";

    return (__bridge_transfer  NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, (__bridge CFStringRef)kAFCharactersToLeaveUnescapedInQueryStringPairKey, (__bridge CFStringRef)kAFCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding));
}

static NSString * AFPercentEscapedQueryStringValueFromStringWithEncoding(NSString *string, NSStringEncoding encoding) {
    return (__bridge_transfer  NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)kAFCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding));
}

#pragma mark -

@interface ZAFQueryStringPair : NSObject
@property (readwrite, nonatomic, strong) id field;
@property (readwrite, nonatomic, strong) id value;

- (id)initWithField:(id)field value:(id)value;

- (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding;
@end

@implementation ZAFQueryStringPair

- (id)initWithField:(id)field value:(id)value {
    self = [super init];
    if (!self) {
        return nil;
    }

    self.field = field;
    self.value = value;

    return self;
}

- (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding {
    if (!self.value || [self.value isEqual:[NSNull null]]) {
        return AFPercentEscapedQueryStringKeyFromStringWithEncoding([self.field description], stringEncoding);
    } else {
        return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedQueryStringKeyFromStringWithEncoding([self.field description], stringEncoding), AFPercentEscapedQueryStringValueFromStringWithEncoding([self.value description], stringEncoding)];
    }
}

@end

#pragma mark -

static NSArray * ZAFQueryStringPairsFromDictionary(NSDictionary *dictionary);
static NSArray * ZAFQueryStringPairsFromKeyAndValue(NSString *key, id value);

static NSString * ZAFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding stringEncoding) {
    NSMutableArray *mutablePairs = [NSMutableArray array];
    for (ZAFQueryStringPair *pair in ZAFQueryStringPairsFromDictionary(parameters)) {
        [mutablePairs addObject:[pair URLEncodedStringValueWithEncoding:stringEncoding]];
    }

    return [mutablePairs componentsJoinedByString:@"&"];
}

NSArray * ZAFQueryStringPairsFromDictionary(NSDictionary *dictionary) {
    return ZAFQueryStringPairsFromKeyAndValue(nil, dictionary);
}

NSArray * ZAFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
    NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];

    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)];

    if ([value isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dictionary = value;
        // Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries
        for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
            id nestedValue = [dictionary objectForKey:nestedKey];
            if (nestedValue) {
                [mutableQueryStringComponents addObjectsFromArray:ZAFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)];
            }
        }
    } else if ([value isKindOfClass:[NSArray class]]) {
        NSArray *array = value;
        NSInteger idx = 0;
        for (id nestedValue in array) {
            [mutableQueryStringComponents addObjectsFromArray:ZAFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[%ld]", key, idx++], nestedValue)];
        }
    } else if ([value isKindOfClass:[NSSet class]]) {
        NSSet *set = value;
        for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
            [mutableQueryStringComponents addObjectsFromArray:ZAFQueryStringPairsFromKeyAndValue(key, obj)];
        }
    } else {
        [mutableQueryStringComponents addObject:[[ZAFQueryStringPair alloc] initWithField:key value:value]];
    }

    return mutableQueryStringComponents;
}


text:
Q: DialogFlow unable to Update Draft I just tried to update my draft on from the dialog flow site (formerly API.AI), and when I click on "Update Draft", I am getting an error message
"Request contains an invalid argument.
The query pattern 'call $SchemaOrg_Person:given-name' contains an undefined parameter 'given-name'"
This just started showing up today, and I am not sure what it is referencing.  How can I clear this error message and update my draft?

A: So I am not sure how, but a "parameter" was added to one of my intents for "given-name". As I am not using that parameter, I just deleted it.  Curious as to how it was added though.

A: I got the same error when there was a dot after the parameter in one of my utterance.
Just delete the dot after the parameter placeholder in the utterance call @Person:given-name if it presents.
I hope it helps.


text:
Q: Element prototype exceptions (not a function or method) whatever i append to $('click_filter1') it shows the error ... is not a function (for show(), hide(), toggle())
if i insert an alert, the alert gets executed, so the framework is init ok
the element with the id exists for sure
what can be the problem of this? why iam getting this error?
    $('click_filter1').addEvent('click', function() {
        $('click_filter1').show();
    }.bind(this));

A: First of all, your title is misleading and not descriptive enough.
Secondly, toggle, show, hide for Element is only available when you include Element.Shortcuts from MooTools-more - be sure to do that, and the code will work as expected.
Working example: http://www.jsfiddle.net/UjF2y/


text:
Q: jquery ui droppable fires all events on pageload I have two droppable and two draggable elements
On doc ready all the droppable events fire.
After which when dragging an element over the droppable element no droppable events fire
The draggable events seem ok though I have not really tested them, I have been concentrating on the bizarre behaviour of the droppable.
The code:
$(document).ready(function() {

$("#sectionDZ").droppable({
    scope:          "subject",
        activate:   alert("Droppable activate event fired"),
        create:     alert("Droppable create event fired"),
        deactivate: alert("Droppable deactivate event fired"),
        drop:       alert("Droppable drop event fired"),
        out:        alert("Droppable out event fired"),
        over:       alert("Droppable over event fired"),
        accept:     "sectnLI",
            });

$(".sectnLI").draggable({
    cursor:         "crosshair",
    delay:          "300",
    helper:         'clone',
    opacity:        "0.65",
    placeholder:        'ui-state-highlight',
    revert:         "invalid",
    scope:          "subject",
    stop:       function (event, ui) {
        alert("Drag stop event has fired");
//      $(this).draggable("destroy");
        }
    });  //  Allow more than one item to be dragged

$("#judgeDZ").droppable({
        activate:   alert("Droppable 2 activate event fired"),
        create:     alert("Droppable 2 create event fired"),
        deactivate: alert("Droppable 2 deactivate event fired"),
        drop:       alert("Droppable drop event fired"),
        out:        alert("Droppable 2 out event fired"),
        over:       alert("Droppable 2 over event fired"),
        scope:      "judge",
        accept:     "judgLI",
            });

$(".judgLI").draggable({
    cursor:         "crosshair",
    delay:          "300",
    helper:         'clone',
    opacity:        "0.65",
    placeholder:        'ui-state-highlight',
    revert:         "invalid",
    scope:          "subject",
    stop:       function (event, ui) {
        alert("Drag stop event has fired");
//      $(this).draggable("destroy");
        }
    });  //  Allow more than one item to be dragged

});

This is in it's own file, there is another .js file containing ui tabs and dialogs code.
Thanks for any help with this.

A: I solved the problem by deleting the file and rewriting the code into another file with a different name. There must have been a non-printing char somewhere in the file.


text:
Q: How to prevent the changing of integer onreadystatechange I am having an issue with my Ajax. At the moment, I have 5 pairs of elements: the dropdowns (the span tags) and the contents of the dropdowns (the ul tags). On the span tags is an event-listener, for an onclick, where if clicked the drop-downs appear, and when clicked elsewhere, drop-downs disappear. With hardcoded li's the dropdowns work fine. However, I am trying to populate the
s with dynamically generated
s using ajax. However, the Ajax is misbehaving.
On the span I also have another event-listener for onchange which calls the js function calloptions();, which is my Ajax. What I am trying to achieve is, if you select an option, the options in the other drop-downs change based on what you have selected. What i have the function do is onchange, loop from dropdown 0 to dropdown 5 changing the
's based on what the values of the all the selects are.
When I debug, however, my value [k] changes to 5 by the time readyState gets to [4] in the first loop? I'm not sure whether the increase in the value of [k] on loop 1 is as a result of the onreadystatechange or something else entirely that I'm missing. This, therefore, results in the function being unable to overwrite the
values because it is looking for span[5] while there are only 5 of them, which then prints Cannot read property 'parentElement' of undefined (...)
HTML

AJAX
function calloptions() {
var toselect = ["class", "topic", "subtopic", "year", "marks"];
for (var k = 0; k < toselect.length; k++) {

    var filters = document.getElementById("filters");
    var span = filters.getElementsByTagName("span");
    var execute = "select";
    var myclass= span[0].innerHTML;
    var topic =span[1].innerHTML;
    var subtopic = span[2].innerHTML;
    var year = span[3].innerHTML;
    var marks =span[4].innerHTML;

    makeRequest('test.php', toselect[k],  myclass, topic, subtopic, year, marks, execute);

    function makeRequest(url, select, myclass, topic, subtopic, year, marks, execute) {

    httpRequest = new XMLHttpRequest();

    if (!httpRequest) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
    }

    httpRequest.open('POST', url);
    httpRequest.onreadystatechange = alertContents;
    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    httpRequest.send("function="+ execute+ "&toselect="+ select+ "&class=" + encodeURIComponent(myclass) + "&topic=" + encodeURIComponent(topic) + "&subtopic=" + encodeURIComponent(subtopic) + "&year=" + encodeURIComponent(year) + "&marks=" + encodeURIComponent(marks));
    }

    function alertContents() {
        if (this.readyState == 4 && this.status == 200) {
            var response = this.responseText;
            var container = span[k].parentElement || span[k].parentNode ;
            var ul =container.getElementsByTagName("ul")[0];
            ul.innerHTML = response;
        }
    }
}
}

PHP
if(!empty($_POST['function']) && !empty($_POST['toselect']))
{
    $toselect = $_POST['toselect'];
    $_POST['function']($toselect);

}

function select($toselect) {
    global $link;

    $variables = "";

    $select_options = array("class", "topic", "subtopic", "year", "marks");

    $unset_options= array(); $set_options= array(); $set_values= array();

    for ($i=0; $i < count($select_options) ; $i++) {
        if(isset($_POST[$select_options[$i]]) && $_POST[$select_options[$i]] != ''){
            array_push($set_options, $select_options[$i]);
        } else {
            array_push($unset_options, $select_options[$i]);
        }
    }

    for ($i=0; $i < count($set_options) ; $i++) {
        array_push($set_values, $_POST{$set_options[$i]});
    }

    for ($i=0; $i < count($unset_options); $i++) {
        $key = array_search ( $unset_options ,  $select_options);

        unset($select_options[$key]);
    }

    $select_options = array_values($select_options);

    for ($i=0; $i < count($set_options) ; $i++) {
        if ($i<1) {
            $variables .= " $set_options[$i]='$set_values[$i]'";
        } else {
            $variables .= " AND $set_options[$i]='$set_values[$i]'";
        }
    }

    if ($variables != "") {
        $variables = "WHERE" . $variables;
    }

    $sql="SELECT DISTINCT $toselect FROM `questions` $variables";

    $result=mysqli_query($link, $sql);

    $test_array = array();

    $i = 0;

    while ($row =mysqli_fetch_array($result)) {
        $test_array[$i] = "
$row[0]
";
        $i++;
    }

    $test_array = implode("", $test_array);

    echo $test_array;
}

I printed the parameters being submitted to the PHP file at httpRequest.send() and ran them as a $_GET in the file, and it works, so I know it not a problem with the PHP, but rather a failure on my Ajax.
I would appreciate assistance with any simpler algorithm/method to achieve the intended goal, but would appreciate even more, help with eliminating my current errors. I am new to both Ajax and javascript and would, therefore, also greatly appreciate a bit of dumbing down. Thanks!

A: At the moment, I still haven't found out what causes my "over-increasing" [k] values, but from experimentation, separating the for loop and the Ajax works. Like so:
function externalFunction() {

    var toselect = ["class", "topic", "subtopic", "year", "marks"];
    for (var i = 0; i < toselect.length; i++) {
        calloptions(i, toselect[i]);
    }
}

function calloptions(x, toselect) {

    var form = document.getElementById("filters");
    var span = form.getElementsByTagName("span");
    var execute = "select";
    var myclass= span[0].innerHTML;
    var topic =span[1].innerHTML;
    var subtopic = span[2].innerHTML;
    var year = span[3].innerHTML;
    var marks =span[4].innerHTML;

    makeRequest('test.php', toselect,  myclass, topic, subtopic, year, marks, execute);

    function makeRequest(url, toselect, myclass, topic, subtopic, year, marks, execute) {

        httpRequest = new XMLHttpRequest();

        if (!httpRequest) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }

        httpRequest.onreadystatechange = alertContents;
        httpRequest.open('POST', url);
        httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        httpRequest.send("function="+ execute+ "&toselect="+ toselect+ "&class=" + encodeURIComponent(myclass) + "&topic=" + encodeURIComponent(topic) + "&subtopic=" + encodeURIComponent(subtopic) + "&year=" + encodeURIComponent(year) + "&marks=" + encodeURIComponent(marks));
}

    function alertContents() {
        if (this.readyState == 4 && this.status == 200) {
            var response = this.responseText;
            var container = span[x].parentElement || span[x].parentNode ;
            var ul =container.getElementsByTagName("ul")[0];
            ul.innerHTML = response;
    }
}

The search still isn't over though, still trying to figure it out...

A: That increment in the value of k isn't due to some mysterious ajax/scope issue it is in fact due to the for loop. k gets incremented even when
your condition fails Yes! you heard it right and i admit this really weird .When you loop is over k is already equal to 5 note that atm. no response has arrived yet.Since all your callback are in the same function they all refer to same k which have value 5 that's why you see the error
for (var k = 0; k < toselect.length; k++) {
//....
//
}

console.log(k); //5

What can you do?
Well you can simple use k-1 in your callback functions or just use some other variable increment it yourself but that would only remove this error and still would be buggy because when response comes they all will see k as having same value and update same .To solve async. issues we generally use closures try searching on that if you have any doubt you can ask me.


text:
Q: Display lists next to each other without float I am trying to display unordered lists next to each other but can't get it to work even when I use css rules to match the way they display.
Heres my code:

       Main

       Included

TestMessage - text

bla - text

asffadgsd - text

iuygouhlubrsf - text

New Test - text

TestFileName - photo

TestFileName2 - photo

jvv - photo

ujjjjjjjjjjj - photo

MR. Bean - text

And my CSS:
.outterList{
    display: inline ;
}

.innerList{
    display: block;
}

What Im trying to show is somthing like:
        List1(empty list)           List2

                                    *item1

                                    *item2

Anyone knows how to fix this?

A: .outterList{
    display: block;
}

.outterList > li {
    display: inline-block;
    vertical-align: top;
}

Demo: http://jsfiddle.net/Q8qNj/4/


text:
Q: protobuf python can't find include I've noticed a few others having problems, and only solution I saw consisted of CXXFLAGS and LDFLAGS, yet those don't seem to work.
Trying to compile C++ protobuff for alternative Python version I compiled and installed on CentOS with virtualenv and on a user account:
$ cd ~/myApp
$ /opt/python-2.7/bin/virtualenv python
$ source ~/myApp/python/bin/activate
(python)$ cd ~/src/protobuf-2.5.0
(python)$ ./configure --prefix=$HOME/usr
(python)$ make && make install

Up pops a message saying:

Libraries have been installed in:
     /home/myuser/usr/lib
If you ever happen to want to link against installed libraries
  in a given directory, LIBDIR, you must either use libtool, and
  specify the full pathname of the library, or use the -LLIBDIR'
  flag during linking and do at least one of the following:
     - add LIBDIR to theLD_LIBRARY_PATH' environment variable
       during execution
     - add LIBDIR to the LD_RUN_PATH' environment variable
       during linking
     - use the-Wl,-rpath -Wl,LIBDIR' linker flag
     - have your system administrator add LIBDIR to `/etc/ld.so.conf'

Ok, moving on:
(python)$ export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=cpp
(python)$ export CXXFLAGS=-I$HOME/usr/include
(python)$ export LDFLAGS=-L$HOME/usr/lib
(python)$ cd python
(python)$ python setup.py build

And it drops out with:
Using EXPERIMENTAL C++ Implmenetation.
running build
running build_py
running build_ext
building 'google.protobuf.internal._net_proto2___python' extension
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I. -I/opt/python-2.7/include/python2.7 -c google/protobuf/pyext/python_descriptor.cc -o build/temp.linux-x86_64-2.7/google/protobuf/pyext/python_descriptor.o
cc1plus: warning: command line option "-Wstrict-prototypes" is valid for Ada/C/ObjC but not for C++
In file included from google/protobuf/pyext/python_descriptor.cc:36:
./google/protobuf/pyext/python_descriptor.h:39:40: error: google/protobuf/descriptor.h: No such file or directory
google/protobuf/pyext/python_descriptor.cc:37:43: error: google/protobuf/descriptor.pb.h: No such file or directory
In file included from google/protobuf/pyext/python_descriptor.cc:36:
./google/protobuf/pyext/python_descriptor.h:55: error: ISO C++ forbids declaration of 'FieldDescriptor' with no type
./google/protobuf/pyext/python_descriptor.h:55: error: invalid use of '::'
./google/protobuf/pyext/python_descriptor.h:55: error: expected ';' before '*' token
./google/protobuf/pyext/python_descriptor.h:81: error: expected constructor, destructor, or type conversion before '*' token
google/protobuf/pyext/python_descriptor.cc:48: error: expected initializer before '*' token
google/protobuf/pyext/python_descriptor.cc:93: warning: deprecated conversion from string constant to 'char*'
google/protobuf/pyext/python_descriptor.cc:93: warning: deprecated conversion from string constant to 'char*'
google/protobuf/pyext/python_descriptor.cc:93: warning: deprecated conversion from string constant to 'char*'
google/protobuf/pyext/python_descriptor.cc:93: warning: deprecated conversion from string constant to 'char*'
google/protobuf/pyext/python_descriptor.cc:93: warning: deprecated conversion from string constant to 'char*'
google/protobuf/pyext/python_descriptor.cc:152: error: ISO C++ forbids declaration of 'DescriptorPool' with no type
google/protobuf/pyext/python_descriptor.cc:152: error: invalid use of '::'
google/protobuf/pyext/python_descriptor.cc:152: error: expected ';' before '*' token
google/protobuf/pyext/python_descriptor.cc:158: error: expected unqualified-id before '*' token
google/protobuf/pyext/python_descriptor.cc:158: error: expected ')' before '*' token
google/protobuf/pyext/python_descriptor.cc:158: error: expected initializer before '*' token
google/protobuf/pyext/python_descriptor.cc:337: error: expected '}' at end of input
google/protobuf/pyext/python_descriptor.cc:337: error: expected '}' at end of input
google/protobuf/pyext/python_descriptor.cc:337: error: expected '}' at end of input
google/protobuf/pyext/python_descriptor.cc:155: warning: 'void google::protobuf::python::CDescriptorPoolDealloc(google::protobuf::python::CDescriptorPool*)' declared 'static' but never defined
error: command 'gcc' failed with exit status 1

A: It would appear that setuptools is not paying attention to the CXXFLAGS environment variable -- you can see that your CXXFLAGS is not appearing in the gcc command line. It looks like it may not even be aware that it's compiling C++, considering that it's using gcc and not g++. Try using CFLAGS instead.


text:
Q: Is It a bug that Visual Studio marks it as an error but when it runs it works completely fine? Im Currently Testing around with Blazor and noticed this weird behaviour and wanted to know if its a know bug or even intentional.
Its pretty normal that visual studio marks something as an error but after building the error is gone but in this case the error stays. I got this code at the beginning:
<p>@Test2</p>
@code {
    [Parameter]
    public string Test1 { get; set; }
    [Parameter]
    public string Test2 { get; set; }
}

and use it like
<TestComponent Test1="@test1" Test2="@test2"/>
@code {
    string test1 = "abc";
    string test2 = "cba";
}

but now if i change the type of test1 or 2 it breaks. lets say i change it to int in the Component and the call like this:
    [Parameter]
    public int Test2 { get; set; }

and
int test2 = 2;

Now the error is there and i haven't found a way to get rid of it. It just says on the bind of Test2

CS1503: Argument 1: cannot convert from 'int' to 'string'

Is there any reason why Visual studio should behave like this or is it just simply a bug?
if it is, where would i file a report?


text:
Q: How distribute repeated value in an array? I'm looking to distribute all repeated value in an array. (I don't know what name is appropriate to describe that).
I will explain you with an example.
I have an array with duplicated values :
IN :
['foo', 'foo', 'bar', 'bar', 'bli', 'bli']

I would like an array with all values distributed. Have a maximum of field/space between 2 repetition of a value.
OUT :
['foo', 'bar', 'bli', 'foo', 'bar', 'bli']

If you prefer with an array containing number could also be good for me :
IN :
[1, 1, 2, 3, 2, 3]

OUT :
[1, 2, 3, 1, 2, 3]

In the worse scenario I can have several uniq value with several duplicated value X time.
If someone have an algorithm name or an implementation to do that (Python would be perfect :p)
Thanks,
Gaël

A: try this:
from collections import Counter
lst = ['foo', 'foo', 'bar', 'bar', 'bli', 'bli']
x = Counter(lst)
max = max(Counter(lst).values())
result_lst = []
for i in range(max):
    for key in x.keys():
        if x[key]:
            result_lst.append(key)
            x[key] -= 1

print result_lst


text:
Q: Why doesn't FFT automatically produce a zero-frequency centered output? There is an operation called Shift which is performed after DFT to bring zero-frequency components to the center of the frequency spectrum.
I have two questions regarding this operation:

*

*Why don't/can't DFT automatically center the zero-frequency components?

*What happens if we don't perform Shift operation after DFT? I.e. how does it affect our other tasks of image processing?

*Can anyone provide me some material to know about this specific operation named Shift?

References:
 - fftw shift zero-frequency to the image center
 - Why we shift the zero-frequency component to the center of the spectrum?

A: The DFT, by definition, uses n=0..N-1 and k=0..N-1, where n is the index into the time-domain signal and k the index into the frequency-domain signal. k also corresponds to the frequency. The DFT is defined this way in analogy to Fourier series.
Since the frequency in the DFT is periodic, one can think of k=N-1 to correspond to k=-1 instead. The shift function thus moves the upper half of the frequencies to the left of the origin, so they can be more readily interpreted as negative frequencies. But this is solely a convenience for display, as it brings the frequency-domain signal to a form that we're more familiar with (this is probably because it makes some Fourier analysis easier to explain, and hence text books display it this way, and hence we learn about Fourier by looking at Frequency plots with the origin in the middle).
For most tasks in image processing, we do not need to shift the origin. Again, it is only for display that this is convenient and pretty.
For example, to compute cross-correlation:
cc = ifft( fft(img1) * conj(fft(img2)) )

Here, the top-left pixel of cc is the origin. If img1==img2, the top-left pixel will be the maximum value. If we had an fft function that shifted the origin to the middle, then the cross-correlation image cc would have its origin in the middle also. After finding the peak, we'd need to do some computations to figure out what the shift between img1 and img2 is. (Not that this is complicated, but it shows that shifting is not necessarily advantageous.)
When convolving, one often has a spatial-domain kernel with the origin in the middle (as for example in this recent question). In this case, one must shift the origin to the top-left before computing the DFT. But there is no point in shifting the origin of the frequency-domain signals just to multiply them together and then undo the shift. One can simply directly multiply the signals that have the origin in the top-left corner:
kernel = ifftshift(kernel)
filtered = ifft( fft(img) * fft(kernel) )

Note that there are two different shift functions, often called fftshift and ifftshift. The one shifts the origin from the top-left to the middle, the other shifts the origin from the middle to the top-left. These two functions do exactly the same thing for even-sized signals (images), but differ if the sizes are odd.


text:
Q: Having a problem with my Pubspec.yaml file I do not understand why this error is coming up. all seems well.[![enter image description here][1]][1]
Error detected in pubspec.yaml:
Error on line 61, column 4: Expected a key while parsing a block mapping.
   ╷
61 │    assets:
   │    ^
   ╵
Please correct the pubspec.yaml file at C:\Users\VICTOR\flutter apps\awsome_app\pubspec.yaml
exit code 1[![enter image description here][3]][3]```

  [1]: https://i.stack.imgur.com/qUxuG.png

A: The YAML format used in pubspec.yaml cares about indentation. Your assets: declaration has an extra space behind it. Remove that extra space. And make sure the - assets\ is also indented properly.
The lines in VSCode will help you align them properly.

A: the pubspec.yaml is a position based script.  The vertical lines in visual studio code will tell you the alignment and indentation requirements.  The editor is letting you know that the directive is out of position


text:
Q: How to redirect with form validation in javascript to PHP webpage with MySQL query to another page I have made a form which has validation technique using javascript
 (register.php), location.href="storedata.php" to redirect to page
 which has MySQL query in , from there I want to redirect to another
 page (successful.php).
Simplified Code is like this:
register.php
   <script type="text/javascript">
    function formValidate(){
    //FORM VALIDATION
    }
   location.href="storedata.php";
    </script>
    <body>
    <form name="register" onsubmit="return formValidate()" method="post">
    //Form Values
    </form>
    </body>

storedata.php
    <?php
    $con=mysqli_connect("localhost","root","root","UserPassDB");
    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

    mysqli_query($con,"INSERT INTO Users (UserName, Email, Password, Gender)
    VALUES ('$_POST[duser]', '$_POST[demail]','$_POST[dpwd]',$_POST[gender] )");

    mysqli_close($con);

    header("Location: successful.php");
    exit();

    ?>

successful.php
<?php echo "Congratulations!!! you have been registered"; ?>

Earlier It was going good but after inserting 1 or 2 values to database, it just empties all fields of form. Can someone please tell me where I am wrong.
OR you can suggests any other way to redirecting to pages like this.

A: you have redirected your "register.php" page to "storedata.php", which is not correct, you need to submit your "register.php" page to "storedata.php", for that remove this line from your code
location.href="storedata.php";

after this give action to your form tag as "storedata.php" i.e.
<form name="register" onsubmit="return formValidate()" method="post" action="storedata.php">


text:
Q: Can't sort by date correctly Instead ordering by day, is ordering by month.
I've tried str_to_date but doesn't have in spark sql, and tried to repeat date_format in order by with no success

A: As you're formatting the date as strings, sort is done by string order. One solution is to change the format so that year comes first, then month, then day. A better way is to order by the Date column (ttr.created_at) and not the formatted string.

A: try the below code
import org.apache.spark.sql.functions._

spark.sql("""
  SELECT TO_DATE(CAST(UNIX_TIMESTAMP(ttr.created_at, 'dd/MM/yyyy') AS TIMESTAMP)) AS data from dl_wallet.tb_transaction as ttr order by data desc """
).show()


text:
Q: Scrolling Title In UIViewController I need a little help, I'm not sure how to approach this problem:
I have UIViewController class with UIScrollView. UIScrollView is used for horizontal scrolling (paging) of UITableViewControllers.
I would like to create effect like the Twitter app for iOS7 so that when the user swipe left or right, and the new controller is loaded, the title on the UINavigationBar changes.
When changing, title does not only appear but it looks like it's on the scrollview itself.

A: use titleView property of UIViewController to give your own custom view, and do animations on it using animateWithDuration Block.

A: You can use this control (which I've used and found great) you can add it as a subView on your UINavigationBar https://github.com/cbpowell/MarqueeLabel


text:
Q: Ionic 3 sqlite export and import database I have created an app with ionic 3. I have used sqlite for database. I want to export database to a folder (outside of my app) and want to see all my back up database file in a list. Then I will choose any backup file and import to my database with file chooser.
Please help me.
Thanks in advance.

A: You can simply create a text file and store JSON encoded data inside it and later decode the data to store it back in the database.
Use Ionic Native File plugin for reading, creating and writing a file: https://ionicframework.com/docs/native/file/

*

*Create an empty directory in external storage.

*For taking a backup, Create a new text file and write your database table schema and rows in JSON format.

*To list previous backups, request native file plugin to return all files inside your previously created folder.

*To import a backup, first export current instance of database( Just for saving latest data). Then you can decode the JSON data inside your backup file and make insert queries for each row.


text:
Q: Best option for DirectX with a modern Windows UI I have been doing so research lately for a new project and have ended up more confused than before I started.  I know similar questions have been done to death but I can't seem to find any good information on what I need to do.  I'm hoping somebody here will be able to offer some advice.
I need to embed DirectX into a .NET application with a modern Windows UI (toolbars, menus, ribbon if possible).  I have prototyped the DirectX part of the application in XNA for proof of concept but I do not need to stick with it, re-writing isn't a problem.  It would be nice to take advantage of the UI goodness from WPF but anything in .NET would be an option (WinForms etc).
The application does not do anything hugely complex:
- It loads of a bitmap image into a texture (or a few textures as the image is often quite large)
- Renders to off screen target (applying a pixel shader based on another texture) and gets the result back as a texture
- Renders to the window with another pixel shader applied
- Pan and zoom of resulting image

The problem is that all my research on-line discounts options but does not suggest an alternative.  For example I have read that:
- Managed DirectX in .NET is now unsupported
- Embedded my XNA application in Winforms or WPF isn't recommended
- WPF supports pixel shaders but doesn't seem to get much love for performance

What is the standard for embedding DirectX into modern Windows applications (if one even exists)?  We can't be the only people wanting to do this in .NET.
What would people recommend?

A: There's two libraries which would be of help:

*

*http://www.slimdx.org/

*http://sharpdx.org/
Both are pretty complete, there's also some samples with WPF interop.


text:
Q: CreateService or StartService hangs on windows 7 x64 CreateService or StartService hangs on windows 7 x64 when i trying to use it to register new service from service.
In service control manager my service, which i try to run, has status 'Starting'.
Code that try to create and run service:
SC_HANDLE hSCManager = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if(!hSCManager)
    throw ::GetLastError();
SC_HANDLE hService = ::OpenService(hSCManager,
                                       TEXT("ProcessManager"),
                                       SERVICE_ALL_ACCESS);

if(!hService && ::GetLastError() == ERROR_SERVICE_DOES_NOT_EXIST)
{
    hService = ::CreateService(hSCManager, TEXT("ProcessManager"),
        TEXT("ProcessManager"), SERVICE_ALL_ACCESS, SERVICE_KERNEL_DRIVER,
        SERVICE_DEMAND_START, SERVICE_ERROR_IGNORE, TEXT("C:\\processmanager.sys"),
        NULL, NULL, NULL, NULL, NULL);
}

if(!hService ||
    (!::StartService(hService, 0, NULL) && ::GetLastError() != ERROR_SERVICE_ALREADY_RUNNING))
{
    ::CloseServiceHandle(hSCManager);
    if(hService)
        ::CloseServiceHandle(hService);
    DWORD err = ::GetLastError();
    throw err;
}

Please help :)

A: From the documentation for ServiceMain:

Do not attempt to start another service in the ServiceMain function.

and

The SCM locks the service control database during initialization, so if a service attempts to call StartService during initialization, the call will block. When the service reports to the SCM that it has successfully started, it can call StartService. If the service requires another service to be running, the service should set the required dependencies.

So, there's your problem: your program is deadlocking because it is calling StartService while the service control database is locked.  (Actually, it is probably deadlocking on the CreateService call first; the documentation doesn't explicitly mention it, but the same restriction applies there too.)
Install the device driver at the same time that you install your service, rather than trying to install it from your service.


text: Q: Sending Emails on localhost for Magento 2.2.5 I am trying to test some email sending from my localhost. I'd like to use an external SMTP server for this matter. I am using Cent OS 6.I can't find the useful topics related for this? Could anyone explain this to me?


text:
Q: Strange behavior with std::nth_element I'm trying to find the median of vectors of (x,y) points using nth_element
        cv::Point2f medOffset;
        vector<float> tempOffsetsX = offsetsX;
        int medLoc = tempOffsetsX.size()/2;
        nth_element(tempOffsetsX.begin(), tempOffsetsX.begin()+medLoc, tempOffsetsX.end());
//      sort(tempOffsetsX.begin(), tempOffsetsX.end());
        medOffset.x = tempOffsetsX[medLoc];

        vector<float> tempOffsetsY = offsetsY;
****** debug out line 1 *********
        nth_element(tempOffsetsY.begin(), tempOffsetsY.begin()+medLoc, tempOffsetsY.end());
//      sort(tempOffsetsY.begin(), tempOffsetsY.end());
        medOffset.y = tempOffsetsY[medLoc];
****** debug out line 2 *********

tempOffsetsX is working just fine but, occasionally, tempOffsetsY is giving very strange results after nth_element. Here is sample output at the marked debug lines
tempOffsetsY1:    5.184135        -1.564125       3.751759                0.221855                -0.742348       1.737648
tempOffsetsY2:    -0.742348       -1.564125       -8885092352.000000      -8850636800.000000      0.000000        0.000000

The results are pretty repeatable until I recompile, at which point the specifics change the the general problem remains. Clearly the vector is getting corrupted somehow but I can't think of how.
Also, if I use sort instead of nth_element it works without problem. For debugging, I tried doing a sort and then nth_element which worked just fine. So somehow the reordering that happens inside nth_element is getting messed up but I can't think of how.
Any ideas how this is happening?
edit - More info about my environment. I'm running Arch Linux. I just did a system update. I should note that this same code did work without problem before the update, and this is the first time I've ran it after the update. But that's a gap of several days and I'm always hesitant to point at system libraries for what is usually my own problem.
[]$ uname -r
3.11.6-1-ARCH

[]$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-unknown-linux-gnu/4.8.2/lto-wrapper
Target: x86_64-unknown-linux-gnu
Configured with: /build/gcc/src/gcc-4.8.2/configure --prefix=/usr --libdir=/usr/lib --libexecdir=/usr/lib --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=https://bugs.archlinux.org/ --enable-languages=c,c++,ada,fortran,go,lto,objc,obj-c++ --enable-shared --enable-threads=posix --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-clocale=gnu --disable-libstdcxx-pch --enable-gnu-unique-object --enable-linker-build-id --enable-cloog-backend=isl --disable-cloog-version-check --enable-lto --enable-gold --enable-ld=default --enable-plugin --with-plugin-ld=ld.gold --with-linker-hash-style=gnu --disable-install-libiberty --disable-multilib --disable-libssp --disable-werror --enable-checking=release
Thread model: posix
gcc version 4.8.2 (GCC)

[]$ pacman -Qi glibc
Name           : glibc
Version        : 2.18-8
....

A: Quite likely you're running into a recent bug in libstdc++, which broke the nth_element function. This has since been fixed, but some Linux releases shipped with the broken version (e.g. Ubuntu 13.10)
A patch and discussion of the bug can be found on the GCC tracker: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=58800


text:
Q: How to convert factor to numeric? I'm analyzing data to University, and i dont know how to convert factor like: 58.4 [57.4-60.3]to numeric
I did :
data$male <- as.character(data$male)
data$male <- as.numeric(data$male)

but it doesnt work.
Warning message:
NAs introduced by coercion
Could you help me with this problem ?

A: We can match one or more whitespace (\\s+) followed by other characters to the end and replace it with "" in sub and then convert to numeric
data$male <- as.numeric(sub("\\s+.*", "", data$male))


text:
Q: removing all words in a sentences with a specific symbol I am trying to remove all the words in a sentence which starts with the symbol $# ,
for example if there is a sentence I am $#trying to $#learn $regex for $#javascript
I would want to remove the words trying , learn and javascript.. IS it possible to acheive through javascript regex??

A: var sentence = "I am $#trying to $#learn $regex for $#javascript";
sentence = sentence.replace(/\$#[^\s]+/g, '');
// output: "I am  to  $regex for "

A: It's necessary to trim string and duplicates of spaces in addition:
sentence = sentence
  .replace(/\s*\$#[^\s]+\s*/g, ' ')
  .replace(/^\s+|\s+$/g, '')
;
// output: "I am to $regex for"


text:
Q: Commands that could include another command I am writing a novel using TeX. I need to indent lines of dialogue by 0.25in from the left margin and by 1in from the right margin. I have thought of using a minipage to accomplish this as the dialogue would need to extend over a number of lines of text. The alternative is to use the command \quotation.
However, I need to use this command frequently and, I am looking for an easy way to accomplish this. Could the minipage command be placed inside a global command? Or \quotation for that matter?
It would be nice to be able to write something like \d in the code instead of having to write out a lengthy command structure each time I need to include dialogue.
I would appreciate any help/advice!
Mike

A:
I need to indent lines of dialogue by 0.25in from the left margin and by 1in from the right margin

This sounds like a job for KOMA-Script's addmargin environment (which is available in other classes through the scrextend package). The environment is a list internally similar to the quotation environment. It allows setting a custom indentation from both sides with it's mandatory argument. With an optional argument a different value can be chosen for the indentation from the left:
\begin{addmargin}[<left indent>]{<indent>}

This can easily be wrapped in a custom command
\newcommand\dialogue[1]{%
  \begin{addmargin}[.25in]{1in}
  #1%
  \end{addmargin}%
}

or a custom environment:
\newenvironment{dialogue}
  {\addmargin[.25in]{1in}}
  {\endaddmargin}

An example:
\documentclass{article}

\usepackage{scrextend}% not needed with a KOMA-Script class
\newenvironment{dialogue}
  {\addmargin[.25in]{1in}}
  {\endaddmargin}

\usepackage{lipsum}% dummy text

\begin{document}

\lipsum[1]

\begin{dialogue}
  \lipsum[2]
\end{dialogue}

\lipsum[3]

\begin{dialogue}
  \lipsum[4]
\end{dialogue}

\lipsum[5]

\end{document}

A: I propose another solution, that uses the enumitem package. More precisely two variants, not knowing if you dialogs begin with a dash or simply use quotes. I'm against commands in such cases because the argument of such a command can be rather lengthy, and it's so easy to forget a closing brace. Instead I propose shortcuts for entering and leaving the environment. Note that the different "parts" of a dialog are introduced by \item (or an alias).
Here is a 'real' example (from Edward Lear):
\documentclass{book}
\usepackage[utf8]{inputenc}
\usepackage{ebgaramond}
\usepackage{enumitem}
\newlist{dialogdash}{description}{1}
\setlist[dialogdash]{labelindent = 0.25in, leftmargin = \labelindent, labelsep = 0.2em, rightmargin = 1in, nosep,topsep = 0.5ex, itemsep = 0.5ex, align = left}
\newenvironment{dlgdash}{\begin{dialogdash}\item[---]}{\end{dialogdash}}

\newlist{dialognodash}{itemize}{1}
\setlist[dialognodash]{label = ,labelindent = 0.25in, leftmargin = \labelindent, rightmargin = 1in, nosep, topsep = 0.5ex, itemsep = 0.5ex, align = left}
\newenvironment{dlgnodash}{\begin{dialognodash}\item }{\end{dialognodash}}

\def\bdlg{\begin{dlgnodash}}
\def\edlg{\end{dlgnodash}}

\parindent=0pt

\begin{document}

The Four Children then entered into conversation with the Blue Bottle-Flies, who discoursed in a placid and genteel manner, though with a slightly buzzing accent, chiefly owing to the fact that they each held a small clothes-brush between their teeth which naturally occasioned a fizzy extraneous utterance.

\begin{dlgdash}
Why, said Violet, would you kindly inform us, do you reside in bottles? and if in bottles at all, why not rather in green or purple, or indeed in yellow bottles?
\end{dlgdash}

 To which questions a very aged Blue-Bottle-Fly answered,

  \bdlg
'We found the bottles here all ready to live in, that is to say, our great-great-great-great-great-grandfathers did, so we occupied them at once. And when the winter comes on, we turn the bottles upside down, and consequently rarely feel the cold at all, and you know very well that this could not be the case with bottles of any other colour than blue.'

\item 'Of course it could not;' said Slingsby, 'but if we may take the liberty of inquiring, on what do you chiefly subsist?'

\item 'Mainly on Oyster-patties,' said the Blue-Bottle-Fly, 'and, when these are scarce, on Raspberry vinegar and Russian leather boiled down to a jelly.'

\item 'How delicious!' said Guy.
\edlg

\end{document}

A: Like the KOMA-related answer, there's a memoir-related answer:
\documentclass[12]{article}
\usepackage[showframe]{geometry}% to visualize output
\usepackage[T1]{fontenc}
\usepackage{lipsum}
\usepackage[strict]{changepage}% <-- or use the memoir class
\newenvironment{dial}
  {\begin{adjustwidth}{0.25in}{1in}
   % other commands?
   \small
   \parindent 0pt%
   \parskip   3pt%
    }
  {\end{adjustwidth}}

\begin{document}

\lipsum[1]

\begin{dial}
\lipsum[2-4]
\end{dial}

\lipsum[5]

\end{document}


text:
Q: What does the Ctrl-Alt-+ shortcut do? Simple question. I was about to assign the Ctrl+Alt++ keyboard shortcut to increase the volume, but I then realized it was already assigned for something. If I press this key combination the screen flashes black for a second, and then comes back. Pressing Ctrl+Alt+- produces similar behavior. So I'm curious, what's this shortcut supposed to do?

A: Ctrl + Alt + F1 through F12 are mapped for switching between virtual consoles. Your graphical display is usually mapped to vt7 or vt8, so F7 or F8.
Ctrl + Alt + BkSp aborts your graphical server and kills all graphical processes.
Ctrl + Alt + - and + switch to a smaller or higher screen resolution, respectively.
Ctrl + Alt + Esc runs xkill by default. The next window you click is killed.
There are several others, but I can't recall them.

If you want to map +/- to something, I'd suggest using the Windows key as a modifier, if you have one. It's treated as a "Super" Meta-key, and doesn't normally have any mappings at all.


text:
Q: Infinite group for which it is still unknown if it is simple Is there an example of an infinite group for which it is still unknown whether or not it is simple?
Is there a criterion for determining the simplicity of infinite groups?

A: Below I will present an example of a finitely presented group which is conjecturally simple. Thank you for the opportunity to communicate this example to a wider community.

Consider the group
$$\Gamma=\langle s,t,u \mid s^7=t^7=u^7=1, u=s^3t^3, u^3=st \rangle. $$
Then $\Gamma$ itself is not simple: it has a non-trivial homomorphism to $\mathbb{Z}/7\mathbb{Z}$, defined by $s\mapsto 1$, $t\mapsto -1$, $u\mapsto 0$.
However, the kernel $\Gamma_0$ of this homomorphism, is conjecturally simple.
Clearly, $\Gamma_0$ is finitely presented, as it is of finite index in $\Gamma$.
Much is known about the groups $\Gamma$ and $\Gamma_0$. For example:

*

*These groups are infinite groups and they have Kazhdan's property (T).

*Every nontrivial normal subgroup in either group is of finite index.

*These groups are non-linear over any field.

These groups act cocompactly on an exotic $\tilde{A}_2$-building of thickness 3, so they are somehow related to the Fano plane, the projective plane over the field with two elements, which hints about the role of the power 3 and 7 in the presentation of $\Gamma$.
The group $\Gamma$ is briefly discussed in section 10.4 here.
It is closely related to the group
$$\langle s,t,u \mid s^7=t^7=u^7=1, u=st, u^3=s^3t^3 \rangle $$
which happens to be an index 3 subgroup of an arithmetic lattice in $\mathrm{SL}_3(\mathbb{F}_2(\!(x)\!))$, thus residually finite.

The above example is in fact a part of the infinite family of groups acting cocompactly on affine buildings. It is conjectured that if the corresponding building is not a Bruhat-Tits building then the acting group contains a simple subgroup of finite index.


text:
Q: Tkinter organizing issues fixed resolution These 3 lines:
Clockframe = Frame(root, height=520, width=960)
Tempframe = Frame(root, height=520, width=960)
Bottomframe = Frame(root, height=520, width=1920)

Combined with these 3 lines:
Clockframe.grid(row=0, column=0)
Tempframe.grid(row=0, column=1)
Bottomframe.grid(row=1, columnspan=1)

gives me the following result:

My goal is:

A: columnspan=1 means that the Bottomframe spans a single column. Since this aligns Bottomframe with the Clockframe in the first column, the first column is expanded to width 1920. This pushes the second column past the 1920th pixel and (possibly) off the screen. You can confirm this by reducing the widths of Bottomframe -- you'll see Tempframe creeping into view.
So change columnspan=1 to columnspan=2 to make the Bottomframe span the first two columns. For example,
import tkinter as tk
root = tk.Tk()
Clockframe = tk.Frame(root, height=520, width=960, background='aqua')
Tempframe = tk.Frame(root, height=520, width=960, background='green')
Bottomframe = tk.Frame(root, height=520, width=1920, background='yellow')

Clockframe.grid(row=0, column=0)
Tempframe.grid(row=0, column=1)
Bottomframe.grid(row=1, columnspan=2)

root.mainloop()


text:
Q: JQuery fade in/out I have a set of divs that fade out and fade in when their respective menulink is clicked. The first div should load automatically on pageload without any fades, and if no content is loaded there should only be a fade in effect.
Now I'm getting all of this done except for the instant load of the first div. When I load the page, no content is present, a fade out occurs and then the first div automatically fades in.
How can I make sure the first div I have automatically loads without any fades?
Current code:
$(document).ready(function () {
  $('a').bind("click", function () {
    $('a').removeClass("actief");
    $(this).addClass("actief");
    var fade = $(this);

    if ($('#content').html()) {
      $(this).addClass("actief");
      $('#content').stop().fadeTo(500, 0, function () {
        $('#content').html("").css('opacity', 0);
        fade.next().clone().appendTo('#content');
        $('#content').stop().fadeTo(500, 1);
      });
    } else {
      $('#content').css('opacity', 0);
      fade.next().clone().appendTo('#content');
      $('#content').stop().fadeTo(500, 1);
    }
  });

  $('a:first').trigger('click');
});

HTML:
This is the html

                    About

About

                    Knowledge

Knowledge

                    Expectations

Expectations

                    More

More

CSS
*{
    margin:0px;
    padding:0px;
}

#container{
    width:800px;
    height:600px;
    margin:auto;
    background-color:#6CF;
}

#menudiv{
    width:800px;
    background-color:#066;
    height:50px;
    float:left;
    margin-top:20px;
    border-bottom:2px solid orange;
}

#content{
    width:800px;
    background-color:#069;
    height:400px;
    float:left;
}

#content p{
    font-family:Arial, Helvetica, sans-serif;
    font-size:14px;
    color:white;
    padding:10px;
}

#content img{
    border: 2px solid white;
    margin-left:10px;
    float:left;
    margin-right:10px;
}

H1{
    font-family:Arial, Helvetica, sans-serif;
    font-size:16px;
    color:white;
    padding:10px;
}

ul li{
    list-style-type:none;
    float:left;
    margin:10px;
    background-color:black;
    color:white;
    border:2px solid white;
    padding:4px;
}

ul li div{
    display:none;
    text-decoration:line-through;
}

ul li .actief{
    color:orange;
}

#menu ul li div{display:none}
#menu ul li:first-child div{display:block}

A: You can do this via CSS,
#menu ul li div{display:none}
#menu ul li:first-child div{display:block}

then it will reset on page load
(you might want to make your CSS a bit more specific though)
Update I:
Oops, didnt spot the .clone() bit, instead of the .trigger("click"), you can use this...
$('a:first').next().clone().appendTo('#content');
This will copy the first div into the page body as you describe
Update II:
To keep the .trigger() you could detect if the .click is triggered by a real click (see here) then bypass the .fade effect in your click function (or there are probably 101 other ways to do it!)


text:
Q: Can I combine a list of tokenized strings to a dataframe in R? I did search, and found several similar questions, but I'm still not understanding this correctly.
I have a dataframe with columns ID, Date, and Text.
df <- data.frame(ID = c('1','2','1'),
               date = c('11/12', '11/13', '11/14'),
               text = c('wow amazing', 'test string', 'thank you wow'))
df$text <- as.character(df$text)

I then tokenize the text, creating a list of words of each row
tokenList <- tokenize_words(df$text)

The end goal is to sum up the occurences or types of words for each unique ID.
Example: ID 1 would have a count sum of 2 for the word 'wow', and a sum of 1 for 'amazing'.
I'm thinking I could do this if I could append or insert this tokenized list into my original dataframe, which has valuable info such as ID and Date.
Or am I thinking of this the totally wrong way?
I see other methods of unnesting the tokenization, meaning each row would contain a single word, and the ID/Date data would be repeated each row for each word.
Any help is appreciated, thank you!

A: One way of handling this task is to use the tidytext and dplyr packages. You split the words with unnest_tokens() then you count how many times each word appeared for each ID using count().
library(dplyr)
library(tidytext)

unnest_tokens(df, input = text, output = word) %>%
count(ID, word, name = "frequency")

#  ID    word    frequency
#  <chr> <chr>       <int>
#1 1     amazing         1
#2 1     thank           1
#3 1     wow             2
#4 1     you             1
#5 2     string          1
#6 2     test            1

A: Here is a base R solution for counting the occurrence of tokens
# set ID as names to values in tokenList
r <- unlist(lapply(seq(x<-`names<-`(tokenList,df$ID)),
                   function(k) x[[k]] <- setNames(x[[k]],rep(names(x[k]),length(x[[k]])))))

# form the initial output data frame
dfout <- data.frame(id = names(r), word = r, cnt = 1)

# sum up occurrence of tokens
dfout <- aggregate(dfout[3], dfout[-3],FUN = sum)

such that
> dfout
  id    word cnt
1  1 amazing   1
2  2  string   1
3  2    test   1
4  1   thank   1
5  1     wow   2
6  1     you   1

Or you can change the last line by dfout <- unique(within(dfout, cnt <- ave(cnt,word,FUN = sum))), such that
> dfout
  id    word cnt
1  1     wow   2
2  1 amazing   1
3  2    test   1
4  2  string   1
5  1   thank   1
6  1     you   1


text:
Q: Uncaught Exception Error PHP Fatal error: Uncaught exception 'Exception' with message '
Error: The following fields have not been filled out- Last Name
' in /vagrant/web/Assignment4/Person.php on line 9
I am trying to check a form to make sure that all of the fields are filled in. If any of them are empty, I want to throw an error that says which fields are empty. I am having a hard time understanding how catching exceptions work, so could anyone tell me how they would fix this?
Person.php
 public function insert()
{

  //Storing required $_POST array fields in variable for isset function

   $expectedValues = array(
       "firstName"   => "First Name",
       "lastName"    => "Last Name",
       "title"       => "Title",
       "office"      => "Office",
       "phoneNumber" => "Phone Number",
       "email"       => "Email",
       );

   //Checking to see if all fields are filled in

    foreach ($expectedValues as $field => $humanName) {
       if (empty($_POST[$field])) {
        $errorArray[] = $humanName;
         foreach($errorArray as $print){
            throw new Exception("
" . "Error: The following fields have not been filled out- " . $print . "
");
         }

         try{
             (count($errorArray) = 0);
         }
         catch(Exception $e){
             echo "
" . $e->getMessage() . "
";
         }
       }
     }

       //If they are, insert them into the Perosn table

               $insert = $this-> doQuery("INSERT INTO Person
                                         VALUES(
                                        '$_POST[firstName]',
                                        '$_POST[lastName]',
                                        '$_POST[title]',
                                        '$_POST[office]',
                                        '$_POST[phoneNumber]',
                                        '$_POST[email]')");

                                  $insert;

         //If insert query is successful, return true
            if ($insert === true){
                return true;
                echo "Congragulations! You now work for Assignment 4 Incorporated";
            }

         //If not, throw an exception

            //else{
              //  throw new Exception
               // ("
" . "Error: Query was unsuccessful:"
               // . " " . $this->error . "
");
               // }

   }

A: If you want to display errors to user then throwing exceptions is wrong way, try this:
foreach ($expectedValues as $field => $humanName) {
   if (empty($_POST[$field])) {
       $errorArray[] = $humanName;
   }
 }
 if (count($errorArray) > 0) {
      echo 'Following fields are empty: '.implode(' ', $errorArray);
 }

Also for the fun, check out HTML5 property required:
<input type="text" required="required" value="" />