text:
Q: AWS python lambda - difference in importing module in lambda than from local project I am havin an issue with importing a common function util file in my AWS lambda. It is a python file and the folder structure looks something like this
(functions folder)
   common_util.py
   (lambda 1 folder)
      lambda1
   (lambda 2 folder)
      lambda2

I need to access the common_util from both these lambdas. When I run my CDK project locally this is easy i use something like .. on the import statement to tell the file it is one directory up
from ..common_util import (...)

When I deploy to AWS as a lambda (I package all of the above) I need to specify the import without the .. because this is the root folder of the lambda
from common_util import(...)

I need an import statement or a solution that will work for both my CDK project and the lambda.
here is the CDK where the lambda is created
const noteIntegrationLambda = new Function(this as any,"my-lambda",
      {
        functionName:
          "my-lambda",
        runtime: StackConfiguration.PYTHON_VERSION,
        handler:
          "my_lambda.execute",
        timeout: Duration.seconds(15),
        code: Code.fromAsset("functions/"),
        role,
        layers: [dependencyLayer],
        environment: env,

        },
      }
    );

A: Lambda layers provide an ideal mechanism to include in solving this problem.  As mentioned in https://medium.com/@manojf/sharing-code-among-lambdas-using-lambda-layers-ca097c8cd500,

Lambda layers allow us to share code among lambda functions. We just
have to upload the layer once and reference it in any lambda function.

So consider deploying your common code via a layer.  That said, to structure your code, I recommend you create a common package that you install locally using pip install, as outlined at Python how to share package between multiple projects.  Then you put that package into a layer that both of your lambdas reference.  That completely solves the problem of how to structure code when your local file structure is different than the lambda file structure.
Also consider these resources:

*

*Import a python module in multiple AWS Lambdas

*What is the proper way to work with shared modules in Python development?

*https://realpython.com/absolute-vs-relative-python-imports/

*Python: sharing common code among a family of scripts

*Sharing code in AWS Lambda

*Installing Python packages from local file system folder to virtualenv with pip
As a layer example, suppose you wanted to include a "common_utils" library for your lambdas to reference.  To make a layer, you would need to create a directory structure that contains that code, then zip the entire directory.  It may be as follows:
/python
    /common_utils
        __init__.py
        common_util.py
        ...

When zipped, the zip file must have the "python" folder and inside of that you put your code.  If you do this and also install your common code as a package, you can import it in your local code and in your lambdas using the same import.
What I do is use pip install to install to a certain file location--the location that I then zip into a layer.  For example, if I wanted to make a layer for the pymysql library I might do
pip install --target=c:\myLayers\python pymysql

That will install the library files into the location I specified, which makes it easy to know what to zip up (just create a zip that includes the "python" directory).

A: I know this question is old, but I ran into a similar issue. My solution was to detect if the current environment is local or lambda using the os package, and then import differently based on the environment (local or cloud). Will leave here as a reference.
if os.environ.get("AWS_EXECUTION_ENV") is not None:
    # For use in lambda function
    from package_a import class_a
else:
    # For local use
    from ...package_a import class_a

Credits to: How to check if Python app is running within AWS lambda function?


text:
Q: I am having difficulties with creating an equipment I am creating an equipment and I have two actions in my equipment controller, new and create.. and I have two views which is new and a partial form..
I also have four tables.. which are equipments, equipment_types, equipment_locations, and equipment_management_informations..
The form looks like..
>= error_messages_for 'equipment'
%table.contentText{:style => "width: 100%"}
  - if @types
    %tr
      %td Equipment Type
      %td= collection_select 'equipment', 'equipment_type_id', @types,  :id, :name, {}, :class => "dropdownSelect"
  %tr
    %td Location
    %td= select 'equipment', 'equipment_location_id', @equipment_locations.collect { |e| ["#{e.name.capitalize!}", e.id]},{}, :class => "dropdownSelect"
  %tr
    %td Serial Number
    %td= text_field 'equipment', 'serial_number', :class => 'textFields'
  %tr
    %td MAC Address
    %td= text_field 'equipment', 'mac_address', :class => 'textFields'
  %tr
    %td IP Address
    %td= text_field 'equipment', 'ip_address', :class => 'textFields'
  - if @stands
    %tr
      %td Stand
      %td= collection_select 'equipment', 'stand_id', @stands, :id, :street_no, :include_blank => true
  %tr
    %td{:valign => 'top'} Description
    %td= text_area 'equipment', 'description', :cols => 45, :rows => '3', :class => "txt_area_effect"

and my new view is like:
> %h3 New equipment
%div{:style => "border: 1px solid #CCC;"}
  - form_tag :action => 'create', :estate_id => @estate do
    = render :partial => 'form'
    = submit_tag "Create"
    - action = "list"
    %input{:type => "button", :value => "Back", :onclick => "window.location='#{action}';", :class => "start"}

and my create action display this a nil when i inspect it
   @equipment = Equipment.find(params[:equipment])

it gives an error like
 Unknown key(s): equipment_type_id, mac_address, description, equipment_location_id, serial_number, ip_address

A: @equipment = Equipment.find(params[:equipment])

should be:
@equipment = Equipment.new(params[:equipment])

or
@equipment = Equipment.new(params[:equipment])

(just posting answer from comments so this stops showing as unanswered)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Photos not synching, macOS 'optimize storage' not working, and 175GB of photos downloaded for no reason Suddenly, my Mac stopped synching my photos:

I have tons of free space on iCloud, and optimize storage is turned on:

There's no way that photos should take up 170 GB of space when there's only 250 GB in total of photos on iCloud:

I have tried:

*

*Turning this function on and off in Photos.app

*Rebooting apps and the device

*Using all available options in the 'manage storage' dialog

*Turning off synching entirely: System Preferences > Internet Accounts > iCloud > Photos (uncheck) > Delete from my device

What else can I try to fix this bug?
Running the latest version of macOS.

Update: Super buggy. I tried turning off iCloud completely, and now get this — 170GB of undeletable "Other" photos stuck on my Mac:

I expected more paying for a premium MacBook Pro and $120 a year of iCloud synching. Do I need to take extreme measures and reinstall macOS completely?

A: There's no reason to take extreme measures.

*

*When was the last backup?

*Set up Time Machine if you have no backup, exclude system files, it only backs up live data and not snapshots.

*Make a new user account and give it admin.

*Turn off automatic log in and reboot.

Now you can use the new admin account to examine if pruning local snapshots clears all the data. If not, delete your old user account (it's safely backed up) and repeat cleaning snapshots. Only then would I consider an erase install if the storage allocation doesn't make sense.
To get control of iCloud, you can restore your user account from backup while the internet is disabled, then disable cloud sync and learn why full automatic didn't give you the results you expected. Nothing seems fundamentally wrong other than perhaps not considering APFS snapshots and needing to gather some info on how much photo data is actually reported as being in the cloud.

A: The only thing that worked here was:

*

*turning off all synching and iCloud features,

*deleting all Photos.app files from my hard drive,

*and then starting with a fresh library.


text:
Q: How to compute a Von Neumann Successor - ∪∪7? I wonder if I have taken the correct approach to demonstrating what ∪∪7 is, using Von Neumann's proposal? And if I am indeed correct? My answer appears a little odd to me!
Question: What is ∪∪7?
By the successor function: r+ = r ∪ {r}
⇒ ∅+ = ∅ ∪ {∅}
⇒ ∅+++++++ = ∅ ∪ {7}
∪7 = ∅, {∅}
⇒ ∪∪7 = ∅
Thankyou for your help!

A: During this answer, when I say "ordinal," I will at all times mean "von Neumann ordinal," i.e.: a transitive set that is well-ordered by $\in$.

Lemma: If $X$ is a set of ordinals, then $\bigcup X$ is the smallest ordinal $\gamma$ such that $\gamma\geq\alpha$ for all $\alpha\in X$. In particular if $X$ has a greatest element, then it is $\bigcup X.$
Proof: Since each ordinal is a set of ordinals, then $\bigcup X$ is a class of ordinals, and so is well-ordered by $\in$. Furthermore, since $X$ is a set, then $\bigcup X$ is a set by Axiom of union. Also, if $\alpha\in \bigcup X,$ then $\alpha\in\beta$ for some $\beta\in X,$ so since $\alpha\subseteq\beta$ and $\beta\subseteq\bigcup X,$ then $\alpha\subseteq\bigcup X,$ and so $\bigcup X$ is transitive. Thus, $\bigcup X$ is an ordinal (say $\gamma$), since it is a transitive set well-ordered by $\in$.
Since $\alpha\subseteq\bigcup X=\gamma$ whenever $\alpha\in X,$ then $\alpha\leq \gamma$ whenever $\alpha\in X.$ Now, suppose that $\beta$ an ordinal such that $\beta\geq\alpha$ whenever $\alpha\in X$. Then $\alpha\subseteq\beta$ whenever $\alpha\in X,$ so $\gamma=\bigcup X\subseteq\beta$, and so $\gamma\leq\beta,$ as desired. $\Box$

You seem to be a bit confused about the successor function. The first few:
$$0:=\emptyset\\1:=0^+=0\cup\{0\}=\{0\}\\2:=1^+=1\cup\{1\}=\{0,1\}\\3:=2^+=2\cup\{2\}=\{0,1,2\}\\4:=3^+=3\cup\{3\}=\{0,1,2,3\}\\\vdots$$

More generally, any ordinal $\alpha$ is the set of all of its predecessors, and in particular, every non-$0$ finite ordinal $n$ has a greatest element, which (by the Lemma) is $\bigcup n$.
In particular, $\bigcup7=6,$ and $\bigcup\bigcup7=\bigcup6=5.$


text:
Q: scala regex - find sentences between the period character I am trying find sentences between two fullstops (period). I tried the following expression but this seems to skip every alternate sentence.
"\\..+?\\.".r.findAllIn("''Super Ducktales'' is an [[Ducktales]]'s episode.  ==Plot== ===Part 1:Liquid assetats=== When the Ma Beagle's birthday is next, the Beagles sabote the new Duckburg's freeway plant to make that the freeeway pass '''acroos''' the Money Bin. After discovery it, [[Scrooge McDuck]] goes talk with the pig major but he can't accept chenge the plant. After, at [[Manor McDuck]], Scrooge realize that he need contract a accounter.").foreach(println(_))

Output is:
.  ==Plot== ===Part 1:Liquid assetats=== When the Ma Beagle's birthday is next, the Beagles sabote the new Duckburg's freeway plant to make that the freeeway pass '''acroos''' the Money Bin.
. After, at [[Manor McDuck]], Scrooge realize that he need contract a accounter.

As a second part of this question, I would also like to extract the first sentence also. Is there any way to incorporate the ^ symbol?
Knowledge of scala is pretty limited

A: This is because regex consumes as it moves along. Do this instead:
"\\.[^.]+"


text:
Q: Detect if user Idle on windows universal app I'm developing a class library for windows 10 universal apps (mobile and desktop device families only). I need to invoke an event if the user has been idle(no touch, mouse move, key press etc) for x number of seconds. This method can be used to solves this problem on android. But I couldn't find a solution on windows UWP.
Is there an API available in UWP to achieve this?

A: You can detect global input with various events on the app's CoreWindow:
Touch and mouse input with CoreWindow.PointerPressed, PointerMoved, and PointerReleased.
Keyboard input: KeyUp and KeyDown (the soft keys) and CharacterReceived (for characters generated via chords & text suggestions)
Use these to detect the user is active and idle out if it goes too long without any of these events.

A: I know this is really old question, but I think you can now get to same result with RegisterBackgroundTask
Just set:
new TimeTrigger(15, false) //For time trigger
Link
new SystemCondition(SystemConditionType.UserNotPresent)) //And so you want to know so user is not present
Link
Example usage in App.xaml.cs:
var builder = new BackgroundTaskBuilder();
builder.Name = "Is user Idle";
builder.SetTrigger(new TimeTrigger(2, false)); //two mins
builder.AddCondition(new SystemCondition(SystemConditionType.UserNotPresent));
// Do not set builder.TaskEntryPoint for in-process background tasks
// Here we register the task and work will start based on the time trigger.
BackgroundTaskRegistration task = builder.Register();
task.Completed += (sender, args) =>
{
    //Handle user not present (Idle) here.
};


