text:
Q: maxLength feature in beanio mapping file is not working I have a requirement where I need to write a field value onto file with max length as 25. From DB I am getting length as 30. I am using 'maxLength=25' attribute in beanio mapping file.It somehow is still allowing value with length greater than 25. Anyone can suggest any solution or workaround for same?

A: It is not possible to force BeanIO validations when writing (marshalling) objects to an OutputStream for delimited formats from my understanding of the documentation, according to Section 4.6.2 Field Validation. Emphasis mine.

4.6.2. Field Validation
BeanIO supports several common field validation rules when reading an
  input stream. All field validation rules are validated against the
  field text before type conversion. When field trimming is enabled,
  trim="true", all validations are performed after the field's text has
  first been trimmed. Field validations are ignored when writing to an
  output stream.

I guess it is working for fixed length formats otherwise you would have an invalid record (although the same argument probably applies to any format)
You have 2 options here:

*

*Enforce the maximum length in your setter and/or getter methods if you want to be paranoid. This will affect your entire application (although I think it is a good idea to ensure your data consistency). You could do this in various ways and with the help of libraries (Apache Commons Lang's StringUtils come to mind). I'm leaving out any null checks, which you should take care of when using these approaches.
public String getFirstName() {
   return firstName.substring(0, 25); // this should really not be necessary if you use the setter
}

public void setFirstName(final String newFirstName) {
  firstName = newFirstName.substring(0, 25);
}

This would not require any changes in your mapping.xml file.

*Enforce the maximum length in an alternative setter and/or getter methods used explicitly by BeanIO for writing (marshalling) your data. Your getter/setter methods then don't do anything special and you add a new getter/setter pair per field. You could use just a  custom getter method when you only want to enforce the length when writing the data.
public String getFirstName() {
   return firstName;
}

public void setFirstName(final String newFirstName) {
  firstName = newFirstName;
}

// the BeanIO specific getter/setter
public String getFirstNameBIO() {
  return firstName.substring(0, 25);
}

public void setFirstNameBIO(final String newFirstName) {
  firstName = newFirstName.substring(0, 25);
}

This would also require changes in your mapping.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<beanio xmlns="http://www.beanio.org/2012/03"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.beanio.org/2012/03 http://www.beanio.org/2012/03/mapping.xsd">

  <stream name="DailyCasesSndStream" format="delimited" strict="true">
    <parser>
      <property name="delimiter" value="|"/>
    </parser>
    <record name="DailyCasesRecord" class="com.run.daily.batch.util.DailyCasesRecord" minOccurs="0"
            maxOccurs="unbounded">
      <field name="firstName" maxLength="25" getter="getFirstNameBIO" setter="setFirstNameBIO"/>
      <!-- OR if you only want the new getter to be used -->
      <field name="midName" maxLength="25" getter="getMidNameBIO"/>
    </record>
  </stream>
</beanio>

Using this test code:
final DailyCasesRecord dailyCasesRecord = new DailyCasesRecord();
dailyCasesRecord.setFirstName("FirstNameFirstNameFirstName");
dailyCasesRecord.setMidNameBIO("MidNameMidNameMidNameMidName");

final StreamFactory factory = StreamFactory.newInstance();
factory.loadResource("mapping.xml");
BeanWriter beanWriter = null;
try (final StringWriter out = new StringWriter()) {
  beanWriter = factory.createWriter("DailyCasesSndStream", out);
  beanWriter.write(dailyCasesRecord);
  System.out.println(out.toString());
} catch (final Exception e) {
  System.err.println(e.getMessage());
} finally {
  if (beanWriter != null) {
    beanWriter.close();
  }
}

I get this output:
FirstNameFirstNameFirstNa|MidNameMidNameMidNameMidN


text:
Q: Error while using if statements #include "stdafx.h"
#include <iostream>

bool primeNumber( int x )
{
    return (x==2,3,5,7) ;
}

int _tmain(int argc, _TCHAR* argv[])
{
    using namespace std ;

    cout << "ENTER ONE DIGIT NUMBER - " ;
    int x ;
    cin >> x ;

    if ( primeNumber )
        cout << x  << " IS A PRIME NUMBER " <<endl;
    else
        cout << x << " IS NOT A PRIME NUMBER " << endl;
    return 0;
}

please help me out ..result is same everytime ie 'x' is a prime number ..
also suggest changes ......i m just a beginner so also suggest ways to improve my code

A: Try this:
if ( primeNumber(x) )

instead of
if ( primeNumber )

And change your return statement like
return x == 2 || x == 3 || x == 5 || x == 7;

if you want to compare the value.

A: return (x==2,3,5,7)

This doesn't do what you think it does, a comma separated expression returns the value of the last expression in the list, you primeNumber  method basically always returns 7 which evaluates to true.
You have to compare the value with each one, eg:
return x == 2 || x == 3 || x == 5 || x == 7;

In addition, like pointed out by Rahul, you are not invoking the method but just comparing the pointer to the function primeNumber to be different from 0, which is trivially true.

A: This function always returns true
bool primeNumber( int x )
{
    return (x==2,3,5,7) ;
}

because there is used the comma operator in the return statement and its value is 7 that differs from 0.
I think you mean the following
bool primeNumber( int x )
{
    return ( x == 2 || x == 3 || x == 5 || x == 7 );
}

Also the condition in if statement
if ( primeNumber )

evaluates also always to true because primeNumber is a valid function pointer that differs from 0.
You have to write
if ( primeNumber( x ) )

As for me then I would write the following way
if ( primeNumber( x % 10 ) )

because nothing prevents the user to enter a number that contains several digits.
The function can be defined the following way
bool primeNumber( unsigned int x )
{
    bool prime = ( x == 2 ) || ( x % 2 != 0 && x != 1 );

    for ( unsigned int i = 3; prime && i * i <= x; i += 2 )
    {
        prime = x % i != 0;
    }

    return prime;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to submit to a Google Form from VBScript (instead of from a VBA macro)? I followed Peter's answer here to create a VBA macro that pushes data to a Google Form by building a URL and sending it through an http object. I would like to accomplish this without having to open Excel, so I'm converting the VBA code to VBS and pulling data from a text document. I got the VBA version working, but I can't seem to get the VBS version to submit right, and need some help. I'm still a beginner at VBS.
When I use Peter's code as written, this block gives me an error: "ActiveX component can't create object: 'MSScriptControl.ScriptControl'
Set http = CreateObject("MSXML2.XMLHTTP")
Set ScriptEngine = CreateObject("MSScriptControl.ScriptControl")
ScriptEngine.Language = "JScript"
ScriptEngine.AddCode "function encode(str) {return encodeURIComponent(str);}"

When I remove all but the "Set http = CreateObject("MSXML2.XMLHTTP") line, the code runs fine, but the data ends up in the connected Google Sheet in a single cell with each entry separated by a comma, instead of each entry in a separate cell like normal. I think it has something to do with how the URL is formatted when it's sent from the VBScript as opposed to the VBA macro.
In order for the VBA macro to work, I had to check Microsoft XML.V3.0 in the VBA Reference menu, which I think enabled the ScriptEngine portion of the code to work, but I don't know what the equivalent of adding a reference is in VBS, or if it's even required.
Here is how I modified Peter's code for VBS:
Dim ScriptEngine
Dim http
Dim myURL
Dim strLine
Dim exportLine
Set http = CreateObject("MSXML2.ServerXMLHTTP")

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objDataFile = objFSO.OpenTextFile("data_file.csv", ForReading)

strLine = objDataFile.ReadLine
exportLine = Split(strLine,",")

myURL = "https://docs.google.com/forms/d/e/ . . . . /formResponse?" & _
        "entry.xxxxxxxxx=" + exportLine(0) + _
        "&entry.yyyyyyyyy=" + exportLine(1) + _
        "&entry.zzzzzzzzz=" + exportLine(2).Text
http.Open "GET", myURL, False
http.setRequestHeader "User-Agent", "Google Chrome 70.03538.102 (compatible; MSIE _
6.0; Windows NT 5.0)"
http.send


text:
Q: Running AVRStudio 32 and JTAGICE MKII on Vista 64 I've attempted installation of AVR studio 32 (for AVR32 UC3 development) and it doesn't appear to work.
Has anyone here gotten this to work in Vista 64?

A: Personally I use a virtual machine running XP...
I notice that Dean Camera (a regular over at AVRFreaks) has been playing with getting AVR tools to work on x64 boxes. See this posting on his blog: http://fourwalledcubicle.com/blog/archives/467. He also mentions that he's recently installed a beta of AVR Studio (http://www.atmel.no/beta_ware) which supports Windows 7 and x64.


text:
Q: What does the surface integral tell us, and how is it different from surface area? In the context of Faraday's Law of Induction,
Will a paraboloid with the same cross sectional area as a major portion of the sphere (Spherical Cap), have the same magnetic flux, when put in an uniform magnetic field ?
If it does have the same flux, does it mean that both the figures have the same surface integral ?
What does the surface integral tell about surfaces which do not lie in a single plane, that is not all points on the boundary of the surface are co-planar, and how is it different from surface area?
Will two surfaces having the same boundary have the same surface integral?

A: In the equation $$\Phi=\int_{\mathbf{s}}\bf B\cdot dA$$ there is a dot product between the magnetic field and the normal area vector. This is evaluated at all points on the surface $\mathbf{s}$ and each one of these dot products depends on the angle between $\bf B$ and $\bf dA$.
For surfaces that are of different shape or orientation, the dot product will be different at points on each surface. So even if the total surface area between two surfaces is the same, the value of $\Phi$ will differ in general.
So a paraboloid and the section of a sphere will not have the same value for $\Phi$ even if the total surface areas and $\bf B$ (which includes the direction of $\bf B$ of course) are the same for each.
The same logic applies to the rest of your question. But:
Will two surfaces having the same boundary have the same surface integral?
Yes.
Any two surfaces that have the same boundary will have equal amounts of flux. For example, if you have a magnet inside a large sphere and slice off a section off the top of the sphere so that you have a very small hemisphere (so that it almost looks like a flat disc) and a larger one being the rest of the sphere, that both of these spheres have the same boundary will mean they have equal amounts of flux.
The number of lines of forces going through the larger hemisphere will be significantly higher than the smaller section, but the number of lines of force coming back into the larger section will cancel most of those leaving so that the net flux going through both surfaces turns out to be equal.

A: In general, a surface integral is exactly the same as an area integral, the only key difference is that it measures the surface area of a non flat surface.
For the same boundary, $\iint da$ will have a different value for every singe surface attached to that closed boundary, because the surface area of a surface depends upon the surface.
Now we have faradays law, which instead of a surface integral, it is a weighted sum of $\frac{\partial \vec{B}} {\partial t} \cdot \vec{da}$. This isn't just a measure of surface area, it is a measure of how much the time derivative of the magnetic field points directly into a chosen surface, * area.
There is a major difference between a regular surface integral and faradays law.
$\oint \vec{E} \cdot \vec{dl} = -\iint \frac{\partial \vec{B}} {\partial t} \cdot \vec{da}$
Here we have a line integral that only depends on the BOUNDARY, equated to a surface integral that shares a boundary with the line integral. This surface integral IS INDEPENDANT of the surface chosen, and unlike the regular surface integral, it only depends upon the boundary, not the surface.
Why is there a difference?
The key in understanding this is that for the integral to be independant of the surface, the inside function must have zero divergence.
Mathematically, we can easily prove this by assuming that this is true for all surfaces, and then finding the condition on B upon which this statement is true, and showing that it is indeed true.
$\oint \vec{E} \cdot \vec{dl} = -\iint\frac{\partial \vec{B}} {\partial t} \cdot \vec{da}$
$\iint \nabla × \vec{E} \cdot \vec{da} = -\iint\frac{\partial \vec{B}} {\partial t} \cdot \vec{da}$
The fact that I cross the surface off here indicates that I'm saying it is true for any surface attached to $\vec{dl}$
$ \nabla × \vec{E} = -\frac{\partial \vec{B}} {\partial t} $
Taking the divergence of both sides
$0 = \nabla \cdot \frac{\partial \vec{B}} {\partial t} $
$\nabla \cdot \vec{B} = c$
Meaning the condition upon which this is true for any surface is when the divergence of $\vec{B}$ is a constant, which is inline with the condition that $\nabla \cdot \vec{B} = 0$
The intuitive way of showing this, is that  for the surface integral to be independant of the surface, the fluxes of 2 chosen surfaces of the same boundary must be the same, meaning constructing a closed surface out of those 2 surfaces, would change $\vec{da}$ for one of them, meaning the total flux out of the closed surface will be $\phi +(-\phi)$ = 0, using divergence theorem we see that this must be 0.


text:
Q: Acumatica Mobile App - Customized but not in any customization project I have a mobile app that I did not write, but need to maintain.
Obviously, it has been customized. The main screen is completely changed:
MAIN MENU SCREEN SHOT FROM MOBILE APP IN ANDROID:

I need to know/change the screen that is being called when the mobile app user selects "Stock Items."
The problem is there is not ANY project in the customization projects list (Screen ID=SM204505) that has any modifications made to the mobile app. I mean NONE of them have ANY modifications. I looked in every project, and even in every tenant's projects. There is no mobile modifications listed anywhere.
The App\Mobile directory is empty except for the standard drilldown.ashx file.

I looked in the SQL Table: [MobileSiteMap] -- but not only do I not find the menu I am looking for, I find no menus available for anything other than CompanyID = 1. (This is company 2)
Where is it getting the customized menu, and how can I change what screen is getting called?

A: Go see if any of your GI is enabled for mobile app. By default they get added to the app main menu without further customization to the mobile app itself.

A: The mobile app is a UI layer for the screens in Acumatica.  It doesn't provide custom functionality to the business logic layer.  To see which screens added by default, create a new customization project.  Next, add a command to edit the sitemap.  On the preview pane, you will notice the folder structure &  screens that are added by default.


text:
Q: not able to run the first run.py of eve I'm trying to learn eve to use it to expose a database and I'm starting from the beginning eve first step.
run.py
from eve import Eve
app = Eve()

if __name__ == '__main__':
    app.run()

settings.py
DOMAIN = {'people': {}}

requirements.txt
scrapy==0.24.4
eve==0.5
pymongo==3.0.1

python run.py
   eve.io.base.ConnectionException: Error initializing the driver. Make sure the database serveris running. Driver exception: ConfigurationError('Unknown option auto_start_request',)

what's wrong? Why is there a problem with the database although I followed exactly what is in the eve quickstart?

*

*virtualenv --version: 12.0.7

*pip -V: 6.1.1

*python --version : 2.7.6

*MongoDB shell version: 2.4.9

A: The error you are getting is because you are running PyMongo 3.0.1 which breaks backward compatibility in a big way. If you look into Eve requirements you will find that it requires PyMongo 2.8 (actually it's 2.7.x in production; 2.8+ on the development branch).
If you got PyMongo 3.0.1, then I suspect that you installed the requirements by hand. The  ideal way to install Eve (or any other Python library really) is to pip install from PYPI, even better if in a virtualenv; see installation page.
For the record, a PyMongo 3.0.1 compatibile branch is ready on GitHub, but it is currently relying on a Flask-PyMongo fork since the current Flask-PyMongo release is not compatible with PyMongo 3+. Also, if you want to run MongoDB 3.0 with Eve you can do that. PyMongo 2.8 is fully compatibile with MongoDB 3.0.


text:
Q: Incorrect template substitution error with g++8.3 I have the following program -
class foo {
    typedef foo type;
};

template<typename A>
using type_t = typename A::type;

template <typename T>
type_t<T> bar(void){
    return type_t<T>();
}

int main() {
    bar<foo>();
    return 0;
}

It is malformed because you cannot access foo::type inside bar because it is private (if I make type public, the program compiles fine.)
But when I try to compile this with g++8.3, I get the following error -
prog.cpp: In function 'int main()':
prog.cpp:16:11: error: no matching function for call to 'bar<foo>()'
  bar<foo>();
           ^
prog.cpp:11:11: note: candidate: 'template<class T> type_t<T> bar()'
 type_t<T> bar(void){
           ^~~
prog.cpp:11:11: note:   template argument deduction/substitution failed:
prog.cpp: In substitution of 'template<class A> using type_t = typename A::type [with A = foo]':
prog.cpp:8:32:   recursively required by substitution of 'template<class A> using type_t = typename A::type [with A = foo]'
prog.cpp:8:32:   required by substitution of 'template<class A> using type_t = typename A::type [with A = foo]'
prog.cpp:11:11:   required by substitution of 'template<class T> type_t<T> bar() [with T = foo]'
prog.cpp:16:11:   required from here
prog.cpp:8:32: fatal error: template instantiation depth exceeds maximum of 900 (use -ftemplate-depth= to increase the maximum)
 using type_t = typename A::type;

Live here on Ideone
What is happening here? Is this a compiler bug or am I not understanding something correctly? Is the typedef being marked as private cause SFINAE to kick in somehow causing it to look for alternate substitutions that are recursive?
Btw, I get the correct error about type being private if I don't use the type alias type_t and directly define the function bar as -
template <typename T>
typename T::type bar(void) {
    return typename T::type();
}

The error also has nothing to do with the fact that foo::type is foo. If I change the typedef to typedef int type, I still get the same error about recursive substitution.


text:
Q: how to know AD Forest name in central admin? I'm creating user profile service application in sharepoint server 2013 . for creating new sync connection , I need to enter Forest name. But I don't have permissions to see AD . I just have Farm account.
I have tried the below powershell cmd but no luck.
$forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()

So anyone have smart idea to know forest name?? Thanks.

A: If you have the AD DS Tools installed you can run the cmdlet Get-ADDomainController
Get-ADDomainController

or
Get-ADDomainController | Select-Object Forest

A: Your Farm Account should have read access to AD for many farm purposes.
So let's suppose it has it.
You can get forest name by executing below code in PowerShell (suspect you have not loaded assembly before calling GetCurrentForest):

[System.Reflection.Assembly]::LoadWithPartialName('System.DirectoryServices') | Out-Null
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()

If you have AD Module installed on your server, you can also use it like this:

Get-ADForest

or

(Get-ADDomain).Forest

Hope it helps.


text:
Q: HTML Required tag does not respond with Jquery I'm trying to let the user fill a form.
When the user has filled the form correctly the logo on the webpage changes and the data of the form gets posted to the PHP page where it is being send to the database.
I have trouble with the "required" attribute working with the Jquery code for the submit button because the attribute does not show up when I hook up any Jquery code.
Is there a way to let the original functionality of the "required" attribute to work with the Jquery code I provided below while staying on the same page?
<form class="center" action="" method="post" id="form">
   <input type="text" id="name" name="name" placeholder="Name" style="width: 175px" required>

   <input type="email" id="email" name="email" placeholder="Email" style="width: 175px" required>

   <input type="text" id="telephone" name="telephone" placeholder="telephone" style="width: 175px" required>

   <select style="width: 175px" id="name" name='city' required>
      <option value='null' selected="selected" disabled="disabled">Select an option</option>
      <option value='option1'>option1</option>
      <option value='option2'>option2</option>
   </select>

   <input type="button" id="submit" value="submit" style="width: 175px">
</form>

$("#submit").on('click', function() {
   $("#image").attr("src", "2.png");
   $.post("sender.php", {
      name: $('#name').val(),
      email: $('#email').val(),
      telephone: $('#telephone').val(),
      city: $('#city').val()
   });
});

A: You need to use event.preventdefault()in jquery. preventdefault will stop default action(submitting the form) and then you can write your code to validate and display error.
$("#submit").on('click', function() {
   event.preventdefault();
// call some function to validate & display error.
   $("#image").attr("src", "2.png");
   $.post("sender.php", {
      name: $('#name').val(),
      email: $('#email').val(),
      telephone: $('#telephone').val(),
      city: $('#city').val()
   });
});

A: Try with this one :-
$("#form").validate({
                submitHandler : function() {
//Your Code
});

User jquery validation for working in all browser


text:
Q: How would a select an ARIMA model based on the ACF and PACF? I am trying to estimate a model based on the ACF and PACF. I understand the ACF applies to MA and PACF applies to AR. Do I just count the significant lines and order it that way? I have used a Box Cox transformation and differenced the data.
I am attempting to forecast monthly oil production in the US. Data chart is posted below.
https://www.eia.gov/dnav/pet/hist/LeafHandler.ashx?n=PET&s=MCRFPUS1&f=M

A: Sometimes too much of a good thing is not so good !.   Your 1201 monthly values starting at at 1920/1 is such an example. The historical plot is hysterical  suggesting that one might start with the last 109 values starting at 2011/1  ... A recent consistent set of values .
Time series can have both auto-projective and/or deterministic structure. If one limits the solution space to purely arima structure ignoring level shifts and time trend changes and changes in model error variance and possible seasonal pulses and assumes no anomalies ..one can come up VERY SHORT of identifying a possibly useful model. .
There is no need/justification to seasonally difference this data set ... there is just 1 month of the year (Feb) that appears to be consistently exceptional (DOWN).
The 109 most recent values are a cacaphony suggesting the need for data mining yielding an error process that is free of structure.
Here is the Actual/Fit and Forecast for the most recent 109 values  . The model form contains NO ARIMA STRUCTURE  and here
To summarize there is a seasonal dummy at February of each year AND an identified error variance enlargement  at 2014/7  from http://docplayer.net/12080848-Outliers-level-shifts-and-variance-changes-in-time-series.html  and time trends and level shift indicators.
The Actual and Cleansed graph is illuminating  . The Forecast graph is here
The residual ACF is here
I used AUTOBOX ( a piece of software that I have helped  develop) to automatically dissect your data to signal and noise . The free time series modelling tools fitting a pre-set of arma models and using a simplistic AIC/BIC criteria will sometimes work on data that is uncomplicated ... your selected series , as most are , is complicated.


text:
Q: Sort Array of strings on characters and return all matching elements I have an array of objects
var carList = [
    {
        car: "maruti",
        colors: ["red", "redish","yellow"]
    },
    {
        car: "ferrari",
        colors: ["purple", "red"]
    },
    {
        car: "Merc",
        colors: ["pink", "green"]
    }
];

Now I have an input search field where user can type the color of the car.
so if the user types red then only maruti and ferrari object should be returned.
and if user types reddish then only maruti object should be returned.
I tried using nested filter
var textToSearch = "re";
var test = carList.filter((x) => x.colors.filter((y)=> y.indexOf("textToSearch") > -1) );

Even if the search string is of only 2 characters like "re" then also it should return maruti and ferrari as output.
but this returns all the objects not just maruti and ferrari
Note: I want that it should return all the matching elements and not just the first matching element.

A:

var carList = [
    {
        car: "maruti",
        colors: ["red", "redish","yellow"]
    },
    {
        car: "ferrari",
        colors: ["purple", "red"]
    },
    {
        car: "Merc",
        colors: ["pink", "green"]
    }
];
var m = carList.filter((eachCar) => {
    var colors = eachCar.colors;
    return colors.filter((eachColor) => {
           return eachColor.indexOf('in') !== -1
    }).length > 0;
});

console.log(m);

A: Use includes() in combination with some() inside the filter() to check if textToSearch exist in the colors array:
var textToSearch = "r";
var test = carList.filter(x => x.colors.some(cl => cl.includes(textToSearch)));
console.log(test);

var carList = [{
    car: "maruti",
    colors: ["red", "redish", "yellow"]
  },
  {
    car: "ferrari",
    colors: ["purple", "red"]
  },
  {
    car: "Merc",
    colors: ["pink", "green"]
  }
];

var textToSearch = "re";
var test = carList.filter(x => x.colors.some(cl => cl.includes(textToSearch)));
console.log(test);

Note: You have to be carefully with this approach since re matches green!

Based on comment:

var carList = [{
    car: "maruti",
    colors: ["red", "redish", "yellow"]
  },
  {
    car: "ferrari",
    colors: ["purple", "red"]
  },
  {
    car: "Merc",
    colors: ["pink", "green"]
  }
];

function getCars(event) {

  // Value of input field
  var value = event.target.name;

  // Sort carList
  var res = carList.filter(x => x.colors.some(cl => cl.includes(value)));

  // Show result to console
  console.log(res);
}
<input onclick="getCars(event);" name="red" type="checkbox">red</input>
<input onclick="getCars(event);" name="llow" type="checkbox">llow</input>

A: Two problems:

*

*The function filter always returns an array, which is truthy value.

*You have a typo on the variable textToSearch which is wrapped by double-quotes.

I recommend you to use the function some along with the function includes instead.

let carList = [{    car: "maruti",    colors: ["red", "redish","yellow"]},{    car: "ferrari",    colors: ["purple", "red"]},{    car: "Merc",    colors: ["pink", "green"]}],
    textToSearch = "ed",
    fieldName = "colors",
    test = carList.filter((c) => c[fieldName].some(c => c.includes(textToSearch)));

console.log(test)
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: I think it's a late answer. But you can follow my regex solution.
Here I use RegExp.prototype.test() method, with help of Array.prototype.some() and Array.prototype.filter().

var carList = [{car: "maruti", colors: ["red", "redish","yellow"]}, {car: "ferrari", colors: ["purple", "red"]}, {car: "Merc", colors: ["pink", "green"]}];

const searchByColor = (list, keyword) => {
    // If you want the keyword must match from the beginning
    // const regex = new RegExp(`^${keyword}`, 'ig');

    // If you want the keyword matches anywhere of the string
    const regex = new RegExp(keyword, 'ig');
    return list.filter(({colors}) => colors.some(color => regex.test(color)));
}

console.log('For keyword "re":', searchByColor(carList, 're'));
console.log('For keyword "redish":', searchByColor(carList, 'redish'));
.as-console-wrapper {min-height: 100%!important; top: 0;}

Note: notice that the color named green also has re substring. It's good to fetch as many relevant search results as you can.
But if you don't want to match anywhere of a string then use the commented first regex approach. That is use the regex as:
const regex = new RegExp(`^${keyword}`, 'ig');

A: You can use filter & some. Inside filter callback use some to get colors which includes the searched color

var carList = [{
    car: "maruti",
    colors: ["red", "redish", "yellow"]
  },
  {
    car: "ferrari",
    colors: ["purple", "red"]
  },
  {
    car: "Merc",
    colors: ["pink", "green"]
  }
]

function getCar(color) {
  return carList.filter(item => item.colors.some(col => col.includes(color)))
}
console.log(' When it is red ', getCar('red'));
console.log('When it is redish', getCar('redish'));


text:
Q: Insertion sort algorithm with sorted list I am preparing for algorithm exam and have the following question: If we provide a sorted list to the insertion sort algorithm, would it still take O(n^2) ?

A: No it should run in O(n) time as this is the best case for this algorithm
https://en.wikipedia.org/wiki/Insertion_sort


text:
Q: switching between models via keybord in asp.net mvc I'm writing module for Orchard CMS. I have Projection with several elements? and each element has it's own javascript popup, which appears after clicking "Popup" button.
How can I make switching between popups by keyboard arrows? Every popup get data from it's own model.
Model:

@T("ProductName -") @Model.Name

@T("Art - ") @Model.Art

@T("Packing - ") @Model.Packing

@T("Country - ") @Model.Country

@T("Price - ") @Model.Price

@T("Name - ") @Model.Name

@T("Art - ") @Model.Art

@T("Price - ") @Model.Price

@T("Packing - ") @Model.Packing

@T("Country - ") @Model.Country

<button onclick="closePopup('@Model.Art');" class="price"></button>

JS:
function showPopup(id) {
var popup = document.getElementById(id);
popup.style.display = 'block';
}

function closePopup(id) {
var popup = document.getElementById(id);
popup.style.display = 'none';
}

document.onkeydown = checkKeycode
function checkKeycode(e) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
if (keycode == 37) {
    alert("left");
}
if (keycode == 39) {
    alert("right");
}
}

So, I need switch between Models where keypressed "left" or "right" (alerts in my code).


text:
Q: I have 4 SQL Server tables that all i am using same primary key i need below condition SQL Query I have 4 tables

*

*client

*clientmanager

*Employee

*project
in SQL Server. For all tables, I am using a primary key clientid so I like to count list of projects, employee, clients mangers using clientid.

A: SELECT  client.clientid, client.client_name, count(Employee.Employee) as Employee,count(project.project) as project
    FROM    ((client  INNER JOIN clientmanager ON client.clientid = clientmanager.clientid)
                      INNER JOIN Employee ON client.clientid = Employee.clientid)
                      INNER JOIN project ON client.clientid = project.clientid


text:
Q: jqplot meter -> Flot? I started using the jqplot library but for implementation reasons, moved on to flot instead.  I found it easier to work with for the data updates I was dealing with.
There was a meter addon for jqplot, and i'd like to get that working again in flot.   Has anyone worked with this before?   I really don't want to distribute this page with 2 different versions of librays that effectively do the same thing.
Basically I need a
  jqplot.meterGaugeRenderer.min.js

file for flot


text:
Q: How to see list of questions I have edited? One of the questions that I had edited few days ago was rejected by someone from SO site, and now I am not able to find what question was that I had edited. And so was wondering how to find the list of questions that I have edited in SO sites?

A: In your Activity tab, under all actions -> suggestions tab you can find all the approved, pending, rejected edits suggested by you.
Or you can use the link to navigate the tab directly.
https://<sitename>.com/users/current?tab=activity&sort=suggestions


text:
Q: WSO2 Greg and ESB integration samples I am attempting to use Greg to hold endpoint URL's for services deployed into non-WSO2 containers (Weblogic/JBoss). I would like to use WSO2 ESB to perform mediation and routing of data through these endpoints.
However, when I look at the WSO2 ESB samples, it is not clear how I instruct the ESB to use WSO2's Greg. Below is the xml used to have the ESB use a registry deployed to the filesystem.
<definitions xmlns="http://ws.apache.org/ns/synapse">
    <registry provider="org.wso2.carbon.mediation.registry.ESBRegistry">
        <parameter name="root">file:./repository/samples/resources/</parameter>
        <parameter name="cachableDuration">15000</parameter>
    </registry>
 </definitions>

My assumption is that the registry tag's provider element should probably be able to be overridden with a web-service address providing access to Greg.
When all is said and done, I would like to create simple BPMN configuration files that connect to Greg, obtain URI's and URL's for the services used by the file, and then to reference them as properties later in the BPMN route.
First question, is this a standard configuration, or is there a better way to integrate WSO ESB and Greg.
Second question, are there any examples I could refer to that will answer this question?

A: Please refer following documentation.
[1] http://wso2.org/library/tutorials/2010/04/sharing-registry-space-across-multiple-product-instances
[2]http://docs.wso2.org/wiki/display/ESB460/Storing+Various+WSO2+Enterprise+Service+Bus+Configurations
Those include how you can store and using WSO2 governance registry in highlevel.
If you need to manage endpoints through API in governance registry following will help.
[3] http://docs.wso2.org/wiki/display/Governance453/Endpoints+with+Governance+API
[4] http://docs.wso2.org/wiki/display/Governance453/Endpoint+Look-up+Sample
Futher this thread include some of the hints how you can access custom stored properties in Registry
[5]How to access system property from WSO2 ESB and Registry

A: WSO2 Governance Registry is a meta data repository, therefore you can use it to store the SOA artifacts (WSDL,Schems,Policies, Mediation configurations , customs artifacts ..etc) of your deployment. After that you can govern  those artifacts through the Governance Registry. You can find more details in the ESB documentation[1].
[1]http://docs.wso2.org/wiki/display/ESB460/Config+and+Governance+Partitions+in+a+Remote+Registry
Thanks & Regards,
Ajith


text:
Q: Keep specific columns from a dataframe pandas I have a dataframe from an import csv using pandas. This dataframe has 160 variables and I would like to keep only 5, 9, 10, 46, 89.
I try this:
dataf2 = dataf[[5] + [9] + [10] + [46] + [89]]

but I take this error:
KeyError: '[ 5 9 10 46 89] not in index'

A: If you want to refer to columns not by their names but by their positions in the dataset, you need to use df.iloc:
dataf.iloc[:, [5, 9, 10, 46, 89]]

Row indices are specified before the comma, column indices are specified after the comma.

A: If the columns that you would like to keep are: 5, 9, 10, 46, 89, then you can index just these ones like so:
dataf2 = dataf[[5, 9, 10, 46, 89]]


text:
Q: BLE: Why are Write Commands slower than Notifications? In the context of BLE (Bluetooth Low Energy), Write Commands can be used to write from a Client to the Server, and Notifications to write from the Server to the Client. In my setup, the Client is a Central device (Android phone), and the Server is a Peripheral (dev board).
After performing several data throughput tests with multiple phones, I noticed that the throughput varies greatly with the phone, which is expected because a great deal of the BLE lower layers implementation is up to the manufacturer to figure out. But what caught my attention was that Write Command always achieve a much lower throughput that Notifications, independently from the phone. Why is that?

A: They should have the same throughput. Multiple write commands and notifications can be sent during one connection event. They are treated the same.
You could use an air sniffer to see if you find any problems.
How long the connection event should be open can be suggested when the connection is created and with connection parameter updates. Sadly, Android's BLE stack hard codes this to the default value, which means no recommendation. That will in practice mean you are limited to 3 or 4 packets per connection event.


text:
Q: Optimize MySQL Query using indexes (what index?) I am struggling to optimize the following query which takes an average of 2000 ms.
select  count(pk)
    from  mytable
    where  (pk<>5
      and  url='test.png'
      and  (data=124578 or  (data is null and  pk=1234578)))
      and  type in (123,456,789,015,789)

Here are some info :
select count(*) from mytable

1 526 588 lines
show indexes in mytable

Table   non_unique  key_name            seq_in_index    column_name collation   cardinality
mytable 0           PRIMARY             1               PK          A           1405079
mytable 1           data                1               data        A           1405079
mytable 1           Media_Code_30       1               code        A           1405079
mytable 1           codeVersionIDX_30   1               code        A           1405079

Explain :
id  select_type table   type        possible_keys   key     key_len ref     rows    extra
1   SIMPLE      mytable ref_or_null PRIMARY,data    data    9       const   635908  Using where

I really have no idea whether this is optimized enough, or it can be better by creating new indexes (or composite indexes).
The query, however, cannot be changed as it is coming from another system on which I do not have my hands on!

A: Hmmm, this query seems difficult to set up an index for:
select count(pk)
from mytable
where (pk <> 5 and url = 'test.png' and
       (data = 124578 or (data is null and pk = 1234578))
      ) and
      type in (123, 456, 789, 015, 789);

My suggestion is to start with type and include the other columns in the index:  mytable(type, url, data, pk).  This is a covering index and that might improve performance a bit.

A: This is not the Answer. Only some sample for using index
SAMPLE
small Table
MariaDB [bb]> SHOW CREATE TABLE useindex\G
*************************** 1. row ***************************
       Table: useindex
Create Table: CREATE TABLE `useindex` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `num1` int(11) DEFAULT NULL,
  `num2` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2031586 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

number of rows and sample data
MariaDB [bb]> SELECT count(*) FROM USEindex;
+----------+
| count(*) |
+----------+
|  2000000 |
+----------+
1 row in set (0.43 sec)

MariaDB [bb]> SELECT * FROM useindex LIMIT 10;
+----+------+------+
| id | num1 | num2 |
+----+------+------+
|  1 |  405 |  906 |
|  2 |  656 |  656 |
|  3 |  906 |  407 |
|  4 |  156 |  157 |
|  5 |  406 |  908 |
|  6 |  656 |  659 |
|  7 |  907 |  409 |
|  8 |  157 |  160 |
|  9 |  407 |  910 |
| 10 |  657 |  661 |
+----+------+------+
10 rows in set (0.00 sec)

EXPLAIN 3 queries (no index)
MariaDB [bb]> EXPLAIN SELECT * FROM useindex WHERE num1 = 500;
+------+-------------+----------+------+---------------+------+---------+------+---------+-------------+
| id   | select_type | table    | type | possible_keys | key  | key_len | ref  | rows    | Extra       |
+------+-------------+----------+------+---------------+------+---------+------+---------+-------------+
|    1 | SIMPLE      | useindex | ALL  | NULL          | NULL | NULL    | NULL | 1996444 | Using where |
+------+-------------+----------+------+---------------+------+---------+------+---------+-------------+
1 row in set (0.00 sec)

MariaDB [bb]> EXPLAIN SELECT * FROM useindex WHERE num2 = 600;
+------+-------------+----------+------+---------------+------+---------+------+---------+-------------+
| id   | select_type | table    | type | possible_keys | key  | key_len | ref  | rows    | Extra       |
+------+-------------+----------+------+---------------+------+---------+------+---------+-------------+
|    1 | SIMPLE      | useindex | ALL  | NULL          | NULL | NULL    | NULL | 1996444 | Using where |
+------+-------------+----------+------+---------------+------+---------+------+---------+-------------+
1 row in set (0.00 sec)

MariaDB [bb]> EXPLAIN SELECT * FROM useindex WHERE num1 = 500 AND num2 = 600;
+------+-------------+----------+------+---------------+------+---------+------+---------+-------------+
| id   | select_type | table    | type | possible_keys | key  | key_len | ref  | rows    | Extra       |
+------+-------------+----------+------+---------------+------+---------+------+---------+-------------+
|    1 | SIMPLE      | useindex | ALL  | NULL          | NULL | NULL    | NULL | 1996444 | Using where |
+------+-------------+----------+------+---------------+------+---------+------+---------+-------------+
1 row in set (0.00 sec)

add 2 indexe
MariaDB [bb]> ALTER TABLE useindex
    -> ADD KEY n1 (num1),
    -> ADD KEY n2 (num2);
Query OK, 0 rows affected (12.08 sec)
Records: 0  Duplicates: 0  Warnings: 0

EXPLAIN with index
see if the WHERE with 2 fields, MySQL use only one INDEX
MariaDB [bb]> EXPLAIN SELECT * FROM useindex WHERE num1 = 500;
+------+-------------+----------+------+---------------+------+---------+-------+------+-------+
| id   | select_type | table    | type | possible_keys | key  | key_len | ref   | rows | Extra |
+------+-------------+----------+------+---------------+------+---------+-------+------+-------+
|    1 | SIMPLE      | useindex | ref  | n1            | n1   | 5       | const | 2003 |       |
+------+-------------+----------+------+---------------+------+---------+-------+------+-------+
1 row in set (0.00 sec)

MariaDB [bb]> EXPLAIN SELECT * FROM useindex WHERE num2 = 600;
+------+-------------+----------+------+---------------+------+---------+-------+------+-------+
| id   | select_type | table    | type | possible_keys | key  | key_len | ref   | rows | Extra |
+------+-------------+----------+------+---------------+------+---------+-------+------+-------+
|    1 | SIMPLE      | useindex | ref  | n2            | n2   | 5       | const | 1993 |       |
+------+-------------+----------+------+---------------+------+---------+-------+------+-------+
1 row in set (0.00 sec)

MariaDB [bb]> EXPLAIN SELECT * FROM useindex WHERE num1 = 500 AND num2 = 600;
+------+-------------+----------+------+---------------+------+---------+-------+------+-------------+
| id   | select_type | table    | type | possible_keys | key  | key_len | ref   | rows | Extra       |
+------+-------------+----------+------+---------------+------+---------+-------+------+-------------+
|    1 | SIMPLE      | useindex | ref  | n1,n2         | n2   | 5       | const | 1993 | Using where |
+------+-------------+----------+------+---------------+------+---------+-------+------+-------------+
1 row in set (0.00 sec)

add COMPOSITE Index over both fields
MariaDB [bb]> ALTER TABLE useindex
    -> ADD KEY n12 (num1,num2);
Query OK, 0 rows affected (7.83 sec)
Records: 0  Duplicates: 0  Warnings: 0

EXPLAIN Queries again
Now they use the COMOSITE Index
MariaDB [bb]> EXPLAIN SELECT * FROM useindex WHERE num1 = 500;
+------+-------------+----------+------+---------------+------+---------+-------+------+-------------+
| id   | select_type | table    | type | possible_keys | key  | key_len | ref   | rows | Extra       |
+------+-------------+----------+------+---------------+------+---------+-------+------+-------------+
|    1 | SIMPLE      | useindex | ref  | n1,n12        | n12  | 5       | const | 2003 | Using index |
+------+-------------+----------+------+---------------+------+---------+-------+------+-------------+
1 row in set (0.00 sec)

MariaDB [bb]> EXPLAIN SELECT * FROM useindex WHERE num2 = 600;
+------+-------------+----------+------+---------------+------+---------+-------+------+-------+
| id   | select_type | table    | type | possible_keys | key  | key_len | ref   | rows | Extra |
+------+-------------+----------+------+---------------+------+---------+-------+------+-------+
|    1 | SIMPLE      | useindex | ref  | n2            | n2   | 5       | const | 1993 |       |
+------+-------------+----------+------+---------------+------+---------+-------+------+-------+
1 row in set (0.00 sec)

MariaDB [bb]> EXPLAIN SELECT * FROM useindex WHERE num1 = 500 AND num2 = 600;
+------+-------------+----------+------+---------------+------+---------+-------------+------+-------------+
| id   | select_type | table    | type | possible_keys | key  | key_len | ref         | rows | Extra       |
+------+-------------+----------+------+---------------+------+---------+-------------+------+-------------+
|    1 | SIMPLE      | useindex | ref  | n1,n2,n12     | n12  | 10      | const,const |    1 | Using index |
+------+-------------+----------+------+---------------+------+---------+-------------+------+-------------+
1 row in set (0.00 sec)

Tell the OPTIMIZER to MERGE INDEX
MariaDB [bb]> SET optimizer_switch='index_merge=on';
Query OK, 0 rows affected (0.00 sec)

drop INDEX n12
MariaDB [bb]> alter table useindex drop key n12;
Query OK, 0 rows affected (0.07 sec)
Records: 0  Duplicates: 0  Warnings: 0

RUN one QUERY with MERGE
MariaDB [bb]> EXPLAIN SELECT * FROM useindex WHERE num1 = 500 AND num2 = 600;
+------+-------------+----------+-------------+---------------+-------+---------+------+------+--------------------------------------------------+
| id   | select_type | table    | type        | possible_keys | key   | key_len | ref  | rows | Extra                                            |
+------+-------------+----------+-------------+---------------+-------+---------+------+------+--------------------------------------------------+
|    1 | SIMPLE      | useindex | index_merge | n1,n2         | n2,n1 | 5,5     | NULL |    1 | Using intersect(n2,n1); Using where; Using index |
+------+-------------+----------+-------------+---------------+-------+---------+------+------+--------------------------------------------------+
1 row in set (0.00 sec)

MariaDB [bb]>

A: MySQL can only use one INDEX in a query.
so it is necessary  to have composite index. the best way for the order of the fields in the index is the field which reduce the resultset mostly and so on.
lets say you have a table with names and birthday and you have many duplicates of names and only a few of birthday. so then create the index like (birthday,name) the mysql search first the records with the searched day and then only in this little result the name

A: The best index for that query is
INDEX(url, type) -- in that order

Indexes should start with any columns that are "= constant" (url in this case), then move on to one more column that is more complex (type IN ...).  See my cookbook.


text:
Q: symfony2 hierarchical ACL I've got the following problem:
Most of my entities are saved with a link to a tree structure with the doctrine tree extension. I started to implement the acl system but soon realised that it would't completely fit.
Small fictional example to make this clear:

*

*Sports group

*

*Tennis group

*Basketball group

*Swimming group

News items can be added to these different groups. Now with the symfony acl i can grant rights to all or individual news entities. I would like to be able to grant rights to the entities in specific groups to one user.
Should i drop the use of the acl system and write my own or is there another way to fix this?


text:
Q: What is purpose of runApp() ? & define runApp() and main() function in flutter? What is the core difference between the runApp() and main() function?
why do we use the runApp() and main() function in the beginning of the flutter code...

A: 1-> main()-=>this is the main function. The flutter compiler doesn't allow to compile of any line of code
2->runApp()--=>this is the main function that runs the main screen. With help of this widget, you can run those screens that you want to run. This screen is known as the root screen of your app.


text:
Q: MS Access popup form conditional on combobox value I am working on a database to store a heap of animal behavioural observation data and am working on creating a form to input data (one of many forms). The main form feeds into a table called "FocalSample" and the subform feeds into a "FocalData" table.
This is the form at present
There will be multiple records in the subform to a single overarching sample, a sample is a 10 minute period and a single animals behaviour is documented over that 10 minutes, noting time in minutes and seconds to calculate duration of time spent in each behaviour.
I need popup forms to come up depending on what is selected in the "Behaviour Type" field of the subform, as the kind of data recorded for a "feed" observation compared to a "social" observation is very different. I have created separate tables for the different behaviour types of data and forms that are set as "popup" forms, but need help with the code to get it to do what I need! :P
I have been trying a variation of the following code that I found here (http://www.justskins.com/forums/pop-up-form-based-238440.html)
Private Sub Campaign_AfterUpdate()
Dim strFormName As String
Select Me.Campaign.Value
Case "In Honor", "In Memory"
strFormName = "HonorMemory"
Case "In-Kind"
strFormName = "InKind"
End Select
DoCmd.OpenForm strFormName, , , , , acDialog
End Sub

But I keep getting an error message after the first row.
Here is the error and code screen
Similar to the other forum link I attached, I also need the popup form to draw a lot of info from the main form, but I'd just be happy to be able to get the popup forms working at the moment.
Sorry for so much detail - I am in a remote area of Africa and only have limited access to internet so am trying to give as much info up front!
Example of popup form - you might be able to determine fields that will feed off the focalsample form
Another example of a popup form - different behaviour type to the previous
EDIT
I have jigged the code now based off previous response but am not getting a different error.This is the code with the error line highlighted -  I am not sure what table name to add if any
Error code

A: The line Select Me.Campaign.Value should read Select Case Me.Campaign.Value.


text:
Q: Error al llamar a digest Mi archivo js:
$scope.loadOptions = function(email) {
   //aqui llamo a varios métodos y al final tengo voy asignando valores a variables
   $scope.$apply();
}

mi archivo html:
<div ng-init="loadOptions">
  <textarea class="w95" name="tinymce${it?.id}" id="tinymce${it?.id}">{{qualitative[${it.id}]}}</textarea>
</div>

Obtengo este error :
Error: [$rootScope:inprog] http://errors.angularjs.org/1.5.3/$rootScope/inprog?p0=%24digest

El valor del textarea hay veces que me lo muestra y otras no, no se si esta relacionado que tengo que actulizar los valores

A: $apply forza la ejecucion de un $digest() por debajo. La directiva ngClick ya tiene un evento $apply() corriendo y no puedes correr 2 $digest() al mismo tiempo.
Solo debes de utilizar $apply() cuando estas fuera del contexto de angularjs. Digase fuera del controlador o en un codigo externo:
$("#button").click(function(){
  angular.element($("#mi-otro-boton-dentro-de-un-controlador").scope().$apply();
});

El evento click de jquery  esta fuera del contexto de angularjs y no ejecuta $apply(), por lo que al ejecutar $apply forzamos manualmente a angular a actualizar la vista utilizando el $digest().
En resumen. Elimina $scope.$apply() ya que ngClick lo esta ejecutando.

A: El problema que estás teniendo se relaciona un poco al funcionamiento de Javascript, otro poco a como funciona Angular. Como dice Einer, el $apply es invocado por Angular en todos los casos, y si intentás llamar a $apply dentro otro $apply, tira el error que estás teniendo.
En algunos casos es necesario volver a llamar el $apply ya que Angular puede no puede detectar cambios que se encuentran fuera de su scope.
Una solución para estos casos, es forzar a Javascript a que genere otra "ronda" o "turno" de ejecución.
En mi caso he tenido situaciones en las cuales necesitaba forzar un refresh y para esos casos, en angular 1 y 2, me ha servido hacer esto:
  setTimeout(function() {
    $scope.$apply(function() {
      $scope.name = "Timeout called!";
    });
  }, 0);

Esta nota (http://jimhoskins.com/2012/12/17/angularjs-and-apply.html) me sirvió mucho para poder entender cuando y como usar el $apply de una forma que no se convierta en un anti-patrón en tu aplicación.
Te dejo un ejemplo de esta teoría aplicada: https://plnkr.co/edit/BZJH9qN6ux3rPRVgyJUk?p=preview
En el ejemplo vas a poder ver varias cosas, de cuando se actualiza y cuando no.
Una sola aclaración mas, siempre antes de aplicar este tipo de soluciones, revisa primero tu lógica, en mi caso, en 8 de cada 10, encontré otra solución que arreglaba el problema.
Segunda aclaración, en vez de setTimeout, conviene usar $timeout que ya tiene incluido un $apply en el código, pero en la respuesta quise demostrar un poco el porqué del error y como solucionarlo de acuerdo a sus causas.
Espero que sea de tu utilidad, en caso contrario, no dudes en volver a preguntar.

A: La forma mas segura de aplicar un $scope.$apply(); es haciendolo dentro de un $timeout. Algo asi:
$timeout(function(){
    $scope.$apply();
});

De esta forma no obtendras el error que describes.


text:
Q: Android webview not show full content (Bootstrap and jQuery) On my mobil yandex or chrome browser shows full content of this page
https://www.sbm.org.tr/tr/OnlineIslemler/Sayfalar/TrafikPoliceSorgula.aspx
but my webview not show full content.
Here is my code
 public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView mWebView = (WebView) findViewById(R.id.webview);

        mWebView = (WebView) findViewById(R.id.webview);

        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);

         mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);

        mWebView.loadUrl("https://www.sbm.org.tr/tr/OnlineIslemler/Sayfalar/TrafikPoliceSorgula.aspx");

      /*  final ProgressDialog progress = ProgressDialog.show(this, "Sayfa", "Yükleniyor....", true);
        progress.show();
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Toast.makeText(getApplicationContext(), "Sayfa yüklendi", Toast.LENGTH_SHORT).show();
                progress.dismiss();
            } `

            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(getApplicationContext(), "Bir hata oluştu", Toast.LENGTH_SHORT).show();
                progress.dismiss();
            }
        });

*/
    }
}

A: Webview has overview mode. For more information see setLoadWithOverviewMode
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);


text:
Q: Proccessing compare combination of 3 Strings I'm making a small game for a school project. In my game I have 9 cards on a 3x3 field, every card has 3 properties: count, shape and color. You have a set when 3 cards share the same or different properties, so when all colors are the same or different and all three shapes are the same or different and all the colors are the same or different.
For example:

*

*1 red triangle, 1 red rectangle, 1 red ellipse.

*1 blue triangle, 2 green triangle

The 3 priorities have to be the same of have to be different. As you see here above the first card has the same count, different shapes and the same color.
Now I have to make a function that will check how many sets there are on the table. I have a function that will check if 3 cards are a set, but I'm not able to make a function that will check all the possible combinations of 3 cards on the field. The cards on the field are saved in a 2 dimensional array.
My program is in Dutch:

*

*setsOpTafel == sets on the table

*kaarten == cards

*aantalSets == number of sets

http://pastie.org/private/zqkfhqew1q8kwqvi6cvm0w
Can somebody help please?
edit:
How to function has to work.
so first of i have to check the combo of 3 cards -> card 1, card 2, card3.
Then card 1, card 2, card 4. and so forth till it has checked all the different combination of 3 different cards.

A: Here is simple solution. I dont know whether it is like you intended or not.
Run Code
class GAME {

    static class Card {

        public enum Shape {

            square, triangle, circle
        }

        public enum Color {

            red, blue, green
        }
        public int count;
        public Shape shape;
        public Color color;

        public int gencode(boolean difcount, boolean difcolor, boolean difshape) {
            int gen = -1;
            if (difcount == true || difcolor == true || difshape == true) {
                gen = 0;
            }
            if (difcount == true) {
                gen = count+1;//for count=0
            }
            if (difcolor == true && shape != null) {
                gen += 1000 * (shape.ordinal() + 1);
            }
            if (difshape == true && color != null) {
                gen += 100000 * (color.ordinal() + 1);
            }
            return gen;
        }

        public String  toString() {
            String s = "Card::properties " + count;
            if (color != null) {
                switch (color) {
                    case red:
                        s += " red";
                        break;
                    case blue:
                        s += " blue";
                        break;
                    case green:
                        s += " green";
                        break;
                    default:

                }
            }
            if (shape != null) {
                switch (shape) {
                    case square:
                        s += " square";
                        break;
                    case triangle:
                        s += " triangle";
                        break;
                    case circle:
                        s += " circle";
                        break;
                    default:

                }
            }

           return s;
        }

    }

    public static void add(HashMap<Integer, ArrayList<GAME.Card>> cardmap, GAME.Card card, int key) {
        ArrayList<GAME.Card> cardlist = cardmap.get(key);
        if (cardlist == null) {
            cardlist = new ArrayList<Card>();
            cardlist.add(card);
            cardmap.put(key, cardlist);
            return;
        }
        cardlist.add(card);
        return;
    }

    public static void showGroups( HashMap<Integer, ArrayList<GAME.Card>> cardmap){
        for (List<GAME.Card> value : cardmap.values()) {
            if(value.size()<=1) continue;
            System.out.println("---------------------------------------------------");
            int ii = 0;
            for (GAME.Card p : value) {
                ii += 1;
                System.out.println("" + ii + ") "+p);
            }
        }
    }

    public static void main(String[] args) {
        HashMap<Integer, ArrayList<GAME.Card>> cardmap = new HashMap< >();
        GAME.Card[] allcards = new Card[9];
     //init here (simple test
     int lennn = GAME.Card.Shape.values().length;
     int lennm = GAME.Card.Color.values().length;
     Random randomGenerator = new Random();
     for (int i = 0; i < allcards.length; i++) {
        int ppp=randomGenerator.nextInt(9);
        int kkk=randomGenerator.nextInt(2456);
        allcards[i] = new Card();
        allcards[i].count = ppp ;
        allcards[i].shape = GAME.Card.Shape.values()[ppp % lennn];
        allcards[i].color = GAME.Card.Color.values()[kkk % lennm];
       }
        System.out.println("######## Generated random cards");
          int ii = 0;
            for (GAME.Card p : allcards) {
                ii += 1;
                System.out.println("" + ii + ") "+p);
            }

        System.out.println("\n########Group at least by one property");
        //group Cards by properties and its values
        for (int i = 0; i < allcards.length; i++) {
            //check one property
            add(cardmap, allcards[i], allcards[i].gencode(true, false, false));
            add(cardmap, allcards[i], allcards[i].gencode(false, true, false));
            add(cardmap, allcards[i], allcards[i].gencode(false, false, true));

        }

        //show groups
        showGroups(cardmap);

        //check two
        System.out.println("\n########Group at least by two properties");
        cardmap = new HashMap< >();
          //group Cards by properties and its values
        for (int i = 0; i < allcards.length; i++) {
            //check two properties
            add(cardmap, allcards[i], allcards[i].gencode(true, true, false));
            add(cardmap, allcards[i], allcards[i].gencode(true, false, true));
            add(cardmap, allcards[i], allcards[i].gencode(false, true, true));
        }

        //show groups
         showGroups(cardmap);

         //check all
         System.out.println("\n########Group  by all properties");
         cardmap = new HashMap< >();
          //group Cards by properties and its values
        for (int i = 0; i < allcards.length; i++) {
            //check all properties
            add(cardmap, allcards[i], allcards[i].gencode(true, true, true));
        }

        //show groups
         showGroups(cardmap);

    }

}


text:
Q: Unable to get custom breakpoints in theme So I would like to get my custom breakpoint values from within the createMuiTheme. I've tried the following but it doesn't work, the breakpoint values are is still the default value.
import { createMuiTheme } from '@material-ui/core/styles';
import createBreakpoints from '@material-ui/core/styles/createBreakpoints';

const breakpointValues = createBreakpoints({
    xs: 0,
    sm: 800,
    md: 960,
    lg: 1280,
    xl: 1920
});

const theme = createMuiTheme({
    breakpoints: {
        values: {
            breakpointValues
        }
    },
    overrides: {
        MuiPopover: {

            root: {
                [breakpointValues.down('xs')]: { // This value is still the default '600'

                    background: "rgba(0, 0, 0, 0.26)",
                }
            }
        }
    }
});

A: Looked at this post and tried the first answer as a solution but could make it work. The second answer however did.


text:
Q: Gradient and maximum and minimum changes Suppose we have a function of $x,y,z$ such as :
$$f(x,y,z) = x^2e^y + 3\sin z$$
If we calculate the gradient of this then that would provide us with a vector quantity which represents the most rapid change.
However if i want to find the direction corresponding to a minimum change in $|f|$ then how would i go about it?


text:
Q: How to get a query string in a windows phone 8.1 app? Sorry to ask such a basic question, but I've spent the last 30mins on google and found nothing (very likely my poor search engine skills!)
I'm upgrading (well, moving code) from a windows phone 8 app to a universal app (the windows store code is largely absent at the moment, I'm currently concentrating on porting over the windows phone stuff).
Previously I was using
NavigationContext.QueryString.TryGetValue

