text:
Q: How to get the bottom coordinate of visible items inTRichView? I am working on one project where I need the pixel of Last visible item in the TRichview.
By using 'LastVisibleItem' Property of TRichView I am able to find the Item Start Cordinate.
but the Problem is I need a pixel value of very last visible word.
Can any one tell me how I can get that?
Thanks in advance.

A: I'm a bit unsure how your LastVisibleItem property works. Below is a suggested solution to get the top-right coordinate of the last visible character. Hope it works for you.
//Function GetCharPos source: http://www.delphipages.com/forum/showthread.php?t=33707
function GetCharPos(AOwner : TControl; Index : LongInt) : TPoint;
var
  p : TPoint;
begin
  AOwner.Perform(EM_POSFROMCHAR,WPARAM(@p),Index);
  Result := p;
end;

//Inspired by: http://www.swissdelphicenter.ch/en/showcode.php?id=1213
function GetLastVisibleCharIndex(AOwner : TControl):integer;
var
  r: TRect;
begin
  //The EM_GETRECT message retrieves the formatting rectangle of an edit control.
  AOwner.Perform(EM_GETRECT, 0, Longint(@r));
  r.Right := r.Right - 1;
  r.Bottom := r.Bottom - 2;
  //The EM_CHARFROMPOS message retrieves information about the character closest to a specified point in the client area of an edit control
  result := AOwner.Perform(EM_CHARFROMPOS, 0, Integer(@r.BottomRight));
end;

//Get the Top-Right coordinate of the last visible character
function GetLastVisibleCharPos(AOwner : TControl):TPoint;
var Index : integer;
begin
  index := GetLastVisibleCharIndex(AOwner);
  result := GetCharPos(AOwner, index);
end;

Example usage:
procedure TForm2.Button3Click(Sender: TObject);
var
  p : TPoint;
begin
  p := GetLastVisibleCharPos(RichEdit1);

  DrawCrossHair(p); //Help visualize the point
end;

//Helper proc to draw a cross-hair
procedure TForm2.DrawCrossHair(p : TPoint);
var
  aCanvas: Tcanvas;
  X, Y: Integer;
begin

  aCanvas := TCanvas.Create;
  Y := RichEdit1.Height;
  X := RichEdit1.Width;
  try
    aCanvas.Handle := GetDC(RichEdit1.Handle);
    aCanvas.Font := RichEdit1.Font;

    aCanvas.Pen.color := clGreen; // Color of line

    //Draw vertical line
    aCanvas.MoveTo(p.x, 0);
    aCanvas.LineTo(p.x, Y);

    //Draw horizontal line
    aCanvas.MoveTo(0, p.Y);
    aCanvas.LineTo(x, p.y);
  finally
    ReleaseDC(RichEdit1.Handle, aCanvas.Handle);
    aCanvas.Free;
  end;
end;


text:
Q: Find all files matching desription and create hard link in directory I would like to find all .mkv files in my download directory and create a hard link to them in my /movies/ directory.
Here's what I have so far:
for i in `find /download/ -name *.mkv`; do ln "$i" /movies/; done

Which almost works: I receive a bunch of hard links to partial file names. That is, instead of a hard link to say The Best Movie Ever.mkv I receive four hard links, one to The one to Best one to Movie and one to Ever.mkv
Any suggestions?

A: Try this way:
find /download/ -name *.mkv -exec ln {} /movies/ \;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Execution time millis equal to 0 - MongoDB I used two NOSQL database, MongoDB and Neo4j, to handle the same information. I want to compare the performance using the first and second db. I talked about my problem with MongoDB in this question: the execution time millis was always equal to 0. So I added approximately 250 documents in my collection but without any success:
> db.team.find({common_name:"Milan"},{_id:0, "stadium.name":1}).explain("executionStats")