text:
Q: JS - Load JSON file content as a JS variable I have a JSON file with content that looks like this:
//filename: b2021.json
[
//file content
]

And I have the following JS file:
//filename: code.js
arrayName = []

function write(){
     window.alert(arrayName); //This function is called on a HTML file
}

And my objective is to load the content from "b2021.json" into "arrayName" but I can't seem to find the right way to do it. Thanks in advance for those who help!

A: It depends on your environment.
On a browser, a couple of options:

*

*Use fetch to load the file from the server, parse it, and store the result in arrayName. Note that this is an asynchronous process.
For instance, in a modern browser with support for modules and top-level await, you could do this in a module:
const arrayName = await fetch("/path/to/your/file.json")
     .then(response => {
         if (!response.ok) {
             throw new Error(`HTTP error ${response.status}`);
         }
         return response.json();
     });

In that code I intentioonally don't handle the promise rejection (which is normally an antipattern) on the basis that your module isn't of any use if the fetch fails. If you want your module to load even if the fetch fails, add a catch:
const arrayName = await fetch("/path/to/your/file.json")
     .then(response => {
         if (!response.ok) {
             throw new Error(`HTTP error ${response.status}`);
         }
         return response.json();
     })
     .catch(error => {
         // ...report the error, then:
         return [/*...default array to use instead...*/];
     });

*If the file exists alongside your source code and you use a bundler of some kind (Webpack, Rollup, Parcel, etc.), many of them support importing JSON as though you were importing a module (either via ESM syntax — import — or CJS syntax — require()).
On Node.js:
Using CJS, you can require() the file; details.
Using ESM, you can import the file; details — as of this writing, support for JSON modules in Node.js's ESM loader is experimental.

A: On the client side, you can use the fetch api like so
fetch("b2021.json")
  .then(response => response.json())
  .then(json => {
    arrayName = json;
  });

Edit: As evolutionxbox mentioned in the comment it is bad style to assign a global variable from a then-block. I would suggest to store the promise in a variable and call it from the write() function.
let fetchJson = fetch("b2021.json")
  .then(response => response.json());

function write(){
   // if promised was resolved before it is resolved instantly on subsequent calls
   fetchJson.then((arrayName) => window.alert(arrayName));
}


text:
Q: Simple Python API for Django Project I'm working on a (Django) website where users can upload CSV files that are stored in a "protected" directory (i.e not in /media/, so users can only access their own files). I'd like to write a Python package that lets users access their files from within Python scripts. What is the best way to go about doing this?
The requirements are essentially: (1) the user "logs in" using their credentials, (2) they can get a list of their files as a string, and (3) they can give a file name and get a Pandas dataframe as output.
From the point of view of the user, the code might look something like this:
import my_api

# User logs in
con = my_api.connect(user="jim", password="password")

# Print list of file names
con.list_data()

# Get pandas dataframe for "File_Name"
df = con.get_data(filename="File_Name")

I don't know if something like the Django Rest Framework is appropriate given my limited requirements. I just need to log the user in, and then two urls/views that "recognize" a user is logged in and pass back the required data.

A: You could consider using JWT. One endpoint /api/login/ would take username and password in the payload authenticate the user and return a JWT. The JWT can contain a pk (pk to make it simple for now) of the user (and many more if you need). Other endpoints like /api/list_data/, /api/get_data/ or /api/data/123/ would need to have the Authorization header with JWT jwt.from.api_login. It would decode the JWT take the user pk from it's payload and with that know which user is requesting.
The my_api client could look like:
import requests

class MyApi(object):

    base_api_url = 'http://myapi.local:8000'
    _token = None

    def _login(self, token):
        self._token = token

    @property
    def _auth_header(self):
        if self._token is None:
            raise Exception('fetch the token first!')
        return {'Authorization': 'JWT {}'.format(self._token)}

    def call_login(self, username, password):
        response = requests.post(
            '/api/login/', json={
                'username': username,
                'password': password,
            }
        )
        response.raise_for_status()
        self._login(response.json()['token'])

    def call_list_data(self):
        response = requests.post(
            '/api/login/', headers=self._auth_header
        )
        response.raise_for_status()
        return response.json()

It's just my approach - I don't like sessions I like REST and JWT's.
Using Django REST Framework (along with restframework jwt) could help but you may be good on your own.


text:
Q: Can I use a CASE statement to switch operators in a TSQL WHERE clause? I have a complex stored proc, part of which generates dynamic SQL to pivot data in various ways based on a number of factors. For the purposes of this question, I'll illustrate a simplified example.
One of the parameters passed in is a country, and the data for the pivot is then filtered to that country. However, now requirements have changed, and either a country or a continent may be passed in. What I'd like to do, then, is to have a WHERE clause which uses a CASE statement to either use the = operator or an IN clause, depending on the parameter passed.
Simplified database structure:
CREATE TABLE Countries
(Country VARCHAR(100),
Continent VARCHAR(20)
)
GO
INSERT INTO  Countries
VALUES ('UK','Europe'),('France','Europe'),('Portugal','Europe'),
('USA','North America'),('Canada','North America'),
('Brazil','South America'),('Peru','South America')
GO

CREATE TABLE Orders
(OrderID INT IDENTITY PRIMARY KEY,
OrderDate DATE,
ShipCity VARCHAR(100),
ShipCountry VARCHAR(100)
)
GO
INSERT INTO Orders (OrderDate, ShipCity, ShipCountry)
    VALUES (GETDATE(), 'London', 'UK'),
    (GETDATE(),'Paris','France'),
    (GETDATE(),'Porto','Portugal'),
    (GETDATE(),'Vale','USA'),
    (GETDATE(),'Cusco','Peru'),
    (GETDATE(),'Montreal','Canada'),
    (GETDATE(),'Rio de Janeiro','Brazil')
GO

Here's my latest attempt at the stored proc (which clearly doesn't work):
CREATE PROC TestProc @Country VARCHAR(100)
AS
BEGIN
    SELECT *
    FROM Orders o
    WHERE
        CASE
            WHEN @Country='Europe' THEN o.ShipCountry IN (SELECT Country FROM Countries c WHERE c.Continent='Europe')
            WHEN @Country='North America' THEN o.ShipCountry IN (SELECT Country FROM Countries c WHERE c.Continent='North America')
            WHEN @Country='South America' THEN o.ShipCountry IN (SELECT Country FROM Countries c WHERE c.Continent='South America')
            ELSE o.ShipCountry=@Country
        END
END

I've also tried using a simple case rather than a searched case, but couldn't get that to work either.
TBH, I'm thinking that the best option is to have two option parameters - @Country and @Continent, and to re-write the calling procedures to match. However, having spent quite a while working on this now, I'd like to know if it is, in fact, possible, and if so, how.
Thanks.

A: DECLARE @Country VARCHAR(100) = 'France';

SELECT *
    FROM Orders o
    WHERE
        o.ShipCountry IN (SELECT Country
                          FROM Countries c
                          WHERE c.Continent=CASE @Country WHEN '<Europe>'
                                                         THEN 'Europe'
                                                         WHEN '<North America>'
                                                         THEN 'North America'
                                                         WHEN '<South America>'
                                                         THEN 'South America'
                                                         ELSE ''
                                                         END
                                or c.Country = @Country)

DBFIDDLE: https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=f15c9e79ff98789ec985556f76017985
EDIT: It's even possible to do it without CASE
DECLARE @Country VARCHAR(100) = '<Europe>';

SELECT o.*
FROM Orders o
INNER JOIN Countries c ON c.Country = o.ShipCountry
WHERE o.ShipCountry = @Country
   OR c.Continent = REPLACE(REPLACE(@Country,'<',''),'>','')

see: DBFIDDLE)

A: you cor make following query.
If the first query doesn't have a result, the second will be tested.
If one is true the row will be selected
DECLARE @country varchar;
SELECT *
FROM Orders o
WHERE o.ShipCountry IN (SELECT Country FROM Countries c WHERE c.Continent=

    CASE
        WHEN @Country='<Europe>' THEN 'Europe'
        WHEN @Country='<North America>' THEN 'North America'
        WHEN @Country='<South America>' THEN 'South America'
        ELSE ''
    END) OR o.ShipCountry = @Country

A: Assuming you use Australasia or Oceania for the continent (and not Australia), seems you should just use a parametrised IN here (and not wrap continent names in less/greater than (<>) symbols):
CREATE PROC dbo.TestProc @Country VARCHAR(100)
AS
BEGIN
    SELECT {List of Explicit Columns you need goes here}
    FROM dbo.Orders O
         JOIN dbo.Countries C ON O.ShipCountry = C.Country
         --If, for some reason, you don't have details of all relevant countries, use a LEFT JOIN
    WHERE @Country IN (O.ShipCountry, C.Continent);
END

db<>fiddle


text:
Q: In a polynomial of $n$ degree, what numbers can fill the $n$? Until now, I've seen that the $n$ could be filled with the set $\mathbb{N}_0$ and $-\infty$ but I still didn't see mentions on other sets of numbers. As I thought that  having 0 and $-\infty$ as degrees of a polynomial were unusual, I started to think if it would be possible for other numbers to also fill the gap.

