text:
Q: XPath group selected node with next sibling I use "net.sf.saxon" % "Saxon-HE" % "9.9.1-6" and i'm trying to group some nodes of a HTML Site with XPath.
HTML Page

Item 1

nested stuff for Item 1

Item 2

nested stuff for Item 2

Item 3

nested stuff for Item 3

Expected result (array)
 1.

Item 1

nested stuff for Item 1

 2.

Item 2

nested stuff for Item 2

 3.

Item 3

nested stuff for Item 3

This is one of my tries/attempts.
//div[contains(@class, 'item-list')]/div[contains(@class, 'row-body') or contains(@class, 'row-title')]

But the result (see below) ist not as expected.
(I need the results e.g. 1. and 2. together.)
1.

Item 1

2.

nested stuff for Item 1

3.

Item 2

4.

nested stuff for Item 2

5.

Item 3

6.

nested stuff for Item 3

I also tried something with "following-sibling", but unfortunately without success.


text:
Q: User fields empty in parse-server server.js mail adapter I use parse-server-amazon-ses-email-adapter and would like to know how to localize the verification email and reset password email.
My clue is to check user's fields and then assign the correct template on server.js or AmazonSESAdapter.js. The problem is that user properties are empty, besides email, username.
For instance, at the example below, firstName is undefined.
Thanks.
emailAdapter: {
      module: 'parse-server-amazon-ses-email-adapter',
      options: {
        // The address that your emails come from
        fromAddress: 'Iron rr',
        accessKeyId: 'gg',
        secretAccessKey: 'gg',
        region: 'eu-west-1',
        // The template section
        templates: {
          passwordResetEmail: {
            subject: 'Redefinir sua senha Iron Trainers',
            pathPlainText: '/opt/bitnami/apps/parse/htdocs/node_modules/parse-server/node_modules/parse-server-amazon-ses-email-adapter/test/email-templates/password_reset_email.txt',
            pathHtml: '/opt/bitnami/apps/parse/htdocs/node_modules/parse-server/node_modules/parse-server-amazon-ses-email-adapter/test/email-templates/password_reset_email.html',
            callback: (user) => {
                return {
                  firstName: user.get('firstName')
                }
              }
              // Now you can use {{firstName}} in your templates
          },
          verificationEmail: {
            subject: 'Confirmar email no Iron Trainers',
            pathPlainText: '/opt/bitnami/apps/parse/htdocs/node_modules/parse-server/node_modules/parse-server-amazon-ses-email-adapter/test/email-templates/verification_email.txt',
            pathHtml: '/opt/bitnami/apps/parse/htdocs/node_modules/parse-server/node_modules/parse-server-amazon-ses-email-adapter/test/email-templates/resendEmailVerification.html',
            callback: (user) => {
                return {
                  firstName: user.get('firstName')
                }
              }
              // Now you can use {{firstName}} in your templates
          },
          customEmailAlert: {
            subject: 'Urgent notification!',
            pathPlainText: '/opt/bitnami/apps/parse/htdocs/node_modules/parse-server/node_modules/parse-server-amazon-ses-email-adapter/test/email-templates/custom_alert.txt',
            pathHtml: '/opt/bitnami/apps/parse/htdocs/node_modules/parse-server/node_modules/parse-server-amazon-ses-email-adapter/test/email-templates/custom_alert.html',
          }
        }

A: You'll need to do your localization in the template callback.
The callback is synchronous, so all of your localization will also need to be synchronous.
emailTemplate.html

  {{localizedText}}

Other templates for each locale:
emailTemplate.en.html

  Hi {{nome}}...

The emailer logic:
// The same templater used by parse-server-amazon-ses-email-adapter
import template from 'lodash.template'

/* ... */

const TemplatesByLocale = {
  en: fs.readFileSync('./emailTemplate.en.html'),
}

verificationEmail: {
  /* ... */
  pathHtml: './path/to/emailTemplate.html',
  callback: (user) => {
    const locale = getLocaleSomehow(user) // needs to be synchronous
    const localizedTemplate = TemplatesByLocale[locale]

    const compiled = template(localizedTemplate, {
      // same interpolation as parse-server-amazon-ses-email-adapter
      interpolate: /{{([\s\S]+?)}}/g
    })
    const localizedText = compiled({
      nome: user.get('nome'), /* ... */
    })
    return {
      localizedText: localizedText,
    }
  },
  /* ... */
}

It's worth noting that parse-server-amazon-ses-email-adapter will use the HTML template (the one specified via pathHtml) before it uses the plain text template, so if you've specified an HTML template you can just leave off the pathPlainText property.

A: As per my understanding this can be done but through a code change in the plugin.
There is a if-else condition at below line in code
https://github.com/ecohealthalliance/parse-server-amazon-ses-email-adapter/blob/0bce9b6c81681c3829a17b208d839d23c846ab05/src/AmazonSESAdapter.js#L90
Since you have not provided any feedback and I have not way to setup this, I have assume that the else part is what gets executed
  const {
    link,
    appName,
    user,
    templateConfig
  } = options;
  const {
    callback
  } = templateConfig;
  let userVars;

  if (callback && typeof callback === 'function') {
    userVars = callback(user);
    // If custom user variables are not packaged in an object, ignore it
    const validUserVars = userVars && userVars.constructor && userVars.constructor.name === 'Object';
    userVars = validUserVars ? userVars : {};
  }

  pathPlainText = templateConfig.pathPlainText;
  pathHtml = templateConfig.pathHtml;

  templateVars = Object.assign({
    link,
    appName,
    username: user.get('username'),
    email: user.get('email')
  }, userVars);

  message = {
    from: this.fromAddress,
    to: user.get('email'),
    subject: templateConfig.subject
  };
}

Now in this part, 2 lines decide the template to be used
pathPlainText = templateConfig.pathPlainText;
pathHtml = templateConfig.pathHtml;

By this time, the callback you have provided has been called. Now in the callback you can set a variable, let assume it is name locale. So you can update the code like below
pathPlainText = templateConfig.pathPlainText + (userVars["locale"] || "en");
pathHtml = templateConfig.pathHtml + (userVars["locale"] || "en");

And then you will create templates which have the locale in the file path and with updated code the correct template will be picked.
You can also look at @bgran answer, at first look I do believe that should work as well

redpajama_set_name: RedPajamaStackExchange


text:
Q: Update table using combination of 2 fields without using primary key Im trying to convert this direct update query into cake's way of updating.
$this->Test->query("UPDATE tests SET rating=3 WHERE goal_id=1 AND employee_id=28");

Normally when we update we set the id and then save, right?
$this->id = 1;
$this->Test->save($data);

But here im making use of combination of (goal_id+employee_id) to identify the rows. So how can i do an update on this?

A: You can use updateAll(), you just happen to be updating 1 record rather than the many records that the name of the method would suggest.
Model::updateAll(array $fields, array $conditions)

So, for your test you'd use:
$this->Test->updateAll(
    array('rating' => 3),
    array('goal_id' => 1, 'employee_id' => 28)
);


text:
Q: Comparing TextViews This always returns the value of "else"...
   public void onClick(View view) {

            System.out.println("Palabra1= "+palabraDes.getText());
            System.out.println("Palabra2= "+palabraOrd.getText());

            String pla1 = palabraDes.getText().toString();
            String pla2 = palabraOrd.getText().toString();

            if (pla1 == pla2) {

                ttsManager.initQueue("Resultado correcto, buen trabajo.");

            } else

                ttsManager.initQueue("Incorrecto, intente de nuevo.");

        }
    });

Launching app:
I/System.out: Palabra1= perro
    Palabra2= perro

A: You can't use == to compare strings. You will have to do if (string1.equals(string2))
   public void onClick(View view) {

        System.out.println("Palabra1= "+palabraDes.getText());
        System.out.println("Palabra2= "+palabraOrd.getText());

        String pla1 = palabraDes.getText().toString();
        String pla2 = palabraOrd.getText().toString();

        if (pla1.equals(pla2)) {

            ttsManager.initQueue("Resultado correcto, buen trabajo.");

        } else

            ttsManager.initQueue("Incorrecto, intente de nuevo.");

    }
});

A: You need to use Equals() instead of ==

A: Both equals() and == are used to compare objects to check for equality however the == checks if both objects point to the same memory location whereas .equals() evaluates values in the objects.
In your case you have to use String.equals
Replace
if (pla1 == pla2)

with
if (pla1.equals(pla2))

A: My problem was that when the text string passed, it came with a space (\ n), then all the forms worked.

A: Cannot use == operator for strings
 Use if(pla1.equals(pla2))

    or

 Use if(pla1.equalsIgnoreCase(pla2))

 instead of if(pla1 == pla2) {

A: Solution:
if (pla1.equals(pla2)) {

   ttsManager.initQueue("Resultado correcto, buen trabajo.");

} else

   ttsManager.initQueue("Incorrecto, intente de nuevo.");
}

In general both equals() and "==" operator in Java are used to compare objects to check equality but here are some of the differences between the two:
Main difference between .equals() method and == operator is that one is method and other is operator.
We can use == operators for reference comparison (address comparison) and .equals() method for content comparison.
In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.
If a class does not override the equals method, then by default it uses equals(Object o) method of the closest parent class that has overridden this method.

I hope it will help you!


text:
Q: How do I modify the code in this extension to run the export function via cron after each order I am currently using the Bulk Import+Export Orders to CSV extension that is available at:
https://www.magentocommerce.com/magento-connect/bulk-import-export-orders-to-csv.html
The main function that I need is the export orders function, which is working fine. As this lets me import my magento orders into the order processing system which is being used for shipping out the products.
What I am trying to achieve is having the export function run automatically, preferably after every order is received. If not at least at certain times of the day.
I have looked around can't seem to find the information on what i need to look for to modify this to allow the cron functionality. The csv file that is generated is perfect for my processing system, order extensions do not format the files as i need.
I'm not the most experience, but am learning as I go along. Please can someone point me to where i need to look to allow the export function to available via a cron job.
All the advice is appreciated, the website is running on magento 1.9.2.2.

A: Have a look at Ffuenf_OrderExporter which I just forked from this very extension. I'll make a bit of a code cleanup there and added directions in Ffuenf_OrderExporter_Model_Cron how you might implement cron functionality. Also remember the settings in config.xml which wires the Model to the Magento Cron System.


