text:
Q: Error on Query with $_SESSION Var $sth7 = $pdo7->prepare("SELECT usr FROM tz_members WHERE id = $_SESSION['id'];");

is giving me this error:
syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

How do I fix this?

A: Try:
$sth7 = $pdo7->prepare("SELECT usr FROM tz_members WHERE id = " . $_SESSION['id'] . ";");

Here's a link to the exact same problem with a solution.


text:
Q: Spring - YML array property is null I am vainly trying to read an array of strings from the application.yml.
Both the Environment and the @Value annotation, always return null.
Everything works if I read an item, instead of the entire array.
Here the code:
Sources

Boot Application and Rest Controllers
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@RestController
class WithEnvCtrl {

    @Autowired
    private Environment env;

    @RequestMapping(value = "/with_env", method = { RequestMethod.GET, RequestMethod.POST }, produces = "application/json")
    public String test() {

        System.err.println(env.getProperty("this.is.array[0]"));
        System.err.println(env.getProperty("this.is.array", List.class));
        System.err.println(env.getProperty("this.is.array", String[].class));

        return env.getProperty("this.is.array[0]");
    }
}

@RestController
class WithValueAnnotation {

    @Value("${this.is.array[0]}")
    private String first;

    @Value("${this.is.array}")
    private List<String> list;

    @Value("${this.is.array}")
    private String[] array;

    @RequestMapping(value = "/with_value_annotation", method = { RequestMethod.GET, RequestMethod.POST }, produces = "application/json")
    public String test() {

        System.err.println(first);
        System.err.println(list);
        System.err.println(array);

        return first;
    }
}

application.yml file
this:
  is:
    array:
      - "casa"
      - "pesenna"

Results

The WithEnvCtrl.test method prints:

casa
null
null
null

The WithValueAnnotation.test method correctly sets the variable first with the first element of the array (casa). However, the annotations @Value on the attributes list and array cause the exception:
java.lang.IllegalArgumentException: Could not resolve placeholder 'this.is.array' in string value "${this.is.array}"

Here is an example project: property-array.
Many thanks in advance!

A: Solved by:

*

*using the annotation @ConfigurationProperties;

*declaring an attribute with the same name as the yml property;

*defining the get method for the attribute;

*initializing the attribute or defining the set method.

Here the code:
import java.util.List;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@RestController
@ConfigurationProperties(prefix="this.is")
class WithValueAnnotation {

    private List<String> array;

    public List<String> getArray(){
        return this.array;
    }

    public void setArray(List<String> array){
        this.array = array;
    }

    @RequestMapping(value = "/test_cfg", method = { RequestMethod.GET,
            RequestMethod.POST }, produces = "application/json")
    public String test() {

        System.err.println(array);

        return array.toString();
    }
}

Thanks @Quagaar.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Library install path for boost I would like to install boost in windows 10 using visual studio 2017 with the following directory structure:
boost-1.65.0/
├── include/
│
├── lib/
│   ├── Debug
│   └── Release
└──

From the source directory of boost, I have tried
bootstrap.bat
b2 -j8 toolset=msvc-14.1 address-model=64 link=static --build-type=minimal variant=debug --prefix=C:\install\boost_1.65.0

Is there any option that I could pass to b2 like install-lib=C:\install\boost_1.65.0\lib\Debug. Any help would be much appreciated.
Thanks.


text:
Q: Need suggestion in Regular expression Regular expression:
.?Description(?:(?!;).)*|.?Resolution(?:(?!;).)*|.?Root Fix(?:(?!;).)*

Input String:
" description: this is first line .
this is second line .
this is thrird ;
and this is some random redundant line "

Expected output:
"description: this is first line .
this is second line .
this is thrird ;"

Current output:
"description: this is first line ."

Could anyone alter this expression to consider anything (blank lines/space) to the left of ;.

A: Why not just match everything till ;
[\s\S]*;
Demo
EDIT:
As pointed out in the comment, \S will also include ;, so the better approach is:
[^;]*;
Demo

A: I have corrected the regex:
\bDescription\b|\bResolution\b|\bRoot Fix\b\:.*?\;

https://regex101.com/r/qC9cH4/70


text:
Q: How to redirect to a specific layout page according to user type? I have a login page that currently redirects to a default layout page when a user successfully logs in. However, I have created a different layout page for the different user and what I want to do is to be able to look through my database and check the type of user and when their username and password is correct, response.redirect them to a specific layout page depending on what type of user they are.  I have different views for each user type.
The different user views under shared folder.
public partial class Login : System.Web.UI.Page
{
    SqlCommand cmd = new SqlCommand();
    SqlConnection con = new SqlConnection();
    SqlDataAdapter sda = new SqlDataAdapter();
    DataSet ds = new DataSet();
    protected void Page_Load(object sender, EventArgs e)
    {
        con.ConnectionString = "Data Source=CHRIS\\SQLEXPRESS;Initial Catalog=FPSDD;Integrated Security=True";
        con.Open();
    }

    protected void BtnLogin_Click(object sender, EventArgs e)
    {
        cmd.CommandText = "SELECT PersonType FROM Person where Username='" + txtUsername.Text + "' and Password='" + txtPassword.Text + "' and PersonType='" + userType.SelectedValue + "'";
        cmd.Connection = con;
        sda.SelectCommand = cmd;
        sda.Fill(ds, "Person");
        if (ds.Tables[0].Rows.Count > 0)
        {
            if (userType.SelectedValue == "Student")
            {
                Response.Redirect(Url.Action(""));
            }
            else if (userType.SelectedValue == "Instructor")
            {
                Response.Redirect("");
            }
            else if (userType.SelectedValue == "Counselor")
            {
                Response.Redirect("");
            }
            else if (userType.SelectedValue == "Parent")
            {
                Response.Redirect("");
            }
            else if (userType.SelectedValue == "Principal")
            {
                Response.Redirect("");
            }
            else if (userType.SelectedValue == "Admin")
            {
                Response.Redirect("");
            }
            else
            {
                cmd.CommandText = "SELECT PersonType FROM Person where Username='" + txtUsername.Text + "' and Password='" + txtPassword.Text + "'";
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                sda.Fill(ds, "Person");

                if (ds.Tables[0].Rows.Count > 0)
                {
                    Label1.Text = "Invalid User Type. Please Try Again!";
                }
                else
                {
                    Label1.Text = "Invalid User Type, Username or Password. Please Try Again!";
                }
            }
        }
    }

A: I will expand on MCoder's original answer.
If you utilize:
return RedirectToAction("YourMethodName", "YourControllerName");

You can pass an overload of this Redirect method a parameter.
When your user logs in, return his/her user type.
Pass it into the Redirect like so:
return RedirectToAction("YourMethodName", "YourControllerName", new { paramName = userType });

And in YourController.YourMethod(paramType paramName) have a conditional statement.
if(paramName = x)
{
    return View("CorrectViewName", appropriateViewModel);
}
else ...

If you have more than 2 or 3 user types, you can use Switch/Case instead of If/Else.

A: Assuming this is a MVC web application.
Do not use response.redirect()
instead use
return RedirectToAction("YourMethodName", "YourControllerName");


text:
Q: Google Chrome fails to load XMLHttpRequest response on Connection close I'm implementing a "load more" functionality, using XMLHttpRequest (AJAX).
The webserver will respond to those calls with a Keep-Alive: timeout=5,max=10 and a Connection: keep-alive headers. On the 10 response it sends a Connection: close header, as expected. All browsers (Safari, Opera, Firefox) continue to process the response, except Chrome. It stops with a status code 0 and no response text.
Here is the JavaScript snippet:
function send(method, data) {
    try {
        let this._request = null;
        let created = false;
        if (!(this._request instanceof XMLHttpRequest)) {
            this._request = new XMLHttpRequest();
            this._request.onreadystatechange = (event) => {
                switch (this._request.readyState) {
                    case XMLHttpRequest.OPENED: {
                        // Do something
                    } break;
                    case XMLHttpRequest.LOADING: {
                        // Do something
                    } break;
                    case XMLHttpRequest.DONE: {
                        // Do something
                    } break;
                }
            };
            this._request.addEventListener(
                'error',
                (event) => {
                        // Do something
                }
            );
            this._request.addEventListener(
                'abort',
                (event) => {
                        // Do something
                }
            );
            created = true;
        }
        this._request.open(String(method), this.path);
        this._request.timeout = 200;
        if (created) {
            // Initialization is done here, like setting request headers...
        }
        this._request.send(data);
    } catch (error) {}
}

Any ideas why Chrome is behaving that way?

A: Turns out that in Chrome the timeout is progressive, meaning it's not reset for each request.


text:
Q: Can you reference OSGi dependencies resolved by Tycho by groupId, artifactId and version? In a Tycho build OSGi dependencies are usually specified in the MANIFEST.MF of the respective modules (e.g., Eclipse plugins). As far as I understand, Tycho identifies those dependencies, resolves them and adds them to the maven build model at build time (sorry for the wayback machine link; the Tycho site seems to undergo some changes right at the moment).
Is it possible to reference such a derived dependency in other maven plugins? For example, if I want to copy particular dependencies with maven-dependency-plugin how would I get to know which groupId, artifactId and version I would have to provide?

A: Tycho has its own dependency resolution mechanism which is different from Maven's. Tycho loads dependencies defined in the Manifest from p2 repositories and not from Maven repositories (at least usually*). Maven artifacts and p2 bundles have different meta-data structures so you can't always map them to each other. For example bundles don't have the concept of group/artifact ID.
Regular Maven plugins can only handle regular Maven dependencies. p2 artifacts are not visible to them.
Depending on what you are trying to achieve, you could try to convert p2 bundles to Maven dependencies first, and then process them with Maven plugins. For your specific example this might help, if you don't mind splitting the build into multiple steps: Use dependencies from Eclipse p2 repository in a regular Maven build?
* You can configure Tycho with pomDependencies=consider to include Maven artifacts. Those would be visible to regular Maven plugins, but I would not recommend doing that, it makes building/deploying harder the more complex the build gets


text:
Q: Find closest solution from a given vector for a linear equation in Matlab Let's imagine that on one hand I have an equation like
y = 5x + 3

and on the other hand I have two vectors of the same size - one representing x-values, other representing y-values (just random values, not a function unfortunately, otherwise this would be quite simple - something like a signal). How can I find the closest pair of values x-y from those two vectors, which will fit or almost fit the equation? Graphically saying I am searching for a point where the equation line would intersect the signal's plot.

A: The question I'm answering is: Given a set of points D = {(x1,y1), (x2,y2), ..., (xN,yN)}, find the point in D which is closest to the line y=5x+3.
Solution: A line can be described as all x which satisfy 0=w' x + b where x and w are 2D vectors and b is a scalar. This is a useful representation because the distance of any point y to this line is monotonically related to |w' y + b|.
In your case we can rewrite the equation as
0 = 5x - y + 3
  = [5,-1].[x;y] + 3

so w = [5;-1]; and b = 3.
That motivates us to find the nearest point as follows
% 10 random data points (column vector format)
D = rand(2,10)*10-5;

% line parameters
w = [5;-1];
b = 3;

% get the index of the closest point
d = abs(w'*D + b);
[~,idx] = min(d);

Example plot

Note This method also generalizes trivially to N-dimensional spaces where 0 = w'x + b describes a hyperplane in N-D spaces.

A: Rewrite equation y = 5x + 3 in form
5 * x - y + 3  = 0

or in general:
A * x + B * y + C = 0

then signed distance (multiplied by L=Sqrt(A*A+B*B)) from this line to point (px, py) is
D = A * px + B * py + C

To compare relative distances from given line you can ignore L-scale and just compare absolute value of D for all points (for absolute values divide all equation coefficients by L)
Note also that D changes its sign when points transit into another half of plane relative to line, so you can register signal plot intersection with line by sign change.


text:
Q: Tricky grouping using xslt 1.0 I need to do a bit tricky mapping using xslt 1.0. need to do grouping only  on the date part of the datetime element. However the element contains the both date and time.Also after grouping need to add the hours.
Here is the input:
<Records>
   <Record>
      <empid>1</empid>
      <datetime>10/10/2010 11:11:00 AM</datetime>
      <hours>5</hours>
    </Record>
    <Record>
      <empid>1</empid>
      <datetime>10/10/2010 10:11:00 AM</datetime>
      <hours>5</hours>
    </Record>
    <Record>
      <empid>1</empid>
      <datetime>10/11/2010 11:11:00 AM</datetime>
      <hours>5</hours>
    </Record>
    <Record>
       <empid>2</empid>
       <datetime>10/10/2010 10:11:00 AM</datetime>
       <hours>2</hours>
    </Record>
    <Record>
      <empid>2</empid>
      <datetime>10/10/2010 9:11:00 AM</datetime>
      <hours>5</hours>
     </Record>
  </Records>

Expected output is:
  <Records>
      <Record>
       <empid>1</empid>
      <detail>
         <date>10/10/2010</date>
         <hours>10</hours>
      </detail>
     <detail>
        <date>10/11/2010</date>
        <hours>5</hours>
     </detail>
    </Record>
    <Record>
       <empid>2</empid>
       <detail>
          <date>10/10/2010</date>
          <hours>7</hours>
       </detail>
    </Record>
 </Records>

Appreciate for any help.

A: This transformation:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:key name="kRecById" match="Record" use="empid"/>
 <xsl:key name="kRecByDateId" match="Record"
          use="concat(empid,'+',substring-before(datetime, ' '))"/>

 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

 <xsl:template match=
  "Record[generate-id()=generate-id(key('kRecById', empid)[1])]">
  <Record>
   <xsl:apply-templates select="empid"/>
   <xsl:apply-templates mode="inGroup" select=
    "key('kRecById', empid)
                [generate-id()
                =
                 generate-id(key('kRecByDateId',
                             concat(empid,'+',substring-before(datetime, ' ')))[1])]"/>
  </Record>
 </xsl:template>

 <xsl:template match="Record" mode="inGroup">
   <detail>
     <date><xsl:value-of select="substring-before(datetime, ' ')"/></date>
     <hours><xsl:value-of select=
     "sum(key('kRecByDateId',
              concat(empid,'+',substring-before(datetime, ' '))
              )/hours)"/>
     </hours>
   </detail>
 </xsl:template>
 <xsl:template match="Record"/>
