text:
Q: Shiny Not Displaying Plot Data I have a data set that looks like the following:
   Rk G       Date    Age Team H.A Opponent Outcome Player postMVP game.num variable value
1:  1 1 2004-11-03 30-270  PHO          ATL W (+30) 1      0        1       V1     1
2:  2 2 2004-11-05 30-272  PHO   @      PHI W (+10) 1      0        2       V1     2
3:  3 3 2004-11-06 30-273  PHO   @      NJN W (+32) 2      0        3       V1     3
4:  4 4 2004-11-09 30-276  PHO   @      CHI W (+20) 3      0        4       V1     4
5:  5 5 2004-11-10 30-277  PHO   @      CLE  L (-5) 4      0        5       V1     5
6:  6 6 2004-11-13 30-280  PHO          SAC  L (-2) 2      0        6       V1     6

I have created a Shiny application with the following code:
Server:
library(shiny); library(dplyr); library(ggvis); library(mosaic); library(ggplot2); library(data.table)

server <- function(input, output){

plotData <- reactive({
var = input$stat
## now filtering on var using the melted data
df <- data %>%
  filter(Player %in% input$Player,
         variable == var)
df
})

 output$plot <- renderPlot({
ggplot(plotData(), aes(x=game.num, y=value, color=Player, shape = postMVP)) +
  geom_point() + labs(x="Game Number", y = "Value") + scale_fill_discrete(name = "Player, Year")
 })
}

UI:
library(shiny)

