text:
Q: Unable to boot newly installed Ubuntu 16.04 using UEFI mode? I have a laptop with Ubuntu 14.04 installed in BIOS (Legacy mode).
sudo dmidecode
BIOS Information
    Vendor: Dell Inc.
    Version: A16
    Release Date: 12/05/2013
...
System Information
    Manufacturer: Dell Inc.
    Product Name: Latitude E6410

Instead of upgrading, I tried to install new Xubuntu 16.04 in UEFI mode.

*

*Switched BIOS boot from Legacy to UEFI and disabled the RAID for SATA.
(SoftRAID/FakeRAID corrupt the GPT table backup in the end of disk, on each boot)

*Booted using USB key in UEFI mode & resized and converted partition table from MBR to GPT.

*Booted again using USB key in UEFI mode and installed Xubuntu. Created a new boot EFI (FAT32) partition.

On reboot, There is a Ubuntu entry in UEFI menu but selecting it raise a BIOS error message about no boot media.
Tried multiple things but no success:

*

*Boot-repair.

*Change EFI partition to FAT16.

*Reinstalled Xubuntu.

sudo sfdisk -d /dev/sda
label: gpt
label-id: 4A4481B5-0322-411E-8D05-552FBE6189AC
device: /dev/sda
unit: sectors
first-lba: 34
last-lba: 976773134

/dev/sda1 : start=     4194304, size=   127924224, type=0FC63DAF-8483-4772-8E79-3D69D8477DE4, uuid=F1D50A87-ACB2-4868-B1EA-66C3D5223EA4, name="Linux filesystem"
/dev/sda2 : start=   874115072, size=    98463744, type=0FC63DAF-8483-4772-8E79-3D69D8477DE4, uuid=C96E6320-18EA-40B2-BA46-79FC66407917, name="Linux filesystem"
/dev/sda4 : start=        2048, size=      409600, type=C12A7328-F81F-11D2-BA4B-00A0C93EC93B, uuid=BCB6E471-44F7-4C42-81EC-B276F1D6B6E6, name="EFI"
/dev/sda5 : start=   154339328, size=   715456512, type=0FC63DAF-8483-4772-8E79-3D69D8477DE4, uuid=AEBBA3F2-F8B6-40C0-ABFE-9F530FC5F641, name="Linux filesystem"
/dev/sda6 : start=   136513536, size=    17825792, type=0657FD6D-A4AB-43C4-84E5-0933C84B4F4F, uuid=515C9B77-B282-4007-8F1A-B0C5D908591E, name="Linux swap"

A: Finally, I got it to boot in UEFI. The problem is with UEFI firmware which seems buggy. It does require the EFI partition to be the first one in the GPT table. The partition entries in GPT table were unordered. (EFI was the first one on disk, but 4th in the table).
I followed instruction below to fix that:

*

*Boot using Live USB

*Backup GPT table
sudo su
swapoff
sfdisk -d /dev/sda > sda.bkp

*Modify new table with new order (EFI is the first)
cp sda.bkp sda.new
nano sda.new

sda.new
label: gpt
label-id: 4A4481B5-0322-411E-8D05-552FBE6189AC
device: /dev/sda
unit: sectors
first-lba: 34
last-lba: 976773134

/dev/sda1 : start=        2048, size=      409600, type=C12A7328-F81F-11D2-BA4B-00A0C93EC93B, uuid=BCB6E471-44F7-4C42-81EC-B276F1D6B6E6, name="EFI"
/dev/sda2 : start=     4194304, size=   127924224, type=0FC63DAF-8483-4772-8E79-3D69D8477DE4, uuid=F1D50A87-ACB2-4868-B1EA-66C3D5223EA4, name="Linux filesystem"
/dev/sda5 : start=   136513536, size=    17825792, type=0657FD6D-A4AB-43C4-84E5-0933C84B4F4F, uuid=515C9B77-B282-4007-8F1A-B0C5D908591E, name="Linux swap"
/dev/sda6 : start=   154339328, size=   715456512, type=0FC63DAF-8483-4772-8E79-3D69D8477DE4, uuid=AEBBA3F2-F8B6-40C0-ABFE-9F530FC5F641, name="Linux filesystem"
/dev/sda4 : start=   874115072, size=    98463744, type=0FC63DAF-8483-4772-8E79-3D69D8477DE4, uuid=C96E6320-18EA-40B2-BA46-79FC66407917, name="Linux filesystem"

*Restore the GPT table
sfdisk /dev/sda < sda.new

Now, I'm able to boot.
References:

*

*Change the number of the partition from sda1 to sda2

