text:
Q: Como manipular un elemento seleccionado en select2 Tengo este código y me gustaría saber cómo guardar los datos seleccionados en una variable para manipularlos como json.
Ya he logrado crear los valores a través de datos json.

function customMatcher(params, data) {
   //show childs if search with parent
          data.parentText = data.parentText || "";
          if ($.trim(params.term) === '') {
              return data;
          }

          if (data.children && data.children.length > 0) {
              var match = $.extend(true, {}, data);

              for (var c = data.children.length - 1; c >= 0; c--) {
                  var child = data.children[c];
                  child.parentText += data.parentText + data.text;

                  var matches = customMatcher(params, child);

                  if (matches == null) {
                      match.children.splice(c, 1);
                  }
              }

              if (match.children.length > 0) {
                  return match;
              }

              return customMatcher(params, match);
          }

          var original = (data.parentText + ' ' + data.text).toUpperCase();
          var term = params.term.toUpperCase();

          if (original.indexOf(term) > -1) {
              return data;
          }

          return null;
      }

  $("#multisearch").select2({
    language: "es",
    closeOnSelect: false,
    matcher: customMatcher,
    placeholder: "Comienza tu búsqueda",
    data: [{
        id: 0,
        text: 'Linea 1',
        children: [{
            id: 1,
            text: 'San Pablo'
          },
          {
            id: 2,
            text: 'Pajaritos'

          },
          {
            id: 3,
            text: 'Las Rejas'
          },
          {
            id: 4,
            text: 'Ecuador'
          }
        ]
      },
      {
        id: 5,
        text: 'Linea 2',
        children: [{
            id: 6,
            text: 'La Cisterna'
          },
          {
            id: 7,
            text: 'El Parrón'

          },
          {
            id: 8,
            text: 'Lo Ovalle'
          },
          {
            id: 9,
            text: 'Ciudad del niño'
          },
          {
            id: 10,
            text: 'Pajaritos'
          }
        ]
      },

    ]
  });

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
 <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
 <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<select multiple id="multisearch" style="width:500px">
  </select>

Deseo poder capturar los valores seleccionados y almacenarlos en una variable con sus datos JSON

A: Buenas tienes que tratar el select como a cualquier otro.
Para obtener los datos usa la function val() de Jquery
 $("#multisearch").val()

Espero te ayude saludos

Para obtener el valor del texto de cada item seleccionado usamos la función each() para iterar cada uno de los valores y agregarlos a un array en el que vamos a combinar el valor con el texto
Espero sea lo que buscas amigo

$("#obtenerDatos").click(function(){
  //console.log($("#multisearch").val())
  var arrayValor = $("#multisearch").val()
  var arrayNombres = []
  $(".select2-selection__rendered").find("li").each(function(index){

    if($(this).text()!=""){
    var valorAnterior = arrayValor[index]
    arrayValor[index] = {
      id:valorAnterior,
      valor:$(this).text().replace("×","")
    }
    }

  })

  console.log(arrayValor)
})

