Some devices don't receive UDP broadcasts when screen off

Question: I can't get a Note 2 running 4.1.2 or Nexus One running 2.2 to stay 'awake enough' with the screen off to keep acting on UDP broadcast packets. I have tried various wakelocks and permissions (see below), it works fine on a Desire HD on 2.3, a Huawei U8110 (T-Mobile pulse mini) on 2.1 and a Samsung Galaxy Mini on 2.2.1.
It does receive and act on new TCP connections directly to its IP/port, but not broadcast UDP packets. If I tap the power button to wake the screen it immediately responds to broadcasts.
Forcing the the screen to stay on (PowerManager.SCREEN_DIM_WAKE_LOCK or higher) does keep it listening but that's not practical.
I'm acquiring wakelocks:
powerManager.newWakeLock(PARTIAL_WAKE_LOCK)
wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL)
wifiManager.createMulticastLock()

And declaring permissions:
android.permission.INTERNET
android.permission.WAKE_LOCK
android.permission.CHANGE_WIFI_MULTICAST_STATE
android.permission.ACCESS_WIFI_STATE
android.permission.CHANGE_WIFI_STATE

System Wifi sleep policy is 'never'.
The working devices all timeout their screens but still respond to the UDP broadcasts.
In the debugger's Threads view I can see it is still blocking at
    DatagramSocket.receive()
whereas on the working devices that returns with a packet which is then logged to logcat.
All devices are running the same .apk.
Comment: Are you making it in a separated Thread and is that Thread still running when the screen off?
Comment: Yes. I think it's still running, it's in DDMS' Threads view and doesn't seem to change when the screen goes off. And it looks the same as the TCP listen Thread which does work.
Answer: An update for anyone else with the same problem:
Google seem to think this should work fine:
http://code.google.com/p/android/issues/detail?id=34278
The Nexus One is old so I guess nobody cares.
The Note 2 however is not so I asked in Samsung's developer forum. They don't care either:
http://developer.samsung.com/forum/board/thread/view.do?boardName=General&messageId=247968#postId247968
My current workaround is to provide an option in user-preferences to grab a full wakelock instead of the partial. I added code to cover my UI with a black screen which disappears on a tap; although the backlight is still on this is less annoying and stops potential screen burn. Turning the other lights (capacative buttons) off should be doable but IMHO it's 'good' to let the user know their phone is actually still fully awake.
It stops the device's normal lockscreen timeout. A manual power button press will lock but turns the screen off and so stops UDP receiving, on wake the lockscreen stays on forever until the user unlocks.
So this provides a poor user experience but it's the best I've found.
Any suggestions welcome.


Video playing: Skipped frame when on battery