</xsl:stylesheet>

when applied on the provided XML document:
<Records>
    <Record>
        <empid>1</empid>
        <datetime>10/10/2010 11:11:00 AM</datetime>
        <hours>5</hours>
    </Record>
    <Record>
        <empid>1</empid>
        <datetime>10/10/2010 10:11:00 AM</datetime>
        <hours>5</hours>
    </Record>
    <Record>
        <empid>1</empid>
        <datetime>10/11/2010 11:11:00 AM</datetime>
        <hours>5</hours>
    </Record>
    <Record>
        <empid>2</empid>
        <datetime>10/10/2010 10:11:00 AM</datetime>
        <hours>2</hours>
    </Record>
    <Record>
        <empid>2</empid>
        <datetime>10/10/2010 9:11:00 AM</datetime>
        <hours>5</hours>
    </Record>
</Records>

produces the wanted, correct result:
<Records>
   <Record>
      <empid>1</empid>
      <detail>
         <date>10/10/2010</date>
         <hours>10</hours>
      </detail>
      <detail>
         <date>10/11/2010</date>
         <hours>5</hours>
      </detail>
   </Record>
   <Record>
      <empid>2</empid>
      <detail>
         <date>10/10/2010</date>
         <hours>7</hours>
      </detail>
   </Record>
</Records>

Explanation:
Two nested Muenchian grouping s, the inner using a composite key.


text:
Q: Print exception error message to console I am struggling to print an error message to the console when calling the getCurrent() method within my print() method. Also, in my getCurrent() method the compiler says i need to return a double. I don't understand the return double problem, shouldn't the try catch block wrap around the call to getCurrent().
getCurrent method:
    public double getCurrent() throws IllegalStateException{
    //check if element
    try{
        if(isCurrent() == true){
            return data[cursor];
        }else{
            throw new IllegalStateException
            ("No Element");
        }//end check
    }//end try
    catch(IllegalStateException e){
        //print error message to console
        System.out.println(e.getMessage());
    }//end catch
}//end method

isCurrent() method:
    public boolean isCurrent(){
    if(cursor < manyItems){
        return true;
    }else{
    return false;
    }
}//end method

print() method:
    public void print(){
    double answer;
    System.out.println(" Capacity = " + data.length);
    System.out.println(" Length = " + manyItems);
    System.out.println(" Current Element = " + getCurrent());
    System.out.print("Elements: ");
    for(int i = 0; i < manyItems; i++){
        answer = data[i];
        System.out.print(answer + " ");
    }//end loop
    System.out.println(" ");
}//end method

main method (can't be adjusted):
  DoubleArraySeq x = new DoubleArraySeq();
  System.out.println("sequence x is empty");
  x.print();
  System.out.println("Trying to get anything from x causes an exception\n");
  System.out.printf("%5.2f", x.getCurrent());

Correct output:
sequence x is empty
capacity = 10
length = 0
No Element
elements:
Trying to get anything from x causes an exception

A: public double getCurrent() throws IllegalStateException{
    //check if element
    try{
        if(isCurrent() == true){
            return data[cursor];
        }else{
            throw new IllegalStateException("No Element");
        }//end check
    }//end try
    catch(IllegalStateException e){
        //print error message to console
        System.out.println(e.getMessage());
    }//end catch
}//end method

You catch your own throws IllegalStateException. remove your try{}catch(){}
public double getCurrent() throws IllegalStateException{
    //check if element
    if(isCurrent() == true){
        return data[cursor];
    }else{
        throw new IllegalStateException("No Element");
    }//end check
}//end method

the main:
try{

    DoubleArraySeq x = new DoubleArraySeq();
    System.out.println("sequence x is empty");
    x.print();
    System.out.println("Trying to get anything from x causes an exception\n");
    System.out.printf("%5.2f", x.getCurrent());
}catch(IllegalStateException e){
    System.err.println("This exception produce because there is no element");
}


text:
Q: How can I update ogr2ogr to include the PostgreSQL driver? I'm trying to use ogr2ogr to upload a shapefile to a remote PostGres installation. When I ran this command:
celenius:~ celenius$ ogr2ogr -f PostgreSQL PG:"host=255.34.00.00 user=postgres dbname=mydb password=***" Dropbox/data/roads.shp;

I got the following error message:
Unable to find driver `PostgreSQL'.
The following drivers are available:
  -> `ESRI Shapefile'
  -> `MapInfo File'
  -> `UK .NTF'
 ...
  -> `SVG'
  -> `CouchDB'
  -> `Idrisi'
  -> `ARCGEN'
  -> `SEGUKOOA'
  -> `SEGY'

(I omitted some of the drivers as they are not relevant). Is there a way that I can update ogr2ogr to include PostgreSQL? I'm using a Mac with OS 10.7.4

A: Save yourself some pain and use the Kyngchaos packaged binaries/frameworks for OSX.GDAL-Complete is the one you are looking for.
Another option is to use HomeBrew.

A: assuming you've compiled gdal from source, just include --with-pg=/path/to/pg_config when you're configuring gdal.
./configure -with-pg=/path/to/pg_config ...

./make clean

./make

./make install

EDIT: Note that pg_config should be in the same directory with your other PostgreSQL binaries, like psql, etc..  Also note, this detail from user259060's answer below: you should verify that an appropriate postgresql-server-dev version is installed (e.g. on Ubuntu use apt list --installed | grep postgresql-server-dev if not found use apt-cache search postgresql-server-dev and install the corresponding package with sudo apt-get install postgresql-server-dev).

A: I got this same message while on Windows.
It was complaining about the type of quotes (single vs. double) I was using around the connection string. Switching the quotes fixed the issue.

A: Using Homebrew you should:

brew install gdal --with-postgresql

or with older versions of gdal:

brew install gdal --with-postgres

if you have already installed gdal with brew before but without postgresql support, just

brew uninstall gdal

A: There is a possibility that you might see something like "PostgreSQL support: no", even though you have configured the source using "--with-pg=/path/to/pg_config"...in that case, run sudo apt-get install postgresql-server-dev-all and then retry.

A: From reading the ogr2ogr Vector formats doc, it looks like you need to install the PostgreSQL client library (libpq).
This similar question seems to give some insight into resolving a similar issue, just with Python bindings.

A: On Ubuntu 18.04 (and possibly other versions), a Postgres wrapper for OGR is available from the package postgresql-11-ogr-fdw. This is for version 11 of Postgres, as it needs to match the version of the client.
For the list the different versions of this package, for the different versions of Postgres use the following:
aptitude search postgres | grep ogr-fdw


text:
Q: EF Core Data Context injection across Projects I have project A which is a class library and project B that uses A. Project A is meant to be a generic helper library that can be used across projects (such as B).
The EF Core datacontext and the data entities need to be defined in project B (as they can vary by project) but I need to inject the datacontext in to constructors of service classes in Project A (which handle everything in a generic way).
In Project B I have the datacontext
public class MyDataContext : DbContext
    {
        public MyDataContext(DbContextOptions<MyDataContext> options): base(options)
        {
        }

        public DbSet<Test> Tests { get; set; }

    }

In project A I have class UnitOfWork that implements IUnitOfWork. In it's constructor I need to inject the datacontext. However since project A cannot reference project B (project A is meant to be generic), I cannot use the actual name of the datacontext in the parameter list. Since the datacontext inherits from DbContext, I tried
public UnitOfWork(DbContext dc){...}

In the startup of Project B, I have
services.AddDbContext<MyDataContext>(options =>
     {
          options.UseSqlServer("...<the connection string> ...");
     });
services.AddScoped<IUnitOfWork, UnitOfWork>();

Everything compiles but in runtime when the UnitOfWork needs to be created, I get the error
System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: IUnitOfWork Lifetime: Scoped ImplementationType: UnitOfWork': Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContext' while attempting to activate 'UnitOfWork'.)