A: The reason for this unusual $-\infty$ is the following:
Consider a non-zero polynomial in $x$. Then its degree is simply the highest power of $x$ which has a non-zero ceofficient. Now it turns out that if you multiply a polynomial of degree $m$ with a polynomial of degree $n$, you get a polynomial of degree $m+n$ (simply because $x^m\cdot x^n=x^{m+n}$). Moreover if we add a poynomial of degree $m$ and a polynomial of degree $n>m$ then the sum has degree $m$.
So far, so good. But now we have a problem: The zero polynomial clearly also is a polynomial, but it does not have a highest non-zero coefficient (because simply all coefficients are zero). Therefore the rule above doesn't tell us which degree we should assign to it. However we can look at the properties of the zero polynomial to figure out a good choice.
First, if we multiply the zero polynomial with any other polynomial, the result is, of course, the zero polynomial. That is, if $d$ is the degree of the zero polynomial, we want to have $d+n=d$ for all $n\in\mathbb N_0$. However there's no number which fulfils this identity. But if we look at the "numbers" $\infty$ and $-\infty$, we find that they have, according to common convention, exactly this property. Therefore it makes sense to use either $d=-\infty$ or $d=\infty$.
To determine which of them to use, we look at the second property, adding polynomials of different degree, and getting a polynomial of the larger degree. Now if we add the zero polynomial to a polynomial of degree $n$, we of course get that other polynomial, with degree $n$. Therefore we want to have $n>d$, which is the case for $d=-\infty$ but not for $d=\infty$. Therefore we assign, by convention, the degree $-\infty$ to the zero polynomial.
As for other values which could be meaningful, I could imagine to look at the space of all functions defined by their power series. In that case, the functions which are power series, but not polynomials, could be given the degree $\infty$.
Another obvious extension of polynomials would be to allow negative powers (such functions would, of course, not be defined at $0$). In that case, a generalized polynomial could have a negative integer degree.
Finally, if looking at functions which are sums of arbitrary (also non-integer) powers, such a generalized polynomial would have real degree.
However you should note that in all those cases, the functions are no longer polynomials, but a generalization which include the polynomials. For polynomials, the only degrees possible are from $\mathbb N_0\cup\{-\infty\}$.

A: So far you are talking about polynomials. I assume the coefficients are in some field $k$ so you would denote them as $k[x]$. Here the degree is in $\mathbb N_0\cup\{-\infty\}$.
Common generalisations are:

*

*The ring $k[x,x^{-1}]$. So these are polynomials in the two variables $x$ and $x^{-1}$ with the relation $x\cdot x^{-1}=1$. Then we can define the degree similar to before as the highest non-vanishing power of $x$. Thus the degree will be in $\mathbb Z\cup\{-\infty\}$. Another name for these objects is Laurent polynomials.

*The ring of formal power series $k[[x]]$. Here you allow also the degree $\infty$ for an formal infinite sum $\sum_{i=0}^\infty a_ix^i$. Degrees are in $\mathbb N_0\cup\{\pm\infty\}$

*The ring of Laurent series. This is a combination of 1. and 2. Polynomials may include negative powers and (possibly infinitely many) positive powers of $x$. Note that we only allow finitely many negative powers since we can't porperly define multiplication otherwise. In the non-algebraic world people sometimes allow infinitely many negative powers as well. The degree however will be in $\mathbb Z\cup\{\pm\infty\}$

*The field of fractions of the polynomial ring $k(x)$. Here an element is a fraction $\frac{P}{Q}$ of two polynomials, where $Q\neq 0$. Addition and multiplication are defined similar as the same operations for ordinary fractions. The degree can be defined as $deg(P)-deg(Q)$. Check that the properties of the degree wrt to the operations are still in place. Also note that $k(x)\neq k[[x]]$, although we also have degrees in $\mathbb Z\cup\{-\infty\}$.

