text:
Q: Phpword: is there a way to use the compatibility word function coming from templating method? Newbie with phpword, I am generating my word.docx using templating with the library phpword but need to remove the compatibility message when opening Word so  I found that but don't know how to use it with TemplateProcessor..
I need to use correctly this method:
$phpWord->getCompatibility()->setOoxmlVersion(15);

My code is:
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('phpWord/Template.docx');
$templateProcessor->setValue('txt1', $txt1);
$templateProcessor->saveAs($nameFile);


text:
Q: Как узнать какие элементы и сколько раз повторяются Подскажите как правильно узнать какие элементы и сколько раз повторяются и если есть элементы которые не повторяются тоже бы узнать это, какой именно из элементов не повторяется... скажем если есть такой вот набор данных:
["vasa", "peta", "vasa", "serega", "vasa", "andrey", "dima", "dima", "sveta", "oleg", "oleg", "oleg", "oleg", "igor", "vasa", "stas", "stas", "oleg", "serega", "serega", "andrey", "mihail", "volandemort"]

A:

var data = ["vasa", "peta", "vasa", "serega", "vasa", "andrey", "dima",
            "dima", "sveta", "oleg", "oleg", "oleg", "oleg", "igor",
            "vasa", "stas", "stas", "oleg", "serega", "serega", "andrey",
            "mihail", "volandemort"];

var result = {};
for(var iter = 0; iter < data.length; iter++) {
  var count = result[data[iter]];
  if (count) {
    result[data[iter]] = count + 1;
  } else {
    result[data[iter]] = 1;
  }
}

console.log(result);

Не повторяются элементы, у которых счетчик 1.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mirror symmetry about the line $y = 1/x$ This seems like a very simple computation, but I don't fully understand it.
Consider the line $y = 1/x$ in the first quadrant (i.e., when $x \geq 0$). We fix a point $x_0$ and consider the line tangent to $y = 1/x$ at the point $x_0$. Computationally, it's easier to see that the $y$-intercept is $2x_0$. The claim that I do not understand is that it should be true "by mirror symmetry" that the $x$-intercept immediately is $2y_0$. The argument the professor made is that
$$y = 1/x \iff xy = 1 \iff x = \frac{1}{y}.$$
I understand this, but we're looking at the tangent line, not at the original function $y$. I can observe the function and "see" that there may be some mirror symmetry, but I don't understand fully how the geometry works.

A: The original equation $y = (1/x)$ is a hyperbola.
This implies that $x = (1/y).$
This means that instead of regarding $y = f(x) = (1/x)$, you can regard $x = g(y) = (1/y).$
Then all of your analysis, namely that the slope is $\frac{-1}{x^2}$ and that $\frac{1}{x_0} + \frac{x_0}{(x_0)^2} = \frac{2}{x_0}$ will be perfectly paralleled when you consider $x = g(y) = (1/y)$.

A: The tangent at the point $(x_0,{1 \over x_0}) = ({1 \over y_0}, y_0)$ has the equation $y={1 \over x_0} -{1 \over x_0^2}(x-x_0)$, or, viewing it from the $y$ axis perspective
$x={1 \over y_0} -{1 \over y_0^2}(y-y_0)$.
It is clear that the equations are the same if we swap the symbol $x$ with $y$ (including the subscripted symbols), however
I would not call it mirror symmetry, more
Since the $y$ intercept is found by setting $x=0$ in the first equation (which gives  ${2 \over x_0})$, using the $x-y$ swap we see that the $x$ intercept is
${2 \over y_0}$.


text:
Q: Pass Multiple Process Creation flags to CreateProcess I am using CreateProcess and I would like to pass CREATE_SUSPENDED and CREATE_NO_WINDOW as the Process Creation Flags.
This is my pinvoke signature:
[DllImport("kernel32.dll", SetLastError = true)]
private static extern Boolean CreateProcess(String lpApplicationName, String lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes,
            Boolean bInheritHandles, UInt32 dwCreationFlags, IntPtr lpEnvironment, String lpCurrentDirectory, Byte[] lpStartupInfo,
            out PROCESS_INFORMATION lpProcessInfo);

The question is: How to pass multiple flags?

A: Since all the flags have a single 1 in a single binary position, you can combine them together by OR-ing or by adding them together:
CREATE_SUSPENDED | CREATE_NO_WINDOW

Here is how it works:
CREATE_NO_WINDOW  is 0x08000000
CREATE_SUSPENDED  is 0x00000004

The result of OR-ing them together is 0x08000004.


text:
Q: Ramda - R.Both with functions taking different number of params Just learning Ramda and find I keep running into this same scenario.   I have 2 conditional functions that I want to evaluate with R.both.   The twist is that 1 function will require an extra parameter.   Something like:
const condition1 = (y) => y===1;
const condition2 = (x, y) => x===y;
const validator = R.both(condition1, condition2)
Notice that the parms for condition2 are switched.   If I know that x will be applied first this works fine.  But what if it isn't?
Do I:
1)  alter condition1 like const conditionAltered = () => condition1
2)  use some Ramda function to do the same (not sure what that would be)
3)  ????
Looking for a "best practice" type answer.

OK, so as it turns out I completely misunderstood how the R.both operated.   First I thought it would auto-curry the passed in conditions and second I didn't realize it short-circuited.
Given that my (1) should read const conditionAltered = (x, y) => condition1(y)

A: Not sure, if the conditions in questions are correct but I will try my best to give a solution.
Let above conditions are like following.
const condition1 = (x) => x === 2;
const condition2 = (x, y) => x > y;

To check both the conditions, you can do
const validator = R.both(condition1, condition2);
validator(2, 1) // return `true`

Now if you want to invert the arguments of condition2, then you can do like following
const condition1 = (x) => x === 2;
const condition2 = (y, x) => x > y;
const validator = R.both(condition1, R.flip(condition2));
validator(2, 1) // return `true`

Note, I have added R.flip() to flip the arguments.

A: As Vipin Kumar demonstrates, you can flip the arguments of one function, but if that has the order you would prefer, then you can alter the other function.
const evenWidth = (width) => width % 2 === 0
const tall = (height, width) => height > width

// (width, height) => boolean
const evenTall = both(evenWidth, flip(tall))

// (height, width) => boolean
const tallEven = both(tall, (_, width) => evenWidth(width))

If you really wanted a point-free version of the latter, you could do this instead:
const tallEven = both(tall, compose(evenWidth, nthArg(1)))

But I find the original easier to read.


text:
Q: Subset selection with LASSO involving categorical variables I ran a LASSO algorithm on a dataset that has multiple categorical variables. When I used model.matrix() function on the independent variables, it automatically created dummy values for each factor level.
For example, I have a variable "worker_type" that has three values: FTE, contr, other. Here, reference is modality "FTE".
Some other categorical variables have more or fewer factor levels.
When I output the coefficients results from LASSO, I noticed that worker_typecontr and worker_typeother both have coefficients zero. How should I interpret the results? What's the coefficient for FTE in this case? Should I just take this variable out of the formula?

A: Perhaps this question is suited more for Cross Validated.
Ridge Regression and the Lasso are both "shrinkage" methods, typically used to deal with high dimensional predictor space.
The fact that your Lasso regression reduces some of the beta coefficients to zero indicates that the Lasso is doing exactly what it is designed for! By its mathematical definition, the Lasso assumes that a number of the coefficients are truly equal to zero. The interpretation of coefficients that go to zero is that these predictors do not explain any of the variance in the response compared to the non-zero predictors.
Why does the Lasso shrink some coefficients to zero? We need to investigate how the coefficients are chosen. The Lasso is essentially a multiple linear regression problem that is solved by minimizing the Residual Sum of Squares, plus a special L1 penalty term that shrinks coefficients to 0. This is the term that is minimized:

where p is the number of predictors, and lambda is a a non-negative tuning parameter. When lambda = 0, the penalty term drops out, and you have a multiple linear regression. As lambda becomes larger, your model fit will have less bias, but higher variance (ie - it will be subject to overfitting).
A cross-validation approach should be taken towards selecting the appropriate tuning parameter lambda. Take a grid of lambda values, and compute the cross-validation error for each value of lambda and select the tuning parameter value for which the cross-validation error is the lowest.
The Lasso is useful in some situations and helps in generating simple models, but special consideration should be paid to the nature of the data itself, and whether or not another method such as Ridge Regression, or OLS Regression is more appropriate given how many predictors should be truly related to the response.
Note: See equation 6.7 on page 221 in "An Introduction to Statistical Learning", which you can download for free here.


text:
Q: Mongodb not able to start in Ubuntu 15.04 I have installed MongoDB 3.0.6 in Ubuntu 15.04 using the following commands.
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
echo "deb http://repo.mongodb.org/apt/debian wheezy/mongodb-org/3.0 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org

In the end in the installation process I got this:
Job for mongod.service failed. See "systemctl status mongod.service" and "journalctl -xe" for details.
invoke-rc.d: initscript mongod, action "start" failed.
dpkg: error processing package mongodb-org-server (--configure):
subprocess installed post-installation script returned error exit status 1
Setting up mongodb-org-mongos (3.0.6) ...
Setting up mongodb-org-tools (3.0.6) ...
dpkg: dependency problems prevent configuration of mongodb-org:
mongodb-org depends on mongodb-org-server; however:
Package mongodb-org-server is not configured yet.

dpkg: error processing package mongodb-org (--configure):
dependency problems - leaving unconfigured
No apport report written because the error message indicates its a followup error from a previous failure.
Processing triggers for systemd (219-7ubuntu6) ...
Processing triggers for ureadahead (0.100.0-19) ...
Errors were encountered while processing:
mongodb-org-server
mongodb-org
E: Sub-process /usr/bin/dpkg returned an error code (1)

After that when I start the server using the below command I get an error and the server is not started.
sudo service mongod start

And the error is
Job for mongod.service failed. See "systemctl status mongod.service" and "journalctl -xe" for details.

Now when I run:
sudo systemctl status mongod.service

I get the following:
mongod.service - LSB: An object/document-oriented database
Loaded: loaded (/etc/init.d/mongod)
Active: failed (Result: exit-code) since Thu 2015-10-08 13:46:08 IST; 22s ago
Docs: man:systemd-sysv-generator(8)
Process: 6604 ExecStart=/etc/init.d/mongod start (code=exited, status=1/FAILURE)

Oct 08 13:46:07 gariya-GA-A55M systemd[1]: Starting LSB: An   object/document-oriented database...
Oct 08 13:46:07 gariya-GA-A55M mongod[6604]: * Starting database mongod
Oct 08 13:46:08 gariya-GA-A55M mongod[6604]: ...fail!
Oct 08 13:46:08 gariya-GA-A55M systemd[1]: mongod.service: control process exited, code=exited status=1
Oct 08 13:46:08 gariya-GA-A55M systemd[1]: Failed to start LSB: An  object/document-oriented database.
Oct 08 13:46:08 gariya-GA-A55M systemd[1]: Unit mongod.service entered failed state.
Oct 08 13:46:08 gariya-GA-A55M systemd[1]: mongod.service failed.

Someone please help, I am new to Ubuntu and MongoDB and I am not getting what is the problem.

A: Recently i ended up with same issue and i tried all the possible solutions explained up here. But it didn't worked out for me. I was getting the below error.
# sudo service mongod restart
Restarting mongod (via systemctl): Job for mongod.service failed because the control process exited with error code. See "systemctl status mongod.service" and "journalctl -xe" for details. [FAILED]

Eventually i figured out the solution which worked for me.
I went to /run/mongodb folder and deleted the file called mongod.pid. Then tried to restart the mongo using # sudo service mongod restart and it's worked!

