text:
Q: Defining which option returned by JSON is greater according to the combination of two data values In order for me to download an image published on a Telegram channel, I need this path:
var contents = JSON.parse(e.postData.contents);
Logger.log(contents.channel_post.photo);

And the answer is:
[{
    "file_id":"AAAAA",
    "file_size":11111,
    "width":253,
    "height":320
},{
    "file_id":"BBBBB",
    "file_size":22222,
    "width":632,
    "height":800
},{
    "file_id":"CCCCC",
    "file_size":44444,
    "width":1400,
    "height":1100
},{
    "file_id":"DDDDD",
    "file_size":33333,
    "width":980,
    "height":750
}]

The user @Newbie told me to use Math.max(width, height) to be able to define which of the container has the highest quality image so that I can define in this call which file_id should i use for download:
contents.channel_post.photo[CONTAINER NUMBER].file_id

In this case the container would be number 3. But I couldn't work with this Math.max, I need help to understand how my code should be to do this work.

A: To retrieve an image URL from a Message object from the Telegram Bot Api you will need to:

*

*Retrieve a Message object (from any of the various APIs)

*extract photo field of type PhotoSize[] Documented Here

*when you choose a PhotoSize (in your case the biggest one) you have file_id

*the you need to pass file_id to getFile() Documented Here

*it will return a File object Documented Here

*that can be then assembled in a URL like https://api.telegram.org/file/bot<token>/<file_path>

A: Is the image quality not already determined by the file_size property? It appears as the resolution increases (width * height), so does the file_size and thereby the quality as well. For this, check my first solution above.
If instead, you want to find the highest quality image based on a ratio comparing width * height and file_size to find the average file_size in bytes per pixel (not recommended), please check my second solution below:
Finding the largest image
This solution sorts the returned array of image data by comparing their resolution (width * height) and then takes the first (largest) image from the newly sorted array.

const contents = {}; contents.channel_post = {}; contents.channel_post.photo = [
  { file_id: "AAAAA", file_size: 11111, width: 253, height: 320 },
  { file_id: "BBBBB", file_size: 22222, width: 632, height: 800 },
  { file_id: "CCCCC", file_size: 44444, width: 1400, height: 1100 },
  { file_id: "DDDDD", file_size: 33333, width: 980, height: 750 }
];

const largestImage = contents.channel_post.photo.sort((a, b) => (b.width * b.height) - (a.width * a.height))[0];

console.log(`The largest image's file_id is ${largestImage.file_id}, which contains ${largestImage.width * largestImage.height} pixels (${largestImage.width}×${largestImage.height})`);

Finding the highest quality image (per pixel)
If you are specifically trying to determine the actual "quality" of the image regardless of resolution, the closest you could get with the data provided would be to divide the file_size by the total pixel area to determine the average file_size in byte per pixel.
By this logic though, the highest quality image would actually be "AAAAA" which I doubt is what you are going for, so you should probably use the first solution I provided, which returns the largest image.
It's worth noting that because image compression algorithms are quite advanced these days, using a formula like this to determine quality per pixel is hardly reliable as it is, so I do recommend using the first solution.

const contents = {}; contents.channel_post = {}; contents.channel_post.photo = [
  { file_id: "AAAAA", file_size: 11111, width: 253, height: 320 },
  { file_id: "BBBBB", file_size: 22222, width: 632, height: 800 },
  { file_id: "CCCCC", file_size: 44444, width: 1400, height: 1100 },
  { file_id: "DDDDD", file_size: 33333, width: 980, height: 750 }
];

const calcImageQuality = ({ file_size, width, height }) => file_size / (width * height);
const highestQualityImage = contents.channel_post.photo.sort((a, b) => calcImageQuality(b) - calcImageQuality(a))[0];

console.log(`The highest quality image's file_id is ${highestQualityImage.file_id}, which contains ${calcImageQuality(highestQualityImage)} bytes per pixel on average`);

A: you can find highest quality image like this:
Math.max.apply(Math, array.map(function(o) { return o.width * o.height; }))


text:
Q: What is the registry key for Windows XP to disable Internet Connection Sharing? What is the registry key for Windows XP to disable Internet Connection Sharing?

A: [HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\ICSharing\Settings\
Enabled (DWORD) - "1" = enable ICS, "0" = disable

redpajama_set_name: RedPajamaStackExchange


text:
Q: Solr Scalability and Server requirement We are currently using Solr4.3 cloud in master slave mode and have been pretty happy with our initial solr POC. We are looking to store Social Data (tweets, blogs, Facebook feed) into Solr and make it searchable, also at the same time utilize the Faceting capabilities provided by Solr.
Going by the amount of social data that comes in, we were wondering what kind of infrastructure would be required to say store 2 TB or data and query them with minimum time.
Also, give the rate in which tweets come in what would be the best indexing strategy.

A: I will suggest you to choose some cloud platform .AWS is one good option in this matter since you can always try and then change your machine if it does'nt suit your requirement.
So what will suit your requirement?
I think for solr since there is a high I/O I will suggest you to go with high I/O machine and good processing power
I suggest using
c3.2xlarge of AWS with  8 ecu,  15 gb ram,  2 x 80 SSD.
and attach to it an EBS volume of atleast 4 TB.

This would solve your problem.


text:
Q: JavaFx TableView how to tell if ScrollBar is visible Based on this example (Option #1) I am creating a fixed column by using 2 TableViews in a SplitPane.
The TableView that shows the other columns (not the fixed one) may get so wide that a ScrollBar is displayed, for which I have to compensate with -fx-padding: 0 0 13px 0; in order to keep the TableRows of both TableViews aligned.
So I have to figure out now whether a ScrollBar is being displayed or not or find a completely different way to ensure the TableRow alignment. The obvious way unfortunately doesn't seem to be working. (The ScrollBar is not null, I just didn't post the code to ensure that)
ScrollBar horizontalScrollBar = (ScrollBar) lookup(".scroll-bar:horizontal");
horizontalScrollBar.visibleProperty().addListener((observable, oldValue, newValue) -> {
    System.out.println(newValueobservableScrollBar);
});

For some reason the Listener is not fired when the ScrollBar appears or disappears.

A: So in order to figure out whether a particular scrollbar is visibile I first had to find it, so I looked up all the scrollbars on that particular table.
Set<Node> scrollBars = itemsTableView.lookupAll(".scroll-bar");

Then filter the set in order to retrieve the specific scrollbar I was looking for (horizontal in my case)
Optional<Node> horizontalScrollBar = scrollBars.stream()
          .filter(node ->
            ((ScrollBar) node).getOrientation().equals(Orientation.HORIZONTAL))
          .findAny();

And then attach the listener to the visibility-property of the scrollbar
horizontalScrollBar.ifPresent(node ->
          node.visibleProperty().addListener((observable, oldValue, newValue) -> {
                    if(newValue)
                    {
                        columnTableView.setStyle("-fx-padding: 0 0 13px 0;");
                    } else
                    {
                        columnTableView.setStyle("-fx-padding: 0 0 0 0;");
                    }
              })
        );

Almost looks kinda simply right? Well, it is, as soon as you have figured out that
lookup(".scroll-bar:horizontal");

does NOT return the horizontal scrollbar but the first (vertical) one. And unless you realize that, your Application will behave kinda mysteriously.


text:
Q: Retrofit2 & Fabric, Crashlytics cannot be used I am using Retrofit 2.0.2 and Fabric 1.21.6 in app.I am not able to request any api using retrofit as it gives the following error.
I followed the solution stated in git : https://github.com/twitter/twitter-kit-android/issues/28 , https://github.com/square/retrofit/issues/1152
Could not find class 'retrofit2.Retrofit$Builder', referenced from method com.wolfmatrix.navz.restApi.service.RestClient.getClient
    05-26 18:20:20.266 24072-24072/com.wolfmatrix.navz E/AndroidRuntime: FATAL EXCEPTION: main
                                                                         Process: com.wolfmatrix.navz, PID: 24072
                                                                         java.lang.NoClassDefFoundError: retrofit2.Retrofit$Builder


text:
Q: .ToListAsync() not found when using WhereIf I am reading this tutorial. I want to use async query with EF Core.
It works well when i use like this:
var tasks = await _taskRepository
    .GetAll()
    //.WhereIf(!string.IsNullOrEmpty(input?.Title), x => x.Title.Contains(input.Title))
    //.WhereIf(input?.State != null, x => x.State == input.State.Value)
    //.OrderByDescending(x => x.CreationTime)
    .ToListAsync();

but i want to use whereif and orderby like
var tasks = await _taskRepository
    .GetAll()
    .WhereIf(!string.IsNullOrEmpty(input?.Title), x => x.Title.Contains(input.Title))
    .WhereIf(input?.State != null, x => x.State == input.State.Value)
    .OrderByDescending(x => x.CreationTime)
    .ToListAsync();

Error:

'IOrderedEnumerable' does not contain a definition for 'ToListAsync' and no extension method 'ToListAsync' accepting a first argument of type 'IOrderedEnumerable' could be found (are you missing a using directive or an assembly reference?)

A: You are using wrong WhereIf extension, it's easy to miss because you need to add extra using Visual Studio won't offer.
You are using extension which returns IEnumerable
Abp.Collections.Extensions.EnumerableExtensions.WhereIf<T>()

You need to use extension that returns IQueryable
Abp.Linq.Extensions.QueryableExtensions.WhereIf<T>()

It's an easy fix, just add at the top of the file using Abp.Linq.Extensions;

A: IOrderedEnumerable<Task> means that you are working with a IEnumerable<Task>.
Entity Framework Core works with IQueryable<T> (which represents a database query), not IEnumerable<T> (which represents an in-memory collection). As soon as the IQueryable<T> is converted to a IEnumerable<T>, the query is executed on the database server and the result retrieved.
So: if you are calling a method that returns IEnumerable<T>, that method was not made to be used in LINQ to Entities.


text:
Q: Lightning Out / Visualforce Pass sObject from Visualforce to Javascript Controller I'm adding a lightning out component to a pre-existing visualforce page. I can pass the values from the sObject bound in the Visualforce page to my Lightning Component by passing these as separate parameters (one for each required field) to associated attributes in my lightning component however I'd like to pass just one attribute and reference this for picking up the fields in my component.
On testing this out this afternoon I've been unable to get this to work.
My Lightning Out VF page is as follows
<apex:page standardController="Impact__c" showChat="false" tabStyle="case" >
    <apex:includeLightning />

</apex:page>

If I pass Incident__r or Incident__c I just get the id of the associated incident record in my component as opposed to a full sObject reference, or I'm not accessing these correctly in the component.  if I do the following I can pass individual fields.
<apex:page standardController="Impact__c" showChat="false" tabStyle="case" >
    <apex:includeLightning />

</apex:page>

Should I be able to pass the full sObject? Is seems the most logical approach instead of individual fields.
Lightning Data Service is not supported on Lightning Out.
Thanks in advance for any tips on this.

A: While it is true that LDS is not available for Lightning Out I think your best bet in this situation would be to retrieve the object's data within the component.
You get the Id from the page, but the component calls the database to retrieve the record with the specified Id.
Of course, you should be able to pass the full sObject if you format it as a JSON in the component's loader, but I think this approach is a little annoying to maintain if you need to change/add/remove the object's fields (because then you'll have to edit not only your component but also the JSON manually).


text:
Q: Natural density of primes congruent to m modulo N and to r modulo S N and S are two different primes. I would like to ask if primes, except N and S, congruent to m modulo N and to r modulo S, gcd(m,N)=gcd(r,S)=1, have natural density 1/φ(Ν)*1/φ(S).

A: Not in general, consider e.g. $N=S$...


text:
Q: Bootstrap Modal from code-behind not Working Need to open a modal when the password or user are incorrect it will stay in Else .. however, does not work , it does not work does not open the modal
protected void bntLogar_Click(object sender, EventArgs e)
    {
        Registrar criptografia = new Registrar();

        if (Login.logarUsuario(txtUser.Text, criptografia.CriptografiaMD5(txtSenha.Text)))
        {
            //Cria um cookie do lado do servidor
            HttpCookie cookie = new HttpCookie("estado", "conectado");

            //Define a validade do cookie (10 dias a partir de hoje)
            cookie.Expires = DateTime.Now.AddMonths(12);

            //Envia o cookie para o cliente
            Response.Cookies.Set(cookie);

            //Redireciona para a pagina inicial
            Response.Redirect("Admin.aspx");

            //fortawsome
        }
        else
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Pop", "openModal();", true);
        }

    }

And I put inside the  JavaScript code

Modal

Warning

Watch out! Your about to be locked out.

                    Close

The tah <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>in this sitemaster

A: You can try this :
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "alert('Informations invalides');", true);

