text:
Q: Intercept response code in webview using google doc to display pdf I have a webview that loads a google doc with a flyer (pdf, from the web) in it.  Some of the flyers are live on my website but others aren't, but I have them coded in the app so when they become available the user will see them.
The google doc in the webview works great with flyers that are available but ones that aren't available yet I get a error-type message in the google doc.  I would like to intercept the 404 response code error from the URL that has the flyer (pdf).  How do I do this?
Current code:
/*opens in app using google docs*/
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginState(PluginState.ON);
mWebView.loadUrl("https://docs.google.com/viewer?url="+round_num_url);
//round_num_url is the url for my flyer

Message in google doc in webview for flyers unavailable - "Sorry, we were unable to find the document at the original source. Verify that the document still exists. You can also try to download the original document by clicker here"
EDIT: doesn't work yet (crashes) after taking suggestions from @x-code
try {
            URL url = new URL(round_num_url);
            HttpURLConnection huc = (HttpURLConnection) url.openConnection();
            huc.setRequestMethod("HEAD");
            huc.connect();
            if (huc.getResponseCode() != 404) {
              // the pdf is available, continue with your code that loads the web view
              // ...
            } else {
              // the pdf is not available, you may need to notify the user
              // ...
            }
            huc.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch(IOException e) {
            e.printStackTrace();
        }

A: Although Google docs will receive a 404 when it tries to access your broken URL, it is not going to return a 404 to the web view, because the Google docs URL is valid.
You should first test your own URL (the URL of your PDF) by trying to load it with for example the AndroidHttpClient and an HttpHead request. If this returns a 404 don't bother trying to load gdocs.
Here is some example code. I used HttpUrlConnection because that is the method recommended by Android docs for new code:
HttpUrlConnection huc = new HttpUrlConnection(round_num_url);
huc.setRequestMethod("HEAD");
huc.connect();
if (huc.getResponseCode() != 404) {
  // the pdf is available, continue with your code that loads the web view
  // ...
} else {
  // the pdf is not available, you may need to notify the user
  // ...
}
huc.disconnect();

I have not compiled this code, and you may have to wrap it in a try / catch block before it will compile.
Update: I had to modify the code to make it work, as suggested above:
try {
    URL url = new URL(strUrl);
    HttpURLConnection huc = (HttpURLConnection) url.openConnection();
    try {
        if (huc.getResponseCode() != 404) {
            // url is available
        } else {
            // url is not available
        }
    } finally {
        huc.disconnect();
    }
} catch (MalformedURLException e) {
    ;
} catch (IOException e) {
    ;
}


text:
Q: DASK Metadata mismatch found in 'from_delayed' JSON file I'm just starting my adventure with DASK and land I'm learning on an example dataset in json format. I know that this is not the easiest data format in the world for a beginner :)
I have a dataset in the json format. I loaded the data via dd.read_json to dataframe and everything goes well. The problem occurred with, for example, the compute() or len() function.
I get this error:
ValueError: Metadata mismatch found in `from_delayed`.

Partition type: `DataFrame`
+----------+-------+----------+
| Column   | Found | Expected |
+----------+-------+----------+
| column1  |   -   | object   |
| column2  |   -   | object   |
+----------+-------+----------+

I tried different things, but nothing helps. I don't know how to handle this error.
Please help, I will be very grateful !

A: My guess is that your JSON data has different columns in different parts of the data.  When Dask DataFrame loads your JSON data it looks at the first chunk of data to determine what the column names and datatypes are.  It then assumes that all of your data looks like this.
This assumption turns out to be wrong in your case and probably there is some column that only appears later on in the file.
You might consider increasing the size of the sample that Dask reads when determining metadata like column names.
df = dd.read_json(..., sample=2**26)

The default is 1MB (2**20)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cursor at the end on a editable div Angular 6 I'm having this problem:
I'm starting with Angular 6, so I wanted to do a text editor which shows the css styles while you are typing.
Seeing that I wasn't able to show the Css styles inside of Textareas, I tried with an editable div when I show the text on [innerHTML]="".
The main problem is when I call the method bound to an (input), the cursor goes to the start of the div, instead of go to the last position to keep typing.
I'm using the following div:

Thank you so much


text:
Q: instance on amazon stopped respond on 80 port I got one instance t2.small EC2 on Amazon. ubuntu 14.04, apache2, php5, mysql (common things).
In case of avoiding some questions fw about open ports, iptables, apache running service, apache listenings ports and other stuff, here it is some detail status of running services

here it is instance security group inbound rules.
inbound rules

It behaves rather strange. It does not respond on 80 port from outside
I've tried to telnet on 80 port from outside without success.
But if I change apache port on (for example) 81, it respond


text:
Q: How to execute nested commands in Ruby I want to execute nested commands using ruby. E.g.,
ls $(cat file_name.txt)

In the command above, file_name.txt is the file name I want to search for. But due to the $ character, it does not work.

A: if it's ruby use the exec method or backticks:
exec("ls $(cat file_name.txt)")
`ls $(cat file_name.txt)`


text:
Q: showing $\{\alpha u : \alpha\in \mathbb{R}\}$ and $\{w+\beta v:w\in Y, \beta\in\mathbb{R}\}$ are closed sets Let $X$ be a normed vector space.
How can I show the following?
(1) Let $0\neq u\in X$. Show that $\{\alpha u : \alpha\in \mathbb{R}\}$ is closed.
(2) If $Y$ is a closed vector subspace of $X$ and $v\in X-Y$, then $\{w+\beta v:w\in Y, \beta\in\mathbb{R}\}$ is closed.
Hope you can help! Thank you.

A: (1) Suppose $\|u\|=1$ and $(\alpha_nu)_n$ converges to some $x\in X$. Then $(\alpha_n)$ is bounded because
$$|\alpha_n|=\|\alpha_nu\|=\|(\alpha_nu-x)+x\|\le \|\alpha_nu-x\|+\|x\|\,.$$
So, a convergent subsequence $\alpha_{n_k}$ can be chosen, say with limit $\alpha$, but then $\alpha_{n_k}u\overset{k\to\infty}\longrightarrow\alpha u$, so $x$ must be $\alpha u$.
(2) Consider the quotient space $X/Y$ with canonical projection $\phi:X\to X/Y$ sending $x\mapsto [x]$. Since $Y$ is closed, the inherited norm $X/Y\ $ ($\|[x]\|_{X/Y}:=d(x,Y)$) is indeed a norm, and we have
$$\phi^{-1}(\{\alpha[v]\mid\alpha\in\Bbb R\})=\{y+\beta v \mid y\in Y,\beta\in\Bbb R\}$$
so this set is the preimage of a closed subspace, hence is closed.


text:
Q: Python: Trying to scan for active bluetooth devices I found online multiple sources that said that discover_devices scans for active bluetooth devices, but for me it was printing all the bluetooth devices that remembered on my computer. Is there something wrong with my code/settings?
`
import bluetooth

nearby_devices = bluetooth.discover_devices(lookup_names=True)
print(nearby_devices)

for addr, name in nearby_devices:
    print('\nname = ', name, "\naddress = ", addr)

`


text:
Q: monitor Google pubsub I am using grafana to monitoring my service, I have new service that deal with google pubsub using spring-cloud-gcp-starter-pubsub, I wanna monitoring the pubsub subscription to show how many message acknowledged and how many one in lag, is there any way to implement that ?

A: You can use google StackDriver to monitor the volume of messages in percentage rather then see exactly how many messages there ware and how many acknowledged.
You can save in you db all messages and acknowledgment if you really like.


text:
Q: Need Apache configuration fixed Issue:
I have loaded Wordpress MU inside of my DocumentRoot. This is working fine however, I now have two projects inside the DocumentRoot that both have a directory with the same name: 'plugins':
/var/www/html/cms/plugins/
/var/www/html/cms/sites/blogs/wp-content/plugins/.
I believe that this is causing a conflict because of my current Apache setup.
When I load my WP MU up and sign in, everything "appears" to be normal but upon looking closely, I noticed that not a single plugin is loading due to Apache 404 error. Example:
https://www.someplaceonline.ext/blogs/wp-content/plugins/active-directory-integration/css/adintegration.css?ver=1.7.1

404 Not found.

I am not sure how to fix this so I have provided my Apache setup.
What I have already tried:
Changing "AliasMatch ^.*/plugins/(.*)$ /var/www/html/cms/plugins/$1" to AliasMatch ^\.\./plugins/(.*)$ /var/www/html/cms/plugins/$1. The reason: references inside of my cms directory to their 'plugins' usually are prefixed with '..', so they are formatted ../plugins/someplugin/etc/etc.ext This continues to load plugins correctly inside of the cms, and verifying my Regular expression at http://www.regextester.com/ leads me to believe this should work to solve the issue however, items such as https://www.someplaceonline.ext/blogs/wp-content/plugins/active-directory-integration/css/adintegration.css?ver=1.7.1 continue to fail to load.
Adding "AliasMatch ^.*/wp-content/plugins/(.*)$ /var/www/html/cms/sites/blogs/wp-content/plugins/$1". I thought I could simply append a new AliasMatch to resolve the path mapping for Wordpress but this also, does not work.
The relevant directory structure:
/var/www/html/
/var/www/html/cms/
/var/www/html/cms/memorybook/
/var/www/html/cms/plugins/
/var/www/html/cms/site_resources/
/var/www/html/cms/sites/
/var/www/html/cms/sites/blogs/

The relevant Apache configuration:
<VirtualHost *:80>
    DocumentRoot /var/www/html/cms/sites/

    #Host names
    ServerName www.someplaceonline.ext
    ServerAlias someplaceonline.ext
    ServerAlias www.spo.ext
    ServerAlias spo.ext

    <Directory "/var/www/html/cms/sites/">
       AllowOverride All
       Allow from All
    </Directory>

    ### This set of directives match the blogs on this server, which is outside of the document root. ###
    Alias /blogs /var/www/html/cms/sites/blogs
    <Directory "/var/www/html/cms/sites/blogs">
        AllowOverride All
        Allow from All
    </Directory>

    ### This set of directives match the memorybook folder which is outside of the doucment root. ###
    Alias /memorybook /var/www/html/memorybook
    <Directory "/var/www/html/memorybook">
        AllowOverride All
        Allow from All
    </Directory>

    ### This set of directive match the plugins folder which is outside of the document root. ###
    #Alias /plugins /var/www/html/cms/plugins
    #<Directory "/var/www/html/cms/plugins">
    #   AllowOverride All
    #   Allow from All
    #</Directory>

    ### This set of directive match the site_resources folder which is outside of the document root. ###
    Alias /site_resources /var/www/html/cms/site_resources
    <Directory "/var/www/html/cms/site_resources">
       AllowOverride All
       Allow from All
    </Directory>

    ### This must be last or else unwanted matches will occur. ###
    AliasMatch ^.*/site_resources(.*)$ /var/www/html/cms/site_resources/$1
    AliasMatch ^.*/plugins/(.*)$ /var/www/html/cms/plugins/$1
    #AliasMatch ^.*/wp-content/plugins/(.*)$ /var/www/html/cms/sites/blogs/wp-content/plugins/$1
</VirtualHost>

A: ### This set of directives match the blogs on this server,
###     which is outside of the document root.
Alias /blogs /var/www/html/cms/sites/blogs
<Directory "/var/www/html/cms/sites/blogs">
    AllowOverride All
    Allow from All