A: My log said:
[initandlisten] Found an invalid index { v: 2, key: { version: 1 }, name:   "incompatible_with_version_32", ns: "admin.system.version"

so:
 $cd /var/lib
 $sudo rm -rf ./mongodb
 $sudo mkdir mongodb
 $sudo chown -R mongodb.mongodb mongodb/
 $sudo service mongod restart

and then all worked fine.

A: sudo nano /etc/systemd/system/mongodb.service
[Unit]
Description=High-performance, schema-free document-oriented database
After=network.target

[Service]
User=mongodb
ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf

[Install]
WantedBy=multi-user.target

sudo systemctl start mongodb
sudo systemctl status mongodb
sudo systemctl enable mongodb
Is job!

A: There is a log file: /var/log/mongodb/mongod.log
In the log I've found the following:
Failed to unlink socket file /tmp/mongodb-27017.sock errno: Operation not permitted

Most probably this was from previous MongoDB version. I deleted the file (rm -rf /tmp/mongodb-27017.sock) and finished the installation:
apt-get install mongodb-org

Now it works. :-)

A: *

*Make sure that the /data/db directory exists

*Make sure your user have write privileges in that directory:
$ sudo chown id -u /data/db

*Execute mongod
If you still have problems and if the file /data/db/mongod.lock exists, remove it and execute mongod --repair.

A: The first thing you should check is a mongodb log file located at /var/log/mongodb/mongod.log
Look for the line with status E containing words like 'failed', 'fatal', etc.

A: I removed the mongodb lock file-

sudo /data/db/mongod.lock

Then restarted the mongodb

sudo service mongod restart

This solved the issue.

A: I was having the same issue, after searching I got the answer that, when I executed
sudo service mongod restart

I changed the permissions from user mongodb to root of the database folder, so the service was not able to read the data.
So to solve I just reverted the permissions back to the user mongodb
sudo chown -R mongodb:mongodb /path-to-db-folder
sudo service mongod restart


text:
Q: using python recursion to calculate the Parenthesis part not working If I enter input with parentheses it resolves only what is inside the parentheses and not what is after or before, if I enter two expressions with parentheses it returns None.
you can see it in the code.
def divide(a, b):
    return a/b
def pow(a, b):
    return a**b
def addA(a, b):
    return a+b
def subA(a, b):
    return a-b
def mul (a, b):
    return a*b
operators = {
  '+': addA,
  '-': subA,
  '*': mul,
  '/': divide,
  '^' : pow,

}

def calculate(s):
    if s.isdigit():
        return float(s)
    elif '[' in s:
        start = s.index('[')
        end = s.rindex(']')
        return calculate(s[start + 1:end])
    for c in operators.keys():
        left, operator, right = s.partition(c)
        if operator in operators:
            return operators[operator](calculate(left), calculate(right))

calc = input("Type calculation:\n")
print("Answer: " + str(calculate(calc)))

input: [2+2]+[2+2]
output: None
input [2+3]*2
output 5

A: Nice idea.
    elif '[' in s:
        ...
        return calculate(s[start + 1:end])