instead of
 ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Pop", "openModal();", true);

but i don't know if it'll solve your problem.


text:
Q: How can wordpress function receive function as argument? How can the WP function add_action receive another function as its argument? I know this by itself is not possible in php (to have custom functions receive other functions as arguments). I deliberately broke some code and found that there is actually a native php function call_user_fun_array beneath this (i think),
but how did they make it so that their own function can have a function as its argument?

A: There is a native PHP function call_user_func() Take a look on this pretty simple example.
function caller($custom_func){
return call_user_func($custom_func);
}
function make_echo(){
echo 'something';
}

caller('make_echo');


text:
Q: Why aremy arrays being wrapped when console.log in terminal? In the terminal of my Mac, If I console.log([1,2,3,4,5,6,7,8,9,10]), the result displayed in the Terminal on multiple lines
"[
  1, 2, 3, 4, 5,
  6, 7, 8, 9, 10
 ] "

My expected and desired output is
"[1,2,3,4,5,6,7,8,9,10]"

all in one line.
I'm not sure if I inadvertently modified a setting or if that's just how Macs output arrays.
My Windows desktop outputs the array in one line.
I am on MacOS using VS code and node.js. I tried looking at my terminal and VSCode settings to no avail.
Does anyone know why the output is formatted into separate lines?


text:
Q: Why the Q.E.D. symbol show after the sentence end and can't show right aligned (as picture below)? \documentclass[twoside,11pt]{book}
\usepackage[left=2.5cm,right=2cm,top=2cm,bottom=2cm,papersize={15.5cm,23.5cm}]{geometry}
\renewcommand{\thechapter}{\Roman{chapter}}
\renewcommand{\thesection}{\arabic{chapter}.\arabic{section}.}
\renewcommand{\thesubsection}{\arabic{chapter}.\arabic{section}.\arabic{subsection}.}
\usepackage{amsthm}
\newtheorem{definition}{Definition}[section]
\newtheorem{theorem}{Theorem}[section]
\renewcommand{\thetheorem}{\thesection\arabic{theorem}}
\renewenvironment{proof}{{\noindent\bfseries Proof.}}{\qedsymbol}
\renewcommand{\qedsymbol}{\rule{1ex}{1ex}}

\begin{document}
    \chapter{ABC}
    blablabla
    \section{ONE}
    \begin{theorem}
        dddd
    \end{theorem}
\begin{proof}
    It is clear.
\end{proof}
\end{document}

I want the text Proof is bold. So I write:
\renewenvironment{proof}{{\noindent\bfseries Proof.}}{\qedsymbol}

Now, I want to Q.E.D. symbol is black square, so I write
\renewcommand{\qedsymbol}{\rule{1ex}{1ex}}

Why the Q.E.D. symbol show after the sentence end and can't show right aligned (as picture below)? How to make it?

I want:

A: From your MWE, came to understand that you need the Proof name in Bold face and the qedsymbol should be in solid black square, for that no need to redefine the proof environment, you can modify the \proofname and \qedsymbol as you wish, and the modified MWE is:
\documentclass[twoside,11pt]{book}
\usepackage[left=2.5cm,right=2cm,top=2cm,bottom=2cm,papersize={15.5cm,23.5cm}]{geometry}
\renewcommand{\thechapter}{\Roman{chapter}}
\renewcommand{\thesection}{\arabic{chapter}.\arabic{section}.}
\renewcommand{\thesubsection}{\arabic{chapter}.\arabic{section}.\arabic{subsection}.}
\usepackage{amsthm}
\newtheorem{definition}{Definition}[section]
\newtheorem{theorem}{Theorem}[section]
\renewcommand{\thetheorem}{\thesection\arabic{theorem}}
%\renewenvironment{proof}{{\noindent\bfseries Proof.}}{\qedsymbol}
\renewcommand{\proofname}{\upshape\textbf{Proof}}
\renewcommand{\qedsymbol}{\rule{1ex}{1ex}}

\begin{document}
    \chapter{ABC}
    blablabla
    \section{ONE}
    \begin{theorem}
        dddd
    \end{theorem}
\begin{proof}
    It is clear.
\end{proof}
\end{document}

And the output is:

A: My suggestion is to use https://tex.stackexchange.com/a/251251/4427 with also a redefinition of \qedsymbol.
\documentclass{article}

\usepackage{amsthm}
\usepackage{xpatch}

\providecommand{\proofnamefont}{\itshape}% the default
\xpatchcmd{\proof}{\itshape}{\normalfont\proofnamefont}{}{}
\renewcommand{\proofnamefont}{\bfseries}% your preference

\renewcommand{\qedsymbol}{\rule{1ex}{1ex}}

\begin{document}

\begin{proof}
Obvious, isn't it?
\end{proof}

\end{document}

A: You can redefine the \proofname and \qedsymbol as folows. It's not necessary to create a black square by the rule command since there is a \blacksquare command in the amssymb package which could produce a black square as the same size as the (white) square.
\documentclass[twoside,11pt]{book}
\usepackage[left=2.5cm,right=2cm,top=2cm,bottom=2cm,papersize={15.5cm,23.5cm}]{geometry}
\renewcommand{\thechapter}{\Roman{chapter}}
\renewcommand{\thesection}{\arabic{chapter}.\arabic{section}.}
\renewcommand{\thesubsection}{\arabic{chapter}.\arabic{section}.\arabic{subsection}.}
\usepackage{amsthm}
\newtheorem{definition}{Definition}[section]
\newtheorem{theorem}{Theorem}[section]
\renewcommand{\thetheorem}{\thesection\arabic{theorem}}

\renewcommand{\proofname}{\upshape\bfseries Proof}
\usepackage{amssymb}
\renewcommand{\qedsymbol}{\ensuremath\blacksquare}

\begin{document}
    \chapter{ABC}
    blablabla
    \section{ONE}
    \begin{theorem}
        dddd
    \end{theorem}
\begin{proof}
    It is clear.
\end{proof}
\end{document}

And the output is as follows.

By the way, the chapter numbers should not be roman since the prefixes in section numbers are arabic. Also, it's not necessary to add dots after section numbers since there are no dots after chapter numbers.


text:
Q: Dynamically adjust stored procedure with one variable holding multiple values I have a stored procedure that takes an input parameter as follows:
@Name NVARCHAR(50) = 'George W Bush'

How can I adjust my where clause dynamically:
SELECT * FROM TABLE
WHERE CONTAINS(FIELD, 'George')
  AND CONTAINS(FIELD, 'W')
  AND CONTAINS(FIELD, 'Bush')

Or for example:
@Name NVARCHAR(50) = 'Harry Potter'

SELECT * FROM TABLE
WHERE CONTAINS(FIELD, 'Harry')
  AND CONTAINS(FIELD, 'Potter')

I have found many solutions here that come so close to doing what I need, but I specifically need for the field to contain each substring of the input parameter.

A: CONTAINS can work with multiple words with AND or OR conditions like this:
 WHERE CONTAINS (FIELD, 'George AND W AND Bush')

So what you can do is change your variable to(given they will always be space-delimited):
DECLARE @Name NVARCHAR(50)
SET @Name = REPLACE('George W Bush', ' ', ' AND ')

SELECT * FROM TABLE
WHERE CONTAINS(FIELD, @Name)

A: Here is a way to split your names, regardless if it is FirstName LastName, or FirstName MiddleName LastName, into parameters which you can use. Of course if you expect more than 2 spaces (three names) this won't work
DECLARE @Name NVARCHAR(50) = 'George W Bush'
DECLARE @Spaces int = (SELECT LEN(@Name)-LEN(REPLACE(@Name, ' ', '')))

DECLARE @FirstName varchar(50) = null
DECLARE @MiddleName varchar(50) = null
DECLARE @LastName varchar(50) = null

IF @Spaces = 2
    BEGIN
        SET @FirstName = LEFT(@Name,CHARINDEX(' ',@Name))
        SET @MiddleName = SUBSTRING(@Name,CHARINDEX(' ',@Name) + 1,1)
        SET @LastName = RIGHT(@Name,CHARINDEX(' ',REVERSE(@Name)))
    END
ELSE IF @Spaces = 1
    BEGIN
        SET @FirstName = LEFT(@Name,CHARINDEX(' ',@Name))
        SET @LastName = RIGHT(@Name,CHARINDEX(' ',REVERSE(@Name)))
    END

SELECT @FirstName, @MiddleName, @LastName

A: CONTAINS will work if your table is full-text indexed, but if it isn't, consider this:
-- Here's my test data
declare @t table
(
   text nvarchar(max)
)

insert @t values('I''m just wild about Harry')
              , ('Sally Potter is important in British theater')
              , ('I love the "Harry Potter" books')

-- Here are our keywords:
declare @Name varchar(max) = 'Harry Potter'

-- To make this work, we need to convert the substrings into tabular form.
-- so here's how we'll do that.

declare @NameXml xml

set @NameXml = convert(xml, '<substrings><substring>' +
               replace(@Name, ' ', '</substring><substring>') +
               '</substring></substrings>')

-- That gives us an XML variable with each substring as a separate
-- element.
;
with mockTable as
(
    select  Keyword = N.a.value('.[1]', 'varchar(100)')
    from    @NameXml.nodes('/substrings/substring') as N(a)
)
-- Now that we have a "mock table", we can use the ALL operator to
-- confirm that each string in our mock table is found in the
-- records we return.
select  *
from    @t
where   1 = ALL (
    select  case
            when [text] like '%' + Keyword + '%'
            then 1
            else 0
            end
    from mockTable
    )

A: Like Ann L. said, CONTAINS and FREETEXT only work when you've already created the FULLTEXT INDEX on the underlying table.
As per you need this string-parsing operation, why not create a user-defined function to handle that, and use it within your Sproc. BTW, I really dont want to use wild cards. :)
CREATE FUNCTION [dbo].[parsing]
(
    @String NVARCHAR(2000),
    @Delimiter NVARCHAR(5)
)
RETURNS @Rtn TABLE
(
    ID INT IDENTITY(1,1),
    Seg NVARCHAR(50)
)
AS
BEGIN
    WHILE(CHARINDEX(@Delimiter,@String)>0)
    BEGIN
        INSERT INTO @Rtn (Seg)
        SELECT LTRIM(RTRIM(SUBSTRING(@String,1,CHARINDEX(@Delimiter,@String)-1)))
        SET @String = SUBSTRING(@String,CHARINDEX(@Delimiter,@String)+LEN(@Delimiter),LEN(@String))
    END
    INSERT INTO @Rtn (Seg)
    SELECT LTRIM(RTRIM(@String))
END


text:
Q: Add vertical scroll bar to mat-expansion-panel I'm using Material Design Expansion Panel to display data in a hierarchical way is illustrated here :

This the way I implement it so I can show multiple AREAs which can contain one or more TEAMs
<mat-accordion>
  <mat-expansion-panel
    *ngFor="let area of myAreas; let index = index; first as firstExpansion"
    [expanded]="firstExpansion">
    <mat-expansion-panel-header>
      <mat-panel-title> TITLE </mat-panel-title>
    </mat-expansion-panel-header>
    <ng-template matExpansionPanelContent >
      <mat-selection-list #teams [multiple]="false">
        <mat-list-option
          *ngFor="let team of area.teams"
          [value]="team">
          <div accordion-button">
            {{team.displayName}}
          </div>
        </mat-list-option>
      </mat-selection-list>
    </ng-template>
  </mat-expansion-panel>