*How to renumber GPT partitions on an umounted disk? (simpler but i didn't try it)


text:
Q: Finding coordinates of the third point of a triangle from given? In ABC triangle we know the coordinates of A and B vertices. We also know lengths of 2 edges shown in the picture and the third edge is calculatable. What is the most efficient functon to find x3 and y3?
Note: I guess there is 2 possible C points. (Don't know how this effects)
Note(2): This question is also similar to finding intersection points of 2 circles.

A: You already said you can compute it as the intersection of two circles. Here's another way, assuming both sides have length $a$ as in the picture:
Find the midpoint $M$ of $AB$ as
$$M = (m_1, m_2) = ( (x_1+x_2)/2, (y_1+y_2)/2).$$
Compute a normal vector to the side $AB$ (orthogonal to $AB$) as:
$$n = (n_1, n_2) = (-(y_2-y_1), (x_2-x_1))$$
The normal $n$ has by construction the length $AB$. Find it via Pythagoras
$$ |n| = \sqrt{n_1^2+n_2^2}.$$
To find the point C, you have to go from $M$ in the direction of $n$ by a distance which equals the height of $C$ with respect to the side $AB$. This height $h$ is given by Pythagoras again:
$$a^2=h^2+\left(\frac{|AB|}{2}\right)^2=h^2+\left(\frac{|n|}{2}\right)^2$$
Then, you get $C$ as:
$$C = M \pm \frac{h}{|n|}n = (m_1 \pm \frac{h}{|n|}n_1, m_2 \pm \frac{h}{|n|}n_2)$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: GitLab issue on mac with Android Studio : SSL peer handshake failed with GitLab repo Suddenly started getting this error during fetch/push/pull from GitLab repo using Android Studio. Tried to run commands from terminal as well no success.
I am using Android studio. Gitlab integration was working fine from many month suddenly started getting this error:
unable to access : SSL peer handshake failed, the server most likely requires a client certificate to connect.
Config global setting for http already set to false. Was not facing any issue it's been months taking pull/push suddenly started getting this error.
Am using mac os : 10.12.6. Am not able to push/pull/fetch from my GitLab repo.
Please help.


text:
Q: Understanding positioning: adding position absolute to img container, doesn't allow me to margin auto. Why? I am trying to understand positioning and I get that when the parent element is positioned relatively you can position children element absolutely. At least I thought I understood this.
I proceeded to give picture element below position:absolute, however when I did this I ran into a problem where I couldn't center the image in mobile view (using media query). I tried to test the centering just normally, but I still couldn't make the image center. I used margin-left: auto and margin-right:auto under .img-circle, but that didn't work.
So I removed position:absolute on .picture class and then boom it worked. One way or another, I had to then re-position the title class.
It looks like my understanding of positioning is a bit off, could someone please help me understand why the above happened exactly? What I could have done to avoid such a mess, because it took me a while to get it. Thank you!
codepen project

/*.picture{
 position:absolute;

}*/

.img-circle{
  margin-top:10em;
  width:20em;
  height:20em;
  border:.2em solid;
  border-radius:50%;
  display:block;
}/*image shape*/

Click to slide the panel right

I'm a self taught web designer, developer, co-founder and entrepreneur based in Finland.

 I'm currently part of a small web development

 team in an upcoming start-up, building web and

 mobile applications.

My passion is to use technology based

 solutions, to help solve real world challenges.

 Competences:

 Languages and Frameworks:

 Javascript, HTML5, CSS3, jQuery, Bootstrap3,

 Angular.js, Meteor.js.

 Tools & expertise:

 Git, Responsive Web Design, Agile

 Methodologies.

A: Margins works fine with relative/static elements. The use of margins for an absolute/fixed element makes no sense since the margins works betweeen elements in the same document flow. When you put position absolute you are going out of the normal flow of the document. So you need another solution to center that. This is an example of a simple global perfect center without pre-knowing the sizes of the elements:
 .img-circle {
     position: absolute;
     left: 50%;
     -webkit-transform: translateX(-50%); /* for iOS devices*/
     transform: translateX(-50%);
 }

See it working:
http://codepen.io/anon/pen/NNPLgw

A: To answer your question, you need to use left/right, margin-left/right and a width to center an element using absolute positioning.

.picture {
  position: relative;
}

.img-circle {
  margin-top: 2em;
  height:20em;
  border:.2em solid;
  border-radius:50%;
  display: block;
  position:absolute;
  /* to vertically center an absolute positioned element below is needed  */
  width: 20em;
  margin-left: auto;
  margin-right: auto;
  left: 0;
  right: 0;
}

So even if that is do-able, it's likely not the best solution. What @Marcos suggest is preferable, or using text-align: center like below

.picture {
  position: relative;
  text-align: center;
}

.img-circle {
  margin-top: 2em;
  width: 20em;
  height:20em;
  border:.2em solid;
  border-radius:50%;
}


text:
Q: php automatic daily http login request I need to recover XML data from a news provider for a website. In order to do so, I need to send a url request to authenticate on a daily basis, and then I need to include the authentication ID with every new request I send. Basically the session expires every 24 hrs and then I need to request a new one to keep receiving my (non-RSS) news feeds. Is there any way to automate this process? With cURL maybe? My knowledge of PHP is fairly basic but I don't imagine I need to manually go into the file every morning, request the ID and copy the numerical string into all of my data requests...?  Also I don't know if this is common practice or if it is specific to our news provider, but any help, or if someone could maybe point me to a PHP tutorial on how to do this would be appreciated.
Thanks!
Jane

A: You can createe your php file to tdo the job then use either:
Windows SCheduler to perform the job at a specific time
or
Cron job to do the same thing in a unix based system,
I hope this is what you are looking for


text:
Q: Getting the value from usercontrol in javascript on button click I have this following scenario. I have a usercontrol in my page which has a radio button. This control is placed in a page, on click of a button in the page I need to know if the radio button is selected. This is a client event click event of the button as I have to show a confirmation message box i.e. if user clicks yes only then I have to do the remaining operation. Can you guide me what would be the best way to find if the radio button in the userControl is selected.
Thanks

A: If the page needs to know, add a public property to the UC:
public bool IsRadioSelected { get { return Radio.Checked; } }

You can also have the RadioButton postback on changing the check by setting the AutoPostBack property to true.
EDIT: For client script, you could also add a public property to the RadioButton:
public string RadioClientID { get { return Radio.ClientID; } }

Then in javascript, you can do:
var radioButtonObject = document.getElementById('<%= RadioClientID %>');
if (radioButtonObject.checked) { /* do this */} else { /* do that*/ }

The problem is the ID of the radio button in client script looks like "ct100_Body_somecontainer_RadioID" and can't be easily directly referenced.  The approach above is safer.


text:
Q: nwjs menu stop working after window.location.href changed The menu stop working after I navigate to another url.
Here's now I added the menu:
var menu = new nw.Menu({
  type: 'menubar'
});
var menuItems = new nw.Menu();

menuItems.append(
  new nw.MenuItem({
    label: 'Surf Google',
    click: function() {
      window.location.href = 'https://google.com';
    }
  })
);

menuItems.append(
  new nw.MenuItem({
    label: 'Surf Github',
    click: function() {
      window.location.href = 'https://github.com';
    }
  })
);

menu.append(
  new nw.MenuItem({
    label: "The Menu",
    submenu: menuItems
  })
);

var w = nw.Window.get();

w.menu = menu

I've created a github branch to show this issue:
https://github.com/wvary/nwjs-firewall-test/tree/tested-menu
Here's how to reproduce this issue:
git clone https://github.com/wvary/nwjs-firewall-test.git
cd nwjs-firewall-test
git checkout tested-menu
npm run build
./dist/nwjs-firewall-test-1.0.0-mac-x64/nwjs-firewall-test.app/Contents/MacOS/nwjs

After the app launches, click on the Google menu item to surf the Google website.
Then click on the Github menu item.  It should surf Github, but it doesn't.

A: You need to create an iframe which takes up the whole page and show it and set it's src attribute to the url you want to go to.
EDIT: you need to use a webview instead of an iframe
HTML:
<webview style="display:none; position:fixed; width: 100%; height:100%; bottom:0; right:0; top:0; left:0;" id="view_iframe"></webview>

JS:
var menu = new nw.Menu({
  type: 'menubar'
});
var menuItems = new nw.Menu();

menuItems.append(
  new nw.MenuItem({
    label: 'Surf Google',
    click: function() {
      document.getElementById("view_iframe").style.display = "block";
      document.getElementById("view_iframe").src = "https://google.com";
    }
  })
);

menuItems.append(
  new nw.MenuItem({
    label: 'Surf Github',
    click: function() {
      document.getElementById("view_iframe").style.display = "block";
      document.getElementById("view_iframe").src = "https://github.com";
    }
  })
);

menu.append(
  new nw.MenuItem({
    label: "The Menu",
    submenu: menuItems
  })
);

var w = nw.Window.get();

w.menu = menu


text:
Q: Fitting a continuous result to categorical predictors semiparametrically Suppose one has a relatively large number of observations, each of which consists of a continuous result and a small number (2 or perhaps 3) of categorical variables, each of which has a large cardinality (up to 10k or so).  So, for instance, one might wish to predict income given a person's university and chosen industry (this is just an example).  Right, now I am essentially fitting a model that looks like
log(income) ~ 0 + university + industry
in R notation, so each university and each industry has an associated "score", but there really is no reason to think the effect is additive, or that taking the log of income is the best transformation.  Still, it seems to work (somewhat).
Another idea I would like to try out is to express log(income) as a sum of all possible polynomial powers (up to total degree 4 or so) of the associated scores - this would require a lot of regularization, I suppose.
However, I suppose what I would really like is just to fit something like
g(income) ~ f(score.industry,score.university) and simultaneously fit g,f,score.industry,score.university where the latter two variables are actually vectors.  Does anyone have any insight as to how this might be done?

A: With up to 10,000 levels of each predictor, you are liable to have huge standard errors around each coefficient--plus, who is going to read the output containing all these results, or fashion a predictive equation out of them?  Instead of using a general linear model like you have, consider looking into data mining techniques like neural networks.  I think it would be more practical.

A: The proportional odds model is semiparametric and robust, and you can use quadratic (and other) penalization to deal with the large number of categories on the right hand side.  This is handled in the R rms package lrm function.  For reasons of computation time you might group income into 200 quantile groups so that you have only 199 intercepts in the model.  Someday I'll make the code more efficient so that no grouping is required at all.  JMP software makes use of patterned matrices so that the prop. odds model runs quickly no matter how many unique values there are in Y.
Quantile regression would be another possibility, although I don't know how to handle the large number of predictor categories.


text:
Q: Callback in Coffee Script I have the following function in coffeescript :
@get_person = (person_id) ->
  $.ajax '/people/'+person_id,
    type: 'GET'
    dataType: 'text'
    error: (jqXHR, textStatus, errorThrown) ->
        $('body').append "AJAX Error: #{textStatus}"
    success: (data, textStatus, jqXHR) ->
        $('.right-bar').html(data)  ->
            alert 1
            $('#interaction_filter').chosen()

The part of
$('.right-bar').html(data)  ->

works perfectly, but the call back below that, does not execute. What am I doing wrong? Nothing is shown in the console either.

A: You cannot wirte:
$('.right-bar').html(data) ->

the syntax doesn't allow that, you can instead sure this
$('.right-bar').html (data) ->

as shown here: http://api.jquery.com/html/
please consider adding the space between html and (data) ->

A: After running it through the CoffeeScript compiler I get the following output:
this.get_person = function(person_id) {};

$.ajax('/people/' + person_id, {
  type: 'GET',
  dataType: 'text',
  error: function(jqXHR, textStatus, errorThrown) {
    return $('body').append("AJAX Error: " + textStatus);
  },
  success: function(data, textStatus, jqXHR) {
    return $('.right-bar').html(data)(function() {
      alert(1);
      return $('#interaction_filter').chosen();
    });
  }
});

I believe what you wanted to do was chain the calls to html(). If so, it would look like this:
@get_person = (person_id) ->
    $.ajax '/people/'+person_id,
        type: 'GET'
        dataType: 'text'
        error: (jqXHR, textStatus, errorThrown) ->
            $('body').append "AJAX Error: #{textStatus}"
        success: (data, textStatus, jqXHR) ->
            $('.right-bar').html(data).html ->
                alert 1
                $('#interaction_filter').chosen()

A: Coffeescript is whitespace sensitive, so you need to indent the body of your callback to make it part of that function.
As Anthony pointed out the first few lines of your original code compile to
this.get_person = function(person_id) {};

$.ajax('/people/' + person_id, {
....

In other words, assign a function that does nothing to this.get_person, and then make an ajax call.
Assuming you wanted the ajax call to happen within the function then try:
@get_person = (person_id) ->
    $.ajax '/people/'+person_id,
        type: 'GET'
        dataType: 'text'
        error: (jqXHR, textStatus, errorThrown) ->
            $('body').append "AJAX Error: #{textStatus}"
        success: (data, textStatus, jqXHR) ->
            $('.right-bar').html(data)  ->
                alert 1
                $('#interaction_filter').chosen()

Indenting the $.ajax line makes it part of the callback function.
If you want to experiment more here's the solution on Try Coffeescript


text:
Q: How to take values of Jmeter variable in coma separated way I'm hitting a rest Api through http GET request in jmeter.
the url is like http://hostName:port/searchParameter=value1,value2,value3
the value1, value2 ... are taken from a file which is like
File.csv
   value1
   value2
   value3
this csv file is not really coma seperated values they are in separate lines.
Now how to achieve this

A: JMeter doesn't provide a suitable test element so you will have to go for __groovy() function and some custom scripting.
I can think of using File.readLines() function to read the contents of your file into memory followed by join() function to convert the array into a comma-separated string.
The final syntax would be:
${__groovy(new File('File.csv').readLines().join('\,'),)}

Demo:

Check out Apache JMeter Functions - An Introduction article to get familiarized with JMeter Functions concept.


text:
Q: FreeRadius doesn't log request in Debug mode Sorry, Radius newbie here …
I try to get a FreeRadius server version 3.0.20 as packaged by NixOS running to authenticate users on a dlink access point. I'm running the server with debug logging enabled.
I started with the default configuration and followed the Getting Started guide. So I added the user testing using testing Cleartext-Password := "password". I could confirm that this authentication works using radtest testing password 127.0.0.1 0 testing123. I also see it as a successful login in the logfile. – Cool, works so far.
Next I tried to authenticate over an access point using the same user and password. So I added the IP of the access point to clients.conf and configured the radius server and shared secret in the access point.
client ap2 {
    ipaddr = 192.168.1.32
    secret = testing123
}

When trying to authenticate I see the Request coming in on tcpdump, but FreeRadius is ignoring it completely: nothing gets logged.
To cross check and verify that the radius server is not only listening on localhost, I added another non-localhost-client and used radtest again with that source IP: everything still worked.
Checking with tcpdump again this is the working request:
192.168.1.144.57243 > 192.168.1.144.1812: [bad udp cksum 0x84d7 -> 0x44fd!] RADIUS, length: 77
    Access-Request (1), id: 0x2c, Authenticator: 106b49030bec802e1bd156ff48e3589a
      User-Name Attribute (1), length: 9, Value: testing
        0x0000: 7465 7374 696e 67
      User-Password Attribute (2), length: 18, Value:
        0x0000: d112 7b01 9c70 9548 d4a1 db33 c648 739e
      NAS-IP-Address Attribute (4), length: 6, Value: 127.0.1.1
        0x0000: 7f00 0101
      NAS-Port Attribute (5), length: 6, Value: 0
        0x0000: 0000 0000
      Message-Authenticator Attribute (80), length: 18, Value: &7u...s..L....|..
        0x0000: 2637 75c2 ead6 73cc d64c ee9f a97c d8d7

And this is the response from FreeRadius:
192.168.1.144.1812 > 192.168.1.144.57243: [bad udp cksum 0x849e -> 0x427b!] RADIUS, length: 20
    Access-Accept (2), id: 0x2c, Authenticator: 750e916c6b56f85eed550088c6cf30fc

In contrast this is request from DLink:
192.168.1.32.36759 > 192.168.1.144.1812: [udp sum ok] RADIUS, length: 103
    Access-Request (1), id: 0x6a, Authenticator: e7e4df28fcd96772ffb508c4df564d
      User-Name Attribute (1), length: 9, Value: testing
        0x0000: 7465 7374 696e 67
      User-Password Attribute (2), length: 18, Value:
        0x0000: a7cb 807f a0dc fdca 8bd4 e19f cbf4 3e79
      Calling-Station-Id Attribute (31), length: 19, Value: 98:f6:21:c0:cc:9d
        0x0000: 3938 3a66 363a 3231 3a63 303a 6363 3a39
        0x0010: 64
      NAS-Identifier Attribute (32), length: 19, Value: c4:e9:0a:21:61:b0
        0x0000: 6334 3a65 393a 3061 3a32 313a 3631 3a62
        0x0010: 30
      NAS-IP-Address Attribute (4), length: 6, Value: 192.168.1.32
        0x0000: c0a8 0120
      NAS-Port-Type Attribute (61), length: 6, Value: Wireless - IEEE 802.11
        0x0000: 0000 0013
      NAS-Port Attribute (5), length: 6, Value: 255
        0x0000: 0000 00ff

FreeRadius isn't logging this request at all, and also sends no response to it.
The first thing I probably wonder most: Why isn't FreeRadius logging the request from the DLink access point while it logs the other request?
Any idea what I am missing why there is no response UDP packet from FreeRadius to the access point?
One "bonus" question: in the UI of the access point the authentication mechanism is called "SPAP" but the "User-Password Attribute" looks like a normal "PAP" authentication. What is the difference between PAP and SPAP? What does SPAP stand for? I couldn't find any protocol documentation for it.

A: I feel embarrassed … the problem I saw the requests with tcpdump but not in the FreeRadius log was, that I blocked the requests in iptables so the UDP packets never arrived at the socket of FreeRadius.
… a perfect layer 8 bug :(


text:
Q: How to delete small independent masks from images? I have binarized image. Yellow = 1 mask, purple = 0 background:

I can filter if the whole masks is small by some threshold this way:
def filter_image(img):
    if img.sum() < 10:
        return np.zeros(img.shape)
    else:
        return img

However how get rid of this small yellow points?

A: That can be easily done with a Morphological Transformation
You can check the docs here
Something like this should work:
import cv2
import numpy as np

img = cv2.imread('some_image.png',0)
kernel = np.ones((5,5),np.uint8)
closing = cv2.morphologyEx(img, cv.MORPH_CLOSE, kernel)

You can play with the values inside the kernel to close the holes with a determinate size.
I hope it helped

A: Maybe you can use sequential morphological dilations and erosions in order to remove this noise.
These operation are also known as open and close.


text:
Q: using git-posh or/and oh-my-posh with Command Prompt(cmd, not Powershell) inside windows terminal Recently switched to new windows terminal, and after hours of searching on internet I was not able to find anything helpful, all what I want is to set up cmd inside new windows terminal to show git branches just like it's achievable for powershell.
eg like this
I have been very comfortable with cmd especially with its ability to use additional linux commands and don't wanna switch to powershell only because of nice displays of git branches. this is a source where everything is nicely explained for powershell, all I want is to do the same for CMD.
thanks in advance

A: In order to use Oh My Posh for shell-prompt customization from cmd.exe, the legacy Windows shell (citing from the docs (tab cmd)):

There's no out of the box support for Windows CMD when it comes to custom prompts. There is however a way to do it using Clink, which at the same time supercharges your cmd experience. Follow the installation instructions and make sure you select autostart.

As you later discovered, this issue on GitHub has background information on why native cmd.exe support isn't possible (even though Oh My Posh is generally shell-agnostic) and why third-party software is needed to make it work.

As for your comments re preferring cmd.exe:

I have been very comfortable with cmd

Migrating from the shell one is used to a new one is undoubtedly a painful transition, but well worth considering in this case:
While not without its quirks, PowerShell is vastly superior in just about every respect to cmd.exe, and enables you to do things you simply cannot do in cmd.exe

its ability to use additional linux commands

Linux (WSL) commands called from the Windows side are all mediated via executables (notably wsl.exe and bash.exe), which you can equally call from PowerShell.


text:
Q: ESLint producing different output when run with npm run-script When I lint my code with eslint scripts/**/*.js I see two linting errors:
» eslint scripts/**/*.js
/Users/user/dev/scripts/application.js
  3:8  error  "React" is defined but never used  no-unused-vars

/Users/user/dev/scripts/components/Header.js
  24:2  error  Unnecessary semicolon  no-extra-semi

✖ 2 problem (2 error, 0 warnings)

That's fine. When I put that command into "scripts" in my package.json then I only get one error.
// package.json
// ...
"scripts": {
  "lint": "eslint scripts/**/*.js"
}
// ...

» npm run lint
/Users/david.tuite/dev/ui/scripts/components/Header.js
  24:2  error  Unnecessary semicolon  no-extra-semi

✖ 2 problems (2 errors, 0 warnings)

What's happening to the other linting error?
edit
I'm starting to suspect this is a globbing problem. The missing linting error is in a file which isn't in a subdirectory of scripts.

A: Globs work differently in the package.json file.
The trick is to wrap the path matchers in single quotes to have them expanded at the shell level before they're passed to eslint.
// package.json
// ...
"scripts": {
  "lint": "eslint 'scripts/**/*.js'"
}
// ...

A: Sounds like David's answer solved the problem he was encountering. However, I had an identical symptom to the problem described.
In my case the problem was that npm was using the node_modules in the project directory which had a different version of the plugin than the global npm folder had.
Running eslint from command line was using the global version. Reconciling those versions resolved the issue in my case.


text:
Q: How to block anything from happening until a func has been completed? I have been looking around and have not found a way to prevent anything from happening until a function is completed. Basically, the events which are below the function are occurring before the function is. Let me show you the code and the console output.
Code:
if locationSwitch.isOn == true {
            let url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=\(location.latitude),\(location.longitude)&result_type=locality&key=AIzaSyDI-ZacHyPbLchRhkoaUTDokwj--z_a_jk"
            loadUrl(url: url) { optionalLocation in
                guard let nonOptionalLocation = optionalLocation else {
                    // Location was nil; Handle error case here
                    return
                }
                // Do something with your location here, like setting UI or something
                print("Optional Location: \(optionalLocation)")
                print("nonOptional Location: \(nonOptionalLocation)")
                cityState = nonOptionalLocation
                print("cityState: \(cityState)")
                print("Within Func")
            }
            print("Within If")
        } else {
            lat = 0.0
            lng = 0.0
            cityState = ""
        }
        print("After If")
        print("cityState Outside If Statement: \(cityState)")
        CoreDataHandler.savePhotoObject(locationCoordinateLatitude: lat, locationCoordinateLongitude: lng, locationLocality: cityState, dateCreated: date, discription: discriptionBox.text!, photo: selectedImageData!)
    }

Console Output:
Before If
Within If
After If
cityState Outside If Statement:
Optional Location: Optional("San Francisco, CA, USA")
nonOptional Location: San Francisco, CA, USA
cityState: San Francisco, CA, USA
Within Func

As you can see
Optional Location: Optional("San Francisco, CA, USA")
nonOptional Location: San Francisco, CA, USA
cityState: San Francisco, CA, USA
Within Func

should come before
Within If

I believe this is happening because the loadUrl function takes so long to complete that the code goes over it and completes the code under it then loadUrl completes and then is printed after everything else. This wouldn't be a problem except for the variable that is set equal to nonOptionalLocation is called after the loadUrl function is completed and because loadUrl ends up finishing after the rest of the code the variable that should be equal to nonOptionalLocation is actually equal to "".
Does anybody know how this could be completed right now I think that I need to block anything from happening until after loadUrl is completed, but if you know of another way to do this please share. Thank You.

A: loadUrl works asynchronously, just put the code to be executed after returning the data into the completion block
if locationSwitch.isOn == true {
    loadUrl(url: url) { optionalLocation in
        guard let nonOptionalLocation = optionalLocation else {
            // Location was nil; Handle error case here
            return
        }
        // Do something with your location here, like setting UI or something
        print("Optional Location: \(optionalLocation)")
        print("nonOptional Location: \(nonOptionalLocation)")
        cityState = nonOptionalLocation
        print("cityState: \(cityState)")
        print("Within Func")
        DispatchQueue.main.async {
            CoreDataHandler.savePhotoObject(locationCoordinateLatitude: lat, locationCoordinateLongitude: lng, locationLocality: cityState, dateCreated: date, discription: discriptionBox.text!, photo: selectedImageData!)
        }
    }
} else {
    CoreDataHandler.savePhotoObject(locationCoordinateLatitude: 0.0, locationCoordinateLongitude: 0.0, locationLocality: "", dateCreated: date, discription: discriptionBox.text!, photo: selectedImageData!)
}

A: Have you used DispatchQueue.main.sync{}, It may be stuck in your UI for a while that is not good but if you have no issue with this then you can try this.
if locationSwitch.isOn{

        DispatchQueue.main.sync {

            let url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=\(location.latitude),(location.longitude)&result_type=locality&key=AIzaSyDI-ZacHyPbLchRhkoaUTDokwj--z_a_jk"

            loadUrl(url: url) { optionalLocation in
                guard let nonOptionalLocation = optionalLocation else {
                    return
                }

                print("Optional Location: \(optionalLocation)")
                print("nonOptional Location: \(nonOptionalLocation)")
                cityState = nonOptionalLocation
                print("cityState: \(cityState)")
                print("Within Func")
            }
        }
        print("Within If")
    } else {
        lat = 0.0
        lng = 0.0
        cityState = ""
    }
    print("After If")
    print("cityState Outside If Statement: \(cityState)")
    CoreDataHandler.savePhotoObject(locationCoordinateLatitude: lat, locationCoordinateLongitude: lng, locationLocality: cityState, dateCreated: date, discription: discriptionBox.text!, photo: selectedImageData!)


text:
Q: How to plot frequency spectrum graph by reading my wav file with FFT import matplotlib.pyplot as plt
from scipy.fftpack import fft
from scipy.io import wavfile  # get the api
fs, data = wavfile.read('output.wav')  # load the data
a = data.T[0]  # this is a two channel soundtrack, I get the first track
b = [(ele/2**8.)*2-1 for ele in a]  # this is 8-bit track, b is now normalized on [-1,1)
c = fft(b)  # calculate fourier transform (complex numbers list)
d = len(c)/2  # you only need half of the fft list (real signal symmetry)
plt.plot(abs(c[:(d-1)]), 'r')
plt.show()

I GOT ERROR
C:\Users\isaco\PycharmProjects\test1\venv\Scripts\python.exe
C:/Users/isaco/PycharmProjects/test1/main.py
Traceback (most recent call last):
File "C:\Users\isaco\PycharmProjects\test1\main.py", line 9, in
plt.plot(abs(c[:(d-1)]), 'r')

TypeError: slice indices must be integers or None or have an __index__ method

Process finished with exit code 1

2. ON MY OTHER COMPUTER
I tried running this code the same way on my other computer. I got a different error on the other computer.
C:\Users\isaco\PycharmProjects\pythonProject1\venv\Scripts\python.exe
C:/Users/isaco/PycharmProjects/pythonProject1/main.py
Traceback (most recent call last):
File "C:\Users\isaco\PycharmProjects\pythonProject1\main.py", line 7, in
b = [(ele/2**8.)*2-1 for ele in a]  # this is 8-bit track, b is now normalized on [-1,1)

TypeError: 'numpy.int16' object is not iterable

Process finished with exit code 1
I'm new to Python. Why am I getting two different errors? I am in the learning process. I'm doing a project on Digital Signal Processing.
After reading the output.wav file where I recorded my voice, I need to calculate it with FFT and then plot the frequency spectrum on the graph.
I couldn't find the source of the error. How can I fix ? Could you help ?


text:
Q: how to initialize diff date formats in spring config xml with constructor injection I have two diff POJOs(Bean Classes) and i need to have diff date format for each bean. Do i need to initialize the SimpleDateFormat twice with diff Ids so that my two POJOs can use the two date formats?
<bean id="dateFormatEmployee" class="java.text.SimpleDateFormat">
    <constructor-arg value="mm-dd-yy"></constructor-arg>
    <constructor-arg value="true" />
</bean>
<bean id="dateFormatUser" class="java.text.SimpleDateFormat">
    <constructor-arg value="dd-mm-yyyy"></constructor-arg>
    <constructor-arg value="true" />
</bean>
<bean id="employee" class="com.kranti.springcore.Employee">
    <constructor-arg name="dob">
        <bean factory-bean="dateFormatEmployee" factory-method="parse">
            <constructor-arg value="12-20-90"></constructor-arg>
        </bean>
    </constructor-arg>
</bean>
<bean id="user" class="com.kranti.springcore.User">
    <constructor-arg name="dob">
        <bean factory-bean="dateFormatUser" factory-method="parse">
            <constructor-arg value="20-12-1995"></constructor-arg>
        </bean>
    </constructor-arg>
</bean>

A: SimpleDateFormat is not a thread safe class and should not be created as a singleton - here is why. As a workaround try putting these formats in a properties file. Inject these formats as necessary in to your code and use it when instantiating the SimpleDateFormat class.
Your properties file could look like:
date.format.user=dd-mm-yyyy
date.format.employee=mm-dd-yy

Lets say you have a service beans which handles employees and users
@Component
public class Employee {

    @Value("${date.format.employee}")
    private String dateFormat; // this will end up with the value mm-dd-yy

    public void doStuff() {
        // your service code here
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
        // do something with simpleDateFormat
    }

}

@Component
public class User {

    @Value("${date.format.user}")
    private String dateFormat; // this will end up with the value dd-mm-yyyy

    public void doStuff() {
        // your service code here
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
        // do something with simpleDateFormat
    }

}


text:
Q: Proving that functor category between two $\mathscr{U}$-categories is a $\mathscr{U}$-category I am using the definition of a categories where $\text{Ob}(C)$ is a set and $\text{Hom}_C(x,y)$ is a set for $x,y\in\text{Ob}(C)$.

A category $C$ is said to be a $\mathscr{U}$-category, if
$\text{Hom}_C(x,y)\in\mathscr{U}$ for all $x,y\in C$. Furthermore, $C$
is called $\mathscr{U}$-small if it is a $\mathscr{U}$-category and, there exists $U\in\mathscr{U}$ such that $\text{Ob}(C)\cong U$.

Fix a universe $\mathscr{U}$ and suppose $C,D$ are $\mathscr{U}$-categories. Moreover, assume $C$ is $\mathscr{U}$-small. I want to prove the claim that $\text{Func}(C,D)$ is a $\mathscr{U}$-category.
Let $F,G:C\rightarrow D$ be two functors. We have to show that $\text{Hom}_{\text{Func}(C,D)}(F,G)\in\mathscr{U}$. Clearly the morphism of functors between from $F$ to $G$ are a subset of $\prod_{x\in\text{Ob}(C)}\text{Hom}_D(F(x),G(x))$. So it is sufficient to show that this latter set is an element of $\mathscr{U}$.
We know that $\text{Hom}_D(F(x),G(x))\in\mathscr{U}$, for all $x\in C$. If it were the case that $\text{Ob}(C)\in\mathscr{U}$, then it would immediately follow that $\prod_{x\in \text{Ob}(C)}\text{Hom}_D(F(x),G(x))\in\mathscr{U}$. However, we only know $\text{ob}(C)$ is isomorphic to a set in $\mathscr{U}$. How can this be used to show that $\prod_{x\in \text{Ob}(C)}\text{Hom}_D(F(x),G(x))\in\mathscr{U}$?
Edit:
Let $u:U\rightarrow\text{Ob}(C)$ be the bijection whose existence we have assumed. From this we get a bijection
$$\prod_{x\in\text{Ob}(C)}\text{Hom}_D(F(x),G(x))\cong\prod_{a\in U}\text{Hom}_D(F(u(a)),G(u(a)))\in\mathscr{U}.$$
This implies that $\prod_{x\in\text{Ob}(C)}\text{Hom}_D(F(x),G(x))$ is isomorphic to an element of $\mathscr{U}$. But we wanted to prove that $\prod_{x\in\text{Ob}(C)}\text{Hom}_D(F(x),G(x))\in\mathscr{U}$.


text:
Q: SwiftUI ListStyle on macOS On macOS, using SwiftUI, regarding List:
I need to modify the List's background color.
Using the view debugger I see that the List has a ListCoresScrollView inside, with an internal _NSScrollViewContentBackgroundView and a NSVisualEffectView. That view has a white background by default. I want to change that particular view (e.g. to become transparent) because it seems to be an internal view.
How can one modify the background view on a list (in macOS, not IOS)?
Btw, I tried using a SidebarListStyle(). That does offer the background I want, but... dragging behavior is different (undesired) in a SidebarListStyle. So an alternative solution to my question could be "how to modify dragging behavior on a SidebarListStyle to mimic the default dragging behavior"?
It has taken me many many hours, but I cannot come up with a proper solution. Can anybody provide a working solution?

A: Update #2 (about 30 mins later)...
This works :)
extension NSTableView {
    open override func viewDidMoveToWindow() {
        super.viewDidMoveToWindow()

        // set the background color of every list
        backgroundColor = .clear
        enclosingScrollView?.drawsBackground = false
        enclosingScrollView?.backgroundColor = .clear
        enclosingScrollView?.autohidesScrollers = true
        enclosingScrollView?.verticalScroller = MyScroller()
    }
}

class MyScroller: NSScroller {
    override func draw(_ dirtyRect: NSRect) {
        self.drawKnob()
    }
}

Original answer
Not sure if you are still looking for an answer, but this is the closest I've managed to get. Still can't get the scrollbars (especially background) to be actually transparent. But, is closer than I was.
Add a swift file with this in your project (for now, I've just put it at the top of my ContentView.swift file).
extension NSTableView {
    open override func viewDidMoveToWindow() {
        super.viewDidMoveToWindow()

        // set the background color of every list
        backgroundColor = .clear
        headerView = nil
        enclosingScrollView?.drawsBackground = false
        enclosingScrollView?.backgroundColor = .clear
        enclosingScrollView?.hasHorizontalScroller = false
        enclosingScrollView?.autohidesScrollers = true
    }
}

From what I've read, this should work. But, it doesn't. I perhaps don't need all of those settings, but I'll keep adding until I can get it fully working.
HTH - please let me know if you've solved it fully.

A: I played with RichS's answer a bit more and found that the following suffices in my project:
extension NSTableView {
    open override func viewDidMoveToWindow() {
        super.viewDidMoveToWindow()

        backgroundColor = .clear
        enclosingScrollView?.drawsBackground = false
    }
}

YMMV, so please look at RichS's answer above if your scrolling does not work as expected.


text:
Q: Aviary SDK android crash on startActivityForResult I have integrated Aviary SDK for photo editing in my application. But when i start intent for result, application just crashed every time.
Please provide any solution.
Following is the code.
Intent newIntent = new Intent(thisContext, FeatherActivity.class );
newIntent.setData( Uri.parse(image_path));
newIntent.putExtra( Constants.EXTRA_IN_API_KEY_SECRET, api_secret_key );
startActivityForResult( newIntent, 1 );

11-10 18:01:05.681: E/AndroidRuntime(18797): FATAL EXCEPTION: main
11-10 18:01:05.681: E/AndroidRuntime(18797): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.fourspan.ecoviate/com.aviary.android.feather.FeatherActivity}: java.lang.NullPointerException
11-10 18:01:05.681: E/AndroidRuntime(18797):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
11-10 18:01:05.681: E/AndroidRuntime(18797):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
11-10 18:01:05.681: E/AndroidRuntime(18797):    at android.app.ActivityThread.access$800(ActivityThread.java:139)
11-10 18:01:05.681: E/AndroidRuntime(18797):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
11-10 18:01:05.681: E/AndroidRuntime(18797):    at android.os.Handler.dispatchMessage(Handler.java:102)
11-10 18:01:05.681: E/AndroidRuntime(18797):    at android.os.Looper.loop(Looper.java:136)
11-10 18:01:05.681: E/AndroidRuntime(18797):    at android.app.ActivityThread.main(ActivityThread.java:5086)
11-10 18:01:05.681: E/AndroidRuntime(18797):    at java.lang.reflect.Method.invokeNative(Native Method)
11-10 18:01:05.681: E/AndroidRuntime(18797):    at java.lang.reflect.Method.invoke(Method.java:515)
11-10 18:01:05.681: E/AndroidRuntime(18797):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
11-10 18:01:05.681: E/AndroidRuntime(18797): Caused by: java.lang.NullPointerException
11-10 18:01:05.681: E/AndroidRuntime(18797):    at com.aviary.android.feather.FeatherActivity.onContentChanged(FeatherActivity.java:916)
11-10 18:01:05.681: E/AndroidRuntime(18797):    at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:293)
11-10 18:01:05.681: E/AndroidRuntime(18797):    at android.app.Activity.setContentView(Activity.java:1937)
11-10 18:01:05.681: E/AndroidRuntime(18797):    at com.aviary.android.feather.FeatherActivity.onCreate(FeatherActivity.java:556)
11-10 18:01:05.681: E/AndroidRuntime(18797):    at android.app.Activity.performCreate(Activity.java:5248)
11-10 18:01:05.681: E/AndroidRuntime(18797):    at   android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
11-10 18:01:05.681: E/AndroidRuntime(18797):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)

Thanks


text:
Q: Configuring youtube-dl I want to configure youtube-dl, that it downloads only audio files in mp3. and in its help it shows the following line:
   You  can  configure  youtube-dl by placing default arguments (such as
   --extract-audio --no-mtime to always extract the audio and  not  copy
   the     mtime)     into     /etc/youtube-dl.conf    and/or    ~/.con‐
   fig/youtube-dl.conf."

BUT in my etc folder is no youtube-dl.conf file, nor is one in the .config folder (im a bloody greenhorn, took me 15 minutes to find the .config folder..)
can anyone help me to configurate youtube-dl?
btw.: I already made it to download the files in mp3 by manual command, but I need to type the commands after every download :/
I have ubuntu 13..... 10? I think? 13. something for sure =) thanks!