But with 8.1 this doesn't work and I can't for the life of me find out how to get the querystring.
Any help would be very gratefully appreciated.

A: You can send a parameter the way Vyas_27 written, but make it looks like
//id - first parameter
//value - second parameter
Frame.Navigate(typeof(SecondPage), "id&value");

To get parameters
string[] parameters = ((string)e.Parameter).Split(new char[] {'&'});
string id = parameters[0];
string value = parameters[1];


text:
Q: How to pass a value by clicking on an image in bootstrap modal back to the main page I am trying to create a form where a button opens the bootstrap modal, and clicking on an image in the modal sends the filename of the image(without the extension would be best) back to the form.
The images in the modal dialogue are loaded from a folder with PHP.
Been at this for a long time and can't figure out how to do this when the images are called in PHP like this:(
Thank you in advance.
EDIT:The image filename should be passed to the textinput in the form.
Modal code:

<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
×
</button>

Choose a picture

Images

<?php
 $files = glob("img/*.*");
  for ($i=0; $i<count($files); $i++) {
      $image = $files[$i];
      echo '

      '
      ;

  }
?>

Main page code:
 <button type="button" class="btn btn-info btn-lg"
 data-toggle="modal" data-target="#myModal">Open Modal
 </button>

 Text
 Input

     <input id="textinput" name="textinput" placeholder="" class="form-
     control input-md" type="text">