{
        "queryPlanner" : {
                "plannerVersion" : 1,
                "namespace" : "Progettino.team",
                "indexFilterSet" : false,
                "parsedQuery" : {
                        "common_name" : {
                                "$eq" : "Milan"
                        }
                },
                "winningPlan" : {
                        "stage" : "PROJECTION",
                        "transformBy" : {
                                "_id" : 0,
                                "stadium.name" : 1
                        },
                        "inputStage" : {
                                "stage" : "COLLSCAN",
                                "filter" : {
                                        "common_name" : {
                                                "$eq" : "Milan"
                                        }
                                },
                                "direction" : "forward"
                        }
                },
                "rejectedPlans" : [ ]
        },
        "executionStats" : {
                "executionSuccess" : true,
                "nReturned" : 1,
                "executionTimeMillis" : 0,
                "totalKeysExamined" : 0,
                "totalDocsExamined" : 253,
                "executionStages" : {
                        "stage" : "PROJECTION",
                        "nReturned" : 1,
                        "executionTimeMillisEstimate" : 0,
                        "works" : 255,
                        "advanced" : 1,
                        "needTime" : 253,
                        "needFetch" : 0,
                        "saveState" : 0,
                        "restoreState" : 0,
                        "isEOF" : 1,
                        "invalidates" : 0,
                        "transformBy" : {
                                "_id" : 0,
                                "stadium.name" : 1
                        },
                        "inputStage" : {
                                "stage" : "COLLSCAN",
                                "filter" : {
                                        "common_name" : {
                                                "$eq" : "Milan"
                                        }
                                },
                                "nReturned" : 1,
                                "executionTimeMillisEstimate" : 0,
                                "works" : 255,
                                "advanced" : 1,
                                "needTime" : 253,
                                "needFetch" : 0,
                                "saveState" : 0,
                                "restoreState" : 0,
                                "isEOF" : 1,
                                "invalidates" : 0,
                                "direction" : "forward",
                                "docsExamined" : 255
                        }
                }
        }

For example in MongoDB, this query will work better than in Neo4j, because I used denormalized model to represent information about teams' stadium. In fact, in Neo4j, this query needs 50 ms as you can see:

So, what can I do to have information about execution time millis in MongoDB? I have some problems if execution time millis is always equal to 0 because I can't show different performance on same queries with the two different NoSQL DB.

A: As stated in your other question that I answered. Your collection is just too small. here is the output I have from a database with over 3K items. Notice my executionTimeInMillis is only 2 milliseconds. You are going to need a lot more data to make mongo really churn. talking 10K plus records depending on what the size of your machine is.
{
"queryPlanner" : {
    "plannerVersion" : 1,
    "namespace" : "arenas.arenas",
    "indexFilterSet" : false,
    "parsedQuery" : {
        "$and" : []
    },
    "winningPlan" : {
        "stage" : "COLLSCAN",
        "filter" : {
            "$and" : []
        },
        "direction" : "forward"
    },
    "rejectedPlans" : []
},
"executionStats" : {
    "executionSuccess" : true,
    "nReturned" : 3718,
    "executionTimeMillis" : 2,
    "totalKeysExamined" : 0,
    "totalDocsExamined" : 3718,
    "executionStages" : {
        "stage" : "COLLSCAN",
        "filter" : {
            "$and" : []
        },
        "nReturned" : 3718,
        "executionTimeMillisEstimate" : 0,
        "works" : 3724,
        "advanced" : 3718,
        "needTime" : 1,
        "needFetch" : 4,
        "saveState" : 31,
        "restoreState" : 31,
        "isEOF" : 1,
        "invalidates" : 0,
        "direction" : "forward",
        "docsExamined" : 3718
    },
    "allPlansExecution" : []
}

}

A: I'm not sure if comparing a denormalized Mongo DB is fair unless you're talking about building a very specific use-case where you won't ever build out complexity on top of what you have.
That said, you'll want to familiarized yourself with the PROFILE and EXPLAIN commands in Neo4j's cypher (assuming you're using version 2.2.x).  That will help you understand what Neo4j is doing.
I expect that one thing that you'll want to do, if you haven't already, is to create an index on the _id property of the Team label like this:
CREATE INDEX ON :Team(_id)

If it's a unique property you'll probably want to create a constraint (which automatically creates an index for you) like this:
CREATE CONSTRAINT ON (n:Team) ASSERT n._id IS UNIQUE

If you do this then that n1 node in your MATCH will be able to use the index to go right to the node(s) on disk that you care about and then do a handful of hops across the PLAYS relationship to get those other nodes.
Also, agreed that you should try testing with more data ;)


text:
Q: Bootstrap: tab transition issue I have to change the original bootstrap CSS slightly in a tab-content in order to allow for a script to run.
.tab-content>.tab-pane:not(.in) {
display: none;
}

Is not an option here since it remove the content from the dom and blocks the script from runing.
I have tried several option, the one working best so far is :
.tab-content>.tab-pane:not(.in) {
display:block !important;
height:0 !important;
}

However the transition is "jumpy", the tab replacing the previous active one disapears for a split second, bringing everything below it up then straight back down. Not smooth at all. Do I have to resort to create the whole thing from scratch or is there a fix using bootsrap ?
edit: added more code
HTML:
`
                        JERSEYS

*BIBS & SKINSUITS

                                VIEW ALL JERSEYS

                                VIEW ALL BIBS & SKINSUITS

`
CSS:
.tab-content>.tab-pane:not(.in) {
    display:block !important;
    height:0 !important;
  }


text:
Q: Power BI dashboard with reports based on a push dataset do not alwasy update regularly I have written a little C# program which pushes data to a a streaming push dataset on Power BI Service.  I have a report with a couple of simple visuals (nothing fancy) which are in turn pinned to a dashboard.
About half the time I open the dashboard the Dashboard updates every few seconds.  But half the time it does not update at all and is laggy even if I push the refresh button.
Why is it inconsistent?  I know the data pusher is running as I can refresh the base report and see the new data points come in.
What is it that I am missing?
Thanks


text:
Q: Htaccess causing subdomain '404 not found' error I'm trying to create a subdomain for showing clients their websites in development, by creating a 'subdomains' folder within 'public_html', and then creating individual 'subdomain' folders within that 'subdomains' folder, and redirecting each new site to its associated folder.
My problem is I expect with my htaccess code, whereb navigating to, for example, subdomain.website.com, I get the error below:
"The requested URL /.php was not found on this server."
...
Here's the code for my htaccess at the moment, just not sure how I can alter this to allow me to use this setup for each future subdomain in the 'subdomains' folder without getting this issue.
ErrorDocument 404 /404.php
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
# RewriteEngine On
# RewriteCond %{HTTP_HOST} !^www\. [NC]
# RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
Any help would be greatly appreciated as I'm in way over my head with htaccess stuff. Thank you in advance!
EDIT just confirming that the only file in the subdomain folder at the moment is an index.php file

A: Add this rule in top of your domain .htaccess file, %1 is your subdomain folder and $1 is your request (default document folder would be index.php).
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^(.*)\.example\.com
    RewriteRule ^(.*)$ /%1/$1 [L,NC,QSA]
</IfModule>

Check manual entry of subdomain folder:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^subdomain\.example\.com
    RewriteRule ^(.*)$ /subdomain/$1 [L,NC,QSA]
</IfModule>


text:
Q: Connecting an almost idempotent complex matrix to a diagonal 1-0 matrix $\newcommand{\diag}{\operatorname{diag}}$Let $e\in M_n(\mathbb{C})$ be an almost idempotent matrix in the sense that $\|e^2-e\|<\varepsilon<\frac{1}{4}$ where the norm is taken to be the usual operator norm, and also $\|e\|\leq N$ (where $N>1$). I want to connect $e$ to a matrix of the form $\diag(I_k,0_{n-k})$ (if it is possible) via a path $(e_t)$ such that for each $t$, $\|e_t^2-e_t\|<\varepsilon$ (or $<4\varepsilon$) and $\|e_t\|\leq N$ (or $\leq 4N$).
By functional calculus, we can get an idempotent $p$ (i.e. $p^2=p$) out of $e$.
One source of information on functional calculus for matrices is An Elementary Approach to the Functional Calculus for Matrices. The $k$ in the first paragraph is the rank of $p$.
I can do it in the case where $e$ is self-adjoint by first connecting $e$ to $p$, and then it is quite straightforward to connect $p$ to the desired matrix. In this case, all eigenvalues of $e$ are real with some of them close to 0 and the remaining ones close to 1. Those close to 0 can be connected to 0 by a path of real numbers, and those close to 1 can be connected to 1. I can write $e=uDu^*$ where $u$ is unitary and $D$ is diagonal with diagonal entries being the eigenvalues of $e$. I can connect $D$ to a matrix of the form $\diag(I_k,0_{n-k})$ by connecting each diagonal entry to 0 or 1. Thus I can connect $e$ to its associated idempotent, which in this case is precisely $u\diag(I_k,0_{n-k})\;u^*$.
But I haven't been able to do it without self-adjointness.


text:
Q: In what base system a given decimal-based number with no terminating decimal expansion can be represented in a finite string of digits? I was reading about precision floating numbers in the mpmath python module documentation and came across this https://mpmath.org/doc/current/contexts.html#arbitrary-precision-interval-arithmetic-iv:

The fact that '0.1' results in an interval of nonzero width indicates
that 1/10 cannot be represented using binary floating-point numbers at
this precision level (in fact, it cannot be represented exactly at any
precision).

This made me wonder if there's a way to determine in what base system a given decimal-based number with no terminating decimal expansion can be transferred in order to be represented in a finite string of digits.

A: It helps to understand why a certain number is terminating or non-terminating in a given base. Let us take base $b$. If you express a number $n$ in base $b$ as:
$$n=d_kd_{k-1}\cdots d_0 \space . \space d_{-1}d_{-2}\cdots d_{-l}$$
then this is equivalent to saying:
$$n=\sum_{i=-l}^k d_i \cdot b^i \implies b^ln=\sum_{i=0}^{k+l} d_{i-l} b^i$$
Now, it is clear that it is necessary $b^ln$ to be an integer for some $l \in \mathbb{N}$ for $n$ to terminate in base $b$. This is clearly a sufficient condition as well since if $b^ln$ is an integer, it clearly terminates in base $b$ (since all integers terminate in all bases), and thus, when dividing $b^ln$ by $b^l$, since it is base $b$, only digits move across the decimal point.
Hence, we have proven that a number $n$ terminates in base $b$ if and only if there exists $l \in \mathbb{N}$ such that $b^ln$ is an integer. This clearly cannot hold for irrational numbers $n$ since:
$$b^ln \in \mathbb{Z} \implies b^ln=t \implies n=\frac{t}{b^l}$$
where both $t$ and $b^l$ are non-zero integers, contradicting the fact that $n$ is irrational. Hence, irrational numbers are non-terminating in all bases.
Although, when you consider rational numbers, some rational numbers terminate in some bases but not in others. Consider the rational number $n=\frac{x}{y}$ in its simplest form. If $y$ has a prime factor $p$ that does not divide $b$, then no matter what $l$ you take, $b^ln$ will still have the prime factor $p$ in its denominator, and hence $b^ln$ cannot be an integer, which means that $n$ is non-terminating in base $b$.
If $y$ does not contain any such prime factor, then all prime factors of $y$ divide $b$. Define $l$ to be the largest power of a prime in the prime factorization of $y$. Then, it is clear that $b^ln$ is an integer since all the primes get cleared from the denominator. Hence, $n$ will terminate in base $b$.
Thus, a rational number is terminating in base $b$, if and only if for the denominator of $n$ in its simplest form, all its prime factors are also prime factors of $b$.

A: It depends what you mean by 'base system'. In base $\pi$, for instance, the units column is $1$, meaning that the 'tens' column is $\pi$, and so on. $\pi$ can be represented as $10$ in base $\pi$. However, if you require that the base is an integer, then no, there isn't an irrational number that can be written as a finite string. We can prove this by contraposition. If a number $n$ has a finite number of digits, then we can write the digits that come after the decimal point as
$$
.d_1d_2d_3\ldots d_k \, .
$$
This means that $$n=\text{integer part + }(b^{-1} \cdot d_1)+(b^{-2}\cdot d_2)+(b^{-3}\cdot d_3)+\ldots+(b^{-k}\cdot d_k) \, .$$The sum of finitely many rationals is rational. Hence, finite number of digits $\implies$ the number is rational. This means that irrational numbers can't have finitely many digits, and so they must have infinitely many digits.


text:
Q: How to operate on spans of rows in a matrix? I have a [2001,2] matrix of (x,y) values, but the number of rows could vary.
I would like to go through the entire matrix, and divide each of the y values by a certain number, depending on their x value.
For example, for x values from 600-700, I would like to divide the corresponding y value by 10. For x values from 700-800, I would like to divide the corresponding y value by 20.
My idea was a for loop that looped the entire matrix, and then nested "if" statements that said
if data[[n, 1]] < 700, data[[n, 2]] = data[[n, 2]]/10

if data[[n, 1]] >= 700 && data[[n, 1]] <800, data[[n, 2]] = data[[n, 2]]/20

However, I can't even figure out how to determine the number of rows in a matrix to ensure I loop the correct 2001 times (I want my code to work for any length).
Dimensions[data] doesn't help and Length[Dimensions[data]] doesn't do it either and neither does Length[Dimensions[Transpose[data]]].

A: Define your function that depends on $x$ as a Piecewise:
div[x_] :=
  Piecewise[{{1, x < 600}, {10, 700 > x >= 600}, {20,
     800 > x >= 700}, {1, x >= 800}}];

Now apply it to your matrix, leaving $x$ the same and dividing $y$ by $div(x)$
a = RandomReal[{0, 1000}, {2001, 2}];
{#1, #2/div[#1]} & @@@ a

Do not use loops, more on that in loop alternatives.

A: Take a matrix:
m = RandomReal[{-1, 1}, {50, 2}];

divlist is the list in which you set the amount you want each row to be divided by.
divlist = Range[50]^2 + 4;
Thread[m/divlist]

{{0.122485, 0.113589, 0.0614795, ..., -0.000421888, 0.000414203, -0.000404009,
    0.000252482},
{0.181547, -0.0939199, -0.00331032, ..., -0.0000740111, -0.000279882, -0.000368139}}

A: data = RandomInteger[{500., 800.}, {10, 2}]

{{583, 614}, {518, 744}, {731, 732}, {783, 593}, {693, 742}, {658,
    601}, {552, 741}, {741, 569}, {522, 524}, {705, 533}}

Table[If[600 <= data[[i, 1]] < 700, data[[i, 2]] = data[[i, 2]]/10,
   If[700 <= data[[i, 1]] < 800, data[[i, 2]] = data[[i, 2]]/20],
   data[[i, 2]] = data[[i, 2]]], {i, 1, Length@data}];

N@data

{{583., 614.}, {518., 744.}, {731., 1.83}, {783., 1.4825}, {693.,
    7.42}, {658., 6.01}, {552., 741.}, {741., 1.4225}, {522.,
    524.}, {705., 1.3325}}


text:
Q: How to set same (constant) hue value for every pixel's of an image by using ColorMatrix? I am trying to set a constant hue value for entire image with using ColorMatrix. My goal is to make entire image look with same color without loosing brightness of any area. I found a way to shift the hue values of an image by using ColorMatrix but i couldn't find any way to set same hue value for all pixels. I can do it with iterating every pixel of image but this approach is too slow. I am not sure if it is possible to do it with ColorMatrix and i am open to possible solutions other than ColorMatrix approach.
Input Image
Hue shifting output Image*
Desired output Image**
*This can be done with color matrix
** I can do this with iterating pixels but not with ColorMatrix
PS: I am trying to do this on Android but i believe the question is not directly related to the android since ColorMatrix approach is common on other platforms like Flash, C# etc.

A: not really familiar here, but i belive this link can help:
http://www.graficaobscura.com/matrix/index.html
it's c code, so you have to translate C -> ColorMatrix, but in the last paragraph there is the operation
Hue Rotation While Preserving Luminance

which seems what you are looking for.

A: I don't think there is a way to do exactly what you're asking for with a ColorMatrix. It sounds like what you want to do is transform from RGB to HSL color space, set H constant across all pixels, and transform back from HSL to RGB. These color space transformations aren't linear, and can't be represented with matrices. Because of the different way these spaces parameterize color, I also suspect some degradation could occur doing RGB->HSL->RGB.
I think the closest you would be able to achieve with the ColorMatrix is by using one to convert to greyscale, and another to weight the RGB values (tint them). This kind of thing is often used to do fake sepia tone photos, but it is not what you are asking for.

A: I have made a quick sample in Flash (this question is tagged as ActionScript), not sure if this is what you are looking for:
http://megaswf.com/serve/1047061
The code:
import com.greensock.*;
import com.greensock.easing.*;
import flash.events.MouseEvent;

colorButton.addEventListener(MouseEvent.CLICK, onColor);
resetButton.addEventListener(MouseEvent.CLICK, onReset);

function onColor(e:MouseEvent):void {
    TweenMax.to(mc, 1, {colorMatrixFilter:{colorize:0x0099ff, amount:1}});
}

function onReset(e:MouseEvent):void {
    TweenMax.to(mc, 1, {colorMatrixFilter:{colorize:0x0099ff, amount:0}});
}

A: here is a quick way to do it, if you want to set the hue to, let's say, h(0.5, 0.2, 0.3).
var matrix:Array = new Array();
matrix = matrix.concat([.5, .5, .5, 0, 0]);
matrix = matrix.concat([.2, .2, .2, 0, 0]);
matrix = matrix.concat([.3, .3, .3, 0, 0]);
matrix = matrix.concat([0, 0, 0, 1, 0]);
var filter:ColorMatrixFilter = new ColorMatrixFilter(matrix);

image.filters = [filter];

I'm not sure it will respect perfectly the luminance, but it may satisfy your need!

A: Check out QColorMatrix, which has a ColorMatrix routine called RotateHue. Source is in C++, but is portable to other languages (I've ported part of it to .NET in the past and it worked great).


text:
Q: Linq Where() not working bitwise operators I'm trying to build an asp.net api using Entity Framework MySql
(IQueryable).where(b=>(((fliter ^ b.BlogStatus) & mask) == 0));

error=System.InvalidOperationException: Unsupported Binary operator type specified.
But EOR(^) doesn't work
I couldn't find a solution for this so I decided not to use "EOR"
(IQueryable).where(b=>(((fliter  | b.BlogStatus) & ~(fliter  & b.BlogStatus)) & mask) == 0);
// x^y == (x|y) & ~(x&y)

error=MySql.Data.MySqlClient.MySqlException (0x80004005): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NOT (0 & 'b'.'BlogStatus')) & 7) = 0
But NOT(~) doesn't work
I couldn't find a solution for this so I decided not to use "NOT"
(IQueryable).where(b=>(((fliter | b.BlogStatus) & (2147483647-(fliter & b.BlogStatus))&mask)) == 0);
// ~x == 2147483647-x

Surprisingly it works but only locally.

*

*Could it be because mariaDb is on the server?

*How can I get this to work without doing nonsense?

*Why don't bitwise operators work?

(sorry for my bad english)


text:
Q: ANN problem: I am building an ANN model to predict the profit of a new startup based on certain features The image of the dataset
import numpy as np
from keras.models import Sequential
from keras.layers import Dense

Loading the data set using pandas as data frame format
import pandas as pd
df = pd.read_csv(r"E:\50_Startups.csv")
df.drop(['State'],axis = 1, inplace = True)

from sklearn.preprocessing import MinMaxScaler
mm = MinMaxScaler()
df.iloc[:,:] = mm.fit_transform(df.iloc[:,:])
info = df.describe()

x = df.iloc[:,:-1].values
y = df.iloc[:,-1].values

from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test = train_test_split( x,y, test_size=0.2, random_state=42)

Initializing the model
model = Sequential()
model.add(Dense(40,input_dim =3,activation="relu",kernel_initializer='he_normal'))
model.add(Dense(30,activation="relu"))
model.add(Dense(1))
model.compile(loss="mean_squared_error",optimizer="adam",metrics=["accuracy"])

fitting model on train data
model.fit(x=x_train,y=y_train,epochs=150, batch_size=32,verbose=1)

Evaluating the model on test data
eval_score_test = model.evaluate(x_test,y_test,verbose = 1)

I am getting zero accuracy.

A: The problem is that accuracy is a metric for discrete values (classification).
you should use:
r2 score
mape
smape
instead.
e.g:
model.compile(loss="mean_squared_error",optimizer="adam",metrics=["mean_absolute_percentage_error"])

A: Adding to the answer of @GuintherKovalski accuracy is not for regression but if you still want to use it then you can use it along with some threshold using following steps:

*

*Set a threshold such that if the absolute difference in the predicted value and the actual value is less than equal to the threshold then you consider that value as correct, otherwise false.

*Ex -> predicted values = [0.3, 0.7, 0.8, 0.2], original values = [0.2, 0.8, 0.5, 0.4].
Now abs diff -> [0.1, 0.1, 0.3, 0.2] and let's take a threshold of 0.2. So with this threshold the correct -> [1, 1, 0, 1] and your accuracy will be correct.sum()/len(correct) and that is 3/4 -> 0.75.

This could be implemented in TensorFlow like this
import numpy as np
import tensorflow as tf
from sklearn.datasets import make_regression

data = make_regression(10000)

model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(100,))])