A: You need to create the config file yourself, it's not created by installation of the program.
Just save from your editor to  ~/.config/youtube-dl.conf (note no dash in .config).
The system-wide default configuration file, /etc/youtube-dl.conf, could be created by installing, but is not. That's not a problem, as the file format is not complicated, so an example file is not important.

Not sure what exactly you are doing, but if it's about repeating the download command with a different url, try using the shell history, pressing Up to recall the command, and edit the file name.
(To show your Ubuntu version, use lsb_release -a)

A: i made an "executable" for downloading musics from youtube ...
my ubuntu 14.10 also does not show up those config files, so what this does is basically executing the cmd for youtube-dl (instead of strange names it uses only what shows up on youtube, without the link in the end) , converts to mp3 and discards video.
to use this you need to:

create a file: (terminal -> touch download.sh)
paste this:
#!/bin/bash
#youtube to mp3 downloader
youtube-dl -o '%(title)s.mp4' --extract-audio --audio-format mp3 $1
mv *.mp3 ~/Music/

terminal again: chmod +x download.sh
to download simply do: sh download.sh link

ex: sh download.sh https://www.youtube.com/watch?v=trolololololol

as it's now executable, you can also do ./download.sh link, your choice ;)

Ps , i'm assuming the creation path as your home (~/download.sh), so when you open terminal, it's where you should be able to execute it ...
Cheers