A: You can use cookies maybe:

The php part would be like this:
<?php
 $files = glob("img/*.*");
  for ($i=0; $i<count($files); $i++) {
      $image = $files[$i];
      echo '

      '
      ;

  }
?>

And after closing your modal you can have your var by calling vars() function. For example having this in main page.
<button type="button" class="btn btn-info btn-lg"
  onclick="vars()" >vars
 </button>

or you can call the vars() right after setting cookie like this:

If you just want to use the image name one time and not store it somewhere for further use you can use this function:

Please select one which is better for your purpose.


text:
Q: RegEx Negative LookBehind in Java I am trying to match list of string that end in .xsd but not in form.xsd I use the following regEx:
ArrayList<String> files = new ArrayList<String>();
files.add("/abadc/asdd/wieur/file1.form.xsd");
files.add("/abadc/asdd/wieur/file2.xsd");

Pattern pattern = Pattern.compile("(?<!form{0,6})\\.xsd$");
for (String file : files) {
    Matcher matcher = pattern.matcher(file);
    if(matcher.find())
    {
        System.out.println("Found >>>> "+file);
    }
}

I expect file2 to be printed out but i do not get any result. Am i doing something wrong here?  I try the same expression in an online java regEx Tester and I get the expected result but I dont get the result in my program.