function customMatcher(params, data) {
   //show childs if search with parent
          data.parentText = data.parentText || "";
          if ($.trim(params.term) === '') {
              return data;
          }

          if (data.children && data.children.length > 0) {
              var match = $.extend(true, {}, data);

              for (var c = data.children.length - 1; c >= 0; c--) {
                  var child = data.children[c];
                  child.parentText += data.parentText + data.text;

                  var matches = customMatcher(params, child);

                  if (matches == null) {
                      match.children.splice(c, 1);
                  }
              }

              if (match.children.length > 0) {
                  return match;
              }

              return customMatcher(params, match);
          }

          var original = (data.parentText + ' ' + data.text).toUpperCase();
          var term = params.term.toUpperCase();

          if (original.indexOf(term) > -1) {
              return data;
          }

          return null;
      }

  $("#multisearch").select2({
    language: "es",
    closeOnSelect: false,
    matcher: customMatcher,
    placeholder: "Comienza tu búsqueda",
    data: [{
        id: 0,
        text: 'Linea 1',
        children: [{
            id: 1,
            text: 'San Pablo'
          },
          {
            id: 2,
            text: 'Pajaritos'

          },
          {
            id: 3,
            text: 'Las Rejas'
          },
          {
            id: 4,
            text: 'Ecuador'
          }
        ]
      },
      {
        id: 5,
        text: 'Linea 2',
        children: [{
            id: 6,
            text: 'La Cisterna'
          },
          {
            id: 7,
            text: 'El Parrón'

          },
          {
            id: 8,
            text: 'Lo Ovalle'
          },
          {
            id: 9,
            text: 'Ciudad del niño'
          },
          {
            id: 10,
            text: 'Pajaritos'
          }
        ]
      },

    ]
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
 <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
 <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<select multiple id="multisearch" style="width:500px"  >
  </select>

      <button id="obtenerDatos" type="button" name="button">Obtener datos del select</button>


text:
Q: NullPointerException on a mouseListener method I am trying to write a code that makes a dot with one click, line with two, triangle with three, and restarts on 4, but I keep getting a nullpointerexception on my first click. Here is my code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class TriangleClicker extends JFrame {
    private final int width = 700;
    private final int height = 800;
    private JPanel panel;
    private MouseListener listener;
    private int p1x;
    private int p1y;
    private int p2x;
    private int p2y;
    private int p3x;
    private int p3y;
    private int count = 0;
    private JComponent tri;

public TriangleClicker() {
    this.setSize(width, height);
    this.add(createPanel());
    this.tri = new MousePressListener();
    this.add(this.tri);
    listener = new MousePressListener();
    this.addMouseListener(listener);
}

public JPanel createPanel() {
    panel = new JPanel();
    panel.setSize(width, height);
    return panel;
}

class MousePressListener extends JComponent implements MouseListener  {
    public Graphics g;
    public void drawLine1(Graphics g) {
        g.setColor(Color.BLACK);
        g.drawLine(p1x, p1y, p1x, p1y);
    }

    public void drawLine2(Graphics g) {
        g.drawLine(p1x, p1y, p2x, p2y);
    }

    public void drawLine3(Graphics g) {
        g.drawLine(p3x, p3y, p1x, p1y);
        g.drawLine(p3x, p3y, p2x, p2y);
    }
    @Override
    public void mouseClicked(MouseEvent e) {
    }
    @Override
    public void mouseEntered(MouseEvent e) {
    }
    @Override
    public void mouseExited(MouseEvent e) {
    }
    public void mousePressed(MouseEvent e) {
        if (count == 0) {
            System.out.println("1");
            p1x = e.getX();
            p1y = e.getY();
            drawLine1(g);
            count++;
        }
        else if (count == 1) {
            p2x = e.getX();
            p2y = e.getY();
            drawLine2(g);
            count++;
        }
        else if(count == 2) {
            p3x = e.getX();
            p3y = e.getY();
            drawLine3(g);
            count++;
        }
        else if(count == 4) {
            g.clearRect(0, 0, WIDTH, HEIGHT);
            p1x = e.getX();
            p1y = e.getY();
            p2x = 0;
            p2y = 0;
            p3x = 0;
            p3y = 0;
            drawLine1(g);
            count = 1;
        }
    }
    @Override
    public void mouseReleased(MouseEvent e) {
    }
}
}

My errors are in the makeLine1() method trying to set the color to black, and in the mousePressed() method trying to call makeLine1().
Thanks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiple instances of model components in Java Swing? Until now I had different model classes for the appropriate Java Swing component, for instance I have several TableModel for several JTable. Every JTable has its own TableModel. The TableModel is based on one object (Model), giving all the required data. Something like this:
public class MyTableModel extends AbstractTableModel {

Model model;

But now I would like to make a change. My interface offers the possibility of multiple instances of Model. So my question is, what should I do?

*

*instantiate multiple objects from MyTable

*change dynamically the current reference to the model upon user interaction

So the basic problem I am facing: I want to use the same JTable with the same TableModel. Should I use multiple TableModel or should I use changing references to the data source?

Similar question:
I want to offer multiple tabs, they change the instance of the underlying model. The do not change the type, but the current instance - meaning, the data changes.
Should I now:

*

*instantiate multiple objects of the view components? For instance instantiate for every available model an own JTable, JPanel, JScrollPane object?

*change dynamically by listening to change events on the tabbed pane the reference of the underyling model

A: If the structure of the table stays the same (i.e. same number of columns, same titles, same column classes), and only its content changes, you should keep the same model instance but change the data (and call fireTableDataChanged).
This will be more efficient, and will allow keeping the current column order, the current sorted column, etc.
If the structure of the table completely changes, changing the model itself is probably easier. You could also call fireTableStructureChanged, but the javadoc of this method says :

This is the same as calling
  setModel(TableModel) on the JTable

Regarding the tabs, the same rule can be followed.

A: If you are going to have multiple tabs with a different tab having a different model then the answer is easy, you need different tables.  At least one for each tab.
Again, if you multiple tabs then you will also need multiple JScrollPanes, etc.
However, if you are going to have a single spot for a table, you might be able to get away with a single JTable and multiple models if you aren't doing something custom to the table.  (See mKorbel's comment).   Either way you could reuse the same JScrollPane.


text:
Q: GeoServer GeoFence LDAP : can't get username when select role I have configured my LDAP authentication and LDAP role services in my GeoServer 2.21.1, so I can log in my GeoServer with my LDAP credentials (it's works). Now, I would like to use GeoFence to manage my layers. I installed it (server), so I see the options in my GeoServer GUI and I can create a data rules. Because of my LDAP configuration, in the role list, I see my LDAP role, but when I select it, the username list won't be populate with the members of this group. If I leave the value *, all members of the group got the restriction (it works).
Early in the day, I can list my username, but I don't know what happened because it's the first time since many days that happened and I restarted the server.
My GeoServer logs and Tomcat logs say nothing useful:
Geoserver :
16 032 17:32:36 TRACE  [geoserver.platform] - Found Property override: 'geoserver.xframe.shouldSetPolicy' to be unset
16 032 17:32:36 TRACE  [geoserver.platform] - Found Java environment variable : 'geoserver.xframe.shouldSetPolicy' to be unset
16 032 17:32:36 TRACE  [geoserver.platform] - Found Servlet context parameter : 'geoserver.xframe.shouldSetPolicy' to be unset
16 032 17:32:36 TRACE  [geoserver.platform] - Found System environment variable : 'geoserver.xframe.shouldSetPolicy' to be unset
16 032 17:32:36 TRACE  [geoserver.platform] - Found Property override: 'geoserver.xframe.policy' to be unset
16 032 17:32:36 TRACE  [geoserver.platform] - Found Java environment variable : 'geoserver.xframe.policy' to be unset
16 032 17:32:36 TRACE  [geoserver.platform] - Found Servlet context parameter : 'geoserver.xframe.policy' to be unset
16 032 17:32:36 TRACE  [geoserver.platform] - Found System environment variable : 'geoserver.xframe.policy' to be unset
16 032 17:32:36 DEBUG  [geoserver.security] - Checking match of request : 'Path: /web/wicket/page, QueryString: 258-1.IBehaviorListener.0-form-tabs-panel-roleName'; against '/web/**'
16 032 17:32:36 DEBUG  [geoserver.security] - Matched Path: /web/wicket/page, QueryString: 258-1.IBehaviorListener.0-form-tabs-panel-roleName with /web/**
16 032 17:32:36 TRACE  [geoserver.monitor] - Testing /web/wicket/page for monitor filtering
16 032 17:32:36 DEBUG  [geoserver.monitor] - /geoserver/web/wicket/page was filtered from monitoring
16 032 17:32:36 DEBUG  [geoserver.ows] - Could not find a layer group named web
16 032 17:32:36 DEBUG  [geoserver.ows] - Could not find a layer group named web
16 032 17:32:36 DEBUG  [org.geoserver] - Thread 80 locking in mode READ
16 032 17:32:36 TRACE  [geoserver.platform] - Found Property override: 'CONFIGURATION_TRYLOCK_TIMEOUT' to be unset
16 032 17:32:36 TRACE  [geoserver.platform] - Found Java environment variable : 'CONFIGURATION_TRYLOCK_TIMEOUT' to be unset
16 032 17:32:36 TRACE  [geoserver.platform] - Found Servlet context parameter : 'CONFIGURATION_TRYLOCK_TIMEOUT' to be unset
16 032 17:32:36 TRACE  [geoserver.platform] - Found System environment variable : 'CONFIGURATION_TRYLOCK_TIMEOUT' to be unset
16 032 17:32:36 DEBUG  [org.geoserver] - Thread 80 got the lock in mode READ
16 032 17:32:36 DEBUG  [org.geoserver] - Thread 80 locking in mode READ
16 032 17:32:36 DEBUG  [org.geoserver] - Thread 80 releasing the lock in mode READ
16 032 17:32:36 DEBUG  [geoserver.filters] - Compressing output for mimetype: text/xml;charset=UTF-8
16 032 17:32:36 DEBUG  [filter.GeoServerSecurityContextPersistenceFilter$1] - SecurityContextHolder now cleared, as request processing completed

Tomcat :
[16/Sep/2022:17:35:16 +0200] "POST /geoserver/web/wicket/page?258-3.IBehaviorListener.0-form-tabs-panel-roleName HTTP/1.1" 200 178

And in the browser :
<?xml version="1.0" encoding="UTF-8"?><ajax-response><component id="userName" ><![CDATA[<select id="userName" name="tabs:panel:userName">
<option selected="selected" value="">*</option>
</select>]]></component></ajax-response>

Do you know what can I do to list username of my LDAP role in geofence?


text:
Q: The checkbox doesn't update the bool property from false to true in mvc application The ViewModel has the following code:
public List<MarketingCode> MarketingCodes { get; set; }

Where MarketingCode is of type:
public class MarketingCode
{

    public bool selected
    {
        get;
        set;
    }
    public MarketingOptionCode name { get; set; }
    public string Line { get; set; }
    public string value { get; set; }

    [Flags]//Indicates that an enumeration can be treated as a bit field; i.e., as a set of flags
    public enum MarketingOptionCode
    {

        Email = 1,

        Post = 2,

        SMS = 3,

        Telephone = 4
    }

}

My view has following code to render CheckBoxList:
 @for (int i = 0; i < Model.MarketingCodes.Count(); i++)
                                    {
                                        var name = @Model.MarketingCodes[i].name.ToString();
                                        <label for="@Model.MarketingCodes[i].name" class="checkbox inlineblock">
                                            @Html.CheckBoxFor(model => model.MarketingCodes[i].selected, new { name = @Model.MarketingCodes[i].name.ToString(), @id = @Model.MarketingCodes[i].name.ToString() }) **@* This works totally fine, even if you click the label, the checkbox will be checked. *@**

                                            @Model.MarketingCodes[i].name
                                        </label>
                                    }

As you can see the CheckBoxes are bind with the selected property but it doesn't get update to true when CheckBox is clicked! The same approach works fine if there is only a single CheckBox. But as such I am using a loop it is not working when I read the value of the property MarketingCodes in my controller, all the selected property is false.
The controller code where I am fetching the values from UI:
I have written this private function to call when the index get method fires and also when the post method fires because the viewmodel was not holding any values when the form was posted. And I guess this is the point where all the selected property is set to false.
 private static void BindMarketingOptions(PersonalDetailsIndexViewModel viewModel)
    {
        viewModel.MarketingCodes = new[] {

            new Bike.ViewModels.MarketingCode { name = Bike.ViewModels.MarketingCode.MarketingOptionCode.Email, Line= "line1", value="value1" },
            new Bike.ViewModels.MarketingCode { name = Bike.ViewModels.MarketingCode.MarketingOptionCode.Post, Line= "line2", value="value2"  },
                new Bike.ViewModels.MarketingCode { name = Bike.ViewModels.MarketingCode.MarketingOptionCode.SMS,Line= "line3", value="value3"  },
                    new Bike.ViewModels.MarketingCode { name = Bike.ViewModels.MarketingCode.MarketingOptionCode.Telephone, Line= "line4", value="value4"  }
                    }.ToList();
    }

I have changed the above method to the following to make my selected property work:
private static void BindMarketingOptions(PersonalDetailsIndexViewModel viewModel)
    {
        if (viewModel.MarketingCodes == null)
        {
            viewModel.MarketingCodes = new[] {

            new Bike.ViewModels.MarketingCode { name = Bike.ViewModels.MarketingCode.MarketingOptionCode.Email, Line= "line1", value="value1"},
            new Bike.ViewModels.MarketingCode { name = Bike.ViewModels.MarketingCode.MarketingOptionCode.Post, Line= "line2", value="value2"},
                new Bike.ViewModels.MarketingCode { name = AQuoteBike.ViewModels.MarketingCode.MarketingOptionCode.SMS,Line= "line3", value="value3"},
                    new Bike.ViewModels.MarketingCode { name = Bike.ViewModels.MarketingCode.MarketingOptionCode.Telephone, Line= "line4", value="value4"}
                    }.ToList();
        }
        for (var i = 0; i < viewModel.MarketingCodes.Count(); i++)
        {
            viewModel.MarketingCodes[i].selected = viewModel.MarketingCodes[i].selected;
        }

    }
BindMarketingOptions(viewModel);
for (var i = 0; i <= viewModel.MarketingCodes.Count(); i++)
                {
                    UserField userField = new UserField();
                    if (viewModel.MarketingCodes[i].selected)  //<--FALSE FOR ALL THE CHECKBOXES
                    {
                        userField.Line = viewModel.MarketingCodes[i].Line;
                        userField.Type = viewModel.MarketingCodes[i].name.ToString();
                        userField.Value = viewModel.MarketingCodes[i].value;
                        BikeQuote.BikeRisk.UserFields.Add(userField);
                    }
                }

A: You are changing the name property of each checkbox - which is what the default model binder uses to try bind the data to your model, best let MVC generate that for you e.g.
@for (int i = 0; i < Model.MarketingCodes.Count(); i++)
{
    ...
    Html.CheckBoxFor(model => model.MarketingCodes[i].selected);
    ...
}

A: The answer can be seen in the question itself. Overriding the name of the checkbox was not an issue, instead I want to override the name so that for attribute of label works with the name of the checkbox. So, if a user clicks the label, the checkbox is clicked.
The actual problem was the way I was binding the data to the MarketingCodes property. I have given the old version as well as the updated version. And it works fine now.


text:
Q: How can I pass JSON to client using Node.js + HBS + Express? Consider, I am sending JSON to client as follows in render page of Express (using hbs as a view engine):
res.render('MyPage.html', { layout: false, PageTitle: 'Project Name', JSON_Data: {field1:'value',field2:'value2'}});

I am able to access and set title of html page by using {{PageTitle}}, following is the code.
  <title>{{PageTitle}}</title>

Now I want to show JSON_data into alert popup.
I've tried following way, but getting Uncaught SyntaxError: Unexpected token {, while debugging in chrome is shows var jsonobj = [object Object]
    function fbOnBodyLoad() {
        var jsonobj = {{JSON_data}};
        alert(jsonobj);
    }

Could any body give some idea on How to access JSON_data and show in alert
Advance Thanks

A: to access the inner elements of the json object, try like this
var jsonobj = "{{JSON_data.field1}}";

may be this might solve the issue.
refer
Handlebars.js parse object instead of [Object object]

A: You could always register a Handlebars helper to format the object into a string format (such as by using JSON.stringify), and then use that helper in your view. http://handlebarsjs.com/block_helpers.html

A: For me it worked by doing in the server:
res.render('pages/register', {
                title: 'Register Form',
                messages: req.flash('error'),
                countries:JSON.stringify(countries)
        });

and then I used this countries variables to assign in angular controller like this:
angular.module('languagesApp', []).controller('DemoController', function($scope) {

    $scope.algo = {{-countries}};
...


text:
Q: Trying to run a python script in task scheduler, but it breaks due to request.urlopen(url) My script works in spyder, but when I try and run it in task schedular (using a bat file) it won't action. I believe the reason to be an issue with the URL request and that I might need to use URL Parser... Not sure how this would work for my code though. (API key is not mine but tester)
import urllib.request as request
import json
import pandas as pd

ETFS = ["VTI"]

def Name (ticker):

    url = "https://eodhistoricaldata.com/api/fundamentals/{ticker}.US?api_token=OeAFFmMliFG5orCUuwAKQ8l4WWFQ67YX".format(ticker=ticker)

    with request.urlopen(url) as response:

            source = response.read()
            data = json.loads(source)

    type(data.get('General',{}).get('Name', []))
    len(data.get('General',{}).get('Name', []))
    Name = (data.get('General',{}).get('Name', []))
    return (Name)

resultname = list(map(Name, ETFS))

d = { "Ticker": ETFS, 'Name': resultname}
dfx = pd.DataFrame(data=d)
dfx.to_excel("Equity ETFs.xlsx")


text:
Q: Finding LCM of two nos in C I have created a code for finding LCM of two nos. I think that the code is correct but I have an undesired output. What ks the problem in this code?
#include<stdio.h>
#include<conio.h>

main()
{
int i, j, a, b, lcm;

printf("Enter two nos : ");
scanf("%d %d", &a, &b);

for(i=1; i<=b; i++)
{
    for(j=1; j<=a; j++)
    {
        if(a*i==b*j)
        {
            lcm=a*i;
            break;
        }
    }
}
printf("LCM=%d", lcm);

getch();
}

A: The LCM of two numbers a,b is at least max(a,b) and at most a*b, so your first idea about the boundaries is correct. But if you take a closer look to one of the definitions of LCM (of two positive integers) a and b you'll find that the LCM is the smallest number such that LCM % a = 0 and LCM % b = 0 where "%" means "remainder of integer division, truncating" and that is exactly what you can use here.
Example:
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  int a, b, lcm;

  printf("Enter two nos : ");
  scanf("%d %d", &a, &b);

  /* TODO: checks and balances! */

  /* Set lcm to the larger of the two numbers */
  lcm = (a < b) ? b : a;

  /* check if both "a" and "b" divide "lcm" without a remainder
   * otherwise increment "lcm" */
  for (;;) {
    if ((lcm % a == 0) && (lcm % b == 0)) {
      /* we got the LCM, break out of loop */
      break;
    }
    /* Otherwise increment "lcm" by one */
    lcm++;
  }

  printf("LCM = %d\n", lcm);

  exit(EXIT_SUCCESS);
}

There are more elegant and more general methods but I think the example above is quite easy to follow.


text:
Q: How to add menu link when activate the wordpress plugin? I am developing a Wordpress plugin. I have some links for showing product Brands name and Product categories listing, in the url: http://testsite.com/product-categories and http://testsite.com/brands like that. So I want this link will be auto generated when plugin is activated and place in the default menu in Wordpress. How can I do that. I tried this code but its not working.
register_activation_hook( __FILE__, array( $this, 'myplugin_activate' ) );

public function myplugin_activate() {
    $product_categories = array(
                'post_content'   => '',
                'post_name'      => 'product-categories',
                'post_title'     => 'Product Categories',
                'post_status'    => 'publish',
                'post_type'      => 'nav_menu_item',
            );

    $brands = array(
                'post_content'   => '',
                'post_name'      => 'brands',
                'post_title'     => 'Brands',
                'post_status'    => 'publish',
                'post_type'      => 'nav_menu_item',
            );

    wp_insert_post( $product_categories );
    wp_insert_post( $brands );
}