shinyUI(fluidPage(

tags$head(
tags$style(HTML("

 .multicol {

   -webkit-column-count: 3; /* Chrome, Safari, Opera */

   -moz-column-count: 3; /* Firefox */

   column-count: 3;

 }

   "))

  ),

 titlePanel(h1('Title', align = "center")),
 hr(),
 mainPanel(
 tabsetPanel(type='tabs',
            tabPanel("Plot", plotOutput("plot")))),
 hr(),
 fluidRow(
   column(2,
       selectInput('stat', "Statistic", choices=c('Field Goal %'='FG.Perc', '3 Pt. %'='ThreePointPerc',"Free Throw %" = "FTPerc", "Rebounds" = "TRB", "Assists" ="ASST", 'Steals' = "STL", "Points" = "PTS", "True Shooting %"= "TrueShootingPerc", "Eff. FG %"= "eFG", "Total Reb. %" = "TRBPerc", "Off. Rating" = "ORtg", "Def. Rating" = "DRtg")))
),

  wellPanel(
  tags$div(class = "multicol", checkboxGroupInput("player", choices = c("one" = 1, "two" = 2, "three" = 3, "four" = 4
    ), label = "Player/Year"
      ))
)

  ))

The application runs and there are not any errors, but the plot does not appear. The axes and background appears, but none of the data plots. If I don't filter the data, i.e. change plotData() to be the total data set, the data plots. Thus, I think there might be something going on in the filtering of the data, but I can't figure out what.


text:
Q: Python dynamic import I have a list of tuples like [(module_name, module_abs_path)(mod2, path2), ...]
The modules are located in the 'modules' subdir where my script lives. I am trying to write a script which reads a conf file and makes some variables from the conf file available to the modules from the modules dir. My intention is to load and run all the modules from this script, so they get access to these variables.
Things I have tried so far but failed:

*

*Tried using  __import__() but it says running by file name is not allowed

*Tried importlib.import_module() but gives the same error.

How should I go about doing this?

A: Have you tried to fix up the path before importing?
from __future__ import print_function
import importlib
import sys

def import_modules(modules):
    modules_dict = dict()
    for module_name, module_path in modules:
        sys.path.append(module_path)  # Fix the path
        modules_dict[module_name] = importlib.import_module(module_name)
        sys.path.pop()                # Undo the path.append
    return modules_dict

if __name__ == '__main__':
    modules_info = [
        ('module1', '/abs/path/to/module1'),
    ]

    modules_dict = import_modules(modules_info)
    # At this point, we can access the module as
    # modules_dict['module1']
    # or...

    globals().update(modules_dict)
    # ... simply as module1

redpajama_set_name: RedPajamaStackExchange


text:
Q: Benchmark express apis with autocannon from postman collection I need to benchmark all my express apis.
I found this package on github. Examples are listed only for one get request.
There are also some other samples for other requests as well.
I want to know should I create a separate script for all the APIs and run them once.
I already have a postman collection for all the APIs. Is there any way I can use that to benchmark them?
If there is any other way to benchmark express APIs, please suggest.
Update
const autocannon = require("autocannon");
const fs = require("fs");

const collection = JSON.parse(fs.readFileSync("./customer-apis-v1.3.2.json", "UTF-8"));
const requests = collection.item;

(async function test() {
  for (const request of requests) {
    console.log(`Testing ${request.name}`);
    for (const item of request.item) {
      const result = await autocannon({
        title: item.name,
        url: item.request.url.raw,
        method: item.request.method,
      });
      autocannon.printResult(result);
    }
  }
})().catch((error) => console.log(error));

A: You can export your Postman Collection as JSON.

*

*Right Click on the collection

*Click export

*Choose Collection type

*Click export
The exported file will be a .json file and will look like this:
{
    "info": {
        "_postman_id": "...",
        "name": "...",
        "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
    },
    "item": [
        {
            "name": "name",
            "request": {
                "method": "GET",
                "header": [],
                "url": {
                    "raw": "http://...",
                    "protocol": "http",
                    "host": [
                        ...
                    ],
                    "path": [
                        ...
                    ],
                    "query": [
                        {
                            "key": "...",
                            "value": "..."
                        }
                    ]
                }
            },
            "response": []
        }
    ],
    "protocolProfileBehavior": {}
}

Then you can use autocannon programatically and read the json file
const autocannon = require("autocannon");
const fs = require("fs");

// read array of items from exported .json file from postman
const requests = JSON.parse(fs.readFileSync("path/to/postman/exported.json", "UTF-8")).items;

async function test() {
  for (const item of requests) {
    // test request using autocannon, pass the method, body, etc. on the autocannon options
    // you might need to manipulate your data in item so you can pass it to autocannon

    console.log(`Testing ${item.name}`);

    const result = await autocannon({
      url: item.request.url.raw,
      method: item.request.method,
      ... // read other options here: https://github.com/mcollina/autocannon#autocannonopts-cb
    })
    console.log(result);
    // or print table
    autocannon.printResult(result);
  }
}

You can also do it without await

The other way is to use Postman built-in Testing utility

*

*Right click on the collection

*Click Edit

*Click Tests tab

*Write your test script there

Doc about writing test: https://learning.postman.com/docs/writing-scripts/test-scripts/
Doc about monitoring test performance: https://learning.postman.com/docs/designing-and-developing-your-api/monitoring-your-api/intro-monitors/


text:
Q: Jbpm6.1.0 console not working - Failed to start service jboss.deployment.unit."jbpm-console.war".WeldService: I'm getting below error while starting the jboss the server.
Just i installed the JBPM 6.1.0 and trying to start the server and deployment also getting fail.
Please advise...

2014-09-16 12:16:54,008 ERROR
  [org.jboss.as.controller.management-operation]
  (DeploymentScanner-threads - 2) JBAS014613: Operation
  ("full-replace-deployment") failed - address: ([]) - failure
  description: {
      "JBAS014771: Services with missing/unavailable dependencies" => ["jboss.deployment.unit.\"jbpm-console.war\".weld.weldClassIntrospector
  is missing [jboss.deployment.unit.\"jbpm-console.war\".beanmanager]"],
      "JBAS014879: One or more services were unable to start due to one or more indirect dependencies not being available." => {
          "Services that were unable to start:" => ["jboss.deployment.unit.\"jbpm-console.war\".INSTALL"],
          "Services that may be the cause:" => [
              "jboss.deployment.unit.\"jbpm-console.war\".beanmanager",
              "jboss.http-upgrade-registry.default",
              "jboss.remoting.remotingConnectorInfoService.http-remoting-connector"
          ]
      } }
2014-09-16 12:16:54,046 INFO  [org.jboss.as.server]
  (DeploymentScanner-threads - 2) JBAS018565: Replaced deployment
  "jbpm-console.war" with deployment "jbpm-console.war" 2014-09-16
  12:16:54,048 INFO  [org.jboss.as.controller]
  (DeploymentScanner-threads - 2) JBAS014774: Service status report
  JBAS014775:    New missing/unsatisfied dependencies:
        service jboss.naming.context.java.app.jbpm-console (unavailable) dependents: [service jboss.deployment.unit."jbpm-console.war".INSTALL]
  service jboss.naming.context.java.module.jbpm-console.jbpm-console

(unavailable) dependents: [service
  jboss.deployment.unit."jbpm-console.war".INSTALL]  JBAS014777:
  Services which failed to start:      service
  jboss.serverManagement.controller.management.http:
  org.jboss.msc.service.StartException in service
  jboss.serverManagement.controller.management.http: JBAS015811: Failed
  to start the http-interface service
        service jboss.jacorb.poa-service.rootpoa: org.jboss.msc.service.StartException in service
  jboss.jacorb.poa-service.rootpoa: JBAS016490: Failed to resolve
  initial reference RootPOA
        service jboss.undertow.listener.default: org.jboss.msc.service.StartException in service
  jboss.undertow.listener.default: Could not start http listener

A: This means that there is another server in the same port that jboss is using:
"org.jboss.msc.service.StartException in service jboss.undertow.listener.default: Could not start http listener", if that's not the issue, please provide the full stack trace.
Regards


text:
Q: Sorting a list Based on list item length country_list= ['Afghanistan', 'Albania', 'Algeria', 'Andorra', 'Angola', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Australia', 'Austria', 'Austrian Empire', 'Azerbaijan', 'Baden*', 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Bavaria*', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bolivia', 'Bosnia and Herzegovina', 'Botswana', 'Brazil', 'Brunei', 'Brunswick', 'Bulgaria', 'Burkina Faso', 'Burma', 'Burundi', 'Cabo Verde', 'Cambodia', 'Cameroon', 'Canada', 'Cayman Islands, The', 'Central African Republic', 'Central American Federation*', 'Chad', 'Chile', 'China', 'Colombia', 'Comoros', 'Congo Free State', 'Costa Rica', 'Ivory Coast', 'Croatia', 'Cuba', 'Cyprus', 'Czechia', 'Czechoslovakia', 'Democratic Republic of the Congo', 'Denmark', 'Djibouti', 'Dominica', 'Dominican Republic', 'Duchy of Parma, The*', 'East Germany (German Democratic Republic)', 'Ecuador', 'Egypt', 'El Salvador', 'Equatorial Guinea', 'Eritrea', 'Estonia', 'Eswatini', 'Ethiopia', 'Federal Government of Germany (1848-49)*', 'Fiji', 'Finland', 'France', 'Gabon', 'Gambia, The', 'Georgia', 'Germany', 'Ghana', 'Grand Duchy of Tuscany', 'Greece', 'Grenada', 'Guatemala', 'Guinea', 'Guinea-Bissau', 'Guyana', 'Haiti', 'Hanover*', 'Hanseatic Republics*', 'Hawaii*', 'Hesse*', 'Holy See', 'Honduras', 'Hungary', 'Iceland', 'India', 'Indonesia', 'Iran', 'Iraq', 'Ireland', 'Israel', 'Italy', 'Jamaica', 'Japan', 'Jordan', 'Kazakhstan', 'Kenya', 'Kingdom of Serbia/Yugoslavia*', 'Kiribati', 'Korea', 'Kosovo', 'Kuwait', 'Kyrgyzstan', 'Laos', 'Latvia', 'Lebanon', 'Lesotho', 'Lew Chew (Loochoo)*', 'Liberia', 'Libya', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall Islands', 'Mauritania', 'Mauritius', 'Mecklenburg-Schwerin*', 'Mecklenburg-Strelitz*', 'Mexico', 'Micronesia', 'Moldova', 'Monaco', 'Mongolia', 'Montenegro', 'Morocco', 'Mozambique', 'Namibia', 'Nassau*', 'Nauru', 'Nepal', 'Netherlands, The', 'New Zealand', 'Nicaragua', 'Niger', 'Nigeria', 'North German Confederation*', 'North German Union*', 'North Macedonia', 'Norway', 'Oldenburg*', 'Oman', 'Orange Free State*', 'Pakistan', 'Palau', 'Panama', 'Papal States*', 'Papua New Guinea', 'Paraguay', 'Peru', 'Philippines', 'Piedmont-Sardinia*', 'Poland', 'Portugal', 'Qatar', 'Republic of Genoa*', 'Republic of Korea (South Korea)', 'Republic of the Congo', 'Romania', 'Russia', 'Rwanda', 'Saint Kitts and Nevis', 'Saint Lucia', 'Saint Vincent and the Grenadines', 'Samoa', 'San Marino', 'Sao Tome and Principe', 'Saudi Arabia', 'Schaumburg-Lippe*', 'Senegal', 'Serbia', 'Seychelles', 'Sierra Leone', 'Singapore', 'Slovakia', 'Slovenia', 'Solomon Islands, The', 'Somalia', 'South Africa', 'South Sudan', 'Spain', 'Sri Lanka', 'Sudan', 'Suriname', 'Sweden', 'Switzerland', 'Syria', 'Tajikistan', 'Tanzania', 'Texas*', 'Thailand', 'Timor-Leste', 'Togo', 'Tonga', 'Trinidad and Tobago', 'Tunisia', 'Turkey', 'Turkmenistan', 'Tuvalu', 'Two Sicilies*', 'Uganda', 'Ukraine', 'Union of Soviet Socialist Republics*', 'United Arab Emirates, The', 'United Kingdom', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Venezuela', 'Vietnam', 'Yemen', 'Zambia', 'Zimbabwe']

How I can sort this list based on this elements length using python?

A: Use sorted() with key=len:
country_list = ['Afghanistan', 'Albania', 'Algeria', 'Andorra', 'Angola', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Australia', 'Austria', 'Austrian Empire', 'Azerbaijan', 'Baden*', 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Bavaria*', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bolivia', 'Bosnia and Herzegovina', 'Botswana', 'Brazil', 'Brunei', 'Brunswick', 'Bulgaria', 'Burkina Faso', 'Burma', 'Burundi', 'Cabo Verde', 'Cambodia', 'Cameroon', 'Canada', 'Cayman Islands, The', 'Central African Republic', 'Central American Federation*', 'Chad', 'Chile', 'China', 'Colombia', 'Comoros', 'Congo Free State', 'Costa Rica', 'Ivory Coast', 'Croatia', 'Cuba', 'Cyprus', 'Czechia', 'Czechoslovakia', 'Democratic Republic of the Congo', 'Denmark', 'Djibouti', 'Dominica', 'Dominican Republic', 'Duchy of Parma, The*', 'East Germany (German Democratic Republic)', 'Ecuador', 'Egypt', 'El Salvador', 'Equatorial Guinea', 'Eritrea', 'Estonia', 'Eswatini', 'Ethiopia', 'Federal Government of Germany (1848-49)', 'Fiji', 'Finland', 'France', 'Gabon', 'Gambia, The', 'Georgia', 'Germany', 'Ghana', 'Grand Duchy of Tuscany', 'Greece', 'Grenada', 'Guatemala', 'Guinea', 'Guinea-Bissau', 'Guyana', 'Haiti', 'Hanover', 'Hanseatic Republics*', 'Hawaii*', 'Hesse*', 'Holy See', 'Honduras', 'Hungary', 'Iceland', 'India', 'Indonesia', 'Iran', 'Iraq', 'Ireland', 'Israel', 'Italy', 'Jamaica', 'Japan', 'Jordan', 'Kazakhstan', 'Kenya', 'Kingdom of Serbia/Yugoslavia*', 'Kiribati', 'Korea', 'Kosovo', 'Kuwait', 'Kyrgyzstan', 'Laos', 'Latvia', 'Lebanon', 'Lesotho', 'Lew Chew (Loochoo)', 'Liberia', 'Libya', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall Islands', 'Mauritania', 'Mauritius', 'Mecklenburg-Schwerin', 'Mecklenburg-Strelitz*', 'Mexico', 'Micronesia', 'Moldova', 'Monaco', 'Mongolia', 'Montenegro', 'Morocco', 'Mozambique', 'Namibia', 'Nassau*', 'Nauru', 'Nepal', 'Netherlands, The', 'New Zealand', 'Nicaragua', 'Niger', 'Nigeria', 'North German Confederation*', 'North German Union*', 'North Macedonia', 'Norway', 'Oldenburg*', 'Oman', 'Orange Free State*', 'Pakistan', 'Palau', 'Panama', 'Papal States*', 'Papua New Guinea', 'Paraguay', 'Peru', 'Philippines', 'Piedmont-Sardinia*', 'Poland', 'Portugal', 'Qatar', 'Republic of Genoa*', 'Republic of Korea (South Korea)', 'Republic of the Congo', 'Romania', 'Russia', 'Rwanda', 'Saint Kitts and Nevis', 'Saint Lucia', 'Saint Vincent and the Grenadines', 'Samoa', 'San Marino', 'Sao Tome and Principe', 'Saudi Arabia', 'Schaumburg-Lippe*', 'Senegal', 'Serbia', 'Seychelles', 'Sierra Leone', 'Singapore', 'Slovakia', 'Slovenia', 'Solomon Islands, The', 'Somalia', 'South Africa', 'South Sudan', 'Spain', 'Sri Lanka', 'Sudan', 'Suriname', 'Sweden', 'Switzerland', 'Syria', 'Tajikistan', 'Tanzania', 'Texas*', 'Thailand', 'Timor-Leste', 'Togo', 'Tonga', 'Trinidad and Tobago', 'Tunisia', 'Turkey', 'Turkmenistan', 'Tuvalu', 'Two Sicilies*', 'Uganda', 'Ukraine', 'Union of Soviet Socialist Republics*', 'United Arab Emirates, The', 'United Kingdom', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Venezuela', 'Vietnam', 'Yemen', 'Zambia', 'Zimbabwe']
country_list = sorted(country_list, key=len)

# pretty print on screen:
from pprint import pprint
pprint(country_list)

Prints:
['Chad',
 'Cuba',
 'Fiji',
 'Iran',
 'Iraq',
 'Laos',
 'Mali',
 'Oman',
 'Peru',
 'Togo',
 'Benin',
 'Burma',
 'Chile',
 'China',
 'Egypt',
 'Gabon',
 'Ghana',
 'Haiti',
 'India',
 'Italy',
 'Japan',
 'Kenya',
 'Korea',
 'Libya',
 'Malta',
 'Nauru',
 'Nepal',
 'Niger',
 'Palau',
 'Qatar',
 'Samoa',
 'Spain',
 'Sudan',
 'Syria',
 'Tonga',
 'Yemen',
 'Angola',
 'Baden*',
 'Belize',
 'Brazil',
 'Brunei',
 'Canada',
 'Cyprus',
 'France',
 'Greece',
 'Guinea',
 'Guyana',
 'Hesse*',
 'Israel',
 'Jordan',
 'Kosovo',
 'Kuwait',
 'Latvia',
 'Malawi',
 'Mexico',
 'Monaco',
 'Norway',
 'Panama',
 'Poland',
 'Russia',
 'Rwanda',
 'Serbia',
 'Sweden',
 'Texas*',
 'Turkey',
 'Tuvalu',
 'Uganda',
 'Zambia',
 'Albania',
 'Algeria',
 'Andorra',
 'Armenia',
 'Austria',
 'Bahamas',
 'Bahrain',
 'Belarus',
 'Belgium',
 'Bolivia',
 'Burundi',
 'Comoros',
 'Croatia',
 'Czechia',
 'Denmark',
 'Ecuador',
 'Eritrea',
 'Estonia',
 'Finland',
 'Georgia',
 'Germany',
 'Grenada',
 'Hanover',
 'Hawaii*',
 'Hungary',
 'Iceland',
 'Ireland',
 'Jamaica',
 'Lebanon',
 'Lesotho',
 'Liberia',
 'Moldova',
 'Morocco',
 'Namibia',
 'Nassau*',
 'Nigeria',
 'Romania',
 'Senegal',
 'Somalia',
 'Tunisia',
 'Ukraine',
 'Uruguay',
 'Vanuatu',
 'Vietnam',
 'Barbados',
 'Bavaria*',
 'Botswana',
 'Bulgaria',
 'Cambodia',
 'Cameroon',
 'Colombia',
 'Djibouti',
 'Dominica',
 'Eswatini',
 'Ethiopia',
 'Holy See',
 'Honduras',
 'Kiribati',
 'Malaysia',
 'Maldives',
 'Mongolia',
 'Pakistan',
 'Paraguay',
 'Portugal',
 'Slovakia',
 'Slovenia',
 'Suriname',
 'Tanzania',
 'Thailand',
 'Zimbabwe',
 'Argentina',
 'Australia',
 'Brunswick',
 'Guatemala',
 'Indonesia',
 'Lithuania',
 'Mauritius',
 'Nicaragua',
 'Singapore',
 'Sri Lanka',
 'Venezuela',
 'Azerbaijan',
 'Bangladesh',
 'Cabo Verde',
 'Costa Rica',
 'Kazakhstan',
 'Kyrgyzstan',
 'Luxembourg',
 'Madagascar',
 'Mauritania',
 'Micronesia',
 'Montenegro',
 'Mozambique',
 'Oldenburg*',
 'San Marino',
 'Seychelles',
 'Tajikistan',
 'Uzbekistan',
 'Afghanistan',
 'Ivory Coast',
 'El Salvador',
 'Gambia, The',
 'New Zealand',
 'Philippines',
 'Saint Lucia',
 'South Sudan',
 'Switzerland',
 'Timor-Leste',
 'Burkina Faso',
 'Saudi Arabia',
 'Sierra Leone',
 'South Africa',
 'Turkmenistan',
 'Guinea-Bissau',
 'Liechtenstein',
 'Papal States*',
 'Two Sicilies*',
 'Czechoslovakia',
 'United Kingdom',
 'Austrian Empire',
 'North Macedonia',
 'Congo Free State',
 'Marshall Islands',
 'Netherlands, The',
 'Papua New Guinea',
 'Equatorial Guinea',
 'Schaumburg-Lippe*',
 'Dominican Republic',
 'Lew Chew (Loochoo)',
 'Orange Free State*',
 'Piedmont-Sardinia*',
 'Republic of Genoa*',
 'Antigua and Barbuda',
 'Cayman Islands, The',
 'North German Union*',
 'Trinidad and Tobago',
 'Duchy of Parma, The*',
 'Hanseatic Republics*',
 'Mecklenburg-Schwerin',
 'Solomon Islands, The',
 'Mecklenburg-Strelitz*',
 'Republic of the Congo',
 'Saint Kitts and Nevis',
 'Sao Tome and Principe',
 'Bosnia and Herzegovina',
 'Grand Duchy of Tuscany',
 'Central African Republic',
 'United Arab Emirates, The',
 'North German Confederation*',
 'Central American Federation*',
 'Kingdom of Serbia/Yugoslavia*',
 'Republic of Korea (South Korea)',
 'Democratic Republic of the Congo',
 'Saint Vincent and the Grenadines',
 'Union of Soviet Socialist Republics*',
 'Federal Government of Germany (1848-49)',
 'East Germany (German Democratic Republic)']

A: Another way is: list.sort(key=lambda x: len(x))


text:
Q: Data Verify based on Dropdownlist Selection in ASP.net MVC I have a Selection List in my View and I am trying to call it in my Controller. I have 2 requirements to satisfy.
1 - If the user selects SSN, then the TaxID input should be equal to SSN in my Table.
2 - If the user selects FEIN, then the TaxID input should be equal to FEIN in my Table.
I am not sure how to write the condition where the system would check as per the above requirements.
I have the controller Code where the system can check only one condition.
View:
@using (Html.BeginForm("CorporationRegistrationPg1", "Corporation", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
<body>
@Html.DropDownListFor(x => x.TAxIDType, Model.TAxIDType)
            @Html.TextBoxFor(x => x.TaxID, new { @class = "feintextbox", maxlength = 9, @placeholder = "xxxxxxxxx" })
            @Html.ValidationMessageFor(x => x.TaxID)

@Html.TextBoxFor(x => x.EmailID, new { @class = "emailid" })
            @Html.ValidationMessageFor(x => x.EmailID)
</body>

Controller:

public ActionResult CorporationRegistrationPg1(Testing CorporationRegistration, string EmailID, int TaxID, string TAxIDType)
        {
            if (ModelState.IsValid)
            {
                using (SUPRTestingDBEntities2 db = new SUPRTestingDBEntities2())
                {
                    if (TAxIDType == "SSN")
                    {
                        var obj = db.SUPRTesting.Where(a => a.EmailID.Equals(CorporationRegistration.EmailID) && a.TaxID.Equals(CorporationRegistration.SSN)).FirstOrDefault();

                        if (obj != null)
                        {
                            if (obj.Active == 0 && obj.Submit == 0)
                            {
                                Session["LoginID"] = obj.LoginID.ToString();
                                Session["EmailAddress"] = obj.EmailID.ToString();
                                return RedirectToAction("CorporationRegistrationPg2");
                            }
                            else
                            {
                                return View();
                            }
                        }
                        else if (obj == null)
                        {
                            return View();
                        }
                    }
                    else if (TAxIDType=="FEIN")
                    {
                        var obj = db.SUPRTesting.Where(a => a.EmailID.Equals(CorporationRegistration.EmailID) && a.TaxID.Equals(CorporationRegistration.FEIN)).FirstOrDefault();

                        if (obj != null)
                        {
                            if (obj.Active == 0 && obj.Submit == 0)
                            {
                                Session["LoginID"] = obj.LoginID.ToString();
                                Session["EmailAddress"] = obj.EmailID.ToString();
                                return RedirectToAction("CorporationRegistrationPg2");
                            }
                            else
                            {
                                return View();
                            }
                        }
                        else if (obj == null)
                        {
                            return View();
                        }
                    }}
            }return View();
        }

In the Controller, I am trying to call the TaxIDType, and I am able to pass the value. But, the new problems are I am unable to check if the TaxID is equal to SSN/FEIN as the system always returns SSN/FEIN as 0 even though I have data in there and system is returning to the same page.
The second problem is when the the system returns to the same page, the dropdown is throwing an error:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Web.Mvc.WebViewPage.Model.get returned null.
Can Someone help me with this?

A: How about you remove the textbox for TaxID and resolve based on the option selected in the dropdown:


text:
Q: Encontrar números en un texto en xamarin forms Estoy haciendo una app en xamarin que tiene que leer textos de ésta, extraer todos los números y sumarlos, el problema está en cómo puedo extraer los números de la variable sms y guardarlos en una variable para al final sumarlo todo, este es el código:
using Mensajeria;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mensajeria
{

    public class datos
    {
        public string num { get; set; }
        public string sms { get; set; }
    }
}
public class men
{
    public List<datos> mens { get; set; }
    public men()
    {
        mens = new List<datos>();
        Load();
    }
    public void Load()
    {
        mens.Add(new datos
        {
            num = "232843874",
            sms = "aldkajsldkaj 2535335 ñadalksdñka",
        });
        mens.Add(new datos
        {
            num = "3123122",
            sms = "skjdlaskdj 78778 laslajsldj"
        });
    }
}

A: Método #1
Puede usar lo siguiente para la extracción de los número en un string:
string valorResultante = new String(sms.Where(Char.IsDigit).ToArray());

Método #2
Un poco mas largo es:
Haciendo uso de la expresión regular \d+ para números enteros:
 string valorResultante = string.Join(string.Empty,
                    Regex.Matches(sms.Text, @"\d+").OfType<Match>().Select(m => m.Value));

Agregue la referencia: System.Text.RegularExpressions.Regex.

Resultado Obtenido
Con ambos métodos se pueden obtener los mismo resultados:

*

*Para esto: sms = "aldkajsldkaj 2535335 ñadalksdñka" el resultado sería: 2535335

*Para esto: sms = "skjdlaskdj 78778 laslajsldj" el resultado sería: 78778
Nota: Para admitir números negativos puede usar la expresión regular: @"-?\d+"

Espero le sea de ayuda!.


text:
Q: Cannot assign to property: 'tile' is a 'let' constant import Foundation

struct Model{

    struct Tile: Identifiable{
        var id: Int
        var x: Int
        var y: Int
        var isBomb = false
        var isSelected: Bool = false
        var numberOfNearbyBombs = 0
    }

    var tileGrid: Array<Array<Tile>>

    static var bombImage = "B"

    mutating func pressTile(_ tile: Tile){
        if !tile.isSelected{
            tile.isSelected = true  // returns this error
        }
    }
}


text:
Q: How to Scaffold database with the data inside it? I am using this code currently to scaffold a database.
dotnet ef dbcontext scaffold "Server=localhost; Database=db; User Id=root; Password=;" MySql.Data.EntityFrameworkCore  --project ../Test.Api/ -c myContext -o Migrations

It works without a problem, but it only gives me the Tables, is there a way to also get the data inside the tables converted to EF?

A:
is there a way to also get the data inside the tables converted to EF?

Not with EF. You would need to query the tables and save the data to JSON or somesuch.


text:
Q: What is the probability that a five-card poker hand contains all 4 suits? I know that my answer is wrong but I don't know why it is wrong.

What is the probability that a five-card poker hand contains all 4 suits?

What I did was I this:
$$\frac{C(4,1)\,C(13,1)\,C(3,1)\,C(13,1)\,C(2,1)\,C(13,1)\,C(1,1)\,C(13,1)\,C(4,4)\,C(48,1)}{C(52,5)}.$$
My logic for $C(4,1)$ was to choose one of the four suits, then the $C(13,1)$ was to pick one of the cards of that suit, and similarly for $C(3,1)$ subtracting one because there is one less suit to choose from.
Same logic applies for $C(2,1)$ and $C(1,1)$ and then $C(4,4)$ and $C(48,1)$ lets me choose any of the remaining $48$ cards from all suits because the last card doesn't matter.
Then answer ends up being something ridiculously big (not a fraction) and I don't know where I went wrong because I believe my logic is sound. What would be the correct answer and why?

A: Your numerator makes it seem like there is a distinction between the "first" chosen suit and the "second" chosen suit and so on... The denominator there is no way of knowing which was "first" or "second", they are all the same.  If you want order to matter then you need order to matter for both numerator and denominator.
Your numerator counted the number of ordered five-card hands where very specifically all suits are present among the first four of the cards.  If you wanted order to matter in the denominator like it does for the numerator then use $P(52,5)$ instead (i.e. $52\times 51\times 50\times 49\times 48$)... but then your numerator misses the mark in another way as it neglects to account for scenarios where the repeated suit occurs twice within the first four cards and the fifth card is a new suit such as $A\spadesuit A\heartsuit K\spadesuit A\diamondsuit A\clubsuit$
For a correct approach

*

*Via Inclusion-exclusion:

Count the number of five card hands.  Remove the number of five card hands missing at least a particular suit and which suit that was (among possibly missing more).  Add back the number of five card hands missing at least two particular suits, subtracting missing at least three particular suits, etc... You can end at that point since it is impossible to be missing four or more suits at a time here (but more complicated scenarios may have you continuing to alternate between adding and subtracting even further)
$$\dfrac{\binom{52}{5}-\binom{4}{1}\binom{39}{5}+\binom{4}{2}\binom{26}{5}-\binom{4}{3}\binom{13}{5}}{\binom{52}{5}}$$

*

*Directly:

Choose which suit is repeated.  Choose the two cards for that suit simultaneously.  For each suit isn't repeated (in alphabetical order) choose which card for that suit is used.
$$\dfrac{\binom{4}{1}\binom{13}{2}13^3}{\binom{52}{5}}$$
If you insist on phrasing this such that order matters... then make sure it matters for numerator and denominator...
Choose the positions of the two cards in the hand for the suit that is repeated.  Choose the suit for those cards.  Choose the rank of the first, and then the rank of the second.  Then for the remaining unused positions, choose a remaining suit and a remaining rank to be used.  Take the ratio with respect to the number of ordered hands possible.
$$\dfrac{\binom{5}{2}\cdot 4\cdot 13\cdot 12\cdot 3\cdot 13\cdot 2\cdot 13\cdot 1\cdot 13}{52\cdot 51\cdot 50\cdot 49\cdot 48}$$

A: First of all, $ \displaystyle {4 \choose 1}{4 \choose 2}{4 \choose 3}{4 \choose 4}$ will order the cards from $4$ suits. It does not matter which suit is chosen first or second or third or fourth. What matters is what cards are chosen in the hand.
Second, after you have chosen first $4$ cards, you multiply by $ \displaystyle {48 \choose 1}$ but that brings in duplicates again. If you chose $ \color  {red} {\diamondsuit A} $ as one of the first four cards and $ \color  {red} {\heartsuit A} $ as the fifth card as part of ${48 \choose 1}$, you will also have a combination where you chose $ \color  {red} {\heartsuit A} $ as one of the first four cards and $ \color  {red} {\diamondsuit A} $ as the fifth card, with other three cards remaining the same.
So to remove the duplicates, you can divide by $2$ and write it as,
$ \displaystyle {13 \choose 1}^4 {48 \choose 1} / \left(2 \cdot {52 \choose 5} \right)$
But I would suggest you approach it as follows -
Choose the suit you will have $2$ cards of and then choose $2$ cards from that suit.
So the desired probability is,
$ \displaystyle {4 \choose 1} {13 \choose 2}{13 \choose 1}^3 / {52 \choose 5}$


text:
Q: Get text prior to edit from inside QLineEdit::textEdited() When I receive a QLineEdit::textEdited() signal, can I see what the text was prior to the edit? I need to compare the text as it was prior to the edit and the text after the edit.
The textEdited() signal has only one argument, which is the new text. Calling QLineEdit::text() also returns the new text.
Right now I can only think of is holding the old text in a QString, and updating that QString each time there is an edit, but then I need to account for programmatic changes (made via QLineEdit::setText()).
Or is there another way to intercept a text change (via validators perhaps) that would allow me to get the text prior to change and after change simultaneously? Preferably for user-changes only (non programmatic).

A:
Right now I can only think of is holding the old text in a QString, and updating that QString each time there is an edit, but then I need to account for programmatic changes (made via QLineEdit::setText())

Granted, I can also only think of that way, but please note that unlike textEdited(), textChanged() would allow you to even catch the programmatic changes as per documentation:

Unlike textChanged(), this signal is not emitted when the text is changed programmatically, for example, by calling setText().


text:
Q: crefrange with different reference types in Cleveref I am using the Cleveref package and in my document defined multiple new cross-reference types that all refer to figures, i.e.,
\Crefname{figure}{Fig.}{Figs.}
\Crefname{fig_a}{Fig.}{Figs.}
\creflabelformat{fig_a}{#2{\color{NavyBlue}#1a)}#3}
\Crefname{fig_b}{Fig.}{Figs.}
\creflabelformat{fig_b}{#2{\color{NavyBlue}#1b)}#3}
\Crefname{fig_c}{Fig.}{Figs.}
\creflabelformat{fig_c}{#2{\color{NavyBlue}#1c)}#3}

The reason for this is that I have figures that contain parts a), b), etc., but not as subfigures but as mere labels in the precompiled figure.
So, in order to reference individual parts of such a figure, I thought I could add multiple labels to the same figure, i.e.,
\begin{figure}
  ...
  \caption{Figure with parts a) and b) and c)}
  \label{figure}
  \label[fig_a]{figure:a}
  \label[fig_b]{figure:b}
  \label[fig_c]{figure:c}
\end{figure}

Now I would like to be able to write
\Cref{figure:a,figure:b}
\Cref{figure:a,,figure:c}

and get a reference as if all those references were of type figure, so something like Fig. 3.2a) and 3.2b) and Fig. 3.2a) to 3.2c). However, as all those references are of different types, what I get is Fig. 3.2a) and Fig. 3.2b) and Fig. 3.2a) to Fig. 3.2b).
How can I get rid of the second Fig. in a range of references?
I tried to solve this with \crefalias{fig_a}{figure} but this did not solve the problem.
Thanks for your help!