Beautifully simple.
But, alas, wrong.
Consider 1+1+1+[8+9]+2+2+2.
Is there a [ bracket in there? Yes.
And the recursive call correctly computes 17.
But we're ignoring the 1's and the 2's.
Also, when the for finishes and we fall of the
end of the function we return None.
Consider doing something else in that case,
perhaps raise a fatal error.

You probably want to invert the order of operations,
so higher priority ops will bind more tightly.

You will find you can iterate through the edit - debug
cycle much more quickly if you write some simple
unit tests
that lock in "working" behavior. Only the last test fails ATM.
class CalculateTest(unittest.TestCase):
    def test_addition(self):
        self.assertEqual(5, calculate("2+3"))
        self.assertEqual(5, calculate("[2+3]"))
        self.assertEqual(9, calculate("2+3+4"))
        self.assertEqual(9, calculate("2+[3+4]"))

I found it convenient to have the function always return a float.

Once you have this function in better shape, please
let us know
how it turned out.

A: The calculate function took into account the first and last parenthesis, skipping the middle ones.
Try the following:
def extract_expression(s):
    start = s.rindex('[')
    end = s.rindex(']')
    return s[start + 1:end]

def calculate(expr):
    for c in operators.keys():
        left, operator, right = expr.partition(c)
        if operator in operators:
            return operators[operator](float(left), float(right))

def solution(s):
    while '[' in s:
        sub_expression = extract_expression(s)
        result = calculate(sub_expression)
        s = s.replace('[' + sub_expression + ']', str(result))

    if s.isdigit():
        return float(s)

    return calculate(s)

calc = input("Type calculation:\n")
print("Answer: " + str(solution(calc)))

input: [2+2]+[2+2],
output: 8.0
input: [2+3]*2,
output: 10.0
input: 2+[2+2],
output: 6.0


text:
Q: Unable to Move Mailbox to new Database - 0 of 0 Succeeded I'm selecting one mailbox to move to a new mailbox database in Exchange 2013, and when I start the Migration job in ECP it shows one Mailbox, but a few moments later when refreshing the job it changes to 0 mailboxes and then completes in an apparent normal state with 0 of 0 succeeded. I deleted this job and all previous ones from the list and tried again - same result.  I deleted the job again and moved on to investigate.
Digging deeper in the console I ran Get-MoveRequest and received the following:
[PS] C:\Windows\system32>get-moverequest

DisplayName                                    Status                    TargetDatabase
-----------                                    ------                    --------------
SystemMailbox{8cc370d3-822a-4ab8-a926-bb94b... Completed
WARNING: The object support.local/Users/SystemMailbox{8cc370d3-822a-4ab8-a926-bb94bd0641a9} has been corrupted, and
it's in an inconsistent state. The following validation errors happened:
WARNING: Database is mandatory on UserMailbox.

The mentioned SystemMailbox appears to be pretty old and was "Disabled" in AD. I tried enabling and disabling the account again, but no joy.  I am not able to remove the request as I cannot identify it, nor have I had any results from repairing the source and destination folder of my migration using:
[PS] C:\Windows\system32>New-MailboxRepairRequest -Database CleanDB -CorruptionType ProvisionedFolder,SearchFolder,Aggre
gateCounts,Folderview

I am at a hard stop as it would seem the errors above are preventing my migration job from completeing and I have not been able to over come what I have found so far.  Any advice?  Thanks in advance.

A: Run below command to check the database of "SystemMailbox{8cc370d3-822a-4ab8-a926-bb94bd0641a9}":
Get-Mailbox -AuditLog | FL Alias,ServerName,Database

If it remains display a warning "Database is mandatory on UserMailbox":

*

*Open ADUC and enable Advanced Features, find "SystemMailbox{8cc370d3-822a-4ab8-a926-bb94bd0641a9}" and open Properties.

*Switch to Attributes Editor and find "homeMDB".

*Copy this value from other mailbox which store in same database, and replace the value for problematic mailbox.

If it remain exists, we may need to recreate it by PrepareAD.
Note: the AD account of those system mailboxes are disabled by default.

A: I finally resolved this by simply deleting the SystemMailbox mentioned above as it seemed to be orphaned in the system.  After, I could migrate mailboxes to and from databases normally and have seen no adverse effects or errors in the application logs.
Note: I did not have to run PrepareAD from the setup.exe.
I hope this helps someone else that has the same issue.


text:
Q: Installation of FinchTV in Ubuntu 20.04 I am using Ubuntu 20.04.3.
I need to install FinchTV in it.
Is there any way to get the software?

A: For software that is not in the standard software repositories, you depend on the install documentation of the software you want to install. First ensure that the software is supported on linux in the first place. If that is the case, installation can take different forms. You may need to compile the software yourself, the developer may provide binary files you can install using an install script, the developper may provide a .deb installation file, or even a software PPA, ... Only you can know, studying the documentation provided by the software.

A: This FinchTV application is available only for macOS and MS Windows. To run it on Ubuntu you need Wine - you have to install it using PlayOnLinux by following the below steps:

*

*Install PlayOnLinux with
sudo apt-get update
sudo apt-get install playonlinux

*Obtain Windows installer package from official site:
cd ~/Downloads
wget -c https://digitalworldbiology.com/sites/default/files/Basic%20page/upfiles/Windows_FinchTV_1_4_0.zip
unzip Windows_FinchTV_1_4_0.zip

*Launch PlayOnLinux

*Click Install, select Install a non-listed application

*Follow the wizard, press Next 4 times

*Specify a name of wine virtual drive, i.e. finchtv, click Next 3 times

*Click Browse and specify path to installer - ~/Downloads/FinchTV_1_4_0/Installer.msi, click Next

*Follow FinchTV windows installer with all default settings

*Create shortcut for FinchTV.exe then select I don't want to make another shortcut, click Next

*Launch FinchTV using desktop shortcut and enjoy.


text:
Q: How do I convert a float number to a whole number in JavaScript? I'd like to convert a float to a whole number in JavaScript. Actually, I'd like to know how to do BOTH of the standard conversions: by truncating and by rounding. And efficiently, not via converting to a string and parsing.

A: If you want a rounded off answer on the downward side:
var intvalue = Math.floor( floatvalue );
var integer = Math.floor(4.56);
Answer = 4

If you want to round off upwards:
var intvalue = Math.ceil( floatvalue );
Answeer would be = 5

A: There are many suggestions here. The bitwise OR seems to be the simplest by far. Here is another short solution which works with negative numbers as well using the modulo operator. It is probably easier to understand than the bitwise OR:
intval = floatval - floatval%1;

This method also works with high value numbers where neither '|0' nor '~~' nor '>>0' work correctly:
> n=4294967295;
> n|0
-1
> ~~n
-1
> n>>0
-1
> n-n%1
4294967295

A: *

*Math.floor() function returns the largest integer less than or equal to a given number.

    console.log('Math.floor : ', Math.floor(3.5));
    console.log('Math.floor : ', Math.floor(-3.5));

*Math.ceil() function always rounds a number up to the next largest integer.

    console.log('Math.ceil : ', Math.ceil(3.5));
    console.log('Math.ceil : ', Math.ceil(-3.5));

*Math.round() function returns the value of a number rounded to the nearest integer.

    console.log('Math.round : ', Math.round(3.5));
    console.log('Math.round : ', Math.round(-3.5));

*Math.trunc() function returns the integer part of a number by removing any fractional digits.

    console.log('Math.trunc : ', Math.trunc(3.5));
    console.log('Math.trunc : ', Math.trunc(-3.5));

A:

//Convert a float to integer

Math.floor(5.95)
//5

Math.ceil(5.95)
//6

Math.round(5.4)
//5

Math.round(5.5)
//6

Math.trunc(5.5)
//5

//Quick Ways
console.log(5.95| 0)
console.log(~~5.95)
console.log(5.95 >> 0)
//5

A: A double bitwise not operator can be used to truncate floats.  The other operations you mentioned are available through Math.floor, Math.ceil, and Math.round.
> ~~2.5
2
> ~~(-1.4)
-1

More details courtesy of James Padolsey.

A: For truncate:
var intvalue = Math.floor(value);

For round:
var intvalue = Math.round(value);

A: Performance
Today 2020.11.28 I perform tests on MacOs HighSierra 10.13.6 on Chrome v85, Safari v13.1.2 and Firefox v80 for chosen solutions.
Results

*

*for all browsers all solutions (except B and K) gives very similar speed results

*solutions B and K are slow

Details
I perform test case which you can run HERE
Below snippet presents differences between solutions
A
B
C
D
E
F
G
H
I
J
K
L

function A(float) {
    return Math.trunc( float );
}

function B(float) {
    return parseInt(float);
}

function C(float) {
    return float | 0;
}

function D(float) {
    return ~~float;
}

function E(float) {
    return float >> 0;
}

function F(float) {
    return float - float%1;
}

function G(float) {
    return float ^ 0;
}

function H(float) {
    return Math.floor( float );
}

function I(float) {
    return Math.ceil( float );
}

function J(float) {
    return Math.round( float );
}

function K(float) {
    return float.toFixed(0);
}

function L(float) {
    return float >>> 0;
}

// ---------
// TEST
// ---------

[A,B,C,D,E,F,G,H,I,J,K,L]
  .forEach(f=> console.log(`${f.name} ${f(1.5)} ${f(-1.5)} ${f(2.499)} ${f(-2.499)}`))
This snippet only presents functions used in performance tests - it not perform tests itself!

And here are example results for chrome

A: You can use the parseInt method for no rounding.  Be careful with user input due to the 0x (hex) and 0 (octal) prefix options.
var intValue = parseInt(floatValue, 10);

EDIT: as a warning (from the comments section), please be aware that certain numeric values will be converted to their exponent form such as 1e21 which results in the incorrect decimal representation of "1"

A: Bitwise OR operator
A bitwise or operator can be used to truncate floating point figures and it works for positives as well as negatives:
function float2int (value) {
    return value | 0;
}

Results
float2int(3.1) == 3
float2int(-3.1) == -3
float2int(3.9) == 3
float2int(-3.9) == -3

Performance comparison?
I've created a JSPerf test that compares performance between:

*

*Math.floor(val)

*val | 0 bitwise OR

*~~val bitwise NOT

*parseInt(val)
that only works with positive numbers. In this case you're safe to use bitwise operations well as Math.floor function.
But if you need your code to work with positives as well as negatives, then a bitwise operation is the fastest (OR being the preferred one). This other JSPerf test compares the same where it's pretty obvious that because of the additional sign checking Math is now the slowest of the four.
Note
As stated in comments, BITWISE operators operate on signed 32bit integers, therefore large numbers will be converted, example:
1234567890  | 0 => 1234567890
12345678901 | 0 => -539222987

A: If look into native Math object in JavaScript, you get the whole bunch of functions to work on numbers and values, etc...
Basically what you want to do is quite simple and native in JavaScript...
Imagine you have the number below:
const myValue = 56.4534931;

and now if you want to round it down to the nearest number, just simply do:
const rounded = Math.floor(myValue);

and you get:
56

If you want to round it up to the nearest number, just do:
const roundedUp = Math.ceil(myValue);

and you get:
57

Also Math.round just round it to higher or lower number depends on which one is closer to the flot number.
Also you can use of ~~ behind the float number, that will convert a float to a whole number.
You can use it like ~~myValue...

A: var intvalue = Math.floor( floatvalue );
var intvalue = Math.ceil( floatvalue );
var intvalue = Math.round( floatvalue );

// `Math.trunc` was added in ECMAScript 6
var intvalue = Math.trunc( floatvalue );

Math object reference

Examples
Positive
// value=x        //  x=5          5<x<5.5      5.5<=x<6

Math.floor(value) //  5            5            5
Math.ceil(value)  //  5            6            6
Math.round(value) //  5            5            6
Math.trunc(value) //  5            5            5
parseInt(value)   //  5            5            5
~~value           //  5            5            5
value | 0         //  5            5            5
value >> 0        //  5            5            5
value >>> 0       //  5            5            5
value - value % 1 //  5            5            5

Negative
// value=x        // x=-5         -5>x>=-5.5   -5.5>x>-6

Math.floor(value) // -5           -6           -6
Math.ceil(value)  // -5           -5           -5
Math.round(value) // -5           -5           -6
Math.trunc(value) // -5           -5           -5
parseInt(value)   // -5           -5           -5
value | 0         // -5           -5           -5
~~value           // -5           -5           -5
value >> 0        // -5           -5           -5
value >>> 0       // 4294967291   4294967291   4294967291
value - value % 1 // -5           -5           -5

Positive - Larger numbers
// x = Number.MAX_SAFE_INTEGER/10 // =900719925474099.1

// value=x            x=900719925474099    x=900719925474099.4  x=900719925474099.5

Math.floor(value) //  900719925474099      900719925474099      900719925474099
Math.ceil(value)  //  900719925474099      900719925474100      900719925474100
Math.round(value) //  900719925474099      900719925474099      900719925474100
Math.trunc(value) //  900719925474099      900719925474099      900719925474099
parseInt(value)   //  900719925474099      900719925474099      900719925474099
value | 0         //  858993459            858993459            858993459
~~value           //  858993459            858993459            858993459
value >> 0        //  858993459            858993459            858993459
value >>> 0       //  858993459            858993459            858993459
value - value % 1 //  900719925474099      900719925474099      900719925474099

Negative - Larger numbers
// x = Number.MAX_SAFE_INTEGER/10 * -1 // -900719925474099.1

// value = x      // x=-900719925474099   x=-900719925474099.5 x=-900719925474099.6

Math.floor(value) // -900719925474099     -900719925474100     -900719925474100
Math.ceil(value)  // -900719925474099     -900719925474099     -900719925474099
Math.round(value) // -900719925474099     -900719925474099     -900719925474100
Math.trunc(value) // -900719925474099     -900719925474099     -900719925474099
parseInt(value)   // -900719925474099     -900719925474099     -900719925474099
value | 0         // -858993459           -858993459           -858993459
~~value           // -858993459           -858993459           -858993459
value >> 0        // -858993459           -858993459           -858993459
value >>> 0       //  3435973837           3435973837           3435973837
value - value % 1 // -900719925474099     -900719925474099     -900719925474099

A: Bit shift by 0 which is equivalent to division by 1
// >> or >>>
2.0 >> 0; // 2
2.0 >>> 0; // 2

A: In your case, when you want a string in the end (in order to insert commas), you can also just  use the Number.toFixed() function, however, this will perform rounding.

A: One more possible way — use XOR operation:

console.log(12.3 ^ 0); // 12
console.log("12.3" ^ 0); // 12
console.log(1.2 + 1.3 ^ 0); // 2
console.log(1.2 + 1.3 * 2 ^ 0); // 3
console.log(-1.2 ^ 0); // -1
console.log(-1.2 + 1 ^ 0); // 0
console.log(-1.2 - 1.3 ^ 0); // -2

Priority of bitwise operations is less then priority of math operations, it's useful. Try on https://jsfiddle.net/au51uj3r/

A: Note: You cannot use Math.floor() as a replacement for truncate, because Math.floor(-3.1) = -4 and not -3 !!
A correct replacement for truncate would be:
function truncate(value)
{
    if (value < 0) {
        return Math.ceil(value);
    }

    return Math.floor(value);
}

A: To truncate:

// Math.trunc() is part of the ES6 spec
console.log(Math.trunc( 1.5 ));  // returns 1
console.log(Math.trunc( -1.5 )); // returns -1
// Math.floor( -1.5 ) would return -2, which is probably not what you wanted

To round:

console.log(Math.round( 1.5 ));  // 2
console.log(Math.round( 1.49 )); // 1
console.log(Math.round( -1.6 )); // -2
console.log(Math.round( -1.3 )); // -1

A: I just want to point out that monetarily you want to round, and not trunc. Being off by a penny is much less likely, since 4.999452 * 100 rounded will give you 5, a more representative answer.
And on top of that, don't forget about banker's rounding, which is a way to counter the slightly positive bias that straight rounding gives -- your financial application may require it.
Gaussian/banker's rounding in JavaScript

A: If you are using angularjs then simple solution as follows In HTML Template Binding

{{val | number:0}}
it will convert val into integer
go through with this link docs.angularjs.org/api/ng/filter/number


text:
Q: Creating dynamic SQL queries in Oracle Trigger I am  trying to write a trigger in Oracle 9i that will create some dynamic insert statements based on the values from the NEWROW that fired the trigger.
I need to pass the value of two fields from the new row to an existing function that returns a table of values (this function already exists and works fine). Basically the function splits the string into table rows.For example, if the two values I pass are 'Shirt,Sweater' and 'Red,Blue' I get back two tables. The first table has the values:
Shirt
Sweater

and the second table has the values
Red
Blue

Pretty simple. Once these two tables are returned I need to create some dynamic insert statements based on the values from these two table like so:
insert into mytable values ('Shirt','Red')
insert into mytable values ('Shirt','Blue')
insert into mytable values ('Sweater','Red')
insert into mytable values ('Sweater','Blue')

It is not necessary that I use the existing function. If the string can be split into arrays withing this trigger and have the same end results that also works.
Any help in this would be great appreciated. Thanks.

A: You want all possible combinations of the array elements, in other words?
FOR i in 1 .. clothing.count LOOP
    FOR j in 1 .. colors.count LOOP
        INSERT INTO mytable VALUES ( clothing(i), colors(j) );
    END LOOP;
END LOOP;


text:
Q: Iterative comparison with pandas I don't know to approach this issue. I have a data frame that looks like this
cuenta_bancaria nombre_empresa  perfil_cobranza  usuario_id  usuario_web
5545              a              123              500199         5012
5551              a              123              500199         3321
5551              a               55              500199         5541
5551              b               55              500199         5246

What I need to do is to iterate between each row per usuario_id and check if there's a difference between each row, and create a new data set with the row changed and the usuario_web in charge of this change, to generate a data frame that looks like this:
usuario_id     cambio           usuario_web
 500199       cuenta_bancaria    3321
 500199       perfil_cobranza    5541
 500199       nombre_empresa     5246

Is there any way to do this? I'm working with pandas on python and this dataset could be a little big, let's say around 10000 rows, sorted by usuario_id.
Thanks for any advice.

A: Compare adjacent rows with ne + shift, obtain a mask, and use this to

*

*index into df to get the required rows

*index into df.columns to get the required columns which change

c = df.columns.intersection(
        ['nombre_empresa', 'perfil_cobranza', 'cuenta_bancaria']
)

i = df[c].ne(df[c].shift())
j = i.sum(1).eq(1)

df = df.loc[j, ['usuario_id', 'usuario_web']]
df.insert(1, 'cambio', c[i[j].values.argmax(1)])

df

   usuario_id           cambio  usuario_web
1      500199  cuenta_bancaria         3321
2      500199  perfil_cobranza         5541
3      500199   nombre_empresa         5246

A: There are a couple ways to iterate over a dataframe:
for index, row in df.iterrows():
    #blah blah blah

but since you're wanting to reference the prior row, I think the easiest will be to iterate by position:
df2 = pd.DataFrame()
for i in range(1, np.shape(df)[0]):
    current = df.iloc[i]
    last = df.iloc[i-1]
    newrow = {'usario_id' = current['usario_id'], 'usario_web'= current['usario_web']}
    if current['cuenta_bancaria'] != last['cuenta_bancaria']:
        newrow['cambio'] = 'cuenta_bancaria'
        df2 = df2.append(newrow, ignore_index = False)
    elif current['nombre_empresa'] != last['nombre_empresa']:
        newrow['cambio'] = 'nombre_empresa'
        df2 = df2.append(newrow, ignore_index = False)
    elif current['perfil_cobranza'] != last['perfil_cobranza']:
        newrow['cambio'] = 'perfil_cobranza'
        df2 = df2.append(newrow, ignore_index = False)


text:
Q: Why would adding a programmatically rendered panel break ajax beahvior for a declared Panel? I have the following frontend code using primefaces

    <p:panel binding="#{widgetBean.panel}"/>

    <p:panel header="Widget 2" id="declaredPanel" style="height:300px; width:300px">
        <p:droppable tolerance="touch" scope="widgetDrop" activeStyleClass="ui-state-highlight" >
            <p:ajax listener="#{widgetBean.widgetDropped}" ></p:ajax>
        </p:droppable>
    </p:panel>

with this for the backend bean:
public Panel getPanel(){
    Panel p = new Panel();
    p.setHeader("test");
    p.setId("programmaticPanel");
    p.setStyle("height:300px; width:300px");
    Droppable d = new Droppable();
    d.setDatasource("availableWidgets");
    d.setTolerance("touch");
    d.setScope("widgetDrop");
    d.setActiveStyleClass("ui-state-highlight");

    FacesContext fc = FacesContext.getCurrentInstance();
    ExpressionFactory ef = fc.getApplication().getExpressionFactory();
    MethodExpression onDropExpr = ef.createMethodExpression(
       fc.getELContext(), "#{widgetBean.widgetDropped}", null, new Class[] {     DragDropEvent.class });

    AjaxBehavior ajaxBehavior = new AjaxBehavior();
    ajaxBehavior.addAjaxBehaviorListener(new AjaxBehaviorListenerImpl(onDropExpr));

    d.addClientBehavior("drop", ajaxBehavior);

    p.getChildren().add(d);
    return p;
  }
  public void widgetDropped(DragDropEvent ddEvent) {
    System.out.println("DROP EXECUTED ON SERVER");
  }

The weirdest thing happens. If I use both ways of rendering the Panel in the UI my ajax listener never gets called.  If I remove the Panel that uses a binding my drop listener gets executed.  On top of that I can return an just a plain jane panel with no droppable children and the declarative panel still will not fire a listener. However the opposite is not true. If I remove the declarative panel the programmticaly bound one still never fires the listener.  Really I have two problems:
1.) rendering a programmatic panel breaks the drop listener event on the declarative Panel
2.) In any scenario the drop listener never gets called for the programmatic Panel.
I'm using Primefaces 3.2 and running on Glassfish 3.1.1 I would LOVE any help at this point. I've researched this problem and found others complain about issues binding ajaxbehaviors programmtically, notably: Linky link This seemed to have solved the issue for some...not the case for me. Thanks!