Can anyone tell me how to do that? One thing I can not do that as page post type.

A: Searching for wp_insert_post and nav_menu_item, I found Programmatically add a Navigation menu and menu items where wp_create_nav_menu is suggested.
Should be a matter of using the functions wp_get_nav_menu_object, wp_create_nav_menu, wp_update_nav_menu_item and get_nav_menu_locations.


text:
Q: How to identify the MAC address of primary physical lan card? I am developing window application in C#. I am using the following code to obtain the MAC address
private void Form1_Load(object sender, EventArgs e)
        {
            lbl1.Text = "Hi";

            string macAddresses = "";

            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (nic.OperationalStatus == OperationalStatus.Up)
                {
                    macAddresses += nic.GetPhysicalAddress().ToString();
                    break;
                }
            }
            lbl1.Text = macAddresses;

        }

In the above code I am not getting the MAC address of the primary lan card. In my computer I created two loopback adapters A & B. I have one physical Lan Card. Now I want to obtain the MAC address of the primary physical Lan Card instead of A & B. How to do this ? Can you please provide me any code or link through which I can resolve the above issue ?

A: Change the condition to:
 // instead of nic.OperationalStatus == OperationalStatus.Up
 nic.NetworkInterfaceType != NetworkInterfaceType.Loopback

Or use this:
    nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet || nic.NetworkInterfaceType  ==  etworkInterfaceType.FastEthernetFx || nic.NetworkInterfaceType ==              NetworkInterfaceType.FastEthernetT

A: I guess you could use this link if you use localhost as the target IP address...
How to get the Mac address


text:
Q: How can I build very big matrix in svg I need to build a matrix of 10000X10000 in canvas/svg. In each cell I need to create a square. I tried to do that with canvas in 2 loops like that:

for(i=0; i<10000; i++){
  for(j=0;j<10000; j++){
    /*some code of drwing*/
    console.log(i,',',j);
  }
}

But this loops take a lot of time. How can I draw big matrix in good performance?
(I need that every cell in the matrix will behave differently depending on the matrix of objects that I get from the database)
Thanks

A: You're most likely best off doing your drawing using canvas, here's why:
While SVG can be rather straight forward to work with, it can easily get expensive to draw (see this article, for example), even if you only do one live DOM insertion as demonstrated below.

function createSvgElement(tag, props) {
  var el = document.createElementNS("http://www.w3.org/2000/svg", tag);
  for (prop in props) {
    el.setAttributeNS(null, prop, props[prop]);
  }
  return el;
}

var svg = document.getElementById('svg');

document.getElementById('input').onclick = function render() {
  var start = new Date();
  var fragment = document.createDocumentFragment();
  for (var x = 0; x < 400; x++) {
    for (var y = 0; y < 400; y++) {
      var circle = createSvgElement('circle', {
        'cx': x,
        'cy': y,
        'r': 0.2,
        'fill': 'red'
      });
      fragment.appendChild(circle);
    }
  }
  svg.appendChild(fragment);
  var time = new Date() - start;
  document.body.appendChild(document.createTextNode(time + 'ms'));
}
svg {
  display: block;
}
<input id="input" type="button" value="render svg" />
<svg id="svg" width="400" height="400"></svg>

The main issue with SVG is, no matter how much you do on your end to reduce work for the browser, in the end, the DOM will still have thousands of elements that the browser has to figure out how to render by itself.

Working with canvas will mean noticeably more work for you, especially if you want to do fancy styles, but as you're relieving the browser of most of the rendering logic (and handling it yourself), it can be a lot faster.

var canvas = document.getElementById('canvas');

document.getElementById('input').onclick = function render() {
  var start = new Date();
  var context = canvas.getContext('2d');
  for (var x = 0; x < 400; x++) {
    for (var y = 0; y < 400; y++) {
      context.beginPath();
      context.arc(x, y, 0.2, 0, 2 * Math.PI, false);
      context.fillStyle = 'red';
      context.fill();
      context.closePath();
    }
  }
  var time = new Date() - start;
  document.body.appendChild(document.createTextNode(time + 'ms'));
}
canvas {
  display: block;
}
<input id="input" type="button" value="render canvas" />
<canvas id="canvas" width="400" height="400"></canvas>

Addendum: I don't use canvas often so there may be a better way to do what I wrote above, however, it will suffice to illustrate the difference.


text:
Q: How can I add authenication fields to Firebase Trigger Email? I keep getting the error: "Missing credentials for PLAIN" I am working on an email notification project for a school district.  I am using the Flutter platform and have connected to Firebase.  I have added the Trigger Email extension, set up the collection in Firestore and set up a Sendgrid account for the SMTP server.  I created a test email directly in the Firestore collection with the configured collection name for the Trigger Email service.  My collection document in firestore looks like this:
message:
subject: Hello from Firebase!
text: This is the plain text body.
html: This is the HTML body
to: xxxxx@gmail.com // my receiving email address

The extension attempts to send the email but then adds this to the document a few seconds later:
delivery
attempts: 1
endTime: //a time in UTC
error: "Error: Missing credentials for "PLAIN""
leaseExpireTime: null
startTime: //a time in UTC
state: "ERROR"


text:
Q: How to resize cordova webview ios 10 I have cordova project, just a simple one that opens my web url in the webview. It worked nicely on older version, but most new in iphone 7 simulator it draws the top os bar (clock etc.) under the web page!
How to make the top bar dissapear or limit the size of webview starting just under the top bar ?
I use cordova-plugin-inappbrowser to open the url into app (not in a external window) after network connection is detected.
screenshot:
https://snag.gy/i9FtLh.jpg

A: The result was to use cordova plugin "cordova-plugin-statusbar" and in deviceready js function StatusBar.overlaysWebView(false);


text:
Q: What is the difference between the 3 catch block variants in C# ( 'Catch', 'Catch (Exception)', and 'Catch(Exception e)' )? In C#, what is the difference Between 'Catch', 'Catch (Exception)', and 'Catch(Exception e)' ?
The MSDN article on try-catch uses 2 of them in its examples, but doesn't explain the difference in usage purposes.
try
{}
catch
{}

try
{}
catch (Exception)
{}

try
{}
catch(Exception e)
{}

How do these differ?  Which ones catch all exceptions, and which ones catch specific exceptions?

A: First version catches all exceptions deriving from the Exception class.
The second version catches specified exception.
The third version catches a specified exception with a declared name. Then in the catch block you can use this object, for example, to see the complete error: e.ToString();
Read more here.

A: All of them do basically the same thing, the difference being the amount of information they provide about the error.
catch (foo ex) {} will filter out all exceptions, except those that can be cast to type foo. It also gives you the instance of the error for you to work on.
catch (foo) {} does the same as above, but it doesn't give you the instance of the exception. You'll know the type of the exception, but won't be able to read information from it.
Notice that in both of those cases, if the type of the exception is Exception, they'll catch all exceptions.
catch {} catches all exceptions. You don't know the type it caught and you can't access the instance.
You can choose which one to use based on how much information you need from the exception should it be caught.
Regardless of which one you use, you can pass the caught exception forward by using the command throw; (without arguments).

