text:
Q: Clear last rows while statement is true How can I loop a function to clear the last row if a statement is true?
Example:
In the first column I have dates or the string 'BugFix' each in a different  row. I need to clear every 'BugFix' if it is in the last row.
Column A
  ------
1  BugFix
2  some Date
3  BugFix
4  some Date
5  BugFix
6  BugFix

In this example I would need to clear two rows:  5 and 6

*

*Clear last row (row 6) because the value is BugFix.

*Check if in new last row (row 5) is BugFix

*It is, so clear that row, check again, but do nothing because in new last row (4) is some Date.

My code only clears row 6. Please help.
function clearLogs(){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('logs');
  var range = sheet.getRange(2, 1, sheet.getLastRow(), sheet.getLastColumn())
  var data = range.getValues();
  var lastRow = sheet.getRange(sheet.getLastRow(), 1).getValue();

  if (lastRow == 'BugFix') {
    sheet.getRange(sheet.getLastRow(),1).clear();
  }
}

A: The first one is just like your example it just clears the last row
function clearLogs(){
  var sheet = SpreadsheetApp.getActive().getSheetByName('logs');
  var range = sheet.getRange(2, 1, sheet.getLastRow()-1, sheet.getLastColumn());//Third parameter is the number of rows not the last row
  var data = range.getValues();
  var lastRow = sheet.getRange(sheet.getLastRow(), 1).getValue();//I assumed the same condition
  if (lastRow=='BugFix') {
    sheet.getRange(sheet.getLastRow(),1,1,sheet.getLastColumn()).clear();//This clears the entire row
  }
}

This one deletes all the rows with "BugFix" in the first column:
function clearLogs1() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Sheet1');
  var rg=sh.getRange(2,1,sh.getLastRow()-1,sh.getLastColumn());
  var data=rg.getValues();
  var d=0;
  data.forEach(function(r,i){if(r[0]=='BugFix'){sh.deleteRow(i+2-d++);}});
}

A: What you need to do is analyze your values from the "bottom up".
This code does it for you:
function clearLastBugFixes() {
  var ss = SpreadsheetApp.getActiveSheet();
  var rowAValues = ss.getDataRange().getValues().map(function(row) {return row[0];}); //The Map functions filters the values only to the ones we want (Column A).
  Logger.log(rowAValues);

  var counter = 0;
  while (rowAValues.pop()=="BugFix") {
    counter++;
  }
  if (counter>0) {
    var deletionRange = ss.getRange(rowAValues.length+2, 1, counter+1, 1); //Gets the range with lines that need to be deleted.
    deletionRange.clear();
  }
}

What it does is:

*

*Gets the non-blank values from the sheets

*Filter these values to the column we want to analyze

*Counts how many cells it needs to delete from the bottom:

*

*Pops the last value and compares it with "BugFix"

*If this is true, add a number to a counter.

*When this stops being true, halt the counting. (Hence the while loop instead of a for)