</mat-accordion>

This way I'm able to show all my areas while expanding the first one to show its embedded teams.
Now the problem is how to make that list scrollable without exceeding the height of the space between Search block and Add new area button like this:


text:
Q: HTTP Post request from Flutter Web I have a function on Google Cloud Functions that I am trying to make a post request to in my Flutter web app. I tested a post request in Python and it worked with the following request:
params = {'input_key':'input_value'}
headers = {"Content-Type": "application/json"}
r = requests.post("https://us-central1-lucid-bond-261904.cloudfunctions.net/cloudFunction", data=jason.dumps(params), headers=headers)

But when I try to do the same request from my Flutter web app using the http package, I keep getting an XMLHttpRequest error. Here's my http request in my flutter web app
String path = "https://us-central1-lucid-bond-261904.cloudfunctions.net/cloudFunction";
Map params = {'input_key':'input_value'}
var response = await http.post(path, body: json.encode(params), headers: <String, String>{'Content-Type': 'application/json'});

I know it successfully triggers the cloud function, because the first thing I have the cloud function do is print 'hello' to the log. It seems to maybe be an error in the way I'm choosing the content-type. I read this thread that implies that the content type might be getting changed to "application/json; charset=utf-8", but the fix that they specified doesn't apply to Flutter Web because the dart io package doesn't work on Flutter Web. So how do I correctly specify the content type? Or is there a better flutter package to use for this situation?
The error thrown back in Flutter is:
Error: XMLHttpRequest error.
    C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 264:20      get current
packages/http/src/browser_client.dart 84:22

And the error in my Cloud Function
line 99, in cloudFunction shop_name = inputs_dict['input_key'] TypeError: 'NoneType' object is not subscriptable

EDIT: Just tried doing the same post request from Postman and it worked successfully. Still not working from my flutter app though. Do I need to enable CORS or something in the Google Cloud Function?

A: I finally made it work. In my cloud function, request.get_json() was returning null. When I added the paramter force=True, it finally worked. I didn't have to do force=True when trigger the function through python or postman, but for some reason triggering it through flutter required the force=true.
request.get_json(force=True)


text:
Q: How to get the id of an element on a button click in mootools(1.1) I have a bunch of links with non-pre-determined id's like so:
Remove 123
Remove 234
Remove 567
Remove 890

I have an event handler like so:
$$('.remove_pid').addEvents({
   'click': removePid
});

which calls this function
function removePid(event)
{
    alert('yo what is my element id???');
}

So the question is how do i get the element id in the function removePid()?
UPDATE:
@Aishwar, event.target.id seems to work in the following case, but not specifically in my case

UPDATE 2:
I thought it was inconsequential, but instead of the text "Remove 123" I actually have an image like so:

So, thanks for @Dimitra for pointing it out. I was surprised with the de-vote but am happy to say i probably deserve it.

A: I do not have experience working with mootools. But I would guess you can just do something along these lines, in removePid:
var element = event.srcElement || event.target
element.id // is the element's id, element is the DOM element itself

A: as per the markup posted in the FINAL update:
http://www.jsfiddle.net/dimitar/Sr8LC/
$$('.remove_pid').addEvents({
    'click': function(e) {
        new Event(e).stop();
        var id = this.getProperty("id");
        alert(id);
        alert(id.replace("pid_", ""));
    }
});

to use a named function and keep the event:
var removeProduct = function(e) {
    new Event(e).stop();
    var id = this.getProperty("id");
    alert(id);
    alert(id.replace("pid_", ""));
};

$$('a.remove_pid').each(function(el) {
    el.addEvents({
        'click': removeProduct.bind(el)
    });
});

within both functions, this will refer to the trigger element (the anchor), so you can read it's property, etc. this.getFirst() will reference the image (if you want it).

A: Think I found it:
function removePid(event)
{
    //alert('yo what is my element id???');
    $(event.target).getParent('a').getProperty('id');
}

This works in FF 3.6


text:
Q: How to put triangle shape for page in android?
How to Add triangle shape for activity or page change like in facebook page?

A: You can use QuickAction Dialog in android Here is example code .

A: If you are considered about the shape
See this answer
Also this article
And simple work around ::Give your parent layout transparent background and place the triangle in center of layout  and you can achieve the position in the image
Or you can go for 9 patch images directly  :: see this


text:
Q: How should I improve my accuracy in Transfer learning? I am training a model for Optical Character Recognition of Gujarati Language. The input image is a character image. I have taken 37 classes. Total training images are 22200 (600 per class) and testing images are 5920 (160 per class). My input images are 32x32 in size.
Below is my code:
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Dense

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten
from tensorflow.keras.layers import Convolution2D, MaxPooling2D
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.layers import MaxPool2D
from tensorflow.keras.layers import ReLU

from tensorflow.keras.callbacks import TensorBoard
import pickle
import time

from datetime import datetime
from packaging import version

import tensorflow as tf
from tensorflow import keras

import numpy as np
from tensorflow.keras import layers

model = tf.keras.applications.DenseNet121(include_top=False, weights='imagenet', pooling='max', input_shape=(32,32,3))

model.trainable = True
print("Number of layers in the base model: ", len(model.layers))

fine_tune_at = 400
for layer in model.layers[:fine_tune_at]:
    layer.trainable =  False

base_outputs = model.layers[-1].output

final_outputs = layers.Dense(37)(base_outputs)
new_model = keras.Model(inputs=model.input, outputs=final_outputs)
new_model.summary()

from tensorflow.keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(
                                   shear_range=0.2,
                                   zoom_range=0.2,

                                   horizontal_flip=False)

test_datagen = ImageDataGenerator(horizontal_flip = False)

training_set = train_datagen.flow_from_directory('C:/Users/shweta/Desktop/characters/train',
                                                 target_size = (32, 32),
                                                 batch_size = 64,
                                                 class_mode = 'categorical')

test_set = test_datagen.flow_from_directory('C:/Users/shweta/Desktop/characters/test',
                                            target_size = (32, 32),
                                            batch_size = 64,
                                            class_mode = 'categorical')

new_model.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])

new_model.fit_generator(training_set,

                         epochs = 25,
                         validation_data = test_set, shuffle=True)
new_model.save('alphanumeric.mod')

Below is my output:

Thanks in advance!!

A: Rescale the input data. You can do this by setting rescale factor to 1. / 255 in the ImageDataGenerator.

A: Try playing around with the ImageDataGenerator to preprocess the dataset before putting in the model. You can find the full options here from the Tensorflow documentation: ImageDataGenerator
As mentioned, try rescaling your data or shuffle it before putting it in model.fit


text:
Q: [Solved]How add actions in Magento2? I create a new module and I would add actions in my module but how ?

A: Spacename/Modulename/view/adminhtml/ui_component/yourlisitng.xml
check this column and add action in that file Spacename\Modulename\Ui\Component\Listing\Column\Actions
<actionsColumn name="actions" class="Spacename\Modulename\Ui\Component\Listing\Column\Actions">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="resizeEnabled" xsi:type="boolean">false</item>
                    <item name="resizeDefaultWidth" xsi:type="string">107</item>
                    <item name="indexField" xsi:type="string">id</item>
                </item>
            </argument>
        </actionsColumn>

Spacename/Modulename/Ui/Componenet/Listing/Column/Youactionfile.php
public function prepareDataSource(array $dataSource)
    {
        if (isset($dataSource['data']['items'])) {
            foreach ($dataSource['data']['items'] as & $item) {
                $name = $this->getData('name');
                if (isset($item['id'])) {
                    $item[$name]['edit'] = [
                        'href' => $this->urlBuilder->getUrl($this->editUrl, ['id' => $item['id']]),
                        'label' => __('Edit')
                    ];
                    $item[$name]['delete'] = [
                        'href' => $this->urlBuilder->getUrl(self::CMS_URL_PATH_DELETE, ['id' => $item['id']]),
                        'label' => __('Delete'),
                        'confirm' => [
                            'title' => __('Delete ${ $.$data.title }'),
                            'message' => __('Are you sure you wan\'t to delete a ${ $.$data.title } record?')
                        ]
                    ];
                  //add here
                }

            }
        }

        return $dataSource;
    }

A: Assuming that you build your module using the ui-components (as the image show) you need to add this at the end of your ui component file, before the <columns> tag is closed.
    <actionsColumn name="actions" class="[Namespace]\[Module]\Ui\Component\Listing\Column\[Entity]Actions">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="indexField" xsi:type="string">[entity]_id</item>
                <item name="urlEntityParamName" xsi:type="string">[entity]_id</item><!-- or the value could be 'id' here depending on how your edit link looks like. This is the name of the get parameter-->
            </item>
        </argument>
    </actionsColumn>

Then create the class.  [Namespace]\[Module]\Ui\Component\Listing\Column\[Entity]Actions
<?php
namespace [Namespace]\[Module]\Ui\Component\Listing\Column;

class [Entity]Actions extends \Magento\Ui\Component\Listing\Columns\Column
{
    /**
     * Url path  to edit
     *
     * @var string
     */
    const URL_PATH_EDIT = 'url/to_entity/edit_page';

    /**
     * Url path  to delete
     *
     * @var string
     */
    const URL_PATH_DELETE = 'url/to_entity/delete_page';

    /**
     * URL builder
     *
     * @var \Magento\Framework\UrlInterface
     */
    protected $_urlBuilder;

    /**
     * @param \Magento\Framework\View\Element\UiComponent\ContextInterface $context
     * @param \Magento\Framework\View\Element\UiComponentFactory $uiComponentFactory
     * @param \Magento\Framework\UrlInterface $urlBuilder
     * @param array $components
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\UiComponent\ContextInterface $context,
        \Magento\Framework\View\Element\UiComponentFactory $uiComponentFactory,
        \Magento\Framework\UrlInterface $urlBuilder,
        array $components = [],
        array $data = []
    )
    {
        $this->_urlBuilder = $urlBuilder;
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }

    /**
     * Prepare Data Source
     *
     * @param array $dataSource
     * @return array
     */
    public function prepareDataSource(array $dataSource)
    {
        if (isset($dataSource['data']['items'])) {
            foreach ($dataSource['data']['items'] as & $item) {
                if (isset($item['[entity]_id'])) {
                    $item[$this->getData('name')] = [
                        'edit' => [
                            'href' => $this->_urlBuilder->getUrl(
                                static::URL_PATH_EDIT,
                                [
                                    '[entity]_id' => $item['[entity]_id']
                                ]
                            ),
                            'label' => __('Edit')
                        ],
                        'delete' => [
                            'href' => $this->_urlBuilder->getUrl(
                                static::URL_PATH_DELETE,
                                [
                                    '[entity]_id' => $item['[entity]_id']
                                ]
                            ),
                            'label' => __('Delete'),
                            'confirm' => [
                                'title' => __('Delete "${ $.$data.name }"'),
                                'message' => __('Are you sure you wan\'t to delete the record "${ $.$data.name }" ?')
                            ]
                        ]
                    ];
                }
            }
        }
        return $dataSource;
    }
}


text:
Q: Bot Framework: Adaptive Cards Capabilities across Channels | Carousel | Input | Action Buttons I was going through the documentation for adaptive cards, and I had a few queries:
There are certain capabilities that I am looking to target through Adaptive Cards, across channels (Webchat, Bing, Skype, Facebook Messenger). These include:
Showing a carousel of cards within the platform
Taking input from user within the card to provide an input/edit experience .
Action buttons as part of card, to perform an action (e.g. opening a webpage) when clicked.