text:
Q: Transform array of keys and array of values into array of objects javascript My question is quite similar to this one: Merge keys array and values array into an object in JavaScript
However, I don't seem to find the solution for my example. If I have these two arrays:
const keys = ['x', 'y', 'z'];

const values = [
  [0, 1, 2],
  [10, 20, 30],
];

How do I combine them into an array of objects, such that would be the expected result?
[
  {
    x: 0,
    y: 1,
    z: 2,
  },
  {
    x: 10,
    y: 20,
    z: 30,
  },
]

A: Cycle through the value arrays and create an object for each, then cycle through the values within those arrays and use the keys array as the keys.

const keys = ['x', 'y', 'z'];

const values = [
  [0, 1, 2],
  [10, 20, 30],
];

const output = [];
values.forEach((v, i) => {
  output[i] = {}; // create objects for each of the value arrays
  v.forEach((w, j) => {
    output[i][keys[j]] = w; // use the correct keys with each of the values
  });
});

console.log(output);

As comments have also pointed out, this can be done with Array.reduce:

const keys = ['x', 'y', 'z'];

const values = [
  [0, 1, 2],
  [10, 20, 30],
];

const output = values.map(x => { // for each of the values arrays
  return x.reduce((a, c, i) => { // take its values
    a[keys[i]] = c // map them to an object property one by one
    return a; // put them together in the same object.
  }, {});
});

console.log(output);

A: You can use Array.prototype.map() and Array.prototype.reduce() for this:

const keys = ['x', 'y', 'z'];

const values = [
  [0, 1, 2],
  [10, 20, 30],
];

const res = values.map(arr => arr.reduce((acc, curr, index) => {
  acc[keys[index]] = curr

  return acc;
}, {x: null, y: null, z: null}));

console.log(res);

Or you can also do it without reduce() like so:
const res = values.map(arr => ({
  [keys[0]]: arr[0],
  [keys[1]]: arr[1],
  [keys[2]]: arr[2]
}));

A:

const keys = ['x', 'y', 'z'];

const values = [
  [0, 1, 2],
  [10, 20, 30],
];

function toObject(keys, values) {
    let final = []
     for (let i = 0; i < values.length; i++){
         let result = {};
         for(let j=0;j<keys.length;j++){
             result[keys[j]] = values[i][j];

         }
        final.push(result)
     }
    return final
    console.log(final)

 }

 toObject(keys,values )

it will work


text:
Q: Keyboard Unresponsive I can't seem to find out why my keyboard work. I have tried changing the speed, changing the class, and swapped it out for using the mouse but I want more keyboard! No errors appear when I run it but the main player just stays in the top left and doesn't move. I've also duplicated this code with less bonus characters and it worked but once I add bonus and more levels, it fails. Any help would be greatly appreciated.
The link is for all the images and code.
https://drive.google.com/drive/folders/162vsO20kRoNBy6IJa3WgSq4D5ZB5PsI2?usp=sharing
import pygame
import random

BLACK = (0, 0, 0)
pygame.init()

class Block(pygame.sprite.Sprite):

    # Constructor. Pass in the color of the block,
    # and its x and y position
    def __init__(self, color, width, height):
        # Call the parent class (Sprite) constructor
        super().__init__()

        # Create an image of the block, and fill it with a color.
        # This could also be an image loaded from the disk.
        self.image = pygame.Surface([width, height])
        self.image.fill(color)

        # Fetch the rectangle object that has the dimensions of the image
        # image.
        # Update the position of this object by setting the values
        # of rect.x and rect.y
        self.rect = self.image.get_rect()

class Player(pygame.sprite.Sprite):

    # Constructor. Pass in the color of the block,
    # and its x and y position
    def __init__(self, x, y):
        # Call the parent class (Sprite) constructor
        super().__init__()

        # Create an image of the block, and fill it with a color.
        # This could also be an image loaded from the disk.
        self.image = pygame.image.load("aboriginal.png")

        # Fetch the rectangle object that has the dimensions of the image
        # image.
        # Update the position of this object by setting the values
        # of rect.x and rect.y
        self.rect = self.image.get_rect()
        # Make our top-left corner the passed-in location.
        self.rect.x = x
        self.rect.y = y

        # -- Attributes
        # Set speed vector
        self.change_x = 0
        self.change_y = 0

    def changeSpeed(self, x, y):
        """ Change the speed of the player"""
        self.change_x += x
        self.change_y += y

    def update(self):
        """ Find a new position for the player"""
        self.rect.x += self.change_x
        self.rect.y += self.change_y

class Bonus(pygame.sprite.Sprite):

    # Constructor. Pass in the color of the block,
    # and its x and y position
    def __init__(self, pic):
        # Call the parent class (Sprite) constructor
        super().__init__()

        # Create an image of the block, and fill it with a color.
        # This could also be an image loaded from the disk.
        self.image = pygame.image.load(pic)

        # Fetch the rectangle object that has the dimensions of the image
        # image.
        # Update the position of this object by setting the values
        # of rect.x and rect.y
        self.rect = self.image.get_rect()

SCREEN_WIDTH = 700
SCREEN_HEIGHT = 400
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
pygame.display.set_caption(('Outback Steakhouse'))
background = pygame.image.load('winter.png')
background2 = pygame.image.load('timthumb.jpg')
background3 = pygame.image.load('winter.png')
background4 = pygame.image.load('timthumb.jpg')
background5 = pygame.image.load('rugbyStadium.png')

# sprites
block_list = pygame.sprite.Group()
bonus_list = pygame.sprite.Group()
all_sprites_list = pygame.sprite.Group()

for i in range(10):
    # This represents a block
    block = Block(BLACK, 20, 15)

    # Set a random location for the block
    block.rect.x = random.randrange(SCREEN_WIDTH)
    block.rect.y = random.randrange(SCREEN_HEIGHT)

    # Add the block to the list of objects
    block_list.add(block)
    all_sprites_list.add(block)

# Create a player instance
player = Player(0,0)
all_sprites_list.add(player)

# Bonus instance
kiwi = Bonus('kiwi.png')
kiwi.rect.x = random.randrange(SCREEN_WIDTH - 64)
kiwi.rect.y = random.randrange(SCREEN_HEIGHT - 64)
bonus_list.add(kiwi)
all_sprites_list.add(kiwi)

done = False

clock = pygame.time.Clock()

font = pygame.font.Font(None, 36)

score = 0

level = 1

# -------- Main Program Loop -----------
while not done:
    # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT

    for event in pygame.event.get():  # User did something
        if event.type == pygame.QUIT:  # If user clicked close
            done = True  # Flag that we are done so we exit this loop

            # Set the speed based on the key pressed
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                player.changeSpeed(-3, 0)
            elif event.key == pygame.K_RIGHT:
                player.changeSpeed(3, 0)
            elif event.key == pygame.K_UP:
                player.changeSpeed(0, -3)
            elif event.key == pygame.K_DOWN:
                player.changeSpeed(0, 3)

        # Reset speed when key goes up
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                player.changeSpeed(3, 0)
            elif event.key == pygame.K_RIGHT:
                player.changeSpeed(-3, 0)
            elif event.key == pygame.K_UP:
                player.changeSpeed(0, 3)
            elif event.key == pygame.K_DOWN:
                player.changeSpeed(0, -3)

    # See if the player block has collided with anything including bonus
    blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True)
    bonus_hit_list = pygame.sprite.spritecollide(player, bonus_list, True)

    # Check the list of collisions.
    for block in blocks_hit_list:
        score += 1
        print(score)
    for bonus in bonus_hit_list:
        score += 10
        print(score)

    # Check to see if all the blocks are gone.
    # If they are, level up.
    if len(block_list) == 0 and len(bonus_list) == 0:
        # Add one to the level
        level += 1

        # Add more blocks. How many depends on the level.
        # Also, an 'if' statement could be used to change what
        # happens customized to levels 2, 3, 4, etc.
        for i in range(level * 10):
            # This represents a block
            block = Block(BLACK, 20, 15)

            # Set a random location for the block
            block.rect.x = random.randrange(SCREEN_WIDTH)
            block.rect.y = random.randrange(SCREEN_HEIGHT)

            # Add the block to the list of objects
            block_list.add(block)
            all_sprites_list.add(block)

        for i in range(level):
            if level == 1:
                kiwi = Bonus('kiwi.png')
                kiwi.rect.x = random.randrange(SCREEN_WIDTH - 64)
                kiwi.rect.y = random.randrange(SCREEN_HEIGHT - 64)
                bonus_list.add(kiwi)
                all_sprites_list.add(kiwi)
            if level == 2:
                koala = Bonus('koala.png')
                koala.rect.x = random.randrange(SCREEN_WIDTH - 64)
                koala.rect.y = random.randrange(SCREEN_HEIGHT - 64)
                bonus_list.add(koala)
                all_sprites_list.add(koala)
            if level == 3:
                kangaroo = Bonus('kangaroo.png')
                kangaroo.rect.x = random.randrange(SCREEN_WIDTH - 64)
                kangaroo.rect.y = random.randrange(SCREEN_HEIGHT - 64)
                bonus_list.add(kangaroo)
                all_sprites_list.add(kangaroo)
            if level == 4:
                boomerang = Bonus('boomerang.png')
                boomerang.rect.x = random.randrange(SCREEN_WIDTH - 64)
                boomerang.rect.y = random.randrange(SCREEN_HEIGHT - 64)
                bonus_list.add(boomerang)
                all_sprites_list.add(boomerang)
            if level == 5:
                rugby = Bonus('rugby.png')
                rugby.rect.x = random.randrange(SCREEN_WIDTH - 64)
                rugby.rect.y = random.randrange(SCREEN_HEIGHT - 64)
                bonus_list.add(rugby)
                all_sprites_list.add(rugby)

    # ALL GAME LOGIC SHOULD GO ABOVE THIS COMMENT

    # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT

    # Clear the screen and add new images
    if level == 1:
        screen.fill(WHITE)
        screen.blit(background, (0, 0))
        message = font.render("Easy Peasy" , True, RED)
        screen.blit(message, [300, 10])
    elif level == 2:
        screen.fill(WHITE)
        screen.blit(background2, (0, 0))
    elif level == 3:
        screen.fill(WHITE)
        screen.blit(background3, (0, 0))
    elif level == 4:
        screen.fill(WHITE)
        screen.blit(background4, (0, 0))
    elif level == 5:
        screen.fill(WHITE)
        screen.blit(background5, (0,0))
    else:
        pygame.quit()

    # Draw all the spites
    all_sprites_list.draw(screen)

    text = font.render("Score: " + str(score), True, BLACK)
    screen.blit(text, [10, 10])

    text = font.render("Level: " + str(level), True, BLACK)
    screen.blit(text, [10, 40])

    # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

    # Limit to 60 frames per second
    clock.tick(60)