*Get the Range with the correct coordinates (to clear multiple columns based on this data, just extend the Range to have the right columns

*Clears it.

Dealing with multiple conditions
First Option: For Loop
You can change the while loop for a for loop that performs the same type of function:

  var counter = 0;
  while (rowAValues.pop()=="BugFix") {
    counter++;
  }

Becomes:
  var counter;
  var rowValue;
  for(counter=0,rowValue=rowAValues.pop(); rowValue=="BugFix" ||  rowValue=="SomethingElse"; counter++) {}

Second Option: Another function
To keep your main function clear of the conditionals and allow for an easier extension, you can also delegate the filtering to another function.
Create a new function like this:
function filterValue(rowValue) {
  return rowValue=="BugFix" ||  rowValue=="SomethingElse";
}

Then change:

  while (rowAValues.pop()=="BugFix") {

To:
  while (filterValue(rowAValues.pop())) {


text:
Q: Alamofire Mailchimp API 3.0 subscribe I am trying to subscribe new user to Mailchimp list using Alamofire.
Problem starts when I'm trying to subscribe new user with .post method and JSONObject as a parameter:
func subscribeMail(){

let credentialData = "<my_api_key>".data(using: String.Encoding.utf8)!
let base64Credentials = credentialData.base64EncodedString(options: [])
let headers = ["Authorization": "Basic \(base64Credentials)"]

let url = "https://us11.api.mailchimp.com/3.0/lists/<my_list_id>/members/"

let jsonObj: [String: AnyObject] = [
    "mail_address" : "testMailAddress@gmail.com" as AnyObject,
    "status" : "subscribed" as AnyObject,
]

let valid = JSONSerialization.isValidJSONObject(jsonObj)
print(valid)

Alamofire.request(url, method: .post, parameters: jsonObj , encoding: URLEncoding.default , headers: headers).responseJSON{response in
    if response.result.isFailure {
       print("Failed")
    }
    else if (response.result.value as? [String: AnyObject]) != nil {
        print(response)
        }
    }

}

I get back status code 400:
SUCCESS: {
detail = "We encountered an unspecified JSON parsing error.";
instance = "";
status = 400;
title = "JSON Parse Error";
type = "http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/";
}

In Mailchimp documentation:
JSONParseError
We encountered an unspecified JSON parsing error.
This error means that your JSON was formatted incorrectly or was considered invalid or incomplete.
As you can see I am checking my jsonObj if its valid. So I dont get this parsing error..
In Mailchimp API 3.0 its written that just email_address and status fields are needed to subscribe new mail.
If I try to to send request with Alamofire using .get method with some mail address that is already subscribed, everything works fine, I can receive all data from Mailchimp.
Is there really problem with my jsonObj or is it somewhere else?

A: Change the object key from 'mail_address' to 'email_address' and give a try.
let jsonObj: [String: AnyObject] = [
    "email_address" : "testMailAddress@gmail.com" as AnyObject,
    "status" : "subscribed" as AnyObject,
]

A: Since you're getting a JSONParseError, your issue is related to the format in which you're sending the parameters.
Try encoding: JSONEncoding.default instead of encoding: URLEncoding.default.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot build Xamarin.iOS with Microsoft Solver Foundation I've added Microsoft Solver Foundation via Nuget to a Xamarin iOS project but it fails to build with this message:
Build FAILED.

MTOUCH : warning MT5215: References to 'gdiplus' might require additional -framework=XXX or -lXXX instructions to the native linker
MTOUCH : warning MT5215: References to 'gdi32' might require additional -framework=XXX or -lXXX instructions to the native linker
MTOUCH : warning MT5215: References to 'user32' might require additional -framework=XXX or -lXXX instructions to the native linker
MTOUCH : warning MT5215: References to 'libX11' might require additional -framework=XXX or -lXXX instructions to the native linker
MTOUCH : warning MT5215: References to 'winspool' might require additional -framework=XXX or -lXXX instructions to the native linker
MTOUCH : warning MT5215: References to 'libcups' might require additional -framework=XXX or -lXXX instructions to the native linker
MTOUCH : warning MT5215: References to 'kernel32' might require additional -framework=XXX or -lXXX instructions to the native linker
clang : error : linker command failed with exit code 1 (use -v to see invocation)
error MT5209 : Native linking error : framework not found Carbon
MTOUCH : error MT5202: Native linking failed. Please review the build log.
    7 Warning(s)
    3 Error(s)

I'm just starting out with Xamarin and I haven't seen these issues before. Does anyone know how I can fix them?
Here's a screenshot

A: I'm not sure if Mircosoft Solver has been updated recently, but my understanding is that it's internal reliance on Linq assemblies meant that it didn't work with the MonoFramework properly.
I've not seen any reference to anyone that's successfully linked the assemblies correctly. I'm not entirely sure if Solver can actually be linked with Xamarin at the moment.
looking at your exception logs above it's pushing the assembly build to the native linker, and it's hitting exceptions with certain dlls. In most native linker cases you would have to wait for the xamarin team to push out an update. But I don't think Solver Foundation is on their list.

Example of native linker bugs


text:
Q: Reloading content into a div at certain interval with jQuery and tabs I had a few tabs that, when clicked, use jquery to load data into a div. I need the data to reload at a 5 second interval, but only the info from the particular tab. So, here's what I have... I think I need to start a setInterval when a tab is clicked, then stop it when another is clicked. Here's my code for the tabs:

So for example, when #xicon1 is clicked, I need it to load alcurrent.php into #actionlist (I can do this), but I need it to reload it every 5 seconds. Then when I click another tab, I need that one to start loading every 5 seconds. So, whichever tab is active, I need the content loaded every 5 seconds.
I've tried setInterval... but no dice.
Thanks.
Edit:
Here's what I've done and I think it works...

Edit2: this might be a little prettier:

Okay, I just want to be sure: When someone clicks on a different tab, its going to stop the other tab's content from refreshing every 5 seconds?

A: What is the syntax of your setInterval, have you tried it like this?
setInterval(function() {
      // Do something every 5 seconds
}, 5000);

A: I think you just need to clear the interval when a new tab is clicked and reset it, like this:

Hope this works for you.


text:
Q: in jquery ui dialog, how can i change the color / contract behind a single modal dialogs using the jquery ui modal dialog, the background shades grey (i assuming this is being driven by my theme roller).  For one specific modal dialog i want the background to be darker than what i am getting by default with the default options.
More importantly, how can i change the shading on the background screen when i load one specific dialog.  In this case, I DON'T want to change the css of my theme roller css as i only want this to apply to one specific page.

A: Could you place the following in your special page : thus overriding the the background
<style>
 .ui-widget-overlay {
      background: url("images/ui-bg_flat_0_aaaaaa_40x100.png") repeat-x scroll 50% 50% #AAAAAA;
       opacity: 0.3;
  }
</style>

Just adjust the opacity to the level you want and for IE you might need modify the image as well..
Hope i understand you...


text:
Q: Calling variables (actually lists) xx1 & xx2 with one xxn command in python I'm writing a code and I have a problem. I have different lists named xx1 and xx2, etc. I have a function like this:
def dotfind(n):
    xone=xdis[n-1]
    xtwo=xdis[n]
    t=toc[n]
    while xone<xtwo:
        t=t+1
        xdis[n-1]=(a*(t**2))/2
        v=a*t
        if xone>=xtwo:
            t=t-1
            v=a*t
    else:
         xx.append( x );
         vv.append( v );
         tt.append( t );

Okay. Don't pay attention to the whole function. Just look at the else part.

If I want the program to get the  "n" and append those variables v & x & t to the xx and vv and tt number n, how can it be done?
This is what I mean: for example if n is 1 then it should do the process on lists xx1 and xx2 and xx3 , if my n is 2, then it should append v & x & t to xx2 and vv2 and tt2, ... .
Please help me!


text:
Q: Proof $ \nabla \cdot ( \nabla g \times \vec{F}) = - \nabla \cdot (g \nabla \times \vec{F})$ How does one tackle the following proof
$$\nabla \cdot ( \nabla g \times \vec{F}) = - \nabla \cdot (g \nabla \times \vec{F}) $$
I tried using the following identity :
$ \nabla \cdot ( \vec{F} \times \vec{G} ) = (\nabla \times \vec{F}) \cdot \vec{G} -  (\nabla \times \vec{G}) \cdot \vec{F}$
But things went wrong. Could someone assist

A: For the RHS, you should get
$$-\nabla g \cdot \mathrm{curl} \ F - g \mathrm{div}(\mathrm{curl} \ F) = -\nabla g\cdot\mathrm{curl} \ F.$$
Using the identity you give, the LHS is
$$(\mathrm{curl} \ \nabla g)\cdot F - (\mathrm{curl} \ F)\cdot\nabla g = -(\mathrm{curl} \ F)\cdot\nabla g,$$
since $\mathrm{curl} \ \nabla f = 0$ for any $f$.


text:
Q: Reactivity in properties not working between controls I have been trying to make my property reactive but for some reason, it does not work. My property is used between two Vue components. I can access the components fine but it's just this property
In the child component, I have a dropdown and I select a user from this. I want to pass it to the parent component
The drop down is a custom control hence it would not be possible to paste its code. But as soon as the user is selected, an event is fired and I can see in the debugger that the even is fired successfully with user selected. Now the problem is passing the value to the parent.
The event in the child component:
computed: {
  ...mapGetters(["selectedParentControl"]),
},
methods {
  onUserSelected(items){
    Vue.set( this.selectedParentControl, 'userObject', items )
  }
}

Parent template:

First User: {{this.userObject}}

But the variable in the parent component doesn't get updated.

A: So if I got you right you want to setup two-way data binding for your custom component. So you can use the v-model.
In your child component define the prop and emit value changes.
props: ['userObject'],
methods {
  onUserSelected(items){
    this.$emit('userObject', items);
  }
}

In your parent component add the v-model directive to your child components element:

   <child v-model="userObject"></child>

First User: {{this.userObject}}


text:
Q: How to add
A: Inside JSX, {...} denotes a JavaScript expression. return index; on its own is not a valid expression.
You have to explicitly create a string so that the {...} are not interpreted by JSX. Template literals may be the easiest solution:

However, I have a hard time coming up with a reason why one would want to create a


text:
Q: Very Very Large Numbrs in Python It was my understanding that python could handle integers of arbitrary length.
It handles addition and multiplication very well, but seems to fall apart with division.
>>> from decimal import Decimal, getcontext
>>> getcontext().prec=2**5
>>> ORIG_NUM=476939688738611836995535477357070857939902076027788232031989775824606225595773435668861833
>>> print(Decimal(ORIG_NUM)/7)
6.8134241248373119570790782479582E+88
>>> print("%.6f" % (Decimal(ORIG_NUM)/7))
68134241248373123068520468160885027682039120236463560535175757714209021725053511199096832.000000

I do not want the e notation hence the getcontext().prec attempts.  Also, confused by the %f dropping the decimal?
>>> getcontext().prec=2**7
>>>QUOTIENT= (Decimal(476939688738611836995535477357070857939902076027788232031989775824606225595773435668861833)/7)

>>>print(QUOTIENT)
68134241248373119570790782479581551134271725146826890290284253689229460799396205095551690.428571428571428571428571428571428571429
>>>QUOTIENT*7
4.7693968873861185e+89
>>> Decimal(QUOTIENT)*7
Decimal('476939688738611861479643277126195193774273841655244923746230303999463152075374578393677824')
>>> print(Decimal(QUOTIENT)*7)
476939688738611861479643277126195193774273841655244923746230303999463152075374578393677824
>>> print(Decimal(QUOTIENT)*7)==ORIG_NUM
476939688738611861479643277126195193774273841655244923746230303999463152075374578393677824
False

Second issue is the numbers do not match up.
Any information on the subject?
Hope that's better...

A: *

*print(Decimal(QUOTIENT)*7)==ORIG_NUM fails because the print function returns None.

*If you want exact division, use the Fraction class.
>>> from fractions import Fraction
>>> x = 476939688738611836995535477357070857939902076027788232031989775824606225595773435668861833
>>> f = Fraction(x, 7)
>>> print(f)
476939688738611836995535477357070857939902076027788232031989775824606225595773435668861833/7
>>> f * 7 == x
True

A: >>> (Decimal(QUOTIENT)*7)-476939688738611836995535477357070857939902076027788232031989775824606225595773435668861833
Decimal('24484107799769124335834371765627456691714240528174856926479601142724815991')

Crazy huge error.
>>> 68134241248373119570790782479581551134271725146826890290284253689229460799396205095551690*7
476939688738611836995535477357070857939902076027788232031989775824606225595773435668861830
>>> MODD=(Decimal(476939688738611836995535477357070857939902076027788232031989775824606225595773435668861833)%7)
3.000000
>>>TRUNCD_QUO=int((Decimal(476939688738611836995535477357070857939902076027788232031989775824606225595773435668861833)/7))
>>>((TRUNCD_QUO*7)+MODD)==ORIG_NUM
True


text:
Q: matlab: truncate large text and append '...' I have a large array of text (text, stored as cell-array), that I want to truncate in matlab, say for 5 characters. Truncating with regexprep is quite efficient, but now, I would love to append a '...' at the end of every truncated match (and only there).
(How) can this be achieved within MATLAB's regexprep?
>> text = {'123456780','1','12'}; %<- small representative sample
>> regexprep(text,'(^.{0,5})(.*)','$1') %capture first 5 characters or less in first group (and replace the text with first group captures)

ans =

  1×3 cell array

    {'12345'}    {'1'}    {'12'}

it should read:
ans =

  1×3 cell array

    {'12345...'}    {'1'}    {'12'}

A: You need to use
regexprep(text,'^(.{5}).+','$1...')

See the regex demo.
The main point is that you need to only trigger the replacement if a string is linger than five chars (else, you do not even need to truncate the string).
Note that regexprep returns the input string as is if there was no regex match found, thus you do not need to worry about strings that are zero to five chars long.
Details:

*

*^ - start of string

*(.{5}) - Capturing group 1 ($1): any five chars

*.+ - any one or more chars, as many as possible.

A: Note that the string 12345... is in fact 8 characters long. You don't want to make the mistake of truncating 1234567 to 12345..., as the truncated version is longer and therefore shouldn't be truncated in the first place.
A solution that takes this into account is:
regexprep(text,'^(.{5}).{3}.+','$1...')

which will only truncate if there are more than 8 characters and, if so, will display the first 5 with the trailing ellipsis.


text:
Q: How do I provide browser drivers to Selenium in Jupyter Lab? I'm using Selenium in JupyterLab on IBM's CognitiveClass Labs, and although the package is easy enough to install there with pip (actually I think it already came pre-loaded), it can't find the drivers it needs in PATH:
from selenium import webdriver
browser = webdriver.Firefox()
[Out] FileNotFoundError: [Errno 2] No such file or directory: 'geckodriver': 'geckodriver'
[Out] WebDriverException: Message: 'geckodriver' executable needs to be in PATH.

It's the same for all other browsers too, just replace 'geckodriver' with the Chrome/IE substitute.
Anyway, this would probably be straightforward on a real python installation but I prefer to use it in JupyterLab if I can. I downloaded the driver .exe files and placed them in my project's directory, which the lab sees as /resources/myproj. Then I added this to the PATH that JupyterLab was already using, and specified the location of the executable for Selenium:
%env PATH=/home/jupyterlab/conda/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/resources/myproj

driver = os.path.normpath(os.path.join(os.getcwd(), 'geckodriver.exe'))
browser = webdriver.Firefox(executable_path=driver)
[Out] PermissionError: [Errno 13] Permission denied: '/resources/myproj/geckodriver.exe'
[Out] WebDriverException: Message: 'geckodriver.exe' executable may have wrong permissions.

Can I (or must I) modify permissions on these files in JupyterLab in order for Selenium to access them? Or is there another way to mimic a browser in Jupyter?
Edit: Corey Goldberg is right, this is a Linux environment not a Windows one and I was able to chmod the linux driver to get over that particular issue. But Selenium is still stopping me.
[Out] SessionNotCreatedException: Message: Unable to find a matching set of capabilities

The questions I have (which make this a very different issue from the one DebanjanB cited) are JupyterLab-specific:

*

*Is it dependent on my local Windows machine's Firefox installation? It has a much older version (52.5.2), so I tried the corresponding version of the gecko driver (17.0) in addition to the latest version. But I doubt that, because I'm not pointing it to Firefox's executable on my local drive.

*Do I need the 32-bit or 64-bit Linux driver? I tried both anyway, both return the same error above. But I still don't know because from what I understand my code is running on IBM's computers, not my own.

Edit2: Resolution
This issue may be specific to my work environment. I installed the latest Firefox to my lab's folder using JupyterLab's terminal
$ cd /tmp
$ wget 'http://download.mozilla.org/?product=firefox-latest-ssl&os=linux64&lang=en-US' -O firefox-67.0.4.tar.bz2
$ tar jxvf firefox-67.0.4.tar.bz2 -C /resources/myproj/

then set marionette capability to False, created an explicit Firefox binary so I could look at the log (ultimately it didn't write anything, don't know why)
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

cap = DesiredCapabilities().FIREFOX
cap["marionette"] = False
driver = os.path.normpath(os.path.join(os.getcwd(), 'geckodriver'))
binary = os.path.normpath(os.path.join(os.getcwd(), 'firefox', 'firefox'))
ff_binary = webdriver.firefox.firefox_binary.FirefoxBinary(firefox_path=binary, log_file='ff_log.log')
browser = webdriver.Firefox(firefox_binary=ff_binary, capabilities=cap, executable_path=driver)
browser.get('http://google.com/')

In the end it seems like something on my side is stopping it, and it's gone beyond the scope of my original question.
[Out] WebDriverException: Message: The browser appears to have exited before we could connect. If you specified a log_file in the FirefoxBinary constructor, check it for details.

A: geckodriver.exe is the driver for Windows.  From the look of your PATH, you need the Linux version.  Once you unarchive it, the executable is named geckodriver (no .exe).  You will then need to run chmod to give it executable permissions before using.


text:
Q: Ratings returned by Google Places API do not match Web UI Ratings Since the change to Google+ Places, ratings are based on a scale from 0-30. However, the API still returns the old 0-5 scale ratings. Does anyone know of a way to get the same overall rating data from the API as a user will see on Google+ Places?

A: Please place a 'Places API - Feature Request' for this here.

A: You could multiply the API rating by 6.


text:
Q: Replace email id by HTML Tag to make a hyperlink inside the text I have a text as follows
For further details, please contact abc.helpdesk@xyz.com

I want to replace the email ID mentioned in the above text by abc.helpdesk@xyz.com So that the email ID would become a clickable object when the above text would be presented on web page
So far I have tried out following
text = 'For further details, please contact abc.helpdesk@xyz.com'
email_pat = re.findall(r'[\w\.-]+@[\w\.-]+\.\w+',text)
email_str = ' '.join(email_pat) #converts the list to string
text_rep = ext.replace(email_str,'email_str')

The above code replace the email string but instead of creating hyperlink it actually does the following
For further details, please contact email_str

Is there any way to tackle this?
Edit
When I am using the above solution in Flask, on frontend I am getting the desired result (i.e. email ID becomes clickable, urls become clickable). But when I click on this I am being redirected to the localhost:5002 instead of opening the Outlook. localhost:5002 is where my Flask App is being hosted.
Even for the url also it is not working. I am using the following code to make the url string clickable.
text = text.replace('url',f'{url}'

The above code is making the usr string clickable, but upon clicking it is being redirected to localhost:5002
Is there any change I need to make in app.run(host=5002) method?

A: You can use re.sub with a lambda:
import re
s = 'For further details, please contact abc.helpdesk@xyz.com'
new_s = re.sub('[\w\.]+@[\w\.]+', lambda x:f'{x.group()}', s)

Output:
'For further details, please contact abc.helpdesk@xyz.com'

A: Your actual problem is the line:
text_rep = ext.replace(email_str, 'email_str')

That does exactly what you say it does, but what you want is this:
text_rep = ext.replace(email_str, f'{email_str}')

Instead of replacing the mail address with that literal string with email_str in it, this formats the string so that it has the mail address in it. This is assuming you run Python 3, for Python 2 it would be more like:
text_rep = ext.replace(email_str, '{email_str}'.format(email_str=email_str))

However, note that your regex to match mail addresses makes some assumptions, a better version can be found here Are email addresses allowed to contain non-alphanumeric characters?
Also, your code assumes there will be only one mail address in the source text string, as you're joining results. A better solution might be one which replaces each individual mail addresses with the correct replacement.
import re

input_text = 'For further details, contact admin@mywebsite.org or the webmaster webmaster123@hotmail.com'

output_text = re.sub(
    r'(?sm)(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})',
    r'<a href="\g<0>">\g<0>', input_text)

print(output_text)

Note that this needs nothing but a basic re.sub.


text:
Q: Kubernetes deployment freezes When trying to run command:
kubectl get deployments

I get this message:
C:\Users\win 10\AppData\Local\Google\Cloud SDK\helloworld-gke>kubectl rollout status deployment helloworld-gke
Waiting for deployment "helloworld-gke" rollout to finish: 0 of 1 updated replicas are available...

and nothing has happened since then, is this a freeze or it is taking time to deploy ?

A: You gave an invalid docker image name in your deployment so it can't succeed.


text:
Q: Android app: decrease battery usage I just finished an app that synchronizes its data with a server (runs SyncAdapter on background). I installed it on my phone, let it run on background (I barely used my phone) and I found out that the 23% of my applications' battery usage belongs to my app, so I really need to decrease  its battery usage.
Right now I have the sync time set to 30 seconds. It's a multi-user app and if other users interact with you you get a notification, I can't set a sync time too high (actually I wanted to decrease it until I saw the battery usage).
In each synchronization it ALWAYS asks the server for any changes and checks for changes in the local database. If there are changes in the local database they are sent to server, and if we retrieve changes from the server they are applied to the local database.
Does anybody know about some tips to reduce battery usage?

A: Probably the best that you can do is to implement GCM (Google Cloud Messaging) using pushing instead of polling.
In this way you will be able to get a "tickle" when something new happened and you will know when ask to the server for datas.

A: A network poll each 30 seconds is very aggressive. I recommend you read this article from Google : http://developer.android.com/training/efficient-downloads/index.html
However, if you really need to request the network that often, I don't see any magical trick for you...


text:
Q: Passing listview selected item from fragment to activity I am trying to pass the selected name from ListView to MainActivity from a Fragment but i am getting null pointer exception in onItemClick method.
Here is the code from the fragment:
getListText getListTextObject;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View rootView=inflater.inflate(R.layout.fragment_main, container, false);

        listView=(ListView) rootView.findViewById(R.id.profile_list);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                nameListItem=(TextView) view;
                String text=nameListItem.getText().toString();

                getListTextObject.getData(text);
            }
        });

        return rootView;
    }

    public void onAttach(Context context){
        super.onAttach(context);

        try{
            getListTextObject=(getListText) context;
        }catch (ClassCastException e){
            throw new ClassCastException(context.toString() + " must implement getListText");
        }
    }

    public interface getListText{
        public void getData(String s);
    }