text:
Q: I need to read a CSV file and split them into different arrays for each column I have a very large data file with around 60000 rows. I need to split the CSV file based on columns into different arrays for each column.
I have 5 columns; State, County, Zipcode, Latitude, Longitude.
How would I, when I read the file, split it and add them in order to each array?
I would have an array for State, County, Zipcode, Latitude, and Longitude.

A: Use a CSV parser - there are plenty for .NET, even a built in one in the VisualBasic namespace.
See TextFieldParser - though in the VisualBasic namespace, it is a regular .NET library that can be used by any .NET language.
There are many other options.

A: If you want to do it manually (i would also recommend to use TextFieldParser), you could use a StreamReader to loop all lines and use String.Split to split by your separator(assuming comma):
var stateList = new List<String>();
var countyList = new List<String>();
var zipCodeList = new List<String>();
var latitudeList = new List<String>();
var longitudeList = new List<String>();

using (var reader = new System.IO.StreamReader(@"C:\Temp\csv.txt"))
{
    string line;
    while ((line = r.ReadLine()) != null)
    {
        var fields = line.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        stateList.Add(fields[0]);
        if (fields.Length > 1)
            countyList.Add(fields[1]);
        if (fields.Length > 2)
            zipCodeList.Add(fields[2]);
        if (fields.Length > 3)
            latitudeList.Add(fields[3]);
        if (fields.Length > 4)
            longitudeList.Add(fields[4]);
    }
}

If you really need an Array instead of a List:
String[] states = stateList.ToArray();
String[] counties = countyList.ToArray();
String[] zipCodes = zipCodeList.ToArray();
String[] latitudes = latitudeList.ToArray();
String[] longitudes = longitudeList.ToArray();