</Directory>

No, this is superfluous since /blogs is already equal to /var/www/html/cms/sites/blogs.
AliasMatch ^.*/site_resources(.*)$ /var/www/html/cms/site_resources/$1

Also a duplicate of its previous Directory block and Alias definition.
If you want this one to work, remove the Alias.
AliasMatch ^.*/plugins/(.*)$ /var/www/html/cms/plugins/$1

The same again as above, with the added sauce that this will never end up at  /var/www/html/cms/sites/blogs/wp-content/plugins/
NOTE that Aliases should end with a slash, unless you know better (you don't.)
Remove the first two sections above, and tell us what the error log says when you shriek "404!".


text:
Q: Why should an application module not require a module that provides a service? The ServiceLoader.java docs notes:

It is strongly recommended that the application module does not require modules which contain providers of the service.

Why is this strongly recommended, what could happen if the recommendation isn't followed?

Context: This indirectly means that modules defining a service shouldn't also export a provider of that service. I thought it would be handy to provide a default implementation of the service within the same module.

A: Why Not Require Provider Module?
The reason is because the uses / provivdes directives and
the java.util.ServiceLoader API is designed for a plugin-like architecture. You control which plugins are available by controlling which providers are on the module-path/class-path. If you requires the provider module, then you can no longer omit it because the application would fail to launch due to missing dependencies.
The Documentation
The documentation you quote makes more sense if you look at the previous sentence as well, which provides more context.

In addition, if the application module does not contain the service, then its module declaration must have a requires directive that specifies the module which exports the service. It is strongly recommended that the application module does not require modules which contain providers of the service.

This is addressing the specific case demonstrated below.
Application Module
module app {
  requires service;
}

Service Module
module service {
  exports com.example.service;

  uses com.example.service.Service;
}

Provider Module
module provider {
  requires service;

  provides com.example.service.Service with
    com.example.provider.ServiceImpl;
}

The above is the recommended approach. And what the documentation is saying is that the app module should not include a requires provider directive. The reason why has already been explained.
Also, note this does not prevent either the service module or the app module from providing a default implementation of the service interface.
Example Module Resolution
If you create and compile an implementation for the above modules, then you can see the module resolution at run-time via --show-module-resolution. I use --limit-modules below to control which modules are resolved to avoid having to mess around with the module-path. As you can see, since app does not requires provider, it is possible to omit provider and still have a working application.
My service interface has a getMessage() method that simply returns a String. My main class iterates the available providers, if any, and outputs the provider's class name and "message". This output comes after, and is clearly distinct from, the module resolution output below.
Note I load the providers from a static method in the Service interface, because the service module is where I have the uses directive for said interface.
With Provider Module
Command:
java --show-module-resolution --limit-modules app,service,provider --module-path <path> --module app/com.example.app.Main

Output:
root app <module-location>
app requires service <module-location>
service binds provider <module-location>
provider requires service <module-location>

APPLICATION OUTPUT
Provider: 'com.example.provider.ServiceImpl'
    message => Hello, World!

Without Provider Module
Command:
java --show-module-resolution --limit-modules app,service --module-path <path> --module app/com.example.app.Main

Output:
root app <module-location>
app requires service <module-location>

APPLICATION OUTPUT
There are no available providers...

Previous Answer
The previous edition of this answer had the following example to demonstrate what the documentation was saying:
Service Module
module service {
  requires provider;

  exports com.example.service;

  uses com.example.service.Service;
}

Provider Module
module provider {
  requires service;

  provides com.example.service.Service with
    com.example.provider.ServiceImpl;
}

Not only was I incorrect regarding the purpose of the documentation, but the above is not even possible as the Java Platform Module System does not allow cyclic dependencies at compile-time.


text:
Q: Generating a values for functions created with purrr:map I'm trying to use purrr:map to create empirical cumulative percentages for values of x_var in a df that are unique to each level of a factor variable.
Ideally, I'd like a result to be a long df where the columns look as follows:
levels (long)   |   x_var   |   epcd_val
Here's an example:
# load packs
if(!require("pacman"))install.packages("pacman")
p_load(dplyr, tibble, purrr)

# generate fake data
samp_dat <- tibble(
x_var = rnorm (1000, 0, 1),
levels = sample(LETTERS[1:4], 1000, replace=TRUE, prob=c(0.25, 0.50, 0.125, 0.125)))

# generates a list of ecdf functions for each level
ecdfs <- samp_dat %>%
  group_split(levels) %>%
  map(., ~ ecdf(.x$x_var))

The resulting ecdfs is a list of edcf functions, which is unique to each level within levels.
I somehow then need to feed the x_var values, grouped on levels, back into this function. However, I'm stuck on how to pull it off with pipes.

A: The ecdf outputs a function, so we feed the 'x_var' into the output function after grouping by 'levels'
library(dplyr)
samp_dat %>%
    group_by(levels) %>%
    mutate(newval = ecdf(x_var)(x_var))


text:
Q: How to generate a random variable by composition? If I want to generate a random variable with such a pdf: $f(x) = \dfrac 3 {2}x^2 : [-1, 1] \to \Bbb R$ by composition, what should I do?
I think I can divide the pdf by $x=0$ into two parts. But the $f(x)$ of the new two parts are the same and the CDF of the left part can be a negitive value.
But I have to use composition for its my homework.
How can I do?


text:
Q: Чтобы программа на всех размерах экранов была одинаковой в tkinter на Python Как сделать так, чтобы программа была одинаковой на всех размерах экранов в tkinter на python. Я пишу программу на компе для телефонов, и когда я её тестировал, то она смотрелась совсем не так, как на компе. Там все кнопки, строки, и все остальное сместилось в одну кучку. Помогите пожалуйста!
Вот код:
import sys
import random
import tkinter as Tk

root = Tk.Tk()

category6 = [("Присядь 5 раз"), ("Пригни 3 раза")]
length_category6 = len(category6)

category12 = [("Присядь 10 раз"), ("Пригни 5 раза")]
length_category12 = len(category12)

sos = 0

def button_click1(event):
    global sos
    sos = 1
    event = random.randrange(0, length_category6)

def button_click2(event):
    global sos
    sos = 2
    event = random.randrange(0, length_category12)

def ura(event):
    global sos
    if sos == 1:
        mlabe12.config(text = 'Задание: ' + category6[event], bg = 'White')
    elif sos == 2:
        mlabe12.config(text = 'Задание: ' + category12[event], bg = 'White')

mbutton = Tk.Button(text = 'Готово', command = lambda: ura, fg = 'Black', bg =
'Orange', width = 16, height = 2)
mbutton.bind("<Button-1>", ura)
mbutton.place(x = 100, y = 345)

root["bg"] = "Light green"
root.geometry('315x500+500+300')
root.resizable(width = False, height = False)

mlabel = Tk.Label(root, text = '                      Выбери возрастную
категорию:
', bg = 'Light blue', font = "Arial 10", height = 2)
mlabel.pack()

vlab = Tk.Label(text = " ", width = 70, height = 15, bg = "Light Blue")
vlab.place(x = 0, y = 400)

vbat1 = Tk.Button(text="6+", width = 5, height = 2, bg = "Pink", fg =
"Black")
vbat1.bind("<Button-1>", button_click1)
vbat1.place(x = 110, y = 432)

vbat2 = Tk.Button(text = "12+", width = 5, height = 2, bg = "Green", fg =
"Black")
vbat2.bind("<Button-1>", button_click2)
vbat2.place(x = 165, y = 432)

flab = Tk.Label(text = "", width = 70, height = 1, bg = "Yellow")
flab.place(x = 0, y = 400)

ylab = Tk.Label(text = " ", bg = "Yellow", height = 4, width = 70)
ylab.place(x = 0, y = 482)

mlabe12 = Tk.Label(root)
mlabe12.pack()

root.mainloop()

A: Используйте относительные размеры с помощью атрибутов place relx и rely
например:
label = Label(root, text='Hello')
 label.place(relx=0,25, rely=0,5)


text:
Q: SQL stored precedure 2 insertstatements with 1 select needed for one insert I got a website with a database running on MySQL Community Server (GPL) version 5.5.37
And I want to write a stored precedure to insert an image in table 1 then select the id from that last post to insert that id in table 2.
I started to google and ended up with this:

CREATE PROCEDURE InsertNewMedia(
    IN insertLocatie varchar(255),
    IN insertNaam varchar(150),
    IN insertOmschrijving longtext,
    IN insertCategorieID  int
)

BEGIN

INSERT INTO MediaDB (idMediaDB, Locatie, Naam, Omschrijving) VALUES (NULL, insertLocatie, insertNaam, insertOmschrijving);

SELECT MAX(idMediaDB) AS Nieuwste FROM MediaDB;

INSERT INTO MediaLink (idMediaLink, OverMijShoots_idOverMijShoots, MediaDB_idMediaDB) VALUES (NULL, insertCategorieID, Nieuwste);

END

I know this is a wrong code but I can't find a good awnser on what I need.
Can anyone help me?

A: I think you are looking for LAST_INSERT_ID():
delimiter //
CREATE PROCEDURE InsertNewMedia(
    IN insertLocatie varchar(255),
    IN insertNaam varchar(150),
    IN insertOmschrijving longtext,
    IN insertCategorieID int
)

BEGIN
    INSERT INTO MediaDB(idMediaDB, Locatie, Naam, Omschrijving)
        VALUES (NULL, insertLocatie, insertNaam, insertOmschrijving);

     INSERT INTO MediaLink (idMediaLink, OverMijShoots_idOverMijShoots, MediaDB_idMediaDB)
        VALUES (NULL, insertCategorieID, LAST_INSERT_ID());

END//
delimiter ;


text:
Q: ASP.NET MVC3 JSON Model-binding with nested class In MVC3, is it possible to automatically bind javascript objects to models if the model has nested objects? My model looks like this:
 public class Tweet
 {
    public Tweet()
    {
         Coordinates = new Geo();
    }
    public string Id { get; set; }
    public string User { get; set; }
    public DateTime Created { get; set; }
    public string Text { get; set; }
    public Geo Coordinates { get; set; }

}

public class Geo {

    public Geo(){}

    public Geo(double? lat, double? lng)
    {
        this.Latitude = lat;
        this.Longitude = lng;
    }

    public double? Latitude { get; set; }
    public double? Longitude { get; set; }

    public bool HasValue
    {
        get
        {
            return (Latitude != null || Longitude != null);
        }
    }
}

When I post the following JSON to my controller everything except "Coordinates" binds successfully:
{"Text":"test","Id":"testid","User":"testuser","Created":"","Coordinates":{"Latitude":57.69679752892457,"Longitude":11.982091465576104}}

This is what my controller action looks like:
    [HttpPost]
    public JsonResult ReTweet(Tweet tweet)
    {
        //do some stuff
    }

Am I missing something here or does the new auto-binding feature only support primitive objects?

A: Yes, you can bind complex json objects with ASP.NET MVC3.
Phil Haack wrote about it recently.
You've got a problem with your Geo class here.
Don't use nullable properties:
public class Geo
{

    public Geo() { }

    public Geo(double lat, double lng)
    {
        this.Latitude = lat;
        this.Longitude = lng;
    }

    public double Latitude { get; set; }
    public double Longitude { get; set; }

    public bool HasValue
    {
        get
        {
            return (Latitude != null || Longitude != null);
        }
    }
}

This is the javascript code I've use to test it:
var jsonData = { "Text": "test", "Id": "testid", "User": "testuser", "Created": "", "Coordinates": { "Latitude": 57.69679752892457, "Longitude": 11.982091465576104} };
var tweet = JSON.stringify(jsonData);
$.ajax({
    type: 'POST',
    url: 'Home/Index',
    data: tweet,
    success: function () {
        alert("Ok");
    },
    dataType: 'json',
    contentType: 'application/json; charset=utf-8'
});

UPDATE
I've tried to do some experiments with model binders and I came out with this solutions which seems to work properly with nullable types.
I've created a custom model binder:
using System;
using System.Web.Mvc;
using System.IO;
using System.Web.Script.Serialization;

public class TweetModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var contentType = controllerContext.HttpContext.Request.ContentType;
        if (!contentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
            return (null);

        string bodyText;

        using (var stream = controllerContext.HttpContext.Request.InputStream)
        {
            stream.Seek(0, SeekOrigin.Begin);
            using (var reader = new StreamReader(stream))
                bodyText = reader.ReadToEnd();
        }

        if (string.IsNullOrEmpty(bodyText)) return (null);

        var tweet = new JavaScriptSerializer().Deserialize<Models.Tweet>(bodyText);

        return (tweet);
    }
}

and I've registered it for all types tweet:
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        ModelBinders.Binders.Add(typeof(Models.Tweet), new TweetModelBinder());

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

A: I experienced the same issue, however in my case this was related to how the data was being transmitted from client side. Make sure the AJAX request is using the proper headers and formatting. For example:
    dataType: 'json',
    contentType: 'application/json; charset=UTF-8',
    data: JSON.stringify({
        MemberId : '123',
        UserName: '456',
        Parameters: [
            { Value : 'testing' },
            { Value : 'test2' }
        ]
    }),


text:
Q: How to submit some text I'm trying to submit (on mousedown) some text which takes up the class "current" when hovered:
$("#SomeDynamicMenu li").live("mousedown", function() {

        var SearchTerms = $('li.current').text();
        $('#SomeForm').submit(SearchTerms);

});

What am I doing wrong?

A: $("#SomeDynamicMenu li").live("mousedown", function() {
    var SearchTerms = $('li.current').text();
    $('#anyHiddenInForm').val(SearchTerms);
    $('#SomeForm').submit();
});

A: $("#SomeDynamicMenu li").live("click", function ()
{
    var SearchTerms = $(this).text();
    var form = $("#SomeForm");
    form.append('<input type="hidden" value="'+SearchTerms+'" name="SearchTerms" />');
    form.submit();
});

Then you'll be able to get your handy $_POST["SearchTerms"] variable in PHP containing the text of the clicked li. Also depending on what version of jQuery .submit() may not work in certain browsers if your submit button has name="submit".
NB: Can easily be changed for "mousedown" rather than "click"


text:
Q: How can use the same method in a controller, receiving an abstract class? I have 5 different jsp with mvc spring forms. In modelAttribute of each form, I have a specific class (for example, dog, cat, mouse, etc). Each form has a submit button, and I want that request will submit in the same method in the controller.
In the controller, I try to get a general class (abstract) such animal. And it gives me an error. How could i do this?
If a receive a cat, this works fine.
Thanks!
the jsp:
<form:form method="post" modelAttribute="Cat" action="../2/submit">
            <form:checkbox path="attribute" />
            <button type="submit">Submit</button>
</form:form>

and the controller:
@RequestMapping(value = "/submit",  produces ="text/html" ,headers = "Accept=" ,  method=RequestMethod.POST)
    public String submitForm(@ModelAttribute Animal animal, Model m) throws IllegalArgumentException, IllegalAccessException {
        return "";
    }

A: I can think of two techniques for this.
Technique: Old School
Use a parameter of type WebRequest in the handler method.
This gives access to the request parameters.
Then you query the parameters you care about to determine the source of the request and to determine the parameters that you require.
@RequestMethod("/blammy")
public String blammy(
    final ModelMap model,
    final WebRequest webRequest)
{
    String something = webRequest.getParameter("something");

    if ("hoot".equals(something))
    {
        ... process a hoot request
    }
    else if ("bark".equals(something))
    {
        ... process a bark request
    }
}

Technique: Front Controller
Proved a method for each form then forward the call to a common method.
@RequestMethod("/fish")
public String fish(
    @ModelAttribute final Fish fish,
    final ModelMap model)
{
     return commonMethod(model, (Animal)fish);
}

@RequestMethod("/cat")
public String cat(
    @ModelAttribute final Cat cat,
    final ModelMap model)
{
     return commonMethod(model, (Animal)cat);
}

public String commonMethod(
    final ModelMap model,
    final Animal animal)
{
    ... blam
}

A: You shouldn't unify request handler methods, in spite use a Service layer with needed business layer so all controllers can invoke the same busines logic.


text:
Q: Changing SelectionStart in TextChanging handler I'm writing a text control with input filtering based on TextBox.
The main idea consists of handling TextChanging event and set correct Text and SelectionStart values.
This worked until Windows 10 Creators Update. Now when I change SelectionStart in TextChanging handler I see correct caret position in UI but next character goes to the old place.
I can not share any code right now but you can reproduce it by adding arbitrary character on each TextChanging call (and setting SelectionStart after this character).
Have Microsoft broken the backward compatibility? Have I done anything wrong?
UPD: So I've found a dirty workaround:
async void OnTextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
    var newText = HandleText(Text);
    var newSelectionStart = HandleTextDiff(newText, Text);
    Text = newText;

    await Task.Yield();
    SelectionStart = newSelectionStart;
}