A: The degree of a polynomial can only take the values that you've specified. For that, let's revisit the definition of a polynomial. Personally, I was taught that a polynomial (in one variable) is an algebraic expression which can be written in the form $$a_0 + a_1x + a_2x^2 + \cdots + a_nx^n$$ where $n$ is a non-negative integer. From this definition, as the degree is the same as $n$, therefore, the degree is also a non-negative integer (I'll not go into the degree of a zero polynomial, which is best left undefined).
On the other hand, Wikipedia says that

A polynomial is an expression of finite length constructed from
  variables (also called indeterminates) and constants, using only the
  operations of addition, subtraction, multiplication, and non-negative
  integer exponents.

Clearly, there is no non-integer expenentiation, nor any division by a variable, so again it is clear that the degree is a non-negative integer.


text:
Q: In the table below, how would you retrieve the unique values for the employee_location without using the DISTINCT keyword?
Check the below employee table which has employee_name & employee_location as columns as shown below:

  employee

  employee_name  |  employee_locatio
    Joe          |   New York
   Sunil         |   India
    Alex         |   Russia
 Albert          |  Canada
   Jack          |  New York
   Alex          |  Russia

A: You can use group by clause
select employee_location
from employee
group by employee_location

A: And you can use UNION:
select employee_location from employee
UNION
select employee_location from employee

Note! This is just an example of having fun with SQL, don't do it in real programming!


text:
Q: How to find PID of an dash-exec command NOTE: I thought I was using bash, but /bin/sh is linked to /bin/dash, which has this weird exec problem.
I have a simple bash shell script on Linux which is used to launch a server process (which I did not write or control) and would like to have the bash shell script output the launched process's PID to a pidfile.
The problem is that bash-exec command does not replace its own process with the launched server process!
So:
echo $$ | cat > /var/run/launched-server.pid

This does not work because the pid in the file will be that of bash not the server process. And if the server process exits bash may not exit leaving the stupid launch script hanging out in the process list.
Does anyone know a way to use bash (or dash maybe?) so that:

*

*Is it possible?

*The launched-server server process's PID will be in my pidfile?

*Ensure that the bash script will die when the launched-server exists and not leave defunct shell processes hanging out in the process list?

Edit:
This snippet from the bash reference manual be of use...
exec
           exec [-cl] [-a name] [command [arguments]]

If command is supplied, it replaces the shell without creating a new process. If the -l option is supplied, the shell places a dash at the beginning of the zeroth argument passed to command. This is what the login program does. The -c option causes command to be executed with an empty environment. If -a is supplied, the shell passes name as the zeroth argument to command. If no command is specified, redirections may be used to affect the current shell environment. If there are no redirection errors, the return status is zero; otherwise the return status is non-zero.

Edit 2:
This is the script (sanitized):
#!/bin/sh

# this is where the server expects to run its services for Daemontools
SERVICE_DIR='/var/service';

# kill stdout, stderr, stdin
exec </dev/null
exec >/dev/null
exec 2>/dev/null

logger -ip daemon.debug -- stdout, stderr, stdin redirected to /dev/null

if [ -d $SERVICE_DIR ]; then
    # sanitized...
    logger -ip daemon.debug -- services and supervisors exited
else
    logger -ip daemon.err -- $SERVICE_DIR does not exist, exiting
    exit 1;
fi

if [ -d /var/run/pid ]; then
    echo $$ | cat > /var/run/pid/launched-server.pid
    logger -ip daemon.debug -- creating launched-server pidfile
fi

# start the server process
logger -ip daemon.info -- launching server on $SERVICE_DIR
exec /usr/local/bin/launched-server

And some ps output to maybe be more clear?
me@chainsaw: ~/dev $ ps ax | grep launched-server
13896 pts/1    S+     0:00 /bin/sh ./server_boot
13905 pts/1    S+     0:00 launched-server /var/service
13938 pts/2    R+     0:00 grep --color=auto launched-server

A: I now realize what the real problem was:
By using #!/bin/sh I was not invoking bash, but dash.
Dash's exec is the shell with the exec problem. If I had used #!/bin/bash from the start, it would have worked as expected.

A: Does your distribution include start-stop-daemon(8)? Wonderfully useful little tool, it was built specifically for starting daemons from shell scripts. (Of course, the daemons outlive the shell scripts, so it may not be a perfect match -- it depends on why you want the shell to outlive your daemon.)
Or, for something simpler:
Could your problem be solved with bash's exec command? It replaces the shell process with whatever program you ask to execute:
#!/bin/bash

echo $$ > /tmp/pidfile
exec /bin/sleep 60

$ ./show_exec.sh
[nothing happens]

And, in another shell:
$ cat pidfile
24686
$ ps auxw | grep 24686
sarnold  24686  0.0  0.0   9728   816 pts/1    S+   04:53   0:00 /bin/sleep 60


text:
Q: SQL - Associate one record from a table to the ones of another only one time I have this 2 tables:
Position/Article
+--------------+---------------+------------------+---------+
| Col Position | Col IdArticle | Col ExpiringDate | Col xxx |
+--------------+---------------+------------------+---------+
|         1001 |           123 | 31/12/2018       | abc     |
|         1002 |           123 | 31/11/2018       | cdf     |
|         1003 |           123 | 31/12/2019       | ghi     |
|         2001 |           456 | 31/12/2018       | lko     |
|         2002 |           456 | 31/01/2018       | oki     |
|         2003 |           456 | 12/12/2019       | oono    |
+--------------+---------------+------------------+---------+

CustomerOrder/Article
+-------------------+---------------+
| Col CustomerOrder | Col IdArticle |
+-------------------+---------------+
| A                 |           123 |
| A                 |           456 |
| B                 |           123 |
| B                 |           456 |
| C                 |           123 |
| C                 |           456 |
+-------------------+---------------+

I want to get, for each CustomerOrder and IdArticle one position for the IdArticle (each position must not be repeated) and extra columns from the table Position/Article
This is the result I would like to have:
+--------------+---------------+--------------+------------------+---------+
| Col Customer | Col IdArticle | Col Position | Col ExpiringDate | Col xxx |
+--------------+---------------+--------------+------------------+---------+
| A            |           123 |         4001 | xxxx             | aaaa    |
| A            |           456 |         2001 | aaaa             | kkkkk   |
| B            |           123 |         1002 | bbbbb            | loojj   |
| B            |           456 |         2002 | cccc             | jokjio  |
| C            |           123 |         1003 | dddd             | hijooi  |
| C            |           456 |         2003 | eeee             | ookii   |
+--------------+---------------+--------------+------------------+---------+

I've tried with joins and row_number but was not able to come to a solution; it's probably much more easier than I think.


text: Q: Constraining sum and signs of coefficients using R glmc package I want to fit a linear regression model in which the coefficients of each variable are non-negative and add up to one (there also can be an unconstrained intercept).  I know how to do this using quadprog, and I've seen some tricks to get the sum of the coefficients right in lm, although I don't think it can guarantee the right signs.  quadprog works well, but doesn't give any of the typical statistical model output.  I thought perhaps I could do what I want with the R package glmc, but I've read through the documentation and I still don't understand how the constraints work, or whether the particular constraints I want to specify are possible in that package.  Is there a way to specify these constraints (coefficients non-negative and sum up to one) with glmc?


text:
Q: How would a resource URI in REST look, that violates principle of not changing its semantic meaning? Fielding writes in his famous dissertation (p.89)

The only thing that is required to be static for a resource is the
  semantics of the mapping, since the semantics is what distinguishes
  one resource from another.

So a resource prot://bookstore.com/new-books-this-week is OK, because although it will always show different books every week, the semantic meaning does not change.
I don't understand how this could be otherwise, unless the above URI starts returning new books from last week or, say, authors instead of books.
Is there a commonly occurring URI pattern in the real world that violates this principle?

A: Fielding's dissertation was based on looking at the design principles that make the web work well and this is one of the things that, at a high level, most websites get right.  If you did something like create sequential pages e.g. /foo/bar/0, /foo/bar/1 and then reassigned them randomly then that would violate this but I doubt anyone does this, at least not for purposefully or for very long.  I propose the reason for that is because URI stability is so fundamental to making things work and Fielding is simply recognizing this.
The only thing that I can think of that I've seen on a regular basis is a website reorganizing all their URIs such that old links to them return 404.  It's not that the pages are no longer available (a.k.a 410: GONE), they just dropped the old URLs without forwarding.  A big blue company did this with their online documentation about a decade or so ago.  I would regularly find a thread related to a problem we were having and someone posting a response like "the solution can be found here" with a link that just gives a 404.  Thankfully, I no longer have to care.  Fielding is right, this is intolerable.
While this might fall into a different category of problems, I argue that it is an example of this because an existing URI's semantic meaning has changed from something to nothing.

A:
Is there a commonly occurring URI pattern in the real world that violates this principle?

Not one that is RESTful, per the definition of REST.
There are billions of cases where a URL's response has changed meaning and caught the consumers of that endpoint off-guard. But that's just a failure of the provider to effectively communicate the semantic meaning of the resource (which is often "This resource represents whatever we feel like it representing and we make no guarantees about its availability"), or an inability of the client to comprehend the level of ineptitude of the provider in avoiding deleting its own website/going bust/tripping over a power cable.
e.g. any web page that used to work but now returns an error page with a 200 response (and not even a 404, let alone a 410).
Doing REST properly (as a provider) boils down to:

*

*Communicating effectively about the meanings of resources

*Using your communication protocol (usually HTTP but not necessarily) properly


text:
Q: Skip rendering of HTML using Jekyll Is there a way to force Jekyll to bypass the rendering of HTML files? I am attempting to build exclusively files of different extensions instead of the default '.html' while defining the content in markdown files.
Currently, this is being achieved by using a generator plugin to build those files. Ideally, I would be able to specify alternative file types in the configuration and bypass the rendering of HTML.
Is this possible without resorting to post-generation file cleanup?

A: Yes, by omitting front-matter.
If you omit front-matter from your files then Jekyll will not process them and will output them as-is. However, you then can't use Markdown for content because Jekyll doesn't process the files other than to copy them to _site.


text:
Q: How can I override the currency formatting for the current culture for an ASP.NET web application? The currency decimal and thousand separators for the en-ZA region are ',' and ' ' respectively, but the separators in common use are '.' for decimal, plus my user wants ',' for the thousands separator. I wish to set these globally, so that I only have to use the {0:C} format string for all my currency fields, without having to any explicit Format or ToString calls.
I would prefer to be able to do this without changing the culture settings on the web server, as I also need to set the decimal places for currency to zero, as cents are not wanted when reporting on estimates of R100k and up etc. I wouldn't want to arbitrarily set the whole culture to zero places, just one for this application.
In comments to his answer on this question, Jon Skeet suggests cloning the current culture and setting and changing the required settings. I have done this as follows:
void Application_Start(object sender, EventArgs e)
{
    var newCulture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
    newCulture.NumberFormat.CurrencyDecimalSeparator = ".";
    newCulture.NumberFormat.CurrencyGroupSeparator = ",";
}

However, how to I activate that new culture for all requests the application handles from this point on? Is there another way to achieve what I wish to do?

A: You can use Application_BeginRequest event to set the culture for every request. Inside event:
var newCulture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
newCulture.NumberFormat.CurrencyDecimalSeparator = ".";
newCulture.NumberFormat.CurrencyGroupSeparator = ",";

System.Threading.Thread.CurrentThread.CurrentCulture = newCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = newCulture;

A: Having asked many questions and done many experiments, I have decided that it's safe to state that the only way of doing this is to use controls derived from the out of box controls and do your own formatting using a customised culture object. Derive your control from e.g. BoundField and provide your own FormatProvider:
public class BoundReportField : BoundField
{
    protected virtual string GetDefaultFormatString(FieldFormatTypes formatType)
    {
        var prop = typeof(FormatStrings).GetProperty(formatType.ToString()).GetValue(null, null);
        return prop.ToString();
    }

    protected virtual IFormatProvider GetFormatProvider(FieldFormatTypes formatType)
    {
        var info = (CultureInfo)CultureInfo.CurrentCulture.Clone();
        info.NumberFormat.CurrencyDecimalDigits = 0;
        info.NumberFormat.CurrencySymbol = "R";
        info.NumberFormat.CurrencyGroupSeparator = ",";
        info.NumberFormat.CurrencyDecimalSeparator = ".";
        return info;
    }

    private FieldFormatTypes _formatType;
    public virtual FieldFormatTypes FormatType
    {
        get { return _formatType; }
        set
        {
            _formatType = value;
            DataFormatString = GetDefaultFormatString(value);
        }
    }

    protected override string FormatDataValue(object dataValue, bool encode)
    {
        // TODO Consider the encode flag.
        var formatString = DataFormatString;
        var formatProvider = GetFormatProvider(_formatType);
        if (string.IsNullOrWhiteSpace(formatString))
        {
            formatString = GetDefaultFormatString(_formatType);
        }
        return string.Format(formatProvider, formatString, dataValue);
    }
}

I will publish an article later with all the gory details.


text:
Q: How to connect ethers.js with metamask? I am using the ethers.js documentation: https://docs.ethers.io/ethers.js/html/cookbook-providers.html .
I am getting the error when setting up the provider -: Uncaught ReferenceError: web3 is not defined
I want to connect my Decentralized Application with the metamask.
For that I am trying to connect the metamask with ethers.js by setting the provider as per the documentation.
I have used provider = new ethers.providers.Web3Provider(web3.currentProvider). But it throws error for the web3 object in the code. This code is exactly as per the documentation. But still isn't working.

        //let provider = new ethers.getDefaultProvider('rinkeby');
        let provider = new ethers.providers.Web3Provider(web3.currentProvider);
        let contract;
        let wallet;
        let abi = [
    {
        "anonymous": false,
        "inputs": [
            {
                "indexed": true,
                "internalType": "address",
                "name": "account",
                "type": "address"
            },
            {
                "indexed": false,
                "internalType": "string",
                "name": "pwd",
                "type": "string"
            }
        ],
        "name": "Pwd_Assigned",
        "type": "event"
    },
    {
        "inputs": [
            {
                "internalType": "string",
                "name": "_passwd",
                "type": "string"
            }
        ],
        "name": "setPwd",
        "outputs": [
            {
                "internalType": "bool",
                "name": "success",
                "type": "bool"
            }
        ],
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "inputs": [
            {
                "internalType": "string",
                "name": "_uname",
                "type": "string"
            }
        ],
        "name": "setUname",
        "outputs": [
            {
                "internalType": "bool",
                "name": "success",
                "type": "bool"
            }
        ],
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "inputs": [
            {
                "internalType": "string",
                "name": "_uType",
                "type": "string"
            }
        ],
        "name": "setUtype",
        "outputs": [
            {
                "internalType": "bool",
                "name": "success",
                "type": "bool"
            }
        ],
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "anonymous": false,
        "inputs": [
            {
                "indexed": true,
                "internalType": "address",
                "name": "account",
                "type": "address"
            },
            {
                "indexed": false,
                "internalType": "string",
                "name": "utype",
                "type": "string"
            }
        ],
        "name": "Type_Assigned",
        "type": "event"
    },
    {
        "anonymous": false,
        "inputs": [
            {
                "indexed": true,
                "internalType": "address",
                "name": "account",
                "type": "address"
            },
            {
                "indexed": false,
                "internalType": "string",
                "name": "uname",
                "type": "string"
            }
        ],
        "name": "Username_Assigned",
        "type": "event"
    },
    {
        "inputs": [],
        "name": "getContractName",
        "outputs": [
            {
                "internalType": "string",
                "name": "_name",
                "type": "string"
            }
        ],
        "stateMutability": "view",
        "type": "function"
    },
    {
        "inputs": [],
        "name": "name",
        "outputs": [
            {
                "internalType": "string",
                "name": "",
                "type": "string"
            }
        ],
        "stateMutability": "view",
        "type": "function"
    },
    {
        "inputs": [
            {
                "internalType": "address",
                "name": "",
                "type": "address"
            }
        ],
        "name": "pwd",
        "outputs": [
            {
                "internalType": "string",
                "name": "",
                "type": "string"
            }
        ],
        "stateMutability": "view",
        "type": "function"
    },
    {
        "inputs": [],
        "name": "symbol",
        "outputs": [
            {
                "internalType": "string",
                "name": "",
                "type": "string"
            }
        ],
        "stateMutability": "view",
        "type": "function"
    },
    {
        "inputs": [
            {
                "internalType": "address",
                "name": "",
                "type": "address"
            }
        ],
        "name": "uname",
        "outputs": [
            {
                "internalType": "string",
                "name": "",
                "type": "string"
            }
        ],
        "stateMutability": "view",
        "type": "function"
    },
    {
        "inputs": [
            {
                "internalType": "address",
                "name": "",
                "type": "address"
            }
        ],
        "name": "uType",
        "outputs": [
            {
                "internalType": "string",
                "name": "",
                "type": "string"
            }
        ],
        "stateMutability": "view",
        "type": "function"
    }
];
        let contractAddress = "0xECFFa8439Fa4DC64388227fA43a420449E895c3f"; // for rinkeby
        let AidTokenAbi = [
            {
                "inputs": [
                    {
                        "internalType": "uint256",
                        "name": "_initialSupply",
                        "type": "uint256"
                    }
                ],
                "stateMutability": "nonpayable",
                "type": "constructor"
            },
            {
                "anonymous": false,
                "inputs": [
                    {
                        "indexed": true,
                        "internalType": "address",
                        "name": "_owner",
                        "type": "address"
                    },
                    {
                        "indexed": true,
                        "internalType": "address",
                        "name": "_spender",
                        "type": "address"
                    },
                    {
                        "indexed": false,
                        "internalType": "uint256",
                        "name": "_value",
                        "type": "uint256"
                    }
                ],
                "name": "Approval",
                "type": "event"
            },
            {
                "inputs": [
                    {
                        "internalType": "address",
                        "name": "_spender",
                        "type": "address"
                    },
                    {
                        "internalType": "uint256",
                        "name": "_value",
                        "type": "uint256"
                    }
                ],
                "name": "approve",
                "outputs": [
                    {
                        "internalType": "bool",
                        "name": "success",
                        "type": "bool"
                    }
                ],
                "stateMutability": "payable",
                "type": "function"
            },
            {
                "inputs": [
                    {
                        "internalType": "address",
                        "name": "_to",
                        "type": "address"
                    },
                    {
                        "internalType": "uint256",
                        "name": "_value",
                        "type": "uint256"
                    }
                ],
                "name": "transfer",
                "outputs": [
                    {
                        "internalType": "bool",
                        "name": "success",
                        "type": "bool"
                    }
                ],
                "stateMutability": "payable",
                "type": "function"
            },
            {
                "anonymous": false,
                "inputs": [
                    {
                        "indexed": true,
                        "internalType": "address",
                        "name": "_from",
                        "type": "address"
                    },
                    {
                        "indexed": true,
                        "internalType": "address",
                        "name": "_to",
                        "type": "address"
                    },
                    {
                        "indexed": false,
                        "internalType": "uint256",
                        "name": "_value",
                        "type": "uint256"
                    }
                ],
                "name": "Transfer",
                "type": "event"
            },
            {
                "inputs": [
                    {
                        "internalType": "address",
                        "name": "_from",
                        "type": "address"
                    },
                    {
                        "internalType": "address",
                        "name": "_to",
                        "type": "address"
                    },
                    {
                        "internalType": "uint256",
                        "name": "_value",
                        "type": "uint256"
                    }
                ],
                "name": "transferFrom",
                "outputs": [
                    {
                        "internalType": "bool",
                        "name": "success",
                        "type": "bool"
                    }
                ],
                "stateMutability": "payable",
                "type": "function"
            },
            {
                "inputs": [
                    {
                        "internalType": "address",
                        "name": "",
                        "type": "address"
                    },
                    {
                        "internalType": "address",
                        "name": "",
                        "type": "address"
                    }
                ],
                "name": "allowance",
                "outputs": [
                    {
                        "internalType": "uint256",
                        "name": "",
                        "type": "uint256"
                    }
                ],
                "stateMutability": "view",
                "type": "function"
            },
            {
                "inputs": [
                    {
                        "internalType": "address",
                        "name": "",
                        "type": "address"
                    }
                ],
                "name": "balanceOf",
                "outputs": [
                    {
                        "internalType": "uint256",
                        "name": "",
                        "type": "uint256"
                    }
                ],
                "stateMutability": "view",
                "type": "function"
            },
            {
                "inputs": [],
                "name": "name",
                "outputs": [
                    {
                        "internalType": "string",
                        "name": "",
                        "type": "string"
                    }
                ],
                "stateMutability": "view",
                "type": "function"
            },
            {
                "inputs": [],
                "name": "standard",
                "outputs": [
                    {
                        "internalType": "string",
                        "name": "",
                        "type": "string"
                    }
                ],
                "stateMutability": "view",
                "type": "function"
            },
            {
                "inputs": [],
                "name": "symbol",
                "outputs": [
                    {
                        "internalType": "string",
                        "name": "",
                        "type": "string"
                    }
                ],
                "stateMutability": "view",
                "type": "function"
            },
            {
                "inputs": [],
                "name": "tokensSold",
                "outputs": [
                    {
                        "internalType": "uint256",
                        "name": "",
                        "type": "uint256"
                    }
                ],
                "stateMutability": "view",
                "type": "function"
            },
            {
                "inputs": [],
                "name": "totalSupply",
                "outputs": [
                    {
                        "internalType": "uint256",
                        "name": "",
                        "type": "uint256"
                    }
                ],
                "stateMutability": "view",
                "type": "function"
            }
        ];
        let AidtokenAddress = "0x17b0e97DF8217a984294De6bDbbb9D7020190479";
        let AidTokenContract;
        let signer = provider.getSigner();
        let usr_account;

        function loadWallet(){
            signer.getAddress().then(async(res)=>{
                usr_account = res;
                await console.log(usr_account);
            });
        }

        // async function setProvider(){
        //   provider = await new ethers.providers.JsonRpcProvider('http://127.0.0.1:8545');
        // }

        function getContract(){
            contract = new ethers.Contract(contractAddress,abi, signer);
            console.log(contract.functions);
        }

        function getTokenContract(){
            AidTokenContract = new ethers.Contract(AidtokenAddress,AidTokenAbi, signer);
        }

        async function getName(){
            // var name = await contract.functions.getContractName();
            // console.log(name);
            await contract.name().then(async (res)=>{
              await console.log(res);
            });
        }

        async function setInfo(event){
            event.preventDefault();
            loadWallet();
            getContract();
            var uname = document.getElementById('uname').value;
            var pwd = document.getElementById('psw').value;
            var utype = document.getElementById('utype').value;
            await contract.functions.setUname(uname).then(async(res)=>{
                console.log(res);
            });
            await contract.functions.setUtype(utype).then(async(res)=>{
                console.log(res);
            });
            await contract.functions.setPwd(pwd).then(async(res)=>{
                console.log(res);
            });
            //getInfo();
        }

        async function getInfo(event){
          event.preventDefault();
            var uname;
            var utype;
            var pwd;
            loadWallet();
            getContract();
            await contract.functions.uname(usr_account).then(async(res)=>{
                uname=res;
                console.log(res);
            });
            await contract.functions.uType(usr_account).then(async(res)=>{
                utype = res;
                console.log(res);
            });
            await contract.functions.pwd(usr_account).then(async(res)=>{
                pwd=res
                console.log(res);
            });
        }

        async function transfer(event){
            event.preventDefault();
            loadWallet();
            getTokenContract();
            await console.log(".....");
            var numberOfTokens = document.getElementById('numberOfTokens').value;
            await AidTokenContract.functions.transfer(numberOfTokens,{
                from: usr_account,
                gasLimit: 500000
            });
        }

        //setProvider();
        loadWallet();
        getContract();
        //getName();

        // setInfo();
        //getInfo();

    <form onsubmit="setInfo(event)">

Register

Please fill in this form to create an account.

                  User Name
                  <input type="text" placeholder="Enter Username" id="uname" required>

                  Choose a User type:
                  <select id="utype" name="utype">
                        <option value="Donor">Donor</option>
                        <option value="NGO">NGO</option>
                        <option value="Government">Government</option>
                  </select>

                  Password
                  <input type="password" placeholder="Enter Password" id="psw" required>

By creating an account you agree to our Terms & Privacy.

                  <button type="submit" id="registerbtn">Register</button>

Already have an account? Sign in.

    </form>

    <form onsubmit="getInfo(event)">
        <button type="submit" >Get Info</button>
    </form>

    <form onsubmit="transfer(event)">
      <input id="numberOfTokens" type="number" name="number" value="1" min="1" pattern="[0-9]">
      <button type="submit" >Donate</button>
  </form>

A: Using ethers.js to interact with Metamask
const provider = new ethers.providers.Web3Provider(window.ethereum, "any");
// Prompt user for account connections
await provider.send("eth_requestAccounts", []);
const signer = provider.getSigner();
console.log("Account:", await signer.getAddress());

A: window.ethereum.enable() is deprecated.
You should use:
ethereum.request({ method: 'eth_requestAccounts' })

A: I too have found this confusing.  According to the ethers.js documentation for Metamask the following is required:
const provider = new ethers.providers.Web3Provider(web3.currentProvider);
const signer = provider.getSigner();

But this causes an error: specifically the web3.currentProvider not being recognised.
The Ethers.js github issue log has a similar complaint at Issue #433.  Using this as a guide I've therefore used window.ethereum in place of web3.currentProvider and also included the .enable() beforehand:
await window.ethereum.enable()
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();

Or alternatively (outside of an async function):
let provider;
window.ethereum.enable().then(provider = new ethers.providers.Web3Provider(window.ethereum));
const signer = provider.getSigner();

This clears the error, and ensures that Metamask asks for permission prior to connecting to the browser/DApp.


text:
Q: Linear Transformations in Linear Alg Does there exist a linear transformation $T : R^3 → R^3$ such that
$ T
\left(\begin{bmatrix}
6
\\ -3
\\ 3
\end{bmatrix}\right) $ =  $
\begin{bmatrix}
1
\\2
\\ 3
\end{bmatrix} $ and $ T
\left(\begin{bmatrix}
4
\\ -2
\\ 2
\end{bmatrix}\right) $ =  $
\begin{bmatrix}
2
\\4
\\ 6
\end{bmatrix} $ How do I go about solving this problem? Looking for some help with my midterm review

A: Notice that the input vectors are multiples of each other and that the output vectors are multiples of each other.  Since those multiples are not the same, such a transform doesn't exist.

A: Hint
Both input vectors are multiples of $\mathbf{u}=\begin{bmatrix}2\\-1\\1\end{bmatrix}$. Then $T(\lambda\mathbf{u})=\lambda(T(\mathbf{u}))$.
Added explanation:
You are given that $T(3\mathbf{u})=\begin{bmatrix}1\\2\\3\end{bmatrix}$, this means
$$T(3\mathbf{u})=3T(\mathbf{u})=\begin{bmatrix}1\\2\\3\end{bmatrix}.$$
But when you use the other condition, you get
$$T(2\mathbf{u})=2T(\mathbf{u})=\begin{bmatrix}2\\4\\6\end{bmatrix}.$$
So you are getting two different values for $T(\mathbf{u})$. Hence such a T cannot exist.

A: Observe that
$$\begin{pmatrix}4\\-2\\2\end{pmatrix}=\frac23\begin{pmatrix}6\\-3\\3\end{pmatrix}$$ , so it must be
$$T\begin{pmatrix}4\\-2\\2\end{pmatrix}=\frac23\;T\begin{pmatrix}6\\-3\\3\end{pmatrix}$$
because of linearity. Is this true?

A: If $T$ exists, we will have
$T(6,-3,3)=T(3(2,-1,1))=3T(2,-1,1)=(1,2,3)$
thus $T(2,-1,1)=\frac{1}{3}(1,2,3)$
and
$T(4,-2,2)=T(2(2,-1,1))=2T(2,-1,1)=(2,4,6)$
which gives
$T(2,-1,1)=(1,2,3)\neq \frac{1}{3}(1,2,3)$
so, such a linear application doesn't exist.

A: This post answers how to find the matrix of a transformation
calculated with respect to the standard basis, E = {e1, e2, e3}
The same pattern goes if I want to calculate the transformation T with respect to another basis, for general example some basis, B = {b1, b2, b3}
Firstly you determine T(ei), as vectors:
Then, you apply Gauss Elimination method on vectors,
on Ri rows in order to find T(ei),
for each i.
Place them as columns to A matrix, empty matrix.
T would normally be the transformation defined by A matrix.
Finally, T would be T(x) = A*x, and x = (x, y, z)
T(x, y, z) = [T(e1), T(e2), T(e3)](x, y, z)
So the solution for this exercise goes like:
T(6, −3, 3) = (1, 2, 3) => 6T(e1) -3T(e2) +3T(e3) = (1, 2, 3)  :R1
T(4, −2, 2) = (2, 4, 6) => 4T(e1) -2T(e2) +2T(e3) = (2, 4, 6)  :R2
R2 <- R2 - 2R1/3 => (2, 4, 6) -2(1, 2, 3)/3 = (0, 0, 0) =>
[2-2/3]*(1, 2, 3) = (0, 0, 0)
So, no such transformation exists.


text:
Q: Convert numbers to degrees in Angular 8 I'm getting 25 from the API which must be converted to -45 and the end result must be:

My current code looks like this:

Basically, I need to convert
0   to -90
25  to -45
50  to   0
75  to  45
100 is  90

FYI, I'm creating a speedometer. You may see the HTML demo: https://jsfiddle.net/bcgzrdfL/

A: This is more of a mathematics problem than programming one. Linear equation y = a*x + b satisfies your transformation conditions. After solving it, given your inputs you'll get the following function:
toDegrees(input: number): number {
  return 1.8 * input - 90;
}

And the usage in the template:


text:
Q: Dynamic query expression builder Hi i was wondering how can i achieve the query expression below in dynamic way :
DataTable _dataSourceMatrix = GetManager.Budget.GetAll().ConvertToDataTable();

switch (EntityType)
{
    case DomainType.Department:
        DataTable _departmentList = GetManager.DepartmentManager.GetAll().ConvertToDataTable();

        var _genericBudgetJoinDepartmentList = from a in _dataSourceMatrix.AsEnumerable()
                                               join b in _departmentList.AsEnumerable()
                                               on a.Field<int>("EntityID") equals b.Field<int>("DepartmentID")
                                               select new { EntityName = b.Field<string>("Name"), Period = a.Field<string>("Period"), Value = a.Field<double>("Value"), EntityID = a.Field<int>("EntityID") };

        _dataSourceMatrix = _genericBudgetJoinDepartmentList.OrderBy(x => x.Period).ConvertToDataTable();

        break;
}

As you can see i have a dynamic type of EntityType to indicate what sort of target datasource that needs to join with the _dataSourceMatrix. I dont want the code getting bloated by keep rewriting the same query expression with just the change of the target source to join. I had came across with some stuff like QueryBuilder, but it does not seems like able to achieve something that i wanted to be. Any idea for that ?

A: Since you have to select the table and field based on the EntityType, there are a number of ways to set them, including using the switch case or creating a Dictionary indexed by EntityType. Once you have them selected, you can process the join:
DataTable _dataSourceMatrix = GetManager.Budget.GetAll().ConvertToDataTable();

DataTable _joinTable = null;
string _joinField = String.Empty;

switch (EntityType) {
    case DomainType.Department:
        joinTable = GetManager.DepartmentManager.GetAll().ConvertToDataTable();
        _joinField = "DepartmentID";
        break;
}

var _genericBudgetJoinDepartmentList = from a in _dataSourceMatrix.AsEnumerable()
                                       join b in _joinTable.AsEnumerable()
                                       on a.Field<int>("EntityID") equals b.Field<int>(_joinField)
                                       select new { EntityName = b.Field<string>("Name"), Period = a.Field<string>("Period"), Value = a.Field<double>("Value"), EntityID = a.Field<int>("EntityID") };

_dataSourceMatrix = _genericBudgetJoinDepartmentList.OrderBy(x => x.Period).ConvertToDataTable();


text:
Q: TextBox text update with MultiThreading I'm having quite an annoying issue with Multithreading, I'm just updating a textBox with multilines inside a loop like this:
if (results.Lines.Count() != 0)
    this.InvokeEx(f => f.results.Text += Environment.NewLine);

this.InvokeEx(f => f.results.AppendText("0\t1"));

When I run this with just one Thread, all looks ok:

But when I run with multi threading (10 Threads at the same time):

It looks like that the writing in the textBox is not Synchronized, everything looks messed up.
Any way to solve this?
This with Windows Forms application with .Net Framework 4.
Thanks in advance.

A: That's because a thread that just wrote a new line, might be preempted by another thread about to write another new line.
You should make sure your two instructions are seen as an atomic operation. I.e., multiple concurrent operations will be seen as if they were sequential.
You do this by introducing a lock around your critical region.
private readonly object _lock = new object();

lock(_lock)
{
    if (results.Lines.Count() != 0)
        this.InvokeEx(f => f.results.Text += Environment.NewLine);

    this.InvokeEx(f => f.results.AppendText("0\t1"));
}

A: You want the appending of the new line with the additional text to be an atomic operation.  Currently you are in no way enforcing the constraint that these two operations be performed atomically, even though you rely on it.  The easiest solution is to simply call Invoke once, and build up the string before doing so:
string textToAppend = ConstructStringToAppend();

this.InvokeEx(f => f.results.AppendText(textToAppend));

Now you know that the string will be written to as one atomic operation.

A: You could eliminate checking the line count every time and condense it to a one-liner:
this.InvokeEx(
    f => f.results.AppendText(string.Concat("0\t1", Environment.NewLine)));


text:
Q: Google sign-in button not working in Chrome Extension I have a firebase app that requires users to be authenticated using Google.
I managed to hook up all settings and users can read/write to their prospective database location on firebase.
The only issue is: I am trying to display the Google-Sign-In button inside a chrome extension pop up. Here is my manifest.json
{
    "manifest_version" : 2,
    "name" : "MY EXTENSION",
    "version" : "0.0.6",
    "browser_action" : {
        "default_popup" : "welcome.html"
    },
    "background" : {
        "scripts" : ["js/jquery.min.js","js/firebase.js","js/firebase_config.js","js/background.js"],
        "persistent" : false
    },
    "oauth2" : {
        "client_id" : "686230544294-m9jfmc18cneiandadq8riborrjmq36in.apps.googleusercontent.com",
        "scopes" : [
            "openid", "email", "profile"
        ]
    },
    "content_security_policy" : "script-src 'self' 'unsafe-eval' https://apis.google.com; object-src 'self'"

}

Here is my welcome.html:
<!DOCTYPE html>

        <meta name="google-signin-scope" content="profile email">
        <meta name="google-signin-client_id" content="686230544294-m9jfmc18cneiandadq8riborrjmq36in.apps.googleusercontent.com">

Welcome. Please sign in

The pop up opens up with everything except for the button. When I inspect its console, I get the following error:

Uncaught uO
  message: "Invalid cookiePolicy"stack: "gapi.auth2.ExternallyVisibleError: Invalid cookiePolicy↵    at new uO (https://apis.google.com/_/scs/apps-static/_/js/k=oz.gapi.en.iUeg......

From firebase side, I can see users signing in.
What am I doing wrong? why doesn't the Sign-In button show up on the extension pop up?

A: If you don't plan to request additional OAuth scope and are just using this for authentication and not authorization, Firebase Auth signInWithPopup will take care of signing in a user to Google directly for you in Chrome Extensions as long as you whitelist your chrome extension domain: https://firebase.google.com/docs/auth/web/google-signin#authenticate_with_firebase_in_a_chrome_extension


text:
Q: Can't translate the post meta data (Date) in another language I want to translate the post meta data (date) in chines language for example, September 13, 2017, should be translated as 2017年9月13. But my code gives it in English. Do you see any error? Please help.
Thank you in advance.
  $time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time>';
        if (get_the_time('U') !== get_the_modified_time('U')) {
            $time_string .= '<time class="updated" datetime="%3$s">%4$s</time>';
        }

        $time_string = sprintf($time_string,
            esc_attr(get_the_date('c')),
            esc_html(get_the_date()),
            esc_attr(get_the_modified_date('c')),
            esc_html(get_the_modified_date())
        );
        printf(__(' %3$s', 'colormag'),
            esc_url(get_permalink()), esc_attr(get_the_time()), $time_string
        );

A: You don't need to change any code.
get_the_date without an argument will use the date_format option in your WordPress settings. The option F j, Y will substitute F as "September", but if you have a translation of "September" it will be used.
Comments have suggested the use of date_i18n. This is used automatically when you call get_the_date(). Translations of the days and months are in WordPress core and will be used if installed. e.g. The Chinese translation of "September" is here,
However, if you want to print "2017年9月13" I think you will have to set a custom format in your WordPress settings as:
Y年m月d

Under Settings > General > Date Format, select "Custom" and enter that into the field. I've tested that and it formats the Chinese characters just fine.


text:
Q: Is it possible to access ResourceFunctions with MMA <12 I thought I was late to the party and that ResourceFunctions had been around for some time, but I see now from @DanielLichtblau 's post community post here they arrived only in June 2019.
It seems MMA 12 is required to use the built in function ResourceFunction, but many functions would probably work perfectly well in MMA <12.
The question is: can one get and use ResourceFunctions without MMA 12 - if so, how?

A: Go to the web page of the resource you're trying to access. In the top-right corner there is a button "Source Notebook" that allows you to download the notebook that defines the resource function. Open it, execute it, and you're probably good to go.

A: Note: once the new "ResourceSystemClient" is on the paclet server all of this gymnastics will be unnecessary
Run this in the cloud:
rsc=PacletFind["ResourceSystemClient"][[1]]["Location"];
pac=CreateArchive[rsc,"RSC.paclet"];
CopyFile[pac, CloudObject["RSC.paclet", Permissions->"Public"]]

Then click on the link which will download the file.
Next, locally, install that with
pac = PacletInstall["path/to/RSC.paclet"]

That should complain about version mismatches, so then run
SystemOpen@pac["Location"]

Find the PacletInfo.m file and change the MathematicaVersion->"12.0+" to MathematicaVersion->"11.0+".
Next run
RebuildPacletData[]

And if all goes well ResourceFunction will be made available. If it's not, you'll need to restart Mathematica to get it to show up.


text:
Q: How to create a iframe that appears when you click a button using jquery I would like to have an iframe inserted into a column div on my web page when someone clicks on it. How do I make this possible? When someone is just viewing the page the iframe will be made invisible, but when a button is clicked the iframe will be made visible. How can I do this?

A: Give your iframe a class like hidden iframe then add the following JavaScript before the closing </body> tag:
Your Frame
<iframe src="..." other-iframe-stuff="" class="hidden iframe">

</iframe>

JS
<script>
$(function(){
   $(".your-toggle-btn").click(function(){
      $(".iframe").removeClass("hidden");
   });
});
</script>

Your button should have a your-toggle-btn class and define the following CSS styles:
CSS
.hidden {
    display: none;
}

A: Give your iframe and button classes or data-attributes, so you can reference them.
Then create an event that displays the iframe on button click, using jQuerys hide() and show() functions. It's important that the iframe is visible to start with if you wan't the site to function when javascript is turned off.
<script>
$(function(){
   var $button = $('.iframe-opener'); // or [data-iframe-opener]
   var $iframe = $('.iframe'); // or [data-iframe]
   $iframe.hide();
   $button.click(function() {
       $iframe.show();
   });
});
</script>


text:
Q: Hardcode the date value in Query SSRS I have a query which I am trying to hard code the date value. Currently this data is coming from SSRS Calendar. I think my data is coming little different than expected. To debug all the things I need to hard code the date section.
How can I take care of these things? I am new to SQL and SSRS.
WITH Calendar (Start_Date, End_Date) AS(
Select TOP 6
DATEADD(mm, DATEDIFF(m,0,DATEADD(MONTH, DATEDIFF(MONTH, 0, @StartDate) -6 + Row_Number() Over (Order By CI_ID), 0)),0)[Start_Date],
DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,DATEADD(MONTH, DATEDIFF(MONTH, 0, @StartDate) -6 + Row_Number() Over (Order By CI_ID), 0))+1,0)) [End_Date]
From v_UpdateInfo
Group by CI_ID
)
Select Start_Date, End_Date,
(Select count(distinct ucs.ResourceID)
From v_Update_ComplianceStatus ucs
JOIN v_UpdateInfo ui on ui.CI_ID = ucs.CI_ID and ucs.Status = 2 AND ui.IsSuperseded = 0
JOIN v_CICategoryInfo_All cica JOIN v_CategoryInfo ci on cica.CategoryInstanceID = ci.CategoryInstanceID AND cica.CategoryInstanceName IN (@Category) on ucs.CI_ID = cica.CI_ID
Where ucs.ResourceID IN (Select rs.ResourceID from v_r_system  rs   JOIN V_FullCollectionMembership AS FCM on rs.ResourceID = FCM.ResourceID and FCM.CollectionID = @CollectionID  JOIN v_UpdateScanStatus uss on uss.ResourceID = rs.ResourceID where rs.Operating_System_Name_and0 like '%Workstation 6.1%' And DATEDIFF("d",uss.LastScanTime,getdate()) <= @DaysScanned AND rs.Obsolete0 = 0 )
AND ui.DateRevised BETWEEN cal.Start_Date AND cal.End_Date
) [Windows 7],
(Select count(rs.ResourceID) from v_r_system rs JOIN V_FullCollectionMembership AS FCM on rs.ResourceID = FCM.ResourceID and FCM.CollectionID = @CollectionID  JOIN v_UpdateScanStatus uss on uss.ResourceID = rs.ResourceID where rs.Operating_System_Name_and0 like '%Workstation 6.3%' And DATEDIFF("d",uss.LastScanTime,getdate()) <= @DaysScanned AND rs.Obsolete0 = 0) [Windows 8.1 Total],
(Select count(distinct ucs.ResourceID)
From v_Update_ComplianceStatus ucs
JOIN v_UpdateInfo ui on ui.CI_ID = ucs.CI_ID and ucs.Status = 2 AND ui.IsSuperseded = 0
JOIN v_CICategoryInfo_All cica JOIN v_CategoryInfo ci on cica.CategoryInstanceID = ci.CategoryInstanceID AND cica.CategoryInstanceName IN (@Category) on ucs.CI_ID = cica.CI_ID
Where ucs.ResourceID IN (Select rs.ResourceID from v_r_system rs    JOIN V_FullCollectionMembership AS FCM on rs.ResourceID = FCM.ResourceID and FCM.CollectionID = @CollectionID  JOIN v_UpdateScanStatus uss on uss.ResourceID = rs.ResourceID where rs.Operating_System_Name_and0 like '%Workstation 10%' And DATEDIFF("d",uss.LastScanTime,getdate()) <= @DaysScanned AND rs.Obsolete0 = 0 )
AND ui.DateRevised BETWEEN cal.Start_Date AND cal.End_Date
) [Windows 10],
(Select count(rs.ResourceID) from v_r_system rs JOIN V_FullCollectionMembership AS FCM on rs.ResourceID = FCM.ResourceID and FCM.CollectionID = @CollectionID  JOIN v_UpdateScanStatus uss on uss.ResourceID = rs.ResourceID where rs.Operating_System_Name_and0 like '%Workstation 10%' And DATEDIFF("d",uss.LastScanTime,getdate()) <= @DaysScanned AND rs.Obsolete0 = 0) [Windows 10 Total]
from Calendar cal

