text:
Q: How To: validate input string is an ip or a domain PHP Just share a tool and debug. Maybe usefull for someone.
TOOL:
public function ValidateIpOrHostname($inputString)
{
    $ValidIpAddressRegex = "/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/";
    $ValidHostnameRegex = "/^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$/";
    $isValidIp = preg_match($ValidIpAddressRegex , $inputString);
    $isValidHost = preg_match($ValidHostnameRegex , $inputString);

    return ($isValidIp|| $isValidHost)?1:0;
}

TEST:
EXECUTED  :
ValidateIpOrHostname('123.12.12.12') => Result: 1
EXECUTED  :
ValidateIpOrHostname('123.123.123.123') => Result: 1
EXECUTED  :
ValidateIpOrHostname('1111.1111.1111.1111') => Result: 0
EXECUTED  :
ValidateIpOrHostname('234.234.12345.12345') => Result: 0
EXECUTED  :
ValidateIpOrHostname('-1.1.1.1') => Result: 0
EXECUTED  :
ValidateIpOrHostname('1.1.1.1:80') => Result: 0
EXECUTED  :
ValidateIpOrHostname('google.com') => Result: 1
EXECUTED  :
ValidateIpOrHostname('www.google.com') => Result: 1
EXECUTED  :
ValidateIpOrHostname('http://google.com') => Result: 0
EXECUTED  :
ValidateIpOrHostname('http://www.google.com') => Result: 0
EXECUTED  :
ValidateIpOrHostname('https://google.com') => Result: 0
EXECUTED  :
ValidateIpOrHostname('https://www.google.com') => Result: 0
EXECUTED  :
ValidateIpOrHostname('https://google.com') => Result: 0
EXECUTED  :
ValidateIpOrHostname('https://google.com:80') => Result: 0
EXECUTED  :
ValidateIpOrHostname(''asdjb aosjkdn') => Result: 0
EXECUTED  :
ValidateIpOrHostname('asdjb..ewqe.asd..c') => Result: 0
Improves are welcome.
:)


text:
Q: Saving a text box to pdf in R I am trying to create a bullet-point type list in R, and want to save it in pdf, which successfully resulted in printing the bullet-point list on a window:
 a = paste0("Starting portfolio value: $", prettyNum(1000000,big.mark=",",scientific=F))
 b = "Inflation assumptions of 3% annually"
 c = "Average annual returns: 6%"
 d ="Average annual volatility: 7%"

 text = paste(a, "\n", b, "\n", c, "\n", d, "\n")

 library(grid)
 grid.points(x = rep(10,4), y = c(295, 318, 338, 360), pch = 15, gp = gpar(cex = 0.5))
 grid.text(text, x = 0.05, hjust = 0, gp = gpar(fontsize = 11))

However, I would like to be able to save this to a pdf, along with two other graphs on the same page.
Any way of doing that? Thanks!

A: Try something like this:
a = paste0("Starting portfolio value: $", prettyNum(1000000,big.mark=",",scientific=F))
b = "Inflation assumptions of 3% annually"
c = "Average annual returns: 6%"
d ="Average annual volatility: 7%"

pdf('out.pdf',width=5,height=5)
plot(NA, xlim=c(0,5), ylim=c(0,5), bty='n',
     xaxt='n', yaxt='n', xlab='', ylab='')
text(1,4,a, pos=4)
text(1,3,b, pos=4)
text(1,2,c, pos=4)
text(1,1,d, pos=4)
points(rep(1,4),1:4, pch=15)
dev.off()

Here's the approximate output:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Список в котором 200к имен городов Пишу веб сервис, получение данных по погоде в городе. Есть список городов в котором 200к имен. Решил выводить по первой букве города. На букву "А" 11к городов. И в командную строку( даже если все в одну строку собрать) не помещается.
Подскажите как можно решить проблему?

A: Варианты:

*

*Сделайте сначала выбор страны и региона

*Если у вас что-то типа combobox, выводите туда только первые 5 городов, а при вводе пользователем следующей буквы, уточняйте запрос и выводите новые 5 городов. Примерно так, как делает адресная строка Chrome при вводе произвольного запроса по отдельным буквам.


text:
Q: Can $\sum_{n=1}^{k} \frac1{\sqrt{n}}$ be an integer for $k>1$? In one of new YouTube videos, I've seen the problem: to show that
$$16 < \sum_{n=1}^{80} \frac1{\sqrt{n}} < 17$$
I've solved the problem easily, using
$$\int_2^{81}\frac1{\sqrt{x}}\, dx < \sum_{n=2}^{80} \frac1{\sqrt{n}} < \int_1^{81}\frac1{\sqrt{x}}\, dx$$
But this problem aimed me on another problem:

Can the sum $\sum_{n=1}^{k}  \frac1{\sqrt{n}}$ be an integer number at some positive integer $k>1$?

Is this problem well-known open or closed problem? Or maybe there is some approach allowing to solve this problem easily without using hard mathematical skills?
I've seen the same problem without square roots and it was solved easily.

A: This is not an integer due to the same reason that $H_n$ is not an integer.
Take the largest integer $k$ such that $2^k < n$. If $M = 2^{k - 1} \cdot (2n - 1)!!$, then $\frac{\sqrt{M}}{\sqrt{i}}$ is an algebraic integer for any $i \neq 2^k$ between $1$ and $n$, but $\frac{\sqrt{M}}{\sqrt{2^k}}$ is not algebraic integer. So
$$\sqrt{M} \cdot \sum_{i = 1}^n \frac{1}{\sqrt{i}}$$
is not algebraic integer.