StackTrace for the null pointer exception:
02-25 10:17:14.445 7388-7388/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 java.lang.NullPointerException
                                                     at com.example.user.example.FragmentMain$1.onItemClick(FragmentMain.java:67)
                                                     at android.widget.AdapterView.performItemClick(AdapterView.java:298)
                                                     at android.widget.AbsListView.performItemClick(AbsListView.java:1086)
                                                     at android.widget.AbsListView$PerformClick.run(AbsListView.java:2855)
                                                     at android.widget.AbsListView$1.run(AbsListView.java:3529)
                                                     at android.os.Handler.handleCallback(Handler.java:615)
                                                     at android.os.Handler.dispatchMessage(Handler.java:92)
                                                     at android.os.Looper.loop(Looper.java:137)
                                                     at android.app.ActivityThread.main(ActivityThread.java:4745)
                                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:511)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                                                     at dalvik.system.NativeStart.main(Native Method)

A: Your implementation is bad. Your Activity must implements the "getListText" interface. Then you can call since your Fragment to your Activity, like this:
((getListText)context).getData(text);

And recieve this data in YourActivity.
This answer is more complete. I think that can help you.


text:
Q: Inline CRUD operation on Ant Design Table I am using ant design Table, where I want to add a new row like an inline form when a button is clicked and able to do CRUD operation on this table
When I click the button 1st time it adds a new row in the table with all fields empty but when I click the button again the previously selected data remains,
If you don't understand the problem please watch this YT video: * https://youtu.be/S7-99HqpWvo * here Material UI is used but I want to achieve the same functionality using Ant Design
Please help me with this, Below I have given the codepen link
codepen link:
 [codepen]: https://codepen.io/sandipdeb05/pen/WNdRmxd


text:
Q: Changing a Background-image CSS with Javascript I have a Wordpress site with a background in the header inside of a class.
I'm tring to write a bit of JS to change this background image depending on a hashtag. The Hashtag script is working but the change BG bit isn't - please help... :-(
The script I've writen is:
  document.getElementsByClassName("eut-bg-image").style.backgroundImage = "url(https://boutiqueballer.com/wp/wp-content/uploads/2017/10/chanel.jpg)";
})();

A: getElementsByClassName yields a collection of elements. The individual elements in the collection have the style property, not the collection itself. If you are targeting just one element, you can access it by index:
document.getElementsByClassName('eut-bg-image')[0].style.backgroundImage = ...;

If you are targeting several elements, you may iterate over them:
var elements = document.getElementsByClassName('eut-bg-image');
for(var i = 0; i < elements.length; i++)
   elements[i].style.backgroundImage = ...;

Alternatively, you may use document.querySelector, depending on which level of browser compatibility you need. You can then distinguish between document.querySelectorAll if you want a collection, or docment.querySelector if you want only the first match. Accepts a CSS selector:
document.querySelector('.eut-bg-image').style.backgroundImage = ...;


text:
Q: VSTS Package Management: Missing NuGet package icons in own package feed I'm in the progress of migrating a private NuGet gallery from an Azure App Service to a VSTS Package Management feed. I pushed all nupkg files to this feed, and am able to consume this feed with Visual Studio, but now all packages show the NuGet default icon.
I've checked the feed output with Fiddler: The resulting JSON document contains "iconUrl" properties with the correct URLs but for some reason, they don't show up in the NuGet Package Manager.
Does anybody know how to fix this? Is this an issue with the feed (not returning a correct JSON response) or with the NuGet Package Manager?

A: Our current design doesn't send back image URLs. I'll get it on our backlog to support in the future.


text:
Q: Point A and MX records to different servers The more I read the more confused I get, so please advise...
I bought a godaddy domain.
I have 2 servers, and I want the following...

*

*Justhost (Email)

*Digital Ocean (Web server for app)

How can I receive emails on Justhost, but run the app on Digital Ocean?

*

*Domain should point to which host's nameservers?

*Where do I setup the A record and where do I point it?

*Where do I setup the MX record and where do I point it?

A: DNS, email and web pages are all different services and can all three be hosted on the same or different service providers. If you are confused, you could think them through an analogy:

*

*DNS is like a phone book having information on all the people with their contact information.

*IP addresses on A records are like phone numbers. You could e.g. have one for your landline, one for your gsm, one for work etc.

*Email service is like a fax. You can tell you have a email service through MX records, but eventually it's handled by servers with IP addresses. Likewise, a fax machine has a phone number: there's just a mention on the phone book telling it's not a normal number someone would answer.

*

*If you point your example.com MX to a different domain mail.example.net it's like telling you don't have an own fax number, but faxes to you could be send to a fax machine at your workplace.

Now, neither the phone company handling your gsm nor your fax line doesn't have to maintain a phone directory having your numbers, although they both could. Also, anyone already knowing your number can contact you; the service exists to publish this information. The same applies to DNS.

A: *

*Name servers should point to whoever is hosting your DNS.

*You need to add an A record pointing to your webhost, for example example.com A 192.0.2.123

*You probably also want www.example.com to work, so you can add a CNAME for that as well, pointing at example.com: www.example.com CNAME example.com

*You'll need to add MX records pointing to your email service, for example: MX 5 mx1.example.com Your email provider usually tells you what records to add.