def custom_metric(a, b):
    threshold = 1 # Choose accordingly
    abs_diff = tf.abs(b - a)
    correct = abs_diff >= threshold
    correct = tf.cast(correct, dtype=tf.float16)
    res = tf.math.reduce_mean(correct)
    return res

model.compile('adam', 'mae', metrics=[custom_metric])
model.fit(data[0], data[1], epochs=30, batch_size=32)

A: Just want to say Thank you to everyone who took their precious time to help me. I am posting this code as this worked for me. I hope it helps everyone who is stuck somewhere looking for answers. I got this code after consulting with my friend.
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import np_utils
import pandas as pd
from sklearn.model_selection import train_test_split

# Loading the data set using pandas as data frame format
startups = pd.read_csv(r"E:\0Assignments\DL_assign\50_Startups.csv")
startups = startups.drop("State", axis =1)

train, test = train_test_split(startups, test_size = 0.2)

x_train = train.iloc[:,0:3].values.astype("float32")
x_test = test.iloc[:,0:3].values.astype("float32")
y_train = train.Profit.values.astype("float32")
y_test = test.Profit.values.astype("float32")

def norm_func(i):
     x = ((i-i.min())/(i.max()-i.min()))
     return (x)

x_train = norm_func(x_train)
x_test = norm_func(x_test)
y_train = norm_func(y_train)
y_test = norm_func(y_test)

# one hot encoding outputs for both train and test data sets
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)

# Storing the number of classes into the variable num_of_classes
num_of_classes = y_test.shape[1]
x_train.shape
y_train.shape
x_test.shape
y_test.shape

# Creating a user defined function to return the model for which we are
# giving the input to train the ANN mode
def design_mlp():
    # Initializing the model
    model = Sequential()
    model.add(Dense(500,input_dim =3,activation="relu"))
    model.add(Dense(200,activation="tanh"))
    model.add(Dense(100,activation="tanh"))
    model.add(Dense(50,activation="tanh"))
    model.add(Dense(num_of_classes,activation="linear"))
    model.compile(loss="mean_squared_error",optimizer="adam",metrics =
    ["accuracy"])
    return model

# building a cnn model using train data set and validating on test data set
model = design_mlp()

# fitting model on train data
model.fit(x=x_train,y=y_train,batch_size=100,epochs=10)

# Evaluating the model on test data
eval_score_test = model.evaluate(x_test,y_test,verbose = 1)
print ("Accuracy: %.3f%%" %(eval_score_test[1]*100))

# accuracy score on train data
eval_score_train = model.evaluate(x_train,y_train,verbose=0)
print ("Accuracy: %.3f%%" %(eval_score_train[1]*100))


text:
Q: Cannot select from Google places autocomplete I am developing an ionic app to be run on Android. On a particular screen, I have a google maps and a search box. I have used the phone gap plugin for the google maps to get the native map instead of using Google Maps Javascript API as it is too slow.
The search box is autocomplete to get places from google using the following code -
input = document.getElementById 'search-input'
autocomplete = new google.maps.places.Autocomplete(input)

This turns the input field with autocomplete for places from google. The problem is that I am not able to select any of the options from the autocomplete dropdown.
My HTML code -
<ion-content scroll="false">

     <input id="search-input">

</ion-content>

The map-canvas holds the map. I tried adding ng-focus="disableTap()" to input search-input.
disableTap = ->
   container = document.getElementsByClassName 'pac-container'
   angular.element(container).attr 'data-tap-disabled', 'true'
   angular.element(container).on 'click', ->
        document.getElementById('search-input').blur()

I found this solutions at this link
But this does not work. Any inputs here? I'm at my wits end here.

A: The below worked for me.
From user @TillaTheHun0 :
.controller('MyCtrl', function($scope) {
  $scope.disableTap = function(){
    container = document.getElementsByClassName('pac-container');
    // disable ionic data tab
    angular.element(container).attr('data-tap-disabled', 'true');
    // leave input field if google-address-entry is selected
    angular.element(container).on("click", function(){
        document.getElementById('searchBar').blur();
    });
  };
})

A: Okay i found the solution, this will make you able to select on mobile
add this after creating your map

    $$('body').on('touchstart','.pac-container', function(e){
        e.stopImmediatePropagation();
    })

i will also post my full code in case you're confused :

    var myLatLng = {lat: 36.5802466, lng: 127.95776367};
    document.getElementById('qkp-lat').value = myLatLng.lat;
    document.getElementById('qkp-lng').value = myLatLng.lng;
    window.postmap = new google.maps.Map(document.getElementById('postmap'), {
        center: myLatLng,
        zoom: 6,
        mapTypeControl: false,
        streetViewControl: false,
        disableDefaultUI: true,
        mapTypeId: 'roadmap'
    });

    // GOOGLE MAP RESPONSIVENESS
    google.maps.event.addDomListener(window, "resize", function() {
     var center = postmap.getCenter();
     google.maps.event.trigger(postmap, "resize");
     postmap.setCenter(center);
    });

    //MARKER
    window.PostAdMarker = new google.maps.Marker({
      map: postmap,
      position:myLatLng,
      draggable: true,
      anchorPoint: new google.maps.Point(0, -29)
    });
    //LOAD FROM CURRENT CITY
    var geocoder = new google.maps.Geocoder();
    //AFTER DRAG AND DROP SHOWS THE LAT AND LONG
    google.maps.event.addListener(PostAdMarker, 'dragend', function (event) {
        var latlng = {lat: this.getPosition().lat(), lng: this.getPosition().lng()};
        geocoder.geocode({'location': latlng}, function(results, status) {
          if (status === 'OK') {
            if (results[1]) {
                // saving to dom
                document.getElementById('qkp-lat').value = latlng.lat;
                document.getElementById('qkp-lng').value = latlng.lng;
            } else {
              window.alert('No results found');
            }
          } else {
            window.alert('Geocoder failed due to: ' + status);
          }
        });
    });

    var getlocDiv = document.createElement('div');
    var getlocvar = new getloc(getlocDiv, postmap);
    getlocDiv.index = 1;
    postmap.controls[google.maps.ControlPosition.TOP_RIGHT].push(getlocDiv);

    // Create the search box and link it to the UI element.
    var input = document.getElementById('pac-input');
    var searchBox = new google.maps.places.SearchBox(input);
    postmap.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    // Bias the SearchBox results towards current map's viewport.
    postmap.addListener('bounds_changed', function() {
      searchBox.setBounds(postmap.getBounds());
    });

    var markers = [];
    // Listen for the event fired when the user selects a prediction and retrieve
    // more details for that place.
    searchBox.addListener('places_changed', function() {
      var places = searchBox.getPlaces();

      if (places.length == 0) {
        return;
      }

      // Clear out the old markers.
      markers.forEach(function(marker) {
        marker.setMap(null);
      });
      markers = [];

      // For each place, get the icon, name and location.
      var bounds = new google.maps.LatLngBounds();
      places.forEach(function(place) {
        if (!place.geometry) {
          console.log("Returned place contains no geometry");
          return;
        }
        var icon = {
          url: place.icon,
          size: new google.maps.Size(71, 71),
          origin: new google.maps.Point(0, 0),
          anchor: new google.maps.Point(17, 34),
          scaledSize: new google.maps.Size(25, 25)
        };

        // Create a marker for each place.
        markers.push(new google.maps.Marker({
          map: postmap,
          icon: icon,
          title: place.name,
          position: place.geometry.location
        }));

        if (place.geometry.viewport) {
          // Only geocodes have viewport.
          bounds.union(place.geometry.viewport);
        } else {
          bounds.extend(place.geometry.location);
        }
      });
      postmap.fitBounds(bounds);
    });
    $$('body').on('touchstart','.pac-container', function(e){
        e.stopImmediatePropagation();
    })


text:
Q: if code in python 3.3.3 (count odd, positive values !!?) my code is about :count how many values are even , positive , negative
and it's not working :
thanks for your help
e = [ ]

for c in range(5):

    c=float(input())
    if c<0:
        e.append(c)
        print("{} valor(es) negativo(s)".format(len(e)))
    if c>0:
        e.append(c)
        print("{} valor(es) positivo(s)".format(len(e)))
    if c%2!=0:
        e.append(c)
        print("{} valor(es) par(es)".format(len(e)))
    if c%2==0:
        e.append(c)
        print("{} valor(es) impar(es)".format(len(e)))

i want the o/p like this :
3 valor(es) par(es)
2 valor(es) impar(es)
1 valor(es) positivo(s)
3 valor(es) negativo(s)
when i enter the five ( int )nos
and exit when input==4

A: First you are using the same list for all value types. Count will be correct only the first time! see below for odd & even numbers. Same error above for positive / negative.
Second this is functionnaly wrong:
if c%2!=0:
    e.append(c)
    print("{} valor(es) par(es)".format(len(e)))
