text:
Q: CRC calculation by example I'd like to confirm whether I grasped the concept of CRC calculations correctly. I'll provide two examples, the first is calculating the remainder using normal subtraction, the second uses this weird XOR stuff.
Data bits: D = 1010101010.
Generator bits: G = 10001.
1) Subtraction approach to calculate remainder:
10101010100000
10001|||||||||
-----|||||||||
  10001|||||||
  10001|||||||
  -----|||||||
  000000100000
         10001
         -----
          1111

R = 1111.
2) XOR approach:
10101010100000
10001|||||||||
-----|||||||||
  10001|||||||
  10001|||||||
  -----|||||||
  00000010000|
        10001|
        ------
        000010

R = 0010.

A: Appending 1111 at the end does not satisfy the need since

10927 % 17 != 0

.
Note that as per the definition, the division should be modulo division as it is based upon modulo mathematics.

A: Both answers are correct. =)
(To recheck the first answer:
10101010100000 (binary) mod 10001 (binary)
= 10912 (decimal) mod 17 (decimal)
= 15 (decimal)
= 1111 (binary).)

A: Subtraction is wrongly done. In binary modulo, subtraction, addition, division, and multiplication are the same. So, XOR is correct.


text:
Q: dark mode working! but when opening web page, it is not default mode Dark mode working fine. but only the thing is, whenever I open the web page, always the dark mode is on at the beginning. I want it to be off at first and then turn on by switch. code is like this:
     let button = document.querySelector('.btn');
     let balls = document.querySelector('.btn-ball');

     button.addEventListener('click', ()=> {
       if (balls.classList.contains('ball')){
         balls.classList.remove('ball');
         document.body.classList.remove('all');
       } else {
         balls.classList.add('ball');
         document.body.classList.add('all');
       }
     })

html is like this:

CSS code is this:
     .btn {
        width: 40px;
        height: 70px;
        background: white;
        border: 1px solid black;
        border-radius: 22px;
        position: fixed;
        bottom: 10px;
        left:10px;
        cursor: pointer;
     }
     .btn:hover {
          box-shadow: 1px 1px 10px lightcoral;
     }
     .btn .btn-ball {
          width:30px;
          height: 30px;
          background-color: black;
          margin: 5px auto;
          border-radius: 50%;
          transition: transform .3s ease-out;
     }
     .btn .ball {
          transform: translateY(30px)
     }
     .all {
       background-color: black;
       color: white;
     }

A: Exciting, I just worked through something similar! In my styles, a set of CSS variables are defaulted to light values. I use a media query and :not() selector combination to apply dark styles
/** default light **/
:root {
  --color-surface: #fff;
}

/** override dark **/
:root.dark {
  --color-surface: #121212;
}

@media (prefers-color-scheme: dark) {
  :root:not(.light) {
    --color-surface: #121212;
  }

I have a radio group where the input value doubles as the class name. It's a pretty simple example, it could be rethought to work with a button, checkbox, or other control element.
  const lightInput = document.getElementById('light');
  const darkInput = document.getElementById('dark');

  const handleInput = (event) => {
    document.documentElement.classList.remove('light', 'dark'); // reset
    document.documentElement.classList.add(event.target.value);
  }

  // handle input events
  lightInput.addEventListener('input', handleInput);
  darkInput.addEventListener('input', handleInput);

    <fieldset>
      Theme
      <input id="light" type="radio" name="theme" value="light"> light
      <input id="dark" type="radio" name="theme" value="dark"> dark
    </fieldset>

I'll point out that I'm setting the class on the  element, not sure if it's recommended.

I want [dark mode] to be off at first and then turn on by switch

I'll point out another difference here where I wanted to use a media query for the preferred color scheme first and offer a manual override control as secondary. If you need more details on that let me know, but I hope the explanation above helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Finding the architectures that Python was built for, but from within Python itself Essentially I am looking for a way to find the following, but from within Python without having to run system commands:
$ file `which python2.7`
/Library/.../2.7/bin/python2.7: Mach-O universal binary with 2 architectures
/Library/.../2.7/bin/python2.7 (for architecture i386):    Mach-O executable i386
/Library/.../2.7/bin/python2.7 (for architecture x86_64):  Mach-O 64-bit executable x86_64

Something like:
>>> get_mac_python_archs()
['i386', 'x86_64']
>>>

Possible?

A: As far as I know, there is no truly reliable way other than to examine the executable files themselves to see which architectures have been lipo-ed together, in other words, what file does. While the distutils.util.get_platform() noted elsewhere probably comes the closest, it is based on configuration information at Python build time and the criteria used has changed between releases and even among distributions of the same release.
For example, if you built a Python 2.6 on OS X 10.6 with the 4-way universal option (ppc, ppc64, i386, x86_64), get_platform() should report macosx-10.6-universal.  However, the Apple-suppled Python 2.6 in OS X 10.6 reports the same string even though it is only a 3-way build (no ppc64).  EDIT: That may not be the best example since, come to think of it, you probably couldn't build a ppc64 variant with the 10.6 SDK.  However, the point still holds that the platform string is too context dependent to be totally reliable.  It may be reliable enough for some needs, though.  Otherwise, calling out to file or otool etc is likely the best way to go.

A: The function platform.architecture returns just the platform working:
Python 2.6.5 (r265:79359, Mar 24 2010, 01:32:55)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform
>>> platform.machine()
'i386'

the nearest I can get to is by using distutils.util.get_platform:
>>> import distutils.util
>>> distutils.util.get_platform()
'macosx-10.3-fat'

which is the full answer if you are using Python 2.7/3.2, as you can see in the documentation. "Starting from Python 2.7 and Python 3.2 the architecture fat3 is used for a 3-way universal build (ppc, i386, x86_64) and intel is used for a univeral build with the i386 and x86_64 architectures"


text:
Q: Get value of a h4 selector inside multiple selectors in javascript I have a ul list in HTML and I am struggling to get the inner text of the li element. I will simplify a little the example to be easy to understand what I am trying to do.
I have the following ul with list items:

 A

 B

 C

I have created a click method in javascript that get triggered when a list item is clicked:
$("#table-history > li").on("click", function () {

        console.log("Clicked");
});

How can I take the text inside the
 element ? Is there a way how can I make the click on chain elements/views ?

A: you can use
$('h4.item-title' , this).text()

$("#table-history > li").on("click", function () {

        console.log($('h4.item-title' , this).text());
});

 A

 B

 C

Note:  It will be better to use .trim() to avoid white spaces

$('h4.item-title' , this).text().trim()

A: Try using text():
$("#table-history > li").on("click", function () {
    console.log($(this).text());
});

EXAMPLE

$(document).on('click', '.item', function() {
  alert($(this).text());
});

 A

 B

 C

A: you can use this
$("#table-history > li").on("click", function () {

    console.log($(this).find('h4').text());
});

A: You can try this simplest method:
$("#table-history > li").on("click", function () {
     alert($(this).text().trim());
});

And Your Final Output


text:
Q: javascript process month from date string I have a code that splits the date and assigns each value in a var:
// Jun 22 2015  - 08:00:00 AM MYT
var parts = record.emsDateTime.split("-");
var date = parts[0];
var dt = date.split(" ");
var tm = parts[1];

var yr = Number(dt[2].replace(/\s/g,''));
var mon = Number(months[dt[0]]);
var dy = Number(dt[1]);

var apmRgx = /(AM|PM)/gi;
var apm = tm.toString().match(apmRgx);
var hr = Number(tm.split(":")[0]);
var mint = Number(tm.split(":")[1]);
var scnd = 0;

PV.Logger.logInfo("LOGGED >>>", "onReadRecordTimestampCheck", yr + " " + mon + " " + dy + " " + hr + " " + mint + " " + apm);

Based from the sample date (commented code) the month is June but when i print out the values:
onReadRecordTimestampCheckI 2015 5 22 8 0 AM

It shows "5" which means its May. Does the Month also starts with zero? or is any issue on my code?

A: I believe this is because the months are displayed 0-11, and not from 1-12 like you're thinking.
getMonth()


text:
Q: How to minimize a Java library's exposed interface surface while breaking down the library into subpackages? I'm making a library or two for and Android app and I want to keep the library's exposed interfaces to a minimum to avoid the abstraction leaking everywhere by avoiding making all of the classes 'public'.  I'm also following Maven's package structure.
Coming from C#, I've used the internal access modifier to accomplish what I want; if you're not familiar, internal grants access to anything within the assembly, but not outside of it.  So the few public interfaces are truly public.  The closest analogy, in my opinion, is package-private in Java, but that doesn't quite work when I organize my library into subpackages.
For example, say I have a class Service1 in root and another class Service2 in a subpackage under root.  I'd like Service1 to be able to reference Service2's interface, but preferably not make Service2 public as that'd expose Service2's interface outside of the package, which isn't what I intend.
I imagine this isn't terribly complicated, but I'm a little bit confused as to how to allow sibling/parent packages to access subpackage classes without making them public.  The only solution I've been able to really think of is to either 1) put everything at the same package level which would allow me to use package-private to hide everything that shouldn't be publicly available but is extremely messy or 2) suck it up and make my interfaces public, which admittedly offends my sensibilities.
How is this normally done?  Are all the classes in the same package, but possibly organized by subdirectories?  I've yet to come up with an approach that I truly like.

