text:
Q: SQL Server linked server performance on Oracle after upgrade 2008->2016 I have had a running SQL Server 2008 instance for years where I have several interfaces to an ora11 database exchanging data day for day, everything has been running correctly.
For few days now since upgrading from SQL Server 2008R2 to 2016 and importing the whole SQL Server 2008 database into our new SQL Server 2016 instance.
We were re-establishing our interfaces and everything looked good. I had created the linked server with an ora11 client connecting to the ora11-db. connected worked fine.
But since then, the stored-procedures which I was using in my interfaces, took a lot of more time for running. On SQL Server 2008R2, the linked server updates to ora11 took about a few minutes. The completely same procedure now takes about a few hours for the same number of rows updating to oracle.
My interface procedures almost look like this:

*

*collect local data using a cursor

*iterate through the cursor, looking in the remote database using linked server if the record exists

*insert the missing record using linked server in Oracle db

*close everything and complete
Why is it suddenly that much slower using the exactly the same source? Is there anything new in SQL Server 2016 which needs to be configured properly?
What is wrong?


text:
Q: How to call a service method from another service method with "intent"? I'm completely new to java. I've the following code in which I'm trying to retrieve a value from a database, but I need the value to be returned as a variable:

*

*The caller:

private String readInfo(String parameter, String option) {

        // some data conversion

        Context conVar = this;
        Intent intent = new Intent(conVar, FlipKRetriev.class);
        Log.d("LogMail", "Intent Create");
        //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Log.d("LogMail", "Add Flags");
        conVar.startService(intent);

        //no idea how to call FlipKRetriev.rgetData and return its variable

        Log.d("LogMail", "Start Intent");
        return "Missing Variable from FlipRetriev.rgetData";

    }

*

*The class and function that are getting called:

package com.flipkeyboard;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.os.IBinder;
import android.util.Log;

public class FlipKRetriev extends Service {
    private FlipKDataBas jVarDB;

    @SuppressLint("Range")
    public CharSequence rgetData(String parameter, String options) {
            Log.d("LogMail", "Reached getData");

        jVarDB = new FlipKDataBas(this);

            int iConCCTS = jVarDB.conCCTS();

            Log.d("LogMail", String.valueOf(iConCCTS));
            Log.d("LogMail", "Called DB");

        // some data conversion...
        String varRet, varRet1, varRet2;
        return varRet;
    }
}

*

*And the method "conCCTS" within its "SQLLiteOpenHelper" call:

package com.flipkeyboard;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class FlipKDataBas extends SQLiteOpenHelper {

    public static final String DBA_CCTS = "FlipKDB.db";
    public static final String TAB_CCTS = "CCTS";
    public static final String COL_ID = "ID";
    public static final String COL_NAME = "NAME";
    public static final String COL_EMAL = "EMAL";
    public static final String COL_PHWK = "PHWK";
    public static final String COL_PHMB = "PHMB";
    public static final String COL_CITY = "CITY";
    public static final String COL_CTRY = "CTRY";

    public FlipKDataBas(Context conVar) {
        super(conVar, DBA_CCTS, null, 1);
        Log.d("LogMail", "FlipKDataBas OK");
    }

    @Override
    public void onCreate(SQLiteDatabase varDB) {
        // some code...
    }

    @Override
    public void onUpgrade(SQLiteDatabase varDB, int i, int i1) {
        // some code...
    }

    public int conCCTS() {
        SQLiteDatabase varDB = this.getReadableDatabase();
        Log.d("LogMail", "Count DB");
        return (int) DatabaseUtils.queryNumEntries(varDB, TAB_CCTS);
    }
}

The problem is that I've no idea on how to call the method "rgetData" from the "intent" I'm using in "readInfo".
Any help is appreciated.

A: I was able to resolve this with a workaround:
This basically changes the "intent" method for a more specific series of calls to the FlipKRetriev class.
        // This is to fetch the information from the database
        FlipKRetriev cls = new FlipKRetriev();
            Context conVar = this;

            cls.parameter = txtPar;
            cls.options = option;
            cls.rStartSrv(conVar);
            retValFKR = cls.rgetData();

Where:

*

*parameter/options are variables that I send to the new class.

*retValFKR is the expected return from the initial class that I'm assigning the results to.

The error that I was getting was that I was not passing the Context from the first class to the second one (I was using "this" directly in the second class), which is needed to be able to link them.
    public void rStartSrv(Context context) {
        //parameter = (String) intent.getExtras().get("parameter");
        //options = (String) intent.getExtras().get("options");
        Log.d("LogMail", "Reached On Receive");
        jVarDB = new FlipKDataBas(context);
        int iConCCTS = jVarDB.conCCTS();
        Log.d("LogMail", String.valueOf(iConCCTS));
        Log.d("LogMail", String.valueOf(parameter));
        Log.d("LogMail", String.valueOf(options));
    }

Without the context, the database variables were unable to be called.

redpajama_set_name: RedPajamaStackExchange


text:
Q: what will be happen when using more than one form tag in ASP.Net application? what will be happen when using more than one form tag in web application?
I am using form tag in master page and alos in child page. but it shows error.

A:
what will be happen when using more than one form tag in web application?

You can use as many <form> elements in a page as you want (though they cannot be nested). But, as you've noticed, you can only have only one <form runat="server"> element in each composed Page instance (that is, the control layout of all composed .master pages around the current .aspx page and any child Control or .ascx UserControl instances).
This is because ASP.NET WebForms is built around the assumption that each user's action (a button click, a <select> selection change, a radio-button click, etc) would trigger a "whole page post-back" which would reload the entire page in a POST response, which (combined with __VIEWSTATE) would bring a model similar to VB6 desktop forms to to the web.
...but this was back in 2001 when ASP.NET WebForms was released, and since then everyone has realized that WebForms' "postback" model was a huge mistake and literally broke the web (because it breaks the back-button, it broke the refresh button, it broke the semantics of HTTP methods, and it would transform the web from being a scalable and stateless system into being a horrible stateful system with no real benefits to anyone other than a slightly shallower initial learning-curve for a fraction of software developers who never left their Visual Basic comfort zone).
In short: Stop using ASP.NET WebForms and migrate to ASP.NET MVC as soon as you're able to.


text:
Q: If $x^* (x)=0$ for all $x^* \in X^*$, then $x=0$? If $X$ is any arbitrary vector space, and $X^*$ is its dual, is it true that if $x^* (x)=0$ for all $x^* \in X^*$, then $x=0$?

A: we can use Hahn-Banach theorem to prove it , we take x such that x $\neq$ 0 , we define a functional on $span(x)$ such that $f(x)=1$ for example ...
then there is an extention of $f$ in $X$ .

A: I am going to put my own answer here, expounding on Abderrahim Abdou's. We will use the second form of Hahn-Banach theorem (which can be found on Wikipedia). Suppose for contradiction that $x \neq 0$, then $\text{span}\{x\}$ is nontrivial, and $f(\alpha x)=\alpha$  for every $\alpha \in \mathbb{K}$ is a linear functional on $\text{span}\{x\}$. Consider the seminorm $g$ on $X$ where $g(y)=|f(y)|$ for $y \in \text{span}\{x\}$ and $0$ otherwise. Since $|f| \leq g $ in $\text{span} \{x\}$, then by Hahn-Banach theorem, $f$ extends to a linear function in whole of $X$, therefore, $f \in X^*$, but $f(x)=1 \neq 0$ which is a contradiction.


text:
Q: How to set google protobuf repeated field in java Here is my definition
message point{
  optional float x = 1;
  optional float y = 2;
}
message test{
  repeated field point = 1;
}

In my example.java file I am trying to create a builder as follows:
for(i = 0; i < somearr.size(); i++)
{
    // I get x and y values from traversing the array
    float x = getX;
    float y = getY;

    // now I want to set the repeated field point
}

How do I set the repeated field points?

A: List<Point> points = ...;
Test.newBuilder().addAllPoint(points);

A: Very similar to repeated PhoneNumber example here.
Capitalizing those messages will help code readability.
message Point {
  optional float x = 1;
  optional float y = 2;
}
message Test {
  repeated Point point = 1;
}

java:
Test.Builder b = Test.newBuilder();

for (i = 0; i < somearr.size(); i++) {
    float x = getX; // somehow?
    float y = getY; // ??
    b.addPoint(Point.newBuilder().setX(x).setY(y).build());
}

Test mytest = b.build();


text:
Q: Dropping groups and sub-groups from a list So I have two item lists:
item_list = [
    'item 01-01-01', 'item 01-01-02', 'item 01-01-03',
    'item 01-02-01', 'item 01-02-02', 'item 01-02-03',
    'item 01-03-01', 'item 01-03-02', 'item 01-03-03',

    'item 02-01-01', 'item 02-01-02', 'item 02-01-03',
    'item 02-02-01', 'item 02-02-02', 'item 02-02-03',
    'item 02-03-01', 'item 02-03-02', 'item 02-03-03',

    'item 03-01-01', 'item 03-01-02', 'item 03-01-03',
    'item 03-02-01', 'item 03-02-02', 'item 03-02-03',
    'item 03-03-01', 'item 03-03-02', 'item 03-03-03']

faulty_item_list = [
    'item 01-01-01',
    'item 01-02-01', 'item 01-02-02', 'item 01-02-03',
    'item 01-03-01', 'item 01-03-02', 'item 01-03-03',

    'item 02-01-01', 'item 02-01-02', 'item 02-01-03',
    'item 02-02-01', 'item 02-02-02', 'item 02-02-03',
    'item 02-03-01', 'item 02-03-02', 'item 02-03-03',

    'item 03-01-01', 'item 03-01-02', 'item 03-01-03',
                     'item 03-02-02', 'item 03-02-03',
    'item 03-03-01', 'item 03-03-02', 'item 03-03-03']

And I want to drop all items that make up a group or sub-group so that I can return the following items:
['item 01-01-01', 'item 03-02-02', 'item 03-02-03']

What maybe the best the approach?

A: You can do something like this with list comprehension:
[ item
  for item in faulty_item_list

  # counts how many elements have the same start as the item, except for the last 2 chars
  if sum( other_item.startswith(item[:-2])
          for other_item in faulty_item_list ) < 3
]

Another way to do it, might be better for larger lists:
group_dict = {}

for item in faulty_item_list:
    group_id = item[:-2]
    if group_id not in group_dict:
        group_dict[group_id] = [ 1, [item] ]
    else:
        group_dict[group_id][0] += 1
        group_dict[group_id][1].append(item)

[ item
  for group_id,(count,item_list) in group_dict.items()
  for item in item_list
  if count < 3 ]