All these records need to be added to wherever you're hosting your DNS service.

A: You need to set A and MX DNS record types trough your account on GoDaddy, and everything that is related with your domain name is done there:

*

*A record maps hostname with IP address (this is for your web server for app, so here you will set pointing to IP address on Digital Ocean)

*MX record maps domain name to one or more message transfer agents (this is for your e-mail server, so you will set MX pointing to IP address of your server on Justhost)

List of DNS record types with brief description on wikipedia.
GoDaddy help page


text:
Q: How to get all Dates given "Day Name" Between 2 Dates in c# How to get All Days between given two Dates, given "Day Name"?
Ex: Start_Date = Jan 1, 2011
      End_Date = Jan 20, 2011
      Day Name = Sunday
Here we need to get all Dates with dayname as "SUNDAY"
Ex:
Jan 02, 2011
Jan 09, 2011
Jan 16, 2011

A: DateTime startDate = new DateTime(2011, 1, 1);
DateTime endDate = new DateTime(2011, 1, 20);

while (startDate < endDate)
{
   if (startDate.DayOfWeek == DayOfWeek.Sunday)
   {
      // Do something
   }

   startDate = startDate.AddDays(1);
}

A: How about something like
DateTime startDate = new DateTime(2011, 01, 01);
DateTime endDate = new DateTime(2011, 01, 20);
string dayName = "sunday";

List<DateTime> list = new List<DateTime>();
for (DateTime runDate = startDate; runDate <= endDate; runDate = runDate.AddDays(1))
{
    if (runDate.DayOfWeek.ToString().ToLower() == dayName)
        list.Add(runDate);
}

or even using Enum.TryParse
DateTime startDate = new DateTime(2011, 01, 01);
DateTime endDate = new DateTime(2011, 01, 20);
string dayName = "sunday";
DayOfWeek dow;
Enum.TryParse(dayName, true, out dow);

List<DateTime> list = new List<DateTime>();
for (DateTime runDate = startDate; runDate <= endDate; runDate = runDate.AddDays(1))
{
    if (runDate.DayOfWeek == dow)
        list.Add(runDate);
}

A: I like to use Enumerable.Range for tasks like that:
DateTime start = new DateTime(2011,1,1);
DateTime end = new DateTime(2011,1,20);

var datesThatAreSundays = Enumerable
    .Range(start.DayOfYear, end.Subtract(start).Days + 1)
    .Select(n => start.AddDays(n - start.DayOfYear))
    .Where(d => d.DayOfWeek == DayOfWeek.Sunday);

A: Without having tested:
DateTime start = x;
DateTime end = y;

while (start.DayOfWeek != z)
    start = start.AddDays(1);

while (start <= end)
{
    //DoStuff

    start = start.AddDays(7);
}

A: You may try this
 var firstDate = new DateTime(2011, 1, 1);
 var lastDate = new DateTime(2011, 1, 20);

 var result = (from el in Enumerable.Range(0, (lastDate - firstDate).Days)
                      let date = firstDate.AddDays(el)
                      where date.DayOfWeek == DayOfWeek.Sunday
                      select date).ToArray();


text:
Q: ActiveRecord: group by count of associated has_many records Given that a User has many properties:
class User
  has_many :properties
end

I want a report that would first calculate how many properties each user has, and then group the users that have the same number of properties together, counting them.
I cannot use a counter cache on the User model for reasons that are out of scope of the question (the query merges a dynamic scope of Properties).
To keep it simple, so far we have this:
`User.joins(:properties).group('users.email')
     .order('COUNT(properties.id) DESC').count`

This returns a hash like this:
{
  "email1@gmail.com"=>209,
  "email2@gmail.com"=>160,
  "email3@gmail.com"=>160
}

My goal is, based on the previous example hash, end up with a hash like this:
{
  209 => 1,
  160 => 2
}

Because we had 1 user with 209 properties and 2 users with 160 properties.
I already achieved the result using ruby's .group_by, but the goal is to achieve it using ActiveRecord / SQL only. I don't mind having to run raw SQL if that's necessary.

A: Not sure if you still need help on this. But if other users stumble on this, hope it helps them.
User.joins(:properties).group('users.id')
     .order('COUNT(properties.id) DESC').count


text:
Q: Angular - InnerHtml with styles I've this...
const htmlVar = "

Hello World

";

and on my html I've this..

It's render everything, but the style :(
I attempted the solution of this link: style not working for innerhtml in Angular 2 Typescript
but it's not working. Maybe because it's too old.
Any clue ?

A: As @R.Richards mentioned, use DomSanitizer:
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
.
.
.
htmlVar: SafeHtml;

constructor(protected _sanitizer: DomSanitizer) {
  this.htmlVar = this._sanitizer.bypassSecurityTrustHtml(`

Hello World

    `);
}

I created a stackblitz to illustrate
Also, as @liam already mentioned you should not have , , or  tags as DIV's children


text:
Q: Chrome 31.x support for input:checked+label? I have problem with input:checked+label on Chrome 31.x.
Here is code: demo
I had in my application buttons like the first in demo and it was working a long time. Yesterday, I sow that one functionality stoped working and I didn't have idea why. Today I'm searching web and find nothing... almost. I found old demo for similar functionality and added to this  inside label. And it stoped working.
Anyone knows what happend or how to fix this problem? I wanted to make changes as little as it is passible. There are two options for me now: JS or remove button and restyle "button".
PS. I know, that button in label isn't semantic, but it isn't my code :P

A: It isn't working because Chrome probably adds some kind of "stopPropagation()" for parent labels.
Hacky solution:
$(function () {
  $('body').on('click', 'label button', function (e) {

    $(this).closest('label').trigger('click');

    e.stopPropagation();
    e.preventDefault();
  });
});

A: No Javascript Solution
UPDATE: Solving the Click on Label to Get Checked Status Issue
This also has a pure CSS solution (at least under certain conditions). See this example using this css:
input + label {position: relative;}
input + label button {
  position: relative;
  z-index: -1;
}

This overlays the label over the button element, allowing the label to acquire the click instead of the button. Two consequences of this are:

*

*If the actual button also needed to register the click, then a js solution like tdroL's answer is the only thing that I believe will work.

*The click of the button does not activate the browser's "pressed button" look, since the button is not really being pressed (the label is). If one wanted that, then an additional styling change to the button to make a pressed look would need to happen using a selector like input + label:active button.

Solving the Color Issue (which was not the main issue)
I originally thought the question was about solving the color value of the button, and gave the following answer (which could still be helpful). I think the default value of a button element for color is not inherit as most text is (perhaps this is browser specific). Upon inspection, both Firefox and Chrome for a straight button element show buttontext as the value of the color property, indicating that the browser is controlling the button color. So a more explicit css is needed to set the color of the button, as it is not going to inherit the color from the label element it is nested in (which is what your example is depending upon). So this css works):
input:checked + label button {color:red}

Of course, if you still need the second one working, css would be this:
input:checked + label,
input:checked + label button {
  color:red
}


text:
Q: CakePHP Custom route calling wrong action I have the following code in routes.php:
Router::connect('/c/details/:id/:slug',
    array('controller' => 'cars'),
    array('pass' => array('id', 'slug'))
);

If I try to access http://domain.com/c/details/123/abc, it works. However, if I remove abc (ie the slug), CakePHP tries to access the action 123 (which is the id, not the action).
Error: The action 123 is not defined in controller CarsController