The Inner Exception is
InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContext' while attempting to activate 'UnitOfWork'.

Any help is deeply appreciated.
EDIT
I was asked for the UnitOfWork class details in the comments. So here it is
public class UnitOfWork : IUnitOfWork
    {
        private readonly DbContext dc;
        private readonly IServiceProvider serviceProvider;

        public UnitOfWork(DbContext dc, IServiceProvider serviceProvider)
        {
            this.dc = dc;
            this.serviceProvider = serviceProvider;
        }
        public void BeginTransaction()
        {
            dc.Database.BeginTransaction();
        }

        public void BeginTransaction(IsolationLevel isolationLevel)
        {
            dc.Database.BeginTransaction(isolationLevel);
        }

        public void CommitTransaction()
        {
            dc.Database.CommitTransaction();
        }

        public void RollbackTransaction()
        {
            dc.Database.RollbackTransaction();
        }

        public bool IsTransactionActive()
        {
            return dc.Database.CurrentTransaction != null;
        }

        public async Task<bool> SaveAsync()
        {
            return await dc.SaveChangesAsync() > 0;
        }

        public bool Save()
        {
            return dc.SaveChanges() > 0;
        }

    }

A: Your UnitOfWork service depends on a DbContext type, not the derived MyDataContext type which is registered into DI.
So you have two options:
You can modify the UnitOfWork registration like this (tell the IoC container to instantiate UnitOfWork with MyDataContext):
services.AddScoped<IUnitOfWork>(srp => new UnitOfWork(srp.GetRequiredService<MyDataContext>(), srp));

Or you can register DbContext into DI as well, so the DI container knows that when someone asks for a DbContext it should return MyDbContext:
services.AddScoped<DbContext, MyDataContext>();

Note that the ServiceProvider field seems to be unused in your UnitOfWork class.

A: The solution was to make two changes. First was to explicitly register the service as suggested by @fbede
services.AddScoped<DbContext, MyDataContext>();

Now when we do this, we lose the convenience of setting the DbContextOptionsBuilder options via the AddDbContext Extension method.
So we need to override the OnConfiguring method in the datacontext to set the configurations options we need. For example:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(configuration.GetConnectionString(<key>));
    }

Of course, IConfiguration is injected in the MyDataContext constructor


text:
Q: Show that exists $x \in [a,b]$ such that $\int_a^x f(t)dt = \int_x^b f(t)dt$ Suppose that $f$ is an admissible function (bounded and with the set of discontinuity with volume zero) in $[a,b]$. Show that exists a number $x \in [a,b]$ such that
$$ \int_a^x f(t)dt = \int_x^b f(t)dt$$
My attempt:
My guess is that I must use the fundamental theorem of calculus. If such $x$ exists, it must satify
$$ F(x) = \frac{F(b) + F(a)}{2}$$
for $F' = f$
But I couldn't find such $x$. Any sugestion?
Thanks in advance!

A: Let $$G(x) = \int_a^xf(x)dx$$ so $G(x)$ varies from $0$ to $\int_a^bf(x)dx$. Intermediate value theorem says that for some intermediste $x$, $G(x)$ will attain the middle value.

A: If you want to use intermediate value theorem(IVT), define
$$G(x) = \int_a^x f(u) du - \int_x^b f(u) du$$
Observe that $G(a) = -G(b)$. Thus either they are both zero in which case you are done, or if $G(b) = \alpha > 0$, then $G(a) = -\alpha < 0$ and so by IVT, there exists $x$ such that $G(x)=0$.
This doesn't require fundamental theorem of calculus.


text:
Q: UiPath: get content of text file linked from web page I am using UiPath Community Edition.
There is a link in a web page, that brings to a text file (.txt). If I click on the link, it opens in a new tab. This is the HTML code:
<a name="URL$2" id="URL$2" ptlinktgt="pt_new" tabindex="43"
    onfocus="doFocus_win0(this,false,true);" href="https://www.test/report123.txt"
    onclick="window.open('https://www.test/report123.txt','',''); return false;"
    class="HYPERLINK">
report123.txt
</a>

I would like to read the content of the text file into a variable.
How should I do that?

A: Have you tried Web Recorder and then Output or Screen Scraping Methods?


text:
Q: Meta Query for specific months I have a custom field which stores a date in a timestamp. I want to run a query that display posts based on the month, for example all entries from March, the specific day or year doesn't matter. I'm guessing i need to use the DATE or the DATETIME type for the meta query, but i don't know how to proceed:
if ($_GET['month']) {
    $meta_query[] = array(
            'key' => 'event_start_date',
            'value' => $_GET['month']
    );
}

$args = array(
    'post_type' => 'event',
    'paged' => $paged,
    'posts_per_page' => -1,
    'tax_query' => $cleanArray,
    'meta_key' => 'event_start_date',
    'orderby' => 'meta_value_num',
    'order' => 'DESC',
    'meta_query'=> $meta_query
);

$events = new WP_Query($args);

A: You need the 2 digit month number that you want to query on and then use the code below. This should be easy with php (for example, see this post). In the code below $month is the number of the month in a 2 digit format, eg March would be 03.
$start_date = date('Y'.$month.'01'); // First day of the month
$end_date = date('Y'.$month.'t'); // 't' gets the last day of the month

$meta_query = array(
    'key'       => 'event_start_date',
    'value'     => array($start_date, $end_date),
    'compare'   => 'BETWEEN',
    'type'      => 'DATE'
);

A: For Date Time just add eg. 00:00:00 - 23:00:00
$month      = $_GET['month'];
$start_date = date( 'Y-' . $month . '-01 00:00:00' );
$end_date   = date( 'Y-' . $month . '-t 23:00:00', strtotime( $start_date ) );

$meta_query = array(
    'key'       => 'event_start_date',
    'value'     => array($start_date, $end_date),
    'compare'   => 'BETWEEN',
    'type'      => 'DATETIME'
);

A: WordPress 3.7 introduced the date_query to display posts by month:
$args = array(
    'date_query' => array(
        array(
            'month' => $month
        )
    )
);
$query = new WP_Query( $args );


text:
Q: Why does Si donate its own electron to Al in a p-type semi conductor losing its own stability? Things I have known or been taught before asking this question:

*

*Every electron does not absorb same amount of energy from the environment. So there are some electrons in a semiconductor which can absorb enough energy to leave their orbital and roam freely. They shift from valence band to conduction band.

*Free electrons usually do not fill up the holes of a p-type semiconductor

*Few bonding electrons of Si-Si leave their bonding electron to fill the holes generated due to doping. And this results in movement of holes throughout the material. It is comparable to resonance in a cation having $\sigma$-$\pi$-$(+)$ successive arrangement.
I have asked the following question based on these ideas which are perhaps wrong
Let's say we are talking about silicon semiconductor doped with aluminium or boron. All these are p-block elements and as far as I know they have been observed to be stable when their octets are filled. When Al or B is doped we all know that they will form covalent bonds (3 covalent bonds) with Si. As far as I know due to polarization Al forms covalent bond.
Now, since their octets aren't filled, they will tend to find a electron to form another covalent bond with Si. But why would adjacent Si donate one of its electron to Al? I mean aren't those Si's losing their stability too? Why would one atom lose its own stability to provide another atom stability? Is it the thermal energy gained from the surroundings which lets electrons to leave its location and move to another location (orbital), just as we see during the formation of atomic spectra?
I know all these things don't work that way as I have mentioned, there are a bunch of extremely sophisticated phenomena taking place during those moments. I don't want to dig that far (at least for now), but the least thing I can do is avoid wrong ideas, which is basically why I am asking this question.

A: There are quite a few assumptions/claims in your question which are a bit confusing. Some of them, I don't really understand what you meant, and I think they might point out some underlying confusions (which is fine). For example:

As far as I know due to polarization Al forms covalent bond

What do you mean by polarization, what do you think is polarized, and how do you think it relates to covalent bonding?.

Is it the thermal energy gained from the surroundings which lets electrons to leave its location and move to another location(orbital) just as we see during the formation of atomic spectra

I don't understand the parallel that you are trying to establish between the atomic spectra and this situation. I also don't understand the link that you seem to imply between thermal energy and the "formation" of atomic spectra. You could observe atomic spectra at 0K

Apart from this, I think your main question is:

But why would adjacent Si donate one of its electron to Al?

I think there is another misunderstanding implied in the formulation. Covalent bonds are not about donating electrons (that would be closer to ionic bonding). To keep it simple, it's more about "sharing" them. You can check the wiki page for covalent bonding to learn more about it, it is an important distinction. Basically, two atoms forming a covalent bond will put an electron pair "in common", so that they each have "one more valence electron". So in your case Si, is not "losing" an electron; both Si and Al are "gaining" one.

As to the reason why Si is more than happy to share with his buddies, it is quite straight-forward to explain in simple terms. You already know about the octet rule. Well, silicon has four valence electrons. So it also wants to bond with 4 neighbours to obtain 8 electrons. Atoms are not particularly racist, so Si doesn't care if it shares with another Si or an Al, as long as it gets its electron to satisfy its valence.

You'll note that this answer does not address how that leads to doping and formation of free electrons or holes because your question has nothing that specifically relates to it (your doubts are "one step before" that). But you are welcome to ask questions about it later if you need.


text:
Q: VBA add-in subscription list for App level events I am creating an excel Add-In (.xlam) that needs to selectively respond to workbook/worksheet events, in all open workbooks (user may have multiple workbooks open). I dont want to go down the road of pasting code into other open workbook's ThisWorkbook modules.
I would like the user to be able to select whether the Add-In will respond to the active workbook's events.
What would be the most appropriate solution to achieve this?
Currently, I am thinking of a solution that looks like this:
Enable the Add-In to listen to application level events via a cls_AppEvents class (cls_AppEvents is instantiated on Workbook_open()).
When user clicks button, add the ActiveWorkbook.Name to an array of stings. When user clicks button again, remove the 'ActiveWorkbook.Name` from the array.(This would need to be a dynamic array - is there a better option?)
When application-level TableUpdate (for example) event fires, check the array of workbook names to see if it contains the Workbook's name where the event originated. If so, call whatever function.