text:
Q: External API call in Google Spreedsheet is possible? I have created a Google Spreadsheet with five columns;
Once the user filled the values in the first three columns, It has to call a 3rd party API and fill the value(response) in the forth and fifth columns.
Is it possible to write a code in Google Spreadsheet for API call?
Is it possible to call and get response from external API in Google Spreadsheet?

A: I've recently come accross the same requirement to read the rows of the sheet and send the data in request and record the response. I thought I would share what I worked out after googling a bit...
function testing_this() {
    var data = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
    for (row in data) {
        Logger.log(data[row]);

        var row = data[row]
        var options = {
            'method': 'post',
            'payload': { email:row[1]}
        };
        // sending to API. for example:
        UrlFetchApp.fetch('https://your-rest-api-url/v1/customers/', options);
    }
}

If you want to get the data in the sheet you should use the function:
var response = UrlFetchApp.getRequest("http://your-api-url/");
    for(data in response) {
        var respData = response[data];
        // do whatever u want to do with this data...
    }

Hope it is useful to you all who are facing similar requirement as above.
I've posted this script in github if you want to fork/pull...
https://github.com/joshiparthin/gsheetScriptExperiments/blob/master/readAndSendToApi.js
Cheers,
Parth

A: I can only echo the answer recommending using the powersheets.app extension for Google Sheets.
I had a long list of text paragraphs to translate from one language to another. Something like "in cell A2 is the original text", "in cell B2 I want an automated translation", a thousand times.
Deepl.com provides APIs for free - up to a certain volume - and calling them from Google Sheets with the powersheets extension was a snap:
=JSONPATH(API(CONCATENATE("https://api-free.deepl.com/v2/translate?text=";ENCODEURL(A2);"&target_lang=DE&auth_key=xxxMyDeeplKEYxxx"));"translations.0.text")

A: There's a way to make API calls and have the results go into a spreadsheet - the only way I know to do it is create/open the target spreadsheet, go to tools and then Script editor, and use this as a bound script:
function Maestro() {
var ss = SpreadsheetApp.getActiveSpreadsheet(); //get active spreadsheet (bound to this script)
var sheet = ss.getSheetByName('mae'); //The name of the sheet tab where you are sending the info

var apiCall = 'getUpcomingConference';
var apiKey = '_____key here______';
var apiToken = '______security token______';
var url = 'http://myaccount.maestroconference.com/_access/' + apiCall +"?customer=" + apiKey + "&key=" + apiToken; //api endpoint as a string

var response = UrlFetchApp.fetch(url); // get api endpoint
var json = response.getContentText(); // get the response content as text
var mae = JSON.parse(json); //parse text into json

Logger.log(mae); //log data to logger

var stats=[]; //create empty array to hold data points

var date = new Date(); //create new date for timestamp

//The number in brackets refers to which instance we are looking at - soonest upcoming call is [0], next after that is [1], etc.
stats.push(date); //timestamp
stats.push(mae.value.conference[0].name);
stats.push(mae.value.conference[0].scheduledStartTime);
stats.push(mae.value.conference[0].UID);

//append the stats array to the active sheet
sheet.appendRow(stats);
}

It needs a little interface work but functions! It takes info from an API call and puts it in a spreadsheet.

A: For simple requests you can use IMPORTDATA.
Example query to a JSON API =IMPORTDATA("https://jsonplaceholder.typicode.com/todos/1")
Visual example of what you'll get with IMPORTDATA
If you need something more advanced, I found the extension KPIBees. You simply download it from the marketplace and you're ready to make queries. It has a variety of integrations including Google (Ads, Analytics, Search Console), Facebook Ads, CSV, JSON and much more.
I tried JSON and it works perfectly. It supports request headers (useful for APIs with authentication) and it allows you to choose among different display strategies based on how you want your data to be in your sheet.
Visual example of what you'll get with KPIBees
Screenshot of KPIBees GUI

A: Using the ImportData function with https://github.com/bradjasper/ImportJSON this custom functions (read the readme for more info)


text:
Q: Getting Combinations of Unique Column I want to know if someone knows of a python function that returns a combination of columns without repetition. For example
a= [[1,2],
    [3,4]]
# 1,4 is allowed since not the same column.
# 2,3 is allowed since not the same column.
# 1,3  is not allowed since its the same column.
# 2,4 is not allowed since its the same column.

Even if its a custom function you have made I would like to see it and understand the logic behind it.
Also if possible I want functions from modules readily available in python by default so don't want something like numpy where I have to manually install it via pip.
Thanks :)

A: You can use itertools.product and exclude items in the same column after generating column indices using enumerate:
from itertools import product

def prod(*args):
   for (i, x), (j, y) in product(*map(enumerate, args)):
      if i != j:
         yield (x, y)

a= [[1,2],
    [3,4]]
print(list(prod(*a)))
# [(1, 4), (2, 3)]

a= [[1,2,3],
    [4,5,6]]
print(list(prod(*a)))
# [(1, 5), (1, 6), (2, 4), (2, 6), (3, 4), (3, 5)]

You can generalize this for multiple rows and columns by checking that no column in each combination is repeated:
from itertools import product

def prod(*args):
   for items in product(*map(enumerate, args)):
      if len({i for i, _ in items}) == len(items):
         yield tuple(x for _, x in items)

A: For larger square matrices, you could take use permutations of columns:
from itertools import *

b = [
        [1,2,3],
        [4,5,6],
        [7,8,9],
    ]

def combs(mat=b):
    ncols = len(b[0])
    yield from ([mat[i][j] for i, j in inds]
            for inds in map(enumerate,
                permutations(range(ncols))))

# In [86]: list(q.combs())
# Out[86]: [[1, 5, 9], [1, 6, 8], [2, 4, 9], [2, 6, 7], [3, 4, 8], [3, 5, 7]]

Regarding the last line: given an N x N matrix, there are exactly N! ways to pick an element from each row without ever picking two or more from any column: You have N choices in the first row, N-1 in the second, etc. Hence, each combination that meets your requirement is pinned down by a permutation. map(enumerate, permutations(range(ncols))) gives a list of all valid indexes. For a given index inds, [mat[i][j] for i, j in inds] gives a list corresponding to that index.


text:
Q: Duplicate CSS Declarations Stripped By Browser(s)? I have a PHP application that I must dynamically generate a stylesheet for. The stylesheet has a .php file extension, but I set the Content-Type of the file to text/css via the header function (PHP), and then create properly formed CSS to suit my purpose and include this stylesheet in my page.
The issue I'm seeing is that when I view the CSS file through whatever browser tool I choose - be it Firebug, Chrome Dev Tools or IE Dev Tools, certain class declarations are missing (and it is evident as what is rendered by the browser - those classes don't exist).  When I check the raw output of the file (as in, put the address of the PHP CSS file in the browser to view the raw text), the missing class declarations are indeed there.
What's missing is usually a second (or nth) class that specifies the same background-color value, but different class name.
Here's a specific example:
In the raw output, I have these two classes:
#draft-board div.pick.RB{
  background-color: #FFCC66;
}

#draft-board div.pick.1B {
  background-color: #FFCC66;
}

But in the browser, it only sees:
#draft-board div.pick.RB{
  background-color: #FFCC66;
}