A: In Java, your intended API surface should define your package structure. Avoid the temptation to create subpackages just to "organize" your files in a way that doesn't directly relate to your API design. The perceived need to do so may even hint at poor API design.
With that in mind, you may still want to use a subpackage to create an internal API. For example, a group of classes might want certain members to be accessible to other classes in the group, but not expose those members to the rest of your library. In that case, put them in a subpackage and take advantage of package-private access. You'll need to think carefully about whether the exposed API of the subpackage is something you want to design, document, and support as a separate product. Doing so will make your product more valuable, but of course at some cost to you. If you don't want to support the internal API, or you're not sure yet, the usual solution is to put that API in a subpackage with a name that identifies it as internal, like com.myproduct.internal, or even an entirely different package hierarchy, like the com.sun classes that are exposed by necessity but officially not part of the standard Java API.

A: This may not apply to you since I don't know if Android supports it, but the major feature of the Java 9 update is exactly about this problem.
The modules feature of Java 9 (known as Project Jigsaw) gives you the ability to add a metadata file to a .jar that (among other things) lists the packages that are publicly visible. All other packages are internal to the module. In other words, public classes inside an internal module are equivalent to internal classes in a .Net assembly.

A: I agree with the other answers here, that the standard Java way is to not create the extra packages or use a package call internal.  I did want to point out another option you have with Android.
Android's has a support annotation, RestrictTo.  Anyone using the annotated code outside the proper scope gets a lint warning.
https://developer.android.com/reference/android/support/annotation/RestrictTo
This would allow you to annotate classes, methods, or fields as being restricted to the library itself.
@RestrictTo(RestrictTo.Scope.LIBRARY)

There's other options for the scope also.  This is the pattern Google has been following with the support library.

A: "But possibly organized by subdirectories" makes no sense, as each subdirectory is a new package in Java.
What's typically done is document what the public interface is by package, and document implementation classes as being open to change, use these directly at your own risk.
One way you could also use, and I've seen this used effectively, is split the library into 2 jar files. One file containing the interfaces for the public API only, and a second containing everything else. Provide ample documentation for the interfaces, and next to none for the implementation classes, in the version you release to the public.
And place some trust in your users. Trust them to stick to your public API, most will if it's well enough designed there's no need to mess with the internals directly, simply because messing with your internals would make their own work that much more brittle.


text:
Q: Mark as read a specific notification in Laravel 5.3 Notifications I know that there are many ways to mark as read all notifications of an User in L5.3 like this:
$user = App\User::find(1);

foreach ($user->unreadNotifications as $notification) {
    $notification->markAsRead();
}

Or:
$user->unreadNotifications->markAsRead();

But suppose I want to mark as read a specific notification with a given ID.
In fact, I have made a list of unread user notifications like this:

        @foreach($AuthUser->unreadNotifications as $notif)

                data['action']}}" data-notif-id="{{$notif->id}}">
                    {{$notif->data['message']}}

        @endforeach

As you can see, each a tag has a data-notif-id attribute contain notif ID.
Now I want to send this ID to a script via Ajax (on click event) and mark as read that notification only. for that I wrote this:
$('a[data-notif-id]').click(function () {

        var notif_id   = $(this).data('notifId');
        var targetHref = $(this).data('href');

        $.post('/NotifMarkAsRead', {'notif_id': notif_id}, function (data) {
            data.success ? (window.location.href = targetHref) : false;
        }, 'json');

        return false;
});

NotifMarkAsRead refers to bellow Controller :
class NotificationController extends Controller
    {
        public function MarkAsRead (Request $request)
        {
              //What Do I do Here........
        }
    }

How can I do that while there is not any Notification Model?

A: $notification = auth()->user()->notifications()->find($notificationid);
if($notification) {
    $notification->markAsRead();
}

A: According to this Answer on Github, solution is :

Illuminate\Notifications\DatabaseNotification is where the Model for
  the notifications exists, you can use it to grab a notification by ID
  and delete it. Also if you don't want to use the model you can use a
  normal DB query.

A: This works without fail:
$id = auth()->user()->unreadNotifications[0]->id;
auth()->user()->unreadNotifications->where('id', $id)->markAsRead();

A: You must first make sure that the notification exists first so that you can make adjustments to it and I do not recommend using the unreadNotifications object because in the event that there are no unread notifications an error will occur because of that
$notification_id = "03fac369-2f41-43d0-bccb-e364aa645f8a";
$Notification = Auth::user()->Notifications->find($notification_id);
if($Notification){
   $Notification->markAsRead();
}

or you can directly edit without any check
DB::table('notifications')->where('id',$notification_id)->update(['read_at'=>Carbon::now()])

A: This method worked fine for me:
$unreadNotifications = Auth::user()->unreadNotifications()->whereIn('id', $items)->get();

where $items is an array of notifications' ids!

A: Instead of the following :
$user->unreadNotifications->markAsRead();

let's use :
$user->unreadNotifications->first()->markAsRead();


text:
Q: Gitkraken with TFS 2015 I upgraded to gitkraken 2.2 and I'm not able to login to TFS 2015 repositories anymore. Asking username and password and my current windows credentials doesn't work. Tried with active directory domain domain\myuser but didn't work as well. Stuck to use it now since prompting for any commands. I have no issues by doing git commands via git bash or any other git tool (like git extensions)
Repositories are using HTTP and not HTTPS, could it be an issue as well ?
TFS Server : TFS 2015 update 1

A: I just tested Gitkraken 2.2 with my TFS 2015 Update 3 and TFS 2017, both can be connected without issue.
If you could login TFS 2015 repositories with the previous version of Gitkraken, I'm afraid you need to upgrade your TFS 2015.1 to TFS 2015.3 or later version.

A: Works now with latest release 2.3.3.
Thanks Gitkraken for your nice work


text:
Q: How to use localstorage store the jquery mobile's checkbox state?

                1
                2
                3
                4
                5

                1
                2
                3
                4
                5

I did a table use jquery mobile.okay!and then i wanna hide some columns,so i tapping the "Columns..." , now i hidden the columns,but how i use the localstorage store my operation,when i refresh this page it's not all columns show. i know there got 'ui-checkbox-on' and 'ui-checkbox-off'....
THX!

A: To store data:
localStorage.setItem("username", username);

To retrieve data:
var username = localStorage.getItem("username");

In your case something like:
HTML:
<input type="checkbox" onclick="toggle('.myClass', this)" >

   check 1.

<input type="checkbox"  onclick="toggle('.myClass2', this)" >

   check 2.

<input type="checkbox"  onclick="toggle('.myClass3', this)" >

   Check 3.

JS:
function toggle(className, obj) {
    var $input = $(obj);
    if ($input.prop('checked')) {
        $(className).css("visibility", "hidden");
        console.log(className);
        localStorage.setItem(className,'hidden')
    }
    else {
        $(className).css("visibility", "visible");
        localStorage.setItem(className,'visible')
    }
}

CSS:
input[type="checkbox"] {
  clear: both;
  float:left;
}

JSFiddle: https://jsfiddle.net/dudu84/jxghvoqv/2/


text:
Q: Primefaces (NullPointerException) Here's the problem.
I want to use primefaces, on server (using Glassfish 3.x) code, seems to be ok, but after running, i get this NPE error.
And cant figure out, where its coming from..
my Bean:
package mybean;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import org.primefaces.model.chart.PieChartModel;

@ManagedBean(name = "chartBean")
@RequestScoped

public class ChartBean {

    private PieChartModel model;

    public ChartBean() {
        model = new PieChartModel();
        model.set("Brand 1", 540);
        model.set("Brand 2", 325);
        model.set("Brand 3", 702);
        model.set("Brand 4", 421);
        }

    public PieChartModel getModel() {
        return model;
    }
}

And index page:
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:p="http://primefaces.prime.com.tr/ui">

    <h:head></h:head>
<f:view>
  <h:form>
    <h:outputText value="Hello My blog!!" />
    <h:inputText value="#{helloMyBlog.webFramework}" />
    <p:editor />
    <p:calendar navigator="true" pages="4"/>
    <p:pieChart value="#{chartBean.model}" />
   </h:form>
</f:view>
</html>

What can cause NPE? (Note, whole page cant be rendered because of this)
Thank you.

A: Do you have helloMyBlog bean with accessible webFramework?
Your getter for PieChartModel wont return chart, maybe you should call ChartBean() in it and return it's value.