text:
Q: What does Hadoop do with unreplicated data when client closes its connection? I am running a Hadoop 2.5.0-cdh5.3.2 cluster.  Flume is running elsewhere writing data to this cluster.  When the cluster is under heavy load, the flume-agent finishes writing and attempts to close the file before HDFS has finished replicating the data.  The close fails and is retried, but the flume-agent is configured with a timeout and when the close cannot complete in time, the flume-agent disconnects.
What does HDFS do with the file that has not finished replication?
I was under the impression a background thread would finish the replication, but I am seeing only partially written blocks in my cluster.  There is one good copy of the block and the replicas are only partially written, so HDFS considers the block corrupt.
I've read through the recovery process and did not think I'd be left with unwritten blocks.
I have the following client settings:
dfs.client.block.write.replace-datanode-on-failure.enable=true
dfs.client.block.write.replace-datanode-on-failure.policy=ALWAYS
dfs.client.block.write.replace-datanode-on-failure.best-effort=true

I set these because it seemed that the flume-agent was losing connections to datanodes and failing.  I wanted it to retry, but if a block was written, to call it good and move on.
Is best-effort preventing the remaining blocks from being written?  This seems pretty useless if it results in the final block being called corrupt.

A: I think flume agend is loosing hdfs connection before it can successfully close the file. DFS client caches some data locally. Before closing the file, it must flush this local cache. If the hdfs connection is lost, close will fail and the block will be marked corrupt. There is one scenario in which hdfs connection is unexpectedly closed. Hdfs Client registers shutdown hooks. The order in which shutdown hook are is invoked is not guaranteed. In your case if the flume agent is shutting down, hdfs client shutdown may get invoked and file close will fail. If you think this is possible, try disabling shutdown hooks.
fs.automatic.close = false


text:
Q: How can i remove rows from several tables with SQL? I have a 3 tables:
mainTable:
id | uniqField
--------------
1  | 1111
2  | 1111
3  | 2222
4  | 2222
5  | 3333
6  | 4444

table1:
id|name|deleted
----------
 1|Mike|0
 2|Mike|0
 5|John|0

table2:
id|name|deleted
----------
 3|Peke|0
 4|Peke|0
 6|Vels|0

That tables bind by id field.
Now i want to remove duplicates from this tables. For mainTable i can use:
DELETE mainTable
FROM mainTable
LEFT OUTER JOIN (
   SELECT MIN(id) as RowId, uniqField
   FROM mainTable
   GROUP BY uniqField
) as KeepRows ON
   mainTable.id= KeepRows.RowId
WHERE
   KeepRows.RowId IS NULL

But in tables1 and table2 i want to set deleted field to 0->1 to duplicates I mean:
1  | 1111
2  | 1111  -> duplicate->remove

 1|Mike|0
 2|Mike|0->duplicate-> 0->1

A: Try this one -
SET NOCOUNT ON;

DECLARE @mainTable TABLE
(
    id INT,
    uniqField INT
)

INSERT INTO @mainTable (id, uniqField)
VALUES (1, 1111), (2, 1111), (3, 2222), (4, 2222), (5, 3333), (6, 4444)

DECLARE @deleted TABLE (id INT)

;WITH cte AS
(
    SELECT *, RowNum = ROW_NUMBER() OVER (PARTITION BY uniqField ORDER BY 1/0)
    FROM @mainTable
)
DELETE FROM cte
OUTPUT DELETED.id INTO @deleted
WHERE RowNum > 1

DECLARE @table1 TABLE
(
    id INT,
    uniqField VARCHAR(10),
    deleted BIT
)

DECLARE @table2 TABLE
(
    id INT,
    uniqField VARCHAR(10),
    deleted BIT
)

INSERT INTO @table1 (id, uniqField, deleted)
VALUES (1, 'Mike', 0), (2, 'Mike', 0), (5, 'John', 0)

INSERT INTO @table2 (id, uniqField, deleted)
VALUES (3, 'Peke', 0), (4, 'Peke', 0), (6, 'Vels', 0)

UPDATE @table1
SET deleted = 1
FROM @deleted
WHERE [@deleted].id = [@table1].id

UPDATE @table2
SET deleted = 1
FROM @deleted
WHERE [@deleted].id = [@table2].id

SELECT * FROM @table1
SELECT * FROM @table2

Output -
id          uniqField  deleted
----------- ---------- -------
1           Mike       0
2           Mike       1
5           John       0

id          uniqField  deleted
----------- ---------- -------
3           Peke       0
4           Peke       1
6           Vels       0


text:
Q: Why do I get an access violation when I call Microsoft Communicator 2007's IMessengerContacts.Count method? I want to display the contacts from my list onto a TListBox.  I have Communicator installed and running on my Windows 7 PC, running Delphi XE.  I am using CommunicatorAPI_TLB and CommunicatorPrivate_TLB.
I click on the login and logout buttons, and the programs works as expected: my Communicator logs in and out.  Cool.
The problem is when I try to click on the list-users button.  The Contacts.Count method seems to throw me an access violation.  I tried it with groups, and the same results.  Can anyone spot what I am doing wrong?
  { This IMessenger3 Class Inherits from the IMessenger2 interface -> IMessenger... }
  Communicator : IMessenger3;
  Contacts     : IMessengerContacts;
  Contact      : IMessengerContact;
  Groups       : IMessengerGroups;
  Connected    : Boolean;

End;

Var
  frmMain: TfrmMain;

Implementation

{$R *.dfm}

{ ---------------------------------------------------------------------------- }

Procedure TfrmMain.FormCreate(Sender: TObject);
Begin
  Communicator := CoMessenger.Create;
End; { FormCreate Procedure }

Procedure TfrmMain.btnSignInClick(Sender: TObject);
Begin
  Communicator.AutoSignin;
  Connected := True;
End;  { btnSignInClick Procedure }

Procedure TfrmMain.btnSignOutClick(Sender: TObject);
Begin
  Communicator.Signout;
  Connected := False;
End;  { btnSignOutClick Procedure }

Procedure TfrmMain.btnLoadContactsClick(Sender: TObject);
Var
  ContactIndex : Integer;
Begin
  { Load my contacts into a listbox }
  Contacts := IMessengerContacts (Communicator.MyContacts);
  Groups   := IMessengerGroups (Communicator.MyGroups);

  If (Contacts <> Nil) Then Begin

    try
      showmessage (inttostr(Groups.Count));
      showmessage (inttostr(Contacts.count));
    except
    end;
  (*
    For ContactIndex := 0 To (Contacts.Count) Do Begin

     Contact := IMessengerContact (Contacts.Item (ContactIndex));

     { Add the contact to the list }
     lbxContacts.AddItem (Contact.FriendlyName, Nil);

    End; { For }
  *)
  End; { If <> Nil }

End;

A: Change the two typecasts to use as instead. If the problem is that the interface isn't available, you'll at least get an error message that's meaningful.
Change
Contacts := IMessengerContacts(Communicator.MyContacts);
Groups   := IMessengerGroups (Communicator.MyGroups);

to
Contacts := Communicator.MyContacts as ImessengerContacts;
Groups   := Communicator.MyGroups as IMessengerGroups;

You should probably do the same thing to other places you're typecasting to get interfaces. It's always better when possible to ask for them politely than to forcibly grab them. :)

A: It's been a loooooong time since i've written any Delphi (about 14 years) but i'm going to hazard a guess at this.
For security reasons some of the methods in the IMessenger interfaces are marked as NotScriptable. My guess is that your Delphi app is being treated by the interface as a scripting language, i.e. not native C++ code, and that's causing the Access Violation. You could prove this by looking at the reference to work out which are scriptable and which are not, and see which throw the Access Violation.
As for fixing it - as I said, i'm no Delphi expert, but is there another way you can instantiate the IMessenger objects? Or create a wrapper around the API in another language, to call from Delphi (there is an example of this here)


text:
Q: Opers and global differential operators This is a follow up question to a previous question of mine and my thought of answer to it.
Given a (compact) Riemann surface $\Sigma$, a $SL(n,\mathbb{C})$-oper is a rank $n$ holomorphic vector bundle $E\rightarrow \Sigma$, s.th. $\det(E)\cong \mathcal{O}$ is trivial, together with a holomorphic connection $\nabla:E\rightarrow E\otimes K_\Sigma$ ( $K_\Sigma$ being the canonical bundle of $\Sigma$) satisfying the following list of axioms:
1) There is a flitration by holomorphic subbundles $0=F^0\subset F^1\subset \cdots \subset F^n=E$.
2) The connection is Griffiths transverse: $\nabla(F^i)\subset F^{i+1}\otimes K_\Sigma$ .
3) The connection is non-degenerate in the following sense: The induced map $F^i/F^{i-1}\rightarrow F^{i+1}/F^i\otimes K_\Sigma$ is an isomorphism.
By non-degeneracy $E$ is in fact completely specified by $F^1$ and for $SL(n,\mathbb{C})$ it has to hold $F^1\cong K^{\frac{n-1}{2}}_\Sigma$. Having this, an $SL(n, \mathbb{C})$ is equivalent to an $n$-th order differential operator $P:\Omega^{\frac{-n+1}{2}}\rightarrow \Omega^{\frac{n-1}{2}}$, where $\Omega$ is the sheaf of holomorphic sections of $K_\Sigma$.
Q1 Is the converse true? I.e. given a holomorphic line bundle $L\rightarrow \Sigma$ with sheaf of holomorphic sections $\mathcal{L}$ and an n-th order holomorphic differential operator $P:\mathcal{L}\rightarrow \mathcal{L}$, can I construct from this an $SL(n,\mathbb{C})$ oper?
I think to answer to this is yes, but I cannot track a reference for this.
From the discussion I have in my previous question, it seems that to any rank $n$ vector bundle $H$ of degree zero with a holomorphic connection one gets at least locally a $n$-th order holomorphic differential operator defining its flat sections, due to the existence of a local cyclic section.
Q2 As I think the answer to the first question is yes, the local picture cannot glue in general I suppose. So the question is, do the local cyclic sections glue to a global cyclic section if and only if the bundle $H$ has an oper structure?


text:
Q: Exception when sending file through Stream I want to download a file directly from dropbox.I am able to retrieve the contents of a file which I want to download directly from dropbox.I am unable to send the file through stream to a browser.
Following exception:
An exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll but was not handled in user code
Additional information: Access to the path 'C:\Program Files (x86)\IIS Express\FirstLab_1.pdf' is denied.
at the line
using (FileStream fileStream = new FileStream(filename, FileMode.Create))
Following is my code:
public FileStreamResult Download(string bkpath)
{

    string bookname = bkpath;
    var accessToken = new OAuthToken("d2iwy26brzqhetr0", "xxxxxxxxxxxx");
    var api = new DropboxApi(ConsumerKey, ConsumerSecret, accessToken);
    var file = api.DownloadFile("dropbox", bookname);
    string path = file.Path;
    string filename = Path.GetFileName(path);
    // Create random data to write to the file.
    byte[] dataArray = new byte[file.Data.Length];
    new Random().NextBytes(dataArray);

    using (FileStream fileStream = new FileStream(filename, FileMode.Create))
    {
        // Write the data to the file, byte by byte.
        for (int i = 0; i < dataArray.Length; i++)
        {
            fileStream.WriteByte(dataArray[i]);
        }

        // Set the stream position to the beginning of the file.
        fileStream.Seek(0, SeekOrigin.Begin);

        // Read and verify the data.
        for (int i = 0; i < fileStream.Length; i++)
        {
            if (dataArray[i] != fileStream.ReadByte())
            {
                Response.Write("Error writing data.");
            }
        }
        return new FileStreamResult(fileStream, "application/pdf");
    }
}

Please help me out to get the file download direcly from dropbox as I am resolving this exception for a about long time and couldn't get the solution.

A: The exception message describes the problem pretty well. Simply either
a) Right click on 'C:\Program Files (x86)\IIS Express\' folder -> Properties -> Security and give the write permission to everyone.
or much better
b) write the file into the temp directory.
string filename = Path.Combine(Path.GetTempPath(), Path.GetFileName(path));