A: Problem is solved by
\usepackage[nameinlink,capitalize]{cleveref}
\Crefname{figure}{fig.}{Fig.}
\Crefname{fig_a}{fig.}{Fig.}
\creflabelformat{fig_a}{#2{\color{NavyBlue}#1a)}#3}
\Crefname{fig_b}{fig.}{Fig.}
\creflabelformat{fig_b}{#2{\color{NavyBlue}#1b)}#3}
\Crefname{fig_c}{fig.}{Fig.}
\creflabelformat{fig_c}{#2{\color{NavyBlue}#1c)}#3}


text:
Q: How to get story page number in an IDML Document? I require extracting the page number of a particular story in IDML Document. However, I'm unable to find any way to do so.There is a page tag in spread_xxx.xml describing pages in a spread. But that has no particular mapping to a story or vice-versa.

A: In ExtendScript you can query parents of the placed story paragraph and one of them is the page.
I do not see an easy way to do this in IDML
There is a folder called Spreads with a separate spread for every two pages and with page being child element of the spread.You can also see text frames
Stories have their IDs like Self="u18e". You can see them in the designmap.xml as idPkg:Story.
How the paragraphs are linked to spreads I can not find.

A: You can't. As one said in another forum where you might have asked*  :
IDML isn't a representation of a document but a bunch of instructions about how to construct the document. So a page number can only be accessed at the document interpretation stage i.e. opening the idml file.
*(this question is present in multiple forums at this time)


text:
Q: Strange behavior when parsing a CSV I've ran into a problem when parsing a CSV (with 2 coloumns)
Array ( [0] => Array ( [0] => oldcustomer 1 => newcostumer 4245945 [2] => 6773197 4260367 [3] => 6773381 4889300 [4] => 6764472 4740434 [5] => 6764555 4710449 [6] => 6764560
I want it to be in separate arrays and the newcostumerID is mixed with "oldcustomer ID"
CSV File:
oldcustomer;newcostumer
4245945;6773197
4260367;6773381
4889300;6764472
4740434;6764555
4710449;6764560
4699714;6766531
4451642;6775682
4534699;6775683
4378586;6775684
4711005;6775685
4502714;6775686
4288738;6775687
CSV Parse (stolen from here)
function csvstring_to_array($string, $separatorChar = ',', $enclosureChar = '"', $newlineChar = "\n") {
// @author: Klemen Nagode
$array = array();
$size = strlen($string);
$columnIndex = 0;
$rowIndex = 0;
$fieldValue="";
$isEnclosured = false;
for($i=0; $i<$size;$i++) {

    $char = $string{$i};
    $addChar = "";

    if($isEnclosured) {
        if($char==$enclosureChar) {

            if($i+1<$size && $string{$i+1}==$enclosureChar){
                // escaped char
                $addChar=$char;
                $i++; // dont check next char
            }else{
                $isEnclosured = false;
            }
        }else {
            $addChar=$char;
        }
    }else {
        if($char==$enclosureChar) {
            $isEnclosured = true;
        }else {

            if($char==$separatorChar) {

                $array[$rowIndex][$columnIndex] = $fieldValue;
                $fieldValue="";

                $columnIndex++;
            }elseif($char==$newlineChar) {
                echo $char;
                $array[$rowIndex][$columnIndex] = $fieldValue;
                $fieldValue="";
                $columnIndex=0;
                $rowIndex++;
            }else {
                $addChar=$char;
            }
        }
    }
    if($addChar!=""){
        $fieldValue.=$addChar;

    }
}

if($fieldValue) { // save last field
    $array[$rowIndex][$columnIndex] = $fieldValue;
}
return $array;

}

A: Look at the explode function. Take your string and run explode("\n",$string) to get an array of rows. Then iterate over each row and explode on the ; character.
$rows = explode("\n",$string);
$oldcustomer = array();
$newcustomer = array();
foreach ($rows as $row) {
  $columns = explode(";",$row);
  $oldcustomer[] = $columns[0];
  $newcustomer[] = $columns[1];
}
print_r($oldcustomer);
print_r($newcustomer);

A: You can use the following code to solve your problem
$row = -1;
$oldcustomer=array();
$newcustomer=array();
if (($handle = fopen("yourfile.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
        if($row==-1){//Skipping first line
            $row++;
            continue;
        }
        $oldcustomer[$row]=$data[0];
        $newcustomer[$row]=$data[1];
        $row++;
    }
    fclose($handle);
    print_r($oldcustomer);
    print_r($newcustomer);
}


text:
Q: Spring Boot Map with Map Key I am trying to create a
Map<String,Map<Map<String,String>,String>> properties2

as a configurable property with Spring Boot properties file.
I have been previously been able to get a :
Map<String, Map<String,String>> properties

populated with
properties.[A].B=C

where A is the first key and B the second key with a value of C.
I have already tried
properties2.[A].[B=C]=D

which doesn't allow the later components to start although it doesn't throw errors
Does anyone know how I can populate the properties2 map correctly?

A: you can nest properties as following
private final Map<String, Map<String, Map<String, String>>> namespace = new HashMap<>();

namespace.[foo].[bar].a=alpha

May be you have error here Map,String>> properties2
as you you're using Map<String,String> as as key try this instead Map<String, Map<String, Map<String, String>>>


text:
Q: Difference, in terms of completeness, between the Dirac well and barrier I was in my undergraduate QM lecture and we just finished with the Dirac barrier. My question is as follows: We know that the Dirac well's complete set of solutions requires one bound state and an infinite set of scattering states (plane waves). The solutions to the Dirac barrier are a only a set of scattering states (plane waves again). How can both sets of solutions be complete? I asked this question in lecture and was told that no one-to-one correspondence exists between the two sets of plane waves, so the comparison is improper, but I've been unable to find anything else on the subject.

A: I'm not quite sure what OP asks, but the potential profile $V$ clearly matters. E.g. if $\lim_{|x|\to \infty}V(x)=\infty$, such as, the harmonic oscillator, or the infinite well, then there are no scattering states at all!


text:
Q: Android Java - change requestLocationUpdates refresh in class I have this class GPS_Service below. It's working perfectly. From MainActivity I  can change the value of variable GPS_Service.gpsupdatedelay to adjust how often the GPS is invoked via requestLocationUpdates in GPS_Service. From MainActivity I change the value via GPS_Service.gpsupdatedelay = 10000; I think I also need to invoke some aspect of GPS_Service to make the variable value change take place? I cannot see a way to invoke GPS_Service.onCreate() nor do I think I should do that?
QUESTION: After having adjusted the value of gpsupdatedelay, how may I get the variable value-change in the parameters of requestLocationUpdates to take place and actually adjust the GPS frequency?
Thank you in advance.
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

public class GPS_Service extends Service {
    private LocationListener listener;
    private LocationManager locationManager;
    public static Integer gpsupdatedelay;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        Log.e("GPS","onCreate");
        listener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Intent i = new Intent("location_update");
                //i.putExtra("coordinates",location.getLongitude()+" "+location.getLatitude());

                i.putExtra("coordinate1",location.getLatitude());
                i.putExtra("coordinate2",location.getLongitude());
                Log.e("GPS","sendBroadcast");
                sendBroadcast(i);
            }
            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {
            }
            @Override
            public void onProviderEnabled(String s) {
            }
            @Override
            public void onProviderDisabled(String s) {
                Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
            }
        };
        locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        //noinspection MissingPermission
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,gpsupdatedelay,0,listener);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if(locationManager != null){
            //noinspection MissingPermission
            locationManager.removeUpdates(listener);
        }
    }
}

A: You actually should not have the gpsupdatedelay variable defined as static.  Instead of having it defined as static and accessing it directly from the Activity, send in the new value as an Intent Extra when you need to update it.
The first step is to define the onStartCommand() method override, which will update the new interval value, unregister the old location listener, and re-register for location updates with the new interval:
public class GPS_Service extends Service {
    private LocationListener listener;
    private LocationManager locationManager;
    public Integer gpsupdatedelay = 10000; //NOT static!

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    //Added:
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int newGpsUpdateDelay = intent.getIntExtra("new_gps_update_delay", -99);
        if (newGpsUpdateDelay != -99 && locationManager != null) {
            gpsupdatedelay = newGpsUpdateDelay;
            //noinspection MissingPermission
            locationManager.removeUpdates(listener);
            //noinspection MissingPermission
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,gpsupdatedelay,0,listener);
        }
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        Log.e("GPS","onCreate");
        listener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Intent i = new Intent("location_update");
                //i.putExtra("coordinates",location.getLongitude()+" "+location.getLatitude());

                i.putExtra("coordinate1",location.getLatitude());
                i.putExtra("coordinate2",location.getLongitude());
                Log.e("GPS","sendBroadcast");
                sendBroadcast(i);
            }
            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {
            }
            @Override
            public void onProviderEnabled(String s) {
            }
            @Override
            public void onProviderDisabled(String s) {
                Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
            }
        };
        locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        //noinspection MissingPermission
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,gpsupdatedelay,0,listener);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if(locationManager != null){
            //noinspection MissingPermission
            locationManager.removeUpdates(listener);
        }
    }
}

