text:
Q: Visual C++: Invalid allocation size. Why is this happening? Im the process of learning C++. I got stuck debugging some of my code on VC++, with the following error-
Debug Error
*path to filename.exe*
Invalid allocation size:429496723 bytes.

The error precisely occurs when the debugger reaches the following block: EDIT: Ive added the entire main function to help check if maxlen is taking on any unexpected values(none that I notice though)
int main(){

    vector <Student_info> students;

    Student_info record;

    string::size_type maxlen=0;// length of the longest name

    //read and store all the students data.

    //maxlen contains the length of the name of the longest student.

    while (read(cin,record)){
    // find the length of the longest name
        max(maxlen,record.name.size());
        //add the student record to the vector.

        students.push_back(record);
    }
    //arrange the records alphabetically.
    sort(students.begin(),students.end(),compare);// this may look weird but the fact that the names have to be compared is checked using the predicate.

        //write out the names and grades.

        for(vector<Student_info>::size_type i =0;i!=students.size();i++){

            //padding to ensure that there is vertical alignment.
            cout<<students[i].name<<string(maxlen+1-students[i].name.size(),' ');// debugger stops here!
            //compute grade.
            try{
                double final_grade=grade(students[i]);
                streamsize prec=cout.precision();
                cout<<setprecision(3)<<final_grade<<setprecision(prec);
            }
            catch(domain_error e){
            //catch error if hw vector is empty!

                e.what();

            }
            cout<<endl;

            }
        return 0;
        }

A: You might look at the line:
max(maxlen,record.name.size());

Is it possible that you meant:
maxlen = max(maxlen,record.name.size());

A: You're never assigning a value to maxlen after initliazing it to 0.  Then later you're subtracting 1 from that giving a negative offset.
Inside your first while loop you probably want...
   maxlen = max( maxlen, record.name.size() );


text:
Q: Conflict between onCLick() and swipe left/right in ViewPager I'm facing a problem regarding a ViewPager that hosts multiple fragments.
The ViewPager's horizontal swipe is working very well when I'm swipping left/right.
The thing is I have a menu that should appear if I click anywhere in a fragment. The problem is when I'm adding an onClick() event inside the fragment, the ViewPager swiping become particularly inaccurate, and it's hard to swipe between fragments by now. Indeed, the onClick() event is fired instead of detecting a swipe.
Then, I have a lot of false/positive when I'm trying to switch between fragments.
Do you have an idea of workaround for this?
Maybe I can intercept the touch event before it reaches the fragment when a beginning of swipe is detected?
I hope my question is enough clear for you, don't hesitate to ask details.
Regards,

A: It happened on me when i have TextViews inside ViewPager Fragment with
android:gravity="center_horizontal"
android:singleLine="true"

I had to change singleLIne to android:maxLines="1"

A: I often use ViewPager with Jake Wharton's ViewPager Indicator. I have to see I never encounter the problem you said.
The viewpager has a good implementation to identify click gesture and swiping gesture.
Maybe you'd better provide some code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: LockerService issue with Safari, Component not accessible in debugger Component:
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />

Controller:
    doInit : function(component, event, helper) {

       console.log(component);
       debugger;
    },

Safari Debugger presents error on component, and when used for doing more complex functions, fails. This is present on desktop, iPhone and simulator Safari.

A: For any future readers.. this has been fixed a while ago in a patch and the Safari debugger should now log LockerService objects without errors.


text:
Q: Accessing a data.frame subset by specific dates generates NA I have a data.frame where each column contains the monthly returns on various stocks since 2014 and the first column contains the observation date. I need to access the returns for those stocks on specific dates (say 2018-01-31, or between 2014-02-03 and 2018-01-01) in order to compute several statistics. The data set looks like:
       Date           aer  api            ar           ccj           cve          fcu
2014-02-20  0.1114229582 <NA>  0.0274509804  0.0458167331 -0.0684382963  0.245283019
2014-02-21  0.1486823856 <NA>  0.0364592781  0.0434139122 -0.0666423889  0.196261682
2014-02-24  0.1714285714 <NA>  0.0701561065  0.0552788845 -0.0488694384  0.284313725
2014-02-25  0.1584653878 <NA>  0.0585154416  0.1024531025 -0.0465631929  0.317307692

When I calculate the covariance matrix for the returns on specific date ranges, the assignment works correctly. However, when I try to perform the same operation for one particular date in order to multiply that row of returns by another vector I get NAs
library(timeSeries)
library(quantmod)
library(PerformanceAnalytics)
library(ggplot2)
library(caTools)
library(dplyr)
library(portfolio)
library(fBasics)
library(zoo)