Why is this?
Here's a public example page:
http://www.phpdraft.com/public_draft.php?action=draftBoard&did=9
(and here's the raw CSS output for that page:)
http://www.phpdraft.com/css/draft_board_dynamic_styles.php

A: I found the issue: CSS class names cannot start with a digit, hence the reason why all three browsers were not recognizing the CSS - they were properly following CSS while I was not!


text:
Q: How to implement a recursive function similar to Array.prototype.find Given a data structure like this:
[
  {
    id: 7,
    isOpen: false,
    children: [
      {
        id: 678,
        parentId: 7,
        isOpen: false
      }
    ]
  },
  {
    id: 268,
    isOpen: false
  }
]

How can we implement a function that will return the object that matches a given id?
For example
f(7)
should return
{
  id: 7,
  isOpen: false,
  children: [
    {
      id: 678,
      parentId: 7,
      isOpen: false
    }
  ]
}

and f(678) should return
{
  id: 678,
  parentId: 7,
  isOpen: false
}


text:
Q: Problems accessing folder from a web part (The Object Specified does not belong to a list) I have a document library on my SharePoint 2010 site called Files.  I want to create a web part on my site's home page that lists the contets of that Doc Library.  So, from the home page I click on Page > Edit.  In the zone where I want the part added, I click on Insert > Existing List.  I find my "Files" document library under Web Parts, then click Add.  My web part gets added with all my folders laid out.  But, when I click on one of the folders, it shows this error:

Error  The object specified does not belong to a list.
Troubleshoot issues with Microsoft SharePoint Foundation.
Correlation ID: 5b1e17c6-9fc1-4b34-a110-58f199aed0c2
Date and Time: 3/10/2016 2:46:22 PM

I've tried accomplishing this task with other Document Libraries, and am experiencing the same problem.  So, I know it's not the document library.  I'm totally at a loss... the files in the document library launch just fine.  But the folders... no.  What is going on here?  How can I display a list of subfolders in a document library and have those folders be clickable in the web part?

A: When I had this issue it was due to another web part on the site that was disrupting the way the library web part was working. If you add ?contents=1 to the URL of the site you can see all of the XsltListViewWebPart's that exist on that page. One of those might be an imported web part that is causing your issue.


text:
Q: How can I add SRID 4326 (Spatial Types) to Workbench when adding columns? When I add a column with type POINT in the EER Diagram, is there anything I can do with that diagram so when I generate automatically the scripts, SRID 4326 is attached to CREATE TABLE script? If I don't setup that number, then by default is zero (flat), but I do need 4326 (sphere).
If not possible, does that mean I cannot synchronise my model with my server automatically and I have to add these changes manually all the time?

A: I couldn't figure this out either. I believe adding a SRID to a column is currently not supported by MySQL Workbench.
To check that it is indeed not supported, I did the following:

*

*Added a SRID to a column of an existing DB

*Reversed engineered a script of this DB (using Workbench)

*Checked the script if it included the set SRID for the column

*Was disappointed that it didn't...

The "good" news is though, that as it is not supported, MySQL Workbench won't pick up on a missing SRID on a column when synchronizing sources.
This means that once you set the SRID on a column yourself, it won't cause any problems when synchronizing in the futures.
Note that in order to set a SRID on a column, there can't be a (spatial) index on that column. Therefore, you must remove the index, set the SRID and then add the index back.
Below is a short and simple script, which I used to do this. Don't forget to update it to your use-case:
DROP INDEX `my_idx` ON my_table;
ALTER TABLE my_table MODIFY COLUMN my_column POINT NOT NULL SRID 4326;
ALTER TABLE my_table ADD SPATIAL INDEX `my_idx` (`my_column`) VISIBLE;


text:
Q: Unexpected behavior when using SortBy as a dataset filter I am still experimenting with datasets. Recently I tried to query the Titanic example to get info on the oldest passengers. Here is what I tried
titanic = ExampleData[{"Dataset", "Titanic"}];
titanic[Select[#age > 65 &]]

That's fine, but I really wanted the data sorted by age. The documentation for datasets mentions that SortBy can be used as filtering operator, but gives no further details on it use that I could find. So I was left to experiment on my own. Here is my second attempt.
titanic[Select[#age > 65 &] /* SortBy["age"]]

The result shows sorting, but the "age" category is only locally sorted within each "class" category. That is not what I wanted. I wanted the sort to treat the "age" category as if it were the major key of the dataset. Does anyone know how to dot that?
I did find a work-around but it's weird.
titanic[Select[#age > 65 &], RotateLeft[#, 1] &][SortBy[42]]

Note that the argument to SortBy is complete nonsense, but this last code works as I want. Can anyone explain this result?
One last question. Since there is essentially no useful documentation on using SortBy in the way I have above, it's hard to dispute any behavior it shows. Nevertheless, I ask if you think I should report the behavior I have observed to Wolfram tech support as a possible bug?

A: I do not believe that this behaviour is a bug.  The correct usage would be SortBy[#age&] or SortBy[Key@"age"]. The rest of this response will explain these assertions.
The crucial point is that the "age" argument in SortBy["age"] is not conferred with any special meaning on account of SortBy being used as a Dataset operator.
In the absence of such special treatment, SortBy["age"] gives us the same result as if we used it as a normal function outside of a query.  That is, the result is the same as if we say SortBy[Identity] or simply Sort.  This point will be elaborated upon later in this response.  But for now let us take up why SortBy arguments receive no special treatment in a dataset query.
Dataset Query Operators
One might reasonably expect that since titanic[All, "age"] returns the age values from all of the associations, then by extension titanic[SortBy["age"]] should sort by them.  Unfortunately, this is not so.  To understand why, we must delve into what exactly constitutes a Dataset operator.
The Dataset documentation tells us:

Dataset[...][op1, op2, ...] is equivalent to Query[op1, op2, ...][Dataset[...]].

In turn, the Query documentation describes a domain specific language or DSL that defines query operators for hierarchical data.  This is somewhat like the Graphics DSL for graphical operations.  {Red, Circle[]} is just an inert list as a free-standing expression, but it has special meaning inside a Graphics form.
So it is with Query operators: "age" is just a string by itself, but the documentation tells it takes the role of a key selector descending operator within a Query.  Indeed, all of the descending operators have special treatment in the query context.
Very few "ascending" operators are given special treatment.  The documentation calls out the following special cases, called "ascending subquery operators":

Query[...]                    perform a subquery on the result
{op1, op2, ...}               apply multiple operators, yielding a list
op1 /* op2 /* ...             apply op1, then apply op2, at the same level, etc.
<|key1->op1,key2->op2,...|>   apply multiple operators, yielding an association
{key1->op1,key2->op2,...}     apply different operators to specific parts

Note carefully the use of op1 and op2 in the descriptions, and well as the explicit statement that they refer to operators.
In contrast, the description of SortBy makes no mention of operators:

SortBy[crit]     sort parts in order of crit

Thus, a close reading tells us that SortBy parameters are not operators.  This is true for all ascending operators that do not appear in the "subquery" list above.
One might accept that this is documented behaviour, but then wonder why SortBy, Merge, Counts and all the other ascending operators do not accept operator arguments?
Allowing operators in arbitrary ascending operators would cause confusion.  Observe that any expression that is not explicitly designated as a descending operator is by definition an ascending operator.  This includes all user-defined functions.  How can the query evaluator decide whether to treat any given argument as an operator?  Which arguments to  Histogram should be operators?  What about the arguments of a user-supplied function?  It is difficult to tell without contextual knowledge.  This would mean either long lists of exceptions, or some elaborate syntax to designate exceptions.  In my opinion, WRI chose wisely to go with the exhibited simple rules.
What does SortBy["age"] mean?
Earlier, it was stated that SortBy["age"] is the same as SortBy[Identity]:
list = { <| "class" -> "1st", "age" -> 99 |>, <| "class" -> "2nd", "age" -> 1 |> };

SortBy["age"] @ list === SortBy[Identity] @ list === Sort @ list

(* True *)

Why?  SortBy["age"] specifies that the list is to be sorted by the result of applying "age" to each associations, as if we were sorting like this:
Sort["age" /@ list]

(* {age[<|class->1st,age->99|>],age[<|class->2nd,age->1|>]} *)

Since the head "age" is inert, it is simply wrapped around each association.  This wrapper does not change the lexicographic order of the list elements.  So the result ends up being sorted first by class and then by age since that is the order that the keys appear in the association.
If the keys were reversed, then the age sort would appear to work... but only by blind luck!
list2 = { <| "age" -> 99,"class" -> "1st" |>, <| "age" -> 1, "class" -> "2nd" |> };

SortBy[list2, "age"]

(* {<|age->1,class->2nd|>,<|age->99,class->1st|>} *)

If we wish to reliably sort by age, then we need to use one of the following forms:
SortBy[list, #age&]

(* {<|class->2nd,age->1|>,<|class->1st,age->99|>} *)

SortBy[list, Key["age"]]

(* {<|class->2nd,age->1|>,<|class->1st,age->99|>} *)

These both correctly extract the age key from each assocation.
But It Could Have Worked...
Having said all that, I will note in closing that if WRI had added an up-value to Association along the lines of...
s_String @ a_Association ^:= a @ s

... then we would not be having this discussion.  The original example would have worked, and all without having to introduce any exceptional cases into the Query DSL.

A: You have to use a pure function also for SortBy
titanic[Select[#age > 65 &] /* SortBy[#age &]]

Since #age will pick out the values of the key "age" in the association.


text:
Q: Temporarily set home for android I have an application that uses CATEGORY_HOME so that when you push the home button it keeps you within my app. After the user selects my app as the default home it is set for the whole device.
I was wondering how you disable the home going within my app when you are not in my app when pushing the home button. After doing some research I think I need to use the package manager but I do not know how to implement this.
The activity is defined as home in the Manifest:
<activity
        android:name=".home"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.HOME" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

And here is how I go to the home and how I set it:
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);

A: Why are you configuring category HOME in your manifest ? You can override home pressing behavior by overriding :
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_HOME)) {
        Toast.makeText(this, "Home button pressed!", Toast.LENGTH_LONG).show();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

Then just do whatever it is you're doing when pressing the button inside the app. Outside the app it will work normally of course.
EDIT
Just checked it, doesn't work on my device, but it seems like if you override onAttachedWindow() and disable HOME, it might do the trick. Just remember to reassign the key using onKeyDown() (just like posted above this edit).
@Override
public void onAttachedToWindow() {
    getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
    super.onAttachedToWindow();
}


text:
Q: Why should I mark all fields private in immutable classes? From JDK documentation:

Don't provide "setter" methods — methods that modify fields or objects
  referred to by fields. Make all fields final and private. Don't allow
  subclasses to override methods. The simplest way to do this is to
  declare the class as final. A more sophisticated approach is to make
  the constructor private and construct instances in factory methods. If
  the instance fields include references to mutable objects, don't allow
  those objects to be changed: Don't provide methods that modify the
  mutable objects. Don't share references to the mutable objects. Never
  store references to external, mutable objects passed to the
  constructor; if necessary, create copies, and store references to the
  copies. Similarly, create copies of your internal mutable objects when
  necessary to avoid returning the originals in your methods.

example:
final public class ImmutableRGB {

    // Values must be between 0 and 255.
    final private int red;
    final private int green;
    final private int blue;
    final private String name;

    private void check(int red,
                       int green,
                       int blue) {
        if (red < 0 || red > 255
            || green < 0 || green > 255
            || blue < 0 || blue > 255) {
            throw new IllegalArgumentException();
        }
    }

    public ImmutableRGB(int red,
                        int green,
                        int blue,
                        String name) {
        check(red, green, blue);
        this.red = red;
        this.green = green;
        this.blue = blue;
        this.name = name;
    }

    public int getRGB() {
        return ((red << 16) | (green << 8) | blue);
    }

    public String getName() {
        return name;
    }

    public ImmutableRGB invert() {
        return new ImmutableRGB(255 - red,
                       255 - green,
                       255 - blue,
                       "Inverse of " + name);
    }
}

Please, explain why should l mark fields as private?


text:
Q: Parse error: syntax error, unexpected $end I'm trying to put html code into the variable, can't understand what i'm doing wrong here.
with the following code i'm getting
Parse error: syntax error, unexpected $end

the code
if (!empty($VIDEO_META)){
        $og_video = <<<HTML
                <meta property="og:type" content="video" />

                <meta property="og:video" content="{$CURRENT_URL}"/>
                <meta property="og:video:secure_url" content="{$CURRENT_URL}"/>

                <meta name="og:video:height" content="280" />
                <meta name="og:video:width" content="420" />
                <meta name="og:video:type"  content="application/x-shockwave-flash" />
        HTML;
}else{
        $og_video = <<<HTML
                <meta property="og:type"  content="website" />
        HTML;
}

A: The HereDOC ( $og_video = <<<HTML ) is wrong, it has to be a the direct start of a line.
Check: http://php.net/manual/en/language.types.string.php for details on this.
Also remove any whitespace after HTML, that causes errors too.
Otherwise, there's really nothing wrong with it, should work quite nicely.


text:
Q: Global variable scope issue I have a vb.net (I am new to vb.net) site that is supporting 10 languages and 30 or 40 countries. I have it architected so that all the files that contain content are located in a inc folder located at root and are called into my container files via Response.WriteFile. My plan is to make the paths the the container files dynamic and set them in a file in the country folders.
My question is what type of files should I use and and how would I use them? Thanks
Hierarchy example
/inc/content.aspx (when pulled into the us folder file need to reference the variables set in config file at the /us/ level)
/us/index.aspx (container file calling files in inc folder with Response.WriteFile)
/us/configFile (file will contain variables that set paths within all files)

A: .Net has a fairly well thought out way of doing Globalization or Internationlization that is built into the framework.
Do yourself a favor and work with the framework instead of going through the pain of writing this from scratch.


text:
Q: Does Datanode read configuration file from Namenode? I am trying to find a quick and dirty answer for the following question:
Does datanode read configuration file from namenode?

A: No, it does not.
Only in the case where the namenode is on the same server and uses the configuration files from the same directory. This is usually the case when using the pseudo-distributed configuration. In a distributed fashion, the datanode is usually on a different machine and thus uses its own configuration files. No synchronization is happening on the Hadoop application level.


text:
Q: How to decorate service method in external dependency with Resilience4j circuit breaker (specifically on spring cloud config server)? How can I decorate a service method in an external library with Resilience4j circuit breaker? Specifically, I want to decorate a method in spring cloud config server (the server itself, not client code): org.springframework.cloud.config.server.environment.EnvironmentController.labelled(...). It takes multiple parameters. I can't annotate it because it is in a 3rd-party library.
EnvironmentController class is a Spring @RestController.
I see methods in CircuitBreaker for decorating Callables, Functions, etc., but none that seem to apply to this. (I'm completely new to Resilience4j, so I'm hoping I'm missing a simple solution.)

A: A common approach (not only to Resilience4j, but to Spring in general) would be to use a BeanPostProcessor (you can see a non-related example here).
Then in the beanPostProcessor, you can get a handle of your EnvironmentController and wrap around its implementation/method with your Resilience4j CicrcuitBreaking logic.
Basically the approach would be something like:

*

*Use a BeanPostProcessor in your @Configuration to get a handle of the fully wired EnvironmentController

*Wrap your own CircuitBreaker implementation with Resilience4j around the EnvirommentController's methods that you are interested in

*Profit

If that doesn't fully clear the picture, I can add some sample code to get you started, just let me know. Keep in mind that's probably just one of the many ways this can be approached.
Edit:
Some code (not sure if it works, haven't tested, spring-boot is notoriously annoying in terms of using a shit-ton of aop for the MVC mapping autoconfig, so you might have to play around with aspects or proxy config instead), might look like (keep in mind I'd use lombok to avoid all the boilerplate, for posterity):
@Configuration
@Slf4j
public class MyConfig {

    // or however the heck you get your breaker config
    private final CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom().build();
    private final CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.of(circuitBreakerConfig);
    private final CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("suchBreakerMuchWow");

    @Bean
    public CircuitBreakerAwarePostProcessor circuitBreakerAwarePostProcessor() {
        return new CircuitBreakerAwarePostProcessor();
    }

    public class CircuitBreakerAwarePostProcessor implements BeanPostProcessor {

        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            if (bean instanceof EnvironmentController) {
                return new CircuitBreakerFriendlyEnvironmentController((EnvironmentController) bean);
            }
            return bean;
        }
    }

    private interface Exclude {
        Environment labelled (String name, String profiles, String label);
    }

    @RequiredArgsConstructor
    private class CircuitBreakerFriendlyEnvironmentController implements Exclude {

        @Delegate(types = EnvironmentController.class, excludes = Exclude.class)
        @NonNull private final EnvironmentController environmentController;

        @Override
        public Environment labelled(String name, String profiles, String label) {
            return circuitBreaker.executeSupplier(() -> {
                log.info("such wow");
                return environmentController.labelled(name, profiles, label);
            });
        }
    }
}


text:
Q: Terminal: Line going invisible after line break See Screenshot.
After the first line hits end of the terminal and the cursor/text goes into the second line the first line goes invisible and the second takes it's place.
The first line will still be executed and I am still able to go back and edit the now invisible text.

A: I found the answer, turning off "Set locale variables automatically" was the reason.
It can be set in the Preferences > Profiles > Terminal Tab > Environment.


text:
Q: Expanding $E[N^2]-E[N]$ I'm trying to prove $$\sum_{i=0}^{\infty}iP[N>i]=\frac{1}{2}(E[N^2]-E[N])$$
by expanding both the RHS and LHS and showing that they are equal. The first thing I did was multiply both sides by $2$ to get $$2\sum_{i=0}^{\infty}iP[N>i]=E[N^2]-E[N]$$
which made it simpler to expand the LHS. I ended up getting the following equality:
$$2\sum_{i=0}^{\infty}iP[N>i] = 2P[N=2] + 6P[N=3] + 14P[N=4] + \cdots$$
When trying to expand the LHS, however, I did not know how to proceed once I saw $E[N^2]$. So, I have 2 questions:
(1) Is the following true: $E[N^2]-E[N] = E[N^2 - N] = E[N(N-1)]?$
(2) Can $E[N^2]$ be expanded in a similar way to $E[N]$? i.e. $E[N^2] = 0^2P[N=0] + 1^2P[N=1] + 2^2P[N=2^2]$? I know this is 100% incorrect, but I can't figure out how else it would be expanded.
Thank you!

A: Yes, what you wrote $\Bbb E[N^2]-\Bbb E[N]=\Bbb E[N(N-1)]$ is correct. You can expand it as $$\Bbb E\left[N(N-1)\right]=\sum_{i=1}^{\infty}i(i-1)P(N=i)=2P(N=2)+6P(N=3)+12P(N=4)+\dots$$ Now, go back and check where this $14P(X=4)$ comes from in the expansion of the LHS. It should be $12P(X=4)$.

Your expansion of $\Bbb E\left[N^2\right]$ is correct as well.


text:
Q: After inputting a value in QLineEdit(), I want to display only the rows in QTableWidget by pressing the search button When you entered a value in the edit window created by the QLineEdit() function, and then clicked QPushButton, you tried to print only the rows that matched the values entered in the edit window. If you press the search button without entering anything, you want to see all the results (rows) again.
I used setRowHidden() to do this, but I do not see the above results.
Is there a function that provides the above functions? I would like to know if there is a solution.
I tried changing the argument value of setRowHidden() to True or False, but I could not get the desired result.
def OnFilter(self):
    for i in range(0, tableWidget.rowCount()):
        item = tableWidget.item(i, 1)
        if (item is not None and item.data(QtCore.Qt.EditRole) == (self.SearchEdit.text())):
            tableWidget.setRowHidden(i, False)
        else:
            tableWidget.setRowHidden(i, True)

self.SearchEdit = QLineEdit()
self.SearchButton = QPushButton("search")
self.SearchButton.clicked.connect(self.OnFilter)

If you press the search button after entering the value in the current edit window, only the corresponding line is output. However, if you try to view the entire value (row) by clearing the value entered in the edit window and pressing the search button, nothing will be output.

A: You are saying that when self.SearchEdit.text() == ""  all rows should be shown, but your code treats an empty string ("") same as a keyword and tries to match it in your table.
Put an if statement in your function so that if  self.SearchEdit.text() == "", all rows are displayed. You can do like this:
    def OnFilter(self):
        if self.SearchEdit.text() == "":
            for i in range(0, tableWidget.rowCount()):
                tableWidget.setRowHidden(i, False)
            return
        for i in range(0, tableWidget.rowCount()):
            item = tableWidget.item(i, 1)
            if (item is not None and item.data(QtCore.Qt.EditRole) ==
            (self.SearchEdit.text())):
                tableWidget.setRowHidden(i, False)
            else:
                tableWidget.setRowHidden(i, True)


text:
Q: Deploy sveltekit app on vercel using node adapter I'm trying to deploy my app on vercel using node adapter. I know that i should use the vercel adapter but i made some changes to make sveltekit work with socket.io. I followed this guide: https://joyofcode.xyz/using-websockets-with-sveltekit.
The Node adapter creates the index.js and handler.js files in your build folder when you run npm run build — creating a custom server works by importing the handler from build/handler.js and using your custom server instead of index.js. Then I created a index.js file at the root of the project with the following content:
import http from 'http';
import express from 'express';
import injectSocketIO from './src/lib/websockets/socketIoHandler.js';
import { handler } from './build/handler.js'

const app = express();
const server = http.createServer(app);

// // Inject SocketIO
injectSocketIO(server);

// // SvelteKit handlers
app.use(handler);

server.listen(3000, () =\> {
console.log('Running on http://localhost:3000');
});

i tryied in some ways to make the deploy but I can't make it work...
How could I deploy the app on vercel? Thanks!
enter image description here
using this vercel.json file:
{
  "version": 2,
  "builds": [
    {
      "src": "./index.js",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/web/(.*)",
      "dest": "/"
    }
  ]
}

enter image description here

A: To put this simply, the adapter-vercel exists, because Vercel mainly works on the front-end aspect and is serverless. socket.io will not work on Vercel mainly because Vercel will freeze your app (including your socket) after it detects an inactivity in the application.
So TLDR; you can't use socket.io on Vercel. You can see more on that here:
https://vercel.com/guides/do-vercel-serverless-functions-support-websocket-connections


text:
Q: Is there a way to use gsutil while impersonating a service account? I am in the process of attempting to adjust user permissions in Google Cloud and have created a service account that other users can impersonate to access various projects. The gcloud command has the --impersonate-service-account option to make API calls with the proper authentication, but I was wondering if anyone knows how to make such calls using gsutil.
Here's an example of what a successful call looks like using gcloud:
gcloud --impersonate-service-account=superuser@PROJECT1.iam.gserviceaccount.com iam service-accounts list --project PROJECT2

A: There is no such option in the top-level gsutil command-line options (at least not a documented one).
By contrast the gcloud --impersonate-service-account is documented.
Things to try:

*

*if you use the gsutil distributed with the gcloud SDK - it has some ability to use the credentials established by gcloud auth, see Configuring/Using Credentials Via Cloud Sdk Distribution Of Gsutil

*if you use the standalone version, check the gsutil config command, which should allow specifying a service account credentials (see also Updating To The Latest Configuration File):

-e Prompt for service account credentials. This option requires that -a is not set.

A: Yes, here's the option:
$ gsutil -i [SERVICE-ACCOUNT]@[PROJECT] [GSUTIL-COMMAND]

Example:
$ gsutil -i myserviceaccount@iam.gserviceaccount.com ls


text:
Q: Custom runtime dockerfile for asp.net core 5 with Google cloud error CS1003: Syntax error, I am trying to publish the Asp.net core 5 application to the google cloud using the visual studio plugin.
app.yaml
runtime: custom
env: flex

manual_scaling:
  instances: 1
resources:
  cpu: 1
  memory_gb: 0.5
  disk_size_gb: 10

Docker file
FROM mcr.microsoft.com/dotnet/aspnet:5.0
WORKDIR /app
# Copy csproj and restore as distinct layers
COPY *.csproj ./
RUN dotnet restore
# Copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o out
# Build runtime image
FROM mcr.microsoft.com/dotnet/aspnet:5.0
WORKDIR /app
COPY --from=build-env /app/out .
EXPOSE 8080
ENV ASPNETCORE_URLS=http://*:8080
ENTRYPOINT ["dotnet", "Falcon-Identity.dll"]

When I publish using publish to google cloud from context menu I am getting the below exception
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(1,23): error CS1003: Syntax error, '(' expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(1,23): error CS1001: Identifier expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(1,30): error CS1001: Identifier expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(1,30): error CS1003: Syntax error, ',' expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(1,31): error CS1003: Syntax error, ',' expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(1,37): error CS1001: Identifier expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(1,37): error CS1003: Syntax error, ',' expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(1,41): error CS1003: Syntax error, ',' expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(2,9): error CS1001: Identifier expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(2,9): error CS1003: Syntax error, ',' expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(2,10): error CS1003: Syntax error, ',' expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(3,3): error CS1024: Preprocessor directive expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(4,6): error CS1003: Syntax error, ',' expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(4,8): error CS1003: Syntax error, ',' expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(4,16): error CS1001: Identifier expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(4,16): error CS1003: Syntax error, ',' expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(4,17): error CS1003: Syntax error, ',' expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(5,12): error CS1003: Syntax error, ',' expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(6,3): error CS1024: Preprocessor directive expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(7,6): error CS1003: Syntax error, ',' expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(7,10): error CS1003: Syntax error, ',' expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(8,12): error CS1003: Syntax error, ',' expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(8,20): error CS1001: Identifier expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(8,20): error CS1003: Syntax error, ',' expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(8,21): error CS1003: Syntax error, ',' expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(8,31): error CS1003: Syntax error, ',' expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(8,32): error CS1003: Syntax error, ',' expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(8,34): error CS1001: Identifier expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(8,34): error CS1003: Syntax error, ',' expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(9,3): error CS1024: Preprocessor directive expected [C:\Projects\falcon-identity\Falcon-Identity\Falcon-Identity.csproj]
C:\Projects\falcon-identity\Falcon-Identity\Dockerfile(10,9): error CS1003: Syntax error, ',' e

A: I encountered an identical problem with same exceptions.
It was caused by setting the build action on the docker file incorrectly (properties tab - incorrectly set the build action of the file to "C# compiler" instead of "None").

A: I solved mine: As I created the Dockerfile using VisualStudio, it has changed the .csproj inserting the following lines:
  <ItemGroup>
    <Compile Include="Dockerfile" />
  </ItemGroup>

commeting it out solved the problem.
It was clear the reason of the error, right? the dotnet was trying to compile it, thus the syntax error thrown.

A: I'm able to deploy an ASP.NET 5.0 app successfully to App Engine flex (and then Cloud Run).
I'm less familiar with .NET and so I used a simpler configuration but, I think you should be able to apply what I've done to your case too.
Dockerfile:
FROM mcr.microsoft.com/dotnet/sdk:5.0

WORKDIR /app

COPY ./app/*.csproj .
RUN dotnet restore

COPY ./app/ .

EXPOSE 8080
ENTRYPOINT ["dotnet", "run","--urls=http://+:8080"]

And:
BILLING=...
PROJECT=...
REGION=...

gcloud projects create ${PROJECT}

gcloud beta billing projects link ${PROJECT} \
--billing-account=${BILLING}

gcloud app create \
--region=${REGION} \
--project=${PROJECT}

mkdir ${PWD}/app

# Create 'empty' ASP.NET (web)app
docker run \
--interactive --tty --rm \
--volume=${PWD}/app:/app \
mcr.microsoft.com/dotnet/sdk:5.0 \
dotnet new webapp -o app

# Change generated files to `$whoami`
# Or `$(id -u):$(id -g)`
chown -R $(whoami):$(whoami) ./app

docker build \
--tag=68103677:v1 \
--file=./Dockerfile \
.

docker run \
--interactive --tty --rm \
--publish=8080:8080 \
68103677:latest

# Prove it
curl localhost:8080

# Deploy
gcloud app deploy ./app.yaml \
--project=${PROJECT} \
--quiet

# Test
gcloud app browse \
--project=${PROJECT}

Just for giggles, we can deploy the container image created by the App Engine deployment and deploy the container to Cloud Run:
gcloud services enable run.googleapis.com \
--project=${PROJECT}

# Grab the App Engine image
IMAGE=$(\
  gcloud container images list \
  --repository=us.gcr.io/${PROJECT}/appengine \
  --limit=1 \
  --format="value(name)")

# Deploy it to Cloud Run
# For testing, deploy without authentication
# We need to replicate `ENTRYPOINT` with `--command` and `--args`
NAME="aspnet"
gcloud run deploy ${NAME} \
--image=${IMAGE} \
--command="dotnet" \
--args="run","--urls=http://+:8080" \
--max-instances=1 \
--region=${REGION} \
--project=${PROJECT} \
--allow-unauthenticated

# Grab its endpoint
ENDPOINT=$(\
  gcloud run services describe ${NAME} \
  --project=${PROJECT} \
  --platform=managed \
  --region=${REGION} \
  --format="value(status.address.url)") && \
echo ${ENDPOINT}

# Browse or...
curl ${ENDPOINT}

# Delete it when done
gcloud run services delete ${NAME} \
--region=${REGION} \
--project=${PROJECT} \
--quiet


text:
Q: Where do you get the Black Hole spell? Is it in a grimoire with other spells? Or do you have to defeat someone/something to get it?

A: According to the wiki, the Magical Purple Shark Fin (obtained by killing the purple-finned shark) grants the Black Hole spell.


text:
Q: laravel | html - How to set default select option in form based on db field? I am using laravel 5.4 and I have a select field in my record update form for gender.
I have already got the gender value of the record being updated.
It is {{$customer_profile->gender}}
But I cant figure out how to set default of this select field in my form based on the value of {{$customer_profile->last_name}} which is either m or f

      Gender
             <select class="form-control" name="gender">
                     <option value="m">Male</option>
                     <option value="f">Female</option>
             </select>

Please help

A: I guess you mean how to set selected attribute based on $customer_profile->gender value. You can do this:
<option value="m" {{ $customer_profile->gender === 'm' ? 'selected' : '' }}>Male</option>
<option value="f" {{ $customer_profile->gender === 'f' ? 'selected' : '' }}>Female</option>


text:
Q: .NET types in PowerShell classes I am trying to get my head around PowerShell Class best practices, and running into some confusion with a simple class to handle Balloon Tips.
Add-Type -assemblyName:System.Drawing
Add-Type -assemblyName:System.Windows.Forms

class PxMessage {
    static [PxMessage] $instance
    static $balloon
    static $defaultIcon

    static [PxMessage] GetInstance($processIcon) {
        if ([PxMessage]::instance -eq $null) {
            [PxMessage]::instance = [PxMessage]::new()
            #[PxMessage]::balloon = [Windows.Forms.NotifyIcon]::new()
            [PxMessage]::balloon = New-Object Windows.Forms.NotifyIcon
            [PxMessage]::defaultIcon = $processIcon
        }

        return [PxMessage]::instance
    }

    [Void] SendMessage ([String]$title, [String]$message, [String]$messageIcon) {
        [PxMessage]::balloon.icon = [PxMessage]::defaultIcon
        [PxMessage]::balloon.balloonTipTitle = $title
        [PxMessage]::balloon.balloonTipText = $message
        [PxMessage]::balloon.balloonTipIcon = $messageIcon
        [PxMessage]::balloon.visible = $true
        [PxMessage]::balloon.ShowBalloonTip(0)
        [PxMessage]::balloon.Dispose
    }
}

$processIcon = [System.Drawing.Icon]::ExtractAssociatedIcon($(Get-Process -id:$PID | Select-Object -expandProperty:path))
$message = [PxMessage]::GetInstance($processIcon)

$message.SendMessage('Title', "$(Get-Date)", 'Info')

I have two questions:
1: Why does [PxMessage]::balloon = New-Object Windows.Forms.NotifyIcon work, but [PxMessage]::balloon = [Windows.Forms.NotifyIcon]::new() does not (Unable to find type error)? And does this suggest that using [Type]::new() is not yet fully supported, and for consistency sake I am better off using New-Object everywhere? Or at least everywhere in my own Classes?
2: I would like to type my properties & parameters, but I also get Unable to find type errors when I type the $balloon & $defaultIcon properties, or if I type the $processIcon parameter in the GetInstance method.
Obviously I can type Properties, even with my type being defined. So what is different about the two [System.Drawing] & [System.Windows.Forms], and is this a bug, or a feature? And are there other types that behave similarly?

A: This is essentially a race condition!
When PowerShell starts executing a script file, it goes through 3 phases:

*

*Parsing

*Compilation

*Execution

The very first thing that is processed in the compilation phase, (so before execution even begins) is:

*

*All using statements at top of the script

*Any type definitions - any class or enum keywords - are compiled separately

So the errors related to resolving the [Windows.Forms.NotifyIcon] type literal inside the class definition are actually thrown before Add-Type -AssemblyName:System.Windows.Forms gets a chance to ever run!
Couple of options:
Nested scripts
Write a separate loader script that loads the dependency:
# loader.ps1
Add-Type -AssemblyName System.Windows.Forms,System.Drawing
. .\scriptWithTypes.ps1

# scriptWithTypes.ps1
class ClassDependentOnForms
{
  [Windows.Forms.NotifyIcon]$BalloonTipIcon
}

With modules
With modules it's a bit simpler to manage dependencies ahead of compiling the custom type definitions - just add the assembly names as RequiredAssemblies to the module manifest:
New-ModuleManifest ... -RootModule moduleWithTypes.psm1 -RequiredAssemblies System.Windows.Forms,System.Drawing

Load from disk with using assembly ...
If the required assembly's path is known, you can load it at parse time with a using assembly statement:
using assembly '.\path\to\System.Drawing.dll'
using assembly '.\path\to\System.Windows.Forms.dll'

class FormsDependentClass
{
  [Windows.Forms.NotifyIcon]$BallonTipIcon
}

For your use case, this last one is not very attractive because you'd need to hardcode the assembly instead of just loading it from the GAC by name.

Why does this occur in the first place?
This behavior might be slightly confusing because everything else in PowerShell is just straightforward "one statement at a time"-interpretation.
The reason for this exception is to allow scripts and functions to encapsulate custom parameter types:
param(
  [CustomEnumType]$Option
)

begin {
  enum CustomEnumType {
    None
    Option1
    Option2
  }
}

end {
  # do something based on $Option
}

Without this preemptive compilation of CustomEnumType at parse time, PowerShell would be unable to offer autocompletion and input validation for the -Option parameter argument - because it's type would not exist


text:
Q: Sorting firestore collection before and after limiting I am trying to get the last 1000 items from firestore and then sort them in ascending. So I tried
  connection()
    .collection(`somecollection`)
    .orderBy("timestamp", "desc")
    .limit(1000)
    .orderBy("timestamp")

Having orderBy twice doesn't seem to work. But works with one orderBy
I know I could do this in client but is it possible to run this am I missing something here.

A: You don't even need to orderBy by ascending, as it is by default.
connection()
.collection(`somecollection`)
.limit(1000)

EDIT:
Firestore doesn't support the functionality you are looking for, so you need to query the initial data in a descending order, and the on client sort it in the way you need
connection()
.collection('somecollection')
.orderBy('timestamp', 'desc')
.limit(1000);


text:
Q: curl POST work with user meta but not the custom user meta I created a custom user_meta, but I cant update it via curl.
I can do this with user_meta
curl --header "Authorization: Basic ACCESS_TOKEN" -X POST -d "description=New description" http://domain.com/wp-json/wp/v2/users/1

But I cant do the same with custom meta
curl --header "Authorization: Basic ACCESS_TOKEN" -X POST -d "user_continent=Asia" http://domain.com/wp-json/wp/v2/users/1

This may help
How I add the custom meta to the API:
add_action( 'rest_api_init', 'adding_user_meta_rest' );

function adding_user_meta_rest() {
$user_metas = array('account_psn_title', 'account_psn_id', 'account_steam_title', 'account_steam_id', 'account_twitch_title', 'account_twitch_id', 'account_xbox_title', 'account_xbox_id', 'account_youtube_title', 'account_youtube_id', '_uw_balance', 'user_continent', 'user_platform');
    foreach ($user_metas as $user_meta) {
        register_rest_field( 'user',
            $user_meta,
            array(
                'get_callback'      => 'user_meta_callback',
                'update_callback'   => 'user_meta_update_callback',
                'schema'            => null,
            )
        );
    }

}
function user_meta_callback( $user, $field_name, $request) {
    return get_user_meta( $user[ 'id' ], $field_name, true );
}
function user_meta_update_callback( $user, $field_name, $request) {
    update_user_meta( $user[ 'id' ], $field_name, XXXX );
}

function user_meta_update_callback is my attempt to make those custom meta editable.
What should I put in user_meta_update_callback in place of the XXXX?
Am I doing right?

A: arguments get_callback and update_callback receive different arguments.
try this exemple which works for a field user_continent
add_action("rest_api_init", function () {

    register_rest_field(
          "user"
        , "user_continent"
        ,
        [
            "get_callback" => function ($user, $field_name, $request, $object_type) {

                return get_user_meta($user["id"], $field_name, TRUE);

            },
            "update_callback" => function ($value, $user, $field_name, $request, $object_type) {

                update_user_meta($user->ID, $field_name, $value);

            },
        ]
    );

});

A: You'll get the value as the first parameter, or you could get it out of $request, which is a WP_REST_Request object. Since you're using POST, the parameters out of $request->get_body_params() which will return an array. If you just need the actual meta value, you don't need to do this.
Your callback function should look something like this:
function user_meta_update_callback( $value, $user, $field_name, $request ) {
    update_user_meta( $user[ 'id' ], $field_name, $value );
}


text:
Q: Difficulty with Caesar Cipher Chi-Squared In case you are unfamiliar with the cipher. The idea is to be able to encode a message by shifting letters in the alphabet. Ex. d shift 3 -> a. Then be able to decode the message using the crack method. The crack method makes an array full of chi square values (compared to natural alphabetical frequencies in table) for every possible shift (its index) and checks to see which shift has the smallest value. It then takes this value and decodes it using this shift amount.
The problem, is I am getting the smallest chi square value in the wrong address of the array to be able to decode it accurately. I'm not looking for someone to give me the answer, just for where I should look in my code to make the correction.
Thanks in advance.
import java.util.Arrays;

public class Cipher {
//alphabet frequency
static double[] table = {8.2, 1.5, 2.8, 4.3, 12.7, 2.2, 2.0, 6.1, 7.0, 0.2, 0.8, 4.0, 2.4, 6.7,
    7.5, 1.9, 0.1, 6.0, 6.3, 9.1, 2.8, 1.0, 2.4, 0.2, 2.0, 0.1};

//convert letter to number
static int let2nat(char c)
{
    return ((int) c) - 97;
}
//convert number to letter
static char nat2let(int code)
{
    return (char) (code + 97);
}
//shift a letter to another letter shftAmt spaces away
static char shift(int shftAmt, char c)
{
    if (let2nat(c) < 0 || let2nat(c) > 25)
        return c;
    return nat2let((let2nat(c) + shftAmt) % 26);

}
//encodes a string using the given shift amount
static String encode(int shftAmt, String str)
{
    char[] encodedStr = new char[str.length()];
    for(int i = 0; i < str.length(); i++)
        encodedStr[i] = shift(shftAmt, str.charAt(i));
    return new String(encodedStr);
}
//performs the inverse method to encode
static String decode(int shftAmt, String str)
{
    char[] decodedStr = new char[str.length()];
    for(int i = 0; i < str.length(); i++)
        decodedStr[i] = shift(0 - shftAmt, str.charAt(i));
    return new String(decodedStr);
}
//determines how many lowercase letters are in the string str
static int lowers(String str)
{
    int count = 0;
    for(int i = 0; i < str.length(); i++)
        if(let2nat(str.charAt(i)) >= 0 && let2nat(str.charAt(i)) <= 25)
            count++;
    return count;
}
//calculates the number of a character in a string
static int count(char c, String str)
{
    int counter = 0;
    for(int i = 0; i < str.length(); i++)
        if(c == str.charAt(i))
            counter++;
    return counter;
}
//calculates the percent off num1 to num2
static double percent(int num1, int num2)
{
    return ((double) num1/num2 * 100);
}
//find the ratio frequency of all letters in the string str
static double[] freqs(String str)
{
    double[] count = new double[26];
    for(int i = 0; i < str.length(); i++)
        if(let2nat(str.charAt(i)) >= 0 && let2nat(str.charAt(i)) <= 25)
            count[let2nat(str.charAt(i))]++;
    for(int i = 0; i < 26; i++)
        count[i] = percent((int)count[i], lowers(str));
    return count;
}
//rotates a list n places to the left
static double[] rotate(int n, double[] list)
{
    int j = 0;
    while(j<n){
        double starter = list[0];
        //shift one left
        for(int i = 0; i < list.length-1; i++)
            list[i] = list[i+1];
        list[list.length-1] = starter;
        j++;
    }
    return list;
}
//calculates the chi square value
static double chisqr(double[] os)
{
    double chitotal = 0;
    for(int i = 0; i < os.length; i++)
        chitotal += ((Math.pow((os[i] - table[i]), 2)) / table[i]);
    return chitotal;
}
//returns the first position at whcih a value occurs,if returns 999999 then it doesnt exist in the array
static int position(double a, double[] list)
{
    for(int i = 0; i < list.length; i++)
        if(list[i] == a)
            return i;
    return 999999;
}
static String crack(String str)
{
    double[] frequencies = freqs(str);
    double[] chisqrValues = new double[26];
    for(int i = 0; i < 26; i++)
        chisqrValues[i] = chisqr(rotate(i, frequencies));
    int smallestIndex = 0;
    for(int i = 1; i < 26; i++)
        if(chisqrValues[i] < chisqrValues[smallestIndex])
            smallestIndex = i;
    return decode(smallestIndex, str);
}
public static void main(String[] args)
{
    System.out.println(crack(encode(3, "haskellisfun")));
}

}

A: As mentioned in comment, your code for shifting is wrong when negative numbers are used as the index parameter, and this is because of how Java handles negative values when the % operator is used. To be safe, you should do something like:
// shift a letter to another letter shftAmt spaces away
static char shift(int shftAmt, char c) {
  if (let2nat(c) < 0 || let2nat(c) > Z_TO_A - 1) {
     return c;
  } else {
     // do a safe shift
     int result = (let2nat(c) + shftAmt) % Z_TO_A;
     result += Z_TO_A;
     result %= Z_TO_A;
     return nat2let(result);
  }
}

But as also mentioned in comments, this isn't the cause of your bug, and to find that bug, you should test each method, best with unit testing, or if not, then your with your own test methods, to be sure that they're all behaving as expected, and if not, at least allowing you to isolate your bug which will put you half way towards solving your problem.
As an aside, my own take on the problem is to not ignore upper case letters as your code does, but since they are part of the text letter frequency, they should be used when calculating our own letter frequency. Something like this could work well:
/**
 *
 * @author hovercraft
 * {@link http://stackoverflow.com/q/31303332/522444}
 */
public class Cipher2 {
   // just ban "magic" numbers
   public static final int A_VALUE = (int) 'a';
   public static final int Z_TO_A = (int) ('z' - 'a') + 1;
   // alphabet frequency
   static double[] table = { 8.2, 1.5, 2.8, 4.3, 12.7, 2.2, 2.0, 6.1, 7.0, 0.2,
         0.8, 4.0, 2.4, 6.7, 7.5, 1.9, 0.1, 6.0, 6.3, 9.1, 2.8, 1.0, 2.4, 0.2,
         2.0, 0.1 };

   // convert letter to number
   static int let2nat(char c) {
      return ((int) c) - A_VALUE;
   }

   // convert number to letter
   static char nat2let(int code) {
      return (char) (code + A_VALUE);
   }

   // shift a letter to another letter shftAmt spaces away
   static char shift(int shftAmt, char c) {
      if (let2nat(c) < 0 || let2nat(c) > Z_TO_A - 1) {
         return c;
      } else {
         // do a safe shift
         int result = (let2nat(c) + shftAmt) % Z_TO_A;
         result += Z_TO_A;
         result %= Z_TO_A;
         return nat2let(result);
      }
   }

   private static String crack(String encrypted) {
      int[] letterCount = new int[Z_TO_A];
      for (char c : encrypted.toCharArray()) {
         letterCount[let2nat(c)]++;
      }
      double[] letterFrequency = new double[Z_TO_A];
      for (int i = 0; i < letterCount.length; i++) {
         letterFrequency[i] = (double) letterCount[i] * 100 / Z_TO_A;
      }

      int index = 0;
      double minChiSqrSum = calcChiSqrSum(index, letterFrequency);
      for (int i = 0; i < Z_TO_A; i++) {
         double chiSqrSum = calcChiSqrSum(i, letterFrequency);
         if (chiSqrSum < minChiSqrSum) {
            minChiSqrSum = chiSqrSum;
            index = i;
         }
      }
      return encode(index, encrypted);
   }

   private static double calcChiSqrSum(int i, double[] letterFrequency) {
      double sum = 0.0;
      for (int j = 0; j < letterFrequency.length; j++) {
         double observed = letterFrequency[j];
         int tableIndex = (i + j + Z_TO_A) % Z_TO_A;
         double expected = table[tableIndex];
         double delta = observed - expected;
         double chiSqr = delta * delta / expected;
         sum += chiSqr;
      }
      return sum;
   }

   private static String encode(int shift, String text) {
      StringBuilder sb = new StringBuilder();
      for (char c : text.toCharArray()) {
         // convert all upper case to lower case
         // this is a judgment call on my part
         c = Character.toLowerCase(c);
         if (let2nat(c) >= 0 && let2nat(c) < Z_TO_A) {
            sb.append(shift(shift, c));
         }
      }
      return sb.toString();
   }

   public static void main(String[] args) {
      String test1 = "Hello world. How is it going? It's going fine with me";
      String test2 = "When, in the course of human events, it becomes "
            + "necessary for one portion of the family of man to assume "
            + "among the people of the earth a position different from "
            + "that which they have hitherto occupied, but one to which "
            + "the laws of nature and of nature's God entitle them, "
            + "a decent respect to the opinions of mankind";

      // let's throw it for a complete loop: ... but it works!
      String test3 = "Lorem ipsum dolor sit amet, consectetur adipiscing "
            + "elit, sed do eiusmod tempor incididunt ut labore et dolore "
            + "magna aliqua. Ut enim ad minim veniam, quis nostrud "
            + "exercitation ullamco laboris nisi ut aliquip ex ea commodo "
            + "consequat. Duis aute irure dolor in reprehenderit in "
            + "voluptate velit esse cillum dolore eu fugiat nulla pariatur. "
            + "Excepteur sint occaecat cupidatat non proident, sunt in "
            + "culpa qui officia deserunt mollit anim id est laborum.";

      // an unfair test:
      String test4 = "abcdefghijklmnopqrstuvwxyz";

      String test5 = "haskellisfun";
      String[] tests = { test1, test2, test3, test4, test5 };

      for (String test : tests) {
         System.out.println(crack(encode(6, test)));
      }
   }
}


text:
Q: Find absolute extrema of the function $ \ f(x)=1-|x-1| , \ \ x \in [-9,4] \ $ on the closed interval Find absolute extrema of the function  $ \ f(x)=1-|x-1| , \ \ x \in [-9,4] \ $ on the closed interval.
Answer:
$f(x)= \begin{array} (2-x) , \ \ if \ x \in [1,4] \\  \  \ x , \ \ if  \ \  x \in [-9,1] \end{array} \ $
The function has not critical point.
Thus the extrema occurs at the end points $ \ x=1, x=4, x=-9 \ $
Now,
$ f(1)=1, \ f(-9)=-9 , \ f(4)=-2 \ $
Thus,
absolute minima $ \ f(-9)=-9 \ $
absolute maxima $ \ f(1)=1 \ $
I need confirmation of my work.

A: Your work is correct. The absolute maximum value of $1$ is attained at $x=1$ and the absolute minimum value of $-9$ is attained at $x=-9.$


text:
Q: Difference between mouse data received from SDL_GetRelativeMouseState and SDL_PollEvent(&event) What is the difference between mouse position data received from  SDL_GetRelativeMouseState() and SDL_PollEvent() ?

A: That's the same difference that there exists between SDL_GetRelativeMouseState and SDL_GetMouseState.
The former works as though x and y are:

set to the mouse deltas since the last call to SDL_GetRelativeMouseState() or since event initialization

The latter works as though x and y are:

set to the mouse cursor position relative to the focus window for the currently selected mouse

Note that events usually come with both the position relative to the active window and the delta with the last known position.


text:
Q: getting DeprecationWarning while using db.collection.count() function using pymongo in python? I'm using

MongoDB shell version v4.4.0
and
pymongo 3.10.0 version

when I use any_db.any_collection.count() or any_db.any_collection.count({}) the warning show in console
DeprecationWarning: count is deprecated. Use estimated_document_count or count_documents instead. Please note that $where must be replaced by $expr, $near must be replaced by $geoWithin with $center, and $nearSphere must be replaced by $geoWithin with $centerSphere
  print(f'Total Categories = {db.rank_list_category.count({})}')

My code:
import pandas as pd
from src.utils import get_full_path
from pymongo import MongoClient
from bson.objectid import ObjectId

client = MongoClient('localhost', 27017)
db = client['techexpert']

print(f'Total Categories = {db["rank_list_category"].count({})}')

Output:
Total Categories = 5

    /home/mobin/PycharmProjects/IMDb/src/database/database_service_provider.py:17: DeprecationWarning: count is deprecated. Use estimated_document_count or count_documents instead. Please note that $where must be replaced by $expr, $near must be replaced by $geoWithin with $center, and $nearSphere must be replaced by $geoWithin with $centerSphere
  print(f'Total Categories = {db.rank_list_category.count({})}')

A: As mentioned in the documentation

The count() method is deprecated and not supported in a transaction. Please use count_documents() or estimated_document_count() instead.

When migrating from count() to count_documents() the following query operators must be replaced - $where, $near, $nearSphere

Changed in version 3.7: Deprecated.

So use count_documents

A: You are getting this warning because pymongo is deprecating the count function, meaning that you should not use it anymore in new code.
Change your use from:
db.collection.count({})

to
db.collection.count_documents({})


text:
Q: PrimeNG piechart not appearing in Angular Hi im following the document on primeng's page.
i have already installed charts.js package using npm
npm install chart.js --save

App.module.ts
import {ChartModule} from 'primeng/chart';
@NgModule({
...
imports: [
...
ChartModule,
],
... })

Piechart.component.html

Members

piechart should appear here^^

Piechart.component.ts
data: any;

constructor() {
    this.data = {
        labels: ['A','B','C'],
        datasets: [
            {
                data: [300, 50, 100],
                backgroundColor: [
                    "#FF6384",
                    "#36A2EB",
                    "#FFCE56"
                ],
                hoverBackgroundColor: [
                    "#FF6384",
                    "#36A2EB",
                    "#FFCE56"
                ]
            }]
        };
}

according to the documentation the piechart should appear but for some reason it does not appear and instead just leaves a gap??
scrnshot
please help!!!

A: Include this in your angular.json file, if not already added:
"architect": {
 "build": {
  //..others
  "options: {
   "scripts": [
     "node_modules/chart.js/dist/Chart.js",
     //..others
     ],
     //..others
    }
  }
  //..others
 }


text: Q: Problems with Dual Boot, Computer not starting I was trying dual boot installation of Ubuntu over Windows 10. After starting the installation of Ubuntu, something weird happened and the computer shut down. Now I am trying to restart the system but it isn't booting since then. PLease help


text:
Q: How to remove a string from an array based on string matching id I'm currently rendering a Checkbox where if checked, the data (id in a string) is saved in state. However I'm trying to put together the functionality for if the checkbox is unchecked, the data needs to be removed from the state (which is an array of strings).
I have come up with this solution however I don't think I am using .splice correctly or if that's the best option for me to use as it doesn't work.
<Checkbox
        onChange={(e) => {
          e.target.checked
            ? setSelectedStyles([...selectedStyles, s.id])
            : e.target.checked === false &&
              selectedStyles.map((id) => id === s.id)
            ? selectedStyles.splice(s.id)
            : console.log(`didn't work`)
        }}
      ></Checkbox>

To clarify, selectedStyles is an array of strings stored in state. s.id is the id (string) I'm checking against.
Does anyone have any thoughts on how to approach this?
Thanks in advance

A: Try this:
onChange={(e) => {
  e.target.checked
  ? setSelectedStyles([...selectedStyles, s.id])
  : setSelectedStyles(selectedStyles.filter(x => x !== s.id))
}}

The filter method allows to clone the array while removing the needed item at the same time.
You should never mutate a React state like you attempted to do whith splice.


text:
Q: Getting File Name Node,Js I am just beginning with nodejs.
The following code makes a copy of the file I send via parameter in the curl.
For example  curl --upload-file 11.png localhost:8080
In good theory this file, needs to have a new name that will be 111.png according to my code
How do I get this name from the headers?
var http=require('http');
var fs = require('fs');
http.createServer(function(request,response){
    var name = 'content-encoding';
    var encoding = request.headers[name];
    var newFile=fs.createWriteStream(encoding+"1");
    var size=request.headers['content-length'];
    var upload=0;
    request.pipe(newFile);
    request.on('data',function(chunck){
        upload+=chunck.length;
        var progress=(upload/size)*100;
        response.write("progress: "+parseInt(progress,10)+ "%\n");
    });
}).listen(8080);
console.log('Server Running');


text:
Q: SQL Query second relation i have a problem i want to take SQL query language that returns the employee's (id) supervisor to his supervisor.
I have a tab employee
create table employee (
    id int not null,
    surname varchar(50),
    name varchar(30),
    boss_id int)

A: You may try this...
  select a.id, b.boss_id
  from employee as a
  inner join employee as b on a.boss_id=b.id

For test case
create table DemoTable
(
    accountid bigint
    ,parentid bigint
    ,accountname nvarchar(128)
)
insert DemoTable(accountid,parentid,accountname)
select 1, null, 'Root'
union select 2, 3, 'Child1'
union select 3, 1, 'Child2'

Query:
select a.accountid, b.parentid from DemoTable as a
inner join DemoTable as b on a.parentid=b.accountid

output is as : pass accountid as 2
accountid   parentid
   2           1

Here 2  >>  3  >>  1


text:
Q: Does column order matter when defining unique constraints How is this
CREATE TABLE foo (
    id   SERIAL PRIMARY KEY,
    col1 VARCHAR(50) NOT NULL,
    col2 VARCHAR(50) NOT NULL,
    col3 DOUBLE PRECISION NULL,
    UNIQUE(col1, col2)
);

Different from this?
CREATE TABLE foo (
    id   SERIAL PRIMARY KEY,
    col1 VARCHAR(50) NOT NULL,
    col2 VARCHAR(50) NOT NULL,
    col3 DOUBLE PRECISION NULL,
    UNIQUE(col2, col1) -- reversed column ordering
);

From what I understand both commands will generate an index on the two columns to enforce the unique constraint but with different ordering.
So I would not need to generate a separate index to speed up queries like this in either case.
SELECT id, col3 FROM foo WHERE col1 = 'stack' AND col2 = 'overflow'

However if future queries will also involve querying by column "col2" alone like below the latter form is preferred because the index will still be usable right?
SELECT id, col3 FROM foo WHERE col2 = 'overflow'

A: The order matters if you expect to ever use the index as a partial index.  For example, suppose you had a unique index on (col1, col2), and you wanted to optimize the following query:
SELECT col1, col2 FROM foo WHERE col1 = 'stack';

The index on (col1, col2) could still be used here, because col1, which appears in the WHERE clause, is the leftmost portion of the index.  Had you defined the unique constraint on (col2, col1), the index could not be used for this query.


text:
Q: Freeze grid when checkbox is checked I have a grid that has a checkbox for each row,when i select the checkbox its does some search in the grid,so i have i little delay,less then a second,but if the user check a lot of box fast,for example 5,it marks all 5,but when the process finish it it go back and mark only one.I need something that freeze the grid when the first one is marked,i tried some JS but didn`t work.This is part of my grid.
<div style="width: 100%; height: auto; max-height: 400px; overflow-y: auto;overflow-x: hidden">
            <asp:GridView runat="server" AllowSorting="true"  class="Tabelas" Width="700px"  ID="grdSimulacao" OnRowDataBound="grdSimulacao_OnDataBound" DataSourceID="odsResultado"
                AutoGenerateColumns="False" ItemStyle-CssClass="FixedHeader"  HeaderStyle-CssClass="FixedHeader"    CellPadding="2" PageSize="2" OnPageIndexChanging="grdSimulacao_PageIndexChanging">
                <HeaderStyle CssClass="TabelasHeader branca-10NN"  HorizontalAlign="Center"></HeaderStyle>
                <RowStyle CssClass="TabelasBody grid" ></RowStyle>
                <AlternatingRowStyle CssClass="TabelasBodyAlt grid" BackColor="#EEEEEE"></AlternatingRowStyle>
                <Columns>
                    <asp:TemplateField HeaderText="Todos" >

                        <HeaderTemplate />

                        <HeaderTemplate>
                            <asp:Button ID="btnTodos" Text="Todos" Width="50px" CssClass="button" runat="server" OnClick="btnTodos_Click" />
                        </HeaderTemplate>

                        <ItemTemplate>

                            <asp:CheckBox  ID="chkSeleciona" runat="server" OnCheckedChanged="chkSeleciona_OnCheckedChanged"  ToolTip='<%# Bind("calculo") %>'
                                Enabled='<%# (Convert.ToBoolean(Eval("checkbox_status")) == true) ? false : true %>' Checked='<%# Eval("checkbox") %>' AutoPostBack="True" />
                        </ItemTemplate>
                        <ItemStyle HorizontalAlign="Center" Width="40px" />

                    </asp:TemplateField>


text:
Q: How to play .avi file in Google Colab? I have found only ways to play '.mp4' files. I even tried to download .avi file and it is showing file is corrupted. I even tried to change .avi to .mp4 using online tools but nothing worked fine.

A: Use the python moviepy package
from moviepy.editor import *

path="file.avi"

clip=VideoFileClip(path)
clip.ipython_display(width=280)

A: You need to convert avi to mp4 with ffmepg
!ffmpeg -i input.avi output.mp4

Then get the file content into data_url
from IPython.display import HTML
from base64 import b64encode
mp4 = open('output.mp4','rb').read()
data_url = "data:video/mp4;base64," + b64encode(mp4).decode()

Then display it with HTML()
HTML("""
<video controls>
      <source src="%s" type="video/mp4">
</video>
""" % data_url)

Here's a working example.


text:
Q: jQuery target generic class item but unique href with trigger click I am trying to target a generic item class with a unique href value based on if hash value is appended to the url unload I want to emulate the click that would normally happen on the page.
jQuery:
if(window.location.hash) {
    var hash = window.location.hash;
    function showHashVideo() {
        jQuery("a.btn").attr("href", hash).trigger('click');
    }
    jQuery(showHashVideo);
}

HTML:
Watch Video

A: jQuery trigger will not trigger DOM event clicks, so you must do this.
jQuery("a.btn").attr("href", hash).get(0).click()

You need to use Attribute-Equals-Selector jQuery( "[attribute='value']" )
jQuery('a.btn[href="' + hash + '"]').get(0).click();

A: As far as I can read you want to find elements HREF which matches an A element. You can do this:
jQuery("a.btn[href='" + hash + "']").trigger("click");

This will trigger a click on the a.btn with the href=hash.


text:
Q: How can I make my form field validate asynchronously? In a form field where I take a username, I want it to be unique. So everytime the user types something I have to check it with my Firebase records. But that happens asynchronously and validator is not working with the async tasks and I have to manually show a snackbar for it. Is there any way I can make this fit into form only?
Future<bool> check(String name) async {
final QuerySnapshot result = await Firestore.instance
    .collection('users')
    .where('name', isEqualTo: name.toLowerCase())
    .getDocuments();
final List<DocumentSnapshot> documents = result.documents;
if (documents.length > 0) return false;
return true;}

This is the function I want to call in place of validator of user_name field.


text:
Q: Specific Group By in Pandas I have a pandas dataframe in this format:
 id    Role  time  text
 id1   A     t1   text1
 id1   B     t2   text2
 id1   B     t3   text3
 id1   A     t4   text4
 id1   B     t5   text5
 id1   A     t6   text6
 id1   A     t7   text7
 id2   A     t8   text8
 id2   B     t9   text9
 id2   B     t10  text1
 id2   B     t11  text10
 id2   A     t12  text11
 id2   A     t13  text12

I would like to form a dataframe or even a text file like this:
 id    Role  text
 id1   A     text1
 id1   B     text2, text3
 id1   A     text4
 id1   B     text5
 id1   A     text6, text7
 id2   A     text8
 id2   B     text9, text10, text11
 id2   A     text12, text13
 id2   B     text11
 id2   A     text12, text13

Or in the text format:
text1
text2, text3
text4
text5
text6, text7
==NEXT ID==
text8
text9, text10, text11
text12, text13
text11
text12, text13

I've used group by in pandas but I can't get it done since group by Role will put al texts together. Thanks.

A: check if 'Role' is equal to its prior value and do a cumulative sum to simulate a third grouping.
g3 = (df.Role != df.Role.shift()).cumsum().rename('clump')
df.groupby(['id', 'Role', g3], sort=False).text.apply(', '.join).reset_index()

    id Role  clump                  text
0  id1    A      1                 text1
1  id1    B      2          text2, text3
2  id1    A      3                 text4
3  id1    B      4                 text5
4  id1    A      5          text6, text7
5  id2    A      5                 text8
6  id2    B      6  text9, text1, text10
7  id2    A      7        text11, text12

To dump this to text files
g3 = (df.Role != df.Role.shift()).cumsum().rename('clump')
d1 = df.groupby(['id', 'Role', g3], sort=False).text.apply(', '.join).reset_index()

for n, g in d1.groupby('id').text:
    print(g)
    print()
    # g.to_csv('{}.csv'.format(n))

0           text1
1    text2, text3
2           text4
3           text5
4    text6, text7
Name: text, dtype: object

5                   text8
6    text9, text1, text10
7          text11, text12
Name: text, dtype: object


text:
Q: How to input the value for the number of rows in an array? I would like to input the number of rows in the Pascal Triangle which will be used in the Dim i(10, 10) As Integer line.
Below is the code without this function:
Sub PascalTriangle()

    Dim i(10, 10) As Integer
    Dim p, j As Integer

    i(0, 0) = 1
    i(1, 0) = 1
    i(1, 1) = 1

    For p = 2 To 10 'put one for the first column, here the number of row is 10
        i(p, 0) = 1

        For j = 1 To p
            i(p, j) = i(p - 1, j - 1) + i(p - 1, j)
        Next
    Next

    For p = 0 To 10
        For j = 0 To p
            Cells(p + 1, j + 1) = i(p, j)
        Next
    Next
End Sub

A: Try this, please:
Sub PascalTriangle_ChooseNoOfRows()
    Dim i() As Long, p As Long, j As Long, lngR As Long, inpAns As String

    inpAns = InputBox("Now much rows must Pascal function process?", "Choose the number of rows", 10)
    If inpAns = "" Then Exit Sub
    If IsNumeric(inpAns) Then
        lngR = CLng(inpAns)
    Else
        MsgBox "You must write a number!": Exit Sub
    End If
    ActiveSheet.Cells.Clear
    ReDim i(lngR, lngR)
    i(0, 0) = 1: i(1, 0) = 1: i(1, 1) = 1

    For p = 2 To lngR
        i(p, 0) = 1
        For j = 1 To p
            i(p, j) = i(p - 1, j - 1) + i(p - 1, j)
        Next j
    Next
    For p = 0 To lngR
        For j = 0 To p
            Cells(p + 1, j + 1) = i(p, j)
        Next j
    Next
End Sub


text: Q: How to get exact Search volumes for google Keywords? I have a set of keywords for an idea, I have put those keywords to the Google planner and i get search volume in ranges but I want exact search volumes for those keywords like ubersuggest is giving us. I wonder how an individual can achieve this?


text:
Q: c++ EOF running one too many times? This is my first time using EOF and/or files, and I am having an issue where my code hangs, which I believe is because my EOF is looping one too many times.
I am imputing from a file, and dynamically creating objects that way, and it hangs once the file is run through.
        while( !studentFile.eof() )
    {
        cout << "38\n";
        Student * temp = new Student();
        (*temp).input( studentFile );

        (*sdb).insert( (*temp) );
    }

This chunk of code is the code in question. The cout >> "38\n"; is the line number and the reason I believe it is hanging from looping one too many times.
The file only contains 4 student's worth of data, yet 38 appears 5 times, which is the reason I believe it is looping one too many times; Once it gets the last bit of data, it doesn't seem to register that the file has ended, and loops in again, but there is no data to input so my code hangs.
How do I fix this? Is my logic correct?
Thank you.

A: This is because the EOF flag is only set after you try to read and get no data. So it would go
Test for EOF -> No EOF
Try to read one line -> Good, read first line
Test for EOF -> No EOF
Try to read one line -> Good, read second line
Test for EOF -> No EOF
Try to read one line -> Good, read third line
Test for EOF -> No EOF
Try to read one line -> Good, read fourth line
Test for EOF -> No EOF
Try to read one line -> EOF

But by the Try to read one line -> EOF, you're already in the body of the while on the fifth iteration, which is why you're seeing the loop run 5 times. So you need to read before you check for EOF.

A: Others have already pointed out the details of the problem you've noticed.
You should realize, however, that there are more problems you haven't noticed yet. One is a fairly obvious memory leak. Every iteration of the loop executes: Student * temp = new Student();, but you never execute a matching delete.
C++ makes memory management much simpler than some other languages (e.g., Java), which require you to new every object you use. In C++, you can just define an object and use it:
Student temp;

temp.input(studentFile);

This simplifies the code and eliminates the memory leak -- your Student object will be automatically destroyed at the end of each iteration, and a (conceptually) new/different one created at the beginning of the next iteration.
Although it's not really a bug per se, even that can still be simplified quite a bit. Since whatever sdb points at apparently has an insert member function, you can use it like a standard container (which it may actually be, though it doesn't really matter either way). To neaten up the code, start by writing an extraction operator for a Student:
std::istream &operator>>(std::istream &is, Student &s) {
    s.input(is);
    return is;
}

Then you can just copy data from the stream to the collection:
std::copy(std::istream_iterator<Student>(studentFile),
          std::istream_iterator<Student>(),
          std::inserter(*sdf));

Note that this automates correct handling of EOF, so you don't have to deal with problems like you started with at all (even if you wanted to cause them, it wouldn't be easy).

A: You need to check the stream status bits immediately after performing an operation on a stream.  You don't show the code, but it would appear that (*temp).input(studentFile) is doing the reading from the stream.  Call eof() (or other status check) after doing the read but before processing with the data you (attempted to) read.