pygame.quit()

A: The player doesn't move because you don't call the update method in the application loop:
while not done:
    # [...]

    player.update()


text:
Q: Proving resolution inference rule without truth table I came across resolution inference rule stating:

$((p\lor q)\land (\lnot p\lor r))\rightarrow(q\lor r)$

I googled a lot but what I get is either the proof using truth table or using this to prove others.
Then I tried something like this:
$LHS \equiv (p\lor q)\land (\lnot p\lor r)$
$\equiv (p\land \lnot p)\lor(p\land r)\lor (q\land \lnot p)\lor (q\land r)$
$\equiv (p\land r)\lor (q\land \lnot p)\lor (q\land r)$
But I cannot move further.
I also tried to prove the whole statement to true:
$(p\lor q)\land (\lnot p\lor r) \leftrightarrow (q\lor r)$
$\equiv \lnot((p\lor q)\land (\lnot p\lor r)) \lor (q\lor r)$
$\equiv \lnot(p\lor q)\lor \lnot(\lnot p\lor r) \lor (q\lor r)$
$\equiv (\lnot p\land \lnot q)\lor (p\land \lnot r) \lor (q\lor r)$
But I am unable to solve this further to equate this to TRUE. Where I am going wrong?

A: Resolution is not an equivalence.
The easiest way to derive it is to use the tautological equivalence between : $A \to B$ and $\lnot A \lor B$.
Thus :

$(p∨q)∧(¬p∨r)$

is equivalent to :

$(\lnot q \to p) \land (p \to r).$

Then, applying Hypothetical syllogism, we get :

$\lnot q \to r$

i.e. : $q \lor r$.

A: Using the equivalences $A\lor B\equiv \neg A \to B$ and $\neg \neg A \equiv A$, your formula

$((p\lor q)\land (\lnot p\lor r))\rightarrow(q\lor r)$

is equivalent to:
$$
((\neg p\to q)\land (p \to r)) \to (\neg q\to r)\text{,}
$$
But $(\neg p\to q) \equiv (\neg q\to p)$, so the above formula is equivalent to:
$$
((\neg q\to p)\land (p \to r)) \to (\neg q\to r)\text{.}
$$
This should be straightforward to prove. Details on request.

A: Here is a proof of the resolution inference rule using a Fitch-style proof checker and
introduction and elimination rules:

Kevin Klement's JavaScript/PHP Fitch-style natural deduction proof editor and checker http://proofs.openlogicproject.org/


text:
Q: How to setup Elixir on Sublime Text 3 Hi I'm brand new to Elixir, haven't even ran a code yet. But I've downloaded it, downloaded the appropriate packages on sublime, restarted sublime and it doesn't work. And when I save a .ex file it doesn't get a logo, opposed to a .py file that gets the python logo. So I don't know if Sublime can't find the Elixir program, should it be added to my path? I don't know what to do here, and would love some help as I'm sitting in the dark, and can't find much support since Elixir isn't as widely used. And I'm really depending on this for a job opportunity. I appreciate any and all help!

A: I've installed following plugins in Sublime: Elixir, Elixir Sublime and ElixirSyntax.
File should be saved as .exs in order to be recognized by Sublime.
In case autocomple plugin does not work for you be sure that in Preferences/Settings the key "auto_complete" is set to true


text:
Q: Enqueue makes no difference in Symfony/Elasticsearch index creation In a Symfony 4.3 application with Elastcsearc 6.8 plus  friendsofsymfony/elastica-bundle v5.1.0
an index creation task takes 18 minutes to complete either with or without enqueue/enqueue-bundle 0.9.12 and enqueue/fs 0.9.12. Is there a package I'm missing (altho' enqueue says it's a complete solution) or a configuration error?
fos_elasitica.yaml:
fos_elastica:
    serializer: ~
    clients:
        default: { host: localhost, port: 9200 }
    indexes:
        house_date:
            types:
                house_date:
                    serializer:
                        groups: [house_date]
                    persistence:
                        # the driver can be orm, mongodb or phpcr
                        driver: orm
                        model: App\Entity\Contact
                        provider: ~
                    finder: ~

enqueue.yaml:
enqueue:
    default:
        transport: '%env(resolve:ENQUEUE_DSN)%'
        client: ~
enqueue_elastica:
    transport: '%enqueue.default_transport%

'
Edit:
After much exploration I've inched along but without ultimate success. Added was enqueue/elastica-bundle and enqueue.yaml has been edited to appear as above.
[An identical installation in Windows reaches a 256M memory limit at about 54% completion, again regardless of the presence of the enqueue components.]

A: It is likely true that the seemingly long time to populate the index was the result of an improper definition. The definition incorporated four entities (via relationships). By changing Contact to Household, which has a one to many relationship with Contact, time to populate the index was reduced was reduced by a factor of 10. As a result I'm abandoning this question and marking it Answered.


text:
Q: setAuthConfig() vs setAuthConfigFile() in the Google OAuth2.0 API While reading the online Google OAuth2.0 documentation, I have seen:
This:
$client->setAuthConfigFile('secret_keys.json');
And this:
$client->setAuthConfig('secret_keys.json');
They are being used in the same situations and I would like to know if there is any difference between them, or if I shall stick to use one of them always.

A: Use setAuthConfig.
setAuthConfigFile is now just an alias for backwards compatibility and is deprecated.
setAuthConfigFile just calls setAuthConfig
Refer to this. https://github.com/google/google-api-php-client/blob/master/src/Google/Client.php and search for public function setAuthConfigFile($file)


text:
Q: jqPlot MeterGaugeRenderer - set diameter causes error I am showing multiple Meter Gauges on a single page, in conjunction with Bootstrap, to provide responsiveness. What is obvious is they are all calculating slightly different sizes, so I hoped to use diameter.
Here is my working code:
    s1 = [322];
$.jqplot('spend',[s1],{
    seriesDefaults: {
        renderer: $.jqplot.MeterGaugeRenderer,
        rendererOptions: {
           min: 100,
           max: 500,
           intervals:[200, 300, 400, 500],
           intervalColors:['#66cc66', '#93b75f', '#E7E658', '#cc6666'],
           intervalOuterRadius: 56,
           ringColor: '#222',
           padding: 3,
           tickColor: '#111',
           ringWidth: 4,
           needleThickness: 11,
           shadowOffset: 10,
           label: "£"
        }
    },
    title: 'Spend'
});

If I add
diameter:200,

I get no output, and:
'this._center.0' is null or not an object  jqplot.meterGaugeRenderer.js, line 616 character 13
'this._center.0' is null or not an object  jqplot.meterGaugeRenderer.js, line 616 character 13

I have also tried
diameter:50,

and
diameter:500,

in case I was not providing adequate space, or too much space, but I rather doubt it, as intervalOuterRadius is set at 56, I have also assumed that
diameter:200

is correct syntax given that
intervalOuterRadius:56

(as well as various other values) is correct. I cannot find anyone else who has had this problem, and have had no response on the jqplot google group.
Oh yeah, and I'm primarily writing for IE8 atm but it will need to be used on ie11 in time.


text: Q: Слишком много кода в VIPER? Здравствуйте. Я просмотрел много репозиториев с исходным кодом приложений, построенных по VIPER и прочитал пару статей про VIPER. Решил использовать его в своем новом проекте. Проект я почти закончил, но как мне показалось, при постронии приложения по VIPER, увеличивается количество кода и довольно ощутимо. Приложение небольшое (всего три экрана и две модельки), но кода получилось многовато. Еще один минус - огроменные конструкторы классов, для передачи в них интеракторов, репозиториев и т. д. Из плюсов можно отметить довольно легкое написание unit-тестов. Сейчас я задумался, а стоит ли вообще использовать его в своих будущих проектах? Поэтому вопрос такой: кто использует VIPER в своих проектах? Если не VIPER, то что используете вы и почему? Возможно ли построить по методологии VIPER действительно большое приложение? Например, мой следующий проект - электронная библиотека с магазином и читалкой электронных книг EPUB.


text:
Q: Error in indval (labdsv) in R - "All species must occur in at least one plot" I ran the following Indicator Species Analysis (indval) code from labdsv package in R on a dataframe called "data" where species abundances are columns and sites are rows as below:
     Site    Species X  Species Y  Species Z etc
     1       10         3          5
     2       5          15         220
     3       0          1          0
     4       21         100        3

In a separate file is the corresponding Group data for each site which is either group 1 or group 2 (called this spe.grp), that is the following:
    Groups
    1
    2
    1
    2

I removed categorical variables so that spe.only has only the species data
   spe.only <- data[,2:1521]

I then removed species which do not occur in any sample
   spe.only[, (!apply(spe.only==0,2,all))]

I then ran Indicator species based on Groups (1) or (2)
  (iva <- indval(spe.only, spe.grp$Groups))

But I get

"Error in indval.default(spe.only, spe.grp$Status) :    All species
must occur in at least one plot"

How do I resolve this error so that I can run indval correctly?

A: The step
spe.only[, (!apply(spe.only==0,2,all))]

was not assigned back to the original object  i.e. if we don't assign it back it, the output from the above step only prints on the console and not updates the original object
spe.only <- spe.only[, (!apply(spe.only==0,2,all))]

Now do the indval
> library(labdsv)
> indval(spe.only, spe.grp$Groups)
$relfrq
           1 2
SpeciesX 0.5 1
SpeciesY 1.0 1
SpeciesZ 0.5 1

$relabu
                  1         2
SpeciesX 0.27777778 0.7222222
SpeciesY 0.03361345 0.9663866
SpeciesZ 0.02192982 0.9780702

$indval
                  1         2
SpeciesX 0.13888889 0.7222222
SpeciesY 0.03361345 0.9663866
SpeciesZ 0.01096491 0.9780702

$maxcls
SpeciesX SpeciesY SpeciesZ
       2        2        2

$indcls
 SpeciesX  SpeciesY  SpeciesZ
0.7222222 0.9663866 0.9780702