text:
Q: Can't make a replacement ref "permanent" I had to merge two branches into another, and I wanted to capture/record this history. First I tried an octopus merge, but the branches were too different and Git refused to perform the merge. To be clear, there are three branches involved, not two.
As an alternative, I checked out the files I needed, from each branch, did a three way diff on each set of files, then committed. To record the history, I then used git replace --graft. Aside from having to handle the merge without Git's held (aside from it keeping track of the files in the other branches...which is a big deal) it went well.
I then found out that rather than this new commit being part of the branch proper, it is instead substituted for the actual commit whenever something calls for it. This is not desirable. Admittedly, I don't know of any disadvantages with having things handled in this fashion, but that isn't to say there aren't negative side effects. Besides, it seems messy and improper.
Looking up a solution, I find that git filter-branch -- --all should do the trick...except it doesn't seem to. First off, I expected at least the replacement commit's hash to change. Also, the errors I'm getting seem to indicate something went wrong.
Rewrite 500495d563d9209cf21d660e7d78d2a7677e570b (291/318) (6 seconds passed, remaining 0 predicted)
WARNING: Ref 'refs/heads/cleanup
WARNING: Ref 'refs/heads/planning' is unchanged
WARNING: Ref 'refs/heads/devel' is unchanged
WARNING: Ref 'refs/remotes/nm/cleanup
WARNING: Ref 'refs/remotes/nm/planning' is unchanged
WARNING: Ref 'refs/remotes/nm/devel' is unchanged
WARNING: Ref 'refs/replace/3ec2686d2ae2ba9e7583836e26e25c7bd0b8aa19' is unchanged
WARNING: Ref 'refs/tags/sent/18-01-11' is unchanged
WARNING: Ref 'refs/tags/sent/18-02-11' is unchanged
WARNING: Ref 'refs/tags/sent/18-10-23' is unchanged
WARNING: Ref 'refs/tags/sent/18-10-24' is unchanged
WARNING: Ref 'refs/tags/sent/18-12-27' is unchanged
WARNING: Ref 'refs/tags/sent/18-12-31' is unchanged

The questions are then "How else could I have done this", "did something actually go wrong", and/or "how can I 'fix' this?" I understand git graft is another way to handle the first step but (1) it seems to be some horribly hacked together solution and I've read its advised against and (2) I'm having trouble finding docs on git graft leading me to believe it has been removed in favor of git replace --graft.
In case it matters, I had already run git gc prior to running git filter-branch. I actually performed the git replace part early last week, and only saw that it might be a good idea to "cement" the commit today.


text:
Q: How do you put lists in webbrowser links? I'm trying to create a program that opens a random Bitly link in your browser.
import random
import webbrowser

#set the length of the url
length = random.randint(1,7)

#list of all possible characters in the key
characters = ['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h',
 'H', 'i', 'I', 'j', 'J', 'k', 'K', 'l', 'L', 'm', 'M', 'n', 'N', 'o', 'O', 'p', 'P',
  'q', 'Q', 'r', 'R', 's', 'S', 't', 'T', 'u', 'U', 'v', 'V', 'w', 'W', 'x', 'X', 'y',
   'Y', 'z', 'Z',]

#create the string of text on the end of the link
key = []
for x in range (1, length):
    key.append(random.choice(characters))

webbrowser.open_new_tab('https://bit.ly/', *key, sep='')

When I do this it gives me

TypeError: open_new_tab() got an unexpected keyword argument 'sep'

But if I can't put "sep" into that argument, how else am I suposed to make the link open correctly?

A: You can use
key_str = "".join(key)

to join all of the characters in key into a single string. The URL could be constructed with
url = f"https://bit.ly/{key_str}"

By the way, instead of defining a list of upper- and lower-case letters, you can use string.ascii_letters.