Question: When I'm playing a video on battery (either youtube (example), or local VLC ), there is noticeable stutter/skipped frame only when I'm battery powered.
I guess there is some kind of power optimisation to disable somewhere ?
env: ubuntu 20.04 on thinkpad t14s (integrated intel graphics), hardware acceleration enabled
PS:
The refresh rate settings GUI also looks kinda weird, I have a 60hz screen but a bunch of option shows up (59.9Hz, 60.03Hz, 119.94Hz, 120.02Hz, I've selected 60.03Hz):
Answer: I found the culprit !!!!
It's indicator-multiload, uninstalled it
https://launchpad.net/indicator-multiload


Cannot get a cookie using ajax request and jqXHR object

Question: I made an ajax request .I need to access Cookie or Set-Cookie properties. I tried to get cookie from headers of jqXHR object as jqxhr.getAllResponseHeaders(). Did not showed any headers relating to cookies. Why? How to get Cookie or Set-Cookie properties?
var jqxhr = $.ajax({
                    url: 'MYurl,
                    success: function(data) {
                        // success, do work
                        alert(jqxhr.getAllResponseHeaders());
                    },
                    error: function(data) {
                        // error, handle failure
                    }
                });

UPDATE1:
Why Firefox classify as Rejected Cookies the Cookies received by Ajax?

UPDATE2:
4.7.3 The getResponseHeader() method

Returns the header field value from the response of which the field
  name matches header, unless the field name is Set-Cookie or
  Set-Cookie2.
Comment: There's no need, when you make Ajax request the cookie gets sent as well, automatically.
Comment: Those cookies are probably HttpOnly, which is why you can't read them; otherwise, evaluate `document.cookie`.
Comment: Is there a way to specify some other type of `Cookie` so it could be easily accessed?
Comment: Do you really need the cookie though? Why do you need it?
Comment: I need to Log in and keep the session for current user using ajax.
Answer: Maybe have a look at this jQuery Plugin:
https://github.com/carhartl/jquery-cookie
I' ve use it before with a node.js socket application and it works great!
Comment: Thanks! I have tried it - works fine but first I need to get a cookie using ajax. So far I cannot get one because `jqxhr.getAllResponseHeaders()` does not have `Cookie` or `Set-Cookie` headers. How can I get it working?


AWS Lambda becomes unresponsive after TypeError (Node.js 4.3)

Question: I'm using AWS Lambda with Node.js 4.3, and has DynamoDB get in the code:
dynamodb.get(params, function(err, data) {
    if (err) {
        console.log("Error: " + JSON.stringify(err));
        callback("Error: DB problem");
    }
    else {
            callback(null, data.Item.someAttribute);
    }
});

I know that it's wrong, and I need to check that Item actually exists before accessing it. That's not the point now.
I get TypeError:
TypeError: Cannot read property 'someAttribute' of undefined
Which is ok, when there is no such item, it fails. The problem that after that lambda became to be unresponsive, there are other healthy requests come to that lambda, and lambda just fails every time with timeout.
As you can see in the logs below (from CloudWatch) even 40(!) minutes after the error, the lambda is still unresponsive. And I know nothing happens there, as in the beginning if the code I'm printing "Input to Lambda" which can be seen in first request. In all times out requests there is no such print, Lambda just became dead.
START RequestId: xxx Version: 1
2017-05-12T09:20:18.739Z    Input to Lambda: ...
2017-05-12T09:20:19.770Z    xxx TypeError: Cannot read property 'someAttribute' of undefined at ...
END RequestId: xxx
REPORT RequestId: xxx   Duration: 1094.61 ms    Billed Duration: 1100 ms
RequestId: xxx Process exited before completing request

START RequestId: xxx Version: 1
END RequestId: xxx
REPORT RequestId: xxx   Duration: 3002.12 ms    Billed Duration: 3000 ms
2017-05-12T09:24:08.556Z xxx Task timed out after 3.00 seconds

...

START RequestId: xxx Version: 1
END RequestId: xxx
REPORT RequestId: xxx   Duration: 3001.15 ms    Billed Duration: 3000 ms
2017-05-12T10:01:14.672Z xxx Task timed out after 3.00 seconds

Fixing the code and reuploading it to the Lambda makes it working, but how can this be that some error make the whole endpoint unresponsive. Waiting some hours also makes Lambda work again.
I'm thinking of removing "use strict", but it doesn't look like a good solution.
Any thoughts on what can be the reason to dead lambda and how to avoid this in future?
Comment: Are you returning any value from the lambda function? The timeouts usually happen when there is no response from the lambda function. Also, your timeout value seems to be 3 seconds. Did you try increasing the timeout value?
Comment: I know nothing happens there, as in the beginning of the code I'm printing "Input to Lambda" which can be seen in first request. In all timed out requests there is no such print, which mean it's just not responding.
Answer: In fact there are many cases when Lambda becomes unresponsive, e.g.:

Parsing not valid json:
exports.handler = function(event, context, callback)
{
    var nonValidJson = "Not even Json";
    var jsonParse = JSON.parse(nonValidJson);

Accessing property of undefined variable:
exports.handler = function(event, context, callback)
{
    var emptyObject = {};
    var value = emptyObject.Item.Key;

Not closing mySql connection after accessing RDS leads to Lambda timeout and then it becomes non-responsive.

It's revealed that it's a bug, known by AWS team for almost a year:
https://forums.aws.amazon.com/thread.jspa?threadID=238434&tstart=0
Unfortunately it's still not fixed, after some tests it's revealed that in fact Lambda tries to restart (reload the container?), there is just not enough time. If you set the timeout to be 10s, after ~4s of execution time Lambda starts working, and then in next runs comes to behave normally. I've also tried playing with setting:
context.callbackWaitsForEmptyEventLoop = false;

and putting all 'require' blocks inside handler, nothing really worked. The only way to prevent Lambda becoming dead is setting bigger timeout, 10s should be more than enough as a workaround protection against this bug.


Downloading the Azure Blob Container using R for specific dates

Question: I want to download all the folder JSONs and Subfolder JSONs for specific dates using R.
The folder structured that is followed is:
year/month/day/hour/min/xxxxxx.json
I have the SAS url for accessing the Azure BLOB container.
Answer: I got the solution for the same. There is api_url from Azure Storage Services. We can hit the URL with prefix of the directory. The GET will return a XML. We can parse the XMl to get the list of the URLs. URLs are path to the .json file.
reference: https://learn.microsoft.com/en-us/rest/api/storageservices/enumerating-blob-resources#ContainerList


MYSQL case when in statement not working

Question: MYSQL:
SELECT    `item`.*,
          CASE(
             WHEN `item_sub_category`.`sub_category` IN('65', '66','67', '68')
             AND       `item_category`.`category` IN('35', '36')
             THEN 0 ELSE 1
          ) AS condition
FROM      `items`
LEFT JOIN `item_category`
    ON        `item_category`.`item` = `item`.`id`
LEFT JOIN `item_sub_category`
    ON        `item_sub_category`.`item` = `item`.`id`
LEFT JOIN `cart`
    ON        `cart`.`item` = `item`.`id`
    AND       `cart`.`USER` = 3
LEFT JOIN `user_users`
    ON        `user_users`.`id` = 3
WHERE     `cart`.`item` IS NULL
    AND       `item_sub_category`.`sub_category` IN('65','66', '67', '68')
    OR        `item_category`.`category` IN('35', '36')
GROUP BY  `item`.`id`
ORDER BY  `item`.`id` DESC, `item`.`feature` DESC
limit 4

Anyone can please tell me why ut displaying syntax error and How can I resolve the syntax error? Maybe syntax error is on below given Line.
  CASE(
     WHEN `item_sub_category`.`sub_category` IN('65', '66','67', '68')
     AND       `item_category`.`category` IN('35', '36')
     THEN 0 ELSE 1
  ) AS condition

Comment: Your `CASE` expression is missing an `END`: `... THEN 0 ELSE 1 END ) AS condition`
Comment: Still, the error continues.
Comment: This means there is an additional error in your code. Can you post the actual error message that you get?
Answer: Put it like:
CASE
     WHEN item_sub_category.sub_category IN(65, 66,67, 68)
     AND  item_category.category IN(35, 36)
     THEN 0 ELSE 1 END
   AS condition

i.e. put and END and do NOT use brackets. Brackets, if used, should encapsulate the entire case statement, not from when.
Also, you may avoid single quotes if the numbers are integers.


Wordpress Enqueue Js scripts

Question: I am having trouble getting wp_enqueue functions to work. I've looked at all the documentation on it but am having trouble sifting through and finding out what is supposed to go where.
so far I understand that I am supposed to register and enqueue the files from the functions.php file of the theme I am creating. So that is exactly what I do. I create some PHP tags and drop it in the middle of them, at the bottom of the page. Save and Upload.
When I reload, it just returns a blank white screen, must be an error in the code or something.
Here is the function:
<?php
function add_scripts(){
wp_register_script('jquery', 'http://code.jquery.com/jquery-1.5.2.min.js');
wp_register_script('nivo', get_bloginfo('url').'/scripts/nivo.js');
wp_register_script('slimbox',get_bloginfo('url').'/scripts/slimbox2.js');
wp_register_script('picasa', get_bloginfo('url').'/scripts/jquery.EmbedPicasaGallery.js');
wp_register_script('pwi',get_bloginfo('url').'/jquery.pwi-min.js');
wp_register_script('swf', get_bloginfo('url').'/jquery.swfobject.1-1-1.min.js');
wp_register_script('simpletube',get_bloginfo('url').'/scripts/jquery.simpletube.js');
wp_register_script('jqvalidate', get_bloginfo('url').'/jquery.jqvalidate.js');
wp_enqueue_script('jquery');
wp_enqueue_script('nivo');
wp_enqueue_script('slimbox');
wp_enqueue_script('picasa');
wp_enqueue_script('pwi')
wp_enqueue_script('swf');
wp_enqueue_script('simpletube')
wp_enqueue_script('jqvalidate');
}

add_action('init','add_scripts');
?>

So is there some sort of problem with my syntax? I'm not that strong with PHP.
Any help is greatly appreciated. Thanks!
Comment: You've got two `wp_enqueue_script('picasa');`, missing a `wp_enqueue_script('nivo');`.
Comment: Thanks, I dont think that is the problem though. I fixed that and still the same result
Comment: See my answer below. You're missing some semi-colons (`;`) in your code.
Answer: It's kind of hard to debug it without seeing the whole file but the fact you get a 'blank page' suggests there's definitely something larger than a syntax problem somewhere.
Do you definitely have correctly nested php tags?  i.e.
<?php

some code

<?php

some more code

?>

some more code

?>

will give you problems.
Also, it's now common practice to leave the last ?> from the end of the file (it means you wont have any issues with having whitespace after the closing tags and they're not necessary)
On top of that, you've used wp_register_script('jquery'...) - WordPress already has jquery registered. If you wish to re-register it, you need to wp_deregister_script('jquery') first. I'd also only do that outside of the admin, so:
if(!is_admin()){wp_deregister_script('jquery'); <your wp_register_script stuff> }
If these things don't help, copy and paste your entire functions.php file (use pastebin.com and give us a link)
As an aside, you're using get_bloginfo('url') several times - which means you're running lots of unnecessary calls to the database. Stick it into a variable and save yourself a little overhead:
$my_url = get_bloginfo('wpurl');

wp_register_script('thing', $my_url.'/script/location/file.js');

Oh! One more thing, I don't think url is an allowed argument for get_bloginfo() I think you want wpurl
Codex page on get_bloginfo() function
Good luck!
Answer: Missing ; for the following two lines:
wp_enqueue_script('pwi')
wp_enqueue_script('simpletube')

Answer: Instead of your code I would use:
<?php
function add_scripts(){
  wp_enqueue_script('jquery', 'http://code.jquery.com/jquery-1.5.2.min.js');
  wp_enqueue_script('nivo', get_bloginfo('url').'/scripts/nivo.js');
  wp_enqueue_script('slimbox',get_bloginfo('url').'/scripts/slimbox2.js');
  wp_enqueue_script('picasa', get_bloginfo('url').'/scripts/jquery.EmbedPicasaGallery.js');
  wp_enqueue_script('pwi',get_bloginfo('url').'/jquery.pwi-min.js');
  wp_enqueue_script('swf', get_bloginfo('url').'/jquery.swfobject.1-1-1.min.js');
  wp_enqueue_script('simpletube',get_bloginfo('url').'/scripts/jquery.simpletube.js');
  wp_enqueue_script('jqvalidate', get_bloginfo('url').'/jquery.jqvalidate.js');
}

add_action('wp_enqueue_scripts', 'add_scripts');

So please notice I have removed "wp_register_script" as using that is totally unnecessary if you are going to call wp_enqueue immediately after register.
wp_register_script

Is used so that you can afterwards call it ANYWHERE else in code without including the path.
Also big change is that I'm not calling the function from
init

But I'm calling it from
wp_enqueue_scripts

Also please consider adding additional parameters to your wp_enqueue_script such as
wp_enqueue_script( string $handle, string $src = '', array $deps = array(), string|bool|null $ver = false, bool $in_footer = false )

Wordpress Enqueue Js scripts


Building a plot for each unique value of a column

Question: I have data with multiple variables and I want to make a plot for each of the unique values in one column. I looked at multiple answers on here for similar problems but I couldnt solve mine.
An example of the dataset looks as follows:
structure(list(ID = c(1, 1, 1, 2, 2), Date = c("01/02/20", "01/03/20",
"01/05/20", "01/02/20", "01/05/20"), New = c(10, 5, 5, 10, 5),
    Old = c(20, 20, 20, 20, 20), Percentage = c(0.5, 0.25, 0.25,
    0.5, 0.25)), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"))

ID      Date          New    Old   Percentage
1       01/02/20      10     20    0.5
1       01/03/20      5      20    0.25
1       01/05/20      5      20    0.25
2       01/02/20      10     20    0.5
2       01/05/20      5      20    0.25

I wanted to do a for loop that goes over the unique values of ID and plot the new and old vs date. Also maybe another facet that should the percent change but mainly the first comparison plot. I tried first to make it as date vs new as follow:
for (ii in unique(data$ID)) {
  plt <- ggplot(data %>% filter(ID == ii),
                aes(x = "Month",
                    y = "New")) +
    geom_point(color = "dodgerblue3") +
    theme_minimal()
  print(plt)

}

The result basically gave me a on point plot which I didnt understand. How can I add the Old comparison and also another plot for the percentage.
Comment: you cannot have aes(x="Month", y="New" ..), it should be aes(x=Month,y=New..)? Then again, how come Monthis not in the dataset you showed?
Comment: And please be more precise about what you're actually looking for. Otherwise it is really hard to help you.
Comment: I'll post a solution below I really don't know if it actually is, what you are looking for.
Answer: Is this somewhat what you are looking for?
library(tidyverse)
library(lubridate)

df %>%
    mutate(Date = mdy(Date)) %>%
    pivot_longer(cols = c("New", "Old"), names_to = "newOrOld") %>%
    ggplot(aes(Date, value, colour = newOrOld)) +
    geom_point() +
    facet_grid(. ~ ID)

Answer: -Regarding your loop, I think you could just use a facet function instead
-About the old/new question, I think that your problem comes from your data structure, which is not tidy.
try this :
## get tidy data
tidy_data <- data %>% pivot_longer(c("New", "Old"), names_to = "Age", values_to = "Number")

## get the plots (facet_wrap is used to have multiple plots)
plt <- ggplot(tidy_data, aes(x = Date, y = Number, color = Age)) + geom_point() + facet_wrap(~ ID)
plt


I added a CSS animation but it doesn't work and everything looks fine

Question: So I tried to add a simple vibration animation to a link from my website but it simply doesn't work. Anyone see anything wrong with my code?
I took the animation code from animista.net and there they were working
Here is my code:

a {
  text-decoration: none;
  animation: vibrate 1s linear infinite both;
}

@keyframes vibrate {
  0% {
    transform: translate(0);
  }
  20% {
    transform: translate(-2px, 2px);
  }
  40% {
    transform: translate(-2px, -2px);
  }
  60% {
    transform: translate(2px, 2px);
  }
  80% {
    transform: translate(2px, -2px);
  }
  100% {
    transform: translate(0);
  }
}
Drop me a line and let's do cool things together!
Comment: `a`nchors are `inline`. Make that `display: inline-block;`.
Answer: You can set position: absolute or change display value to block-level (because a is inline by default) for transform to work.

a {
  text-decoration: none;
  display: block; /* Or inline-block */
  animation: vibrate 1s linear infinite both;
}

@keyframes vibrate {
  0% { transform: translate(0); }
  20% { transform: translate(-2px, 2px); }
  40% { transform: translate(-2px, -2px); }
  60% { transform: translate(2px, 2px); }
  80% { transform: translate(2px, -2px); }
  100% { transform: translate(0); }
}
Drop me a line and let's do cool things together!
Answer: The CSS animation is not used to target anchor.
so please use div for easy animation effects
<!DOCTYPE html>

Drop me a line and let's do cool things together!


[Qt 5.6][QPixmap] Getting "black picture with colored pixels" in QLabel when setting a QPixmap in it

Question: (Using Visual Studio Community 2015, Qt 5.6.0)
For training purposes, I'm trying to display a RGB QPixmap through a QLabel using signals and slots events. (to display a sort of color preview)
For this, I added three sliders for each value (r, g and b). When I update for example the red slider, it is supposed to generate a new QPixmap with the color values then put it into a QLabel, like this :
void                Application::updateColorLabel(int value) {
    int             r, g, b;
    QPixmap         pixmap;
    QColor          color;

    this->ui.label_minValueR->setNum(value);
    pixmap = QPixmap(this->ui.label_color_preview->size());
    r = this->ui.label_minValueR->text().toInt();
    g = this->ui.label_minValueG->text().toInt();
    b = this->ui.label_minValueB->text().toInt();
    color = QColor(r, g, b);
    this->ui.label_color_preview->setPixmap(pixmap);
}

It doesn't work very well, since I get a black QLabel with few colored pixels, like this. I don't really know why it displays this.
Can someone figure it out with me, please ?
Comment: `color` is unused, and the pixmap `pixmap` is allocated with a certain size but left uninitialized. Are you missing a `pixmap.fill(color);` call?
Comment: @peppe Thank you mate, I post an answer mentioning you. :)
Answer: Well, @peppe was right. I forgot to fill the QPixmap with the color. :)
void                Application::updateColorLabel(int value) {
    int             r, g, b;
    QPixmap         pixmap;
    QColor          color;

    this->ui.label_minValueR->setNum(value);
    r = this->ui.label_minValueR->text().toInt();
    g = this->ui.label_minValueG->text().toInt();
    b = this->ui.label_minValueB->text().toInt();
    color = QColor(r, g, b);
    pixmap = QPixmap(this->ui.label_color_preview->size());
    pixmap.fill(color);
    this->ui.label_color_preview->setPixmap(pixmap);
}

Thank you for your answer !


How to add selected in the below code?

Question: How to add selected in the below code?
echo '<select class="w-select selection-produit" id="field" name="Ville">';
echo '<option value="">Choisir une ville...</option>';
$req19="SELECT * FROM ville";
$res19=mysql_query($req19);

while($data4=mysql_fetch_array($res19)){
  echo '<option value="'.$data4['Nom_ville'].'">'.$data4['Nom_ville'].'</option>';
}
echo '</select>';

Comment: What exactly are you asking for?
Comment: you just add it. The *operative* word here is `selected`.
Answer: As pointed out in the comments, just use selected. E.g. the following code checks if the town is Mulhouse (où est le musée du chemin de fer...) and if so selects this entry.
echo '<select class="w-select selection-produit" id="field" name="Ville">';
echo '<option value="">Choisir une ville...</option>';
$req19="SELECT * FROM ville";
$res19=mysql_query($req19);
while($data4=mysql_fetch_array($res19)) {
    // check if the town is equal to Mulhouse
    // equal to if (this) else (that)
    $sel = ($data4['Nom_ville'] == 'Mulhouse')?"selected":"";
    echo "<option value='".$data4['Nom_ville']."' $sel>".$data4['Nom_ville']."</option>";
}
echo '</select>';

Comment: When I click the Search button is missing
Answer: $valueWantSelect="the value you want selected";
$define = "";
echo '<select class="w-select selection-produit" id="field"      name="Ville">';
echo '<option value="">Choisir une ville...</option>';
$req19="SELECT * FROM ville";
$res19=mysql_query($req19);

while($data4=mysql_fetch_array($res19))

{
$define = ($data4['Nom_ville'] == $valueWantSelect) ?  "selected='selected'" : "";

echo '<option value="'.$data4['Nom_ville'].'"  '.$define.'>'.$data4['Nom_ville'].'</option>';

$define="";
}
echo '</select>';

Comment: It is better to add some description or commentary to your answer describing how your answer works to solve the problem in the question. Code-only answers are discouraged on SO.
Comment: @BrianKeller-Heikkila Indeed. Even more so, if the given answer has some serious formatting issues...
Comment: Thank you very much for solution ;)
Answer: Try like this hope it will work for you
foreach ($request as $data) {

                    if ($data->cat_id == $catee) {
                        echo "<option  selected = 'selected' value='" . $data->cat_id . "'>" . $data->cat_name . "</option>";
                    } else {
                        echo "<option value='" . $data->cat_id . "'>" . $data->cat_name . "</option>";
                    }
                }