Task.Yield makes the assignment of SelectionStart to run asynchronously after the control internal assignment.
That's very dirty and ugly because it causes caret blinking in some cases but the only working solution I can find.

A: Maybe you should try setting the SelectionLength to 0
Another option might be to use SetCaretPos Api call
[DllImport("User32.dll")]
static extern bool SetCaretPos(int x, int y);


text:
Q: How to declare a C# variable that returns a sliced string of another variable in my SSIS package? I'm creating a file transfer package that copies files into an output folder and then copies them into a separate archive.  The files are frequently replaced with new files with a file name format such as xxxx20190427.zip I created a foreach loop in SSIS to copy / move the files but I can't figure out how to replace old versions. As I move the files into the output folder, I want to replace the file from the previous load. I'm trying to create a script task that creates a variable based on the substring of the variable declared in the foreach loop so that if the file xxxx20190427.zip is present, it checks for the "xxxx" portion in the filenames of my output folder and deletes that file if it's present so that only the newest file is available.

A: An overview of the process is below, with a couple C# Script Tasks used in this example.  For the Script Tasks be sure to add the proper references as indicated below, with these being the using statements at the beginning of each section of code.

*

*Add an Execute SQL Task to the beginning of the Control Flow.  The file names from the current execution will be held in a table that will be created in this task.  Example SQL for this is below.  This checks if the table exists, drops the table if it's present, and then creates it.

*You probably already have the file name for each iteration stored in a variable, but if not add a string variable at Index 0 of the Foreach Loop.  This can be done on the Variable Mappings pane.

*Within the Foreach Loop add a Script Task after all the components.  Add the string variable holding the file name in the ReadOnlyVariables field.  This script task (uses C#) will insert the file name used in each iteration to a table that will be used later.  While doing the insert with C# is a slightly more involved than just an Execute SQL Task, the FileInfo.Name property can be used to ensure only the file name is stored, as opposed to the file name with path.

*After the Foreach Loop create another Script Task.  If variables are used to hold the name of the output folder and file prefix add these in the ReadOnlyVariables field as before.  Code for this is also below.  First the names of the files from the current execution are retrieved and stored in the currentExecutionFiles list.  The files in the output directory are then enumerated through, with any files that have the prefix and were not used in the current package execution deleted.

*This is optional, but I'd recommend adding another Execute SQL Task at the end of the package to drop the table holding the file names.  The DROP statement from the first Execute SQL Task can just be used for this.

CREATE and DROP DDL for Execute SQL Task:
IF (OBJECT_ID(N'DATABASE.SCHEMA.FILES') IS NOT NULL)
BEGIN
DROP TABLE DATABASE.SCHEMA.FILES
END;

CREATE TABLE DATABASE.SCHEMA.FILES
(
[FILENAME] VARCHAR(250)
)

C# Script Task to Store File Names:
using System.Data;
using System.Data.SqlClient;
using System.IO;

string currentFile = Dts.Variables["User::FileNameVariable"].Value.ToString();
FileInfo currentFileInfo = new FileInfo(currentFile);
//Integrated Security for Windows authentication
string connectionStr = @"Data Source=Server;Initial Catalog=Database;Integrated Security=SSPI;";
string cmd = @"INSERT INTO DATABASE.SCHEMA.FILES ([FILENAME]) VALUES (@file)";

 using (SqlConnection conn = new SqlConnection(connectionStr))
 {
     using (SqlCommand sql = new SqlCommand(cmd, conn))
     {
         SqlParameter pFileName = new SqlParameter("@file", SqlDbType.VarChar);
         pFileName.Direction = ParameterDirection.Input;
         pFileName.Size = 250;
         //use FileInfo.Name to get only file path
         pFileName.Value = currentFileInfo.Name;
         sql.Parameters.Add(pFileName);
         conn.Open();
         //insert file name
         sql.ExecuteNonQuery();
     }
 }

C# Script Task to Delete Old Files:
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;

string outputFolder = Dts.Variables["User::OutputFolder"].Value.ToString();
string filePrefix = Dts.Variables["User::FilePrefix"].Value.ToString();

DirectoryInfo di = new DirectoryInfo(outputFolder);
List<string> currentExecutionFiles = new List<string>();

string connectionStr = @"Data Source=Server;Initial Catalog=Database;Integrated Security=SSPI;";
string cmd = @"SELECT [FILENAME] FROM DATABASE.SCHEMA.FILES";

using (SqlConnection conn = new SqlConnection(connectionStr))
{
    using (SqlCommand sql = new SqlCommand(cmd, conn))
    {
        conn.Open();
        using (SqlDataReader dr = sql.ExecuteReader())
        {
            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    //get file names from table holding names from current execution
                    currentExecutionFiles.Add(dr[0].ToString());
                }
            }
        }
    }
}

foreach (FileInfo fi in di.EnumerateFiles())
{
    //check for file with prefix (case insensitive) that was not in current execution
    if (fi.Name.StartsWith(filePrefix, StringComparison.InvariantCultureIgnoreCase)
                        && !currentExecutionFiles.Contains(fi.Name))
    {
        fi.Delete();
    }
}


text:
Q: Spark MinMaxScaler on dataframe Assuming I have follwoing dataframe
+---+-----+-------+
|day| time| result|
+---+-----+-------+
|  1| 6   |  0.5  |
|  1| 7   |  10.2 |
|  1| 8   |   5.7 |
|  2| 6   |  11.0 |
|  2| 10  |  22.3 |
+---+-----+-------+

I like to normalize the results per day while keeping the time belonging to each result. I like to use MinMaxScaler I assume I have cast the values to dense vector for each day but how I do I keep time values?

A:
I like to normalize the results  (...) I like to use MinMaxScaler

These two requirements are mutually exclusive. MinMaxScaler cannot be used to operate on groups. You can use window functions
from pyspark.sql.functions import min, max, col
from pyspark.sql.window import Window