text:
Q: Support 'background-size' property on older browsers? Is there a way that I can use the CSS3 'Background-Size' property and then use something like Modernizr to ensure that it's supported in older browsers (in particular I want to use 'background-size: cover' option)?
I took a look at cssFx, which is mentioned from the Modernizr website, but this only seems to add vendor prefixes for browsers which need them to use a property, rather than allowing browsers such as IE8 to support the background size property.
Also looked at CSS3Pie, but that doesn't seem to currently support the background-size property.
[11/10/2011 - By older browsers I'm thinking mainly of IE7/8, but ideally I would like to cover FF3.6, etc.]

A: You can see support for background-size and its properties at: http://www.standardista.com/css3/css3-background-properties
This CSS supports IE9+, FireFox 3.6+, Safari, Chrome:
background-size: cover;
-moz-background-size: cover;

For IE7/8 support, caniuse.com lists this polyfill: https://github.com/louisremi/background-size-polyfill

A: You're right that background-size is not supported on a number of older browsers.
The typical solution to this is to simulate it using an additional <div> or even an <img> element positioned behind the element you want to have the background.
This can be achieved simply by using additional markup, but this solution has the disadvantage of meaning that you'll be using it for all browsers, instead of the background-size property. In other words, it means deliberately degrading your code for the sake of old browsers, which is not ideal.
If you want to use the CSS property for browsers that support it, you could use a bit of Javascript to generate the above markup, but only if required. This means that modern browsers can happily use background-size, and only older browsers will use the fallback.
There are a number of Javascript solutions to this available on the web (a quick google turned up the following: http://css-tricks.com/766-how-to-resizeable-background-image/ among others), but more importantly you need to know how to trigger it based on the browser.
This is where Modernizr comes in. The description you've given of Modernizr in the question is not entirely accurate. What it does is produce a set of CSS classes in your HTML markup and matching variables in your Javascript that represent all the browser features. These are boolean flags indicating whether the current browser supports.
So with Modernizr you can then check in Javascript whether the browser supports background-size or not, and only run the alternative javascript function if it doesn't support it.
if(!Modernizr.backgroundsize) {
    //do stuff here to simulate the background-size property for older browsers.
}

Hope that helps.

A: First of all there is an easy fix for Firefox 3.6. There is a vendor prefix:
-moz-background-size

With regard a solution when using media queries: You could use Modernizr to target another image for when users are viewing older browsers, this would mean another browser request. However, presumably you will be loading smaller images for each query where the screen size gets smaller. Because Modernizr will create a situation where these requests will be ignored in newer browsers you will cut down on server requests for the majority of people using newer browsers.
Out of curiosity, I tried the above solution and it worked. I applied the following modernizr classes as: .no-backgroundsize for non background-size supporting ie and loaded in a new image.
For all other browsers I added the class .backgroundsize and included the prefix mention at the top for FF. This could be repeated for each media query with a new image for .no-background. This is one way to solve the problem.
-I edited this post after I tried it 12/15/12.

A: I think you probably want to use modernizr to check whether or not the property is supported in the current browser. If not, try to figure out an alternative display of your site/application that still looks good without the need of the background-size property.
Of course, you can also try another approach that does not involve this property at all like an underlying div with a picture in it (which you can size) and the content that is overlapping this div. Good luck.

A: Another option would be Background Size Polyfill:
.selector {
    background-size: cover;
    /* The url is relative to the document, not to the css file! */
    /* Prefer absolute urls to avoid confusion. */
    -ms-behavior: url(/backgroundsize.min.htc);
}

A: Best sample to support better:
  background-image: url(bg-image.png);

      -webkit-background-size: 100% 100%;           /* Safari 3.0 - Old Chrome - Old Android */
         -moz-background-size: 100% 100%;           /* Gecko 1.9.2 (Firefox 3.6) */
           -o-background-size: 100% 100%;           /* Opera 9.5 */
              background-size: 100% 100%;           /* Gecko 2.0 (Firefox 4.0) and other CSS3-compliant browsers */

Don't add this, because it made problem in new firefox versions:
-moz-border-image: url(bg-image.png) 0;    /* Gecko 1.9.1 (Firefox 3.5)

Source: mozilla.org


text:
Q: Inverse of an absolute value Suppose $f(x) = e^{-|x|}$ then it follows:
$$y = e^{-|x|} $$
$$x = e^{-|y|} $$
$$ \log(x) = -|y| $$
$$-\log(x) = |y| $$
Im assuming the equation for the inverse depends on the range of $x$, and the range of $x$ is $0$ to $\infty$. I am just not sure where to go next.

A: In your second step
$$y = e^{-|x|} \iff x = e^{-|y|} $$
you should specify you are changing variables to avoid confusion.
To find the inverse note that $f:\mathbb R \to (0,1]$  is even and that $f(x)$ is monotonic for $x\ge 0$ then we can find the inverse for the restriction
$$f:[0,\infty) \to (0,1] $$
that is
$$y = e^{-x} \iff \log y =\log (e^{-x})=-x$$
then the inverse function is
$$f(x)=-\log x$$
In a similar way for the restriction
$$f:(-\infty,0] \to (0,1] $$
the inverse function is
$$f(x)=\log x$$


text:
Q: Excel Macro Userform - single code handling multiple checkboxes I've got a user form that looks like the image below, with a naming convention to identify levels & positions (like the example above the pic). I have the current code below, as well - but I haven't added code for each of the "Port" checkboxes yet, and eventually I'll be inserting/removing a value specific to each checkbox into arrays based on whether they're checked/un-checked.
I'd like to know about the following:

*

*Are conditions based on checking or un-checking a checkbox better chosen by reading whether it's checked/un-checked (like I'm doing below), or upon "a change" in ticking?

*Can I shorten the number or times I code an action for any checkbox on the form to just one (or a few) case(s) instead of coding every one of those (I'll eventually be assigning a value to an array (or removing one) based on what's checked (or un-checked))?

*Can I take a portion of the name of a checkbox (like the first 4 or 6 characters) as a value to determine what I'm handling if #2 is possible?
I've been staring at this so long I'm a little brain-dead - I'm not sure if I'm asking the right questions here, or what else to ask. Essentially, I want to avoid having to repeat what is pretty much the same thing over and over (like I'm doing now).
Private Sub UserForm_Initialize()
Dim chBox As Control
Dim comboBox As Control
Dim arrFreq() As String
Dim i As Long

    'Use the Split function to create two zero based one dimensional arrays.
    arrFreq = Split("Unused|700|850|1900|2100", "|")
    For Each comboBox In ADSinputform.Controls
        If TypeOf comboBox Is MSForms.comboBox Then
            For i = 0 To UBound(arrFreq)
                'Use .List property to write array data to all the comboBoxes
                comboBox.List = arrFreq
            Next i
        End If
    Next
    'Empty NameTextBox
    SiteNameTextBox.Value = siteName

End Sub

Private Sub AlphaSectCheckbox_Click()

    If AlphaSectCheckbox.Value = True Then AlphaAnt_Frame.Visible = True
    If AlphaSectCheckbox.Value = False Then
        AlphaAnt_Frame.Visible = False
        For Each chBox In AlphaAnt_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub BetaSectCheckbox_Click()

    If BetaSectCheckbox.Value = True Then BetaAnt_Frame.Visible = True
    If BetaSectCheckbox.Value = False Then
        BetaAnt_Frame.Visible = False
        For Each chBox In BetaAnt_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub GammaSectCheckbox_Click()

    If GammaSectCheckbox.Value = True Then GammaAnt_Frame.Visible = True
    If GammaSectCheckbox.Value = False Then
        GammaAnt_Frame.Visible = False
        For Each chBox In GammaAnt_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub DeltaSectCheckbox_Click()

    If DeltaSectCheckbox.Value = True Then DeltaAnt_Frame.Visible = True
    If DeltaSectCheckbox.Value = False Then
        DeltaAnt_Frame.Visible = False
        For Each chBox In DeltaAnt_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub A1Checkbox_Click()

    If A1Checkbox.Value = True Then A1Port_Frame.Visible = True
    If A1Checkbox.Value = False Then
        A1Port_Frame.Visible = False
        For Each chBox In A1Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub A2Checkbox_Click()

    If A2Checkbox.Value = True Then A2Port_Frame.Visible = True
    If A2Checkbox.Value = False Then
        A2Port_Frame.Visible = False
        For Each chBox In A2Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub A3Checkbox_Click()

    If A3Checkbox.Value = True Then A3Port_Frame.Visible = True
    If A3Checkbox.Value = False Then
        A3Port_Frame.Visible = False
        For Each chBox In A3Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub A4Checkbox_Click()

    If A4Checkbox.Value = True Then A4Port_Frame.Visible = True
    If A4Checkbox.Value = False Then
        A4Port_Frame.Visible = False
        For Each chBox In A4Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub A5Checkbox_Click()

    If A5Checkbox.Value = True Then A5Port_Frame.Visible = True
    If A5Checkbox.Value = False Then
        A5Port_Frame.Visible = False
        For Each chBox In A5Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub A6Checkbox_Click()

    If A6Checkbox.Value = True Then A6Port_Frame.Visible = True
    If A6Checkbox.Value = False Then
        A6Port_Frame.Visible = False
        For Each chBox In A6Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub B1Checkbox_Click()

    If B1Checkbox.Value = True Then B1Port_Frame.Visible = True
    If B1Checkbox.Value = False Then
        B1Port_Frame.Visible = False
        For Each chBox In B1Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub B2Checkbox_Click()

    If B2Checkbox.Value = True Then B2Port_Frame.Visible = True
    If B2Checkbox.Value = False Then
        B2Port_Frame.Visible = False
        For Each chBox In B2Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub B3Checkbox_Click()

    If B3Checkbox.Value = True Then B3Port_Frame.Visible = True
    If B3Checkbox.Value = False Then
        B3Port_Frame.Visible = False
        For Each chBox In B3Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub B4Checkbox_Click()

    If B4Checkbox.Value = True Then B4Port_Frame.Visible = True
    If B4Checkbox.Value = False Then
        B4Port_Frame.Visible = False
        For Each chBox In B4Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub B5Checkbox_Click()

    If B5Checkbox.Value = True Then B5Port_Frame.Visible = True
    If B5Checkbox.Value = False Then
        B5Port_Frame.Visible = False
        For Each chBox In B5Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub B6Checkbox_Click()

    If B6Checkbox.Value = True Then B6Port_Frame.Visible = True
    If B6Checkbox.Value = False Then
        B6Port_Frame.Visible = False
        For Each chBox In B6Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub C1Checkbox_Click()

    If C1Checkbox.Value = True Then C1Port_Frame.Visible = True
    If C1Checkbox.Value = False Then
        C1Port_Frame.Visible = False
        For Each chBox In C1Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub C2Checkbox_Click()

    If C2Checkbox.Value = True Then C2Port_Frame.Visible = True
    If C2Checkbox.Value = False Then
        C2Port_Frame.Visible = False
        For Each chBox In C2Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub C3Checkbox_Click()

    If C3Checkbox.Value = True Then C3Port_Frame.Visible = True
    If C3Checkbox.Value = False Then
        C3Port_Frame.Visible = False
        For Each chBox In C3Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub C4Checkbox_Click()

    If C4Checkbox.Value = True Then C4Port_Frame.Visible = True
    If C4Checkbox.Value = False Then
        C4Port_Frame.Visible = False
        For Each chBox In C4Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub C5Checkbox_Click()

    If C5Checkbox.Value = True Then C5Port_Frame.Visible = True
    If C5Checkbox.Value = False Then
        C5Port_Frame.Visible = False
        For Each chBox In C5Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub C6Checkbox_Click()

    If C6Checkbox.Value = True Then C6Port_Frame.Visible = True
    If C6Checkbox.Value = False Then
        C6Port_Frame.Visible = False
        For Each chBox In C6Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub D1Checkbox_Click()

    If D1Checkbox.Value = True Then D1Port_Frame.Visible = True
    If D1Checkbox.Value = False Then
        D1Port_Frame.Visible = False
        For Each chBox In D1Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub D2Checkbox_Click()

    If D2Checkbox.Value = True Then D2Port_Frame.Visible = True
    If D2Checkbox.Value = False Then
        D2Port_Frame.Visible = False
        For Each chBox In D2Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub D3Checkbox_Click()

    If D3Checkbox.Value = True Then D3Port_Frame.Visible = True
    If D3Checkbox.Value = False Then
        D3Port_Frame.Visible = False
        For Each chBox In D3Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub D4Checkbox_Click()

    If D4Checkbox.Value = True Then D4Port_Frame.Visible = True
    If D4Checkbox.Value = False Then
        D4Port_Frame.Visible = False
        For Each chBox In D4Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub D5Checkbox_Click()

    If D5Checkbox.Value = True Then D5Port_Frame.Visible = True
    If D5Checkbox.Value = False Then
        D5Port_Frame.Visible = False
        For Each chBox In D5Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Private Sub D6Checkbox_Click()

    If D6Checkbox.Value = True Then D6Port_Frame.Visible = True
    If D6Checkbox.Value = False Then
        D6Port_Frame.Visible = False
        For Each chBox In D6Port_Frame.Controls
            If TypeOf chBox Is MSForms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

Checkbox Naming Convention:
In "Sectors" frame: "AlphaSectCheckbox", "BetaSectCheckbox", "GammaSectCheckbox", "DeltaSectCheckbox"

In "Antennas" frames: (Alpha) "A1Checkbox", "A2Checkbox", "A3Checkbox", etc / (Beta) "B1Checkbox", "B2Checkbox", "B3Checkbox", etc / (Gamma) "C1Checkbox", "C2Checkbox", "C3Checkbox", etc, etc

In "Port" frames: (Alpha - Ant 1) "A1P1Checkbox", "A1P2Checkbox", etc / (Alpha - Ant 2) "A2P1Checkbox", "A2P2Checkbox", etc / (Beta - Ant1) "B1P1Checkbox", "B1P2Checkbox", etc / (Beta Ant2) "B2P1Checkbox", "B2P2Checkbox", etc / (Gamma - Ant1) "C1P1Checkbox", "C1P2Checkbox", etc, etc

=========================Edited 1/11/2016
Here's what I implemented after sous2817 answer, this works great, and I can carry on from here with a fraction of the code. This is a new Class Module named "clsUFCheckBox":
Option Explicit

Public WithEvents aCheckBox As msforms.CheckBox

Private Sub aCheckBox_Click()
Dim chBox As Control
Dim actFrmStr As String

     MsgBox aCheckBox.Name & " was clicked" & vbCrLf & vbCrLf & _
        "It refers to the frame: " & aCheckBox.Tag & vbCrLf & vbCrLf & _
        "Its Checked State is currently " & aCheckBox.Value, vbInformation + vbOKOnly, _
        aCheckBox.Name & " & State"

    actFrmStr = aCheckBox.Tag

    If aCheckBox.Value = True Then ADSinputform.Controls(actFrmStr).Visible = True
    If aCheckBox.Value = False Then
        ADSinputform.Controls(actFrmStr).Visible = False
        For Each chBox In ADSinputform.Controls(actFrmStr).Controls
            If TypeOf chBox Is msforms.CheckBox Then chBox.Value = False
        Next
    End If

End Sub

A: This is too long for a comment, but hopefully it will get you close (or at least starting towards) a solution.
First, add a class to your project.  In this example I called is clsUFCheckBox.  Add this following code to the class:
Option Explicit

Public WithEvents aCheckBox As msforms.CheckBox

Private Sub aCheckBox_Click()
     MsgBox aCheckBox.Name & " was clicked" & vbCrLf & vbCrLf & _
        "Its Checked State is currently " & aCheckBox.Value, vbInformation + vbOKOnly, _
        "Check Box # & State"
End Sub

The above creates a click event that will be fired to each checkbox in a collection (that will be coming up shortly).  This test code will show you a message box that tells you what check box was clicked and what the current state is.  Obviously you'll change this to suit whatever logic you need to solve your current problem, but this will get you started.
Now, in your user form code, add this line at the top (right under your Option Explicit line)
Dim myCheckBoxes() As clsUFCheckBox

This creates an array of the class you created above to hold all of your checkboxes on your form.  Now in your Userform_Initialize() event, add this code:
Dim ctl As Object, pointer As Long
ReDim myCheckBoxes(1 To Me.Controls.Count)

    For Each ctl In Me.Controls
        If TypeName(ctl) = "CheckBox" Then
            pointer = pointer + 1
            Set myCheckBoxes(pointer) = New clsUFCheckBox
            Set myCheckBoxes(pointer).aCheckBox = ctl
        End If
    Next ctl

ReDim Preserve myCheckBoxes(1 To pointer)

This code will loop through all of the controls on your userform and add the checkboxes to the array you created above.  Also, since you're associating all of the checkboxes to the class you've created, you're giving them a common click event.  So each checkbox that you click, runs the same click event.
So there you go.  The dozens and dozens of checkboxes you created at the start, they all run the same _click() event.  You can put logic in that single event to handle each grouping.  The nice thing is, you only have to write the code once and you don't have to add it to each individual checkbox_click event.
If you need a test workbook so you can see it all wired up, let me know and I'll see if I can find a place to upload one for you to review.
Hope that helps.  If you get jammed up, please post back and we'll keep hammering at it.

A: You could call a handler function like this where each checkbox simply passes the key string.
Then put all your similar code into the handler function which deals with relevant frames
Private Sub cbA1_Click()
     handleCB ("A1")
End Sub

Private Sub cbA2_Click()
    handleCB ("A2")
End Sub

Public Function handleCB(cb As String)

    Dim formObj As Control
    Set formObj = Me("cb" & cb)
    MsgBox formObj.Name & Chr(10) & formObj.Value

    'do code with the other controls that have the string cb in them
    'such as your frames etc

End Function

Change/click event shouldn't matter too much


text:
Q: How do I remap META to ALT? I am using emacs in Ubuntu. How can I remap META to the ALT key?

A: Way back when, it did seem that the META key was difficult to map to the ALT.  At that time I had to use xmodmap, and these were the things I had to put in my .xmodmap file.  Some variation of the following always worked (it depended on the system).  My .xinitrc file would have xmodmap read in the file.
!! Note the `!` are comment characters.

!! suggested to make Emacs work under VNC
keysym Alt_L = Meta_L
keysym Alt_R = Meta_R

!! xmodmap -e 'keysym Alt_L = Meta_L' -e 'keysym Alt_R = Meta_R'
!!
!! some environments still can't handle alt key properly
!! add this:
!!
clear Mod1
add Mod1 = Meta_L Meta_R

!! or
!! xmodmap -e "clear Mod1" -e "add Mod1 = Meta_L Meta_R"

A: Use xkeycaps to look at your keyboard mapping and swap the META and ALT modifiers, or just swap the entire keys. Because GNOME has some assumptions about which keys have META and ALT modifiers, it'll probably make your life easier to swap the keys entirely.
xkeycaps should be available as an ubuntu package.

A: If using a Mac, open up terminal then navigate to Terminal > Preferences. Under the profiles tab, check the checkbox on Use Option as Meta Key. See screenshot

That should do the trick.

A: If you run emacs in a gnome-terminal, the gnome-terminal may be capturing your alt key to open the gui menu (File, Edit, ...).  You can change this behavior by selecting Edit >> Keyboard Shortcuts ..., and unchecking `Enable menu access keys ...'.
On my system, Ubuntu 9.04, this lets alt serve as meta for emacs.

A: Usually Meta is mapped to the Alt key by default.
What is displayed in the echo area at the bottom of the Emacs window when you type Alt+X?  If you see M-x then Alt is working as Meta.


text:
Q: Finding hot topics in twits based on the frequency of the words I am building a Java web service for finding the hot topics in a special location (latitude , longitude) based on the frequency of the word which is being used in the twits.
I am using twitter4j api for fetching the twits,and I can filter them with their location.
can anybody help me and tell me how to process the data and get the hot topics?
I will really appreciate that.

A: I would suggest you to look into "probabilistic latent semantic indexing". You can use the "topicmodels" package for that.
This video might be of use to you: Video on Probabilistic latent semantic indexing


text:
Q: Enhancing a search query written with regex to support whitespace I have the following regex:
/("[^"]+"|[^\s]+:[^\s]+)/

If I gave it the following:
tag:closed  tag:open tag:Trello status:new

it will match these groups:

*

*tag:closed

*tag:open

*tag:Trello

*status:new
I tried to enhance it to support whitespace so that it matches:
tag:"don't merge"

I tried:
/("[^"]+"|[^\s]+:[^\s]+|["\w\s"]+)/

but that didn't work. How can I achieve that?

A: http://rubular.com/r/DNWKz44BbF
You need to negate the doublequotes in your other match otherwise it's a shorter match for regex to use.
([^\s]+:"[^"]+"|[^\s]+:[^\s"]+)

A: /(\S+:(?:"[^"]+"|\S+))/

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


text:
Q: Trigger an event when Computer is added to Active Directory Maybe this is a dumb question, but i'm going to ask i anyway ;)
I need to run a script whenever a Computer is added to my Active Directory.
The easiest way to do this i figured, was to bind a task to an event.
However, i coudn't find any event that gets triggered when a Computer is added to AD, nor did i find a way to active it.

A: I found the solution: when the 'Audit Account Management' Policy is enabled (explained here) the event 4741 will be triggered when a Computer is created (source). When a task is coupled with this event, you're able to run a script as soon as the event occurs. ;)  Thanks!


text:
Q: A homological criterion for collapsibility? On page 256 of Kirby and Siebenmann one finds the following lemma (its proof an "elementary exercise", so they only give a hint):

Taking $A$ to be a point and iterating this collapsing lemma, this seems to give a criterion for collapsibility of simplicial complexes: a finite simplicial complex $B$ is collapsible if and only if $\tilde{H}^m(B;\mathbb{Z}_2) = 0$ for all $m$. This seems false to me. First of all this can't be true if $B$ is a classifying space of a finitely presented acyclic group (like Higman's group). It also contradicts well-known examples of non-collapsible simplicial complexes like the house with two rooms (or at least a triangulation of it) or Rudin's non-collapsible triangulation of the 3-disk. In fact, those examples also give contradictions to the hint.
So am I misinterpreting this lemma or is it not correct? It is used in the proof for the sliced structure classification theorem for open 4-manifolds that do not admit a handle decomposition. If the lemma is not correct, can that proof be fixed?

A: This question was essentially answered in the comments. I'm collecting the information in an answer, because it might be interesting to some people.
Firstly, the lemma as stated is false. There was some discussion about whether the lemma can be iterated. To see this is the case, note a simplicial collapse of B onto a subcomplex containing $A$ in particular must fix $A$ and will be homotopy equivalence rel $A$. Using iteration the following simplicial complexes $B$ with $A = \ast$ give counterexamples:

*

*A triangulation of the house with two rooms is a contractible but not collapsible simplicial complex of dimension 2.

*The second barycentric subdivision of the dunce hat is another contractible but not collapsible simplicial complex of dimension 2.

*Rudin's triangulation is a non-collapsible triangulation of the 3-disk.

*This question lists various other interesting examples of non-collapsible triangulations of disks.

Without iterating you get a counterexample from Higman's group (or any other finitely-presented acyclic group). This is the finitely presented acyclic group $G = \langle x_i|x_ix_{i+1}x_i^{-1}\rangle_{i \in \mathbb{Z}/4\mathbb{Z}}$. There is a finite simplicial complex $BG$ of dimension 2 that is a classifying space for $G$. Taking $A = *$, we get that $H^2(BG,*;\mathbb{Z}/2\mathbb{Z}) = 0$, so the lemma would imply that $BG$ collapses onto, and thus is homotopy equivalent to, a simplicial complex of dimension 1. But every finite simplicial complex of dimension 1 has a free group as fundamental group.
As Oscar Randal-Williams suggests in the comments, the lemma is true if one additionally assumes that at most two $m$-simplices in $B\backslash A$ attach to an $(m-1)$-simplex in $B \backslash A$. For suppose this is the case, but all $m$-simplices $S$ in $B \backslash A$ that have the property that each face not in $A$ is the face of another $m$-simplex (there is then exactly one of these by the additional assumption). It suffices to prove we can collapse at least one $m$-simplex in $B \backslash A$, because the additional assumption and homological condition are preserved by such a collapse. Consider the sum of all $m$-simplices in the cellular chain complex of the pair $(B,A)$: $\sigma = \sum_i S_i$. Then $\partial \sigma$ is $0$, as faces either lie in $A$ or appear twice (and we are working modulo $2$). Thus $\sigma$ is a cycle, but this contradicts $H_m(B,A;\mathbb Z/2\mathbb Z)=0$, which follows from the assumption on cohomology using the universal coefficient theorem.
This additional assumption is satisfied if $B$ is a PL manifold of dimension $m$, because in that case the link of every $(m-1)$-simplex is either $S^0$ or a point (depending on wither the $(m-1)$-simplex is in the boundary or not). One cannot iterate the lemma with the additional assumption, so we do not get contradiction (e.g. from Rudin's triangulation). Coincidentally, it does prove the classical result that every triangulation of the 2-disk is collapsible (apply the lemma with additional assumption, and then note that every tree is collapsible).
Finally, if one looks to Lemma (e) on page 257 of Kirby-Siebenmann and its eventual application in the proof of Theorem A.1 on page 262, part ($\delta$), we see that in the proof we can get away with only using the lemma in the case that $B$ is a PL-manifold of dimension $m$. The sliced structure classification theorem for open 4-manifolds that do not admit a handle decomposition is safe.


text:
Q: How to write real value of -2.12683575e-04 in a file (Python) I am currently working with really tiny values and when I try to write a value like -0.000212683575 in a file, it write me -2.12683575e-04.
The problem is that I would like to have this value -0.000212683575 written in the file or a least this one -0.00021268 if there are too much numbers.
How could I do this ?
I use Python 2.7
Thank you very much

A: Python allows you to choose formats.  For example, this gives the scientific notation that you don't want:
>>> x =  -0.00021268357
>>> '{:.2e}'.format(x)
'-2.13e-04'

But, this format gives the decimal notation that you prefer:
>>> '{:.9f}'.format(x)
'-0.000212684'

We can use these formats when we write to a file:
>>> with open('output', 'w') as f:
...     f.write('{:.9f}'.format(x))
...
>>> open('output').read()
'-0.000212684'

You can read about the format method, and all its complex and powerful features, here.
Python also offers printf style formatting.  For example:
>>> '%f' % x
'-0.000213'
>>> '%e' % x
'-2.126836e-04'

A: While writing a number in a file, you can write it as a string and it'll be all you need. ex:
>>> num = -0.000212683575
>>> f = open("a.txt","w")
>>> f.write(str(num))
>>> f.close()
>>> open("a.txt","r").read()
'-0.000212683575'
>>>


text:
Q: Can a PandasUDF take in a series of type String and return a series of type Array? I'm trying to use PandasUDF's to preprocess images. This involves converting from Base64 strings to NumPy arrays. I would like the PandasUDF to take in a series of type string, and return a series of type list (I can convert np array to list before putting it into a Pandas series). Using the following code, I get the error pyarrow.lib.ArrowTypeError: Expected bytes, got a 'list' object
from pyspark.sql.types import *
from pyspark.sql.functions import pandas_udf, PandasUDFType

    @pandas_udf("string", ArrayType(IntegerType()))
    def base64_to_np(base64_images: Iterator[pd.Series]) -> Iterator[pd.Series]:
        for images in base64_images:
            img_arrays = []
            for img in list(images):
                img_bytes = base64.b64decode(img)
                img_array = np.load(BytesIO(img_bytes))
                img_arrays.append(img_array.tolist()) # img_arrays.append(str(img_array)) works
            img_series = pd.Series(img_arrays, copy = False)
            yield img_series

However, I am able to run this UDF if I return the np array after casting it into a string. It would be better if I could return a series of type array so I won't have to convert from string to array later on. Is there a way to do this?


text:
Q: Understanding const pointers to const value in C++ I have two questions.
First of all I have a little problem with the understanding of const pointers to const values. I don't get why B::insert works, while C::insert results in a compiler error. I mean doesn't the list in C exactly equals the parameter of C::insert?
My second question is whether A const * const a, could also be written as const A& a.
class A
{
    //Do stuff
};

class B
{
private:
    list<A const *> l;

public:
    void insert(A const * const a)
    {
        l.push_back(a);
    }
};

class C
{
private:
    list<A const * const> l;

public:
    void insert(A const * const a)
    {
            l.push_back(a);
    }
};

Edit (Compile error):
g++ -Wall  -c  -O2 "sonnensystem.cpp" -std=c++11 (im Verzeichnis: C:\Users\Kenan\Desktop\OPR\cppcode\Konzepte\Kapselung\Architektur\sonnensystem01)
In file included from C:/TDM-GCC-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/x86_64-w64-mingw32/bits/c++allocator.h:33:0,
             from C:/TDM-GCC-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/bits/allocator.h:46,
             from C:/TDM-GCC-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/string:41,
             from C:/TDM-GCC-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/bits/locale_classes.h:40,
             from C:/TDM-GCC-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/bits/ios_base.h:41,
             from C:/TDM-GCC-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/ios:42,
             from C:/TDM-GCC-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/ostream:38,
             from C:/TDM-GCC-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/iostream:39,
             from sonnensystem.cpp:1:
C:/TDM-GCC-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/ext/new_allocator.h: In instantiation of 'struct __gnu_cxx::new_allocator<const A* const>':
C:/TDM-GCC-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/bits/allocator.h:92:11:   required from 'class std::allocator<const A* const>'
C:/TDM-GCC-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/bits/stl_list.h:315:9:   required from 'class std::__cxx11::_List_base<const A* const, std::allocator<const A* const> >'
C:/TDM-GCC-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/bits/stl_list.h:507:11:   required from 'class std::__cxx11::list<const A* const>'
sonnensystem.cpp:28:27:   required from here
C:/TDM-GCC-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/ext/new_allocator.h:93:7: error: 'const _Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::const_reference) const [with _Tp = const A* const; __gnu_cxx::new_allocator<_Tp>::const_pointer = const A* const*; __gnu_cxx::new_allocator<_Tp>::const_reference = const A* const&]' cannot be overloaded
       address(const_reference __x) const _GLIBCXX_NOEXCEPT
       ^
C:/TDM-GCC-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/ext/new_allocator.h:89:7: error: with '_Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::reference) const [with _Tp = const A* const; __gnu_cxx::new_allocator<_Tp>::pointer = const A* const*; __gnu_cxx::new_allocator<_Tp>::reference = const A* const&]'
       address(reference __x) const _GLIBCXX_NOEXCEPT
       ^
Kompilierung fehlgeschlagen.

A: In your declaration A const * const, the first const says that the A * pointer points to a value that can't be changed (a const pointer).  The second const says that the value of that pointer can't be changed, just like a const int can't be changed.  Since list (and other standard containers) require their members to be assignable, they can't be const values.
For your second question, a A const * const and const A& are similar, but not interchangeable, as the ways you use them are different.

A: When using std::list<T>, one of the requirements for T is that it is CopyAssignable. See http://en.cppreference.com/w/cpp/container/list.
When you use a const type as the parameter, that requirement is not met. You will see a similar error, if not the same error, if you use:
std::list<const int> a;
a.push_back(10);

Anyway,
list<A const * const> l;

is not usable.

A: The only real difference between A const * const and A const & is that it is easier to check that the pointer is invalid (you could cast a nul pointer to A and then dereference to get a null A reference, it's just easier to go if(!a)).
The C::insert case is due to the code trying to assign to the internal node value. It would probably work if you used emplace_back instead of push_back.


text:
Q: Cannot use `substring` method on an array element in `.map` I'm trying to edit an entire array by running a function on every item in it that checks if it has a double quote as the first character and then cuts it out. The code for that looks like this:
args = args.map(function(arg){
  if(arg.substring(0, 1) === "\""){
    return arg.substring(1)
  }
});

When I run this code I get returned with the following error:
index.js:97
if(arg.substring(arg.length()-1, arg.length()) === "\""){
       ^

TypeError: Cannot read property 'substring' of undefined

The parameter of a function can usually be used in an if statement within the function, so I don't know why it's returning undefined here. This list does have items in it.

A: Looks like your args array is having elements of type other than string. So make sure that the elements of the args array are strings.
If you are trying to create an array of only those elements which start with a double quote (of course after removing that double quote), map() is a bad choice as it will add undefined to the resultant array. forEach() would be the better choice in such case.
var newArgs = [];
    args.forEach(arg => {
         if(arg[0] === '"'){
              newArgs.push(arg.substring(1));
         }
    });

If you are trying to create an array where you will have all the elements in the args but some args elements with double quote removed (if it is the first character), then map() is a good choice, but it is being used in a wrong way.
args = args.map(function(arg){
     if(arg.substring(0, 1) === "\""){
          return arg.substring(1);
     }
    // what if the above `if` statement is false?
    // This function is not returning anything in such case.

});

Correct usage would be:
args = args.map(arg => (arg[0] === '"') ? arg.substring(1): arg);

var args = ['test1', '"test2', 'test3', '"test4', '"test5'];
var newArgs = [];
args.forEach(arg => {
     if(arg[0] === '"'){
          newArgs.push(arg.substring(1));
     }
});
console.log('forEach: ' + newArgs);
// returns ["test2", "test4", "test5"]

// Your code in question:
newArgs = args.map(function(arg){
     if(arg.substring(0, 1) === "\""){
          return arg.substring(1);
     };
});
console.log('Your code: ' + newArgs);
// returns [undefined, "test2", undefined, "test4", "test5"]

// If you want to get all elements but with double quote removed (if present as first character
newArgs = args.map(arg => (arg[0] === '"') ? arg.substring(1): arg);
console.log('proper map: ' + newArgs);
// returns ["test1", "test2", "test3", "test4", "test5"]

A: for example if you have:
args = ["a","b",'"c"'];
args = args.map(arg=>arg.slice(0,1)=='"'?arg.slice(1,-1):arg)
its return
["a", "b", "c"]

A: You're using the map function on an empty array. So you just need to fill the args array with some values before attempting to call map on it.

A: Assuming you have an array that looks like this ['"item1"', 'item2',  '"item3"', 'item4'];
let arr = ['"item1"', 'item2',  '"item3"', 'item4'];

let newArr = arr.filter(element => (/^[^\"]/).test(element.trim()))

console.log(newArr); // item2, item4

A: TypeError: Cannot read property 'substring' of undefined
you are mapping an array which contains undefined element at certain index, now in this case before using any function you need make sure that arg is not undefined like :
 args = args.map(function(arg){
  if(arg!==undefined){
     if(arg.substring(0, 1) === "\""){
        return arg.substring(1)
      }
   }
 })

this will make sure you are not using any member function on an undefined element, hope this will help!


text:
Q: Unit Testing with Mockery return false I have written this test :
public function testSetVisitorLog()
{
    $visitorRepositoryMock = Mockery::mock('App\Repositories\VisitorStatisticRepository');
    $this->app->instance('App\Repositories\VisitorStatisticRepository',$visitorRepositoryMock);
    $visitorRepositoryMock->shouldReceive('setLog')->once();

    $visitorAction = new VisitorStatisticAction($visitorRepositoryMock);
    $this->assertEquals(true,$visitorAction->setLog('fars'));
}

I call setLog in VisitorStatisticAction class with an string input
in VisitorStatisticAction i have this :
public function setLog($organizationSlug)
{
    dd($this->repository->setLog($organizationSlug));
    if (!$this->repository->setLog($organizationSlug)) {
        return false;
    }
    return true;
}

I don't know why dd($this->repository->setLog($organizationSlug)); is return null
setLog in repository is this :
public function setLog($organizationSlug)
{
    $visitor = new VisitorStatistic();
    $visitor->organization_slug = $organizationSlug;
    $visitor->ip = request()->ip();
    $visitor->url = url()->current();
    $visitor->save();
    return $visitor;
}

A: I found the answer :)
Add andReturn() and it returns right answer
$visitorRepositoryMock->shouldReceive('setLog')->once()->andReturn(new VisitorStatistic());


text:
Q: Open Circuit Voltage Calculation I am trying to find out why this system:

should have an Open Circuit Voltage of:
\$U = U0 + I0*R2 + 0*R3\$
\$  = U0 + I0R2\$
I understand why the R3 component doesn't change anything but I fail to understand why R1 isn't contributing anything.
To be clear with all of you. This is an old exam question that I'm using to study for the test but can't find the answer in either the textbook or in the lecture material.
Thanks in advance

A: Start with KVL,

-U0 - I0R2 + 0*R3 + U = 0
U = U0 + I0R2

A: Look at the current source and where the current must flow. It goes through \$R_1\$ and \$R_2\$, right? But when looking at the terminals \$A\$ and \$B\$, they only see the voltage of \$U_0\$ plus the drop across \$R_2\$. The drop across \$R_1\$ exists, but it doesn't have an impact on the terminals. It just impacts the potential difference across the current source. And terminals \$A\$ and \$B\$ don't care about that part of it.
Just walk through by summing the voltages around the loop from \$B\$ to \$A\$. No \$R_1\$ in there, right?

A: *

*Short out the part with no current flowing ( Open circuit ) like R3

*Short out the R values in series with a current source like R1 because it has no effect on the voltage drop on R2 in that single loop.

*now what do you get?


text:
Q: How to solve the import cycle using an interface in Golang? I have encountered an import cycle problem @icza and I am trying to use the interface to solve this but after going through some resources, I still didn't understand properly and it is giving me an error that
Error
runtime: goroutine stack exceeds 1000000000-byte limit runtime: sp=0xc020160360 stack=[0xc020160000, 0xc040160000] fatal error: stack overflow
file1.go
package dir1

type Functions interface {
    Second(string) string
}

func First(f Functions, message string) string {
    importFile2 := f.Second("second file")
    return "Welcome to " + message + " and message from file 2: " + importFile2
}

file2.go
package dir2

import "github.com/ibilalkayy/app/dir1"

type SecondT struct{}

func (SecondT) Second(message string) string {
    importFile1 := dir1.First(SecondT{}, "first file")
    return "Welcome to " + message + " and message from file 1: " + importFile1
}

main.go
package main

import (
    "fmt"

    "github.com/ibilalkayy/app/dir1"
    "github.com/ibilalkayy/app/dir2"
)

func main() {
    fmt.Println("Hello world")
    first := dir1.First(dir2.SecondT{}, "first file")
    fmt.Println(first)
}


text:
Q: Post запрос используя retrofit Нужно создать POST запрос с отправкой логина,пароля и получением токена, мне порекомендовали retrofit, так как стандартными способами это не получается сделать. Но я не понимаю как в нем создается запрос (документацию смотрел), к примеру
public interface API {
   @POST("/v1/registration")
   Response registerUser();
}

Но я не понимаю как минимум , где ссылка на сайт и где задаются параметры запроса. Тут я вижу запрос на регистрацию пользователя, но где все данные? он берет их из метода?
UPD:
   public interface API {
    @POST("/v1/registration")
    Response registerUser(@Body RegistrationBody registrationBody);
    Call<RegistrationResponse> registerUser();
}
public class RegistrationBody{
    public String login;
    public String password;
}
public class RegistrationResponse {
    public String token;
}
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://myserver1.com")
        .build();
API api = retrofit.create(API.class);
@POST("/v1/registration")
Call<RegistrationResponse> registerUser(@Body RegistrationBody registrationBody) {
    return null;
}
Call<RegistrationResponse> call = api.registerUser();
call.enqueue(new Callback<RegistrationResponse() {
    @Override
    public void onResponse(Response<RegistrationResponse> response) {
        if (response.isSuccess()) {
            // tasks available
        } else {
            // error response, no access to resource?
        }
    }

есть ошибки начиная с call.enqueue

A: Например у нас есть сервер с POST методом регистрации - https://myserver1.com/v1/registration
Например данный метод принимает Json вида:
{
  "logins": "ttt",
  "password": "123"
}

и возвращает ответ вида
{
    "token":"someToken"
}

Тогда в проекте надо определить интерфейс, описывающий данный метод сервера таким образом
public interface API {
   @POST("/v1/registration")
   RegistrationResponse registerUser(@Body RegistrationBody registrationBody);
}

Где RegistrationBody и RegistrationResponse это классы со следующими полями:
public class RegistrationBody{
    public String login;
    public String password;
}

public class RegistrationResponse {
    public String token;
}

Далее для обращения к серверу сначала необходимо создать объект Retrofit куда необходимо передать имя сервера и любую другую дополнительную информацию.
Retrofit retrofit = Retrofit.Builder()
                .baseUrl("https://myserver1.com")
                .build();

После, из этого объекта можно получить реализацию интерфейса с методами
API api = retrofit.create(API.class);

Ну и далее у объекта api вызывать нужные методы. Только помните, что нельзя лезть в интернет в основном потоке. Что бы вынести обращение к серверу в отдельный поток можно воспользоваться средствами, которые предоставляет Retrofit. Для этого надо в интерфейсе возвращаемый параметр обернуть в тип Call
@POST("/v1/registration")
Call<RegistrationResponse> registerUser(@Body RegistrationBody registrationBody);

и потом вызвать
Call<RegistrationResponse> call = api.registerUser(...);
call.enqueue(new Callback<RegistrationResponse() {
    @Override
    public void onResponse(Response<RegistrationResponse> response) {
        if (response.isSuccess()) {
            // tasks available
        } else {
            // error response, no access to resource?
        }
    }

    @Override
    public void onFailure(Throwable t) {
    }
}

UPD:
В метод api.registerUser(...) необходимо передать объект RegistrationBody предварительно заполнив его данными:
RegistrationBody body = new RegistrationBody();
body.login = "myLogin";
body.password = "12345";

api.registerUser(body);

Сериализация происходит с использованием библиотеки GSON, как правильно сериализовать объект, читайте в официальной документации.
Для работы в асинхронном режиме просто в интерфейсе API создайте метод, который будет возвращать Call<T> вместо T


text:
Q: How to select key name dynamically? I have a variable as follows:
var test={
    line1:"1",
    line2:"2"
}

How can I access those keys dynamically ? like I want to do :
test."line"+1 ="3";

Thanks

A: It's
test['line'+1] = '3'

The dot syntax does not allow computed keys.

A: test.line1=3;
will do the necessary.

A: you need to use bracket notation, since you have a variable key
test["line"+1] ="3";

A: To access keys like that, you need to use the square bracket syntax eg
test["line" + 1] = 3

A: in order to acces elements you have to correct the code like this
test["line"+1] ="3";


text:
Q: How do I configure Git to automatically pull from origin on branch change? When I switch branches, I'd like to always pull the latest changes from origin if local is clean and behind its origin counterpart. The local branch is a tracking branch of its remote branch, and fetch works as intended.

*

*Can Git be configured to do this automatically?

*Is there a repository-wide setting to do this for all branches? (Our branches are frequently created and deleted as company policy is one branch per task which is PR'd and merged when reviewed)

EDIT:
For context, I use Visual Studio 2017 and mostly its user interface to perform Git commands. There's no problem keeping Git up-to-date. There are a few Git commands that I need to do using the command-line, such as renaming a branch, or hidden repo settings.
When I say the "local is clean", yes that refers to the worktree from git status, and in VS where there are no outgoing commits or locally modified files. VS has a very nice UI which shows you this information in real-time.
By

(Our branches are frequently created and deleted as company policy is
  one branch per task which is PR'd and merged when reviewed)

This was supposed to be an off-hand way of saying "I really don't want to set this setting or hook up for every single branch", but the explanation is:
We create our own local branches split off of a master branch to fulfil a task. In VS, this is "Create local branch from..." which performs a checkout of the branch with the desired name.
Under the hood, I'm sure this is equivalent to git checkout -b fillcatnip master. fillcatnip is an untracked local branch until pushed to the remote, but it'll be pushed as a new branch fillcatnip rather than to the original master. At that point, it becomes a tracking branch and can be given a pull request (PR) to be merged back into master when the task has been completed.
BUT if master has moved on and conflicted before the PR can be fulfilled, then the branch cannot be merged until the conflicts have been resolved. By the time this happens, I may have already begun another task. Hence, if I save the task I'm currently on (commit & push, stash, whatever), then switch back to the conflicted branch, I'd like that branch's remote copy and not my own local copy, as somebody may have pushed changes to it while it's been awaiting merging.

A: You need a git hook — in your case it's post-checkout hook. In the hook you call git pull.
Something like this:
#!/bin/sh

prev_HEAD="$1"
new_HEAD="$2"
new_branch="$3"

if [ "$new_branch" = 1 ]; then
    git pull origin "$new_HEAD"
fi

exit 0

A: The answers to the two questions are "not exactly" and "no", but also "normally there's no need", and in fact, the question itself does not make a lot of sense as asked.  The first and largest problem lies in the phrase "if local is clean"—what, precisely, does this mean?
If "clean" refers to what git status reports:
On branch master
Your branch is up-to-date with 'origin/master'.

nothing to commit, working tree clean

then "clean" refers to the work-tree, and sometimes perhaps to the index, as compared to each other and/or the HEAD commit.
Unless you use git worktree add to create auxiliary work-trees, there's only one work-tree (and one corresponding index) for any given Git repository.  (If you do use git worktree add, each added work-tree is on its own separate branch.  That might in fact be the answer you are really looking for, here.)
Let's note here as well that a branch name like master or feature denotes one particular commit, which Git calls the tip commit of that branch.  There are other meanings for the word "branch": see What exactly do we mean by "branch"?  But when you have a branch checked out, what this implies is that you have one particular commit checked out as well.  That commit's contents fill the index and the work-tree.
The command that switches branches—or to a "detached HEAD"—is git checkout.  It accomplishes the branch-switching (or HEAD-detaching) by writing, into the index and the work-tree, whatever is needed to achieve the switch from the commit you had checked-out before, to the commit you will have checked-out now.  If the work-tree was clean before the git checkout, this is always possible, and the work-tree will be clean after the git checkout as well.
If the work-tree is not clean before the git checkout, it's sometimes, but not always, still possible to switch branches: see Checkout another branch when there are uncommitted changes on the current branch.  In that case, the work-tree will generally also be not-clean after the git checkout has switched branches.  The not-clean-ness will be because the checkout, when switching branches, did not have to update the index and work-tree entries for the files that did not match the commit that you had checked out just before you ran git checkout branchname.
Checking if the work-tree is clean
With the above out of the way, note that git-sh-setup, a script that is available to other Git scripts, includes a function named require_clean_work_tree.  You can examine this code, or simply use it, to determine whether a work-tree is clean.
You can combine this with phd's answer about using a post-checkout hook to do the check and, if appropriate, run git merge or git fetch && git merge.  (I recommend avoiding git pull entirely: break it down into its two separate steps like this.  Your life will be happier afterward.)
Why I suspect you should not need this at all

(Our branches are frequently created and deleted as company policy is one branch per task which is PR'd and merged when reviewed)

As a general rule, if you're not going to work on a named branch (make new commits on it), you should not create it in the first place.  Having not created it, you never need to worry about updating it either.
Suppose, for instance, that you have a repository with one remote named origin, and on origin, there are branches for various tasks.  You want to inspect origin/task/feedkittens occasionally, but work on the (single) task task/fillcatnip.
In this case, to inspect things, go ahead and use the "detached HEAD" mode:
git checkout origin/task/feedkittens

To work on things, use git checkout to create task/fillcatnip from origin/task/fillcatnip:
git checkout task/fillcatnip

This works because git checkout will, if you ask it to check out a branch that doesn't exist, search for an origin/ branch that otherwise has the same name.  If so, it will create the local branch such that the branch tip commit is the same as the remote-tracking name's commit.  At the same time, it will set up the local branch to track (have as its upstream) the remote-tracking name.
By creating the local branch name, you can now create new commits.  These will make the local branch
By avoiding creating task/feedkittens, you can just run git fetch and git checkout origin/task/feedkittens to see the latest.  You will be in "detached HEAD" mode, so it's usually a bad idea to create new commits now, but this means there's no need to drag around a local branch.
When the branch named task/feedkittens is deleted on origin, you can have your own remote-tracking name get deleted automatically during git fetch by setting:
git config fetch.prune true

As soon as you git checkout some other commit or name, you stop being detached-HEAD on the origin/task/feedkittens commit that no longer has a name.
If you want to work on (as in "add commits to") multiple different branches simultaneously, consider using git worktree add, as long as your Git is at least version 2.5.  Each added work-tree has its own private index, but all the added work-trees share the single underlying repository.  If your Git is too old, consider just making separate clones for each branch you want to work on at once.


text:
Q: C# Reflection: Is it possible to view the code of a constructor gained using reflection?
Possible Duplicate:
c# Can I use reflection to inspect the code in a method?

So I am messing around with reflection and something struck me. Is it possible to view the code of a constructor obtained using the GetConstructor() method without navigating to the file and viewing it in visual studio. Is it possible for example to get the ConstructorInfo object and then print out the code that is associated with that constructor  to the console window? Might seem a silly question but I have never really needed to look into reflection before so I am pretty new to it and am not sure as to how much it is capable of.
Also as a side note what is it that determins which constructor will be used as the default? Is it just the one with the least parameters?

A: Basically, code is only available in form of MSIL instructions. See Can I use reflection to inspect the code in a method? for more info.


text:
Q: TcpClient Only Returns First Result in Spring WebFlux Controller I have an HTTP service exposing a GET endpoint that connects to a simple echo server via TCP. The HTTP service is running on Netty.
@RestController
public class OurTcpClient {

    private Connection connection;

    @GetMapping("echo1")
    public Mono<String> echo(@RequestParam("value") final String value) {
        this.connection.outbound()
            .sendString(Mono.just(String.format("%04d", value.length()) + value)) // prepend length
            .then()
            .subscribe();
        return this.connection.inbound()
            .receive()
            .asString()
            .next();
    }

    @PostConstruct
    public void init() {
        this.connection = TcpClient.create()
            .host("localhost")
            .port(10002)
            .wiretap(true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .connectNow();
    }
}

My expectation is that I can query the service at, for example, http://localhost:8081/echo1?value=hi, as many times as I like, and receive "hi" back in each response. This works for the first request. The second request hangs indefinitely. If I then cancel the second request and attempt another, I get the following error:
{
    "timestamp": "2020-04-13T18:56:40.221+0000",
    "path": "/echo1",
    "status": 500,
    "error": "Internal Server Error",
    "message": "Only one connection receive subscriber allowed."
}

Any help would be greatly appreciated.

A: In the example you use next()
return this.connection.inbound()
            .receive()
            .asString()
            .next();

According to the Flux#next javadoc Emit only the first item emitted by this Flux, into a new Mono., then the subscription will be canceled.
In the context of Reactor Netty when you use next, timeout, take etc. operators that cancel the subscription this means that the connection will be closed.


text:
Q: Cómo limitar registros agrupados por columnas Estoy intentando implementar una consulta en la que como máximo pueda tener 4 empresas para la misma fecha y el mismo intervalo horario (estas no han de ser distintas). El problema es que la consulta no muestra lo que se espera. Es decir, en la lista de abajo, en vez de las 5 primeras filas, deberían ser 4, pues ya se habría superado el límite. ¿Cómo podría hacer la consulta?
Lista completa

Consulta
$query = $this->db->query('SELECT * FROM entregas
        JOIN intervaloshorarios on entregas.idIntervaloHorario= intervaloshorarios.idIntervaloHorario
        GROUP BY entregas.fechaCita, intervaloshorarios.intervaloHorario <= 4
        ORDER BY entregas.fechaCita asc
    ;');

Lista después de la consulta

A: En MySql tendras que seleccionar la consulta y limitarla a los 4 primeros registros
 SELECT * FROM entregas order by empresa desc limit 4

En cambio en sql es tan simple como:
SELECT top 4 * FROM entregas


text:
Q: Linear Algebra - Using 2 Transition matrices to find the 3rd transition matrix If Given the transition matrices:
$$
 P_{A \rightarrow B} \begin{bmatrix}
3 &1 \\ 5 & 2
\end{bmatrix}
 P_{B \rightarrow C} \begin{bmatrix}
7 &2 \\ 4 & -1
\end{bmatrix}
$$
How would one determine the transition matrix of A to C?
My first intuition was to premultiply the second to the first.
Any help would be appreciated.

A: Usually the action of a matrix on a vector is represented as a left multiplication (rows by columns) of the matrix by the vector: $P \vec v$ . In this case you are right: we have
$$
P_{A\to C}=P_{B\to C}P_{A\to B}
$$


text:
Q: Can't install printer After upgradeing my system to Ubuntu 15.04 I can't my printer (Canon 4350d).
I add my printer via localhost:631 (cups) but it's not added at System -> Printers.
Cups displays all printers on the network, but I can't print and can't add printer in System -> Printers.

A: Try setting the "Share This Printer" option within the CUPS settings of the printer.
This made my printers available after upgrading to 15.04.
I hope this solves the problem for you.


text:
Q: Formula for increment text value I have the column with a combination of text and number - T-00001. I would like to have the formula to get T-00002, T-00003, and so on. I tried to use CONCATENATE("T-",RIGHT("T-00001",5)+1) but I get T-2, without 4 nulls. Is it possible to receive it in the correct format?

A: if you want to drag it use:
=TEXT(ROW(A1), "T-00000")

if not, use:
=INDEX(IF(A2:A="",,TEXT(ROW(A1:A), "T-00000")))

if you plan empty rows use:
=INDEX(IF(A2:A="",,TEXT(COUNTIFS(A2:A, "<>", ROW(A2:A), "<="&ROW(A2:A)), "T-00000")))

for fixed range:
=INDEX(TEXT(SEQUENCE(20), "T-00000"))

to increment ony with each unique:
=INDEX(IFNA(TEXT(VLOOKUP(A2:A, {UNIQUE(FILTER(A2:A, A2:A<>"")),
 SEQUENCE(COUNTUNIQUE(A2:A))}, 2, 0), "T-00000")))


text:
Q: Do we still require separate licence for TeamExplorer as Standalone client if already have vs2010 We have Visual Studio 2010 premium edition on our systems and Can succesfully use Team Explorer build in it. But I want to use Team explorer separatly. How can I install it separatly without installing VS2010 on some user machines or can we separate vs2010 and team explorer if already installed. Also Do I still need to have separate licence for this per user. I know we have Team web access but need team explorer independently.
Please guide.
I have read the following posts but still not clear:

*

*Standalone GUI client for TFS 2010 Source Control

*Does the free Team Explorer client work without Visual Studio

A: If you have a TFS Client Access License (CAL) for these users, then you can use the standalone Team Explorer at no additional cost.
You should already have a CAL for those users if they're using TFS Web Access, so yes, they should be able to use the standalone Team Explorer.


text:
Q: Erro ao fazer consulta no MYSQL Estou tentando fazer uma consulta e retornar para o usuário via Ajax e está sendo exibidos os seguintes erros:

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in line 77 --> while($experiencia = mysqli_fetch_assoc($resultado)){

Warning: Invalid argument supplied for foreach() in line 89 --> foreach($resultado as $valor){

MEU AJAX:
jQuery(document).ready(function($){
  $('.enviar').click(function(){
      $.ajax({
      url: '<?php bloginfo("template_url") ?>/consulta.php',
      type: 'POST',
      data: 'nome=' + $("#nome").val() + '&email=' + $("#email").val() + '&estilo=' + $("#estilo").val() + '&experiencia=' + $("#experiencia").val() + '&altura=' + $("#altura").val() + '&peso=' + $("#peso").val(),
      error: function(){
          alert('ERRO!!!');
      },
      success: function(data){
          $('#resultado').html(data);
      }
    });
  });
});

CONSULTA.PHP
include "banco.php";
function BuscaAlgo($conectar){

$query = "SELECT  USU.usuario,
                 USU.nome,
                 USU.exp,
                 USU.altura,
                 USU.peso,
                 PRAN.exp_ref,
                 PRAN.altura_ref,
                 PRAN.peso_ref,
                 PRAN.tipo_prancha,
                 PRAN.tamanho_prancha,
                 PRAN.meio_prancha,
                 PRAN.litragem_prancha
                  FROM DADOS_USUARIO AS USU
                       INNER JOIN PRANCHA AS PRAN
                           on USU.exp = PRAN.exp_ref
                            WHERE USU.altura = PRAN.altura_ref
                              AND USU.peso = PRAN.peso_ref
                                ORDER BY USU.usuario DESC LIMIT 1";

$resultado = mysqli_query($conectar,$query);

$retorno = array();

while($experiencia = mysqli_fetch_assoc($resultado)){
  $retorno[] = $experiencia;
}
return $resultado;
}

$resultado = array();
$resultado = BuscaAlgo($conectar);

foreach($resultado as $valor){
  echo $valor["usuario"]; print(".  .  .  .");
  echo $valor["nome"]; print(".  .  .  .");
  echo $valor["exp"]; print(".  .  .  .");
  echo $valor["altura"]; print(".  .  .  .");
  echo $valor["peso"]; print(".  .  .  .");
  print("///////");
  echo $valor["tipo_prancha"]; print(".  .  .  .");
  echo $valor["tamanho_prancha"]; print(".  .  .  .");
  echo $valor["meio_prancha"]; print(".  .  .  .");
  echo $valor["litragem_prancha"];
}

BANCO.PHP:
<?php

$bdServidor = '127.0.0.1';
$bdNome = 'word1';
$bdUsuario = 'root';
$bdSenha = '';

$conectar = mysqli_connect($bdServidor,$bdUsuario, $bdSenha, $bdNome);

if (mysqli_connect_errno($conectar))
{
    echo "Problemas para conectar no banco. Verifque os dados!";
    die();
}

O que estou fazendo de errado?
ENCONTREI O ERRO
O erro estava nas tabelas do meu banco. Algumas delas estavam diferentes das que eu tinha declarado no SELECT. Problema resolvido. Tanto o SELECT quanto o retorno dele estão corretos e funcionais.

A: Sua consulta está errada e a função está retornando false. É sempre bom verificar após a consulta se a mesma foi feita corretamente.
$resultado = mysqli_query($conectar,$query);
if( !$resultado )
{
    die("Consulta falhou.");
}

E eu acredito que você queira retornar a varíavel $retorno na função BuscaAlgo().
Se você quiser fazer JOIN com mais de uma referência use INNER JOIN PRANCHA AS PRAN ON USU.exp = PRAN.exp_ref AND USU.altura = PRAN.altura_ref AND USU.peso = PRAN.peso_ref

A: Você está usando a tabela PRANCHA AS PRAN no WHERE mas só setou ela para o INNER JOIN, você deve setar ela da seguinte forma:
SELECT  USU.usuario,
             USU.nome,
             USU.exp,
             USU.altura,
             USU.peso,
             PRAN1.exp_ref,
             PRAN1.altura_ref,
             PRAN1.peso_ref,
             PRAN1.tipo_prancha,
             PRAN1.tamanho_prancha,
             PRAN1.meio_prancha,
             PRAN1.litragem_prancha

             FROM

             PRANCHA AS PRAN1,

             DADOS_USUARIO AS USU

             INNER JOIN PRANCHA AS PRAN2 on USU.exp = PRAN2.exp_ref

              WHERE

              USU.altura = PRAN1.altura_ref

              AND USU.peso = PRAN1.peso_ref

              ORDER BY USU.usuario DESC LIMIT 1


text:
Q: uWSGI runs Python 2 with Plugin Python36 -> doesn't find Django in Venv I'm trying to setup a simple Django project with Nginx, uWSGI on my Centos7-Server with this Tutorial:
How to Serve Django Applications with uWSGI and Nginx on CentOS 7
But I've tried to change this project into running Django 2 with Python 3.6
Everything worked pretty well, till creating firstsite.ini file.
  1 [uwsgi]
  2 project = firstsite
  3 username = user
  4 base = /home/%(username)
  5 plugins-dir = /usr/lib64/uwsgi/
  6 plugin = python36
  7 virtualenv = %(base)/Env/%(project)
  8 chdir = %(base)/%(project)
  9 home = %(base)/Env/%(project)
 10 module = %(project).wsgi:application
 11
 12 master = true
 13 processes = 5
 14
 15 uid = %(username)
 16 socket = /run/uwsgi/%(project).sock
 17 chown-socket = %(username):nginx
 18 chmod-socket = 660
 19 vacuum = true

There I got stuck into. While setting up and trying to reach the Django Site I got an Internal Server Error. After checking error-log files and messages, I've implemented logto into my .ini file::
   21 #Error Logs
   22 logto = %(base)/%(project)/error.log

after checking this file it tells me this Error-Message::
*** Starting uWSGI 2.0.18 (64bit) on [Wed Aug 14 13:27:24 2019] ***
compiled with version: 4.8.5 20150623 (Red Hat 4.8.5-36) on 23 July 2019 10:27:56
os: Linux-3.10.0-957.21.3.el7.x86_64 #1 SMP Tue Jun 18 16:35:19 UTC 2019
nodename: ip-172-31-34-37.eu-central-1.compute.internal
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 1
current working directory: /etc/uwsgi/sites
detected binary path: /usr/bin/uwsgi
chdir() to /home/user/firstsite
your processes number limit is 3775
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uwsgi socket 0 bound to UNIX address /run/uwsgi/firstsite.sock fd 3
setuid() to 1001
Python version: 2.7.5 (default, Jun 20 2019, 20:27:34)  [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
Set PythonHome to /home/user/Env/firstsite
*** Python threads support is disabled. You can enable it with --enable-threads ***
Python main interpreter initialized at 0x234f0e0
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 437520 bytes (427 KB) for 5 cores
*** Operational MODE: preforking ***
Traceback (most recent call last):
  File "./firstsite/wsgi.py", line 12, in <module>
    from django.core.wsgi import get_wsgi_application
ImportError: No module named django.core.wsgi
unable to load app 0 (mountpoint='') (callable not found or import error)
*** no app loaded. going in full dynamic mode ***
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 21976)
spawned uWSGI worker 1 (pid: 21978, cores: 1)
spawned uWSGI worker 2 (pid: 21979, cores: 1)
spawned uWSGI worker 3 (pid: 21980, cores: 1)
spawned uWSGI worker 4 (pid: 21981, cores: 1)
spawned uWSGI worker 5 (pid: 21982, cores: 1)

If I manually try to get this django project runing with the same Env, there is no problem. So  I thought that it could be because of the fact that uwsgi is running Python 2.7.5 instead of Python 3.6.
I also checked the plugin python with uwsgi --plugin python36 -s:0
*** Starting uWSGI 2.0.18 (64bit) on [Thu Aug 15 04:16:19 2019] ***
compiled with version: 4.8.5 20150623 (Red Hat 4.8.5-36) on 14 August 2019 14:16:35
os: Linux-3.10.0-957.21.3.el7.x86_64 #1 SMP Tue Jun 18 16:35:19 UTC 2019
nodename: ip-172-31-34-37.eu-central-1.compute.internal
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 1
current working directory: /usr/lib64/uwsgi
detected binary path: /usr/local/bin/uwsgi
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 3775
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uwsgi socket 0 bound to TCP address :37796 (port auto-assigned) fd 3
Python version: 3.6.8 (default, Apr 25 2019, 21:02:35)  [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
*** Python threads support is disabled. You can enable it with --enable-threads ***
Python main interpreter initialized at 0x17756c0
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 72920 bytes (71 KB) for 1 cores
*** Operational MODE: single process ***
*** no app loaded. going in full dynamic mode ***
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI worker 1 (and the only) (pid: 6476, cores: 1)

So it looks to me, that I've created my 36-plugin the right way.
Would be really grateful if someone could help me out.

A: this is where the real problem is it can't find django
are you sure that django is installed in that environment you mentioned?
i mean "Env"
Traceback (most recent call last):
  File "./firstsite/wsgi.py", line 12, in <module>
    from django.core.wsgi import get_wsgi_application
ImportError: No module named django.core.wsgi

in that link you mentioned i couldn't find
virtualenv = %(base)/Env/%(project)

try changing it to
virtualenv = %(base)/Env

if that didnt solve your problem please specify django, python versions you are using plus your project structure


text:
Q: Override Fragment functions on Xamarin Android if fragment is created using Forms Embedding I have created a forms page in Xamarin and used that page as a fragment using Xamarin Forms Embedding.
var fragment = new FormsPage().CreateFragment(context);

I would like to override the OnBackPressed() control in Android version of the app.
What's the best possible way to do it as I can't override it inside the Xamarin Forms Page.

A:
I would like to override the OnBackPressed() control in Android version of the app.

You could override OnBackButtonPressed in Xamarin.Forms, this event also be raised when the hardware back button is pressed in Android and this event is not raised on iOS.
If you want remove fragment from the stack in OnBackPressed() method, you could override this method in your Activity like this :
public override void OnBackPressed()
{
    base.OnBackPressed();
    if (FragmentManager.BackStackEntryCount != 0)
    {
        FragmentManager.PopBackStack();
    }
    else
    {
        base.OnBackPressed();
    }
}


text:
Q: Why does gcc use stack area without decrementing stack pointer? For this simple C program,
int test(int a,int b)
{
    int k=89;
    return a+b;
}
int main()
{
    test(5,3);
}

gcc 10 produces the following assembly code (using https://godbolt.org/ and verified on my machine):
test:
        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp-20], edi
        mov     DWORD PTR [rbp-24], esi
        mov     DWORD PTR [rbp-4], 89
        mov     edx, DWORD PTR [rbp-20]
        mov     eax, DWORD PTR [rbp-24]
        add     eax, edx
        pop     rbp
        ret
main:
        push    rbp
        mov     rbp, rsp
        mov     esi, 3
        mov     edi, 5
        call    test
        mov     eax, 0
        pop     rbp
        ret

As you can see, gcc is using stack area without decrementing stack pointer.
Is this normal? Isn't gcc supposed to decrement esp before using stack area?


text:
Q: Overlay of any app is positioned incorrectly  Here's an image of a problem I got when bought a second monitor. It does not appear on my primary one. Has anyone ran into the same problem? Any app with overlay, downloaded from app store, is behaving itself the same way. Things 3, Telegram for instance.
Software update, smc and nvram resets proved themselves useless as usual
Ventura 13.0.1 (22A400), MacBook Air M1 16gb


text:
Q: Can I use a network switch/bridge to "convert" a WPA2-Enterprise access point to WPA2-Personal? I moved into a college dorm that provides WiFi with WPA2-Enterpise+PEAP - every student must supply an individual username and password to connect to the university network. One of my devices, a game console, does not support WPA2-Enterprise, only WPA2-Personal. Normally one would simply get a network switch that connects to the host network via WAN and connect the local devices via LAN/WLAN, but there are no LAN ports available to plug my own switches/routers to.
My idea is to have a switch that connects to the school network via WPA2-Enterprise+PEAP like a normal computer would, but then hosts another access point that uses something simpler that my other devices can support (either LAN or WPA2-Personal).
Which then brings the question: what do I need to set up a WLAN-to-(W)LAN switch with different authentication protocols? I've only configured LAN-to-(W)LAN switches before and I don't know what kind of features I should be looking for when buying a network switch that lets me do the above. Googling "WiFi-to-WiFi switch" yields either LAN-to-WLAN switches or other irrelevant results.
Postscript: I have read similar questions on Superuser but they concern extending the same network with the same authentication/encryption protocols, which is not the case here.

A: 1) If your console has a wired network port (it's ambiguous in your question whether "no LAN ports" refers to your dorm or your console), you could use a wireless bridge. Basically, a wireless bridge acts like a reverse-access-point - the wireless bridge connects to the existing WLAN, and provides a wired network port for you to connect to, seamlessly moving the traffic from the WLAN to the wired port and vice versa. See https://kb.netgear.com/227/What-is-a-wireless-bridge for a picture and possibly a better explanation. Just google "wireless bridge" and choose one that supports WPA2-Enterprise (or use OpenWRT).
2) If your console doesn't have a wired network port, you could bridge two WLANs - the WPA2-Enterprise WLAN you're trying to join, with a new WPA2-Personal WLAN you would create. You could do it with two devices, using a wireless bridge (see my first suggestion above) wired to a separate access point which you have configured with WPA2-Personal. Or, if you choose the right device, you could do it with one device, basically doing the above internally (OpenWRT can do this, especially if you get a device with two separate radios, some radios can do this simultaneously on just the one radio but that can be tricky to verify before you buy).


text:
Q: How to use ember select for static dropdown? This has to be easy, but I'm failing.
I have this in a template:
<select {{action 'setType' this value="target.value"}}> <!-- I've tried various things for the value -->
  <option value="0">Choice 1</option>
  <option value="1">Choice 2</option>
</select>

I have this in a controller:
setType: function(mymodel, type) {
  mymodel.set('type', type);
  mymodel.save();
}

The action is firing, the model is available, but none of my guesses are sending the value of the select to the controller action.
I'm using Ember 1.13.7

A: You need to link your action to the event onchange:
<select onchange={{action "setType" value="target.value"}}>

Also, take into account that you are naming value the parameter that the action will receive and you aren't sending the model in that action as a parameter.


text:
Q: How to install Microsoft Access Database Engine or OLEDB to Azure SQL Database I wanted to know how can I install Microsoft Access Database Engine or OLEDB to my azure sql server. I need to read excel file using Stored Procedure in Azure SQL which shows error for missing OLEDB provider. In local system installing Microsoft Access Database Engine setup solved the issue but not sure about azure sql.

A: In short, you cannot. The Azure SQL PaaS offering does not allow for external installations. You will have to use a secondary system to do the transfer of Excel data into SQL Azure DB. If you are just trying to copy the data in SSMS has a powerful import data wizard. If you need an automated process I would check into Data Factory.
Another option would be to run SQL Server in an VM but depending on your database size that may be overkill.


text:
Q: Link between Models in Django I am new to Django. I wanted to know how to link data of the foreign key. Here is the code.
 class CreateSchool(models.Model):

        schoolName = models.CharField(primary_key=True, max_length=250)

    class SchoolDetails(models.Model):

        createSchool = models.OneToOneField(CreateSchool,to_field='schoolName')

        principalName = models.CharField(max_length=250)

        schoolAddress = models.CharField(max_length=500)

    class kidDetails(models.Model):

        schoolUID = models.ForeignKey(SchoolDetails,to_field='schoolUID')

        childName= models.CharField(max_length=245)

        childUID = models.CharField(max_length=245)

my question is when i enter the details of the kid, how to store the kids data with respect to schoolDetails and createschool model from the UI.
When i do it from admin panel, it dont allow me to save kids data unless i create a school and schooldetails.
For example, I need to store kid A in 1 school and i want to store kid 2 in 2 school. How to achieve this. I am completely beginner.  Any help would be great.

A: See the example below:
class PaymentPlan():

  name = models.CharField(max_length=200)
  amount = models.FloatField(null=True)
  discount = models.FloatField(null=True)
  discount_amount = models.FloatField(null=True)
  no_of_users = models.CharField(null=True,max_length=100)
  no_of_brands = models.CharField(null=True,max_length=100)
  no_of_jobs = models.CharField(null=True,max_length=100)
  payment_data = models.CharField(null=True,max_length=100)
  plan_type = models.CharField(null=True,max_length=100)

class AccountSubscriptionDetail():
  plan = models.ForeignKey(PaymentPlan, related_name="plan_data")
  expiry_date = models.DateTimeField(default=timezone.now)
  charge = models.CharField(null=True,blank=True,max_length=100)
  billing_cycle = models.CharField(null=True,blank=True,max_length=100)
  account = models.ForeignKey(Account, related_name="account_sub_data")

Here i have defined foreignkeys connect to other modal you can use in this way