So, far i tried this.
Declare start_date = '2019-06-01';
declare end_date = '2019-11-30';
    --WITH Calendar (Start_Date, End_Date) AS(
    Select TOP 6
    DATEADD(mm, DATEDIFF(m,0,DATEADD(MONTH, DATEDIFF(MONTH, 0, @StartDate) -6 + Row_Number() Over (Order By CI_ID), 0)),0)[Start_Date],
    DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,DATEADD(MONTH, DATEDIFF(MONTH, 0, @StartDate) -6 + Row_Number() Over (Order By CI_ID), 0))+1,0)) [End_Date]
    From v_UpdateInfo
    Group by CI_ID
    )
    Select Start_Date, End_Date,
    (Select count(distinct ucs.ResourceID)
    From v_Update_ComplianceStatus ucs
    JOIN v_UpdateInfo ui on ui.CI_ID = ucs.CI_ID and ucs.Status = 2 AND ui.IsSuperseded = 0
    JOIN v_CICategoryInfo_All cica JOIN v_CategoryInfo ci on cica.CategoryInstanceID = ci.CategoryInstanceID --AND
    --cica.CategoryInstanceName -- IN (@Category)
    on ucs.CI_ID = cica.CI_ID
    Where ucs.ResourceID IN (Select rs.ResourceID from v_r_system  rs   JOIN V_FullCollectionMembership AS FCM on rs.ResourceID = FCM.ResourceID
     and FCM.CollectionID = 'ABC0028'  JOIN v_UpdateScanStatus uss on uss.ResourceID = rs.ResourceID
     where rs.Operating_System_Name_and0 like '%Workstation 6.1%' And DATEDIFF("d",uss.LastScanTime,getdate()) <= @DaysScanned AND rs.Obsolete0 = 0 )
    AND ui.DateRevised BETWEEN cal.Start_Date AND cal.End_Date
    ) [Windows 7],
    (Select count(rs.ResourceID) from v_r_system rs JOIN V_FullCollectionMembership AS FCM on rs.ResourceID = FCM.ResourceID
    and FCM.CollectionID = 'ABC0028'  JOIN v_UpdateScanStatus uss on uss.ResourceID = rs.ResourceID
    where rs.Operating_System_Name_and0 like '%Workstation 6.3%'
    And DATEDIFF("d",uss.LastScanTime,getdate()) <= @DaysScanned AND rs.Obsolete0 = 0) [Windows 8.1 Total],
    (Select count(distinct ucs.ResourceID)
    From v_Update_ComplianceStatus ucs
    JOIN v_UpdateInfo ui on ui.CI_ID = ucs.CI_ID and ucs.Status = 2 AND ui.IsSuperseded = 0
    JOIN v_CICategoryInfo_All cica JOIN v_CategoryInfo ci on cica.CategoryInstanceID = ci.CategoryInstanceID
    --AND cica.CategoryInstanceName IN (@Category)
     on ucs.CI_ID = cica.CI_ID
    Where ucs.ResourceID IN (Select rs.ResourceID
    from v_r_system rs  JOIN V_FullCollectionMembership AS FCM on rs.ResourceID = FCM.ResourceID and FCM.CollectionID = 'ABC0028'
    JOIN v_UpdateScanStatus uss on uss.ResourceID = rs.ResourceID
    where rs.Operating_System_Name_and0 like '%Workstation 10%' And DATEDIFF("d",uss.LastScanTime,getdate()) <= @DaysScanned AND rs.Obsolete0 = 0 )
    AND ui.DateRevised BETWEEN cal.Start_Date AND cal.End_Date
    ) [Windows 10],
    (Select count(rs.ResourceID) from v_r_system rs JOIN V_FullCollectionMembership AS FCM on rs.ResourceID = FCM.ResourceID and
     FCM.CollectionID = 'ABC0028'  JOIN v_UpdateScanStatus uss on uss.ResourceID = rs.ResourceID where rs.Operating_System_Name_and0
     like '%Workstation 10%' And DATEDIFF("d",uss.LastScanTime,getdate()) <= @DaysScanned AND rs.Obsolete0 = 0) [Windows 10 Total]
    --from Calendar cal