A: Well, your code example works for me.... but the {0,6} after the 'm' makes no sense..... why can there be 0 to 6 'm's ?
The expression:
"(?<!form)\\.xsd$"

would make more sense, but then I would also change your loop to use the matches() method, and change the regex accordingly:
Pattern pattern = Pattern.compile(".+(?<!form)\\.xsd");
for (String file : files) {
    Matcher matcher = pattern.matcher(file);
    if(matcher.matches())
    {
        System.out.println("Found >>>> "+file);
    }
}


text:
Q: Why is sizeof(int) different than sizeof(int*)? I am wondering why in the following program sizeof(int) returns a different value than sizeof(int*).
Here is the small program:
int main(){
    std::cout<<sizeof(int)<<endl;
    std::cout<<sizeof(int*)<<endl;
    return 0;
}

And here is the output:
4
8

Till now I remember the size of a integer pointer is 4byte(gcc compiler). How can I check the correct size of a pointer? Is it computer dependent?
I am running ubuntu 12.04
# lsb_release -a

Distributor ID: Ubuntu
Description: Ubuntu 12.04 LTS
Release:    12.04
Codename:   precise

Is the size of pointer is not constant(standard size)  8 bytes.

A: sizeof(char) == 1
There are no other guarantees(*).
In practice, pointers will be size 2 on a 16-bit system, 4 on a 32-bit system, and 8 on a 64-bit system.