df = spark.createDataFrame(
    [(1, 6, 0.5), (1, 7, 10.2), (1, 8, 5.7), (2, 6, 11.0), (2, 10, 22.3)],
    ("day", "time", "result"))

w = Window.partitionBy("day")

scaled_result = (col("result") - min("result").over(w)) / (max("result").over(w) - min("result").over(w))

df.withColumn("scaled_result", scaled_result).show()
# +---+----+------+------------------+
# |day|time|result|     scaled_result|
# +---+----+------+------------------+
# |  1|   6|   0.5|               0.0|
# |  1|   7|  10.2|               1.0|
# |  1|   8|   5.7|0.5360824742268042|
# |  2|   6|  11.0|               0.0|
# |  2|  10|  22.3|               1.0|
# +---+----+------+------------------+

or group, aggregate and join:
minmax_result = df.groupBy("day").agg(min("result").alias("min_result"), max("result").alias("max_result"))

minmax_result.join(df, ["day"]).select(
    "day", "time", "result",
     ((col("result") - col("min_result")) / (col("max_result") - col("min_result"))).alias("scaled_result")
).show()
# +---+----+------+------------------+
# |day|time|result|     scaled_result|
# +---+----+------+------------------+
# |  1|   6|   0.5|               0.0|
# |  1|   7|  10.2|               1.0|
# |  1|   8|   5.7|0.5360824742268042|
# |  2|   6|  11.0|               0.0|
# |  2|  10|  22.3|               1.0|
# +---+----+------+------------------+


text:
Q: expected value of an exponential distribution I've been stuck at this problem for hours now. So first I know that the expected value of $X\sim\operatorname{Exponential}(\lambda)$ is $1/\lambda.$ But I can't figure out what the expected value is given this information:
$X\sim\operatorname{Exponential}(3)$ and $Y=\exp(2x)$
So, how do I calculate the $\operatorname E[Y]$? A step by step would be helpful, I've been stuck for hours.

A: First, if $X \sim Exp(\lambda)$, then it has a p.d.f. given by $f_\lambda(x) = \lambda \mathrm{e}^{-\lambda x}$. By the definition of expectation:
$$ \mathrm{E}[Y] = \mathrm{E}[\mathrm{e}^{2X}] = \int_0^\infty \mathrm e^{2x} f_3(x) \mathrm{d} x = 3 \int_0 ^\infty \mathrm{e}^{2x}\mathrm{e}^{ - 3 x}\mathrm d x = 3 \int_0^\infty \mathrm{e}^{-x}\mathrm{d}x = 3.$$

A: Let $X\sim\mathsf{Expo}(\lambda)$ and $Y=e^{aX}$ with $\lambda>a>0$. Then for $y>1$ we have
\begin{align}
\mathbb P(Y\leqslant y) &= \mathbb P\left(e^{aX}\leqslant y\right)\\
&= \mathbb P\left(X\leqslant \frac{\log y}a\right)\\
&= 1 - e^{-\frac{\lambda}a\log y}\\
&= 1 - \left(e^{\log y}\right)^{-\frac\lambda a}\\
&= 1 - y^{-\frac\lambda a}.
\end{align}
It follows that
\begin{align}
\mathbb E[Y] &= \int_1^\infty \left(1-\mathbb P(Y\leqslant y)\right)\ \mathsf dy\\
&= \int_1^\infty y^{-\frac\lambda a}\ \mathsf dy\\
&= \frac\lambda{\lambda-a}.
\end{align}
If $\lambda=3$ and $a=2$ then this is equal to $3$.


text:
Q: Are there any statements considered a proof for any of these conditional statements? The following conditional statements are some of building blocks of a proof I've written:
$$\forall\alpha,A\in\mathbb Z^*,\forall B\in\mathbb Z^+\left(\frac{A}{GCD\left(A,B\right)}=\alpha\rightarrow A=\alpha\times{GCD\left(A,B\right)}\right)$$
$$\forall A,E\in\mathbb Z^*,\forall B,F\in\mathbb Z^+\left(\frac{E}{F}\times\frac{A}{B}=\frac{E\times A}{F\times B}\rightarrow\forall\alpha\in\mathbb Z^*,\forall\beta\in\mathbb Z^+\left(\left(A=\alpha\times GCD\left(A,B\right)\wedge B=\beta\times GCD\left(A,B\right)\right)\rightarrow \frac{E}{F}\times\frac{A}{B}=\frac{E\times\alpha\times GCD\left(A,B\right)}{B\times\beta\times GCD\left(A,B\right)}\right)\right)$$
$$\forall\alpha,A,E\in\mathbb Z^*,\forall\beta,B,F\in\mathbb Z^+\left(\frac{E}{F}\times\frac{A}{B}=\frac{E\times\alpha\times{GCD\left(A,B\right)}}{F\times\beta\times{GCD\left(A,B\right)}}=\frac{E\times\alpha}{F\times\beta}\rightarrow\frac{E}{F}\times\frac{A}{B}=\frac{E\times\alpha}{F\times\beta}\right)$$
$$\forall\alpha,A,C,E\in\mathbb Z^*,\forall\beta,B,D,F\in\mathbb Z^+\left(\frac{E}{F}\times\frac{A}{B}=\frac{E\times\alpha}{F\times\beta}=\frac{E}{F}\times\frac{C}{D}\rightarrow\frac{E}{F}\times\frac{A}{B}=\frac{E}{F}\times\frac{C}{D}\right)$$
Now I need to make sure that none of these statements need to be proved(which seems to me they don't need to), or more accurately there are no statements that can be provided as a proof for any of these, so any tip is appreciated.

A: For the first one, you would need an axiom that relates division and multiplication, because such mathematical operators are not built into logic. So, for example, you could use as an axiom:
$$\forall z \in \mathbb Z^* \forall x,y \in \mathbb Z^+ (\frac{x}{z}=y \leftrightarrow x = y \times z)$$
Also, you need to rewrite an expression like $x=y=z$ (like you have in the third and fourth statements) using a conjunction: $x = y \land y = z$.
Otherwise, the last three statements can all be proven using pure logic ... and with that additional axiom, the first statement can be proven as well ... and the crucial logical inference in all cases is $= Elim$, which states that for any terms $t_1$ and $t_2$, and any formula $\varphi(x)$: if you have a statement $\varphi(t_1)$, as well as a statement $t_1 = t_2$, then you can infer statement $\varphi(t_2)$, where $\varphi(t_2)$ is the result of replacing some or all occurrences of $t_1$ in $\varphi(t_1)$ with $t_2$.
Below, for example, would be the formal proof for the last statement:

*

*Assume $$\alpha,A,C,E\in\mathbb Z^*,\beta,B,D,F\in\mathbb Z^+$$

*Assume $$\frac{E}{F}\times\frac{A}{B}=\frac{E\times\alpha}{F\times\beta} \land \frac{E\times\alpha}{F\times\beta}=\frac{E}{F}\times\frac{C}{D}$$
3.$$\frac{E}{F}\times\frac{A}{B}=\frac{E\times\alpha}{F\times\beta} \qquad(\land \: Elim \: 2)
 $$

*$$\frac{E\times\alpha}{F\times\beta}=\frac{E}{F}\times\frac{C}{D}\qquad(\land \: Elim \: 2)
 $$

*$$\frac{E}{F}\times\frac{A}{B}=\frac{E}{F}\times\frac{C}{D} \qquad(= \: Elim \: 3,4)
 $$

*$$\left(\frac{E}{F}\times\frac{A}{B}=\frac{E\times\alpha}{F\times\beta} \land \frac{E\times\alpha}{F\times\beta}=\frac{E}{F}\times\frac{C}{D}\right)\rightarrow\frac{E}{F}\times\frac{A}{B}=\frac{E}{F}\times\frac{C}{D}\qquad(\rightarrow \: Intro \: 2-5)
 $$

*$$\forall\alpha,A,C,E\in\mathbb Z^*,\forall\beta,B,D,F\in\mathbb Z^+\left(\left(\frac{E}{F}\times\frac{A}{B}=\frac{E\times\alpha}{F\times\beta} \land \frac{E\times\alpha}{F\times\beta}=\frac{E}{F}\times\frac{C}{D}\right)\rightarrow\frac{E}{F}\times\frac{A}{B}=\frac{E}{F}\times\frac{C}{D}\right)\qquad(\forall \: Intro \: 1-6)
 $$


text:
Q: HTTPS SSL Connection not trusted, despite certificate being fine I have got 2 sitest hosted on Windows 2012 R2 IIs 8.5.
One is instance of umbraco while other is .Net core based api (Lets call it MyApi).
I want to perform certain search action on umbraco so umbraco makes call to the api which calls back the Umbraco/Api. Call to the MyApi is fine, however the call from MyApi to the Umbraco/Api is problem. The Umbraco api logs:
Search failed System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
Certificates themselves are provided by our customer's inner authority, which is trusted root in server storage. Now originaly we have had problem with certificates, as they missed first DNS record we use for api call (the DNS records are not created yet, we use record in 'hosts') but that shoud be fiex by now.
I have updated the SSL error handler in the code so it logs an error and number in SSL Enum.
                            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            System.Net.ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) =>
            {
                _logger.LogError("Received TLS errror " + ((int)sslPolicyErrors).ToString());
                return false;
            };

            _logger.LogDebug("Search starting");
            if (model.Username != null)
            {
                model.Favourites = _workplaceContext.GetUserFavourites(_dataContext, model.Username);
            }
            else if (model.JustFavourites)
            {
                return BadRequest();
            }
            using (var client = new HttpClient())
            {

                client.BaseAddress = new Uri(_configuration.GetValue<string>("UmbracoApiUrl"));
                _logger.LogDebug("Searching for addres " + new Uri(_configuration.GetValue<string>("UmbracoApiUrl")));
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
                var json = JsonConvert.SerializeObject(model);
                using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json"))
                {
                    var response = await client.PostAsync("workplace/search", stringContent);
                    if (response.IsSuccessStatusCode)
                    {
                        _logger.LogDebug("Search API Call success");
                        var jsonResponse = await response.Content.ReadAsStringAsync();
                        var responseModel = JsonConvert.DeserializeObject<SearchResponseModel>(jsonResponse);
                        _logger.LogDebug("Search response TotalCount = " + responseModel.TotalCount);
                        return responseModel;
                    }
                    else
                    {
                        _logger.LogDebug("Search API Call status - " + response.StatusCode);
                        return StatusCode((int)response.StatusCode);
                    }
                }
            }

Originaly we received number 2 error. Now we just receive number 0, which should be no problem. Despite that, connections is still not working. I have read various articles regarfding this and enabled troubleshooting through  in web config of umbraco, but haven't found any useful information. I need method to troubleshoot the MyApi. Could somone point me a direction how to troubleshoot it to the similar degree of detail as umbraco (i am not much familiar with .NET core apps)?
The interesting part of error log:
2019-07-08 13:35:32.1745||DEBUG|XXXApi.Controllers.WorkplaceController|Search starting
2019-07-08 13:35:32.1901||DEBUG|XXXApi.Controllers.WorkplaceController|Searching for addres https://xxx.yy.zz/umbraco/api/
2019-07-08 13:35:32.2682||ERROR|XXXCApi.Controllers.WorkplaceController|Received TLS errror 0
2019-07-08 13:35:32.2682||ERROR|XXXApi.Controllers.WorkplaceController|Search failed System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
   at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
   at System.Net.PooledStream.EndWrite(IAsyncResult asyncResult)
   at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
   --- End of inner exception stack trace ---