A: You have 2 date parameters controlling your query. They are Start_Date and End_Date. You will need to update all references to these in the query. In the original query you posted there are 2 references.
To keep modification to the query minimal all I did in this solution is modify the CTE to use your hard coded dates.
Also, want to note that there are other variables besides the dates in this query that will need to be declared and handled. They are @DaysScanned and @CollectionID. Since you didn't mention them in your OP I am assuming they are not an issue for you.
WITH Calendar (Start_Date, End_Date)
AS (SELECT CAST('2019-06-01' AS DATETIME2) AS [Start_Date],
           CAST('2019-11-30' AS DATETIME2) AS [End_Date])
SELECT Start_Date,
       End_Date,
       (
           SELECT COUNT(DISTINCT ucs.ResourceID)
           FROM v_Update_ComplianceStatus ucs
               JOIN v_UpdateInfo ui
                   ON ui.CI_ID = ucs.CI_ID
                      AND ucs.Status = 2
                      AND ui.IsSuperseded = 0
               JOIN v_CICategoryInfo_All cica
                   JOIN v_CategoryInfo ci
                       ON cica.CategoryInstanceID = ci.CategoryInstanceID
                          AND cica.CategoryInstanceName IN ( @Category )
                   ON ucs.CI_ID = cica.CI_ID
           WHERE ucs.ResourceID IN
                 (
                     SELECT rs.ResourceID
                     FROM v_r_system rs
                         JOIN V_FullCollectionMembership AS FCM
                             ON rs.ResourceID = FCM.ResourceID
                                AND FCM.CollectionID = @CollectionID
                         JOIN v_UpdateScanStatus uss
                             ON uss.ResourceID = rs.ResourceID
                     WHERE rs.Operating_System_Name_and0 LIKE '%Workstation 6.1%'
                           AND DATEDIFF("d", uss.LastScanTime, GETDATE()) <= @DaysScanned
                           AND rs.Obsolete0 = 0
                 )
                 AND ui.DateRevised
                 BETWEEN cal.Start_Date AND cal.End_Date
       ) [Windows 7],
       (
           SELECT COUNT(rs.ResourceID)
           FROM v_r_system rs
               JOIN V_FullCollectionMembership AS FCM
                   ON rs.ResourceID = FCM.ResourceID
                      AND FCM.CollectionID = @CollectionID
               JOIN v_UpdateScanStatus uss
                   ON uss.ResourceID = rs.ResourceID
           WHERE rs.Operating_System_Name_and0 LIKE '%Workstation 6.3%'
                 AND DATEDIFF("d", uss.LastScanTime, GETDATE()) <= @DaysScanned
                 AND rs.Obsolete0 = 0
       ) [Windows 8.1 Total],
       (
           SELECT COUNT(DISTINCT ucs.ResourceID)
           FROM v_Update_ComplianceStatus ucs
               JOIN v_UpdateInfo ui
                   ON ui.CI_ID = ucs.CI_ID
                      AND ucs.Status = 2
                      AND ui.IsSuperseded = 0
               JOIN v_CICategoryInfo_All cica
                   JOIN v_CategoryInfo ci
                       ON cica.CategoryInstanceID = ci.CategoryInstanceID
                          AND cica.CategoryInstanceName IN ( @Category )
                   ON ucs.CI_ID = cica.CI_ID
           WHERE ucs.ResourceID IN
                 (
                     SELECT rs.ResourceID
                     FROM v_r_system rs
                         JOIN V_FullCollectionMembership AS FCM
                             ON rs.ResourceID = FCM.ResourceID
                                AND FCM.CollectionID = @CollectionID
                         JOIN v_UpdateScanStatus uss
                             ON uss.ResourceID = rs.ResourceID
                     WHERE rs.Operating_System_Name_and0 LIKE '%Workstation 10%'
                           AND DATEDIFF("d", uss.LastScanTime, GETDATE()) <= @DaysScanned
                           AND rs.Obsolete0 = 0
                 )
                 AND ui.DateRevised
                 BETWEEN cal.Start_Date AND cal.End_Date
       ) [Windows 10],
       (
           SELECT COUNT(rs.ResourceID)
           FROM v_r_system rs
               JOIN V_FullCollectionMembership AS FCM
                   ON rs.ResourceID = FCM.ResourceID
                      AND FCM.CollectionID = @CollectionID
               JOIN v_UpdateScanStatus uss
                   ON uss.ResourceID = rs.ResourceID
           WHERE rs.Operating_System_Name_and0 LIKE '%Workstation 10%'
                 AND DATEDIFF("d", uss.LastScanTime, GETDATE()) <= @DaysScanned
                 AND rs.Obsolete0 = 0
       ) [Windows 10 Total]
