text:
Q: Как отобразить уведомление единожды в день в строго определённое время? Собрался сделать напоминание пользователю типа "зайдите в игру, соберите денежки". Уведомление должно появляться каждый день ровно в 12:00. Не понимаю - оно появляется, не обращая внимания на календарь!
Вот мой MainActivity.java
public class MainActivity extends Activity
{

 AlarmManager alarmManager;

 private PendingIntent alarmIntent;

 @Override
 protected void onCreate(Bundle savedInstanceState)
{ //начало onCreate

  super.onCreate(savedInstanceState);

        alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

        Intent intent = new Intent(this, AlarmReceiver.class);
        alarmIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 00);
    long timeToStart = calendar.getTimeInMillis();
    if(System.currentTimeMillis() < timeToStart){
        timeToStart += 24 * 60 * 60 * 1000; // one day
    }
    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, timeToStart, AlarmManager.INTERVAL_DAY, alarmIntent);
}
} // конец class

Вот мой AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        Toast.makeText(context,"Alarm Raised",Toast.LENGTH_SHORT).show();
        NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        Intent intent1 = new Intent(//что писать???);
        PendingIntent pendingIntent=PendingIntent.getActivity(context,0,intent1,0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setSmallIcon(R.drawable.ic_launcher);
        builder.setContentTitle("Тест");
        builder.setContentText("Тест");
        builder.setPriority(Notification.PRIORITY_MAX);
        builder.setDefaults(Notification.DEFAULT_SOUND);
        builder.setLights(0x0000FF,3000,2000);
        builder.setContentIntent(pendingIntent);
        notificationManager.notify(56, builder.build());
    }
}

И блок кода в манифесте
 <receiver    android:name="ru.diskrim.nebo.AlarmReceiver"
          android:enabled="true"
          android:exported="true"
      >

Уведомление появляется при запуске MainActivity. А должно ровно в 12:00 только когда приложение закрыто.

    alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, AlarmReceiver.class);
    alarmIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 16);

long timeToStart = calendar.getTimeInMillis();
if(System.currentTimeMillis() < timeToStart){
    timeToStart += 24L * 60L * 60L * 1000L; // one day
}
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, timeToStart, AlarmManager.INTERVAL_DAY, alarmIntent);

Теперь уведомление вообще не отображается. В 16:00 ничего не произошло. Пробовал когда приложение и открыто, и закрыто...

A: Ошибка скорее всего тут
calendar.set(Calendar.HOUR_OF_DAY, 00);

Вы сбрасываете время на ноль часов текущего дня, что всегда меньше текущего времени. Поэтому это условие всегда false
if(System.currentTimeMillis() < timeToStart){
    timeToStart += 24 * 60 * 60 * 1000; // one day
}

И как результат, будильник всегда в прошлом и "звонит" сразу же.


text:
Q: How can I get the activeClass to work with static pages after a Next.js export? I'm creating a small website with next.js in order to deploy on Github as a static HTML website. I'm having some problems with the classic "active" navbar classes. Is there any way to get Next to export the appropriate active classes when compiling the static pages?
I have a navbar component which is added to a layout component and used on both pages:
const Navbar = () => (

<Link activeClassName="active" href="/">About Me</Link>

<Link activeClassName="active" href="/skills">Skills</Link>

);

export default Navbar;

And I have this link component which applies the active class when the application is deployed locally:
import { withRouter } from 'next/router'
import Link from 'next/link'
import React, { Children } from 'react'

const ActiveLink = ({ router, children, ...props }) => {
    const child = Children.only(children);

    let className = child.props.className || null;

    if (router.pathname === props.href && props.activeClassName) {
        className = `${className !== null ? className : ''} ${props.activeClassName}`.trim();
    }

    delete props.activeClassName;

    return <Link {...props}>{React.cloneElement(child, { className })}</Link>
}

export default withRouter(ActiveLink);

This code works perfectly while I'm running it locally as a react app, but if I export to /out as static HTML the active classes no longer get applied. I'm not quite sure how to fix this and I've been looking everywhere. I keep finding conflicting answers and nothing seems to work. I can post more of my code if necessary.

A: import { withRouter } from 'next/router'
import Link from 'next/link'
import React, { Children } from 'react'

const ActiveLink = ({ router, children, ...props }) => {
    debugger;

    console.log(JSON.stringify(`Props: ${props}`))

    console.log(JSON.stringify(`Router: ${router}`))

    const child = Children.only(children);

    let className = child.props.className || '';

    const { activeClassName, ...restProps } = props;

    if (router.pathname === props.href && activeClassName) {
        className = `${className} ${props.activeClassName}`.trim();
    }

    return <Link {...restProps}>{React.cloneElement(child, { className })}</Link>
}

export default withRouter(ActiveLink);

Try using Node debugger with Chrome in VSCode to step through this component in both static and SSR modes and see what the difference is.
Otherwise try pasting the console output into JSONEditorOnline and checking there.
We know the answer has to do with this line
    if (router.pathname === props.href && props.activeClassName) {

redpajama_set_name: RedPajamaStackExchange


text:
Q: Emulating a web browser to wrap the functionality of several similar web sites I'm interested in emulating the functionality of a web browser in C++ so that I can create a wrapper for several web sites. Right now, the biggest issues with these sites are that they make heavy use of JavaScript that interacts with the HTML DOM. Thus, the simple solution of using curl to download the page, and something like RapidXML to parse its contents is out.
Next, I considered using something like v8 with curl, and that solves the issue of interpreting the JavaScript on the page nicely. However, it doesn't solve the issue of connecting the HTML DOM methods with the JavaScript; in other words, document.getElementById() would fail in v8.
Next, I considered WebKit, which seems like it's perfectly suited to emulate a web browser--after all, Chromium and Safari both utilize it in their web browsers. However, it's a little too complete. I don't need all of the rendering aspects it includes.
So, I'd be looking for some way to:

*

*Make an SSL connection to a web site

*Interpret the JavaScript on that web site in connection with the HTML DOM

*Set the value of the username/passwords <input> fields with my username and password

*Simulate clicking the "Submit" button by calling the formSubmit() function, from <input type="button" onClick="formSubmit()">

*Handle the HTTP POST form action and the subsequent HTTP 301 and JavaScript redirects (accomplished using window.location)

*Repeat 2-5 as needed

Besides what I've already considered, what other options do I have? Ideally, I'd want this to be extremely lightweight, without requiring linking to many libraries.
I'm primarily concerned with developing for Windows 7 64-bit.

A: Well, this sounds all too much like a brute-force program. Disregarding that, and since you don't seem to need to render any website, I think you should just fetch the file through cURL or something, then parse it, check for the form through using a regex, retrieve the form action, then make a request using the method taken from the <form> tag and whichever input you want.
Problem is, there would be no proper way to know when is it that you've logged in properly, unless you made some kind of per-site checking. This comes mainly from the fact that many sites use sessions rather than direct cookies or HTTP auth, and since you can't read from sessions directly, it is impossible for you to guess when the session has changed.
That's the most lightweight solution I can come up with right now.


text:
Q: Encoding error using wicked_pdf and rails ActiveJob I am using wicked-pdf to simplify generating pdf invoices in my Rails 5 application. I have two actions making use of the pdf functionality of wicked-pdf. The first action generates the pdf and renders it in a new browser window. The second method attaches the pdf to an email.
Both of these actions work just fine. The issue comes in when I set my pdf mailer action to 'deliver_later' using ActiveJob/Sidekiq. When I add 'deliver_later' I am presented with a error stating:

"\xFE" from ASCII-8BIT to UTF-8

This error does not happen if I use the "deliver_now" command. Using "deliver_now" send the email and attaches the PDF correctly.
Here is some of my code for the mailing action, mailer and job:
invoices_controller.rb
...
def create
  respond_to do |format|
    format.html do
      pdf = render_to_string( pdf: @order.ruling_invoice,
                          template: "orders/invoices/show.pdf.haml",
                          encoding: "utf8",
                          locals: { order: @order.decorate}
                        )
      SendInvoiceMailJob.new.perform( @order, pdf, @order.token )
      redirect_to order_url(id: @order.id, subdomain: current_company.slug),     notice: "This invoice has been emailed."
    end
  end
end
...

send_invoice_mail_job.rb
...
def perform( order, pdf, order_token )
  InvoiceMailer.send_invoice(order, pdf, order_token).deliver_later
end
...

invoice_mailer.rb
...
def send_invoice( order, pdf_invoice , invoice_token)
    @order = order
    attachments["#{invoice_token}.pdf"] = pdf_invoice
    mail(
    to: @order.email,
        from: @order.seller_email
    )
end
...

Why would this code work using "deliver_now" in send_invoice_mail_job.rb but it doesn't work using "deliver_later" ?

A: You can't just throw binary data (the PDF) into job arguments.
https://github.com/mperham/sidekiq/wiki/Best-Practices#1-make-your-job-parameters-small-and-simple

A: You need to move the PDF compiling from outside of your mailer job to inside it. So in your controller, you can do:
SendInvoiceMailJob.new.perform(@order, @order.token)

Then in your mailer job you can do:
def send_invoice(order, invoice_token)
    @order = order

    pdf = render_to_string(
      pdf: @order.ruling_invoice,
      template: "orders/invoices/show.pdf.haml",
      locals: { order: @order.decorate }
    )                        )

    attachments["#{invoice_token}.pdf"] = pdf_invoice
    mail(
    to: @order.email,
        from: @order.seller_email
    )