A: Solution: The original error was in certificate and got fixed, BUT the callback returning false I used for debugging caused problem marking connection unsuccessful. It took like 2 days to figure it out. So since moment i got 0 in enum, it was just bug in my debugging code.
Oh and don't forget to unsubscribe the delgate.


text:
Q: How do I call a function within a function? (CoffeeScript) I have a function I created getData() which is within another function, and when I try to call it I get in the console "getData is not defined". I tried @getData() and that does not work either. Is this even possible to do within the function?
class SomeCollection

   parse: (data) =>

       handleData: (data) ->
          return data

       getData: ->
          Session.ajax
          url: "someurl"
          type: 'get'

       getData().done handleData

I've also tried putting those functions outside of the parse() function but whenever i try to reference getData() or @getData() it always gives me the error that it's not defined.

A: It's not entirely clear what you're trying to do, but change those :s to =s and indent the two lines after Session.ajax, and at least it will make some amount of sense:
class SomeCollection

   parse: (data) =>

       handleData = (data) ->
          return data

       getData = ->
          Session.ajax
             url: "someurl"
             type: 'get'

       getData().done handleData

Your parse method's data parameter is not used anywhere, but hopefully you realize that.

A: Do not use the colon since that's for defining property values. Use an equals sign:
getData = () =>
 alert('hello!');

getData()

JSFiddle Demo: http://jsfiddle.net/etuy0t2c/


text:
Q: Removing a specific element from an object that is located inside a parent element I have the following object:
const jj = {
    "type": "doc",
    "content": [{
        "type": "paragraph",
        "content": [{
            "type": "text",
            "text": "HI  \n"
        }, {
            "type": "text",
            "marks": [{
                "type": "link",
                "attrs": {
                    "href": "https://infosysta-my.sharepoint.com/:x:/p/elie%5Fiskandar/EXmik99OQBBNiJua1zbbiUIBwU8QEVOzyXl3qRV3ZnhADw",
                    "__confluenceMetadata": null
                }
            }],
            "text": "Client List - MW.xlsx"
        }]
    }, {
        "type": "paragraph",
        "content": [{
            "type": "text",
            "text": "regards,"
        }]
    }],
    "version": 1
};

I need to remove the "__confluenceMetadata":null key/value so the new object will be:
const jj = {
    "type": "doc",
    "content": [{
        "type": "paragraph",
        "content": [{
            "type": "text",
            "text": "HI  \n"
        }, {
            "type": "text",
            "marks": [{
                "type": "link",
                "attrs": {
                    "href": "https://infosysta-my.sharepoint.com/:x:/p/elie%5Fiskandar/EXmik99OQBBNiJua1zbbiUIBwU8QEVOzyXl3qRV3ZnhADw"
                }
            }],
            "text": "Client List - MW.xlsx"
        }]
    }, {
        "type": "paragraph",
        "content": [{
            "type": "text",
            "text": "regards,"
        }]
    }],
    "version": 1
};

I tired to iterate through the elements using let arr = Object.entries(ADFDocJson); but I couldn't reach what I needed.
I am looking for a generic method to use as this is just an example object and there might be multiple objects in the marks array.

A: Presented below is one possible way to achieve the desired objective.
Code Snippet

const removeMeta = argObj => (
  Object.fromEntries(
    Object.entries(argObj)
    .map(([k, v]) => (
      k !== 'content'
      ? ([k, v])
      : ([k, (
        v.map(ob1 => (
          !('content' in ob1)
          ? ({...ob1})
          : ({...ob1,
            content: ob1.content.map(
              ob2 => (
                !('marks' in ob2)
                ? ({ ...ob2 })
                : ({ ...ob2,
                  marks: ob2.marks.map(ob3 => (
                    !('attrs' in ob3 &&
                    '__confluenceMetadata' in ob3.attrs &&
                    ob3.attrs['__confluenceMetadata'] === null
                    )
                    ? ({ ...ob3 })
                    : ({ ...ob3,
                      attrs: Object.fromEntries(
                        Object.entries(ob3.attrs)
                        .filter(
                          (
                            [k2, v2]
                          ) => (
                            k2 !== '__confluenceMetadata'
                          )
                        )
                      )
                    })
                  ))
                })
              )
            )
          })
        ))
      )])
    ))
  )
);
const jj = {
    "type": "doc",
    "content": [{
        "type": "paragraph",
        "content": [{
            "type": "text",
            "text": "HI  \n"
        }, {
            "type": "text",
            "marks": [{
                "type": "link",
                "attrs": {
                    "href": "https://infosysta-my.sharepoint.com/:x:/p/elie%5Fiskandar/EXmik99OQBBNiJua1zbbiUIBwU8QEVOzyXl3qRV3ZnhADw",
                    "__confluenceMetadata": null
                }
            }],
            "text": "Client List - MW.xlsx"
        }]
    }, {
        "type": "paragraph",
        "content": [{
            "type": "text",
            "text": "regards,"
        }]
    }],
    "version": 1
};

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

Explanation
Iterate over the various key-value pairs of the object, and then iterate over the nested 'content' arrays, identify the relevant prop and filter it out.


text:
Q: Why is it okay to do this? I am studying asymptotic recurrences for algorithms, and the book says:
$$T(n) = 2T(n/2) + \Theta (n)$$
is technically
$$T(n) = T(\lfloor n/2 \rfloor) + T(\lceil n/2 \rceil) + \Theta (n)$$
for an algorithm (e.g. Mergesort). However apparently it's okay to analyze the running time using the first recurrence. Why is it okay to approximate the second recurrence with the first one?

A: You are interested in the asymptotic behaviour; you can show that any $T$ satisfying the second relation is monotone (increasing), and then you can use the "sandwiching" theorem to relate solutions to the second to solutions to the first —up to some term which will, in hindsight (once you have the solution to the first relation) prove to be negligible.


text:
Q: Observing Task exceptions within a ContinueWith There are various ways in which to observe exceptions thrown within tasks.  One of them is in a ContinueWith with OnlyOnFaulted:
var task = Task.Factory.StartNew(() =>
{
    // Throws an exception
    // (possibly from within another task spawned from within this task)
});

var failureTask = task.ContinueWith((t) =>
{
    // Flatten and loop (since there could have been multiple tasks)
    foreach (var ex in t.Exception.Flatten().InnerExceptions)
        Console.WriteLine(ex.Message);
}, TaskContinuationOptions.OnlyOnFaulted);

My question:  Do the exceptions become automatically observed once failureTask begins or do they only become observed once I 'touch' ex.Message?

A: sample
Task.Factory.StartNew(testMethod).ContinueWith(p =>
            {
                if (p.Exception != null)
                    p.Exception.Handle(x =>
                        {
                            Console.WriteLine(x.Message);
                            return false;
                        });
            });

A: They are viewed as observed once you access the Exception property.
See also AggregateException.Handle.  You can use t.Exception.Handle instead:
t.Exception.Handle(exception =>
            {
            Console.WriteLine(exception);
            return true;
            }
    );


text:
Q: Unbound Prefix Error when XML Parsing in Eclipse I want to add Toolbar widget to my application. So when I add xml code to layout file I got Unbound prefix error. What should I do to solve this?
My layout.xml
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.dizikolikk.MainActivity" >

<android.support.v7.widget.Toolbar

   android:id="@+id/my_toolbar"
   android:layout_width="match_parent"
   android:layout_height="?attr/actionBarSize"
   android:background="?attr/colorPrimary"
   android:elevation="4dp"
   android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
   app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

</RelativeLayout>