text:
Q: C - dynamic allocation of 2D game board of unknown dimensions I want to code a board-based game and want to represent the board as a 2D char-array.
In particular, the board consists of 4 different types of characters/cells:

*

*The player (S)

*The goal cell (A)

*Walls (#)

*Monsters (^, v, <, >)

Monsters look in a certain direction which is denoted by the arrow-like characters above.
I want to be able to load a Level from a text file where the following is unknown:

*

*the number of lines in the file (rows in a 2D-array)

*the number of chars in each line

An example Level text file:
    ######                                 ##########
    #  < #                                 #        #
    #    #########                         #       ##
    #    #       #                         #^      #
    #    #       #                        ##       #
  ###            #      ########        ###        #
  #     #   ######      #      ##########   #     ##
  #     #^  #           #                 #########

As you can see the first 3 lines have 49 chars, but the other ones contain 48/47 chars.
The difference might be much higher, so that I need to use dynamic allocation for both dimensions.
Should I read the file character-by-character or line-by-line using a fixed size buffer, extending it when necessary?
This is what I tried:
int needed_num_rows = 1;
int needed_bytes_col = 16;

char **board = calloc(needed_num_rows, sizeof(char*));
char *buf = calloc(needed_bytes_col, sizeof(char));

int idx = 0;
while (fgets(buf, needed_bytes_col, level_file) != NULL) {
    if (buf[needed_bytes_col - 1] != '\n' && buf[needed_bytes_col - 1] != '\0') { // not read to the end yet
        needed_bytes_col = needed_bytes_col * 2 + 1;
        buf = realloc(buf, needed_bytes_col);
        buf += needed_bytes_col;
    } else { // whole line has been read
        if (idx + 1 > needed_num_rows) {
            needed_num_rows = needed_num_rows * 2 + 1;
            board = realloc(board, needed_num_rows);
        }

        board[idx++] = buf;
        needed_bytes_col = 16;
        buf = calloc(needed_bytes_col, sizeof(char));
    }
}

A: Your code is a bit [too] complex with too many special cases.
It can be refactored/simplified. Easier to read the line into a fixed [maximum] size buffer and then use strdup
char **board = NULL;
size_t board_count = 0;
size_t board_max = 0;

char buf[1000];

while (fgets(buf,sizeof(buf),level_file) != NULL) {
    // strip newline
    buf[strcspn(buf,"\n")] = 0;

    // allocate more rows
    // the increment here is arbitrary -- adjust to suit
    if (board_count >= board_max) {
        board_max += 10;
        board = realloc(board,sizeof(*board) * board_max);
    }

    // store the new row
    board[board_count++] = strdup(buf);
}

// trim array to exact amount used
board = realloc(board,sizeof(*board) * board_count);

UPDATE:

what if line is 4000 chars long? –
0___________

The TL;DR is char buf[1000000]; Of course, we can make buf a char * and do a realloc on it [independent of realloc for board], and reloop, but I think that's overkill in this circumstance.
However ...
If the board is going to be arbitrarily large (e.g millions of rows and rows that can have a million chars [or ten]), then we could dynamically allocate everything in place:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char **board = NULL;
size_t board_count = 0;
size_t board_max = 0;

int
lineget(char **bufp,FILE *level_file)
{
    char *buf;
    size_t bufmax = 0;
    size_t buflen = 0;
    char *cp;
    size_t off = 0;
    size_t remlen;
    size_t addlen;
    int valid = 0;

    buf = *bufp;

    while (1) {
        // get amount of free space remaining in buffer
        remlen = bufmax - off;

        // increase buffer length if necessary (ensure we have enough space
        // to make forward progress) -- this "lookahead" limit is arbitrary
        // as is the increment
        if (remlen < 2) {
            bufmax += 1000;
            buf = realloc(buf,bufmax);

            if (buf == NULL) {
                perror("realloc");
                exit(1);
            }

            remlen = bufmax - off;
        }

        // append to the buffer
        cp = fgets(&buf[off],remlen,level_file);
        if (cp == NULL)
            break;

        valid = 1;

        // get length of newly added chars
        addlen = strlen(&buf[off]);

        // get total length of filled area
        buflen = off + addlen;

        // check for newline and strip it and stop if we get one
        if (addlen > 0) {
            if (buf[buflen - 1] == '\n') {
                buf[--buflen] = 0;
                break;
            }
        }

        // increase the offset into the buffer
        off += addlen;
    }

    // trim buffer to length
    buf = realloc(buf,buflen);

    *bufp = buf;

    return valid;
}

void
readfile(void)
{

    while (1) {
        // allocate more rows
        // the increment here is arbitrary -- adjust to suit
        if (board_count >= board_max) {
            board_max += 10;
            board = realloc(board,sizeof(*board) * board_max);

            // set null pointers on unfilled rows
            for (size_t idx = board_count;  idx < board_max;  ++idx)
                board[idx] = NULL;
        }

        // fill the current row
        if (! lineget(&board[board_count],stdin))
            break;

        // advance row count
        ++board_count;
    }

    // trim array to exact amount used
    board = realloc(board,sizeof(*board) * board_count);
}

A: Here you have the function which reads the line of unknown size dynamically allocating buffer for it.
#define LINEDELTA 256

char *readline(FILE *fi)
{
    char *result = NULL;
    size_t currentSize = 0;
    if(fi)
    {
        do
        {
            char *tmp;
            tmp = realloc(result, currentSize + LINEDELTA);
            if(tmp) result = tmp;
            else { /* add error handling*/ }
            if(fgets(result + currentSize - !!currentSize, LINEDELTA + !!currentSize, fi) == (result + currentSize))
            {

            }
            else { /* add error handling*/ }
            currentSize += LINEDELTA;
        }while(strchr(result, '\n'));
    }
    return result;
}

A: Instead of using dynamic memory allocation for every single line, I would recommend reading the file in two passes: Once for determining the maximum size of both dimensions, and once to actually read the data.
That way, you will know the exact memory requirements after the first pass, and can allocate a memory buffer of an appropriate size before the second pass.
One advantage of this solution is that having a fixed length in both dimensions is probably the memory representation that you will want to have after loading the game.
Therefore, I would recommend the following code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main( void )
{
    FILE *level_file;
    char *board;
    char buffer[1024];
    size_t rows = 0;
    size_t cols = 0;
    size_t current_line;

    level_file = fopen( "level.txt", "rt" );
    if ( level_file == NULL )
    {
        fprintf( stderr, "error opening file!\n" );
        exit( EXIT_FAILURE );
    }

    //first pass of file to determine size of both dimensions
    while ( fgets( buffer, sizeof buffer, level_file ) != NULL )
    {
        char *p;
        size_t length;

        //verify that line was not too long
        p = strchr( buffer, '\n' );
        if ( p == NULL )
        {
            //there are 3 explanations for not finding the newline character:
            //1. end-of-file was encountered
            //2. I/O error occurred
            //3. line was too long to fit in buffer

            if ( feof( level_file ) )
            {
                //make p point to terminating null character
                p = buffer + strlen( buffer );
            }
            else if ( ferror( level_file ) )
            {
                fprintf( stderr, "I/O error occurred\n" );
                exit( EXIT_FAILURE );
            }
            else
            {
                fprintf( stderr, "line was too long to fit in buffer\n" );
                exit( EXIT_FAILURE );
            }
        }

        //calculate number of columns in line
        length = p - buffer;

        //update cols to higher value, if appropriate
        if ( length > cols )
            cols = length;

        rows++;
    }

    //verify that loop terminated due to end-of-file
    if ( !feof( level_file ) )
    {
        fprintf( stderr, "error reading with fgets!\n" );
        exit( EXIT_FAILURE );
    }

    //rewind file back to start
    rewind( level_file );

    //allocate memory for board
    board = malloc( rows * cols );
    if ( board == NULL )
    {
        fprintf( stderr, "error allocating memory for board!\n" );
        exit( EXIT_FAILURE );
    }

    //second pass of file to actually read the data
    current_line = 0;
    while ( fgets( buffer, sizeof buffer, level_file ) != NULL )
    {
        char *p;
        size_t length;

        //verify that line was not too long
        //note that it is possible that file was changed since the
        //first pass, so it is not wrong to check again (but maybe
        //not necessary)
        p = strchr( buffer, '\n' );
        if ( p == NULL )
        {
            //this is identical to first pass

            if ( feof( level_file ) )
            {
                //make p point to terminating null character
                p = buffer + strlen( buffer );
            }
            else if ( ferror( level_file ) )
            {
                fprintf( stderr, "I/O error occurred\n" );
                exit( EXIT_FAILURE );
            }
            else
            {
                fprintf( stderr, "line was too long to fit in buffer\n" );
                exit( EXIT_FAILURE );
            }
        }

        //calculate number of columns in line
        length = p - buffer;

        //verify that line consists only of valid characters
        if ( strspn(buffer," SA#^v<>") != length )
        {
            fprintf( stderr, "invalid characters found in file!\n" );
            exit( EXIT_FAILURE );
        }

        //make sure that line length has not increased since first pass
        if ( length > cols )
        {
            fprintf( stderr, "detected that file has changed since first pass!\n" );
            exit( EXIT_FAILURE );
        }

        //calculate start of row in board
        p = board + current_line * cols;

        //copy line contents into board
        memcpy( p, buffer, length );

        //fill rest of line with space characters
        for ( size_t i = length; i < cols; i++ )
            p[i] = ' ';

        //increment loop counter
        current_line++;
    }

    //verify that loop terminated due to end-of-file
    if ( !feof( level_file ) )
    {
        fprintf( stderr, "error reading with fgets!\n" );
        exit( EXIT_FAILURE );
    }

    fclose( level_file );

    printf( "rows: %d, cols: %d\n\n", rows, cols );

    //print board contents
    for ( size_t i = 0; i < rows; i++ )
    {
        for ( size_t j = 0; j < cols; j++ )
        {
            putchar( board[i*cols+j] );
        }

        putchar( '\n' );
    }

    free( board );
}

I have tested this program successfully with the following input file:
   # S A v <
   #### ## A
AAA ###

Note, however, that this program only supports lines up to 1022 characters (1024 including the newline and terminating null character), due to the following declaration:
char buffer[1024];
Although it is possible to increase this size, it is generally a bad idea to allocate more than a few kilobytes on the stack, as this could cause a stack overflow. Therefore, if it is possible for a single line to be larger than a few kilobytes, then it would be appropriate to allocate buffer somewhere else than the stack, for example by using dynamic memory allocation instead.

A: This seems a bit complicated however you look at it. I used mmap() and a line parsing function. This function does only the newline finding, plus skip repeated ones and check the length. The idea was to have three returns: -1 = finished, -2 = skip this line, positive = use this line (or use the second parameter e.g. a struct).
So even if one parses only the lines' existence and length, it still is some kind of parsing. The main part is:
plret = parse_lines(&pmap)

pmap is the moving copy of the mmap() mapping. parse_lines() advances it. plret tells you whether to 1) stop 2) continue or 3) act and continue.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/mman.h>