end

That way you're not passing the PDF binary into the jobs queue.


text:
Q: How can I ensure that I install compatible versions of JAGS and rjags in Ubuntu? I would like to write a script that installs JAGS and rjags on a new ubuntu installation, and that will work independently of the currently available versions of these packages. I'd like to know how I can do this while avoiding conflicts between versions.
I have the following R script, initialize.R:
system('apt-get install jags')
install.packages('rjags')

So that I can run from bash:
sudo R --vanilla < initialize.R

However, the most recent version of JAGS in the Ubuntu repository is 2.2, and the version of rjags available from CRAN depends on JAGS > 3.0.
I am interested in installing compatable JAGS and rjags, perhaps either:

*

*installing a specific version of JAGS (e.g. 2.2) and the compatable rjags version (which version?)

*generically installing the version of JAGS currently in the ubuntu repository and the appropriate rjags version, or

*generically installing the most recent version of rjags at cran and the appropriate version of JAGS

The ability to do case 1 is essential, but am also curious how I could implement cases 2 and/or 3.
questions:

*

*How can I do this?

*Is there a more sound approach?

update: following link in Dirk's answer, the following worked:
add-apt-repository ppa:marutter/rrutter
apt-get update
apt-get install r-cran-rjags

A: Michael Rutter provides an r-cran-rjags package via his repository; this works with the jags package you already have installed.  See  this message on r-sig-devel for details, and you may want to subscribe to and follow the r-sig-debian list to stay abreast of these things.


text:
Q: WhenEvent - energy conservation not valid I would like to simulate the following conservative system, with purely elastic impacts (coefficient of restitution is 1). Applying the WhenEvents the energy of the system is not conserved.
How can I correct this?

T = 10;
a = 0.1;
b = 0.1;
c = 1
{solu[t_], {data}} =
  Reap[NDSolveValue[{a*u1''[t] + b*(u1[t] - u2[t]) == 0,
     u2''[t] + u2[t] + b*(u2[t] - u1[t]) == 0, u1[0] == 0,
     u1'[0] == 3, u2[0] == 0, u2'[0] == 0,
     WhenEvent[Abs[(u2[t] - u1[t])] == c, Sow[{t, u2[t] - u1[t]}]],
     WhenEvent[
      Abs[(u2[t] - u1[t])] ==
       c, {u1'[t] -> ((a - 1)*u1'[t] + 2*u2'[t])/(1 + a),
       u2'[t] -> (2*a*u1'[t] + (1 - a)*u2'[t])/(1 + a)} ]},
    {u1[t], u2[t], t}, {t, 0, T}, MaxStepSize -> 0.001]];

Plot[a*(solu'[t][[1]])^2 + (solu'[t][[2]])^2 +
  b*((solu[t][[1]]) - (solu[t][[2]]))^2 + (solu[t][[2]])^2, {t, 0, T},
  PlotRange -> {{0, T}, All}, Frame -> True,
 FrameLabel -> {"t", "Energy"}]

A: Apparently, we need to show the corrected code and the result
T = 10;
a = 1/10;
b = 1/10;
c = 1;
{U1, U2, U11, U21} =
  NDSolveValue[{a*u1''[t] + b*(u1[t] - u2[t]) == 0,
    u2''[t] + u2[t] + b*(u2[t] - u1[t]) == 0, u1[0] == 0, u1'[0] == 3,
     u2[0] == 0, u2'[0] == 0,
    WhenEvent[
     Abs[u2[t] - u1[t]] ==
      c, {u1'[t],
       u2'[t]} -> {((a - 1) u1'[t] + 2 u2'[t])/(1 +
          a), (2 a u1'[t] + (1 - a) u2'[t])/(1 + a)}]}, {u1, u2, u1',
    u2'}, {t, 0, T}, WorkingPrecision -> 30];
energy[t_] :=
 a*(U11[t])^2 + (U21[t])^2 + b*((U1[t]) - (U2[t]))^2 + (U2[t])^2
Plot[energy[t] - energy[0], {t, 0, T}, PlotRange -> {{0, T}, All},
 Frame -> True, FrameLabel -> {"t", "Energy"}]

Here, the deviation of energy from the initial value of about $10^{-11}$

On the second fig. the solution is shown
Plot[{U1[t], U2[t]}, {t, 0, 10}]


text:
Q: python comma separate values by thousands without trailing zeros I am trying to comma separate float amount by thousands. I am able to do that using the locale.format() function. But the expected output is not considering the decimal points.
import locale
locale.setlocale(locale.LC_ALL, 'en_US')
amount = locale.format('%d', 10025.87, True)
amount
'10,025'

My expected output should be 10,025.87, keeping the trailing values. Please let me know if something of this sort is possible
Value: 1067.00
Output: 1,067

Value: 1200450
Output: 1,200,450

Value: 1340.9
Output: 1,340.9

A: How about this:
import locale
locale.setlocale(locale.LC_ALL, 'en_US')
# strip any potential trailing zeros because %f is used.
amount = locale.format('%f', 10025.87, True).rstrip('0').rstrip('.')
amount  # '10,025.87'


text:
Q: Regex expression to exclude any number from any place I have a code which takes a string as input and discards all the letters and prints only the numbers which doesn't contain 9 at any of the place.
I have decided to do it with the help of regex but couldn't find a working expression to achieve it where it is needed to be modified?
I have also tried with [^9] but it doesn't work.
import re

s = input().lstrip().rstrip()
updatedStr = s.replace(' ', '')
nums = re.findall('[0-8][0-8]', updatedStr)
print(nums)

The code should completely discard the number which contains 9 at any place.
for example - if the input is:
"This is 67 and 98"

output: ['67']
input:
"This is the number 678975 or 56783 or 87290 thats it"

output: ['56783'] (as the other two numbers contain 9 at some places)

A: I think you should try using:
nums=re.findall('[0-8]+',updatedStr)

Instead.
[0-8]+ means "one or more ocurrences of a number from 0 to 8"
I tried : 12313491 a asfasgf 12340 asfasf 123159
And got: ['123134', '1', '12340', '12315']
(Your code returns the array. If you want to join the numbers you should add some code)

A: It sounds like you wan't to match all numbers that don't contain a 9.
Your pattern should match any string of digits that doesn't contain a nine but ends and starts with a non-digit
pattern = re.compile('(?<=[^\d])[0-8]+(?=[^\d])')
pattern.findall(inputString) # Finds all the matches

Here the pattern is doing a couple of things.

*

*(?<=...) is a positive look behind. This means we will only get matches that have a non digit before it.

*[0-8]+ will match 1 or more digits except 9

*(?=...) is a lookahead. We will only get matches that end in a non digit.

Note:
inputString does not need to be stripped. And in fact this pattern may run into issues if there is a number at the beginning or end of a string. To prevent this. simply pad it with any chars.
inputString = ' ' + inputString + ' '

Look at the python re docs for more info


text:
Q: Component Event Not working - parameter value not showing in JS Console I added these Console.logs to RowsPerPageController.js

selectedValue prints "5" to Console as expected
But it seems "5" is never added as a param to the event.
Furthermore, in Test1Controller.js I have a console log at the very beginning of function rowsPerPageChange. That never prints, which may indicate the event is not actually firing or being caught by the Parent's handler.
I've been at this for some hours and had another pair of eyes on it :| Your help is much appreciated!
My Parent Component: Test1.cmp
<aura:component access="public" implements="force:appHostable,lightning:isUrlAddressable,flexipage:availableForAllPageTypes" controller="FirebirdOrganizationsController">
<aura:attribute name="quanitySelected" type="String" default="0"/>

<aura:handler name="RowsPerPageEvent"
                event="c:RowsPerPageEvent"
                action="{!c.rowsPerPageChange}" />

<c:RowsPerPage/>

Test1Controller.js
({
doInit: function(component, event, helper) {

},
rowsPerPageChange : function(component, event, helper) {
    console.log("In Parent JS: rowsPerPageChange function");
    component.set("v.quanitySelected", event.getParam("rowsPerPage"));
    var test = component.get("v.quanitySelected");
    console.log(test);
    //helper.getDataBasedOnRowsPerPage(component, helper);
}

})
RowsPerPageEvent.evt
<aura:event type="COMPONENT" description="Rows Per Page Event">
<aura:attribute name="rowsPerPage" type="String" default="0"/>

My Child Component: RowsPerPage.cmp
<aura:component>
<aura:registerEvent name="RowsPerPageEventChange" type="c:RowsPerPageEvent" />

Show

    <ui:inputSelect value="20" aura:id="rowsPerPageSelect" change="{!c.rowsPerPageChange}">
        <ui:inputSelectOption text="5" value="5"/>
        <ui:inputSelectOption text="10" value="10"/>
        <ui:inputSelectOption text="20" value="20"/>
        <ui:inputSelectOption text="30" value="30"/>
    </ui:inputSelect>

RowsPerPageController.js
({
rowsPerPageChange : function(component, event, helper)
{
    var selectedValue = component.find("rowsPerPageSelect").get("v.value");
    console.log("### selectedValue: ", selectedValue);
    var rowsPerPageChangeEvent =
        component.getEvent("RowsPerPageEventChange");
        console.log("getEvent: ", component.getEvent("RowsPerPageEventChange"));
        rowsPerPageChangeEvent.setParams({
            "rowsPerPage" : selectedValue
        });
    console.log("getEvent: ", component.getEvent("RowsPerPageEventChange"));
    console.log("### rowsPerPageChangeEvent: ", rowsPerPageChangeEvent);

    rowsPerPageChangeEvent.fire();
}

})

A: Okay I felt bad we weren't able to solve it yesterday, so I went and created a mock of your components in a dev box.  I have the event firing, listening, and logging on both ends properly. Here's the code:
Parent.cmp:
<aura:attribute name="quanitySelected" type="String" default="0"/>

<aura:handler event="c:RowsPerPageEvent"
              action="{!c.rowsPerPageChange}" />

<c:RowsPerPage/>

Parent.js
rowsPerPageChange : function(component, event, helper) {
    console.log(event.getParam('rowsPerPage'));
}

Event component did not change - use your original one.
RowsPerPage.cmp:
<aura:registerEvent name="rowsPerPageEvent" type="c:RowsPerPageEvent" />

Show

    <ui:inputSelect value="20" aura:id="rowsPerPageSelect" change="{!c.rowsPerPageChange}">
        <ui:inputSelectOption text="5" value="5"/>
        <ui:inputSelectOption text="10" value="10"/>
        <ui:inputSelectOption text="20" value="20"/>
        <ui:inputSelectOption text="30" value="30"/>
    </ui:inputSelect>

RowsPerPageController.js:
rowsPerPageChange : function(component, event, helper) {
    var selectedValue = component.find("rowsPerPageSelect").get("v.value");
    console.log("### selectedValue: ", selectedValue);
     var rowsPerPageEvent = $A.get("e.c:RowsPerPageEvent");
    rowsPerPageEvent.setParams({
        "rowsPerPage": selectedValue
    });
    console.log('prefire')
    rowsPerPageEvent.fire();

}

A: Everything in my original post is fine except for...
name in the handler (on Parent .cmp)
    <aura:handler name="RowsPerPageEvent"
                event="c:RowsPerPageEvent"
                action="{!c.rowsPerPageChange}"/>

did not match name in the registerEvent (on Child .cmp)
<aura:registerEvent name="RowsPerPageEventChange" type="c:RowsPerPageEvent" />

ALSO, includeFacets="true" was needed on the handler
So replace handler in my original post with this, and it works perfectly...
    <aura:handler name="RowsPerPageEventChange"
                event="c:RowsPerPageEvent"
                action="{!c.rowsPerPageChange}"
                includeFacets="true" />


text:
Q: Hadoop learning development workflow with Eclipse and AWS I have Installed a single node hadoop 2.8 on AWS free tier nano instance. I have a local windows machine with eclipse on it. What is a good learning workflow. I am not sure of capabilities of AWS orhadoop. Should I write code in local eclipse build a jar, transfer it AWS machine and run it?
If I have to write and create a jar from local machine should I have hadoop installed? how should I do? and What is good learning path from installation to being comfortable with working on hadoop?


text:
Q: Formatting python dictionaries with break lines I have this dictionary;
results = {'name': sectionAddr.name,
               'count': sampleCount,
               'finish_count': len(finished),
               'inside4_count': inside4Count,
               'inside10_count': inside10Count,
               'finish_rate': 100 * len(finished) / sampleCount,
               'inside4_rate': 100 * inside4Count / sampleCount,
               'inside10_rate': 100 * inside10Count / sampleCount,
               'mean_error': meanError,
               'stddev_error': stddevError,
               'samples': sampleResults}
    results['error'] = getError(results

But I need do display it; and if i do that by the formatting to str, it looks like a string, i.e. a line. How i should to break line after the each variable?
Something like that:
results = {'name': sectionAddr.name + '\n',
'finish_count': len(finished), ...

doesn't work,
how I can break lines?

A: A pretty print would probably meet your needs;
import pprint
pprint.pprint(result)

If you don't feel like using pretty print;
result = {'a': '1',
          'b': '2',
          'c': '3'}

print('\n'.join(('\t'.join(item) for item in result.items())))

Outputs;
a   1
c   3
b   2

A: You can use pprint.pformat to get a nicely formatted string:
import pprint

results = {'name': "sectionAddr.name",
               'count': "sampleCount",
               'finish_count': "len(finished)",
               'inside4_count': "inside4Count",
               'inside10_count': "inside10Count",
               'samples': "sampleResults"}

s = pprint.pformat(results)

print(s)

Output:
{'count': 'sampleCount',
 'finish_count': 'len(finished)',
 'inside10_count': 'inside10Count',
 'inside4_count': 'inside4Count',
 'name': 'sectionAddr.name',
 'samples': 'sampleResults'}

Or, if you do not need it as a string but want to print to the console directly, you can use pprint.pprint:
pprint.pprint(results)

Note that a dictionary has no fixed order, so the keys in the formatted string might be in different order.
Both pformat and pprint accept additional parameters, so you can modify the result: docs

A: Python Pretty Printer Documentation
>>> import pprint
>>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
... ('parrot', ('fresh fruit',))))))))
>>> stuff = ['a' * 10, tup, ['a' * 30, 'b' * 30], ['c' * 20, 'd' * 20]]
>>> pprint.pprint(stuff)
['aaaaaaaaaa',
 ('spam',
  ('eggs',
   ('lumberjack',
    ('knights', ('ni', ('dead', ('parrot', ('fresh fruit',)))))))),
 ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
 ['cccccccccccccccccccc', 'dddddddddddddddddddd']]