A: This error occurs when you use an undefined namespace in your XML layout (in this case it's the 'app' namespace)
You need to add
xmlns:app="http://schemas.android.com/apk/res-auto"

to your XML layout.


text:
Q: $().next() returning the same element multiple times I tried to name the title as best I could. A little difficult for me to explain.
I'm having an issue with some code I'm writing (which runs in a widget on my wordpress site.) What I've written here emulates this issue. Just fyi I'm very new to jquery, JS, etc.
What I'm trying to do is set the variable "thumb" to the element after "widget-code". It works, however it's only finding that element ("thumb-class") in "wordpress-post1"
The console output is:
wordpress-post1
wordpress-post1
wordpress-post1

But it should be:
wordpress-post1
wordpress-post2
wordpress-post3

This is the actual code

I'm going to try and clarify a little more:
This code is placed in an html widget which the wordpress theme I'm using provides. It hooks into each post. This is the only place I can put code, and this is the only code I've written. (I haven't altered the theme's files in any way.)
I have no control over the name of the classes or IDs. And they're dynamic. An unlimited number of posts could exist. Therefore I can't hardcode anything.
In order for this code to work correctly it'll need to find the sibling of the "widget-code" element in only the post it's running from.
This is the link to the code on JSFiddle: http://jsfiddle.net/pattnvy3/
Would appreciate any help on the matter.

A: This can help if you want to have multiple IDs:
$(document).ready(function(){
    $("[id^=widget-code]").each(function(){
        console.log(this.parentElement.className);
    });
});

But, still multiple same Ids are not recommended.
FIDDLE
Update: Declare a global variable var i=0; and keep increment it like :

DEMO

A: As per the immediate comments, it is invalid markup to use an id for multiple elements.  That said, changing your id to a class such that:

would allow you to to a jQuery selector like so:
$('.widget-code').each(function (){
    var thumb = $(this).next();
    console.log(thumb[0].parentElement.className);
});

However, if I may make a recommendation, I would say that you tag each of your wordpress-post divs with the class "wordpress-post" and then have a more specific id which is the value you want to print.
Then it would look like this:

and your javascript like this (with jQuery):
$('.widget-code').each(function (){
    var post = $(this).closest('.wordpress-post');
    console.log(post.attr('id'));
});

or even simpler:
$('.wordpress-post').each(function (){
    console.log($(this).attr('id'));
});

depending on the needs you have.   If you have any questions as to what you need, feel free to comment and I will get back to you as soon as I can.

A: A pure javascript method:
This is just a workaround since you have no control over ids or classes, this will target all div elements on the page, loop through them and search for any that contains wordpress-post in the class name.

window.onload=function(){
var posts=document.getElementsByTagName('div');
 for(var i=0; i<posts.length; i++){
   if(posts[i].className.indexOf("wordpress-post")> -1){
     console.log(posts[i].className);
     //Snippet Use
     alert(posts[i].className);
   }
}}

If you have any questions, please leave a comment below and I will get back to you as soon as possible.
I hope this helps. Happy coding!

A: If you want a nasty hack, try

Demo: Fiddle
It will give the container class wordpress-post1, then you can use it to find any of the descendant element.


text:
Q: How do I expand variables in a string? I have two files named proc and env.
In proc:
python -m SimpleHTTPServer $PORT

In env:
PORT=8080

I need to echo the following string (don't exec it) without knowing PORT in file
python -m SimpleHTTPServer 8080

*

*export $(cat env) can help me load env.

*eval $(cat proc) can help me exec it (which I don't need).

*${!var} maybe useful to expand $PORT, but I don't know how to use it.

A: You could source the env file, export the PORT variable and use envsubst to substitute the variable in proc.
This is run in a subshell to keep your environment clean.
(. ./env; export PORT; envsubst '$PORT' <proc)

Output:
python -m SimpleHTTPServer 8080

A: If you don't have envsubst, you can use this little one-liner, which works on any POSIX shell.
$ . ./env; eval echo $(cat proc)
python -m SimpleHTTPServer 8080

All caveats about eval apply, i.e. you should make sure proc is safe to eval without unwanted side-effects. Limitations: will work only with a one line proc and may change some white-space between arguments to a single blank.

A: You can use the follow command:
export $(cat env) && eval echo $(cat proc)


text:
Q: STL priority_queue copies comparator class I'm trying to create a priority queue with a custom comparator:
std::priority_queue<int, std::vector<int>, MyComparator> pq;

My problem is that MyComparator has a method that stores additional state. Because MyComparator is copied to the priority queue (as far as I can tell), there's no way for me to call this method on the MyComparator instance held by the priority queue. Is there any way to either:

*

*get access to the MyComparator instance held by the priority queue, or:

*somehow pass the original MyComparator instance in by reference

A: Comparison objects used in STL containers as well as predicates used in STL algorithms must be copyable objects and methods and algorthims are free to copy these functions however they wish.
What this means is that if your comparison object contains state, this state must be copied correctly so you may need to provide a suitable copy constructor and copy assignment operator.
If you want your comparison object to containt mutable state then the problem is more complex as any copies of your comparison object need to share the mutable state. If you can maintain the state as a separate object then you can have your comparison objects keep a pointer to this external state; if not you will probably find that you need shared ownership of the common state so you will probably require something like tr1::shared_ptr to manage this.

A: I've run into this before myself with std::sort's comparator template argument.  Defining a proper copy constructor should do the trick, e.g.:
class MyComparator
{
    public:

        MyComparator(const MyComparator& other)
        {
            // copy members
        }

        // ...
};

Unless your comparator class is heavy (and if so, that leads to plenty of other questions..) it shouldn't cause much of an issue.

A: This is disgusting, but you could give your MyComparator a static MyComparator* me member and then overload the copy constructor to assign this pointer to this. There may be a better way, but nothing comes to mind.

A: You can try specifying a reference type in the template specialisation:
std::priority_queue<int, std::vector<int>, MyComparator&> pq;

But IIRC there are cases where this still doesn't work and STL implementations may force a copy anyway. I'm not sure from your question if maybe you need to define a copy constructor/assignment operator to copy whatever the internal state is, although that's painful if it's expensive to copy.


text:
Q: Regex for replacing commas only within square brackets I have a text file and it contains comma separated strings.  But some of the strings separated by commas are of the form [*,*,*,...].  So for example:
"Hello", "Goodbye", ["Yes", "No", "Maybe], "Indeed", ["Why", "What"]
I want to be able to parse the file to replace only commas within square brackets with a semicolon.  There can be any number of brackets and any number of commas within the brackets.
I tried using this code in R but its not working as planned, some commas outside my brackets are being replaced:
repeat{
          tmp <- gsub("(\\[.*\\K),(?=.*\\])", ";", tmp, perl = TRUE) # replace last comma found within braces with semicolon
          if (sum(grepl("(\\[.*\\K),(?=.*\\])", tmp, perl = TRUE)) == 0) {  # repeat until no more commas found
            break
          }
        }

Can anyone help with regex that can solve this problem?  Thanks!

A: To replace all commas inside square brackets with semi-colons, you may use
gsub("(?:\\G(?!^)|\\[)[^][,]*\\K,", ";", x, perl=TRUE)

See the regex demo. The regex above does not check for the closing ] though. If it is required, use
gsub("(?:\\G(?!^)|\\[)[^][,]*\\K,(?=[^][]*])", ";", x, perl=TRUE)

See another regex demo
Details

*

*(?:\G(?!^)|\[) - end of the previous match (\G(?!^)) or (|) a [ (\[)

*[^][,]* - 0+ chars other than [ and ] and a ]

*\K - match reset operator that discards all the text matched so far

*, - a comma

*(?=[^][]*]) - a positive lookahead that requires 0+ chars other than [ and ] and a ] immediately to the right of the current location.


text:
Q: Query all child columns I have the following kind of setup with one-to-many relationships:
class Parent(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  children_a = db.relationship("ChildA", backref="parent", lazy="dynamic")
  children_b = db.relationship("ChildB", backref="parent", lazy="dynamic")
  children_c = db.relationship("ChildC", backref="parent", lazy="dynamic")

class ChildA(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  # Some other properties
  parent_id = db.Column(db.Integer, db.ForeignKey("parent.id"))

class ChildB(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  # Some other properties
  parent_id = db.Column(db.Integer, db.ForeignKey("parent.id"))

# etc..

What I want to do is get a combined list of all children of a Parent instance.
The only way I can think of doing it would be querying each of the relationships separately and then combining them into a single list, but I doubt that's a very good way to go about it.
Is there a better way to do it?

A: I solved it by using joined table inheritance.


text:
Q: BareOS delete old backup and free up space BareOS - drive full. How do I delete (cancel with bconsole) old jobs?
In this case I want to completely remote job #11030 and free that disk space up. How?
When I use bconsole's disable job=11030 is gives me "not found".


text:
Q: not able to position text over image in a flex item I'm trying to position some text to the bottom right corner of an image that's in a flex layout. It doesn't seem to be working. I'm very new to flex and am making a lot of mistakes. I have a left column and a right column, both of which contact 6 rows of 2 images. In the middle I have some explanatory text. I want the numbers 1 through 12 to be superimposed on the lower right corner of each image.
html:

1

12 people to meet in 2018

css:
.flexbox-container {
        display:flex;
        flex-wrap:wrap;
        flex-direction:row;
        align-items:stretch;
        align-items: flex-start;
        justify-content: space-between;
    }
    .flexbox-2col-container {
        flex: 2;
        display:flex;
        flex-wrap:wrap;
        flex-direction:row;
        align-items:stretch;
        justify-content: space-between;
    }
    .flexbox-1widecol-container {
        flex: 1;

        padding: 10px;

    }
        h3 {
            font-family: Roboto, sans-serif;
            font-weight: 600;

        }
    .column50perc {
        width: 50%;
        padding: 10px 5px 0 5px;
        justify-content: space-between;
    }
    img {
        cursor: pointer;
        position: relative;
        display:block;
    }
    img:hover {

    }
    .middle {

    }
    .middle h3 {
        background-color: #404040;
        color: white;
    }
    .number {
        position: absolute;
        display: inline-block;
        bottom: 0;
        right: 0;
        background-color: black;
        color: white;
        z-index: 2;
        width: 50px;
        height: 50px;
    }

Please let me know what I'm doing wrong.

A: You are using absolute position so you should make the parent element relative position. Like that each box will be positioned relatively to his container and thus correctly positioned on the image:

.flexbox-container {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  align-items: stretch;
  align-items: flex-start;
  justify-content: space-between;
}

.flexbox-2col-container {
  flex: 2;
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  align-items: stretch;
  justify-content: space-between;
}

.flexbox-1widecol-container {
  flex: 1;
  padding: 10px;
}

h3 {
  font-family: Roboto, sans-serif;
  font-weight: 600;
}

.column50perc {
  padding: 10px 5px 0 5px;
  justify-content: space-between;
  position: relative;
}

img {
  cursor: pointer;
  position: relative;
  display: block;
}

img:hover {}

.middle {}

.middle h3 {
  background-color: #404040;
  color: white;
}

.number {
  position: absolute;
  display: inline-block;
  bottom: 0;
  right: 0;
  background-color: black;
  color: white;
  z-index: 2;
  width: 50px;
  height: 50px;
}

1

2

3

12 people to meet in 2018


text:
Q: Is there any short way to add multiple items I am adding data to table. Table looks like this:

I am getting multiple data from my JSP page that should be entered uniquely each time.
Means in table prod_id and sc_id will remain same for this request.
Suppose I am getting 3 items then I have to use 3 insert query that will pass each item one by one.
I am using JSP and sevlet for this.
So my question is that is there any unique or other way to do so using single INSERT statement?

A: In mMSQL you can insert multiple rows in one insert command:
http://dev.mysql.com/doc/refman/5.5/en/insert.html
For example:

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);


text:
Q: Automorphism group of flag manifolds? If $F=F(n_1, \ldots, n_k)$ is the (complex) flag variety associated to the partition $(n_1, \ldots, n_k)$, what is the automorphism group of $F$? Here I mean holomorphic and/or variety automorphisms.
In the simplest case of $\mathbb{CP}^n$ this is just $PGL_{n+1}(\mathbb{C})$, though the proof relies on knowing that the Picard group of $\mathbb{CP}^n$ is $\mathbb{Z}$. I'm not even sure what to expect for the next-simplest case of Grassmannians. There's always a sizeable action of a general linear group, but I don't know if it's onto.
Sorry if this is well-known but I haven't been able to find the answer anywhere. If it's so well-known that I should be ashamed, then I'd also ask: is it known for flags of type other than $A$?

A: Claudio's answer settles the determination of $\mathrm{Aut}^{\mathrm{o}}(F)$; that of $\mathrm{Aut}(F)$ is more subtle. For Grassmannians this is a classical result of Chow (Ann. of Math. (2) 50 (1949), 32-67): $\mathrm{Aut}(\mathbb{G}(p,n))$ is connected (hence equal to $\mathrm{GL}(n)$) except in the case $n=2p$, where $\pi _0(\mathrm{Aut}(\mathbb{G}(p,2p ))=\mathbb{Z}/2$. This has been extended to all flag varieties by Tango: On the automorphisms of flag manifolds.
Bull. Kyoto Univ. Ed. Ser. B No. 49 (1976), 1-9. He proves that the automorphism group of $\mathbb{F}(n;n_1,\ldots ,n_k)$ is connected except in the case $n_i+n_{k-i}=n$ for all $k$,  where it has 2 components.

A: Irreducible complex flag manifolds are of the form $X=G/P=G_u/K$ where $G$ is a complex simple Lie group and $P$ is a parabolic subgroup, and $G_u$ is a compact
real form of $G$ and $K=P\cap G_u$. As a rule, the connnected automorphism group $Aut^0(X)$ coincides with $G$, with the only exceptions:

*

*$X=G_2/U_2$, $Aut^0(X)=SO_7(\mathbb C)$.

*$X=Sp_r/Sp_{r-1}U_1$, $Aut^0(X)=PSL_{2r}(\mathbb C)$.

*$X=SO_{2r+1}/U_r$, $Aut^0(X)=PSO_{2r+2}(\mathbb C)$.

You can find a discussion in chapters 3 and 4 in Lie group actions in complex analysis, by Dmitri N. Akhiezer, Aspects of Mathematics, vol. E27, Friedr. Vieweg, Braunschweig and Wiesbaden, 1995.
Edit: Thanks to abx for the further explanations and original papers.
I just wanted to point out that the reducible case and the full automorphism group are also discussed in the book by Akhiezer. In the reducible case,
the connected automorphism group splits as the direct product of the connected automorphism groups of the factors. Moreover $Aut(X)$ is the semidirect product
of $Aut^0(X)$ by a finite group isomorphic to the subgroup of the automorphism group of the Dynkin diagram of the complex semisimple Lie group $Aut^0(X)$ preserving the vertices corresponding to the parabolic subalgebra.

A: While the question and answers have explained different aspects of the story for complex groups and homogeneous spaces, it might be worthwhile to place the question in a broader context.  The complex groups here can just as well be regarded as algebraic groups, with the underlying field algebraically closed of any characteristic.   The picture is remarkably similar in all cases, though expressed in somewhat different language.    In any case, for any homogeneous space the starting point is the ambient group acting naturally, but there may be further automorphisms.
Two classical references of interest are available online (though in French).   Both are rather short but also somewhat sophisticated:
Demazure treated flag varieties in the context of algebraic geometry here.  As he remarks, the complex situation had already been handled by Tits here.
The varieties or manifolds of interest all have the form $G/P$ but can be studied from different angles.   Aside from this, I've added a tag tp emphasixe the group-theoretic setting.

A: See the paper by Srinivas and Paranjape, Inventiones mathematicae , 1998, vol 2. That paper addresses precisely this question.


text:
Q: I want to add Appium (Script)Recording & Playback Functionality in Project is it possible as we know Appium has functionality to generate script for Mobile Testing. actually I want to to add this functionality in project. is it possible using java.

A: You have to implement the functionality by yourself, probably build a full app.
Appium-Desktop is s Node.js application, if you are familiar with js you can get idea for implementation from source code


text:
Q: how to move files located in on-premises windows based file share using scala? Background : I am using Azure ADFV2 to move data from fileshare to ADLS, after the file is moved successfully I want to archive the file within fileshare location.
How do I connect to on-premises windows based file share and move the files from one folder to another within the fileshare using scala. I am not sure how to establish the connectivity to a file share.

A: You can use file system linked service to establish the connectivity to a file share.

*

*create a self-hosted integration runtime on ADF and install it on your machine.

*create a file system linked service, and for "Connect via integration runtime" field, choose the self-hosted ir you created in 1.

*configure you linked service and dataset as the doc instructs: https://learn.microsoft.com/en-us/azure/data-factory/connector-file-system


text:
Q: Command not found when trying to run a nodeschool lesson I'm not sure if this is purposeful but when running the...
npm install learnyounode -g

..command in terminal, the module is being created in my home directory. When I try to run the 'learnyounode' command from the directory that I run the npm install from I get the message 'command not found'. I've looked in the usr directory but the learnyounode directory is not in there.
After everything intalls I get the following output
/Users/username/npm/bin/learnyounode -> /Users/username/npm/lib/node_modules/learnyounode/learnyounode.js
learnyounode@0.4.1 /Users/username/npm/lib/node_modules/learnyounode
├── duplexer@0.1.1
├── through@2.3.4
├── boganipsum@0.1.0
├── hyperquest@0.1.8 (through@2.2.7)
├── concat-stream@1.2.1 (bops@0.0.6)
├── bl@0.6.0 (readable-stream@1.0.26)
├── through2-map@1.2.1 (through2@0.2.3, terminus@1.0.9)
└── workshopper@0.7.2 (map-async@0.1.1, tuple-stream@0.0.2, split@0.2.10, mkdirp@0.3.5,     xtend@2.1.2, colors-tmpl@0.1.0, terminal-menu@0.2.0, optimist@0.6.1, msee@0.1.1)

ps. I have a fresh install of node in my usr folder. I am more concerned that this problem is going to happen when I want to install other packages via NPM in the future.

A: I installed without the -g flag and it installed globally.

A: Trying to install learnyounode,
This path returns:
/Library/Frameworks/Python.framework/Versions/2.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin


text:
Q: Unclear algorithm requirement I don't know if this task is familiar to you, but I have to admit that it is unclear to me. If anyone has met, please explain to me. I'm not looking for a solution, just a clarification of what is required. Thank you.
Task:
For a random array of structs of type {id, value }, return a new struct, with an unique
id and a value such as the next positive integer, which isn't present in the existing
structure list and with at least one smaller integer appearing at least twice in the
same list.
For example:
a = [{id:1, value:3}, {id:2, value:7}, {id:3, value:3}, {id:4, value:1}, {id:5, value:4}]
value 1 - appears once
value 3 - appears 2 times
value 4 - appears once
value 7 - appears once
Solution: {id: 6, value: 5}
About id everything is clear, but does value (in this case 5) is there because 3x2 is 6 and value needs to be smaller than (in this case) 6?

A: You have a list of structures, each with an id and a value. You need to create a new structure with a unique id and a value such that the value is the smallest positive integer that is not already present in the list, and at least one smaller integer appears at least twice in the list.
For example, given the list of structures a:
[
  {id: 1, value: 3},
  {id: 2, value: 7},
  {id: 3, value: 3},
  {id: 4, value: 1},
  {id: 5, value: 4}
]

The value 1 appears once, the value 3 appears twice, the value 4 appears once, and the value 7 appears once. Therefore, the solution would be a new structure with {id: 6, value: 5}, because 5 is the smallest positive integer that is not already present in the list and at least one smaller integer (in this case, 3) appears at least twice in the list.
If {id: 6, value: 5} was appended to list a, then the next solution would be {id: 7, value: 6} because 6 is the smallest integer that does not appear as a value that also has a smaller integer that appears twice (3 again.)


text:
Q: PHP DOM LoadXML processing infinite loop when xml has parse errors How to stop the loop when xml data have parse errors?
//xml data <column><col>Col1</col><col>Col2</col><col>Col3</col><column>

$xml = new DOMDocument();
$xml->loadXML($item_xml);

//loads the data
// find column
if(!empty(   $xml->documentElement)){
   foreach(  $xml->documentElement->childNodes as $xmlChild){
          if($xmlChild->nodeName == 'column'){
             return $xmlChild;
         }
    }
}

If any XMl parse errors. it continuously process without throwing any exception.
How to avoid if xml parse errors?

A: You can use libxml_get_errors():
$xml = new DOMDocument();

// Don't display errors and warnings
$errorState = libxml_use_internal_errors(TRUE);

// Load the XML now
$xml->loadXML($item_xml);

// Get all the errors, as an array
$errors = libxml_get_errors();

// If the array is not empty
if(!empty($errors)) {
    // Markup contains error(s)
}

Demo


text:
Q: Customise Custom tooltips WPF / Silverlight I have a custom tooltip style which works great, but, on some occassions I want to be able to hide the arrow (the Path section) or position the tooltip differently.  How can I achieve that and how would I set it in practice? 99% of the time Tooltips are set via XAML & Bindings but occasionally they are set using code and the ToolTipService
<Style x:Key="{x:Type ToolTip}"
       TargetType="ToolTip">
  <Setter Property="OverridesDefaultStyle"
          Value="true" />
  <Setter Property="HasDropShadow"
          Value="True" />
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="ToolTip">
        <StackPanel>
          <Border CornerRadius="3"
                  HorizontalAlignment="Center"
                  VerticalAlignment="Top"
                  Padding="10,7"
                  BorderThickness="0"
                  Background="#e5323232">
            <StackPanel>
              <TextBlock FontFamily="Arial"
                         FontSize="12"
                         Text="{TemplateBinding Content}"
                         Foreground="#f0f0f0" />
            </StackPanel>
          </Border>
          <Path Margin="10,0,0,0"
                Fill="#e5323232"
                Data="M 0 0 L 6 6 L 12 0 Z" />
        </StackPanel>
      </ControlTemplate>
    </Setter.Value>
  </Setter>

  <Setter Property="Placement"
          Value="Top" />
  <Setter Property="HorizontalOffset"
          Value="-8" />
  <Setter Property="VerticalOffset"
          Value="0" />
</Style>

A: You may be able to put these controls on.
<Path Margin="10,-0.5,0,0" Fill="#e5323232" Data="M 0 0 L 6 6 L 12 0 Z"/>

A: I want to show tool tip at dynamic position so I found following solutions.
Firstly i have added one user control "SimplePopupContent " as
public partial class SimplePopupContent : UserControl
    {
        public SimplePopupContent(string value)
        {
            InitializeComponent();
            textBlockPopUp.Text = value;
        }

        private void LayoutRoot_MouseLeave(object sender, MouseEventArgs e)
        {
            this.Visibility = Visibility.Collapsed;
        }
    }

I want to show tool tip for textblock.
TextBlock t = new TextBlock();
Popup simplePopup = new Popup();

And I have written code on mouse enter event of textblock as
t.MouseEnter += (s, args) =>
                            {
                                this.simplePopup.Child = new SimplePopupContent("Hi");
                             this.simplePopup.Margin = new Thickness(XOffset ,70, 0,0);
                              this.simplePopup.Width = 30;
                                this.simplePopup.Child.MouseLeave += new MouseEventHandler(Child_MouseLeave);
                                this.simplePopup.IsOpen = true;
                            };

And
public void Child_MouseLeave(object sender, MouseEventArgs e)
        {
           this.simplePopup.IsOpen = false;

        }

Hope this will help you.


text:
Q: KIVY_VIDEO provider not selecting ffpyplayer I'm trying to run the share/kivy-examples/demo/kivy-catalog example on Ubuntu 18.04.
I keep getting
[INFO   ] [Video       ] Provider: gstplayer
[WARNING] [Image       ] Unable to load image </home/erik/anaconda3/envs/kivyenv/share/kivy-examples/widgets/cityCC0.mpg>
[ERROR  ] [Image       ] Error loading texture ../../widgets/cityCC0.mpg
...
[WARNING] [MTD         ] Unable to open device "/dev/input/event6". Please ensure you have the appropriate permissions.
[WARNING] [VideoGstplayer] b"No decoder available for type 'video/mpeg, systemstream=(boolean)true, mpegversion=(int)1'."
[ERROR  ] [VideoGstplayer] b'Your GStreamer installation is missing a plug-in.'
[ERROR  ] [VideoGstplayer] b'Internal data stream error.'

despite having Gstreamer (or atleast the good/bad/ugly, whatever that is). The installation page notes that Gstreamer is not included, but I checked with apt list --installed *gstreamer* that I have those packages.
Then I tried to use ffpyplayer - I've set the environment variable in the terminal using KIVY_VIDEO=ffpyplayer and even in the python file  via
os.environ['KIVY_VIDEO'] = 'ffpyplayer'
But kivy keeps using gstplayer, as seen in the [INFO] line above.
How can I either get this to work with gstreamer/gstplayer or get kivy to use ffpyplayer? I installed the latter with pip.
I also installed the ubuntu-restricted-extras after seeing this and this
All the simpler kivy examples have worked so far ("hello world").
This link says not to worry about the permissions warning on "/dev/input/event6", so I won't.

A: I more closely examined my installation. I realized from the install page that kivy requires python < 3.8. I removed my virtual environment, and created a new one using python 3.7. conda install kivy -c conda-forge  downloaded gstreamer and gst-plugins-base along with kivy. I can now run sll but the media section the kivycatalog/main.py
The media section of the catalog still shows warnings and errors in the terminal, the same as before.


text:
Q: iPhone's Safari: why geolocation prompt appears twice? Consider the following iPhone scenario:

*

*Select Settings->General->Reset->Reset Location & Privacy (just to ensure all warnings are cleared as a preparation to this test)

*Open Safari and point to http://maps.google.com

*Select OK when ["Safari" would like to use your current location] message appears.

*Select OK again when ["https://maps.google.com" would like to use your current location] message appears right after.

So far so good. Now scroll up so you can see the URL box of Safari, and select the reload button (the rounded arrow next to the URL). This will resubmit the form and will cause the message on step 4 to appear again! (at least on my iOS 6, iPhone 5 device)
Any idea why message appears again after I already confirmed "https://maps.google.com" to use my current location? Is this a known issue?
I encountered this issue in my iPhone based app using UIWebView so I decided to check the same scenario using the built-in Safari app. I was very surprised to find out that this happens with Safari app as well...
Any help will be most appreciated.

A: I believe it's because of 2 different types of geo location firing. First you have the native w3c with the safari request and then the Phonegap call from within the browser. I'm having the same issue.
My problem is that he geolocation in google maps will only  once after resetting the location and privacy settings. Figured out that google has set some restrictions in the fine print. Exploring some open source mappi g options right now (Openstreetmap) which will accept my google kml files.


text:
Q: Cavalieri's principle for a 3 dimensional sphere By using Cavalieri's principle (Measure Theory) i want to prove for $R \geq 0$ and $B_R=\{(x,y,z) \in \mathbb{R}^n : x^2+y^2+z^2 \leq R^2\}$ that
$\lambda_3(B_R) = \frac{4}{3}\pi R^3$.
I already proved for $K=\{(x,y)\in \mathbb{R}^2 : x^2+y^2 \leq R^2\}$ that
$\lambda_2(K)=\pi R^2$.
I know i can use this to prove $\lambda_3(B_R)$ but in which way?

A: Using Cavalieri's principle you need to calculate

*

*$\int_{-R}^R\lambda_2(K(z))\;dz$ where

*$\lambda_2(K(z))= \pi r^2(z) = \pi (R^2-z^2)$
Now, evaluating gives immediately
$$\pi\int_{-R}^R(R^2-z^2)\;dz =\frac{4}{3}\pi R^3$$


text:
Q: ASP.NET MVC2 Can't get full id of element I have this strongly typed view form for my model. Problem is that I can't seem to get the IDs right. My view model has form models within it so I have to call some elements like:
<%: Html.TextBoxFor(m => m.Business.Business2)%>

Problem is with this code:
viewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(partialFieldName)

If my partialFieldName is "Business2" it should return "Business_Business2" but it only returns "Business2". However, if I use
<%: Html.EditorFor(x => x.Business) %>

it returns "Business_Business2". I can't use Html.EditorFor since I have css classes to place on my form elements. I can't do much of my client side validations without the right Id so this has really been bugging me. Any ideas?
Here are my codes:
Models
public class BusinessModel
    {
        public string Business1 { get; set; }
        public string Business2 { get; set; }
    }

    public class AccountModel
    {
        public string Account1 { get; set; }

        [MustMatch("Account1")]
        public string Account2 { get; set; }
    }

    public class SampleWrappedModel
    {
        public BusinessModel Business { get; set; }
        public AccountModel Account { get; set; }
    }

Validations
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public sealed class MustMatchAttribute : ValidationAttribute
    {
        private const string DefaultErrorMessage = "Must match {0}";

        public MustMatchAttribute(string propertyToMatch)
            : base(DefaultErrorMessage)
        {
            PropertyToMatch = propertyToMatch;
        }

        public string PropertyToMatch { get; private set; }

        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, PropertyToMatch);
        }

        public override bool IsValid(object value)
        {
            throw new Exception("MustMatchAttribute requires the DataAnnotationsMustMatchValidator adapter to be registered");
        }
    }

    //Adapter class
    public class DataAnnotationsMustMatchValidator : DataAnnotationsModelValidator<MustMatchAttribute>
    {
        public DataAnnotationsMustMatchValidator(ModelMetadata metadata, ControllerContext context, MustMatchAttribute attribute)
            : base(metadata, context, attribute)
        {
        }

        public override System.Collections.Generic.IEnumerable<ModelValidationResult> Validate(object container)
        {
            var propertyToMatch = Metadata.ContainerType.GetProperty(Attribute.PropertyToMatch);
            if (propertyToMatch != null)
            {
                var valueToMatch = propertyToMatch.GetValue(container, null);
                var value = Metadata.Model;

                bool valid = Equals(value, valueToMatch);
                if (!valid)
                {
                    yield return new ModelValidationResult { Message = ErrorMessage };
                }
            }
        }

        public override System.Collections.Generic.IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            string propertyIdToMatch = GetFullHtmlFieldId(Attribute.PropertyToMatch);
            yield return new ModelClientMustMatchValidationRule(ErrorMessage, propertyIdToMatch);
        }

        private string GetFullHtmlFieldId(string partialFieldName)
        {
            ViewContext viewContext = (ViewContext)ControllerContext;
            return viewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(partialFieldName);
        }
    }

    public class ModelClientMustMatchValidationRule : ModelClientValidationRule
    {
        public ModelClientMustMatchValidationRule(string errorMessage, string propertyIdToMatch)
        {
            ErrorMessage = errorMessage;

            ValidationType = "mustMatch";

            ValidationParameters.Add("propertyIdToMatch", propertyIdToMatch);
        }
    }

A: What the TemplateInfo does with GetFullHtmlFieldName and GetFullHtmlFieldId methods, is simply prepending HtmlFieldPrefix to passed partialFieldName. If I understood correctly, you need kind of helper able to return html field name from labmda expression
 public static string GetHtmlFieldName<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
 {
     return ExpressionHelper.GetExpressionText(expression);
 }

And then you could use
Html.GetHtmlFieldName(m => m.Business.Business2)

This will return Business.Business2

A:
I can't use Html.EditorFor since I have css classes to place on my form elements.

You could write a custom editor template then. So in your view:
<%: Html.EditorFor(x => x.Business) %>

and then inside ~/Views/Shared/EditorTemplates/BusinessModel.ascx:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<BusinessModel>" %>
<%: Html.TextBoxFor(m => m.Business1) %>
<%: Html.TextBoxFor(m => m.Business2) %>
...

or if you don't like the conventional places and names for templates you could customize that as well:
<%: Html.EditorFor(x => x.Business, "MyBusinessTemplate") %>

or if it is only a matter of applying additional attributes to your input elements you could do it in an even more elegant way: by writing a custom DataAnnotationsModelMetadataProvider.
I would recommend you to always use EditorFor instead of TextBoxFor.


text:
Q: altering DOM in beforeunload in Chrome Is it possible to alter DOM in beforeunload handler? Chrome seems to apply DOM modifications after the user pressed "stay" in browser alert about leaving the page, and I want a part of the page to be hidden while this alert is visible.
See the demo:

This text should disappear when the user tries to leave the page

https://jsfiddle.net/qmatic/6sLp7rmq/
The only solution I have so far is to animate the div to opacity:0 and to have a code in setInterval that constantly resets this animation. While the code is running the div is always visible. Chrome stops all the code when it shows an alert, so the animation finally runs till the end and hides the div. But it's a terrible solution - I'm constantly updating the DOM to reset the animation. Does anyone have any better ideas?

A: The process being executed by Chrome appears to be:
1) call the handler, waiting synchronously for its return value
2) if the return (event.returnValue) is suitably undefined, continue the unload
3) otherwise present a modal popup of some kind, getting the user's permission to cancel the navigation.
4) if navigation is cancelled, stay on the page and apply a refresh cycle to the page view.
I have stepped through an onbeforeunload handler in the debugger, and when I do so, style changes WILL take effect before the modal dialog appears instead of after it closes.  This seems to indicate that using the debugger introduces additional DOM refresh cycles that would otherwise not occur in normal running.  I am trying to find a way to get one of these refresh cycles to occur programmatically from within the handler, but so far no luck.
In other browsers, there seems to be refresh cycles inserted between steps 1-4 above, giving the desired behavior.