text:
Q: Interpreting some domain issues of (potential) momentum operators In the context of mathematical quantum mechanics, a well known no-go theorem known as Hellinger-Töplitz tells us that an unbounded, symmetric operator cannot be defined everywhere on the Hilbert space $\mathcal H$. Thus, for many operators of interest in quantum mechanics, we must resort to restricting the domain on which they may act. Along with the Hamiltonian, the momentum operator
$$ p:=-i\frac{\rm d}{\mathrm{d}x}$$
is the most prominent example of such an operator. Now, one of the most important questions is clearly: What is the correct domain of definition for the momentum operator?
In order to answer this question, it is of crucial importance to consider the question of self-adjointness: Only self-adjoint operators are admissible as observables of the theory, and there are certain vital mathematical results, such as the spectral theorem and Stone's theorem, which make it clear that any 'good' momentum operator must certainly be self-adjoint: $ p^\star= p$. So, the original question is refined slightly: What is the correct domain $\mathcal D( p)\subset \mathcal H$ that allows us to construct a self-adjoint momentum operator?
Recently, one of my lecturers treated a concrete incarnation of this (general and possibly vague) question: Consider a Hilbert space $\mathcal H=L^2(0,1)$ and two 'candidate momenta', $ p_0$ and $ p_\alpha$, with domains
$$\mathcal D(p_0)=\{\psi\in \mathcal H \,|\, \psi\in \text{AC}(0,1),\psi'\in\mathcal H, \psi(0)=0=\psi(1)\} $$
$$ \mathcal D(p_\alpha)=\{\psi\in \mathcal H \,|\, \psi\in \text{AC}(0,1),\psi'\in\mathcal H, \psi(0)=\alpha\psi(1)\},\hspace{.5cm}|\alpha|=1 $$
Are these operators self-adjoint? As it turns out, it can be shown that $p_0$ is symmetric but not self-adjoint. However, $p_\alpha$ is self-adjoint. It seems that the domain of $p_0$ is 'too small'.
Now, my question is: What does the conclusion that $p_0\neq p_0^\star$ imply for the canonical freshman QM example of the infinite potential well? As far as I'm aware, it is conventional to take exactly the boundary conditions that we assume to define the domain of $p_0$ when solving the Schrödinger equation in this case. Can we conclude that the notion of momentum cannot be rigorously defined in this elementary example? Or, at the very least, do we have to admit some $\psi$ that obey non-physical boundary conditions?

For those interested, this is a related question, also touching upon domain issues of momentum operators.

A: Although we can define the momentum as a self-adjoint operator in $L^2[0,1]$ as you proposed, I think it's rather artificial to think about it as having relation to momentum in the case of $L^2(\Bbb{R})$. Realize that the operator $p_1$ with domain
$D(p_1)=\{\psi\in\mathcal{H}^1[0,1]\,|\,\psi(1)=\psi(0)\}$, is related to spatial translations via the unitary group $U(t)=\exp(-itp_1)$, whose action is
$$(U(t)\psi)(x)=\psi[x-t\pmod{1}],$$
so it's about a particle in a torus, not in an infinite square-well. Different values of $\alpha$, just give different phases to the wavefunction when it reaches the border and goes to the other side.
So, in my opinion, these operators are not actually related to the momentum as usually conceived. The idea of an infinite square-well does not allow spatial translations, so there's no self adjoint operator associated to a unitary translation group in this case. This happens for example in the case of a particle in the postive real line $\Bbb{R}_+$. In this case, the space $L^2[0,\infty)$ allows only translations to the right, not to the left, so you can not have a self-adjoint operator associated to a unitary group of translations. In this case, the operator $p=-i\dfrac{d}{dx}$ has no self-adjoint extensions, for any initial domain, although it is symmetric. For a particle in a box, we can think in the same way. There's no operator associated to spatial translations, because there is no spatial translations allowed.
It's also important to note that the hamiltonian $H$ in this case is given by the Friedrich  extension of $$p_0^2=-\frac{d^2}{dx^2}\\
\mathcal{D}(p_0^2)=\{\psi\in\mathcal{H}^2[0,1]\,|\,\psi(0)=\psi'(0)=0=\psi'(1)=\psi(1)\}$$
$H$ cannot be the square of any $p_\alpha$, since the domains do not match.
Edit: As pointed out by @jjcale, one way to take the momentum in this case should be $p=\sqrt{H}$, but clearly, the action of $p$ can't be a derivative, because it has the same eigenfunctions of $H$, which are of the form $\psi_k(x)=\sin \pi kx$. This ilustrates the fact that it's not related to spatial translations as stated above.
Edit 2: There's is a proof that the Friedrich extension is the one with Dirichilet boundary conditions in Simon's Vol. II, section X.3.
The domains defined by the spectral theorem are indeed $\{\psi: p_\alpha\psi\in\mathcal{D}(p_\alpha)\}$. To see this, realize that in this case, since the spectrum is purely point, by the spectral theorem, we have
$$p_\alpha=\sum_{n\in \Bbb{Z}}\lambda_{\alpha,n}P_n,$$
where $\lambda_{\alpha,n}$ are the eigenvalues associated to the normalized eigenvectors $\psi_{\alpha,n}$, and $P_n=\psi_n\langle\psi_n,\cdot\rangle$ are the projections in each eigenspace. The domain $\mathcal{D}(p_\alpha)$ is then given by the vectors $\xi$, such that
$$\sum_{n\in \Bbb{Z}}|\lambda_{\alpha,n}|^2\|P_n\xi\|^2=\sum_{n\in \Bbb{Z}}|\lambda_{\alpha,n}|^2|\langle\psi_n,\xi\rangle|^2<+\infty$$
Also, $\xi\in\mathcal{D}(p_\alpha^2)$ iff
$$\sum_{n\in \Bbb{Z}}|\lambda_{\alpha,n}|^4\|P_n\xi\|^2=\sum_{n\in \Bbb{Z}}|\lambda_{\alpha,n}|^4|\langle\psi_n,\xi\rangle|^2<+\infty$$
But then, $p_\alpha\xi$ is such
$$\sum_{n\in \Bbb{Z}}|\lambda_{\alpha,n}|^2\|P_np_\alpha\xi\|^2=\sum_{n\in \Bbb{Z}}|\lambda_{\alpha,n}|^2|\langle\psi_n,p_\alpha\xi\rangle|^2=
\sum_{n\in \Bbb{Z}}|\lambda_{\alpha,n}|^2|\langle p_\alpha\psi_n,\xi\rangle|^2=
\sum_{n\in \Bbb{Z}}|\lambda_{\alpha,n}|^4|\langle\psi_n,\xi\rangle|^2<+\infty$$
So, $\mathcal{D}(p_\alpha^2)= \{\psi: p_\alpha\psi\in\mathcal{D}(p_\alpha)\}$.

A: The fact that $D(p_0)$ is not big enough to define a self-adjoint operator does not mean it is not included into the domain of the self-adjoint momentum. The choice of boundary conditions for the function is a specification of the vector, not of the operator.
Once you have fixed the self-adjoint extension you are considering (choosing the proper domain, usually of essential self-adjointness), you can take any state in the domain to apply the operator $p$. Obviously, to study the Schrödinger equation you need a vector in the domain of the Hamiltonian, not of the momentum  (and there are vectors in $D(p_0)$, or also $D(p_\alpha)$, that does not belong to the domain of the Hamiltonian ;-) )
The problem, in general, is that the closure of an operator is taken in the graph topology, and that is not very explicit, so you have to be careful and be sure to end in the right closure, that have not to be too small to be equal to the domain of the adjoint.


text:
Q: C++ stod function equivalent A friend of mine sent me his program. He uses "stod" function to convert string to double. Is there any other possibility to do such thing?
My complier shows error "stod was not declared in this scope"
I've included #include <string> #include <cstdlib> but nothing has changed.
My complier doesn't use C++11 features. By the way, that program were prepared as a school project, without purpose of using C++11.

A: std::atof() is a quick option handed over from C language, you have to include <cstdlib> to use it.
Otherwise  you can use std::stringstream to handle it.
    #include<sstream>

    std::string value="14.5";
    std::stringstream ss;
    ss<< value;

    double d=0.0;
    ss>>d;

A: A quick and dirty way to convert a string to a double would be
#include <sstream>
#include <string>

std::string text;
double value;
std::stringstream ss;
ss << text;
ss >> value;

But be aware of the error check needed to validate correct conversion
EDIT: You will need to test the stringstream for failure with
if (ss.fail()) { /* error */ }

Source http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/


text:
Q: BigQuery SQL - Create New Column Based on the Max Value from Multiple Columns I have a table contains info about customers and their purchases amount of each type of food. I want to create new columns that is the most freq type of food they have purchased. Is there an efficient way to do this?
I tried using case when and do one-to-one comparison, but it got very tedious.
Sample data:

Cust_ID
apple_type1
apple_type2
apple_type3
apple_type4
apple_type5
apple_type6

1
2
0
0
3
6
1

2
0
0
0
1
0
1

3
4
2
1
1
0
1

4
5
5
5
0
0
0

5
0
0
0
0
0
0

--WANT

Cust_ID
freq_apple_type_buy

1
type5

2
type4 and type6

3
type1

4
type1 and type2 and type3

5
unknown

A: Consider below approach
select Cust_ID, if(count(1) = any_value(all_count), 'unknown', string_agg(type, ' and ')) freq_apple_type_buy
from (
  select *, count(1) over(partition by Cust_ID) all_count
  from (
    select Cust_ID, replace(arr[offset(0)], 'apple_', '') type,cast(arr[offset(1)] as int64) value
    from data t,
    unnest(split(translate(to_json_string((select as struct * except(Cust_ID) from unnest([t]))), '{}"', ''))) kv,
    unnest([struct(split(kv, ':') as arr)])
  )
  where true qualify 1 = rank() over(partition by Cust_ID order by value desc)
)
group by Cust_ID

if applied to sample data in your question - output is

A: This uses UNPIVOT to turn your columns in to rows.  Then uses RANK() to assign each row a rank, which means if multiple rows are matched in quantity, they share the same rank.
It then selects only the products with rank=1 (possibly multiple rows, if multiple products are tied for first place)
WITH
  normalised_and_ranked AS
(
  SELECT
    cust_id,
    product,
    qty,
    RANK() OVER (PARTITION BY cust_id ORDER BY qty DESC) AS product_rank,
    ROW_NUMBER() OVER (PARTITION BY cust_id ORDER BY qty DESC) AS product_row
  FROM
     yourData
  UNPIVOT(
    qty FOR product IN (apple_type1, apple_type2, apple_type3, apple_type4, apple_type5, apple_type6)
  )
)
SELECT
  cust_id,
  CASE WHEN qty = 0 THEN NULL ELSE product END   AS product,
  CASE WHEN qty = 0 THEN NULL ELSE qty END   AS qty
FROM
  normalised_and_ranked
WHERE
  (product_rank = 1 AND qty > 0)
  OR
  (product_row = 1)

Edit: fudge added to ensure row of nulls returned if all qty are 0.
(Normally I'd just not return a row for such customers.)


text:
Q: Android Output Frame Coordinates In the Google Tango doc for the TangoSupport_fitPlaneModelNearPoint function the intersection_point value is given as a Vec3 in "Output Frame Coordinates"
When debugging this I find that the positive Z coordinate is always the distance away from the camera
I am assuming the right-hand rule so anyone have a source to confirm that this is what is meant for "Output Frame Coordinates"?

A: The resulting plane equation will be in the same reference frame that you pass the parameters in with.  That is the output coordinate space being referred to here.
So if you use StartOfService for your reference frame, then pass in base=StartOfService, target=DepthCamera for the point cloud position and base=StartOfService, target=ColorCamera or Device, depending on which one you are using for positioning the 3D camera.

A: Check the unit, the Tango device is output in "meter" and some of system unit is in "mm"


text:
Q: How can i add a logo in my PDF Output (R Shiny)? I have this minimal R Shiny example, and i want to add a logo in the top of the page.
Is there any possibility ?
Thanks !
library(shiny)
shinyApp(
  ui = fluidPage(DT::dataTableOutput('tbl')),
  server = function(input, output) {
    output$tbl = DT::renderDataTable(server = FALSE,
      iris,extensions="Buttons",options = list(dom = 'Bfrtip',initComplete = JS(
        "function(settings, json) {",
        "$(this.api().table().header()).css({'color': '#fff','background':'#dd4b39'});",
        "}"),
        buttons = list(
          list(extend = "pdf",title = "My DataTable")
        )
    ))
  }
)

A: library(shiny)
library(DT)
library(base64enc)

ui <- fluidPage(
  tags$head(
    tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"),
    tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js")
  ),
  br(),
  DTOutput("dtable")
)

server <- function(input, output, session){

  output[["dtable"]] <- renderDT({
    datatable(
      iris[1:5,],
      extensions = "Buttons",
      options = list(
        dom = "Bfrtip",
        buttons = list(
          list(
            extend = "pdfHtml5",
            customize = JS(
              "function(doc) {",
              "  doc.content.splice( 1, 0, {",
              "    margin: [ 0, 0, 0, 12 ],",
              "    alignment: 'center',",
              sprintf(
                "    image: '%s',",
                dataURI(
                  file = "https://www.r-project.org/logo/Rlogo.png",
                  mime = "image/png"
                )
              ),
              "    width: 50",
              "  })",
              "}"
            )
          )
        )
      )
    )
  })

}

shinyApp(ui, server)


text:
Q: Displaying a GeoServer Map from a Java Mobile Application How can I display a Map generated by GeoServer from a Java Mobile Application?
I would like to display it inside a Java App instead of a android application. Is this possible?

A: All you need to do is create a correct URL in your app and use Java to open the URL and fetch the contents as an image. The display the image as usual.
To determine what URL you need you should read the WMS specification, or if you are in a hurry crib one from the GeoServer examples page or any other web map you can find.

A: Geoserver is a Server based application that generates maps by sending tiles to a Client Application.
The two most Common Client Applications are Openlayers and Leaflet which rely on JavaScript to handle the presentation of the tiles to the end user on the Client.
JavaSE has the ScriptEngineManager (javax.script package) which can execute JavaScript, and the documentation on that can be see Here!
A simple example of its usage is as follows:
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
engine.eval("print('Hello, GIS World')");

You would need to ensure your mobile application in Java could support this engine, then implement either OpenLayers or Leaflet to handle the map display.

Caveats:

*

*OpenLayers and Leaflet assume you have a Browser available to display the maps

*I have not done this, I am not aware of anyone else who has

*I am not aware of any other solution

*This will be a LOT of work and effort to get working

Alternatively, if your Java Application on the phone used a Browser you could simply implement Openlayers or Leaflet as a normal implementation, provided that the browser met the minimum requirements.


text:
Q: jQuery mobile and href links inside a table not working I'm working with jQuery mobile and populating a table by using ajax, one of the fields is a href that I'm assigning a class to, to present an alert in the screen, and it does not fire anything:
I have tried by using the double quotes and single quotes without success:
Double quotes:
$("#table1").append("
" + element.field1 + "	" + element.field2 + "	" + element.field3 + "
");

Single quotes:
$("#table1").append('
' + element.field1 + '	' + element.field2 + '	' + element.field3 + '
');

jQuery method:
$(".linkTest").click(function(){
    alert("It works");
});

The table is populated correctly but the alert is not showing up when clicked. If I add a button outside the table, it works:
 TEST

I would appreciate your help, thanks!

A: $(".linkTest").click() won't apply to any dynamically created elements added subsequently. Either do $(".linkTest").click() after the dynamic content is added or bind the event to a containing element e.g. $('body').on('click', '.linkTest', function() { });

A: Because your link is dynamically added to DOM, so click event will not work.

This is exactly what you looking for event Delegation and
  also have to prevent default function of hyperlink

Consider following snippet:
$("#table1").on('click','.linkTest', function(e){
    e.preventDefault();//for prevent default redirect
    alert("It works");
});


text:
Q: Google Maps API Convert points (stars) to circles with a radius of 1000 feet I'm trying to convert the stars in the below example to circles that have a radius of 1000 feet. Can anyone assist?
Similar to this: https://developers.google.com/maps/documentation/javascript/examples/circle-simple
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Google Maps API</title>

A: 1000ft are 304.8 meters, draw a google.maps.Circle with this radius and use the given position as center.
To open the infowindow set the position & map-properties (instead of calling the open-method)
function createMarker(place) {
  var circle = new google.maps.Circle({
    map: map,
    center: place.geometry.location,
    radius:304.8
  });

  google.maps.event.addListener(circle, 'click', function() {
    service.getDetails(place, function(result, status) {
      if (status != google.maps.places.PlacesServiceStatus.OK) {
        alert(status);
        return;
      }
      infoWindow.setOptions({
                             content:result.name,
                             map:circle.getMap(),
                             position:circle.getCenter()
                            });

    });
  });
}


text:
Q: Extract query name and it's fields from a GraphQL query in java I'm basically trying to instrument GraphQL queries to identify what queries and fields the user is hitting the most. For this I want to extract the query name and it's respective fields whenever the point
graphQL.execute(query) hits in my code.
I've seen some posts that were using/suggesting to use Apollo server but I do not use Apollo. For example in this query
query getMultipleResults {
  personSearch(text: "xyz") {
   totalCount
   results {
     name
     dob
     SSN
   }
  }
 }

I would like to get the query name: personSearch and the fields to be: totalCount, results and its fields name, dob and SSN.

A: While creating the graphql schema, you can define the instrumentation type.
While every graphql execution, get the execution result which has the tracing information in details about fields ,time and resolver.
for more information please refer my GitHub account : AnkushNakaskar with project "springbootspqrgraphql"
For tracing : please add "TracingInstrumentation" for tracing.


text:
Q: Failed to access mail object MAPI from calling function I'm going to access Outlook MAPI folder and get mail address.Here is my method
 public static string GetSenderEmailAddress(Microsoft.Office.Interop.Outlook.MailItem mapiObject)
    {
        Microsoft.Office.Interop.Outlook.PropertyAccessor oPA;
        string propName = "http://schemas.microsoft.com/mapi/proptag/0x0065001F";
        oPA = mapiObject.PropertyAccessor;
        string email = oPA.GetProperty(propName).ToString();
        return email;
    }

When button click event called,i need to fire that method and retrieve mail address.
Button click event is here.
      private void button3_Click(object sender, RibbonControlEventArgs e)
        {

 string mailadd =  ThisAddIn.GetSenderEmailAddress(Microsoft.Office.Interop.Outlook.MailItem);
        System.Windows.Forms.MessageBox.Show(mailadd);

}

Error goes here

Microsoft.Office.Interop.Outlook.MailItem is a 'type'which is not valid in the given context

This is my first addin,Does anyone know how to achieve this result?

A: You can use the RibbonControlEventArgs to access the Context which will provide you the MailItem instance.
private Outlook.MailItem GetMailItem(RibbonControlEventArgs e)
{
    // Inspector Window
    if (e.Control.Context is Outlook.Inspector)
    {
        Outlook.Inspector inspector = e.Control.Context as Outlook.Inspector;
        if (inspector == null) return null;
        if (inspector.CurrentItem is Outlook.MailItem)
            return inspector.CurrentItem as Outlook.MailItem;
    }
    // Explorer Window
    if (e.Control.Context is Outlook.Explorer)
    {
        Outlook.Explorer explorer = e.Control.Context as Outlook.Explorer;
        if (explorer == null) return null;
        Outlook.Selection selectedItems = explorer.Selection;
        if (selectedItems.Count != 1)  return null;
        if (selectedItems[1] is Outlook.MailItem)
            return selectedItems[1] as Outlook.MailItem;
    }
    return null;
}

You can add this method and then make use of it like so...
string mailAddress = string.Empty;
Outlook.MailItem mailItem = GetMailItem(e);
if (mailItem != null)
    mailAddress =  ThisAddIn.GetSenderEmailAddress(mailItem);


text:
Q: What have your experiences been with Entity Framework? EF has been out for awhile now and I'm considering evaluating it - what have your experiences been?
I am interested in both web and desktop applications, and maybe some comparisons between EF and other ORM tools that you've used.
Learning curve is a factor since there is a team involved. Is this thing a bloated mess, or it is lean and sharp?
I heard that Microsoft is using this internally and in a big way, so that's a good sign. If you have any thoughts about how it might fit into the cloud-based future that MS seems to be spending their money on these days, that might also be interesting. After all, if this is something we might all eventually need to know, that would raise the priority level a notch or two.
Thanks a lot!

A: Well, I just finished implementing a complete system in EF, it was my first real experience with the EF in a production environment.  The app is running now for about 45 days with 100's of users hitting it daily with no issues.
I think the largest thing is that you have to change your thinking.  If you are thinking like a relational database ORM then you already have the wrong mindset.  You need to think in terms of partial methods, objects and extentions.  Once you get that basic mindset down things start to flow (and you rewrite a lot of code from when you first started).
Getting Help is rough
The other frustrating part of EF is that everywhere you go for help is full of L2S biggots who think they already know everything you need to do and keep trying to tell you to drop it and just use L2S...  If I would have ASKED for how to do that in L2S then maybe their opinion would be valid...
EF Works Fine
The basic ability to generate objects that you can then extend through partial methods works well.  I actually was pretty frustrated at the early stages because I kept trying to get things the way I would in a SQLCommand.  Once you realize you can think in terms of what the business logic needs rather than how SQL works you can get a lot more done.
For example - I kept trying to do joins to get a list of things that were related by a specific FK for various tasks.  Once I finally figured out that I can hand the entire where claus to the EF and let figure out how to get the data back to me quickly the code was actually much faster.
Includes stink
The Include syntax feels like a hack to me though.  Having to use .Include("TableName.DetailTable") is UGLY.  Maybe I am just spoiled by intellisense, but I hate that syntax.
On demand load
Master detail loads are also a bit ugly.  If you don't want to include them you can always take their reference and see if it .IsLoaded then call .Load.  Why?  Can't the object do that for me?  I ended up implementing an extention method on my objects that if I try to load a detail class that is not loaded it loads it on demand.  Seems like that should have been built in to me.
Note: The detail load of a filtered recordset mentioned in the above post is not complicated, but is not obvious either.  You can filter using Lambda expressions.
Do you EVER want to move the project?
Here is the big reason:  Non vendor lock-in.  If you EVER want to take that code to another database you CANNOT do it with Linq2SQL.  There is no provider model.  You may have a chance to move an EF system to another vendor.  In my case the same project runs on SQL Server and VistaDB EF (Alpha) without code changes.  So I can xcopy deploy it, or connect to a server as I choose at runtime.

A: EDIT (yes, 3 years later)... I no longer hate EF... Entity Framework 4.1 and up is great - it (finally) solves all of the issues/failings that it has had in the past. Note, not "4.0", but "4.1" finally removed the ugly use of 'magic strings', etc. It has Contains and everything else plus more.
Below is my old comment from 2008
I personally hate EF. I LOVE LINQ-2-SQL. Here are my concrete warnings about EF:
1) EF doesn't support the "Contains" function. So, if you have a table of 10,000 'accounts', and you wanted to return some accounts that the user supplied a list of the ID's... you would have to download all 10,000 and do a for loop.
2) EF doesn't support lazy-loading: http://www.singingeels.com/Articles/Entity_Framework_and_Lazy_Loading.aspx
3) If you have a simple "Type" table, example AccountType... and you wanted to select all accounts from the Accounts table where AccountTypeID == 9, there is not a clean way of doing it in EF... EF would hide that field, and make you supply an instance of an AccountType class.
All of these issues are solved in L2S.
EDIT: Oh, you did ask "what are your experiences..." not just about issues. In my new job, they have a 205 table database, 600+ stored procedures, etc. I wanted to bridge the gap into the new world of programming... so I converted the DAL to a 1-1 "drag all tables in" version using EF. Here's what it looked like: Giant EDM
After only 1 week, I had to rip it out and replace it with L2S due to the issues I mentioned above, and a few more.

A: After trialing EF for a new project (ASP.Net/ WCF) I found:
Querying to be very very easy to implement via LINQ.
Most of the time the generated T-SQL was on the money.
Support for N-tier apps was majorly lacking.
Management of instances to the object context was equally painful in n-layer, asp.net applications.
EF Designer was lacking some obvious features, was always diving into the XML.
Updates incur either costly database roundtrips or have crazily obscure methods to try and avoid them.
Performance hit was significantly noticeable from an POCO & SP based n/tier app.
This was expected but not to the extend we noticed. Even after compiling queries.
The time we saved in development due to the ease of querying, was soon lost trying to do what was previously simple tasks.
As Brain touched on, referring to entity type or table name by string was majorly annoying and felt very messy, found myself writing wrappers to return these from a single point.
If you want to use a single layer app, then many of the issues we encountered may not apply.
But for us, we are keeping our eye out for V2 and hopefully some improvements.


text:
Q: Browser back button doesn't work and doesn't change the value in state I am working on a project which uses backend API to fetch data and display on the frontend using react. I am not a react professional but learning by working on a project, Since the last 3 months I am stuck on one problem and still couldn't figure out how can it be solved.
This is the format of data that I receive
{
"data": [],
"meta": {
"page": 1,
"total": 382,
"per_page": 10,
"total_pages": 39,
"search_query": {},
"message": ""
}
}

This is how the URL looks like
const url = `${
    CONSTANTS.BASE_URL
  }/jobs?page=${counter}&position=${searchField.toLowerCase()}&city=${locationField.toLowerCase()}&job_type=${jobType}`;

I am using useHistory from react-router-dom to show dynamic url on the browser.
import { useHistory } from 'react-router-dom';
let jobHistory = useHistory();

This is how I pushed the URL into browser to look it dynamic
useEffect(() => {
    searchJobs(setIsLoading, setData, setMeta, url);
    setToggleSearch(false);
    jobHistory.push(
      `?page=${counter}${searchField ? `&position=${searchField.toLowerCase()}` : ''}${
        locationField ? `&city=${locationField.toLowerCase()}` : ''
      }${jobType ? `&job_type=${jobType}` : ''}`
    );
  }, [counter, jobType, toggleSearch]);

This is how searchJobs is being implemented
export default async (setIsLoading, setData, setMeta, url) => {
  try {
    setIsLoading(true);
    const res = await fetchData(url);
    setData(res.data);
    setMeta(res.meta);
    setIsLoading(false);
  } catch (error) {
    console.error(error);
  }
};

I have a pagination component that I implemented using Semantic UI react.
This is how I have controlled the value of counter
 {meta && meta.total > 0 && <CustomPagination meta={meta} setCounter={setCounter} />}

by passing it inside the CustomPagination Component, which looks like this.
const CustomPagination = ({ meta, setCounter }) => {
  const pageChange = (e, { activePage }) => {
    setCounter(activePage);
  };

  return (
    <>
      <div className="pagination">
        {meta && meta.total_pages && meta.total_pages > 1 && (
          <Pagination
            defaultActivePage={meta.page}
            onPageChange={pageChange}
            firstItem={false}
            lastItem={false}
            prevItem={{ content: <Icon name="angle left" />, icon: true }}
            nextItem={{ content: <Icon name="angle right" />, icon: true }}
            totalPages={meta.total_pages}
          />
        )}
      </div>
    </>
  );
};

export default CustomPagination;

Here comes the problem:

*

*Pagination works pretty well when I just press the Pagination numbers and it displays correct value in the URL, but when I press the back button, the URL changes the value but the output on the page remains the same. This problem occurs by clicking on normal pagination or by searching using keywords, I mean in both cases.

*The second case, if I go to page number 6 by clicking on pagination, it displays me 10 jobs result on that page and URL looks something like this ?page=6 and after I click on individual jobs /jobs/23499 and try to come back using the browser back button, the URL again takes me to the 1st page ?page=1.

*The third case, As a user I want to go to page 8 just by renaming the page number at URL, If I try to do so, again it redirects me to ?page=1
In my opinion, all the problems are caused by the wrong way of handling the value of the counter. Being a beginner, I couldn't figure out how it can be implemented correctly. Just to make sure, I have posted my whole code in this gist or you can see the problem live here, just need to signup first. Any help would be more than appreciated. Thank you all developers in advance.

A: In essence, the react-router-dom history is implemented with a stack data structure. If you want to go forward you "push" a url onto the stack and when you want to go back you perform a "pop" operation. From your code example, it looks like you use the history hook to get you to your pagination view but then you don't update your stack when you paginate.
Solution:
Looks like you need to push your new urls with the updated query parameter during the onclick Event of your pagination. When you go back you can pop or use the history.goBack() function provided .


text:
Q: addClass('open') is not working in jquery i am facing some weird problem. i am trying to add "open" class on certain condition. I am using following code.
 $('.stereo-nav-pos .login-register').addClass("open");

but its not working. I have tried to debug and i came to know that actually its appending "open" class and then its going to jquery.js file,at the end of jquery.js execution its removing "open" class from DOM.
then i have tried to add class called "openn" and it worked fine. So i am figuring out the issue why jquery.js file is remove "open" class from DOM?
If i try to run this code in console then its working fine.
can anyone tell me what's going wrong here?
Thanks in advance

A: I'm not sure if this will work for you or not, I had encountered similar problem a while ago.
What I've done is that I used setTimeout().
So you may try this:
setTimeout(function(){
   $('.stereo-nav-pos .login-register').addClass("open");
},10);

This will let the function to add the class open after a while so that it doesn't gets removed by the other jQuery function.

A: Adding class "open" works just fine.
Try to see if your selector selects anything
console.log("test",$('.stereo-nav-pos .login-register').length);

Check this jsfiddle test.
http://jsfiddle.net/ja4xapdg/

A: Tested it and it seems to work just fine for me, there must be something different that causes this problem to occur.
Result if it doesn't work: red background
Result if it does work: green background
http://jsfiddle.net/mnbtnk7h/


text:
Q: Sort JSONs by IP Network in python3 I would like to sort these JSON objects by the key "vnet" in each range (eg. range1, range2) in python3.
I have been able to sort it like this:
source["range1"].sort(key=lambda x: x["vnet"])

But unfortunately it does not use any IP address logic and sorts it by char.
Unsorted example:
{
    "range1": [
        {
            "name": "vnet1",
            "vnet": "192.168.11.0/25",
            "subnet": []
        },
        {
            "name": "vnet2",
            "vnet": "192.168.2.0/24",
            "subnet": []
        }
    ],
    "range2": [
        {
            "name": "vnet3",
            "vnet": "10.168.11.0/25",
            "subnet": []
        },
        {
            "name": "vnet4",
            "vnet": "10.168.2.0/25",
            "subnet": []
        },
        {
            "name": "vnet5",
            "vnet": "10.168.220.0/25",
            "subnet": []
        }
    ]
}

Sorted it should look like:
{
    "range1": [
        {
            "name": "vnet2",
            "vnet": "192.168.2.0/24",
            "subnet": []
        },
        {
            "name": "vnet1",
            "vnet": "192.168.11.0/25",
            "subnet": []
        }
    ],
    "range2": [
        {
            "name": "vnet4",
            "vnet": "10.168.2.0/25",
            "subnet": []
        },
        {
            "name": "vnet3",
            "vnet": "10.168.11.0/25",
            "subnet": []
        },
        {
            "name": "vnet5",
            "vnet": "10.168.220.0/25",
            "subnet": []
        }
    ]
}

I would very much appreciate any help on this, since I am stuck here right now.

A: Assuming you have your dict stored in json_dict.
You can use socket.inet_aton(__ip_string: str) as a key to sorting function. It will convert ip string to 32-bit packed binary.
So the following code will do what you want
import socket

json_dict = {
    "range1": [
        {
            "name": "vnet1",
            "vnet": "192.168.11.0/25",
            "subnet": []
        },
        {
            "name": "vnet2",
            "vnet": "192.168.2.0/24",
            "subnet": []
        }
    ],
    "range2": [
        {
            "name": "vnet3",
            "vnet": "10.168.11.0/25",
            "subnet": []
        },
        {
            "name": "vnet4",
            "vnet": "10.168.2.0/25",
            "subnet": []
        },
        {
            "name": "vnet5",
            "vnet": "10.168.220.0/25",
            "subnet": []
        }
    ]
}

for key, value in json_dict.items():
    value.sort(key=lambda x: socket.inet_aton(x['vnet'].split("/")[0]))

print(json_dict)


text:
Q: How to call a variable from nested function in Jquery I wanted to get the value of chkArray variable when called outside the method.
When I called getValues().total from outside the method I am getting a error message as cannot read property total of undefined.
function getValues(){
chkArray = new Array() ;
$("input[type=checkbox]:checked").each(function fire() {
 var total = chkArray.push($(this).val());
console.log(chkArray)
});
};

Kindly, help how to call that variable outside the method

A: Use this:
  function getValues(){
     var total = new Array() ;
     $("input[type=checkbox]:checked").each(function fire() {
       total.push($(this).val());
      });
   return total;
  };

Call function
var total= getValues();
console.log(total);

A:

function getValues() {
  var total = new Array();
  $("input[type=checkbox]:checked").each(function() {
    total.push($(this).val());
  });
  return total;
};

function doSomething() {
  var k = getValues();
  console.log(k);
}

1
<input type="checkbox" name="myCheckbox" value="1" />

2
<input type="checkbox" name="myCheckbox" value="2" />

3
<input type="checkbox" name="myCheckbox" value="3" />

4
<input type="checkbox" name="myCheckbox" value="4" />

5
<input type="checkbox" name="myCheckbox" value="5" />

<input type="button" onClick="doSomething()" value="Click me" />


text:
Q: Loading an image before pdf appears on target="_blank" new tab I am creating and displaying a PDF file which happens after I click a certain button. This all happens in a new tab (target="_blank"), and is all coded server-side.
How can I put a "loading image" when the new tab opens to show that yes a PDF file is being created, please wait.
Thank you and all suggestions are welcomed.

A: Rather then link directly to the PDF, create an HTML "wrapper" in which you put an object tag whose style allows it to cover the entire window. You can then put a standard loading gif (or whatever) on top. Using the object onload event, hide the loading image when the PDF is loaded. Then use JavaScript to set the data property of the object tag to the PDF.


text:
Q: How to serialize an XML differently if a tag is CDATA or not? I have a very complex XML which I serialize into object, but now we changed some tags which were normal string to CDATA.
We need to maintain the software retro compatible with old versions, the problem is: I use the serialized object through all code. So is totally unfeasible refactor all the code to work with two different possible serialized objects (one with CDATAs and another with strings.
The objects is very big so I don't want to 'clone' one to another changing the property kinds.
I would like a way to use the same object but when the serialize will happen identify if the tag is a CDATA or a string and set to the correct property in the object.
How could I do this?


text:
Q: Issue on formatting a json structure in java I want to create a json like this using java:
"foo": {
         "key1": "value1",
         "key2": "value2",
         }

i know how to create a key value json or a json array , but i don't know how to create a structure like this.
any helps?
thanks in advance.

A:
It seems your values are more relative to Map of java. So you need
  to find how to convert Map into json with java. Usually json
  processing is performing with frameworks such json and gson. However
  you can do it manually with StringBuilder class. Refer following
  example to manually create json with java.

Manually create json with java
    Map<String, String> map = new HashMap<>();
    map.put("key1", "value1");
    map.put("key2", "value2");

    //convert it to json maually
    StringBuilder builder = new StringBuilder();
    builder.append("\"foo\":{");
        builder.append("\n");
    for (String key : map.keySet()) {
        builder.append("\t");
        builder.append("\"").append(key).append("\"");
        builder.append(":");
        builder.append("\"").append(map.get(key)).append("\"");
        builder.append(",");
        builder.append("\n");
    }
    builder.append("\t}");

    String json = builder.toString();
    System.out.println(json);

output:
"foo":{
    "key2":"value2",
    "key1":"value1",
    }

Follow example below to convert Map<K,V> into json with jackson.
    Map<String, String> map = new HashMap<>();
    map.put("key1", "value1");
    map.put("key2", "value2");

    String json = new ObjectMapper().writeValueAsString(map);
    System.out.println(json);


text:
Q: converting all fields in a structtype to array I have this structtype with over a 1000 fields, every field type is a string.
root
 |-- mac: string (nullable = true)
 |-- kv: struct (nullable = true)
 |    |-- FTP_SERVER_ANAUTHORIZED_FEAT_B64: string (nullable = true)
 |    |-- FTP_SERVER_ANAUTHORIZED_FEAT_CODE: string (nullable = true)
 |    |-- FTP_SERVER_ANAUTHORIZED_HELP_B64: string (nullable = true)
 |    |-- FTP_SERVER_ANAUTHORIZED_HELP_CODE: string (nullable = true)
 |    |-- FTP_SERVER_ANAUTHORIZED_SYST_B64: string (nullable = true)
 |    |-- FTP_SERVER_ANAUTHORIZED_SYST_CODE: string (nullable = true)
 |    |-- FTP_SERVER_HELLO_B64: string (nullable = true)
 |    |-- FTP_STATUS_HELLO_CODE: string (nullable = true)
 |    |-- HTML_LOGIN_FORM_ACTION_0: string (nullable = true)
 |    |-- HTML_LOGIN_FORM_DETECTION_0: string (nullable = true)
 |    |-- HTML_LOGIN_FORM_INPUT_PASSWORD_NAME_0: string (nullable = true)
 |    |-- HTML_LOGIN_FORM_INPUT_TEXT_NAME_0: string (nullable = true)
 |    |-- HTML_LOGIN_FORM_METHOD_0: string (nullable = true)
 |    |-- HTML_REDIRECT_TYPE_0: string (nullable = true)

I want to select only the fields which are non null, and some identifier of which fields are non-null. Is there anyway to convert this struct to an array without explicitly referring to each element ?

A: I'd use an udf:
from pyspark.sql.types import *
from pyspark.sql.functions import udf

as_array = udf(
    lambda arr: [x for x in arr if x is not None],
    ArrayType(StringType()))

df.withColumn("arr", as_array(df["kv"])))


text:
Q: Cordova app - Use ringer volume instead of media in Android I'm using Cordova v4.1.2. The app uses media volume by default, and I want it to use the ringer volume for the sounds it plays. (Like in WhatsApp)
I used setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);in the onCreate() function. But it gives an error.
This is my CordovaApp.java. (in platforms\android\src\com\XX\XX)
import android.os.Bundle;
import org.apache.cordova.*;