(*) See the comment of James Kanze.

A: The size of a pointer is system, compiler, and architecture-dependent. On 32-bit systems it will typically be 32 bits while on 64-bit systems they will typically be 64 bits.
If you're trying to store a pointer into an integer for later restoration into the pointer again you can use the type intptr_t which is an integral type big enough to hold (I believe) normal (non-function) pointer types.

A:
For 32-bit systems, the 'de facto' standard is ILP32 - that is, int,
  long and pointer are all 32-bit quantities.
For 64-bit systems, the primary Unix 'de facto' standard is LP64 -
  long and pointer are 64-bit (but int is 32-bit). The Windows 64-bit
  standard is LLP64 - long long and pointer are 64-bit (but long and int
  are both 32-bit).
At one time, some Unix systems used an ILP64 organization.
None of these de facto standards is legislated by the C standard
  (ISO/IEC 9899:1999), but all are permitted by it.

and

If you are concerned with portability, or you want the name of the
  type reflects the size, you can look at the header , where
  the following macros are available:
int8_t int16_t int32_t int64_t
int8_t is guaranteed to be 8 bits, and int16_t is guaranteed to be 16
  bits, etc.

See this question.

A: The size of an int and an int* are completely compiler and hardware dependent.  If you're seeing eight bytes used in an int*, you likely have 64-bit hardware, which translates into eight bytes per pointer.
Hope this helps!