A: A linear transformation of a finite dimensional vector space over a field $k$ has a trace.
Now let $k\subset K$ be a finite extension of fields. For $\alpha$ an element of $K$ we have the trace
$$\operatorname{Tr}_{K/k}(\alpha)$$ defined as the trace of the linear operator $x \mapsto \alpha \cdot x$ ( multiplication by $\alpha$).
Fact: if $d$ rational is not a perfect square and $K$ is a field containing $\sqrt{d}$ then $$\operatorname{Tr}_{K/\mathbb{Q}}(\sqrt{d})= 0$$
Indeed: let $\beta_1$, $\ldots$, $\beta_m$ be a basis of $K$ over the subfield $\mathbb{Q}(\sqrt{d})$. Then $\beta_1$, $\ldots$, $\beta_m$, $\sqrt{d} \beta_1$, $\ldots$, $\sqrt{d} \beta_m$ form a basis of $K$ over $\mathbb{Q}$. In this basis the operator "multiplication by $\sqrt{d}$ has a matrix with diagonal elements all $0$. Done.
Now to show that $\alpha \colon = \sum_{d \in M} \sqrt{d}$ is not rational if $M$ is a finite set of positive rationals that are not square. Indeed, consider a finite extension $K$ of $\mathbb{Q}$   containing all these roots. We have $$
\operatorname{Tr}_{K/\mathbb{Q}}(\alpha) = \sum_{d \in M} \operatorname{Tr}_{K/\mathbb{Q}} (\sqrt{d})= 0$$
But the trace of a  rational number $r$ equals $\operatorname{Tr}_{K/\mathbb{Q}}(r)= n r$, where $n = [K\colon \mathbb{Q}]$.   Hence the above positive sum cannot be a rational number.
With a bit more care, we can show that incomensurable roots of rational numbers are linearly independent over $\mathbb{Q}$.
$\bf{Added:}$ Indeed, say we have
$$\sum c_m \rho_m= 0$$
$c_m$ rationals, and  $\rho_m$ are radicals of rationals, and incomensurable ( that is $\frac{\rho_m}{\rho_{m'}} \not \in \mathbb{Q}$). Then we get
$$c_1 = - \sum_{m> 1} c_m \frac{\rho_m}{\rho_1}$$
and taking traces we get $c_1 = 0$. (Note that $\frac{\rho_m}{\rho_1}$ is an irrational radical, so of trace $0$).


text:
Q: Powershell script to install Azure Service Fabric SDK, runtime and tools silently I'm trying to write a script to download an install Azure Service Fabric SDK, runtime and tools into a few servers.
My issue is that the installer provided here is a Web Installer, and does not support silent mode.
I found a guy that solved this issue here. His code:
# Install Service Fabric Runtime
Invoke-WebRequest "http://download.microsoft.com/download/3/2/1/3217654F-6882-4CEA-BD51-49287EDECE9B/MicrosoftServiceFabric.6.0.232.9494.exe" -OutFile "C:\ServiceFabricRuntime.exe" -UseBasicParsing; \
Start-Process "C:\ServiceFabricRuntime.exe" -ArgumentList '/AcceptEULA', '/QUIET' -NoNewWindow -Wait; \
rm "C:\ServiceFabricRuntime.exe"

# Install Service Fabric SDK
Invoke-WebRequest "http://download.microsoft.com/download/3/2/1/3217654F-6882-4CEA-BD51-49287EDECE9B/MicrosoftServiceFabricSDK.2.8.232.msi" -OutFile "C:\ServiceFabricSDK.msi" -UseBasicParsing; \
Start-Process "msiexec" -ArgumentList '/i', 'C:\ServiceFabricSDK.msi', '/passive', '/quiet', '/norestart', '/qn' -NoNewWindow -Wait; \
rm "C:\ServiceFabricSDK.msi"

As you can see, he's using direct links to the .msi installers (as well as other guys are doing in other threads like these two answers.).
So my questions is, how do i get a direct link to the msi with the latest version of these installers?
And the follow up question would be, is there a universal link that will automatically download the latest version of these tools?
Thanks in advance.

A: I know this is not exactly what you asked for but you can use Web Platform Installer Command Line to install WebPI products silently. The idea is to download WebPICMD and run installation of Service Fabric SDK from the cmd line. The powershell script can look like this:
Invoke-WebRequest "https://download.microsoft.com/download/C/F/F/CFF3A0B8-99D4-41A2-AE1A-496C08BEB904/WebPlatformInstaller_amd64_en-US.msi" -OutFile "C:\WebPlatformInstaller.msi" -UseBasicParsing;
Start-Process "msiexec" -ArgumentList '/i', 'C:\WebPlatformInstaller.msi', '/passive', '/quiet', '/norestart', '/qn' -NoNewWindow -Wait;
rm "C:\WebPlatformInstaller.msi"

WebPICMD.exe /Install /Products:MicrosoftAzure-ServiceFabric-CoreSDK /AcceptEULA

Product MicrosoftAzure-ServiceFabric-CoreSDK will install latest version of Service Fabric SDK and Service Fabric Runtime silently.
If you want to install something different from the WebPI run :
WebPICMD.exe /List /ListOption:All
This command will list all of the available products, just grab the id of the product and run install command.
More about WebPICMD here.

A: To add on the answer above, if WebPlatformCMD gives you Windows' UAC consent window issues, you can use PSEXEC tools to run the installer as system account, avoiding that problem.
Example code:
 Invoke-WebRequest "https://go.microsoft.com/fwlink/?LinkId=287166" -OutFile "$env:temp\WebPlatformInstaller_amd64_en-US.msi" -UseBasicParsing

 Start-Process "msiexec" -ArgumentList "/i $env:temp\WebPlatformInstaller_amd64_en-US.msi /passive /quiet /norestart /qn" -NoNewWindow -Wait

 $psToolsPath = "$env:temp\pstools"
 New-Item $psToolsPath -ItemType directory -force -erroraction silentlycontinue
 Invoke-WebRequest -Uri https://download.sysinternals.com/files/PSTools.zip -OutFile $psToolsPath\PSTools.zip

 Expand-Archive "$psToolsPath\PSTools.zip" $psToolsPath -force
 cd $psToolsPath
 Start-Process psexec64 -ArgumentList "-s /accepteula WebPICMD.exe /Install /Products:MicrosoftAzure-ServiceFabric-CoreSDK /AcceptEULA"

Small note on SteppingRazor's answer above.
You can ease out the ArgumentList Parameter value like this:
Start-Process "msiexec" -ArgumentList "/i C:\WebPlatformInstaller.msi /passive /quiet /norestart /qn -NoNewWindow -Wait

Instead of
Start-Process "msiexec" -ArgumentList '/i', 'C:\WebPlatformInstaller.msi', '/passive', '/quiet', '/norestart', '/qn' -NoNewWindow -Wait;

Then using variables in the string is also easier.


text:
Q: why getting arrays with 0 indexes? after my var_dump, i saw these arrays with the same index. Why is that happening?. how can i make instead of zeros it'll be 0, 1, 2,
3....
Here's my full code, its a very very long code: I have this table in my codeigniter view.
                Total       Expected
  Day(s)   |Hours Worked | Total hr/day | Undertime | Overtime
2015-05-01 | 09:00:00    | 09:00:00     | 00:00:00  | 00:00:00
2015-05-05 | 08:32:00    | 09:00:00     | 00:28:00  | 00:00:00
2015-05-06 | 09:21:00    | 09:00:00     | 00:00:00  | 00:21:00
2015-05-07 | 08:22:00    | 09:00:00     | 00:38:00  | 00:00:00
2015-05-08 | 06:30:00    | 09:00:00     | 00:30:00  | 00:00:00
2015-05-09 | 08:42:00    | 09:00:00     | 00:18:00  | 00:00:00
2015-05-10 | 09:00:00    | 09:00:00     | 00:00:00  | 00:00:00
2015-05-11 | 09:24:00    | 09:00:00     | 00:00:00  | 00:24:00
2015-05-12 | 09:41:00    | 09:00:00     | 00:00:00  | 00:41:00
2015-05-13 | 08:46:00    | 09:00:00     | 00:14:00  | 00:00:00
2015-05-14 | 08:54:00    | 09:00:00     | 00:06:00  | 00:00:00
            ttl: 96:12:00|ttl: 99:00:00 |ttl:       |ttl:

In getting the total hours from total_hr/day and total_hours is different from Undertime and Overtime. Because it should be Undertime is the result of (expected_total_hr/day-total_hours_worked), overtime is (total_hours_worked-expected_total_hr/day)
what i want is to get the overall total of undertime and overtime.
foreach ($unique_date as $late)
         {
    $ttl_hrs_wrked = $late['total_hrs_worked'];
    $expected_hrsAday = $late['expected_hrsAday'];
    $duty  = strtotime($ttl_hrs_wrked);
    $expected = strtotime($xpected_hrsAday);
    $hour  = $expected-$duty; //getting the Undertime
             //$hour  = $duty-$expected -> getting the Overtime

    I want to try the array_sum() that's why i tried making $hour as an array. but when i checked. it resulted to:

    $timeArrays = array( date("00:i",$hour ));
    }

    var_dump($timeArrays);

    ?>

    array (size=1)
      0 => string '00:00' (length=5)
    array (size=1)
      0 => string '00:28' (length=5)
    array (size=1)
      0 => string '00:39' (length=5)
    array (size=1)
      0 => string '00:38' (length=5)
    array (size=1)
      0 => string '00:30' (length=5)
    array (size=1)
      0 => string '00:18' (length=5)
    array (size=1)
      0 => string '00:00' (length=5)
    array (size=1)
      0 => string '00:36' (length=5)
    array (size=1)
      0 => string '00:19' (length=5)
    array (size=1)
      0 => string '00:14' (length=5)
    array (size=1)
      0 => string '00:06' (length=5)

I tried doing this: $timeArrays[] = (date("00:i",$hour ));
   but when i var_dump( $timeArrays);
it resulted into this.

array (size=1)
  0 => string '00:00' (length=5)
array (size=2)
  0 => string '00:00' (length=5)
  1 => string '00:28' (length=5)
array (size=3)
  0 => string '00:00' (length=5)
  1 => string '00:28' (length=5)
  2 => string '00:39' (length=5)
array (size=4)
  0 => string '00:00' (length=5)
  1 => string '00:28' (length=5)
  2 => string '00:39' (length=5)
  3 => string '00:38' (length=5)
array (size=5)
  0 => string '00:00' (length=5)
  1 => string '00:28' (length=5)
  2 => string '00:39' (length=5)
  3 => string '00:38' (length=5)
  4 => string '00:30' (length=5)
array (size=6)
  0 => string '00:00' (length=5)
  1 => string '00:28' (length=5)
  2 => string '00:39' (length=5)
  3 => string '00:38' (length=5)
  4 => string '00:30' (length=5)
  5 => string '00:18' (length=5)
array (size=7)
  0 => string '00:00' (length=5)
  1 => string '00:28' (length=5)
  2 => string '00:39' (length=5)
  3 => string '00:38' (length=5)
  4 => string '00:30' (length=5)
  5 => string '00:18' (length=5)
  6 => string '00:00' (length=5)
array (size=8)
  0 => string '00:00' (length=5)
  1 => string '00:28' (length=5)
  2 => string '00:39' (length=5)
  3 => string '00:38' (length=5)
  4 => string '00:30' (length=5)
  5 => string '00:18' (length=5)
  6 => string '00:00' (length=5)
  7 => string '00:36' (length=5)
array (size=9)
  0 => string '00:00' (length=5)
  1 => string '00:28' (length=5)
  2 => string '00:39' (length=5)
  3 => string '00:38' (length=5)
  4 => string '00:30' (length=5)
  5 => string '00:18' (length=5)
  6 => string '00:00' (length=5)
  7 => string '00:36' (length=5)
  8 => string '00:19' (length=5)
array (size=10)
  0 => string '00:00' (length=5)
  1 => string '00:28' (length=5)
  2 => string '00:39' (length=5)
  3 => string '00:38' (length=5)
  4 => string '00:30' (length=5)
  5 => string '00:18' (length=5)
  6 => string '00:00' (length=5)
  7 => string '00:36' (length=5)
  8 => string '00:19' (length=5)
  9 => string '00:14' (length=5)
array (size=11)
  0 => string '00:00' (length=5)
  1 => string '00:28' (length=5)
  2 => string '00:39' (length=5)
  3 => string '00:38' (length=5)
  4 => string '00:30' (length=5)
  5 => string '00:18' (length=5)
  6 => string '00:00' (length=5)
  7 => string '00:36' (length=5)
  8 => string '00:19' (length=5)
  9 => string '00:14' (length=5)
  10 => string '00:06' (length=5)

A: It was happening because of the array. The array is storing the the value with index 0. Remove the array and store it in the $timeArrays[]. Try this -
$timeArrays[] = date("00:i",$hour);

Hope the problem will be solved.


text:
Q: MYSQL/PHP: Newbie with INSERT INTO guys
I have the following problem. I've made a database called "dsaidovsite" and SQL table inside it called "General Settings", there I've added ID, and PageTopTitle collumns. In the collumn ID,PageTopTitle is already added a row 0,DSPixels Design .I wanted to do the following: I open the ACP, insert the website title, and a PHP script delete the current row, and insert new with ID 0 again (because php should know which row exactly to remove, that why I use ID to identify the row) and the new PageTopTitle value. Here is the PHP I tried to make:
$qry = "DELETE FROM General Settings WHERE id = 0"
$qry = "INSERT INTO `dsaidovsite`.`GeneralSettings`(`ID`, `PageTopTitle`) VALUES('0','$PageTopTitle')";
$result = mysql_query($qry);

It is giving me error unexpected T_VARIABLE on:
$qry = "INSERT INTO `dsaidovsite`.`GeneralSettings`(`ID`, `PageTopTitle`) VALUES('0','$PageTopTitle')";`

I think that it is from the 0, and I don't know how to make it add an exact value into the ID column. I hope you got my point and I'll very happy if you help me with this.
Kind Regards,
Denis Saidov

A: Your code should be like this:
$qry = "DELETE FROM General Settings WHERE id = 0";
mysql_query($qry); //first delete
$qry = "INSERT INTO `dsaidovsite`.`GeneralSettings`(`ID`, `PageTopTitle`)     VALUES('0','$PageTopTitle')";
$result = mysql_query($qry); //then add

You missed this ; at the end of the delete ;)
PS: You should go for mysqli or PDO...mysql extension is deprecated
Saludos.

A: Lets break this down.
First off unexpected T_VARIABLE is PHP telling you it ran into a Variable when it wasn't expecting to. Taking this into consideration, it told you what line so we look around there.
             $qry = "DELETE FROM General Settings WHERE id = 0"
error line-> $qry...

Looking at the line the error provides, you see that there is a variable and what comes before it is another line. At the end of the line we notice no ;. Done. That problem is fixed.
As for your thought that 0 may be doing it. PHP doesn't care what you're doing in your MySQL command other than to evaluate the string then pass on to MySQL. Your command is good since you used double quotes, $PageTopTitle will be evaluated.
Further comments:
You only run mysql_query once and that is after the second setting of $qry so the DELETE command will not be executed.


text:
Q: Is email tracking with invisible pixel - secure? Our company want to install a tracking feature (installed as an add-on to google) that pushes an invisible pixel to emails, and than you see if that email was opened or not.
The addon asks to get all data from the browser upon installation
Is that a secure thing?
I feel that it's giving a 3rd party, access to ALL my data/passwords/bank info...
Should I install such an addon?

A: Maybe!!
I've done email marketing with tracking where I designed the lot (the tracking system, the email, the databases etc). The idea is you include an image, when you download the image it sends details which is then executed on the server.
However, you must realise that, unless the technology has moved so quickly I'm behind, you have to download the pixel. If you don't download the pixel (the pixel means image) then it won't work.  And email clients like Outlook often automatically prevent images from downloading!
So, is it secure? That depends on your set up and security. If you have an email client which allows me to run javascript or even execute macro's etc, then I would say no. And I could exploit it.
The other issue is you may have is, the third party (in this case Google), may be able to track you for your own needs (and I'm not suggesting for the power of evil). For example, tracking programs often include the users email so you know who opened the email. Emails are unique so maybe Google can also store this information gathered from your mail shot.  Then, if the client has Gmail, the next time they log on to Gmail, they see adverts more tailored for their needs. This could even be showing your competitors.
Now, and this paragraph is opinion based, since you are doing this via Google, and I would say they are a fairly big company that the likelyhood is they are very security conscious. Having a vulnerability where data was leaked in the manner you describe would greatly damage their reputation; not something they would want to do. However, doing the same thing via Dodgy Dealing Enterprises may result in something less than ethical!

A: I don't think this will work as a "tracking" mechanism anymore for Gmail. I've used to use it but since Google introduced new secure way of viewing pictures in Gmail; where you download and upload all photos from Google servers, it won't work. It will display that the Email was opened as soon as Google (not the tracked user) downloads the photo from that link to its servers.
Here's the announcement:
Gmail Blog
So to answer your question, it's safe for the user, and since Chrome uses Sandboxing, it's safe for you. But does it work? I don't think so, since the default is the new way, and users have to manually select the old way.

A: As a generic statement, An add-on can theoretically steal any data your browser has access to, so its important to only download and install browser add-ons from developers you trust.
As for the tracking pixel, the service likely just hosts the image and logs the people who download it specifically. That means that for a person recieving one of these emails, their privacy is impacted to the same extent that visiting any webpage is. the site operator can see the IP address of the client (and from that infer geographic location), see what is in your system clipboard, your agent string, in some cases your visited site history, etc. They can read cookies from prior visits, and call plugins that may have additional information to provide (like the old flash stealth cookies). Is this secure? I would generally say no.
In the end, while I believe that using this (or any kind of read receipt algorithm) is unethical, if the user isn't give a prior opportunity to opt out, that is up to you, at least in the US when anyone can track anyone for any reason that turns a profit.
Hope that helps.


text:
Q: MySQL CURRENT_TIMESTAMP Error Parsing DDL for microseconds This is the MySQL table that I want, but focus on datum_en_tijd:
CREATE TABLE `navigatie` (
    `navigatie_id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
    PRIMARY KEY (`navigatie_id`),
    `huidige_vraaggroep` varchar(255) NOT NULL,
    `vorige_vraaggroep` varchar(255) DEFAULT NULL,
    `richting` varchar(255) NOT NULL,
    `datum_en_tijd` timestamp(3) NOT NULL,
    `schadegeval_id` bigint(20) UNSIGNED DEFAULT NULL,
    `claim_id` bigint(20) UNSIGNED DEFAULT NULL,
    `gebruiker_id` bigint(20) NOT NULL,
    `soort_gebruiker` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

As you can see TIMESTAMP is with (3) for milliseconds
Whenever I try to Alter Table... in MySQL Workbench I get this error:

When I do View DDL, I get a new tab with this query:
delimiter $$

CREATE TABLE `navigatie` (
  `navigatie_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `huidige_vraaggroep` varchar(255) NOT NULL,
  `vorige_vraaggroep` varchar(255) DEFAULT NULL,
  `richting` varchar(255) NOT NULL,
  `datum_en_tijd` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  `schadegeval_id` bigint(20) unsigned DEFAULT NULL,
  `claim_id` bigint(20) unsigned DEFAULT NULL,
  `gebruiker_id` bigint(20) NOT NULL,
  `soort_gebruiker` varchar(255) NOT NULL,
  PRIMARY KEY (`navigatie_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$

Note the change on
`datum_en_tijd` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),

Is this a bug or what?
Also note the SYNTAX ERROR on line 8 MySQL WorkBench gives us:

I'm running MySQL 5.6.16

A:
Incompatible change: In very old versions of MySQL (prior to 4.1), the
  TIMESTAMP data type supported a display width, which was silently
  ignored beginning with MySQL 4.1. This is deprecated in MySQL 5.1, and
  removed altogether in MySQL 5.5. These changes in behavior can lead to
  two problem scenarios when trying to use TIMESTAMP(N) columns with a
  MySQL 5.5 or later server:
When importing a dump file (for example, one created using mysqldump) created in a MySQL 5.0 or earlier server into a server from

a newer release series, a CREATE TABLE or ALTER TABLE statement
  containing TIMESTAMP(N) causes the import to fail with a syntax error.
To fix this problem, edit the dump file in a text editor to replace any instances of TIMESTAMP(N) with TIMESTAMP prior to

importing the file. Be sure to use a plain text editor for this, and
  not a word processor; otherwise, the result is almost certain to be
  unusable for importing into the MySQL server.

http://dev.mysql.com/doc/refman/5.1/en/timestamp-initialization.html
So you cant have
`datum_en_tijd` timestamp(3)

instead you need to use
`datum_en_tijd` timestamp

or
`datum_en_tijd` datetime(3)

A: Yes timestamp does not require this any more, i usually just use it with either DEAFAULT or ON UPDATE CURRENT_TIMESTAMP, you may find either useful.

A: Some variants to pick from:
created_at timestamp(3) NOT NULL DEFAULT '1970-01-01 12:34:56'
mysql_row_created_at timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3)
created_at timestamp(3) NULL DEFAULT NULL
Each has its own pluses and minuses.
Don't (ever) use datetime, as that has no related timezone, it is mostly just liike a (packed) string.
The MySQL timestamp type is physically stored in UTC (it is a UNIX-epoch delta). It is rendered in the active timezone of the session.


text:
Q: remove transparent of imageresource in floating action button i have set a floating action button background as translucent but when i set image resource it happen to be translucent too how can i remove translucent in an image
resource in floating action button
xml codes.
    <android.support.design.widget.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/fabwallaper"
    android:layout_marginLeft="25dp"
    app:borderWidth="0dp"
    android:layout_marginBottom="3dp"
    android:elevation="6dp"
    app:pressedTranslationZ="16dp"
    app:layout_anchor="@id/appbar"
    app:layout_anchorGravity="bottom|left|start"
    android:backgroundTint="@color/colorAccent"
    />

java code.
        actionButton=(FloatingActionButton) findViewById(R.id.fabwallaper);
    actionButton.setAlpha(0.25f);
    actionButton.setImageResource(R.drawable.ic_terrain_white);

A: You need to set image from XML file. Try this one android:src="@drawable/your_image_res" and
change android:backgroundTint="@color/colorPrimary" to app:backgroundTint="@color/colorPrimary".
Look at that difference:
android:backgroundTint="@color/colorPrimary"

app:backgroundTint="@color/colorPrimary"

A: You're setting the button as translucent. Try using the alpha percentage with the backgroundTint color, so you'd set
android:backgroundTint="@color/colorWithAlphaLevel"

And your ImageResource would not be affected.
To set apha do a color, just add 1 byte to your original color, for example:
#000000 represents a full black, adding 1 more byte it would be #FF000000
For 25% alpha you would need #40000000


text:
Q: How to Embed PDF in browser in Django instead of downloading it? My problem is that the browser downloads the pdf instead of displaying it.
I tried some solutions from this site (for example) but none of them worked for me.
I use this code in my html file and nothing else:
{% load static %}
<body>
    <object data="test.pdf" type="application/pdf" title="SamplePdf" width="500" height="720">
        <embed src="{% static 'test.pdf' %}" >
    </object>
</body>

Ideas?

A: Displaying PDF has nothing in common with Django, you can handle it with pure HTML:
Recommended way to embed PDF in HTML?
Have you tried:
<embed src="{% static 'test.pdf' %}" width="500" height="375"
 type="application/pdf">

?


text:
Q: Laravel 5 Cache/Paginate Issue So I decided to go from Laravel 4 to 5 which took me around 1-2 days because I barely knew how to do the transition. While doing the Upgrade for my app i came across a small problem with Json Pagination.
This code is what allows a PageQuery to be Paginated Via KnockoutJS
/**
 * Builds paginate query with given parameters.
 *
 * @param  array   $params
 * @param  integer $page
 * @param  integer $perPage
 *
 * @return array
 */
public function buildPaginateQuery(array $params, $page = 1, $perPage = 15)
{
    $query = $this->model;

    $query = $this->appendParams($params, $query);

    $count = (new Cache)->remember('count', '2000', function() use ($query){
        return $query->count();
    });

    $totalPages = $count / $perPage;

    $query = $query->skip($perPage * ($page - 1))->take($perPage);

    $query = $query->order(isset($params['order']) && $params['order'] ? $params['order'] : null);

    //$query = $query->cacheTags(array($this->model->table, 'pagination'))->remember(2000);

    $query = (new Cache)->remember(array($this->model->table, 'pagination'), '2000', function() use ($query){
        return $query;
    });

    return array('query' => $query, 'totalPages' => $totalPages, 'totalItems' => $count);
}

which eventually lead to this error in this screenshot

The Error directs to the code above and this code specifically
/**
 * Get the full path for the given cache key.
 *
 * @param  string  $key
 * @return string
 */
protected function path($key)
{
    $parts = array_slice(str_split($hash = md5($key), 2), 0, 2);
    $path  = $this->directory() . '/'.join('/', $parts).'/'.$hash;

    //unset the tags so we use the base cache folder if no
    //tags are passed with subsequent call to the same instance
    //of this class
    //$this->tags = array();

    return $path;
}

Im using a custom Cache Driver called TaggedFile. This worked fine in L4 but came across errors because There were some files removed within the Cache Alias. Like the StoreInterface. Can I receive some help for this? If you need me to post anything I will.
More Stuff:
Before I used this to Register the taggedFile Driver in global.php:
Cache::extend('taggedFile', function($app)
{
    return new Illuminate\Cache\Repository(new Lib\Extensions\TaggedFileCache);
});

I do not know where exactly to put this. Does anyone know the equivalent of that? I tried putting it in AppServiceProvider but an error came up saying:
Call to undefined method Illuminate\Support\Facades\Cache::extend()

This used to work in L4 so i decided to go into the vendor folder manually find what the problem was....
This only had: getFacadeAccessor (Which L4 also only had but extend worked)
So i decided to use getFacadeAccessor and it worked, but i don't know if that was the solution or not.

A: As you noticed you are passing an array as a $key value, the safest way would be to replace the code
$parts = array_slice(str_split($hash = md5($key), 2), 0, 2);

With
$parts = array_slice(str_split($hash = md5(json_encode($key)), 2), 0, 2);

NB: I am not sure what version of php you are running, but json_encode( ... ) is normally faster then serialize( ... )


text:
Q: Any idea how to attack this integral $\int_0^{\infty} p^2 e^{-\beta\sqrt{p^2+1}} \, dp$ I need to do this integral:
$\int_0^{\infty} p^2 e^{-\beta\sqrt{p^2+1}} \, dp$
($\beta > 0$)
Any technique how to do this integral? (apparently not possible in closed form) or at least produce the result as a rapidly converging series.
A closely related formula (just a Gaussian integral):
$\int_0^{\infty} p^2 e^{-\beta p^2 } \, dp = \frac{\sqrt{\pi }}{4 \beta ^{3/2}}$
and on the other hand:
$\int_0^{\infty} p^2 e^{-\beta p } \, dp = \frac{2}{\beta^3}$
Progress 1:
So, intuition tells that for $\beta\to 0$ the integral behaves like $\beta^{-3}$ and for $\beta\to\infty$ as $\beta^{-3/2}$.
Progress 2:
From related texts in the field I am getting the hint that it maybe expressable in terms of a modified Bessel function $K_2$.
Progress 3 (solution):
From experimenting with Bessel functions I get that
$\int_0^{\infty} p^2 e^{-\beta\sqrt{p^2+1}} \, dp = K_2(\beta)/\beta$
I'll still accept an answer with the derivation

A: Substitute $p=\sinh{t}$ and get the integral is equal to
$$\int_0^{\infty} dt \, \left ( \cosh^3{t}-\cosh{t}\right) e^{-\beta \cosh{t}}$$
Use the fact that
$$K_1(\beta) = \int_0^{\infty} dt \, \cosh{t}\, e^{-\beta \cosh{t}}$$
and the recurrence relations for modified Bessels; I get as the value of the integral
$$K_1''(\beta)-K_1(\beta) = \frac14 [K_3(\beta)- K_1(\beta)]$$


text:
Q: Can you auto-run a custom functions add-in, or dynamically run it from a different add-in (same domain)? TL;DR - By default, a custom functions add-in registered with Excel is available, but not running, when Excel loads. It only gets run if one of its custom functions is used (or if it has a task pane and the user opens it). Is there any way to auto-run it or trigger running it from a different add-in (in the same domain) that is running?
Details:
We have multiple custom functions add-ins: a "main" one everyone has and a few other optional ones providing sets of functions appropriate to different job roles, controlled by Active Directory membership. They use the shared runtime. Each add-in has a task pane (though the users rarely open them).
Sometimes, code in a custom function in one of the non-"main" add-ins needs to show a warning message to the user (not as its return value). Since they have task panes, we could have functions in each add-in show warnings by showing their task pane (showAsTaskpane) and putting the messages there. But there are cross-cutting warnings we would prefer to only show in the "main" add-in's task pane rather than having them show up willy-nilly here and there. That's not a problem when the "main" add-in is loaded in memory and running; we can use a BroadcastChannel to send messages to it. But if it happens that none of the functions in that "main" add-in have been used (yet) and the user hasn't opened its task pane, that add-in isn't loaded/running, so we can't send messages to it.
Is there any way to get that add-in running in that situation? Whether by auto-running it on load (I don't see anything in the manifest reference for that), or by having the custom function in the other add-in dynamically tell Excel to run the "main" add-in?

A: For your question: "Is there any way to auto-run it or trigger running it from a different add-in (in the same domain) that is running?"
I think the answer is no.
Not sure whether helpful, I'd like to provide you with a doc link of auto-open feature. After setting your add-in auto-open,  your add-in task pane can open automatically if the add-in is already installed on the user's device.


text:
Q: Global variable becoming undefined from within event listener - javascript I have a function that creates a new image and gives it an event listener, which needs to access a global variable. The global variable (_currentSection) is defined until it gets to the declaration of the event listener, when it then becomes undefined. Here is the function:
function relMouseCoords(event) {
    var totalOffsetX = 0;
    var totalOffsetY = 0;
    var canvasX = 0;
    var canvasY = 0;
    var currentElement = this;

    do {
        totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
        totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
    } while (currentElement = currentElement.offsetParent)

    canvasX = event.pageX - totalOffsetX;
    canvasY = event.pageY - totalOffsetY;

    //alert( 'x: ' + canvasX + '         y: ' + canvasY);

    for (var i = 0; i < _currentSection.allHotSpots.length; i++) {
        if (canvasX > _currentSection.allHotSpots[i].topLeft[0] &&
            canvasX < _currentSection.allHotSpots[i].bottomRight[0] &&
            canvasY > _currentSection.allHotSpots[i].topLeft[1] &&
            canvasY < _currentSection.allHotSpots[i].bottomRight[1]) {
            //alert( 'x: ' + canvasX + '         y: ' + canvasY);
            if (_currentSection.allHotSpots[i].isPicZoom === "false") {
                appendHotSpot(_currentSection.allHotSpots[i], _currentSection.thePicture, _context, true);
            } else {
                picZoomCode = _currentSection.allHotSpots[i].myPicZoom;
                var img = new Image();
                img.onload = function() {
                    _context.drawImage(img, 0, 0, _canvas.width, _canvas.height);
                }
                img.src = "data:image/jpeg;base64," + _currentSection.allHotSpots[i].picture;

                img.addEventListener('load', function() {
                    if (_currentSection.allHotSpots[i].allHotSpots) {
                        for (var j = 0; j < _currentSection.allHotSpots[i].allHotSpots.length; j++) {
                            appendHotSpot(_currentSection.allHotSpots[i].allHotSpots[j], _currentSection.allHotSpots[i].thePicture, _context, false)
                        }
                    }
                }, false);
            }
        }
    }
}
HTMLCanvasElement.prototype.relMouseCoords = relMouseCoords;

So within img.addEventListener I need access to _currentSection, but it only just goes undefined in img.addEventListener. How do i keep it as being defined?

A: Try putting the variable above var currentElement = this;


text:
Q: how do I link the class with main method in the same file This is my first time using C# to create the program. How do I GetXMLData then add the record after that update the data in xml file? This program do not return me the error, but I could not see the data id "4" has been added into the record.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace LinQ
{
    class Program
    {
        private string path = "TestData.xml";

        private void GetXMLData()
        {
            XDocument testXML = XDocument.Load(path);
            var students = from student in testXML.Descendants("Student")
                           select new
                           {
                               ID = Convert.ToInt32(student.Attribute("ID").Value),
                               Name = student.Element("Name").Value
                           };

            foreach (var student in students)
            {
                // Do other operations with each student object
            }
        }
        private void InsertXMLData(string name)
        {
            XDocument testXML = XDocument.Load(path);

            XElement newStudent = new XElement("Student",
                                           new XElement("Name", name)
                                       );
            var lastStudent = testXML.Descendants("Student").Last();

            int newID = Convert.ToInt32(lastStudent.Attribute("ID").Value);
            newStudent.SetAttributeValue("ID", 4);
            testXML.Element("Students").Add(newStudent);
            testXML.Save(path);
        }

        private void UpdateXMLData(string name, int id)
        {
            XDocument testXML = XDocument.Load(path);
            XElement cStudent = testXML.Descendants("Student").Where(c => c.Attribute("ID").Value.Equals(id.ToString())).FirstOrDefault();

            cStudent.Element("Name").Value = name;
            testXML.Save(path);
        }

        static void Main(string[] args)
        {
            //GetXMLData();
            //InsertXMLData(string name);
        }
    }
}

A: Your Main function isn't doing anything.
change
    static void Main(string[] args)
    {
        //GetXMLData();
        //InsertXMLData(string name);

    }

to
    static void Main(string[] args)
    {
        GetXMLData();
        InsertXMLData("paul");
    }

you also have to make your methods static.
change
private void GetXMLData()

private void InsertXMLData(string name)

private void UpdateXMLData(string name, int id)

to
private static void GetXMLData()

private static void InsertXMLData(string name)

private static void UpdateXMLData(string name, int id)

If you want to access your methods without making them static, you have to create an instance of your object.
Like:
Program myProgram = new Program();
myProgram.GetXMLData();
myProgram.InsertXMLData("paul");

A: Please give proper path for xml file or keep it in exe location.
Below are the changes required to compile your code
class Program
{

    private static string path = "D:\\TestData.xml";

    static void Main(string[] args)
    {
        GetXMLData();
        InsertXMLData("XYZ");
    }

    private static void GetXMLData()
    {
        // try
        // {
        XDocument testXML = XDocument.Load(path);
        var students = from student in testXML.Descendants("Student")
                       select new
                       {
                           ID = Convert.ToInt32(student.Attribute("ID").Value),
                           Name = student.Element("Name").Value
                       };

        foreach (var student in students)
        {
            // Do other operations with each student object

        }
        //  }
        //catch (Exception err)
        //{
        //    MessageBox.Show(err.Message);
        //}
    }
    private static void InsertXMLData(string name)
    {
        //try
        //{
        XDocument testXML = XDocument.Load(path);

        XElement newStudent = new XElement("Student",
                                       new XElement("Name", name)
                                   );
        var lastStudent = testXML.Descendants("Student").Last();

        int newID = Convert.ToInt32(lastStudent.Attribute("ID").Value);
        newStudent.SetAttributeValue("ID", 4);
        testXML.Element("Students").Add(newStudent);
        testXML.Save(path);
        //}
        //catch (Exception err)
        //{
        //    MessageBox.Show(err.Message);
        //}
    }

    private static void UpdateXMLData(string name, int id)
    {
        //try
        //{
        XDocument testXML = XDocument.Load(path);
        XElement cStudent = testXML.Descendants("Student").Where(c => c.Attribute("ID").Value.Equals(id.ToString())).FirstOrDefault();

        cStudent.Element("Name").Value = name;
        testXML.Save(path);
        //}
        //catch (Exception err)
        //{
        //    MessageBox.Show(err.Message);
        //}
    }
}

A: Having a quick look over the code, it appears there are two problems that could cause the application to perform incorrectly.
Firstly,
The method calls in Main() have been commented out, uncomment (remove the leading //) for the two methods.
Secondly,
The functions GetXMLData(), InsertXMLData(), and UpdateXMLData() are not static, and require a class instance to be used.  You can fix this by adding the keyword static or use a class instance to call the functions.
Either change the function definitions to something like
 private static void GetXMLData()
 private static void InsertXMLData()
 private static void UpdateXMLData()

or use a class instance
 Program p = new Program();
 p.GetXMLData();

There are no doubt other issues within the code, but this should get you started.


text:
Q: jQuery Data Attribute value I have an array of values taken from inputs (prices[]), I want to add value to an input value based on selected option that have data attribute.
price input
I want to take value from data-price and put the value of data attribute in price[], but when I select, it doesnt work properly just for the first item.
Newly added product
Code

$('.products').change(function() {
  let price = $(this).children(':selected').data('price');
  $('.prices').val(price);
});

  Product
  <select class="form-control kt-select2 products" id="kt_select2_2" name="products[]" required>
    <option selected disabled>Select a product</option>
    <option value="1" data-price="1">Product 1</option>
    <option value="2" data-price="2">Product 2</option>
    <option value="3" data-price="3">Product 3</option>
  </select>

    Product Price
    <input type="text" class="form-control prices" id="price" name="price[]" placeholder="Enter product price" value="0" required>

A: You need to select the prices element that belongs to that particular product, i created a div with the class of product-wrap that has both the select and the price input, you should select a element that has both inputs

$('.products').change(function() {
  let price = $(this).children(':selected').data('price');
  $(this).closest('.product-wrap').find('.prices').val(price);
});

    Product
    <select class="form-control kt-select2 products" id="kt_select2_2" name="products[]" required>
      <option selected disabled>Select a product</option>
      <option value="1" data-price="1">Product 1</option>
      <option value="2" data-price="2">Product 2</option>
      <option value="3" data-price="3">Product 3</option>
    </select>

      Product Price
      <input type="text" class="form-control prices" id="price" name="price[]" placeholder="Enter product price" value="0" required>

    Product
    <select class="form-control kt-select2 products" id="kt_select2_2" name="products[]" required>
      <option selected disabled>Select a product</option>
      <option value="1" data-price="1">Product 1</option>
      <option value="2" data-price="2">Product 2</option>
      <option value="3" data-price="3">Product 3</option>
    </select>

      Product Price
      <input type="text" class="form-control prices" id="price" name="price[]" placeholder="Enter product price" value="0" required>


text:
Q: Connecting Unifi Controller running in Docker on ESXi to default VLAN while isolating other containers and container host from default VLAN I have an ESXi 6.7 host with 6 physical NICs. Those NICs are configured as follows:
vSwitch0:

vSwitch1:

The NICs assigned to vSwitch0 are physically connected to a Netgear switch who's ports are untagged for the specific VLAN that I wish to manage ESXi from.
The NICs assigned to vSwitch1 are physically connected to a Netgear switch who's ports are tagged with the VLANs that I want to make available to the virtual machines running in my ESXi host (VLANs 10 and 50). Presently, my virtual machines in my ESXi host are only configured to be on VLAN 10.
I have been experimenting with Docker lately, so I spun up a Ubuntu Server 22.04 virtual machine to run as my Docker host. I added a Unifi Controller container and have managed to adopt my access points into the controller by using the "set inform" command from within the access point's cli.
I am looking at expanding my Unifi network, and after doing some further research, I have realized that in order to streamline the device adoption process, I need to get my Unifi Controller onto my default VLAN. Here is where things start to get complicated for me....
In order for the container to access the default VLAN, I figured that I would need to first get my container host connected to the default VLAN. I attempted to achieve this by creating a new vSwitch (vSwitch2). The physical NIC associated with vSwitch2 is tied to the Netgear switch that is configured only for untagged traffic. I figured that isolating the untagged traffic to this specific VM via a dedicated vSwitch was safer than allowing all of my servers access to the default VLAN.
vSwitch2:

I then added a 2nd NIC to my Docker host.

This 2nd NIC did not receive an IP address via DHCP. I thought that I may have had a switch configuration issue, so for testing purposes, I tried assigning the 2nd NIC to VLAN 10 and then to VLAN 50. To my surprise, it still did not receive an IP via DHCP. At this point, it is evident that the 2nd NIC not receiving an IP is a result of something being misconfigured within my Ubuntu Server VM. Before I go down the rabbit hole of making lots of configuration changes, I wanted to ask the following:

*

*If I want to use my Docker host for my Unifi Controller as well as other future containers, would it make sense to connect the host to two separate networks in this case?

*Is it possible to connect the Docker host to more than one network, but ensure the host is only accessible from only 1 of those networks? If so, how is this achieved?

*Does my docker host need to have an IP address on a network in order for the container to be accessed (assuming the container is configured for macvlan networking).

*Would it make sense for the Unifi Controller to be configured with macvlan networking?

*Was configuring a separate vSwitch (vSwitch2) the right choice for isolating the default VLAN?

*From a security standpoint, do I need to make architecture/network topology changes?


text:
Q: Java compiler asking for semicolon I've looked through this code for awhile, counted brackets, all that stuff. And I can't find an error. I'm using Eclipse, developing for Android, and it's asking for a semicolon (commented, it's near the bottom).
package com.example.lesson1;

import android.app.Activity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;

public class TextPlay extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.text);

        final Button checkCommand = (Button) findViewById(R.id.bResults);
        final ToggleButton passToggle = (ToggleButton) findViewById(R.id.tbPassword);
        final EditText input = (EditText) findViewById(R.id.etCommands);
        final TextView display = (TextView) findViewById(R.id.tvResults);

        passToggle.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                if (passToggle.isChecked()) {
                    input.setInputType(InputType.TYPE_CLASS_TEXT
                            | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                } else {
                    input.setInputType(InputType.TYPE_CLASS_TEXT);
                }

            }
        });
        checkCommand.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                String check = input.getText().toString();
                if (check.toLowerCase().equals("boss")) {
                    display.setText("Yup, pretty damn boss!");
                } else if (check.toLowerCase().equals("password")) {
                    display.setText("Simple");
                }
            }
        }); // here is the semicolon it wants
    }

}