A: No one has yet mentioned the historical aspect of this question.
In .NET it is legal to throw an object that does not derive from Exception. (It is not legal in C#, but it is in some other managed languages.) Many people are unaware of this fact, but it is legal. Since that is crazy, in .NET 2.0 the default was changed: if you attempt to throw something that is not an exception then it is automatically wrapped in the RuntimeWrappedException class which obviously is an exception.  That object is then thrown.
Because of this oddity, in C# 1.0 it was common to see code that did both:
try
{ do something }
catch(Exception)
{ handle the exception }
catch
{ handle the thrown non-exception }

And in fact there were security and correctness issues; there are situations in which for security reasons you must catch anything that is thrown (possibly to re-throw it) and people would think reasonably that catch(Exception) caught everything, but it didn't.
Fortunately since .NET 2.0 things have been more sensible; you can rely on catch {}, catch(Exception) {} and catch(Exception ex) {} to all catch everything should you need to.
And finally: if for some crazy reason you want to turn on the C# 1.0 behavior, you can put
[assembly:System.Runtime.CompilerServices.RuntimeCompatibility(WrapNonExceptionThrows = false)]

in your program.

A: In your example, nothing, since you're not doing anything with the exception. But to clarify…

*

*This catches everything but does nothing with the exception.
catch {}

This is only useful when you want to say guarantee a return from a method.

*This catches only exceptions of type Exception (which is everything) but does nothing with the exception.
catch (Exception) {}

This is useful if you wanted to limit the type of exception being caught by specifying which types you want to handle. Any other exceptions will bubble up the call stack until a proper handler is found.

*This catches only exceptions of type Exception (which is everything) and could do something with the exception, but happens to do nothing
catch (Exception ex) {}

This technique gives you a lot more options. You could log the exception, inspect the InnerException, etc. And again you can specify which types of exceptions you wish to handle.
Unless you're re-throwing the exception somehow, all of these are bad practice. In general, you should only catch the exceptions you can meaningfully handle and allow anything else to bubble up.

A: In short...
Catch without a parameter will receive any exception but provide no means to address it.
Catch (Exception) will essentially do the same thing, because you've specified the root Exception type.  As opposed to Catch (IOException) which would only catch the IOException type.
Catch (Exception ex) catches all exceptions and provides a means to address it via the ex variable.
Read more:  http://msdn.microsoft.com/en-us/library/ms173160.aspx

A: Adding catch(Exception e) will give you access to the Exception object, which contains details about the exception that was thrown, such as its Message and StackTrace; it is useful to log this information to help diagnose bugs. A simple catch without declaring the exception that you're trying to catch won't give you access to the exception object.
Also, catching the base Exception is generally considered bad practice because it's far too generic, and where possible you should always case for a specific exception first. For example, if you're working with files you might consider the following try/catch block:
try{
    //open your file and read/write from it here
}catch(FileNotFoundException fe){
    //log the message
    Log(fe.Message);
}catch(Exception e){
    //you can catch a general exception at the end if you must
}finally{
    //close your file
}

A: At the highest level they are all the same; they all catch exceptions.
But to drill down further, in the first case you are catching an exception and doing nothing with it (you don't have a defined type).  In the second example, you are catching an exception of the Exception type.  In your last example, you are catching the same Exception type as in example 2 but, now you are putting the exception into a variable that would allow you to show it in a MessageBox or:
e.Message

It's important to note as well that exceptions are tiered meaning, if you are catching multiple types of exceptions in the same try/catch block, you go from the most specific exception type to the most general.  Like this:
try {
}
catch (SqlException sqlExc) {
}
catch (Exception exc) {
}


text:
Q: How many times do you have to play until you get the humble scrap and unlock the palicos island How many times do you have to play the caravan quests until you get the humble scrap and unlock the palicos island?

A: Once you get to 4* caravan quests and get to Cheeko Sands, you will get some quests that will eventually unlock all of the Palico facilities, including the island and the minigame to get more humble scrap.
The specific quests are Wild Palico Panic (which will give you an additional palico) and then Meownster Hunter Havoc (which unlocks everything else).


text:
Q: Why does JSON.parse(null) return null? Whenever you pass in null to JSON.parse:

console.log(JSON.parse(null))

It returns null, but I can't find any docs on why this is the case. Is there a reason why this returns null?
Other things to note:

*

*This may be due to type conversion, as passing JSON.parse("null") also returns null, but is this specified anywhere?

A: This is due to JSON.parse(text\[,receiver\]) specifications, where:

*

*Let jsonString be ? ToString(text).

It is converting the text to a string (null -> "null"). This is then passed to the internal JSON parser
Once it is in the parser, JSON.parse not only works with full JSON structures, but also JSON values such as number, string, and null.
Therefore, null is parsed as the null value, and returned straight back.


text:
Q: Render Legends into JqPlot Bar charts I am  using jqPlot  graph for Bar graphs
Code :
 <script type="text/javascript">
   $(document).ready(function () {
     var s1 = [48,32,15,10,5,5,3,3];
     var s2 = [37,27,10,7,3,3,1,1];

     var ticks =["ID theft","CI","GLT","Rx Card","SI term","AD+","GIWL","P and C"];
     plot2 = $.jqplot('chart2', [s1,s2], {
        seriesDefaults: {
            renderer: $.jqplot.BarRenderer,
            pointLabels: { show: true }
        },
        series:[
      {label:'#2012'},
      {label:'#2013'}
        ],
        legend: {
            show: true,
            location: 'e',
            placement: 'inside'
        },
        axes: {
            xaxis:{
                ticks:ticks,
                renderer:$.jqplot.CategoryAxisRenderer,
                tickOptions:{markSize:0}
            },
            yaxis:{ticks:[0, 100], tickOptions:{formatString:'%d\%'}}
        }
    });

    $('#chart2').bind('jqplotDataHighlight',
        function (ev, seriesIndex, pointIndex, data) {
            $('#info2').html('series: ' + seriesIndex + ', point: ' + pointIndex + ', data: ' + data);
          }
      );

    $('#chart2').bind('jqplotDataUnhighlight',
        function (ev) {
            $('#info2').html('Nothing');
          }
     );
});

Problem ::  Legends are  not coming properly into graphs

A: You most likely forgot to include jquery.jqplot.css
include it: <script src="https://bitbucket.org/cleonello/jqplot/raw/e8af8a37f0f14ea1e8c630ecfe6f1b1933794036/src/jquery.jqplot.css"></script>
Or copy the following code into your css file:
//jquery.jqplot.css
    /*rules for the plot target div.  These will be cascaded down to all plot elements         according to css rules*/
     .jqplot-target {
    position: relative;
    color: #666666;
    font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
    font-size: 1em;
    /*    height: 300px;
    width: 400px;*/
    }
    /*rules applied to all axes*/
     .jqplot-axis {
    font-size: 0.75em;
    }
    .jqplot-xaxis {
    margin-top: 10px;
    }
    .jqplot-x2axis {
    margin-bottom: 10px;
    }
    .jqplot-yaxis {
    margin-right: 10px;
    }
    .jqplot-y2axis, .jqplot-y3axis, .jqplot-y4axis, .jqplot-y5axis, .jqplot-y6axis, .jqplot-y7axis, .jqplot-y8axis, .jqplot-y9axis, .jqplot-yMidAxis {
    margin-left: 10px;
    margin-right: 10px;
}
/*rules applied to all axis tick divs*/
 .jqplot-axis-tick, .jqplot-xaxis-tick, .jqplot-yaxis-tick, .jqplot-x2axis-tick, .jqplot-y2axis-tick, .jqplot-y3axis-tick, .jqplot-y4axis-tick, .jqplot-y5axis-tick, .jqplot-y6axis-tick, .jqplot-y7axis-tick, .jqplot-y8axis-tick, .jqplot-y9axis-tick, .jqplot-yMidAxis-tick {
    position: absolute;
    white-space: pre;
}
.jqplot-xaxis-tick {
    top: 0px;
    /* initial position untill tick is drawn in proper place */
    left: 15px;
    /*    padding-top: 10px;*/
    vertical-align: top;
}
.jqplot-x2axis-tick {
    bottom: 0px;
    /* initial position untill tick is drawn in proper place */
    left: 15px;
    /*    padding-bottom: 10px;*/
    vertical-align: bottom;
}
.jqplot-yaxis-tick {
    right: 0px;
    /* initial position untill tick is drawn in proper place */
    top: 15px;
    /*    padding-right: 10px;*/
    text-align: right;
}
.jqplot-yaxis-tick.jqplot-breakTick {
    right: -20px;
    margin-right: 0px;
    padding:1px 5px 1px 5px;
    /*    background-color: white;*/
    z-index: 2;
    font-size: 1.5em;
}
.jqplot-y2axis-tick, .jqplot-y3axis-tick, .jqplot-y4axis-tick, .jqplot-y5axis-tick, .jqplot-y6axis-tick, .jqplot-y7axis-tick, .jqplot-y8axis-tick, .jqplot-y9axis-tick {
    left: 0px;
    /* initial position untill tick is drawn in proper place */
    top: 15px;
    /*    padding-left: 10px;*/
    /*    padding-right: 15px;*/
    text-align: left;
}
.jqplot-yMidAxis-tick {
    text-align: center;
    white-space: nowrap;
}
.jqplot-xaxis-label {
    margin-top: 10px;
    font-size: 11pt;
    position: absolute;
}
.jqplot-x2axis-label {
    margin-bottom: 10px;
    font-size: 11pt;
    position: absolute;
}
.jqplot-yaxis-label {
    margin-right: 10px;
    /*    text-align: center;*/
    font-size: 11pt;
    position: absolute;
}
.jqplot-yMidAxis-label {
    font-size: 11pt;
    position: absolute;
}
.jqplot-y2axis-label, .jqplot-y3axis-label, .jqplot-y4axis-label, .jqplot-y5axis-label, .jqplot-y6axis-label, .jqplot-y7axis-label, .jqplot-y8axis-label, .jqplot-y9axis-label {
    /*    text-align: center;*/
    font-size: 11pt;
    margin-left: 10px;
    position: absolute;
}
.jqplot-meterGauge-tick {
    font-size: 0.75em;
    color: #999999;
}
.jqplot-meterGauge-label {
    font-size: 1em;
    color: #999999;
}
table.jqplot-table-legend {
    margin-top: 12px;
    margin-bottom: 12px;
    margin-left: 12px;
    margin-right: 12px;
}
table.jqplot-table-legend, table.jqplot-cursor-legend {
    background-color: rgba(255, 255, 255, 0.6);
    border: 1px solid #cccccc;
    position: absolute;
    font-size: 0.75em;
}
td.jqplot-table-legend {
    vertical-align:middle;
}
/*
These rules could be used instead of assigning
element styles and relying on js object properties.
*/

/*
td.jqplot-table-legend-swatch {
    padding-top: 0.5em;
    text-align: center;
}

tr.jqplot-table-legend:first td.jqplot-table-legend-swatch {
    padding-top: 0px;
}
*/
 td.jqplot-seriesToggle:hover, td.jqplot-seriesToggle:active {
    cursor: pointer;
}
.jqplot-table-legend .jqplot-series-hidden {
    text-decoration: line-through;
}
div.jqplot-table-legend-swatch-outline {
    border: 1px solid #cccccc;
    padding:1px;
}
div.jqplot-table-legend-swatch {
    width:0px;
    height:0px;
    border-top-width: 5px;
    border-bottom-width: 5px;
    border-left-width: 6px;
    border-right-width: 6px;
    border-top-style: solid;
    border-bottom-style: solid;
    border-left-style: solid;
    border-right-style: solid;
}
.jqplot-title {
    top: 0px;
    left: 0px;
    padding-bottom: 0.5em;
    font-size: 1.2em;
}
table.jqplot-cursor-tooltip {
    border: 1px solid #cccccc;
    font-size: 0.75em;
}
.jqplot-cursor-tooltip {
    border: 1px solid #cccccc;
    font-size: 0.75em;
    white-space: nowrap;
    background: rgba(208, 208, 208, 0.5);
    padding: 1px;
}
.jqplot-highlighter-tooltip, .jqplot-canvasOverlay-tooltip {
    border: 1px solid #cccccc;
    font-size: 0.75em;
    white-space: nowrap;
    background: rgba(208, 208, 208, 0.5);
    padding: 1px;
}
.jqplot-point-label {
    font-size: 0.75em;
    z-index: 2;
}
td.jqplot-cursor-legend-swatch {
    vertical-align: middle;
    text-align: center;
}
div.jqplot-cursor-legend-swatch {
    width: 1.2em;
    height: 0.7em;
}
.jqplot-error {
    /*   Styles added to the plot target container when there is an error go here.*/
    text-align: center;
}
.jqplot-error-message {
    /*    Styling of the custom error message div goes here.*/
    position: relative;
    top: 46%;
    display: inline-block;
}
div.jqplot-bubble-label {
    font-size: 0.8em;
    /*    background: rgba(90%, 90%, 90%, 0.15);*/
    padding-left: 2px;
    padding-right: 2px;
    color: rgb(20%, 20%, 20%);
}
div.jqplot-bubble-label.jqplot-bubble-label-highlight {
    background: rgba(90%, 90%, 90%, 0.7);
}
div.jqplot-noData-container {
    text-align: center;
    background-color: rgba(96%, 96%, 96%, 0.3);
    }


text:
Q: Is there a way to make this query more efficient performance wise? This query takes a long time to run on MS Sql 2008 DB with 70GB of data.
If i run the 2 where clauses seperately it takes a lot less time.
EDIT - I need to change the 'select *' to 'delete' afterwards, please keep it in mind when answering. thanks :)
select *
From computers
Where Name in
      (
      select T2.Name
      from
            (
            select Name
            from computers
            group by Name
            having COUNT(*) > 1
            ) T3
      join computers T2 on T3.Name = T2.Name
      left join policyassociations PA on T2.PK = PA.EntityId
      where (T2.EncryptionStatus = 0 or T2.EncryptionStatus is NULL) and
            (PA.EntityType <> 1 or PA.EntityType is NULL)
      )
OR
      ClientId in
      (
      select substring(ClientID,11,100)
      from computers
      )

A: or can be poorly optimized sometimes.  In this case, you can just split the query into two subqueries, and combine them using union:
select *
From computers
Where Name in
      (
      select T2.Name
      from
            (
            select Name
            from computers
            group by Name
            having COUNT(*) > 1
            ) T3
      join computers T2 on T3.Name = T2.Name
      left join policyassociations PA on T2.PK = PA.EntityId
      where (T2.EncryptionStatus = 0 or T2.EncryptionStatus is NULL) and
            (PA.EntityType <> 1 or PA.EntityType is NULL)
      )
UNION
select *
From computers
WHERE ClientId in
      (
      select substring(ClientID,11,100)
      from computers
      );

You might also be able to improve performance by replacing the subqueries with explicit joins.  However, this seems like the shortest route to better performance.
EDIT:
I think the version with join's is:
select c.*
From computers c left outer join
     (select c.Name
      from (select c.*, count(*) over (partition by Name) as cnt
            from computers c
           ) c left join
           policyassociations PA
           on T2.PK = PA.EntityId and PA.EntityType <> 1
      where (c.EncryptionStatus = 0 or c.EncryptionStatus is NULL) and
            c.cnt > 1
     ) cpa
     on c.Name = cpa.Name left outer join
     (select substring(ClientID, 11, 100) as name
      from computers
     ) csub
     on c.Name = csub.name
Where cpa.Name is not null or csub.Name is not null;

A: Swapping IN for EXISTS will help.
Also, as per Gordon's answer: UNION can out-perform OR.
SELECT computers.*
FROM   computers
 LEFT
  JOIN policyassociations
    ON policyassociations.entityid = computers.pk
WHERE  (
          computers.encryptionstatus = 0
       OR computers.encryptionstatus IS NULL
       )
AND    (
          policyassociations.entitytype <> 1
       OR policyassociations.entitytype IS NULL
       )
AND    EXISTS (
         SELECT name
         FROM   (
                 SELECT name
                 FROM   computers
                 GROUP
                     BY name
                 HAVING Count(*) > 1
                ) As duplicate_computers
         WHERE  name = computers.name
       )

UNION

SELECT *
FROM   computers As c
WHERE  EXISTS (
         SELECT SubString(clientid, 11, 100)
         FROM   computers
         WHERE  SubString(clientid, 11, 100) = c.clientid
       )

You've now updated your question asking to make this a delete.
Well the good news is that instead of the "OR" you just make two DELETE statements:
DELETE
FROM   computers
 LEFT
  JOIN policyassociations
    ON policyassociations.entityid = computers.pk
WHERE  (
          computers.encryptionstatus = 0
       OR computers.encryptionstatus IS NULL
       )
AND    (
          policyassociations.entitytype <> 1
       OR policyassociations.entitytype IS NULL
       )
AND    EXISTS (
         SELECT name
         FROM   (
                 SELECT name
                 FROM   computers
                 GROUP
                     BY name
                 HAVING Count(*) > 1
                ) As duplicate_computers
         WHERE  name = computers.name
       )
;

DELETE
FROM   computers As c
WHERE  EXISTS (
         SELECT SubString(clientid, 11, 100)
         FROM   computers
         WHERE  SubString(clientid, 11, 100) = c.clientid
       )
;

A: Some things I would look at are
1. are indexes in place?
2. 'IN' will slow your query, try replacing it with joins,
3. you should use column name, I guess 'Name' in this case, while using count(*),
4. try selecting required data only, by selecting particular columns.
Hope this helps!


text:
Q: Meager subspaces of a Banach space and weak-* convergence I previously asked a version of this question on Math.SE, but didn't receive an answer.  (But there is a bounty there if you want to claim it!)
Let $X$ be a Banach space.  (If it helps, feel free to assume that $X$ is separable.)  In this question, "subspace" means a linear subspace of $X$, not necessarily closed.

Q1. Suppose $E \subset X$ is a subspace which is meager, so that we can write $E = \bigcup_n E_n$, where the $E_n$ are nowhere dense subsets of $X$. Can the $E_n$ be taken to be subspaces of $X$?  That is, can a meager subspace always be written as a countable union of nowhere dense subspaces?

Note that the trivial approach of replacing each $E_n$ with its linear span does not work, since the linear span of a nowhere dense set is not necessarily nowhere dense (consider the unit sphere).

Q1a.  If the answer to Q1 is yes, can the subspaces $E_n$ be taken to be increasing, i.e $E_1 \subset E_2 \subset \cdots$?  Can we write $E$ as a a countable increasing union of nowhere dense subspaces?

The trivial approach of replacing $E_n$ by $E_1 + \dots + E_n$ does not work, since the sum of two nowhere dense subspaces may not be nowhere dense (for instance, in $C([0,1])$, consider the mean-zero functions and the constants).

This came up in the context of thinking about the following related question.

Q2. Let us say a subspace $E \subset X$ determines weak-* convergence if for every sequence $\{f_n\} \subset X^*$ such that $f_n(x) \to 0$ for every $x \in E$, we have $f_n(x) \to 0$ for every $x \in X$.  Is it true that $E$ determines weak-* convergence if and only if $E$ is nonmeager?
Q2a. If not, what are necessary and sufficient conditions for $E$ to determine weak-* convergence?

Clearly it is necessary that $E$ be dense.  A rookie mistake is to guess that density is also sufficient, but this is false and it is easy to find counterexamples.
By a version of the uniform boundedness principle and the triangle inequality, every nonmeager subspace determines weak-* convergence (see below for a sketch).  This is a very strong condition, since as discussed in this question, a nonmeager proper subspace of $X$ lacks the Baire property and so must be rather pathological, not a space we are likely to encounter in everyday life.  For practical purposes, requiring that $E$ be nonmeager is essentially as strong as requiring that $E = X$.
I was wondering whether "nonmeager" is in fact necessary.
Suppose we could write $E = \bigcup_n E_n$ where $E_n$ are increasing nowhere dense subspaces.  Since $E_n$ is nowhere dense, it is not dense, so by Hahn-Banach we may find $f_n \in X^*$ with $f_n(E_n) = 0$ and $\|f_n\| = n$.  Then $f_n(x) \to 0$ for every $x \in E$, but $\{f_n\}$ is unbounded so by the uniform boundedness principle, there exists $x \in X$ with $\{f_n(x)\}$ unbounded.  So such an $E$ does not determine weak-* convergence.
Therefore, if Q1a has an affirmative answer, so does Q2.

Footnote: Here's a sketch of the argument that nonmeager subspaces determine weak-* convergence.  Suppose $E$ is nonmeager and $\{f_n\} \subset W^*$ with $f_n(x) \to 0$ for $x \in E$. Let $A_k = \bigcap_n \{x : |f_n(x)| \le K\}$.  $A_k$ is closed, and since $\{f_n(x)\}$ is bounded for $x \in E$, we have $E \subset \bigcup_k A_k$.  By Baire, some $A_k$ has nonempty interior, and a little rearrangement shows that $M := \sup_n \|f_n\| < \infty$, as in the usual uniform boundedness principle.  Now since $E$ is nonmeager, it must be dense, since non-dense subspaces are nowhere dense.  For any $x \in X$, fix $\epsilon$ and choose $x' \in E$ with $\|x-x'\| < \epsilon$.  Then $|f_n(x)| \le |f_n(x')| + M \epsilon$; letting $n \to \infty$ we get $\limsup_n |f_n(x)| \le M \epsilon$, but $\epsilon$ was arbitrary so $f_n(x) \to 0$.