text:
Q: How is the gradient and hessian of logarithmic loss computed in the custom objective function example script in xgboost's github repository? I would like to understand how the gradient and hessian of the logloss function are computed in an xgboost sample script.
I've simplified the function to take numpy arrays, and generated y_hat and y_true which are a sample of the values used in the script.
Here is a simplified example:
import numpy as np

def loglikelihoodloss(y_hat, y_true):
    prob = 1.0 / (1.0 + np.exp(-y_hat))
    grad = prob - y_true
    hess = prob * (1.0 - prob)
    return grad, hess

y_hat = np.array([1.80087972, -1.82414818, -1.82414818,  1.80087972, -2.08465433,
                  -1.82414818, -1.82414818,  1.80087972, -1.82414818, -1.82414818])
y_true = np.array([1.,  0.,  0.,  1.,  0.,  0.,  0.,  1.,  0.,  0.])

loglikelihoodloss(y_hat, y_true)

The log loss function is the sum of  where .
The gradient (with respect to p) is then  however in the code its .
Likewise the second derivative (with respect to p) is  however in the code it is .
How are the equations equal?

A: The log loss function is given as:

where

Taking the partial derivative we get the gradient as

Thus we get the negative of gradient as p-y.
Similar calculations can be done to obtain the hessian.


text:
Q: How do you setup unit testable model validation with dependency injection in ASP.NET Core 2 MVC? I am building an ASP.NET Core 2 MVC application. A lot of the time I need to make use of dependencies to validate user input. I want my validation methods to be unit testable, and I want to be able to inject mocked dependencies into them. This is something I have previously done in MVC5 to great success but cannot work out the ASP.NET Core 2 equivalent.
This is how I would do it in MVC5:
// the view model to be validated
public class MyViewModel {
  public string Username { get; set; }
}

// the model validator that will have dependencies injected into it
public class MyViewModelValidator : ModelValidator
{
  private IUserService users;
  private MyViewModel model;

  public MyViewModelValidator(ModelMetadata metadata, ControllerContext controllerContext, IUserService users)
    : base(metadata, controllerContext)
    {
      this.users = users;
      this.model = base.Metadata.Model as MyViewModel;
    }