/* file must have NL at end, and memory a \0 */
int parse_lines(char **pmap) {

    int const maxline = 60;
    char *map = *pmap;
    while(*map == '\n')            //skip empty lines???
        map++;

    if (! *map)
        return -1;                 // means EOF

    char *nnl = strchr(map, '\n');
    *pmap = nnl + 1;               // new position for caller: start of next line

    if (nnl - map < maxline)
        return nnl - map;          // return length of line
    else
        return -2;                 // too long
}
void parse_file() {
    char const *f = "test";
    size_t const mmlen = 256*256;                     // or fstat()

    int fd = open(f, O_RDONLY);
    char *mapping = mmap(0, mmlen, PROT_READ, MAP_PRIVATE, fd, 0),
         *pmap = mapping;

    int plret;
    while ((plret = parse_lines(&pmap)) != -1)

        if (plret > 0) {

            char *s = calloc(plret+1, 1);
            memcpy(s, pmap-plret-1, plret);           // NL (+1) or not?

            printf("%d at %p now %p:\t\"%s\"\n", plret, pmap, s, s);
            free(s);                                  // rather store it in an array
        }
        else
            printf("line too long - skip or truncate or abort\n");

    /* End of File */
    munmap(mapping, mmlen);
    // + realloc array for @s-pointers, if it was allocated "big enough"
}
int main(void) {
    parse_file();
}

I left out the array arr[idx++] = s (without the checking/realloc). But the output illustrates nicely what is going on (the third to last line is extra long):
53 at 0x7fdc29283036 now 0x5557230822a0:        "    ######                                 ##########"
53 at 0x7fdc2928306c now 0x5557230826f0:        "    #  < #                                 #        #"
53 at 0x7fdc292830a2 now 0x555723082730:        "    #    #########                         #       ##"
52 at 0x7fdc292830d7 now 0x555723082770:        "    #    #       #                         #^      #"
52 at 0x7fdc2928310c now 0x5557230827b0:        "    #    #       #                        ##       #"
52 at 0x7fdc29283141 now 0x5557230827f0:        "  ###            #      ########        ###        #"
52 at 0x7fdc29283176 now 0x555723082830:        "  #     #   ######      #      ##########   #     ##"
51 at 0x7fdc292831aa now 0x555723082870:        "  #     #^  #           #                 #########"
line too long - skip or truncate or abort
2 at 0x7fdc292831fd now 0x5557230828b0: "##"
1 at 0x7fdc292831ff now 0x5557230828d0: "#"

The bytes at 0x7fd... found a new home as strings at 0x555...
They lost the newline but now have a null terminator.


text:
Q: Disable some checkboxes in form I was wondering if there is an easy way of how to disable one checkbox from modifying it by user (Symfony 2.1). I was trying something like this:
     $builder->add('adminRoles', 'entity',  array(
            'property' => 'roleName',
            'class' => 'MyBundle:Role',
            'query_builder' => function(EntityRepository $er) {
                return $er->createQueryBuilder('r')
                    ->orderBy('r.roleName', 'ASC');
            },
            'disabled' => $this->disabledRoles,
            'expanded' => true,
            'multiple'  => true
     ));

By $this->disabledRoles I meant an array of IDs of Role entities or entities themselves, but it seems that it just accepts boolean value which is applied for all entities (checkboxes). Thanks for your advice :-)

A: You will need to add a form listener in order to customize individual elements.
http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html
It might seem like a lot of work but it's easy enough once you work through the examples.  You will end up passing disabledRoles to the listener and then setting the disabled flag accordingly.