In order to update the value from the Activity, just create an Intent, put the new value in the new_gps_update_delay Extra, and call startService() in order to send the updated info to the Service:
    int newDelay = 678;
    Intent i = new Intent(this, GPS_Service.class);
    i.putExtra("new_gps_update_delay", newDelay);
    startService(i);

This works since the startService() method can be called even if the Service is already running.  If the service is already running, essentially it just runs the onStartCommand() method override.
From the documentation for startService():

If this service is not already running, it will be instantiated and
  started (creating a process for it if needed); if it is running then
  it remains running.
Every call to this method will result in a corresponding call to the
  target service's onStartCommand(Intent, int, int) method, with the
  intent given here. This provides a convenient way to submit jobs to a
  service without having to bind and call on to its interface.


text:
Q: VB.net retrieve specific value from an array create by a class? I have a Class called 'account'. Here is the code:
 Public Class Account
Private accounttype As String
Private accountnumber As Integer
Private branchcode As String
Private currency As String
Private balance As Integer

Public Sub New()
    accounttype = " "
    accountnumber = 0
    branchcode = " "
    currency = " "
    balance = 0
End Sub
Public Sub New(ByVal cu As String, ByVal na As Integer, ByVal su As String, ByVal a1 As String, ByVal a2 As Integer)
    accounttype = cu
    accountnumber = na
    branchcode = su
    currency = a1
    balance = a2