$pval
SpeciesX SpeciesY SpeciesZ
   0.678    0.319    0.671

The error is reproducible on the original 'spe.only' object
> indval(spe.only, spe.grp$Groups)
Error in indval.default(spe.only, spe.grp$Groups) :
  All species must occur in at least one plot

data

spe.only <- structure(list(SpeciesX = c(10L, 5L, 0L, 21L), SpeciesY = c(3L,
15L, 1L, 100L), SpeciesZ = c(5L, 220L, 0L, 3L), SpeciesD = c(0,
0, 0, 0)), row.names = c(NA, -4L), class = "data.frame")

spe.grp <- structure(list(Groups = c(1, 2, 1, 2)),
class = "data.frame", row.names = c(NA,
-4L))


text:
Q: MySQL: select last full 5 minute interval I want to select from my table the last full 5 minute interval.
Example:

*

*Time now: 09:32 am --> select --> 09:25 - 09:30 am

*Time now: 10:44 pm --> select --> 10:35 - 10:40 pm

I know how to group my select into 5 minute intervals
date_sub(date_sub(starttime, INTERVAL (MINUTE(starttime) % 5) MINUTE), INTERVAL (SECOND(starttime)) SECOND) as INTERVAL_START,
   date_add(date_sub(date_sub(starttime, INTERVAL (MINUTE(starttime) % 5) MINUTE), INTERVAL (SECOND(starttime)) SECOND), INTERVAL 5 MINUTE) as INTERVAL_END,

I also know how to select the last 5 minutes
where  (endtime between now()-Interval 5 minute and now())

But how do I get the last full 5 minute interval like shown in the example above?

A: If you just want to limit the result set to records happening within 5 minutes of the most recent endtime then you can try the following:
SELECT *
FROM yourTable
WHERE endtime > (SELECT MAX(endtime) FROM yourTable) - INTERVAL 5 MINUTE

A: Your question is still not very clear as you didn't mention expected output based on your input. However, you can use this code to get start_time and end_time based on now(). Change now() as per your requirement.
select
date_sub(str_to_date(concat(hour(now()),':',floor(minute(now())/5)*5),'%H:%i'),interval 5 minute) as start_time,
str_to_date(concat(hour(now()),':',floor(minute(now())/5)*5),'%H:%i') as end_time,
now();

Explanation: First divide the minutes by 5, then take the floor(remove decimal) and multiply it by 5. This will give you nearest end time. Subtract 5 minutes from it to get start_time.

A: You were close:
WHERE endtime > date_sub(now(), interval 3 minute);

A: use
select ceil(minute(now())/5) as `x`

You will get x (1-12), after that just multiply it by 5
if we are are "32" then x = 7 (32/5 = 6.x => 7)
between ((x-1)*5) and (x*5)    = (7-1)*5 and 7*5 = 30-35

=== added ====
just concat it into an hour

A: I think I got it:
select
   a.end_time - Interval 5 minute as start_time,
   a.end_time
from
   (
    select
      str_to_date(concat(date(now()), ' ', hour(now()),':',floor(minute(now())/5)*5),'%Y-%m-%d %H:%i') as end_time
  ) a

Result


text:
Q: eclipse not running maven build using keyboard shortcuts I have observed this in Spring tool suite as well as with Eclipse.
If I fire up the IDE - I cannot use shortcuts to run maven build.
( alt + shift + X + M )
The context menu shows up and it also seems as if the build has been fired - but console indicates that it has not.
To get around this - the first time eclipse is loaded - I do the build manually ( right click on project - Run as - maven install )
Note once I do this - the keyboard shortcuts to build work fine .
Is this a bug or an incorrect user understanding ?


text:
Q: Mochizuki's Gaussian Integral Analogy In his latest 115-page overview, Mochizuki spends some time explaining "alien copies" by the analogue of evaluating the Gaussian integral by squaring it and introducing a second variable/dimension. In sections 1.1 to 1.7 (pages 5-10) he goes through this, and then in section 3.8 (pages 89-94) he revisits the analogy.
I have two questions about this. Firstly, one gets that $I^2=(\int_{-\infty}^\infty e^{-x^2}\,dx)^2=\pi$, and by positivity one finds $I=\sqrt\pi$. What is the analogue in the IUT setting of "positivity" here? Do the choices up to a unit not matter somehow?
Secondly, I wonder about the scope of alien copies. At the end of the day, if I read 3.8 correctly in #10 and #11 in the table on page 92 and the computations in 3.7(iv) (page 89), the main result of the analogy is to evaluate (to first order) the left side of the inequality at the top of page 87.
So my question is: are alien copies "only" useful for this Gaussian-like evaluation, or do they play a role throughout? (NB: the word "alien" does not appear in the text from pages 22-90.) Alternatively, do they also enlighten the derivation of the inequality (see 3.7(ii) starting on page 85) in the first place, or the estimation of its right side?
Since no one has answered yet, maybe I'll add a third question. In 2.2 on page 11, a distinction (quite important I gather) between étale-like and Frobenius-like structures is made, the former being "zero mass" objects, such as (1.4) the differentials "$dx\,dy$" in the Gaussian evaluation. Are there Frobenius-like structures with the Gaussian analogue, and if so, what are they?

A: For all the similarities, there's a significant difference between both parts of the analogy.
In the IUT side of the analogy, we are trying to compare the "mutually alien copies" at each end of the $\Theta$-link
$$\{\underline{\underline{q^{j^2}}}\} \longleftrightarrow \underline{\underline{q}}\tag{1}$$
But in the case of the Gaussian integral, we are introducing the second (alien) copy in order to evaluate the first, not to compare them.
$$\bigg(\int_{-\infty}^\infty e^{-x^2}\,dx\bigg)\bigg(\int_{-\infty}^\infty e^{-x^2}\,dx\bigg)\longleftrightarrow \quad?$$
So at some point we need to reverse the process. That's not case in IUT.
To be more precise, the alien copies in question are $\Theta^{\pm\text{ell}}\text{NF}$-Hodge theaters (denoted $\bullet$ in the diagram below) in the domain/codomain of the $\Theta$-link, and the analogy is between a pair of such a Hodge theaters and one evaluation of the Gaussian integral. But there is a infinite lattice of such a pairs at work in IUT, the log-theta lattice.

This process doesn't have to be undone in any way, in order to evaluate individual elements of the lattice, the way we need to go from $I^2$ to $I$.

The "Gaussian-like evaluation" is basically the main result of IUT, so I would say that it appear throughout and at the same time it is "only" useful for this.
A different instance of the use of alien copies would be Mochizuki's theory of mono-anabelian reconstruction. In that case we have Galois theaters and $\mathfrak{log}$-Frobenius functors between them,
$$\mathfrak{log}:\mathfrak{Th}_\mathbb{T}^\bullet [Z] \longrightarrow \mathfrak{Th}_\mathbb{T}^\bullet [Z]$$
The derivation of inequality 3.7(ii) follows from $(1)$ and the Kummer isomorphisms [IUTechIII Theorem A, (ii)], which yield
$$-|\log (\underline{\underline{\Theta}})| \leq -|\log (\underline{\underline{q}})|$$
All of this involves of course the log-theta lattice (i.e. the "alien copies").

I think the analogy is supposed to be something like this:
$$\text{zero mass} \longleftrightarrow \text{étale-like} \longleftrightarrow dx\,dy$$
$$\text{positive/net mass} \longleftrightarrow \text{Frobenius-like} \longleftrightarrow \lim \sum dx\,dy$$


text:
Q: Is there a way in just HTML/JavaScript to get a "Switched" UserAgent from the header rather than navigator object I was just wondering as this code is in pure HTML with some JavaScript that gets me my current IP addresses (using jQuery AJAX call to a IPv4/v6 site) and also gets me my useragent.
However as it's all JS, I get the UA from the Navigator object rather than the headers, and using an agent switcher extension it changes the UA when I call a page that outputs the headers server side say with a google search of "what is my user-agent", but my page just gets the ua from the navigator object and it is always the true UserAgent never the switched one e.g
let ua= navigator.userAgent;
document.querySelect('#UA').innerHTML = "UserAgent: <b>" + ua + "</b>";

Is there a way to get the header / switched agent as well as or instead of the way I am getting at the moment?


text:
Q: How to find the maximum value in a row in plpgsql? I am having the following table

Student Id
Subject A
Subject B
Subject C
Subject D

1
98
87
76
100

2
90
100
64
71

This table contains information about the marks scored by students in various subject.
Now I need to find the maximum mark scored by each student among the various subject
I need the output to be like

Student Id
Subjects
Maximum Mark

1
Subject D
100

2
Subject B
100

A: This would need a lateral join with the list of subject/mark from the corresponding columns. This works for any number of Subject X columns.
select ext."Student Id", l.*
from the_table ext, lateral
(
   select l.key, l.value::numeric
   from the_table t, lateral json_each_text(to_json(t)) l(key, value)
   where "Student Id" = ext."Student Id" and l.key like 'Subject%'
   order by l.value::numeric desc limit 1
) l;

DB-Fiddle demo


text:
Q: How to determine the value of an SMD coil? I am trying to repair one PCB where an SMD coil seems to be burned out.
I would like to replace this component, but I have no idea about how to determine the value of this SMD device, because it is not marked.
How can I get this value?

A: You could make an estimate by measuring the package size using calipers and then searching digikey to see what is the most popular value for that package size.  Err on the side of using a value that is too large.
Also, you could follow the traces to see what IC it is connected to, and then look at the reference schematic in the datasheet of that IC and see if it recommends an inductor value.


text:
Q: Html.Actionlink passing null values to controller I have this method in my controller called "DirectorySearchController"
public ActionResult PersonDetails(FoundPerson person) //for some reason person is null here
{
    DirectoryViewModel viewModel = new DirectoryViewModel();
    viewModel.person = person;
    return View(viewModel);
}

When I pass some parameters to it from the view using Html.Actionlink it returns a null value

    @if (ViewBag.Message == "NO RESULTS FOUND")
    {

@ViewBag.Message

    }
    else
    {
            foreach (var employee in Model)
            {

@Html.ActionLink(employee.name, "PersonDetails", "DirectorySearch", new { person = employee}, null)

            }
    }

But the funny thing is that when I pass the parameter without using the "new" keyword it passes the correct value. However, the problem is I need to pass multiple parameters so I need to use the "new" keyword.

@Html.ActionLink(employee.name, "PersonDetails", "DirectorySearch", employee, null)

A: I think you are not using the correct overload of ActionLink.  Try with either of these
The first one should mostly work according to your case:
<%=Html.ActionLink(employee.Name, "PersonalDetails", "DirectorySearch", new { person = employee }, null)%>

<%=Html.ActionLink(employee.Name, "PersonalDetails", new {person = employee})%>

Just a recommendation here.  Ideally I'd use an Input submit to post the data to the Controller.  You may either use a Model class OR FormCollection in the controller side to retrieve the values you entered in the View.

A: You should not pass model to the controller action like new { person = employee } in Html.ActionLink. Because what happens is, when you generate the action link the object you pass is converted into RouteValueDictionary which will be passed to the UrlHelper to append the route dictionary values to the link.
When you pass an anonymous object like in the first case the RouteValueDictionary stores a single parameter with name person and to set the value it sees that you have passed an object, it can't serialize the complete instance and set it to the single property so all it does is set the type name of the model Employee as the value to the person. So you will see the generated link as http://someserver/DirectorySearch/PersonDetails?person=Models.Employee
If you pass an instance like you did in the second case then it iterate all the properties and create key/value pairs, while the keys are the property names and the values are the property values, finally they all appended to the link as querystrings. In the case the generated url will be http://someserver/DirectorySearch/PersonDetails?Property1=Value1&Property2=Value2
Correct
@Html.ActionLink(employee.name, "PersonDetails", "DirectorySearch", employee, null)