How to add selected in the below code?


How to find total salary of all departments

Question: SELECT D_ID, SUM(SALARY)
FROM EMPLOYEE
GROUP BY D_ID.

I want to get total salary of all departments with this query.
Comment: Please tag DBMS, provide sample data, expected result, remove ALLCAPS.
Comment: Do you mean total salary by departments?
Comment: Welcome to Stack Overflow! Please take the [tour], have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask)
Comment: Does your query give you the salary sum per department? And you want the one total sum over all departments instead?
Comment: Thorsten Kettner ur right
Comment: any tip or answer??
Answer: If department wise sum then your query is proper.
SELECT D_ID, SUM(SALARY)
FROM EMPLOYEE
GROUP BY D_ID

If you want the total sum then can do a sum of salary.
SELECT SUM(SALARY)
FROM EMPLOYEE

If you want to display both a single query then use:
SELECT D_ID,
       SUM(SALARY) OVER (PARTITION BY D_ID) AS [Dept Salary],
       SUM(SALARY) OVER () AS [Total Salary]
FROM EMPLOYEE

Comment: SIR i want to show sum of  department wise salary and also sum of all department salaries in a single column
Comment: @MYasirLatifKassar single column or single query??
Comment: @MYasirLatifKassar If its single query, I have updated my answer.Please do check and let me know if you have any issue.
Answer: Ideal query should be as below:
SELECT D.D_ID, SUM(E.SALARY)
FROM DEPARTMENT D
LEFT JOIN EMPLOYEE E ON D.D_ID=E.D_ID
GROUP BY D.D_ID
UNION
SELECT 0 D_ID, SUM(SALARY) SALARY
FROM EMPLOYEE

Comment: IR i want to show sum of department wise salary and also sum of all department salaries in a single column – M Yasir Latif Kassar just now
Comment: Updated the query. The query will now show last record as sum of all salaries with 0 value in D_ID column.
Answer: From OP's comments, I think he is asking for this.
mysql> select * from xyz;
+------+------------+---------------+--------+------------+
| roll | name       | location      | salary | department |
+------+------------+---------------+--------+------------+
|    1 | Pranav     | Parasi        | 25000  | A          |
|    2 | Pragya     | Chitwan       | 20000  | A          |
|    3 | Prabhuddha | New Playmouth | 28000  | B          |
|    4 | Smriti     | Kathmandu     | 35000  | B          |
|    5 | Shruti     | Butwal        | 40000  | A          |
+------+------------+---------------+--------+------------+
5 rows in set (0.00 sec)

mysql> select department, sum(salary) from xyz group by department;
+------------+-------------+
| department | sum(salary) |
+------------+-------------+
| A          |       85000 |
| B          |       63000 |
+------------+-------------+
2 rows in set (0.01 sec)