I believe that most of these actions are available for Webchat, Bing, Skype, Microsoft Teams. Is there a way to accomplish this for channels like Facebook and Kik using adaptive cards? What is the level of customization required from the same?
Also, is Carousel supported across channels?
Thank you for the help!.

A: For the Carousel question, see @kienct89 comment: you have samples of Carousel display in https://docs.botframework.com/en-us/channel-inspector/channels/Facebook?f=Carousel&e=example1.
For the Adaptive cards, see the Visualizer on http://adaptivecards.io/visualizer/ and you will face the problem that taking input is not supported for Facebook and Kik for example (only Bing and Webchat have the possibility for input in their sample).


text:
Q: GAE - Google Cloud Storage - Upload error 503 I got the following code in my jsp
<%@ page import="com.google.appengine.api.blobstore.BlobstoreServiceFactory" %>
<%@ page import="com.google.appengine.api.blobstore.BlobstoreService" %>
<%@ page import="com.google.appengine.api.blobstore.UploadOptions" %>
<%
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();

String uploadUrl = blobstoreService.createUploadUrl("/test.jsp", UploadOptions.Builder.withGoogleStorageBucketName("my_bucket"));

%>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload Page</title>

Upload v1

    <form name="form1" id="form1" action="<% out.print(uploadUrl); %>" method="post" enctype="multipart/form-data" target="upload_iframe">
    <input type="hidden" name="hiddenfield1" value="ok">
    Files to upload:

    <input type="file" name="myFile">

        <button type="submit">Send</button>
    </form>

i also set my bucket at public read like this:
python c:\gsutil\gsutil setacl public-read gs://my_bucket

My ACL file looks like this:
<?xml version="1.0" ?>
<AccessControlList>
    <Owner>
        <ID>00b4903a97dfaa16aff41eeb91e90b5fb524f1daf0d88fceca29b6f647412e8d</ID>
    </Owner>
    <Entries>
        <Entry>
            <Scope type="GroupById">
                <ID>00b4903a97dfaa16aff41eeb91e90b5fb524f1daf0d88fceca29b6f647412e8d</ID>
            </Scope>
            <Permission>FULL_CONTROL</Permission>
        </Entry>
        <Entry>
            <Scope type="GroupById">
                <ID>00b4903a97d3721750cd84cf5e8be336cba9847dba5c2e4a1e88aa514db970d2</ID>
            </Scope>
            <Permission>FULL_CONTROL</Permission>
        </Entry>
        <Entry>
            <Scope type="GroupById">
                <ID>00b4903a97c265aa840305b07236a7ea78681916c9e63ab74c0deb237f60f05e</ID>
            </Scope>
            <Permission>READ</Permission>
        </Entry>

<Entry>
   <Scope type="UserByEmail">
      <EmailAddress>
         my_app@appspot.gserviceaccount.com
      </EmailAddress>
   </Scope>
   <Permission>
      WRITE
   </Permission>
 </Entry>

    </Entries>
</AccessControlList>

And now each time i upload i get a error: 503 Service Unavailable

A: Ok i finally solved it,
The error was doing this :
python c:\gsutil\gsutil setacl public-read gs://my_bucket

actually erased the acl file so removed my_app@... permission :/


text:
Q: How can we interchange the colors of districts in 4 color problem In the paper On the geographical problem of the Four Colors by Kempe, at the end of page 194, it is stated that

It will readily be seen that we can interchange the colours of the
  districts in one or miore of the red and green regions without doing
  so in any others, and the map will still be properly coloured. The
  same remarks apply to the regions composed of districts of any other
  pair of colour. Now if a region composed of districts of any pair of
  colours, say red and green as before, be of either of the forms shown
  in Figures 3 and 4, it will separate the surface into twvo parts, so
  that we map be quite certain that no yellow or blue districts in one
  part can belong, to the same yellow and blue region as any yellow or
  blue district in the other part

But I'm having trouble understading his argument. I mean as far as I understood, those lines in the figures are the boundaries of regions which contain districs, and if we change the colors of district, say blue and green, in one region only, there will be no problem, but can't a district of blue color in the inner region have a neighbour with green color in the outer region ?

A:
I couldn't figure out how to post an image in a comment, so ...
The map has two red/green regions, A and D. It has two blue/yellow regions, B and C. Region B consists of a single blue district. If green and red were switched in region A, the other regions would be unaffected. Every district in A is adjacent to other districts in A or blue/yellow districts in B or C.
The single district in region B can be blue or yellow.
If we wanted blue/green regions and red/yellow regions instead, there would be a single blue/green region and 4 red/yellow regions.


text:
Q: How to make Unity 3D work with Bumblebee using the Intel chipset I have a Sony VAIO S laptop with the dreaded Optimus and finally managed to get Bumblebee to work fully on Ubuntu 12.04 so that I can utilize both the hardware acceleration of the Intel chipset as well as the Nvidia one via optirun and/or bumble-app-settings.
However, the desktop effects don't work. But they should, I vaguely remember that they worked for a while before I had Bumblebee installed.
This is what I get with the support test:
:~$ /usr/lib/nux/unity_support_test -p
Xlib:  extension "NV-GLX" missing on display ":0".
OpenGL vendor string:   Tungsten Graphics, Inc
OpenGL renderer string: Mesa DRI Intel(R) Ivybridge Mobile
OpenGL version string:  1.4 (2.1 Mesa 8.0.2)

Not software rendered:    yes
Not blacklisted:          yes
GLX fbconfig:             yes
GLX texture from pixmap:  yes
GL npot or rect textures: yes
GL vertex program:        yes
GL fragment program:      yes
GL vertex buffer object:  no
GL framebuffer object:    yes
GL version is 1.4+:       yes

Unity 3D supported:       no