Your use-case:
import pprint
pprint.pprint(results)


text:
Q: How say to some behavior attach to all ui elements of some type by defaut? For example, I want have all MediaElements in my app that after mouse click on mediaelement leads to play/pause/play/pause... It is possible to say such behavior to attach to all associated elements in app?

A: It is straight forward to iterate through all the children of the grid and attach the event appropriately.
In your XAML be sure to give a name for your grid:
    <Grid x:Name="gr01"...

You can write a function for attaching the events and call that in the Window_Loaded event.
namespace AttachEventDemo {
   public partial class MainWindow : Window {
      // ... usual initialization code goes here
      private void Window_Loaded( object sender, RoutedEventArgs e ) {
         AttachEvent( );
      }

      private void AttachEvent( ) {
         foreach ( var item in gr01.Children ) {
            switch ( item.GetType( ).ToString( ) ) {
               case "System.Windows.Controls.Button":
                  Button b = item as Button;
                  b.Click += b_Click;
                  txtLog.Text = "Added click event for button " + b.Name + Environment.NewLine + txtLog.Text;
                  break;

               case "System.Windows.Controls.CheckBox":
                  CheckBox cb = item as CheckBox;
                  cb.Checked += cb_Checked;
                  txtLog.Text = "Added click event for checkkbox " + cb.Name + Environment.NewLine + txtLog.Text;
                  break;

               default:
                  break;
            }
         }
      }

      void cb_Checked( object sender, RoutedEventArgs e ) {
         CheckBox cb = sender as CheckBox;
         txtLog.Text = "CheckBox " + cb.Name + " checked changed!" + Environment.NewLine + txtLog.Text;
      }

      private void b_Click( object sender, RoutedEventArgs e ) {
         Button b = sender as Button;

         txtLog.Text = "Button " + b.Name + " was clicked!" + Environment.NewLine + txtLog.Text;
      }
   }
}


text:
Q: tikzpicture graph does not output correctly upon printing Could you please tell me why these graphs B and E would print with unwanted borders like they do in the screenshot?

Please note that I have applied the same setting for every graph on this page and it is only B and E have this issue erroneously.
The pdf version latex compiles is attached which looks perfect.

Many thanks
Edit: The following is the corrected code for the graph B. The domain of the graph was -7:7 before which caused the problem in the graph, and E had the same problem. I hope this helps!
\pgfplotsset{every axis/.append style={
axis x line=middle,    % put the x axis in the middle
axis y line=middle,    % put the y axis in the middle
title={$ $},
axis line style={<->}, % arrows on the axis
xlabel={$x$},          % default put x on x-axis
ylabel={$y$},          % default put y on y-axis
ticks=none
}}
\begin{tikzpicture}
\begin{axis}[
xmin=-2,xmax=2,ymin=-1.4,ymax=1.4
]
\addplot[thick,color=black,samples=100,domain=-2:2] {-0.55*(x^3/3-1.25^2*x)};
\end{axis}
\end{tikzpicture}


text:
Q: How to freeze a radio button list at selected radio button in asp.net? How to freeze a radio button list at selected radio button in ASP.net? My code has a radio button list like:

*