If I use /c/details/:id/:slug/:action/*, which was what I had before upgrading from 1.2 (yeah, pretty old) to 2.2.1 and it was working fine, CakePHP also tries to access action 123 whether I have a slug or not.
URLs without slugs always worked before upgrading CakePHP and with the code I have in the controller, if there was no slug in the URL, it would redirect to the right URL.
Edit: I just checked and it seems that when I don't provide with a slug, the whole thing is shifted. c is ignored, details becomes the controller and 123becomes the action.
[request] => CakeRequest Object
    (
        [params] => Array
            (
                [plugin] =>
                [controller] => details
                [action] => 123
                [named] => Array()
                [pass] => Array()
                [isAjax] =>
            )

When the correct would be, and which is what I get if I provide with a slug:
[request] => CakeRequest Object
    (
        [params] => Array
            (
                [plugin] =>
                [controller] => cars
                [action] => index
                [named] => Array()
                [pass] => Array
                    (
                        [0] => 123
                        [1] => abc
                    )

                [id] => 123
                [slug] => abc
                [isAjax] =>
            )

Any idea what may be causing this issue now?

A: You may need 2 routes if you want the slug to be optional (not sure). In any case, add the action key to each route as well.
Router::connect('/c/details/:id',
    array('controller' => 'cars', 'action' => 'details'),
    array('pass' => array('id'))
);

Router::connect('/c/details/:id/:slug',
    array('controller' => 'cars', 'action' => 'details'),
    array('pass' => array('id', 'slug'))
);


text:
Q: filling missing data with mean in pandas dataframe Error: U4 cannot be converted to a FloatingDtype train1=train1.fillna('mean')
TypeError: <U4 cannot be converted to a FloatingDtype
imputed values of mean were expected

A: It would help if you would show an example of what is in your train1 DataFrame. But I guess you don't have only floats in there. One solution might be to convert to float first?
train1_imputed = float(train1).fillna('mean')

A: You can't pass a function to fillna or a name of function. Try:
train1 = train1.fillna(train1.mean())


text:
Q: How to get the NEW text in TextChanged? In a TextBox I'm monitoring the text changes. I need to check the text before doing some stuff. But I can only check the old text in the moment. How can I get the new Text ?
private void textChanged(object sender, EventArgs e)
{
    // need to check the new text
}

I know .NET Framework 4.5 has the new TextChangedEventArgs class but I have to use .NET Framework 2.0.

A: Getting the NEW value
You can just use the Text property of the TextBox. If this event is used for multiple text boxes then you will want to use the sender parameter to get the correct TextBox control, like so...
private void textChanged(object sender, EventArgs e)
{
    TextBox textBox = sender as TextBox;
    if(textBox != null)
    {
        string theText = textBox.Text;
    }
}

Getting the OLD value
For those looking to get the old value, you will need to keep track of that yourself. I would suggest a simple variable that starts out as empty, and changes at the end of each event:
string oldValue = "";
private void textChanged(object sender, EventArgs e)
{
    TextBox textBox = sender as TextBox;
    if(textBox != null)
    {
        string theText = textBox.Text;

        // Do something with OLD value here.

        // Finally, update the old value ready for next time.
        oldValue = theText;
    }
}

You could create your own TextBox control that inherits from the built-in one, and adds this additional functionality, if you plan to use this a lot.

A: Have a look at the textbox events such as KeyUp, KeyPress etc. For example:
private void textbox_KeyUp(object sender, KeyEventArgs e)
{
    // Do whatever you need.
}

Maybe these can help you achieve what you're looking for.

A: Even with the older .net fw 2.0 you should still have the new and old value in the eventArgs if not in the textbox.text property itself since the event is fired after and not during the text changing.
If you want to do stuff while the text is being changed then try the KeyUp event rather then the Changed.

A: private void stIDTextBox_TextChanged(object sender, EventArgs e)
{
    if (stIDTextBox.TextLength == 6)
    {
        studentId = stIDTextBox.Text; // Here studentId is a variable.

        // this process is used to read textbox value automatically.
        // In this case I can read textbox until the char or digit equal to 6.
    }
}


text:
Q: How can I prevent the warning No xauth data; using fake authentication data for X11 forwarding? Every time I initiate an ssh connection from my Mac to a Linux (Debian) I do get this warning:
No xauth data; using fake authentication data for X11 forwarding.

This also happens for tools that are using ssh, like git or mercurial.
I just want to make a local change to my system in order to prevent this from appearing.
Note: I do have X11 server (XQuartz 2.7.3 (xorg-server 1.12.4)) on my Mac OS X (10.8.1) and it is working properly, I can successfully start clock locally or remotely.

A: I would add this as a comment, but I don't have enough rep. Adding one more line to sorin's solution worked for me.
On the client machine, edit your ssh config file with vim ~/.ssh/config
Then add these lines to it:
Host *
    ForwardAgent yes
    ForwardX11 yes
    XAuthLocation /opt/X11/bin/xauth

You can double check your xauth location with:
which xauth

A: Found the cause, my ~/.ssh/config was incomplete, you need both:
Host *
    ForwardAgent yes
    ForwardX11 yes

My mistake was that I included only the ForwardX11 option.

A: Letting Ubuntu bash on Windows 10 run ssh -X  to get a GUI environment on a remote server

*

*First

Install all the following. On Window, install Xming. On Ubuntu bash, use sudo apt install to install ssh xauth xorg.
sudo apt install ssh xauth xorg

*

*Second

Go to the folder contains ssh_config file, mine is /etc/ssh.

*

*Third

Edit ssh_config as administrator(USE sudo). Inside ssh_config, remove the hash # in the lines ForwardAgent, ForwardX11, ForwardX11Trusted, and set the corresponding arguments to yes.
# /etc/ssh/ssh_config

Host *
    ForwardAgent yes
    ForwardX11 yes
    ForwardX11Trusted yes

*

*Forth

In ssh_config file, remove the front hash # before Port 22 and Protocol 2, and also append a new line at the end of the file to state the xauth file location, XauthLocation /usr/bin/xauth, remember write your own path of xauth file.
# /etc/ssh/ssh_config

#   IdentifyFile ...
    Port 22
    Protocol 2
#   Cipher 3des
#   ...
#   ...
    ...
    ...
    GSSAPIDelegateCredentials no
    XauthLocation /usr/bin/xauth

*

*Fifth

Now since we are done editing ssh_config file, save it when we leave the editor. Now go to folder ~ or $HOME, append export DISPLAY=localhost:0 to your .bashrc file and save it.
# ~/.bashrc
...
...
export DISPLAY=localhost:0

*

*Last

We are almost done. Restart your bash shell, open your Xming program and use ssh -X yourusername@yourhost. Then enjoy the GUI environment.
ssh -X yourusername@yourhost

The problem is also in Ubuntu subsystem on Windows, and the link is at
https://gist.github.com/DestinyOne/f236f71b9cdecd349507dfe90ebae776
Note: the linked text includes 2 typos (XauthLocaion instead of XauthLocation)

A: There is a bug in MacOS at the moment.  I came across this too.  The fix for me involved adding the following to my .bash_profile
dispdir=`dirname $DISPLAY`
dispfile=`basename $DISPLAY`
dispnew="$dispdir/:0"
if [ -e $DISPLAY -a "$dispfile" = "org.x:0" ]; then
  mv $DISPLAY $dispnew
fi
export DISPLAY=$dispnew

Essentially the name for the file pipe associated with your X root can't be handled correctly, and thus needs correction.  :-)

A: i just removed ~/.Xauthority (destination machine) from my root folder and ssh -X 192.168.123.1  again and ik worked.

A: Including
XAuthLocation /opt/local/bin/xauth
in ~/.ssh/config
in my macOS Sierra 10.12.6 worked for me. A small change from answer 7).

A: This started happening to me after moving my Cygwin installation from one PC to another. The issue seemed to be the hostname change: the magic cookie no longer corresponded to the hostname of the new PC.
Running
touch ~/.Xauthority
xauth add :0 . `mcookie`

on the local Cygwin installation fixed the problem for me -- xauth list now listed a magic cookie associated with the correct hostname of the new PC, and the warning stopped appearing.

A: As noted, it seems that xauth on OS X Yosemite has regressed to an old version that doesn't work with XQuartz's $DISPLAY setting:
% xauth -V
1.0.9
% xauth generate $DISPLAY .
xauth: (argv):1:  bad display name "/private/tmp/com.apple.launchd(...)/org.macosforge.xquartz:0" in "add" command

A: None of the posted solutions worked for me.  My client (desktop) system is running macOS 10.12.5 (Sierra).  I added -v to the options for the ssh command and it told me,
debug1: No xauth program.

which means it doesn't have a correct path to the xauth program.  (On this version of macOS the path to xauth is nonstandard.)  The solution was to add this line to /etc/ssh/ssh_config (may be /etc/ssh/config in some setups) or in ~/.ssh/config (if you don't have admin rights):
XAuthLocation /opt/X11/bin/xauth

Now the warning message is gone.

A: In my case it was the problem of .Xauthority containing the Magic cookie
not forwarded, Fabby on http://askubuntu.com/questions/571116/ recommends
on 2014-11-14 to add this line at the end of the .bashrc or . profile
to allow forwarding of xauth keys between users when calling su:
export $(dbus-launch)

I added also previously:
export XAUTHORITY=~/.Xauthority

to ensure remote called with ssh -X ̍@ will find it.
In my case .Xauthority is a symlink to original user /home//.Xauthority I su from...
  cd /home/<child_user>;ln -sf /home/<parent_user>/.Xauthority .xAuthority

with correct rights:
  sudo chown <parent_user> /home/<parent_user>/.profile
  chmod a+rw /home/<parent_user>/.profile

so it is accessible to  and to .  will be able to trigger apps on  and display X-windowed result on its local screen throughout proxy account !
TIP : Check xauth list...if reflects magic cookie on .

A: My goal was get quiet ssh-based command line login t Linux hosts from my macOS client. E.g. I didn't want to see any banners or messages. Just setup cert-based login so I could type an alias at the and get a prompt on the host machine.  To accomplish that I did the following:

*

*On the Debian 10 Linux host I touched (e.g. created)
~/.hushlogin

*However, on macOS Catalina ssh client I was getting the message:
No xauth data; using fake authentication data for X11 forwarding.
After confirming xauth binary location, I addedXAuthLocation /opt/X11/bin/xauth to /etc/ssh/sshd_config on the macOS client, but that did not work for me when I used this command:
ssh -Y user@debian10

In the final analysis @ssanch's answer did work for me. But before I discovered that solution I stumbled on a workaround that might help some people:
ssh -Yy user@host

Adding lowercase -y flag to the ssh command line causes it to send it's log output to syslog instead of stderr, and that allows for the desired quiet login also.

A: For anyone having the same trouble, I've tested all the other answers, nothing worked for me: launch xterm by ssh from local Windows 10 to Linux Debian 10 buster remote box.
The way worked for me is

*

*Install Xming.exe under Windows and run it,

*Then under Windows using PowerShell:
$env:DISPLAY="localhost:0"
ssh.exe -Y user@example.com

instead of ssh.exe -X user@example.com.
$env:DISPLAY is mandatory. Shell environment variable $DISPLAY is automatically set by xauth or similar.
I've reported the detail on stackoverflow.


text:
Q: Probability that a point is contained in at least one interval (given N equal length intervals)
Given a point $x \in [0,T]$ and $N$ intervals of equal length $w<T$, what is the probability of at least one interval containing $x$? The starting positions of the intervals are independently sampled.

My reasoning was:

*

*The probability of an interval containing $x$ is $w/T$.

*The probability of at least one interval containing $x$, $P(\text{at least one}) = P(\text{any one int})$ or $P(\text{any two ints})$ or $\dots$

Therefore, $$P(\text{at least one}) = \sum_{k=1}^{N}\binom{N}{k}\left(\frac{w}{T}\right)^{k}$$
However, that doesn't seem to be it... I would appreciate any help.
Regards,
Misel

A: Hint:  Presumably the intervals are allowed to overlap.  As you say, the chance of a given interval containing $x$ is $\frac wT$, so the chance that the given interval does not contain $x$ is $1-\frac wT$.  The chance that no interval contains $x$ is ????


text:
Q: Alphabetical sorting should be case sensitive or not? There is a scenario of sorting data based on alphabetical order in my application. I am little confused, whether my sorting should be case sensitive or not, which would be better for user experience?
The data, I want to sort here is a list of form names.
I will not allow the user to change the sort order, so I should choose a user friendly sorting.


text:
Q: Establishing PPTP-connection in a Kubernetes POD I'm trying to set up a pod running a pptp-client.
I want to access a single machine behind the VPN and this works fine locally , my docker container adds records to my localhost's routing table, all is well.
ip route add x.x.x.x dev ppp0

I am only able to establish a connection to the VPN-server as long as privileged is set to true and network_mode is set to "host"
The production environment is a bit different, the "localhost" would be one of our three operating nodes in our Google Container cluster.
I don't know if the route added after the established connection would be only accessible by the containers operating inside that node.. but this is a later problem.
docker-compose.yml
version: '2'
services:
  pptp-tunnel:
    build: ./
    image: eu.gcr.io/project/image
    environment:
     - VPN_SERVER=X.X.X.X
     - VPN_USER=XXXX
     - VPN_PASSWORD=XXXX
    privileged: true
    network_mode: "host"

This seems to be more difficult to achieve with kubernetes, though both options exist and is declared as you can see in my manifest. (hostNetwork, privileged)
Kubernetes Version
Version 1.6.6
pptp-tunnel.yml
apiVersion: v1
kind: Service
metadata:
  name: pptp-tunnel
  namespace: default
  labels:
spec:
  type: ClusterIP
  selector:
    app: pptp-tunnel
  ports:
    - name: pptp
      port: 1723
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: pptp-tunnel
  namespace: default
spec:
  replicas: 1
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
    type: RollingUpdate
  selector:
    matchLabels:
      app: pptp-tunnel
  template:
    metadata:
      labels:
        app: pptp-tunnel
    spec:
      hostNetwork: true
      containers:
      - name: pptp-tunnel
        env:
        - name: VPN_SERVER
          value: X.X.X.X
        - name: VPN_USER
          value: XXXX
        - name: VPN_PASSWORD
          value: 'XXXXX'
        securityContext:
          privileged: true
          capabilities:
            add: ["NET_ADMIN"]
        image: eu.gcr.io/project/image
        imagePullPolicy: Always
        ports:
        - containerPort: 1723

I've also tried adding capabilities: NET_ADMIN as you can see, without effect. Setting the container in priviliged mode should disable the security, i shouldn't need both.
Would be nice to not have to set the container to priviliged mode and just rely on capabilities to bring the ppp0 interface up and add the routing.
What happens when the POD starts is that the pptp-client simply keeps sending requests and times out.
(This happens with my docker container locally aswell until i turn network_mode "host" on.)
sent [LCP ConfReq id=0x1 <asyncmap 0x0> <magic 0xa43cd4b4> <pcomp> <accomp>]
LCP: timeout sending Config-Requests

But this is without hostNetwork enabled, if i enable it i simply get a single request sent, and then modem hangup.
using channel 42
Using interface ppp0
Connect: ppp0 <--> /dev/pts/0
sent [LCP ConfReq id=0x7 <asyncmap 0x0> <magic 0xcdae15b8> <pcomp> <accomp>]
Script ?? finished (pid 59), status = 0x0
Script pptp XX.XX.XX.XX --nolaunchpppd finished (pid 60), status = 0x0
Script ?? finished (pid 67), status = 0x0
Modem hangup
Connection terminated.

Declaring the HostNetwork boolean let's me see multiple interfaces shared from the host, so this is working but somehow im not able to establish a connection, i cant figure out why.
Perhaps there is a better solution? I will still need to establish a connection to the VPN-server but adding a routing record to the host may not be the best solution.
Any help is greatly appreciated!


text:
Q: How to access firefox web console command history? It is fairly easy to access the last 30 (!) javascript console commands in Google Chrome devtools:
Undock devtools and press Ctrl+Shift+I in it to inspect devtools itself.
In that new devtools window, type following commands in the console:
> location.origin
"chrome-devtools://devtools"
> JSON.parse(localStorage.consoleHistory).join('\n')
"inp.style.backgroundColor = "rgb(250, 0, 250)"
inp.style.backgroundColor = "rgb(250, 255, 250)"
...
inp.style.backgroundSize
inp.style.backgroundColor"
> JSON.parse(localStorage.consoleHistory).length
30

How can I do the equivalent in Firefox?
I wouldn't mind if it had a longer command history than google chrome.
That pastebin answer was only good for a day. So here it is again, thanks @msucan!
function getWebConsolePanel(tab) {
    var gDevTools = Cu.import("resource:///modules/devtools/gDevTools.jsm", {})\
.gDevTools;
    var tools = Cu.import("resource://gre/modules/devtools/Loader.jsm", {}).dev\
tools;
    var target = tools.TargetFactory.forTab(tab || gBrowser.selectedTab);
    var toolbox = gDevTools.getToolbox(target);
    var panel = toolbox.getPanel("webconsole");
    return panel;
}

getWebConsolePanel();

A: Updated instructions based on @msucan's answer

*

*Press F12 to open the web console

*Open the Developer Tools Settings (F1)

*Check "Enable browser chrome and add-on debugging toolboxes" and "Enable remote debugging"

*Open the Browser Toolbox (Ctrl-Alt-Shift-I) and click Ok.

*Copy/paste this code:

async function getWebConsolePanel(tab) {
  const { require } = ChromeUtils.import("resource://devtools/shared/loader/Loader.jsm");
  const devtools = require("devtools/client/framework/devtools").gDevTools;
  var toolbox = await devtools.getToolboxForTab(tab || gBrowser.selectedTab);
  var panel = toolbox.getPanel("webconsole");
  return panel;
}

*You can then access the history as an array using

*

*(await getWebConsolePanel()).hud.ui.wrapper.getStore().getState().history.entries;
(note: a web console needs to be open on the open tab)

Relevant links:
gDevTools is now a commonjs module. bugzilla discussion
How to get history from console panel
getHistoryEntries function definition

A: *

*Press F12 to open the developer toolbox (eg. the web console), then

*Switch to the Options panel.

*Enable chrome debugging.

*Open Scratchpad (Shift-F4).

*Copy/paste this code: https://pastebin.mozilla.org/3757211

*Go to Environment > Browser.

*Pick Execute > Display or Inspect.

And now you will see the web console history for the currently selected tab.


text:
Q: Is it possible to draw a rectangle over a charting element? I have some XAML like this drawing a scatterplot of a time series (X-Axis: DateTime, Y-Axis: Integer Value):
<Grid Name="chartgrid">
    <charting:Chart Name="scatterplot">
    </charting:Chart>
</Grid>

I am able to add a graphic object such as a line to this grid as one of its children but have to do so using X and Y coordinates that are different from the ones used by the chart control. Of course this is expected because the chart sets up its own axis.
The only approach I could think of is to add some dummy points to the graph as a different series but am hoping there is a better way to do this. Any suggestions?
EDIT: Added a figure to clarify further.

A: The only way I can think of is by examining the Virtual Tree looking for both axis objects.
Perhaps by using the VisualTreeHelper
Once you know their positions and their sizes combined with the scale information you can hopefully get from the chart control you could calculate the transformation from chart point to Silverlight coordinate.

A: Are you tying to adorn the Grid with a rectangle? If so why not using a border? ... (Sorry I dont have option to comment yet. Hence I asked you this question as an answer)

A: I would create an Adorner to do the actual drawing of your overlay stuff. Create this layer in your Chart control, or a class that encapsualtes both. And give the Chart class the proper Matrix or Transform to convert the given coordinates in your overlay objects to the current Chart transform. Also helpful is TransformToDescendant which allows you to convert a point from your chart for example, to your adorner.
I don't know what and how you transform the position on your chart IScrollInfo, RenderTransform etc. But with this information i think you can achieve what you are looking for.


text:
Q: How to set up prefix for steps method for whispering in Intellij If cucumber step definition starts with value, then IntelliJ doesn´t whisper code and we need to copy/paste it. Guys from team agreed to put some prefix unique for each method/process to help IntelliJ whisper. There is also condition that already existing steps which begins with value should be accepted as usual without any necessary code change.
I have tried to do something like code below to accept value or prefix with pipe but IntelliJ doesn´t whisper but code pass without error.
@Given("^DB:SQL UPDATE |.*, SQL UPDATE: (.*)$")
    public void update(String sql) throws SQLException {

        .......

We expect IntelliJ to whisper code using this prefix and others when writting step definintion like this:
Scenario Outline: Task list for team inbox filtered by org units

    Given Empty OrgUnits table, SQL UPDATE: DELETE FROM r_org_unit

A: SOLVED:
@And("^.*, SQL UPDATE: (.*)$")
@Then("^DB:SQL .*, SQL UPDATE: (.*)$")
    public void update(String sql) throws SQLException {

From now when you start writting code like
And up... IntelliJ will whisper you as well as
And DB... also whispering method
Thanks.


text:
Q: Starting List Item Workflow using Javascript on custom edit page I have a custom edit page with some Javascript inserted using a CEWP.
From this page I am calling a function to start a list item workflow on the current item being edited.
I am using the following common function held in a separate library:
function startWorkflow(itemId, subId) {
        var context = SP.ClientContext.get_current(),
            web = context.get_web(),
            wfServiceManager = SP.WorkflowServices.WorkflowServicesManager.newObject(context, web),
            subService = wfServiceManager.getWorkflowSubscriptionService().getSubscription(subId);

        context.load(subService);

        context.executeQueryAsync(function () {
            console.log("Subscription was loaded, attempting to start workflow.");
            if (itemId != null && itemId != '' && itemId != undefined) {
                var itemParam = {};
                wfServiceManager.getWorkflowInstanceService().startWorkflowOnListItem(subService, itemId, itemParam);
            } else {
                console.log("Item Id was not provided.  Ending function.");
                return;
            }

            context.executeQueryAsync(function () {
                console.log("Successfully started workflow.");
            }, function (sender, args) {
                console.log("Failed to start the workflow.");
                console.log("Error: " + args.get_message() + "\n" + args.get_stackTrace());
            });
        }, function (sender, args) {
            console.log("Failed to load the subscription.");
            console.log("Error: " + args.get_message() + "\n" + args.get_stackTrace());
        });
    };

The function is running as far as the first executeQueryAsync, but then the 'fail' callback is being invoked, returning the "Failed to load the subscription." console.log with the args.message() being "Unexpected response from server".
As part of my debugging I am calling the same function from a custom site page and this function runs as expected with the workflow successfully starting on the required list item.
So, my question(s) are:

*

*Is it possible to start a list item workflow on an item currently being 'edited'?

*If so, where is my code wrong?


text:
Q: Kendo UI MVVM - Changing Model not firing DataSource change event I have a Grid bound to a DataSource via MVVM.
I select a row in the Grid, accordingly I use this:
var grid = e.sender;
var rowSelected = grid.dataItem(grid.select());
this.set("currentAccount", rowSelected);

Where "currentAccount" holds the currently selected row. Also, "currentAccount" is bound to a Form to be edited by user.
Now, when I do changes on the form fields, they are not being automatically reflected on Grid. I need to call grid.refresh() for the changes to show on grid. With further debugging, I noticed that the datasource defined inside the viewmodel and that is used for Grid, is not firing it's Change event!
However, when user presses a button "Add new record", the following is used to create a new empty model inside the datasource, setting this new model returned by .add() function to be the "currentAccount":
var newRow = this.get("accRegDatasource").add( this._makeAccountModel( 0 ) );
this.set("currentAccount", newRow);
var row = input_map.grid().find(" tr[data-uid='" + newRow.uid + "']");
input_map.kendoGrid().select(row);

Above, I am adding a new empty row. Once I start editing the Form fields, automatically they are being reflected on the Grid without having to call grid.refresh. Even the datasource defined in the viewmodel is firing it's change event.
Any idea why this behavior?
Thanks


text:
Q: not found: type MultipleTextOutputFormat in spark scala I have a requirement to output the partitions based on the key. I'm trying using  MultipleTextOutputFormat.
I found this https://stackoverflow.com/a/26051042/6561443
but when I am trying to do the same in spark-shell I am getting the error.
scala> import org.apache.hadoop.io.NullWritable
import org.apache.hadoop.io.NullWritable

scala> import org.apache.spark._
import org.apache.spark._

scala> import org.apache.spark.SparkContext._
import org.apache.spark.SparkContext._

scala> import org.apache.hadoop.mapred.lib.MultipleTextOutputFormat
import org.apache.hadoop.mapred.lib.MultipleTextOutputFormat

scala> class RDDMultipleTextOutputFormat extends MultipleTextOutputFormat[Any, Any] {
        override def generateActualKey(key: Any, value: Any): Any =
          NullWritable.get()
             override def generateFileNameForKeyValue(key: Any, value: Any, name: String): String =
          key.asInstanceOf[String]
      }

<console>:11: error: not found: type MultipleTextOutputFormat
       class RDDMultipleTextOutputFormat extends MultipleTextOutputFormat[Any, Any] {
                                                 ^
<console>:13: error: not found: value NullWritable
           NullWritable.get()

If I submit this application with spark-submit ,I am getting
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1

Am I missing something here? Doesn't it work in spark-shell?

A: I've encountered the same issue.
Try to write
class RDDMultipleTextOutputFormat extends org.apache.hadoop.mapred.lib.MultipleTextOutputFormat[Any, Any] {

instead.
Worked for me. Don't know why.


text:
Q: Javascript and css animation How can I make an animation? When I press a button like Monday, the object with the correct color will move down, and if it is not the button pressed like "Tuesday" the previous object will move up and the correct object will move down. Thank you in advance
Here is the example of code..

function myFunction(myColor) {
  const square_day = document.getElementById("square")
  switch (myColor) {
    case "Monday":
      square_day.style.borderColor = "#ff7f98";
      square_day.style.backgroundColor = "#ff7f9880";
      square_day.style.animation = "square-to-circle 1s .83s"
      break
    case "Tuesday":
      square_day.style.borderColor = "#d7d77b";
      square_day.style.backgroundColor = "#d7d77b80";
      square_day.style.animation = "square-to-circle 1s .83s"
      break
  }
#square {
  height: 500px;
  width: 500px;
  position: relative;
  border-style: solid;
  border: 10px solid;
  background-color: grey;
  margin-left: auto;
  margin-right: auto;
  border-color: black;
  top: -700px;
}

@keyframes square-to-circle {
  0% {
    top: -700px
  }
  100% {
    top: 0px;
  }
}

      <button class="button" id="Monday" value="Monday" onclick="myFunction(this.value)">Monday</button>
      <button class="button" id="Tuesday" value="Tuesday" onclick="myFunction(this.value)">Tuesday</button>
      <button class="button" id="Wednesday" value="Wednesday" onclick="myFunction(this.value)">Wednesday</button>
      <button class="button" id="Thursday" value="Thursday" onclick="myFunction(this.value)">Thursday</button>
      <button class="button" id="Friday" value="Friday" onclick="myFunction(this.value)">Friday</button>
      <button class="button" id="Saturday" value="Saturday" onclick="myFunction(this.value)">Saturday</button>
      <button class="button" id="Sunday" value="Sunday" onclick="myFunction(this.value)">Sunday</button>

A: I wasn't sure if you planned on only using the one square or adding one for each day. It appeared you would have one for each day since you had it in a container. Here's an answer using one for each day.

function myFunction(myColor) {
  const squares = document.getElementsByClassName("square");

  for (let i = 0; i < squares.length; i++) {
    if (myColor == squares[i].id) {
      squares[i].style.transform = "translate(-50%, 20px)";
    } else {
      squares[i].style.transform = "translate(-50%, -700px)";
    }
    switch (myColor) {
      case "Monday":
        squares[0].style.borderColor = "#ff7f98";
        squares[0].style.backgroundColor = "#ff7f9880";
        break;
      case "Tuesday":
        squares[1].style.borderColor = "#d7d77b";
        squares[1].style.backgroundColor = "#d7d77b80";
        break;
      case "Wednesday":
        squares[2].style.borderColor = "purple";
        squares[2].style.backgroundColor = "violet";
        break;
      case "Thursday":
        squares[3].style.borderColor = "forestgreen";
        squares[3].style.backgroundColor = "green";
        break;
      case "Friday":
        squares[4].style.borderColor = "darkorange";
        squares[4].style.backgroundColor = "orange";
        break;
      case "Saturday":
        squares[5].style.borderColor = "blue";
        squares[5].style.backgroundColor = "lightblue";
        break;
      case "Sunday":
        squares[6].style.borderColor = "red";
        squares[6].style.backgroundColor = "pink";
        break;
    }
  }
}
.square {
  height: 500px;
  width: 500px;
  position: absolute;
  left: 50%;
  border-style: solid;
  border: 10px solid;
  background-color: grey;
  border-color: black;
  z-index: -1;
  transform: translate(-50%, -700px);
  transition: all 1s;
}

      <button class="button" id="Monday" value="Monday" onclick="myFunction(this.value)">Monday</button>
      <button class="button" id="Tuesday" value="Tuesday" onclick="myFunction(this.value)">Tuesday</button>
      <button class="button" id="Wednesday" value="Wednesday" onclick="myFunction(this.value)">Wednesday</button>
      <button class="button" id="Thursday" value="Thursday" onclick="myFunction(this.value)">Thursday</button>
      <button class="button" id="Friday" value="Friday" onclick="myFunction(this.value)">Friday</button>
      <button class="button" id="Saturday" value="Saturday" onclick="myFunction(this.value)">Saturday</button>
      <button class="button" id="Sunday" value="Sunday" onclick="myFunction(this.value)">Sunday</button>

EDIT: Adding another option for just using one square element

const square = document.getElementById("square");

function myFunction(myColor) {
  const squareBounds = square.getBoundingClientRect();
  if (squareBounds.top < 0) {
    changeColor(myColor);
  } else {
    square.style.transform = "translate(-50%, -700px)";
    setTimeout(changeColor, 500, myColor);
  }
}

function changeColor(myColor) {
  switch (myColor) {
    case "Monday":
      square.style.borderColor = "#ff7f98";
      square.style.backgroundColor = "#ff7f9880";
      break;
    case "Tuesday":
      square.style.borderColor = "#d7d77b";
      square.style.backgroundColor = "#d7d77b80";
      break;
    case "Wednesday":
      square.style.borderColor = "purple";
      square.style.backgroundColor = "violet";
      break;
    case "Thursday":
      square.style.borderColor = "forestgreen";
      square.style.backgroundColor = "green";
      break;
    case "Friday":
      square.style.borderColor = "darkorange";
      square.style.backgroundColor = "orange";
      break;
    case "Saturday":
      square.style.borderColor = "blue";
      square.style.backgroundColor = "lightblue";
      break;
    case "Sunday":
      square.style.borderColor = "red";
      square.style.backgroundColor = "pink";
      break;
  }
  setTimeout(dropDown, 500, square);
}

function dropDown(square) {
  square.style.transform = "translate(-50%, 20px)";
}
.square {
  height: 500px;
  width: 500px;
  position: absolute;
  left: 50%;
  border-style: solid;
  border: 10px solid;
  background-color: grey;
  border-color: black;
  z-index: -1;
  transform: translate(-50%, -700px);
  transition: all 1s;
}

      <button class="button" id="Monday" value="Monday" onclick="myFunction(this.value)">Monday</button>
      <button class="button" id="Tuesday" value="Tuesday" onclick="myFunction(this.value)">Tuesday</button>
      <button class="button" id="Wednesday" value="Wednesday" onclick="myFunction(this.value)">Wednesday</button>
      <button class="button" id="Thursday" value="Thursday" onclick="myFunction(this.value)">Thursday</button>
      <button class="button" id="Friday" value="Friday" onclick="myFunction(this.value)">Friday</button>
      <button class="button" id="Saturday" value="Saturday" onclick="myFunction(this.value)">Saturday</button>
      <button class="button" id="Sunday" value="Sunday" onclick="myFunction(this.value)">Sunday</button>

EDIT: Adding alpha to background

let m = { Monday: 0, alpha: 0 };
let t = { Tuesday: 0, alpha: 0 };
let w = { Wednesday: 0, alpha: 0 };
let th = { Thursday: 0, alpha: 0 };
let f = { Friday: 0, alpha: 0 };
let s = { Saturday: 0, alpha: 0 };
let su = { Sunday: 0, alpha: 0 };
let arr = [m, t, w, th, f, s, su];

function myFunction(myColor) {
  const squares = document.getElementsByClassName("square");
  for (let i = 0; i < squares.length; i++) {
    if (myColor == squares[i].id) {
      squares[i].style.transform = "translate(-50%, 20px)";
    } else {
      squares[i].style.transform = "translate(-50%, -700px)";
    }
    if (arr[i].hasOwnProperty(myColor)) {
      arr[i].alpha = 0;
    } else {
      arr[i].alpha = 1;
    }

    switch (myColor) {
      case "Monday":
        squares[0].style.borderColor = "#ff7f98";
        squares[0].style.backgroundColor = "rgba(0, 150, 15," + m.alpha + ")";
      case "Tuesday":
        squares[1].style.borderColor = "#d7d77b";
        squares[1].style.backgroundColor = "rgba(0, 255, 255," + t.alpha + ")";
      case "Wednesday":
        squares[2].style.borderColor = "purple";
        squares[2].style.backgroundColor = "rgba(190, 0, 237," + w.alpha + ")";
      case "Thursday":
        squares[3].style.borderColor = "forestgreen";
        squares[3].style.backgroundColor = "rgba(0, 150, 15," + th.alpha + ")";
      case "Friday":
        squares[4].style.borderColor = "darkorange";
        squares[4].style.backgroundColor = "rgba(209, 160, 0," + f.alpha + ")";
      case "Saturday":
        squares[5].style.borderColor = "blue";
        squares[5].style.backgroundColor = "rgba(38, 237, 255," + s.alpha + ")";
      case "Sunday":
        squares[6].style.borderColor = "red";
        squares[6].style.backgroundColor = "rgba(255, 77, 249," + su.alpha + ")";
    }
  }
}
.square {
  height: 500px;
  width: 500px;
  position: absolute;
  left: 50%;
  border-style: solid;
  border: 10px solid;
  border-color: black;
  z-index: -1;
  transform: translate(-50%, -700px);
  transition: all 2s;
}

      <button class="button" id="Monday" value="Monday" onclick="myFunction(this.value)">Monday</button>
      <button class="button" id="Tuesday" value="Tuesday" onclick="myFunction(this.value)">Tuesday</button>
      <button class="button" id="Wednesday" value="Wednesday" onclick="myFunction(this.value)">Wednesday</button>
      <button class="button" id="Thursday" value="Thursday" onclick="myFunction(this.value)">Thursday</button>
      <button class="button" id="Friday" value="Friday" onclick="myFunction(this.value)">Friday</button>
      <button class="button" id="Saturday" value="Saturday" onclick="myFunction(this.value)">Saturday</button>
      <button class="button" id="Sunday" value="Sunday" onclick="myFunction(this.value)">Sunday</button>


text: Q: Find $k$ s.t. $\mathbb{A}^{2}_{k}\to \mathbb{A}^{1}_{k}$ is not closed. Let $k$ be a field and let $f:\mathbb{A}^{2}_{k}\to \mathbb{A}^{1}_{k}$ be a map between affine scheme induced by natural inclusion $i:k[Y]\hookrightarrow k[X, Y]$, $Y\mapsto Y$. I want to show that this map is not a closed map in general, but I don't know how to find such counterexample. First, I tried to find a maximal ideal $\mathfrak{m}\subset k[X, Y]$ s.t. $i^{-1}(\mathfrak{m})=\mathfrak{m}\cap k[Y]\subset k[Y]$ isn't a maximal ideal, which shows that $f$ maps the closed point $\mathfrak{m}_{x}\in \mathbb{A}^{2}_{k}$ to some non-closed point $i^{-1}(\mathfrak{m})_{x}$. However, there's no such example if $k$ is algebraically closed by Hilbert's Nullstellensatz. So I tried to find such example when $k=\mathbb{R}$ or $k=\mathbb{F}_{p}$, but I don't know well how maximal ideals of $k[X, Y]$ looks like in these cases.


text:
Q: Node.js + MongoDB: Generating shorter ID I would like to create forum script with Node.js and MongoDB, but I have a problem with IDs which are pretty long in Mongo's case. I was already searching for solution, but I didn't find anything except the posts in which is written that I need to create ID's myself. I know more about PHP and MySQL, but I need Node for some realtime application in addition of forum. I would use generated ID for identifyng forum post, and next to it it would be thread's title - like this: address.domain/1/my-new-thread.
What do you recommend me?

A: I've used mongoose-pureautoinc and it works without problems.


text: Q: Recommendation on addressing custom routing in elasticsearch We have been using Elasticsearch for long and have come to a point where we need to do some custom routing. To place the problem in context, in one of the most important index, among many fields in a document, there are 2 fields lets call them eventkind and user. Now as it is many users are associated to a single eventkind and many eventkind to single user. Due to some requirements now we have opposing requirements and faces a issue on how to design the custom reading. If we using eventkind for routing, that will make the user spread out in many shards and hence a query that is based on user is slower and vice-versa. Would like to get some recommendation and thoughts on how one can address this.


text:
Q: C# - Odd Null Reference Exception during testing, why does this happen? This references my last question which appears to have been abandoned. I am experiencing an odd "bug" if you will with C# and MS VS 2015. To reproduce the error, follow the steps:

*

*Open console app project and copy paste code below.

*Set a break point here:

*First run code past break point, it works! :D

*Then run code again but this time STOP at the break point and DRAG the executing statement cursor INTO the if statement from here:

to here:

Hit Continue and an NRE exception is thrown. Why does this happen? Is it just me? What is the technical explination for this?
CODE:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace testapp
{
    class Program
    {
        static void Main(string[] args)
        {
            FILECollection randomCollection = new FILECollection();
            // Fill with junk test data:
            for(int i = 0; i<10; i++)
            {
                FILE junkfile = new FILE() { fileName = i.ToString(), folderName = i.ToString(), fileHashDigest = new byte[1] };
                randomCollection.Add(junkfile);
            }

            if (true)
            {
                Console.WriteLine("testing this weird exception issue...");
                FILE test;
                test = new FILE();
                test.fileName = "3";
                test.folderName = "3";
                test.fileHashDigest = new byte[1];

                FILE exists = randomCollection.Where(f => f.fileName == test.fileName &&
                                              f.fileHashDigest.SequenceEqual(test.fileHashDigest)).First();
            }
        }
    }

    public class FILE
    {
        public FILE() { _fileName = "";}
        private string _fileName;
        public string fileName
        {

            get
            {
                    if (false)
                        return this._fileName.ToUpper();
                    else
                        return this._fileName;
            }
            set
            {

                    if (false)
                        this._fileName = value.ToUpper();
                    else
                        this._fileName = value;
            }
        }
        public string folderName { get; set; }
        public byte[] fileHashDigest { get; set; }
    }

    public class FILECollection : IEnumerable<FILE>, ICollection<FILE>
    {
        private HashSet<FILE> svgHash;
        private static List<FILE> PreallocationList;
        public string FileName = "N/A";

        /// <summary>
        /// Default Constructor, will not
        /// preallocate memory.
        /// </summary>
        /// <param name="PreallocationSize"></param>
        public FILECollection()
        {
            this.svgHash = new HashSet<FILE>();
            this.svgHash.Clear();
        }

        /// <summary>
        /// Overload Constructor Preallocates
        /// memory to be used for the new
        /// FILE Collection.
        /// </summary>
        public FILECollection(int PreallocationSize, string fileName = "N/A", int fileHashDigestSize = 32)
        {
            FileName = fileName;
            PreallocationList = new List<FILE>(PreallocationSize);
            for (int i = 0; i <= PreallocationSize; i++)
            {
                byte[] buffer = new byte[fileHashDigestSize];
                FILE preallocationSVG = new FILE()
                {
                    fileName = "",
                    folderName = "",
                    fileHashDigest = buffer
                };
                PreallocationList.Add(preallocationSVG);
            }
            this.svgHash = new HashSet<FILE>(PreallocationList);
            this.svgHash.Clear(); // Capacity remains unchanged until a call to TrimExcess is made.
        }

        /// <summary>
        /// Add an FILE file to
        /// the FILE Collection.
        /// </summary>
        /// <param name="svg"></param>
        public void Add(FILE svg)
        {
            this.svgHash.Add(svg);
        }

        /// <summary>
        /// Removes all elements
        /// from the FILE Collection
        /// </summary>
        public void Clear()
        {
            svgHash.Clear();
        }

        /// <summary>
        /// Determine if the FILE collection
        /// contains the EXACT FILE file, folder,
        /// and byte[] sequence. This guarantees
        /// that the collection contains the EXACT
        /// file you are looking for.
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool Contains(FILE item)
        {
            return svgHash.Any(f => f.fileHashDigest.SequenceEqual(item.fileHashDigest) &&
                                    f.fileName == item.fileName &&
                                    f.folderName == item.folderName);
        }

        /// <summary>
        /// Determine if the FILE collection
        /// contains the same file and folder name,
        /// byte[] sequence is not compared. The file and folder
        /// name may be the same but this does not guarantee the
        /// file contents are exactly the same. Use Contains() instead.
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool ContainsPartially(FILE item)
        {
            return svgHash.Any(f => f.fileName == item.fileName &&
                                    f.folderName == item.folderName);
        }

        /// <summary>
        /// Returns the total number
        /// of FILE files in the Collection.
        /// </summary>
        public int Count
        { get { return svgHash.Count(); } }

        public bool IsReadOnly
        { get { return true; } }

        public void CopyTo(FILE[] array, int arrayIndex)
        {
            svgHash.CopyTo(array, arrayIndex);
        }

        public bool Remove(FILE item)
        {
            return svgHash.Remove(item);
        }

        public IEnumerator<FILE> GetEnumerator()
        {
            return svgHash.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return svgHash.GetEnumerator();
        }
    }
}

I think either I am debugging in a terribly wrong way, or Microsoft should take a look at this. It's like future code is breaking current code...which is impossible!

A: OK here's my best guess..
First, as I mentioned in the comments, the exception doesn't occur if you comment out the line FILE exists = randomCollection.Where(f => f.fileName == test.fileName && f.fileHashDigest.SequenceEqual(test.fileHashDigest)).First();
Second, I noticed the same behavior can be reproduced with the following code:
if (true)
{
    object o;
    o = new object();
    Func<bool> m = () => o == null;
}

i.e. the cause seems to be related to the variable being used in a lambda expression. So, looking at the same code snippet above in ILSpy I get the following:
Program.<>c__DisplayClass0_0 <>c__DisplayClass0_ = new Program.<>c__DisplayClass0_0();
<>c__DisplayClass0_.o = new object();
Func<bool> func = new Func<bool>(<>c__DisplayClass0_.<Main>b__0);

so my best guess is that the NullReferenceException refers to <>c__DisplayClass0_ intance being null - and I'm therefore inclined to believe that the stepping through the if(true) actually skipped the first line where <>c__DisplayClass0_ is instantiated


text:
Q: How can I copy files by modified date using terminal? I am attempting to copy files based on their modified date, as the file names do not include the date in them. Coincidentally, the files are the 22 newest files in the directory, so if I run the command ls -lt | head -22, the outputted files are exactly what I want to copy.
I had read this thread here, but the accepted answer didn't seem to work in Terminal, and it isn't exactly filtering by date, just by head.
I am running macOS Sierra 10.12.5.

A: The way to go for this kind of task, is to use find :
find ./dir -mtime -10 -type f -exec cp {} ./another_dir/ \;

Replace -mtime -10 (last 10 days) by what you expect.
And PLEASE, don't parse ls output. Check http://mywiki.wooledge.org/ParsingLs

A: $ cp `ls -1t | head -22` /destination/dir


text:
Q: Vertices dominating over a particular vertex in the graph
In the above graph, which vertices dominating over vertex 6?

A: Answer is 0,1,2,3,4,5.
A vertex A is said to be dominating over vertex B, only if there is path from the entry node to B that is going through vertex A. In above question, only vertex 7 cannot lie in the path from any source vertex to destination,that is vertex 6.