public class CordovaApp extends CordovaActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        super.init();
        // Set by <content src="index.html" /> in config.xml
        loadUrl(launchUrl);
        setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
    }
}

It shows the following error on running:

There is no error when I remove the line setVolumeControlStream(AudioManager.STREAM_VOICE_CALL); from the java file, and the app runs perfectly. Any views on how to fix this?

A: Fixed it myself. Really easy if you were an Android geek, but anyways such a question was never asked before so I'll post the answer for others running into this same trouble.
I was right in changing the audio stream, but I was changing that in the wrong file! Doh!
This is where you should change it..
\platforms\android\CordovaLib\src\org\apache\cordova\CordovaActivity.java

at line 351 change it to setVolumeControlStream(AudioManager.STREAM_RING);
If you want to use the ringer volume though.
If you build and press the hardware volume keys, it will change and appear to use the ringer volume of course. But my case was a bit different.
I was using the cordova Media plugin org.apache.cordova.media. So when I play an audio using this plugin, it re-wires the stream back to media stream (STREAM_MUSIC). I was back to ground zero. The idea is to re-wire the plugin itself to use the audio stream of your choice. No rocket science, just change 2 lines in 2 files.
File:
\platforms\android\src\org\apache\cordova\media\AndroidHandler.java

Line 383:
setVolumeControlStream(AudioManager.STREAM_RING);