A: Update:  Here is a ZFC (probably even ZF+DC) counterexample for Q1.  It's from probability and kind of indirect, maybe someone will be able to find something shorter.
Let $X = C_0([0,1])$, the space of continuous functions $\omega$ on $[0,1]$ having $\omega(0)=0$.  Fix $0 < \alpha < 1/2$ and let $E = C^{0,\alpha}([0,1]) \cap X$ be the subspace of $\alpha$-Hölder continuous functions.  There are several ways to see that $E$ is meager in $X$.  For instance, by Arzelà-Ascoli, the balls of $E$ under the Hölder norm are compact in $X$, hence $E$ is a countable union of compact sets, each of which is nowhere dense in $X$ by Riesz's lemma.  Or, the argument mentioned in the question: $E$ is Banach in its own norm, hence analytic in $X$, hence has the Baire property in $X$, hence must be meager. (That doesn't work because $E$ is not separable in its own norm, hence not Polish.)
Now let $\mu$ be the Wiener measure on $X$.  It is well known that $\mu(E) = 1$, since Brownian motion is almost surely $\alpha$-Hölder continuous for any $\alpha < 1/2$.  On the other hand, suppose $F$ is any nowhere dense subspace of $X$, so that its closure is a proper closed subspace of $X$.  By Hahn-Banach there is a nonzero continuous linear functional $f$ that vanishes on $F$.  Now $\mu$ is a nondegenerate Gaussian measure on $X$, so $f$ has a nondegenerate one-dimensional Gaussian distribution under $\mu$; in particular, $\mu(F) \le \mu(\{f = 0\}) = 0$.  Thus every nowhere dense subspace has measure zero, so by countable additivity, $E$ cannot be a countable union of such.
Previous answer.  It is consistent with ZF+DC that the answer to Q1 is No.
Consider an example in which $E$ is separable Banach in a stronger norm $\|\cdot\|_E$; for instance, $X = L^2([0,1])$ and $E = C([0,1])$.  Then $E$ is analytic in $X$, hence has the Baire property, hence must be meager.   If $E$ can be written as a countable union of subspaces $E_n$ then by Baire category one of them must be nonmeager with respect to  $\|\cdot\|_E$, hence doesn't have the BP in $E$.  But Shelah proved it is consistent with ZF+DC that every subset of a Polish space has the BP.
In our specific example we can see explicitly that $C([0,1])$ is meager in $L^2([0,1])$: the sup-norm balls $B_n = \{f : \|f\|_\infty \le n\}$ are closed in $L^2$ with empty interior.
I don't see whether this helps us with Q2.

A: The answer to Q2 is No.
I am grateful to Damian Sobota for drawing my attention to the following paper:

Darst, R. B.
  On a theorem of Nikodym with applications to weak convergence and von Neumann algebras.
  Pacific J. Math. 23 (1967) 473–477.  MR0238084

(Damian mentioned it in the question Convergence of functionals on compact projections on a separable Hilbert space.)
Darst's result is as follows (notation slightly adjusted):

Theorem. Suppose $\{\mu_n\}$ is a sequence of bounded and finitely additive complex measures on a $\sigma$-algebra $\mathcal{B}$ of subsets of a set $\Omega$ such that for each $B \in \mathcal{B}$ we have $\sup_n |\mu_n(B)| < \infty$. Then $\sup_n \sup_{B \in \mathcal{B}} |\mu_n(B)| < \infty$.