text:
Q: Recaptcha Missing input response using Angularjs and PHP I am having trouble with recaptcha requests. I am using the vc Recaptcha service for Angular JS with PHP validation. I receive the error 'missing-input-reponse' from the reCaptcha object when submitting the form.
The site is built with AngularJS and PHP, I am using a data factory to send requests to the server using the $http object. I am implementing password reset functionality and I want to use reCaptcha on the reset form. This is where I'm having trouble.
The backend is all working properly, it definitely seems to be a problem with the Captcha request. My reCaptcha API codes are working elsewhere on the site but without the AngularJS implementation.
My controller looks like this:
MySite.controller('passwordResetController', function($rootScope, $scope, $window, $location, $routeParams, Data, vcRecaptchaService) {
    $rootScope.showControls = false;
    $scope.response = null;
    $scope.widgetId = null;
    $scope.form = {email: '', id: '', response: ''};
    $scope.model = {
        key: // MY SITE KEY //
    };
    $scope.setResponse = function (response) {
        console.info('Response available');
        $scope.response = response;
    };
    $scope.setWidgetId = function (widgetId) {
        console.info('Created widget ID: %s', widgetId);
        $scope.widgetId = widgetId;
    };
    $scope.cbExpiration = function() {
        console.info('Captcha expired. Resetting response object');
        vcRecaptchaService.reload($scope.widgetId);
        $scope.response = null;
     };
    $scope.sendReset = function(form) {
        var valid;
        $scope.form.response = $scope.response;
        console.log($scope.form.response);
        Data.post('/sendreset', {form:form})
        .then(function(results) {
            console.log(results);
            if (results.status === 'success') {
                valid = true;
            } else {
                valid = false;
            }
            Data.toast(results);
        });
        console.log('sending the captcha response to the server', $scope.response);
        if (valid) {
            console.log('Success');
            Data.post('/createRequest', {
                form: form
            }).then(function(results) {
                if (results.status === 'success') {
                    $scope.sendMail(form);
                }
            });
        } else {
            console.log('Failed validation');
            vcRecaptchaService.reload($scope.widgetId);
        }
    }
    $scope.sendMail = function(form) {
        Data.post('/sendPasswordReset', {
            form: form
        }).then(function(results) {
            Data.toast(results);
            if (results.status === 'success') {
                $location.path('login');
            }
        });
    }
});

My PHP validation is:
$app->post('/sendreset', function() use ($app) {
    $r = json_decode($app->request->getBody());
    $post = [
        'secret' => //== MY SECRET KEY ==//,
        'response' => $r->form->response
    ];
    $ch = curl_init('https://www.google.com/recaptcha/api/siteverify');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    $response = curl_exec($ch);
    curl_close($ch);
    var_dump($response);
    $response = json_decode($response, true);
    // check result
    if (isset($response['success']) && $response['success'] == true) {
        $response['status'] = 'success';
        echoResponse(200, $response);
    } else {
        $response['status'] = 'error';
        $response['message'] = 'Captcha test failed';
        echoResponse(201, $response);
    }
});

The Data functionality is all working properly.
Any help would be hugely appreciated.

A: The response from the server is a string not an array. I changed the controller to search for 'true' in the string, works fine now.


text:
Q: How to read key from keyboard in c++? How to read key from keyboard in c++ ?
i used _getch() but this is not working always.
i heard about win32 keyboard api. i am targeting to windows so window specific technique is fine. can anyone give me simple example how to read key and check for arrow and function key.
i read article
How to simultaneous read keys on keyboard?
but this is not working in may case. here is my attempt inspired from above linked reference
char temp;
BYTE keys[256];
while(true)
{
    temp = _getch();
    if(GetKeyboardState(keys))
    {
        if(keys[VK_UP]&0xF0)
        {
            // Move Up : Case failing when i pressed up key
        }
        else if(keys[VK_DOWN]&0xF0 || keys[VK_RETURN]&0xF0)
        {
            // Move Down : Case failing when i pressed down or enter

        }
        else if(keys[VK_TAB]&0xF0)
        {
            // Move Next : Case failing when i pressed tab
        }
        else
        {
            // Print charecter which read using _getch()
            cout<<temp;
        }

    }
}

i read MSDN article but do not understand what they are doing. i am doing such program first time so please make your example clear and illustrative so i can easly get it.  thanks

A: I don't have a Windows machine at hand to test this out, but I am thinking that the fact that you are using temp = _getch(); before GetKeyboardState(keys) is eating your characters.

A: there are many library in C++ which handle this type of problem, if you are the choice, I advise you to use QKeySequence and other classes to let useful keyboard management.
If you want to see example, refer you to chromium project, here is an example used to test code of "keyboard driver".
you can either search many example with "filetype" syntax in google search engine (example : filetype:cc GetKeyboardState)...
you need to set correctly the layout before use GetKeyboardState...
Hope this help you.
Regards,
/Mohamed


text:
Q: EPERM installing KuduSync on Azure I'm experiencing an 'EPERM' error trying to install KuduSync globally either from the Kudu debug console or automatically from the deploy.cmd file.
Here's the error log when I try to run npm install -g kudusync from the debug console:
npm http GET https://registry.npmjs.org/kudusync
npm http 304 https://registry.npmjs.org/kudusync
npm ERR! error rolling back Error: EPERM, rmdir 'D:\Program Files (    x86)\nodejs\0.10.5\node_modules\kudusync'