File:
\platforms\android\src\org\apache\cordova\media\AudioPlayer.java

Line 526:
setVolumeControlStream(AudioManager.STREAM_RING);

And you're good to go. Remember to replace STREAM_RING with your desired audio stream.


text:
Q: Аутентификация при помощи сертификата Как надо настроить IIS и сайт, чтобы можно было сделать аутентификацию по сертификату пользователя? Хотелось бы, чтобы при попытке обращения к сайту у пользователя запрашивался сертификат и после его выбора осуществлялся вход на сайт и данные сертификата становились бы доступны в Request.ClientCertificate.
В наличии windows 8, IIS 8, visual studio 2012. Сайт пишу на MVC 4.
На текущий момент настроил сайт с доступом по SSL.
Если в настройках сайта не указывать параметры "Требовать SSL" и указать "Игнорировать сертификаты клиента", то сайт запускается нормально. Иначе выдает ошибку.
Окно запроса сертификата не появилось ни разу.
Подскажите, что я еще не доделал?

A: Вопрос решился.
Проблема была в неправильном сертификате сервера.
Кому интересно, все заработало после этого:
Общие действия:

*

*Установил VipNet CSP 4.1 (просто решил попробовать с ним :), но, думаю, с другими криптопровайдерами будет аналогично).

Установка сертификата на сервер:

*

*Сделал запрос на сертификат для web-сервера при помощи "Создание запроса на сертификат" из пакета VipNet CSP в формат *.p10 в кодировке Base64.

*При помощи сервиса https://www.cryptopro.ru/certsrv сделал тестовый сертификат.

*При помощи VipNet CSP открыл контейнер, который был выбран (или создан) при создании запроса и установил в него присланный сертификат.

*Скачал и установил в корневые доверенные сертификаты - сертификат тестового сервера КриптоПро.

*Установил созданный сертификат сервера в хранилище сертификатов компьютера. В IIS, после этого, в "Сертификатах сервера" этот сертификат должен быть доступен.

*На сайте сделал привязку по https с указанием созданного сертификата.

Установка тестового клиентского сертификата:
Эта процедура выполняется выполняется аналогично, но при создании запроса тип выписываемого сертификата используется "Шифрование и подпись" и установка выполняется в личное хранилище сертификатов.
Чтобы сертификат стал запрашиваться при обращении к сайту, для него в параметрах SSL надо указать "Требовать SSL" и "Требовать сертификат клиента".
Проверял с тестовым сертификатом и с сертификатом на карте УЭК.


text:
Q: Break to first for loop inside multiple for loops? I'm trying to break from a loop to the very first loop (so very first loop can continue), but if I break from the point [self saveContext] I'll go one level up, right?
- (void)arrangeAllContacts
{
    NSArray *messages = [HumanResponse allAcceptedRecordsTextMessages];
    __block CoreDataPhotoRecord *photoDetails;

    self.addressBook = ABAddressBookCreateWithOptions(NULL, NULL);

    /* NSMutableArray *emails = [NSMutableArray new]; */
    NSArray *mobiles = [NSArray new];
    NSString *name;

    if (!self.allContacts) {
        NSLog(@"NO ADDRESS BOOK ENTRIES TO SCAN");
        return;
    }

    for (int a=0; a<messages.count; a++) {
        photoDetails = (CoreDataPhotoRecord *)messages[a];

        for (int i=0; i<self.allContacts.count; i++ ) {
            ABRecordRef person = (__bridge ABRecordRef)self.allContacts[i];

            /* ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty); */
            ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
            CFIndex phoneNumberCount = ABMultiValueGetCount(phoneNumbers);

            for (int k=0; k<phoneNumberCount; k++) {
                CFStringRef phoneNumberValue = ABMultiValueCopyValueAtIndex(phoneNumbers, k);

                NSString *phoneNumber = (__bridge NSString *)(phoneNumberValue);
                phoneNumber = [self getCleanMobile:phoneNumber];

                if ([phoneNumber isEqualToString:photoDetails.message.mobile]) {
                    name = [self nameForPerson:self.selectedPerson];
                    mobiles = [self numbersForContact:phoneNumbers];
                    /* emails = [self emailsForContact:emails]; */

                    [MagicalRecord saveWithBlockAndWait:^(NSManagedObjectContext *localContext) {
                        photoDetails = [photoDetails MR_inContext:localContext];
                        photoDetails.message.contactName = name;
                        photoDetails.message.contactNumber = mobiles;
                    }];
                    [self saveContext];

                    // How to break to first 'for' loop?
                }
            }
        }
    }

    if (self.addressBook != nil) {
        CFRelease(self.addressBook);
    }
}