This effectively provides a counterexample to Q2.
To be concrete, let us take $\Omega = \mathbb{N}$, $\mathcal{B} = 2^{\mathbb{N}}$.  Then, in the notation of this question, let $X = \ell^\infty(\mathbb{N})$. (For simplicitly let us work over $\mathbb{R}$, and identify $X$ as the space of  bounded real-valued functions on $\mathbb{N}$.)  Then $X^*$ can be identified as the set of bounded and finitely additive signed measures on $\mathcal{B} = 2^{\mathbb{N}}$, where the pairing with $X$ is integration, and the dual norm is given by the total variation.
Let $E \subset X$ be the space of simple functions (those with finite range; equivalently, the linear span of the indicator functions).  Darst's theorem implies that $E$ determines weak-* convergence.  For suppose $\{\mu_n\} \subset X^*$ satisfies $\int x\,d\mu_n \to 0$ for every $x \in X$.  Taking $x = 1_B$ for arbitrary $B \subset \mathbb{N}$, we see that $\mu_n(B) \to 0$, and in particular $\sup_n |\mu_n(B)| < \infty$.  Darst's result then implies that $\sup_n \sup_{B \subset \mathbb{N}} |\mu_n(B)| < \infty$, which means $\sup_n \|\mu_n\| < \infty$ (see Claim 1 below).  Since $E$ is dense in $X$, it follows by the triangle inequality (see the last part of the footnote to the question) that $\mu_n \to 0$ weakly-*.
(In fact, if I am reading Darst's paper correctly, he actually shows more: that $\mu_n \to 0$ weakly, i.e. in the topology $\sigma(X^*, X^{**})$.)
On the other hand, $E$ is meager in $X = \ell^\infty$.  To see this, just let $E_k$ be the set of all $x \in \ell^\infty$ whose range contains at most $k$ numbers.  Clearly $E_k$ has empty interior (every ball contains a function with infinite range).  And $E_k$ is closed: suppose $x_n \in E_k$ and $x_n \to x$ in $X$ (i.e. uniformly).  If the range of $x$ contains $m$ numbers, $t_1, \dots, t_m$, we can choose $\varepsilon$ so small that the balls $B(t_i, \varepsilon)$ are pairwise disjoint.  Yet there is $n$ sufficiently large that $\|x_n - x\| < \varepsilon$, meaning that each of the $m$ balls must contain a number from the range of $x_n$.  Hence $m \le k$, and we have $x \in E_k$.  So $E_k$ is nowhere dense, and $E = \bigcup_k E_k$.
So $E$ is meager, yet it determines weak-* convergence.
I would still be interested to know whether there is a counterexample with $X$ separable.

Proof of Claim 1. Suppose $\mu$ is a finitely additive signed measure and $\sup_{B \subset \mathbb{N}} |\mu(B)| = M$.  Let $A_1, A_2, \dots, A_m$ be finitely many disjoint subsets of $\mathbb{N}$.  Arrange these sets so that $\mu(A_i) \ge 0$ for $1 \le i \le k$ and $\mu(A_i) < 0$ for $k+1 \le i \le m$.  Then let $B_1 = A_1 \cup \dots \cup A_k$ and $B_2 = A_{k+1} \cup \dots \cup A_m$.  Then
$$\begin{align*}
\sum_{i=1}^m |\mu(A_i)| &= \sum_{i=1}^k \mu(A_i) - \sum_{i=k+1}^m \mu(A_i) \\
&= \mu(B_1) - \mu(B_2) \\
&= |\mu(B_1)| + |\mu(B_2)| \le 2M
\end{align*}$$
Since $\|\mu\|$ is the supremum of the left side over all finite partitions of $\mathbb{N}$, we have $\|\mu\| \le 2M$.


text:
Q: How to turn off stack protector in linux kernel easily? I wrote a simple module for the Linux Kernel and it has a stack buffer overflow vulnerability. I want to exploit the module, but I have to turn off the stack protector in the kernel first. How could I do this quickly and simply?
Is it required to compile the kernel every time?
Is there any other way to turn off stack protection in a module of the Linux Kernel (without compiling the kernel)?

A: Those options work by passing options to the compiler, so the most straightforward way is to recompile the kernel.
However for a reproducible and module-specific way kbuild allows you to set custom CFLAGs on a per-module basis.
https://www.kernel.org/doc/Documentation/kbuild/makefiles.txt
You particularly want to set -fno-stack-protector for the modules you want to exploit.
DKMS additionally allows you to set up automatic rebuild for out of tree drivers against arbitrary kernel versions.


text:
Q: Unable to add reference to third party dll in a UWP project Since a UWP app is a .NET Core app, a reference to a third party dll created in .NET 4.0 is not getting added in my UWP project in VS2017. I'm getting the error shown below. A similar question has been answered here. But since that question is about 6 years old, and since then a lot has changed in the .NET Core world, I thought may be there are some better solutions to my problem than just rather complicated workarounds. Are there any simpler solutions to make a third party dll reference added to a UWP project?
Error:

A: You can't add a .NET Framework DLL to a UWP app.
The best/closest thing you can to is add a desktop extension to your UWP process, which is a separate process that can run the full .NET Framework on desktop and therefore load this DLL.
Here is a tutorial on desktop extension for UWP: https://stefanwick.com/2018/04/06/uwp-with-desktop-extension-part-1/


text:
Q: Codename one's VKB not showing in android build I have installed an android build of codename one on motorola atrix.
Now I have a textfield. WHen I click on the textfield, android's keyboard shows up.
I don't want that. I want to show Codename One's key board(white and transparent). How do i do that?

A: There is an API called Display.setDefaultVirtualKeyboard() but it probably won't work for Android since we use native input on Android always by default. The keyboard is the smaller issue, the copy/paste and other features available on these OS's are the main reason we chose the native keyboard.
You can file a bug on this and we can evaluate the complexity of adding something like this, but it will probably be a bit of a pain to fix.

A: Ok, so with Shai's comment given above: this is how i got android to show codename one's keyboard.
Textfield field = new TextField();

        VirtualKeyboard vkb = new VirtualKeyboard();
        VirtualKeyboard.bindVirtualKeyboard(field, vkb);//binding the vkb to a particular textfield
        Display.getInstance().setDefaultVirtualKeyboard(vkb);

Now, the datachange listener for textfield works smooth. Also the hint of the textfield clears out when textfield receives focus.


text:
Q: Install package in separate area for read-only Anaconda Linux install at work we have a central, read-only, Linux Anaconda installation, and several projects need library packages for their individual project members.
Is there a way to conda install packages in a writable area set aside for each project?
Our Linux servers are also not directly web connected, but we can transfer data from a Windows machine that is. Is there a way for the windows conda to download data for our Linux install in such a way that I can transfer the downloaded files to Linux and then finish the install on Linux , with the conda linux not needing a direct web connection?
Thanks in advance :-)

A: The best answer to this question is a bit oblique: the Anaconda Distribution is designed for a single user on a single system with unrestricted access to the Internet.  Any other use is considered "off label" and YMMV, though there are no license restrictions in place preventing you from trying to use it as you see fit.  Anaconda Enterprise is the commercial product that is specifically designed for multi-user, server-deployed Anaconda with firewall restrictions.  Security, governance, indemnification, support, collaboration, etc. etc. Check out https://www.continuum.io/ for more details.
But there are "work around" ways to achieve what you want, albeit complicated ones.  For it to be reliable, reproducible, and maintainable you're going to end up reimplementing a lot of what is in Anaconda Enterprsie.  Here are some tips:

*

*Check out the "conda in multi-user environments" documentation

*Check out the "Centralized Anaconda installation" documentation

*Regular user alice for project foo can do conda create -p /nfs/project/foo/envs/custompython --offline anaconda; conda activate /nfs/project/foo/envs/custompython; conda install pkg1 pkg2 pkg3

*You're going to run into ownership/permission issues.  If you have sensible umask values then when alice's colleague bob tries to update pkg2 in the foo project he'll discover that he can't unlink the files alice wrote there.  There is stuff you can do (as the IT admin) with chown, or alice can do with chmod, but its all a bit of a bother and there are lots of ways you can paralyze a conda environment because it is expecting "writability" to be binary for a particular environment.  There is a long history in the conda GH issue tracker of people (myself included) shooting themselves in the foot by starting a conda env setup with one account and then making mods with another account that bork out half way through, leaving everything inconsistent.

*Be careful about .condarc files.  My advice: avoid them everywhere but in the base Anaconda installation (say, inside /opt/anaconda/.condarc).  All sorts of weird stuff can happen when multiple overlaying .condarc files come together (the docs reference above discusses this).

*People can create their own environments in an "offline" mode so long as the packages specified in those new environments (and their dependencies) are a subset of the packages available in the base environment (or subsequently added to the package cache), taking into account versions as well, of course.

*You can download packages using your online Windows machine by grabbing them from repo.continuum.io and from anaconda.org.  Make sure you download them for the right platform.  But the challenge: you need to download a set of packages that will satisfy the dependencies of the package you want to install.  There isn't a super easy way to get that information when you're offline.

*Once you drop new packages into the Linux system's package cache be sure to re-run conda index.

*Beware installing packages directly from their tarballs: this will not pick up any dependencies and does what is called a "force" install.  So doing conda install /path/to/conda/pkg-ver.tar.bz2 is actually most similar to doing conda install --force --no-deps pkg=ver (though not identical, to be sure).  --force means the install will happen NO MATTER WHAT, even if it will break your environment (violate existing package dependencies), and --no-deps means you won't get any of the dependencies of pkg installed.


text:
Q: Assigning row number according to the Column value SQL Server? I have a table like this in SQL server 2014:
name
a
a
b
b
b
c
d
d
d

I want to create another column that is S.No. , but serial number value will be assigned according to name column. If name occurs 2 times the value of s.no. will be 1 and 2.If d is 3 times than value for d will be 1,2 and 3 and than again counter will start with 1 for e. so the table will be like:
name    S.no.
a       1
a       2
b       1
b       2
b       3
c       1
d       1
d       2
d       3

Any solution? thanks for the help.

A: Use ROW_NUMBER():
SELECT name, ROW_NUMBER() OVER (PARTITION BY name ORDER BY (SELECT 1)) [S.no.]
FROM T