  public override IEnumerable<ModelValidationResult> Validate(object container)
  {
      List<ModelValidationResult> errors = new List<ModelValidationResult>();

      if (this.users.CheckExists(this.model.Username))
      {
          errors.Add(new ModelValidationResult() { MemberName = nameof(MyViewModel.Username), Message = "Username is not available" });
      }

      return errors;
  }
}

// this class works out which validator is required for a given model and
// injects the appropriate dependencies that is resolves using unity in my
// in my case
public class ViewModelValidatorProvider : ModelValidatorProvider
{
  private IUnityContainer container;

  public ViewModelValidatorProvider() => this.container = DependencyResolver.Current.GetService<IUnityContainer>();

  public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context)
  {
    if (metadata.ModelType == typeof(MyViewModel))
      yield return new MyViewModelValidator(metadata, context, this.container.Resolve<IUserService>());
  }
}

// the provider is hooked up in the app start in Global.asax.cs file
public class MvcApplication : System.Web.HttpApplication
{
  protected void Application_Start()
  {
    ModelValidatorProviders.Providers.Add(new ViewModelValidatorProvider());
  }
}

Now I can just create an instance of the validator with mocked dependencies and away I go! Sadly ASP.NET Core 2 doesn't have the ModelValidator class and everything I have found so far seems to want to inject dependencies via the controller or to resolve them with in an IValidatableObjects Validate() function.
Is it possible to do this in MVC Core?

A: So following the post @Nkosi left in a comment on the question I started down the right path (I think) and ended up implementing a validation system based on type filters.
To start I have a base validator model that we need to implement in our type filters:
    public abstract class BaseViewModelValidator<TModel> : IAsyncActionFilter
    where TModel : class
{
    public async virtual Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        // get the model to validate
        if (context.ActionArguments["model"] is TModel model)
            await this.ValidateAsync(model, context.ModelState);
        else
            throw new Exception($"View model of type `{context.ActionArguments["model"].GetType()}` found, type of `{typeof(TModel)}` is required.");

        await next();
    }

    public abstract Task ValidateAsync(TModel model, ModelStateDictionary state);
}

Then, because it is much nicer to use it as a named attribute rather than [TypeFilter(typeof(SomeActionFilter))], I create a TypeFilterAttribute that wraps the implementation of my base validator like this:
public class DemoViewModelValidatorAttribute : TypeFilterAttribute
{
    public DemoViewModelValidatorAttribute()
        : base(typeof(DemoViewModelValidator))
    {
    }

    internal class DemoViewModelValidator : BaseViewModelValidator<DemoViewModel>
    {
        private readonly ISomeService service;

        // dependencies are injected here (assuming you've registered them in the start up)
        public DemoViewModelValidator(ISomeService service) => this.service = service;

        public async override Task ValidateAsync(DemoViewModel model, ModelStateDictionary state)
        {
            if (await this.service.CheckSomethingAsync(model))
                state.AddModelError(nameof(model.SomeProperty), $"Whoops!!!");
        }
    }
}

You can then unit test your DemoViewModelValidator to your hearts content! Hopefully someone finds this useful!


text:
Q: SQL Server : Update Flag on Max Date on Foreign key I'm trying to do this update but for some reason I cannot quite master SQL sub queries.
My table structure is as follows:
 id  fk    date     activeFlg
---  --  -------    ---------
 1   1   04/10/11      0
 2   1   02/05/99      0
 3   2   09/10/11      0
 4   3   11/28/11      0
 5   3   12/25/98      0

Ideally I would like to set the activeFlg to 1 for all of the distinct foreign keys with the most recent date. For instance after running my query id 1,3 and 4 will have an active flag set to one.
The closest thing I came up with was a query returning all of the max dates for each distinct fk:
SELECT MAX(date)
FROM table
GROUP BY fk

But since I cant even come up with the subquery there is no way I can proceed :/
Can somebody please give me some insight on this. I'm trying to really learn more about sub queries so an explanation would be greatly appreciated.
Thank you!

A: You need to select the fk to and then restrict by that, so
SELECT fk,MAX(date)
FROM table
GROUP BY fk

To
With Ones2update AS
(
  SELECT fk,MAX(date)
  FROM table
  GROUP BY fk
)
Update table
  set Active=1
from table t
join Ones2update u ON t.fk = u.fk and t.date = u.date

also I would test first so do this query first
With Ones2update AS
(
  SELECT fk,MAX(date)
  FROM table
  GROUP BY fk
)
selct fk, date, active
from table t
join Ones2update u ON t.fk = u.fk and t.date = u.date

to make sure you are getting what you expect and I did not make any typos.
Additional note:  I use a join instead of a sub-query -- they are logically the same but I always find joins to be clearer (once I got used to using joins).  Depending on the optimizer they can be faster.