if c%2==0:
    e.append(c)
    print("{} valor(es) impar(es)".format(len(e)))

Define:
pares = []
impares = []

in your loop, write this
if c%2==0:
    pares.append(c)
    print("{} valor(es) par(es)".format(len(pares)))
else:
    impares.append(c)
    print("{} valor(es) impar(es)".format(len(impares)))

proof of concept and trying to be as pythonic as possible
(I have made the example non-interactive, and using only integers. Like ShadowRanger noted, modulo on floats won't work very well with this code)
# define 4 lists
the_list = [list() for i in range(4)]
negative_values,positive_values,odd_values,even_values = the_list

z=[1,2,-5,-7,0,3,-4]
for c in z: #range(5):

    #c=float(input())
    if c<0:
        negative_values.append(c)
    elif c>0:
        positive_values.append(c)
    if c%2==0:
        even_values.append(c)
    else:
        odd_values.append(c)

print("{} negative values, {} positive values, {} odd values, {} even values".format(*tuple(len(x) for x in the_list)))


text:
Q: Окно называется не так Код:
from tkinter import *

class newWorld():
    windowName="freesby"

    worldEditor = Tk()

    worldEditor.title(windowName)
    worldEditor.mainloop()

world=newWorld()
world.windowName="opus"

Резельтат:
Окно называется "freesby", хотя по-моему оно должно называться "opus".
Подскажите, что делать!

A: У вас приложение начинается раньше чем оно прочитает world.windowName.
1 вариант
from tkinter import *

class NewWorld:
    def __init__(self, title, **kwargs):
        super().__init__(**kwargs)
        window_name = "freesby"
        world_editor = Tk()
        world_editor.title(title)
        print(window_name)
        world_editor.mainloop()

world = NewWorld("opus")

2 вариант (но как по мне не очень его использовать)
from tkinter import *

class NewWorld:
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.window_name = "freesby"

        self.world_editor = Tk()

        self.world_editor.title(self.window_name)

world = NewWorld()
world.world_editor.title('opus')
world.world_editor.mainloop()


text:
Q: sort date field with tablesorter I'm using the JQuery tablesorter plugin. The table has a column that shows dates in the format 05 Mar 2012. The tablesorter plugin seems to treat this column as text, because it sorts it in the order

*

*05 Mar 2012

*06 Jan 2012

*07 Dec 2012

How can I sort these dates in chronological order instead?

A: Parse the date string to a Date, then convert it to milliseconds. Let tablesorter sort the column as numeric.
$.tablesorter.addParser({
    id: 'my_date_column',
    is: function(s) {
        // return false so this parser is not auto detected
        return false;
    },
    format: function(s) {
        var timeInMillis = new Date.parse(s);
        return timeInMillis;
    },
    // set type, either numeric or text
    type: 'numeric'
});

$(function() {
    $("table").tablesorter({
        headers: {
            6: {       // Change this to your column position
                sorter:'my_date_column'
            }
        }
    });
});

If you have trouble with Date.parse, see my answer to this question.

A: You can also add a hidden span tag before your date in numerical format (yyyymmdd). This text will come first and be used for sorting but it will be hidden from sight and only show the format you want.
    2013092323rd September 2013

A: You will need to use addParser method and create a parser that converts your string to date object.
follow example on plugin site
http://tablesorter.com/docs/example-parsers.html
If need a date parser:
http://www.datejs.com/
EDIT:  your dates convert easily in format shown:
 console.log(new Date('05 Mar 2012'))//  logs proper date object

A: Haven't used tablesorter in a while but I seem to remember having a similar issue with UK dates.
You can add a dateformat parameter to the tablesorter plugin with your custom dateformat.
dateFormat: 'dd MMM yyyy'


text:
Q: 'Input' does not contain a definition for 'GetMouseButton' how is this possible? I've wanted to try developing for touch screen but for some reason it said:

'Input' does not contain a definition for 'touched'

Then I tried with the old fashioned way, which worked for me a million times, but now doesn't.

'Input' does not contain a definition for 'GetMouseButton'

Does someone know the source of my problem?
    void Update() {
        if(Input.GetMouseButton(0))
            Debug.Log("Pressed left click.");

        if(Input.GetMouseButton(1))
            Debug.Log("Pressed right click.");

        if(Input.GetMouseButton(2))
            Debug.Log("Pressed middle click.");

    }

A: Oh my god, I am so stupid.
I've already reinstalled Unity, VS and everything maybe twice.
And I didn't see what caused the problem...
The problem was that I named my script 'Input'
Oh my GOOOOD


text:
Q: How to flatten a json structure in HIVE? I have a JSON structure that looks like this.
There is a structure nested in a column.
HEADER:
{"user":{"location":"USA","id":1514008171,"name":"Auzzie Jet","screenname":"metalheadgrunge","geoenabled":false},"tweetmessage":"Anthrax - Black - Sunglasses hell","createddate":"2013-06-20T12:08:44","identifier":"1234","geolocation":null}

When I query this, this works:
SELECT *
FROM TBL a
WHERE header.identifier = '1234'

But then, when I want to find the location from the nested json structure. It does not work:
SELECT *
FROM TBL a
WHERE header.identifier = '1234'
and a.header.user.location LIKE '%USA%'

Does anyone know how to query this in HIVE?

A: For flattening json structure you need to first create lateral view using json_tuple that's how you can be able to achieve what you intend to.
Please find the complete solution how to do it.
Step 1: Create external table tweets with single column tweet with data type of string.
CREATE EXTERNAL table tweets (tweet string);
Now put the json string
{"user":{"location":"USA","id":1514008171,"name":"Auzzie Jet","screenname":"metalheadgrunge","geoenabled":false},"tweetmessage":"Anthrax - Black - Sunglasses hell","createddate":"2013-06-20T12:08:44","identifier":"1234","geolocation":null}
Step 2: In text file named tweets.txt and run the below command to load the data from text file into hive table.
LOAD data local inpath 'tweets.txt' into table tweets;
Once done, now we are ready to play on our Json string.
So basically here what we are trying to achieve is querying on identifier and location fields which are basically at different levels.
user
    location    :   USA
    id          :   1514008171
    name        :   Auzzie Jet
    screenname  :   metalheadgrunge
    geoenabled  :   false
tweetmessage    :   Anthrax - Black - Sunglasses hell
createddate :   2013-06-20T12:08:44
identifier  :   1234
geolocation :   null

Level 1 fields are  => user, tweetmessage, createddate,identifier, geolocation
Level 2 Fields are  => location, id, name, screenname, geoenabled
So firstly we need to create lateral View on Level 1 so that we can query on Level 1 fields. In our example we need to query on identifier. Also to query on Level 2 fields we need to explode our User view which would be possible by lateral view.
LATERAL VIEW json_tuple(t.tweet, 'user', 'identifier' ) t1 as `user`, `identifier`

and then to query on location, we need to create another lateral view for level 2 fields.
LATERAL VIEW json_tuple(t1.`user`,'name', 'location') t2 as `name`, `location`

and that's it finally we can use select on tweets with lateral views.
Step 3 and Final Query:
SELECT t.* FROM tweets t LATERAL VIEW json_tuple(t.tweet, 'user', 'identifier' ) t1 as `user`, `identifier` LATERAL VIEW json_tuple(t1.`user`,'name', 'location') t2 as `name`, `location` where t1.`identifier`=1234 and `location` ="USA";
For more read on lateral view :LateralView
and on Json_Tuple : JsonTuple


text:
Q: What is $\varphi(0)$? $\varphi$ is Euler's totient function. My question is:

*

*When/if $\varphi$ is defined at $0$, what is it usually defined as?

*Is there a "most natural" or more commonly accepted definition of $\varphi(0)$?
This is a soft question, because it's of course a matter of convention.

Here are three possible definitions, with some justification.
Definition 1: $\boldsymbol{\varphi(0) = 2}$. Note that for $n \ge 1$,
$\varphi(n) = \left| \left( \mathbb{Z} / n \mathbb{Z} \right)^* \right|$, the number of units mod $n$.
Plugging in $n = 0$, we get
$$
\varphi(0)
= \left| \left( \mathbb{Z} / 0 \mathbb{Z} \right)^* \right|
= \left| \left( \mathbb{Z} \right)^* \right|
= \left| \{-1, 1\} \right|
= 2.
$$
Definition 2: $\boldsymbol{\varphi(0) = 0}$.
If $a \mid b$, then $\varphi(a) \mid \varphi(b)$.
To preserve this property for $b = 0$, we need that $\varphi(a) \mid \varphi(0)$ for all $a$, implying $\varphi(0) = 0$.
WolframAlpha returns $\varphi(0) = 0$.
However, the Wolfram Math World page explains:

By convention, $\phi(0)=1$, although the Wolfram Language defines EulerPhi[0] equal to 0 for consistency with its FactorInteger[0] command.

which gives us
Definition 3: $\boldsymbol{\varphi(0) = 1}$.
Does anyone know the reason for this convention?

More observations

*

*Any choice of $\varphi(0)$ is consistent with the multiplicativity of $\varphi$.

*$\varphi(mn) = \varphi(m) \varphi(n) \frac{d}{\varphi(d)}$, where $d = \gcd(m,n)$, implies $\varphi(0) = 0$. This supports definition 2.

*If $\varphi(n) = \sum_{ab = n} a \mu(b)$, then note that when $ab = 0$, $a = 0$ or $b = 0$, and since $\mu(0) = 0$, $a \mu(b) = 0$. So this is $\sum 0 = 0$, again agreeing with definition 2.

A:
$\varphi(n)$ is the number of positive integers not larger than $n$ that are coprime to $n$.

There are no positive integers not larger than $0$, so by definition, if we were to define $\varphi(0)$, we would want it to equal $0$. This agrees with $$\varphi(n)=n\prod_{\text{prime} \ p\lvert n} \left(1-\frac{1}{p} \right), $$ where the product runs over all the primes, when $n=0$. We may indeed note that we cannot deduce from this the infinitude of the primes, since in any finite case the product is smaller than $1$, and is thus nullified by $n=0$.


text:
Q: CSS - position: absolute not working to place div above all other elements I am using Javascript (more specifically the VueJS framework) to build a page called mainTextEditor which has a text field and a 'popup' made using a div with a v-if which shows the div when the condition met is true.
It may be important to note that this is a component within another component like so (Inserted using main-text-editor):
<template>
    <v-card flat>

            <v-card-title class="form-title pl-0 pr-1">{{ itemHere.name }}</v-card-title>

        <v-card-actions>

               // HERE IS WHERE THE COMPONENT IS INSERTED

        </v-card-actions>
    </v-card>
</template>

This is the code used to generate the mainTextEditor text field and popup above:
<template>

        <v-card flat>
            <v-text-field :editor="editor"/>
        </v-card>

            <v-list class="pt-0 pb-0" dense v-for="item in filteredItems" :key="item.id" >
                <v-list-item class="d-flex">
                    <v-list-item-title>
                        {{ item.name }}{{ item.structure }}
                    </v-list-item-title>
                </v-list-item>
            </v-list>

</template>

editorContentIsUsingFormulas is true when the text field is clicked
CSS styles used above:
.formula-options {
    z-index: 2 !important;
    background-color: white;
    width: 30vw;
    max-height: 40vh;
    overflow-y: scroll;
    position: absolute !important;
    border-radius: 20px;
    border: 2px solid grey;
    margin-left: 3px;
}

.temp-build-ellipse {
    max-height: 39.98px;
    overflow: hidden;
    text-overflow: ellipsis;
}

.temp-build-overflow {
    height: 39.98px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space:nowrap
}

The issue is that although the div has been styled to show position: absolute, if the text field in question is at the bottom of the page then it creates whitespace that goes beyond the full 100vh of the entire page.
Here is what it looks like in the middle of the page:

Here is what it looks like at the bottom (Please note that the purple represents the full page):

Here is what a text field looks like at the side of the page (note that the white part on the right hand side is the end of the page and I can no longer see the right hand side of the div):

I am assuming that because the div is towards the bottom of the  tag, it is positioned at the bottom of the text field. However, I am under the impression that position: absolute should fix it, though this doesn't seem to be the case. What might I be doing wrong?

A: Hmm.. interesting. Can you just try min-height: 100vh? Sorry If I misunderstand the question.


text:
Q: Pages, custom Bullet points I am creating a specification for a project within pages on Mac.
For my functional requirements I want to have bullet points for each requirement.
I currently have

*

*this is a requirement
1.1 this is an extension

*etc etc

*blah blah
3.1 ....

But would like to also have numbered non-functional requirements so would prefer this.
F1. this is a requirement
F2. etc etc
F3. blah blah

NF1. this is a requirement
NF2. etc etc
NF3. blah blah
Does anyone know is this is possile with pages ?


text:
Q: Continuously differentiable functions dense in $L^2[a,b]$ I read in Kolmgorov-Fomin's Элементы теории функций и функционального анализа (p. 408 here) that the set of continuously differentiable functions are dense everywhere in space $L^1[a,b]$ of Lebesgue integrable functions on $[a,b]$ endowed with distance $d(f,g)=\int_{[a,b]}|f-g|d\mu$.
I know that the set of continuous functions is dense everywhere in $L^1[a,b]$, but how to prove that the set of continuously differentiable functions is dense everywhere too? I thank you all very much!!!

A: It is a direct consequence of Stone-Weierstrass' theorem. Let $f\in L_1[a,b]$, and $\epsilon>0$. You know that there is some $g\in C[a,b]$ such that $\int_a^b|f-g|d\mu<\epsilon/2$. Now, let $p$ a polynomial such that $\|p-g\|_\infty<\epsilon/[2(b-a)]$.
Then
$$\int_a^b|f-p|d\mu\le\int_a^b|f-g|d\mu+\int_a^b|g-p|d\mu<\epsilon$$


text:
Q: What does angle bracket mean? I am reading this Covariance notes and it has the following explanation:
$$cov(X, Y) = \langle(X-\mu_X)(Y-\mu_Y)\rangle$$
$$=\langle X Y\rangle - \mu_X\mu_Y$$
where $\mu_X = \langle X \rangle, \mu_Y = \langle Y \rangle$ are the respective means, which can be written as:
$$cov(X, Y) = \sum\limits_{i=1}^N\frac{(x_i-\bar{x})(y_i-\bar{y})}{N}$$
As a result
$$\langle XY \rangle - \langle X \rangle\langle Y \rangle = \sum\limits_{i=1}^N\frac{(x_i-\bar{x})(y_i-\bar{y})}{N}$$
What is $\langle X \rangle$?


text:
Q: how to divide a list to two lists and get all possible combinations I have a list:
list1 = [1,2,3]

and I want to dived it to two list such that:
list2 = [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
list3 = [[1,2,3], [2,3], [1, 3], [1, 2] ,[3], [2], [1], []]

I tried different loops but didn't get all combinations and I thought maybe there is an elegant way instead.

A: Perhaps using itertools.
import itertools

list2 = []
for i in range(4):
    for j in itertools.combinations([1,2,3], r=i):
        list2.append( list(j) )

the output
[[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]


text:
Q: Leetcode 78: Subsets confused why duplicate subsets are generated I'm working on Leetcode 78: subsets and I've copied over the question below.
Given an integer array nums of unique elements, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
I have a solution that generates some of the subsets, but not all of them. It also includes duplicate subsets.
def subsets(self, nums: List[int]) -> List[List[int]]:
        subsets = []
        expected_subsets = 2**len(nums)
        def generate_subset(subset, nums):
            # base case , gone too far
            if len(subsets) >= expected_subsets:
                return
            if len(subsets) < expected_subsets:
                subsets.append(subset)
            for i in range(len(nums)):
                # choose the current element
                generate_subset(subset+[nums[i]], nums[i+1:])
                # don't choose the current element
                generate_subset(subset, nums[i+1:])
        generate_subset([], nums)
        return subsets

My thinking is that for generating subsets, at each choice (number from nums) we have two options. We can either choose the current number (nums[i]) and generate the subset from the rest of the array, or we can skip the current number (nums[i]) and generate the subset from the rest of the array. But for the input nums = [1,2,3], my code generates [[],[1],[1,2],[1,2,3],[1,2],[1],[1,3],[1]] where the expected output is [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]. So I have some duplicate subsets. I'm unsure why [2] and [3] are not being generated. For reference, I have solved Leetcode 46: Permutations previously and I probably had my solution for that in mind (copied below) when I was solving subsets.
def permute(self, nums: List[int]) -> List[List[int]]:
        results = []
        n = len(nums)
        def dfs(permutation, nums):
            if len(permutation) == n:
                results.append(copy.deepcopy(permutation))
                return
            for i in range(len(nums)):
                permutation.append(nums[i])
                dfs(permutation, nums[:i] + nums[i+1:])
                # backtracking
                permutation.pop()
        dfs([], nums)
        return results

Can anyone explain why by subset code generates duplicate subsets? The issue of duplicate subsets is related to why I'm not generating the complete list of subsets.

A: No need to have the second recursive call, the working solution is:
def subsets(nums: List[int]) -> List[List[int]]:
    subsets = []
    expected_subsets = 2 ** len(nums)

    def generate_subset(subset, nums):
        # base case , gone too far
        if len(subsets) >= expected_subsets:
            return
        if len(subsets) < expected_subsets:
            subsets.append(subset)
        for i in range(len(nums)):
            generate_subset(subset + [nums[i]], nums[i+1:])

    generate_subset([], nums)
    return subsets

print(subsets([1, 2, 3]))

# [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]

Try to manually go through recursion calls and you understand why the previous version didn't work, took me a while. On that recursive call, you get current and recursively process the rest.

This is an example of explicit pick/don't pick approach:
def subsets(nums: List[int]) -> List[List[int]]:
    result = []

    def powerset(alist, index, curr):
        if index == len(alist):
            result.append(curr)
            return

        powerset(alist, index + 1, curr + [alist[index]])
        powerset(alist, index + 1, curr)

    powerset(nums, 0, [])
    return result

A: Similar but alternative solution.
def subsets(nums):
    power_set = []
    subset = []
    nums_len = len(nums)

    def find_subsets(start):
        power_set.append(subset.copy())

        for i in range(start, nums_len):
            subset.append(nums[i])
            find_subsets(i + 1)
            subset.pop()

    find_subsets(0)
    return power_set


text:
Q: Single Chinese character determined as length 2 in Java/Scala String I'm trying to split out all the Chinese characters from a String, but I bumped into a strange situation for the character
scala> ""
res1: String =

scala> res1.length
res2: Int = 2

scala> res1.getBytes
res3: Array[Byte] = Array(-16, -91, -111, -82)

scala> res1(0)
res4: Char = ?

scala> res1(1)
res5: Char = ?

It's a single character, but Java/Scala determine it as two unknown characters. And usually I see Chinese character taking three bytes in UTF-8, but this character takes four.
Hence, I can't split a String and find this single character. Even worse, when using myString.replaceAll("[^\\p{script=Han}]", "") to kick out all the non-Chinese characters, the second part of  is replaced and it becomes an invalid String.
Is there any solution to this? I'm using openjdk-8-jdk on Ubuntu.

A: For length you should use
string.codePointCount(0, string.length());

For replacement it is best to avoid regex, which is char-based. You could write a loop relying on String#offsetByCodePoints() and manually remove characters based on String.codePointAt() and Character.isIdeographic().

A: You have encountered a Surrogate Pair. That character is U+2546E, which as you see, is a lot bigger than 2^16. It is represented in a Java or Scala String as the sequence 0xD855 0xDC6E.
If you want a regex library that handles this sort of thing transparently, I happen to know where to find one: TCL regex ported to Java. If you don't want to go there, you need to use the Code Point methods of String and Character in java to navigate.

A: The Java standard library unicode support predates the current standard and as such the support for astral (non-BMP) characters is... limited; several APIs will treat them as the individual surrogate pairs as you saw. If you are doing extensive string manipulation it might be best to use ICU4J, which I understand offers regexes with full unicode support.

A: Based on @Marko's answer, here's an example to split a String:
scala> val x = "硓abc"
x: String = 硓abc

scala> (0 to x.codePointCount(0, x.length)).map(c => x.offsetByCodePoints(0, c)).sliding(2).map(w => x.substring(w.head, w.last)).toList
res1: List[String] = List(硓, , a, b, c)

And to determine if each character is a CJKV:
scala> (0 until x.codePointCount(0, x.length)).map(c => x.offsetByCodePoints(0, c)).map(i => Character.isIdeographic(x.codePointAt(i))).toList
res2: List[Boolean] = List(true, true, false, false, false)

A: Probable that this character is invalid or unsupported in UTF-8 but supported in UTF-16, resulting in some incompatibilities between JVM and Scala shell. Is your system big- or little-endian? Also you could try getting the character's Unicode Code Point and check if it is UTF-8 or UTF-16. Also, Chinese has compounded letters, like Japanese Kanji and Furigana, so that may also be a part of your problem.

A: i think you want to replace/split the string.That you can do without knowing the length of the string.Because java takes sequence of string also to replace a particular char or sequence of char in a string. For example :-`public class Test {
public static void main(String[] args) {

    String s="";
    System.out.println(s.replace("", "k"));

}
}

`
And if you want to split the String then go for stringtokenizer.For example :-
StringTokenizer st= new StringTokenizer("your sentence or String","the problematic char/string");


text:
Q: C# Process.start opening multiple PDFs unexpectedly I have a program that scans in document bar codes and then allows for the user to click on a link which will open up a PDF associated with that bar code.  My program works fine however I am running into a bug(?) in my code where every so often instead of opening the PDF once, the system will open it multiple times (5+) and it doesn't seem to be consistent.  I'm hesitant to rewrite the code completely since it is actually working, it is simply inconvenient to have to close multiple windows.  The method that I believe is causing the problem is below.  Any help would be greatly appreciated as I am not sure where to start.
private void dgDisplay_CellContentClick(object sender,   DataGridViewCellEventArgs e)
    {
        id = (int)comboBox1.SelectedValue;
        string ImagePath = getImagePath(id);
        string filename = "";

        if (e.ColumnIndex == 1)
        {
            filename = dgDisplay[e.ColumnIndex, e.RowIndex].Value.ToString();
            filename = @ImagePath + filename + ".tif";
            if (File.Exists(filename))
            {
                Process.Start(filename);
            }
            else
            {
                MessageBox.Show(filename);
            }
        }
    }


text:
Q: In what format is it best to return an error in REST What format should I return the response to the API user if an error occurred? Just return the response as a status code and error message:
Full authentication is required to access this resource

(the status 401 was returned)
Or it is better to return it in this format:
 {
    "timestamp": "2020-06-14T21:20:52.941+0000",
    "status": 401,
    "error": "Unauthorized",
    "message": "Full authentication is required to access this resource",
    "path": "/api/users/me"
}

A: Well, it depends:
If you know your front end urgently requires the direct message of the error, ignoring anything else, then going for the short and direct to the point answer might be your best choice.
But honestly, if experience in programming has taught me anything, is that the more information you have about something, the better, ESPECIALLY IF IT'S an ERROR!!! With the longer response, you have many more tools in you hand, both for giving the final user a better look of your application - You can present for the user a small title, a detailed message and, for example, use an internal code to show a red "error" box if a fatal error ocurred or a "warning" yellow box if a validation simply failed - and especially for the dev to solve that problem (The final user might never see the "timestamp", "status", "path" or stacktrace of the error - He shouldn't... - But it will surely help you track what caused the error).
Take a look at these (1, 2 and 3) articles to help you decide your situation and, if needed, customize your error response structure


text:
Q: Accessing IAuthSession in non-controller classes in ServiceStack/MVC4 I am new to ServiceStack, so this is probably a noob question:
I am working on an ASP.NET MVC4 application that uses ServiceStack and am trying to figure out how I could get a hold of the current IAuthSession from within a class (either a EF context or a PetaPoco Database) used by my MVC4 controllers derived from ServiceStackController.
The class in question is registered with Funq with the ReuseScope.Request scope (i.e. on the per-HTTP request basis), and ideally I'd like every instance of it to be autowired with the current IAuthSession using either a constructor parameter or a public property.
How do I do that?

UPDATE
After some digging I came up with what I think might work.
In my AppHost.Configure I register a lambda that returns a session from the current request:
container.Register<IAuthSession>(c =>
    HttpContext.Current.Request.ToRequest().GetSession());

Also:
container.RegisterAutoWired<EFCatalogDb>();

where EFCatalogDb is my EF context that takes IAuthSession as a constructor argument:
public class EFCatalogDb : DbContext
{
    public EFCatalogDb(IAuthSession session) : base()
    { }
    // ...etc....
}

Unfortunately I am not at the point in my development when I can test this workaround, so have to ask others if it makes sense at all.

A: My first suggestion would be to try to keep IAuthSession out of your database classes since that creates a dependency on ServiceStack that seems unnecessary.
That being said, I think you could go the route of registering IAuthSession and having the container automatically inject IAuthSession. A better way might be creating your own 'wrapper class' around IAuthSession and injecting that into your database classes. That would then break the dependency on ServiceStack.
If you have no issue keeping a dependency on ServiceStack another possibility would be using the SessionFeature class and doing something like
var key = SessionFeature.GetSessionKey();
authSession = AppHost.Resolve<ICacheClient>().Get<IAuthSession>(key);


text:
Q: Joomla call specific function from component to module I just want to call a specific function in a component. From the RokGallery Component in com_rokgallery\lib\RokGallery\Model.file.php is a &createNew function that i need in a module. Did anyone know how I can call these from my module and gave them spec variables?
In components\com_rokgallery\lib\RokGallery\Job\Processor\import.php on Line 31 is something other that I think I need for these...
I hope someone can help me ....
Regards, Marvin.

A: In theory you can require the file and use the Class.
To do that you have to import the rokgallery library.
$include_file = realpath(JPATH_ROOT . DS . 'components'. DS . 'com_rokgallery' . DS . 'include.php');

$included_files = get_included_files();
if (!in_array($include_file, $included_files) && ($libret = require_once($include_file)) !== 'JOOMLA_ROKGALLERY_LIB_INCLUDED') {
    JError::raiseWarning(100, 'RokGallery: ' . implode('<br /> - ', $loaderrors));
    return;
}

Once that you can use the static method createNew
$file = RokGallery_Model_File::createNew($filename, $filepath);


text:
Q: How many keys must a B-Tree Node have? I am trying to implement a B-tree and I've read this article:
https://www.geeksforgeeks.org/introduction-of-b-tree-2/
These are two points that they wrote:

*

*Every node except the root must contain at least t-1 keys. The root may contain a minimum of 1 key.

*All nodes (including root) may contain at most (2*t – 1) keys.

t is normally a value that depends upon disk block size.
Then they gave an example with an arbitrary values t of 5 and drew this:

What I don't understand is, they said that every node, except the root must contain at least t-1 keys. In this example, t is 5, but none of the nodes have at least (t-1)=4* keys.


text:
Q: TypeError: Cannot read property 'defaultView' of undefined - Angular I am having a runtime error where it gives me the stack trace of defaultView in my angular app, and it prevents me from moving on in my project.

The error: ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'defaultView' of undefined
TypeError: Cannot read property 'defaultView' of undefined
I have googled this, but none of the questions have angular in them. So I think this is the first one about defaultView with angular.
I have some code that takes an address and outputs a marker on to the map. I got the error from https://developers.google.com/maps/documentation/javascript/geocoding

Code in Stackblitz: https://stackblitz.com/edit/angular-gib2mq.
index.d.ts in the root folder makes the import statement work: import { } from 'googlemaps';
declare module "googlemaps";

I also have @types/googlemaps installed through npm install --save @types/googlemaps

I want to the error to go away, but it happens every time I run my app.
Thanks!

A: Looks like you have a pretty big misunderstanding of how to use the @agm package. That's okay! Some notes:

*

*you don't need this.map or the latlng types. You just pass numbers the to components

*call triggerResize(true) on the map when you need to recenter

*you don't need to explicitly import the libraries in the config...not sure why that is actually. Just make sure the API key you are using has them enabled

*finally, you need to give the map a static height, or its parent needs one (css reasons that I won't get into). You can always set the height with typescript.

Working stackblitz (minus the API key): https://stackblitz.com/edit/angular-yebacm
Good luck!
edit: you also don't need declare module "googlemaps";


text:
Q: Generate transaction ID for POS I don't exactly know how to describe this so I am having trouble googling the answer or finding it on this forum.
Basically I am working on a point of sale system. I have written a few of these but they have never been a server and multiple client design.
I was wondering how do POS systems generate the transaction ID's when there are simultaneous transactions and what happens to a cancelled transaction ID?

A: Instead taxing the database for this ID generation, you might do this using a GUID.  Also, this allows for the possibility of your terminals functioning independently with cached data even when the network connection is severed (was a requirement for one of my projects).

A: I've done POS stuff.
When you need the newest inserted row's primary key to use as transaction ID, return the @@identity value to use on the client side.
Cancelled transactions can either be rolled back if you've been doing all the work within a TRANSACTION block in SQL or a .NET transaction, but the easiest way that causes the least problems is really just having an isCancelled boolean field that gets set to true when the transaction is cancelled.


text:
Q: Trouble deciding on how to build a LiDAR system for 2D and/or 3D mapping OVERVIEW OF MY LIDAR PROJECT
Three of us are attempting to build a 2D LiDAR (Light Detection and Ranging) system to scan an indoor area or tunnel system. The data will be used to reconstruct a 2D image. If 2D is accomplished within our timeline we will proceed in designing a 3D system. Our end goal is to integrate it into an obstacle avoidance system but our timeline is too short to accomplish this so our focus will be on developing 2D/3D mapping system.
QUESTIONS THAT ARE OF A CONCERN TO ME
1.)
Which strategy in using the laser will be better in generating data to produce a reconstructed image "map". Such as....
Do I invert the laser beam to where it's a line that reflects off objects/corners then process the data through an edge-detection algorithm to reconstruct a map? Example .
Do I just use the single beam to scan multiple points using "time of flight" strategy to calculate distance to create a point cloud map. Example
2.)
3D LiDAR scanners are extremely expensive and the project requirements state 70% of the project needs to be built. In other words I cannot just go out and buy a scanning device.
So whatever strategy I use I have to be able to make multiple scans taking in a extremely large amount of data points. This would mean I would have to use a MCU that could extract and calculate all those individual scans and I just don't see that happening with a Arduino or even a FPGA. From previous sensor projects i've done i've always experienced delay even using XBEE's to transmit the data to my computer to be processed.
3.)
What MCU will be powerful enough to capture this data (RaspberryPi,BeagleBoard,Arduino,FPGA). Will I need to share the load and transmit the data to my computer for image reconstruction. If so what type of transmitter/receiver will do this without a huge delay.
4.)
2D and 3D reconstruction requires some heavy duty algorithms. Therefore, having a prebuilt library or software that has this built in would significantly save time.
RESOURCES THAT I HAVE CONSIDERED USING
Matlab seems to be used in reconstructing and mapping images through using edge-detection algorithms. There are several toolboxes Matlab sells that deal with image processing. However, I don't believe I could use Arduino,RaspberryPi,BeagleBoard,etc with Matlab unless I transmitted the data to my computer for processing inside Matlab.
OpenCV located HERE is a open source C++ library that is for "Computer Vision". It has a library full of functions for image processing. It is compadiable on Window,Linux,Unix systems also. However, I don't think I could use it with a LiDAR system. OpenCv is used for Stereo Vision. For more information take a look HERE. At the bottom of the link there are some great tutorials explaining how to use two webcams to acquire 2D and even 3D reconstructed images like HERE for example.
OTHER METHODS I HAVE RESEARCHED FOR MY PROJECT
The overall scope of this project is to reconstruct a 2D "3D if time allows" reconstructed image "map" of the entire scan from start to finish. Even though the end goal would be to incorporate this into an obstacle avoidance system I have to consider a method that meets the requirements I mentioned earlier. Other methods I've considered are as follows.....
Sonar (Example)
Stereo Vision (Example)
3D Laser Mapping processing data into a "Point Cloud" (Example)
I'm not for sure what this video is demonstrating as in whether its using LiDAR or Sonar. But it's using SLAM "Simultaneous Localization and Mapping" alogrithms to generate a 3D map. This seems to be theclosest idea we are trying to simulate.(demo).
ADVICE & GUIDANCE
As you seen the sonar method looks very nice and would match the end goal of our project. However, Stereo Vision would allow me to use OpenCV which is free and open source on a platform like the RaspberryPi or BeagleBoard. I could technically use Matlab also with Stereo Vision. However, LiDAR seems very promising and something that would require more hardware design which would meet the requirements more.
Any guidance/information anyone has for me on where I could find more information or just advice on what direction I should take would be extremely helpful and appreciated. Our current funding for our project is at $3000. We are going to the approval board here in 2 weeks and everyone in the group is having a hard time deciding on what direction would be more approachable. Therefore, hearing some other input would be very useful at this point.