data.returns$Date<-as.Date(data.returns$Date,format="%Y-%m-%d")
data.returns_m$Date<-as.Date(data.returns_m$Date,format="%Y-%m-
%d")
# defining monthly dates to compute returns
date_enddec17<-as.Date("2017-12-29")
date_endjan18<-as.Date("2018-01-31")
date_endfeb18<-as.Date("2018-02-28")
date_endmar18<-as.Date("2018-03-29")
date_endapr18<-as.Date("2018-04-30")
date_endmay18<-as.Date("2018-05-31")
date_endjun18<-as.Date("2018-06-29")
date_endjul18<-as.Date("2018-07-31")
date_endaug18<-as.Date("2018-08-31")
date_endsep18<-as.Date("2018-09-28")
date_endoct18<-as.Date("2018-10-31")
date_endnov18<-as.Date("2018-11-30")
date_enddic18<-as.Date("2018-12-31")

date_list <- c(date_enddec17, date_endjan18, date_endfeb18,
date_endmar18, date_endapr18, date_endmay18, date_endjun18,
           date_endjul18, date_endaug18, date_endsep18,
date_endoct18, date_endnov18, date_enddic18)

# initialising the lists for the statistics
Covariance <- list()
W_gmv <- list()
ret_m <- list()

# for loop to calculate the statistics for each date
local <- 0
for (i in date_list) {
  local <- local + 1
  Covariance[[local]] <-
cov(na.omit(data.returns[data.returns$Date>=i-365*4 &
data.returns$Date<=i,2:ncol(data.returns)]))
      W_gmv[[local]<-  (solve(Covariance[[local]])%*%e)%*%solve(t(e)%*%solve(Covariance[[local]])%*%e)

      ret_m[[local]] <- 1 + t(as.matrix(as.numeric(data.returns_m[data.returns_m$Date==i+30,-1]))) %*%W_gmv[[local]]

}

I expected to obtain a list (ret_m) with 13 numbers, each of them representing the monthly return for that specific date, instead I got a list of 13 NAs. Surprisingly this didn't happen with the covariance calculation (first command in the loop), which worked perfectly fine.

A: If you just want monthly returns, have you tried quantmod::monthlyReturn()?
If your data is in a dataframe you might need to convert it to an xts object first. The timekt package is helpful to convert from data frames to xts objects, or other way around. Try this:
library(timekt)
my_xts <- timekt::tk_xts(my_dataframe)
quantmod::monthlyReturn(my_xts$ar)


text:
Q: Let PayPal Express Checkout verify the Address We are using PayPal Express checkout (it's API) to let customers checkout products in our shop and add the delivery address at the same time.
We only ship to Germany and when a customer checks out, returns to our page and we get to know vie the PayPal API his address is not in Germany, we don't capture the authorized payment. Sometimes however, customers try to trick us and write AT-1234 in the zip field, to indicate they want shipping to austria. They let the country field with the "Germany" value.
Is it possible to let PayPal validate the Address during Express Checkout, such that invalid zip codes cannot be added?

A: You could the AddressVerify API to check the postal code and postal address.  You can find more on this in the developers guide at https://www.x.com/sites/default/files/pp_nvpapi_developerguide.pdf on page 25.  Another option that I have seen merchants implement is the Callback API along with Express Checkout.  Information on this is found in the same guide on page 55.  This allows you to update the PayPal Review page with shipping options, insurance, and tax information during the checkout.  You can also generate a message that gets displayed that states you do not ship to that location.  Some merchants will also tie this in with 3rd party shipping provider API, so that they can calculate real time shipping charges based on the type of shipping the buyer selected.
Hope this helps you out!


text:
Q: How to get value from radio button dynamically i am creating a form for searching a client, using either id or email both are set to be unique. Application made on Codeignitor.

*

*I have created a form with two radio buttons, one for search with ID and another for search with mail+dob.

*Depending on the radio button selected, corresponding input fields shown.

*In controller, it choose the model function based on the radio button value.

This is I coded, i need to pass the value of radio button to Controller.php file
Form(only included the radio button)

$(document).ready(function() {
  $("#usingdob").hide();
  $("#usingmail").hide();
  $("input:radio").click(function() {
    if ($(this).val() == "id") {
      $("#usingId").show();
      $("#usingdob").hide();
      $("#usingmail").hide();

    } else {
      $("#usingId").hide();
      $("#usingdob").show();
      $("#usingmail").show();
    }
  });
});

<input  type="radio" name="optradio" value="id" checked>Using ID

<input  type="radio" name="optradio" value="mail">Using DOB

I expected to get the radio button value correctlyenter image description here

A: JS:
$('input[name="optradio"]').click(function(){
    var optradio = $(this).val();
    //or
    var optradio = $("input[name='optradio']:checked").val();
    if(optradio == 'id'){
      //do your hide/show stuff
    }else{
      //do your hide/show stuff
    }
});
//on search button press call this function
function passToController(){
   var optradio = $("input[name='optradio']:checked").val();
   $.ajax({
    beforeSend: function () {
    },
    complete: function () {
    },
    type: "POST",
    url: "<?php echo site_url('controller/cmethod'); ?>",
    data: ({optradio : optradio}),
    success: function (data) {

    }
   });
}

A: Try this

A: One thing I noticed is that you have 'mail' as a value in the DOB option. Another is that there seems to be 3 options and yet you only have 2 radios?
I adjusted the mail value to dob and created dummy divs to test the code. It seems to work.

$(document).ready(function() {
  $("#usingdob").hide();
  $("#usingmail").hide();
  $("input:radio").click(function() {
    console.log($(this).val());
    if ($(this).val() == "id") {
      $("#usingId").show();
      $("#usingdob").hide();
      $("#usingmail").hide();
    } else {
      $("#usingId").hide();
      $("#usingdob").show();
      $("#usingmail").show();
    }
  });
});

<input  type="radio" name="optradio" value="id" checked>Using ID

<input  type="radio" name="optradio" value="dob">Using DOB

  Using Id div

  Using dob div

  Using mail div

As far as passing the value to the controller goes, ideally the inputs should be in a form. When you submit the form, the selected value can be passed to the php.
<?php
if (isset($_POST['submit'])) {
    if(isset($_POST['optradio']))
    {
       Radio selection is :".$_POST['optradio'];  // Radio selection
    }
?>

A: If you want to get currently checked radio button value Try below line which will return current radio button value
var radioValue = $("input[name='gender']:checked").val();
if(radioValue)
{
alert("Your are a - " + radioValue);
}


text:
Q: Please explain this example of Rosen's book In Kenneth Rosen's book example number 13 of Chapter 1.5 says,
There is a woman who has taken a flight on every airlines
In the example the solution is like this:
Let $P(w,f)$ $:$ $w$ has taken $f$
$Q(f,a)$ $:$ $f$ is a flight in $a$
And the answer is $∃w∀a∃f(P(w,f)∧Q(f,a))$
My question is why the answer is not $∃w∀a∃f(Q(f,a)\to P(w,f))$?
What is the difference between these two answers? Please explain.

A: The issue is that $Q(f,a) \rightarrow P(w,f)$ is a weaker statement than $Q(f,a) \land P(w,f)$; in particular, the first statement is true if $Q(f,a)$ is false regardless of whether $P(w,f)$ is true or not. This prevents it from matching up with the verbal statement.
For example, you could have a woman $w$ who has never taken a flight by some particular airline $a$, but since there exists a flight $f$ that is on some other airline, $Q(f,a) \rightarrow P(w,f)$ is true, so this woman could satisfy your logical statement but not Rosen's, and not the verbal statement.
In fact, as long as there are flights on at least two airlines, every woman would satisfy $\forall a \exists f (Q(f,a) \rightarrow P(w,f))$.


text: Q: How to scale a form to full screen using WebView? I have a form that only takes up a small portion of the page it is on, so in webview it has huge gaps and I need it to be full screen. I figured out how to scale it by zooming to my device but the problem is I need to use this app on multiple devices with many potential screen resolutions. My final goal is to have the form be full screen on any device as soon as you open the app.


text:
Q: Download files from the web server by java
*

*I would like to download the temp files from an web server

*The code i tried is below, but i am getting only the HTML content being written the ouput file

*But the url path contains 712 files in .gz format

This is the code I am using:
import java.io.*;

public class SampleFile{
    public static void main(String args[]) throws IOException{
        BufferedInputStream in = new BufferedInputStream(new java.net.URL("http://xxx:9080/xxx/xxx/xxx/xxx/xxx.jsp?file=/apps/WasApps/xxx/templogs/xxx.log.xxx_Server1.2012-04-01.gz").openStream());
        FileOutputStream fos = new FileOutputStream("LocalPath\\koushik.txt");
        BufferedOutputStream bout = new BufferedOutputStream(fos,1024);

        int x=0;
        byte[] data = new byte[1024];
        while((x=in.read(data,0,1024))>=0) {
            bout.write(data,0,x);
        }

        bout.close();
        in.close();
    }
}


text:
Q: Изменение данных в текстовом поле, от выбранного пункта из списка В общем суть проблемы такая у меня есть список
<select>
  <option>Вариант 1</option>
  <option>Вариант 2</option>
</select>
и есть поле
<input type="text" value="50$" disabled />
проблема в общем в том что от выбора значения из списка меняется сумма в текстовом поле.
Кто что предложит? =)
A: <select id="myselect"> <option value="1">Вариант 1</option> <option value="2">Вариант 2</option> </select>
<input type="text" value="50$" id="mytext" disabled />

//Для jquery сами разберетесь
    function $(id){
      return document.getElementById(id);
    }

$('myselect').onchange = function(){
  switch($('myselect').value){
    case '1': $('mytext').value=20; break;
    case '2': $('mytext').value=30; break;
    case '3': $('mytext').value=100500; break;
  }
}


text:
Q: Javascript is not working in animation on scroll I am trying to make the  elements appears using the Animation on Scroll (AOS) feature.
I tried downloading the JS and CSS files and linking them locally, tried using different animation names, used it on the images and div tags.
I think the problem is in the linking or the JS file. unfortunately I'm not an expert in JS.
This is the HTML file

<link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">

© All rights are reserved .


text:
Q: Is it possible to invert Jquery selectors to include everything except this? In Jquery if you want to select something you can use various combinations of selector. Is is possible to invert this selection?
var item = $('#someitemparent').html($('#someitem'));

Is it possible to invert this to everything thing else but not #someitem?

....

... otheritems

A: Use .not() or :not()
var item = $('.someitem').not('#notme');

var item = $('*').not('#notme');


text:
Q: Javafx: update TableCell I have a TableView and a custom MyTableCell extends CheckBoxTreeTableCell<MyRow, Boolean>, In this cell is @Overridden the updateItem method:
@Override
public void updateItem(Boolean item, boolean empty) {
    super.updateItem(item, empty);
    if(!empty){
        MyRow currentRow = geTableRow().getItem();
        Boolean available = currentRow.isAvailable();
        if (!available) {
            setGraphic(null);
        }else{
            setGraphic(super.getGraphic())
        }
    } else {
        setText(null);
        setGraphic(null);
    }
}

I have a ComboBox<String> where I have some items, and when I change the value of that combobox I want to set the visibility of the checkboxes depending on selected value. So I have a listener:
comboBox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
        if (newValue.equals("A") || newValue.equals("S")) {
            data.stream().filter(row -> row.getName().startsWith(newValue)).forEach(row -> row.setAvailable(false));
        }
    });

*

*The data is an ObservableList<MyRow>

*This is just an example and a simplified version of my code

When I change the value in comboBox the table's the chekboxes don't disappear until I scroll or click on that cell. There is a "sollution" to call table.refresh(); but I don't want to refresh the whole table, when I want to refresh just one cell. So I tried to adding some listeners to trigger the updateItem, but I failed at every attempt. Do you have any idea how can I trigger the update mechanism for one cell, not for the whole table?

A: Bind the cell's graphic, instead of just setting it:
private Binding<Node> graphicBinding ;

@Override
protected void updateItem(Boolean item, boolean empty) {
    graphicProperty().unbind();
    super.updateItem(item, empty) ;

    MyRow currentRow = getTableRow().getItem();

    if (empty) {
        graphicBinding = null ;
        setGraphic(null);
    } else {
        graphicBinding = Bindings
            .when(currentRow.availableProperty())
            .then(super.getGraphic())
            .otherwise((Node)null);
        graphicProperty.bind(graphicBinding);
    }
}


text:
Q: how to imported jupyter notebook which also imported the other notebook? I have 3 jupyter notebooks. The 2nd one import the first one. The 3rd one import the 2nd one.
I installed ipynb and used the below codes the import previous notebook.
Running 2nd notebook is fine with imported data and plot from 1st notebook. However when I run the 3rd notebook, the error says:
ImportError: Could not import 2ndnotebook.ipynb for ipynb.fs.full.RCA_2ndnotebook: not a valid ipynb file
what is the reason? Thanks for your help.
from ipynb.fs.full.firstnotebook import *

The detail errors are:
UnicodeDecodeError                        Traceback (most recent call last)
~\miniconda3\envs\tf_cpu\lib\site-packages\ipynb\fs\full\__init__.py in get_code(self, fullname)
     28                 try:
---> 29                     nb = json.load(f)
     30                 except ValueError:

~\miniconda3\envs\tf_cpu\lib\json\__init__.py in load(fp, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    292     """
--> 293     return loads(fp.read(),
    294         cls=cls, object_hook=object_hook,

~\miniconda3\envs\tf_cpu\lib\encodings\cp1252.py in decode(self, input, final)
     22     def decode(self, input, final=False):
---> 23         return codecs.charmap_decode(input,self.errors,decoding_table)[0]
     24

UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 11976754: character maps to <undefined>

During handling of the above exception, another exception occurred:

ImportError                               Traceback (most recent call last)
<ipython-input-5-678a15847c0e> in <module>
----> 1 from ipynb.fs.full.2ndnotebook import *

~\miniconda3\envs\tf_cpu\lib\site-packages\ipynb\fs\full\__init__.py in get_code(self, fullname)
     30                 except ValueError:
     31                     # This is when it isn't a valid json file
---> 32                     raise ImportError('Could not import {path} for {fn}: not a valid ipynb file'.format(
     33                         path=self.path,
     34                         fn=fullname

ImportError: Could not import 2ndnotebook.ipynb for ipynb.fs.full.2ndnotebook: not a valid ipynb file


text:
Q: How do I add an array as an Object Property to a class declared within a PHP extension? I want my PHP extension to declare a class equivalent to the following PHP:
class MyClass
{
    public $MyMemberArray;

    __construct()
    {
        $this->MyMemberArray = array();
    }
}

I'm following the examples in "Advanced PHP Programming" and "Extending and Embedding PHP" and I'm able to declare a class that has integer properties in PHP_MINIT_FUNCTION.
However, when I use the same approach to declare an array property in PHP_MINIT_FUNCTION, I get the following error message at runtime:
PHP Fatal error:  Internal zval's can't be arrays, objects or resources in Unknown on line 0

There's an example on page 557 of Advanced PHP Programming of how to declare a constructor which creates an array property, but the example code doesn't compile (the second "object" seems to be redundant).
I fixed the bug and adapted it to my code:
PHP_METHOD(MyClass, __construct)
{
    zval *myarray;
    zval *pThis;

    pThis = getThis();

    MAKE_STD_ZVAL(myarray);

    array_init(myarray);
    zend_declare_property(Z_OBJCE_P(pThis), "MyMemberArray", sizeof("MyMemberArray"), myarray, ZEND_ACC_PUBLIC TSRMLS_DC);
}

And this compiles, but it gives the same runtime error on construction.

A: The answer is to use add_property_zval_ex() in the constructor, rather than zend_declare_property().
The following works as intended:
PHP_METHOD(MyClass, __construct)
{
    zval *myarray;
    zval *pThis;

    pThis = getThis();

    MAKE_STD_ZVAL(myarray);

    array_init(myarray);
    add_property_zval_ex(pThis, "MyMemberArray", sizeof("MyMemberArray"), myarray);
}


text:
Q: Strange COM interop exception 0x80005000 using System.DirectoryServices.AccountManagement libraries I'm trying to write something that (amongst other things) adds a user to an AD group - using VS2010, .Net4 and the library facilities in System.DirectoryServices.AccountManagement.
I've gotten a user and group by code like the sample below, and this works for other operations like enabling or disabling accounts.
group = System.DirectoryServices.AccountManagement.GroupPrincipal.FindByIdentity(_UserContext, Name);

user = System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(_UserContext, Name);

Now, trying to add the user to the group like:
group.Members.Add(user);

I get an error with a stack trace beginning like the one listed below with a COM interop error 0x80005000 (unknown).  This also happens with other users and on 32 and 64 bit builds.  Searching this on the web comes up with a few forum questions, but I can't find any answers.  In theory, this should work - this codeproject sample is doing much the same thing.
Has anyone seen this error or have any idea what might have caused it?
Stack trace top:
Unhandled Exception: System.DirectoryServices.AccountManagement.PrincipalOperati
onException: Unknown error (0x80005000) ---> System.Runtime.InteropServices.COME
xception: Unknown error (0x80005000)
   at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
   at System.DirectoryServices.DirectoryEntry.Bind()
   at System.DirectoryServices.DirectoryEntry.get_AdsObject()
   at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne
)
   at System.DirectoryServices.DirectorySearcher.FindOne()
   at System.DirectoryServices.AccountManagement.ADStoreCtx.IsMemberOfInStore(Gr
oupPrincipal g, Principal p)
   --- End of inner exception stack trace ---
   at System.DirectoryServices.AccountManagement.ADStoreCtx.IsMemberOfInStore(Gr
oupPrincipal g, Principal p)
   at System.DirectoryServices.AccountManagement.PrincipalCollection.ContainsNat
iveTest(Principal principal)
   at System.DirectoryServices.AccountManagement.PrincipalCollection.Contains(Pr
incipal principal)
   at System.DirectoryServices.AccountManagement.PrincipalCollection.Add(Princip
al principal)
   at System.DirectoryServices.AccountManagement.PrincipalCollection.Add(UserPri
ncipal user)

A: I also ran into the same issue with a (GroupPrincipal instance).Members.Add(UserPrincipal instance).
The workaround (in IronPython) is rather simple thanks to the GetUnderlyingObject method.
de = group.GetUnderlyingObject
# Group member DNs are kept in 'member' attribute in LDAP
de.Properties['member'].Add(user.DistinguishedName)
de.CommitChanges() # Save your work

A: Just ran into this and noticed that the code project sample was explicitly using the domain's name when creating the context (instead of using null). I changed my code to explicitly specify the domain name, and now it's working fine - I can group.Members.Add(user) without issue.


text:
Q: How to reset a variable to 0 every 24 hours in Javascript? I want to reset a variable automatically without any user interaction to 0 every midnight.
How to do that in vanilla Javascript?
Or does Chrome have any default method to do it. Because I store that variable in Chrome.storage.local.
What is the best way to do it in either vanilla JS or using chrome apis?

A: You've said you're storing the value in Chrome.storage.local. Also store the date/time you saved that value. When you load it, if midnight has passed since that time, reset the value to zero.
In case the page has been left open overnight, either always load the value from storage before using it (even if you already have it in a JavaScript variable), or do the same thing at the JavaScript level (remember the date/time and reset the value). Although you can set a timer, pages that sit idle for a long period of time have their timers de-prioritized by modern browsers, so it probably wouldn't be reliable to do this with a timer.

A: It is impossible to do so automatically without user accessing the page.
But, you can add script to the page which onload check the last time the value was stored and if the time passed you can reset the variable.
Rough code to make this:
const isToday = (someDate) => {
  const today = new Date()
  return someDate.getDate() == today.getDate() &&
    someDate.getMonth() == today.getMonth() &&
    someDate.getFullYear() == today.getFullYear()
}

window.onload = function init() {
    const { value, date } = JSON.parse(localStorage.getValue('key'));

    if (!isToday(date)) {
        localStorage.setValue('key', JSON.stringify({ date: new Date(), value: defaultValue}))
    }
}

A: Without server assisting to do that, you may want to implement reset_variable() to be scheduled with helping of setTimeout() https://developer.mozilla.org/en-US/docs/Web/API/setTimeout and setInterval() https://developer.mozilla.org/en-US/docs/Web/API/setInterval - But you have to trigger setInterval() at midnight first, and adjust the interval as 24h. Thus, you have to implement some algorithm to calculate when to start executing (trigger) setInterval() using the setTimeout().
With server assisting, you may want to implement a cron-like job in the server. The job may look like sending some predefined values to reset the variable on the browser.
Therefore, you can do it in diverse ways. The simplest way is over WebSocket https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API.
Explanation:
Browser/Client-side:
Implement a Listener on the browser Ex, message event https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/message_event, whenever you caught a message, process that message if it's the predefined value to reset the variable, then someVar.reset().
Server-side:
Create a handler to connect to the client-side WebSocket Listener -WebSocket supported in most programming languages-.
Implement a cron-like job to execute a function every midnight. I have no idea if you have a server, and if so, which programming language you are using. However, a cron-like job can be implemented in several programming languages, and basically, it can be implemented natively on Unix-like OSs, you may want to ask another question if you need help regarding this.
The function should send a predefined value using the handler of the WebSocket connection.
-you can do some Security validation though-


text:
Q: What does mean the phrase "fall through" in slang? It's from GTA 5, just look at 12:07 on Youtube.
As two characters leave a car dealership, one homie is offering to another to get in a car, he says:

How 'bout we fall through, homie?

What does it mean at this context?


text:
Q: Prove for $Pr[A] - Pr[B] \leq Pr[A \setminus B]$ I have events $A$ and $B$
I want to prove that for $Pr[A] - Pr[B] \leq Pr[A \setminus B]$.
I need help getting started. Are there any axioms of probability I could use to rewrite this?

A: Use the following syntax:
$p(X) \equiv $ probability of event $X$ occurring
$(XY) \equiv $ the event that events $X$ and $Y$ both occur
$(\neg X) \equiv $ the event that event $X$ does not occur.
Clearly $(B)$ can be partitioned into two mutually exclusive events:
$[B(\neg A)]$ and $(BA).$
Thus, $p(B) = p[B(\neg A)] + p(BA).$
Similarly, $p(A) = p[A(\neg B)] + p(BA).$
Therefore:
$p(A) - p(B) = p(A) - \{p[B(\neg A)] + p(BA)\} \leq p(A) - p[BA] = p[A(\neg B)].$

A: To begin with, I would start with noticing that $A\cup B = (A\cap B^{c})\cup B$. Indeed, we have
\begin{align*}
(A\cap B^{c})\cup B = (A\cup B)\cap(B\cup B^{c}) = (A\cup B)\cap \Omega = A\cup B
\end{align*}
where $\Omega$ is the sample space.
Moreover, we do also have that $A\subseteq A\cup B$. Since $A\cap B^{c}$ and $B$ are disjoint, the following result holds due to the monotonicity of the probability measure as well as the finite additivity property:
\begin{align*}
\mathbb{P}(A) \leq \mathbb{P}(A\cup B) & = \mathbb{P}((A\cap B^{c})\cup B) = \mathbb{P}(A\cap B^{c}) + \mathbb{P}(B) \Rightarrow \mathbb{P}(A) - \mathbb{P}(B) \leq \mathbb{P}(A\cap B^{c})
\end{align*}
and we are done.
Hopefully this helps!

A: Start with expressing $A$ and $B$ as unions of disjoint sets. $$A=(A\smallsetminus B)\cup(A\cap B)\\ B =  (B\smallsetminus A)\cup(A\cap B)$$Now the additive property of probability can be applied.


text:
Q: Splitting and copying csv fields in pandas I have a csv file for eg
ID,Name,products
101,Tesco,Apple;Banana;Oranges
102,Lidl,Juice;Yogurt
103,Aldi,Fruits;vegetables;rice
Using the pandas library I want to split these into a new csv such that for the products column there is only one value for every field
The following code I've tried only selects those particular column and writes the values to a new csv. I want to modify the output.
df=pd.read_csv('final.csv',delimiter=",", index_col="ID",encoding="ISO-
8859-1")
df1=df[,"Name","Products"]
df1.to_csv('a.csv',header='True')
print (df1)

I want the new csv generated to have the values in the following format-
101,Tesco,Apple
101,Tesco,Banana
101,Tesco,Oranges
102,Lidl,Juice
102,Lidl,Yogurt
103,Aldi,Fruits
..

A: We can:
1) Split the items in each row with delimiter ";". Then we get one column for each item.
2) We then unstack the columns to get them as rows, and then remove the index level that is added based on the previous column values.
3) Name this pd.Series and join on the main df.
prod = df['products'].str.split(";", expand=True).unstack().reset_index(level=0, drop=True).dropna()

    ID
    101         Apple
    102         Juice
    103        Fruits
    101        Banana
    102        Yogurt
    103    vegetables
    101       Oranges
    103          rice

prod.name = 'product'

df = df.join(prod.to_frame())
df.drop('products', axis=1, inplace=True)

Output:

      Name     product
ID
101  Tesco       Apple
101  Tesco      Banana
101  Tesco     Oranges
102   Lidl       Juice
102   Lidl      Yogurt
103   Aldi      Fruits
103   Aldi  vegetables
103   Aldi        rice


text:
Q: bash string comparison with nested variables So i'm quite new to bash and im just writing a basic script to run an application utility for me. All i want to is then check the output for a specific string response and log if it has an error. Now I am able to get the script working if I just use this line
if [[ $condition == *"added"* ]] ; then

as soon as i try to look for a exact comparision
if [[ "$condition" == "CONDITION:${2} DATE:${3} added" ]] ; then

it does not work even though from what I can see the output is correct. I have a feeling im comparing wrong or some secrete characters are being added which is a bash function I havent learned yet. Any help would be greatly appreciated.
UPDATE!
So with the feedback I have been given I have tried to make my code more clear and get some idea of what the raw string values are. Thanks everyone so far for replying back. Below is the updated script and output
#!/usr/bin/sh
# This script posts a condition sent to it by the Shout Destination table
# in CCM. Used to generate JOB_LATE incidents.
# If an error is encountered it is logged in the
# job_late_error_log.txt file.
# utility -> ctmcontb -ADD <Condition Name> <Condition Date>
# Condition format -> L@%%JOBNAME-%%NODEID -> JOB_LATE format
# $2 = L@%%JOBNAME-%%NODEID $3 = <Condition Date>
cmd_output=$(ctmcontb -ADD $2 $3)
time_stamp=$(date)
working_directory=/apps/ctm/devsv/scriptsadmin/do_condition/
error_file=job_late_error_log.txt
write_file_to_location=$working_directory$error_file
#if [[ $cmd_output == *"added"* ]] ; then
echo below is the hex output of "CONDITION:${2} DATE:${3} added"
echo "CONDITION:${2} DATE:${3} added" | od -xc
echo below is the command for $cmd_output
echo "$cmd_output" | od -xc
cmd_ouput_no_space = "$(echo -e "${cmd_output}" | tr -d '[[:space:]]')"
echo below is the command with white spaces removed
echo $cmd_ouput_no_space
if [[ "$cmd_ouput_no_space" == "CONDITION:${2} DATE:${3} added" ]] ; then
    echo $cmd_ouput_no_space
    echo successfull ran util
    exit 0
else
#   echo $cmd_ouput_no_space $time_stamp >> $write_file_to_location
    echo $cmd_ouput_no_space
    echo error occurred running util
    exit 1
fi

and the output:
ctmtest1-tctmsv80 [9] job_late.sh ctmtest1 u350932-test2 0816
below is the hex output of CONDITION:u350932-test2 DATE:0816 added
0000000     434f    4e44    4954    494f    4e3a    7533    3530    3933
           C   O   N   D   I   T   I   O   N   :   u   3   5   0   9   3
0000020     322d    7465    7374    3220    4441    5445    3a30    3831
           2   -   t   e   s   t   2       D   A   T   E   :   0   8   1
0000040     3620    6164    6465    640a
           6       a   d   d   e   d  \n
0000050
below is the command for CONDITION:u350932-test2 DATE:0816 added
0000000     2043    4f4e    4449    5449    4f4e    3a75    3335    3039
               C   O   N   D   I   T   I   O   N   :   u   3   5   0   9
0000020     3332    2d74    6573    7432    2044    4154    453a    3038
           3   2   -   t   e   s   t   2       D   A   T   E   :   0   8
0000040     3136    2061    6464    6564    0a00
           1   6       a   d   d   e   d  \n
0000051
job_late.sh[19]: cmd_ouput_no_space:  not found
below is the command with white spaces removed

error occurred running util

im not to familiar with the od -xc call but it looks like my values are different which make sense. Not sure why though?
UPDATE 2:
So i tried removing all white spaces using line
cmd_ouput_no_space = "$(echo -e "${cmd_output}" | tr -d '[[:space:]]')"

that i found here:
How to trim whitespace from a Bash variable?
but it doesn't seem to work. I have updated my original script and ouput at the top of this post with the errors im having.

A: There is a space before CONDITION in the captured cmd_output.


text:
Q: Which Flash rendering cases are faster when the wmode embed param is set to "gpu"? In May 2008 (about three years ago, as of the time of this posting), an engineer who worked on Flash Player 10 wrote the following in a blog post talking about GPU compositing:

Just because the Flash Player is using [GPU compositing] does not mean it will be faster. In the majority of cases your content will become slower... Content has to be specifically designed to work well with GPU functionality. The software rasterizer in the Flash Player can optimize a lot of cases the GPU cannot optimize, you as the designer will have to be aware of what a GPU does and adapt your content accordingly. I realize this statement is useless unless we can provide guidance, something we can hopefully achieve in the not to distant future.

Is anyone aware of any such guidance having been provided by Adobe in the succeeding three years? The only relevant information I could find was in this article, which provides optimization tips for hardware rendering, but not for hardware-accelerated compositing, which is what the "gpu" wmode embed param turns on.
Short of testing each piece of content individually, how can I determine when my content would benefit from the use of GPU compositing and when the use of GPU compositing would be a detriment?
Thanks in advance!

A: The link you provided contains a lot of information on how to set up your content to work well with gpu rendering (which is, in fact, what Flash Player 10.1 and higher will do, when wmode is set to gpu).  This includes compositing, and also some other functionalities.
In essence, compositing means assembling a screen image from combining and/or layering bitmaps.  So you can safely assume that performance will increase when using the gpu render mode with little vector-based content, or when cacheAsBitmap is used.
Apart from vector-related things, most of the optimization methods that work for the 10.1 player should work for earlier versions, as well.
However, I would assume that there is no definitive set of rules to define which optimization methods are best and which will ultimately degrade performance.  You will always have to test and verify any assumptions you make about what is going to be faster, especially when deploying to different hardware platforms.


text:
Q: How to initialize IDictionary in constructor? In TagBuilder and other classes I can write something like:
var tr = new TagBuilder("HeaderStyle"){InnerHtml = html, [IDictionary Attributes]}

but I don't know how to pass the IDictionary parameter.
How can I do that on the fly? Without creating a Dictionary variable.
TagBuilder is an example, there are other classes that accept a parameter IDictionaryas well. The question is about the generic case.

A: The following blog post has a helper method that can create Dictionary objects from anonymous types.
http://weblogs.asp.net/rosherove/archive/2008/03/11/turn-anonymous-types-into-idictionary-of-values.aspx
void CreateADictionaryFromAnonymousType()
   {
       var dictionary = MakeDictionary(new {Name="Roy",Country="Israel"});
       Console.WriteLine(dictionary["Name"]);
   }

private IDictionary MakeDictionary(object withProperties)
   {
       IDictionary dic = new Dictionary<string, object>();
       var properties =
           System.ComponentModel.TypeDescriptor.GetProperties(withProperties);
       foreach (PropertyDescriptor property in properties)
       {
           dic.Add(property.Name,property.GetValue(withProperties));
       }
       return dic;
   }

A: Another way to create Dictionaries from Anonymous types:
new Dictionary<int, StudentName>()
{
    { 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}},
    { 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317}},
    { 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198}}
};

http://msdn.microsoft.com/en-us/library/bb531208.aspx

A: If you're referring to the Attributes property, the setter is private, so you can't set it in an object initializer.
After you've initialized the TagBuilder, you should be able to add individual attributes with tr.Attributes.Add(key,value).


text:
Q: What is the use case for shadowing variables? One of the things the coffeescript programming language is criticized for is its treatment of variable declarations and scope (example).
The answers to this question (and the blog I linked to above) seem to hinge on the false dichotomy of variables either being able to be shadowed or else be global. In any language with reasonable scoping rules, this conceit seems (to me) to be a non-sequiter. In the aforementioned coffeescript:
foo = 5
f = () ->
  foo = 12 #foo in the outer scope is closed-over
  bar = 3  #binds a name in f's scope
  null

f()
foo #12
bar #undefined because it was bound in an inner scope

So clearly, bar is not global. If the snippet above was itself inside a non-global scope then foo would not be either. It seems to me that shadowing a variable from an outer scope in a language with lexical closure could only possibly create confusion. So why does coffeescript get slammed for removing the possibility? Is there an important use case here I'm missing? Regardless of how one may feel about the rest of coffeescript, this behavior seems desirable to me.

A: The issue with the way you describe it (I don't know coffeescript myself) is that it makes it too easy to break existing code without realizing it.  Let's say you have this code:
bar = 5
// 100 lines of code
f = () ->
    foo = 12
    null

// 100 lines of code
print bar

Now you decide that "bar" is a lousy name and you rename the global to "foo".  Suddenly all hell breaks loose. Maybe you don't even notice right away, it slips through your tests and hits production.
Now consider other strategies:
Shadowing (C/C++/others) Have locals shadow globals.  In this case, the code just runs as is.  foo in the local scope does not affect the global scope, so everything works as before.
Disallow (C#) The compiler tells you not to do that.  You change the name of one or the other and everything is fine.
Shadow or make explicit  (Python) Have locals shadow globals, but let developers make the use of the global explicitly.  Again, everything just works as before.
A related use case, for which these same comments apply, is if you pull and existing function, either just copying the code or using some include method, where a local happens to use the name of a global in the new file.

A: The backlash towards CoffeeScript specifically is likely because CoffeeScript is supposed to be a language that is similar to Javascript; it is advertised as a variation or extension of Javascript. The homepage even says:

The golden rule of CoffeeScript is: "It's just JavaScript".

Javascript developers might be hesitant to try CoffeeScript when the foundational implicit behavior that they have grown accustomed to has been changed.


text:
Q: To change the style of
* when input is empty I was making a search field for my website in html but I am not understanding how to change the display to none using javascript.

function search() {
    var input            =               document.getElementById("myInput");
    var filter           =               input.value.toUpperCase();
    var ul               =               document.getElementById("myUL");
    var li               =               ul.getElementsByTagName("li");

    for (i = 0; i
 -1) {
            li[i].style.display = "block";
        }

        else {
            li[i].style.display = "none";
        }
    }
}

    <input type="text" id="myInput" onkeyup="search()" placeholder="Search.." title="Type in a name">

About Me

Agnes

Billy

Bob

Calvin

Christina

Cindy

A: Here would be a solution : notice the && filter to be sure the input has a value and call the function on page ready to hide it first ;)

function search() {
    var input            =               document.getElementById("myInput");
    var filter           =               input.value.toUpperCase();
    var ul               =               document.getElementById("myUL");
    var li               =               ul.getElementsByTagName("li");

    for (i = 0; i
 -1 && filter) {
            li[i].style.display = "block";
        }

        else {
            li[i].style.display = "none";
        }
    }
}
search()

    <input type="text" id="myInput" onkeyup="search()" placeholder="Search.." title="Type in a name">

About Me

Agnes

Billy

Bob

Calvin

Christina

Cindy

A: In a comment you've said you want none of the list items to be visible when the text field is empty. Just default to display: none and override it when you find  a match.
Doing that with minimal changes:

function search() {
    var input            =               document.getElementById("myInput");
    var filter           =               input.value.toUpperCase();
    var ul               =               document.getElementById("myUL");
    var li               =               ul.getElementsByTagName("li");

    for (i = 0; i
 -1) {

            li[i].classList.add("show");
        }
        else {
            li[i].classList.remove("show");
        }
    }
}
#myUL li {
  display: none;
}
#myUL li.show {
  display: block;
}

    <input type="text" id="myInput" onkeyup="search()" placeholder="Search.." title="Type in a name">

About Me

Agnes

Billy

Bob

Calvin

Christina

Cindy

As I mentioned in a comment above, if you don't need to support Internet Explorer, you can use toggle instead of add and remove. You could also use string's includes on modern browsers. So:
li.classList.toggle("show", filter && txtValue.toUpperCase().includes(filter));

I'd make more changes, though:

*

*Declare i

*Use modern event handling

*Use the input event, not keyup

*Don't make search a global function

*Use querySelectorAll
With those changes:

// Scoping function so we don't create a global
(function() {
    // Hook up the search
    var input = document.getElementById("myInput");
    input.addEventListener("input", search);

    function search() {
        var input  = document.getElementById("myInput");
        var filter = input.value.toUpperCase();
        var items  = document.querySelectorAll("#myUL li");

        for (var i = 0; i < items.length; i++) {
            var li        = items[i];
            var a         = li.querySelector("a");
            var txtValue  = (a.textContent || a.innerText).toUpperCase();

            if (filter && txtValue.indexOf(filter) > -1) {
                li.classList.add("show");
            } else {
                li.classList.remove("show");
            }
        }
    }
})();
#myUL li {
  display: none;
}
#myUL li.show {
  display: block;
}

    <input type="text" id="myInput" placeholder="Search.." title="Type in a name">

About Me

Agnes

Billy

Bob

Calvin

Christina

Cindy

A: The if has the wrong condition:
Use filter && txtValue.toUpperCase().indexOf(filter) > -1 which only yields true if filter is not falsy (empty string would be) and filter is not found in txtValue

function search(e) {
  var input = e.target;
  var filter = input.value.toUpperCase();
  var ul = document.getElementById("myUL");
  var li = ul.getElementsByTagName("li");

  console.clear()
  for (i = 0; i
 -1) {
      li[i].style.display = "block";
    } else {
      li[i].style.display = "none";
    }
  }
}

document.getElementById('myInput').addEventListener('input', search);
#myUL .search_li {
  display: none;
}

  <input type="text" id="myInput" placeholder="Search.." title="Type in a name">

About Me

Agnes

Billy

Bob

Calvin

Christina

Cindy

A: your code is working fine, you just have to add the event listener for it like this :
document.getElementById('myInput').addEventListener('keyup', search) after the search() function definition, and delete the  onkeyup="search()" from the html

A: Add this condition at the end of your for-loop
if(filter==='' || filter===undefined){
    li[i].style.display = "none";
}


text:
Q: How to get list of all sites in Wordpress Multisite Network? I need some php request for get list of all sites in wp-network. Is it possible?

A: You can use
 <?php wp_get_sites( $args ); ?>

Examples ,for bellow v 3.0
<?php
$blog_list = get_blog_list( 0, 'all' );
foreach ($blog_list AS $blog) {
    echo 'Blog '.$blog['blog_id'].': '.$blog['domain'].$blog['path'].'
';
}
?>

A: Using WordPress functions is a bit problematic, when you aim compatibility with all multisite versions:

*

*get_blog_list is not only deprecated, but it does not return sites not flagged as public either. Strangely, the oficial documentation hasn't warned us about that (you discover only when your code fails).

*get_sites, in contrast, works only in WP 4.6.0 or higher

I prefer using the following code, which is compatible with all WordPress versions (as of 3.0.0, of course), and returns all sites of the installation (even the archived ones, deactivated ones, etc.):
global $wpdb;
$blogs = $wpdb->get_results( "SELECT blog_id, domain, path FROM $wpdb->blogs ORDER BY blog_id" );

If you want to filter your results, not showing the archived ones, deactivated ones and spam sites, you have to indicate that in the query as follows:
global $wpdb;
$blogs = $wpdb->get_results( "SELECT blog_id, domain, path FROM $wpdb->blogs WHERE archived = '0' AND deleted = '0' AND spam = '0' ORDER BY blog_id" );

Note: $blogs array is an object collection; you will have to build your own site list with the informations that comes inside every object (id, path, domain) that is more appropriate for you, as exemplified in Firefog and Aurovrata answers.

A: As of WP 4.6 there is a new function to query sites, get_sites($query_arg) which is a parallel to the familiar get_posts($query_args) used for retrieving posts,
$blogs = get_sites();
foreach( $blogs as $b ){
    $b->blog_id
    //Do stuff
}

NOTE: As pointed out by @guido-walter-pettinari in the comment below, get_sites() is a front for instantiating a new WP_Sites_query object which sets some default query parameters, including the 'number' of sites to return to 100!

A: In the usual way, you will be unable to get the blog name. To fetch blog names, you can use this little hack as follows.
$blog_list = get_blog_list(0, 'all');
foreach ($blog_list as $blog) {
    switch_to_blog( $blog['blog_id'] );
    $option = 'blogname';
    $value = get_option( $option );
    echo $value . '
';
    restore_current_blog();
}

Also, you can use the following alternative method to get the same result by calling the database directly.
global $wpdb;
foreach ($wpdb->get_results("SELECT blog_id, domain, path FROM $wpdb->blogs WHERE archived = '0' AND deleted = '0' AND spam = '0' ORDER BY blog_id") as $key => $blog) {
    switch_to_blog( $blog->blog_id );
    $option = 'blogname';
    $value = get_option( $option );
    echo $value . '
';
    restore_current_blog();
}


text:
Q: HTML element moving when viewport width changes, but no change in CSS Having a strange issue which has happened to me before but I couldn't figure out the issue either. I can work around it but I'd prefer to understand why it's happening so that I can fix the root issue.
The position of a  element is changing between 1200px and 1999px as you can see here:
1200px:

1999px:

The element is behaving like there is a breakpoint at 1200 but there isn't and the css doesn't change either according to Chrome dev tools.
You can see that the margin and position change slightly but not enough to cause such a shift in position.
I am using Bootstrap in case that matters.
Does anyone have any idea what's causing this?

A: This is the problem:
margin-top: 1.5%
You have a percentage based margin value, therefore, on resize, the positioning of the H2 will vary.
If you don't want it to vary, change it to another unit, for example px.
Also, you might want to specify offsets properties (left/right, top/bottom) of the element:

absolute
The element is removed from the normal document flow; no space is created
  for the element in the page layout. Instead, it is positioned relative
  to its closest positioned ancestor if any; otherwise, it is placed
  relative to the initial containing block. Its final position is
  determined by the values of top, right, bottom, and left. This value
  creates a new stacking context when the value of z-index is not auto.
  Absolutely positioned boxes can have margins, and they do not collapse
  with any other margins. Source MDN


text:
Q: Unnumbered footnote in Beamer I'm looking for the most versatile option to insert a footnote in beamer with no number.
Thanks so much,
Asaf

A: You could define your own command that yields an unnumbered footnote as shown in the following MWE:
\documentclass{beamer}
\newcommand\unfootnote[1]{%
  \begingroup
  \renewcommand\thefootnote{}\footnote{#1}%
  \addtocounter{footnote}{-1}%
  \endgroup
}

\begin{document}

\begin{frame}
Some text\unfootnote{An unnumbered footnote} \footnote{a numbered footnote}
\end{frame}

\end{document}

A: The footnote number can be removed with a slight adjustment of beamers footnote template:
\documentclass{beamer}

\setbeamertemplate{footnote}{%
  \parindent 1em\noindent%
  \raggedright
  \insertfootnotetext\par%
}

\begin{document}

\begin{frame}

text \footnotetext{A test footnote in the first column}

\end{frame}

\end{document}


text:
Q: .NET Core 3.1 WPF moving .xaml files to class library I'm migrating an old WPF project to .NET Core 3.1 and some of my .xaml views are not in the .exe assembly, they're in a class library.
Visual Studio doesn't recognize any of the WPF namespaces in the class library project, like these:

using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

If I change the type of the project to .exe, it works, but it's really ugly in my opinion.
In AspNetCore when I have similar issues and need to access specific AspNetCore namespaces in a class library, I need to include this in the .csproj:

  <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
  </ItemGroup>

Is there a similar FrameworkReference value for WPF projects?

A: In the project file, add an entry <UseWPF>true</UseWPF> to your TargetFramework:
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <UseWPF>true</UseWPF>
  </PropertyGroup>

</Project>


text:
Q: bash scripting to update an XML element attribute based on prior value I have an xml file that consists of strings
<server name="srv-usr--crt-Internal.vcdn--lfagent1">

and
<server name="srv-usr--crt-Internal.vcdn--lfagent2">
                                          ^^^^^^^^

I want to run a bash script, which continuously executes the xml file by changing the value in the server name i.e for the first time the values will be lfagent1 and lfagent2, the xml file is executed and then the value changes to lfagent3 and lfagent4. There should be around 500 to 1000 such iterations.
How to write a bash script for this test?

A: This answer uses XMLStarlet for parsing and updating XML safely.
The first job is extracting the content:
filename="input.xml"
IFS=$'\n' read -r -d '' -a old_names \
  < <(xmlstarlet sel -t -m '//server/@name' -v . -n <"$filename")

Next, generating the new values. Assuming that the only numbers that exist in any name are at the end:
new_names=( )
for name in "${old_names[@]}"; do
  name_prefix=${name%%[0-9]*}
  old_number=${name#$name_prefix}
  new_number=$(( old_number + ${#old_names[@]} ))
  new_names+=( "${name_prefix}${new_number}" )
done

Finally, generating and running a command to update the XML file:
update_command=( xmlstarlet ed )
for idx in ${!new_names[@]}; do
  update_command+=(
    -u "//server[$((idx + 1))]/@name" # XPath uses 1-indexed values
    -v "${new_names[$idx]}"           # ...whereas bash arrays are 0-indexed
  )
done
tempfile=$(mktemp "$filename.XXXXXX")
"${update_command[@]}" <"$filename" >"$tempfile" && mv "$tempfile" "$filename"

A: Use proper XML tools for processing XML. For example, xsh:
open file.xml ;
for //server {
    my $x = xsh:match(@name, '^(srv-usr--crt-Internal.vcdn--lfagent)([0-9]+)$') ;
    if (2 = count($x))
        set @name concat($x[1], 2+$x[2]) ;
}
save :b ;


text:
Q: R:subsetting a list using NULL I have a dataset "Boston" in MASS library in R. I want to exclude variables "chas","dis","rad","black","lstat". However the code
data[c("chas","dis","rad","black","lstat")]<-NULL

doesn't work. Can any on tell me why?

A: data[,c("chas","dis","rad","black","lstat")]<- list(NULL)

will work. I'm not entirely sure why. My guess is it has to do with how [<-.data.frame works - note that data[,"chas",drop=F] <- NULL will not work, but data[,"chas"] <- NULL will.

A: you can just use
Boston[,-which(names(Boston)%in%c("chas","dis","rad","black","lstat"))]


text:
Q: Problems with buildbot shell command : Adding single quotes to last argc argument I am running buildbot v0.8.9 and encountering a really weird problem.
I try to change the access permissions of exe files and runs into troubles.
Here is the code I first wrote :
ShellCommand(command=["chmod", "u+rwx , "*.exe"],workdir="myWorkDir",descriptionDone=["Changing permission access"])

This result in :
chmod u+rwx '*.exe'
After I read that article which seemed to be what I wanted, but after following it and doing :
ShellCommand(command=["sh", "chmod u+rwx *.exe"],workdir="myWorkDir",descriptionDone=["Changing permission access"])

I got this :
sh 'chmod u+rwx *.exe'

So the problem of the last argument single quoted is still there.

A: I finally found the response, reading the article I linked again since I had to do something else kind of related to that issue :
I wanted to use the "-c" argument, and I was missing it on my 2nd attempt.
So here is the correct code :
ShellCommand(command=["sh", "-c", "chmod u+rwx *.exe"],workdir="myWorkDir",descriptionDone=["Changing permission access"])


text:
Q: How do I create a query for A and ( B or C ) in Eloquent How should I create an eloquent query to select where A and (B or C)
$user->whereHas( 'roles', function( $query ) use( $role_slugs ){
    return $query->whereIn( 'slug', $role_slugs );
} )-> ???

The idea here is to add a search term that should search by email or name... (but it has to keep the role always
->orWhere( 'email', 'like', '%' . $search_term . '%' )
->orWhere( 'name', 'like', '%' . $search_term . '%' )->get();

The problem is that if I do this, it ignores the role slug. I need to be able to search within the results of the first part of the query.
I don't want to do something like:
$users = $user->whereHas( 'roles', function( $query ) use( $role_slugs ){
    return $query->whereIn( 'slug', $role_slugs );
} )->get();

return $users->filter( function( $user ) use( $search_term ){
    return ( substr_count( $search_term, $user->email ) > 0 ) || ( substr_count( $search_term, $user->name ) > 0 );
} );

A: Following your logic: where A AND (B OR C)
So, you should enclose the parenthesis in a closure function passed to the where():
$users = User::query()
        ->whereHas('roles', function ($query) use ($role_slugs) {
            return $query->whereIn('slug', $role_slugs);
        })
        ->where(function ($query) use ($search_term) {
            $query->where('email', 'like', '%' . $search_term . '%')
                ->orWhere('name', 'like', '%' . $search_term . '%');
        })
        ->get();


text:
Q: Ember SPA application with related models Lets say we are working on a recipe app and we have 2 get requests initially.
/ingredients/
/recipes/
These create the recipe and the ingredient model.
Now recipes are made of ingredients and amount of each ingredient.
And ingredients only have names.
Now populating the models are easy using the models and the default serializes and the adapters if we confirm to the https://jsonapi.org/
How do we handle when one of the ingredients is deleted. In the backend I use django if and ingredient is deleted DB also deletes all the recipes that have relation to the that ingredients.
But on the SPA application the let say we ran
ingredient.deleteRecord();
  ingredient.get('isDeleted'); // => true
  ingredient.save();

or
ingredient.destroyRecord();

How does the recipes model get updated ? So do you manually do what server does on the client(and delete related recipes by custome code)? Or should you just update the list and repopulate it(easier). And can you give dependencies between models so a model in the store would know that it need to be updated when one of it dependencies model is changed so it automatically  make a get request and repopulate itself(are routes/models that clever?)
On that note what is the standard way of keeping server and client in sync.
What is the standard for this sort of stuff. Should client app re-get all that data again just to be sure that server and spa are insync and uptodate.
Thanks

A: In the scenario where an ingredient gets deleted, the save has gone through successfully on the backend and now needs that ingredient needs to be removed from many recipes on the frontend before your UI is truly in sync, I would suggest using this gist to push your delete properly into the store: https://gist.github.com/runspired/96618af26fb1c687a74eb30bf15e58b6


text:
Q: Swift - Date from components is incorrect when printed. Date has 2 values? I'm trying to store a time of day in a Date:
let calendar = NSCalendar.init(identifier: .gregorian)
let components = NSDateComponents()
components.hour = 7
components.minute = 0

var newDate = calendar?.date(from: components as DateComponents)!

print(newDate!)

However, this yields some bizarre results when I try to print or otherwise use the value. Here's a Swift Playground of the results:

How can newDate be both 7:00AM and 11:56AM at the same time?

A: You didn't specify a time zone (by setting the timeZone property of either components or calendar). So the system used your local time zone to convert components to a date.
The playground system used your local time zone to convert newDate to the string "Jan 1, 1 at 7:00 AM". (The playground system has special-case code for displaying Date objects. The special-case code uses your local time zone.)
The print function used the UTC time zone to convert newDate to the string "0001-01-01 11:56:02 +0000".  (The print function uses the CustomStringConvertible protocol. Date's CustomStringConvertible implementation uses the UTC time zone.)
I deduce that your local time zone is US/Eastern time, also known as America/New_York:
import Foundation

var calendar = Calendar(identifier: .gregorian)
let components = NSDateComponents()
components.hour = 7
components.minute = 0

for timeZoneIdentifier in TimeZone.knownTimeZoneIdentifiers {
    calendar.timeZone = TimeZone(identifier: timeZoneIdentifier)!
    let date = calendar.date(from: components as DateComponents)!
    let dateString = "\(date)"
    if dateString == "0001-01-01 11:56:02 +0000" {
        print("\(timeZoneIdentifier) \(date)")
    }
}
// Only one line of output: America/New_York 0001-01-01 11:56:02 +0000

So why the weird minutes and seconds in UTC? Because at noon on November 18, 1883, the US and Canada railway companies began using a new, standard time system, which is the time system we still use today. Observe:
import Foundation

let formatter = ISO8601DateFormatter()

var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(identifier: "America/New_York")!
let components = NSDateComponents()

components.year = 1883
components.month = 11
components.day = 18

components.hour = 11
print(formatter.string(from: calendar.date(from: components as DateComponents)!))
// prints 1883-11-18T15:56:02Z

components.hour = 12
print(formatter.string(from: calendar.date(from: components as DateComponents)!))
// prints 1883-11-18T17:00:00Z

Prior to noon, the difference from UTC time is 4:56:02.
Before the advent of standard railway time, we typically defined local time based on local apparent noon (the moment when the sun is highest in the sky and shadows point exactly north or south or disappear entirely if the sun is directly overhead).
If we look at the definition of America/New_York in the tz Time Zone Database, we find this:
# From Paul Eggert (2014-09-06):
# Monthly Notices of the Royal Astronomical Society 44, 4 (1884-02-08), 208
# says that New York City Hall time was 3 minutes 58.4 seconds fast of
# Eastern time (i.e., -4:56:01.6) just before the 1883 switch.  Round to the
# nearest second.

and a bit further down:
Zone America/New_York   -4:56:02 -  LMT 1883 Nov 18 12:03:58

This explains the difference we see above prior to noon on November 18, 1883.


text:
Q: How to concatenate strings of multiple columns from table in SQL Server using dplyr? As title, I would like to concatenate a few columns from a table in SQL Server, I tried to use the paste function as below but give the following error:
> tbl(channel,'##iris') %>%
+   mutate(string=paste(Species,'-',
+                       Sepal.Length,'-',
+                       Sepal.Width,'-',
+                       Petal.Length,'-',
+                       Petal.Width,sep=''))
Error: PASTE() is not available in this SQL variant

A: I found a solution here provided by Ben Baumer., and want to share it here.
The approach is to use CONCAT instead of paste.
> tbl(channel,'##iris') %>%
+   group_by(Species,Sepal.Length,Sepal.Width,Petal.Length,Petal.Width) %>%
+   summarise(string=MAX(CONCAT(Species,'-',
+                               Sepal.Length,'-',
+                               Sepal.Width,'-',
+                               Petal.Length,'-',
+                               Petal.Width))) %>%
+   head(.,1)
# Source:   lazy query [?? x 6]
# Database: Microsoft SQL Server 11.00.6251[dbo@WCDCHCMSAH01\CMSAH_DC7_MP1/data_ha_amr]
# Groups:   Species, Sepal.Length, Sepal.Width, Petal.Length
  Species Sepal.Length Sepal.Width Petal.Length Petal.Width string
  <chr>          <dbl>       <dbl>        <dbl>       <dbl> <chr>
1 setosa          4.30        3.00         1.10       0.100 setosa-4.3-3-1.1-0.1

A: Using the tidyverse on R data.frames, tidyr::unite would be the idiomatic way to go.
Not being a dplyr verb though, it has not been translated to be used through dbplyr / SQL.
You can define your own unite this way in SQL server (I couldn't test unfortunately but it should work) :
unite.tbl <- function (data, col, ..., sep = "_", remove = TRUE)
{
  dot_names <- sapply(substitute(list(...))[-1], deparse)
  shown_cols <- if (remove)
    setdiff(data$ops$vars, dot_names)
  else data$ops$vars
  shown_col_str <- paste(shown_cols, collapse = ", ")
  concat_str <- paste0("CONCAT(",paste(dot_names, collapse = paste0(",'",sep,"',")),")")
  col <- deparse(substitute(col))
  subquery <- capture.output(show_query(data), type = "message")[-1] %>% paste(collapse = " ")
  query    <- paste("SELECT",shown_col_str,",",concat_str,"AS",col,"FROM (",subquery,")")
  tbl(data$src$con, sql(query))
}

and then :
tbl(channel,'##iris') %>%
  unite(string,
        Species, Sepal.Length, Sepal.Width, Petal.Length, Petal.Width,
        sep = '',remove=FALSE)

For a DBMS that supports the || concatenation operator (e.g. Oracle), just replace the concat_str definition by :
concat_str <- paste(dot_names, collapse = paste0(" || '", sep, "' || "))


text:
Q: ASP.NET session expire time I want to set the session life span to 2h, but i'm not sure how.
If I set the <sessionState timeout="120" /> in web.config I still get logged out every few minutes. Am I setting it wrong ?
Thanks!

A: your timeout is mostlikely not session but authentication, look for the below line and change that:
 <authentication mode="Forms">
  <forms name=".EMSOLG_ASPXAUTH" timeout="120" />
</authentication>

A: You can use session timeout in codebehind like this
Session.Timeout = 120;

A: If you have hosted the website in IIS , you can configure the required timeout in IIS.


text:
Q: Boto S3 throws httplib.IncompleteRead occasionally I have several daemons that read many files from Amazon S3 using boto. Once every couple of days, I'm running into a situation where an httplib.IncompleteRead is thrown out from deep inside boto. If I try and retry the request, it immediately fails with another IncompleteRead. Even if I call bucket.connection.close(), all further requests will still error out.
I feel like I might've stumbled across a bug in boto here, but nobody else seems to have hit it. Am I doing something wrong? All of the daemons are single-threaded, and I've tried setting is_secure both ways.
Traceback (most recent call last):
  ...
  File "<file_wrapper.py",> line 22, in next
    line = self.readline()
  File "<file_wrapper.py",> line 37, in readline
    data = self.fh.read(self.buffer_size)
  File "<virtualenv/lib/python2.6/site-packages/boto/s3/key.py",> line 378, in read
    self.close()
  File "<virtualenv/lib/python2.6/site-packages/boto/s3/key.py",> line 349, in close
    self.resp.read()
  File "<virtualenv/lib/python2.6/site-packages/boto/connection.py",> line 411, in read
    self._cached_response = httplib.HTTPResponse.read(self)
  File "/usr/lib/python2.6/httplib.py", line 529, in read
    s = self._safe_read(self.length)
  File "/usr/lib/python2.6/httplib.py", line 621, in _safe_read
    raise IncompleteRead(''.join(s), amt)

Environment:

*

*Amazon EC2

*Ubuntu 11.10

*Python 2.6.7

*Boto 2.12.0

A: I've been struggling with this problem for a while, running long-running processes which read large amount of data from S3. I decided to post my solution here, for posterity.
First of all, I'm sure the hack pointed to by @Glenn works, but I chose not to use it because I consider it intrusive (hacking httplib) and unsafe (it blindly returns what it got, i.e. return e.partial, despite the fact it can be real-error-case).
Here is the solution I finally came up with, which seems to be working.
I'm using this general-purpose retrying function:
import time, logging, httplib, socket

def run_with_retries(func, num_retries, sleep = None, exception_types = Exception, on_retry = None):
    for i in range(num_retries):
        try:
            return func()  # call the function
        except exception_types, e:
            # failed on the known exception
            if i == num_retries - 1:
                raise  # this was the last attempt. reraise
            logging.warning(f'operation {func} failed with error {e}. will retry {num_retries-i-1} more times')
            if on_retry is not None:
                on_retry()
            if sleep is not None:
                time.sleep(sleep)
    assert 0  # should not reach this point

Now, when reading a file from S3, I'm using this function, which internally performs retries in case of IncompleteRead errors. Upon an error, before retrying, I call key.close().
def read_s3_file(key):
    """
    Reads the entire contents of a file on S3.
    @param key: a boto.s3.key.Key instance
    """
    return run_with_retries(
        key.read, num_retries = 3, sleep = 0.5,
        exception_types = (httplib.IncompleteRead, socket.error),
        # close the connection before retrying
        on_retry = lambda: key.close()
    )

A: It may well be a bug in boto, but the symptoms you describe are not unique to it. See
IncompleteRead using httplib
https://dev.twitter.com/discussions/9554
Since httplib appears in your traceback, one solution is proposed here:
http://bobrochel.blogspot.in/2010/11/bad-servers-chunked-encoding-and.html?showComment=1358777800048
Disclaimer: I have no experience with boto. This is based on research only and posted since there have been no other responses.

A: If you are reading a large amount of data from S3, you may have to chunk/multi-part your read/write.
There is a good example here on doing the multi-part (http://www.bogotobogo.com/DevOps/AWS/aws_S3_uploading_large_file.php)


text:
Q: wireless connection asking password for every connection fail My system knows the password for a wireless ssid, and it is connected too. but whenever the wireless connection is disconnected it should always try connect to it, but after three or 4 attempts it is assuming like "the wifi password is not correct" so it is again asking like this.

i don't want to get this prompt, because i have to hit enter to connect again but i havent keyboard and mouse so i am operating my pc with remote system so if this type of prompts appear then it will not connect to wifi again.
the wifi connection should not stop for trying the wifi but it should not ask the password again how to automate this?


text:
Q: Convert access.log to JSON format using python **This is my python code, I'm trying to convert NGINX logs.
I'm reading logs from access.log file and using regular expressions to convert it into JSON format and i need to upload these logs to Elasticseach. Please also guide related to that. I'm new into both**
 import json
 import re

 i = 0
 result = {}

with open('access.log') as f:
  lines = f.readlines()

regex = '([(\d\.)]+) - - \[(.*?)\] "(.*?)" (\d+) - "(.*?)" "(.*?)"'

for line in lines:

  r = re.match(regex,line)

  if len(r) >= 6:
    result[i] = {'IP address': r[0], 'Time Stamp': r[1], 'HTTP status': r[2], 'Return status':
                 r[3], 'Browser Info': r[4]}
    i += 1
 print(result)

with open('data.json', 'w') as fp:
 json.dump(result, fp)

I'm facing the following error
Traceback (most recent call last):
   File "/home/zain/Downloads/stack.py", line 17, in <module>
    if len(r) >= 6:
TypeError: object of type 'NoneType' has no len()

These are log format
127.0.0.1 - - [23/May/2022:22:44:14 -0400] "GET / HTTP/1.1" 200 3437 "-" "Mozilla/5.0   (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0"
127.0.0.1 - - [23/May/2022:22:44:14 -0400] "GET /icons/openlogo-75.png HTTP/1.1" 404 125 "http://localhost/" "Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0"
127.0.0.1 - - [23/May/2022:22:44:14 -0400] "GET /favicon.ico HTTP/1.1" 404 125 "http://localhost/" "Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0"

Expected output is
IP Address: 127.0.0.1 Time Stamp: 23/May/2022:22:44:14  HTTP Status: "GET / HTTP/1.1" Return Status: 200 3437  Browser Info: "Mozilla/5.0   (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0"

A: I took my cue from this code. Believe the following should do it:
import json
import re

i = 0
result = {}

with open('access.log') as f:
    lines = f.readlines()

regex = '(?P<ipaddress>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) - - \[(?P<dateandtime>.*)\] \"(?P<httpstatus>(GET|POST) .+ HTTP\/1\.1)\" (?P<returnstatus>\d{3} \d+) (\".*\")(?P<browserinfo>.*)\"'

for line in lines:

    r = re.match(regex,line)

    if r != None:
        result[i] = {'IP address': r.group('ipaddress'), 'Time Stamp': r.group('dateandtime'),
                     'HTTP status': r.group('httpstatus'), 'Return status':
                     r.group('returnstatus'), 'Browser Info': r.group('browserinfo')}
        i += 1

print(result)

with open('data.json', 'w') as fp:
    json.dump(result, fp)

Result (print(json.dumps(result, sort_keys=False, indent=4))):
{
    "0": {
        "IP address": "127.0.0.1",
        "Time Stamp": "23/May/2022:22:44:14 -0400",
        "HTTP status": "GET / HTTP/1.1",
        "Return status": "200 3437",
        "Browser Info": "Mozilla/5.0   (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0"
    },
    "1": {
        "IP address": "127.0.0.1",
        "Time Stamp": "23/May/2022:22:44:14 -0400",
        "HTTP status": "GET /icons/openlogo-75.png HTTP/1.1",
        "Return status": "404 125",
        "Browser Info": "Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0"
    },
    "2": {
        "IP address": "127.0.0.1",
        "Time Stamp": "23/May/2022:22:44:14 -0400",
        "HTTP status": "GET /favicon.ico HTTP/1.1",
        "Return status": "404 125",
        "Browser Info": "Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0"
    }
}


text:
Q: If $f$ is holomorphic and $\lim_{|z|\to\infty} |f(z)| = 0$ then $f$ is polynomial
If  $f: \mathbb{C} \to \mathbb{C}$ is holomorphic and  $\lim_{|z|\to\infty} |f(z)| = 0$ then $f$ is polynomial

My attempt
I tried to prove that $f^{(k)}(w) = 0$,  $\forall w\in \mathbb{C}$ and for all $k \geq n$ for some $n$.
Given $\varepsilon>0 $ there exists $\delta>0$ such that $|f(z)|<\varepsilon$,  if $|z|\geq \delta$.
For $w\in\mathbb C$ fixed and $r$ such that $C = \{z \in \mathbb{C},|z-w|=R\}\subset\{z\in\mathbb C,|z|\geq \delta\}$, we have from  the Cauchy integral formula
$$f^{(k)}(w) =\frac{k!}{2i\pi}\int_C\frac{f(z)}{(z-w)^{k+1}}dz
 $$
hence
$$|f^{(k)}(w)|\leq \frac{k!}{2\pi}\int_C  \frac{|f(z)|}{|z-w|^{k+1}}|dz|\leq
\frac{\varepsilon k!}{R^{k}}$$
I am stuck here.
I don't know how to find $n$ and if the inequality I've proved helps.

A: We have $\lim_{|z|\to\infty} |f(z)| = 0$, so $\exists R,\forall z \in\mathbb{C}/D(0,R),|f(z)|<1$, also since $f$ is holomorphic it is continuous in $D(0,R)$, so $f$ is bounded in $D(0,R)$ thus $\exists M,\forall z \in D(0,R),|f(z)|<M$. Finally $\forall z \in \mathbb{C},|f(z)|<\max(1,M)$. So with Liouville's theorem $f$ is constant, so $f$ is a polynomial.


text:
Q: SQL - SUM Alias (GROUP BY) I'm having some issues grouping by an Alias column in SQL. This column contains both positive and negative numbers, and as a result, I want my "ARI_APLNO" column to be the sum of both the positive and negative numbers.
This is the code I currently have:
SELECT        ARI_APLNO,
CASE
WHEN ARI_TYPE = 1 OR ARI_TYPE = 3 THEN ARI_AMOUNT + ARI_SLSTAX
WHEN ARI_TYPE = 2 AND ARI_AMOUNT < 0 THEN ARI_AMOUNT * - 1
WHEN ARI_TYPE = 5 THEN (ARI_AMOUNT + ARI_SLSTAX) * - 1
ELSE - ARI_AMOUNT END AS TotalValue
FROM            dbo.ARITEMA
GROUP BY TotalValue, ARI_APLNO

Wondering if I could please have some assistance?
Thank you in advance.

A: ;WITH CTE AS (
SELECT        ARI_APLNO,
CASE
WHEN ARI_TYPE = 1 OR ARI_TYPE = 3 THEN ARI_AMOUNT + ARI_SLSTAX
WHEN ARI_TYPE = 2 AND ARI_AMOUNT < 0 THEN ARI_AMOUNT * - 1
WHEN ARI_TYPE = 5 THEN (ARI_AMOUNT + ARI_SLSTAX) * - 1
ELSE - ARI_AMOUNT END AS TotalValue
FROM            dbo.ARITEMA
 )

SELECT ARI_APLNO,SUM(TotalValue) FROM CTE
GROUP BY ARI_APLNO

Try framing a CTE with all the conversions and then do SUM which will be easier and clean to handle new changes in future.


text:
Q: How to trigger multiple gnome-terminal windows automatically and keep them open and active? the related part of the code is:
main code
#.....some code

send "flag1\r"
exec gnome-terminal -t "tab1" -x bash "$HOME_PATH/scripts/startTask1.tcl"
send "flag2\r"
exec gnome-terminal -t "tab2" -x bash "$HOME_PATH/scripts/startTask2.tcl"

#.....some code

startTask1.tcl
#.....some code
expect "flag for task2 to go"
send "flag3\r"
interact
send "flag4\r"

#.....some code

then i found, i can see the prints of flag1 and flag3, the window "tabl" is opened, but the tab2 could not be triggered.
I tried to closed the tabl windows, then tab2 was opened. However, what i want is to keep those 2 windows open both automatically.
My understanding is: "interact" give out the control, then the next terminal should be opened automatically, right?
I'm freshman on this, so some words above may be not exact. Very appreciate for the reply, thanks.

A: I could be mistaken but I believe the program called terminator is the only tabbed shell that uses multiple shells simultaneously. Be forewarned though, the order of calls may look simultaneous but in reality they are going to go in and out of memory in an order that can place things in userspace, kernelspace, or swapspace, at intervals that parse according to the scripting order.

A: Your problem is that the outer program is waiting for the gnome-terminal process to finish before going on to the next step. It finishes when the subordinate process (expect I guess?) finishes.
You can run both at the same time by putting a & as a separate argument at the end of the exec:
exec gnome-terminal -t "tab1" -x bash "$HOME_PATH/scripts/startTask1.tcl" &

However, you won't be able to get the two tasks to collaborate with each other easily this way, as they are using separate virtual terminals under the covers. In fact, there'll be one virtual terminal for each gnome-terminal and another one (at least) for each expect.
I think you need to take a few steps back and work out what you really want to do. There probably are ways to do it, but they might need a different approach to the one you're currently using which looks like it is doomed to failure.


text:
Q: Can't enhance kodo JPA classes I am just moving to Kodo JPA version 4.2 and it isn't going smoothly.
when I run my any build script (in eclipse 3.4.1) I get
BUILD FAILED
D:\My Documents\eclipseWorkspaces\cnmp e341\blue ebig\ebig\src\java\build.xml:91: <openjpa-1.1.0-r422266:657916 fatal user error> org.apache.openjpa.util.MetaDataException: MetaDataFactory could not be configured (conf.newMetaDataFactoryInstance() returned null). This might mean that no configuration properties were found. Ensure that you have a META-INF/persistence.xml file, that it is available in your classpath, or that the properties file you are using for configuration is available. If you are using Ant, please see the <properties> or <propertiesFile> attributes of the task's nested <config> element. This can also occur if your OpenJPA distribution jars are corrupt, or if your security policy is overly strict.

My build.xml is sitting in my java directory next to my META-INF directory containing my persistence.xml file
here is the snippet from the build.xml
<target name="enhance">
    <echo>base dir is ${basedir}</echo>
  <!-- define the kodoc task; this can be done at the top of the    -->
  <!-- build.xml file, so it will be available for all targets      -->
  <taskdef name="kodoc" classname="kodo.ant.PCEnhancerTask"/>

  <!-- invoke enhancer on all .jdo files below the current directory -->
  <kodoc>
    <fileset dir=".">
        <include name="**/jpa/*.java" />
        <include name="**/jpa/*.class" />
    </fileset>
    <classpath>
        <pathelement location="${basedir}"/>
    </classpath>
  </kodoc>
</target>

The entity class files are in the jpa directory. So the directory structure looks like this:
+ top
  + src
    + java
    | + com
    |   + splat
    |   | + jpa
    |   |   - entity.java
    |   | + stuff
    |       - Object.java
    | + META-INF
    |   - persistence.xml
      - build.xml

I had thought I had followed the directions in the doc., but clearly I didn't.
Thanks

A: This problem was fixed by adding config propertiesFile="../../config/ebig.kodo.properties"/>
to the task it now looks like
  <kodoc>
    <config propertiesFile="../../config/ebig.kodo.properties"/>
    <fileset dir=".">
        <include name="**/jpa/*.java" />
        <include name="**/jpa/*.class" />
    </fileset>
    <classpath>
        <pathelement location="${basedir}"/>
    </classpath>
  </kodoc>


text:
Q: How to use ajax to post to kintone endpoint using AWS lambda and nodejs This is my first Stack Overflow post. I'm bumping into a wall trying to hit an API to add records into a Kintone App. I'm using ajax to send to AWS lambda function that uses nodejs. I know my AWS api gateway is working. I just can't figure out why the JSON object is not posting to the add record end point.
Here is my JSON object:
body: {
    app: 1,
    record: {
        Text: {
            value: 'Sample'
        },
        Number: {
            value: 1
       }
    }
}

Here is my ajax post:
$.ajax({
    type: "POST",
    url: 'http://my-aws-endpoint/add-record',
    dataType: 'json',
    data: JSON.stringify({ body })
    // data: body
}).done(function(response) {
    console.log(response);
});

Here is my nodejs:
var querystring = require('querystring');
var https = require('https');
var DOMAIN = 'mydomain.com';
var AUTH_VALUE = 'myauthvalue;
var headers = {
    'api-token': 'myapitoken',
    'Content-Type': 'application/json'
};
exports.handler = function (event, context) {
    var postData = querystring.stringify(
        event.body
    );
    var options = {
        hostname: DOMAIN,
        port: 443,
        path: '/k/v1/add-record.json',
        method: 'POST',
        headers: headers
    };

    var req = https.request(options, function (res) {
        var data = '';
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
        data += chunk;
    });
    res.on('end', function () {
        context.done(null, JSON.parse(data));
    })
});
req.on('error', function (e) {
    console.log('problem with request: ' + e.message);
});

req.write(postData);

req.end();};

And this the response I'm getting:
{code: "CB_IJ01", id: "FyttteBzB4eDaWEwoNUO", message: "Invalid JSON string."}

In advance thanks for your help!

A: When you are executing, please try encoding the body using JSON.stringify.
The part,
data: JSON.stringify({ body }),
You might be seeing the error because it has the "{}'s".
Change it to,
data:JSON.stringify(body)
Thanks


text:
Q: Upgrade to the Firebase Crashlytics iOS SDK objective-c, @import FirebaseCrashlytics not found I am converting Fabric iOS SDK to Firebase Crashlytics iOS SDK
I follow below firebase google docs link https://firebase.google.com/docs/crashlytics/upgrade-sdk?platform=ios
I already Installed pod according to link
pod 'Firebase/Crashlytics'
pod 'Firebase/Analytics'

According to docs when I try to import @import FirebaseCrashlytics . I get an error like @import FirebaseCrashlytics module not found.
I did not understand below code in firebase google docs link
${PODS_ROOT}/FirebaseCrashlytics/run
/path/to/pods/directory/FirebaseCrashlytics/upload-symbols.

Let me correct if I am wrong anywhere

A: You have to run the script using Mac terminal by using the below command for dSYM upload.
1). project/ios% pod install
2). cd ..
3). project% /path/to/pods/directory/FirebaseCrashlytics/upload-symbols -gsp /path/to/GoogleService-Info.plist -p ios /path/to/downloaded dSYMs


text:
Q: What was this user trying to hack and is it possible? I randomly got on my website today and happened to notice this:
String.fromCharCode(67, 79, 78, 67, 65, 84, 95, 87, 83, 40, 67, 72, 65, 82, 40, 51, 50, 44, 53, 56, 44, 51, 50, 41, 44, 117, 115, 101, 114, 40, 41, 44, 100, 97, 116, 97, 98, 97, 115, 101, 40, 41, 44, 118, 101, 114, 115, 105, 111, 110, 40, 41, 41)

Someone tried entering a string. Confused, I looked it up and found out I can translate it.
CONCAT_WS(CHAR(32,58,32),user(),database(),version())

What does this information reveal and can you actually get into a database from javascript?

A: I think it is important to recognize that your website will likely be under attack no matter how secure you make it. That's why we make things secure, right? First rule is don't panic!
Just because someone searches for http://example.com/q=<script>alert('xss')</script> doesn't mean you are vulnerable to cross site scripting. They are checking to see if you are.
Just because someone tries to make their username ' OR 1=1-- doesn't mean you have a SQL injection vulnerability.
The person/bot who entered this text was probing to see if you were vulnerable to SQL injection. CONCAT_WS(CHAR(32,58,32),user(),database(),version()) is just an attempt at blind SQL injection to see if they can insert something and get the database to return data. This information is not particularly valuable, but the fact that they can get it would be. The next thing to do would be to modify or dump your database (or maybe even just tell you about the vulnerability) depending on their motives.
We can't really tell you if you are vulnerable from anything just from the information given. Just that someone was attempting to probe your site for vulnerabilities, which happens all the time to many, many people.
So basically, the user was testing to see if you were vulnerable (not necessarily malicious), but we can't tell you if your system is weak to this. It would depend on how you handled that string.

A: With the help of the comments from Zachrip and Marc B:

He was attempting to SQL inject you. Javascript itself can't touch
  your DB, but that translated string can do some things (it would
  concatenate a string using those functions). –  Zachrip
it's an sql injection attack attempt. it'd reveal details about your
  DB and the account used to connect to it. e.g. root: mysql : 5.5.56 –
  Marc B

(pointed by user Rocket Hazmat, CHAR(32,58,32) translates to ' : ')
And for your concern (very good concern):
This itself wouldn't make an intruder able to get inside your db. This would give - maybe/probably - valuable informations for the attacker, although. With more information, more windows get open for exploitment.


text:
Q: How can I turn this array structure into this other pattern? From this:
[["a", "b"], ["a", "c"], ["a", "d"], ["d", "e"], ["d", "f"], ["f", "g"]]
To this:
[["a", "b"], ["a", "c"], ["a", "d", "e"], ["a", "d", "f", "g"]]
The first element of each inner array represents a "father" and the second one a "son", so the final goal is to find grandsons, grandgrandsons... and then group them in bigger arrays, where all descendants are together.
Maybe it's an easy task, but I've been struggling to figure out how to get it!

A: If you like to get all relations, without parts which are included in other results, you could get an object of all descendant and start with the parents who are not having parents.

let
    getNodes = k => parents[k]
        ? parents[k].flatMap(getNodes).map(a => [k, ...a])
        : [[k]],
    data = [["a", "b"], ["a", "c"], ["a", "d"], ["d", "e"], ["d", "f"], ["f", "g"]],
    parents = {},
    children = new Set,
    result;

for (const [p, c] of data) {
    (parents[p] ??= []).push(c);
    children.add(c);
}

result = Object
    .keys(parents)
    .filter(p => !children.has(p))
    .flatMap(getNodes);

result.map(a => console.log(...a));


text:
Q: Displaying Source Code of HTML I'm creating a Feature Index for a website and I thought that it would be nice if the user could just click on a link to view the source code instead of using the browser developer tools. After some research I found that we can easily view the source code of the current page like this:
View Source

Sadly, i'm kind of a big javascript noob still and was wondering if there is a way to hyperlink to the source code of other HTML pages on the site.
Thanks

A: Please note that the view-source protocol is blocked in several browsers
If you need to show the source of the page and other pages on the same site, you might do something like this assuming the html is well formed - I am using jQuery to get the data by the way (note link 2-4 will not work in this demo) :

    $(function() {
      $(".codeLink").on("click", function(e) {
        e.preventDefault(); // cancel the link
        if (this.id == "thispage") {
          $("#codeOutput").html(("" + $("html").html() + "").replace(/</g, "<"));
        } else {
          $.get($(this).prop("href"), function(data) {
            $("#codeOutput").html(data.replace(/</g, "<"));
          });
        }
      });
    });
    code {
      display: block;
      white-space: pre;
      font-family: Consolas, Courier, monospace;
    }

Source of this page

Source of page 2

Source of page 3

Source of page 4

A: Yeah, exactly the same as you did now: direct the user to the url with view-source: prepended to the url. Example given, view-source:http://www.stackoverflow.com will direct your visitor to the source of stackoverflow. But beware that this depends solely on the browser you are using, meaning: some users will see the source, other users might not.
And a bonus jquery to convert all source code links (with class 'source') (not tested)
Page 1 (source)
Page 2 (source)
External (source)

jQuery(document).ready(function ($) {
    $('a.source').each(function() {
        $(this).attr('href', 'view-source:' + $(this).attr('href'));
    });
});

A: You can use this.

View Source

A: As explained on this site, you need to append the full url to the view-source: part.
window.location = 'view-source:' + window.location;

However, it might be better to either create a plain text copy (as a .txt file) or use php to set the documents header of Content-Type to text/plain, to ensure that all users are able to use the feature, no matter what browser they're using.


text:
Q: Immutable js : how to compare List with same contents and different ordered? I am trying to compare different orderd List of Immutable js.
I thought "equals" would be work, but it is only true when is same order.
is there any way to compare for containing same content?
var list1 = Immutable.List.of({a:1},2,{b:3},4);
var list2 = Immutable.List.of(2,{a:1},4,{b:3});
console.log(list1.equals(list2)) //false

A: There are two problems:

*

*by definition, order is essential to lists

*Two ordinary Javascript objects are never equal to each other, even if they have the same contents.

You could, however, do this:
const set1 = Immutable.Set.of(Immutable.Map({a:1}),2,Immutable.Map({b:3}),4);
const set2 = Immutable.Set.of(2,Immutable.Map({a:1}),4,Immutable.Map({b:3}));
console.log(set1.equals(set2)) //true

Nota bene: using var with an immutable defeats the entire purpose! . Use const.


text:
Q: Shell script - child - background process I have the following situation :
As root Script_A.sh is run on the server and sleeps until triggered.
When triggered, it calls Script_B.sh, which loops on the server to determine which actions it needs to perform. Once it generates its list of actions, it will submit Script_C.sh as the process owner (su - $sUser -c "/path/to/correct/script.sh").
My problem: is there a way to run the su - $sUser -c "/path/to/correct/script.sh" in background? I do not want to run the 3rd script sequentially.

A: It works fine for me to just put & at the end as usual:
su - "$sUser" -c "/path/to/script.sh" &

If that doesn't work for you you'll need to edit your question to include more details about your problem.

A: Appending an & to the command is the way to run a command in the background. So:
su - $sUser -c "/path/to/correct/script.sh" &

Or if you want to make sure the script won't receive a SIGHUP (hang up signal) from script B use disown
su - $sUser -c "/path/to/correct/script.sh" & disown

I'm not 100% sure that this is going to have the exact effect that you need, as there may be side-effects from using su.
The nohup command is also useful for this type of endeavour, as it stops any output to the terminal, but it depends on your particular circumstances.
This answer has more clarification on the use of &, disown and nohup.


text:
Q: Run python script inside php I am trying to run a python script in php to test file reading so i can continue my work and do more code. I tried with a small txt file and php file but the output of python script is an empty string. All the files are in the same directory and i am using XAMPP in VISTA OS.
php file
<?php

$validation= exec('python script.py juliodantas.txt') ;
echo $validation ;

var_dump($validation);

?>

python file: (script.py)
#!C:\Python27\python.exe
print "Content-Type: text/html\n"

import sys
fich_input= sys.argv[1]

def test(fich):
    input_fil=open(fich,'r')
    s=''
    cont=0
    for line in input_fil:
        cont+=1
        s+=line
    return (line,cont)

test(fich_input)

txt file is tab formated file  (juliodantas.txt)
CAS Smiles  InchI   Mol_name    LAB Institution Species Cell_type   Subcellular Bio_target  Conditions  Asay_parameter  Observations    Assay_ID    strain  Tissue  target_type value   Unity   Comparisons Experimental_error
12233   535 2435d   3r5rg   4t4t    4t  4t34t4  4t4t4   4trgdf  vgery4  345y4   grfbg   gergh   hj6yu   wde kukl    derj,.i gjyy    htht5u  thyt5   tht56   thtrj4yeg
the output of php:
string(0) ""

A: If I may quote the manual for exec():

The last line from the result of the command.

Your Python program prints out "Content-Type: text/html\n", so the last line of its output is an empty line.
If you want the whole output of the program inside a variable, use the second, optional parameter of exec:
$validation = "";
exec('python script.py juliodantas.txt', $validation);

echo impode("\n", $validation); // should print "Content-Type: text/html\n"

Update:
I've previously used the deprecated (and apparently, now removed) call-with-pass-by-reference syntax. Shame on me. Also, apparently exec() returns the output as a line-based array, so you've got to join it if you want to have it as a single string.


text:
Q: Which Green Lantern characters appear in war with Darkseid? In the movie Justice League Dark: Apokolips War when Darkseid attacks the planet of Oa he has a fight with members of the Green Lantern Corps. There were 4-5 members who are killed by Darkseid in the fight. They appear to be important members of the Green Lantern Corps. Which members were present there in the fight with Darkseid, help me identify them by naming them?
The images of the Green Lanterns from the fight are given below

A: All the Green Lanterns that appear in the movie are:
Arisia

Arkkis Chummuck

Chaselon

Galius Zed

Green Man

Guy Gardner

John Stewart

Kilowog

Palaqua (not 100% sure on this one)

Salakk

A: These are the GLs from your images
Image 1: John Stewart

Image 2 Three GLs(left to right):

*

*Galius Zed

*Arkkis Chummuck

*Green Man

Image 3: The GL jumping on Darkseid Kilowog

NOTE: All images taken from Justice League: The Animated Series

PS: In addition to the GLs in your question, the other lanterns in the movie are mentioned here (apart from John and Kilowog as they are quite well-known):

[...] members of the Green Lantern Corps (Arisia Rrab, Arkkis Chummuck, Chaselon, Galius Zed, Green Man, Guy Gardner, Palaqua, and Salaak) all have non-speaking roles and cameos, being left as minor characters.


text:
Q: Accessing the music files in iPhone I need to build a system which backup and restore system in which all the phone datas
including audio, video, pictures. From iPhone 4.0 , there is support for accessing the videos
and photos from the library . Is there any way to access the music files. I need to convert those music files into binary format . Is there any way to accomplish this...
awaiting for the response
Best Regards,
Mohammed Sadiq.

A: Mohammed,
Please see the Add Music example on Apple's website:
http://developer.apple.com/iphone/library/samplecode/AddMusic/Introduction/Intro.html
-Rob