Wrong
@Html.ActionLink(employee.name, "PersonDetails", "DirectorySearch", new {person = employee }, null)

You can use anonymous object to pass route parameters to the action link but at the time you should not pass reference types but built-in types like integer, string..
Ex.
@Html.ActionLink(employee.name, "PersonDetails", "DirectorySearch",
new { Id = 23, Name = "Mark" }, null)


text:
Q: How to access Application class variables in activity in kotlin android
*

*I used to access application class private variables by using a
public methods in java

*How to do the same using kotlin

App.kt
class App : Application() {

    private var app: App? = null
    private var movieAppComponent: MovieAppComponent? = null

    override fun onCreate() {
        super.onCreate()
        app = this

        movieAppComponent = DaggerMovieAppComponent.builder()
            .applicationModule(ApplicationModule(this))
            .netModule(NetModule(Keys.BASE_URL, this))
            .build()
    }

    fun getApp(): App? {
        return app
    }

    fun getMovieAppComponent(): MovieAppComponent? {
        return movieAppComponent
    }

}

MainActivity.kt
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
         setContentView(R.layout.activity_main)
        App.getApp().getMovieAppComponent().inject(this)
    }

}

Error:
App.getApp().getMovieAppComponent().inject(this)

Here getApp() i am getting as unresolved reference

A: Solution 1:
class App : Application() {

    private var movieAppComponent: MovieAppComponent? = null

    companion object {
        private var app: App? = null

        fun getApp(): App? {
            return app
        }
    }

    override fun onCreate() {
        super.onCreate()
        app = this

        movieAppComponent = DaggerMovieAppComponent.builder()
            .applicationModule(ApplicationModule(this))
            .netModule(NetModule(Keys.BASE_URL, this))
            .build()
    }

    fun getMovieAppComponent(): MovieAppComponent? {
        return movieAppComponent
    }
}

Solution 2:
No need to create such method. You can use type casting in your Activity:
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
         setContentView(R.layout.activity_main)
        (application as? App)?.getMovieAppComponent()?.inject(this)
    }
}


text:
Q: Cannot run escaped Windows command line on python When I run the following command on a Windows command prompt, no problem.
java -jar "C:\Program Files (x86)\SnapBackup\app\snapbackup.jar" main

I tried running the command in a python script. It fails. My python script is like this;
import os
command_line = 'java -jar "C:\Program Files (x86)\SnapBackup\app\snapbackup.jar" main'
os.system(command_line)

The error message received is

Error: Unable to access jarfile C:\Program Files
  (x86)\SnapBackuppp\snapbackup.jar

Can someone help? Thanks.
I am using python 2.7.9

A: Try this:
command_line = 'java -jar "C:\\Program Files (x86)\\SnapBackup\\app\\snapbackup.jar" main'

Explanation
Windows uses backslashes ("\") instead of forward slashes ("/"). This isn't an issue when using the Windows command line itself, but causes problems when using other tools that process escape sequences. These escape sequences each start with a backslash. Typically, strings in Python process them.
https://docs.python.org/2/reference/lexical_analysis.html#string-literals
If you look closely at your error...

Error: Unable to access jarfile C:\Program Files (x86)\SnapBackuppp\snapbackup.jar

...you'll notice that it says SnapBackuppp, instead of SnapBackup\app
What happened?
The "\a" was being processed as the ASCII Bell (BEL) escape sequence (see link above). The other characters with a backslash in front of them weren't affected, because they don't correspond to an escape sequence. (That is, the \P in C:\Program Files (x86), etc.)
To avoid processing the \a as the Bell character, we need to escape the backslash itself, by typing \\a. That way, the second backslash is treated as a "normal" backslash, and the "a" gets read as expected.
You can also tell Python to use a raw (unprocessed) string by doing this:
command_line = r'java -jar "C:\Program Files (x86)\SnapBackup\app\snapbackup.jar" main'
(Note the r just before the first quote character.
Alternatively, you could also use forward slashes.
command_line = 'java -jar "C:/Program Files (x86)/SnapBackup/app/snapbackup.jar" main'
However, this may not work in all cases.

A: You should probably use subprocess instead of os.system https://docs.python.org/2/library/subprocess.html.  Also, like others before me have noted, you have unescaped backslashes.  Use os.path.join to remedy the situation:
import subprocess, os
jarPath = os.path.join('c:', 'Program Files (x86)', 'SnapBackup', 'app', 'snapbackup.jar')
command_line = ['java', '-jar', jarPath, 'main']
subprocess.call(command_line)

A: You are using backslashes in the command line. In python better use forward slashes or escape the backslashes with a backslash


text:
Q: Adjustable sharpen color matrix I am using .NET AForge libraries to sharpen and image. The "Sharpen" filter uses the following matrix.
 0  -1   0
-1   5  -1
 0  -1   0

This in fact does sharpen the image, but I need to sharpen the image more aggressively and based on a numeric range, lets say 1-100.
Using AForge, how do I transform this matrix with numbers 1 through 100 where 1 is almost not noticeable and 100 is very noticeable.
Thanks in advance!

A: The one property of a filter like this that must be maintained is that all the values sum to 1. You can subtract 1 from the middle value, multiple by some constant, then add 1 back to the middle and it will be scaled properly. Play around with the range (100 is almost certainly too large) until you find something that works.
You might also try using a larger filter matrix, or one that has values in the corners as well.
I would also suggest looking at the GaussianSharpen class and adjusting the sigma value.


text:
Q: JHipster new module : cannot add translation I have added a new module with several components inside JHipster. I would like so add the translation in the html part with the JHipsterTraslationService and tried to do it but I do not know. I think I have to suscribe to the new service but I don't know how.

A: Jhipster use jhiTranslate in the html, for example: <label class="form-control-label" jhiTranslate="myApp.myComponent.myWelcome">My default welcome text</label>,
this refers to the value of the field in your translation .json file, it will look for it in that file and replace it with the value it has. Otherwise, it will show the value, "My default welcome text".
When you create a component with jhipster using angular cli, the translation files are created in each language folder of your application.(example: myApplicationName\src\main\webapp\i18n\en)
This is the example they put in their documentation (Generating Components, Directives, Pipes and Services) for create components:
ng generate component my-new-component
ng g component my-new-component # using the alias

# Components support relative path generation
# Go to src/app/feature/ and run
ng g component new-cmp
# your component will be generated in src/app/feature/new-cmp
# but if you were to run
ng g component ../newer-cmp
# your component will be generated in src/app/newer-cmp

I believe that it is easy and better to use this method of creation, because it will create all the necessary files, be it a component, service, directive, route, etc.
Additionally, if you have already created the components, you will have to manually create each .json file in its corresponding folder according to the languages of your application. You can also add another language to your application (How to add languages after project generation?).
Other way.... U can try add other language, with the generator. And check that files was added and what change, with this u can know what files or subscriptions can change.
I hope this helps. ;)


text:
Q: Why is "null" treated as string here in the below code and is concatenated to the name of the file? I have a method to check the operating system type and return a suitable path according to the type of OS. This path is used by another method which accepts this path and saves a file to t
hat location. Now if the OS is not Windows, Linux or Mac then the method returns null. The problem is that this null is treated as a string and null gets added to the name of the saved file e.g; nullFile.txt and saves it in the location where the program is stored.
What can I do to prevent this from happening?
public static String checkOS() {
    String store = "";
    String OS = System.getProperty("os.name").toLowerCase();
    if(OS.indexOf("win") >= 0){
        store = "C:/";
    } else if(OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 ){
        store = "/home/";
    } else  if(OS.indexOf("mac") >= 0){
        store = "/home/";
    } else{
        return null;
    }
    return store;
}

A: You don't show the code, but you're probably doing
String filename = checkOS() + "File.txt";

In String concatenation, null values are converted to the string "null", so you have to code an explicit null check.
String osName = checkOS();
String fileName;
if (osName == null)
    // do whatever you need to do
else
    filename = checkOS() + "File.txt";

As to the option of returning an empty string from checkOS instead of null, that is a possibility but in either case the caller of checkOS is going to need to test the result as I'm sure you want to do something different for that case.    A null return is the most generic option.


text:
Q: Style in inline HTML not working? Below is the code for selected option in HTML which is working:
<!DOCTYPE html>
<html>
<head>
<style>
.Orange{color:Orange;}
.Red{color:Red;}
.Green{color:Green;}
</style>
</head>
<body>

<SELECT id='select' NAME='select' class="form-select" OnChange='this.className=this.options[this.selectedIndex].className' style='font-family : Arial; font-size : 10px; '>
<OPTION CLASS = 'null' VALUE='' TITLE='' style = 'color:null' SELECTED>
<OPTION CLASS = 'Red' VALUE='108R675' TITLE='Red'  >Red
<OPTION CLASS = 'Green' VALUE='108R723' TITLE='Green' >Green
<OPTION CLASS = 'Green' VALUE='108R725' TITLE='Green' >Green
<OPTION CLASS = 'Orange' VALUE='108R726' TITLE='Orange' >Orange
<OPTION CLASS = 'Green' VALUE='109R642' TITLE='Green' >Green
<OPTION CLASS = 'Orange' VALUE='109R754' TITLE='Orange' >Orange </SELECT>

</body>
</html>

But I want to use the style within Selected tags along with font size and family. But if I do that the color style is not working.
I am trying like this;
<!DOCTYPE html>
<html>
<head>
</head>
<body>

<SELECT id='select' NAME='select' class="form-select" OnChange='this.className=this.options[this.selectedIndex].className' style='font-family : Arial; font-size : 10px; .Orange{color:Orange;}.Red{color:Red;}.Green{color:Green;}'>
<OPTION CLASS = 'null' VALUE='' TITLE='' style = 'color:null' SELECTED>
<OPTION CLASS = 'Red' VALUE='108R675' TITLE='Red'  >Red
<OPTION CLASS = 'Green' VALUE='108R723' TITLE='Green' >Green
<OPTION CLASS = 'Green' VALUE='108R725' TITLE='Green' >Green
<OPTION CLASS = 'Orange' VALUE='108R726' TITLE='Orange' >Orange
<OPTION CLASS = 'Green' VALUE='109R642' TITLE='Green' >Green
<OPTION CLASS = 'Orange' VALUE='109R754' TITLE='Orange' >Orange </SELECT>

</body>
</html>

Any idea?

A: The style attribute is being used incorrectly.
This is what you have:
<SELECT id='select'
        NAME='select'
        class="form-select"
        OnChange='this.className=this.options[this.selectedIndex].className'
        style='font-family : Arial; font-size : 10px;
              .Orange{color:Orange;}.Red{color:Red;}.Green{color:Green;}'>

You can only insert styles in the style attribute. You're including selectors (the classes). That's invalid.

3. Syntax and
  Parsing
The value of the style attribute must match the syntax of the contents
  of a CSS declaration block (excluding the delimiting braces).

Use the head section of the document or an external stylesheet to define selectors.
<head>

<style>

  .Orange{color:Orange;}
  .Red{color:Red;}
  .Green{color:Green;}

</style>

</head>

A: Keep the styles for the colors in the <head><style> tag. You can not use the style attribute of an element to define CSS classes. Font-family etc. will be inherited from the parent element, so the <option> will inherit the font from the <select>.

A: First Of all Style attribute inline html tag are not used proper
if u want to use class then use other type of CSS like internal, and external
you do not use class inside inline style attribute
<SELECT id='select'
        NAME='select'
        class="form-select"
        OnChange='this.className=this.options[this.selectedIndex].className'
        style='font-family : Arial; font-size : 10px;
              .Orange{color:Orange;}.Red{color:Red;}.Green{color:Green;}'>

BUT YOU CAN USE IT BELOW METHOD
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
      .Orange{color:Orange;}
      .Red{color:Red;}
      .Green{color:Green;}
</style>
</head>
<body>

<SELECT id='select'
    NAME='select'
    class="form-select Orange Red Green"
    OnChange='this.className=this.options[this.selectedIndex].className'
    style='font-family : Arial; font-size : 10px;'>

</body>
</html>

A: In style tag you cannot include classes:
style='font-family : Arial; font-size : 10px; .Orange{color:Orange;}.Red{color:Red;}.Green{color:Green;}'

That is the reason it is not working.

<!DOCTYPE html>
<html>
<head>
<style>
.Orange{color:Orange;}.Red{color:Red;}.Green{color:Green;}
</style>
</head>
<body>

<SELECT id='select' NAME='select' class="form-select" OnChange='this.className=this.options[this.selectedIndex].className' style='font-family : Arial; font-size : 10px;'>
<OPTION CLASS = 'null' VALUE='' TITLE='' style = 'color:null' SELECTED>
<OPTION CLASS = 'Red' VALUE='108R675' TITLE='Red'  >Red
<OPTION CLASS = 'Green' VALUE='108R723' TITLE='Green' >Green
<OPTION CLASS = 'Green' VALUE='108R725' TITLE='Green' >Green
<OPTION CLASS = 'Orange' VALUE='108R726' TITLE='Orange' >Orange
<OPTION CLASS = 'Green' VALUE='109R642' TITLE='Green' >Green
<OPTION CLASS = 'Orange' VALUE='109R754' TITLE='Orange' >Orange </SELECT>

</body>
</html>

Try adding as shown in snippet.


text:
Q: ViewPager not showing anything Please, advice. I can't get ViewPager working. Here is what I'am doing:
1) This is my LinearLayout in which I will put the ViewPager. I'am sure that it's work. I can put any View in it:
<LinearLayout
    android:id="@+id/view_contact_values_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/view_contact_sub_nav"
    android:orientation="vertical"
    android:paddingLeft="10dip" >