npm ERR! error rolling back  kudusync@0.1.24 { [Error: EPERM, rmdir 'D:\Program Files (    x86)\nodejs\0.10.5\node_modules\kudusync']
npm ERR! error rolling back   errno: 50,
npm ERR! error rolling back   code: 'EPERM',
npm ERR! error rolling back   path: 'D:\\Program Files (    x86)\\nodejs\\0.10.5\\node_modules\\kudusync' }
npm ERR! Error: EPERM, rmdir 'D:\Program Files (x86)\nodejs\0.10.5\node_modules\kudusync'
npm ERR!  { [Error: EPERM, rmdir 'D:\Program Files (    x86)\nodejs\0.10.5\node_modules\kudusync']
npm ERR!   errno: 50,
npm ERR!   code: 'EPERM',
npm ERR!   path: 'D:\\Program Files (x86)\\nodejs\\0.10.5\\node_modules\\kudusync' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! System Windows_NT 6.2.9200
npm ERR! command "node" "D:\\Program Files (x86)\\npm\\1.2.18\\node_modules\\npm\\bin\\npm-    cli.js" "install" "-g" "kudusync"
npm ERR! cwd D:\home
npm ERR! node -v v0.10.5
npm ERR! npm -v 1.2.18
npm ERR! path D:\Program Files (x86)\nodejs\0.10.5\node_modules\kudusync
npm ERR! code EPERM
npm ERR! errno 50
npm ERR! stack Error: EPERM, rmdir 'D:\Program Files (    x86)\nodejs\0.10.5\node_modules\kudusync'
npm ERR! Error: EPERM, open 'D:\home\npm-debug.log'
npm ERR!  { [Error: EPERM, open 'D:\home\npm-debug.log'] errno: 50, code: 'EPERM', path:     'D:\\home\\npm-debug.log' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! System Windows_NT 6.2.9200
npm ERR! command "node" "D:\\Program Files (x86)\\npm\\1.2.18\\node_modules\\npm\\bin\\npm-    cli.js" "install" "-g" "kudusync"
npm ERR! cwd D:\home
npm ERR! node -v v0.10.5
npm ERR! npm -v 1.2.18
npm ERR! path D:\home\npm-debug.log
npm ERR! code EPERM
npm ERR! errno 50
npm ERR! stack Error: EPERM, open 'D:\home\npm-debug.log'

Has someone already experienced and solved this issue ?
Thanks!
EDIT
Upon further searching I discovered that the folder the system is trying to remove doesn't exist, neither its parent, the path ends at D:\Program Files (x86)\nodejs\0.10.5\. Any clue ?


text:
Q: transparent div over an image but opaque text I have the following HTML code which simply shows an image with a transparent black overlay containing text.
I don't wan't my text to be transparent. I tried with z-index, but my text is still transparent:

What's wrong with my code?
This is my HTML:

Hockey

Sample text

     ...

and this is my css:
.hilight h2{
    font-family: Helvetica, Verdana;
    color: #FFF;
    z-index: 200;
}

.promo {
    position: relative;
}
.promo img {
    z-index: 1;
}

.hilight {
    background-color: #000;
    position: absolute;
    height: 85px;
    width: 415px;
    opacity: 0.65;
    font-family: Verdana, Geneva, sans-serif;
    color: #FFF;
    bottom: 0px;
    z-index: 1;
}

A: You need to set the opacity to the background only, not the entire div and it's contents. You can do this with rgba color selection eg
div {
   background: rgba(0,0,0,0.50);
}

The other way of doing it would be to use a semi-transparent png image with some background-position. This would then be multibrowser compatible

A: For cross browser support use transparent 1x1 pixel png image to do this.
You can generate the image on this site: http://www.1x1px.me/
Then just remove background-color and opacity and simply use background:url(bg.png);
jsFiddle Live Demo

A: change the background of .hilight to rgba(0,0,0,0.65) and remove the opacity.
.hilight {
 background-color: rgba(0,0,0,0.65);
 position: absolute;
 height: 85px;
 width: 415px;
 font-family: Verdana, Geneva, sans-serif;
 color: #FFF;
 bottom: 0px;
 z-index: 1;
}

A: Everything inside  will have the opacity of 0.65. Move the text outside the overlay div.


text:
Q: Unable to understand a crash while adding a field in vcard in ejabberd I am trying to add a new field in the vcard as "Abc" . For this I added an xml for this "Abc" field in xmpp_codec.spec file. And referenced it in the #vcard_temp. I placed the xmpp_codec.erl,xmpp_codec.hrl, xep0054.erl files thus generated after 'make spec' in their respective directories.
But when I try to add a value of this field by sending this iq
<<"<iq id='D2sPz-22' type='set'><vCard xmlns='vcard-temp'><N><GIVEN>byname</GIVEN></N><Abc>10</Abc><FN>byname </FN><NICKNAME>byname</NICKNAME></vCard></iq>">>

I get this error
[error] Hook vcard_iq_set crashed when running mod_avatar:vcard_iq_convert/1:
** Reason = {error,{badrecord,vcard_temp},[{mod_avatar,convert_avatar,[{file,"src/mod_avatar.erl"},{line,320}],3},{mod_avatar,vcard_iq_convert,[{file,"src/mod_avatar.erl"},{line,110}],1},{ejabberd_hooks,safe_apply,[{file,"src/ejabberd_hooks.erl"},{line,380}],4},{ejabberd_hooks,run_fold1,[{file,"src/ejabberd_hooks.erl"},{line,364}],4},{mod_vcard,process_sm_iq,[{file,"src/mod_vcard.erl"},{line,210}],1},{gen_iq_handler,process_iq,[{file,"src/gen_iq_handler.erl"},{line,132}],3},{gen_iq_handler,process_iq,[{file,"src/gen_iq_handler.erl"},{line,111}],4},{ejabberd_sm,route,[{file,"src/ejabberd_sm.erl"},{line,143}],1}]}
** Arguments = [{iq,<<"D2sPz-22">>,set,<<"en">>,{jid,<<"dgNW1Udm4Us">>,<<"example.com">>,<<"Smack">>,<<"dgnw1udm4us">>,<<"example.com">>,<<"Smack">>},{jid,<<"dgNW1Udm4Us">>,<<"example.com">>,<<>>,<<"dgNW1Udm4Us">>,<<"example.com">>,<<>>},[{vcard_temp,undefined,<<"myname ">>,{vcard_name,undefined,<<"myname">>,undefined,undefined,undefined},<<"myname">>,undefined,undefined,[],[],[],[],undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,[],undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,<<"10">>}],#{ip => {}}}]
06:47:47.776 [debug] SQL: "begin;"
06:47:47.776 [debug] SQL: "UPDATE vcard SET vcard='<vCard xmlns=''vcard-temp''><N><GIVEN>myname</GIVEN></N><FN>myname </FN><NICKNAME>myname</NICKNAME><Abc>10</Abc></vCard>' WHERE username='dgNW1Udm4Us'"
06:47:47.777 [debug] SQL: "UPDATE vcard_search SET username='dgNW1Udm4Us', fn='myname ', lfn='myname ', family='', lfamily='', given='myname', lgiven='myname', middle='', lmiddle='', nickname='myname', lnickname='myname', bday='', lbday='', ctry='', lctry='', locality='', llocality='', email='', lemail='', orgname='', lorgname='', orgunit='', lorgunit='', abc='', labc='' WHERE lusername='dgNW1Udm4Us'"

In mod_avtar.erl around line 320 is this function
convert_avatar(LUser, LServer, VCard) ->
    case get_converting_rules(LServer) of
    [] ->
        pass;
    Rules ->
        case VCard#vcard_temp.photo of
        #vcard_photo{binval = Data} when is_binary(Data) ->
            convert_avatar(LUser, LServer, Data, Rules);
        _ ->
            pass
        end
    end.

And line 320 is case VCard#vcard_temp.photo of inside this function.
And I'm unable to understand this error as since I haven't changed the #vcard_photo record, why does it says that vcard_temp is a bad record?
EDIT
This is the #vcard_temp record generated after adding the xml and making the spec
-record(vcard_temp, {version :: 'undefined' | binary(),
                     fn :: 'undefined' | binary(),
                     n :: 'undefined' | #vcard_name{},
                     nickname :: 'undefined' | binary(),
                     photo :: 'undefined' | #vcard_photo{},
                     bday :: 'undefined' | binary(),
                     adr = [] :: [#vcard_adr{}],
                     label = [] :: [#vcard_label{}],
                     tel = [] :: [#vcard_tel{}],
                     email = [] :: [#vcard_email{}],
                     jabberid :: 'undefined' | binary(),
                     mailer :: 'undefined' | binary(),
                     tz :: 'undefined' | binary(),
                     geo :: 'undefined' | #vcard_geo{},
                     title :: 'undefined' | binary(),
                     role :: 'undefined' | binary(),
                     logo :: 'undefined' | #vcard_logo{},
                     org :: 'undefined' | #vcard_org{},
                     categories = [] :: [binary()],
                     note :: 'undefined' | binary(),
                     prodid :: 'undefined' | binary(),
                     rev :: 'undefined' | binary(),
                     sort_string :: 'undefined' | binary(),
                     sound :: 'undefined' | #vcard_sound{},
                     uid :: 'undefined' | binary(),
                     url :: 'undefined' | binary(),
                     class :: 'confidential' | 'private' | 'public' | 'undefined',
                     key :: 'undefined' | #vcard_key{},
                     desc :: 'undefined' | binary(),
                     abc :: 'undefined' | binary()}).
-type vcard_temp() :: #vcard_temp{}.

A: If you modified a library that re-defines a record (in this case the vcard_temp record), you better recompile ejabberd, to ensure all the code uses the new record definition.
Also, it's worth checking if the old vcard_temp record definition is still being used somewhere. If you use SQL storage for mod_vcard, probably nnot, but better  make sure.


text:
Q: search functionality on multi-language django site I'm building a multi-language Django site, and I'm using django-transmeta for my model data translations. Now I'm wondering if there is a Django search app that works with multi-language models. I've played with Haystack and it works fine for single-language sites, but I can't get it to work with transmeta's metaclasses...
Does anybody have any experience with this? Any pointers would be appreciated!
cheers,
martin

A: This more of a starting point than a full solution, but I hope it help and that other users
can improve this idea and reach a better solution.
Using Haystack to index a multilingual site (using django-transmeta or django-multilingual) you face two problems:

*

*how to index the content for all the
languages

*how to search the query
the correct index depending on the
selected languages

1) Index the content for all the languages
Create a separate fields for each language in every SearchIndex model, using a common prefix
and the language code:
text_en = indexes.CharField(model_attr='body_en', document=True)
text_pt = indexes.CharField(model_attr='body_pt')

If you want to index several fields you can obviously use a template. Only one of the indexes can have document=True.
If you need pre-rendered http://haystacksearch.org/docs/searchindex_api.html field for
faster display, you should create one for each language (ie, rendered_en, rendered_pt)
2) Querying the correct index
The default haystack auto_query method is programmed to receive a "q" query parameter on the request
and search the "content" index field - the one marked as document=True - in all the Index models.
Only one of the indexes can have document=True and I believe we can only have a SearchIndex
for each django Model.
The simplest solution, using the common search form, is to create a Multilingual SearchQuerySet
that filters based, not on content, but on text_ (text being the prefix used on
the Searchindex model above)
from django.conf import settings
from django.utils.translation import get_language
from haystack.query import SearchQuerySet, DEFAULT_OPERATOR

class MlSearchQuerySet(SearchQuerySet):
    def filter(self, **kwargs):
        """Narrows the search based on certain attributes and the default operator."""
        if 'content' in kwargs:
            kwd = kwargs.pop('content')
            kwdkey = "text_%s" % str(get_language())
            kwargs[kwdkey] = kwd
        if getattr(settings, 'HAYSTACK_DEFAULT_OPERATOR', DEFAULT_OPERATOR) == 'OR':
           return self.filter_or(**kwargs)
        else:
            return self.filter_and(**kwargs)

and point your search URL to a view that uses this query set:
from haystack.forms import ModelSearchForm
from haystack.views import SearchView

urlpatterns += patterns('haystack.views',
    url(r'^search/$', SearchView(
        searchqueryset=MlSearchQuerySet(),
        form_class=ModelSearchForm
    ), name='haystack_search_ml'),
)

Now your search should be aware of the selected language.

A: I wrote a detailed explanation about how-to do it here: http://anthony-tresontani.github.com/Django/2012/09/20/multilingual-search/
That implies writing a custom solr engine (backend + query) and settings multiple cores by languages.

A: There are few commercial products - for example multilingual indexer for Solr or Lucene capable of determining the language automatically.
I don't like commercial products but the idea is nice and simple - crawl the website, determine the language (with meta tag for example) and index.
So choose the search engine and try to extend it to handle multilingual sites.
Good question though, let us know how you solved this.

A: Here is a solution.
Use Sphinx.  Create an index for each locale.  E.g. Articles-en_us, Articles-es_mx, etc.
When you pass the search query to the sphinx search api, append the locale code to the index name.
Here is a reference on how to setup sphinx with django.

A: Avoid sphinx if you can since you're going to want less dependencies. I use django to achieve multilingua using parameter hl=languageCode eg hl=el for greek or whatever 39 languages or so django with appengine supports. gae engineers will update backend no matter my updates, .po files with project gettext are my languagepack


text:
Q: C++ few istream pointer and refferecnes and refactoring The function below works, but it's seems to me it has very bad smell.
My project communicate with device over HTTP, it has some url with digest authentication, some pages without.
Some url compressed with deflate, some none.
So my function has 3 different way to get istream.
And i need to read istream in one place in the bottom of function.
But as said good people from another my question C++ variable visable scopes and strems, pointers in this case is bad.
And in this code in some cases creates dynamic object.
Poco::InflatingInputStream* inflater = new Poco::InflatingInputStream(*respStreamPtr);

And this is path to memory leaks?
If create inflater without new statement, then *respStreamPtr has no data out of if block scope.
So, please give me advice how to refactor this code in right way.
    std::ostream& requestStream = session->sendRequest(request);
    istream* respStreamPtr;
    respStreamPtr = &session->receiveResponse(response);
    if (response.getStatus() == HTTPResponse::HTTP_UNAUTHORIZED)
    {
        credentials->authenticate(request, response);
        session->sendRequest(request);
        respStreamPtr = &session->receiveResponse(response);
    }
    if (response.has("Content-Encoding") && response.get("Content-Encoding") == "deflate") {
        Poco::InflatingInputStream* inflater = new Poco::InflatingInputStream(*respStreamPtr);
        respStreamPtr = &std::istream(inflater->rdbuf());
    }
    std::ostringstream stringStream;
    stringStream << respStreamPtr->rdbuf();
    responseBody = stringStream.str();

A: Yes, that will be a memory leak, as every time you use new it will create a new object, which you never delete
However, you use the inflater variable outside of the scope it's declared in, so currently have no way of nicely deleting it without modifying other code. For a simple fix, you could just declare Poco::InflatingInputStream* inflater = nullptr; at the top of your code, then delete it at the end.
I'd strongly recommend reading up on how to manage memory correctly in c++, and even taking a look at smart pointers (but not without learning the fundamentals first)
Poco actually has functionality which does a lot of what you're trying to do, so your example could be easily condensed (disclaimer: untested):
session->sendRequest(request);
auto& responseStream = session->receiveResponse(response);
if (response.getStatus() == HTTPResponse::HTTP_UNAUTHORIZED)
{
    credentials->authenticate(request, response);
    session->sendRequest(request);
    responseStream = session->receiveResponse(response);
}
if (response.has("Content-Encoding") && response.get("Content-Encoding") == "deflate")
{
    Poco::InflatingInputStream inflater(responseStream);
    StreamCopier::copyStream(inflater, responseStream);
}
responseBody << responseStream;


text:
Q: how to append text in hdfs file with java api? I want create code java to save or append my text content to file in hdfs, but it returns Error, the flowing is my java code to append my text content to my file in HDFS system:
public class FileAppend {

    public static final String uri = "hdfs://192.168.3.152:9000/work/log.txt";

    public static void main(String[] args) throws IOException {

         String content = "bonjour";
         Configuration conf = new Configuration();

         FileSystem fs = FileSystem.get(URI.create(uri), conf);

         boolean flag = Boolean.getBoolean(fs.getConf().get("dfs.support.append"));

         System.out.println("dfs.support.append is set to be " + flag);

         if (true) {

         FSDataOutputStream fsout = fs.append(new Path(uri));

         PrintWriter writer = new PrintWriter(fsout);

         writer.append(content);

         writer.close();

         } else {

         System.err.println("please set the dfs.support.append to be true");

         }

         fs.close();

and the code my return thus erreur:
juil. 04, 2016 10:01:32 AM org.apache.hadoop.ipc.Client$Connection handleConnectionFailure
INFOS: Retrying connect to server: /192.168.3.152:9000. Already tried 0 time(s).
juil. 04, 2016 10:01:33 AM org.apache.hadoop.ipc.Client$Connection handleConnectionFailure
INFOS: Retrying connect to server: /192.168.3.152:9000. Already tried 1 time(s).
juil. 04, 2016 10:01:34 AM org.apache.hadoop.ipc.Client$Connection handleConnectionFailure
INFOS: Retrying connect to server: /192.168.3.152:9000. Already tried 2 time(s).
juil. 04, 2016 10:01:35 AM org.apache.hadoop.ipc.Client$Connection handleConnectionFailure
INFOS: Retrying connect to server: /192.168.3.152:9000. Already tried 3 time(s).


text:
Q: rails 5, remote: true form empty data I am trying to migrate Rails 4.2 application to Rails 5.1. In rails 4.2 we heavily used JQuery. At the moment I am struggling to make the forms, with remote: true attribute work properly. As an example this is a simple form where user select the country
= simple_form_for(:user_data,
  url: user_path(@user),
  remote: true,
  method: :patch,
  data: {'user-update' => true},
  dataType: 'json',
  html: wrapper: :horizontal_form ) do |f|
  .panel.panel-default
    .panel-body
      .col-md-8
        = f.input :country, label: 'Country',
      = f.button :submit

The controller
def update
  @user.update!(user_params)
  render json: @user
end

I have tried to add the respond_to with js response format, but in that case it tries to convert the @user to executable javascript. As of the event handler looks like this
  $('form[data-user-update]')
  .on('ajax:success', function(e, data, status, xhr) {
     // The data variable is empty
  })
  .on('ajax:error', function(e, error, status, xhr) {
    $('.simple_form').renderFormErrors('user_data', error.responseJSON);
  });

EDIT
Response Header
HTTP/1.1 200 OK
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Content-Type: application/json; charset=utf-8
ETag: W/"f53889092c58dc37054386c9504ad1ff"
Cache-Control: max-age=0, private, must-revalidate
X-Request-Id: 712b59ff-8011-4b10-a905-83e559b47452
X-Runtime: 0.101165
Transfer-Encoding: chunked

Request Header
Accept:text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8,et;q=0.6
Connection:keep-alive
Content-Length:71
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:localhost:3000
Origin:http://localhost:3000
Referer:http://localhost:3000/users/470d573b-b0f1-4822-b036-7d37be6672d6
X-Requested-With:XMLHttpRequest

Response
{
  firstName:'John',
  lastName: 'Smith',
  country: 'USA'
}

A: Just figured it out while running into the very same problem.
As per http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html#dealing-with-ajax-events
I assume you're using rails-ujs instead of older jquery-ujs. In jquery-ujs the code would work and data, status, xhr would be returned; rails-ujs however only returns one attribute - event and additional things are accessed through array on event.details
As per example in the guide
document.body.addEventListener('ajax:success', function(event) {
  var detail = event.detail;
  var data = detail[0], status = detail[1],  xhr = detail[2];
})

You can access response by calling event.detail[0]
If you've got quite a bit of code relying on this functionality, probably a better bet is to change rails-ujs back to jquery-ujs


text:
Q: Target a product in a list and increment/decrement its quantity I have a list of products and I want to be able to target each product and increment/decrement its quantity on button click. Please how can achieve this in plain Javascript?
This code can only capture the first item in the list, and that's because I used the item's index. How do I target the rest of the items dynamically and increase/decrease their quantity?

Product One

Description One

                <button action="remove">-</button>
                <input type="text" value="1" class="item-quantity">
                <button action="add">+</button>

Product Two

Description Two

                <button action="remove">-</button>
                <input type="text" value="1" class="item-quantity">
                <button action="add">+</button>

Product Three

Description Three

                <button action="remove">-</button>
                <input type="text" value="1" class="item-quantity">
                <button action="add">+</button>

Product Four

Description Four

                <button action="remove">-</button>
                <input type="text" value="1" class="item-quantity">
                <button action="add">+</button>

Product Five

Description Five

                <button action="remove">-</button>
                <input type="text" value="1" class="item-quantity">
                <button action="add">+</button>

CSS
li {list-style-type:none;
    border: solid 1px gray;
    margin: 10px;
    padding: 15px;

}

JS
const checkoutBag = document.getElementById('checkout-bag');
const itemCount =  document.getElementsByClassName("item-quantity");

let itemQuantity = 1;
checkoutBag.addEventListener("click", function(event){
  const more = event.target.attributes.action.value; //add product
  const less = event.target.attributes.action.value; //remove product
  if(more =="add"){
    itemQuantity++
    document.getElementsByClassName("item-quantity")[0].value = itemQuantity;
  }
  if(less =="remove"){
    itemQuantity--
    document.getElementsByClassName("item-quantity")[0].value = itemQuantity;
   }

   if(itemQuantity < 1) {
    itemQuantity = 0;
  }
  document.getElementsByClassName("item-quantity")[0].value = itemQuantity;

});

A: codesandbox demo
The HTML/CSS code is the same and hasn't changed.
const productOptions = document.querySelectorAll(".product-options");

productOptions.forEach((node) => {
  const itemCount = node.querySelector(".item-quantity");
  const add = node.querySelector("button[action='add']");
  const remove = node.querySelector("button[action='remove']");

  add.addEventListener("click", () => {
    itemCount.value = parseInt(itemCount.value, 10) + 1;
  });

  remove.addEventListener("click", () => {
    itemCount.value = parseInt(itemCount.value, 10) - 1;
  });
});


text:
Q: bundle.js not found with webpack dev server I'm having an issue with React/Redux/Webpack/Router.
Any "sub pages", such as: "/home/test", "users/registration" etc... fail to be loaded - and I get errors loading the "bundle.js" file generated by webpack.
The reason seems to be that the request to fetch the "bundle.js" is with the following url:
for path "/home/test": "/home/bundle.js"
for path "/users/registration": "/users/bundle.js"
Same issue occurs with the loading of "css" files and other resources.
This is my webpack configuration:
    const { resolve } = require('path');

const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const OpenBrowserPlugin = require('open-browser-webpack-plugin');

const config = {
  devtool: 'cheap-module-eval-source-map',

  entry: [
    'react-hot-loader/patch',
    'webpack-dev-server/client?http://localhost:8080',
    'webpack/hot/only-dev-server',
    './main.js',
    //'./assets/scss/main.scss',
  ],

  output: {
    filename: 'bundle.js',
    path: resolve(__dirname, 'dist'),
    publicPath: '/',
  },

  context: resolve(__dirname, 'src'),

  devServer: {
    hot: true,
    contentBase: resolve(__dirname, 'build'),
    publicPath: '/',
    historyApiFallback: true
  },

  module: {
    rules: [
      /* {
        enforce: "pre",
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loader: "eslint-loader"
      }, */
      {
        test: /\.(js|jsx)$/,
        loaders: [
          'babel-loader',
        ],
        exclude: /node_modules/,
      },
      {
        test: /\.(scss|sass)$/,
        exclude: /node_modules/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            'css-loader',
            {
              loader: 'sass-loader',
              query: {
                sourceMap: false,
              },
            },
          ],
          publicPath: '../'
        }),
      },
      { test: /\.(png|jpg|gif)$/, use: 'url-loader?limit=15000&name=images/[name].[ext]' },
      { test: /\.eot(\?v=\d+.\d+.\d+)?$/, use: 'file-loader?&name=fonts/[name].[ext]' },
      { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, use: 'url-loader?limit=10000&mimetype=application/font-woff&name=fonts/[name].[ext]' },
      { test: /\.[ot]tf(\?v=\d+.\d+.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/octet-stream&name=fonts/[name].[ext]' },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=image/svg+xml&name=images/[name].[ext]' },
    ]
  },

  plugins: [
    new webpack.LoaderOptionsPlugin({
      test: /\.js$/,
      options: {
        eslint: {
          configFile: resolve(__dirname, '.eslintrc'),
          cache: false,
        }
      },
    }),
    new webpack.optimize.ModuleConcatenationPlugin(),
    new ExtractTextPlugin({ filename: './styles/style.css', disable: true, allChunks: true }),
    new CopyWebpackPlugin([{ from: 'vendors', to: 'vendors' }]),
    new OpenBrowserPlugin({ url: 'http://localhost:8080' }),
    new webpack.HotModuleReplacementPlugin(),
  ],
};

module.exports = config;

It seems as if it always uses "../bundle.js" to find it for some reason.
Any help would be appreciated :)
Thank you,


text:
Q: How do I stop tables from messing with alignment? I'm new to TeX and I'm having a hard time understanding how paragraphs, alignment, indentation, and all that works.
Some text here.

\begin{tabular}{ l l }
  a & b \\
  c & d \\
\end{tabular}

Some more text here.

The text at the bottom gets shifted to the right to line up with the table. I want to stop this. It should be a new paragraph and appear exactly as the one at the top. Additionally, I've been using \hfill to add some space between the text and the table. Is that the "correct" way to do it?

A: Besides the indentation issue that @Werner described, the other placement issues can be understood with thinking in boxes as that is how TeX works.
Consider the following, where the TeX code is on the left and the output on the right.
Note that the first two cases produce identical output as the new line is taken to be a separation between a word, and each word is considered as a box.  In the third case, the blank line in between indicates a new paragraph so each word (box) is placed on a new line.

Now consider your case with text and tables, and think of the table as being placed in a box. So Some text here. is treated similar to the AA in the above example, the table is treated as BB, and the subsequent text Some more text here. is treated as CC.
So, the output of the first example below is similar to the output of the first two examples above where each box is placed next to each other, and the second example below is comparable to the last case above where each box is treated as a new paragraph and placed on its own line.

\documentclass{article}
\usepackage{xcolor}
\usepackage{showexpl}

\lstdefinestyle{demoLatexStyle}{
    basicstyle=\small\ttfamily,
    numbers=left, numberstyle=\tiny, stepnumber=2, numbersep=5pt,
    frame=none,
    backgroundcolor=\color{yellow},
    pos=r
}
\lstloadlanguages{[LaTeX]TeX}

\begin{document}
\begin{LTXexample}[style=demoLatexStyle]
    AA
    BB
    CC
\end{LTXexample}

\begin{LTXexample}[style=demoLatexStyle]
    AA BB CC
\end{LTXexample}

\begin{LTXexample}[style=demoLatexStyle]
    AA

    BB

    CC
\end{LTXexample}

\begin{LTXexample}[style=demoLatexStyle]
Some text here.
\begin{tabular}{ l l }
  a & b \\
  c & d \\
\end{tabular}
Some more text here.
\end{LTXexample}

\begin{LTXexample}[style=demoLatexStyle]
Some text here.

\begin{tabular}{ l l }
  a & b \\
  c & d \\
\end{tabular}

Some more text here.
\end{LTXexample}
\end{document}

A: The first paragraph after a sectional unit (like \section or \subsection) are usually treated differently and not indented. Subsequent paragraphs, including your tabular which is set on its own line with a blank line between the items will be indented by a length \parindent. If you don't want this indent, use \noindent at the start the paragraph. If you don't want any indent at all, use \setlength{\parindent}{0pt} in your document preamble.


text:
Q: R: Annual composite raster based on the median: How to get the index of the original layer for each pixel? I have a list of rasterstacks which are timeseries (300+ layers) for different bands. The timeseries are irregular, and therefore I want to create annual composites based on median ndvi. Thus from the available images for one year, the pixel with the (close to) median ndvi is chosen. For the other bands I want to create annual composites based on this ndvi composite. I try to make a mask in which each pixel has the value of the index of the image used for the median ndvi composite. I will apply this on the other bands, so I have 'the same' annual composite for each band per year.
Unfortunately, I am stuck on making the mask. I created some dummy data and somehow it returns two indexrasters (one with values 1-3, the other 2-4), while I expected one (with values 1-4).
Also my function cannot handle NA values and adding na.rm to the calc function does not solve this.
I am wondering what I need to adjust to get one output layer with values from 1-4, and how to let the 'which'-function deal with NAs.
#dummy data:
r <- raster(nrow=5, ncol=5)
set.seed(20181114)
s <- stack(lapply(1:5, function(i) setValues(r, runif(25, max=50))))
names(s) <- c("X2001", "X2002a", "X2002b", "X2002c", "X2002d")
#s$X2002a[2] <- NA

AnnualMask <- function(ts, year){
  year <- as.character(year)
  ts_year <- subset(ts, (grep(year, names(ts))))
  indexraster <- calc(ts_year, function(x){
    medianval <- median(x, na.rm = TRUE)
    which(abs(x - medianval) == min(abs(x - medianval)))
           })
  return(indexraster)
}

mask2002 <- AnnualMask(s, 2002)
plot(mask2002)

A: I am not sure yet about the part with the values ranging in 1-4, however here is something concerning the which part and dealing with NA:
# here is some dummy data
x <- c(3,4,5,NA,1,-2-45,2,54)

# now here is the which part as found in your function
medianval <- median(x, na.rm = TRUE)
which(abs(x - medianval) == min(abs(x - medianval)))
# returning in this case
integer(0)

# now let's add na.rm = T in the min function
medianval <- median(x, na.rm = TRUE)
which(abs(x - medianval) == min(abs(x - medianval), na.rm = T))
# returning
[1] 1

A: Thanks for providing good example data:
library(raster)
r <- raster(nrow=5, ncol=5)
set.seed(20181114)
s <- stack(lapply(1:5, function(i) setValues(r, runif(25, max=50))))
names(s) <- c("X2001", "X2002a", "X2002b", "X2002c", "X2002d")
s[[2]][1:3] <- NA

Here are two functions that do the same. #1 is perhaps simpler but probably less efficient.
annualIndex1 <- function(ts, year) {
    year <- as.character(year)
    ts_year <- subset(ts, (grep(year, names(ts))))
    medianval <- calc(ts_year, median, na.rm = TRUE)
    dif <- abs(ts_year - medianval)
    which.min(dif)
}
x1 <- annualIndex1(s, 2002)

This one uses calc to combine multiple steps
annualIndex2 <- function(ts, year){
    year <- as.character(year)
    ts_year <- subset(ts, (grep(year, names(ts))))

    fun <- function(x){
        y <- median(x, na.rm=TRUE)
        which.min(abs(x - y))
    }
    calc(ts_year, fun)
}
x2 <- annualIndex2(s, 2002)

The results are the same (and there are no NAs)
all(values(x1) == values(x2))
#[1] TRUE

However, if you make a cell NA in all layers
s[5] <- NA

function 2 fails. It could be adjusted like this
annualIndex2b <- function(ts, year){
    year <- as.character(year)
    ts_year <- subset(ts, (grep(year, names(ts))))

    fun <- function(x){
        if (all(is.na(x))) return( NA )
        y <- median(x, na.rm=TRUE)
        which.min(abs(x - y))
    }
    calc(ts_year, fun)
}

x2b <- annualIndex2b(s, 2002)

You use the term "mask", but really you are creating an index, can you can use the appropriate cells with strackSelect like this:
ts_year <- subset(ts, (grep(year, names(ts))))
v <- stackSelect(ts_year, x2)


text:
Q: Another Model for the API I\m using WebAPI in ASP.net MVC 4.5, and I was wondering what is the best practice when dealing the db entities, should I create another Model (you can call it API model or Service model) that deals with the API, pretty much the same way you create a View model to deal with the razor view, or just communicate directly with the db using the EF entities.

A: When it's a public API, I think its better to create extra Web API entities (Models in MVC). You can write a method to map the db entities to Web API entities. When you create extra entities your sure the public side of your API doesn't change when you change database entities.


text:
Q: Installing Gitosis on EC2/Ubuntu I'm trying to get gitosis to work on my Ubuntu instance on EC2. I'm having a problem with getting the right key to work.
I SSH to my server using the key provided in the AWS console: it's a public key (using the SSH IdentityFile option). All pretty standard. I'm using the official Ubuntu 10.04 AMI.
The installation of gitosis creates a new user. I'm supposed to provide a public key from my local machine. This doesn't work. I'm getting "Permission denied (publickey)."
In an attempt to mend the situation, I tried using the private key from the server to initialize the repository or adding the public key to the authorized keys of the created using. I managed to move one step closer, but then I got "fatal: 'gitosis-admin.git' does not appear to be a git repository" when trying to clone the admin repository.
Update:
I found out that the problem occurred because I specified an IdentityFile for my server in the .ssh/config file. When I removed it, the cloning worked. However, now I need to specify it every time I try to SSH into the server from the terminal. Is there a way around this?

A:
I found out that the problem occurred because I specified an IdentityFile for my server in the .ssh/config file. When I removed it, the cloning worked. However, now I need to specify it every time I try to SSH into the server from the terminal. Is there a way around this?

A couple.

*

*You can load both keys into the SSH agent, and both will be used whenever needed.
In Ubuntu, one should be running already, so just run ssh-add on both key files. (In fact, the GNOME Keyring component appears to load ~/.ssh/id_* automatically on logon.)

*You can have two Host definitions in ~/.ssh/config: one for interactive use, one for Git.
Host mybox
    Hostname foo.domain.tld
    IdentityFile ~/.ssh/ec2-key

Host mybox-git
    Hostname foo.domain.tld

git clone git@mybox-git:gitosis-admin.git

*In some cases, Gitosis is unnecessary – git can push and pull over SSH without any special configuration. (Although Gitosis does help with authorization in multiple-user cases.)


text:
Q: What are the solutions of $|x+y|=|x|+|y|$? So I am having a problem in solving this type of equation.
The problem I am dealing with is...
$$\left|(2x-1) + \frac{3x-1}x\right| = \left|2x-1\right| + \left|\frac{3x-1}x\right|$$
Please help me with this problem.
Thank you so much.

A: Hint: If considered over the reals, $|a+b| = |a| + |b|$ holds if and only if $a$ and $b$ are of same sign, or at least one of $a, b$ is $0$.
For you question, determine the intervals over which $2x-1$ is positive/zero/negative, and the intervals over which $(3x-1)/x$ is positive/zero/negative, and then take suitable unions/intersections. (Care must be taken at then endpoint $x = 0$, since $x$ appears in denominators.)

A: Another approach, assuming $x$ and $y$ are real:
$$\begin{aligned}
|x+y| = |x| + |y|
&\iff |x+y|^2 = (|x|+|y|)^2 \\
&\iff (x+y)^2 = |x|^2 + 2|x||y| + |y|^2 \\
&\iff x^2 + 2xy + y^2 = x^2 + 2|x||y| + y^2 \\
&\iff 2xy = 2|x||y| \\
&\iff xy = |x||y| \\
&\iff xy = |xy| \\
&\iff xy \geq 0 \\
\end{aligned}$$
In your case, the original problem is therefore equivalent to
$$(2x-1)\left(\frac{3x-1}{x}\right) \geq 0$$
which should be straightforward to solve.

A: Hint: A brute force approach is to drop one set of abs bars and replace the equation by two alternatives, one with "$+$" and one with "$-$" before the group that carried the bars.
The alternatives are logically "ORed", so each solution to each alternative is a solution to the original.
This can then be continued to double the number of equations again and again.


text:
Q: How to receive data passed by the server on client side I want to pass data from the server to the client (GET request), when I was using pug I did it with
// Server:
res.render('pageToRender', { variableToPass: value })

And on the client side I just referred to it with variableToPass. How can I do this with html and javascript though? I cannot find out...

A: It is possible via hack by inlining string value of javascript variable in a template
Here the example:
template.pug

Forbes's Pug source code!

server.js
res.render('pageToRender', { variableToPass: JSON.stringify(value) })


text:
Q: Disjunctive Normal Form I need some help understanding how to convert a formula into disjunctive normal form.
Can anybody explain how one would write φ = ((p ∨ q ∨ r) → (¬p ∧ r)) in disjunctive normal form?
Is it possible to use truth tables to help converting to DNF form?

A: I think a truth table could work for simpler propositions, but this one in question is relatively complicated - using logical equivalences might be easier.
Consider a conditional proposition $P \implies Q$, this is equivalent to $(\neg P \vee Q)$, which can be verified using a truth table.
Thus considering, $\varphi = ((P \vee Q \vee R) \implies (\neg P \land R))$,
\begin{align}
&\phantom{{}\equiv{}} ((P \vee Q \vee R) \implies (\neg P \land R))\\
&\equiv \neg (P \vee Q \vee R) \vee (\neg P \land R) \\
&\equiv ((\neg P) \land (\neg Q) \land (\neg R)) \vee (\neg P \land R) \\
&\equiv ((\neg P \land R) \vee \neg P) \land ((\neg P \land R) \vee \neg Q) \land ((\neg P \land R) \vee \neg R) \\
& \phantom{((P \vee Q \vee R) \implies} \vdots
\end{align}
which can be simplified using logical equivalences.
Hope this helps.


text:
Q: Neo4J Java Bolt Driver I am currently using the new SDN 4 ogm.properties file to configure the HttpDriver and was going to test with the new Neo4J 3.0 version.  Has the new Bolt driver been released yet to test with or is there a scheduled release date for it?  Currently the documentation only lists the Http or Embedded options.

A: No, the Bolt driver is work in progress. It'll be released when Neo4j 3.0 is out. We don't have scheduled dates for milestone releases yet.


text:
Q: WCF in a windows service I have a windows service that exposes a TCP connection (using WCF). This service starts and works fine on my machine (which uses windows firewall).
My colleagues are using mcafee security software (which includes a firewall). When they start the windows service it works some of the time, but the rest of the time the service times out (takes over 30 seconds to start). They get messages in their event log saying ...
Windows Firewall was unable to notify the user that it blocked an application from accepting incoming connections on the network.
We have a WIX installer which installs this windows service.
So my question is how do I make the WIX installer insert the firewall rules, more importantly will that work with mcafee? Do you think that will solve the problem?
What is the standard way of dealing with windows services that expose TCP connections? Normally a prompt would appear for a standard GUI or console app, but I am guessing this is impossible for a windows service.

A: The WiX v3 toolset ships with a Firewall extension that can configure the Windows firewall. I don't know much about McAfee but hopefully they read the Windows firewall configuration. If not, you'll need an API to poke holes in McAfee's firewall.


text:
Q: Keeping dialogs on top of window, but not on top of everything In my WPF application I have a lot of custom dialog boxes that pop open so the user can do various things with someDialogClass.ShowDialog(). To make sure that the dialog stays on top of the window that called it, I add Topmost="True" to the Window tag of the dialog's XAML file. This works, but the dialog is shown over every window open—even other applications. This is really annoying. So is there a way to have the dialog forced to always be on top of its parent, but not necessarily on top of other applications?
Here is a simplified version of the Window tag of the dialogs I have (omitting all the xmlns stuff):
<Window
mc:Ignorable="d"
ShowInTaskbar="False"
Topmost="True"
WindowStartupLocation="CenterOwner"
ResizeMode="NoResize"
SizeToContent="WidthAndHeight"
WindowStyle="ToolWindow">

A: You need to set the Owner of the Dialog/Window and it will then be on top of only that window.
For example:
var loginForm = new LoginForm();
loginForm.Owner = Application.Current.MainWindow;
var success = loginForm.ShowDialog();

Do not set the TopMost property on the Window otherwise it will be on top of every window.


text:
Q: Is there a way to block mouse and key press events to a certain program / window? I have an application written in Java, but I am also using the JNI to execute C++ written by myself. I would now like to generate mouse and key press events programmatically. For reasons, events from the "real mouse" interfere with those that are generated. Is there a way to completely block any mouse and key events being sent to that application/window?
The program is running on Ubuntu 20 and hence it uses the X Window system.
Edit: A solution which intercepts mouse/keyboard events on a very low-level and simply ignores them is equally appreciated. I simply don't want them to reach the windows created from Java code.


text:
Q: Android's ArrayAdapter - add strings listview instead of replace This is how I add an array to listview:
ListView my_listview = (ListView)findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, my_array);
my_listview.setAdapter(adapter);

my_array is uri of a file.
It works well. But next next time I want to array a new array, then I don't want to replace with with new one instead add new ones to the existing ones. How can I accomplish that?

A: You need to be using an ArrayList<String> my_array rather than a String[] my_array and then you can do:
my_array.addAll(other_array);

to add elements from a new array to your array. Then you can do:
adapter.notifyDataSetChanged();

to update your ListView with the new elements.


text:
Q: Red-Blue Hackenbush is a cold game Does the following proof make sense to prove that finite Red(Richard)-Blue(Louise) Hackenbush is a cold game?
If all edges touching the ground are exclusively red or blue, clearly one of the players has a winning strategy always (irrespective of whether they play first or second).
Else, assume Richard has a winning strategy as a first player. Now let Louise make the first move.
If Louise's move removes the edge that Richard wanted to remove as a first player(because of how the edges are connected), it is obvious that Richard has a winning strategy. Similarly, if Louise moves an edge that she couldn't have moved if Richard had moved first, again, Richard has a winning strategy by removing his first edge.
If Louise moves an edge that is not connected to R₁ then Richard assumes that R₁ is not present,  and plays by his strategy.
When Louise, for the first time, removes an edge connected to R₁, Richard removes R₁ and assumes that R₂(the edge he would've removed if he was playing first using his strategy) is not present and follows the strategy.
Continuing this way,

*

*If Louise removes an edge not connected to Rⱼ , Richard plays by his strategy assuming Rⱼ
is not there.

*If Louise removes an edge connected to Rⱼ, Richard removes Rⱼ and here on plays assuming Rⱼ₊₁
(the edge he would've removed if he was playing first using his strategy) is not present.

*If Louise's move removes Rⱼ, Richard can win (starting by removing Rⱼ₊₁)

*If Louise removes an edge that she couldn't have moved if Rⱼ wasn't present, again Richard has a winning strategy (removing Rⱼ next)

In this way, we show that if Richard can win as the first player, then he can win as the second player as well. Hence this Hackenbush game is R type.
A similar argument applies if Louise has a winning strategy as the first player.

A: Your proof is constructive and clear. Below is an alternative proof.

Given a hackenbush position $G$, and an edge $e$, let $G[e]$ denote the result of moving on edge $e$. We need to show that for any blue edge $b$, $G[b]<G$, or that Richard wins moving first and second on $G[b]-G$. It is obvious that Richard wins moving first on $G[b]-G$ (by moving to $G[b]-G[b]$), so assume Louise goes first. There are two types of options available to Louise.

*

*She can remove another blue edge $b'$ from $G[b]$, resulting in $G[b,b']-G$. I claim that a winning response for red is to remove $b'$ from $-G$, resulting in $G[b,b']-G[b']$.

*

*If $b$ is present in $G[b']$, then this follows by induction, since $G[b,b']$ is a left option of $G[b']$.

*If $b$ is not present in $G[b']$, then $G[b,b']=G[b]$, so Richard has moved to the zero position, and therefore wins.

*Louise's other option is to $G[b]-G[r]$, where $r$ is a red edge.

*

*If removing $b$ kills $r$, then Richard wins with by moving to $G[b]-G[r,b]=G[b]-G[b]=0$. The same goes if removing $r$ kills $b$.

*If removing neither of $b$ or $r$ kills the other, then it follows that $G[b,r]$ is a left option of $G[b]$ and a right option of $G[r]$, so by induction, we have
$$
G[b]<G[b,r]<G[r]
$$
proving Richard wins on $G[b]-G[r]$.


text:
Q: counting actual characters in a URI encoded string On the client, I have a textarea and I extract its value like this:
var TheURIEncodedString = encodeURI($('#TheTextArea').val());

The string then looks like this:
"This%20is%20a%20test%0AThis%20is%20a%20new%20line"

I send this string via ajax and when I receive it on the server, I need to count the number of actual characters, not the length of the string.
How can I do this?

A: Use HtppUtility.UrlDecode:
HttpUtility.UrlDecode("This%20is%20a%20test%0AThis%20is%20a%20new%20line").Length;

Result:
This is a test
This is a new line

A: Use the  HtppUtility.UrlDecode method
int numberOfCharacters =
    HttpUtility.UrlDecode("This%20is%20a%20test%0AThis%20is%20a%20new%20line").Length;


text:
Q: Not registering bolded text inside json item using JavaScript So I have an list with items where the years are bolded. But when i put them in JSON and later I set the text in HTML, the text is not bolded. In the link ,now I have the bold tags and the text . This is confusing . Can i make this work ?

Here's a time line of Dr. Borlaug's life:

1938  - Marries wife of 69 years Margret Gibson. Gets laid off due to budget cuts. Inspired by Elvin Charles Stakman, he returns to school study under Stakman, who teaches him about breeding pest-resistent plants.

1941  - Tries to enroll in the military after the Pearl Harbor attack, but is rejected. Instead, the military asked his lab to work on waterproof glue, DDT to control malaria, disenfectants, and other applied science.

1942  - Receives a Ph.D. in Genetics and Plant Pathology

1944  - Rejects a 100% salary increase from Dupont, leaves behind his pregnant wife, and flies to Mexico to head a new plant pathology program. Over the next 16 years, his team breeds 6,000 different strains of disease resistent wheat - including different varieties for each major climate on Earth.

1945  - Discovers a way to grown wheat twice each season, doubling wheat yields

1953  - crosses a short, sturdy dwarf breed of wheat with a high-yeidling American breed, creating a strain that responds well to fertalizer. It goes on to provide 95% of Mexico's wheat.

1962  - Visits Delhi and brings his high-yielding strains of wheat to the Indian subcontinent in time to help mitigate mass starvation due to a rapidly expanding population

1970  - receives the Nobel Peace Prize

1983  - helps seven African countries dramatically increase their maize and sorghum yields

1984  - becomes a distinguished professor at Texas A&M University

2005  - states "we will have to double the world food supply by 2050." Argues that genetically modified crops are the only way we can meet the demand, as we run out of arable land. Says that GM crops are not inherently dangerous because "we've been genetically modifying plants and animals for a long time. Long before we called it science, people were selecting the best breeds."

This is the part of mine JSON.
{"divHoldingTitle":{"title":"Dr. Norman Borlaug","textSave":"The man who saved a billion lives"},"imageHolder":{"theBigPicture":"./images/smiling-people.jpg","textUnderPicture":"Dr. Norman Borlaug, second from left, trains biologists in Mexico on how to increase wheat yields - part of his life-long war on hunger."},"bigList":{"itemList":[{"item":"1914  - Born in Cresco, Iowa"},{"item":"
1933  - Leaves his family\'s farm to attend the University of Minnesota, thanks to a Depression era program known as the\'National Youth Administration\'"}]}}

 for(i in obj.bigList.itemList){

    $('li').text(obj.bigList.itemList[i].item);
}

};
The problem is this.
Screenshot of the problem
As you can see. The lists have
* 1933  - Leaves his family's farm to..
But it is not bolded.
I am not sure how to solve this problem. I am using JavaScript .

A: This is due to using .text() method - it removes all formatting tags.
Use html() instead:
$('li').html(obj.bigList.itemList[i].item);


text:
Q: Creating callbacks with blocks I'm new to Objective-C having come from the JavaScript world, and I'm trying to define a "callback" property on a class. In JavaScript land we're used to passing around functions willy-nilly, but it seems Objective-C isn't so lenient.
Here's how I tried to do it (trying to simplify things as much as possible):
@interface CallbackThing : NSObject
  @property (nonatomic) NSString *derpDerp;
  @property (nonatomic) SEL callback;
@end

Then later in another class....
CallbackThing *testCallbackThing = [CallbackThing alloc] init];
testCallbackThing.callback = @selector(methodInThisCLass);

Finally in another class...
if (self.testCallbackThing.callback != nil){
    [self.thatOtherClass performSelector:self.testCallbackThing.callback];
}

That works great! I was so proud of myself... Until...
"warning: performSelector may cause a leak because its selector is unknown!"
Trying to read up on things, and it seems that the new way to do things is to use blocks... But none of the examples I've looked at make much sense in this scenario.

A: Not sure what your specific use case is, but blocks are easy. First, declare your block type:
typedef void (^MyBlock)(NSArray*, NSString*);

Then you can set this as a property, like you did with SEL:
@property(nonatomic, copy) MyBlock block;

Then, you simply call the block, which executes it:
self.block(someArray, someString);


text:
Q: How to keep dropdown list value after submit HTML
<td>
    <select name="Year" id="Year" value="">
        <option value=""></option>
    </select>
</td>

JavaScript to create the list
for (i = new Date().getFullYear(); i > 1900; i--)
{
    $('#Year').append($('<option />').val(i).html(i));
}

How do i keep the value of the year that is submitted?

A: In JS, since you have the year in the querystring, grab that and set it to the select box.
$('#Year').val(location.search.match(/year=([^&]+)/i)[1]);

A: The most obvious way is to pass $_POST['Year'] to a session or a cookie or to insert it into a database table and through PDO or MySQLi commands fetch the specific result anytime you want.

A: In your PHP you'll have access to the values that are posted.  In this case it will be in $_POST['Year'], $_GET['Year'] or $_REQUEST['Year'], as Year is the name of your select.
The issue you have is that the select is built by javascript, rather than PHP.  Because of that you need to set it using javascript too.  Therefore you need to get the data from PHP into javascript - does that make sense to you?
OK.
So what you need to do, is generate a call to a javascript function using PHP.  When the browser receives and renders the page it will run the javascript and set the value.
An example might be:
$year = $_POST['Year'];
echo( "<script>$('#Year').val('$year')<\script>" );

This would depend on how your PHP outputs the pages (I.E. what frameworks you are using, etc)
However, by far the simplest solution would be be actually build the select in PHP instead - if that's an option.

A: If the form is submitted to itself via GET, you can read the value from the querystring and set the value on the list:
for (var i = new Date().getFullYear(); i > 1900; i--)
{
    $('#Year').append($('<option />').val(i).html(i));
}
if (/[&?]Year=(\d{4})(&|$)/.test(location.search)) {
    var year = RegExp.$1;
    $('#Year').val(year);
}