*MyPlayer

*MyABC

*MyNum

*MyD

*MyK

*MyM

*MyC

*MyU

*MyY

*MyPop

*MyCost

*MyLast

*MyCo

*MyName

*MyID

*MyCust

*MyStudent

*MyOffice

*MyVehicle

*MyVoucher

These are all in a scrollbar Radio Button List which is fixed upto some height that only top few is visible after page load or refresh. I want to freeze it wherever the selected radio button is, so that user don't have to scroll down to see what he has selected in case he selects the last options of the list.

A: Try this :
ListItem selectedItem = radioButtonList.SelectedItem;
selectedItem.Attributes.Add("onload", "this.focus();");


text:
Q: Get next cell in UIcollectionView in Swift I need to get the next cell inside cellForItem within a collection view so that I can update a view object. When I try the following below it doesn't work. I've also tried indexPathForVisibleItems passing in indexPath.row + 1 and the produces an index out of range error.
    let index = IndexPath(row: indexPath.row + 1, section: indexPath.section)
            if let nextCell = collectionView.cellForItem(at: index) as! MKRCell {
                nextCell.setupWaitView(time: timeToWait)
                nextCell.waitViewHeightConstraint.constant = 80
                nextCell.waitView.alpha = 1
                nextCell.waitView.isHidden = false
            }

Is this possible to achieve or will I need to do this via another way?
Thanks

A: No, it is not possible to get the cell object before initialization in cellForItemAt but here
you can receive the call before displaying the cell from UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView,willDisplay cell: UICollectionViewCell,forItemAt indexPath: IndexPath) {
     if let myCell = cell as? MKRCell {

     }
}

AND
If you want to set up the cell you have to setup view in the UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

}

A: You should update the cell in:
func collectionView(_ collectionView: UICollectionView,
    cellForItemAt indexPath: IndexPath) -> UICollectionViewCell

Remember to modify only the cell you'll be returning from this method. Other cells might not have exist at that moment.
Alternatively you can keep a weak reference to the cell and update it when needed.


text:
Q: How to make my html helpers in razor templates more reusable? I have a form with multiple addresses. A business address, a billing address, and a shipping address. Naturally I want to use the same code.
My razor template looks something like this:

    @Html.TextBoxFor(x => x.BillingAddress.Line2, new { Class = "optional" })
    @Html.ValidationMessageFor(x => x.BillingAddress.Line2)

    @Html.TextBoxFor(x => x.BillingAddress.Line3, new { Class = "optional" })
    @Html.ValidationMessageFor(x => x.BillingAddress.Line3)

....

And when rendered looks something like this:
<input type="text" value="" name="BillingAddress.Line1" id="BillingAddress_Line1" data-val-required="The Street Address field is required." data-val="true" class="text-box single-line">

Now say I will have the same code, for Business and shipping but it will look like this:

      @Html.TextBoxFor(x => x.BusinessAddress.Line2, new { Class = "optional" })

      @Html.TextBoxFor(x => x.BusinessAddress.Line3, new { Class = "optional" })

How can I get rid of this code duplication?

A: The way I do it, is to create strongly typed Display/Editor templates for "Address".
Then call @Html.EditorFor(x=>x.BusinessAddress) or @Html.DisplayFor(x=>x.BusinessAddress)
You can also create different templates for different uses, and then optionally supply the name of the template in the Editor/DisplayFor methods.
BTW, the templates I mention may reside in the ~Views/Shared/EditorTemplates or ~Views/Shared/DisplayTemplates folders, respectively. Or they may reside with in a specific Controllers views folder, under EditorTemplates or DisplayTemplates.
Edit: Here is a link that demonstrates this.
Editor Tempates
Edit 2: Here is an example to try and explain further, per your comment.
Address Model
public partial class Address
{
    public int AddressId { get; set; }
    public string Street1 { get; set; }
    public string Street2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
}

Editor Template: This file is named "Address.cshtml" and located in my "~Views/Shared/EditorTemplates" folder.
@model Address

@Html.HiddenFor(model => model.AddressId)

    @Html.LabelFor(model => model.Street1)

    @Html.EditorFor(model => model.Street1)
    @Html.ValidationMessageFor(model => model.Street1)

    @Html.LabelFor(model => model.Street2)

    @Html.EditorFor(model => model.Street2)
    @Html.ValidationMessageFor(model => model.Street2)

    @Html.LabelFor(model => model.City)

    @Html.EditorFor(model => model.City)
    @Html.ValidationMessageFor(model => model.City)

    @Html.LabelFor(model => model.State)

    @* Populated from Helper *@
    @Html.DropDownListFor(m => m.State, new SelectList(statesDictionary, "Key", "Value"), string.Empty)
    @Html.ValidationMessageFor(model => model.State)

    @Html.LabelFor(model => model.Zip)

    @Html.EditorFor(model => model.Zip)
    @Html.ValidationMessageFor(model => model.Zip)

Create View: This is my view that will implement the editor template for my model. Note the line @Html.EditorForModel();
@model Address

@{
    ViewBag.Title = "Create";
}

Create

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Address</legend>

        @Html.EditorForModel()

            <input type="submit" value="Create" />

    </fieldset>
}

    @Html.ActionLink("Back to List", "Index")

Now if my model for my view was something else, that linked to an "Address", I would have used @Html.EditorFor(model => model.BusinessAddress)
As for the names, that's completely under your control. By default, they get mapped to you property names, but you can change any by supplying an object containing your html attribues in the EditorFor overloads.

A: I don't see any duplication to get rid of in the DRY sense. If you have 3 similar fields on a form, you will need three similar elements in the markup.

A: Why not introduce an AddressType field? All 3 address types you mention share the same fields just their type is different; what will set each appart is the value of AddressType. Make sense?


text:
Q: On Heroku, Error: The hook `grunt` is taking too long to load Trying to deploy a SailsJS app to Heroku for the first time and struggling with it.
My app works properly locally (MacOS X).
$ sails --version
0.12.3