</LinearLayout>

2) Next I'm creating the ViewPager in code:
private void createViewPager() {
    ViewPager viewPager = new ViewPager(this);
    DatesPagerAdapter datesPagerAdapter = new DatesPagerAdapter(this);
    viewPager.setAdapter(datesPagerAdapter);
    viewPager.setCurrentItem(1);
    llContainer.addView(viewPager);
}

3) And the ViewPagerAdapter (PagerAdapter):
@Override
public Object instantiateItem(ViewGroup container, int position) {
    LayoutInflater inflater = (LayoutInflater) container.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View v = inflater.inflate(R.layout.dates_carusel_item, null);
    ((ViewPager) container).addView(v, 0);
    return v;
}

@Override
public int getCount(){
    return 5;
}

But when I open my Activity, there is nothing showing in my LinearLayout.
P.S.: Sorry for the bad question styling. Code tag in this editor is strange.

A: Take a class extending Fragemnt
class ExampleFragment extends Fragment
{
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.dates_carusel_item, null);
  return v;
}

And in your PagerAdapter do this
    private class DatesPagerAdapter extends FragmentPagerAdapter
{
    public DatesPagerAdapter(FragmentManager fm) {
        super(fm);
    }
    @Override
    public Fragment getItem(int arg0) {
        ExampleFragment fragment=new ExampleFragment();
        Bundle bundle=new Bunlde();
        //put bundle data here
        fragment.setArguments(bundle);
        return fragment;
    }
    @Override
    public int getCount() {
        5;
    }
}

Whatever view you want to set do it on the Example Fragment and add your viewPager
ViewPager pager=new ViewPager(this);
pager.setAdapter(new DatesPagerAdapter);
llContainer.addView(pager)

Add your ViewPager in xml itself to get it proprly alligned or else you can setLayoutParams in runtime if its a visibilty error
     android:layout_width="match_parent" android:layout_height="wrap_content"      android:orientation="vertical" android:layout_below="@id/view_contact_sub_nav"android:id="+id/view_contact_values_container"
android:paddingLeft="10dip">
<android.support.v4.view.ViewPager
    android:id="@+id/imagesgallery"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />
</LinearLayout>


text:
Q: Using UDP sockets to receive data I am writing an application and I don't understand a point. I am trying to receive data from a specific client. In a TCP socket, accept returns to you an fd number, so you can communicate over this fd number with a specific client.
In recvfrom, anything cannot specify that receive data from that client. It receives data from everyone who sent. I am trying to solve this, but I am not sure how to do this.
The second problem is that, after opening a socket, I open other socket. I send second socket number to client, and client sends second data on this second socket. In server side, the server listens to the first socket (not the second socket). But although client sends data from the second socket and the server listens to the first socket, server takes data. I print two socket as integer and see that two are different. How can the server read data that is sent on second socket, on the first socket?

Yeah, my question is a bit complicated. Basically I say:
recvfrom(sock, &client, sizeof(Client), MSG_WAITALL, (struct sockaddr *)&clientAddr2, &size);

How can tell a specific client (say client 2) to listen in the line above? (in TCP sockets, it is done by fd number, but how it is in UDP socket?).

A: Accept isn't used with udp. You call socket, you call bind to establish the port, you call sendto and recvfrom.
I'm afraid that I can't follow your description very well, but I hope this helps.
TCP and UDP are distinct and not compatible protocols. UDP clients and servers talk to each other, TCP clients and servers talk to each other. Hypothetically, you could use a RAW socket to talk to TCP on the other side, but you'd have to have a complete TCP protocol implementation.
UDP has no connections. If you have a concept of different clients, you have to sort them out with data you put inside the packets.

A: If I understand what you are looking for, you would need to bind each socket on the server to a different port number.  Then the client would need to send to the desired port.
However, it may not be necessary to do that.  The server could examine the address that is supplied via the recvfrom() call and associate it with the appropriate client and process it (e.g., via a worker thread) according to which client sent it.

A: I don't think you can use UDP to communicate with TCP. UDP is not a super set of TCP. They are two different protocols of the same layer. For more info try this page
When you open two sockets to the same port in a computer, you are not guaranteed that both sockets will receive the data. In fact, in my experience only the first socket will.


text:
Q: mysql php - latin1? I have a mysql table, I made it in latin1 style and it is all that way.  How can I make a table that is all latin1 except one column, which i need to be able to accept chinese characters?
Also, Whats the best structure for a column with chinese characters?

A: alter table your_table
modify column
chinese_column varchar(255) collate utf8_general_ci; <-- or any relevant collate

details can be found here


text:
Q: Mapping a function on two nested objects I am trying to map a function dplyr::mutate on two sets of nested tibbles contained in a data set. My goal is to add new columns to each tibble nested in db$data.y by using the corresponding coefficients in the nested tibbles db$data.x.
Below, I provided a reproducible example. Each row of db refers to a different scale that we are validating. The nested tibbles in db$data.x contain the variance components that will be used to perform further calculations. The nested tibbles in db$data.y contain the same set of two columns wherein the combination of the number of occasions (from 1 to 10) and raters (from 1 to 2) is different for every row.
library(dplyr)
library(purrr)

coefficients <- data.frame(Scale = rep(1:5, each = 5),
                           Component = rep(c("R", "S", "T", "RxS", "SxT"), 5),
                           Value = rep(c(2, 4, 7, 3, 5, 5, 6, 7, 3, 5, 2, 6, 3, 6, 4, 7, 3, 7, 12, 8, 7, 11, 14, 9, 2))) %>%
                           group_by(Scale) %>% nest()

sim.data <- data.frame(Scale = rep(1:5, each = 20),
                       Occasion = rep(1:10, 2),
                       Rater = rep(1:2, each = 10)) %>%
                       group_by(Scale) %>% nest()

db <- left_join(coefficients, sim.data, by = "Scale")

#> db
# A tibble: 5 x 3
#  Scale data.x           data.y
#  <int> <list>           <list>
#1     1 <tibble [5 x 2]> <tibble [20 x 2]>
#2     2 <tibble [5 x 2]> <tibble [20 x 2]>
#3     3 <tibble [5 x 2]> <tibble [20 x 2]>
#4     4 <tibble [5 x 2]> <tibble [20 x 2]>
#5     5 <tibble [5 x 2]> <tibble [20 x 2]>

#> db$data.x[[1]]
# A tibble: 5 x 2
#  Component Value
#  <fct>     <dbl>
#1 R             2
#2 S             4
#3 T             7
#4 RxS           3
#5 SxT           5

#> db$data.y[[1]]
# A tibble: 20 x 2
#   Occasion Rater
#      <int> <int>
# 1        1     1
# 2        2     1
# 3        3     1
# 4        4     1
# 5        5     1
# 6        6     1
# 7        7     1
# 8        8     1
# 9        9     1
#10       10     1
#11        1     2
#...

The final goal is to calculate the column db$data.y$Abs for each scale for which we need to use the variance components contained in db$data.x. I could do this for each scale separately, but it seems extremely time-consuming. Is there anyone who can help with this?
db$data.y[[1]] %>%
     mutate(Abs = db$data.x[[1]][[1,2]] / db$data.y[[1]]$Occasion +
                  db$data.x[[1]][[2,2]] / db$data.y[[1]]$Rater +
                  db$data.x[[1]][[3,2]] / (db$data.y[[1]]$Occasion * db$data.y[[1]]$Rater))

# A tibble: 20 x 3
#   Occasion Rater Abs
#      <int> <int> <dbl>
# 1        1     1 13
# 2        2     1  8.5
# 3        3     1  7
# 4        4     1  6.25
# 5        5     1  5.8
# 6        6     1  5.5
# 7        7     1  5.29
# 8        8     1  5.12
# 9        9     1  5
#10       10     1  4.9

I have tried with purrr::map2 but, if I am not mistaken, it works on two columns of the same nested object, whereas in this case, I am dealing with two different nested objects. I would be happy to consider other solutions as well.

A: I think you're right that you can use map2(), but you'll need to use it within a mutate() so you can use the two nested columns as the first two arguments of that function.
You then can use your current mutate() code as the function within map2() to modify data.y.  You'll see I replace the current data.y with the modified object with the same name in the outer mutate().
Something like that would look like:
db %>%
    mutate(data.y = map2(data.x,
                         data.y,
                         ~mutate(.y, Abs = .x[[1, 2]]/.y$Occasion +
                                     .x[[2, 2]]/.y$Rater +
                                     .x[[3, 2]]/(.y$Occasion*.y$Rater))))

The first data frame looks like
db %>%
    mutate(data.y = map2(data.x,
                         data.y,
                         ~mutate(.y, Abs = .x[[1, 2]]/.y$Occasion +
                                     .x[[2, 2]]/.y$Rater +
                                     .x[[3, 2]]/(.y$Occasion*.y$Rater)))) %>%
    pull(data.y) %>%
    pluck(1)

# A tibble: 20 x 3
   Occasion Rater   Abs
      <int> <int> <dbl>
 1        1     1 13
 2        2     1  8.5
 3        3     1  7
 4        4     1  6.25
 5        5     1  5.8
 6        6     1  5.5
 7        7     1  5.29
 8        8     1  5.12
 9        9     1  5
10       10     1  4.9
...