A: Start with the core feature, which is the laser and getting a useful result from it's output and some form of feedback. Usually an Avalance PIN diode. Have some design aspects such as required range, like 1-10 metres, or 3-30 metres etc. This will fundamentally affect the circuit design. The closer range and better result you need means your circuits will quickly reach RF signal frequencies for operating the laser. I have personally looked into this myself for mobile robotics projects of mine, and I will be going down the path of continuous wave phase shift (or frequency modulated ) style .
There are pros and cons to each method of laser operation, such as pulsed Time of Flight needs very fast clock speeds and has an annoying minimum range issue. The continuous wave method is far easier and rather than minimum range issues has long range overlap issues, which could be dealt with by building a layered laser system for different range resolutions.
There is a few research papers and other literature I have found during my research, and a good starting one on comparison of techniques is Nejad & Olyaee. 2006. Comparison of TOF, FMCW and Phase-Shift Laser Range-Finding Methods by Simulation and Measurement
The reason why I suggest phase shift modulation fused with some other logic/error checking mechanism is because the circuitry behind it is the simplest - a single clock generator and a PLL (or even an easily available RF modulator) to drive a laser, and then receive data through the PIN diode. This is then passed through an RF amplifier, and you can immediately use a clock divider to scale the received laser pulses down to a reasonable frequency that any cheapo frequency -> wavelength conversion IC/opamp can deal with. The wavelength of the transmitted signal tells you your range, and the received difference in wavelength tells you the distance to the target point.
The complexity of the circuitry required is not too difficult, but it IS a lot. The microcontroller you use should be a powerful [ARM] processor, with USB fast speed to dump the data to a computer for processing.
the last stage of your project after testing the operation of the single point scanner, is to make it sweep - either by using a servo, slip ring and rotating mount, or usually a spinning mirror and very accurate encoders (like what you see in a laser printer - the rotating metal hexagon. rip an old laser printer up, it's fun!)
Once you have a mirror spinning single-point scanner, in comparison to an existing LIDAR solution such as the Hokuyo lidars, or SICK, which scan at around 40Hz, and 1050 single points of data each cycle, meaning your own system to be comparable should be able to sample and buffer data at a whopping 40KHz.


text:
Q: Ejabberd OAuth / REST 401 Unauthorized I'm trying to request the Ejabberd REST Web Services with the /api/connected_users endpoint but the request always returns me 401 Unauthorized HTTP errors.
Here is my OAuth configuration.
 -
port: 5280
module: ejabberd_http
request_handlers:
  "/websocket": ejabberd_http_ws
  # OAuth Support
  "/oauth": ejabberd_oauth
  # ReST API:
  "/api": mod_http_api
web_admin: true
http_bind: true
register: true
captcha: false

...

commands_admin_access: configure
commands:
  - add_commands: user
oauth_expire: 3600
oauth_access: all

As explained in the documentation I use the following URL to generate an OAuth 2 Access Token for the admin user.
http://localhost:5280/oauth/authorization_token?response_type=token&client_id=myclient&redirect_uri=http://localhost:5280&scope=sasl_auth
It returns me my OAuth Token.
http://localhost:5280/?access_token=oLn8Hebh051l2PdCM15tSvHrEI25CpBs&token_type=bearer&expires_in=3600&scope=sasl_auth&state=
Finally to request the api/connected_users endpoint I do the following.
curl -v -X GET -H "X-Admin: true" -H "Authorization: Bearer oLn8Hebh051l2PdCM15tSvHrEI25CpBs" http://localhost:5280/api/connected_users
But it always returns me 401 Unauthorized errors.
In my ejabberd.log file I have this.
2016-02-09 09:47:12.177 [info] <0.497.0>@ejabberd_listener:accept:333 (#Port<0.16419>) Accepted connection 127.0.0.1:62395 -> 127.0.0.1:5280
2016-02-09 09:47:12.177 [debug] <0.546.0>@ejabberd_http:init:154 S: [{[<<"websocket">>],ejabberd_http_ws},{[<<"oauth">>],ejabberd_oauth},{[<<"api">>],mod_http_api},{[<<"register">>],mod_register_web},{[<<"admin">>],ejabberd_web_admin},{[<<"http-bind">>],mod_http_bind}]
2016-02-09 09:47:12.177 [info] <0.546.0>@ejabberd_http:init:158 started: {gen_tcp,#Port<0.16419>}
2016-02-09 09:47:12.177 [debug] <0.546.0>@ejabberd_http:process_header:281 (#Port<0.16419>) http query: 'GET' <<"/api/connected_users">>
2016-02-09 09:47:12.177 [debug] <0.546.0>@ejabberd_http:process:353 [<<"api">>,<<"connected_users">>] matches [<<"api">>]
2016-02-09 09:47:12.178 [info] <0.546.0>@mod_http_api:log:388 Admin call connected_users [] from 127.0.0.1:62395

So how to configure Ejabberd to allow the admin user to request all the Ejabberd REST Web Services ?
My users are stored in Mysql, as OAuth Tokens are stored in Mnesia could it be the problem ?
Thanks,
Baptiste

A: Be sure you are using the @host when entering username if it's specified in that way in ejabberd.yml. I wasn't receiving any response from REST requests because I was using just admin for user, when should be admin@somehost in user name.
Please let me know if this doesn't help.

A: make sure you enter correct User(jid): ( User (jid): user@hostname)
it worked for me.


text:
Q: Image superposition with transparency in Matlab I am trying to display a lung CT image as a background image and its ROI mask over the first image with transparency. The following image

Until now I have developed the following code:
load example.mat
fig = figure;
him = imagesc(img);
colormap(gray)
set(him, 'AlphaData', 0.3 * mask)

But it only display with transparency the region covered by the Mask. What I really want is the whole lung displayed with the Mask over it in some color like green.
This image is an example of what I am trying to reach.

This is the link for the file contaning the CT lung matrix and the Mask matrix.
Link for the .mat file with the images

A: You can just overlay another image:
hold on
ih = image(cmask, 'AlphaData', mask.*.3, 'CDataMapping', 'direct');

Here, cmask is obtained for example by
cmask = zeros(size(mask, 1), size(mask, 2), 3);
cmask(:, :, 2) = mask.*255;

to get a green mask.


text:
Q: Prolog: Can't see the file I am learning how to program in prolog. I'm currently learning I/O and encountered the following problem.
I want to read the file dane.txt using this program:
czytajPlik :-
    open('dane.txt',read,X),
    current_input(CI),
    set_input(X),
    kodOdczytujacy,
    close(X),
    set_input(CI).

kodOdczytujacy :- read(Term), obsluz(Term).

obsluz(end_of_file):-!.
obsluz(Term) :-
         write(Term),nl,kodOdczytujacy.

However when in Prolog, when I try to use czytajPlik., I get the following error:
ERROR: open/3: source_sink `'dane.txt'' does not exist (No such file or directory)

The file exists and has the proper name.

A: The error means that the Prolog interpreter (I'm guessing SWIPl) cannot open the file, because it cannot find the file.
The interpreter looks in the directory it was started in, by default. You should either qualify the file with the path, or cd into the correct directory.
So let's say that you've started Prolog from a directory ~/prologstuff while the file is in ~/misc.
czytajPlik :-
    cd('../misc'),
    open('dane.txt',read,X),
    ...

or
czytajPlik :-
    open('../misc/dane.txt',read,X),
    ...

should solve your problem.


text:
Q: Why do I need to run source command for making .bash_profile alias available? My .bash_profile is like below:
alias l='ls -l'
alias p='pwd'
alias sites='cd /home/caveman/sites'
alias time_card='cd /home/caveman/sites/time-card/time-card'
alias ping='ping google.com'
alias bash_profile='gedit /home/caveman/.bash_profile'
alias webroot='cd /var/www'

every time I log into my machine I need to run the source .bash_profile to make all the alias available.
Can you guys figure out where is the problem is?

A: The ~/.bash_profile is only read in login session.
Also, having a ~/.bash_profile prevents the sourcing of ~/.profile, that is the preferred file to use for login shell in the bash configuration for Ubuntu.
When you log in the Display Manager (I suppose GDM), the ~/.profile is read by default (I don't know if GDM follows bash rules and read ~/.bash_profile instead, if exists).
Even if ~/.bash_profile were read from GDM, aliases are not inherited, so
the shell you have in a graphics terminal (that is not a login shell) cannot see them.
The solution is: put your aliases in ~/.bashrc, and use aliases only for very simple things, otherwise use functions.
The file ~/.bashrc is read by non-login interactive shells, and is sourced in ~/.profile, so that its content is also available in login shells.

A: You could just add the aliases to ~/.bash_aliases instead


text:
Q: JVM freezes when AttributedString's iterator is drawn by graphics object I have an array of AttributedString objects. I use them so that I can set part of the string one color and the rest of the string another color.
I have noticed, however, that everything stalls in the code when the graphics object uses the drawString() method on the AttributedString.getIterator(). The code stops right on the first one and then continues normally for the rest.
I also have reason to believe that the getIterator() method is not what is slowing it down. I have tried making an array of AttributedCharacterIterators that gets the iterators from the AttributedString array while the other resources are loading and using that array for the drawing of the strings.
If it helps, I am on Mac OSX El Capitan 10.11.6 Also, the installed JRE I'm using is Java SE 8 [1.8.0_65].
Here is the relevant code:
private static AttributedString[] exampleList = new AttributedString[6];

// In the main method
exampleList[0] = new AttributedString("Example String Zero");
exampleList[0].addAttribute(TextAttribute.FOREGROUND, Color.BLUE, 0, 2);
exampleList[1] = new AttributedString("Example String One");
exampleList[1].addAttribute(TextAttribute.FOREGROUND, Color.BLUE, 0, 5);
exampleList[2] = new AttributedString("Example String Two");
exampleList[2].addAttribute(TextAttribute.FOREGROUND, Color.BLUE, 0, 3);
exampleList[3] = new AttributedString("Example String Three");
exampleList[3].addAttribute(TextAttribute.FOREGROUND, Color.BLUE, 0, 4);
exampleList[4] = new AttributedString("Example String Four");
exampleList[4].addAttribute(TextAttribute.FOREGROUND, Color.BLUE, 0, 5);
exampleList[5] = new AttributedString("Example String Five");
exampleList[5].addAttribute(TextAttribute.FOREGROUND, Color.BLUE, 0, 2);
for(int i = 0; i < creditNames.length; ++i)
    exampleList[i].addAttribute(TextAttribute.FONT, scoreFont);

// In the paintComponent(Graphics g) method overriden for the JPanel where everything is drawn
g2d.setColor(Color.WHITE);
g2d.setFont(scoreFont);
int y = 10;
for(AttributedString a : exampleList)
    g2d.drawString(a.getIterator(), 50, y += 50);

If anything else is needed, please let me know.


text:
Q: Organizar comillas para enviar parámetro correctamente Estoy tratando de enviar un parámetro a una función pero no es posible la organización de las comillas para el atributo onclick y la función addclientes.
Me aparece el siguiente error Uncaught SyntaxError: Unexpected end of input, y la construcción del elemento html queda mal ya que el parámetro trae varias comillas ejemplo: "{"ClienteNombre":"Nico", "DocumentNombre ":"12e3","Numero":"456"}"
var info = JSON.stringify(datos[i]);
    var fila = '
' +
                   '' + cont + '	' +
        ' <input type="checkbox" name="checkclients" id = value' + i + ' style = "text-align: center;" onclick = "addclients("' + info +'")/> 	' +
                   '' + datos[i].ClienteNombre + '	' +
                   '' + datos[i].DocumentNombre + '	' +
                   '' + datos[i].Numero + '	' +
                   '' + dv + '	' +
                   '
';

A: Tienes un error al agregar el id, te faltan las comillas.
Para tu función debes tener cuidado con el orden, para tu caso debe ser asi
onclick = "addclients(\'' + info + \'')"/>

Nota que agregué \' para indicar que ' forma parte del string

A: Lo recomendable es usar plantillas de texto para evitar este tipo de problemas al concatenar y, de paso, hacer más legible el código:
var info = JSON.stringify(datos[i]);
var fila = `

               ${cont}
               <input type="checkbox" name="checkclients" id="${value}${i}" style="text-align: center;" onclick="addclients('${info}')">
               ${datos[i].ClienteNombre}
               ${datos[i].DocumentNombre}
               ${datos[i].Numero}
               ${dv}

`;


text:
Q: Privileged command as part of cronjob I have a personal username/password on a unix machine with limited privileges. Whenever I need  to execute some commands I have to substitute user using the su command, then I execute it normally.
Now, I need to add a cronjob that uses such privileged commands so I added the cronjob on the crontab of the user I substituted to in order to have access to these commands.
Strangely, it turned out to me that these commands fail to run for some reason as a cronjob although when I execute them directly from shell (after su) they work seamlessly.
Why does this happen? Why do these commands not work as part of cronjobs?

A: They probably expect some environment variable to be set somehow, but it isn't when the command is run directly as that user. Usually $PATH.

A: I would add an output file to your cron entry so you can see why it failed to execute. i.e:
*/5 * * * *   path_to_script.sh > /tmp/myscript.out 2>&1

After 5 minutes, check /tmp/myscript.out and see what it's complaining about.
Of course it would help finding out if you have the permission to create crons in the first place.


text:
Q: Why many local ports were opened in simple sql connection? I have an application that simply opens an SqlConnection to a remote host.
My code is something like this:
SqlConnection sc = new SqlConnection();
sc.ConnectionString = sConnectionString;
sc.Open();

I ran the application while my network monitoring tool is open. I noticed that there were 4 local ports opened that communicates with the 1433 port of the remote host. I am expecting that only 1 port will open. Why is this so?

A: I am guessing that you haven't closed your sqlconnection and it has been opened continuously , try restarting the server and (try restarting your computer as well) . And use this code after you do your work. It happened to me before and this worked for me .
SqlConnection sc = new SqlConnection();
sc.ConnectionString = sConnectionString;
sc.Open();
// do you coding here
// complete all the operations related to this connection
//close the connection
sc.Close();

A: If you have permissions to see the open database connections in the remote database server, compare this to the tcp/ip connections open in the machine hosting the application.
If the number of connections open on the database server match with the corresponding tcp/ip connections, you can be sure that there are multiple simultaneous connections open, and debug this further.
In SQL Server 2008, execute sp_who2 or open the Activity Monitor. You should be able to identify the connection sources from the results. In the application host use netstat -n or other network monitoring tool.
See Also

Too many connections to SQL 2005


text:
Q: PhoneGap push plugin get data when app is in background? Solution:
The problem seems to be with messages sent by Firebase Test Console but I don't know why, yet. I started to send messages by using node-gcm and everything is working as expected from the beginning.
Both messages sent to a single device by device token. Messages in logcat:

*

*Sent from Firebase Test Console (Not working from bg):

01-06 14:36:06.618 19422 19422 I chromium: [INFO:CONSOLE(95702)] "{"sound":"default","title":"├üFA fizet├ęs 2016.11.30-a","message":"K├Âvetkez┼Ĺ esed├ękes k├Âtelezetts├ęg: ├üFA fizet├ęs 2016.11.30-a","additionalData":{"id":"1","google.message_id":"0:1483709767111210%********","coldstart":false,"collapse_key":"********","foreground":true}}", source: file:///android_asset/www/build/main.js (95702)

*

*Sent by node-gcm script (Working even from bg):

01-06 14:37:41.037 19422 19422 I chromium: [INFO:CONSOLE(95702)] "{"title":"├üFA fizet├ęs 2016.11.30-a","message":"K├Âvetkez┼Ĺ esed├ękes k├Âtelezetts├ęg: ├üFA fizet├ęs 2016.11.30-a","additionalData":{"id":"1","google.message_id":"0:1483709856368443%*********","coldstart":false,"collapse_key":"do_not_collapse","foreground":false}}", source: file:///android_asset/www/build/main.js (95702)
The difference I see is the collapse_key property, which contains the apk name of the application and the sound. Could this be caused by collapse_key?
Updated shortened version:

*

*Device registration is successful.

*Test notifications sent from Firebase Test Console.

*They arrive to the device:

*

*When app is in the foreground, notification event is fired as it should be. OK

*When app is in the background, the message appears on the notification bar of the os. If I click on it, my app gets activated and that's all. The notification event has not been called this way. NOT OK

Original question:
I'm using phonegap-push-plugin and I can not get the notification event fired when the app is in the background and clicking on the notify event on Android.
If the app is active, I can see that the event called on logcat. However if it is in the background and I click on the event notification, the app gets activated and nothing else happens according to logcat events. I have tried adding content-available: 1 as an additional parameter in the Firebase test console, but that didn't help either.
Here is a row from logcat that shows up when the app is active:
01-05 22:41:59.981  9076  9186 V PushPlugin: extrasToJSON:
{"sound":"default","title":"Msg title","message":"Msg
body","additionalData":
{"id":"1","google.message_id":"0:1483652521531127%d86d9************",
"coldstart":false,"collapse_key":"************","foreground":true}}

The code is the same as everywhere else, I have immediate console.logs after the callback has been fired:
push.on('notification', (data) => {
    console.log('onNotification'); // not shown when app is in bg

A: Push plugin send notification when it is in background.
There is an event defined in Plugin documentation which fired by notification received , Try to catch the event and send notification using Local Notification plugin.

A: Please change your attributes for initialize the notification plugin using following way
        var push = PushNotification.init({
            android: {
                senderID: "12345679",
                forceShow : true
            },
            browser: {
                pushServiceURL: 'http://push.api.phonegap.com/v1/push'
            },
            ios: {
                alert: "true",
                badge: "true",
                sound: "true"
            },
            windows: {}
        });

android.forceShow its Controls the behavior of the notification when app is in foreground.
If true and app is in foreground, it will show a notification in the notification drawer, the same way as when the app is in background (and on('notification') callback will be called only when the user clicks the notification). When false and app is in foreground, the on('notification') callback will be called immediately.
For more details look into plugin documentation from here..
Also please look into the issue from here...
Hopes this will help you !!!


text:
Q: display a div based on url parameter My website is trackschoolbus.com. You can see a login form at the top right. What I have set up is when a wrong input is given it redirects to home page with a parameter as ?er=1 i.e. http://www.trackschoolbus.com/?er=1.
I need to display a error message when the error url comes so I have written

and the html is

wrong input

my login form is
<form name="login-form" id="login-form" method="post" action="http://www.trackschoolbus.com/vehicleTracking/index.php">
    <input name="LoginForm[username]" id="LoginForm_username" type="text" placeholder="Registered Email" value="" class="error" required/>
    <input maxlength="30" name="LoginForm[password]" id="LoginForm_password" type="password" placeholder="Password" value="" class="error" required />
    <input type="submit" onclick="this.disabled=true;this.form.submit();" name="yt0" class="btn-submit" value="Login" />
</form>

still it shows display none.

A: use php
    <form name="login-form" id="login-form" method="post" action="http://www.trackschoolbus.com/vehicleTracking/index.php">
            <input name="LoginForm[username]" id="LoginForm_username" type="text" placeholder="Registered Email" value="" class="error" required/>
            <input maxlength="30" name="LoginForm[password]" id="LoginForm_password" type="password" placeholder="Password" value="" class="error" required />
            <input type="submit" onclick="this.disabled=true;this.form.submit();" name="yt0" class="btn-submit" value="Login" />
            <?php if (isset($_GET['er']) && $_GET['er'] == 1) {
                echo '
wrong input
';
            }?>
            </form>

A: You can use this code
if ($_REQUEST['er']==1)
{
   echo '';
}

A: This is relatively simple in javascript.
Using the code snippet in this thread: How can I get query string values in JavaScript?

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
if (getParameterByName("er") == "1")
    $("#display").show();
});


text:
Q: Jquery to swap out certain links with a specific ID's using each Can someone tell me why this jquery does not work?
<script type="text/javascript">
        jQuery('a').each(function(){
            jQuery("#get-pricing-now-button-hotfix8").attr("href", "/en/starting-prices/");
        });
    </script>

I have a few buttons on the page which have an id value of get-pricing-now-button-hotfix8 and I need the ahref value for those links switch to /en/starting-prices/.
I was able to get it working for one link using the following but only changes 1 single button.
  <script type="text/javascript">
        jQuery(document).ready(function() {
            jQuery("#get-pricing-now-button-hotfix8").attr("href","/en/starting-prices/");
        });
    </script>

Please help!

A: Thank you @cloned for pointing me in the right direction.
In the end, I used this code and any instance to the new URL.
I changed #get-pricing-now-button-hotfix8 to .get-pricing-now-button-hotfix8 (changed from ID to class)
  <script type="text/javascript">
    jQuery(document).ready(function() {
        jQuery(".get-pricing-now-button-hotfix8").attr("href","/en/starting-prices/");
    });
</script>


text:
Q: Create new Object with filter from another Object I have an array of Objects from backend like this:

items = [{
    id: 0
    name: "example1"
    price: 15
    sizes: [10, 12, 15.5]
    types: ["one", "two"]
  },
  {
    id: 1
    name: "example2"
    price: 15
    sizes: [10, 12, 15.5]
    types: ["one", "two"]
  }
]

I'm receiving id as props and use find() like this:

let addedItem = items.find((item) => item.id === id)

And as result (for id = 0):

addedItem = {
  id: 0
  name: "example1"
  price: 15
  sizes: [10, 12, 15.5]
  types: ["one", "two"]
}

I'm getting also data like this type(1), size(0) as props.
So how can I create new Object like this?:

item = {
  id: 0
  name: "example1"
  price: 15
  size: 10
  type: "two"
}

A: I would just format the new object.
let item = items.find((item) => item.id === id)
let formattedItem = {
    id: item.id,
    name: item.name
    price: item.price
    size: item.sizes[0]
    type: item.types[0]
}

I would also check if sizes is a valid array, for example
type: item.types.length ? item[0] : null

A: You should not use hardcoded indexes to get the values in the client-side, this should be handled in the server-side only but still, if you want to make it work this will do it.
If you want the type[1] and size[0] you can use map() to structure your result object.
let addedItem = items.find((item) => item.id === id).map(x => {
     return {
        id: x.id,
        name: x.name,
        price: x.price,
        size: x.size[0],
        type: x.type[1]
     })

A: Well, thanks for everybody. My answer:

let item = items.find((item) => item.id === id)
let formattedItem = {
    ...item,
    size: item.sizes[size]
    type: item.types[type]
}


text:
Q: Elementor seems to be showing shortcode, not contents In this Elementor-made WP website one of the pages has mutated into just its Shortcode description showing, insted of the actual contents and UI:
https://www.agenciadinamita.com/nosotros/
I have already tried to re-introduce it through both PHPmyAdmin and the Classic Editor, but that didn't work. Has this happened to anyone?

A: Your website is not working based on Elementor, it is built with Visual Composer. Install and activate it and will start working.

A: The shortcodes seem coming from the Visual Composer Page Builder.  Also, your page doesn't look edited by using elementor page builder on that page.
I recommend to install and activate the Visual Composer Page Builder plugin on the website to make this page working.