End Sub
Public ReadOnly Property Getaccountnumber() As String
    Get
        Return accountnumber
    End Get
End Property

Public ReadOnly Property Getbalance() As Integer
    Get
        Return balance
    End Get
End Property

Public Overrides Function ToString() As String
    Return "Account Type: " & accounttype & vbCrLf & "Account Number: " & accountnumber.ToString & vbCrLf & "Branch Code: " & branchcode & vbCrLf & "Currency: " & currency & vbCrLf & "Balance: " & balance.ToString

End Function

End Class

I have then hard coded a few accounts like this.
    Dim account1 As New Account("Savings", "1", "S1", "Khajalee", 1000)
    accodetails.Add(account1)

I would like to know how I go about getting the 'balance' value for an account from the array. Any help would be wonderful!!As you can see i have tried getting the balance with a few different codes but no luck.
Thanks

A: Provided, by "the array", you mean accodetails, then you can access any item in the array by index, like this:
Dim myAccount As Account = accodetails(0)

Then you can access any property in the Account object via that variable, like this:
Dim myBalance As Integer = myAccount.GetBalance

Or, more simply, you can access the property directly from the item in the list, without assigning it to a variable, like this:
Dim myBalance As Integer = accodetails(0).GetBalance


text:
Q: Date format is not working in some computers, SQL Query Below date format is not working in some computers I do know why,
SELECT FORMAT (getdate(), 'dd/MM/yyyy ') as date

I use SQL Query. What is the problem?
Please anyone can help me

A: I tried to convert variable instead of converting in SQL Query


text:
Q: output of the following code related to macros Please explain the output — I am getting the output as 20,
but it should be 64 if I am not wrong.
#include<stdio.h>
#define SQUARE(X) (X*X)
main()
{
    int a, b=6;
    a = SQUARE(b+2);
    printf("\n%d", a);
}

A: The correct result is 20.
Macros are simple text substitutions.
To see that the result is 20, just replace the X with b+2. Then you have:
b+2*b+2

as b is 6 it is
6+2*6+2

which is 20
When using macros it is important to use parenthesis so the macro should look
# define SQUARE(X) ((X)*(X))

Then the result will be 64 as the evaluation is
(b+2)*(b+2)

(6+2)*(6+2)

8*8

64


text:
Q: Get quantity attribute in products list page
I'm using magento 2.
I want to get this attribute in products list page. Does anyone show me how ?
Thanks !

A: You need define new observer
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="catalog_product_collection_load_after">
        <observer name="Your_Module_Add_Quantity" instance="Your\Module\Observer\AddQuantityToCollectionObserver"/>
    </event>
</config>

With code like
namespace Your\Module\Observer;
class AddQuantityToCollectionObserver implements ObserverInterface
{
    /**
     * Add information about product Quantity to collection
     * Used for product collection after load
     *
     * @param EventObserver $observer
     * @return void
     */
    public function execute(EventObserver $observer)
    {
        $productCollection = $observer->getEvent()->getCollection();
        $websiteId = $this->storeManager->getStore($productCollection->getStoreId())->getWebsiteId();
        foreach ($productCollection as $product) {
            $productId = $product->getId();
            $stockStatus = $this->stockRegistryProvider->getStockStatus($productId, $websiteId);
            $product->setQty($stockStatus->getQty());
        }
    }
}

A: try this
   <?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
        echo $StockState->getStockQty($product->getId(), $product->getStore()->getWebsiteId());
?>


text:
Q: AWS Amplify breaks binary posts to AWS API-Gateway I'm creating a web application using React / Aws Amplify as the front end and AWS API-Gateway and S3 in the back end and Cognito as our user authentication. I have a page where the user needs to submit a form and a file. I was able to set this up for text files but once I started to work on binary files bad things happened.
I build the API in AWS and tested it using Postman as well as Curl and I'm able to post binary files. When I make the call through Amplify it stops working. I can make the call through Axios but then I need to turn off the Authentication, hence why I'm trying to do this through amplify. I also do not want to use amplify storage as it does not meet my needs. What typically happens is the file size is larger then the file sent and when I download it out of S3 it does not work any longer.
import React, { Component } from "react";
import "./Dashboard.css";
import { API } from "aws-amplify";
import { saveAs } from 'file-saver';
import axios from 'axios';

export default class Home extends Component {
  uploadLambda = async (event) => {
    //This one work if I turn off User Authentication

    let file = event.target.files[0];
    let reader = new FileReader();
    reader.readAsArrayBuffer(file);

    reader.onload = async () => {

      try
      {
        return axios({
          method: 'POST',
          url: 'https://XXXXXXXXXX.execute-api.us-east-1.amazonaws.com/dev/upload',
          headers: {
            'Content-Type': 'application/pdf'
          },
          data: reader.result
        });
      }
      catch(e)
      {
        console.log(e);
      }
    }
  }

  uploadImageLambda = async(event) => {
    //This is the one I'm trying to get to work with binary files
    var file_name = event.target.files[0].name;
    console.log('Saving File Via Lambda: ' + file_name);
    var reader = new FileReader();
    reader.readAsDataURL(event.target.files[0]);
    //reader.readAsBinaryString(event.target.files[0]);
    //reader.readAsArrayBuffer(event.target.files[0]);

    reader.onload = async () =>
    {
      try
      {
        /**
        Someone suggested this but it does not fix the problem
        let encoded = reader.result.toString().replace(/^data:(.*,)?/, '');
        if ((encoded.length % 4) > 0) {
          encoded += '='.repeat(4 - (encoded.length % 4));
        }
        console.log(encoded);
        //"isBase64Encoded": "true",
        **/
        return await API.post("lambdadocshell", 'upload', { 'headers': { 'Content-Type': 'application/pdf', },  'body': reader.result });
      }
      catch (e)
      {
        console.log(e);
      }
    }
  }

  render() {
    return (

Upload A File

          <form onSubmit={this.handleSubmit} enctype="multipart/form-data">
            Select File: <input type="file" onChange={this.uploadLambda} />
          </form>

    );
  }
}

In the code above you can see 2 upload functions, both hit the same API-Gateway. uploadLambda works but only if authentication on the API-Gateway is turned off. uploadImageLambda does not work regardless of authentication. We do use the Amplify in a number of other pages to move JSON back and forth to the API without issues. You can also see commented code as we tried a number of different ways to get amplify to work.

A: After talking with AWS support, they said that amplify apparently does a JSON.stringify to the data which then increases the length of the file. Currently there does not seem to be a workaround for this issue. As such they suggested that I use Axios to make the request to API Gateway. Hopefully this will be resolved in the future.


text:
Q: Проблема с импортом файла в Visual Studio Возникла ситуация, что в вузе задали реализовать программу с использованием определенных заголовочных файлов, импортировал их в проект но при подключении в программу возникла проблема, что VS их не видит, притом что между собой они видят друг друга(один заголовок импортируется в другой)
PS: На код в main не смотрите просто экспериментировал

A: Для того чтобы добавить уже созданный файл в свой проект в VS необходимо

*

*Перенести нужный файл в свой проект в VS

*Нажать ПКМ на "Исходные файлы" в обозревателе решений, далее "добавить", "существующий элемент"

*Находим нужный файл в своем проекте и добавляем его


text:
Q: How to get new acess token from refres token for google api in postman I am trying to get new access token from my refresh token for google drive api. In my google playground it works but when I want to create the same request in postman or my code it doesn't work and I always get error "Invalid grand type". I don't know to find what is problem.
google developers playground

postman headers and body

A: You need to understand that there is three steps to the Oauth2 dance.
step one is requesting access of the user and getting the authorization code.

HTTP GET https://accounts.google.com/o/oauth2/auth?client_id={clientid}.apps.googleusercontent.com&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/analytics.readonly&response_type=code

Note &response_type=code tells the server you want an authorization code returned.

*step two is to exchange that code for an access token and refresh token.

POST https://accounts.google.com/o/oauth2/token
code=4/X9lG6uWd8-MMJPElWggHZRzyFKtp.QubAT_P-GEwePvB8fYmgkJzntDnaiAI&client_id={ClientId}.apps.googleusercontent.com&client_secret={ClientSecret}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code

Note the part where it says &grant_type=authorization_code.  this tells the server you are giving them an authorization code.
3 the final step is refreshing your access token.

POST https://accounts.google.com/o/oauth2/token
client_id={ClientId}.apps.googleusercontent.com&client_secret={ClientSecret}&refresh_token=1/ffYmfI0sjR54Ft9oupubLzrJhD1hZS5tWQcyAvNECCA&grant_type=refresh_token

Note &grant_type=refresh_token you are telling the server you are sending them a refresh token.
You appear to be sending a refresh token with the wrong grant type.
I have a video on how to set up postman to use google oauth2

*

*How to set up Oauth2 in PostMan.

*Google 3 Legged OAuth2 Flow
Note: Due to a recent change with Making Google OAuth interactions safer by using more secure OAuth flows  redirect uri of urn:ietf:wg:oauth:2.0:oob is going to stop working soon.


text:
Q: Opengl Large SSBO hangs when reading I have multiple SSBO(4 SSBO) of size 400400100 ints and my fragment shader updates the value of this ssbo. I do this by calling the drawelements call and I read the data after the draw call by first binding the specific SSBO and then calling the glMapBuffer and type casting the ptr to an int.
The GPU does heavy processing (loops with 10000 iteration) and updates the SSBO. I have a print statemnt after the drawelement call which is shown on the screen and a print statement after the bind call, which is also displayed but the glMapBuffer call takes forever and hangs the system.
In Windows task manager, the GPU is not used for majority of the time and only CPU is used. I think its because the GPU is only used during the draw call.
Plus, Is my understanding correct that when I call glMapBuffer, only the binded ssbo is transfered?
Do you guys have any suggestion as to what might be causing this issue?
I tried using glmapbuffer range, which caused similar problem.
glDrawElements(GL_TRIANGLES, NUM_OF_TRIANGLES , GL_UNSIGNED_INT, 0);

std::cout << 'done rendering' <<std::endl; //prints this out

glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0);

glBindBuffer(GL_SHADER_STORAGE_BUFFER, SSBO);

std::cout << 'done binding ssbo' <<std::endl; //prints this out

GLint *ptr;

ptr = (GLint *) glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_ONLY); //hangs here