A: if i understand you correctly, you want to "break" from the third loop to the first one(top one in the hierarchy) ?
if that is so , just define a Boolean in the beginning (or outside the loops),and when you want to break, set it to yes, and add an if statement in the beginning of the second loop : if (shouldBrake)beak;

A: As suggested earlier, defining a boolean and checking it in the for loop:
for (int i=0; notFoundPhoneNumber && i<self.allContacts.count; i++ ) {
Personally I find it more readable to do a while loop for the contacts (our mind tends to skip a condition of a for loop), so you can do:
while (shouldStop)
{
    if (i == self.allContacts.count)
    {
        shouldStop = true;
    }
    ...
}

or do a while on the complex condition notFoundPhoneNumber && i<self.allContacts.count
Any other solution will require redesign to your data structure (and I assume you don't want it)

A: You just make a function for phone number things and return boolean value.
    for (int i=0; i<self.allContacts.count; i++ ) {
        ABRecordRef person = (__bridge ABRecordRef)self.allContacts[i];

        /* ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty); */
        ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
        CFIndex phoneNumberCount = ABMultiValueGetCount(phoneNumbers);
        if ([self phoneNumberThings:phoneNumberCount]) break;
    }

〜〜〜〜
- (BOOL)phoneNumberThings:(int)phoneNumberCount {
    for (int k=0; k<phoneNumberCount; k++) {
         CFStringRef phoneNumberValue = ABMultiValueCopyValueAtIndex(phoneNumbers, k);

          NSString *phoneNumber = (__bridge NSString *)(phoneNumberValue);
          phoneNumber = [self getCleanMobile:phoneNumber];

          if ([phoneNumber isEqualToString:photoDetails.message.mobile]) {
              name = [self nameForPerson:self.selectedPerson];
              mobiles = [self numbersForContact:phoneNumbers];
              /* emails = [self emailsForContact:emails]; */

              [MagicalRecord saveWithBlockAndWait:^(NSManagedObjectContext *localContext) {
                  photoDetails = [photoDetails MR_inContext:localContext];
                  photoDetails.message.contactName = name;
                  photoDetails.message.contactNumber = mobiles;
              }];
              [self saveContext];

              // How to break to first 'for' loop?
              return YES
          }
    }
    return NO;
}


text:
Q: HTTP 500 - Internal Server Error - Deploying Sample Tomcat Web Applications click for screenshot
I am trying to open a webapps-WAR file in my browser with Tomcat. I am getting an HTTP 500 error as shown in screen shot. Do I need to upgrade SQL? I have version 5.7.22.
Error: client does not support authentication protocol requested by server. Consider upgrading SQL

A: Try upgrading your MySQL Connector/J.
https://dev.mysql.com/downloads/connector/j/


text:
Q: how to export all FreeIPA users list to a csv format? How can export all FreeIPA users to a csv file?

A: This command worked for me:
ipa user-find --all | grep -E "User Login|First|Last|UID|Email" > IPA_RAW.txt

after that, use this perl line to convert the format:
perl -ne 'chomp; print $_ . (($. % 8) ? "," : "\n")' IPA_RAW.txt | awk "Add your filters here" > users-list.csv

thanks

A: Late but full "copy/paste" answer (based on previous ones - thanks -  I could have quit after writing ipa2json); for present and future needs.
Export users with:
ipa user-find --all > ipa.txt

If the output is truncated adjust the limit with the command below and retry:
ipa config-mod --searchrecordslimit=######

To use this method you need nodejs on the machine (or container) where you intend to process ipa.txt; for this I suggest using nvm:
# install nodejs version manager (nvm) for the current user (not root!)
wget https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash

# install the latest nodejs long time support (lts) version for the current user
nvm install --lts

Install the required scripts as command line tools for the current user:
npm i -g ipa2json      # to convert ipa output to json
npm i -g equalizejson  # to spread missing fields in every record
npm i -g json2csv      # to convert the json to csv

Convert ipa output to json with:
ipa2json ipa.txt > ipa.json

Equalize the json (you need all the fields in all the instances for proper csv conversion) and convert to csv :
equalizejson ipa.json | json2csv > ipa.csv

To uninstall nvm, nodejs and the scripts you may just remove the $NVM_DIR folder (usually ~/.nvm), as documented when you type "nvm" in the terminal.


text:
Q: google weather api problems I am having problems with google weather api I have been using this script http://komunitasweb.com/2009/09/showing-the-weather-with-php-and-google-weather-api/ for sometime now but earlier I got this error:

Warning: simplexml_load_file()
  [function.simplexml-load-file]:
  //www.google.com/ig/api?weather=bermuda:2:
  parser error : Opening and ending tag
  mismatch: meta line 1 and HEAD in
  /home/webmx04/public_html/weather/widgetlive1.php
  on line 3
Warning: simplexml_load_file()
  [function.simplexml-load-file]:
  302 Moved
  in
  /home/webmx04/public_html/weather/widgetlive1.php
  on line 3
Warning: simplexml_load_file()
  [function.simplexml-load-file]: ^ in
  /home/webmx04/public_html/weather/widgetlive1.php
  on line 3
Warning: simplexml_load_file()
  [function.simplexml-load-file]:
  //www.google.com/ig/api?weather=bermuda:6:
  parser error : Opening and ending tag
  mismatch: HEAD line 1 and HTML in
  /home/webmx04/public_html/weather/widgetlive1.php
  on line 3
Warning: simplexml_load_file()
  [function.simplexml-load-file]:
   in
  /home/webmx04/public_html/weather/widgetlive1.php
  on line 3
Warning: simplexml_load_file()
  [function.simplexml-load-file]: ^ in
  /home/webmx04/public_html/weather/widgetlive1.php
  on line 3
Warning: simplexml_load_file()
  [function.simplexml-load-file]:
  //www.google.com/ig/api?weather=bermuda:7:
  parser error : Premature end of data
  in tag HTML line 1 in
  /home/webmx04/public_html/weather/widgetlive1.php
  on line 3
Warning: simplexml_load_file()
  [function.simplexml-load-file]: in
  /home/webmx04/public_html/weather/widgetlive1.php
  on line 3
Warning: simplexml_load_file()
  [function.simplexml-load-file]: ^ in
  /home/webmx04/public_html/weather/widgetlive1.php
  on line 3
Fatal error: Call to a member function
  xpath() on a non-object in
  /home/webmx04/public_html/weather/widgetlive1.php
  on line 4

Can anyone help me thank you
My code:
<?
$xml = simplexml_load_file('http://www.google.com/ig/api?weather=bermuda');
$information = $xml->xpath("/xml_api_reply/weather/forecast_information");
$current = $xml->xpath("/xml_api_reply/weather/current_conditions");
$forecast_list = $xml->xpath("/xml_api_reply/weather/forecast_conditions");
?>

    <title>Google Weather API</title>

Current Weather

           <img src="<?= 'http://www.rgbdahosting.com' . $current[0]->icon['data']?>" alt="More on Weather"?>

<?= $current[0]->temp_f['data'] ?>°F

<?= $current[0]->condition['data'] ?>

A: Apparently Google introduced Captcha to their Weather API. It will work one, two or three times, but after few request from the same server it will ask to reproduce Captcha. Something that your plugin isn't able to do.
I'm not aware of the way to get around this, so it looks like we will have to find another weather API to use. If I'm wrong please do correct me, it would be helpful.
Caching results from Google Weather might also help. 1 request in 15 or 30 minutes should be acceptable, no?


text:
Q: How to use curl in wordpress/woocommerce i wanted to apply the API settings of woocommerce in wordpress so its like i wanted to get the list of customers in my site. however there was a curl command which i am not familiar on where to place this command. I hope you can help me out
curl https://example.com/wc-api/v2/customers \ -u consumer_key:consumer_secret

i got this from wootheme site http://woothemes.github.io/woocommerce-rest-api-docs/?shell#view-list-of-customers

A: You need to configure woocommerce in the following ways

*

*Enable Rest API in woocommerce setting

*Set custom permalink structure other than default in wordpress settings

*Generate API KEYs for user in edit user

Some other approach i would suggest:

*

*Create a custom plugin this will help you to keep the working easy for you.

*Add API Client Library in your custom plugin. (API Client Library is where the rather than using the curl you can user functions which are user friendly)

*Use API Client Library function and access the data you want explore the library for the function which are defined in it.

For more details you need to go through links like which will help you achieve you purpose.
http://gerhardpotgieter.com/2014/02/10/woocommerce-rest-api-client-library/


text:
Q: I have a score with a no value I'm creating a quiz and I use local storage to show the user their previous attempts. And I have a problem. When you take the quiz one time, at the end it shows "Score 0:" and then "Score 1: actual score". I'm not sure where that score 0 came from. If anyone could help me, it would be much appreciated.
document.querySelector(".check").onclick = function () {
        /* Hide unneeded sections and showing scores */
        quiz.classList.add("hidden");
        correctAnswer.classList.remove("hidden");

        /*Showing all previous scores */
        const lastScore = localStorage.getItem("latestScore") || "";

        const scoreDetail = lastScore.split(',');

        scoreDetail.push(score);

        localStorage.setItem("latestScore", scoreDetail);

        let userScoreTemplate = `<h2>This Round's Score: ${score}</h2>`;

        scoreDetail.map((items, index) => {
            userScoreTemplate += `<h3>Score ${index}: ${items}</h3>`;
        });

        let userScoreBoard = document.querySelector(".user-score");

        userScoreBoard.innerHTML = userScoreTemplate;
    };

A: ${index} will be equal to 0 initially as Arrays always begin at index 0.
The fix:
scoreDetail.map((items, index) => {
    index++; //increase index by 1;
    userScoreTemplate += `<h3>Score ${index}: ${items}</h3>`;
});

Explanation TL;DR:
Most programming languages use a zero-based index as an Array is a pointer and the index relates to the pointer's memory location. So the first memory location would be 0, and the second slot would be 1.

A: Nevermind, I just had to do this:
scoreDetail.map((items, index) => {
            userScoreTemplate += `<h3>Score ${index}: ${items}</h3>`;
            if (items==""){
                userScoreTemplate="";
            };
        });