heroku log
heroku logs -a myapp-webrtc
2016-06-02T16:52:45.297076+00:00 app[web.1]:
2016-06-02T16:52:45.297142+00:00 app[web.1]:  *-> You might have a malformed LESS, SASS, CoffeeScript file, etc.
2016-06-02T16:52:45.297191+00:00 app[web.1]:
2016-06-02T16:52:45.297277+00:00 app[web.1]:  *-> Or maybe you don't have permissions to access the `.tmp` directory?
2016-06-02T16:52:45.297383+00:00 app[web.1]:      e.g., `/app/.tmp` ?
2016-06-02T16:52:45.297434+00:00 app[web.1]:
2016-06-02T16:52:45.297485+00:00 app[web.1]:      If you think this might be the case, try running:
2016-06-02T16:52:45.297607+00:00 app[web.1]:      sudo chown -R 58669 /app/.tmp
2016-06-02T16:52:45.297675+00:00 app[web.1]:
2016-06-02T16:53:01.611997+00:00 app[web.1]: Error: The hook `grunt` is taking too long to load.
2016-06-02T16:53:01.612013+00:00 app[web.1]:     at Timer.listOnTimeout (timers.js:198:5) { [Error: The hook `grunt` is taking too long to load.
2016-06-02T16:53:01.612012+00:00 app[web.1]:     at tryOnTimeout (timers.js:224:11)
2016-06-02T16:53:01.612010+00:00 app[web.1]: Make sure it is triggering its `initialize()` callback, or else set `sails.config.grunt._hookTimeout to a higher value (currently 20000)
2016-06-02T16:53:01.612011+00:00 app[web.1]:     at Timeout.tooLong [as _onTimeout] (/app/node_modules/sails/lib/app/private/loadHooks.js:85:21)
2016-06-02T16:53:01.612014+00:00 app[web.1]: Make sure it is triggering its `initialize()` callback, or else set `sails.config.grunt._hookTimeout to a higher value (currently 20000)] code: 'E_HOOK_TIMEOUT' }
2016-06-02T16:53:02.849738+00:00 heroku[web.1]: Process exited with status 0
2016-06-02T16:53:02.872998+00:00 heroku[web.1]: State changed from starting to crashed
2016-06-02T16:53:06.350353+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=myapp-webrtc.herokuapp.com request_id=2d8d592c-b091-4b87-b347-378498e5716c fwd="93.201.9.157" dyno= connect= service= status=503 bytes=
2016-06-02T16:53:06.921700+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=myapp-webrtc.herokuapp.com request_id=df38991d-ef49-4563-a119-034aa717644a fwd="93.201.9.157" dyno= connect= service= status=503 bytes=
2016-06-02T17:15:14.982813+00:00 heroku[web.1]: State changed from crashed to starting
2016-06-02T17:15:24.437298+00:00 heroku[web.1]: Starting process with command `npm start`
2016-06-02T17:15:28.109941+00:00 app[web.1]:
2016-06-02T17:15:28.109962+00:00 app[web.1]: > myapp-sails-website@0.0.0 start /app
2016-06-02T17:15:28.109966+00:00 app[web.1]:
2016-06-02T17:15:28.109965+00:00 app[web.1]: > node app.js
2016-06-02T17:15:32.969953+00:00 app[web.1]: designed for a production environment, as it will leak
2016-06-02T17:15:32.969938+00:00 app[web.1]: Warning: connect.session() MemoryStore is not
2016-06-02T17:15:32.969954+00:00 app[web.1]: memory, and will not scale past a single process.
2016-06-02T17:15:39.385511+00:00 app[web.1]: ------------------------------------------------------------------------
2016-06-02T17:15:39.385517+00:00 app[web.1]:   [Function: _cleanupCallback] ]
2016-06-02T17:15:39.385487+00:00 app[web.1]:
2016-06-02T17:15:39.392709+00:00 app[web.1]:
2016-06-02T17:15:39.385518+00:00 app[web.1]: Running "bower:install" (bower) task
2016-06-02T17:15:39.385518+00:00 app[web.1]: >> Cleaned target dir /app/assets/vendor
2016-06-02T17:15:39.385519+00:00 app[web.1]: ------------------------------------------------------------------------
2016-06-02T17:15:39.385516+00:00 app[web.1]: Fatal error: Path must be a string. Received [ '/tmp/0077235362b904e0706919379d9abb40/bower/fontawesome-26-IEN3KJ',
2016-06-02T17:15:39.394064+00:00 app[web.1]:  *-> Are "grunt" and related grunt task modules installed locally?  Run `npm install` if you're not sure.
2016-06-02T17:15:39.393890+00:00 app[web.1]: Troubleshooting tips:
2016-06-02T17:15:39.392884+00:00 app[web.1]: Looks like a Grunt error occurred--
2016-06-02T17:15:39.394010+00:00 app[web.1]:
2016-06-02T17:15:39.394278+00:00 app[web.1]:  *-> You might have a malformed LESS, SASS, CoffeeScript file, etc.
2016-06-02T17:15:39.392993+00:00 app[web.1]: Please fix it, then **restart Sails** to continue running tasks (e.g. watching for changes in assets)
2016-06-02T17:15:39.393169+00:00 app[web.1]:
2016-06-02T17:15:39.393066+00:00 app[web.1]: Or if you're stuck, check out the troubleshooting tips below.
2016-06-02T17:15:39.394178+00:00 app[web.1]:
2016-06-02T17:15:39.394816+00:00 app[web.1]:      sudo chown -R 51606 /app/.tmp
2016-06-02T17:15:39.394625+00:00 app[web.1]:
2016-06-02T17:15:39.394892+00:00 app[web.1]:
2016-06-02T17:15:39.394374+00:00 app[web.1]:  *-> Or maybe you don't have permissions to access the `.tmp` directory?
2016-06-02T17:15:39.394532+00:00 app[web.1]:      e.g., `/app/.tmp` ?
2016-06-02T17:15:39.394328+00:00 app[web.1]:
2016-06-02T17:15:39.394676+00:00 app[web.1]:      If you think this might be the case, try running:
2016-06-02T17:15:52.228153+00:00 app[web.1]: Error: The hook `grunt` is taking too long to load.
2016-06-02T17:15:52.228162+00:00 app[web.1]: Make sure it is triggering its `initialize()` callback, or else set `sails.config.grunt._hookTimeout to a higher value (currently 20000)
2016-06-02T17:15:52.228164+00:00 app[web.1]:     at Timeout.tooLong [as _onTimeout] (/app/node_modules/sails/lib/app/private/loadHooks.js:85:21)
2016-06-02T17:15:52.228165+00:00 app[web.1]:     at tryOnTimeout (timers.js:224:11)
2016-06-02T17:15:52.228165+00:00 app[web.1]:     at Timer.listOnTimeout (timers.js:198:5) { [Error: The hook `grunt` is taking too long to load.
2016-06-02T17:15:52.228167+00:00 app[web.1]: Make sure it is triggering its `initialize()` callback, or else set `sails.config.grunt._hookTimeout to a higher value (currently 20000)] code: 'E_HOOK_TIMEOUT' }
2016-06-02T17:15:53.669743+00:00 heroku[web.1]: State changed from starting to crashed
2016-06-02T17:15:53.655028+00:00 heroku[web.1]: Process exited with status 0
2016-06-02T18:06:31.272886+00:00 heroku[web.1]: State changed from crashed to starting
2016-06-02T18:06:36.225210+00:00 heroku[web.1]: Starting process with command `npm start`
2016-06-02T18:06:38.532682+00:00 app[web.1]: > myapp-sails-website@0.0.0 start /app
2016-06-02T18:06:38.532687+00:00 app[web.1]: > node app.js
2016-06-02T18:06:38.532667+00:00 app[web.1]:
2016-06-02T18:06:38.532688+00:00 app[web.1]:
2016-06-02T18:06:40.055713+00:00 app[web.1]: Warning: connect.session() MemoryStore is not
2016-06-02T18:06:40.055780+00:00 app[web.1]: memory, and will not scale past a single process.
2016-06-02T18:06:40.055777+00:00 app[web.1]: designed for a production environment, as it will leak
2016-06-02T18:06:43.891199+00:00 app[web.1]: ------------------------------------------------------------------------
2016-06-02T18:06:43.891203+00:00 app[web.1]:   [Function: _cleanupCallback] ]
2016-06-02T18:06:43.891204+00:00 app[web.1]: >> Cleaned target dir /app/assets/vendor
2016-06-02T18:06:43.891202+00:00 app[web.1]: Fatal error: Path must be a string. Received [ '/tmp/9f58527d2d49adf07e59162a077b871c/bower/bootstrap-26-nvHWyj',
2016-06-02T18:06:43.891205+00:00 app[web.1]: ------------------------------------------------------------------------
2016-06-02T18:06:43.891203+00:00 app[web.1]: Running "bower:install" (bower) task
2016-06-02T18:06:43.891391+00:00 app[web.1]: Looks like a Grunt error occurred--
2016-06-02T18:06:43.891393+00:00 app[web.1]: Please fix it, then **restart Sails** to continue running tasks (e.g. watching for changes in assets)
2016-06-02T18:06:43.891906+00:00 app[web.1]:
2016-06-02T18:06:43.891934+00:00 app[web.1]:  *-> Are "grunt" and related grunt task modules installed locally?  Run `npm install` if you're not sure.
2016-06-02T18:06:43.891899+00:00 app[web.1]: Troubleshooting tips:
2016-06-02T18:06:43.891390+00:00 app[web.1]:
2016-06-02T18:06:43.891433+00:00 app[web.1]: Or if you're stuck, check out the troubleshooting tips below.
2016-06-02T18:06:43.891476+00:00 app[web.1]:
2016-06-02T18:06:43.891189+00:00 app[web.1]:
2016-06-02T18:06:43.892016+00:00 app[web.1]:  *-> You might have a malformed LESS, SASS, CoffeeScript file, etc.
2016-06-02T18:06:43.891973+00:00 app[web.1]:
2016-06-02T18:06:43.892187+00:00 app[web.1]:
2016-06-02T18:06:43.892084+00:00 app[web.1]:
2016-06-02T18:06:43.892304+00:00 app[web.1]:
2016-06-02T18:06:43.892265+00:00 app[web.1]:      sudo chown -R 59724 /app/.tmp
2016-06-02T18:06:43.892088+00:00 app[web.1]:  *-> Or maybe you don't have permissions to access the `.tmp` directory?
2016-06-02T18:06:43.892144+00:00 app[web.1]:      e.g., `/app/.tmp` ?
2016-06-02T18:06:43.892259+00:00 app[web.1]:      If you think this might be the case, try running:
2016-06-02T18:06:59.974471+00:00 app[web.1]:     at Timeout.tooLong [as _onTimeout] (/app/node_modules/sails/lib/app/private/loadHooks.js:85:21)
2016-06-02T18:06:59.974435+00:00 app[web.1]: Error: The hook `grunt` is taking too long to load.
2016-06-02T18:06:59.974469+00:00 app[web.1]: Make sure it is triggering its `initialize()` callback, or else set `sails.config.grunt._hookTimeout to a higher value (currently 20000)
2016-06-02T18:06:59.974474+00:00 app[web.1]: Make sure it is triggering its `initialize()` callback, or else set `sails.config.grunt._hookTimeout to a higher value (currently 20000)] code: 'E_HOOK_TIMEOUT' }
2016-06-02T18:06:59.974473+00:00 app[web.1]:     at Timer.listOnTimeout (timers.js:198:5) { [Error: The hook `grunt` is taking too long to load.
2016-06-02T18:06:59.974472+00:00 app[web.1]:     at tryOnTimeout (timers.js:224:11)
2016-06-02T18:07:00.662956+00:00 heroku[web.1]: Process exited with status 0
2016-06-02T18:07:00.697875+00:00 heroku[web.1]: State changed from starting to crashed

Any pointers?
my bower.json
$ more bower.json
{
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components",
    "test",
    "tests"
  ],
  "dependencies": {
    "bootstrap": "~3.3.6",
    "fontawesome": "~4.6.3"
  },
  "exportsOverride": {
    "bootstrap": {
      "js": "dist/js/*.min.*",
      "less": "less/"
    },
    "fontawesome": {
      "less": "less/",
      "fonts": "fonts/"
    },
    "jquery": {
      ".": "dist/*.min.*"
    }
  },
  "name": "sails-website",
  "version": "0.1.0",
  "author": "joel",
  "private": true
}

grunt build
$ heroku run  node_modules/.bin/grunt build
Running node_modules/.bin/grunt build on ⬢myapp-webrtc... up, run.3290
Running "bower:install" (bower) task
>> Cleaned target dir /app/assets/vendor
Fatal error: Path must be a string. Received [ '/tmp/3fc3abe767162452221ee2ffa49efa28/bower/fontawesome-3-h46jhs',
  [Function: _cleanupCallback] ]

Bower version on Heroku
$ heroku run bower --version
Running bower --version on ⬢ myapp... up, run.8617
1.2.8

A:
Getting the error "Arguments to path.join must be strings"?  Clear cache and update to Bower 1.3.8.

buildpack
Not sure this one is compulsory, but since I had it
$ heroku buildpacks:set https://github.com/heroku/heroku-buildpack-nodejs#v90

Clean the bower cache
$ heroku run bower cache clean

package.json
{
  "scripts": {
    "postinstall": "bower install; grunt build",    <==== ADDED THIS LINE
    "debug": "node debug app.js",
    "start": "node app.js"
  },
  "dependencies": {
    "bower": "1.3.8",     <==== ADDED THIS TO MAKE SURE TO USE VERSION 1.3.8
    "connect-redis": "^3.0.2",
    "ejs": "2.3.4",
    "grunt": "0.4.5",
    "grunt-bower": "^0.21.2",
    "grunt-bower-task": "^0.3.4",
    "grunt-contrib-clean": "0.6.0",
    "grunt-contrib-coffee": "0.13.0",
    "grunt-contrib-concat": "0.5.1",
    "grunt-contrib-copy": "0.5.0",
    "grunt-contrib-cssmin": "0.9.0",
    "grunt-contrib-jst": "0.6.0",
    "grunt-contrib-less": "1.1.0",
    "grunt-contrib-uglify": "0.7.0",
    "grunt-contrib-watch": "0.5.3",
    "grunt-sails-linker": "~0.10.1",
    "grunt-sync": "0.2.4",
    "include-all": "~0.1.6",
    "rc": "1.0.1",
    "sails": "~0.12.3",
    "sails-disk": "~0.10.9"
  },
  "name": "myapp-sails-website",
  "private": true,
  "version": "0.0.0",
  "description": "a Sails application",
  "keywords": [],
  "main": "app.js",
  "repository": {
    "type": "git",
    "url": "git://github.com/joel/myapp.git"
  },
  "author": "joel",
  "license": ""
}

then git push heroku master
$ heroku run bower --version
Running bower --version on ⬢ myapp... up, run.3350
1.3.8

that resolved my issue.


text:
Q: populate data from database when tab key is pressed I am using jquery, ajax and php to retrieve data from database. I want to achieve a functionality i.e. When user inputs product code and press TAB Key the data should be filled in textarea. I'm new to ajax n php, I've checked my query in SQL it is working.. Please help me
html
<input type="text" class="form-control col-md-5 detectTab" name="product_code" />
<textarea class="form-control autogrow" id="container" name="desc" rows="3" cols="5" placeholder="Remarks" required></textarea>

Script
    <script type="text/javascript">
$(function(){
    $("#product_code").keydown(function(e){
if(9 == e.keyCode){
       var postlink = 'loaddesc.php';
            $.post(postlink).done(function(data){
                if(data)
                    $("#container").val(data);
                else
                    $("#container").val('No Data Received');
            }
        }
    })
})
</script>

loaddesc.php
<?php
include('config.php');
if($_POST['$product_code'] )
{
$product_code=$_POST['product_code'];
$sql=mysqli_query($con, 'SELECT concat(A.PRODUCT_CAT_NAME," - ", B.name," - ", C.PRODUCT_SERIAL_NO," - ",c.product_desc) Product_Details
                        FROM dms_product_cat A, dms_product_type B, dms_products c WHERE A.product_cat_id = 1 AND B.product_cat_id = A.product_cat_id and B.type_id = c.product_type
and c.product_code = "$product_code"');
    while($row=mysqli_fetch_array($sql))
    {
    $data=$row['Product_Details'];
    echo $data;
    }
}
?>

A: Your sql query can not works because variables in single quote strings are not evaluated.
Anyway it s a bad idea to build your request like this. There is a sql injection vulnerability in it.
You should read this:
How can I prevent SQL injection in PHP?

A: Logical Solution to your question

When user inputs product code and press TAB Key the data should be
  filled in textarea.

*

*START

*input box where user will fill data and will press tab

*a javascript function call on pressing key

*check whether the key is "tab"

*jquery post method fire to server requesting data

*fetched data in success

*display the data in the required textarea

*DONE

CODE SAMPLE
<html>
<head>
    <title>TEST AJAX</title>
</head>

<body>
    <!-- The input Box -->
    <input type="text" name="product_code" id="product_code" autofocus/>
    <!-- The Text Area -->
    <textarea id="container" name="desc" placeholder="Remarks"></textarea>
</body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
    // Will fire on any key press in input box
    $("#product_code").keydown(function(e){

        //alert(e.keyCode); // Remove the comment to check for keypress Code

        // KeyCode 9 is for TAB key
        if(9 == e.keyCode){
            // Sending via ajax to fetch data
            var postlink = ''; // Required Backend Script Handler
            $.post(postlink).done(function(data){
                // Handling the fetched data
                if(data)
                    $("#container").val(data); // Filling data in textarea
                else
                    $("#container").val('No Data Recieved'); // No data recieved
            }
        }
    })
})
</script>
</html>

I believe your issue is settled now.

Thanks & Regards


text:
Q: How to pass command with its arguments as a single argument to script? I have a script I use for building my kernel, and in it I have a function I want to use to catch errors in my build commands, but I can't figure out how to pass multiple arguments as one to get it working properly. The syntax is as follows:
run_build() {
cmd=$($1)
status=${PIPESTATUS[0]}
$*
if ($status != 0); then
    echo "$cmd failed!"
    exit 1
else
    echo "$cmd succeeded."
fi
}

The problem is, when I try to pass a make command with its arguments, the make command is being executed with no arguments. I tried to use the "$*" syntax to call all arguments but it doesn't seem to work. An example command would be
make O=out -j8 zImage

I need the next 3 arguments to be included when calling the line from the script. Anyone have ideas?

A: The proper solution to this is probably something like
if "$@"; then
    echo "$@ succeeded" >&2
else
    rc=$?
    echo "$@ failed" >&2
fi

but this still seems like you are replacing perfectly good built-in functionality with something worse.

A: Not fond of this setup for a few obvious reasons and few less obvious.
For the record, c.f. this page on why not to do this.
Also worthy of note, in case you shift to eval, which idealogically is kind of what this function is doing... please read this too.
...but for a simplistic solution -
Arguments come in as an array. If you are running the build, then make your function run the build, with quoted arguments.
run_build() {
  if make "$@"  # QUOTED, *explicit* call to make
  then echo "'make $@' succeeded."
  else echo "'make $@' failed."
       return 1 # exit in function only sets return - be explicit
  fi
}

run_build O=out -j8 zImage # run_build as a make synonym

Don't try to build do-anything functions.
That way lies madness.
If you must use other commands than make, then validate and verify.
run_build() {
  local cmd=$1
  shift
  case "$cmd" in
  make|or|some|other|specifically|ok|word)
    if "$cmd" "$@" # QUOTED!!!
    then echo "'$cmd $@' succeeded."
    else echo "'$cmd $@' failed."
         return 1
    fi
  ;;
  *) echo "Invalid argument: '$cmd' not recognized."
     return 1
  ;;
  esac
}