Screenshot: https://dl.dropbox.com/u/986549/error.png

A: Try going into Project > clean. See if that gets rid of the error. Also, keep the semicolon.


text:
Q: Placing a SQLite database into a JSON object to send to a server from iOS I am trying to take my entire local sqlite database on an iOS device and send it using http post to my server to insert it into a MySQL database. I am using FMDB for my database and I have 5 tables I want to insert into an object. I was able to do this with my remote server using php but not sure how to do this within xcode. this is my code for sending the object but i dont know how to pack the json object which i stole from another answer (How do I send the data I have in my sqlite database to the server with HTTP and JSON)
NSMutableURLRequest *request;
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%d", [requestdata length]] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:requestdata];

//this kicks off the request asynchronously
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

A: I wouldn't recommend transferring large BLOB data like that with JSON, but if you absolutely must:
Here, the binary data must be send via a JSON String. To get a "string" from your binary you need to encode your binary data which eventually results in a "string". For example, use base64 encoding. This encoding will convert your binary data into an ASCII string.
This string can then be used for the JSON string:
JSON:
{
    "sqlite_database": "aJ6Fnh1nfh37sg20zBAskfh0QRb ..."
}

NSData has methods to encode binary data: base64EncodedDataWithOptions: and base64EncodedStringWithOptions:.
You should then be able to send this JSON with a POST request whose content type is application/json (don't use "application/x-www-form-urlencoded").


text:
Q: IBDesignable localisable strings I'm using Xcode's export for localisation feature, and I have a custom IBDesignable UIControl with a IBInspectable string. I'm wondering if there's a way to include this string to the exported .xliff file.

A: In the User Defined Runtime Attribute, you can set the type to localized string. And this allow the string to be included in the exported file. However, I haven't found a way to make the field default to localized string type, so you'll need to change the type every time by yourself.


text: Q: Уникальный текст - первоисточник Распознаёт ли google и yandex поиски сайт, которые разместил первым определённый текст? Т.е. если сайт-вредитель скопировал у вас текст и разместил на какой-то промежуточный сайт для вреда, то пострадает ли сайт, который первым опубликовал его?


text:
Q: AngularJs switch templateUrl and access modeldata I need to switch the template URL in my directive and I have to transfer some modeldata.
I've tried to use a function to switch the template like:
.directive("sqGridData", function ($sce, $rootScope, angularProxySrv) {
   return {
   ...
    template: function (tElement, tAttrs) {
      //Not working got Exception
      //var val = $rootScope.$eval(tAttrs.sqType);

      if (tAttrs.sqType) {
         if (tAttrs.sqType === 'Iframe') {
             return '

';
         }
         if (tAttrs.sqType === 'Table') {
             return '

';
         }
      }
   },

that did not work, because the tAttrs value was a expression and here I only got the string value of the expression like "{{item.WidgetConfig.WidgetType}}" and not the Value itself.

then I've tried to use ngInclude and switch template in the link function. (The templates in the html are the same like above in the template function)
template: '

',
link: function (scope, elem, attr) {
   var wasCalled = false;
   if (!wasCalled) {
       wasCalled = true;

      if (scope.sqGridData.WidgetType === 'Iframe') {
         scope.cntUrl = "/Templates/widget.directives.iFrame.html";
      }
      if (scope.sqGridData.WidgetType === 'Table') {
         scope.cntUrl = "/Templates/widget.directives.table.html";
      }
  }
}

that seems to work, but now I've the problem I don't know how to pass my modelvalues to my directives I've loaded in the include. I thought it should work with require:
.directive("sqIframe", function ($sce) {
    return {
        restrict: "A",
        require: "^sqGridData",
        template: '

',
        scope: {
            sqIframe: "="
        },
        link: function (scope, elem, attr, ngModel) {
              scope.cntUrl = "Home/WidgetHtmlTemplate?name=" + ngModel.HtmlTemplateName;
               scope.IframeUrl = $sce.trustAsResourceUrl(ngModel.WidgetName);;
            }
        }
    }
})

but I only get an error, that the Controller "sqGridData" can't be found. Is there a better way to solve this kind of Problem or someone knows what I am making wrong?

A: This can be solved with a single directive, a function for templateUrl switching templates based on an attribute value, a scope with a generic name for the model value passed, and an ng-switch where the directive is called, not in the directive.
Your html would switch on type, where the "-when" is the value of the type.

Your directive would look something "like" this...
.directive('sqGridData', function () {
    //Returns the desired template based on the 'template" attribute value
    return {
        restrict: 'EA',
        replace: true,
        scope: {
            modelval: '=modelvalue'
        },
        templateUrl: function (elem, attr) {
            switch (attr.template) {
                case 'Iframe':
                    return "/Templates/widget.directives.iFrame.html";
                case 'Table':
                    return "/Templates/widget.directives.table.html";
                default:
                    return null;
            }
        }
    };
});

OR if you want less code, and a less flexible, lazy coder version, where the template is NAMED specifically to the Type, you could do this...
templateUrl: function (elem, attr) { return '/Templates/widget.directives.' + attr.template + '.html"; }

Now in your templates, you will need to use the generic name for the scope value you wanted available on your directives isolated scope in both templates.

     {{ modelval.imaStringPropertyOnTheItemWidgetConfig }}

Then all the magic hits the fan.

A: I've found an solution for my problem.
Using the Directive:

A directive to switch between my templates/directives
angular.module("widget.directives", ["angularProxySrv"])
    .directive("sqGridData", function () {
        return {
          restrict: 'A',
          template: '

',
          scope: {
              sqGridData: "="
          },
          link: function (scope, elem, attr) {
              scope.sqGridData = scope.sqGridData;

              if (scope.sqGridData.WidgetType === 'Iframe') {
                  scope.cntUrl = "Templates/widget.directives.iFrame.html";
              }

              if (scope.sqGridData.WidgetType === 'Table') {
                  scope.cntUrl = "Templates/widget.directives.table.html";
              }
          }
      }
  })

I need to declare the
scope.sqGridData = scope.sqGridData;

I don't know if there is a better solution, but this was the only way to access the scope property from the child directive with the scope.$parent - is there perhaps a better solution (I've tried the require property but this did not work)?
The Templates content for "widget.directives.iFrame.html"

The Templates content for "widget.directives.table.html"

The Directive for the sqTable
.directive("sqTable", function (angularProxySrv) {
    return {
          restrict: "A",
          replace: true,
          template: '

',
          scope: true,
          link: function (scope, elem, attr, ngModel) {
              scope.cntUrl = "Home/WidgetHtmlTemplate?name=" + scope.$parent.sqGridData.HtmlTemplateName;
              angularProxySrv.LoadWidgetDataByWidgetName(scope.$parent.sqGridData.WidgetName).then(function (data) {
              scope.Data = data;
          });
        }
      }
    })


text:
Q: Add Package explorer in RCP-Application result in loosing some icon In my eclispe rcp application I added a package explorer adding org.eclipse.jdt.ui

When I use my rcp-app, as I create a new Project by "New Project Wizard" to add a "General Project", the project is  correctely created, but the corresponding icon in package explorer view is not loaded.
What is the plugin I have to add to my application to see that all the (platform) Icons correctly ?
Thanks a lot

A: This is a known issue in Eclipse RCP applications.
https://bugs.eclipse.org/bugs/show_bug.cgi?id=234252
The work around is to add some code to your ApplicationWorkbenchAdvisor.java
Here's some more documentation about this issue in RCP
http://help.eclipse.org/ganymede/topic/org.eclipse.platform.doc.isv/guide/cnf_rcp.htm
In this code example, I've added the images for the Project Explorer and the Problems View.
Here's what I had to add to my initialize method...
  public void initialize(IWorkbenchConfigurer configurer) {
     super.initialize(configurer);

     // here's some of my code that does some typical RCP  configuration
     configurer.setSaveAndRestore(true);
     PlatformUI.getPreferenceStore().setValue(
            IWorkbenchPreferenceConstants.SHOW_TRADITIONAL_STYLE_TABS, false);

    // here is the work around code
    /*
     * This is a hack to get Project tree icons to show up in the Project Explorer.
     * It is descriped in the Eclipse Help Documents here.
     *
     * http://help.eclipse.org/ganymede/topic/org.eclipse.platform.doc.isv/guide/cnf_rcp.htm
     *
     */

    IDE.registerAdapters();

    final String ICONS_PATH = "icons/full/";

    Bundle ideBundle = Platform.getBundle(IDEWorkbenchPlugin.IDE_WORKBENCH);

    declareWorkbenchImage(
            configurer,
            ideBundle,
            IDE.SharedImages.IMG_OBJ_PROJECT,
            ICONS_PATH + "obj16/prj_obj.gif",
            true);

    declareWorkbenchImage(
            configurer,
            ideBundle,
            IDE.SharedImages.IMG_OBJ_PROJECT_CLOSED,
            ICONS_PATH + "obj16/cprj_obj.gif",
            true);

    declareWorkbenchImage(
            configurer,
            ideBundle,
            IDEInternalWorkbenchImages.IMG_ETOOL_PROBLEMS_VIEW,
            ICONS_PATH + "eview16/problems_view.gif",
            true);

    declareWorkbenchImage(
            configurer,
            ideBundle,
            IDEInternalWorkbenchImages.IMG_ETOOL_PROBLEMS_VIEW_ERROR,
            ICONS_PATH + "eview16/problems_view_error.gif",
            true);

    declareWorkbenchImage(
            configurer,
            ideBundle,
            IDEInternalWorkbenchImages.IMG_ETOOL_PROBLEMS_VIEW_WARNING,
            ICONS_PATH + "eview16/problems_view_warning.gif",
            true);

    declareWorkbenchImage(
            configurer,
            ideBundle,
            IDEInternalWorkbenchImages.IMG_OBJS_ERROR_PATH,
            ICONS_PATH + "obj16/error_tsk.gif",
            true);

    declareWorkbenchImage(
            configurer,
            ideBundle,
            IDEInternalWorkbenchImages.IMG_OBJS_WARNING_PATH,
            ICONS_PATH + "obj16/warn_tsk.gif",
            true);

    /*
     * End of hack in this method...
     */
}

private void declareWorkbenchImage(IWorkbenchConfigurer configurer_p, Bundle ideBundle, String symbolicName, String path, boolean shared)
{
    URL url = ideBundle.getEntry(path);
    ImageDescriptor desc = ImageDescriptor.createFromURL(url);
    configurer_p.declareImage(symbolicName, desc, shared);
}

Hope this helps.
Thanks!

A: You should probably using the Project Explorer rather than the Package Explorer. The Package Explorer is Java-specific, the Project Explorer can do Java and everything else.
Here is some more information: http://help.eclipse.org/indigo/topic/org.eclipse.platform.doc.isv/guide/cnf.htm

A: You have to register some adapters in your WorkbenchAdvisor#initialize(IWorkbenchConfigurer) method manually.
Call in this method (you'll find the IDE class in bundle org.eclipse.ui.ide.application
org.eclipse.ui.ide.IDE.registerAdapters();


text:
Q: Currency Converter - can't multiply sequence by non-int of type 'float' error I'm relatively new to Python and coding in general, and was recently tasked with designing a Currency Converter in Python. I've almost finished the code, but an issue arose on the final line.
currenctcurrency = input ("Select a starting currency: ")
print ('You selected %s' %currentcurrency)

value = input ("Input your current value: ")

new currency = input ("Select a new currency: ")
if currentcurrency == 'Pound' and newcurrency == 'Pound':
    convertor = 1

The above part of the code repeats for each combination of the four supported currencies - pound, euro, dollar and yen.
rint ("Do you want to convert", (value), (currentcurrency), "to", (newcurrency), "?")
answer = input ("Yes/No: ")
if answer == 'No':
    quit(1)
if answer == 'Yes':
    result = (convertor) * (value)
    print (result)

When I run the code, the inputs run successfully but when it tries to multiply the two variables together I get an error which reads:
TypeError: can't multiply sequence by non-int of type 'float'
As I said earlier, I'm new to Python and don't properly understand what I need to do to fix this. I would really appreciate if anyone could give me a simple/explained answer to my issue.
Thank you all for reading, have a great day!

A: Just change this line:
value = input ("Input your current value: ")

to this:
value = float(input("Input your current value: "))

The reason you get the error is that the input function returns a string.  You can multiply strings (or any sequence) with integers, for example "foo" * 3 evaluates to "foofoofoo". But that obviously doesn't work with floating-point numbers, and it isn't what you want. Instead, you want to turn the string into a number, and then multiply it with your convertor value.

A: input returns a string (a sequence of characters). You need to parse the string to a numerical value.
You might want to try:
value = float(input("Input your current value: "))


text:
Q: Can we append data to a Vector in FlatBuffer? I am working on this project where we store the log details for each run.
We are planning to use Flatbuffers for the same
This is my flatbuffer schema
table logData
{
   Id:int;
   attemptId:int;
   line:string;
}

table log
{
   maxLimit: int;
   counter: int;
   job:[logData]; //Vector of Tables
}

Now for the first run we just add data to the table using the helper functions provided by the Auto-Generated files
logBuilder build(builder);
builder.add_maxLimit(10);
auto data = builder.CreateVector(some_vector)
builder.add_job(data);

Now for the second run we have new data so, Is there any way to append more data to the vector job, whilst keeping the old data intact?


text:
Q: Changing the Keymap in Ubuntu Is it possible, using Ubuntu Linux, to change the meanings of the keyboards keys? I needed the right shift key to act as the home key and the right ctrl key to act as the end key. How to do this system wide for every installed application?

A: Sathya's comment solved the problem completely.
Sathya mentioned a Link on AskUbuntu solving the same problem.
The link is https://askubuntu.com/questions/24916/how-do-i-remap-certain-keys


text:
Q: ssh config - do not execute remote command I would like to setup one of the SSH connections in my ssh_config file to use the -N ssh flag. I can't find any matching config keyword for this parameter. I'm using the connection for port forwarding only and I would like it to use -N every time I execute ssh host. I'm using mosh for the interactive shell.
-N      Do not execute a remote command.  This is useful for just forwarding ports (protocol version 2 only).

A: I'm fairly sure you can't do that and like you I can't find a way of doing it in the manner that you want. If typing ssh -N host doesn't appeal then you could always try creating an alias if mosh supports it.

A: I don't know about mosh, but for the OpenSSH client you can specify a ProxyCommand in the config file. The relevant entry for hostname foobar.baz.edu (my favorite university) and dynamic forwarding of port 9999 would be:
Host FooBar
   HostName foobar.baz.edu
   ProxyCommand ssh -ND 9999 %h


text:
Q: Optimization with constrained gradient I am trying to use Lagrange multipliers to solve a constrained optimization problem. The problem looks like:
$$\text{Minimize}\hspace{3mm}R(b_1(x),b_2(x))$$
$$\hspace{11mm}\text{Subject to}\hspace{3mm}c_1 \nabla b_1 + c_2 \nabla b_2 = 0.$$
Naively applying the usual vector calculus methods results in needing the derivatives with respect to $b_1$ and $b_2$ of $R$, which is easy enough to compute in the problem I am solving. I also need the derivatives with respect to $b_1$ and $b_2$ of the second equation, which I am not sure how to do.
Is there a simple way to compute the derivatives that I need? If not, is there a standard formulation that will work for this type of problem?


text:
Q: Angular 4 select not updating value in ngIf I have an ngIf that uses a value from a select to display or not another select, but when i change the value in first select, the ngIf still use the old value. The code I'm using:

 First select
 <select name="status" class="form-control"[(ngModel)]="status.status">
  <option *ngFor="let s of listStatus" [selected]="s.id === status.status" [value]="s.id">{{s.text}}</option>
 </select>

 Second select
 <select name="blockLevel" class="form-control" [(ngModel)]="status.blockLevel">
  <option *ngFor="let s of listBlockedLevel" [selected]="s.id === status.blockLevel" [value]="s.id">{{s.text}}</option>
 </select>

In the component.ts the value is correctly updated. I tried to show the value using {{status.status}} and the value doesn't change.

Solution
I resolve my problem using ChangeDetectorRef. In the first select i used a method to update the value

<select name="status" class="form-control" [ngModel]="status.status" (ngModelChange)="setStatus($event)">

and in ts component i used this

public setStatus(event: any) {
    this.status.status = event;
    this.ref.detectChanges();
}

in component constructor i used this to import ChangeDetectorRef

private ref: ChangeDetectorRef

A: The select input component changes the id from type number to a string.
Option 1
For the second div, use one of the following *ngIf options:
*ngIf="status.status === 1 || status.status === '1'"
or
*ngIf="status.status == 1"
Working Plunker 1
Option 2 (Recommended)
If you do not like the idea of the select input changing the id to a string, you can use [ngValue] instead of [value] to save the entire status object itself and then reference the id using status.id.
Working Plunker 2


text:
Q: Table rates -> Free shipping from X € - different taxes Is there a way to set free shipping in tablerates for a Total inkl. Tax? The problem is tablerates are using the subtotal without tax but i need it including tax. Because we use two different taxes, we can´t just calculate the price without tax.
I want to set free-shipping in my tablerates .csv for a Total of 19€ including tax. How is this possible?

A: You can add new Condition in Table Rates for Price incl. Tax vs. Destination. In order to do that in app/code/core/Mage/Shipping/Model/Carrier/Tablerate.php -> public function getCode below this line:
'package_value' => Mage::helper('shipping')->__('Price vs. Destination'),

add this code:
'package_value_incl_tax'  => Mage::helper('shipping')->__('Price incl. Tax vs. Destination'),

and below this:
'package_value' => Mage::helper('shipping')->__('Order Subtotal (and above)'),

add this:
'package_value_incl_tax'  => Mage::helper('shipping')->__('Order Subtotal incl. Tax (and above)'),

This to be able to work you have to add in app/code/core/Mage/Shipping/Model/Shipping.php -> public function collectRatesByAddress below:
$request->setPackageValue($address->getBaseSubtotal());

this:
$request->setPackageValueInclTax($address->getPackageValueInclTax());

and in app/code/core/Mage/Sales/Model/Quote/Address.php -> public function requestShippingRates below:
$request->setPackageValue($item ? $item->getBaseRowTotal() : $this->getBaseSubtotal());

this:
$request->setPackageValueInclTax($item ? $item->getBaseRowTotalInclTax() : $this->getBaseSubtotalInclTax());


text:
Q: Creating tar file in Python with tarfile makes directory tree inside of tar.gz For creating tar.gz file I use the below code.
import os
import tarfile
def tardir(path, tar_name):
    with tarfile.open(tar_name, "w:gz") as tar_handle:
        for root, dirs, files in os.walk(path):
            for file in files:
                tar_handle.add(os.path.join(root, file))
tardir('C:/../../projects/project_folder', 'C:/../../projects/project_folder/tar_files/tar_file.tar.gz')
tar.close()

I want gzip the tar_files folder and when i unzip it I only want to see this folder. But with the above code, inside of tar file I see it stores with directory tree. Like when I open it i see the below folders

/../../projects/project_folder

How can i solve this problem ?
Thanks for answering

A: Below code from below link solves my question.

How to create full compressed tar file using Python?

import tarfile
import os.path

def make_tarfile(output_filename, source_dir):
    with tarfile.open(output_filename, "w:gz") as tar:
        tar.add(source_dir, arcname=os.path.basename(source_dir))

Giving absolute address to the params output_filename and source_dir works appropriate


text:
Q: Eigenvalue problem involving fractional laplacian Does the problem
$$(-\Delta)^s u=\lambda u \text{ in } \mathbb R^N $$ admit a non-trivial solution when $s\in (0, 1)$ and $\lambda>0.$

A: This is too long for a comment, and actually there is a number of questions that appeared in the comments, so let me summarize my points here.

*

*The answer to the original question: is there a solution to $(-\Delta)^s u = \lambda u$, is positive: $u(x) = \cos(\lambda^{1/(2s)} x_1)$ is an example.
More generally, any $u$ equal to the Fourier transform of a finite measure supported on the sphere $|\xi| = \lambda^{1/(2s)}$ is a solution, and in some sense, these are all solutions.

*If $u$ is a solution and $u \in H^{2s}$, then $u$ and $(-\Delta)^s u$ have well-defined Fourier transforms (in the $L^2$ sense), and $\widehat{(-\Delta)^s u}(\xi) = |\xi|^{2s} \hat{u}(\xi)$. Therefore, $|\xi|^{2s} \hat{u}(\xi) = \lambda \hat{u}(\xi)$, which implies that $\hat{u} = 0$ a.e. Consequently, $u = 0$ a.e., that is, there is no non-trivial solution.
A similar argument will work as long as the Fourier transform of $(-\Delta)^s u$ can be identified with $|\xi|^{2s} \hat{u}(\xi)$. This is the case when, for example, $u$ is a tempered distribution and $(-\Delta)^s u$ is defined in the sense of $\mathscr{S}'$-convolution of tempered distributions. Consequently, every distributional solution is necessarily the inverse Fourier transform of a distribution supported on the sphere $|\xi| = \lambda^{1/(2 s)}$. Note that there are numerous technicalities here, related to the definition of $\mathscr{S}'$-convolution, and I did not attempt to verify all details.

*If $u$ is assumed to be non-negative, then again there are no non-trivial solutions, at least as long as we assume that $(1 + |x|)^{-N - 2s} u(x)$ is integrable and $u$ is, say, smooth. (More generally, instead of smoothness we may require that $(-\Delta)^s u$ is defined in, say, the distributional sense. Indeed: in this case the convolution of $u$ with a bump function will be smooth, and it will satisfy the equation, and thus it will be zero. By approximation, $u$ is zero a.e.)
In this case we can write Dynkin's formula for $u$: $$ u(x) = \int_B G_B(x, y) (-\Delta)^s u(y) dy + \int_{B^c} P_B(x, z) u(z) dz , $$ where $B$ is a (large) ball, $G_B$ is the Green's function, and $P_B$ is the Poisson kernel for $(-\Delta)^s$ in $B$. In particular, $$ u(x) \geqslant \int_B G_B(x, y) (-\Delta)^s u(y) dy , $$ and sending the radius of $B$ to infinity we find that $$ u(x) \geqslant \int I_{2s}(y - x) (-\Delta)^s u(y) dy ,$$ where $I_{2s}$ is the Riesz potential kernel. (Here we need $(-\Delta)^s u(y) \ge 0$ in order to apply monotone convergence theorem. In fact, equality holds, but we will not need that.)
Recall that $(-\Delta)^s u = \lambda u$, and suppose that $u$ is non-negative and not equal to zero a.e. If $N < 2 s$, then we obtain $u(x) = \infty$ right away (because $I_{2s}(x) = \infty$). Otherwise, we use a "self-improving" estimate: since $I_{2s}(y - x) = C_{N,s} |y - s|^{2s - N} \ge C_{N,s} (1 + |x|)^{2s - N} (1 + |y|)^{2s - N}$, we find that $$ u(x) \geqslant C_{N,s} \lambda (1 + |x|)^{2s - N} \int (1 + |y|)^{2s - N} u(y) dy . \tag{$\star$} $$ Since $u(x)$ is not everywhere zero, we get $u(x) \geqslant c_1 (1 + |x|)^{2s - N}$ for some $c_1 > 0$. Plugging this bound into $(\star)$ and estimating the integral leads to an improved estimate $u(x) \geqslant c_2 (1 + |x|)^{4s - N}$ if $N > 4s$, and $u(x) = \infty$ otherwise. In the former case, we iterate further to get $u(x) \geqslant c_3 (1 + |x|)^{6s - N}$ if $N > 6 s$, and $u(x) = \infty$ otherwise. After a finite number of steps, we find that $u(x) = \infty$, a contradiction.
All properties of $(-\Delta)^s$ used in the above argument seem to be quite standard in the potential theory crowd, and some of them date back to Riesz's 1938 article. For more details and reference, you may like to see my survey Fractional Laplace Operator and its Properties in the Handbook of Fractional Calculus with Applications. Vol. 1: Basic Theory, or my earlier article Ten equivalent definitions of the fractional Laplace operator. (I bet there are more convenient references, feel free to edit and add them if you like).


text:
Q: ruby string comparisons .match vs .eql? When I used .match and .eql? for string comparison they gave different results
text_from_page = "wrong length (should be 64 characters)"
error_text = "wrong length (should be 64 characters)"
if(text_from_page.eql? error_text)
 puts 'matched'
else
  puts 'Not matched'
end

The following comparison did not work
if(text_from_page.match error_text)
 puts 'matched'
else
  puts 'Not matched'
end

Does anyone know the reason for this?

A: As always, don't just use methods without reading their documentation. There can be important notes.
Here's eql?:

Two strings are equal if they have the same length and content.

Here's match:

Converts pattern to a Regexp (if it isn't already one), then invokes its match method on str. If the second parameter is present, it specifies the position in the string to begin the search.

Note the part about converting. In a regular expression ( and ), among other characters, have significant meaning. You can't use match arbitrarily here. It has a very specific function.
You rarely see .eql? used in actual Ruby code, the convention is simply this:
text_from_page == error_text

The eql? method is primarily intended for internal use. It comes into play when doing comparisons, and when finding things in a container like an Array or Hash.

A: @tadman. Thank you. That solved my issue. The ".match" compares the hash values where as the ".eql" compares the stings.


text:
Q: leaflet highlight part of polyline in leaflet.js  i have polyline in openstreet map:
point1(long, lat), 2(long, lat)....pointXY(long,lat)
Is possible (and how) highlight or change color only segment from point 2 to 5, no matter how to invoke.
I try add another polyline, but with more segments its mess with more and more duplicit points.
Working sample:
http://next.plnkr.co/edit/FyUzMG9Y9NrbYrzL
i looking for turn segment between [40,10],[10,10],[10,30] red. If its possible, by index [2,3,4]
thanks for help

A: You can try GeoJson layer to highlight a line. Just make sure that geojson coordinates are in LngLat format.
var map = L.map('map', {
  center: [0, 0],
  zoom: 0,
  layers: [
    L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: 'Map data © OpenStreetMap contributors',
    }),
  ],
});

var data = {
  type: 'FeatureCollection',
  features: [
    {
      type: 'Feature',
      geometry: {
        type: 'LineString',
        coordinates: [[30, 10], [45, 45]],
      },
      properties: {
        color: 'green',
      },
    },
    {
      type: 'Feature',
      geometry: {
        type: 'LineString',
        coordinates: [[10, 40], [10, 10], [30, 10]],
      },
      properties: {
        color: 'red',
      },
    },
    {
      type: 'Feature',
      geometry: {
        type: 'LineString',
        coordinates: [[-45, -45], [10, 40]],
      },
      properties: {
        color: 'black',
      },
    },
  ],
};

var geoJsonLayer = L.geoJson(data, {
  onEachFeature: function(feature, layer) {
    if (layer instanceof L.Polyline) {
      layer.setStyle({
        color: feature.properties.color,
      });
    }
  },
}).addTo(map);

Plunker: http://next.plnkr.co/edit/s4Q72s7RyOLp714U?preview
Ref: https://embed.plnkr.co/plunk/XqzvdR


text:
Q: Find an item in a file in Bash cat "test1.txt" | while read delete
do
  grep -i "$delete" test2.txt > /home/user/nodes_deleted.txt
done

It's not working. Can anyone help. It's just printing all entries in test1.txt to nodes_deleted.txt.

A: Your  expected input and output are quite vague, but since you have asked for a custom message "no match found..", I am putting together a small shell script for this, with file1 and file2 contents as follows,
abc
bcd

and file2 as
abc_no

And the script.sh contents as,
#!/bin/bash

while IFS= read -r line
do
   capture=$(grep -i "$line" file2 2>/dev/null)

   if [ ! -z "$capture" ]
   then
       echo "$capture"
   else
       echo "$line not found"
   fi

done <file1

Running it on the command line gives output
$ bash script.sh
abc_no
bcd not found


text:
Q: Display divs beneath each other I am trying to make my divs display vertically (beneath each other) but I am having no luck, I really can't think of the problem, any help is appreciated.
Here is a JSFiddle
I also tried this:
#div1 {
    float: right;
}
#div2 {
    float: right;
    clear: right;
}

with no luck

A: My problem was that I had typos in my HTML and CSS


text:
Q: Sending encrypted data between Android app and PHP script I'm trying to send encrypted data from my android app to a PHP scripts that decrypts the data.
In android I use the following encryption method:
public String encryptAES(String key, String mdp) throws NoSuchPaddingException, NoSuchAlgorithmException {
    byte[] skey = key.getBytes();
    byte[] pwd = mdp.getBytes();
    byte[] encrypted = null;
    SecretKeySpec secretKeySpec = new SecretKeySpec(skey, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    try {
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
    try {
        encrypted = cipher.doFinal(pwd);
    } catch (IllegalBlockSizeException | BadPaddingException e) {
        e.printStackTrace();
    }
    return Arrays.toString(Base64.encode(encrypted, Base64.DEFAULT));
}

and I use this to decrypt in PHP:
$data = mcrypt_decrypt(MCRYPT_RIJNADEAL_128, $key, $cipherText, MCRYPT_MODE_ECB);

The problem is that it doesn't decrypt to the wanted plain text in PHP.

A: Arrays#toString() returns an array representation with [, ] and commas. You can directly get a Base 64 encoded string through the Base64 class:
return Base64.encodeToString(encrypted, Base64.DEFAULT);

In PHP you need to decode the ciphertext before use
$cipherText = base64_decode($cipherText);

To make sure you use the same mode of operation, you need to provide a full cipher string (providers may have different defaults, so you need to specify it yourself to prevent problems):
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

And use the same padding (PKCS#5/PKCS#7 padding is the same) in PHP (only provides ZeroPadding). This answer provides drop in code for that.

Further security considerations
Don't use ECB mode. It is very insecure. Use at the very least CBC mode with a random IV. The IV doesn't have to be secret, so you can simply prepend it to the ciphertext before you encode and send it. The IV can be sliced off before decryption and used for decryption.
To make it even more secure, you should authenticate your ciphertexts. This can be with an authenticated mode like GCM or with an encrypt-then-MAC scheme with a strong MAC like HMAC-SHA256.


text:
Q: Docker: How to create an environment variable in the host machine that points to a directory in a docker container? I am using Docker to run four containers to run a backend web application. The backend web application uses buildout to assemble the software.
However, the frontend, which is installed and runs on the host machine (that is, not using Docker), needs to access the buildout directory inside one of the four docker containers.
Moreover, the frontend uses an environment variable called NTI_BUILDOUT_PATH that is defined on the host machine. NTI_BUILDOUT_PATH must point to the buildout directory, which is inside the aforementioned container.
My problem is that I do not know how to define NTI_BUILDOUT_PATH such that it contains a directory that points towards the buildout directory that is needed by the front end for SSL certificates and other purposes.
I have researched around the web and read about volumes and bind mounts but I do not think they can help me in my case.

A: One way you can do that is by copying your buildout folder into the host machine using docker cp
docker cp <backend-container-id>:<path-to-buildout> <path-to-host-folder>

For Example if your backend's container_id is d1b5365c5bca and your buildout folder is in /app/buildout inside the container. You can use the following command to copy it to the host.
docker cp d1b5365c5bca:/app/buildout /home/mahmoud/app/buildout

After that you docker rm all your containers and recreate new ones with a bind mount to the buildout folder in the host. So following the previous example we'll have
docker run -v /home/mahmoud/app/buildout:/app/buildout your-backend-image
docker run -v /home/mahmoud/app/buildout:/app/buildout -e NTI_BUILDOUT_PATH=/app/buildout your-frontend-image


text:
Q: linux shell script exec(wget) in java I make server monitering application in java.
I exec shell script(wget --no-cache -t 1 -T 1000 --spider ServerURL 2>&1 | grep 'HTTP')
I gain result
but in java exec shell script..
I don`t gain result...
source code
String command = "wget --no-cache -t 1 -T 1000 --spider " + monitering_url +" 2>&1 | grep 'HTTP'";
shellCmd(command);
public static void shellCmd(String command) throws Exception {
          Runtime runtime = Runtime.getRuntime();
          Process process = runtime.exec(command);
                    //Thread.sleep(5000);
          InputStream is = process.getInputStream();
          InputStreamReader isr = new InputStreamReader(is);
          BufferedReader br = new BufferedReader(isr);
          String line;
          while((line = br.readLine()) != null) {
              System.out.println(line);
          }
      }

monitering_url = serverURL
I want result print...
help me!!

A: Your command is a shell script, and must be passed to a shell for interpretation:
Process process = runtime.exec(new String[] {"/bin/sh", "-c", command});

Note the use of the array to pass the arguments to the shell process. Without it the command string will be tokenised before being passed to the interpreter, which is not what you want.


text:
Q: Spring Actuator JVM metrics not showing when GlobalMethodSecurity is enabled I'm setting up Spring Actuator in an existing Spring Boot application. Everything works fine, except that JVM metrics (CPU, memory, GC, ..) are missing from the one returned by /metrics endpoint.
I'm using Spring Boot 2.1.4. I explicitly configured GlobalMethodSecurity and exluded SecurityAutoConfiguration.
This is my security configuration:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {

    private final IAuthService authService;

    @Autowired
    public MethodSecurityConfig(IAuthService authService) {
        this.authService = authService;
    }

    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        return new CustomMethodSecurityExpressionHandler(authService);
    }
}

While these are the metrics properties that I'm using:
management:
  security:
    enabled: false
  server:
    address: 0.0.0.0
    port: 8080
  endpoints:
    web:
      exposure.include: metrics,prometheus
      exposure.exclude:
  metrics:
    enable.jvm: true

With this configuration, available metrics are:
{
  "names": [
    "jdbc.connections.active",
    "jdbc.connections.max",
    "jdbc.connections.min",
    "tomcat.global.sent",
    "tomcat.sessions.created",
    "tomcat.global.request.max",
    "hikaricp.connections.idle",
    "hikaricp.connections.pending",
    "tomcat.global.request",
    "tomcat.sessions.expired",
    "hikaricp.connections",
    "tomcat.global.received",
    "hikaricp.connections.active",
    "hikaricp.connections.creation",
    "tomcat.sessions.rejected",
    "tomcat.threads.config.max",
    "hikaricp.connections.max",
    "hikaricp.connections.min",
    "tomcat.global.error",
    "tomcat.sessions.active.current",
    "tomcat.sessions.alive.max",
    "hikaricp.connections.usage",
    "tomcat.threads.current",
    "hikaricp.connections.timeout",
    "tomcat.sessions.active.max",
    "hikaricp.connections.acquire",
    "tomcat.threads.busy"
  ]
}

If I temporarly remove @EnableGlobalMethodSecurity, the available metrics become:
{
  "names": [
    "jvm.threads.states",
    "jdbc.connections.active",
    "process.files.max",
    "jvm.memory.used",
    "jvm.gc.memory.promoted",
    "jvm.memory.max",
    "system.load.average.1m",
    "jvm.gc.max.data.size",
    "jdbc.connections.max",
    "jdbc.connections.min",
    "jvm.memory.committed",
    "system.cpu.count",
    "tomcat.global.sent",
    "jvm.buffer.memory.used",
    "tomcat.sessions.created",
    "jvm.threads.daemon",
    "system.cpu.usage",
    "jvm.gc.memory.allocated",
    "tomcat.global.request.max",
    "hikaricp.connections.idle",
    "hikaricp.connections.pending",
    "tomcat.global.request",
    "tomcat.sessions.expired",
    "hikaricp.connections",
    "jvm.threads.live",
    "jvm.threads.peak",
    "tomcat.global.received",
    "hikaricp.connections.active",
    "hikaricp.connections.creation",
    "process.uptime",
    "tomcat.sessions.rejected",
    "process.cpu.usage",
    "tomcat.threads.config.max",
    "jvm.classes.loaded",
    "hikaricp.connections.max",
    "hikaricp.connections.min",
    "jvm.classes.unloaded",
    "tomcat.global.error",
    "tomcat.sessions.active.current",
    "tomcat.sessions.alive.max",
    "jvm.gc.live.data.size",
    "log4j2.events",
    "hikaricp.connections.usage",
    "tomcat.threads.current",
    "jvm.gc.pause",
    "hikaricp.connections.timeout",
    "process.files.open",
    "jvm.buffer.count",
    "jvm.buffer.total.capacity",
    "tomcat.sessions.active.max",
    "hikaricp.connections.acquire",
    "tomcat.threads.busy",
    "process.start.time"
  ]
}

I expect that the security of the method should not affect the publication of JVM metrics.
How should I configure Actuator/Security in order to have all metrics?
Thanks in advance for the help!

A: I managed to make it work by adding this configuration:
@Configuration
public class ActuatorMetricsConfig {

    @Bean
    InitializingBean forcePrometheusPostProcessor(BeanPostProcessor meterRegistryPostProcessor, PrometheusMeterRegistry registry) {
        return () -> meterRegistryPostProcessor.postProcessAfterInitialization(registry, "");
    }

}


text:
Q: How can i get more then 50 results to display in excel using mysql? I've searched and searched and i can't find my answer. i'm hoping someone can help. I have a code that searches a mysql database and displays X amount of results on a website. I searcher can then export the results into an excel spreadsheet. my problem is the results come back in the hundreds and the spreadsheet will only show me 50. there is a lot more to this code but something is telling me perhaps it's in here and to save putting over 400 lines of code in i'm showing this.
$sql .= ",
                        IF (cycle_id = 4,
                            " . ((4 == $next_available_quarter) ?
                                "'" . $next_available_quarter_month[4] . "-{$next_available_quarter_year}'" :
                                "'" . $next_available_quarter_month[4] . "-" . ($next_available_quarter_year+1) . "'") . "
                            ,
                            IF (cycle_id = 3,
                                " . ((3 == $next_available_quarter) ?
                                    "'" . $next_available_quarter_month[3] . "-{$next_available_quarter_year}'" :
                                    "'" . $next_available_quarter_month[3] . "-" . ($next_available_quarter_year+1) . "'") . "
                                ,
                                IF (cycle_id = 2,
                                    " . ((2 == $next_available_quarter) ?
                                        "'" . $next_available_quarter_month[2] . "-{$next_available_quarter_year}'" :
                                        "'" . $next_available_quarter_month[2] . "-" . ($next_available_quarter_year+1) . "'") . "
                                    ,
                                    " . ((1 == $next_available_quarter) ?
                                        "'" . $next_available_quarter_month[1] . "-{$next_available_quarter_year}'" :
                                        "'" . $next_available_quarter_month[1] . "-" . ($next_available_quarter_year+1) . "'") . "
                                    )
                                )
                            )
                        )
                    )
                )
            ) as next_run
    FROM
        tax_search_loans tsl
    LEFT JOIN
        tax_searches ts
    ON
        (tsl.tax_search_loan_id = ts.tax_search_loan_id)
    LEFT JOIN
        tax_search_results tsr
    ON
        (tsr.tax_search_id = ts.tax_search_id)
    LEFT JOIN
        states
    ON
        (tsl.state_id = states.state_id)
    LEFT JOIN
        tax_search_loan_officers tslo
    ON
        (tslo.tax_search_loan_officer_id = tsl.tax_search_loan_officer_id)
    WHERE
        tsl.active = 'Y' AND
        tslo.active = 'Y' AND
        tslo.customer_code IN ('" . implode("','", explode(',', $DB->cleanString($_GET['custcodes']))) . "') AND
        (ts.active IS NULL OR ts.active = 'Y') AND
        (tsr.active IS NULL OR tsr.active = 'Y')
        LIMIT 0, 50
    ";

A: Remove the LIMIT 0, 50 statement or change it to whatever you want your max rows displayed to be.


text:
Q: Symfony sfDoctrineGuard insert-sql error 1005 I've fresh isntall of Symfony 1.4 with Doctrine ORM.
I'm looking to install the plugin sfDoctrineGuard.  I followed the instructions here:
http://www.symfony-project.org/plugins/sfDoctrineGuardPlugin
all works fine until this step:
symfony doctrine:insert-sql
when I get an error:

SQLSTATE[HY000]: General error: 1005 Can't create table 'kickboxing.#sql-2b5b_a8f' (error 150) Failing Query "ALTER TABLE profile ADD CONSTRAINT profile_sf_guard_user_id_sf_guard_user_id FOREIGN KEY (sf_guard_user_id) REFERENCES sf_guard_user(id)

It did seem to create some tables:
profile
sf_guard_forgot_password
sf_guard_group
sf_guard_group_permission
sf_guard_permission
sf_guard_remember_key
sf_guard_user
sf_guard_user_group
sf_guard_user_permission
any ideas?
UPDATE:
I'm after spotting this really has nothign to do with doctrine/symfony. The issue seems to be with mysql I ran the alter command above in MySQL and of course I get same error.
For reference on that I've Debian Squeeze installed and mysql 5.
UPDATE2 :
when i run
SHOW INNODB STATUS;

I get

LATEST FOREIGN KEY ERROR
110927  7:58:35 Error in foreign key constraint of table _kickboxing/#sql-2b5b_a86:
  FOREIGN KEY (sf_guard_user_id) REFERENCES sf_guard_user(id):
  Cannot find an index in the referenced table where the
  referenced columns appear as the first columns, or column types
  in the table and the referenced table do not match for constraint.
  Note that the internal storage type of ENUM and SET changed in
  tables created with >= InnoDB-4.1.12, and such columns in old tables
  cannot be referenced by such columns in new tables.
  See http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
  for correct foreign key definition.

A: Looks like a mySql issue. You can get a full (better) description of the error by logging into the mysql console and running

show innodb status

then look for the LATEST FOREIGN KEY ERROR to get an idea of what went wrong

A: I am using Symfony 1.4.16 and to configure sfDoctrineGuardPlugin, I followed  prettyscripts.com but the schema.yml should be as follows;
Note: user_id is integer(8) thats what the size of sf_guard's id column type is.
sfGuardUserProfile:
  tableName: sf_guard_user_profile
  actAs:        { Timestampable: ~ }
  options:      { collate: utf8_unicode_ci, charset: utf8 }
  columns:
    id:         { type: integer(8), primary: true, autoincrement: true }
    user_id:    { type: integer(8), notnull: true }
    fullname:   { type: string(80) }
    email:      { type: string(100) }
  relations:
    User:
      class: sfGuardUser
      foreign: id
      local: user_id
      type: one
      onDelete: cascade
      foreignType: one
      foreignAlias: Profile


text:
Q: Sound not working in Ubuntu 14.04
Initially it was working fine and suddenly it stopped working. After installing AMAROK audio player.
This is about the ALSAMIXER

Looking for help ? Thanks in advance

A: *

*Reinstall alsa-utils
sudo apt-get install alsa-utils --reinstall

*Download and install alsa-lib
On this page you will find all versions https://launchpad.net/ubuntu/+source/alsa-lib
Or find Here a link to version 1.0.25-4(the stable version)

*

*Extract the archive and run the following code in the extracted directory
./configure && make

*Then
sudo make install


text:
Q: react-native how to assign assign multiple .replace() as a variable? I am using .replace() method to filter my data.
Like this :
this.state.date.toString().slice(13,15)
.replace('Jan', '01')
.replace('Feb', '02')
.replace('Mar', '03')
.replace('Apr', '04')
.replace('May', '05')
.replace('Jun', '06')
.replace('Jul', '07')
.replace('Aug', '08')
.replace('Sep', '09')
.replace('Oct', '10')
.replace('Nov', '11')
.replace('Dec', '12')
.replace(/\s/g, '')

The problem is that I need to apply this method in multiple places and I want to assign all the .replace() method as a variable.
edited
I want to assign .replace() as a variable like this
const filter = .replace('Jan', '01')
.replace('Feb', '02')
.replace('Mar', '03')
.replace('Apr', '04')
.replace('May', '05')
.replace('Jun', '06')
.replace('Jul', '07')
.replace('Aug', '08')
.replace('Sep', '09')
.replace('Oct', '10')
.replace('Nov', '11')
.replace('Dec', '12')
.replace(/\s/g, '')

So I could use it like this :
this.state.date.toString().slice(13,15).filter

A: Sounds like you want to extract the logic into a function:
const changeToMonthNums = str => str
.replace('Jan', '01')
.replace('Feb', '02')
.replace('Mar', '03')
.replace('Apr', '04')
.replace('May', '05')
.replace('Jun', '06')
.replace('Jul', '07')
.replace('Aug', '08')
.replace('Sep', '09')
.replace('Oct', '10')
.replace('Nov', '11')
.replace('Dec', '12')
.replace(/\s/g, '');

// ...

const thisDateWithMonthNums = changeToMonthNums(this.state.date.toString().slice(13,15))

To be less repetitive, you could use an array:
const months = ['Jan', 'Feb', 'Mar', ...];
const pattern = new RegExp(months.join('|'), 'g');
const changeToMonthNums = str => str
  .replace(
    pattern,
    match => String(months.indexOf(match) + 1).padStart(2, '0')
  )
  .replace(/\s/g, '');

const months = ['Jan', 'Feb', 'Mar'];
const pattern = new RegExp(months.join('|'), 'g');
const changeToMonthNums = str => str
  .replace(
    pattern,
    match => String(months.indexOf(match) + 1).padStart(2, '0')
  )
  .replace(/\s/g, '');

console.log(changeToMonthNums('foo Feb bar'));