A: Just in another way by using Count()
select
Name,
Count(1) over (partition by Name ORDER BY Name ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as Slno
from MyTable


text:
Q: Difference between Structural Design Pattern and Behavioral Design Pattern? I was reading on the design patterns basics and came across the two basic definition of Structural Patterns and Behavioral Pattern which is like:
Structural Design Patterns:Generally deal with relationships between entities, making it easier for these entities to work together.
Behavioral Design Patterns:Used in communications between entities and make it easier and more flexible for these entities to communicate.
reading it, I cannot differentiate between them, can someone guide me how they are different, by giving some simplest example?

A: I am pretty unsure if my explanation and example really cover the most important principles
Think of behavior as scenarios external to the structures. A certain data structure can "be used" in multiple behaviors/scenarios.
On the other hand think of structure related logic as being internal to the structure. The structure gets affected by various changes and executes some actions as a consequence.
That being said we can exemplify with the following:
Structure design patterns will define a weblog by defining its constituents as higher level business objects such as Article/Image/Comment. The constituents are aware of one another and how to connect to each other.
$image = new Image;
$image->title = 'Image title';
$image->url = 'http://example.com/file.ext';
$image->save(); // will save the image to a DB

$article->title = 'The title i have set';
/* $article->url_key = 'the_title_i_have_set'; */
// this ^^ element of logic will be done automatically by the article
$article->addImage($image); // will save the connection between the
                            // article and the image to DB

Behavior design patterns will define a weblog by its use cases (scenarios) using lower level business objects such as Article/ArticleToImage/Image/ArticleToComment. The business objects are not aware of each other and are "maneuvered" into place by the scenario logic.
$image = new Image;
$image->title = 'Image title';
$image->url = 'http://example.com/file.ext';
$image->save(); // will save the image to a DB

$article->title = 'The title i have set';
$article->url_key = $controller->getURlKey($article->title);
$article->save(); // saves article to DB

$article_to_image = new ArticleToImage;
$article_to_image->article = $article;
$article_to_image->image = $image;
$article_to_image->save();

TL;DR
If the storage objects are smart (contain logic) that's structural design. If the storage objects are dumb (they can only store data and transfer it to the DB) you then need a behavioral design to manage them.

A: Sorry that my explanation will be in C#.
Observer is behavioral pattern: Presents interface, allowing object to communicate without any concrete knowledge about each other. Also known as Publish-Subscribe pattern. Object to inform other object about its state, without the knowledge which are these objects.
Adapter is structural pattern: Adapter converts the given class' interface into another class requested by the client. Wrap an existing class with a new interface. Impedance match an old component to a new system. Allows classes to work together when this is impossible due to incompatible interfaces.
Adapter example:
interface ITarget
{
  List<string> GetProducts();
}

public class VendorAdaptee
{
   public List<string> GetListOfProducts()
   {
      List<string> products = new List<string>();
      products.Add("Gaming Consoles");
      products.Add("Television");
      products.Add("Books");
      products.Add("Musical Instruments");
      return products;
   }
}

class VendorAdapter:ITarget
{
   public List<string> GetProducts()
   {
      VendorAdaptee adaptee = new VendorAdaptee();
      return adaptee.GetListOfProducts();
   }
}

class ShoppingPortalClient
{
   static void Main(string[] args)
   {
      ITarget adapter = new  VendorAdapter();
      foreach (string product in adapter.GetProducts())
      {
        Console.WriteLine(product);
      }
      Console.ReadLine();
   }
}

Observer example: Event handler and just events
using System;
namespace wildert
{
    public class Metronome
    {
        public event TickHandler Tick;
        public EventArgs e = null;
        public delegate void TickHandler(Metronome m, EventArgs e);
        public void Start()
        {
            while (true)
            {
                System.Threading.Thread.Sleep(3000);
                if (Tick != null)
                {
                    Tick(this, e);
                }
            }
        }
    }
        public class Listener
        {
            public void Subscribe(Metronome m)
            {
                m.Tick += new Metronome.TickHandler(HeardIt);
            }
            private void HeardIt(Metronome m, EventArgs e)
            {
                System.Console.WriteLine("HEARD IT");
            }

        }
    class Test
    {
        static void Main()
        {
            Metronome m = new Metronome();
            Listener l = new Listener();
            l.Subscribe(m);
            m.Start();
        }
    }
}

A: Best way to explain would be to take two examples from two categories.
Composite from Structural patterns defines a tree like structure, so focuses on the relationship. One to many and has a type of relationships so that whole and part can be treated alike.
Observer pattern on the other hand from Behavioral design patterns focus on communication. How do we let the interested parties know any changes to the object. Sort of publisher to subscriber. Does not define a strict structure, but forces on implementing methods, i.e. channels of communications.
Hope it's useful.

A: Structural patterns are used for defining the static properties of the system (see Class diagram).
Example: Factory pattern can be used to create entities which constitute your system. You can have object Button that have different graphical properties on Windows vs. OS X. Factory pattern will create the Button regardless of the OS and the created object will have the same interfaces on both OSs expose the same behavior despite having different internals.
Behavioral patterns are used for defining the dynamic behavior of the system (see Activity, Sequence etc. diagrams).
Example: Adapter pattern can be used at runtime to transparently allow interfacing of 2 entities that do not share interface between them. It effectively changes the behavior of an object at runtime.


text:
Q: Oreo startLocalOnlyHotspot customize SSID and PASSWORD (API 26) It's just known that since Android Oreo (API 26) is not posible to enable the wifi hotspot as in previous versions, with setApEnable().
Google has hiden and protected those methos, and the only posibility is to enable a local only hotspot with WifiManager.startLocalOnlyHotspot as here is described:
https://developer.android.com/reference/android/net/wifi/WifiManager#startLocalOnlyHotspot(android.net.wifi.WifiManager.LocalOnlyHotspotCallback,%20android.os.Handler)
For my project I need the hotspot funcionality to comunicate with another device, no internet needed but, I need to create the hotspot with some specific credentials that are preconfigured on the other device.
I've checked android documentation but I don't see if it's possible to do a startLocalOnlyHotspot with predefined parameters, SSID and PASSWORD.
Anyone knows if it's possible to configure them?
Thanks!


text:
Q: Solve this inequality with nested radicals (possibly by induction) I tried to solve this problem by induction but didn't succeed. Given the series
$$ a_n = \sqrt{1+\sqrt{2+\sqrt{3+\sqrt{... + \sqrt{n}}}}}$$
Prove that $a_n < 2 (\forall n \in \mathbb{N^*}) $
Now I thought that maybe I could find a reccurence formula. I haven't found one. Another way I tought of was squaring both sides and substracting the number before the radical n times but that made it more complicated. Can someone lend me a hand on this?

A: Fix $x \ge 0$, and define $(a_n)$ by
$$
a_n
=
\sqrt{x^2 +
 \sqrt{x^4 +
  \sqrt{x^8 +
   \sqrt{\cdots +
    \sqrt{x^{2^n}}
   }
  }
 }
}
$$
Then for all $n > 1$, we have the relation
$$a_n^2=x^2+xa_{n-1}$$
Now let $x = \sqrt{5}-1$.

Claim:$\;a_n < 2$, for all $n$.

Proceed by induction on $n$.

For $n=1$, we have $a_1=\sqrt{x^2}=x = \sqrt{5}-1< 2$.

Suppose $a_n < 2$, for some positive integer $n$.

Then we get
$$a_{n+1}^2 =  x^2+xa_n < x^2+2x = (\sqrt{5}-1)^2+2(\sqrt{5}-1)= 4$$
so $a_{n+1} < 2$, which completes the induction.

Next, compare $x^{2^n}$ and $n$ . . .

Claim:$\;x^{2^n} > n$, for all $n$.

Proceed by induction on $n$.

For $n=1$, we have $x^{2^1} = x^2 = (\sqrt{5}-1)^2 > 1$.

For $n=2$, we have $x^{2^2} = x^4 = (\sqrt{5}-1)^4 > 2$.

Suppose $x^{2^n} > n$, for some positive integer $n \ge 2$.

Then we get
$$x^{2^{n+1}}=\left(x^{2^n}\right)^2 > n^2 \ge 2n > n+1$$
so $x^{2^{n+1}} > n+1$, which completes the induction.

Hence, for all $n$, we have
$$
\sqrt{1 +
 \sqrt{2 +
  \sqrt{3 +
   \sqrt{\cdots +
    \sqrt{n}
   }
  }
 }
} <
\sqrt{x^2 +
 \sqrt{x^4 +
  \sqrt{x^8 +
   \sqrt{\cdots +
    \sqrt{x^{2^n}}
   }
  }
 }
} < 2
$$

A: It is well known that the iteration $x\mapsto \sqrt{1+x}$ with starting point $x=0$ converges to $\varphi=\frac{1+\sqrt{5}}{2}$, i.e.
$$ \sqrt{1+\sqrt{1+\sqrt{1+\sqrt{1+\ldots}}}}=\frac{1+\sqrt{5}}{2}.\tag{1} $$
If we multiply both sides by $2^{1/4}$ we get
$$ \sqrt{2^{1/2}+\sqrt{2+\sqrt{4+\sqrt{16+\ldots}}}}=\frac{1+\sqrt{5}}{2^{3/4}}<2\tag{2} $$
and the LHS of $(2)$ is blatantly larger than any $a_n$ since $2^{2^{n-2}}\geq n$ for any $n\geq 1$.
Actually
$$ \lim_{n\to +\infty} a_n = \sup_{n\geq 1}a_n \approx 1.75793\ldots < \frac{2495-\sqrt{5}}{1418}.\tag{3}$$

A: $$\sqrt{1+\sqrt{2+\sqrt{3+\sqrt{... + \sqrt{n}}}}}\le \sqrt{1\sqrt{2\sqrt{3\sqrt{...\sqrt{n}}}}} = \prod_{k=1}^nk^{\frac{1}{2^k}} < 1.7$$


text:
Q: Rails nested routing I'm having three models with nested resource.
class User < ActiveRecord::Base
  has_many :basiccases
end

class Basiccase < ActiveRecord::Base
  belongs_to :user
  has_one :form3_c
end

class Form3C < ActiveRecord::Base
 belongs_to :basiccases
end

resources :basiccases  do
  resources :form3_cs
  end

I'm trying to send the basiccase to the new form using
<%= link_to "ADD Form3C", new_basiccase_form3_c_path(@basiccase)%>

and fetch the new value in the form using
<%= form_for([@form3c, @basiccase]) do |f| %>

in new view in form_for method.
My controller code
class Form3CsController <  ApplicationController
  #before_filter :authenticate

  def new
    @title = "New Form 3C"
    @basiccase = Basiccase.find_by_id(params[:id])

    @form3c = Form3C.new if signed_in?
  end

  def create
       @form3c = @basiccase.build_form3_c(params[:form3c])
          if @form3c.save
            flash[:success] = "Form created!"
            redirect_to current_user
          else
            flash[:warning] ="Failed to create a Form"
            render 'users/show'
          end
  end
end

My main aim is to get the basiccase_id in the create method of form3_c controller and assign the foreign key attribute.  Is my approach correct ?
I'm getting an error
undefined method `model_name' for NilClass:Class
Extracted source (around line #2):

1:
Add Form 3C

2: <%= form_for(@basiccase) do |f| %>
3:     <%= render 'shared/error_messages', :object => f.object %>
4:
5:

A: Try
<%= form_for([@basiccase, @form3c]) do |f| %>


text:
Q: Listbox selection change not firing on click on child in list box item I have a wpf user control which contains a Listbox which is binded to my View Model. Each Listbox item is consists of three textblock. I made the UI in a way that when user clicks on the Frist TextBlock(Title) function in my View Model will get called.
To uniquely Identify the ListBox item corresponding to which text block now got clicked. I added another property in my view model which is bindied to SelectionChanged Event in the Listbox. So whenever my TextBlock binded command get exectuted I will use my SelectionChanged Property to find which List Box Item and use its data context.
But the issue I am facing now is that when User clicks on the First textblock, selectionchanged event is not firing. When User clicks outside the First Textblock only Selection Changed event is getting fired. Which made my view model to process wrong list box items.
Following is the XAML snippet.
                <ListBox ScrollViewer.CanContentScroll="False" ScrollViewer.HorizontalScrollBarVisibility="Disabled"  ScrollViewer.VerticalScrollBarVisibility="Auto" SelectedItem="{Binding SelectedNotificationItem}" ItemsSource="{Binding MyArray}" BorderThickness="0" Margin="0, 0, 0, 0" ItemContainerStyle="{StaticResource HoverBackgroundStyle}"  Name="NotificationListBox" >
                 <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Grid>
                            <Border BorderThickness="4,0,0,0" BorderBrush="{Binding ColorThing, Converter={StaticResource SeverityToColorConverter} }" Margin="0, 0, 0, 0">
                                <StackPanel Margin="8, 0" Orientation="Vertical">
                                    <TextBlock   Style="{StaticResource HoverUnderlineStyle}" FontWeight="Bold" TextTrimming="CharacterEllipsis" Name="Title" Text="{Binding Title}" TextWrapping="WrapWithOverflow" Margin="0,4,0,0" >
                                        <TextBlock.InputBindings>
                                            <MouseBinding MouseAction="LeftClick" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.ClickTitleCommand}"></MouseBinding>
                                        </TextBlock.InputBindings>
                                    </TextBlock>

                                    <TextBlock  FontWeight="Normal" Name="Desc" Text="{Binding Description}" TextWrapping="WrapWithOverflow">

                                    </TextBlock>
                                    <TextBlock  FontWeight="Normal" Foreground="Gray" Name="Date" Text="{Binding CreationTime, StringFormat={}{0:ddd MM.dd.yyyy} }" Margin="0,4,0,4">
                                    </TextBlock>

                                </StackPanel>
                            </Border>
                        </Grid>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

A: Could you try changing your XAML to SelectedItem="{Binding SelectedNotificationItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"

A: Change the ListBox into an ItemsControl and change the orientation to horizontal


text:
Q: How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")? I am having a problem converting a datetime which is in string format but I am not able to convert it using "yyyyMMdd" format.
My code is:
string tpoc = refSubClaim.BenefitsFolder.BenefitFolderIdNumber.ToString();
string[] tpocinfo = Regex.Split(tpoc,";");

for (int i = 0; i < tpocinfo.Length; i++)
{
    switch (i)
    {
        case 0:
        {
            string[] tpoc2 = Regex.Split(tpocinfo[0], ",");
            claimantAuxillaryRecord.TPOCDate2 = tpoc2[0].ToString();
            claimantAuxillaryRecord.TPOCAmount2 = Convert.ToDecimal(tpoc2[1]);
            claimantAuxillaryRecord.FundingDelayedBeyondTPOCStartDate2 = tpoc2[2].ToString();
        }
        break;

A: Parsing DateTime:
To parse a DateTime, use one of the following methods:

*

*DateTime.Parse

*DateTime.ParseExact
Alternatively, you may use try-parse pattern:

*

*DateTime.TryParse

*DateTime.TryParseExact
Read more about Custom Date and Time Format Strings.
Converting DateTime to a string:
To return a DateTime as a string in "yyyyMMdd" format, you may use ToString method.

*

*Code snippet example: string date = DateTime.ToString("yyyyMMdd");

*Note upper-cased M's refer to months and lower-cased m's to minutes.

Your case:
In your case, assuming you don't want to handle scenario when date is different format or misssing, it would be most convenient to use ParseExact:
string dateToParse = "20170506";
DateTime parsedDate = DateTime.ParseExact(dateToParse,
                                          "yyyyMMdd",
                                          CultureInfo.InvariantCulture);

A: Use  DateTime.TryParseExact() if you want to match against a specific date format
   string format = "yyyyMMdd";
    DateTime dateTime;
    DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,
                                             DateTimeStyles.None, out dateTime);

A: You could use DateTime.TryParse() instead of DateTime.Parse().
With TryParse() you have a return value if it was successful and with Parse() you have to handle an exception

A: Simply just do in this way.
string yourFormat = DateTime.Now.ToString("yyyyMMdd");

Happy coding :)

A: You can convert your string to a DateTime value like this:
DateTime date = DateTime.Parse(something);

You can convert a DateTime value to a formatted string like this:
date.ToString("yyyyMMdd");

A: It's the Simple way to convert to format
 DateTime.Now.ToString("yyyyMMdd");

A:
no its a string with yyyy/mm/dd and i need it in yyyyMMdd format

If you only need to remove the slashes from a string don't you just replace them?
Example:
myDateString = "2013/03/28";
myDateString = myDateString.Replace("/", "");

myDateString should now be "20130328".
Less of an overkill :)

A: if you have a date in a string with the format "ddMMyyyy" and want to convert it to "yyyyMMdd" you could do like this:
DateTime dt = DateTime.ParseExact(dateString, "ddMMyyyy",
                                  CultureInfo.InvariantCulture);
dt.ToString("yyyyMMdd");

A: Based on the property names it looks like you are trying to convert a string to a date by assignment:
claimantAuxillaryRecord.TPOCDate2 = tpoc2[0].ToString();

It is probably due to the current UI culture and therefore it cannot interpret the date string correctly when assigned.

A: From C# 6:
var dateTimeUtcAsString = $"{DateTime.UtcNow:o}";

The result will be: "2019-01-15T11:46:33.2752667Z"

A: String to yyyy-MM-dd date format:
Example:
TxtCalStDate.Text = Convert.ToDateTime(objItem["StartDate"]).ToString("yyyy/MM/dd");

A: If you want to have DATE as string with TIME as well. We can do like this:
    //Date and Time is taking as current system Date-Time
    DateTime.Now.ToString("yyyyMMdd-HHmmss");

A: A more simple way I came across while searching for this answer as well;
string date = DateTime.Now.ToString("yyyyMMdd", System.Globalization.CultureInfo.GetCultureInfo("en-US"));

A: You can try these codes
claimantAuxillaryRecord.TPOCDate2  = Convert.ToDateTime(tpoc2[0]).ToString("yyyyMMdd");

Or
claimantAuxillaryRecord.TPOCDate2 = Convert.ToDateTime(tpoc2[0]).ToString("yyyyMMdd hh:mm:ss");


text:
Q: To identify duplicates in a 5.5 Billion record Teradata table I have 5.5 Billion records in a Teradata table. The table has 114 columns. What's the best way to find exact duplicate rows? I need to get the duplicate records inserted in another table for further processing.
Thanks


text:
Q: How to get sum of char values produced in a loop? Sorry if the title is misleading or is confusing, but here is my dilemma.
I am inputting a string, and want to assign a value to each capitalized letter in the alphabet (A=1, .. Z=26) and then add the values of each letter in that string.
Example: ABCD = 10  (since 1 + 2 + 3 + 4)
But I don't know how to add all the values in the string
NOTE: This is only for capitalized letters and strings
public class Test {

    public static void main(String[] args) {

        Scanner scannerTest = new Scanner(System.in);
        System.out.println("Enter a name here: ");

        String str = scannerTest.nextLine();

        char[] ch = str.toCharArray();
        int temp_integer = 64;

        for (char c : ch) {
            int temp = (int) c;

               if (temp <= 90 & temp >= 65){
            int sum = (temp - temp_integer);
            System.out.println(sum);
        }
      }
    }
}

So, as you can see I print out the sum for each time its looped,
meaning: if I input "AB", the output will be 1 and 2.
However, I want to go a step further, and add these two values together, but I'm stumped, any suggestions or help? (NOTE: this is not a assignment or anything, just practising problem sets)

A: I would prefer to use the character literals. You know that the range is A to Z (1 to 26), so you can subtract 'A' from each char (but you need to add 1 because it doesn't start at 0). I would also call toUpperCase on the input line. Something like,
Scanner scannerTest = new Scanner(System.in);
System.out.println("Enter a name here: ");
String str = scannerTest.nextLine().toUpperCase();
int sum = 0;
for (char ch : str.toCharArray()) {
    if (ch >= 'A' && ch <= 'Z') {
        sum += 1 + ch - 'A';
    }
}
System.out.printf("The sum of %s is %d%n", str, sum);

Which I tested with your example
Enter a name here:
ABCD
The sum of ABCD is 10

A: Using 64 to represent the character before 'A' in the ascii table is difficult to understand, you can perform substration between characters in Java directly.
So if 'A' represent 1, then just do c - 'A' + 1 will give you the corresponding integer value for each capitalized letter.
To get the sum, just sum up: initialize the sum as 0, and in the for loop, add increment sum by the value you calculated. You can use the incremental assignment operation: +=
Scanner scannerTest = new Scanner(System.in);
    System.out.println("Enter a name here: ");

    String str = scannerTest.nextLine();

    char[] ch = str.toCharArray();
    int sum = 0;
    for (char c : ch) {
        sum += c - 'A' + 1;
    }
    System.out.println(sum);

A: Change only your for to these:
int sum = 0;
for(int i = 0; i < ch.length; i++){
    sum += (int) ch[i] - 96;
    System.out.println(sum);
}

The sum += (int) ch[i] - 96; is because the char a is the value 97, as your say, you want char a corresponde to 1, note that a is different than A
Check the char value here: https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html
This was tested and worked fine! Good Luck

A: It would look something like this (in C programming language) which you can easily modify for other programming languages:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
  int i;
  char word[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  unsigned int sum = 0;
  unsigned int charVal;

  for (i=0; i < strlen(word); ++i) {
    charVal = word[i] - 'A' + 1;
    printf("Value of %c is %d\n", word[i], charVal);
    sum += charVal;
  }
  printf("Sum of %s = %d\n", word, sum);
  return(0);
}

The trick is to take the character value, subtract the baseline 'A' value and add 1 to arrive at your calculation range:
charVal = word[i] - 'A' + 1;

A: Achieve the same in a concise way by employing Java 8's lambda functions
String str = "ABCD";
int sum = str.chars()
                .filter(c -> c >= 'A' && c <= 'Z')
                .map(c -> 1 + c - 'A')
                .reduce(0, Integer::sum);


text:
Q: Concatenate String Constant with auto incremented integer and store in mysql database I want to Store something like this in userID of Database(DDN00000001,DDN00000002,DDN00000003 and so on , as user ID)
How to concatenate the string in front of integer and store in database.

A: If you want to convert integer identifiers to this form in PHP, before sending it to the database, you can use str_pad:
$user_id = 1;
$padded_user_id = 'DDN' . str_pad ($user_id, 8, '0', STR_PAD_LEFT);


text:
Q: Chopper active when no power? I'm looking in how to activate a current chopper in a motor application, when there is no power available from a power supply Vin. This should prevent the motor from turning too fast in power off mode.
Now there is a Vin DC voltage (+48VDC, current limited to 15A) and the intermediate circuit voltage Vbus. The intermediate circuit voltage can be increase by turning the motor, when there is no Vin voltage. On Vbus there is a current chopper Q1 with R1, that shorts Vbus in normal operation, when the Vbus > Vin + threshold and this is done by a uC, that applies a signal to the chopper. Now I designed the following concept:

The concept should allow a disconnected Vin to trigger Q1 and so short the Vbus, but I see some problems here, why this will not work:

*

*At startup when Vin ramps up, the voltage will be shorted until it reaches the threshold to trigger the chopper off. It might work, since Vin is current limited with hiccup mode, but I'm unsure about this

*The most critical part I think is the linear mode of Q1, when Vin is too low at startup. This might destroy Q1 and so somehow the braking should start only when there is enough Vbus voltage, in this case +12VDC.

So, has anyone an idea on how to improve the concept or maybe tackle the problem from a different angle?
Edit:
Something else that came to my mind was a relay, but I would like to prevent electromechanical stuff for this:
Edit: I have one problem, there seems to exist no NC relay for 30A and more. So I need somehow another method.

Edit 2: Another solution that came to my mind is to use a MOSFET in diode mode and then trigger the gate connection with a NC relay. The thing is, there are huge losses in the FET, since a modern FET has a Vgth of around 1-2V and so for a current of 15A, the FET will probably has a 4V drop, which leads to 60W of losses. Since the high current through the resistor comes only with increasing voltage, this increasing voltage might be usable to fully turn on the FET.
If for example there are 5V voltage from the motor, there will flow 2.5A, a loss of around 10W in the FET. This 5V can then be used (threshold based to somehow turn the FET fully on. I'm still thinking of this logic to achieve this.
What I could do ist to directly source the MOSFET from the Power Input, so this might work without high losses, since only at very low voltage the losses are high, but the resistor stops too much current and so this should be fine. The relay can probably also be replaced by a PMOS

A: DC contactors with NC contacts are not easy to find. More commons are auxiliaries contactors, with 4 NC contacts, for AC current. Some manufacturers have available coils for 48 Vdc, that you can use directly. But you have to derate current of contacts to use them in DC according datasheet, and if not enough current with one contact, use parallel contacts connected to individual resistors, just to split current and not to be overloaded. You can keep the resistor to the MOSFET or use the new ones with diodes. See example for 2 poles.

Regarding the startup, a delay timer (KT) should switch DC power to motor controller after this contactor has been actívated, to avoid the initial short of braking resistors.
EDIT: Added diagram with logic. An auxiliary relay can activate MOSFET Q1 when power power shutdown (t4), if gate control can support this voltage. The braking relay KB should keep activated this time with a capacitor bank, so when the NC contact close (t3), low voltage will remain in Vbus. If a inrush current limiter is necessary in the aux. power supply because cap. bank, timer on delay t1 > t2.
With this stuff, the brake relay will not switch with Vbus voltage neither in start or shutdown.

simulate this circuit – Schematic created using CircuitLab


text:
Q: Is is possible to set BufferSize in FileStream? I need to write large data into disk, so I use FileStream.openAsync():
this.file_stream = new FileStream();
this.file_stream.openAsync(fl, FileMode.WRITE);

//Write large get from database
while(i < 10240000) {
    this.file_stream.write(bigDatas)
    i = i + 1;
}

And then, the app killed by Linux kenkel (message copy from 'dmesg'):

Killed process 4267 (MyFlex) total-vm:1282708kB, anon-rss:863176kB, file-rss:756kB

So, is there any way to set buffer size in FileStream?

A: You are trying to execute a cycle 10 millions of times.
The problem is not the buffer of the FileStream. Say thanks to Linux that stop the execution of your App and avoid that your system blow up.
You need to save one file and when the file is saved, go for the next, look at the code, the "writeFile" function wait for the CLOSE event to execute itself again.
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.events.Event;

var file:File;
var stream:FileStream = new FileStream();

stream.addEventListener(Event.CLOSE, writeFile);

var cont:uint = 0;
//---I do not think that you need to run a code 10 million times (This code will save the file 10 times)
var total:uint = 10;

//---Write file in the Desktop in the folder "test"
function writeFile(evt:Event = null){

    cont++;

    if(cont == total + 1) {

        stream.removeEventListener(Event.COMPLETE, writeFile);

        trace("finish");

    }else{

        trace("write file number " + cont);

        file = File.desktopDirectory.resolvePath("test/data" + cont);

        stream.openAsync(file, FileMode.WRITE);

        stream.writeByte(0xFF);

        stream.close();

    }

}

//---Execute the function for first time
writeFile();