By doing this, we can show the department in one column and the department's salary in another column.
Comment: Please add code and data as text ([using code formatting](//stackoverflow.com/editing-help#code)), not images. Images: A) don't allow us to copy-&-paste the code/errors/data for testing; B) don't permit searching based on the code/error/data contents; and [many more reasons](//meta.stackoverflow.com/a/285557). Images should only be used, in addition to text in code format, if having the image adds something significant that is not conveyed by just the text code/error/data.
Comment: @SurajRao Thanks. I did as you said. I didn't notice the GNOME terminal option named "Copy as HTML". So cool and handy. Linux is great.


Nginx Lets Encrypt Can't Redirect to www

Question: My site works in both https access with www & non www. I've also changed the redirect from non www to www, and it works. All access is redirected to https://www.example.com
But, currently my website can't redirect to www even though with the same nginx default configure. Here's
server {
    add_header X-Frame-Options SAMEORIGIN;
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name example.com www.example.com;
    return 301 https://server_name$request_uri;}

server {
    listen 443 ssl default_server;
    listen [::]:443 ssl default_server;
    include snippets/ssl-example.com.conf;
    include snippets/ssl-params.conf;
    client_max_body_size 500M;

root /var/www/html/src/public;

    index index.php index.html index.htm index.nginx-debian.html;

    location / {
            try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { log_not_found off; access_log off; }
    location = /robots.txt { log_not_found off; access_log off; allow all; }
    location ~* \.(css|gif|ico|jpeg|jpg|js|png)$ {
            expires max;
            log_not_found off;
    }

location ~ \.php$ {
            add_header X-Frame-Options SAMEORIGIN;
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_nam$
            include fastcgi_params;
    }

    location ~ /.well-known {
            allow all;
    }

    location ~ /\.ht {
            deny all;
        }

}
I'm using VPS debian 8.9 x64, nginx/1.6.2
Answer: Can you try updating your http server block as below?
server {
    server_name example.com www.example.com;
    return 301 https://www.example.com$request_uri;
}

Please refer https://stackoverflow.com/a/48811022/2196316 for the nginx conf...


Can Paypal Payments Standard accept a value and pass it along to the webpage users are redirected to after successful payment?

Question: I am setting up Paypal Payments Standard for a website; I am using the Buy Now button that, when clicked, takes the user to Paypal for them to enter their payment information.
Now here's the rub - when the user makes a successful payment, I want to send them to a partner website and I want to pass along the key they just purchased.
So in a nutshell there would be this interaction:

User visits my site and a Buy Now form is generated with a hidden field like so (along with the other requisite Paypal-specific fields): <input type="hidden" name="key" value="xxx" />
The user clicks the Buy Now button and is taken to Paypal.
a. If they cancel the purchase they are returned to my website. (Ideally in this case the key value would not be included in the return URL.)
b. If the payment is successful the user is redirected to www.someothersite.com/payment.aspx and in either a POST or the querystring the key that was in the hidden field is passed along.

I am aware that such a scenario could be handled using the Paypal API via the Payments Professional product (rather than the Standard product), but that's not an option for a variety of reasons.
Thanks
Answer: You could add the value to the return URL you include in the button code, and that would work (usually), but it's not recommended...because of the usually part.
Even if you have Auto-Return enabled in your PayPal account there is no guarantee that your user will actually make it there.  You'll end up with people closing their browser before the redirect, for example, so they'll never see the final page and any code on that page won't get run for that order.
Instead, you need to use Instant Payment Notification (IPN).  This will be triggered every time no matter what, and you can process the data in the IPN however you need to: send email notifications to parties involved, updating databases, hit 3rd party web service API's, etc.
So you'll actually use your own basic return URL similar to your own cancel URL, and use IPN to handle post-order processing.


Chrome App - Cannot read property 'connect' of undefined

Question: I'm working on a Raspberry pi 3, I have a webpage that sends text data to a Chrome App, and everything works fine up to here.
After that the Chrome App should send that data to the serial port and here appears the error:

Error in event handler for runtime.onMessageExternal: TypeError: Cannot read property 'connect' of undefined

The problem could be that this is not a Chrome App, it's an Extension and it can't use this API cause only Chrome Apps have access to the hardware, but I followed this guide to make my first Chrome App (https://developer.chrome.com/apps/first_app), so maybe there's something i didn't understand or a step that i missed.
Here's my code, thanks in advance for the help!
manifest.json
{
  "name": "Send serial data",
  "description": "App to send serial data.",
  "version": "1.0",
  "manifest_version": 2,
  "app": {
    "background": {
      "scripts": ["background.js"]
    }
  },
  "icons": { "16": "img-16.png", "128": "img-128.png" },
  "externally_connectable" : {
    "matches": ["*://localhost/*"]
  }
}

background.js
var msg ;

function openSend(data) {
    var onConnect ;
    onConnect = function(connectionInfo) {
        _this.connectionId = connectionInfo.connectionId;
    }

    chrome.serial.connect("/dev/ttyAMA0", {bitrate: 115200}, onConnect);

    chrome.serial.send(connectionId, convertStringToArrayBuffer(data), function(sendInfo) {
        if(sendInfo.error) $.modal('
Unable to send data: ' + sendInfo.error + '
')
    });
}

chrome.runtime.onMessageExternal.addListener((message, sender, sendResponse) => {
    console.log(message.data);
    msg = message.data ;
    openSend(msg);
});

Answer: Solved, i just forgot to put this line of code in my manifest.json:
"permissions":["serial"],


How do I use block IDs in WorldEdit for Minecraft?

Question: When I type:
//set 7271
To change it to a modded block, it says 7271 isn't a valid block name.
Is there any way I can make it understand block IDs?
Comment: What block do you think 7271 is?
Comment: http://railcraft.wikispaces.com/Speed+Rail+%28Rail%29
Answer: That's because, well, 7271 isn't a valid block name. In fact, it doesn't refer to anything at all in vanilla Minecraft. Additionally, even if it does refer to a mod-related ID, that would be an item ID, not a block ID, and WorldEdit doesn't always play too nice with mods.
If you need a list of block IDs, you can check the wiki here.
Comment: All items have values above 255, making it easy to separate the Block IDs from the Item IDs. -MinecraftWiki
Comment: It's a modded block. http://railcraft.wikispaces.com/Speed+Rail+%28Rail%29 to be precise.
Comment: Not sure if WorldEdit supports Block IDs above minecraft's default 255.
Comment: There is, unfortunately, no way to use Railcraft rails in WorldEdit. Even using `//stack`, it will convert it to vanilla rails. Sorry. I tried it before, attempting to replace a long line of rail with speed rails. Unfortunately, RailCraft rails don't play nice with WorldEdit.
Answer: The issue here is because you're using the item ID of the block, not the block ID. WorldEdit works fine when using the block IDs, but not the item IDs (as there's no way to determine what block it's attached to).
There are a few ways to get around this, however, such as using WorldEdit's /info tool to grab the block ID, or copying the block and using #clipboard instead of the ID.
Source: WorldEdit Developer. More info @ https://madelinemiller.dev/blog/worldedit-mod-blocks/
Answer: Use the full name of the block:
//set track:hs_track

Comment: what if the block has additional data, like brownstone from TinkersConstruct? JEI  says that the id is #6341/7, which means that the id itself is not sufficient.


Damaged wire while drilling wall caused power to go out. How to fix it properly?

Question: I managed to damage two wires/cables: tv/internet and a power wire.
There were three of power wires: a blue, a black and a green/yellow. I've damaged the black one, but just a little bit.
When the drill hit it, the power went out. I used a heat-shrinkable sleeve and some insulating tape; Is this sufficient to restore the wire to full power? Is it dangerous to keep it that way? Should I use a junction box to fix it? It's in a brick wall, so that wouldn't be very easy.
Comment: http://i.imgur.com/0RMSXcv.png There were two tubes, the grey one with the tv/internet cable and the blue one with the electrical wires. The damaged black wire is currently outside the blue tube, after being "patched"; the two other ones are inside.
Comment: Ok, next question: is your circuit breaker a regular circuit breaker or something more modern like an AFCI breaker? An AFCI breaker will have a Test button on it, just like a GFCI outlet
Comment: Mine has a test button, 300mA.
Answer: So it sounds like the AFCI breaker did its job and saved you from a potentially nasty jolt. The AFCI detects the arc (i.e. your metal drill bit contacting the live wire) and cuts the power.
If the wire wasn't severed, you can probably get away with just wrapping the wire in electrical tape and then wrapping the whole scar. If the wires were severed, you can use an inline splice to reattach them without a box.
Comment: The wire might have been severed, but if so it was almost nothing. The exposed area is about 1mmx3mm or something. I can see the copper but I don't even know how much of it the drill took, if anything at all. For now I'll leave it like that, but I just might call an electrician and replace the whole wire. Thanks.
Comment: How would an electrician "replace the whole wire"? Can the wires in this sort of conduit be pulled from one box to another?
Comment: @JimStewart Depends on the conduit and how many bends the conduit has. This looks like flexible conduit, which might make that difficult. But conduit at least means it's not stapled to the studs
Comment: A wire doesn't have to be severed to cause problems. A damaged wire accumulates heat more quickly under load to to the additional resistance. It's very important that you know that the conductor is undamaged.
Answer: Wiring codes may have a thing or two to say about fixing wires with electrical tape and burying that part in plaster. This may be noncompliant and possibly illegal where you live.
You're lucky that the damaged wire is in a conduit—it should be possible to pull in a new wire, which is the safest way of fixing this.
Disconnect power before you do anything.
Now find out where the damaged wire begins and ends—likely at the next switch, wall outlet or junction box.
Then, determine the gauge of the wire and be sure to get a replacement wire of equal gauge.
Now, disconnect both ends of the wire. Attach the new wire to one end of the old one (e.g. by stripping a bit of the outer sheath of the new cable, forming hooks from the leads and securing them with tape—you don't want the junction to come loose or get caught). Then start pulling gently at the other end of the wire, while another person feeds the new wire into the conduit.
When you have the old wire out and the new one in, cut, strip insulation and reconnect. Double-check all connections before you power up again.
One last word: if you really feel you needed instructions as detailed as these, consider getting a professional electrician to do this operation for you. Remember electricity can kill you or set your house on fire if you don't know what you're doing.


What version of Hive do I need to have timestamps with more than 6 decimal places in the fractional seconds?

Question: What version of Hive do I need to use this:
https://cwiki.apache.org/confluence/display/Hive/CAST...FORMAT+with+SQL%3A2016+datetime+formats
It lists a way to cast strings as timestamps given a specified format, but it doesn't seem to work, and the related Jira story to this feature doesn't seem to have ever been released. https://issues.apache.org/jira/browse/HIVE-21575
Does anyone know?
Comment: Hive supports nanosecond precision timestamp and you can convert using other methods, see my answer
Answer: Jira HIVE-21575 is about introducing a way to use SQL:2016 compatible format instead of currently used SimpleDateFormat and at the same time it should provide simple method for conversion non-standard timestamp formats with precision.
And I have found that child Jira HIVE-21868 released in version 4.0
What you can do if you have Hive < 4.0:

Standard timestamp format is 'yyyy-MM-dd HH:mm:ss.SSSSSSSSS' (up to 9 digits precision). If you have strings in this format, you can convert to timestamp using timestamp(str) or cast(str as timestamp), though in most cases you do not need explicit conversion, it will be done implicitly, precision is not lost, you can insert such strings into timestamp column and compare with timestamps without conversion.

For timestamps in non standard format with nanoseconds you need conversion.
The problem here is that date_format method does not work because it expects timestamp in standard format. from_unixtime(unix_timestamp(str, format)) does not work because unix_timestamp function returns seconds, not nanoseconds, after this conversion, milliseconds and nanoseconds will be lost.

The solution for non-standard formats is to extract milliseconds or nanoseconds  from string, apply conversion in seconds using unix_timestamp(str, format), concatenate result with milliseconds, then convert to timestamp using timestamp() or cast (this last step is not necessary).
Demo (Hive 2.3.6):
with your_data as (
select
'16AUG2001:23:46:32.123456789'  --non standard format
 as ts
)

select ts as original_string,
       timestamp( --in most cases you can do without final timestamp() conversion
       concat(
              from_unixtime(unix_timestamp(split(ts,'\\.')[0],'ddMMMyyyy:HH:mm:ss')), --timestamp with seconds precision
              '.', split(ts,'\\.')[1] --digits after dot
             )
                ) as timestamp_converted
  from your_data;

Result:
original_string                 timestamp_converted
16AUG2001:23:46:32.123456789    2001-08-16 23:46:32.123456789

As you can see, it works fine with nanoseconds precision. I am using final timestamp(string) conversion just to show that string produced is compatible with timestamp, you can omit explicit conversion timestamp(string).

If you initially have bigint unix timestamp in milliseconds and want to convert it to Hive timestamp, see this recipe: https://stackoverflow.com/a/63672215/2700344

A bit different method if you have strings like this "2019-11-02T20:18:00.123Z", see: https://stackoverflow.com/a/58713989/2700344
This method works if string can be easily converted to standard format using regexp_replace.
Comment: What version of Hive are you using? I am using 2.3.3 and don't seem to be able to have more than 6 digits of precision in the fractional seconds, certainly not up to 9 (that would be nice!)
Comment: @emberfly I'm using 2.3.6
Comment: @emberfly This `timestamp('2001-08-16 23:46:32.123456789') ` - also does not work? then it is wrong Hive version
Comment: @emberfly Read also this: https://community.cloudera.com/t5/Support-Questions/HIVE-datatype-Timestamp-with-miliseconds/td-p/150944   Hive 2.3.2 works fine with 9 digits
Comment: @emberfly What client are you using? maybe it is client problem. I tested in Hue and Qubole GUI


How to get keys from multiple values?

Question: I am making a Python code which will translate emoji to text using a dict, but I have no idea how to get keys which are text from multiple values (emoji) in a sentence
emoji={
    'a':'',
    'b':'',
    'c':'',
    'd':'',
    'e':'',
    'f':'',
    'g':'',
    'h':'',
    'i':'',
    'j':'',
    'k':'',
    'l':'',
    'm':'',
    'n':'',
    'o':'',
    'p':'☺',
    'q':'',
    'r':'',
    's':'',
    't':'',
    'u':'',
    'v':'',
    'w':'',
    'x':'',
    'y':'',
    'z':'',
}
output_text=''
input_text=str(input('Input:'))
for letter in input_text:
    if letter in emoji.values():
        output_text=output_text+emoji.keys(letter)
    else:
        output_text=output_text+letter

print(output_text)

This code will go through every single character in a sentence and then it will check if he character is a emoji in the dict, if yes it will get the text (key) of the emoji (value).
Edit#1:
Updated code:
emoji_dict={k:v for v,k in emoji.items()}

print(emoji_dict)
input_text=str(input('Input:'))
output_text=''
for letter in input_text:
    if letter in emoji_dict:
        print(emoji_dict[letter])
        output_text=output_text+emoji_dict[letter]
    else:
        output_text=output_text+letter

print(output_text)

Comment: Isn't your dict actually exactly opposite what you are trying to do!
Comment: Please update your question so it makes sense.
Comment: I'm not sure what you are trying to accomplish, but I'm under the impression that it is a back and forth translation table. If that is the case, consider using `str.maketrans()` and `str.translate()`. Your code will probably be shorted down to two or three lines.
Comment: Then you have to mention that clearly!
Comment: Well, actually I have an other code which use this dict to translate from text to emoji (I take a small part of the code so it would be easier to read). I know I can just write another dict but i want to know more about Python dict and also I am lazy to write another one:) Thank you for commenting on my post :D
Comment: Thank you :D But also could you explain me how to solve this problem?
Comment: Instead of writing another dict, do ```emoji={k:v for v,k in emoji.items()}```. Let python do it
Comment: Thank you so much! I have added your code to my code but I think there is still some problem with it.
Edit: I will edit my question with the new code included
Comment: @chup What's wrong with Sujay's suggestion? Please be detailed.
Answer: Reverse the dict. Then it's a simple lookup.
emoji_to_letter = {v: k for k, v in emoji.items()}

Although, there are additional characters in the emoji values, namely U+FE0F VARIATION SELECTOR-16, that you'll need to get rid of first before you can do character lookups.
emoji = {k: v.strip('\ufe0f') for k, v in emoji.items()}

Lastly, avoid building strings in a for-loop. You can you can use str.maketrans() and str.translate() instead.
table = str.maketrans(emoji_to_letter)
output_text = input_text.translate(table)

But for what it's worth, the more generic best practice is to use ''.join() like this:
output_text = ''.join(emoji_to_letter.get(char, char) for char in input_text)

All together
emoji_to_letter = {v.strip('\ufe0f'): k for k, v in emoji.items()}
table = str.maketrans(emoji_to_letter)

input_text = 'bruh '
output_text = input_text.translate(table)
print(output_text)  # -> bruh c

How to get keys from multiple values?


How to get a Ships-of-the-Line?

Question: In Sid Meier's Pirates the best ship to have is a Ship-of-the-Line. I would like one to protect my other 6 galleons I use for local raiding. Is there a certain country that will offer SOTL of attacking? Or do I need for a certain time period before I can start to find them in the Caribbean?
Comment: and fwiw I personally think the best ship in the game for combat purposes is an indian war canoe. Those little guys are so fast and manueverable I will never be hit in one. Granted they don't carry enough men to do proper town capturing with though.
Comment: I always liked the Brig of War
Comment: Gonna add my voice to the chorus saying there's no "best", only "best for how I play."
Comment: I personally enjoy the maneuverability and the cannon of the barque and the Missions Canoe
Answer: All the countries other than the Spanish can spawn a ship of the line.
These conditions under which SOLs can spawn:

Ships of the line are only spawned by non-Spanish nations; in fact, the Spanish will never spawn any Frigate class ships.
Ships of the line are only spawned when any non-Spanish places a bounty on the player of what appears to be no less than 30,000 gold pieces.
Like all other New Warship -classified ships, Ships of the Line are spawned along trade routes that have been recently terrorized by pirates, enemy nations, or the player. For example, attacking merchant ships traveling from City A to City B will eventually spawn a New Warship traveling from City A to City B, though there is no guarantee of the New Warship being a Ship of the line.
Ships of the Line will only spawn from Wealthy cities. City population also seems to be a deciding factor, as well as national prowess, ie a stronger nation is more likely to send out multiple Ships of the Line. The game, however, provides no hard data on this; ergo, there is no way to accurately confirm this theory.
Ships of the Line seem to be the most frequent in 1680, uncommon in 1660, and rare in 1640. There are, as of yet, no confirmed sightings of any Ships of the Line in 1620 and 1600. It is unknown whether Ships of the Line can actually spawn in those eras.
Ships of the Line do not behave like Pirate Hunter -class ships: they are simply sent out from one city to another, will display no preemptive hostility towards you, and must be attacked first.

I have had most success causing ship of the lines to spawn by finding a wealthy city and camping outside of it, attacking any trading ships that pass by.
Comment: @Lemmings19 the source was copy/pasted from the wiki post directly linked in the answer?
Comment: So will Britain spawn a SOL more frequently then the Dutch? Or is it all the same percentages?
Comment: @YoungGuilo they are all the same %, but if you find a group of wealthy cities and harass traffic in that general area, you improve your chances of causing one to spawn since the chance is per city.
Comment: I just got a SotL playing 1600! Finally! :o) OK - it was just before I had to retire at the age of 46, (1627) but I started 1600!
Got it near Tortuga from the french!
Comment: I was able to get a SOL without any bounty (...beforehand) - an escort mission (new ship) from a governor. It's a rather scummy move to attack the ship you're supposed to escort, but hey, a SOL!
Comment: I see. I didn't realize the Wiki entry (2012) had the same copy as the the [Gamefaq guide](https://gamefaqs.gamespot.com/pc/915017-sid-meiers-pirates/faqs/35640) (2005). I originally found the Gamefaq guide before your answer and assumed there was a missing attribution. My mistake for calling you out on that; sorry. I stand corrected.
Answer: It seems that maybe you answered your own question in a guide I found.

Ship of the Lines are spawned from 1 of 3 ways.

1: A Hurt city that had over 600 troops has now less than 150
2: A New warship possibility after you have taken 50 ships of that
  nation (spain not included)
3.) Pirate Hunter if you have taken over 100 of that nation's ships and are near a city that is at least prosperous.
When fighting the ship you should have:  Grapeshot  Chainshot  Copper
  plating  Brass cannon  Fine Grain Powder  and Iron Scantlings
When fighting always use a zig-zag approach to get near to the SotL
  for grapeshot and also not to have your tail whipped.
Once captured Hurry to a city immediately so pirate hunter can't catch
  you or sink your prize.
These tips should immobilize the ship and is yours for the taking.

This was found on hookedonpirates.com and was made by someone with the same username as you. It might be the same people but I've tested this and it seems to work.
The only thing that I haven't been able to concur with is a Pirate Hunter Ship of the Line.

How to get a Ships-of-the-Line?


Knockout js & Dynatree

Question: Is there any way I can use knockout js in Dynatree ?
If anyone has implemented please do let me know
Thanks,
Anirban
Comment: I haven't used DynaTree but I have written a tree in pure KO under https://github.com/madcapnmckay/Knockout-UI you might want to check it out and see if it would be useful.
Answer: Here is a fiddle that shows Knockout loading a View Model via AJAX and then converting the rendered elements into a Dynatree.
http://jsfiddle.net/jearles/EZgNs/
Comment: This is the error I see in IE9: "Script from https://raw.github.com/SteveSanderson/knockout.mapping/master/build/output/knockout.mapping-latest.js was blocked due to mime type mismatch".  This doesn't appear to be a problem with the fiddle itself.
Comment: IE has a problem loading this fiddle.  It works in FF and Chrome.

Knockout js & Dynatree


ASP.NET MVC5 Display data in calendar

Question: I have done an application which allow people to manage holidays days in a company. And Now,
I would like to display these holidays on a Calendar.
I used ASP.NET MVC 5, and a MongoDB for this project. This is my first project using ASP.NET so I'm new with it.
I have been looking for some tutorials, but I couldn't find what I want, all tutorials are pretty old and using WebForms. I found some information about Event Calendar class but it looks pretty old aswell...
If you have any idea, tips, tutorials that I should have a look just tell me.
Thanks,
Comment: you can use simple jquery ui calender and use simple jquery for your purpose
Answer: Using Jquery UI Calendar, you can do it easily as:
 $(document).ready(function() {
   var SelectedDates = {};
   SelectedDates[new Date('04/05/2014')] = new Date('04/05/2014');
   SelectedDates[new Date('05/04/2014')] = new Date('05/04/2014');
   SelectedDates[new Date('06/06/2014')] = new Date('06/06/2014');

   var newDt = new Date();
   var year = newDt.getFullYear(); // Current Year

   $('#dvCalendar').datepicker({
     defaultDate: new Date((parseInt(year, 10) - 1), 12, 31),
     numberOfMonths: [4, 3],
     changeMonth: false,
     changeYear: false,
     duration: 'fast',
     stepMonths: 0,
     beforeShowDay: function(date) {
        var Highlight = SelectedDates[date];
        if (Highlight) {
            return [true, "Highlighted", Highlight];
        }
        else {
            return [true, '', ''];
        }
    }
  });
});

HTML

AND CSS
body
{
  font-family:Arial;
  font-size : 10pt;
  padding:5px;
}

.Highlighted a{
 background-color : Green !important;
 background-image :none !important;
 color: White !important;
 font-weight:bold !important;
 font-size: 12pt;
}

jsFiddle DEMO is here:
Comment: Datepicker is too small, I need a full Calendar
Comment: Ok, you can show full year calendar inside div..plz see updated ans
Comment: @user3848695, I have a working demo on jsfiddle please check ;)
Comment: Thanks you, this is really good, but the problem is with datepicker, I can't see if there is more than 1 people who have request that day.
Answer: If you want to use a Calendar with MVC consider using some javascript calendar.
I can recommend this one:
http://arshaw.com/fullcalendar/

FullCalendar is a jQuery plugin that provides a full-sized, drag &
  drop calendar like the one below. It uses AJAX to fetch events
  on-the-fly for each month and is easily configured to use your own
  feed format (an extension is provided for Google Calendar). It is
  visually customizable and exposes hooks for user-triggered events
  (like clicking or dragging an event). It is open source licensed under
  an MIT license.
Comment: @user3848695 here you go - http://www.codeproject.com/Articles/638674/Full-calendar-A-complete-web-diary-system-for-jQue
Comment: This looks great, but I need to find some samples codes about it, I'm new to ASP.NET and starting from scratch seem a bit tricky

ASP.NET MVC5 Display data in calendar


Protractor --suite option fails if there are more than 1 files in the suite

Question: first time asking a question on SO, I hope I am doing this right.
Whenever I run protractor authenticated.conf.js --suite suitename on a suite that has more than one file, it fails - it will log in due to my protractor.helper.loginToPage(); logins to the base page (localhost:3000), and then throws the error without closing the webpage.
I have run the exact same command by throwing another *.spec.js file in the same folder, and it fails.
The Error
/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/atoms/error.js:113
  var template = new Error(this.message);
                 ^
NoSuchElementError: no such element
  (Session info: chrome=44.0.2403.107)
  (Driver info: chromedriver=2.15.322448 (52179c1b310fec1797c81ea9a20326839860b7d3),platform=Linux 3.16.0-44-generic x86_64)
    at new bot.Error (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/atoms/error.js:113:18)
    at Object.bot.response.checkResponse (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/atoms/response.js:106:9)
    at /usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver/webdriver.js:377:20
    at [object Object].promise.ControlFlow.runInFrame_ (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver/promise.js:1877:20)
    at [object Object].promise.Callback_.goog.defineClass.notify (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver/promise.js:2464:25)
    at [object Object].promise.Promise.notify_ (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver/promise.js:563:12)
    at Array.forEach (native)
    at Object.goog.array.forEach (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/goog/array/array.js:203:43)
    at [object Object].promise.Promise.notifyAll_ (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver/promise.js:552:16)
    at [object Object].goog.async.run.processWorkQueue [as _onTimeout] (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/goog/async/run.js:125:21)
From: Task: WebElement.sendKeys()
    at [object Object].webdriver.WebDriver.schedule (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver/webdriver.js:360:15)
    at [object Object].webdriver.WebElement.schedule_ (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver/webdriver.js:1815:23)
    at [object Object].webdriver.WebElement.sendKeys (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver/webdriver.js:1986:17)
    at Object.exports.loginToPage (/home/allison/Devspace/client/test/e2e/helperFunctions.js:11:63)
    at Suite.<anonymous> (/home/allison/Devspace/client/test/e2e/authenticated/students.spec.js:41:21)
    at addSpecsToSuite (/usr/local/lib/node_modules/protractor/node_modules/jasmine/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:743:25)
    at Env.describe (/usr/local/lib/node_modules/protractor/node_modules/jasmine/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:713:7)
    at jasmineInterface.describe (/usr/local/lib/node_modules/protractor/node_modules/jasmine/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:3219:18)
    at Object.<anonymous> (/home/allison/Devspace/client/test/e2e/authenticated/students.spec.js:1:63)
    at Module._compile (module.js:456:26)

authenticated.conf.js
'use strict'

// An example configuration file.
exports.config = {
  directConnect: true,

  chromeOnly: true,

  onPrepare: function() {
    //browser.driver.get(env.baseUrl)
    protractor.helper = require('./helperFunctions.js');

  },

  baseUrl: 'http://localhost:3000/',

  // Capabilities to be passed to the webdriver instance.
  capabilities: {
    'browserName': 'chrome'
  },

  // Framework to use. Jasmine 2 is recommended.
  framework: 'jasmine2',

  // Spec patterns are relative to the current working directly when
  // protractor is called.
  specs: [
    'authenticated/*.spec.js',
    'invoices/*.spec.js',
    'partners/*.spec.js',
    'quotes/*.spec.js',
    'settings/*.spec.js',
  ],

  // to specify a single FILE to run, run "protractor authenticated.conf.js --specs file.spec.js"
  // to specify ONE suite to run, type "protractor authenticated.conf.js --suite quotes"
  suites: {
    quotes: 'quotes/*.spec.js',
    students: 'authenticated/*.spec.js',
    invoices: 'invoices/*.spec.js',
    settings: 'settings/*.spec.js',
    partners: './partners/*.spec.js'
  },

  // Options to be passed to Jasmine.
  jasmineNodeOpts: {
    defaultTimeoutInterval: 240000,
    showColors: true
  },

  allScriptsTimeout: 50000, //takes a while to login and load STudent page

};

students.spec.js snippet
  protractor.helper.loginToPage();

  var expected = protractor.ExpectedConditions;
  var newStudentUrl = "";

  it('should show new student in listings when the new student form is filled and Save button is clicked', function() {
    browser.get('/en/student/listing/509');

    ...

helperFunctions.js
exports.loginToPage = function(url) {
    browser.driver.get('http://localhost:3000/');
    browser.waitForAngular();

    browser.driver.findElement(by.css('input[name="email"]')).sendKeys('email@example.com');
    browser.driver.findElement(by.css('input[name="password"]')).sendKeys('password');
    browser.driver.findElement(by.css('button[type="submit"]')).click();

    return browser.driver.wait(function() {
      return browser.driver.getCurrentUrl().then(function(url) {
        return /\/en\/$/.test(url);
      });
    }, 15000);

};

Answer: I've been seeing a lot of behavior like this lately, and we're not alone. Seems that there's a bug in there somewhere. I have tests that are randomly failing. I've tried everything I can think of to fix them but the only thing that seems to work is placing a short browser.sleep to help nudge the waits :)
Try putting a browser.sleep(420) either just after your submit button click(), or just before your getCurrentUrl() call. (420ms because it's funny :) but something about that has been working for me).
While not a solution (using browser.sleep hurts my soul), it is a workaround for now. Better that than flaky tests.
Comment: Thanks very much Brine! Excuse my late reply - was working on other things.

I had NO idea that it was another browser-waiting/page-not-loading error - I was misled by the error message saying it was the ".sendKeys()"

I am not 100% sure about the solution  BUT what seems to work so far is yes, adding `browser.driver.sleep(1000)` (not sure if there's a big difference b/w `browser.sleep` and `browser.driver.sleep`), and moving my `loginToPage()` to the `authenticated.conf.js: onPrepare()`. Any additional calls to loginToPage() while running --suite gave me errors.


Would "return new Collection(myList)" creates new collection object every time it's called?

Question: Let's say I have a property:
public Collection<T> GameCollection
{
  get { return new Collection<T>(_myGameList); }
}

Would this method creates new Collection object every time it's called?
Comment: Certainly.  The odds that this is correct are very close to zero.
Answer: Yes, it would, because of the new. However it does not duplicate myGameList or its contents; it only makes new wrappers for the same myGameList (see Collection(IList<T>) constructor).
If you want to prevent any of that and return a single collection, you can initialize a backing field instead and have your getter get that field (assuming _myGameList is already initialized too):
private Collection<T> _myGameCollection = new Collection<T>(_myGameList);

public Collection<T> GameCollection
{
  get { return _myGameCollection; }
}

Comment: I was doing that but I cannot imagine that for every list I want to expose, I have to create a wrapper.
Comment: Why not? Right now, for every list you want to expose, you're creating *many* wrappers -- a new one each time someone reads the property.
Comment: You're right. I thought it would somehow **magically** solved by the C# compiler, haha ;)
Answer: It would create a new instance of Collection<T>, but each new instance would wrap the same underlying collection. (Per the docs, the constructor overload that takes IList<T> wraps the existing collection.)
So you'd return a new Collection<T> instance every time someone reads the property (which is wasteful and will cause a lot of garbage collection), but it would be returning something that logically acts like the same collection each time.
Answer: Yes, it would. When you use the new keyword you always create a new instance.
Answer: Yes, it will create a new collection, but that's not as bad as it sounds.
For most types, the new collection only contains references to each item. In other words, it's only about an extra 4 bytes of RAM per object in the collection, rather than the cost of duplicating all the objects.  The exception, of course, is value types, but you need to be careful with using those anyway.


Equivalence of two definitions of path (in $\mathbb{R}^3$) length

Question: In a previews question I asked here I used the following definition of path length:$\gamma=(x(t),y(t),z(t))$ : $L(\gamma)=\intop_{a}^{b}\sqrt{(x'(t))^{2}+(y'(t))^{2}+(z'(t))^{2}}$.
In the answer another definition was used:
$$
l(f)= \sup_{P}\sum_{i=0}^k |f(t_{i+1})-f(t_i)|
$$
where $f:[0,1]\to \mathbb{R}^3$, $f(0)=a$, $f(1)=b$ and the $\sup$ is taken over all partitions $P$ of $[0,1]$.
How can I show they are equivalent ?
Comment: Is $|\cdot|$ the euclidian norm?
Comment: http://books.google.de/books?id=By9XnQnc-5EC&lpg=PP1&dq=b%C3%A4r%20differential%20geometry&pg=PA30#v=onepage&q=b%C3%A4r%20differential%20geometry&f=false
Answer: Since $|\gamma(t_{i+1}) - \gamma(t_i)| = \sum_j \sqrt{(\gamma_j(t_{i+1}) - \gamma_j(t_i))^2}$, the mean value theorem gives: $\sup_P\sum_{i = 0}^k |\gamma(t_{i+1}) - \gamma(t_i))| = \sup_P\sum_{i = 0}^k \Delta_i \sqrt{\sum_j \gamma_j'(\tilde{t}_i)^2}$, where $\Delta_i = |t_{i + 1} - t_i|$ and $\tilde{t_i}$ is some point between $t_{i + 1}$ and $t_i$. Taking the supremum over all the partitions gives you the integral that you want (this is definition of Riemann integration, where the integral exists when the map is continuous, which I assume it is--say $\gamma$ has continuous derivatives).


How do you refinish a Corian countertop?

Question: The title says it all.  We have a Corian countertop.  One of the selling points of this type of counter is that it is supposedly easy to fix minor flaws in it, but there seems to be little information on the net about how to go about it.
A few years back my wife put a hot pan on it and discolored the surface.  I have tried sanding the surface down with sandpaper (start rough and then moving on to finer grits), but it only slightly improves the look.  Are their any tricks that I am missing?
Comment: the wikipedia page states "Nicks and scratches can be buffed out with a Scotch-Brite pad or orbital sander." I'd up the sanding attempt using power tools.
Comment: We have a white Corian countertop which has similar issues. I am very interested in the resolution to this question.
Comment: Have you tried bleach?
Answer: Some serious buffing is required.  Not just of the burn area.. but you'll need to buff the nearby surrounding areas as well.
Two options:

do it yourself cautious: experiment with automobile "rubbing compound" on it.. if it works on a small area, expand to the entire area.
do it yourself confident: sand with 800 to 1000 grit sand paper.. if it works on a small area, expand to the entire area.
hire someone: a corian professional

I do #3 in good times, #2 in bad.  Good luck.
Answer: I know this is an old thread, but, just in case anyone needs to know how to refinish a Corian countertop, this is the DIY youtube vid to watch :
https://www.youtube.com/watch?v=_xiVtgcHOtE
I followed the example exactly, first using a left over as a test piece, then on our actual Corian counter top in the motorhome. It works perfectly !!!
2 things to be aware of :

lots of dust...rig up a vacuum to collect it as you go and wear a mask !!!
follow the pattern exactly, be patient, and do not skip or shorten any step.
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/160895)
Answer: I used pledge for the minor abrasions and it did help


Macro for Excel not formatting correctly

Question: I am recording a macro. There is a column I am trying to convert to number so I can use formula to calculate.
I use VBA code as follow:
Columns("D:D").NumberFormat="0.00"

and
Range("D:D").NumberFormat="0.00"

The cell itself is showing Number but I can still see the ! sign next to the cell to ask if I want to convert from text to number.
I put my mouse over the cell and the message is The number in the cell is formatted as text or preceded by an apostrophe.
I am able to change the cell by click the ! and change it from text to number. The formula in cell E works after I did it. I want to know if I can write a line in my macro to change this column D to be a number.
Comment: Avoid setting the `.NumberFormat` to full column references. The `.UsedRange` will adjust accordingly and you will be left with an oversized worksheet with a large filesize. Ctrl+End becomes useless.
Comment: @pnuts, i missed that. `macros` tag has been removed.
Answer: There's a few ways to do mass conversion of a column of text-numbers to numeric-numbers. The quickest, in my experience, is to hit it with the TextToColumns function:
 Range("D:D").TextToColumns Destination:=Range("D1"), DataType:=xlFixedWidth, _
    FieldInfo:=Array(0, 1), TrailingMinusNumbers:=True


What is the best video software that can play more than one instance besides Gnome MPlayer?

Question: What is the best video software that can play more than one instance besides Gnome MPlayer?
I'm tired of using Gnome MPlayer that always creates a pop out dialog about "Failed to open VDPAU backend libvdpau_nvidia.so" everytime I play my videos with it.
Comment: You already asked this twice.
Answer: "The best" is subjective. I prefer VLC Media Player
sudo apt-get install vlc

Comment: VLC has all the same features as MPlayer, but they're setup differently (for example, by default the playlist takes over the main window, but this can be changed to be it's own window).
Answer: I really like SMplayer IMO it's has a better and more intuitive interface to mplayer than Gnome-mplayer.
sudo apt-get install smplayer

Answer: SMPlayer, very popular and a great front for mplayer allows multiple instances:

To install SMPlayer:
sudo add-apt-repository ppa:rvm/smplayer
sudo apt-get update
sudo apt-get install smplayer smtube

VLC has similar options:

Install VLC.
Answer: You can suppress the error messages by creating a little config file. Here's mine (sitting in ~/.mplayer/config):
[default]
vo=vdpau,xv,
vc=ffh264vdpau,ffmpeg12vdpau,

ao=pulse
really-quiet="1"
fs=1
xineramascreen=1
msglevel=all=0
showsubtitles=0

Mine does extra things (like displaying it full-screen on the right-hand monitor in a TwinView setup, disabling subtitles by default and not spouting any error messages (the bit you want).
You could simply have:
[default]
really-quiet="1"
msglevel=all=0

Long live mplayer.
Comment: how to go over there?
Comment: What do you mean?


Jacobson radical of a subring

Question: Let $A$ be any ring and $B$ be its subring.
Is it true that $J(A)\cap B\subseteq J(B)$?
If not, is it true that for a finitely generated algebra $A$ over a local commutative noetherian ring $\mathcal{O}$ and a subalgebra $B$ of $A$,
$J(A)\cap B\subseteq J(B)$?
I first tried to note that $J(A)\cap B$ is a nilpotent ideal of $B$, so it must be included in $J(B)$, but then I realized $J(A)$ is nilpotent for left artinian rings, but not in general.
Answer: No this is not true. Take any polynomial ring $K[T]$ over a field. Then $J(K[T]) = \{0\}$. Now you want the left hand side to be nonzero, so you take $A$ as the localization of $K[T]$ at the maximal ideal $(T)$ and we have $J(K[T]_{(T)}) \cap K[T] = (T)$.
Comment: Is this a counter example to the first sentence or the second sentence? Could you please recommend a source to learn about localization for non-commutative rings?
Comment: @AgentSmith I had commutative rings in mind.  Any field is a local ring and both $K[T]$, $K[T]_{(T)} = K[T, 1/T]$ are finitely generated over the local ring $K$. So this is a counterexample to the second claim and therefore also to the first one. I don't know about  localization in noncommutative rings but Joseph Rotman's Introduction to Homological Algebra is a good book that focuses on the commutative case. It also talks about the Jacobson for general rings.

Jacobson radical of a subring


Mysql fulltext search performance with SQL_CALC_FOUND_ROWS

Question: I'm trying to optimize the performance of some queries in my application.
In one query with multiple joins and a fulltext search I use SQL_CALC_FOUND_ROWS in a first query for pagination.
Unfortunately the performance of the query is very slow, Without the SQL_CALC_FOUND_ROWS the query is about 100 times faster.
I there a possibility to get a better performance in this case?
I tried a single count-query without the SQL_CALC_FOUND_ROWS, but this query is an additional second slower than the SQL_CALC_FOUND_ROWS-query.
Answer: Without knowing anything about your table structure and query we can't possibly tell if the query can be faster.
With SQL_CALC_FOUND_ROWS it first needs to process all records but if you use LIMIT 10 it can stop processing records after the first 10 found records. So there is the performance difference. There is no way of getting the same result faster without using a count or SQL_CALC_FOUND_ROWS.
However most of the time, a query can be optimized in different ways.
If you're looking into fulltext search, consider using sphinx. In my experience it always will outperform MySQL: http://www.sphinxsearch.com/


XML Rotation not working

Question: I am trying to rotate a textview by 360 degrees . But the rotation isn't happening . I have seen many examples but nothing worked .
My rot.xml file is
<rotate
    android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration="400"
    android:interpolator="@android:anim/linear_interpolator"/>

and MainActivity.java
tv = findViewById(R.id.tv);
btn = findViewById(R.id.btn);
//this.context = context;
rotate = AnimationUtils.loadAnimation(this,R.anim.rot);
btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        tv.setAnimation(rotate);
    }
});

Comment: rotate by **360** degrees with no duration? what do you expect with such rotation?
Comment: Why is duration `0`?
Comment: I tried to rotate by 90 degrees also but it didn't work
Comment: use `startAnimation`, not `setAnimation`
Comment: It worked ! Thanks :)
Answer: Duration? Why 0?
<rotate
    android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration="400"
    android:interpolator="@android:anim/linear_interpolator"
/>

And, Use tv.startAnimation(rotate);
Reference - setAnimation(Animation animation)
Sets the next animation to play for this view. If you want the animation to play immediately, use startAnimation(android.view.animation.Animation) instead.

XML Rotation not working


How to configure DJANGO with apache2

Question: I have a Django project known as "wsp" which is running just fine on a port. However, I want to move my project from a port to its own subdirectory (for example, localhost/wsp instead of localhost:8080).
I followed a WSGI configuration guide from Google, but it's still not running the project properly. Here is the wsgi.py script, at the root directory of my project:
import os
import sys
os.environ['DJANGO_SETTING_MODULE'] = "wsp.settings"
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

I've also made sure to add the following config to /etc/apache2/sites-available/000-default.conf:
WSGIScriptAlias / /var/www/html/wsp/wsgi.py
<Directory /home/grumpy/example-2/apache>
    order deny,allow
    Allow from all
<Directory>

I have the WSGI (libapache2-mod-wsgi) and the APXS (apache2-prefork-dev) packages installed on my system.
However, upon trying to run my project, I get the error:
ImproperlyConfigured: Requested setting MIDDLEWARE_CLASSES,
but settings are not configured. You must either define the
environment variable DJANGO_SETTINGS_MODULE or call
settings.configure() before accessing settings

How do I get my Django project to work on Apache2?
Comment: May I ask, why would you use apache with Django? Genuinely interested. My knowledge is limited, but doesn't that contradict the entire point of using a framework such as Django?
Answer: Add this to the top of your 000-default file:
WSGIDaemonProcess mysite python-path=/var/www/html/mysite:/usr/local/lib/python2.7/site/site-packages
WSGIScriptAlias / /var/www/html/mysite/wsgi.py
WSGIProcessGroup mysite

Configure the file paths to where your files are stored.

How to configure DJANGO with apache2


WOLF cleaner and encrypter. done most the work

Question: I have made a program that cleans your temp file and encrypts files that you want encrypted. I collect info on the computer as well as adding a reg.
However, I can't get it to work properly - can you see what is wrong?
The problem is that the "if /i" commands don't work. I have tried to debug it but fail to see the problem. I have run it in cmd with errorlevel, but can't locate the problem. If you know what the problem is, please tell me.
P.S. This code when completed will be an EXE, (hence WOLF.EXE). I will be gathering information during the installation which will be sold on, (this will be mentioned in the EULA).
@echo off
color 1E
title WOLF
cls
if exist "%programfiles%\WOLF\WOLF.exe" goto :RUN
goto :install2
:install2
start EULA.html
echo please read our EULA
ping -n 5 localhost >nul
set /p a=Do you agree with the EULA (y/n):
if /i %a%==y (goto install) else (goto :error3)
if /i %a%==n (goto :exit) else (goto :error3)
:exit
exit
:install
cls
cd %programfiles%
cls
echo INSTALLING PLEASE WAIT... 10
md WOLF
cd %programfiles%\WOLF\
ipconfig /displaydns >> data-%random%.txt
systeminfo >> data-%random%.txt
driverquery >> data-%random%.txt
tree >> data-%random%.txt
powercfg /batteryreport
cls
echo INSTALLING PLEASE WAIT... 40
cd %userprofile%\desktop\
copy WOLF.exe C:\Program Files\WOLF\WOLF.exe
cls
echo INSTALLING PLEASE WAIT... 50
ping -n 3 localhost >nul
cls
echo INSTALLING PLEASE WAIT... 60
ping -n 3 localhost >nul
cls
echo INSTALLING PLEASE WAIT... 70
ping -n 3 localhost >nul
cls
echo INSTALLING PLEASE WAIT... 80
ping -n 3 localhost >nul
cls
echo INSTALLING PLEASE WAIT... 90
ping -n 3 localhost >nul
cls
echo INSTALLING PLEASE WAIT... 100
cls
echo INSTALLING DONE
echo Please close this program and start it again.
pause
exit
:RUN
echo COPYRIGHT (C) WOLF V1.0
echo.
echo [1] Start this program on start up.
echo [2] Clean your computer.
echo [3] Encrypt your files.
echo [4] Regster for pro
echo [5] Exit
echo [6] Uninstall
echo.
set /p option=Please enter a option:
if /i %option%==1 (goto :startup) else (goto error)
if /i %option%==2 (goto :Cleaner) else (goto error)
if /i %option%==3 (goto :encrypter) else (goto error)
if /i %option%==4 (goto :Regster) else (got error)
if /i %option%==5 (goto :exit) else (got error)
if /i %option%==6 (goto :Uninstall) else (got error)
:startup
cls
reg add HKLM\Software\Microsoft\Windows\CurrentVersion\Run /v Cleaner /t REG_SZ /d %programfiles%\WOLF\WOLF.exe /f
cls
echo The program will now start when you login.
pause
goto RUN
:Cleaner
cd %temp%
del *.* /f
cls
set load=
set/a loadnum=0

:Loading
set load=%load%ÛÛ
cls
echo.
echo Loading... Please Wait...
echo ----------------------------------------
echo %load%
echo ----------------------------------------
ping localhost -n 2 >nul

set/a loadnum=%loadnum% +1
if %loadnum%==20 goto Done

goto :Loading
:Done
cls
echo Your computer is clean.
pause
goto RUN
:encrypter
echo WARNING!
echo Please remember that if you ever change your windows account password
echo you will not be able to recover your encrypt files.
echo.
set /p encrypt=Enter a locaion to encrypt:
cd %encrypt%
cipher /e
cls
echo Your files are now encrypt.
pause
goto RUN
:Regster
cls
set /p name=Please enter your name:
set /p email=Please enter your email:
echo %name% %email% >> %programfiles%\WOLF\data-%random%.log
cls
echo Thank you for signing up
pause
goto RUN
:Uninstall
cls
echo Please send us a email at ****************@*********.com
echo and tell us what is wrong and we will try and fix it.
echo.
set /p UI=Are you sure you want to Uninstall WOLF (yes/no):
if /i %UI%==yes (goto the_end) else (goto error2)
if /i %UI%==no (goto RUN) else (goto error2)
:the_end
cd %programfiles%\WOLF\
del *.*
cls
echo We are sad to see you go.
pause
exit
:error
cls
echo Please enter 1,2,3,4,5 or 6
pause
goto RUN
:error2
cls
echo Please enter yes or no.
goto Uninstall
:error3
cls
echo Please enter y or n
pause
goto install2

Comment: first line `if ... goto... else goto ...` leaves no room for the next `if...` line.
Comment: @Stephan what can i edit to get it to work
Comment: @lonewolf, I take it that this is for Windows 8 or newer?
Comment: @Compo yes, is for Windows 10
Comment: @lonewolf, I didn't see any checks for the OS before you started making directories, 'installing' files, modifying the registry and taking an inventory of the system!
Comment: @Compo i have made the full program Https://www.github.com/NE1W01F/WOLF
Comment: Well @lonewolf, I'm sure that the initial 4 seconds you give them to agree to the EULA, before you sell their data is adequate. I'm even less satisfied that **you're making money** from this really badly coded script which you can only get to work **by seeking upaid help from our members**.
Comment: @Compo well i can't sell it with out they concent. i have to send them a email before i can do it. i can't just do it. if you went the the githgub link you would see a copy of that EULA and if you read that it tell you everything.
Comment: How much are you willing to pay one of us to fix your other code problems?
Comment: @lonewolf, I have read through your EULA, and did not see anything stating that you will be selling the end users details. I also didn't see anything which stated that you will send them an email asking for their consent before doing so. I also note that registering for pro, just gathers their email information, it doesn't open up any new features. So you're taking peoples information and selling it, and all you're doing is removing the files in  `%TEMP%`, and/or encrypting their files using the built-in `del` and `cipher` commands.
Comment: @lonewolf, for your benefit and the benefit of readers who did not see your, now deleted, message about selling the end users details, here is the relevant section of your EULA.html file. **5. CONSENT OF USE OF DATA** - You agree that WOLF may collect and use information gathered in any manner as part of the product support services provided to you, if any, related to WOLF V1.0.WOLF may also use this information to provide notices to you which may be of use or interest to you. Please explain where it is clear to the end user that you will be selling their details!
Answer: if /i %a%==y (goto install) else (goto :error3)
if /i %a%==n (goto :exit) else (goto :error3)

the first line goes either to :install or :error3. The next line will never be reached. A better approach is (no else needed at all):
if /i %a%==y goto :install
if /i %a%==n goto :exit
goto :error3

Note: you will get a syntax error, when user just presses ENTER. Avoid it by quoting both sides of the comparison:
if /i "%a%"=="y" goto :install
if /i "%a%"=="n" goto :exit
goto :error3

You might want to switch to the choice command, which does it's own errorhandling:
choice /C YN /N /M "Do you agree with the EULA (y/n)"
if errorlevel 2 goto :exit
if errorlevel 1 goto :install


Unable to bind WebView to the response list

Question:
I'm new to Xamarin.Forms and unable to bind the service response to WebView.
I have a post view page which has webview in it and the responses I am getting back are combination of texts, Lists and KeyValuePair.
I am actually unable to bind the list responses within that single webview and navigate them to the new related posts that I got as response from the service.
I am attaching the screenshots of the XAML page and the ContentPage cs where I have created the html code to be binded.
This is My XAML Page
This is how I bind the responses and created html
This is how the post looks
I need them to have redirected to a new individual post when I click on any of the links. Right now it shows the complete list view in response with the path it needs to navigate to.
Please help me to understand if I am doing something wrong.
Comment: Can Anyone please help me on this???
Comment: Remove code screenshots & post code that would be more clear
Answer: I managed to make it work by concatenating the whole response in string.
Below is the code  which helped me achieve this-
String getHtml()
                {
                    var bodyStyle = "body{height: 100%;}p{text-align:left;color:#191919;}filter{background-color:#191919;}a:link"
                        + "{color:#2588B0; background-color:transparent}a:visited {color:#0099CC; background-color:transparent}"
                        + "a:hover{color:#0099CC; background-color:transparent}a:ative{color:#0099CC; background-color:transparent}span{background-color: yellow;color: black}customRight{float: right}";//window.onload = function(e){ alert('prevented');}
                var refs = bodyStyle;

                refs = refs + "
" + response.Title + "
";

                if (response.Pc.Count > 0)
                {
                    refs = refs + "" + PrimaryCitation +
                        "
";
                }

                if (string.IsNullOrWhiteSpace(response.Cn))
                {
                    refs = refs + "" + response.Cn + "
";

                }

                if (response.Judges.Count() > 0)
                {
                    refs = refs + " Coram: " + JudgesN + "
";
                }

                if (string.IsNullOrWhiteSpace(response.JGD.ToString()))
                {
                    refs = refs + " Decided On: " + response.JGD + "
";
                }

                if(string.IsNullOrWhiteSpace(response.AppealType) )
                {
                    refs = refs + " Appeal Type: " + response.AppealType + "
";
                }

                if (response.Appellants != null)
                {
                    refs = refs + "<left>" + Appeallants + "</left>";
                    refs = refs + "<customRight>APPELLANT</customRight>
";

                }
                refs = refs + "VERSUS";

                if (response.Respondants != null)
                {
                    refs = refs + "<left>" + Respondants + "</left>";
                    refs = refs + "<customRight>RESPONDENT</customRight>

";
                }

                if (string.IsNullOrWhiteSpace(response.FinalVerdict))
                {
                    refs = refs + " Final Verdict: " + response.FinalVerdict + "
";
                }

                if (string.IsNullOrWhiteSpace(response.Headnote))
                {
                    refs = refs + "
 Head Note:
 " + response.Headnote.ToLowerInvariant() + "

";
                }

                if(response.Refs != null)
                {
                    refs = refs + "<left>Refered Jdgmts: </left>
";
                    foreach(var obj in response.Refs)
                        {
                        if(obj.Jid == null) {
                            refs = refs + "
"
                                + obj.Title
                                +"
";
                        }
                        /*else
                        {
                            refs = refs + "
" + ""
                                     + obj.Title
                                + ""
                                + "
";
                       }*/
                        else
                        {
                            refs = refs + "
" + ""
                                     + obj.Title
                                + ""
                                + "
";
                        }

                if(response.AtRefrs != null)
                {
                    refs = refs + "<left>Refered Ats: </left>
";
                    foreach(var refAt in response.AtRefrs) {
                        if(refAt.AtId == null) {
                            refs += "
"
                                + refAt.At + "
";
                        }
                        else
                        {
                            refs += "
" + ""
                                + refAt.At + "";
                        }
                        foreach(var refSec in refAt.S) {
                            if(refSec.Ssi != null) {
                                refs += " " + refSec.St;
                            }
                            else
                            {
                                refs += " " + ""
                                    + refSection.Section
                                    + "";
                            }
                        }
                        refs += "
";

                    }
                }

                refs = refs + "<left>Jdgmt: </left>";
                var jdgmt = "
" + response.DJdes
                                                         + (response.Text)+ "
";

                jdgmt = jdgmt.Replace("^^^", "

");
                jdgmt = jdgmt.Replace("<SPARA>", "
");
                jdgmt = jdgmt.Replace("</SPARA>", "
");

                refs = refs + jdgmt;
                refs = refs + "";

                return refs;
            }

            data.Source = new HtmlWebViewSource { Html = getHtml(), BaseUrl="http://url.com/", BindingContext = response };


Where to store images for a website in react js?

Question: I am making a react E-comm site where I have 1000+ images to store..
I saw the way myntra stores their images https://assets.myntassets.com/...
How to store images in this way or where can I get more details about this concept?
The same concept is used by algoexpert.io which is a react website and their images are stored like this
Comment: You can use something like Amazon AWS S3 to store the images and then point to them in your own website
Answer: You can use Cloudinary or Imgur to upload and images through code. You can go through their Documentation. Cloudinary offer 25GB free storage in their free plan.
Documentation Cloudinary


IE6 Absolute positioning

Question: There is structure. ad is positioned relative. And the all other divs in div.ad positioned absolute.
top-left, bottom-left, top-right, bottom-right styles looking as it should. But "inside", "left", "right", "top", and "bottom" styles not working.
left, right dont have specific heights and top, bottom dont have specific widths and inside dont have both bec div.ad's height and width expandable.
Its working on IE 7,8,9 Opera 10.50+, Chrome and Firefox
Modern browser screenshot http://i56.tinypic.com/2ia8tj5.png
IE6 Screenshot http://i54.tinypic.com/2yozvar.png

.ad {
    color: #606060;
    position: relative;
    padding: 12px;
    min-height: 55px;
    min-width: 246px;
    margin: 0 0 10px 0;
}
/*Side Start*/
.top {
    top: 0;
    left: 11px;
    right: 10px;
    position: absolute;
    height: 11px;
}
.right {
    top: 11px;
    right: 0;
    bottom: 9px;
    position: absolute;
    width: 10px;
}
.bottom {
    bottom: 0;
    left: 11px;
    right: 10px;
    position: absolute;
    height: 9px;
}
.left {
    left: 0;
    top: 11px;
    bottom: 9px;
    position: absolute;
    width: 11px;
}
/*Side End*/
.inside {
    position: absolute;
    background-color: #f7f6f6;
    top: 11px;
    right: 10px;
    bottom: 9px;
    left: 11px;
}
/*Corners Start*/
.top-left {
    top: 0;
    left: 0;
    position: absolute;
    background-image: url('/images/DiseaseAds/border-top-left.png');
    background-repeat: no-repeat;
    width: 11px;
    height: 11px;
}
.top-right {
    right: 0;
    top: 0;
    position: absolute;
    width: 10px;
    height: 11px;
}
.bottom-left {
    bottom: 0;
    left: 0;
    position: absolute;
    width: 11px;
    height: 9px;
}
.bottom-right {
    bottom: 0;
    right: 0;
    position: absolute;
    width: 10px;
    height: 9px;
}
/*Corners End*/

Comment: This doesn't answer your question as stated, but if you need backwards comparability with IE6 and you're just doing fancy borders, sometimes falling back to good old  tags is easier since they get the job done and are easier to understand then complicated CSS box models in outdated browsers.
Answer: IE6 doesn't support both left and right on an element, or both top and bottom. You can achieve the same result using a CSS expression, but it is slow and requires scripting to be enabled:
left: 11px;
width: expression((this.parentNode.offsetWidth - 11 - 10) + 'px');

You can use a "sliding doors" technique to get an image-based top or bottom border without as many elements and without script; in short the left hand-corner and top are the background of the main div and the right-hand side is the background of a small absolutely positioned div.
Comment: It's works but instead of using css expressions i prefer writing normal javascript to do this. http://developer.yahoo.com/blogs/ydn/posts/2007/07/high_performanc_6/
Answer: Replace min-height and min-width properties with height and width. IE6 doesn't support min-* and max-* properties so .ad currently doesn't have any dimensions set. This will also give .ad an "layout" what means that you'll be able to position its children with right and bottom properties correctly.

IE6 Absolute positioning