text:
Q: MonoTouch RedLaser SDK Object I am trying to use the RedLaser SDK 3.30 with MonoTouch. Here is the code I am using:
https://github.com/mono/monotouch-bindings/tree/master/RedLaser
When I click the thunderbolt button to scan a barcode, my app crashes on my iPod touch. I am using ARM7. Here is my crash log:
wait_fences: failed to receive reply: 10004003
0   RedLaserSample                      0x01669015 mono_handle_native_sigsegv + 244
1   RedLaserSample                      0x01681cf1 sigabrt_signal_handler + 112
2   libsystem_c.dylib                   0x309cf7ed _sigtramp + 48
3   libsystem_c.dylib                   0x309c520f pthread_kill + 54
4   libsystem_c.dylib                   0x309be29f abort + 94
5   libc++abi.dylib                     0x367cef6b abort_message + 46
6   libc++abi.dylib                     0x367cc34d _ZL17default_terminatev + 24
7   libobjc.A.dylib                     0x3414036f _objc_terminate + 170
8   libc++abi.dylib                     0x367cc3c5 _ZL19safe_handler_callerPFvvE + 76
9   libc++abi.dylib                     0x367cc451 _ZdlPv + 0
10  libc++abi.dylib                     0x367cd79f __cxa_throw + 122
11  RedLaserSample                      0x00040565 _ZN5zxing6qrcode19FinderPatternFinder18selectBestPatternsEv + 172
12  RedLaserSample                      0x000416a5 _ZN5zxing6qrcode19FinderPatternFinder4findERKNS_11DecodeHintsE + 512
13  RedLaserSample                      0x0003a8b3 _ZN5zxing6qrcode8Detector6detectERKNS_11DecodeHintsE + 366
14  RedLaserSample                      0x00046c53 _ZN5zxing6qrcode12QRCodeReader6decodeENS_3RefINS_12BinaryBitmapEEENS_11DecodeHintsE + 130
15  RedLaserSample                      0x0004edcb _ZN5zxing6Reader6decodeENS_3RefINS_12BinaryBitmapEEE + 458
16  RedLaserSample                      0x00055be9 -[FormatReader decode:] + 116
17  RedLaserSample                      0x00013749 -[ZXingDecoder findCodesInBitmap:bytesPerRow:width:height:] + 656
18  RedLaserSample                      0x0005b6df -[BarcodePhotoEngine zxingFindBarcodesInPixmap:] + 222
19  RedLaserSample                      0x00053551 __38-[BarcodeEngine findBarcodesInPixMap:]_block_invoke_066 + 76
20  libdispatch.dylib                   0x35737c59 _dispatch_call_block_and_release + 12
21  libdispatch.dylib                   0x35742cab _dispatch_queue_drain + 274
22  libdispatch.dylib                   0x35742b19 _dispatch_queue_invoke$VARIANT$up + 36
23  libdispatch.dylib                   0x3574378b _dispatch_worker_thread2 + 214
24  libsystem_c.dylib                   0x30980dfb _pthread_wqthread + 294
25  libsystem_c.dylib                   0x30980cd0 start_wqthread + 8

A: In the current SDK, version 3.3, there is an issue with QR Codes. When the app starts, click the QR code button and it says no. It scans normal now.


text:
Q: Arduino dc motor in sync with servo motor I have this simple arduino code that drives two Dc motor using L298N  which is a motor driver together with two servo motors. The code is working fine for the motor driver but not for the servo motor:
#include <Servo.h>

Servo myservo;
Servo myservo2;
int num=1;
int IN1=8;
int IN2=9;
int ENA=3;

int IN3=10;
int IN4=11;
int ENA2=4;

void setup()
{
  myservo.attach(40);
  myservo2.attach(42);

 pinMode(IN1,OUTPUT);
 pinMode(IN2,OUTPUT);

 pinMode(IN3,OUTPUT);
 pinMode(IN4,OUTPUT);
}
void loop()
{
   intialPos();

 while(motor_run())
  {
        turnOne();
       delay(3000);
       intialPos();
       delay(10000);
       turnSecond();
       delay(3000);
  }

}
int motor_run()
{

  analogWrite(ENA, 1500);// motor speed
  digitalWrite(IN1,LOW);// rotate forward
  digitalWrite(IN2,HIGH);

  analogWrite(ENA2, 1500);// motor speed
  digitalWrite(IN3,HIGH);// rotate forward
  digitalWrite(IN4,LOW);

  delay(3000);
  return (1);
}
void intialPos()
{
  myservo.write(70);
   myservo2.write(135);
  delay(2000);
}
void turnOne()
{
  myservo2.write(170);
  myservo.write(135);
  delay(2000);
}
void turnSecond()
{
  myservo2.write(70);
  myservo.write(30);
  delay(2000);
}

My problem is to make the dc motor code continues to execute while the servo motor do its thing which is turning. But all it does was to make the dc motor work and the servo motors are unmoving. I'm using the servo motor as a rudder in a boat so I need to make the dc motor continuously working while the servo motor turns to a direction. I've heard multi threading but it is not supported on arduino. I found another way to make them in sync with each other which is using cycle or timing, but the sample code was confusing so can someone give me a code snippet and some detailed explanation for it.

A: For the people who are curious on how i did it..this is the code with the little revision. Since I found out the movement is going backward not forward.
#include <Servo.h>

Servo myservo;
Servo myservo2;
int num=1;
int IN1=8;
int IN2=9;
int ENA=3;

int IN3=10;
int IN4=11;
int ENA2=4;

void setup()
{
  myservo.attach(40); // right side servo motor
  myservo2.attach(42); // left side servo motor

 pinMode(IN1,OUTPUT);
 pinMode(IN2,OUTPUT);

 pinMode(IN3,OUTPUT);
 pinMode(IN4,OUTPUT);
}
void loop()
{
   intialPos();

 while(motor_run())
  {
       intialPos();
       turnOne();
       delay(3000);
       intialPos();
       delay(10000);
       turnSecond();
       delay(3000);
  }

}
int motor_run()
{
  Serial.println("dc motor is working");
  analogWrite(ENA, 255);// motor speed
  digitalWrite(IN1,HIGH);// rotate forward
  digitalWrite(IN2,LOW);

  analogWrite(ENA2, 255);// motor speed
  digitalWrite(IN3,HIGH);// rotate forward
  digitalWrite(IN4,LOW);

  return (1);
}
void intialPos()
{
  Serial.println("servo motor in intial position");
  myservo.write(70);
  myservo2.write(135);

}
void turnOne()
{
  Serial.println("servo motor turnOne");
  myservo2.write(170);
  myservo.write(135);
}
void turnSecond()
{
  Serial.println("servo motor turnSecond");
  myservo2.write(70);
  myservo.write(30);
}


text:
Q: Sort Array of Objects Based on number of Keys it contains This is a sample code but it does not seem to sort the array. All I want is the array of object sorted in such a manner that the object with maximum keys comes first.
CSVData.sort(function(item1,item2){
                            return Object.keys(item2).length - Object.keys(item1);
                        });

A: You were close
CSVData.sort(function(item1,item2){
   return Object.keys(item1).length - Object.keys(item2).length;//notice the length property here
});

Also notice that item1 is before item2, assuming that you want to sort in ascending order. For descending order, it will be
   return Object.keys(item2).length - Object.keys(item1).length;


text:
Q: Cannot see linked service or management hub in ADF I am new to azure cloud infrastructure, I am trying to create a azure data factory, which I did now I am trying to create a linked service to another SaaS provider "salesforce". I am not seeing any place to create one.
I have consulted the following links, but could not find anything yet.
I cannot see management hub
https://learn.microsoft.com/en-us/azure/data-factory/author-management-hub
or in azure portal
https://learn.microsoft.com/en-us/azure/data-factory/concepts-linked-services
Thank you

A: Please ref this tutorial: Copy data from and to Salesforce by using Azure Data Factory

*

*This article outlines how to use Copy Activity in Azure Data Factory
to copy data from and to Salesforce. It builds on the Copy Activity
overview article that presents a general overview of the copy
activity.

You could create the Salesforce linked service from here Data Factory UI on Portal:
Manage-->linked services-->new-->Salesforce:

Configure the Salesforce:


text:
Q: Owin 3rd party login with Google or Facebook redirect failed (/Account/ExternalLoginCallback not working) C# MVC When we test our program in local server the 3rd party login works fine, but that's not the case when we publish it onto the actual server. When we use 3rd party login on actual server, it didn't work.
So far what we know is our server provider is using https while our IIS server setting is using http. Could this be the cause? If not, any idea what's the problem we are encountering?
Here is the URL when we are entering account on Facebook 3rd party login page:
https://www.facebook.com/login.php?skip_api_login=1&api_key=569249369941462&signed_next=1&next=https%3A%2F%2Fwww.facebook.com%2Fv2.8%2Fdialog%2Foauth%3Fredirect_uri%3Dhttp%253A%252F%252Fwww.ipce.com.tw%252Fsignin-facebook%26state%3DwXOgKtgLeatXfqXP-Cv-Rc5EJu7AYiWQyqyN4bqtWfgZr6ncxzc9uerpXv4uSKZoSUQpWwO5AUt2YksiIP3q05GhjVUoT94kMZD5E57a2PgMaJT8oSrXh1K9lrH3g88DF0M2jtGX-DWJl-UJ66g_neu5xx1pGsIc3NBvblBjQfWM_rR6Vt8qB16GTCMqxSsQXhH4UXRDuQY5eBLSUKS7W0SRJMzDNClgMRT-VTZ7Gvv4oYTEAXnFG6qmh41o-xT5%26scope%3Demail%26response_type%3Dcode%26client_id%3D569249369941462%26ret%3Dlogin%26logger_id%3D2a07ffc7-acf8-ad97-0b9f-b45dcff38b39&cancel_url=http%3A%2F%2Fwww.ipce.com.tw%2Fsignin-facebook%3Ferror%3Daccess_denied%26error_code%3D200%26error_description%3DPermissions%2Berror%26error_reason%3Duser_denied%26state%3DwXOgKtgLeatXfqXP-Cv-Rc5EJu7AYiWQyqyN4bqtWfgZr6ncxzc9uerpXv4uSKZoSUQpWwO5AUt2YksiIP3q05GhjVUoT94kMZD5E57a2PgMaJT8oSrXh1K9lrH3g88DF0M2jtGX-DWJl-UJ66g_neu5xx1pGsIc3NBvblBjQfWM_rR6Vt8qB16GTCMqxSsQXhH4UXRDuQY5eBLSUKS7W0SRJMzDNClgMRT-VTZ7Gvv4oYTEAXnFG6qmh41o-xT5%23_%3D_&display=page&locale=zh_TW&logger_id=2a07ffc7-acf8-ad97-0b9f-b45dcff38b39

and this is the URL after we login, back to our home page but /Account/ExternalLoginCallback is not called
https://www.ipce.com.tw/?code=AQAUdHG-r1AxBOy1xkVm4sklkq-tBKn-9c_PAYqqpZmwiseTcKWAnTRJkoyeoZkiwReg_x7VSnMymQiWgqp0ZdnhlH1ypijH-FSyaca5BDCMJUS04x05CNVjrN5HvuRXdVJkv2OHwzqkTSWvkwC6S58nrRckIjroKjjGDqaWvldOt_0g8nFe_ZvLovj_hbdQs5SPE4M97CpPrm0ExudeEddEo1zn29RIMabS204kF445Hn73X90RTy7WpIqAINpcIIwK4XeAQMcoqoBQinaVRyjrNxjvKoAEXqBPBKKkdJn7u3bx94rFZXqHGGMJ6uth0rBSpDPJgtq0M1XMmYXfESjS&state=wXOgKtgLeatXfqXP-Cv-Rc5EJu7AYiWQyqyN4bqtWfgZr6ncxzc9uerpXv4uSKZoSUQpWwO5AUt2YksiIP3q05GhjVUoT94kMZD5E57a2PgMaJT8oSrXh1K9lrH3g88DF0M2jtGX-DWJl-UJ66g_neu5xx1pGsIc3NBvblBjQfWM_rR6Vt8qB16GTCMqxSsQXhH4UXRDuQY5eBLSUKS7W0SRJMzDNClgMRT-VTZ7Gvv4oYTEAXnFG6qmh41o-xT5#/_=_

I tried forcing http to https, but a server error 500 happened, I can't figure another way to fix the problem.
somebody help me please
Try 1
I set localhost server Route like this:
routes.MapRoute(
     name: "SigninFacebook",
     url: "signin-facebook",
     defaults: new { controller = "Member", action = "ExternalLoginCallback" }
);

It works! but it responded HTTP ERROR 500.
I tried applying the setting to actual server, well, nothing happened.
It still redirect to our home page, and ExternalLoginCallback still not called.
I doubt our actual server didn't get to signin-facebook Route.