If you aren't at least doing that, what's the purpose of the function? I mean, you are passing in all the parts of the command anyway, and not doing much with them beside executing them. Why not just...you know, execute them, instead of bothering with a function? But even if you keep it to it's simplest, quote, quote, quote.
run_build() { "$@" && echo "'$@' succeeded" || {
                      echo "'$@'failed; return 1; }; }

A: First point, you don't want to pass the entire command as a single argument: I'm trying to put a command in a variable, but the complex cases always fail!
This is the main error: cmd=$($1) -- the $() syntax invokes Command Substitution that executes the first argument. Just use cmd=$1 to store the first parameter into the "cmd" variable.
Additional errors:

*

*if ($status != 0); then -- that syntax is incorrect: use if ((status != 0)); then for proper arithmetic evaluation.

*$* -- to execute the positional parameters correctly, use "$@" (with the quotes) -- that form will maintain any arguments that contain whitespace as intended.


text:
Q: Command Query Separation violation What do you think about
 if(!DoSomething()) return;

In Clean Code this is viewed as violation of Command Query Separation.
But how can we understand if something in command DoSomething() went wrong?
What about sql command (ex: void Delete(Table))? How can we know if that table existed?
Thanks.

A: If something went wrong, DoSomething() should probably throw an exception, if you as the caller must handle it.
E.g.:
try
{
  DoSomething();
  // .. do more after success
}
catch(SomeException ex) // maybe focus on a special error
{
  // maybe do something special or just clean up!
}

A: I agree with the comments from rObiwahn that you should check CanDoSomething before issuing a command of DoSomething.  In a pure CQRS environment, DoSomething would not return anything and if anything prevented Something from happening (not due to an exception, but a race condition or something else changing between CanDoSomething and DoSomething), your domain would issue a DoSomethingWasInvalid event (or something like that) which would allow your application to eventually become consistent.
It may sound complex, but it really becomes pretty simple once you start breaking down the logic into small chunks and allow your application to embrace eventual consistency.
There are a lot of good resources on the DDD/CQRS group in google groups.  A question like 'How do you tell the sender that a command failed?' is similar to your question a bit.  People like Udi Dahan, Greg Young, Rinat Abdullin and others monitor that group and provide some really great answers.  I'd recommend checking that out every now and then, too.
Hope this helps!

A: I will write this example in Eiffel to make it simple to understand.
my_code
      -- Calls the `do_something' routine
   do
      set_table ("my_table")
      do_something
   end

do_something
      -- Something to do
   require
      valid_table: is_valid_table (table_name)
   do
      sql_list := execute_sql_on_table (table_name)
   ensure
      has_result: sql_list.count > 0
   end

sql_list: ARRAYED_LIST [STUFF]

table_name: STRING

set_table (a_name: STRING)
       -- Set `table_name' to `a_name'
   require
      has_name: not a_name.is_empty
      valid_table: is_valid_table (a_name)
   do
      table_name := a_name
   ensure
      table_name_set: table_name.same_string (a_name)
   end

delete_table (a_name: STRING)
      -- Delete `a_name' from the database.
   require
       valid_table: is_valid_table (a_name)
   do
      execute_sql ("DROP TABLE " + a_name)
   ensure
       table_gone: not is_valid_table (a_name)
   end

*

*The feature `do_something' is a command, where the array sql_list is to be loaded with STUFF from the table "my_table".

*The precondition contract on do_something' makes it the responsibility of the clientmy_code' to provide table_name' before making the call todo_something'.

*In return, the post-condition ensure contract makes it the responsibility of the supplier do_something' fill the arraysql_list' with instances of STUFF.

*The feature `sql_list' is a query, returning a reference pointer to an array of STUFF.

*Similarly, the feature table_name' is a query returning a reference pointer to a STRING, which is set with a "setter" command calledset_table'.

In this case, the "contracts" of Design-by-Contract take care of ensuring appropriate separation of concerns and who is responsible for what in this small bit of code above. Notice the distinct lack of TRY-CATCH constructs in the code. In this case, the data source is expected to have "my_table". The presence of the contracts means the software will raise an exception when the contract fails. A require failure says the caller is broken, while a failure in an ensure post-condition points at the supplier feature.
Finally, this code exhibits clear Command-Query-separation and the application of quality assurance gained from Design by Contract. Thus, the original question can be answered:
"But how can we understand if something in command DoSomething() went wrong? What about sql command (ex: void Delete(Table))? How can we know if that table existed?"
While it might be true that a call to delete_table ("my_table") might be injected into some ancestor or might happen on another thread, this is what the contracts are for in do_something'. As long as those contracts stand guard over calls todo_something', the process will be appropriately handled. An injected call to `delete_table' will simply cause the contract to fail.
All of this is presuming it is NOT OK to DROP TABLE on "my_table" and that doing so is tragically accidental. However, if it becomes OK to DROP TABLE on "my_table" then a retry mechanism or other "handler" is needed to manage this use case and the code above will not work.

A: i really had this thing came to my mind now, [why we don't think of "concerns of separation" rather than "separation of concerns"!] i know its off topic but too much push for standards will lead to NO WHERE. from history of mankind it easy to see how much of practices/standards proven wrong with time! it's all about your perspective of excellence.
so in such case i always try to think of the opposite to stay REAL. i want to say more but i think that's enough from my perspective of answering ;)
good luck!


text:
Q: Detect HTTP interruption in Java I'm making a REST call to an external system from Java. If there are any connection interruptions like if the external system goes offline, I need a listener to detect that and perform corresponding actions. Kindly let me know if I can achieve this in Java. Preferably in Java 8.
Currently i'm not getting any exception if I get into any such situation. I having the below code currently
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(HOSTNAME);
    Invocation.Builder requestBuilder;

    requestBuilder = target.path(URL).request(MediaType.APPLICATION_JSON)
                                                .header(HEADER_AUTHORIZATION, AUTH_TOKEN);
    Response response = null;
    if (HTTP_POST.equalsIgnoreCase(method)) {
        try{
        response = requestBuilder.post(Entity.entity(message, MediaType.APPLICATION_JSON_TYPE));
        }catch(Exception ex ){
            ex.printStackTrace();
        }
    } else if (HTTP_GET.equalsIgnoreCase(method)) {
        response = requestBuilder.get();
    }

    String executeMessage = null;
    if(response != null){
        if (response.getStatus() == 200) {
            executeMessage = response.readEntity(String.class);
            return new JSONObject(executeMessage);
        } else {
            executeMessage = response.readEntity(String.class);
            final JSONObject status = new JSONObject();
            status.put(STATUS_CODE, response.getStatus());
            status.put(STATUS_INFO, response.getStatusInfo());
            status.put("response", executeMessage);
            final JSONObject error = new JSONObject();
            error.put(ERROR, status);
            return error;
        }
    }

A: If you use Spring Boot you can try a declarative REST client called Feign:
@FeignClient(url = "example.com", fallback = YourTestFeignClient.YourTestFeignClientFallback.class)
public interface YourTestFeignClient {

    @RequestMapping(method = RequestMethod.POST, value = "/example/path/to/resource/{id}")
    YourTestResponse requestExternalResource(@RequestParam("id") Long id, SomeRequestDTO requestDTO);

    @Component
    public static class YourTestFeignClientFallback implements YourTestFeignClient {

        @Override
        public YourTestResponse requestExternalResource(Long id, SomeRequestDTO requestDTO) {
            YourTestResponse testResponse = new YourTestResponse();
            testResponse.setMessage("Service unavailable");
            return testResponse;
        }

    }
}

All you need to do here is to inject YourTestFeignClient in your code and invoke method requestExternalResource on it. This will call POST example.com/example/path/to/resource/34with JSON body taken from SomeRequestDTO. In case a request fails a fallback method inside YourTestFeignClientFallback will get called, which then returns some default data.

A: You could create your own Listener and make your Http calls async with the results passed back to the calling class once the HTTP response/error is ready.  For example (with typos):
Create an interface that your main class will implement and your Http Client will make use of...
public interface MyHttpListener {
  public httpComplete(MyHttpResults results);
}

Implement in your main class.
public MyClass implements MyHttpListener {

  public void processHttpRequests(){
      for(int i=0; i<10; i++){
        // instantiate your Http Client class
        HttpClient client = new HttpClient();

        // register the listener
        client.addHttpListener(this);

        // execute whatever URL you want and you are notified later when complete
        client.executeRequest("http://whatever");
     }
  }

  public httpRequestComplete(MyHttpResults results) {
    // do something with the results
    results.getResponseCode();
    results.getRawResponse();
    results.whatever();
  }

}
Add method to your HttpClient to accept listeners
public class MyHttpClient {
    List<MyHttpListener> httpListenerList = new ArrayList();

   // register listeners
   public void addHttpListener(MyHttpListener listener){
     httpListenerList.add(listener);
   }

   // this is the method that processes the request
   public void executeRequest(String url) {

     // do whatever you were doing previously here

     // optional POJO to wrap the results and/or exceptions
     MyHttpResults results = new MyHttpResults();
     results.withResponseCode(response.getResponseCode());
     results.withResponse(responseAsString);
     results.withException(ex);
     results.withWhatever(whatever);

     // notify listeners
     notify(results);

   }

  public void notify(MyHttpResults results){
      // notify listeners
      for(MyHttpListener listener : httpListenerList){
         listener.httpComplete(results);
      }
  }

 }

A: If you want to constantly check external REST service whether it is offline you have to setup some sort of periodical ping request. Any response will mean that service is online. Absence of response during some period of time will mean that something is wrong.
The problem you are facing rises from that java TCP Socket connect method is blocking and java socket default connect timeout is 0, which is actually infinity as it is said in javadoc.
So that means that you won't get any response at all by default if the service is offline.
The only correct and simple option here is to set a timeout. In your case the easiest way would be to use Jersey Client property setup, like this:
Client client = ClientBuilder.newClient();
// One second timeout may not be a really good choice unless your network is really fast
client.property(ClientProperties.CONNECT_TIMEOUT, 1000);

And only in this case you will get an exception, which will indicate, that REST service you are trying to ping is not accepting connections.
Set timeout with caution according to the real network capabilities, in some cases it should be more than 5 or even 15 seconds (e.g. WiFi and GPRS connections).


text:
Q: ng-class is not being updated cy.on('tap', 'edge,:selected', function (event) {
  $scope.$apply(function (response) {

    $scope.dataToDisplay = {
      data1:true
    }

  });
});

I have the following code above. It is an event that fires as any edge is clicked/tapped on in a Cytoscape.js graph.
I am able to display the $scope object utilizing $scope.$apply. In the html, I also have an ng-class directive that will display accordingly whether it's true/false. However, the ng-class does not seem to respond as the value changes.
Below is a snippet of the ng-class directive,

Assistance is much appreciated.
I would like to clarify that the class does get updated as the page loads. However, I have an additional ng-click event that toggles the true/false. This does not add/remove the class as the value change but the value does get updated in the view. How can I achieve update the class as the value changes?


text:
Q: How to split and keep float numbers together Ruby and Python I am programming a math expression checker. I have this string:
oper = "((234+3.32)+(cos4-sin65))"

I want to split this string by separating all "()"s and operators minus numbers or trigonometric ratios to get this result:
oper = ['(', '(', '234', '+', '3.32', ')', '+', '(', 'cos4', '-', 'sin65', ')', ')']

How would the split be?

A: Here's my example solution.
oper = "((234+3.32)+(cos4-sin65))"
separators = ['(', ')', '+', '-', 'cos', 'sin']

def sep_at_beg(x):
    for separator in separators:
        if len(x) >= len(separator) and x.startswith(separator):
            if separator in ['cos', 'sin']:
                if len(x) > len(separator)+1 and x[len(separator)+1].isdigit():
                    return x[:len(separator)+2]
                return x[:len(separator)+1]
            return separator
    return False

def separate(x):
    return_x = []
    idx = 0
    so_far = ''
    while idx < len(x):
        separator = sep_at_beg(x[idx:])
        if separator:
            if so_far:
                return_x.append(so_far)
            return_x.append(separator)

            so_far = ''
            idx += len(separator)
        else:
            so_far += x[idx]
            idx += 1
    if so_far:
        return_x.append(so_far)
    return return_x

oper = separate(oper)
print(oper)

Outputs:
['(', '(', '234', '+', '3.32', ')', '+', '(', 'cos4', '-', 'sin65', ')', ')']

A: Ruby:
oper = "((234+3.32)+(cos4-sin65))"
re = Regexp.union("(" ,")", "+", "-", /[^()\-+]+/)
p oper.scan(re) # => ["(", "(", "234", "+", "3.32", ")", "+", "(", "cos4", "-", "sin65", ")", ")"]

A: There is an easier way, use it:
oper = "((234+3.32)+(cos4-sin65))"
separators=["(",")","+","-"]

def my_split(o, l, j="@"):
    for e in l:
        o = o.replace(e, j+e+j)
    return [e for e in o.split(j) if e]

print(my_split(oper, separators))


text:
Q: Chain rule applied in one point Let $g(u, v)=e^u + \sin v$ and $f(x, y, z)=(xy, xz)$ . Calculate $D(g o f)$ in $(0,1,0)$ applying chain rule.
So here is what I have done:
$$\frac{\partial g}{\partial x} = \frac{\partial g1}{\partial u} \frac{\partial u}{\partial x} + \frac{\partial g2}{\partial u} \frac{\partial u}{\partial x} = e^u * y + 1*y + \cos v * z $$
$$\frac{\partial g}{\partial y} = \frac{\partial g1}{\partial u} \frac{\partial u}{\partial y} + \frac{\partial g2}{\partial u} \frac{\partial u}{\partial y} = e^u * x + u*y $$
$$\frac{\partial g}{\partial z} = \frac{\partial g2}{\partial v} \frac{\partial v}{\partial z}  = \cos v * x $$
I think I am going in a good way but I do not know what I should do now.


text:
Q: Starting a detached screen session and a Java program with one command I found an answer on super user that the following should create a screen session in detached mode. But it is not working in my situation.
screen -dmS sessionname java -jar /root/programone/myprogram.jar

What am I doing wrong?

A: The Syntax is correct. But the screen sessions lives only if the program running in it lives.  So it's probably the java program returned error or finished successfully, in other words, ended.
To test this feature of screen, you can do this:

screen -dmS cat cat

It will start a screen session named cat with the program cat running in it.  then with screen -ls you can see the session named cat listed.  you can then use screen -r cat to attach it.


text:
Q: nuget overwrite files Is it possible to force nuGet packages to overwrite existing files? I need a nice way of applying patches (files, dll, resources) across 3  similar projects and through that this could be a nice solution.

A: Overwriting content files isn't supported today.

A: As David Fowler suggest in this discussion
http://nuget.codeplex.com/discussions/252305
you can deploy your files in a temp folder and then overwrite them at the original location by using PowerShell script.

A: It can be accomplished with powershell and a package dependencies...
I have a NuGet package that I create for ASP.NET MVC it has all the files that I want to add to the standard Mvc project (DisplayTemplates, EditorTemplate, Extensions, BaseController, etc). Let say its called "Company.WebMvc"
I created another NuGet package called "Company.WebMvc-Prep" That has an Install.ps1 script that deletes anything I don't want from the standard Mvc project. Here is an code example of deleting the existing Scripts files...
param($installPath, $toolsPath, $package, $project)

#Remove Script Files

$scripts = $project.ProjectItems | Where-Object { $_.Name -eq "Scripts" }

if ($scripts) {

    $scripts.ProjectItems | ForEach-Object { $_.Delete() }

}

I then make "Company.WebMvc-Prep" a dependency of "Company.WebMvc". Why? because Install.ps1 (normally) is run after NuGet adds the files from the content folder. I need it to delete the files first then add the new ones. So when you call...
Install-Package Company.WebMvc
Company.WebMvc-Prep is installed first because it is a dependency (runs Install.ps1)
Then Company.WebMvc is installed which adds your content.
Long and short of it is... You Can overwrite existing content on your project via a NuGet package.
P.S. Remember you can also you partial classes to isolate NuGet package code vs. project specific code.

A: Although you apparently can't specify this for all installs of the package (according to the other answers), it is actually possible to specify it for a single install. Install the package with:
Install-Package com.company.mypackage -FileConflictAction Overwrite

This will automatically overwrite all files that conflict during the install process.


text:
Q: Floating action button in Tumblr app after they apply matirial design theme I would like to ask, how you can develop an animation floating button such that one in Tumblr android app?
I know how to make floating action button, but i don't know how to animate it and make it floating on screen.
UPDATED
I found the official library
"A motion-driven animation framework for Android"
https://github.com/tumblr/Backboard

A: https://android-arsenal.com/details/1/1781 There are more such open source projects that you can use for your need. I remember seeing one such looking just like the tumblr implementation but forgot where. Do a search in github and forums like android-arsenal.com


text:
Q: Terminal Disk Free `df` returns Huge `ifree` free inodes This has been going on for a few years through several upgrades. In the Terminal when I type df -h the ifree numbers are ridiculously high and clearly off.
Example:
$ df /
Filesystem   512-blocks      Used Available Capacity iused               ifree %iused  Mounted on
/dev/disk1s1  489825072 442781368  39401000    92% 2253035 9223372036852522772    0%   /

The disks /private/var/vm and Android File Transfer Agent.app also have huge numbers for ifree.
System Information:
About This Mac:
macOS Mojave
Version 10.14.6
MacBook Pro (Retina, 15-inch, Mid 2014)

$ uname -a
Darwin xxxxxxx.xxxx.xx.comcast.net 18.7.0 Darwin Kernel Version 18.7.0: Thu Jun 18 20:50:10 PDT 2020; root:xnu-4903.278.43~1/RELEASE_X86_64 x86_64

A: My best guess is that these are filesystems that do not have inodes (the vast majority of modern filesystems don't, actually pretty much only old Unix filesystems do), and so the filesystem driver just synthesizes an arbitrary number because the 50 year old API says the driver must provide a number of free inodes even though modern filesystems haven't had them in a decade.
In particular, I am assuming that your / filesystem is APFS, which is indeed neither a traditional Unix filesystem (it was designed specifically for macOS) nor an old filesystem (it was announced in 2016). APFS is fully 64 bit, and as far as I know, it doesn't use a traditional inode-based scheme. Actually, the entire design of APFS and the way it intersects multiple layers of the traditional Unix filesystem, VFS, and block device stack, is very much non-traditional, and much more reminiscent of ZFS and the Be filesystem (which is no surprise since the designer of BeFS works at Apple now).
Note that the number you showed is very close to the maximum 64 bit signed integer (9223372036854775807), or in other words, it is close to the maximum of size_t in a 64 bit version of Darwin. In fact, the sum of used and free inodes is exactly 9223372036854775807. So, what is happening here, is that the filesystem driver simply synthesizes 263-1 (size_tmax) inodes for use.
Presumably, when you say that "it has been going on for a few years", you are talking about the move from 32 bit to 64 bit Darwin, and before that, the numbers were closer to 2147483647, which is of course the maximum for size_t in 32 bit Darwin.
For fun, you might download the open source Darwin source code from Apple and compile a 32 bit version of df, and I bet you, the numbers you will see are 2253035 and 2145230612 (2147483647 - 2253035).