First of all, I kind of doubt that the chipset doesn't support VBOs (essentially a standard feature in GL).
Neither Xorg.0.log nor Xorg.8.log show any particular errors.
As for the Nvidia drivers: In order to get them to work, I had to install the 304.22 drivers (older ones wouldn't work). They clobbered libglx.so, so I reinstated the xserver-xorg-core libglx.so in its original place, moved Nvidia's libglx.so to an nvidia-specific folder and specified that folder in the bumblebee.config. That seems to work and shouldn't cause the problem I see here.
For fun, I tried to use the Nvidia chipset for Unity, but that didn't fly either:
~$ optirun /usr/lib/nux/unity_support_test -p
OpenGL vendor string:   NVIDIA Corporation
OpenGL renderer string: GeForce GT 640M LE/PCIe/SSE2
OpenGL version string:  4.2.0 NVIDIA 304.22

Not software rendered:    yes
Not blacklisted:          yes
GLX fbconfig:             yes
GLX texture from pixmap:  no
GL npot or rect textures: yes
GL vertex program:        yes
GL fragment program:      yes
GL vertex buffer object:  yes
GL framebuffer object:    yes
GL version is 1.4+:       yes

Unity 3D supported:       no

A: The problem was with libGL.so.1 - apparently, the Nvidia installer also removed the Intel one and replaced it with its own.
So I retrieved it from libgl1-mesa-glx and changed the symlink in /usr/lib to point to it.
I'm not going to go into the details of how to set up Bumblebee, but there are some key parts that are missing that aren't really documented:

*

*The Nvidia driver installer is likely to destroy your existing libglx.so (in /usr/lib/xorg/modules/extensions) and libGL.so (in /usr/lib). Back those up before installing the driver. If you already lost them, you could get them back by resintalling xserver-xorg-core and libgl1-mesa-glx, but when I tried that the first time, it left my laptop in a bad state (black screen after login, had to go into recovery), so I would recommend getting those manually via dpkg-deb.

*After installing the Nvidia driver, you'll notice that Nvidia replaced the two files listed above with symlinks to the Nvidia libraries. In my case, for example, libglx.so is a symlink to libglx.so.304.22.

*Since Bumblebee needs both drivers, and since it can only differentiate by directory, let move drivers for each graphics adapter into a separate directory. The Nvidia installer I used installed some drivers into /usr/lib/nvidia-current, let's use that. Keep in mind that we need to separate libraries and Xorg modules. Here are where I put the relevant files:
In /usr/lib:
libGL.so.304.22   -- Nvidia's driver (unchanged where the installer put it)
libGL.so          -- symlink to libGL.so.1
libGL.so.1        -- symlink to /usr/lib/x86_64-linux-gnu/mesa/libGL.so.1,
                     i.e. the libgl1-mesa-glx driver

In /usr/lib/x86_64-linux-gnu/mesa:
libGL.so.1   -- symlink to libGL.so.1.2
libGL.so.1.2 -- The normal driver from libgl1-mesa-glx

In /usr/lib/nvidia-current:
libGL.so   -- symlink to libGL.so.1
libGL.so.1 -- symlink to /usr/lib/libGL.so.304.22 (i.e. Nvidia's driver)

In /usr/lib/nvidia-current/xorg:
libglx.so -- symlink to /usr/lib/xorg/modules/extensions/libglx.so.304.22

In /usr/lib/xorg/modules/extensions:
libglx.so.1       -- symlink to libglx.so.xserver
libglx.so.304.22  -- Nvidia's driver (unchanged from where the installer put it)
libglx.so.xserver -- I renamed the original libglx.so to that and put it here

Finally, we need to modify /etc/bumblebee/bumbleebee.conf to tell the system where to find the Nvidia drivers. I'm using the nvidia driver (as opposed to nouveau), so in the nvidia section, I'm using this:
KernelDriver=nvidia
Module=nvidia
PMMethod=auto
# colon-separated path to the nvidia libraries
LibraryPath=/usr/lib/nvidia-current:/usr/lib32/nvidia-current
# comma-separated path of the directory containing nvidia_drv.so and the
# default Xorg modules path
XorgModulePath=/usr/lib/nvidia-current/xorg,/usr/lib/xorg/modules

Note how the LibraryPath and XorgModulePath points to the Nvidia drivers, so if Bumblebee is looking for them, it'll find them. If Unity is looking for them, it'll look in /usr/lib and and /usr/lib/xorg/modules/extensions, and we made sure that those symlink to the non-Nvidia ones.
This is possibly a bit clumsy in places, but what can I say? It works perfectly:
Unity 3D works will full desktop effects, and they're lightning fast but still using the energy-saving slow Intel chipset. Normal 3D acceleration is available to apps like VirtualBox. optirun works, and I have the choice of running "glxspheres" (at ~60 fps) or "optirun glxspheres" (at ~120 fps).


text:
Q: Python program in AWS Elastic MapReduce fails in step execution I'm trying to start a Python program in Elastic MapReduce Step Execution. It is a Spark Application with the following parameters:
Deploy-mode: Cluster
Spark-submit options: --executor-memory 1g
Application location: s3n://movielens-20m-dataset/Movie-Similarities-10m.py
Arguments: 260
Action on failure: Terminate cluster
Why does the Cluster fail on start-up?
This is my program script:
import sys
from pyspark import SparkConf, SparkContext
from math import sqrt

def loadMovieNames():
    movieNames = {}
    with open("s3n://movielens-20m-dataset/movies.dat") as f:
        for line in f:
            fields = line.split("::")
            movieNames[int(fields[0])] = fields[1].decode('ascii', 'ignore')
    return movieNames

def makePairs((user, ratings)):
    (movie1, rating1) = ratings[0]
    (movie2, rating2) = ratings[1]
    return ((movie1, movie2), (rating1, rating2))

def filterDuplicates( (userID, ratings) ):
    (movie1, rating1) = ratings[0]
    (movie2, rating2) = ratings[1]
    return movie1 < movie2

def computeCosineSimilarity(ratingPairs):
    numPairs = 0
    sum_xx = sum_yy = sum_xy = 0
    for ratingX, ratingY in ratingPairs:
        sum_xx += ratingX * ratingX
        sum_yy += ratingY * ratingY
        sum_xy += ratingX * ratingY
        numPairs += 1

    numerator = sum_xy
    denominator = sqrt(sum_xx) * sqrt(sum_yy)

    score = 0
    if (denominator):
        score = (numerator / (float(denominator)))

    return (score, numPairs)

conf = SparkConf()
sc = SparkContext(conf = conf)

print "\nLoading movie names..."
nameDict = loadMovieNames()

data = sc.textFile("s3n://movielens-20m-dataset/ratings.dat")

# Map ratings to key / value pairs: user ID => movie ID, rating
ratings = data.map(lambda l: l.split("::")).map(lambda l: (int(l[0]), (int(l[1]), float(l[2]))))

# Emit every movie rated together by the same user.
# Self-join to find every combination.
ratingsPartitioned = ratings.partitionBy(100)
joinedRatings = ratingsPartitioned.join(ratingsPartitioned)

# At this point our RDD consists of userID => ((movieID, rating), (movieID, rating))

# Filter out duplicate pairs
uniqueJoinedRatings = joinedRatings.filter(filterDuplicates)

# Now key by (movie1, movie2) pairs.
moviePairs = uniqueJoinedRatings.map(makePairs).partitionBy(100)

# We now have (movie1, movie2) => (rating1, rating2)
# Now collect all ratings for each movie pair and compute similarity
moviePairRatings = moviePairs.groupByKey()

# We now have (movie1, movie2) = > (rating1, rating2), (rating1, rating2) ...
# Can now compute similarities.
moviePairSimilarities = moviePairRatings.mapValues(computeCosineSimilarity).persist()

# Extract similarities for the movie we care about that are "good".
if (len(sys.argv) > 1):

    #change values while working with a sample set
    scoreThreshold = 0.97
    coOccurenceThreshold = 400

    movieID = int(sys.argv[1])

    filteredResults = moviePairSimilarities.filter(lambda ((pair,sim)): \
        (pair[0] == movieID or pair[1] == movieID) \
        and sim[0] > scoreThreshold and sim[1] > coOccurenceThreshold)

    results = filteredResults.map(lambda ((pair,sim)): (sim, pair)).sortByKey(ascending = False).take(10)

    #Write to file
    f = open("s3n://movielens-20m-dataset/movie-sims", "w")

    f.write("Top 10 similar movies for " + nameDict[movieID])
    print "Top 10 similar movies for " + nameDict[movieID]
    for result in results:
        (sim, pair) = result
        # Display the similarity result that isn't the movie we're looking at
        similarMovieID = pair[0]
        if (similarMovieID == movieID):
            similarMovieID = pair[1]
        f.write(nameDict[similarMovieID] + "\tscore: " + str(sim[0]) + "\tstrength: " + str(sim[1]))
        print nameDict[similarMovieID] + "\tscore: " + str(sim[0]) + "\tstrength: " + str(sim[1])
    f.close()

I get the following log:
2016-03-14T08:22:53.984Z INFO startExec 'hadoop jar /var/lib/aws/emr/step-runner/hadoop-jars/command-runner.jar spark-submit --deploy-mode cluster --executor-memory 1g s3n://movielens-20m-dataset/Movie-Similarities-10m.py 260'
2016-03-14T08:22:53.986Z INFO Environment:
  TERM=linux
  CONSOLETYPE=serial
  SHLVL=5
  JAVA_HOME=/etc/alternatives/jre
  HADOOP_IDENT_STRING=hadoop
  LANGSH_SOURCED=1
  XFILESEARCHPATH=/usr/dt/app-defaults/%L/Dt
  HADOOP_ROOT_LOGGER=INFO,DRFA
  AWS_CLOUDWATCH_HOME=/opt/aws/apitools/mon
  UPSTART_JOB=rc
  MAIL=/var/spool/mail/hadoop
  EC2_AMITOOL_HOME=/opt/aws/amitools/ec2
  AWS_RDS_HOME=/opt/aws/apitools/rds
  PWD=/
  HOSTNAME=ip-172-31-23-45
  LESS_TERMCAP_se=[0m
  LOGNAME=hadoop
  UPSTART_INSTANCE=
  AWS_PATH=/opt/aws
  LESS_TERMCAP_mb=[01;31m
  _=/etc/alternatives/jre/bin/java
  LESS_TERMCAP_me=[0m
  NLSPATH=/usr/dt/lib/nls/msg/%L/%N.cat
  LESS_TERMCAP_md=[01;38;5;208m
  runlevel=3
  AWS_AUTO_SCALING_HOME=/opt/aws/apitools/as
  UPSTART_EVENTS=runlevel
  HISTSIZE=1000
  previous=N
  HADOOP_LOGFILE=syslog
  PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/sbin:/opt/aws/bin
  EC2_HOME=/opt/aws/apitools/ec2
  HADOOP_LOG_DIR=/mnt/var/log/hadoop/steps/s-341AYJAV1HCS5
  LESS_TERMCAP_ue=[0m
  AWS_ELB_HOME=/opt/aws/apitools/elb
  RUNLEVEL=3
  USER=hadoop
  HADOOP_CLIENT_OPTS=-Djava.io.tmpdir=/mnt/var/lib/hadoop/steps/s-341AYJAV1HCS5/tmp
  PREVLEVEL=N
  HOME=/home/hadoop
  HISTCONTROL=ignoredups
  LESSOPEN=||/usr/bin/lesspipe.sh %s
  AWS_DEFAULT_REGION=eu-central-1
  LANG=en_US.UTF-8
  LESS_TERMCAP_us=[04;38;5;111m
2016-03-14T08:22:53.986Z INFO redirectOutput to /mnt/var/log/hadoop/steps/s-341AYJAV1HCS5/stdout
2016-03-14T08:22:53.986Z INFO redirectError to /mnt/var/log/hadoop/steps/s-341AYJAV1HCS5/stderr
2016-03-14T08:22:53.986Z INFO Working dir /mnt/var/lib/hadoop/steps/s-341AYJAV1HCS5
2016-03-14T08:22:54.022Z INFO ProcessRunner started child process 6515 :
hadoop    6515  2312  0 08:22 ?        00:00:00 bash /usr/lib/hadoop/bin/hadoop jar /var/lib/aws/emr/step-runner/hadoop-jars/command-runner.jar spark-submit --deploy-mode cluster --executor-memory 1g s3n://movielens-20m-dataset/Movie-Similarities-10m.py 260
2016-03-14T08:22:54.024Z INFO Synchronously wait child process to complete : hadoop jar /var/lib/aws/emr/step-runner/hadoop-...
2016-03-14T08:23:44.029Z INFO waitProcessCompletion ended with exit code 1 : hadoop jar /var/lib/aws/emr/step-runner/hadoop-...
2016-03-14T08:23:44.029Z INFO total process run time: 50 seconds
2016-03-14T08:23:44.155Z INFO Step created jobs:
2016-03-14T08:23:44.155Z WARN Step failed with exitCode 1 and took 50 seconds

A: Connecting to the Cluster via SSH and starting the program from the Terminal App "solves" the problem. The movies.dat file needs to be on the clusters local file system, too.


text:
Q: How to make bootstrap labels inline with scrolling x overflow within a bootstrap column Here is the code https://jsfiddle.net/bnb34kzm/ .

        Default
        Primary
        Success
        Info
        Warning
        Danger

        <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Action </button>

Action

.col-xs-6

I tried "white-space", "display:inline", etc. But in general, once I make the labels inline, they overflow the bootstrap column div. I couldn't find a way to restrict the width of div.input-group, while keeps it being a single line containing the div.form-control and div.input-group-btn.

A: Add this line of code in your html after .input-group class.


text:
Q: Hyperledger fabric Crypto materials If we see the crypto-config folder in basic-network of fabric-sample, we have various certificate materials with various types:
└── example.com
├── ca
│   ├── 0d46ccf0e9436c1bc3b6e2bf80cdb202c4943604f95c72ee0ff839d3ec300719_sk
│   └── ca.example.com-cert.pem
├── msp
│   ├── admincerts
│   │   └── Admin@example.com-cert.pem
│   ├── cacerts
│   │   └── ca.example.com-cert.pem
│   └── tlscacerts
│       └── tlsca.example.com-cert.pem
├── orderers
│   └── orderer.example.com
│       ├── msp
│       │   ├── admincerts
│       │   │   └── Admin@example.com-cert.pem
│       │   ├── cacerts
│       │   │   └── ca.example.com-cert.pem
│       │   ├── keystore
│       │   │   └── 2fb065725bf1b7e2811c0e8ca8d37f5a951fc4cd1162a47aad8accf9ddd10291_sk
│       │   ├── signcerts
│       │   │   └── orderer.example.com-cert.pem
│       │   └── tlscacerts
│       │       └── tlsca.example.com-cert.pem
│       └── tls
│           ├── ca.crt
│           ├── server.crt
│           └── server.key
├── tlsca
│   ├── 6a211ed18880b4db3867831c977809902713b8e321a5ab55ecc104dafc2eec49_sk
│   └── tlsca.example.com-cert.pem
└── users
    └── Admin@example.com
        ├── msp
        │   ├── admincerts
        │   │   └── Admin@example.com-cert.pem
        │   ├── cacerts
        │   │   └── ca.example.com-cert.pem
        │   ├── keystore
        │   │   └── db670eed8487a93c35ae448b9f84c2f241a7a8c87df0544fc1dc08baf7832aa0_sk
        │   ├── signcerts
        │   │   └── Admin@example.com-cert.pem
        │   └── tlscacerts
        │       └── tlsca.example.com-cert.pem
        └── tls
            ├── ca.crt
            ├── server.crt
            └── server.key

Can anyone explain why there are so too many of these files why are some of these files duplicated(such as ca.example.com-cert.pem have many copies) and there purpose.
What are .pem files used for?
What are .crt files used for?
What are .key files used for?
What are ** ...._sk** files used for?
And why the fabcar example manage it only by using 3 files.??
fabcar/creds
├── 5890f0061619c06fb29dea8cb304edecc020fe63f41a6db109f1e227cc1cb2a8-priv
├── 5890f0061619c06fb29dea8cb304edecc020fe63f41a6db109f1e227cc1cb2a8-pub
└── PeerAdmin

Thanks for your help

A: Each Organization requires a unique root certificate (ca-cert), that binds specific components (peers and orderers) to that organization.
Transactions and communications within Fabric are signed by an entity's private key (keystore), and then verified by means of a public key (signcerts).
As different organization also required to communicate or share their ledger so there is need of CA or MSP on organization level. Within each organization we can have multiple peers so we need certification for these peers too. Even peers from different organizations can join each other so signcerts(for authenticating) and TLScerts(for a secure handshake).
To have a look how these are generate i suggest you to Manually generate the artifacts
http://hyperledger-fabric.readthedocs.io/en/latest/build_network.html
and see the different certs in the folders inside as you created them.
These are keys used by fabcar to generate the above mentioned certificates.


text:
Q: How to send TLS client certificate with no certification chain without modifying Java application source? Gradle project needs to deploy build results to private Artifactory server. Latter requires client TLS authentication. User certificates are provided by server owner as a keystore with 1 private key entry, and that entry has certification chain of size 1:
Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

Alias name: myalias
Creation date: 08.09.2020
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=myuser, O=Sharaga Inc, C=Far far away
Issuer: CN=CA, O=Sharaga Inc, C=Far far away
...

When Gradle tries to connect to server, Java TLS implementation refuses to send client certificate:
*** CertificateRequest
Cert Types: RSA, DSS, ECDSA
Supported Signature Algorithms: SHA256withRSA, SHA256withDSA, SHA256withECDSA, SHA384withRSA, Unknown (hash:0x5, signature:0x2), SHA384withECDSA, SHA512withRSA, Unknown (hash:0x6, signature:0x2), SHA512withECDSA, SHA1withRSA, SHA1withDSA, SHA1withECDSA
Cert Authorities:
<CN=CA, O=Sharaga Inc, C=Far far away>
pool-1-thread-1, READ: TLSv1.2 Handshake, length = 4
*** ServerHelloDone
Warning: no suitable certificate found - continuing without client authentication
*** Certificate chain
<Empty>

This behavior is observed under Java 8 and Java 11, both on Linux and Windows.
I tried to access the server with test application by modifying key manager implementation so that it always chooses "myalias" to send to server, and it worked:
// Uses Artifactory client library:
// https://github.com/jfrog/artifactory-client-java

            PrivateKeyStrategy aliasStrategy = new PrivateKeyStrategy() {
                @Override
                public String chooseAlias(Map<String,PrivateKeyDetails> aliases, Socket socket) {
                    return "myalias";
                }
            };

            char[] password = "keystorepassword".toCharArray();

            Artifactory artifactory = ArtifactoryClientBuilder.create()
                .setUrl("https://theserver/artifactory")
                .setUsername("myuser")
                .setPassword("mypassword")
                .setSslContextBuilder(SSLContexts.custom().loadKeyMaterial(new File("mykeystore.pfx"), password, password, aliasStrategy))
                .build();

TLS debug output:
*** CertificateRequest
Cert Types: RSA, DSS, ECDSA
Supported Signature Algorithms: SHA256withRSA, SHA256withDSA, SHA256withECDSA, SHA384withRSA, Unknown (hash:0x5, signature:0x2), SHA384withECDSA, SHA512withRSA, Unknown (hash:0x6, signature:0x2), SHA512withECDSA, SHA1withRSA, SHA1withDSA, SHA1withECDSA
Cert Authorities:
<CN=CA, O=Sharaga Inc, C=Far far away>
main, READ: TLSv1.2 Handshake, length = 4
*** ServerHelloDone
matching alias: myalias
*** Certificate chain
chain [0] = [
[
  Version: V3
  Subject:CN=myuser, O=Sharaga Inc, C=Far far away
  Signature Algorithm: SHA256withRSA, OID = 1.2.840.113549.1.1.11
...

(Chain length is 1 here, but handshake succeeds.)
Is there a way to send client certificate without certification chain forcefully in existing Java application without changing/recompiling it? Maybe there are some system properties to tune this behavior?

A: After some debugging I found the reason. javax.net.ssl.keyStore* system properties do not affect Gradle Artifactory Plugin, it knew nothing about client certificate, and certificate chain was in fact empty (zero length).
If there is at least one certificate in a chain then it is sent to server successfully.


text:
Q: Single Server Multiple Virtual PCs remote access to Virtual PCs We want to setup one mega server (8GB RAM, Quad Core Processor) and install Virtual Machines for the following tasks.

*

*Virtual Machine for SVN server, Bug tracker

*Virtual Machine for Sharepoint portal development

*Virtual machine for IIS deployment for client access

we will be port forwarding request to virtual machine instance.
Can two developer can access different virtual machine using VNC at same time?

A: You can have multiple developers access different VMs using VNC and port forwarding, but I'd suggest assigning different IPs to each VM and using a bridged rather than NAT'd network configuration.
If you use NAT, the behaviour of accessing a VM differs depending on if you're accessing it from the main network or a different VM.
I'd also suggest RDP rather than VNC for remote access. The performance tends to be better, and it's one less piece of software to maintain.


text:
Q: "Interrupted system call" when reading test data in XCTestCase Using Xcode (11.4.1) on Catalina (10.15.4, only updated from Mojave 5 days ago), with a tiny SPM-based project opened in Xcode in "folder mode" (i.e. not an actual .xcodeproj), I have a test which should read some input data from a sample file. Following recommendations for constructing a URL to those files, Data(contentsOf:) cannot read it, although the generated URL is correct.
The code is:
func testCanReadConfigFromFile() {
    let thisDirectory = URL(fileURLWithPath: #file)
        .deletingLastPathComponent()

    let url = thisDirectory
        .appendingPathComponent("Test_data", isDirectory: true)
        .appendingPathComponent("Config.json", isDirectory: false)

    print(url.absoluteString)

    do {
        let _ = try Data(contentsOf: url)
    } catch let error {
        print(error)
        print(error.localizedDescription)
    }
}

The exception is:
Error Domain=NSCocoaErrorDomain Code=256 "The file "Config.json" couldn't be opened."
UserInfo={NSFilePath=/full/path/to/project/Tests/ProjectTests/Test_data/Config.json,
NSUnderlyingError=0x100b0aa30
{Error Domain=NSPOSIXErrorDomain Code=4 "Interrupted system call"}}

If I take the string output by print(url.absoluteString) and in a terminal execute file <absoulteString>, it confirms that my file does exist at that path (and that it is JSON).
"Interrupted system call" makes me think Catalina's stricter sand-boxing rules are to blame, but I have not been shown a permissions dialog. This project is within my ~/Documents folder, which Xcode does have permission to read.
Edited to add:
swift test at the command line works. It's only running tests in Xcode that exhibits the problem.


text:
Q: Issue authenticating Web api from MVC app I have MVC application and a Web Api hosted on different server. But i am not able to authenticate my web api's using ADFS if accessed from my mvc web app.
Getting "CORS Error"
Thanks in advance

A: You need to add Nuget Package Microsoft.ASP.Net.Cors and add [EnableCors("", "", "*")] attribute to your controller class
[EnableCors("*", "*", "*")]
public class YourController : ApiController
{
}

Add this in WebApiConfig.cs
public static void Register(HttpConfiguration config)
  {
    config.EnableCors();
  }

You may check this Link.

A: Please do not add a CORS filter with "*" (wild cards to allow any IP/Domain..).
Owasp's Cheat Sheet has some handy pointers and further information: https://www.owasp.org/index.php/HTML5_Security_Cheat_Sheet#Cross_Origin_Resource_Sharing


text:
Q: Django Issue Template Does Not Exist at /deals/ I am new Django user. When I run program in Django I got this error please help.
Template Does Not Exist at /deals/

{'form': <DealsForm bound=False, valid=Unknown, fields=(name;pages;email)>}

view.py
class DealsForm(ModelForm):
class Meta:
    model = Book
    fields = ['name','pages','email']

def deals(request):
    products = Product.objects.all()
    form = DealsForm()

    context = {'products': products}
    if request.method == "POST":
        form = DealsForm(request.POST, request.FILES)
        if form.is_valid():
           form.save()
           return redirect('products/deals')
    else:
        form = DealsForm()
        return render('products/deals.html',{'form': form}, context_instance=context)

A: Your mistake was the arguments to the render function, it waits parameters like
render(request, 'name_of_template.html', context_dict)
Also, check your form variable it must be inside of the context dictionary, try adding it this way before pass it to render:
context['form'] = form
These things should work now.


text:
Q: Validation for Multiple File upload using asp.net C# web forms I want to validate multiple uploaded files. It should accept only .png and .jpg files. Below is my code:
protected void uploadFile_Click(object sender, EventArgs e)
{
    if (multipleFile.HasFiles)
    {
        string filenameWithPath = string.Empty;
        foreach (HttpPostedFile uploadedFile in multipleFile.PostedFiles)
        {
            filenameWithPath = System.IO.Path.Combine(
                Server.MapPath("~/Uploads/"),
                uploadedFile.FileName);
            uploadedFile.SaveAs( filenameWithPath );
            ltStatusText.Text += "File-"
                + uploadedFile.FileName
                + " uploaded successfully.
";
        }
    }
}

A: I got answer.
Below is Design code:

<form id="form1" runat="server">
    <asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />
    <asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="UploadMultipleFiles" />

    <asp:Label ID="Information" runat="server" ForeColor="Green" />
</form>

Below is C# Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text.RegularExpressions;

public partial class CS : System.Web.UI.Page
{
 protected void UploadMultipleFiles(object sender, EventArgs e)
 {
  foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
   {
    string fileName = Path.GetFileName(postedFile.FileName);

        Regex reg = new Regex(@"^.*\.(jpg|JPG|jpeg|PNG|png)$");
        if (reg.IsMatch(fileName))
        {
            postedFile.SaveAs(Server.MapPath("~/Uploads/") + fileName);
            Information.Text = string.Format("{0} files have been uploaded successfully.", FileUpload1.PostedFiles.Count);
        }
        else
        {
            Information.Text = "files have been uploaded fail , please check file format!";
        }
    }
   }
  }


text:
Q: Does Gzip/Deflate recognize patterns I am studying the inner-workings of Gzip, and I understand that it uses a combination of Huffman Coding and LZ77.
I also realize that a Gzip file is divided into blocks, and each block has a dictionary built for it. Then frequent occurrences of similar data are replaced by pointers pointing at locations in the dictionary.
So the phrase "horses race other horses" would have the word horses replaced by a pointer.
However what if I have an array of 32 bit integers, but it only stores numbers up to 24 bits? For arguments sake lets say these 24 bit numbers are very random and hard to compress and hard to find repetition in.
This would make the first 8 bits of every integer an easy to compress string of 0's, but each string would need a pointer and each pointer still takes up some amount of data. Even a 1 bit pointer (which I know is smaller than what's realistically possible) would still take up 12.5% of the original space.
That would seem somewhat redundant when the array could easily be reduced to a "24 bit" array, with basic pattern recognition.
So my question is:
Does Gzip contain any mechanisms to better compress a file than dictionary pointers?
How well can Gzip compress small amounts of repetitive data, followed by small amounts of hard to compress data?

A: Each deflate block does not have a "dictionary built for it". What is built for each deflate block is a set of Huffman codes for the literal/length symbols and the distance symbols.
The dictionary you refer to is simply the 32K bytes of uncompressed input that immediately precede the bytes currently being compressed. That's it. Each length/distance pair can refer to a string of 3 to 258 bytes in the last 32K. That is independent of deflate blocks, and such references often go back one or more blocks.
Deflate will not do well trying to compress a sequence of three random bytes, zero byte, three random bytes, zero byte ... There will be no useful repeated strings, where deflate will only be able to Huffman code the literals, with zeros being more frequent. It would code zeros as two bits, since they occur a little more than 25% of the time, and the rest of the literals to at least 8.25 bits each. For this data that would give an average of about 6.7 bits per byte or a compressed ratio of 0.85. In fact gzip gives about 0.86 on this data.
If you want to compress that sequence, simply remove the zero bytes! Then you are done, with no further compression possible at a ratio of 0.75.


text:
Q: Trying to understand a proof of the Maximal ergodic theorem Let $(\Omega,\mathfrak A,P)$ be a probability space, $\Theta:\Omega\to\Omega$ be $(\mathfrak A,\mathfrak A)$-measurable with $P=P\circ\Theta^{-1}$ and $$A_n:=\frac1n\sum_{i=0}^{n-1}F\circ\Theta^i\;\;\;\text{for }F\in\mathcal L^1(P).$$
Let $F\in\mathcal L^1(P)$. I'm trying to understand the following proof of the Maximal ergodic theorem, $$\operatorname E\left[F;\max_{1\le i\le n}A_iF\ge0\right]\ge0\tag1$$ for all $n\in\mathbb N$:

First of all, shouldn't $$M_{n-1}\circ\Theta=M_n-F\tag2$$ hold everywhere (not only on $B$)? And what's the point of taking the positive part $x^+:=\max(x,0)$? It should clearly hold $$X=M_n-M_{n-1}\circ\Theta\ge M_n-M_n\circ\Theta\tag3,$$ since $M_n$ is (pointwisely) a maximum over a greater set than the set over which the maximum in $M_{n-1}$ is taken ... What am I missing?

A: It's not the case that $M_{n-1}\circ\Theta = M_n-F$ holds everywhere. Let's take $n=2$. Then $M_2 = \max(F,F+F\circ\Theta)$ and $M_1\circ\Theta = F\circ\Theta$. Then $M_2 = F+M_1\circ\Theta$ if and only if $F\circ\Theta \ge 0$. This is the point of taking positive part $x^+ = \max(x,0)$.


text:
Q: declaring New Microsoft.Office.Interop.Excel.Application outside of Sub makes the VSTO COM addin to freeze during loading I have created an Excel COM add in which opens a windows form from a ribbon button. I want to populate the combobox using data from an external excel spreadsheet as well as populate the textboxes based on the selected name.
The part of the form where this applies
when placing the block of code:
Dim ExcelApp = New Microsoft.Office.Interop.Excel.Application ' this is causing the issue
Dim ClientListBook = ExcelApp.Workbooks.Open("C:\Users\SoftwareDev\Desktop\ASSETS\MasterFile.xlsx")
Dim ClientListSheet = ClientListBook.Sheets(1)

below the Public Class Form1 as seen below:
Imports Microsoft.Office.Interop.Excel
Public Class Form1
    Dim ExcelApp = New Microsoft.Office.Interop.Excel.Application ' this is causing the issue
        Dim ClientListBook = ExcelApp.Workbooks.Open("C:\Users\SoftwareDev\Desktop\ASSETS\MasterFile.xlsx")
        Dim ClientListSheet = ClientListBook.Sheets(1)

    Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbClientName.SelectedIndexChanged

            End Sub

it causes the Add in to freeze
But when Placing the same block of code into the Sub Form1_Load and Sub  ComboBox1 as seen below, the add in works although it is very slow and i suspect it is an incorrect implementation.
THIS IS THE WORKING FULL CODE FOR THE FORM:
Imports Microsoft.Office.Interop.Excel
Public Class Form1

    Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbClientName.SelectedIndexChanged
        Dim ExcelApp = New Microsoft.Office.Interop.Excel.Application ' this is causing the issue
        Dim ClientListBook = ExcelApp.Workbooks.Open("C:\Users\SoftwareDev\Desktop\ASSETS\MasterFile.xlsx")
        Dim ClientListSheet = ClientListBook.Sheets(1)

        Dim iStartedRow As Integer
        Dim iTotalRows As Integer

        ' count the number of rows in the worksheet
        iTotalRows = ExcelApp.ActiveWorkbook.Sheets(1).Range("a1").CurrentRegion.Rows.Count

        ' populates the textboxes using clientList data

        For iStartedRow = 2 To iTotalRows
            If Me.cmbClientName.Text = ClientListSheet.Cells(iStartedRow, 1).text Then
                Me.txtSal.Text = ClientListSheet.Cells(iStartedRow, 4).text
                Me.txtInvMan.Text = ClientListSheet.Cells(iStartedRow, 5).text
            End If
        Next

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim ExcelApp = New Microsoft.Office.Interop.Excel.Application ' this is causing the issue
        Dim ClientListBook = ExcelApp.Workbooks.Open("C:\Users\SoftwareDev\Desktop\ASSETS\MasterFile.xlsx")
        Dim ClientListSheet = ClientListBook.Sheets(1)

        Dim StartedRow As Integer
        Dim TotalRows As Integer

        ' clear any existing data
        Me.cmbClientName.Items.Clear()

        ' count the number of rows in the worksheet
        TotalRows = ExcelApp.ActiveWorkbook.Sheets(1).Range("a1").CurrentRegion.Rows.Count

        ' create a loop to add data into combobox
        For StartedRow = 2 To TotalRows
            Me.cmbClientName.Items.Add(ClientListSheet.Cells(StartedRow, 1).Text)
        Next

    End Sub

End Class

Please would you let me know how i can correctly implement this and if it would be better and faster to use Microsoft Access database instead. I am new to VSTO COM add ins and VB.Net, this is my first project so i understand that my implementation may be suboptimal and will appreciate all feedback.
Thank you

A: If you declare and initialize these variables on the class level, they are created when the constructor runs.
There is absolutely no reason to initialize them immediately - you can declare them on the class level, but create them only when needed
Moreover, if your code is running in a VSTO addin, there is absolutely no reason to create an instance of the Excel.Application object -  it is already available to you.
Hardcoding the file path is obviously also a problem...
Public Class Form1
    Dim ExcelAppe
    Dim ClientListBook
    Dim ClientListSheet

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ExcelApp = Globals.ThisAddin.Application
        ClientListBook = ExcelApp.Workbooks.Open("C:\Users\SoftwareDev\Desktop\ASSETS\MasterFile.xlsx")
        ClientListSheet = ClientListBook.Sheets(1)


text:
Q: Differentiation under integration of a function of 3 variable Can anyone tell me why
$\frac{d}{dx}\int_a^x \int_c^d f(x,y,z)dz dy=\int_c^d f(x,x,z)dz+\int_a^x \int_c^d f_x(x,y,z)dz dy$ ?

A: Let $g(x,y) = \int_{c}^d f(x,y,z) \textrm{d}z$.
Then we have by Differentiation under the integral sign
\begin{eqnarray}
\frac{ \partial }{\partial x} \int_a^x g(x,y) \textrm{d}y &=& g(x,x) + \int_a^x \frac{ \partial }{\partial x} g(x,y) \textrm{d}y \\
&=& \int_c^d f(x,x,z) \textrm{d}z + \int_a^x \frac{ \partial }{\partial x} \int_c^d f(x,y,z) \textrm{d}z \textrm{d}y \\
&=&\int_c^d f(x,x,z) \textrm{d}z + \int_a^x \int_c^d \frac{ \partial }{\partial x} f(x,y,z) \textrm{d}z \textrm{d}y
\end{eqnarray}
We used the Differentiation under the integral sign in the first step on $g(x,y)$ and in the last step on $f(x,y,z)$.


text:
Q: How can I achieve dynamic for-loop? I have to list out all the sum of multiple array
For example I have a 2D array with dynamic length and the inititial length is 2, but the lenght will change dynamically.
Each element length must be 3.
function addSum(){
    let length =3;
    //calculate all sum of two array
    let arrayGroup = [[1,2,3],[1,2,3]]

    for(let i=0; i< length ;i++){
       for(let j=0; j< length ;j++){
           let sum = arrayGroup[0][i] +  arrayGroup[1][j]
           console.log(sum)
       }
    }
}

//result in console should look like:
//2
//3
//4
//3
//4
//5
......and so on

Additional Info:
arrayGroup = [[1,2,3],[1,2,3]]
1 st sum= 1+1
2 nd sum= 1+2
3 rd sum= 1+3
4 th sum= 2+1
5 th sum= 2+2
6 th sum= 2+3
7 th sum= 3+1
8 th sum= 3+2
9 th sum= 3+3
This is all the sum of a 2-element array

if arrayGroup is 3 element array [[1,2,3],[1,2,3],[1,2,3]]
1 st sum= 1+1+1 // arrayGroup[0][0] + arrayGroup[1][0] + arrayGroup[2][0]
2 nd sum= 1+1+2
3 rd sum= 1+1+3
4 th sum= 1+2+1
5 th sum= 1+3+1
6 th sum= 2+1+1
7 th sum= 3+1+1
....and so on, until list all the combination

The above code is to show how I get result of two elements, however when the number element in arrayGroup become N, how can I get all result of N element (i.e  arrayGroup = [[1,2,3],[1,2,3],.......,[1,2,3]])?

A: what you are trying to compute is called cartesian product of arrays, you can read this term ( or you will find cartesian product of sets in mathematics )

function cartesian(arr1, arr2) {
    const ans = [];

    for(let x of arr1) {
        for (let y of arr2) {
            ans.push(x + y);
        }
    }
    return ans;
}

let arr = [[1,2,3], [1,2,3], [1,2,3]];

let ans = [0];

for (let x of arr) ans = cartesian(ans,x);

console.log(ans)

also, we can simplify the code and make it shorter as well using some higher-order functions but try to understand the logic before going into syntactical improvements.
In short cartesian product is like multiplying two sets, what this code is doing is computing product for N lists by multiplying one list to the existing result at a time.
eg if you were to calculate a product of 1,6,5  you can do
ans = 1

for (let x in [1,6,5] ) ans = ans * x

Also note that if elements will always be [1,2,3], there can be faster methods to calculate the final result, because then there is a pattern to output as you are not calculating the cartesian product of random elements.

A: This is solution if I understood your question properly.

function addSum(){

    //calculate all sum of two array
    let arrayGroup = [[1,2,3],[1,2,3],[1,2,3]]
    let length = arrayGroup.length

    for(let i=0; i< length ;i++){
      let arr1 = arrayGroup[i]
      let position = i+1;
      if(position < length){
       let arr2 = arrayGroup[position]

        arr2.forEach(a=>{
          arr1.forEach(n=>{
          console.log(a+n)
          })

      })
      }

    }
}

addSum()


text:
Q: Spring Data Specification orderBy subquery On my MySql project I got this particular model with 3 entities: Prodotto with many childs QuotaIngrediente, that in turn is Many-to-One child of Ingrediente too. All my relationships are bi-directional.
All of them got an autogenerated integer Id and other fields removed to focus on the interesting ones.
@Entity
public class Prodotto {
    private List<QuotaIngrediente> listaQuoteIng = new ArrayList<QuotaIngrediente>();

    @OneToMany(mappedBy = "prodotto", cascade = CascadeType.ALL, orphanRemoval = true)
    public List<QuotaIngrediente> getListaQuoteIng() {
        return listaQuoteIng;
    }

@Entity
public class QuotaIngrediente{

    private Prodotto prodotto;

    private Ingrediente ing;

    private Double perc_ing;

    @ManyToOne
    @JoinColumn(name = "prodotto")
    public Prodotto getProdotto() {
        return prodotto;
    }

    @ManyToOne
    @JoinColumn(name = "ing")
    public Ingrediente getIng() {
        return ing;
    }

@Entity
public class Ingrediente {
    private Set<QuotaIngrediente> quoteIng = new HashSet<QuotaIngrediente>();

    @OneToMany(mappedBy = "ing", cascade = CascadeType.ALL, orphanRemoval = true)
    public Set<QuotaIngrediente> getQuoteIng() {
        return quoteIng;
    }

I'm using SpringData Specification and I can build a query to get Prodotto based on Ingrediente criteria, this way:
public static Specification<Prodotto> getProdottoByIngSpec (String ing) {

    if (ing != null) {
        return (root, query, criteriaBuilder) -> {
            query.groupBy(root.get(Prodotto_.id));

            return criteriaBuilder.like(((root.join(Prodotto_.listaQuoteIng))
                                                .join(QuotaIngrediente_.ing))
                                                .get(Ingrediente_.nome), "%"+ing+"%");
        };

It works as expected, but now I want to sort it by the QuotaIngrediente perc_ing field OF THAT SPECIFIC INGREDIENTE.
Obviously I'm asking how to do it on DB, not in business logic.

A: I was struggling with a false problem due to a wrong assumption of mine. Solution was the simplest. Just sort by orderBy CriteriaQuery method. The query I used to search already filtered the QuotaIngrediente returning just the lines that match my search criteria. Then this is the only line I had to add to my Specification:
query.orderBy(builder.desc((root.join(Prodotto_.listaQuoteIng))
                                   .get(QuotaIngrediente_.perc_ing)));


text:
Q: Is there a (effective) way to get 5 records to the left and right of a specific record with Access SQL? Like the title says, I am trying to do a SELECT statement where I am selecting 1 specific record (the one the person searched for) but I also want to get 5 records (the 5 that come before and after the specific one) to the right and left of the specific searched record, while keeping the current/focused record on the searched one.
The records ID's (where they search for) consist out of date values combined with numbers. So for example in this month the first created record looks like this 1602030001 <-- Year(16), month (02), day (03) and first record (0001). So the second one they create this month will be 1602030002 and so on.
So if they search for record 16020050 (50th record in February) I want to show records 16020044 to 16020055.
I already did something like this but it has a downside:
Get the searched record (16020050) and in VBA set a max and min variable (int) to do -5 and + 5 to the searched record number. Then use these variables to do a SELECT like:
SELECT * FROM SearchRecord WHERE ID > MinVariable (16020044) AND ID < MaxVariable (16020055)
However, the downside to this is that when the month February for example has only 500 records so 16020500 and then march started (16030001) and the person is searching for the 500th record on February it would also search for records that don't exist (up to 505 while that 5 are already in March --> 16030005).
I don't know a more effective/smarter way to get those 5 extra record to each side and also maintain logic that if you search for the last record in a specific month that the 5 records to the right will start in the next month.
I hope it makes sense;)

A: For a table named [MyTable]
ID
--------
16020493
16020494
16020495
16020496
16020497
16020498
16020499
16020500
16030001
16030002
16030003
16030004
16030005
16030006
16030007

we can get the starting ID of the range centred around ID=16020500 by using the query
SELECT MIN(ID) AS StartID
FROM
    (
        SELECT TOP 6 ID
        FROM MyTable
        WHERE ID <= 16020500
        ORDER BY ID DESC
    )

which returns
StartID
--------
16020495

and we can simply use that query as a subquery in the WHERE clause of a query to return the 11 rows (5 before + the main one + 5 after):
SELECT TOP 11 *
FROM MyTable
WHERE
    ID >= (
        SELECT MIN(ID) AS StartID
        FROM
            (
                SELECT TOP 6 ID
                FROM MyTable
                WHERE ID <= 16020500
                ORDER BY ID DESC
            )
    )
ORDER BY ID

returning
ID
--------
16020495
16020496
16020497
16020498
16020499
16020500
16030001
16030002
16030003
16030004
16030005

A: I have to imagine this is won't be fast though it is a fairly elegant way to think about the problem. This was more common when top didn't exist. The initial filter should help restrict the search to a window of ids around the previous two months (assuming there are always at least five records in a month).
select *
from SearchRecord sr1
where
        id between [Id:] / 10000 * 10000 - 9999 and [Id:] / 10000 * 10000 + 10005
    and (select count(*) from SearchRecord sr2 where sr2.id between sr1.id and [Id:]) <= 6
    and (select count(*) from SearchRecord sr3 where sr3.id between [Id:] and sr1.id) <= 6

A: I tried to simulate your situation, I created a table variable (you can skip this you have your table) and I used to do the right statement but I dont think this is the best optimized statement. Anyway it worked for my simulated table.
DECLARE @SearchRecord TABLE (ID BIGINT)

DECLARE @i INT=1
WHILE @i<=50
BEGIN
    INSERT INTO @SearchRecord SELECT 16020000+@i
    INSERT INTO @SearchRecord SELECT 16030000+@i
    SET @i=@i+1
END

--Your Logic
DECLARE @SearchedID INT= 16020050
DECLARE @Minid INT
DECLARE @Maxid INT
DECLARE @NearID INT
SET @i=0
SET @NearID=@SearchedID
WHILE @i>=-5
BEGIN
    IF EXISTS (SELECT * FROM @SearchRecord WHERE id=@nearID)
    BEGIN
        set @minid=@nearID
        PRINT @minid
        SET @i=@i-1
    END
    SET @nearID=@nearID-1
END
SET @i=0
SET @nearID=@SearchedID
WHILE @i<=5
BEGIN
    IF EXISTS (SELECT * FROM @SearchRecord WHERE id=@nearID)
    BEGIN
        set @maxid=@nearID
        PRINT @maxid
        SET @i=@i+1
    END
    SET @nearID=@nearID+1
END

SELECT * FROM @SearchRecord WHERE (ID BETWEEN @minid AND @maxid) OR id=@searchedID  ORDER BY id


text:
Q: iBooks Author custom layout I'm looking to build an iBook with iBooks Author which would require a jQuery masonry-esque layout and I have scoured the web for documentation, help, tutorials, and articles that may help me embark on this project but to no avail. I know custom layouts are possible because the project uses this iBook as a reference. Would anyone be able to point me in the right direction that may help me in this quest? I must first say that I'm a front-end developer by trade and I've never created an iBook before.
Thank you in advance!

A: The layouts are all editable when using the graphical interface of iBooks Author. I don't see why you couldn't edit the files on the filesystem if you wanted to do advanced editing, but for most uses the GUI works well for my needs.
Start with a template you like and open it:

*

*View menu -> Show Layouts

*make your changes

*File menu -> Save as Template...


text:
Q: null handling in ORACLE Stored Procedure is like below.
CREATE OR REPLACE PROCEDURE FIRSTPROC (ID1 IN VARHAR2, ID2 OUT NUMBER )
AS

BEGIN
 SELECT id2val INTO ID2
 FROM
 WHERE id1val = ID1;
END

If i am passing
if i pass valid value then i am getting the output.
ID1 := 5;
ID1 as NULL  VALUE I AM GETTING run time ERROR in the SELECT statement. Please note my table contains NULL values also. How to handle this condition.
ID1 := null;
 calling the procedure
Please let me know what changes i need to make?

A: NULL is not equal to NULL.  So when you are passing in NULL, and doing a query using only an equality condition, you can't get a match.  So I assume you are getting a no-data-found exception (P.S. instead of saying you are getting "an error" it can be helpful to say specifically what error you are getting).
You have to handle NULL explicitly.
SELECT id2val INTO id2
FROM whatever
WHERE ( id1val = id1 OR (id1val IS NULL AND id1 IS NULL) )

Another possibility is to use a condition like NVL( id1val, -1 ) = NVL( id1, -1 ), where -1 is some value that will never actually occur in your data. But this is dependent on choosing a good sentinel value, and can impact the effectiveness of indexes on the query.
Note that if your table contains multiple rows with NULL values for ID1VAL, this query will then raise too-many-rows.

A: NULL is not equals to NULL, but you can use the nvl function to fix your equality like this
WHERE nvl(id1val, 'na')=nvl(id1, 'na')

A: Comparing whether a NULL value is equal to another value (including another NULL) will always return false. Instead you can compare if the two values are equal or if the first value IS NULL and the second value IS NULL.
Amending my previous answer to your last question:
CREATE OR REPLACE PROCEDURE FIRSTPROC (
  ID1 IN  table_name.id1val%TYPE,
  ID2 OUT table_name.id2val%TYPE
)
AS
BEGIN
  SELECT id2val
  INTO   ID2
  FROM   table_name
  WHERE  ( id1val = ID1 OR ( ID1 IS NULL AND id1val IS NULL ) );
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    ID2 := NULL;
  WHEN TOO_MANY_ROWS THEN
    ID2 := NULL;
END;
/


text:
Q: Java, why are objects known as instances of a class? Classes are a software bundle of variables and functions, also known as a blueprint that defines the variables and methods common to objects of a certain kind. So why are objects also known as instances of a class?

A: Like you said, class is a blueprint; objects are made using those blueprints.
Its like you have a blueprint of a car - you have one blueprint, but many cars based on that blueprint.

A: According to dictionary.com: An instance is - "an example or single occurrence of something"
An object is a single occurrence or realization of a class.

A: Class is a syntactic notion, governed by compile time rules, such as naming, scope, etc. That your program defines a class A means that 1) you have a type, and 2) that the right class loader will be able to find A's bytecode on the classpath. But it doesn't mean that your running program is able to operate on this class. An operable object with its own state must be first instantiated with new, which, at run time, will cause the classloader to allocate memory required to hold that state. You can have any number of objects of a single class A, all of type A but with their own state memory.


text:
Q: Accessing members of associated @OneToOne entity in POST_LOAD event listener I have two entities that look similar this:
EntityA:
@Entity
@Getter
@Setter
@Table(name = "TABLE_A")
    public class EntityA implements SomeInterface {

    @Id
    @Column(name = "A_ID")
    private Long id;

    @OneToOne(mappedBy = "entityA")
    private EntityB entityB;

    @ManyToOne
    @JoinColumn(name = "A_C_ID")
    private EntityC entityC;

    ...
    some other fields

    @Override
    public EntityC retrieveEntityC() {
        return getEntityC();
    }
}

EntityB:
@Entity
@Getter
@Setter
@Table(name = "TABLE_B")
public class EntityB implements SomeInterface {

    @Id
    @Column(name = "B_ID")
    private Long id;

    @OneToOne(fetch = FetchType.EAGER, optional = false)
    @JoinColumn(name = "B_A_ID", unique = true, nullable = false)
    private EntityA entityA;

    ...
    some other fields

    @Override
    public EntityC retrieveEntityC() {
        return getEntityA().retrieveEntityC();
    }
}

I have implemented Hibernate event listener of type POST_LOAD. When Hibernate tries to load EntityA, it triggers loading of its child - entityB - first. When entityB is loaded, the POST_LOAD event is fired and my event listener is beeing called (in context of EntityB). In my listener I call retrieveEntityC() method from entityB, which calls retrieveEntityC() method from entityA to finally get entityC from entityA. The problem is that I get NULL instead of exact entityC object. The entityA object is just a proxy, with only id field populated and other fields set to NULL. Calling a getter does not result in retrieving an object from database as I would suspect.
In this scenario, is there any way to make Hibernate actually get entityC from database?


text:
Q: Suppress tslint messages when 'ionic serve' Does anybody have an idea how can I suppress tslint messages in terminal when running 'ionic serve'?
I have imported some external components and there are pretty much unused imports there that's filling up my terminal container quite quickly and prevent me to see other important messages there. There are also other warnings there that are not so important so I just want to suppress that.
Tks

A: It seems that changing the rules in configuration file tslint.json can help with that.
  {
   ...
   "rules": {
      "no-duplicate-variable": true,
      "no-unused-variable": [
        false
      ]   },
   ...
   }

Or a pattern can be used, like here:
https://palantir.github.io/tslint/rules/no-unused-variable/


text:
Q: AppFabric / WF 4.0 instances stuck despite no bookmark and pending timer I already posted a question about this (Abandoned instances that will not continue execution (zombie instances)), but still haven't got an answer.
A difference I have noticed from the last question is that it can happen also when the configuration of the service Action on unhandled exception is set AbandonAndSuspend.
So the scenario is a long term Workflow service hosted in IIS using AppFabric persistence store. This service performs some actions and then polls the result from a database. This polling is done every 30 minutes. For some reason the WF gets stuck and doesn't do anything else. Checking the InstancesTable I can see a past pending timer and an old LastUpdateTime.
The only workaround I found is to suspend and then resume the instances, which is obviously a painful process (there are around 5000 instances in this situation).
Thanks in advance

A: The problem, as suspected, was related to the maximum number of concurrent instances. Due to some technical problems in a WCF that might be unavailable, there were a number of instances continuously running (retrying a call to that WCF) that were coping that number of maximum concurrent instances. Due to that, there were very few instances activated on every detection period. Thanks Maurice for your help


text:
Q: ReverseMatch error in Django password reset views I have been following some online tutorial on how to setup the Django email reset views but I still get the reverse match error:
Reverse for 'django.contrib.auth.views.password_reset_confirm' with arguments '()' and keyword arguments '{'uidb36': '2', 'token': '3fk-e9d14405e0aaf252475e'}' not found

My URLs setting are like this:
url(r'^login_retrieval/$', 'django.contrib.auth.views.password_reset',
    {'post_reset_redirect' : '/login_retrieval_done/',
     'template_name' : 'core/password_reset_form.html'}),
url(r'^login_retrieval_done/', 'django.contrib.auth.views.password_reset_done'),
url(r'^password_reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'django.contrib.auth.views.password_reset_confirm',
    {'post_reset_redirect' : '/user/password/done/'}),
url(r'^user/password/done/$',
    'django.contrib.auth.views.password_reset_complete'),

I can get to the email address input page but when I click send email, it just returns the reverse match error.
Can anyone help me?
Thanks.

A: Have you updated to Django 1.6 or above?
If so, you just have to replace uidb36 with uidb64. This applies to {% url ... %} calls in templates, reverse() calls in Python code and the regexes in your urls.py.
Picking one example from your urls.py:
url(r'^password_reset/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', 'django.contrib.auth.views.password_reset_confirm',
    {'post_reset_redirect' : '/user/password/done/'}),

See Django 1.6 Release Notes