text:
Q: COALESCE to get NULL as well as NOT NULL values in SQL Server 2008 I have a query written in MySQL as :
select RecordID, AppInstanceID, ID
 where RecordID like ?
 and((isNull(AppInstanceID) OR AppInstanceID=  CASE  WHEN COALESCE(?,'') = ''  THEN AppInstanceID  ELSE ?  END)
 and(isNull(ID) OR ID=  CASE  WHEN COALESCE(?,'') = ''  THEN    ID  ELSE ?  END)

This gives me Null as well as Not Null Values.
Now, I m shifting to SQL Server 2008.
How can I achieve this coalesce functionality in SQL Server 2008.
User can pass % in recordId field and he should get all data, either null as well as not null.

A: I'm not entirely sure what your question is, so this may be an answer, but it is certainly advice. You can rewrite your where clause as follows:
SELECT RecordID, AppInstanceID, ID
WHERE RecordID LIKE ?
AND (AppInstanceID IS NULL OR AppInstanceID = ISNULL(?, AppInstanceID))
AND (ID IS NULL OR ID = ISNULL(?, ID)

CASE WHEN COALESCE(?,'') = '' THEN ID ELSE ? END

Is exactly the same as writing
COALESCE(?, ID)

The CASE statement is completely unnecessary. (And COALESCE can be swapped for ISNULL as in my code above)

A: If you want all the NULL and NOT NULL values you dont have to put anything in your where Clause, just SELECT the columns you want and it will return all the values regardless of if thery are NULL or NOT NULL.
But if your using Like operator to filter out some results and then you also want all the NULL values you could do something like this.
select RecordID, AppInstanceID, ID
WHERE RecordID like '%'
OR RecordID IS NULL

It will return all the rows where RecordID has some value Like defined by you or NULL values.

A: I have found the solution. Here's how it works.
select RecordID, AppInstanceID, ID
 where RecordID like ?
 and(AppInstanceID=  CASE  WHEN COALESCE(?,'') = ''  THEN AppInstanceID  ELSE ?  END)
 and(ID=  CASE  WHEN COALESCE(?,'') = ''  THEN    ID  ELSE ?  END)

Thanks


text:
Q: recommened xml, xpath tools for J2ME We are start working with J2ME application where we need the XML parsers based SAX, DOM and Xpath navigation support.
I found kXML recommended by many developers. What are other free/open source libraries available you found useful and using in your application?

A: I used minixpath once. Does simple things and is lightweight. It uses kxml internally.


text:
Q: Removing from ArrayList Not Working The following portion of code is supposed to loop over one array "idleusers," removing these users from an arraylist "finalusers" if they also have a certain application running.
$apps = get-process -IncludeUserName |  Sort-Object -Property ID -Unique

foreach ($app in $apps){
    if ($idleusers -contains $app.username) {
        if ($app.path -like 'C:\Program Files (x86)\DirectoryOfTheApplication\*') {
            #if ($app.username -eq 'Domain\UsernameThatDoesNotRemove') {
            #    $finalusers.remove('Domain\UsernameThatDoesNotRemove')
            #}
            $finalusers.remove($app.username)
        }
    }
}

$finalusers

This works, and removes most of the desired users, but there are 2 or 3 users left over that did not get removed. The commented-out if loop is one that I used to try and debug. When you un-comment those lines and run the code, it does remove the user. This means that the if statements should be working properly, and the problem is most likely with the remove statement.
Edit 2:
Sorry for the poor question, I've been a lurker here for a long time but this is my first shot at participating. I read the help article and tried to narrow down the code. Here it is, the full script, without the functions and without anything that didn't pertain to this error:
$quserresult = invoke-expression -Command "quser /SERVER:$serverName" | select -Skip 1

$users = @()

foreach($row in $quserresult)
{
    $person = new-object Object
    $columns = $row.Replace("  ", " ").Split(" ") | ? {$_ -ne ""}

    $person | add-member -membertype noteproperty -name UserName -value $columns[0]

    $users += $person
}

$idleusers = @()
foreach($usrn in $users){
    $nme = $usrn.UserName
    $idleusers += "Domain\$nme"
}

[System.Collections.ArrayList]$finalusers = $idleusers

$apps = get-process -IncludeUserName |  Sort-Object -Property ID -Unique

foreach ($app in $apps){
    if ($idleusers -contains $app.username) {
        if ($app.path -like 'C:\Program Files (x86)\DirectoryOfTheApplication\*') {
            #if ($app.username -eq 'Domain\UsernameThatDoesNotRemove') {
            #    $finalusers.remove('Domain\UsernameThatDoesNotRemove')
            #}
            $finalusers.remove($app.username)
        }
    }
}

$finalusers

Final Edit: Thanks, it was because -contains is not case sensitive. I made sure to format it all in lowercase and now it works.
The final code:
$quserresult = invoke-expression -Command "quser /SERVER:$serverName" | select -Skip 1

$users = @()

foreach($row in $quserresult)
{
    $person = new-object Object
    $columns = $row.Replace("  ", " ").Split(" ") | ? {$_ -ne ""}

    $person | add-member -membertype noteproperty -name UserName -value $columns[0]

    $users += $person
}

$idleusers = @()
foreach($usrn in $users){
    $nme = $usrn.UserName.ToLower()
    $idleusers += "staley\$nme"
}

[System.Collections.ArrayList]$finalusers = $idleusers

$apps = get-process -IncludeUserName |  Sort-Object -Property ID -Unique

foreach ($app in $apps){
    $appuser = $null
    $appuser = $app.username
    if ($appuser) {
        if ($idleusers -contains $appuser.ToLower()) {
            if ($app.path -like 'C:\Program Files (x86)\DirectoryOfTheApplication\*') {
                $finalusers.remove($appuser.ToLower())
            }
        }
    }
}

$finalusers

A: Jonathan Muller's comment almost certainly points at your problem.
The comparison $idleusers -contains $app.username is not as strict as the comparison used by ArrayList when it tries to remove the $app.username element. The former comparison will match "Domain\UserName" with "domain\username", but the latter will not. If you use -ccontains instead of -contains, that would be case sensitive, but I don't think that will solve your problem, it would only make the comparisons more consistent - it's likely that modifying code in get-terminal-users is the correct solution.
However, I'm not able to reproduce the problem because you haven't posted the code for get-terminal-users.


text:
Q: How do I use APIs with access tokens in apps created with create-react-app How do I hide an API's secret access tokens in a production build of an app created with create-react-app?
I've visited this question but it does not have an acceptable answer to my question. I do not want to use process.env.REACT_APP_SECRET_VALUE in my app as this variable would be exposed in the client-side javascript.
Given that the production build of a create-react-app app is composed of static files only, the only solution I can think of involves only using APIs that use a combination of public client IDs and some form of backend client whitelisting, IP or otherwise.
Am I missing something here?

A: Like you already mentioned, you can request an api backend that only returns your secret if it's whitelisted IP.
But still can you be a litle more specific what are you trying to achieve, just guessing but maybe you need to look at direction of some authentication first so after that the user on the client side would be able to do something (see secret).

A: You're on the right track. If you're unwilling/unable to expose keys for services you're  using, you may need to create an endpoint on a server somewhere that you call and have that endpoint proxy the relevant API request. Amazon's API gateway could probably handle this for you.
https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-usage-plans.html


text:
Q: How can I use the TaggedDocument function (Gensim \ Doc2Vec) via Reticulate in R? I am trying to run Python's gensim package in R environment via reticulate. More specifically, I am trying to build a doc2vec model, for which a corpus of tokens and tags needs to be prepared.
The TaggedDocument function is where I am having problems. Here's an example in python of what I am trying to reproduce in R:
import pandas as pd
import numpy as np
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from nltk.tokenize import word_tokenize

data = ["this is the first sentence",
        "running doc2vec via reticulate",
        "r and python bff forever",
        "this aint working"]

tags = ["a","b","a","c"]

corpus = pd.DataFrame({"sentences": data, "labels": tags})

tagged_data = corpus.apply(
    lambda r: TaggedDocument(words=word_tokenize(r['sentences']), tags=[r.labels]), axis=1)

This results in an output of this kind:
0       ([this, is, the, first, sentence], [a])
1    ([running, doc2vec, via, reticulate], [b])
2         ([r, and, python, bff, forever], [a])
3                  ([this, aint, working], [c])
dtype: object

which can be used to build a vocabulary and train a doc2vec model.
How can I get to the same result in R (possibly without loops)?
library(reticulate)

gensim <- import("gensim")
Doc2Vec <- gensim$models$Doc2Vec
TaggedDocument <- gensim$models$doc2vec$TaggedDocument

sentences <- c("this is the first sentence",
        "running doc2vec via reticulate",
        "r and python bff forever",
        "this aint working")

labels <- c("a","b","c","a")

Thanks in advance!
* EDIT *
I have been trying an even simpler setting:
library(reticulate)

gensim <- import("gensim")
Doc2Vec <- gensim$models$Doc2Vec
TaggedDocument <- gensim$models$doc2vec$TaggedDocument

sentences <- c("this is the first sentence")
tags <- c("a")

df <- data.frame (tokens= sentences, labels = tags)

tagged_docs <- TaggedDocument(words = df$tokens, tags = df$labels)

but I keep receiving the same error message:

Blockquote
  Error in py_call_impl(callable, dots$args, dots$keywords) :
    AttributeError: 'str' object has no attribute 'words' - Detailed traceback:
    File "C:\Anaconda\lib\site-packages\gensim\models\doc2vec.py", line 1184, in build_vocab
      progress_per=progress_per, trim_rule=trim_rule
    File "C:\Anaconda\lib\site-packages\gensim\models\doc2vec.py", line 1381, in scan_vocab
      total_words, corpus_count = self._scan_vocab(documents, docvecs, progress_per, trim_rule)
    File "C:\Anaconda\lib\site-packages\gensim\models\doc2vec.py", line 1310, in _scan_vocab
      if isinstance(document.words, string_types):

---
What am I doing wrong?

A: I did not get your error, I am on reticulate_1.16 and gensim 3.8.3, ntlk 3.4.4. Might be easier if you call a python script and pass it back to R.
This would be your python script:
py_script = c("", "import pandas as pd", "import numpy as np", "from gensim.models.doc2vec import Doc2Vec, TaggedDocument",
"from nltk.tokenize import word_tokenize", "", "tagged_data = r.df_py.apply(",
"    lambda r: TaggedDocument(words=word_tokenize(r['sentences']), tags=[r.labels]), axis=1)",
"")

cat(py_script,sep="\n")

import pandas as pd
import numpy as np
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from nltk.tokenize import word_tokenize

tagged_data = r.df_py.apply(
    lambda r: TaggedDocument(words=word_tokenize(r['sentences']), tags=[r.labels]), axis=1)

writeLines(py_script,"run.py")

Then in R:
library(reticulate)

sentences <- c("this is the first sentence",
        "running doc2vec via reticulate",
        "r and python bff forever",
        "this aint working")

labels <- c("a","b","c","a")
df = data.frame(sentences,labels)

df_py <- r_to_py(df)
py_run_file("run.py")
py$tagged_data
$`0`
TaggedDocument(['this', 'is', 'the', 'first', 'sentence'], ['a'])

$`1`
TaggedDocument(['running', 'doc2vec', 'via', 'reticulate'], ['b'])

$`2`
TaggedDocument(['r', 'and', 'python', 'bff', 'forever'], ['c'])

$`3`
TaggedDocument(['this', 'aint', 'working'], ['a'])


text:
Q: How to make a state name dynamic? I am using this.state.stateName which state name is defined at getInitialState function at the beginning. If I want the stateName to be dynamic, how can do it?
I tried this but it did not work.

roductButtonClicked:function(obj){
  if( this.state.obj.objectID  == "")
    alert("null")
 }


text:
Q: Revit Python Shell - Iterate over each Element, find View Name and group by Sheet Number I want to create a list of all Viewports by associated sheet number, View Name and Location Center. Like so:
vPorts = [('A0.01, View Name 01',[Center of ViewPort location]),('A0.02, View Name 01',[Centre of ViewPort location]),('A0.02, View Name 02',[Center of ViewPort location]),('A0.04, View Name 01',[Centre of ViewPort location]), etc.]

This so a user can align Multiple Viewports to each other in a listbox (not shown here) in WPF. I have the below:
import clr
clr.AddReferenceByPartialName('PresentationCore')
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName('System')
clr.AddReferenceByPartialName('System.Windows.Forms')

from Autodesk.Revit.DB import *
from Autodesk.Revit.DB.Architecture import *
from Autodesk.Revit.DB.Analysis import *
from Autodesk.Revit.UI import *

doc = __revit__.ActiveUIDocument.Document

#List of ViewPort Elements
vPorts = []

#List for ViewPorts by sheet number, view name and location
vPortsloc = []

col_sheets = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets).WhereElementIsNotElementType().ToElements()
for sheet in col_sheets:

    vPorts.append(sheet.GetAllViewports())

for vp in vPorts:
    print(vp)

Which gets me all the Viewports on all Sheets as List objects.
But I now want to format this list as stated above. I tried the following:
for vp in vPorts:
    v = doc.GetElement(vp.ViewId)
    vPortsloc.append(v.SheetNumber + v.Name + (v.GetBoxCenter().ToPoint()))

I believe I am not iterating over the whole List of lists. Not to mention I am new to python.. Any help would be really appreciated. Thanks!

A: Thanks Callum that helped alot! I just had to fix one or two typos, use append () instead of add, and get the View Name as well instead of the Sheet Name. As below
viewPorts = list(FilteredElementCollector(doc).OfClass(Viewport))
viewPortTriples = []

for vp in viewPorts:
    sheet = doc.GetElement(vp.SheetId)
    view = doc.GetElement(vp.ViewId)
    viewPortTriples.append([sheet.SheetNumber, view.ViewName, vp.GetBoxCenter()])

print(viewPortTriples)

A: It could help to visualise multiple-dimensioned Lists like this:
vPortTriples  = [
    [Sheet Number, Sheet Name, ViewPort Center],
    [Sheet Number, Sheet Name, ViewPort Center],
    [Sheet Number, Sheet Name, ViewPort Center]
]

It looks like youre appending three separate items to a List. Should they be added as a new List, like this?
vPortTriples.append([v.SheetNumber, v.Name, v.GetBoxCenter().ToPoint()])

If you really are looking to catch every Viewport in a project, you can fetch all the ViewPorts by Class, so in your code it would look like:
# I find it easiest to convert FilteredElementCollector to a list
viewPorts = list(FilteredElementCollector(doc).OfClass(Viewport))
viewPortTriples = []

for vp in viewPorts:

    # need to fetch the ViewPorts Sheet
    sheet = doc.GetElement(vp.SheetId)

    # add a new List to the 'viewPortTriples' List
    viewPorts.Add([sheet.SheetNumber, sheet.Name, vp.GetBoxCenter()]

This is a pretty expensive way to do it though, better to fetch them only for the relevant sheet - say, by a specific Sheet Number (which may have been what you were trying to do in your example anyway!):
def getViewPorts (document, sheetNumber): # returns [[viewPort, bboxCenter], ... ]

    sheets = list(FilteredElementCollector(document).OfClass(ViewSheet))
    try:
        targetSheet = [i for i in sheets if i.Sheetnumber == sheetNumber][0]
    except:
        print 'failed to find sheet',sheetNumber
        return []

    viewPortLocations = [] # a list of [[viewPort, bboxCenter], ... ]
    for vpId in targetSheet.GetAllViewports():
        vp = document.GetElement(vpId)
        viewPortLocations.Add([vp, vp.GetBoxCenter()])

    return viewPortLocations


text:
Q: How to use Android RXJava to chain linked Retrofit calls and return new Object model So the scenario is one where we need to make 2 retrofit calls,
 @GET("/")
Observable<Search> searchMovies(@Query("apikey") String apiKey, @Query("s") String searchKey);

@GET("/")
Observable<Details> getMovie(@Query("apikey") String apiKey, @Query("t") String searchKey);

the first one is to get a list and then for each item in that list we will make a new call in order to get further information about that movie.
So the first question I have is how can I chain these 2 calls together inside ond rxjava method ?
The second question that i have follows up from this one in that I want to chain these 2 calls together inside and Rxjava method but then return a new observable pojo object based upon a few fields from each of the response. So for example say that request 1 contains "Name" and then request 2 contains "plot". I want to compose what would be a list of MovieInformation pojo objects based on these 2 fields and wrap that into an observable.

A: You should use flatMap operator to chain these two calls.
Normally getMovie() should take in parameteres the result of searchMovies(). I suppose that apiKey,searchKey are the result of getMovies(apikey,searchKey) :
yourretrofitservice.searchMovies(apikey,searchKey)

                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())

                //waiting for response of yourretrofitservice.searchMovies()

                .flatMap(new Func1<Search, Observable<Details>>() {

                    @Override
                    public Observable<Details> call(Search search_result) {

                        return yourretrofitservice.searchMovies(apiKey, searchKey); //maybe searchKey = search_result (you should define how to set the result of the First Retrofit call in the second call

                    }

                })

                //waiting for the response  of yourretrofitservice.getMovie()

                .flatMap(new Func1<Search, Observable<YourPojoClass>>() {

                    @Override
                    public Observable<YourPojoClass> call(Search search_result) {
                        //do something with pojo_object
                        return pojo_object; second call

                    }

                })

                .subscribe(new Action1<YourPojoClass>() {

                    @Override
                    public void call(YourPojoClass  pojo_object) {
                        //Your final action
                    }

                });

FlatMap operator : http://reactivex.io/documentation/operators/flatmap.html


text:
Q: Devise - LogIn parameters invalid email and password I am new to RoR and I used devise gem for authentication.
I have a login form which is created by command "rails g devise:views"
If I change the form_for(:session,.......) it shows invalid email and password and if I change to form_for(:user,......) it is working.
Questions:
1)Why only user resource not any other resource or controller because the first parameter is for only use for params i.e, params[:session][email].
2)Where is it documented in Devise gem docs?
Can anyone please help me with this issue ?
Thanks in advance !!!!Sorry for silly doubt!


text:
Q: What is an electric quadrupole and how to find its net electric field on a point which is on the dipole axis? In a question of my book it says that an electric quadrupole is a system of two dipoles of equal magnitude but opposite in sign. If that's the case and since they are vectors, won't they cancel out and cause the net dipole to be zero?  Apart from this can someone tell me how to find out the net electric field on a point on the dipole axis of an electric quadrupole?

A: Quadrupoles arise from dipoles in the same way that dipoles arise from point charges: you take two opposing ones at a finite separation $\mathbf s$, and then you take the limit of $s\to0$ while the dipoles' moments $p$ grow to infinity in such a way as to keep $ps$ constant. And, in the same way that the point charges' fields do not fully cancel out (giving us dipolar fields that decay as $1/r^3$ instead of $1/r^2$), the dipoles' fields don't fully cancel out either, yielding a zero total dipole but producing a quadrupolar field that decays as $1/r^4$. It's all exactly analogous to the monopole-to-dipole limit.


text:
Q: Kotlin Gradle driver dependency not found I've been trying to write a gradle task which will execute some SQL.
When executing the task it fails with:
* What went wrong:
A problem occurred configuring root project 'xyz'.
> Could not create task ':resetDatabase'.
   > com.microsoft.sqlserver.jdbc.SQLServerDriver

with stacktrace enabled I can see:
Caused by: java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver

The relevant bits of my build.gradle.kts look like:
import java.util.*
import java.io.FileInputStream
import groovy.sql.Sql

repositories {
    mavenLocal()
    jcenter()
}

dependencies {
    implementation("com.microsoft.sqlserver:mssql-jdbc:8.2.0.jre8")
}

val resetDatabase = tasks.register("resetDatabase") {
    val properties = Properties()
    properties.load(FileInputStream(file("./webBasedPortal.properties")))

    val sqlToExecute = File("./clearDatabase.sql").readText()

    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver")

    val sql = Sql.newInstance(
        properties.getProperty("db.url"),
        properties.getProperty("db.user"),
        properties.getProperty("db.password")
    )
    sql.execute(sqlToExecute)
}