FROM Calendar cal;


text:
Q: How can I target Windows 10 IoT Core 17763 in a Visual Studio Project? My current version of Windows 10 IoT Core Dashboard (1.0.1810.11000) allows for setting up a device with version 17763 of Windows 10 IoT Core.

In Visual Studio 2017 (15.87) though, I only have the option to target 17134 in my Universal Windows project (on the Application tab in the project settings page).

I worry about issues related to inconsistent versions. Is this justified? Or can I expect these versions to work together seamlessly?
I considered trying to get the IoT Dashboard to target the older version that Visual Studio is using but from what I understand, it will pretty much just keep jumping to the latest version with no option to target older versions. I saw somewhere that Windows IoT Enterprise allows for more control over versions. Do I need to go down that path if I want consistent versions between the Dashboard and Visual Studio? This comparison would indicate that Core would otherwise be the best choice for my requirements?
Ideally, I would like some means of getting Visual Studio to target the new version. Is this possible? How would I do that?

A: After installing the Windows 10 SDK, I was able to select version 17763 as the target version in Visual Studio.


text:
Q: Can't read the file with BufferedReader I'm trying to read a file from the assets folder in my Android project but can't make it work. I'm trying something like this:
public class MainActivity extends AppCompatActivity {

    TextView fileContentTextView;
    StringBuilder stringBuilder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fileContentTextView = findViewById(R.id.file_content_textview);