text:
Q: Sorting subset of indices according to some criteria Consider

*

*a vector of the first n natural numbers, I, I=[0, 1, ...n-1], n<=32.

*another vector of naturals, S, S[i]<=2000, for any i=0..n-1, not necessarily unique

*a subset of I with m elements, J, 0 <= J[j] < n, for any j=0...m-1

Is it there an efficient way (in terms of CPU cycles/cache friendliness/memory) to sort the elements of J according to S(J)?
C++ code which uses standard algorithms are preferred.
Example:
I     = [0, 1, 2, 3, 4]
S     = [10, 50, 40, 20, 30]
J     = [1, 3, 4]
S(J)  = [50, 20, 30]
J sorted according to S(J) = [3, 4, 1]

I've considered working with std::multimap, to get the sorting for 'free', but the machinery behind std::multimap (allocations, etc) seems expensive.
Using std::pair to bind J and S(J) would allow using std::sort. The downside is that extra memory and an extra loop is needed to get the final sorted J.
My take is to sort both J and S(J) simultaneously using S(J) as a criteria in a hand written sort routine. However, writing a sort function in 2019 seems awkward.
Is it a clever way to do this? Is it possible to exploit the fact that n<=32?

A:
My take is to sort both J and S(J) simultaneously using S(J) as a criteria in a hand written sort routine. However, writing a sort function in 2019 seems awkward.