A: I suppose it happens because you provide redirect_uri=localhost.
This parameter is used to redirect the browser page after successful 3rd party login to provide a auth code from Facebook to your server.
It works in your test environment because your webserver is local so browser can perform redirect to localhost.
But in production environment the real domain name should be used instead of localhost.


text:
Q: Like Button error click (Int)0? When you click on the button goes (Int)0.Can someone tell me how to solve this error? I tried without connecting to the server, this method worked.I need help help.What is the reason for this error? did the lesson appcoda Like Instagramm.
 import UIKit

class CustomSoccerHeaderView: UITableViewHeaderFooterView {

    var saveBravo: Soccer?

    @IBOutlet weak var bravoBtn: UIButton! {
        didSet {
            bravoBtn.layer.cornerRadius = bravoBtn.frame.size.width/2
            bravoBtn.layer.masksToBounds = true

        }
    }

    @IBOutlet weak var countBravo: UILabel!

    @IBAction func saveClick(_ sender: UIButton) {

        if (saveBravo != nil) {

            if var clickBravissimo: Int = saveBravo!.object(forKey: "bravissimo") as? Int {

                clickBravissimo += 1

                saveBravo!.setObject(clickBravissimo, forKey: "bravissimo")
                saveBravo!.saveInBackground()

            }

        }
    }

    @IBOutlet weak var nameHeader: UILabel!

    @IBOutlet weak var imageHeader: UIImageView!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code

    }

    }


text:
Q: Regenerating PHP session ID and double refresh - browser not recieveing the new cookie I've replaced the somewhat buggy CodeIgniter session library with my own native session implementation.
Both act in the same way, and change the session ID after a certain period of time, and both suffer the same issue, for the sake of this question lets say the session is regenerated each minute.
When a user views a page, and waits one minute, on the next page request the session ID would be regenerated. However there is an issue when the users request times out or if they "double refresh" the page. The browser does not receive the new cookie, which therefore starts a new session on the next request. So if the user hits refresh at the point in which the ID is regenerated and hits refresh again in quick succession, they lose their session.
I know changing the session ID is a good idea to prevent session fixation but is there any way around this issue? Obviously increasing the time in which the ID is regenerated will limit the possibility of this happening but it still seems likely to happen.
Thanks for your help!

A: *

*Add a column 'previous_session_ID' to your DB

*Move the current session ID into 'previous_session_ID' - then generate new session ID and store that in the current_session_ID

*When user tries to access your page with a session ID - check the current ID AND the 'previous_session_ID'

Problem solved - they can now do a 'double refresh' and still access the page.


text:
Q: EntityFunction for Relational Database error I am a student and I am new of Mathematica.
I am working with relational databases and I am following the guide "Relational Database quick start" find here: https://reference.wolfram.com/language/tutorial/RelationalDatabasesQuickStart.html
I have successfully managed to connect to my database. Now I am using the Entity Framework to query my database.
The problem is that I want to pass a global value inside the EntityFunction and not define the column name a priority. I would like to use the code inside a function and pass dynamic parameters to this function.
So this first example works.
EntityValue[
  FilteredEntityClass[
   "Customer",
   EntityFunction[e, e["City"] != "Vancuver"]
   ],
  {"FirstName"},
  "PropertyAssociation"
  ] // Dataset

But I want to do something like this
function[var_,value_] := (
 entity = EntityValue[
  FilteredEntityClass[
   "Customer",
   EntityFunction[e, e[var] != value]
   ],
  {"FirstName"},
  "PropertyAssociation"
  ] // Dataset;
 Return[entity];
);

res = function["City", "Vancouver"];

When I try this second solution I get this error
EntityFunction::invexpr: The expression e[var] cannot be compiled to SQL.

Is it not possible to do something like this?

A: Since EntityFunction, just like Function, holds its variable and body, you will have to inject the value into it. This is not specific to EntityFunction, and is a common problem of injecting values into held expressions. Just as in other such cases, you can use e.g. With to do that:
With[{var = "City"},
  EntityValue[
    FilteredEntityClass[
      "Customer",
      EntityFunction[e, e[var] != "Vancuver"]
    ],
    {"FirstName"},
    "PropertyAssociation"
  ] // Dataset
]

A: Most probable this
Dataset vw. Association
sheets sufficient help for the intend of the question. Since the answer there goes deeper than this question it hard to name this question a duplicate. It is too under question whether the shown competence on relational data handling from the questioner is sufficient to understand the answer suggested.
Aside from typing scoping is for sure a possible resolution, change of perspective to this question.


text:
Q: Automatic code generated By analogy, in Eclipse IDE and many others, when I declare some private attributes of the class, I can generate the getters and setters methods automatically. It's very useful for example, to declare with about 20 attributes and I finally have all my methods created.
Have we got the same functionality in xCode IDE, I mean ... When I am coding in the ".h" some declarations methods, could I have automatically the declaration in the ".m" ....
e.g:
In ".h", the code bellow:
- (NSString *)loadMessageLabelFr:(id)sender;

In ".m", the code 'desired' generated with a menu functionality:
- (NSString *)loadMessageLabelFr:(id)sender{

}

A: Getters and setters are generated implicitly by the compiler for your class properties. E.g. having
@property int count;

implicitly gives you the following things:
1) an ivar named _count, which stores the value of the property.
2) a getter and a setter
- (int)count
{
    return _count;
}

- (void)setCount:(int)count
{
    _count = count;
}

This code is inserted at compile time, and so you don't see it in your .m file. It is nice because this way your code is not cluttered by trivial getters and setters. If you want your getter or setter to do something else than just set or return a value, you need to define the method the usual way, e.g.:
- (void)setCount:(int)count
{
    NSLog(@"Count set to %d", count);
    _count = count;
}

A: I know what you mean - many times, after declaring 10 methods in my header, I wanted them somehow transferred to my implementation file.
However...
This is not Java, the objects and file organization is completely different

*

*You don't have to define the method and it is still a valid use case. There are classes which don't have specific method definitions and handle the method calls in doesNotRecognizeSelector:

*You can add method definitions at runtime

*You can define methods from one header in multiple implementation files.
By these reasons (and many others), generating method headers in the implementation files could have more cons than pros.
The simplest Xcode solution are

*

*Copy-paste method headers from the .h to the .m.

*Use autocompletion, writing the beginning of the header, e.g. - (BOOL) will allow you to autocomplete faster.

A: How are you defining your instance variables?
The answer to your question (for instance variables) is 'no, but do you really need them'...
Use properties and the accessor methods are created for you during compilation. In practice you need to explicitly implement very few accessor methods.
For the public methods, the answer is just no, but, you can copy the method definitions and then just add the brackets so not a lot of work (you don't even need to remove the semi-colon).
Also, and this works for both variables and publicly defined methods, start typing:
- a

and Xcode will offer auto completions of the line for you with appropriate method names.


text:
Q: continously run a javascript function I am designing a web-page to allow users to edit geographical features on the fly.  I use a simple function to calculate road lengths that they have been created.  The issue is that I have to reload the page to update the statistics.  The function I use to create the statistics is below, how can I make this run to update the stat's without reloading the page:
function postExecute() {
    var roadLengthCalc = Math.round(RoadLength['RoadLength']);
    document.getElementById("Road_Length").innerHTML = roadLengthCalc;
}

A: You can use the setInterval function:
For example:
setInterval(function(){ postExecute(); },3000);

The 3000 is the frequency in milliseconds.
Documentation:
You can find the full documentation for this function at the link below:
http://www.w3schools.com/jsref/met_win_setinterval.asp
JSFiddle working example:
http://jsfiddle.net/d5DkA/


text:
Q: If the transformation is not onto, does that mean that it is not one to one? If transformation T: V -> V and it is not onto, then nullity is not 0
So, it seems like it is not one-to-one when it is not onto.
And, If transformation is onto, is it one to one? because nullity is 0 ?

A: If (as I assume you mean) $V$ is a finite-dimensional vector space and $T: V \to V$ is a linear map, then the Rank-Nullity law gives that
$$\text{rank } T + \text{null } T = \dim V,$$
and so in particular
$$T \text{ is onto} \Leftrightarrow T \text{ is one-to-one} \Leftrightarrow \text{rank } T = \dim V \Leftrightarrow \text{null } T = 0.$$
If $V$ is infinite-dimensional, this no longer need be the case. For example, consider the vector space $S$ of sequences in, e.g., $\mathbb{R}$; the right-shift transformation $R: S \to S$ defined by
$$R(x_1, x_2, x_3, \ldots) := R(0, x_1, x_2, \ldots)$$
is linear and one-to-one (it has a left inverse, namely the obvious left-shift transformation) but is not onto (the first term of any sequence in the image is $0$).

A: They are different concepts. Either can hold or both or neither.
$f: [0,\infty) \to [0,\infty)$
$f(x) = x+ 1,$
is one-one (injective) but not onto (surjective.)

A: 1) $1-1$ but not onto: inclusion of a proper subspace into its superspace space, e.g., $\mathbb R \rightarrow \mathbb R^2 : x \rightarrow (x,0)$.
2) Onto, but not $1-1$: Opposite direction: Projection map from superspace into subspace, e.g., $L: \mathbb R^2 \rightarrow \mathbb R : (x,y) \rightarrow x $.


text:
Q: How to reference ArrayList into a HashMap