        stringBuilder = new StringBuilder();

        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                AssetManager assetManager = getBaseContext().getAssets();
                try {
                    InputStream inputStream = assetManager.open("cos.txt");
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    String str;
                    str = bufferedReader.readLine();
                    stringBuilder.append(str);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        Log.d("ECG", stringBuilder.toString());
        String textToShow = stringBuilder.toString();
        fileContentTextView.setText(textToShow);
    }
}

But nothing shows up in the log or when trying to setText. Don't know what I'm doing wrong.
Thanks in advance.

A: I am not sure why you need to use AsyncTask.execute(). As explained by CommonsWare's comment, it executes in a background thread (separate from the main UI thread). Thus, stringbuilder.append(str) is being called later whereas Log.d("ECG", stringBuilder.toString());   String textToShow = stringBuilder.toString(); fileContentTextView.setText(textToShow); are being called sooner.
There are thus, two ways to correct this:

*

*Remove the code from AsysncTask.execute() as shown:

public class MainActivity extends AppCompatActivity {

    TextView fileContentTextView;
    StringBuilder stringBuilder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fileContentTextView = findViewById(R.id.file_content_textview);

        stringBuilder = new StringBuilder();

        AssetManager assetManager = getBaseContext().getAssets();
        try {
            InputStream inputStream = assetManager.open("cos.txt");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String str;
            str = bufferedReader.readLine();
            stringBuilder.append(str);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Log.d("ECG", stringBuilder.toString());
        String textToShow = stringBuilder.toString();
        fileContentTextView.setText(textToShow);
    }
}

*Put the log.d and fileContentTextView.setText(textToShow); inside the AsyncTask.execute()

public class MainActivity extends AppCompatActivity {

    TextView fileContentTextView;
    StringBuilder stringBuilder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fileContentTextView = findViewById(R.id.file_content_textview);

        stringBuilder = new StringBuilder();

        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                AssetManager assetManager = getBaseContext().getAssets();
                try {
                    InputStream inputStream = assetManager.open("cos.txt");
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    String str;
                    str = bufferedReader.readLine();
                    stringBuilder.append(str);
                    Log.d("ECG", stringBuilder.toString());
                    String textToShow = stringBuilder.toString();
                    fileContentTextView.setText(textToShow);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }
}

I have tested both and they have worked for me.


text:
Q: Detecting hand written X and find its center (intersection of the two lines forming an X) I'm working with opencv and need some technique to achieve the following,

*

*what could be the best way to detect handwritten Xs in an image? also how to find the center of each X? given that the background could be white or vary.
sample images are attached

_

*is there is a way to detect handwritten English characters (alphabets) in general? (this is out of the scope of the original question?)

A: What i am going to suggest is possible theoretically.
When you are going to write "X" draw 4 circles to it's corners. And use finding circle algorithm of opencv. Search it so basic to use. The function will give the center of circles as output to you. Then draw line between cross circles. If those 2 lines intersects it is an X and the intersection point is the center you are looking for. Basic geometry. You can do all with 30 mins google search if you are familiar with coding.


text:
Q: Returning an object of same return type gives a syntax error I have two functions. They are as follows,
public Post findById(Long id){
    for (Post thePost : ALL_POSTS) {
        if(thePost.getId()==id){
            return thePost;
        }
    }
    return null;
}

public Post findById_Two(Long id) {
    ALL_POSTS.forEach((thePost) -> {
        if(thePost.getId()==id){
            System.out.println(thePost.getId()==id);
            return thePost;
        }
    });
    return null;
}

As you can see, both functions have a return Type of class Post and returns an object of the same class after a simple check. The first function works fine without any errors while the second function gives me an Unexpected return value error while trying to return thePost.
Can you please let me know what is causing this error and where did I go wrong?

A: The problem is that using return from inside a lambda expression returns from the lambda. Your forEach expects a Consumer<Post>, which is normally void. It's okay to provide a lambda that does return a value where void is expected (the value is just ignored), but you are returning a value only where you have a match—and then you'd proceed to return null unconditionally.
If you're going to use lambdas, use lambda style:
public Post findById_streams(Long id) {
  return ALL_POSTS.stream()
    .filter(post -> id.equals(post.getId()))
    .findFirst()
    .orElse(null);
}

(Note also that you have a bug in comparing Long by ==; the code above handles that.)


text:
Q: Save values in db with submit button only I am trying to save some values into db, on first page i am running some matches and on the the 2nd page i need to save values. on first page only click button is shown to user, when he clicks , the values are stored.
code
<form action="ms_insert.php" method="post">
<input type="submit" value="Claim your daily bonus" name="test">
</form>

How can i submit all the values that are outside the form and send them to the   ms_insert.php and process the values.
What i need to achieve it like this.
some values shall be matched , on successful match it will save the enteries into the db.
Here is the exact code that i am using now :
<?php
if ( $thismemberinfo[msurf] >= $msurfclicks ) {
$sql=$Db1->query("INSERT INTO d_bonus VALUES('$userid','0.02',NOW())");
echo "success";
}
else
{
echo "wrong";
}
?>
<form action="" method="post">
<input type="hidden" value="123" name="match">
<input type="submit" value="Claim your daily bonus $o.o2" name="claim">
</form>

I want this php code to excute when user click the submit button.

A: There are two ways that I can think of doing this:

*

*Simply set the post variable to another value as described here:
$_POST['text'] = 'another value';

This will override the previous value corresponding to text key of the array. The $_POST is super global associative array and you can change the values like a normal php array.

*Second would be to use _SESSION tags as described in this post:
In the first.php:
$_SESSION['favcolor'] = 'green';

In ms_insert.php:
echo $_SESSION['favcolor']; // green

P.S. You can also use cookies
Additional sources:

*

*http://www.felixgers.de/teaching/php/hidden1.html

A: You can use Javascript with a XHR object for example or try to insert your values to store in hidden inputs.
Solution 1 : AJAX, for example :
Your JS (Here with Jquery):
function saveInDb(){

    /* Retrieve your values in your page : */
    var myValue1 = $('#value1Id').val();
    var myValue2 = $('#value2Id').val();

    /*Create a Jquery ajax object : */
    $.ajax({
      type: "POST",
      url: "ms_insert.php",
      data: { "value1": myValue1, "value2": myValue2 }
    }).done(function( msg ) {
        alert( "Data Saved");
    });
}

Your HTML :
My value 1
My value 2
<button onclick=saveInDb()></button>

Solution 2 : the HTML  with hidden inputs :
<form action="ms_insert.php" method="post">
   <input type="hidden" value="My value 1" name="value1">
   <input type="hidden" value="My value 2" name="value2">
   <input type="submit" value="Claim your daily bonus" name="test">
</form>