You are on the right track, but you don't need to write your own sort.  You can leverage a lambda to get the custom sorting behavior you want while still using std::sort to sort the array for you.  What you'll do is take the values supplied to the lambda and use them as indexes into S and the comparing those results. That would give you code like
int main()
{
    int S[] = {10, 50, 40, 20, 30};
    int J[] = {1, 3, 4};
    std::sort(std::begin(J), std::end(J),[&S](auto lhs, auto rhs){ return S[lhs] < S[rhs]; });
    for (auto e : J)
    {
        std::cout << e << " ";
    }
}

Which outputs
3 4 1


text:
Q: Gravar conteúdo entre  no Selenium IDE Possuo o seguinte código:

Praça Henrique Lavoie Júnior, 701

Irajá - Rio de Janeiro - RJ - 21231-200

Eu gostaria de gravar o que está entre os  e gravar em uma variável
Teria como fazer isso ?
Gostaria que ficasse algo + ou - assim:

Praça Henrique Lavoie Júnior, 701 Irajá - Rio de Janeiro - RJ - 21231-200

A class="OSInline" está presente em várias partes da tela então acho que não da pra aproveita-la para esse caso

A: achei na internet a possivel solução
javascript{storedVars.labelValue = storedVars.labelValue.replace(/(\r\n|\n|\r)/gm,"")}
Eu guardo o meu texto em uma variavel e depois uso esse comando em javascript...porem quando eu utilizo...fica na cor amarela meu selenium IDE e não acontece nada
alguem pode me ajudar ??
Eu gostaria de tira a quebra de linha
Exemplo:
Hello
World
E colocar assim:  Hello World
Alguem pode me ajudar por favor ?


text:
Q: Measuring dynamic memory usage using C++ sanitizers I am looking for a simple way to measure the total memory used by a C++ application. I am aware of valgrind but recently I came across C++'s memory sanitizer. Is it possible to measure the max heap/stack memory used by a C++ executable binary using any sanitizer ?

A: use time -v which can give you a bunch of useful information about an application as:
    System time (seconds): 0.00
    Percent of CPU this job got: 0%
    Elapsed (wall clock) time (h:mm:ss or m:ss): 0:05.00
    Average shared text size (kbytes): 0
    Average unshared data size (kbytes): 0
    Average stack size (kbytes): 0
    Average total size (kbytes): 0
    Maximum resident set size (kbytes): 2144
    Average resident set size (kbytes): 0
    Major (requiring I/O) page faults: 0
    Minor (reclaiming a frame) page faults: 179
    Voluntary context switches: 2
    Involuntary context switches: 1
    Swaps: 0
    File system inputs: 0
    File system outputs: 0
    Socket messages sent: 0
    Socket messages received: 0
    Signals delivered: 0
    Page size (bytes): 4096
    Exit status: 0