I have an ArrayList of getCourses and a HashMap for a ComboBox below:
public class QueryCourses {
public static ArrayList<Courses> getCourses() throws ClassNotFoundException, SQLException {
    String queryCourses = "SELECT course_id, course_title FROM tblcourses";
    Connection conn = DbConnection.ConnectDB();
    Statement stmt = conn.createStatement();
    ResultSet rs;
    rs = stmt.executeQuery(queryCourses);
    ArrayList<Courses> courseList = new ArrayList<>();
    while (rs.next()) {
        Courses crse = new Courses(rs.getInt("course_id"), rs.getString("course_title"));
        courseList.add(crse);
    }
    return courseList;
}

public HashMap<String, Integer> hashMap(){
    HashMap<String, Integer> map = new HashMap<>();
    final ComboBox<Courses> cmbCourse = new ComboBox(courseList.getItems());
    Connection conn = DbConnection.ConnectDB();

    try {
        Statement stmt = conn.createStatement();
        String qry = "SELECT `course_id`, `course_title` FROM `tblcourses`";
        ResultSet rs = stmt.executeQuery(qry);
        Courses crse;

        while (rs.next()) {
            crse = new Courses(rs.getInt(1), rs.getString(2));
            cmbCourse.addItem(crse);
        }
    } catch (SQLException ex) {
        Logger.getLogger(NewStudentController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return map;
}

}
I would like to reference the ArrayList onto the HashMap of a ComboBox in which has the id of a course and its title but I do not know which to reference the getCourses or the courseList.  Either of which gives me an error, am I missing something or what? This will then output onto the ComboBox the title and can return the key for database insertion.

A: ArrayList cannot be referenced to HashMap. You need to iterate through the arraylist (from getCourses() ) and individually set each element to the map.
Something like :
for(Course crse : getCourses()){
  map.put(crse.getId(),crse.getTitle() );
}


text:
Q: Precautions to prevent iPhone virus from attachment In a momentary lapse of sanity, I opened up an attachment (a .pdf) from an unknown email address (the domain doesn't seem to be a website) in the gmail app on my iPhone 5. Realizing that there was a reasonable probability that there was a Trojan, I quickly closed the file.
I now have the following related questions:

*

*Is there any chance I just put a virus on my iPhone?

*If so, what should I do to scan my phone and verify?

*In the future, is there a recommended way to scan such attachments as a precaution before opening them?

Looking at a number of questions on this website, I have learned that for my (non-jailbroken) phone, it is fairly unlikely that I got a virus, but I'd appreciate knowing that for sure.

A: You are most likely safe, as there are extremely, extremely rare cases of getting a virus this easily, as iOS is extremely secure. There are no incidents of getting a virus from PDF on iOS, so you are definitely secure.


text:
Q: Android Firebase Realtime: Writing an object with nested objects into db Is it possible to write a nested structure into firebase realtime db?
In my case I want to write a user to DB which have a reference to a Socks object which have String properties. In the db I need a child called "SocksCards" with childs with its properties. With this sample code the socksCard object is ignored, the user data is updated.
public void onDataChange(@NonNull DataSnapshot snapshot) {
                    User user = snapshot.getValue(User.class);
                    user.addSocksCards(socks);
                    userDb.setValue(user);
                }

public class User {
    public String username, surname, firstName, email, id, gender;
    private SocksCard socksCards;
    public User(){
    }

    public User(String username, String surname, String firstName, String email, String id, String gender){
        this.username = username;
        this.surname = surname;
        this.firstName = firstName;
        this.email = email;
        this.id = id;
        this.gender = gender;
    }

    public void addSocksCards(SocksCard sc){
        this.socksCards = sc;
    }
}

public class SocksCard {
    private String socksID;

    public SocksCard(String socksID){
        this.socksID = socksID;
    }

    public String getSocksID() {
        return socksID;
    }

}

A: Firebase only consider public fields, getters and setters when reading/writing Java objects from/to the database. Since SocksCard socksCards is private, and there is no getters and/or setter, the field is indeed ignored.
The two simplest approaches are to either mark the field as public:
public SocksCard socksCards

,  or to add a public getter for it:
public SocksCard getSocksCards(){
    return this.socksCards;
}


text:
Q: Pybind11 default argument numpy array or None I am wrapping some C++ code to use it from Python. I want to call a C++ function with an argument that can take a None value or a numpy.array of the same size of another input variable. This is the example:
import example

# Let I a numpy array containing a 2D or 3D image
M = I > 0
# Calling the C++ function with no mask
example.fit(I, k, mask=None)
# Calling the C++ function with mask as a Numpy array of the same size of I
example.fit(I, k, mask=M)

How can I code it in C++ with pybind11? I have the following function signatures and code:
void fit(const py::array_t<float, py::array::c_style | py::array::forcecast> &input,
         int k,
         const py::array_t<bool, py::array::c_style | py::array::forcecast> &mask)
{
    ...
}

PYBIND11_MODULE(example, m)
{
    m.def("fit", &fit,
        py::arg("input"),
        py::arg("k"),
        py::arg("mask") = nullptr // Don't know what to put here?
    );

Thank you very much!

A: With C++17's std::optional, here's an example that should work. For earlier versions of C++, you might want a backported optional.h and implement your own optional_caster similar to the one in pybind11/stl.h.
Say you want this function:
def add(a, b=None):
    # Assuming a, b are int.
    if b is None:
        return a
    else:
        return a + b

Here's the equivalent C++ pybind implementation:
m.def("add",
    [](int a, std::optional<int> b) {
        if (!b.has_value()) {
            return a;
        } else {
            return a + b.value();
        }
    },
    py::arg("a"), py::arg("b") = py::none()
);

In python, this function can be called with:
add(1)
add(1, 2)
add(1, b=2)
add(1, b=None)

For numpy arrays, simply modify the std::optional<int> with std::optional<py:array> or std::optional<py:array_t<your_custom_type>> in the example.


text:
Q: wordpress fetch data greater than id 100 we are trying to fetch data from WordPress post for one no of rows there is no issue but we want to use where clause in query. We want to fetch all rows whose id is greater than 100. we tried compare but later we came to know that compare is for meta_query. we dont want to use meta_query column as there is no data in that column.
we tried to increase the offset and i was hopeful that it will work but it did not work
$paginate_by = '1000';
    $offset = 0;
    $has_more_images = true;

    while ( $has_more_images ) {
        $args = array(
            'p'              => $comp_last_id, // is 100
            'posts_per_page' => $paginate_by,
            'offset'         => 0,
            'post_type'      => 'attachment',
            'post_status'    => 'any',
            'orderby'        =>'ID',
            'order'          => 'ASC'

        );

        $the_query = new WP_Query( $args );
        if ( $the_query -> have_posts () ) {
            while ( $the_query -> have_posts () ) {
                $the_query -> the_post ();
                $idall = get_the_ID ();
            }
        }
        $args['offset'] += $paginate_by;
            }

any help in how to fetch all rows whose id greater than 100 will be great

A: Try using posts_where filter:
https://codex.wordpress.org/Plugin_API/Filter_Reference/posts_where
Where for conditions that apply only to your query so that all query are not affected. conditions like is_page(), is_single(), etc


text:
Q: Separate a long text from a SQL read in asp .net Im currently using a gridview table so show some data using SQL. So i have read in some info and displayed them in my gridview. This is how it looks
As you can se, i am displaying the path. The thing is that i only want to display the last part of the path that shows the date and how many km the car has traveled. Im using asp .net and my boundfield method looks like this
<asp:BoundField DataField="ReadOutID" HeaderText="ReadOutID" InsertVisible="False" ReadOnly="True" SortExpression="ReadOutID" />
                                <asp:BoundField DataField="FileName" HeaderText="FileName" SortExpression="FileName" />
                                <asp:BoundField DataField="FileTime" HeaderText="FileTime" SortExpression="FileTime" />
                                <asp:BoundField DataField="ImportTime" HeaderText="ImportTime" SortExpression="ImportTime" />
                                <asp:Boundfield DataField="FullPath" DataFormatString="{0:C}" HeaderText="Comment" SortExpression="Comment" />

How can i just show the last part?

A: You can add this kind of expression into a template field
Text='<%# Eval("filename").ToString().Substring(0,9) %>'

Or you can write a function in .cs file like this.
protected getString(string str) { return (str..Substring(0,9)); }

And use this in gridview label as
Text='<%# getString(Eval("filename").ToString()) %>'

A: I'll try to simplify it:
the pathway for different cars looks like this
X:\05_General\T\TestVehicleInfo\Vehicles\Aamir_2107005\Readouts\All\20160201_474km_TMSupdate_newE2\Aamir_2107005_20160201_474km_XCOM_ALL_DTC_BMV_after.txt
X:\05_General\T\TestVehicleInfo\Vehicles\Amazonas_3859276\Readouts\All\20141218_7237km_SOP1505P3_Update\After\XCOM\Amazonas_3859276_20141218_0km_XCOM_ALL_DTC_SSBTOA.txt
The first one is for the car named aamir and the second one is for the car amazonas
I would like to write out everything from the date forward. in these two cases i would like to write out
20160201_474km_TMSupdate_newE2\Aamir_2107005_20160201_474km_XCOM_ALL_DTC_BMV_after.txt
and
20141218_7237km_SOP1505P3_Update\After\XCOM\Amazonas_3859276_20141218_0km_XCOM_ALL_DTC_SSBTOA.txt
the first one is for aamir and the second one for amazonas. Do you understand me?


text:
Q: How do I display my Bootstrap nav items under my title horizontally in mobile view? on desktop, I like how the nav bar looks, but when resized to a mobile size, it pushes itself to the size/under the heading vertically but I would like it to display horizontally.
I have tried displaying inline which did not work.
I know how to use media queries but I just need help displaying each nav item next to each other under the heading.

document.body.classList.add('fade');

document.addEventListener("DOMContentLoaded", function(e) {
  document.body.classList.remove('fade');
});
body {
  opacity: 1;
  transition: 0.7s opacity;
}

body.fade {
  opacity: 0;
  transition: none;
}

.header {
  padding-left: 50px;
}

#nav {
  padding-right: 50px;
}

.nav {
  transition: linear 0.4s;
}

.nav:hover {
  color: #5a5f61;
  text-decoration: underline;
}

.mt-5 {
  margin-top: 5% !important;
}

.mt-6 {
  margin-top: 2.5% !important;
}

.mt-7 {
  margin-top: 2.5% !important;
}

.bgcolor {
  background-color: lemonchiffon;
}

@media only screen and (min-device-width: 320px) and (max-device-width: 486px) {
  .mt-5 {
    margin-top: 10% !important;
  }
  .mt-6 {
    margin-top: 2.5% !important;
  }
  .mt-7 {
    margin-top: 2.5% !important;
  }
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />

 Main Brand Heading

      Portfolio

      About

      Contact

Fluid jumbotron

This is a modified jumbotron that occupies the entire horizontal space of its parent.

Fluid jumbotron

This is a modified jumbotron that occupies the entire horizontal space of its parent.

Fluid jumbotron

This is a modified jumbotron that occupies the entire horizontal space of its parent.

A: You can add a media query for change the flex-direction property and then adjust the margins and paddings for a better result. For example:
EDIT: I added another lines to force the nav elements to still in flex-direction: row.

body {
    opacity: 1;
    transition: 0.7s opacity;
}

body.fade {
    opacity: 0;
    transition: none;
}

.header {
    padding-left: 50px;
}

#nav {
    padding-right: 50px;
}

.nav {
    transition: linear 0.4s;
}

.nav:hover {
    color: #5a5f61;
    text-decoration: underline;
}

.mt-5 {
    margin-top: 5% !important;
}

.mt-6 {
    margin-top: 2.5% !important;
}

.mt-7 {
    margin-top: 2.5% !important;
}

.bgcolor {
    background-color: lemonchiffon;
}

@media only screen and (min-device-width : 320px) and (max-device-width : 486px) {
    .mt-5 {
        margin-top: 10% !important;
    }

    .mt-6 {
        margin-top: 2.5% !important;
    }

    .mt-7 {
        margin-top: 2.5% !important;
    }
}

@media only screen and (max-width : 786px) {
    #nav {
        flex-direction: column;
        justify-content: center;
        padding-right: 0px;
    }

    .header {
        padding-left: 0px;

    }

    .navbar-nav.ml-auto {
        margin-left: 0 !important;
    }

    ul {
        flex-direction: row !important;
    }

    ul li a  {
        padding-right: .5rem !important;
        padding-left: .5rem !important;
    }
}

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="css/styles.css">
    <title>Hello, world!</title>

 Main Brand Heading

                Portfolio

                About

                 Contact

Fluid jumbotron

This is a modified jumbotron that occupies the entire horizontal space of its parent.

Fluid jumbotron

This is a modified jumbotron that occupies the entire horizontal space of its parent.

Fluid jumbotron

This is a modified jumbotron that occupies the entire horizontal space of its parent.


text:
Q: Console.log from a class' function I want to test if my function inside my class returns the given sentence. But if I try to test using console.log, it returns ReferenceError: rev is not defined. What am I doing wrong?
class store {
    constructor(revenue, workers) {
        this.revenue = revenue;
        this.workers = workers;
    }
}

class storeManager extends store {
    constructor(name) {
        super(revenue, workers);
        this.name = name;
    }

    rev() {
        return "The stores revenue is" + this.revenue;
    }

    hiredWorkers() {
        return "The store has" + this.revenue + "workers";
    }
};

console.log(rev())

I'm a fairly new programmer, so bear with me if this is a stupid question.

A: The entire point of a class is to provide a template to bundle up functionality into a self-contained object and not have globals for everything.
rev is a method that appears on instances of the class. It isn't a global.
You have to create an instance of the class:
const myInstance = new StoreManager("some value for name");

(Note that this is going to fail because your constructor calls super() and tried to pass the values of variables which don't exist in the constructor method).
… and then call the method on that:
const result = myInstance.rev();