A: This is the general idea.  You can flesh out the details.
update t
set activeFlg = 1
from yourTable t
join (
select id, max([date] maxdate
from TheForeignKeyTable
group by [date]
)  sq on t.fk = sq.id and t.[date] = maxdate


text:
Q: VSCode/NestJs case sensitive import highlighting for TS/JS just had a bad case of windows being case insensitive and my ci pipe in the cloud being case sensitive on import FileNames. Initially it seemed to be realted to a different issue (tspaths) so i wasted some time there.
So I wonder if there is a way to configure vs code to auto correct incorrect import casing (couldn'T find a plugint that seems to do that) or if i can integrate that somehow in a nestjs standard build (e.g. for webpack i Know there is CaseSensitivePathsPlugin which does that) but I use the default building tools for nest,js and dont really wanna switch for only that reason


text:
Q: How to convert dockerfile commands to maven xml entries? I am dockerizing my Java applications by maven docker plugin.
I found a simple docker-maven-plugin that creates a simple docker file..
I want to know how to convert docker file command such as ADD,COPY,VOLUME etc. in to maven xml entries ?
I mean I need to be able to customize my dockerfile through maven pom.xml
I could not find any documentations or tutorial for this ...
Thanks for your input.


text:
Q: SQL Server creating wrong table names, why? Question: when I create a table (T_TableName) using SQL Server Management-Studio, it always creates the table as
Domain\UserName.T_TableName

instead of
dbo.T_TableName

What's wrong ?

A: You need to either create your table as "dbo.Whatever", OR you need to change your default schema (or have your SA do it for you) by issuing a command like:
ALTER USER [DOMAINNAME\UserName] WITH DEFAULT_SCHEMA = dbo;

A: Call it dbo.T_TableName in SSMS.  If you have the correct permissions, it will work.

A: If you don't specify a schema explicitly on your table name to be created, it will be created in the user's current default schema.
I bet the user you're using has its own personal schema set as its default schema - that's why your tables get created in his own personal schema.
You can check what database users you have and what their default schema is by inspecting sys.database_principals (SQL Server 2005 and up):
SELECT name, type_desc, default_schema_name
FROM sys.database_principals

To solve this:

*

*specify the schema you want to use explicitly (best practice anyway!)
CREATE TABLE dbo.T_TableName

*change the user's default schema to dbo
ALTER USER [Domain\YourUser] WITH DEFAULT_SCHEMA = dbo

But as a general rule of thumb, I recommend always using the "dbo." prefix explicitly, if you want to have all your database objects in the dbo schema. Helps with performance, too (ever so slightly) since SQL Server won't have to go hunting in different schemas, if you explicitly tell it where your db objects live.

A: Are you assigned as db_owner for the database you created the table in? If not, this could be the issue. Try adding your user mapping permissions to the database as such.
USE [yourDatabase]
GO
EXEC sp_addrolemember N'db_owner', N'DOMAIN\UserOrGroup'
GO


text:
Q: Merge branch into master I have created a branch out of the master branch where I have done different changes. But meanwhile, I have done a few changes to the master branch as well. Every time I try to merge the second branch into the main branch, the changes I have done to the main branch get overwritten by the second branch.
What is the correct way of doing the merge?
Note that I am using Git Extensions.


text:
Q: Counting character frequencies in an array of characters - x86 Assembly I'm trying to count the occurrences of characters in a string.
My code is below:
data segment 'DSEG'
    text        db  "This is a sentence.",0     ; string
    textSize    dw  $ - text - 1                ; size of string, - 1 to account for null-termination character
    freqTable   dd  256 DUP(0)
ends 'DSEG'

code segment 'CSEG'
start:
mov ax, data        ; set segment registers
mov ds, ax
mov es, ax
;---------------------------------------

sub cx, cx
mov cx, textSize        ; number of times to loop
L1:
    mov ax, [OFFSET text + cx - 1]  ; loop from back using cx, put character in ax
    inc [OFFSET freqTable + 4*ax]   ; increment table's index at the ascii value of character
    LOOP L1

;---------------------------------------
mov ax, 4c00h       ; return to OS
int 21h

ends 'CSEG'
end start           ; set entry point

I made an array of DWORDS where each index would represent a character.  I then loop through the string and tried to increment the array at the ascii value of each character.
However, I get a wrong parameters error when I try to increment in the loop.  I'm not sure what is causing this error.  I am guessing I can't just increment the way I'm trying to.  How do I properly create the frequency table?  Am I missing something small?

A: X86 doesn't allow for memory addressing through use of the AX and CX registers as you did. You can however use EAX and ECX for this purpose.
Troughout next code snippet bits EAX[8,31] and ECX[16,31] will remain zero.
;---------------------------------------
 xor  eax, eax
 xor  ecx, ecx
 mov  cx, textSize        ; number of times to loop
L1:
 mov  al, [OFFSET text + ecx - 1]
 inc  [OFFSET freqTable + eax*4]
 loop L1
 ;---------------------------------------

A: To help you understand how to count characters I created next little program with EMU8086 (compatible with your assembly) : the program ask the user for a filename, open the file, read all characters and count them, and close the file.
Next image shows how it works : there is an array of frequencies ("freq_array") with 256 positions. Each position is the counter of the corresponding char, for example, the position 65 is the counter for 'A' (chr(65)).

Everytime one char is read from file, the char itself is used as offset to reach its counter. For example, if the char 48 ('0') is read from file, the number 48 is added to the array offset (offset + 48), and that position is incremented. When the file ends, all its chars have been counted.
Now the code :
.model small
.stack 100h

;-----------------------------------------

.data

freq_array   dw 256 dup(0) ;ARRAY OF FREQUENCIES OF EACH ASCII CHARACTER.

msj          db 13,10,'Enter name of file: $'

filename     db 99        ;MAX NUMBER OF CHARACTERS ALLOWED (98).
             db ?         ;LENGTH (NUMBER OF CHARACTERS ENTERED BY USER).
             db 99 dup(0) ;CHARACTERS ENTERED BY USER. END WITH CHR(13).

filehandler  dw ?         ;FILE HANDLER.

the_char     db ?         ;CHAR READ FROM FILE.

;-----------------------------------------

.code
start:

;INITIALIZE DATA SEGMENT.
  mov  ax, @data
  mov  ds, ax

  call get_source_file        ;GET FILE NAME.
  call count_chars            ;FILL FREQ_ARRAY WITH FREQUENCIES OF CHARS.

;WAIT FOR ANY KEY.
  mov  ah, 7
  int  21h

;FINISH PROGRAM.
  mov  ax, 4c00h
  int  21h

;-----------------------------------------

get_source_file proc
;DISPLAY MESSAGE.
  mov dx, offset msj
  mov ah, 9
  int 21h

;CAPTURE FILENAME FROM KEYBOARD.
  mov ah, 0Ah
  mov dx, offset filename
  int 21h

;CAPTURED STRING ENDS WITH CHR(13), BUT FILES REQUIRE
;THE FILENAME TO END WITH CHR(0), SO LET'S CHANGE IT.
  mov si, offset filename + 1 ;STRING LENGTH.
  mov cl, [ si ]        ;MOVE LENGTH TO CL.
  mov ch, 0             ;CLEAR CH TO USE CX.
  inc cx                ;ONE MORE BYTE TO REACH CHR(13).
  add si, cx            ;NOW SI POINTS TO CHR(13).
  mov al, 0
  mov [ si ], al        ;REPLACE CHR(13) BY 0.

  ret
get_source_file endp

;-----------------------------------------
;READ ALL CHARACTERS FROM FILE INCREASING THE COUNTER OF
;EACH CHARACTER IN THE ARRAY OF FREQUENCIES. EACH CHARACTER
;IS USED AS THE OFFSET OF ITS OWN COUNTER, EXAMPLE: THE
;COUNTER FOR 'A' IS THE POSITION 65 OF FREQ_ARRAY.

count_chars proc
;OPEN FILE.
  mov  ah, 3dh          ;SERVICE TO OPEN FILE.
  mov  al, 0            ;OPEN AS READ ONLY.
  mov  dx, offset filename + 2
  int  21h
  mov  filehandler, ax ;NECESSARY FOR OPERATIONS ON FILE.

;COUNT CHARACTERS.
reading:
;READ ONE CHAR FROM FILE.
  mov  ah, 3fh          ;SERVICE TO READ FROM FILE.
  mov  bx, filehandler
  mov  cx, 1            ;HOW MANY BYTES TO READ.
  mov  dx, offset the_char ;WHERE TO STORE THE READ BYTES.
  int  21h

;CHECK END OF FILE.
  cmp  ax, 0
  je   end_reading      ;IF READ ZERO BYTES, FINISH.

;INCREASE COUNTER. THE CHAR ITSELF IS BEEN USED AS INDEX: THE
;COUNTER FOR CHAR 65 ('A') IS IN THE 65th POSITION OF THE ARRAY.
  mov  si, offset freq_array
  mov  al, the_char     ;USE CHAR AS OFFSET OF ITS OWN COUNTER.
  mov  ah, 0            ;CLEAR AH TO USE AX.
  shl  ax, 1            ;AX * 2, BECAUSE EVERY COUNTER IS 2 BYTES.
  add  si, ax           ;SI POINTS TO COUNTER POSITION.
  inc  [ word ptr si ]  ;INCREMENT COUNTER FOR CURRENT CHAR.
  jmp  reading          ;REPEAT PROCESS.

end_reading:
;CLOSE FILE.
  mov  ah, 3eh          ;SERVICE TO CLOSE FILE.
  mov  bx, filehandler
  int  21h

  ret
count_chars endp

;-----------------------------------------

end start

Hope this help you.
This is 16 bits, because the array is DW. To make it compatible with 32 bits (array DD), change next lines:
freq_array   dd 256 dup(0)

shl  ax, 2             ;AX * 4, BECAUSE EVERY COUNTER IS 4 BYTES.

inc  [ dword ptr si ]  ;INCREMENT COUNTER FOR CURRENT CHAR.


text:
Q: Reposition of UIView with subviews not working when resizing a sibling view with auto layout I have two views that I am trying to resize/reposition with auto layout.

I have set the following constraints:
Red view:

*

*Top space to superview: 0

*Trailing and leading space to superview: 0

*Height equals: 100

Blue view:

*

*Top space to red view: 0

*Trailing and leading space to superview: 0

*Height equals: 100

Both views are subviews of self.view. And the blue view has a UILabel as a subview (not shown in the screenshot).
What I want to do is to change the size of the red view (with animation) and have the blue view follow that size change:
- (IBAction)resizeButtonPressed:(UIButton*)sender
{
    [UIView animateWithDuration:0.25 animations:^{
        if (sender.selected) {
            self.redViewHeightConstraint.constant = 100; // collapse
        }
        else {
            self.redViewHeightConstraint.constant = 200; // expand
        }
        [self.view layoutIfNeeded];
    }];

    sender.selected = !sender.selected;
}

The animation works and the size of the red view changes. However, the blue view never changes position, even though it has a constraint to the bottom of the red view.
I have tried adding [self.blueView layoutIfNeeded] and even both [self.view setNeedsUpdateConstraints] and [self.blueView setNeedsUpdateConstraints], but it made no difference.
The weird thing is that if I remove the label from the blue view everything works as expected. As soon as I add it again the blue view remains static. It makes no difference if the label has any constraints or not.

A: I've also encountered the same problem.
I solved it by saving the frame of the label before the animation block (CGRect frame = self.label.frame;) and in the animation block set the frame of the label again (self.label.frame = frame;)

A: Here is a complete implementation:
@interface ViewController ()

@property(nonatomic, strong) NSLayoutConstraint* redViewHeightConstraint;

@end

@implementation ViewController

-  (void)viewDidLoad
{
    [super viewDidLoad];

    UIView* redView = [[UIView alloc] init];
    UIView* blueView = [[UIView alloc] init];

    redView.translatesAutoresizingMaskIntoConstraints = NO;
    blueView.translatesAutoresizingMaskIntoConstraints = NO;

    redView.backgroundColor = [UIColor redColor];
    blueView.backgroundColor = [UIColor blueColor];

    NSDictionary* views = NSDictionaryOfVariableBindings(redView, blueView);

    [self.view addSubview:redView];
    [self.view addSubview:blueView];

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[redView]|"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:views]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[blueView]|"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:views]];

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:redView
                                                          attribute:NSLayoutAttributeTop
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:self.view
                                                          attribute:NSLayoutAttributeTop
                                                         multiplier:1
                                                           constant:0]];

    self.redViewHeightConstraint = [NSLayoutConstraint constraintWithItem:redView
                                                                attribute:NSLayoutAttributeHeight
                                                                relatedBy:NSLayoutRelationEqual
                                                                   toItem:nil
                                                                attribute:NSLayoutAttributeNotAnAttribute
                                                               multiplier:0
                                                                 constant:100];

    [self.view addConstraint:self.redViewHeightConstraint];

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:blueView
                                                          attribute:NSLayoutAttributeTop
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:redView
                                                          attribute:NSLayoutAttributeBottom
                                                         multiplier:1
                                                           constant:0]];

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:blueView
                                                          attribute:NSLayoutAttributeHeight
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:nil
                                                          attribute:NSLayoutAttributeNotAnAttribute
                                                         multiplier:0
                                                           constant:100]];

    UILabel* label = [[UILabel alloc] init];
    label.text = @"label";
    label.translatesAutoresizingMaskIntoConstraints = NO;
    [blueView addSubview:label];

    [blueView addConstraint:[NSLayoutConstraint constraintWithItem:label
                                                          attribute:NSLayoutAttributeCenterX
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:blueView
                                                          attribute:NSLayoutAttributeCenterX
                                                         multiplier:1
                                                           constant:0]];

    [blueView addConstraint:[NSLayoutConstraint constraintWithItem:label
                                                         attribute:NSLayoutAttributeCenterY
                                                         relatedBy:NSLayoutRelationEqual
                                                            toItem:blueView
                                                         attribute:NSLayoutAttributeCenterY
                                                        multiplier:1
                                                          constant:0]];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self
               action:@selector(resizeButtonPressed:)
     forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"Expand" forState:UIControlStateNormal];
    [button setTitle:@"Collapse" forState:UIControlStateSelected];
    button.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:button];

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:button
                                                          attribute:NSLayoutAttributeTop
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:blueView
                                                          attribute:NSLayoutAttributeBottom
                                                         multiplier:1
                                                           constant:30]];

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:button
                                                          attribute:NSLayoutAttributeCenterX
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:self.view
                                                          attribute:NSLayoutAttributeCenterX
                                                         multiplier:1
                                                           constant:0]];

}

- (IBAction)resizeButtonPressed:(UIButton*)sender
{
    [UIView animateWithDuration:0.25 animations:^{
        if (sender.selected) {
            self.redViewHeightConstraint.constant = 100; // collapse
        }
        else {
            self.redViewHeightConstraint.constant = 200; // expand
        }
        [self.view layoutIfNeeded];
    }];

    sender.selected = !sender.selected;
}

@end


text:
Q: Get Value from Map column with default Currently I use df.withColumn("col", col("mapColumn").getItem("key"))but this gives me null value if the key is not present in the map column. Is there anything equivalent to getOrElse("key", defaultCalue) in Spark/Scala ?
Thanks

A: use when clause.
something like
df.withColumn("col", when(col("mapColumn").getItem("key").isNotNull,col("mapColumn").getItem("key")).otherwise(lit("DEFAULT_VALUE")))

A: Use coalesce, as shown below:
val df = Seq(
  (10, Map(1 -> "a", 2 -> "b")),
  (20, Map(3 -> "c"))
).toDF("idCol", "mapCol")

df.withColumn("mapValOf1", coalesce($"mapCol"(1), lit("unknown"))).show
// +-----+----------------+---------+
// |idCol|          mapCol|mapValOf1|
// +-----+----------------+---------+
// |   10|[1 -> a, 2 -> b]|        a|
// |   20|        [3 -> c]|  unknown|
// +-----+----------------+---------+


text:
Q: How to set variable type on runtime or use generics in member variable? I am reading data from a file, where I am expecting a sequence of data (Array of data).
The data can be of different types...
Array<double>
Array<double[]>
Array<double[,]>
Array<double[,,]>
Array<double[,,,]>
Array<double[,,,,]>
Array<double[,,,,,]>
Array<double[,,,,,,]>
Array<double[,,,,....n]>

Right now, I have used cases for each case and wrote code for maximum 10 dimensions. But I want it to be for n-dimensions.
Is there any other way to write/read data to array without writing nested loops?
Details: (EDIT)
I am reading a binary file, in which two things are specified before the data,
1) Dimensions list
2) Element-Limit
I read these list of integers and build my data type.
For example:
Dimensions = {15,32,128,5}
Element-Limit = {15,32,128,5}
Then I build a 4D- array like this
double[,,,] dataStream = new double[15,32,128,5];

And this dimension and element-limit may be of n-numbers
And one thing more, I am reading a collection of data... this dataStream will go in Array then like this Array<double[,,,]>